xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision 27fbcf8a5036d0cea1c401094c8bb0731ddc87ec)
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/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <net/if.h>
58 #include <net/if_arp.h>
59 #include <net/route.h>
60 #include <sys/sockio.h>
61 #include <netinet/in.h>
62 #include <net/if_dl.h>
63 
64 #include <inet/common.h>
65 #include <inet/mi.h>
66 #include <inet/mib2.h>
67 #include <inet/nd.h>
68 #include <inet/arp.h>
69 #include <inet/snmpcom.h>
70 #include <inet/kstatcom.h>
71 
72 #include <netinet/igmp_var.h>
73 #include <netinet/ip6.h>
74 #include <netinet/icmp6.h>
75 #include <netinet/sctp.h>
76 
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip6_asp.h>
81 #include <inet/tcp.h>
82 #include <inet/tcp_impl.h>
83 #include <inet/ip_multi.h>
84 #include <inet/ip_if.h>
85 #include <inet/ip_ire.h>
86 #include <inet/ip_ftable.h>
87 #include <inet/ip_rts.h>
88 #include <inet/optcom.h>
89 #include <inet/ip_ndp.h>
90 #include <inet/ip_listutils.h>
91 #include <netinet/igmp.h>
92 #include <netinet/ip_mroute.h>
93 #include <inet/ipp_common.h>
94 
95 #include <net/pfkeyv2.h>
96 #include <inet/ipsec_info.h>
97 #include <inet/sadb.h>
98 #include <inet/ipsec_impl.h>
99 #include <sys/iphada.h>
100 #include <inet/tun.h>
101 #include <inet/ipdrop.h>
102 
103 #include <sys/ethernet.h>
104 #include <net/if_types.h>
105 #include <sys/cpuvar.h>
106 
107 #include <ipp/ipp.h>
108 #include <ipp/ipp_impl.h>
109 #include <ipp/ipgpc/ipgpc.h>
110 
111 #include <sys/multidata.h>
112 #include <sys/pattr.h>
113 
114 #include <inet/ipclassifier.h>
115 #include <inet/sctp_ip.h>
116 #include <inet/sctp/sctp_impl.h>
117 #include <inet/udp_impl.h>
118 
119 #include <sys/tsol/label.h>
120 #include <sys/tsol/tnet.h>
121 
122 #include <rpc/pmap_prot.h>
123 
124 /*
125  * Values for squeue switch:
126  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
127  * IP_SQUEUE_ENTER: squeue_enter
128  * IP_SQUEUE_FILL: squeue_fill
129  */
130 int ip_squeue_enter = 2;
131 squeue_func_t ip_input_proc;
132 /*
133  * IP statistics.
134  */
135 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
136 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
137 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
138 
139 typedef struct ip_stat {
140 	kstat_named_t	ipsec_fanout_proto;
141 	kstat_named_t	ip_udp_fannorm;
142 	kstat_named_t	ip_udp_fanmb;
143 	kstat_named_t	ip_udp_fanothers;
144 	kstat_named_t	ip_udp_fast_path;
145 	kstat_named_t	ip_udp_slow_path;
146 	kstat_named_t	ip_udp_input_err;
147 	kstat_named_t	ip_tcppullup;
148 	kstat_named_t	ip_tcpoptions;
149 	kstat_named_t	ip_multipkttcp;
150 	kstat_named_t	ip_tcp_fast_path;
151 	kstat_named_t	ip_tcp_slow_path;
152 	kstat_named_t	ip_tcp_input_error;
153 	kstat_named_t	ip_db_ref;
154 	kstat_named_t	ip_notaligned1;
155 	kstat_named_t	ip_notaligned2;
156 	kstat_named_t	ip_multimblk3;
157 	kstat_named_t	ip_multimblk4;
158 	kstat_named_t	ip_ipoptions;
159 	kstat_named_t	ip_classify_fail;
160 	kstat_named_t	ip_opt;
161 	kstat_named_t	ip_udp_rput_local;
162 	kstat_named_t	ipsec_proto_ahesp;
163 	kstat_named_t	ip_conn_flputbq;
164 	kstat_named_t	ip_conn_walk_drain;
165 	kstat_named_t   ip_out_sw_cksum;
166 	kstat_named_t   ip_in_sw_cksum;
167 	kstat_named_t   ip_trash_ire_reclaim_calls;
168 	kstat_named_t   ip_trash_ire_reclaim_success;
169 	kstat_named_t   ip_ire_arp_timer_expired;
170 	kstat_named_t   ip_ire_redirect_timer_expired;
171 	kstat_named_t	ip_ire_pmtu_timer_expired;
172 	kstat_named_t	ip_input_multi_squeue;
173 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
174 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
175 	kstat_named_t	ip_tcp_in_sw_cksum_err;
176 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
177 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
178 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
179 	kstat_named_t	ip_udp_in_sw_cksum_err;
180 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
181 	kstat_named_t	ip_frag_mdt_pkt_out;
182 	kstat_named_t	ip_frag_mdt_discarded;
183 	kstat_named_t	ip_frag_mdt_allocfail;
184 	kstat_named_t	ip_frag_mdt_addpdescfail;
185 	kstat_named_t	ip_frag_mdt_allocd;
186 } ip_stat_t;
187 
188 static ip_stat_t ip_statistics = {
189 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
190 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
191 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
192 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
193 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
194 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
195 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
196 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
197 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
198 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
199 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
200 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
201 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
202 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
203 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
204 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
205 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
206 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
207 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
208 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
209 	{ "ip_opt",				KSTAT_DATA_UINT64 },
210 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
211 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
212 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
213 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
214 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
215 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
216 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
217 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
218 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
219 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
220 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
221 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
222 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
223 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
224 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
225 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
226 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
227 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
228 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
229 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
230 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
231 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
232 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
233 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
234 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
235 };
236 
237 static kstat_t *ip_kstat;
238 
239 #define	TCP6 "tcp6"
240 #define	TCP "tcp"
241 #define	SCTP "sctp"
242 #define	SCTP6 "sctp6"
243 
244 major_t TCP6_MAJ;
245 major_t TCP_MAJ;
246 major_t SCTP_MAJ;
247 major_t SCTP6_MAJ;
248 
249 int ip_poll_normal_ms = 100;
250 int ip_poll_normal_ticks = 0;
251 
252 /*
253  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
254  */
255 
256 struct listptr_s {
257 	mblk_t	*lp_head;	/* pointer to the head of the list */
258 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
259 };
260 
261 typedef struct listptr_s listptr_t;
262 
263 /*
264  * This is used by ip_snmp_get_mib2_ip_route_media and
265  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
266  */
267 typedef struct iproutedata_s {
268 	uint_t		ird_idx;
269 	listptr_t	ird_route;	/* ipRouteEntryTable */
270 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
271 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
272 } iproutedata_t;
273 
274 /*
275  * Cluster specific hooks. These should be NULL when booted as a non-cluster
276  */
277 
278 /*
279  * Hook functions to enable cluster networking
280  * On non-clustered systems these vectors must always be NULL.
281  *
282  * Hook function to Check ip specified ip address is a shared ip address
283  * in the cluster
284  *
285  */
286 int (*cl_inet_isclusterwide)(uint8_t protocol,
287     sa_family_t addr_family, uint8_t *laddrp) = NULL;
288 
289 /*
290  * Hook function to generate cluster wide ip fragment identifier
291  */
292 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
293     uint8_t *laddrp, uint8_t *faddrp) = NULL;
294 
295 /*
296  * Synchronization notes:
297  *
298  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
299  * MT level protection given by STREAMS. IP uses a combination of its own
300  * internal serialization mechanism and standard Solaris locking techniques.
301  * The internal serialization is per phyint (no IPMP) or per IPMP group.
302  * This is used to serialize plumbing operations, IPMP operations, certain
303  * multicast operations, most set ioctls, igmp/mld timers etc.
304  *
305  * Plumbing is a long sequence of operations involving message
306  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
307  * involved in plumbing operations. A natural model is to serialize these
308  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
309  * parallel without any interference. But various set ioctls on hme0 are best
310  * serialized. However if the system uses IPMP, the operations are easier if
311  * they are serialized on a per IPMP group basis since IPMP operations
312  * happen across ill's of a group. Thus the lowest common denominator is to
313  * serialize most set ioctls, multicast join/leave operations, IPMP operations
314  * igmp/mld timer operations, and processing of DLPI control messages received
315  * from drivers on a per IPMP group basis. If the system does not employ
316  * IPMP the serialization is on a per phyint basis. This serialization is
317  * provided by the ipsq_t and primitives operating on this. Details can
318  * be found in ip_if.c above the core primitives operating on ipsq_t.
319  *
320  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
321  * Simiarly lookup of an ire by a thread also returns a refheld ire.
322  * In addition ipif's and ill's referenced by the ire are also indirectly
323  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
324  * the ipif's address or netmask change as long as an ipif is refheld
325  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
326  * address of an ipif has to go through the ipsq_t. This ensures that only
327  * 1 such exclusive operation proceeds at any time on the ipif. It then
328  * deletes all ires associated with this ipif, and waits for all refcnts
329  * associated with this ipif to come down to zero. The address is changed
330  * only after the ipif has been quiesced. Then the ipif is brought up again.
331  * More details are described above the comment in ip_sioctl_flags.
332  *
333  * Packet processing is based mostly on IREs and are fully multi-threaded
334  * using standard Solaris MT techniques.
335  *
336  * There are explicit locks in IP to handle:
337  * - The ip_g_head list maintained by mi_open_link() and friends.
338  *
339  * - The reassembly data structures (one lock per hash bucket)
340  *
341  * - conn_lock is meant to protect conn_t fields. The fields actually
342  *   protected by conn_lock are documented in the conn_t definition.
343  *
344  * - ire_lock to protect some of the fields of the ire, IRE tables
345  *   (one lock per hash bucket). Refer to ip_ire.c for details.
346  *
347  * - ndp_g_lock and nce_lock for protecting NCEs.
348  *
349  * - ill_lock protects fields of the ill and ipif. Details in ip.h
350  *
351  * - ill_g_lock: This is a global reader/writer lock. Protects the following
352  *	* The AVL tree based global multi list of all ills.
353  *	* The linked list of all ipifs of an ill
354  *	* The <ill-ipsq> mapping
355  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
356  *	* The illgroup list threaded by ill_group_next.
357  *	* <ill-phyint> association
358  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
359  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
360  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
361  *   will all have to hold the ill_g_lock as writer for the actual duration
362  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
363  *   may be found in the IPMP section.
364  *
365  * - ill_lock:  This is a per ill mutex.
366  *   It protects some members of the ill and is documented below.
367  *   It also protects the <ill-ipsq> mapping
368  *   It also protects the illgroup list threaded by ill_group_next.
369  *   It also protects the <ill-phyint> assoc.
370  *   It also protects the list of ipifs hanging off the ill.
371  *
372  * - ipsq_lock: This is a per ipsq_t mutex lock.
373  *   This protects all the other members of the ipsq struct except
374  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
375  *
376  * - illgrp_lock: This is a per ill_group mutex lock.
377  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
378  *   which dictates which is the next ill in an ill_group that is to be chosen
379  *   for sending outgoing packets, through creation of an IRE_CACHE that
380  *   references this ill.
381  *
382  * - phyint_lock: This is a per phyint mutex lock. Protects just the
383  *   phyint_flags
384  *
385  * - ip_g_nd_lock: This is a global reader/writer lock.
386  *   Any call to nd_load to load a new parameter to the ND table must hold the
387  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
388  *   as reader.
389  *
390  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
391  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
392  *   uniqueness check also done atomically.
393  *
394  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
395  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
396  *   as a writer when adding or deleting elements from these lists, and
397  *   as a reader when walking these lists to send a SADB update to the
398  *   IPsec capable ills.
399  *
400  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
401  *   group list linked by ill_usesrc_grp_next. It also protects the
402  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
403  *   group is being added or deleted.  This lock is taken as a reader when
404  *   walking the list/group(eg: to get the number of members in a usesrc group).
405  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
406  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
407  *   example, it is not necessary to take this lock in the initial portion
408  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
409  *   ip_sioctl_flags since the these operations are executed exclusively and
410  *   that ensures that the "usesrc group state" cannot change. The "usesrc
411  *   group state" change can happen only in the latter part of
412  *   ip_sioctl_slifusesrc and in ill_delete.
413  *
414  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
415  *
416  * To change the <ill-phyint> association, the ill_g_lock must be held
417  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
418  * must be held.
419  *
420  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
421  * and the ill_lock of the ill in question must be held.
422  *
423  * To change the <ill-illgroup> association the ill_g_lock must be held as
424  * writer and the ill_lock of the ill in question must be held.
425  *
426  * To add or delete an ipif from the list of ipifs hanging off the ill,
427  * ill_g_lock (writer) and ill_lock must be held and the thread must be
428  * a writer on the associated ipsq,.
429  *
430  * To add or delete an ill to the system, the ill_g_lock must be held as
431  * writer and the thread must be a writer on the associated ipsq.
432  *
433  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
434  * must be a writer on the associated ipsq.
435  *
436  * Lock hierarchy
437  *
438  * Some lock hierarchy scenarios are listed below.
439  *
440  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
441  * ill_g_lock -> illgrp_lock -> ill_lock
442  * ill_g_lock -> ill_lock(s) -> phyint_lock
443  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
444  * ill_g_lock -> ip_addr_avail_lock
445  * conn_lock -> irb_lock -> ill_lock -> ire_lock
446  * ill_g_lock -> ip_g_nd_lock
447  *
448  * When more than 1 ill lock is needed to be held, all ill lock addresses
449  * are sorted on address and locked starting from highest addressed lock
450  * downward.
451  *
452  * Mobile-IP scenarios
453  *
454  * irb_lock -> ill_lock -> ire_mrtun_lock
455  * irb_lock -> ill_lock -> ire_srcif_table_lock
456  *
457  * IPsec scenarios
458  *
459  * ipsa_lock -> ill_g_lock -> ill_lock
460  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
461  * ipsec_capab_ills_lock -> ipsa_lock
462  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
463  *
464  * Trusted Solaris scenarios
465  *
466  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
467  * igsa_lock -> gcdb_lock
468  * gcgrp_rwlock -> ire_lock
469  * gcgrp_rwlock -> gcdb_lock
470  *
471  *
472  * Routing/forwarding table locking notes:
473  *
474  * Lock acquisition order: Radix tree lock, irb_lock.
475  * Requirements:
476  * i.  Walker must not hold any locks during the walker callback.
477  * ii  Walker must not see a truncated tree during the walk because of any node
478  *     deletion.
479  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
480  *     in many places in the code to walk the irb list. Thus even if all the
481  *     ires in a bucket have been deleted, we still can't free the radix node
482  *     until the ires have actually been inactive'd (freed).
483  *
484  * Tree traversal - Need to hold the global tree lock in read mode.
485  * Before dropping the global tree lock, need to either increment the ire_refcnt
486  * to ensure that the radix node can't be deleted.
487  *
488  * Tree add - Need to hold the global tree lock in write mode to add a
489  * radix node. To prevent the node from being deleted, increment the
490  * irb_refcnt, after the node is added to the tree. The ire itself is
491  * added later while holding the irb_lock, but not the tree lock.
492  *
493  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
494  * All associated ires must be inactive (i.e. freed), and irb_refcnt
495  * must be zero.
496  *
497  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
498  * global tree lock (read mode) for traversal.
499  *
500  * IPSEC notes :
501  *
502  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
503  * in front of the actual packet. For outbound datagrams, the M_CTL
504  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
505  * information used by the IPSEC code for applying the right level of
506  * protection. The information initialized by IP in the ipsec_out_t
507  * is determined by the per-socket policy or global policy in the system.
508  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
509  * ipsec_info.h) which starts out with nothing in it. It gets filled
510  * with the right information if it goes through the AH/ESP code, which
511  * happens if the incoming packet is secure. The information initialized
512  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
513  * the policy requirements needed by per-socket policy or global policy
514  * is met or not.
515  *
516  * If there is both per-socket policy (set using setsockopt) and there
517  * is also global policy match for the 5 tuples of the socket,
518  * ipsec_override_policy() makes the decision of which one to use.
519  *
520  * For fully connected sockets i.e dst, src [addr, port] is known,
521  * conn_policy_cached is set indicating that policy has been cached.
522  * conn_in_enforce_policy may or may not be set depending on whether
523  * there is a global policy match or per-socket policy match.
524  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
525  * Once the right policy is set on the conn_t, policy cannot change for
526  * this socket. This makes life simpler for TCP (UDP ?) where
527  * re-transmissions go out with the same policy. For symmetry, policy
528  * is cached for fully connected UDP sockets also. Thus if policy is cached,
529  * it also implies that policy is latched i.e policy cannot change
530  * on these sockets. As we have the right policy on the conn, we don't
531  * have to lookup global policy for every outbound and inbound datagram
532  * and thus serving as an optimization. Note that a global policy change
533  * does not affect fully connected sockets if they have policy. If fully
534  * connected sockets did not have any policy associated with it, global
535  * policy change may affect them.
536  *
537  * IP Flow control notes:
538  *
539  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
540  * cannot be sent down to the driver by IP, because of a canput failure, IP
541  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
542  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
543  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
544  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
545  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
546  * the queued messages, and removes the conn from the drain list, if all
547  * messages were drained. It also qenables the next conn in the drain list to
548  * continue the drain process.
549  *
550  * In reality the drain list is not a single list, but a configurable number
551  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
552  * list. If the ip_wsrv of the next qenabled conn does not run, because the
553  * stream closes, ip_close takes responsibility to qenable the next conn in
554  * the drain list. The directly called ip_wput path always does a putq, if
555  * it cannot putnext. Thus synchronization problems are handled between
556  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
557  * functions that manipulate this drain list. Furthermore conn_drain_insert
558  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
559  * running on a queue at any time. conn_drain_tail can be simultaneously called
560  * from both ip_wsrv and ip_close.
561  *
562  * IPQOS notes:
563  *
564  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
565  * and IPQoS modules. IPPF includes hooks in IP at different control points
566  * (callout positions) which direct packets to IPQoS modules for policy
567  * processing. Policies, if present, are global.
568  *
569  * The callout positions are located in the following paths:
570  *		o local_in (packets destined for this host)
571  *		o local_out (packets orginating from this host )
572  *		o fwd_in  (packets forwarded by this m/c - inbound)
573  *		o fwd_out (packets forwarded by this m/c - outbound)
574  * Hooks at these callout points can be enabled/disabled using the ndd variable
575  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
576  * By default all the callout positions are enabled.
577  *
578  * Outbound (local_out)
579  * Hooks are placed in ip_wput_ire and ipsec_out_process.
580  *
581  * Inbound (local_in)
582  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
583  * TCP and UDP fanout routines.
584  *
585  * Forwarding (in and out)
586  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
587  *
588  * IP Policy Framework processing (IPPF processing)
589  * Policy processing for a packet is initiated by ip_process, which ascertains
590  * that the classifier (ipgpc) is loaded and configured, failing which the
591  * packet resumes normal processing in IP. If the clasifier is present, the
592  * packet is acted upon by one or more IPQoS modules (action instances), per
593  * filters configured in ipgpc and resumes normal IP processing thereafter.
594  * An action instance can drop a packet in course of its processing.
595  *
596  * A boolean variable, ip_policy, is used in all the fanout routines that can
597  * invoke ip_process for a packet. This variable indicates if the packet should
598  * to be sent for policy processing. The variable is set to B_TRUE by default,
599  * i.e. when the routines are invoked in the normal ip procesing path for a
600  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
601  * ip_policy is set to B_FALSE for all the routines called in these two
602  * functions because, in the former case,  we don't process loopback traffic
603  * currently while in the latter, the packets have already been processed in
604  * icmp_inbound.
605  *
606  * Zones notes:
607  *
608  * The partitioning rules for networking are as follows:
609  * 1) Packets coming from a zone must have a source address belonging to that
610  * zone.
611  * 2) Packets coming from a zone can only be sent on a physical interface on
612  * which the zone has an IP address.
613  * 3) Between two zones on the same machine, packet delivery is only allowed if
614  * there's a matching route for the destination and zone in the forwarding
615  * table.
616  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
617  * different zones can bind to the same port with the wildcard address
618  * (INADDR_ANY).
619  *
620  * The granularity of interface partitioning is at the logical interface level.
621  * Therefore, every zone has its own IP addresses, and incoming packets can be
622  * attributed to a zone unambiguously. A logical interface is placed into a zone
623  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
624  * structure. Rule (1) is implemented by modifying the source address selection
625  * algorithm so that the list of eligible addresses is filtered based on the
626  * sending process zone.
627  *
628  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
629  * across all zones, depending on their type. Here is the break-up:
630  *
631  * IRE type				Shared/exclusive
632  * --------				----------------
633  * IRE_BROADCAST			Exclusive
634  * IRE_DEFAULT (default routes)		Shared (*)
635  * IRE_LOCAL				Exclusive (x)
636  * IRE_LOOPBACK				Exclusive
637  * IRE_PREFIX (net routes)		Shared (*)
638  * IRE_CACHE				Exclusive
639  * IRE_IF_NORESOLVER (interface routes)	Exclusive
640  * IRE_IF_RESOLVER (interface routes)	Exclusive
641  * IRE_HOST (host routes)		Shared (*)
642  *
643  * (*) A zone can only use a default or off-subnet route if the gateway is
644  * directly reachable from the zone, that is, if the gateway's address matches
645  * one of the zone's logical interfaces.
646  *
647  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
648  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
649  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
650  * address of the zone itself (the destination). Since IRE_LOCAL is used
651  * for communication between zones, ip_wput_ire has special logic to set
652  * the right source address when sending using an IRE_LOCAL.
653  *
654  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
655  * ire_cache_lookup restricts loopback using an IRE_LOCAL
656  * between zone to the case when L2 would have conceptually looped the packet
657  * back, i.e. the loopback which is required since neither Ethernet drivers
658  * nor Ethernet hardware loops them back. This is the case when the normal
659  * routes (ignoring IREs with different zoneids) would send out the packet on
660  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
661  * associated.
662  *
663  * Multiple zones can share a common broadcast address; typically all zones
664  * share the 255.255.255.255 address. Incoming as well as locally originated
665  * broadcast packets must be dispatched to all the zones on the broadcast
666  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
667  * since some zones may not be on the 10.16.72/24 network. To handle this, each
668  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
669  * sent to every zone that has an IRE_BROADCAST entry for the destination
670  * address on the input ill, see conn_wantpacket().
671  *
672  * Applications in different zones can join the same multicast group address.
673  * For IPv4, group memberships are per-logical interface, so they're already
674  * inherently part of a zone. For IPv6, group memberships are per-physical
675  * interface, so we distinguish IPv6 group memberships based on group address,
676  * interface and zoneid. In both cases, received multicast packets are sent to
677  * every zone for which a group membership entry exists. On IPv6 we need to
678  * check that the target zone still has an address on the receiving physical
679  * interface; it could have been removed since the application issued the
680  * IPV6_JOIN_GROUP.
681  */
682 
683 /*
684  * Squeue Fanout flags:
685  *	0: No fanout.
686  *	1: Fanout across all squeues
687  */
688 boolean_t	ip_squeue_fanout = 0;
689 
690 /*
691  * Maximum dups allowed per packet.
692  */
693 uint_t ip_max_frag_dups = 10;
694 
695 #define	IS_SIMPLE_IPH(ipha)						\
696 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
697 
698 /* RFC1122 Conformance */
699 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
700 
701 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
702 
703 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
704 
705 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
706 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
707 
708 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t);
709 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
710     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
711 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
712 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
713 		    mblk_t *, int);
714 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
715 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
716 		    ill_t *, zoneid_t);
717 static void	icmp_options_update(ipha_t *);
718 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t);
719 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
720 		    zoneid_t zoneid);
721 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
722 static void	icmp_redirect(mblk_t *);
723 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
724 
725 static void	ip_arp_news(queue_t *, mblk_t *);
726 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
727 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
728 char		*ip_dot_addr(ipaddr_t, char *);
729 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
730 int		ip_close(queue_t *, int);
731 static char	*ip_dot_saddr(uchar_t *, char *);
732 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
733 		    boolean_t, boolean_t, ill_t *, zoneid_t);
734 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
735 		    boolean_t, boolean_t, zoneid_t);
736 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
737 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
738 static void	ip_lrput(queue_t *, mblk_t *);
739 ipaddr_t	ip_massage_options(ipha_t *);
740 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
741 ipaddr_t	ip_net_mask(ipaddr_t);
742 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
743 		    zoneid_t);
744 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
745 		    conn_t *, uint32_t, zoneid_t);
746 char		*ip_nv_lookup(nv_t *, int);
747 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
748 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
749 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
750 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
751 			    size_t);
752 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
753 void	ip_rput(queue_t *, mblk_t *);
754 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
755 		    void *dummy_arg);
756 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
757 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
758 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
759 			    ire_t *);
760 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
761 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
762 		    uint16_t *);
763 int		ip_snmp_get(queue_t *, mblk_t *);
764 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
765 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
766 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
767 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
768 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
769 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
770 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
771 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
772 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
773 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
775 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
776 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
777 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
778 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
779 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
780 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
781 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
782 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
783 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
784 static boolean_t	ip_source_routed(ipha_t *);
785 static boolean_t	ip_source_route_included(ipha_t *);
786 
787 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
788 		    zoneid_t);
789 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
790 static void	ip_wput_local_options(ipha_t *);
791 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
792 		    zoneid_t);
793 
794 static void	conn_drain_init(void);
795 static void	conn_drain_fini(void);
796 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
797 
798 static void	conn_walk_drain(void);
799 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
800     zoneid_t);
801 
802 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
803     zoneid_t);
804 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
805     void *dummy_arg);
806 
807 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
808 
809 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
810     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
811     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
812 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
813 
814 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
815 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
816     caddr_t, cred_t *);
817 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
818     caddr_t cp, cred_t *cr);
819 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
820     cred_t *);
821 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
822     caddr_t cp, cred_t *cr);
823 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
824     cred_t *);
825 static squeue_func_t ip_squeue_switch(int);
826 
827 static void	ip_kstat_init(void);
828 static void	ip_kstat_fini(void);
829 static int	ip_kstat_update(kstat_t *kp, int rw);
830 static void	icmp_kstat_init(void);
831 static void	icmp_kstat_fini(void);
832 static int	icmp_kstat_update(kstat_t *kp, int rw);
833 
834 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
835 
836 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
837     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
838 
839 void	ip_input(ill_t *, ill_rx_ring_t *, mblk_t *, size_t);
840 
841 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
842     ipha_t *, ill_t *, boolean_t);
843 
844 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
845 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
846 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
847 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
848 
849 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
850 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
851 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
852 
853 /* How long, in seconds, we allow frags to hang around. */
854 #define	IP_FRAG_TIMEOUT	60
855 
856 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
857 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
858 
859 /*
860  * Threshold which determines whether MDT should be used when
861  * generating IP fragments; payload size must be greater than
862  * this threshold for MDT to take place.
863  */
864 #define	IP_WPUT_FRAG_MDT_MIN	32768
865 
866 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
867 
868 /* Protected by ip_mi_lock */
869 static void	*ip_g_head;		/* Instance Data List Head */
870 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
871 
872 /* Only modified during _init and _fini thus no locking is needed. */
873 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
874 
875 
876 static long ip_rput_pullups;
877 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
878 
879 vmem_t *ip_minor_arena;
880 
881 /*
882  * MIB-2 stuff for SNMP (both IP and ICMP)
883  */
884 mib2_ip_t	ip_mib;
885 mib2_icmp_t	icmp_mib;
886 
887 #ifdef DEBUG
888 uint32_t ipsechw_debug = 0;
889 #endif
890 
891 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
892 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
893 
894 uint_t	loopback_packets = 0;
895 
896 /*
897  * Multirouting/CGTP stuff
898  */
899 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
900 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
901 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
902 /* Interval (in ms) between consecutive 'bad MTU' warnings */
903 hrtime_t ip_multirt_log_interval = 1000;
904 /* Time since last warning issued. */
905 static hrtime_t	multirt_bad_mtu_last_time = 0;
906 
907 kmutex_t ip_trash_timer_lock;
908 krwlock_t ip_g_nd_lock;
909 
910 /*
911  * XXX following really should only be in a header. Would need more
912  * header and .c clean up first.
913  */
914 extern optdb_obj_t	ip_opt_obj;
915 
916 ulong_t ip_squeue_enter_unbound = 0;
917 
918 /*
919  * Named Dispatch Parameter Table.
920  * All of these are alterable, within the min/max values given, at run time.
921  */
922 static ipparam_t	lcl_param_arr[] = {
923 	/* min	max	value	name */
924 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
925 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
926 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
927 	{  0,	1,	0,	"ip_respond_to_timestamp"},
928 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
929 	{  0,	1,	1,	"ip_send_redirects"},
930 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
931 	{  0,	10,	0,	"ip_debug"},
932 	{  0,	10,	0,	"ip_mrtdebug"},
933 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
934 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
935 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
936 	{  1,	255,	255,	"ip_def_ttl" },
937 	{  0,	1,	0,	"ip_forward_src_routed"},
938 	{  0,	256,	32,	"ip_wroff_extra" },
939 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
940 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
941 	{  0,	1,	1,	"ip_path_mtu_discovery" },
942 	{  0,	240,	30,	"ip_ignore_delete_time" },
943 	{  0,	1,	0,	"ip_ignore_redirect" },
944 	{  0,	1,	1,	"ip_output_queue" },
945 	{  1,	254,	1,	"ip_broadcast_ttl" },
946 	{  0,	99999,	100,	"ip_icmp_err_interval" },
947 	{  1,	99999,	10,	"ip_icmp_err_burst" },
948 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
949 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
950 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
951 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
952 	{  0,	1,	1,	"icmp_accept_clear_messages" },
953 	{  0,	1,	1,	"igmp_accept_clear_messages" },
954 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
955 				"ip_ndp_delay_first_probe_time"},
956 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
957 				"ip_ndp_max_unicast_solicit"},
958 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
959 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
960 	{  0,	1,	0,	"ip6_forward_src_routed"},
961 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
962 	{  0,	1,	1,	"ip6_send_redirects"},
963 	{  0,	1,	0,	"ip6_ignore_redirect" },
964 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
965 
966 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
967 
968 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
969 
970 	{  0,	1,	1,	"pim_accept_clear_messages" },
971 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
972 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
973 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
974 	{  0,	15,	0,	"ip_policy_mask" },
975 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
976 	{  0,	255,	1,	"ip_multirt_ttl" },
977 	{  0,	1,	1,	"ip_multidata_outbound" },
978 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
979 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
980 	{  0,	1000,	1,	"ip_max_temp_defend" },
981 	{  0,	1000,	3,	"ip_max_defend" },
982 	{  0,	999999,	30,	"ip_defend_interval" },
983 	{  0,	3600000, 300000, "ip_dup_recovery" },
984 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
985 #ifdef DEBUG
986 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
987 #endif
988 };
989 
990 ipparam_t	*ip_param_arr = lcl_param_arr;
991 
992 /* Extended NDP table */
993 static ipndp_t	lcl_ndp_arr[] = {
994 	/* getf			setf		data			name */
995 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
996 	    "ip_forwarding" },
997 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
998 	    "ip6_forwarding" },
999 	{  ip_ill_report,	NULL,		NULL,
1000 	    "ip_ill_status" },
1001 	{  ip_ipif_report,	NULL,		NULL,
1002 	    "ip_ipif_status" },
1003 	{  ip_ire_report,	NULL,		NULL,
1004 	    "ipv4_ire_status" },
1005 	{  ip_ire_report_mrtun,	NULL,		NULL,
1006 	    "ipv4_mrtun_ire_status" },
1007 	{  ip_ire_report_srcif,	NULL,		NULL,
1008 	    "ipv4_srcif_ire_status" },
1009 	{  ip_ire_report_v6,	NULL,		NULL,
1010 	    "ipv6_ire_status" },
1011 	{  ip_conn_report,	NULL,		NULL,
1012 	    "ip_conn_status" },
1013 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1014 	    "ip_rput_pullups" },
1015 	{  ndp_report,		NULL,		NULL,
1016 	    "ip_ndp_cache_report" },
1017 	{  ip_srcid_report,	NULL,		NULL,
1018 	    "ip_srcid_status" },
1019 	{ ip_param_generic_get, ip_squeue_profile_set,
1020 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
1021 	{ ip_param_generic_get, ip_squeue_bind_set,
1022 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
1023 	{ ip_param_generic_get, ip_input_proc_set,
1024 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1025 	{ ip_param_generic_get, ip_int_set,
1026 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1027 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
1028 	    "ip_cgtp_filter" },
1029 	{ ip_param_generic_get, ip_int_set,
1030 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
1031 };
1032 
1033 /*
1034  * ip_g_forward controls IP forwarding.  It takes two values:
1035  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
1036  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
1037  *
1038  * RFC1122 says there must be a configuration switch to control forwarding,
1039  * but that the default MUST be to not forward packets ever.  Implicit
1040  * control based on configuration of multiple interfaces MUST NOT be
1041  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
1042  * and, in fact, it was the default.  That capability is now provided in the
1043  * /etc/rc2.d/S69inet script.
1044  */
1045 int ip_g_forward = IP_FORWARD_DEFAULT;
1046 
1047 /* It also has an IPv6 counterpart. */
1048 
1049 int ipv6_forward = IP_FORWARD_DEFAULT;
1050 
1051 /*
1052  * Table of IP ioctls encoding the various properties of the ioctl and
1053  * indexed based on the last byte of the ioctl command. Occasionally there
1054  * is a clash, and there is more than 1 ioctl with the same last byte.
1055  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1056  * ioctls are encoded in the misc table. An entry in the ndx table is
1057  * retrieved by indexing on the last byte of the ioctl command and comparing
1058  * the ioctl command with the value in the ndx table. In the event of a
1059  * mismatch the misc table is then searched sequentially for the desired
1060  * ioctl command.
1061  *
1062  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1063  */
1064 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1065 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 
1076 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1077 			MISC_CMD, ip_siocaddrt, NULL },
1078 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1079 			MISC_CMD, ip_siocdelrt, NULL },
1080 
1081 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1082 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1083 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1084 			IF_CMD, ip_sioctl_get_addr, NULL },
1085 
1086 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1087 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1088 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1089 			IPI_GET_CMD | IPI_REPL,
1090 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1091 
1092 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1093 			IPI_PRIV | IPI_WR | IPI_REPL,
1094 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1095 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1096 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1097 			IF_CMD, ip_sioctl_get_flags, NULL },
1098 
1099 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 
1102 	/* copyin size cannot be coded for SIOCGIFCONF */
1103 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1104 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1105 
1106 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1107 			IF_CMD, ip_sioctl_mtu, NULL },
1108 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1109 			IF_CMD, ip_sioctl_get_mtu, NULL },
1110 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1111 			IPI_GET_CMD | IPI_REPL,
1112 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1113 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1114 			IF_CMD, ip_sioctl_brdaddr, NULL },
1115 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1116 			IPI_GET_CMD | IPI_REPL,
1117 			IF_CMD, ip_sioctl_get_netmask, NULL },
1118 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1119 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1120 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1121 			IPI_GET_CMD | IPI_REPL,
1122 			IF_CMD, ip_sioctl_get_metric, NULL },
1123 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1124 			IF_CMD, ip_sioctl_metric, NULL },
1125 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 
1127 	/* See 166-168 below for extended SIOC*XARP ioctls */
1128 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1129 			MISC_CMD, ip_sioctl_arp, NULL },
1130 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1131 			MISC_CMD, ip_sioctl_arp, NULL },
1132 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1133 			MISC_CMD, ip_sioctl_arp, NULL },
1134 
1135 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1136 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 
1157 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1158 			MISC_CMD, if_unitsel, if_unitsel_restart },
1159 
1160 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1161 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 
1179 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1180 			IPI_PRIV | IPI_WR | IPI_MODOK,
1181 			IF_CMD, ip_sioctl_sifname, NULL },
1182 
1183 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1190 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 
1197 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1198 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1199 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1200 			IF_CMD, ip_sioctl_get_muxid, NULL },
1201 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1202 			IPI_PRIV | IPI_WR | IPI_REPL,
1203 			IF_CMD, ip_sioctl_muxid, NULL },
1204 
1205 	/* Both if and lif variants share same func */
1206 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1207 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1208 	/* Both if and lif variants share same func */
1209 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1210 			IPI_PRIV | IPI_WR | IPI_REPL,
1211 			IF_CMD, ip_sioctl_slifindex, NULL },
1212 
1213 	/* copyin size cannot be coded for SIOCGIFCONF */
1214 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1215 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1216 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1217 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1218 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1219 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1220 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1221 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1222 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1223 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1226 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1227 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1228 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1229 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1230 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1231 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1232 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1233 
1234 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1235 			IPI_PRIV | IPI_WR | IPI_REPL,
1236 			LIF_CMD, ip_sioctl_removeif,
1237 			ip_sioctl_removeif_restart },
1238 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1239 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1240 			LIF_CMD, ip_sioctl_addif, NULL },
1241 #define	SIOCLIFADDR_NDX 112
1242 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1243 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1244 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1245 			IPI_GET_CMD | IPI_REPL,
1246 			LIF_CMD, ip_sioctl_get_addr, NULL },
1247 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1248 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1249 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1250 			IPI_GET_CMD | IPI_REPL,
1251 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1252 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1253 			IPI_PRIV | IPI_WR | IPI_REPL,
1254 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1255 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1256 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1257 			LIF_CMD, ip_sioctl_get_flags, NULL },
1258 
1259 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1260 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1261 
1262 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1263 			ip_sioctl_get_lifconf, NULL },
1264 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1265 			LIF_CMD, ip_sioctl_mtu, NULL },
1266 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1267 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1268 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1269 			IPI_GET_CMD | IPI_REPL,
1270 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1271 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1272 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1273 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1274 			IPI_GET_CMD | IPI_REPL,
1275 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1276 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1277 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1278 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1279 			IPI_GET_CMD | IPI_REPL,
1280 			LIF_CMD, ip_sioctl_get_metric, NULL },
1281 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1282 			LIF_CMD, ip_sioctl_metric, NULL },
1283 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1284 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1285 			LIF_CMD, ip_sioctl_slifname,
1286 			ip_sioctl_slifname_restart },
1287 
1288 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1289 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1290 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1291 			IPI_GET_CMD | IPI_REPL,
1292 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1293 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1294 			IPI_PRIV | IPI_WR | IPI_REPL,
1295 			LIF_CMD, ip_sioctl_muxid, NULL },
1296 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1297 			IPI_GET_CMD | IPI_REPL,
1298 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1299 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1300 			IPI_PRIV | IPI_WR | IPI_REPL,
1301 			LIF_CMD, ip_sioctl_slifindex, 0 },
1302 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1303 			LIF_CMD, ip_sioctl_token, NULL },
1304 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1305 			IPI_GET_CMD | IPI_REPL,
1306 			LIF_CMD, ip_sioctl_get_token, NULL },
1307 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1308 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1309 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1310 			IPI_GET_CMD | IPI_REPL,
1311 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1312 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1313 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1314 
1315 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1316 			IPI_GET_CMD | IPI_REPL,
1317 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1318 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1319 			LIF_CMD, ip_siocdelndp_v6, NULL },
1320 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1321 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1322 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1323 			LIF_CMD, ip_siocsetndp_v6, NULL },
1324 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1325 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1326 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1327 			MISC_CMD, ip_sioctl_tonlink, NULL },
1328 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1329 			MISC_CMD, ip_sioctl_tmysite, NULL },
1330 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1331 			TUN_CMD, ip_sioctl_tunparam, NULL },
1332 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1333 			IPI_PRIV | IPI_WR,
1334 			TUN_CMD, ip_sioctl_tunparam, NULL },
1335 
1336 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1337 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1338 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1339 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1340 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1341 
1342 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1343 			IPI_PRIV | IPI_WR | IPI_REPL,
1344 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1345 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1346 			IPI_PRIV | IPI_WR | IPI_REPL,
1347 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1348 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1349 			IPI_PRIV | IPI_WR,
1350 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1351 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1352 			IPI_GET_CMD | IPI_REPL,
1353 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1354 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1355 			IPI_GET_CMD | IPI_REPL,
1356 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1357 
1358 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1359 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1360 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1361 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1362 
1363 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1364 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1365 
1366 	/* These are handled in ip_sioctl_copyin_setup itself */
1367 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1368 			MISC_CMD, NULL, NULL },
1369 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1370 			MISC_CMD, NULL, NULL },
1371 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1372 
1373 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1374 			ip_sioctl_get_lifconf, NULL },
1375 
1376 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1377 			MISC_CMD, ip_sioctl_xarp, NULL },
1378 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1379 			MISC_CMD, ip_sioctl_xarp, NULL },
1380 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1381 			MISC_CMD, ip_sioctl_xarp, NULL },
1382 
1383 	/* SIOCPOPSOCKFS is not handled by IP */
1384 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1385 
1386 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1387 			IPI_GET_CMD | IPI_REPL,
1388 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1389 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1390 			IPI_PRIV | IPI_WR | IPI_REPL,
1391 			LIF_CMD, ip_sioctl_slifzone,
1392 			ip_sioctl_slifzone_restart },
1393 	/* 172-174 are SCTP ioctls and not handled by IP */
1394 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1395 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1396 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1397 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1398 			IPI_GET_CMD, LIF_CMD,
1399 			ip_sioctl_get_lifusesrc, 0 },
1400 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1401 			IPI_PRIV | IPI_WR,
1402 			LIF_CMD, ip_sioctl_slifusesrc,
1403 			NULL },
1404 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1405 			ip_sioctl_get_lifsrcof, NULL },
1406 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1407 			MISC_CMD, ip_sioctl_msfilter, NULL },
1408 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1409 			MISC_CMD, ip_sioctl_msfilter, NULL },
1410 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1411 			MISC_CMD, ip_sioctl_msfilter, NULL },
1412 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1413 			MISC_CMD, ip_sioctl_msfilter, NULL },
1414 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1415 			ip_sioctl_set_ipmpfailback, NULL }
1416 };
1417 
1418 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1419 
1420 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1421 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1422 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1423 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1424 		TUN_CMD, ip_sioctl_tunparam, NULL },
1425 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1426 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1427 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1428 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1429 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1430 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1431 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1432 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1433 		MISC_CMD, mrt_ioctl},
1434 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1435 		MISC_CMD, mrt_ioctl},
1436 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1437 		MISC_CMD, mrt_ioctl}
1438 };
1439 
1440 int ip_misc_ioctl_count =
1441     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1442 
1443 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1444 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1445 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1446 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1447 					/* Settable in /etc/system */
1448 uint_t	ip_redirect_cnt;		/* Num of redirect routes in ftable */
1449 
1450 /* Defined in ip_ire.c */
1451 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1452 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1453 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1454 
1455 static nv_t	ire_nv_arr[] = {
1456 	{ IRE_BROADCAST, "BROADCAST" },
1457 	{ IRE_LOCAL, "LOCAL" },
1458 	{ IRE_LOOPBACK, "LOOPBACK" },
1459 	{ IRE_CACHE, "CACHE" },
1460 	{ IRE_DEFAULT, "DEFAULT" },
1461 	{ IRE_PREFIX, "PREFIX" },
1462 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1463 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1464 	{ IRE_HOST, "HOST" },
1465 	{ IRE_HOST_REDIRECT, "HOST_REDIRECT" },
1466 	{ 0 }
1467 };
1468 
1469 nv_t	*ire_nv_tbl = ire_nv_arr;
1470 
1471 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1472 extern krwlock_t ipsec_capab_ills_lock;
1473 
1474 /* Packet dropper for IP IPsec processing failures */
1475 ipdropper_t ip_dropper;
1476 
1477 /* Simple ICMP IP Header Template */
1478 static ipha_t icmp_ipha = {
1479 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1480 };
1481 
1482 struct module_info ip_mod_info = {
1483 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1484 };
1485 
1486 /*
1487  * Duplicate static symbols within a module confuses mdb; so we avoid the
1488  * problem by making the symbols here distinct from those in udp.c.
1489  */
1490 
1491 static struct qinit iprinit = {
1492 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1493 	&ip_mod_info
1494 };
1495 
1496 static struct qinit ipwinit = {
1497 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1498 	&ip_mod_info
1499 };
1500 
1501 static struct qinit iplrinit = {
1502 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1503 	&ip_mod_info
1504 };
1505 
1506 static struct qinit iplwinit = {
1507 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1508 	&ip_mod_info
1509 };
1510 
1511 struct streamtab ipinfo = {
1512 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1513 };
1514 
1515 #ifdef	DEBUG
1516 static boolean_t skip_sctp_cksum = B_FALSE;
1517 #endif
1518 
1519 /*
1520  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1521  * ip_rput_v6(), ip_output(), etc.  If the message
1522  * block already has a M_CTL at the front of it, then simply set the zoneid
1523  * appropriately.
1524  */
1525 mblk_t *
1526 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid)
1527 {
1528 	mblk_t		*first_mp;
1529 	ipsec_out_t	*io;
1530 
1531 	ASSERT(zoneid != ALL_ZONES);
1532 	if (mp->b_datap->db_type == M_CTL) {
1533 		io = (ipsec_out_t *)mp->b_rptr;
1534 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1535 		io->ipsec_out_zoneid = zoneid;
1536 		return (mp);
1537 	}
1538 
1539 	first_mp = ipsec_alloc_ipsec_out();
1540 	if (first_mp == NULL)
1541 		return (NULL);
1542 	io = (ipsec_out_t *)first_mp->b_rptr;
1543 	/* This is not a secure packet */
1544 	io->ipsec_out_secure = B_FALSE;
1545 	io->ipsec_out_zoneid = zoneid;
1546 	first_mp->b_cont = mp;
1547 	return (first_mp);
1548 }
1549 
1550 /*
1551  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1552  */
1553 mblk_t *
1554 ip_copymsg(mblk_t *mp)
1555 {
1556 	mblk_t *nmp;
1557 	ipsec_info_t *in;
1558 
1559 	if (mp->b_datap->db_type != M_CTL)
1560 		return (copymsg(mp));
1561 
1562 	in = (ipsec_info_t *)mp->b_rptr;
1563 
1564 	/*
1565 	 * Note that M_CTL is also used for delivering ICMP error messages
1566 	 * upstream to transport layers.
1567 	 */
1568 	if (in->ipsec_info_type != IPSEC_OUT &&
1569 	    in->ipsec_info_type != IPSEC_IN)
1570 		return (copymsg(mp));
1571 
1572 	nmp = copymsg(mp->b_cont);
1573 
1574 	if (in->ipsec_info_type == IPSEC_OUT)
1575 		return (ipsec_out_tag(mp, nmp));
1576 	else
1577 		return (ipsec_in_tag(mp, nmp));
1578 }
1579 
1580 /* Generate an ICMP fragmentation needed message. */
1581 static void
1582 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid)
1583 {
1584 	icmph_t	icmph;
1585 	mblk_t *first_mp;
1586 	boolean_t mctl_present;
1587 
1588 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1589 
1590 	if (!(mp = icmp_pkt_err_ok(mp))) {
1591 		if (mctl_present)
1592 			freeb(first_mp);
1593 		return;
1594 	}
1595 
1596 	bzero(&icmph, sizeof (icmph_t));
1597 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1598 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1599 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1600 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1601 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1602 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
1603 }
1604 
1605 /*
1606  * icmp_inbound deals with ICMP messages in the following ways.
1607  *
1608  * 1) It needs to send a reply back and possibly delivering it
1609  *    to the "interested" upper clients.
1610  * 2) It needs to send it to the upper clients only.
1611  * 3) It needs to change some values in IP only.
1612  * 4) It needs to change some values in IP and upper layers e.g TCP.
1613  *
1614  * We need to accomodate icmp messages coming in clear until we get
1615  * everything secure from the wire. If icmp_accept_clear_messages
1616  * is zero we check with the global policy and act accordingly. If
1617  * it is non-zero, we accept the message without any checks. But
1618  * *this does not mean* that this will be delivered to the upper
1619  * clients. By accepting we might send replies back, change our MTU
1620  * value etc. but delivery to the ULP/clients depends on their policy
1621  * dispositions.
1622  *
1623  * We handle the above 4 cases in the context of IPSEC in the
1624  * following way :
1625  *
1626  * 1) Send the reply back in the same way as the request came in.
1627  *    If it came in encrypted, it goes out encrypted. If it came in
1628  *    clear, it goes out in clear. Thus, this will prevent chosen
1629  *    plain text attack.
1630  * 2) The client may or may not expect things to come in secure.
1631  *    If it comes in secure, the policy constraints are checked
1632  *    before delivering it to the upper layers. If it comes in
1633  *    clear, ipsec_inbound_accept_clear will decide whether to
1634  *    accept this in clear or not. In both the cases, if the returned
1635  *    message (IP header + 8 bytes) that caused the icmp message has
1636  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1637  *    sending up. If there are only 8 bytes of returned message, then
1638  *    upper client will not be notified.
1639  * 3) Check with global policy to see whether it matches the constaints.
1640  *    But this will be done only if icmp_accept_messages_in_clear is
1641  *    zero.
1642  * 4) If we need to change both in IP and ULP, then the decision taken
1643  *    while affecting the values in IP and while delivering up to TCP
1644  *    should be the same.
1645  *
1646  * 	There are two cases.
1647  *
1648  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1649  *	   failed), we will not deliver it to the ULP, even though they
1650  *	   are *willing* to accept in *clear*. This is fine as our global
1651  *	   disposition to icmp messages asks us reject the datagram.
1652  *
1653  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1654  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1655  *	   to deliver it to ULP (policy failed), it can lead to
1656  *	   consistency problems. The cases known at this time are
1657  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1658  *	   values :
1659  *
1660  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1661  *	     and Upper layer rejects. Then the communication will
1662  *	     come to a stop. This is solved by making similar decisions
1663  *	     at both levels. Currently, when we are unable to deliver
1664  *	     to the Upper Layer (due to policy failures) while IP has
1665  *	     adjusted ire_max_frag, the next outbound datagram would
1666  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1667  *	     will be with the right level of protection. Thus the right
1668  *	     value will be communicated even if we are not able to
1669  *	     communicate when we get from the wire initially. But this
1670  *	     assumes there would be at least one outbound datagram after
1671  *	     IP has adjusted its ire_max_frag value. To make things
1672  *	     simpler, we accept in clear after the validation of
1673  *	     AH/ESP headers.
1674  *
1675  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1676  *	     upper layer depending on the level of protection the upper
1677  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1678  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1679  *	     should be accepted in clear when the Upper layer expects secure.
1680  *	     Thus the communication may get aborted by some bad ICMP
1681  *	     packets.
1682  *
1683  * IPQoS Notes:
1684  * The only instance when a packet is sent for processing is when there
1685  * isn't an ICMP client and if we are interested in it.
1686  * If there is a client, IPPF processing will take place in the
1687  * ip_fanout_proto routine.
1688  *
1689  * Zones notes:
1690  * The packet is only processed in the context of the specified zone: typically
1691  * only this zone will reply to an echo request, and only interested clients in
1692  * this zone will receive a copy of the packet. This means that the caller must
1693  * call icmp_inbound() for each relevant zone.
1694  */
1695 static void
1696 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1697     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1698     ill_t *recv_ill, zoneid_t zoneid)
1699 {
1700 	icmph_t	*icmph;
1701 	ipha_t	*ipha;
1702 	int	iph_hdr_length;
1703 	int	hdr_length;
1704 	boolean_t	interested;
1705 	uint32_t	ts;
1706 	uchar_t	*wptr;
1707 	ipif_t	*ipif;
1708 	mblk_t *first_mp;
1709 	ipsec_in_t *ii;
1710 	ire_t *src_ire;
1711 	boolean_t onlink;
1712 	timestruc_t now;
1713 	uint32_t ill_index;
1714 
1715 	ASSERT(ill != NULL);
1716 
1717 	first_mp = mp;
1718 	if (mctl_present) {
1719 		mp = first_mp->b_cont;
1720 		ASSERT(mp != NULL);
1721 	}
1722 
1723 	ipha = (ipha_t *)mp->b_rptr;
1724 	if (icmp_accept_clear_messages == 0) {
1725 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1726 		    ipha, NULL, mctl_present);
1727 		if (first_mp == NULL)
1728 			return;
1729 	}
1730 
1731 	/*
1732 	 * On a labeled system, we have to check whether the zone itself is
1733 	 * permitted to receive raw traffic.
1734 	 */
1735 	if (is_system_labeled()) {
1736 		if (zoneid == ALL_ZONES)
1737 			zoneid = tsol_packet_to_zoneid(mp);
1738 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1739 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1740 			    zoneid));
1741 			BUMP_MIB(&icmp_mib, icmpInErrors);
1742 			freemsg(first_mp);
1743 			return;
1744 		}
1745 	}
1746 
1747 	/*
1748 	 * We have accepted the ICMP message. It means that we will
1749 	 * respond to the packet if needed. It may not be delivered
1750 	 * to the upper client depending on the policy constraints
1751 	 * and the disposition in ipsec_inbound_accept_clear.
1752 	 */
1753 
1754 	ASSERT(ill != NULL);
1755 
1756 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1757 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1758 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1759 		/* Last chance to get real. */
1760 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1761 			BUMP_MIB(&icmp_mib, icmpInErrors);
1762 			freemsg(first_mp);
1763 			return;
1764 		}
1765 		/* Refresh iph following the pullup. */
1766 		ipha = (ipha_t *)mp->b_rptr;
1767 	}
1768 	/* ICMP header checksum, including checksum field, should be zero. */
1769 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1770 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1771 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1772 		freemsg(first_mp);
1773 		return;
1774 	}
1775 	/* The IP header will always be a multiple of four bytes */
1776 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1777 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1778 	    icmph->icmph_code));
1779 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1780 	/* We will set "interested" to "true" if we want a copy */
1781 	interested = B_FALSE;
1782 	switch (icmph->icmph_type) {
1783 	case ICMP_ECHO_REPLY:
1784 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1785 		break;
1786 	case ICMP_DEST_UNREACHABLE:
1787 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1788 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1789 		interested = B_TRUE;	/* Pass up to transport */
1790 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1791 		break;
1792 	case ICMP_SOURCE_QUENCH:
1793 		interested = B_TRUE;	/* Pass up to transport */
1794 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1795 		break;
1796 	case ICMP_REDIRECT:
1797 		if (!ip_ignore_redirect)
1798 			interested = B_TRUE;
1799 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1800 		break;
1801 	case ICMP_ECHO_REQUEST:
1802 		/*
1803 		 * Whether to respond to echo requests that come in as IP
1804 		 * broadcasts or as IP multicast is subject to debate
1805 		 * (what isn't?).  We aim to please, you pick it.
1806 		 * Default is do it.
1807 		 */
1808 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1809 			/* unicast: always respond */
1810 			interested = B_TRUE;
1811 		} else if (CLASSD(ipha->ipha_dst)) {
1812 			/* multicast: respond based on tunable */
1813 			interested = ip_g_resp_to_echo_mcast;
1814 		} else if (broadcast) {
1815 			/* broadcast: respond based on tunable */
1816 			interested = ip_g_resp_to_echo_bcast;
1817 		}
1818 		BUMP_MIB(&icmp_mib, icmpInEchos);
1819 		break;
1820 	case ICMP_ROUTER_ADVERTISEMENT:
1821 	case ICMP_ROUTER_SOLICITATION:
1822 		break;
1823 	case ICMP_TIME_EXCEEDED:
1824 		interested = B_TRUE;	/* Pass up to transport */
1825 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1826 		break;
1827 	case ICMP_PARAM_PROBLEM:
1828 		interested = B_TRUE;	/* Pass up to transport */
1829 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1830 		break;
1831 	case ICMP_TIME_STAMP_REQUEST:
1832 		/* Response to Time Stamp Requests is local policy. */
1833 		if (ip_g_resp_to_timestamp &&
1834 		    /* So is whether to respond if it was an IP broadcast. */
1835 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1836 			int tstamp_len = 3 * sizeof (uint32_t);
1837 
1838 			if (wptr +  tstamp_len > mp->b_wptr) {
1839 				if (!pullupmsg(mp, wptr + tstamp_len -
1840 				    mp->b_rptr)) {
1841 					BUMP_MIB(&ip_mib, ipInDiscards);
1842 					freemsg(first_mp);
1843 					return;
1844 				}
1845 				/* Refresh ipha following the pullup. */
1846 				ipha = (ipha_t *)mp->b_rptr;
1847 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1848 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1849 			}
1850 			interested = B_TRUE;
1851 		}
1852 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1853 		break;
1854 	case ICMP_TIME_STAMP_REPLY:
1855 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1856 		break;
1857 	case ICMP_INFO_REQUEST:
1858 		/* Per RFC 1122 3.2.2.7, ignore this. */
1859 	case ICMP_INFO_REPLY:
1860 		break;
1861 	case ICMP_ADDRESS_MASK_REQUEST:
1862 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1863 		    /* TODO m_pullup of complete header? */
1864 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1865 			interested = B_TRUE;
1866 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1867 		break;
1868 	case ICMP_ADDRESS_MASK_REPLY:
1869 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1870 		break;
1871 	default:
1872 		interested = B_TRUE;	/* Pass up to transport */
1873 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1874 		break;
1875 	}
1876 	/* See if there is an ICMP client. */
1877 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1878 		/* If there is an ICMP client and we want one too, copy it. */
1879 		mblk_t *first_mp1;
1880 
1881 		if (!interested) {
1882 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1883 			    ip_policy, recv_ill, zoneid);
1884 			return;
1885 		}
1886 		first_mp1 = ip_copymsg(first_mp);
1887 		if (first_mp1 != NULL) {
1888 			ip_fanout_proto(q, first_mp1, ill, ipha,
1889 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1890 		}
1891 	} else if (!interested) {
1892 		freemsg(first_mp);
1893 		return;
1894 	} else {
1895 		/*
1896 		 * Initiate policy processing for this packet if ip_policy
1897 		 * is true.
1898 		 */
1899 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1900 			ill_index = ill->ill_phyint->phyint_ifindex;
1901 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1902 			if (mp == NULL) {
1903 				if (mctl_present) {
1904 					freeb(first_mp);
1905 				}
1906 				BUMP_MIB(&icmp_mib, icmpInErrors);
1907 				return;
1908 			}
1909 		}
1910 	}
1911 	/* We want to do something with it. */
1912 	/* Check db_ref to make sure we can modify the packet. */
1913 	if (mp->b_datap->db_ref > 1) {
1914 		mblk_t	*first_mp1;
1915 
1916 		first_mp1 = ip_copymsg(first_mp);
1917 		freemsg(first_mp);
1918 		if (!first_mp1) {
1919 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1920 			return;
1921 		}
1922 		first_mp = first_mp1;
1923 		if (mctl_present) {
1924 			mp = first_mp->b_cont;
1925 			ASSERT(mp != NULL);
1926 		} else {
1927 			mp = first_mp;
1928 		}
1929 		ipha = (ipha_t *)mp->b_rptr;
1930 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1931 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1932 	}
1933 	switch (icmph->icmph_type) {
1934 	case ICMP_ADDRESS_MASK_REQUEST:
1935 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1936 		if (ipif == NULL) {
1937 			freemsg(first_mp);
1938 			return;
1939 		}
1940 		/*
1941 		 * outging interface must be IPv4
1942 		 */
1943 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1944 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1945 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1946 		ipif_refrele(ipif);
1947 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1948 		break;
1949 	case ICMP_ECHO_REQUEST:
1950 		icmph->icmph_type = ICMP_ECHO_REPLY;
1951 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1952 		break;
1953 	case ICMP_TIME_STAMP_REQUEST: {
1954 		uint32_t *tsp;
1955 
1956 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1957 		tsp = (uint32_t *)wptr;
1958 		tsp++;		/* Skip past 'originate time' */
1959 		/* Compute # of milliseconds since midnight */
1960 		gethrestime(&now);
1961 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1962 		    now.tv_nsec / (NANOSEC / MILLISEC);
1963 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1964 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1965 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1966 		break;
1967 	}
1968 	default:
1969 		ipha = (ipha_t *)&icmph[1];
1970 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1971 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1972 				BUMP_MIB(&ip_mib, ipInDiscards);
1973 				freemsg(first_mp);
1974 				return;
1975 			}
1976 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1977 			ipha = (ipha_t *)&icmph[1];
1978 		}
1979 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1980 			BUMP_MIB(&ip_mib, ipInDiscards);
1981 			freemsg(first_mp);
1982 			return;
1983 		}
1984 		hdr_length = IPH_HDR_LENGTH(ipha);
1985 		if (hdr_length < sizeof (ipha_t)) {
1986 			BUMP_MIB(&ip_mib, ipInDiscards);
1987 			freemsg(first_mp);
1988 			return;
1989 		}
1990 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1991 			if (!pullupmsg(mp,
1992 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1993 				BUMP_MIB(&ip_mib, ipInDiscards);
1994 				freemsg(first_mp);
1995 				return;
1996 			}
1997 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1998 			ipha = (ipha_t *)&icmph[1];
1999 		}
2000 		switch (icmph->icmph_type) {
2001 		case ICMP_REDIRECT:
2002 			/*
2003 			 * As there is no upper client to deliver, we don't
2004 			 * need the first_mp any more.
2005 			 */
2006 			if (mctl_present) {
2007 				freeb(first_mp);
2008 			}
2009 			icmp_redirect(mp);
2010 			return;
2011 		case ICMP_DEST_UNREACHABLE:
2012 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
2013 				if (!icmp_inbound_too_big(icmph, ipha, ill,
2014 				    zoneid, mp, iph_hdr_length)) {
2015 					freemsg(first_mp);
2016 					return;
2017 				}
2018 				/*
2019 				 * icmp_inbound_too_big() may alter mp.
2020 				 * Resynch ipha and icmph accordingly.
2021 				 */
2022 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2023 				ipha = (ipha_t *)&icmph[1];
2024 			}
2025 			/* FALLTHRU */
2026 		default :
2027 			/*
2028 			 * IPQoS notes: Since we have already done IPQoS
2029 			 * processing we don't want to do it again in
2030 			 * the fanout routines called by
2031 			 * icmp_inbound_error_fanout, hence the last
2032 			 * argument, ip_policy, is B_FALSE.
2033 			 */
2034 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2035 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2036 			    B_FALSE, recv_ill, zoneid);
2037 		}
2038 		return;
2039 	}
2040 	/* Send out an ICMP packet */
2041 	icmph->icmph_checksum = 0;
2042 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2043 	if (icmph->icmph_checksum == 0)
2044 		icmph->icmph_checksum = 0xFFFF;
2045 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2046 		ipif_t	*ipif_chosen;
2047 		/*
2048 		 * Make it look like it was directed to us, so we don't look
2049 		 * like a fool with a broadcast or multicast source address.
2050 		 */
2051 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2052 		/*
2053 		 * Make sure that we haven't grabbed an interface that's DOWN.
2054 		 */
2055 		if (ipif != NULL) {
2056 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2057 			    ipha->ipha_src, zoneid);
2058 			if (ipif_chosen != NULL) {
2059 				ipif_refrele(ipif);
2060 				ipif = ipif_chosen;
2061 			}
2062 		}
2063 		if (ipif == NULL) {
2064 			ip0dbg(("icmp_inbound: "
2065 			    "No source for broadcast/multicast:\n"
2066 			    "\tsrc 0x%x dst 0x%x ill %p "
2067 			    "ipif_lcl_addr 0x%x\n",
2068 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2069 			    (void *)ill,
2070 			    ill->ill_ipif->ipif_lcl_addr));
2071 			freemsg(first_mp);
2072 			return;
2073 		}
2074 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2075 		ipha->ipha_dst = ipif->ipif_src_addr;
2076 		ipif_refrele(ipif);
2077 	}
2078 	/* Reset time to live. */
2079 	ipha->ipha_ttl = ip_def_ttl;
2080 	{
2081 		/* Swap source and destination addresses */
2082 		ipaddr_t tmp;
2083 
2084 		tmp = ipha->ipha_src;
2085 		ipha->ipha_src = ipha->ipha_dst;
2086 		ipha->ipha_dst = tmp;
2087 	}
2088 	ipha->ipha_ident = 0;
2089 	if (!IS_SIMPLE_IPH(ipha))
2090 		icmp_options_update(ipha);
2091 
2092 	/*
2093 	 * ICMP echo replies should go out on the same interface
2094 	 * the request came on as probes used by in.mpathd for detecting
2095 	 * NIC failures are ECHO packets. We turn-off load spreading
2096 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2097 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2098 	 * function. This is in turn handled by ip_wput and ip_newroute
2099 	 * to make sure that the packet goes out on the interface it came
2100 	 * in on. If we don't turnoff load spreading, the packets might get
2101 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2102 	 * to go out and in.mpathd would wrongly detect a failure or
2103 	 * mis-detect a NIC failure for link failure. As load spreading
2104 	 * can happen only if ill_group is not NULL, we do only for
2105 	 * that case and this does not affect the normal case.
2106 	 *
2107 	 * We turn off load spreading only on echo packets that came from
2108 	 * on-link hosts. If the interface route has been deleted, this will
2109 	 * not be enforced as we can't do much. For off-link hosts, as the
2110 	 * default routes in IPv4 does not typically have an ire_ipif
2111 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2112 	 * Moreover, expecting a default route through this interface may
2113 	 * not be correct. We use ipha_dst because of the swap above.
2114 	 */
2115 	onlink = B_FALSE;
2116 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2117 		/*
2118 		 * First, we need to make sure that it is not one of our
2119 		 * local addresses. If we set onlink when it is one of
2120 		 * our local addresses, we will end up creating IRE_CACHES
2121 		 * for one of our local addresses. Then, we will never
2122 		 * accept packets for them afterwards.
2123 		 */
2124 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2125 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2126 		if (src_ire == NULL) {
2127 			ipif = ipif_get_next_ipif(NULL, ill);
2128 			if (ipif == NULL) {
2129 				BUMP_MIB(&ip_mib, ipInDiscards);
2130 				freemsg(mp);
2131 				return;
2132 			}
2133 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2134 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2135 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2136 			ipif_refrele(ipif);
2137 			if (src_ire != NULL) {
2138 				onlink = B_TRUE;
2139 				ire_refrele(src_ire);
2140 			}
2141 		} else {
2142 			ire_refrele(src_ire);
2143 		}
2144 	}
2145 	if (!mctl_present) {
2146 		/*
2147 		 * This packet should go out the same way as it
2148 		 * came in i.e in clear. To make sure that global
2149 		 * policy will not be applied to this in ip_wput_ire,
2150 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2151 		 */
2152 		ASSERT(first_mp == mp);
2153 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2154 			BUMP_MIB(&ip_mib, ipInDiscards);
2155 			freemsg(mp);
2156 			return;
2157 		}
2158 		ii = (ipsec_in_t *)first_mp->b_rptr;
2159 
2160 		/* This is not a secure packet */
2161 		ii->ipsec_in_secure = B_FALSE;
2162 		if (onlink) {
2163 			ii->ipsec_in_attach_if = B_TRUE;
2164 			ii->ipsec_in_ill_index =
2165 			    ill->ill_phyint->phyint_ifindex;
2166 			ii->ipsec_in_rill_index =
2167 			    recv_ill->ill_phyint->phyint_ifindex;
2168 		}
2169 		first_mp->b_cont = mp;
2170 	} else if (onlink) {
2171 		ii = (ipsec_in_t *)first_mp->b_rptr;
2172 		ii->ipsec_in_attach_if = B_TRUE;
2173 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2174 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2175 	} else {
2176 		ii = (ipsec_in_t *)first_mp->b_rptr;
2177 	}
2178 	ii->ipsec_in_zoneid = zoneid;
2179 	ASSERT(zoneid != ALL_ZONES);
2180 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2181 		BUMP_MIB(&ip_mib, ipInDiscards);
2182 		return;
2183 	}
2184 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2185 	put(WR(q), first_mp);
2186 }
2187 
2188 static ipaddr_t
2189 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2190 {
2191 	conn_t *connp;
2192 	connf_t *connfp;
2193 	ipaddr_t nexthop_addr = INADDR_ANY;
2194 	int hdr_length = IPH_HDR_LENGTH(ipha);
2195 	uint16_t *up;
2196 	uint32_t ports;
2197 
2198 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2199 	switch (ipha->ipha_protocol) {
2200 		case IPPROTO_TCP:
2201 		{
2202 			tcph_t *tcph;
2203 
2204 			/* do a reverse lookup */
2205 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2206 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2207 			    TCPS_LISTEN);
2208 			break;
2209 		}
2210 		case IPPROTO_UDP:
2211 		{
2212 			uint32_t dstport, srcport;
2213 
2214 			((uint16_t *)&ports)[0] = up[1];
2215 			((uint16_t *)&ports)[1] = up[0];
2216 
2217 			/* Extract ports in net byte order */
2218 			dstport = htons(ntohl(ports) & 0xFFFF);
2219 			srcport = htons(ntohl(ports) >> 16);
2220 
2221 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2222 			mutex_enter(&connfp->connf_lock);
2223 			connp = connfp->connf_head;
2224 
2225 			/* do a reverse lookup */
2226 			while ((connp != NULL) &&
2227 			    (!IPCL_UDP_MATCH(connp, dstport,
2228 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2229 			    connp->conn_zoneid != zoneid)) {
2230 				connp = connp->conn_next;
2231 			}
2232 			if (connp != NULL)
2233 				CONN_INC_REF(connp);
2234 			mutex_exit(&connfp->connf_lock);
2235 			break;
2236 		}
2237 		case IPPROTO_SCTP:
2238 		{
2239 			in6_addr_t map_src, map_dst;
2240 
2241 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2242 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2243 			((uint16_t *)&ports)[0] = up[1];
2244 			((uint16_t *)&ports)[1] = up[0];
2245 
2246 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2247 			    0, zoneid)) == NULL) {
2248 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2249 				    zoneid, ports, ipha);
2250 			} else {
2251 				CONN_INC_REF(connp);
2252 				SCTP_REFRELE(CONN2SCTP(connp));
2253 			}
2254 			break;
2255 		}
2256 		default:
2257 		{
2258 			ipha_t ripha;
2259 
2260 			ripha.ipha_src = ipha->ipha_dst;
2261 			ripha.ipha_dst = ipha->ipha_src;
2262 			ripha.ipha_protocol = ipha->ipha_protocol;
2263 
2264 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2265 			mutex_enter(&connfp->connf_lock);
2266 			connp = connfp->connf_head;
2267 			for (connp = connfp->connf_head; connp != NULL;
2268 			    connp = connp->conn_next) {
2269 				if (IPCL_PROTO_MATCH(connp,
2270 				    ipha->ipha_protocol, &ripha, ill,
2271 				    0, zoneid)) {
2272 					CONN_INC_REF(connp);
2273 					break;
2274 				}
2275 			}
2276 			mutex_exit(&connfp->connf_lock);
2277 		}
2278 	}
2279 	if (connp != NULL) {
2280 		if (connp->conn_nexthop_set)
2281 			nexthop_addr = connp->conn_nexthop_v4;
2282 		CONN_DEC_REF(connp);
2283 	}
2284 	return (nexthop_addr);
2285 }
2286 
2287 /* Table from RFC 1191 */
2288 static int icmp_frag_size_table[] =
2289 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2290 
2291 /*
2292  * Process received ICMP Packet too big.
2293  * After updating any IRE it does the fanout to any matching transport streams.
2294  * Assumes the message has been pulled up till the IP header that caused
2295  * the error.
2296  *
2297  * Returns B_FALSE on failure and B_TRUE on success.
2298  */
2299 static boolean_t
2300 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2301     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2302 {
2303 	ire_t	*ire, *first_ire;
2304 	int	mtu;
2305 	int	hdr_length;
2306 	ipaddr_t nexthop_addr;
2307 
2308 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2309 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2310 
2311 	hdr_length = IPH_HDR_LENGTH(ipha);
2312 
2313 	/* Drop if the original packet contained a source route */
2314 	if (ip_source_route_included(ipha)) {
2315 		return (B_FALSE);
2316 	}
2317 	/*
2318 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2319 	 * header.
2320 	 */
2321 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2322 	    mp->b_wptr) {
2323 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2324 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2325 			BUMP_MIB(&ip_mib, ipInDiscards);
2326 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2327 			return (B_FALSE);
2328 		}
2329 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2330 		ipha = (ipha_t *)&icmph[1];
2331 	}
2332 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2333 	if (nexthop_addr != INADDR_ANY) {
2334 		/* nexthop set */
2335 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2336 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2337 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2338 	} else {
2339 		/* nexthop not set */
2340 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2341 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2342 	}
2343 
2344 	if (!first_ire) {
2345 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2346 		    ntohl(ipha->ipha_dst)));
2347 		return (B_FALSE);
2348 	}
2349 	/* Check for MTU discovery advice as described in RFC 1191 */
2350 	mtu = ntohs(icmph->icmph_du_mtu);
2351 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2352 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2353 	    ire = ire->ire_next) {
2354 		/*
2355 		 * Look for the connection to which this ICMP message is
2356 		 * directed. If it has the IP_NEXTHOP option set, then the
2357 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2358 		 * option. Else the search is limited to regular IREs.
2359 		 */
2360 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2361 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2362 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2363 		    (nexthop_addr != INADDR_ANY)))
2364 			continue;
2365 
2366 		mutex_enter(&ire->ire_lock);
2367 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2368 			/* Reduce the IRE max frag value as advised. */
2369 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2370 			    mtu, ire->ire_max_frag));
2371 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2372 		} else {
2373 			uint32_t length;
2374 			int	i;
2375 
2376 			/*
2377 			 * Use the table from RFC 1191 to figure out
2378 			 * the next "plateau" based on the length in
2379 			 * the original IP packet.
2380 			 */
2381 			length = ntohs(ipha->ipha_length);
2382 			if (ire->ire_max_frag <= length &&
2383 			    ire->ire_max_frag >= length - hdr_length) {
2384 				/*
2385 				 * Handle broken BSD 4.2 systems that
2386 				 * return the wrong iph_length in ICMP
2387 				 * errors.
2388 				 */
2389 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2390 				    length, ire->ire_max_frag));
2391 				length -= hdr_length;
2392 			}
2393 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2394 				if (length > icmp_frag_size_table[i])
2395 					break;
2396 			}
2397 			if (i == A_CNT(icmp_frag_size_table)) {
2398 				/* Smaller than 68! */
2399 				ip1dbg(("Too big for packet size %d\n",
2400 				    length));
2401 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2402 				ire->ire_frag_flag = 0;
2403 			} else {
2404 				mtu = icmp_frag_size_table[i];
2405 				ip1dbg(("Calculated mtu %d, packet size %d, "
2406 				    "before %d", mtu, length,
2407 				    ire->ire_max_frag));
2408 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2409 				ip1dbg((", after %d\n", ire->ire_max_frag));
2410 			}
2411 			/* Record the new max frag size for the ULP. */
2412 			icmph->icmph_du_zero = 0;
2413 			icmph->icmph_du_mtu =
2414 			    htons((uint16_t)ire->ire_max_frag);
2415 		}
2416 		mutex_exit(&ire->ire_lock);
2417 	}
2418 	rw_exit(&first_ire->ire_bucket->irb_lock);
2419 	ire_refrele(first_ire);
2420 	return (B_TRUE);
2421 }
2422 
2423 /*
2424  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2425  * calls this function.
2426  */
2427 static mblk_t *
2428 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2429 {
2430 	ipha_t *ipha;
2431 	icmph_t *icmph;
2432 	ipha_t *in_ipha;
2433 	int length;
2434 
2435 	ASSERT(mp->b_datap->db_type == M_DATA);
2436 
2437 	/*
2438 	 * For Self-encapsulated packets, we added an extra IP header
2439 	 * without the options. Inner IP header is the one from which
2440 	 * the outer IP header was formed. Thus, we need to remove the
2441 	 * outer IP header. To do this, we pullup the whole message
2442 	 * and overlay whatever follows the outer IP header over the
2443 	 * outer IP header.
2444 	 */
2445 
2446 	if (!pullupmsg(mp, -1)) {
2447 		BUMP_MIB(&ip_mib, ipInDiscards);
2448 		return (NULL);
2449 	}
2450 
2451 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2452 	ipha = (ipha_t *)&icmph[1];
2453 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2454 
2455 	/*
2456 	 * The length that we want to overlay is following the inner
2457 	 * IP header. Subtracting the IP header + icmp header + outer
2458 	 * IP header's length should give us the length that we want to
2459 	 * overlay.
2460 	 */
2461 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2462 	    hdr_length;
2463 	/*
2464 	 * Overlay whatever follows the inner header over the
2465 	 * outer header.
2466 	 */
2467 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2468 
2469 	/* Set the wptr to account for the outer header */
2470 	mp->b_wptr -= hdr_length;
2471 	return (mp);
2472 }
2473 
2474 /*
2475  * Try to pass the ICMP message upstream in case the ULP cares.
2476  *
2477  * If the packet that caused the ICMP error is secure, we send
2478  * it to AH/ESP to make sure that the attached packet has a
2479  * valid association. ipha in the code below points to the
2480  * IP header of the packet that caused the error.
2481  *
2482  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2483  * in the context of IPSEC. Normally we tell the upper layer
2484  * whenever we send the ire (including ip_bind), the IPSEC header
2485  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2486  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2487  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2488  * same thing. As TCP has the IPSEC options size that needs to be
2489  * adjusted, we just pass the MTU unchanged.
2490  *
2491  * IFN could have been generated locally or by some router.
2492  *
2493  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2494  *	    This happens because IP adjusted its value of MTU on an
2495  *	    earlier IFN message and could not tell the upper layer,
2496  *	    the new adjusted value of MTU e.g. Packet was encrypted
2497  *	    or there was not enough information to fanout to upper
2498  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2499  *	    generates the IFN, where IPSEC processing has *not* been
2500  *	    done.
2501  *
2502  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2503  *	    could have generated this. This happens because ire_max_frag
2504  *	    value in IP was set to a new value, while the IPSEC processing
2505  *	    was being done and after we made the fragmentation check in
2506  *	    ip_wput_ire. Thus on return from IPSEC processing,
2507  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2508  *	    and generates the IFN. As IPSEC processing is over, we fanout
2509  *	    to AH/ESP to remove the header.
2510  *
2511  *	    In both these cases, ipsec_in_loopback will be set indicating
2512  *	    that IFN was generated locally.
2513  *
2514  * ROUTER : IFN could be secure or non-secure.
2515  *
2516  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2517  *	      packet in error has AH/ESP headers to validate the AH/ESP
2518  *	      headers. AH/ESP will verify whether there is a valid SA or
2519  *	      not and send it back. We will fanout again if we have more
2520  *	      data in the packet.
2521  *
2522  *	      If the packet in error does not have AH/ESP, we handle it
2523  *	      like any other case.
2524  *
2525  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2526  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2527  *	      for validation. AH/ESP will verify whether there is a
2528  *	      valid SA or not and send it back. We will fanout again if
2529  *	      we have more 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 static void
2535 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2536     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2537     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2538     zoneid_t zoneid)
2539 {
2540 	uint16_t *up;	/* Pointer to ports in ULP header */
2541 	uint32_t ports;	/* reversed ports for fanout */
2542 	ipha_t ripha;	/* With reversed addresses */
2543 	mblk_t *first_mp;
2544 	ipsec_in_t *ii;
2545 	tcph_t	*tcph;
2546 	conn_t	*connp;
2547 
2548 	first_mp = mp;
2549 	if (mctl_present) {
2550 		mp = first_mp->b_cont;
2551 		ASSERT(mp != NULL);
2552 
2553 		ii = (ipsec_in_t *)first_mp->b_rptr;
2554 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2555 	} else {
2556 		ii = NULL;
2557 	}
2558 
2559 	switch (ipha->ipha_protocol) {
2560 	case IPPROTO_UDP:
2561 		/*
2562 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2563 		 * transport header.
2564 		 */
2565 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2566 		    mp->b_wptr) {
2567 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2568 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2569 				BUMP_MIB(&ip_mib, ipInDiscards);
2570 				goto drop_pkt;
2571 			}
2572 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2573 			ipha = (ipha_t *)&icmph[1];
2574 		}
2575 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2576 
2577 		/*
2578 		 * Attempt to find a client stream based on port.
2579 		 * Note that we do a reverse lookup since the header is
2580 		 * in the form we sent it out.
2581 		 * The ripha header is only used for the IP_UDP_MATCH and we
2582 		 * only set the src and dst addresses and protocol.
2583 		 */
2584 		ripha.ipha_src = ipha->ipha_dst;
2585 		ripha.ipha_dst = ipha->ipha_src;
2586 		ripha.ipha_protocol = ipha->ipha_protocol;
2587 		((uint16_t *)&ports)[0] = up[1];
2588 		((uint16_t *)&ports)[1] = up[0];
2589 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2590 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2591 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2592 		    icmph->icmph_type, icmph->icmph_code));
2593 
2594 		/* Have to change db_type after any pullupmsg */
2595 		DB_TYPE(mp) = M_CTL;
2596 
2597 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2598 		    mctl_present, ip_policy, recv_ill, zoneid);
2599 		return;
2600 
2601 	case IPPROTO_TCP:
2602 		/*
2603 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2604 		 * transport header.
2605 		 */
2606 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2607 		    mp->b_wptr) {
2608 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2609 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2610 				BUMP_MIB(&ip_mib, ipInDiscards);
2611 				goto drop_pkt;
2612 			}
2613 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2614 			ipha = (ipha_t *)&icmph[1];
2615 		}
2616 		/*
2617 		 * Find a TCP client stream for this packet.
2618 		 * Note that we do a reverse lookup since the header is
2619 		 * in the form we sent it out.
2620 		 */
2621 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2622 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2623 		if (connp == NULL) {
2624 			BUMP_MIB(&ip_mib, ipInDiscards);
2625 			goto drop_pkt;
2626 		}
2627 
2628 		/* Have to change db_type after any pullupmsg */
2629 		DB_TYPE(mp) = M_CTL;
2630 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2631 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2632 		return;
2633 
2634 	case IPPROTO_SCTP:
2635 		/*
2636 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2637 		 * transport header.
2638 		 */
2639 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2640 		    mp->b_wptr) {
2641 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2642 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2643 				BUMP_MIB(&ip_mib, ipInDiscards);
2644 				goto drop_pkt;
2645 			}
2646 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2647 			ipha = (ipha_t *)&icmph[1];
2648 		}
2649 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2650 		/*
2651 		 * Find a SCTP client stream for this packet.
2652 		 * Note that we do a reverse lookup since the header is
2653 		 * in the form we sent it out.
2654 		 * The ripha header is only used for the matching and we
2655 		 * only set the src and dst addresses, protocol, and version.
2656 		 */
2657 		ripha.ipha_src = ipha->ipha_dst;
2658 		ripha.ipha_dst = ipha->ipha_src;
2659 		ripha.ipha_protocol = ipha->ipha_protocol;
2660 		ripha.ipha_version_and_hdr_length =
2661 		    ipha->ipha_version_and_hdr_length;
2662 		((uint16_t *)&ports)[0] = up[1];
2663 		((uint16_t *)&ports)[1] = up[0];
2664 
2665 		/* Have to change db_type after any pullupmsg */
2666 		DB_TYPE(mp) = M_CTL;
2667 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2668 		    mctl_present, ip_policy, 0, zoneid);
2669 		return;
2670 
2671 	case IPPROTO_ESP:
2672 	case IPPROTO_AH: {
2673 		int ipsec_rc;
2674 
2675 		/*
2676 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2677 		 * We will re-use the IPSEC_IN if it is already present as
2678 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2679 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2680 		 * one and attach it in the front.
2681 		 */
2682 		if (ii != NULL) {
2683 			/*
2684 			 * ip_fanout_proto_again converts the ICMP errors
2685 			 * that come back from AH/ESP to M_DATA so that
2686 			 * if it is non-AH/ESP and we do a pullupmsg in
2687 			 * this function, it would work. Convert it back
2688 			 * to M_CTL before we send up as this is a ICMP
2689 			 * error. This could have been generated locally or
2690 			 * by some router. Validate the inner IPSEC
2691 			 * headers.
2692 			 *
2693 			 * NOTE : ill_index is used by ip_fanout_proto_again
2694 			 * to locate the ill.
2695 			 */
2696 			ASSERT(ill != NULL);
2697 			ii->ipsec_in_ill_index =
2698 			    ill->ill_phyint->phyint_ifindex;
2699 			ii->ipsec_in_rill_index =
2700 			    recv_ill->ill_phyint->phyint_ifindex;
2701 			DB_TYPE(first_mp->b_cont) = M_CTL;
2702 		} else {
2703 			/*
2704 			 * IPSEC_IN is not present. We attach a ipsec_in
2705 			 * message and send up to IPSEC for validating
2706 			 * and removing the IPSEC headers. Clear
2707 			 * ipsec_in_secure so that when we return
2708 			 * from IPSEC, we don't mistakenly think that this
2709 			 * is a secure packet came from the network.
2710 			 *
2711 			 * NOTE : ill_index is used by ip_fanout_proto_again
2712 			 * to locate the ill.
2713 			 */
2714 			ASSERT(first_mp == mp);
2715 			first_mp = ipsec_in_alloc(B_TRUE);
2716 			if (first_mp == NULL) {
2717 				freemsg(mp);
2718 				BUMP_MIB(&ip_mib, ipInDiscards);
2719 				return;
2720 			}
2721 			ii = (ipsec_in_t *)first_mp->b_rptr;
2722 
2723 			/* This is not a secure packet */
2724 			ii->ipsec_in_secure = B_FALSE;
2725 			first_mp->b_cont = mp;
2726 			DB_TYPE(mp) = M_CTL;
2727 			ASSERT(ill != NULL);
2728 			ii->ipsec_in_ill_index =
2729 			    ill->ill_phyint->phyint_ifindex;
2730 			ii->ipsec_in_rill_index =
2731 			    recv_ill->ill_phyint->phyint_ifindex;
2732 		}
2733 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2734 
2735 		if (!ipsec_loaded()) {
2736 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2737 			return;
2738 		}
2739 
2740 		if (ipha->ipha_protocol == IPPROTO_ESP)
2741 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2742 		else
2743 			ipsec_rc = ipsecah_icmp_error(first_mp);
2744 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2745 			return;
2746 
2747 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2748 		return;
2749 	}
2750 	default:
2751 		/*
2752 		 * The ripha header is only used for the lookup and we
2753 		 * only set the src and dst addresses and protocol.
2754 		 */
2755 		ripha.ipha_src = ipha->ipha_dst;
2756 		ripha.ipha_dst = ipha->ipha_src;
2757 		ripha.ipha_protocol = ipha->ipha_protocol;
2758 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2759 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2760 		    ntohl(ipha->ipha_dst),
2761 		    icmph->icmph_type, icmph->icmph_code));
2762 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2763 			ipha_t *in_ipha;
2764 
2765 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2766 			    mp->b_wptr) {
2767 				if (!pullupmsg(mp, (uchar_t *)ipha +
2768 				    hdr_length + sizeof (ipha_t) -
2769 				    mp->b_rptr)) {
2770 
2771 					BUMP_MIB(&ip_mib, ipInDiscards);
2772 					goto drop_pkt;
2773 				}
2774 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2775 				ipha = (ipha_t *)&icmph[1];
2776 			}
2777 			/*
2778 			 * Caller has verified that length has to be
2779 			 * at least the size of IP header.
2780 			 */
2781 			ASSERT(hdr_length >= sizeof (ipha_t));
2782 			/*
2783 			 * Check the sanity of the inner IP header like
2784 			 * we did for the outer header.
2785 			 */
2786 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2787 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2788 				BUMP_MIB(&ip_mib, ipInDiscards);
2789 				goto drop_pkt;
2790 			}
2791 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2792 				BUMP_MIB(&ip_mib, ipInDiscards);
2793 				goto drop_pkt;
2794 			}
2795 			/* Check for Self-encapsulated tunnels */
2796 			if (in_ipha->ipha_src == ipha->ipha_src &&
2797 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2798 
2799 				mp = icmp_inbound_self_encap_error(mp,
2800 				    iph_hdr_length, hdr_length);
2801 				if (mp == NULL)
2802 					goto drop_pkt;
2803 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2804 				ipha = (ipha_t *)&icmph[1];
2805 				hdr_length = IPH_HDR_LENGTH(ipha);
2806 				/*
2807 				 * The packet in error is self-encapsualted.
2808 				 * And we are finding it further encapsulated
2809 				 * which we could not have possibly generated.
2810 				 */
2811 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2812 					BUMP_MIB(&ip_mib, ipInDiscards);
2813 					goto drop_pkt;
2814 				}
2815 				icmp_inbound_error_fanout(q, ill, first_mp,
2816 				    icmph, ipha, iph_hdr_length, hdr_length,
2817 				    mctl_present, ip_policy, recv_ill, zoneid);
2818 				return;
2819 			}
2820 		}
2821 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2822 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2823 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2824 		    ii != NULL &&
2825 		    ii->ipsec_in_loopback &&
2826 		    ii->ipsec_in_secure) {
2827 			/*
2828 			 * For IP tunnels that get a looped-back
2829 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2830 			 * reported new MTU to take into account the IPsec
2831 			 * headers protecting this configured tunnel.
2832 			 *
2833 			 * This allows the tunnel module (tun.c) to blindly
2834 			 * accept the MTU reported in an ICMP "too big"
2835 			 * message.
2836 			 *
2837 			 * Non-looped back ICMP messages will just be
2838 			 * handled by the security protocols (if needed),
2839 			 * and the first subsequent packet will hit this
2840 			 * path.
2841 			 */
2842 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2843 			    ipsec_in_extra_length(first_mp));
2844 		}
2845 		/* Have to change db_type after any pullupmsg */
2846 		DB_TYPE(mp) = M_CTL;
2847 
2848 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2849 		    ip_policy, recv_ill, zoneid);
2850 		return;
2851 	}
2852 	/* NOTREACHED */
2853 drop_pkt:;
2854 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2855 	freemsg(first_mp);
2856 }
2857 
2858 /*
2859  * Common IP options parser.
2860  *
2861  * Setup routine: fill in *optp with options-parsing state, then
2862  * tail-call ipoptp_next to return the first option.
2863  */
2864 uint8_t
2865 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2866 {
2867 	uint32_t totallen; /* total length of all options */
2868 
2869 	totallen = ipha->ipha_version_and_hdr_length -
2870 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2871 	totallen <<= 2;
2872 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2873 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2874 	optp->ipoptp_flags = 0;
2875 	return (ipoptp_next(optp));
2876 }
2877 
2878 /*
2879  * Common IP options parser: extract next option.
2880  */
2881 uint8_t
2882 ipoptp_next(ipoptp_t *optp)
2883 {
2884 	uint8_t *end = optp->ipoptp_end;
2885 	uint8_t *cur = optp->ipoptp_next;
2886 	uint8_t opt, len, pointer;
2887 
2888 	/*
2889 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2890 	 * has been corrupted.
2891 	 */
2892 	ASSERT(cur <= end);
2893 
2894 	if (cur == end)
2895 		return (IPOPT_EOL);
2896 
2897 	opt = cur[IPOPT_OPTVAL];
2898 
2899 	/*
2900 	 * Skip any NOP options.
2901 	 */
2902 	while (opt == IPOPT_NOP) {
2903 		cur++;
2904 		if (cur == end)
2905 			return (IPOPT_EOL);
2906 		opt = cur[IPOPT_OPTVAL];
2907 	}
2908 
2909 	if (opt == IPOPT_EOL)
2910 		return (IPOPT_EOL);
2911 
2912 	/*
2913 	 * Option requiring a length.
2914 	 */
2915 	if ((cur + 1) >= end) {
2916 		optp->ipoptp_flags |= IPOPTP_ERROR;
2917 		return (IPOPT_EOL);
2918 	}
2919 	len = cur[IPOPT_OLEN];
2920 	if (len < 2) {
2921 		optp->ipoptp_flags |= IPOPTP_ERROR;
2922 		return (IPOPT_EOL);
2923 	}
2924 	optp->ipoptp_cur = cur;
2925 	optp->ipoptp_len = len;
2926 	optp->ipoptp_next = cur + len;
2927 	if (cur + len > end) {
2928 		optp->ipoptp_flags |= IPOPTP_ERROR;
2929 		return (IPOPT_EOL);
2930 	}
2931 
2932 	/*
2933 	 * For the options which require a pointer field, make sure
2934 	 * its there, and make sure it points to either something
2935 	 * inside this option, or the end of the option.
2936 	 */
2937 	switch (opt) {
2938 	case IPOPT_RR:
2939 	case IPOPT_TS:
2940 	case IPOPT_LSRR:
2941 	case IPOPT_SSRR:
2942 		if (len <= IPOPT_OFFSET) {
2943 			optp->ipoptp_flags |= IPOPTP_ERROR;
2944 			return (opt);
2945 		}
2946 		pointer = cur[IPOPT_OFFSET];
2947 		if (pointer - 1 > len) {
2948 			optp->ipoptp_flags |= IPOPTP_ERROR;
2949 			return (opt);
2950 		}
2951 		break;
2952 	}
2953 
2954 	/*
2955 	 * Sanity check the pointer field based on the type of the
2956 	 * option.
2957 	 */
2958 	switch (opt) {
2959 	case IPOPT_RR:
2960 	case IPOPT_SSRR:
2961 	case IPOPT_LSRR:
2962 		if (pointer < IPOPT_MINOFF_SR)
2963 			optp->ipoptp_flags |= IPOPTP_ERROR;
2964 		break;
2965 	case IPOPT_TS:
2966 		if (pointer < IPOPT_MINOFF_IT)
2967 			optp->ipoptp_flags |= IPOPTP_ERROR;
2968 		/*
2969 		 * Note that the Internet Timestamp option also
2970 		 * contains two four bit fields (the Overflow field,
2971 		 * and the Flag field), which follow the pointer
2972 		 * field.  We don't need to check that these fields
2973 		 * fall within the length of the option because this
2974 		 * was implicitely done above.  We've checked that the
2975 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2976 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2977 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2978 		 */
2979 		ASSERT(len > IPOPT_POS_OV_FLG);
2980 		break;
2981 	}
2982 
2983 	return (opt);
2984 }
2985 
2986 /*
2987  * Use the outgoing IP header to create an IP_OPTIONS option the way
2988  * it was passed down from the application.
2989  */
2990 int
2991 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2992 {
2993 	ipoptp_t	opts;
2994 	const uchar_t	*opt;
2995 	uint8_t		optval;
2996 	uint8_t		optlen;
2997 	uint32_t	len = 0;
2998 	uchar_t	*buf1 = buf;
2999 
3000 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
3001 	len += IP_ADDR_LEN;
3002 	bzero(buf1, IP_ADDR_LEN);
3003 
3004 	/*
3005 	 * OK to cast away const here, as we don't store through the returned
3006 	 * opts.ipoptp_cur pointer.
3007 	 */
3008 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
3009 	    optval != IPOPT_EOL;
3010 	    optval = ipoptp_next(&opts)) {
3011 		int	off;
3012 
3013 		opt = opts.ipoptp_cur;
3014 		optlen = opts.ipoptp_len;
3015 		switch (optval) {
3016 		case IPOPT_SSRR:
3017 		case IPOPT_LSRR:
3018 
3019 			/*
3020 			 * Insert ipha_dst as the first entry in the source
3021 			 * route and move down the entries on step.
3022 			 * The last entry gets placed at buf1.
3023 			 */
3024 			buf[IPOPT_OPTVAL] = optval;
3025 			buf[IPOPT_OLEN] = optlen;
3026 			buf[IPOPT_OFFSET] = optlen;
3027 
3028 			off = optlen - IP_ADDR_LEN;
3029 			if (off < 0) {
3030 				/* No entries in source route */
3031 				break;
3032 			}
3033 			/* Last entry in source route */
3034 			bcopy(opt + off, buf1, IP_ADDR_LEN);
3035 			off -= IP_ADDR_LEN;
3036 
3037 			while (off > 0) {
3038 				bcopy(opt + off,
3039 				    buf + off + IP_ADDR_LEN,
3040 				    IP_ADDR_LEN);
3041 				off -= IP_ADDR_LEN;
3042 			}
3043 			/* ipha_dst into first slot */
3044 			bcopy(&ipha->ipha_dst,
3045 			    buf + off + IP_ADDR_LEN,
3046 			    IP_ADDR_LEN);
3047 			buf += optlen;
3048 			len += optlen;
3049 			break;
3050 
3051 		case IPOPT_COMSEC:
3052 		case IPOPT_SECURITY:
3053 			/* if passing up a label is not ok, then remove */
3054 			if (is_system_labeled())
3055 				break;
3056 			/* FALLTHROUGH */
3057 		default:
3058 			bcopy(opt, buf, optlen);
3059 			buf += optlen;
3060 			len += optlen;
3061 			break;
3062 		}
3063 	}
3064 done:
3065 	/* Pad the resulting options */
3066 	while (len & 0x3) {
3067 		*buf++ = IPOPT_EOL;
3068 		len++;
3069 	}
3070 	return (len);
3071 }
3072 
3073 /*
3074  * Update any record route or timestamp options to include this host.
3075  * Reverse any source route option.
3076  * This routine assumes that the options are well formed i.e. that they
3077  * have already been checked.
3078  */
3079 static void
3080 icmp_options_update(ipha_t *ipha)
3081 {
3082 	ipoptp_t	opts;
3083 	uchar_t		*opt;
3084 	uint8_t		optval;
3085 	ipaddr_t	src;		/* Our local address */
3086 	ipaddr_t	dst;
3087 
3088 	ip2dbg(("icmp_options_update\n"));
3089 	src = ipha->ipha_src;
3090 	dst = ipha->ipha_dst;
3091 
3092 	for (optval = ipoptp_first(&opts, ipha);
3093 	    optval != IPOPT_EOL;
3094 	    optval = ipoptp_next(&opts)) {
3095 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3096 		opt = opts.ipoptp_cur;
3097 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3098 		    optval, opts.ipoptp_len));
3099 		switch (optval) {
3100 			int off1, off2;
3101 		case IPOPT_SSRR:
3102 		case IPOPT_LSRR:
3103 			/*
3104 			 * Reverse the source route.  The first entry
3105 			 * should be the next to last one in the current
3106 			 * source route (the last entry is our address).
3107 			 * The last entry should be the final destination.
3108 			 */
3109 			off1 = IPOPT_MINOFF_SR - 1;
3110 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3111 			if (off2 < 0) {
3112 				/* No entries in source route */
3113 				ip1dbg((
3114 				    "icmp_options_update: bad src route\n"));
3115 				break;
3116 			}
3117 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3118 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3119 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3120 			off2 -= IP_ADDR_LEN;
3121 
3122 			while (off1 < off2) {
3123 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3124 				bcopy((char *)opt + off2, (char *)opt + off1,
3125 				    IP_ADDR_LEN);
3126 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3127 				off1 += IP_ADDR_LEN;
3128 				off2 -= IP_ADDR_LEN;
3129 			}
3130 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3131 			break;
3132 		}
3133 	}
3134 }
3135 
3136 /*
3137  * Process received ICMP Redirect messages.
3138  */
3139 /* ARGSUSED */
3140 static void
3141 icmp_redirect(mblk_t *mp)
3142 {
3143 	ipha_t	*ipha;
3144 	int	iph_hdr_length;
3145 	icmph_t	*icmph;
3146 	ipha_t	*ipha_err;
3147 	ire_t	*ire;
3148 	ire_t	*prev_ire;
3149 	ire_t	*save_ire;
3150 	ipaddr_t  src, dst, gateway;
3151 	iulp_t	ulp_info = { 0 };
3152 	int	error;
3153 
3154 	ipha = (ipha_t *)mp->b_rptr;
3155 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3156 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3157 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3158 		BUMP_MIB(&icmp_mib, icmpInErrors);
3159 		freemsg(mp);
3160 		return;
3161 	}
3162 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3163 	ipha_err = (ipha_t *)&icmph[1];
3164 	src = ipha->ipha_src;
3165 	dst = ipha_err->ipha_dst;
3166 	gateway = icmph->icmph_rd_gateway;
3167 	/* Make sure the new gateway is reachable somehow. */
3168 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3169 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3170 	/*
3171 	 * Make sure we had a route for the dest in question and that
3172 	 * that route was pointing to the old gateway (the source of the
3173 	 * redirect packet.)
3174 	 */
3175 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3176 	    NULL, MATCH_IRE_GW);
3177 	/*
3178 	 * Check that
3179 	 *	the redirect was not from ourselves
3180 	 *	the new gateway and the old gateway are directly reachable
3181 	 */
3182 	if (!prev_ire ||
3183 	    !ire ||
3184 	    ire->ire_type == IRE_LOCAL) {
3185 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3186 		freemsg(mp);
3187 		if (ire != NULL)
3188 			ire_refrele(ire);
3189 		if (prev_ire != NULL)
3190 			ire_refrele(prev_ire);
3191 		return;
3192 	}
3193 
3194 	/*
3195 	 * Should we use the old ULP info to create the new gateway?  From
3196 	 * a user's perspective, we should inherit the info so that it
3197 	 * is a "smooth" transition.  If we do not do that, then new
3198 	 * connections going thru the new gateway will have no route metrics,
3199 	 * which is counter-intuitive to user.  From a network point of
3200 	 * view, this may or may not make sense even though the new gateway
3201 	 * is still directly connected to us so the route metrics should not
3202 	 * change much.
3203 	 *
3204 	 * But if the old ire_uinfo is not initialized, we do another
3205 	 * recursive lookup on the dest using the new gateway.  There may
3206 	 * be a route to that.  If so, use it to initialize the redirect
3207 	 * route.
3208 	 */
3209 	if (prev_ire->ire_uinfo.iulp_set) {
3210 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3211 	} else {
3212 		ire_t *tmp_ire;
3213 		ire_t *sire;
3214 
3215 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3216 		    ALL_ZONES, 0, NULL,
3217 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3218 		if (sire != NULL) {
3219 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3220 			/*
3221 			 * If sire != NULL, ire_ftable_lookup() should not
3222 			 * return a NULL value.
3223 			 */
3224 			ASSERT(tmp_ire != NULL);
3225 			ire_refrele(tmp_ire);
3226 			ire_refrele(sire);
3227 		} else if (tmp_ire != NULL) {
3228 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3229 			    sizeof (iulp_t));
3230 			ire_refrele(tmp_ire);
3231 		}
3232 	}
3233 	if (prev_ire->ire_type == IRE_CACHE)
3234 		ire_delete(prev_ire);
3235 	ire_refrele(prev_ire);
3236 	/*
3237 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3238 	 * require TOS routing
3239 	 */
3240 	switch (icmph->icmph_code) {
3241 	case 0:
3242 	case 1:
3243 		/* TODO: TOS specificity for cases 2 and 3 */
3244 	case 2:
3245 	case 3:
3246 		break;
3247 	default:
3248 		freemsg(mp);
3249 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3250 		ire_refrele(ire);
3251 		return;
3252 	}
3253 	/*
3254 	 * Create a Route Association.  This will allow us to remember that
3255 	 * someone we believe told us to use the particular gateway.
3256 	 */
3257 	save_ire = ire;
3258 	ire = ire_create(
3259 		(uchar_t *)&dst,			/* dest addr */
3260 		(uchar_t *)&ip_g_all_ones,		/* mask */
3261 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3262 		(uchar_t *)&gateway,			/* gateway addr */
3263 		NULL,					/* no in_srcaddr */
3264 		&save_ire->ire_max_frag,		/* max frag */
3265 		NULL,					/* Fast Path header */
3266 		NULL,					/* no rfq */
3267 		NULL,					/* no stq */
3268 		IRE_HOST_REDIRECT,
3269 		NULL,
3270 		NULL,
3271 		NULL,
3272 		0,
3273 		0,
3274 		0,
3275 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3276 		&ulp_info,
3277 		NULL,
3278 		NULL);
3279 
3280 	if (ire == NULL) {
3281 		freemsg(mp);
3282 		ire_refrele(save_ire);
3283 		return;
3284 	}
3285 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3286 	ire_refrele(save_ire);
3287 	atomic_inc_32(&ip_redirect_cnt);
3288 
3289 	if (error == 0) {
3290 		ire_refrele(ire);		/* Held in ire_add_v4 */
3291 		/* tell routing sockets that we received a redirect */
3292 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3293 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3294 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3295 	}
3296 
3297 	/*
3298 	 * Delete any existing IRE_HOST_REDIRECT for this destination.
3299 	 * This together with the added IRE has the effect of
3300 	 * modifying an existing redirect.
3301 	 */
3302 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST_REDIRECT, NULL, NULL,
3303 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3304 	if (prev_ire) {
3305 		ire_delete(prev_ire);
3306 		ire_refrele(prev_ire);
3307 	}
3308 
3309 	freemsg(mp);
3310 }
3311 
3312 /*
3313  * Generate an ICMP parameter problem message.
3314  */
3315 static void
3316 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid)
3317 {
3318 	icmph_t	icmph;
3319 	boolean_t mctl_present;
3320 	mblk_t *first_mp;
3321 
3322 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3323 
3324 	if (!(mp = icmp_pkt_err_ok(mp))) {
3325 		if (mctl_present)
3326 			freeb(first_mp);
3327 		return;
3328 	}
3329 
3330 	bzero(&icmph, sizeof (icmph_t));
3331 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3332 	icmph.icmph_pp_ptr = ptr;
3333 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3334 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3335 }
3336 
3337 /*
3338  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3339  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3340  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3341  * an icmp error packet can be sent.
3342  * Assigns an appropriate source address to the packet. If ipha_dst is
3343  * one of our addresses use it for source. Otherwise pick a source based
3344  * on a route lookup back to ipha_src.
3345  * Note that ipha_src must be set here since the
3346  * packet is likely to arrive on an ill queue in ip_wput() which will
3347  * not set a source address.
3348  */
3349 static void
3350 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3351     boolean_t mctl_present, zoneid_t zoneid)
3352 {
3353 	ipaddr_t dst;
3354 	icmph_t	*icmph;
3355 	ipha_t	*ipha;
3356 	uint_t	len_needed;
3357 	size_t	msg_len;
3358 	mblk_t	*mp1;
3359 	ipaddr_t src;
3360 	ire_t	*ire;
3361 	mblk_t *ipsec_mp;
3362 	ipsec_out_t	*io = NULL;
3363 	boolean_t xmit_if_on = B_FALSE;
3364 
3365 	if (mctl_present) {
3366 		/*
3367 		 * If it is :
3368 		 *
3369 		 * 1) a IPSEC_OUT, then this is caused by outbound
3370 		 *    datagram originating on this host. IPSEC processing
3371 		 *    may or may not have been done. Refer to comments above
3372 		 *    icmp_inbound_error_fanout for details.
3373 		 *
3374 		 * 2) a IPSEC_IN if we are generating a icmp_message
3375 		 *    for an incoming datagram destined for us i.e called
3376 		 *    from ip_fanout_send_icmp.
3377 		 */
3378 		ipsec_info_t *in;
3379 		ipsec_mp = mp;
3380 		mp = ipsec_mp->b_cont;
3381 
3382 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3383 		ipha = (ipha_t *)mp->b_rptr;
3384 
3385 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3386 		    in->ipsec_info_type == IPSEC_IN);
3387 
3388 		if (in->ipsec_info_type == IPSEC_IN) {
3389 			/*
3390 			 * Convert the IPSEC_IN to IPSEC_OUT.
3391 			 */
3392 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3393 				BUMP_MIB(&ip_mib, ipOutDiscards);
3394 				return;
3395 			}
3396 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3397 		} else {
3398 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3399 			io = (ipsec_out_t *)in;
3400 			if (io->ipsec_out_xmit_if)
3401 				xmit_if_on = B_TRUE;
3402 			/*
3403 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3404 			 * ire lookup.
3405 			 */
3406 			io->ipsec_out_proc_begin = B_FALSE;
3407 		}
3408 		ASSERT(zoneid == io->ipsec_out_zoneid);
3409 		ASSERT(zoneid != ALL_ZONES);
3410 	} else {
3411 		/*
3412 		 * This is in clear. The icmp message we are building
3413 		 * here should go out in clear.
3414 		 *
3415 		 * Pardon the convolution of it all, but it's easier to
3416 		 * allocate a "use cleartext" IPSEC_IN message and convert
3417 		 * it than it is to allocate a new one.
3418 		 */
3419 		ipsec_in_t *ii;
3420 		ASSERT(DB_TYPE(mp) == M_DATA);
3421 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3422 			freemsg(mp);
3423 			BUMP_MIB(&ip_mib, ipOutDiscards);
3424 			return;
3425 		}
3426 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3427 
3428 		/* This is not a secure packet */
3429 		ii->ipsec_in_secure = B_FALSE;
3430 		/*
3431 		 * For trusted extensions using a shared IP address we can
3432 		 * send using any zoneid.
3433 		 */
3434 		if (zoneid == ALL_ZONES)
3435 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3436 		else
3437 			ii->ipsec_in_zoneid = zoneid;
3438 		ipsec_mp->b_cont = mp;
3439 		ipha = (ipha_t *)mp->b_rptr;
3440 		/*
3441 		 * Convert the IPSEC_IN to IPSEC_OUT.
3442 		 */
3443 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3444 			BUMP_MIB(&ip_mib, ipOutDiscards);
3445 			return;
3446 		}
3447 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3448 	}
3449 
3450 	/* Remember our eventual destination */
3451 	dst = ipha->ipha_src;
3452 
3453 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3454 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3455 	if (ire != NULL &&
3456 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3457 		src = ipha->ipha_dst;
3458 	} else if (!xmit_if_on) {
3459 		if (ire != NULL)
3460 			ire_refrele(ire);
3461 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3462 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3463 		if (ire == NULL) {
3464 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3465 			freemsg(ipsec_mp);
3466 			return;
3467 		}
3468 		src = ire->ire_src_addr;
3469 	} else {
3470 		ipif_t	*ipif = NULL;
3471 		ill_t	*ill;
3472 		/*
3473 		 * This must be an ICMP error coming from
3474 		 * ip_mrtun_forward(). The src addr should
3475 		 * be equal to the IP-addr of the outgoing
3476 		 * interface.
3477 		 */
3478 		if (io == NULL) {
3479 			/* This is not a IPSEC_OUT type control msg */
3480 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3481 			freemsg(ipsec_mp);
3482 			return;
3483 		}
3484 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3485 		    NULL, NULL, NULL, NULL);
3486 		if (ill != NULL) {
3487 			ipif = ipif_get_next_ipif(NULL, ill);
3488 			ill_refrele(ill);
3489 		}
3490 		if (ipif == NULL) {
3491 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3492 			freemsg(ipsec_mp);
3493 			return;
3494 		}
3495 		src = ipif->ipif_src_addr;
3496 		ipif_refrele(ipif);
3497 	}
3498 
3499 	if (ire != NULL)
3500 		ire_refrele(ire);
3501 
3502 	/*
3503 	 * Check if we can send back more then 8 bytes in addition
3504 	 * to the IP header. We will include as much as 64 bytes.
3505 	 */
3506 	len_needed = IPH_HDR_LENGTH(ipha);
3507 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3508 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3509 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3510 	}
3511 	len_needed += ip_icmp_return;
3512 	msg_len = msgdsize(mp);
3513 	if (msg_len > len_needed) {
3514 		(void) adjmsg(mp, len_needed - msg_len);
3515 		msg_len = len_needed;
3516 	}
3517 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3518 	if (mp1 == NULL) {
3519 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3520 		freemsg(ipsec_mp);
3521 		return;
3522 	}
3523 	/*
3524 	 * On an unlabeled system, dblks don't necessarily have creds.
3525 	 */
3526 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3527 	if (DB_CRED(mp) != NULL)
3528 		mblk_setcred(mp1, DB_CRED(mp));
3529 	mp1->b_cont = mp;
3530 	mp = mp1;
3531 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3532 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3533 	    io->ipsec_out_type == IPSEC_OUT);
3534 	ipsec_mp->b_cont = mp;
3535 
3536 	/*
3537 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3538 	 * node generates be accepted in peace by all on-host destinations.
3539 	 * If we do NOT assume that all on-host destinations trust
3540 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3541 	 * (Look for ipsec_out_icmp_loopback).
3542 	 */
3543 	io->ipsec_out_icmp_loopback = B_TRUE;
3544 
3545 	ipha = (ipha_t *)mp->b_rptr;
3546 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3547 	*ipha = icmp_ipha;
3548 	ipha->ipha_src = src;
3549 	ipha->ipha_dst = dst;
3550 	ipha->ipha_ttl = ip_def_ttl;
3551 	msg_len += sizeof (icmp_ipha) + len;
3552 	if (msg_len > IP_MAXPACKET) {
3553 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3554 		msg_len = IP_MAXPACKET;
3555 	}
3556 	ipha->ipha_length = htons((uint16_t)msg_len);
3557 	icmph = (icmph_t *)&ipha[1];
3558 	bcopy(stuff, icmph, len);
3559 	icmph->icmph_checksum = 0;
3560 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3561 	if (icmph->icmph_checksum == 0)
3562 		icmph->icmph_checksum = 0xFFFF;
3563 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3564 	put(q, ipsec_mp);
3565 }
3566 
3567 /*
3568  * Determine if an ICMP error packet can be sent given the rate limit.
3569  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3570  * in milliseconds) and a burst size. Burst size number of packets can
3571  * be sent arbitrarely closely spaced.
3572  * The state is tracked using two variables to implement an approximate
3573  * token bucket filter:
3574  *	icmp_pkt_err_last - lbolt value when the last burst started
3575  *	icmp_pkt_err_sent - number of packets sent in current burst
3576  */
3577 boolean_t
3578 icmp_err_rate_limit(void)
3579 {
3580 	clock_t now = TICK_TO_MSEC(lbolt);
3581 	uint_t refilled; /* Number of packets refilled in tbf since last */
3582 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3583 
3584 	if (err_interval == 0)
3585 		return (B_FALSE);
3586 
3587 	if (icmp_pkt_err_last > now) {
3588 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3589 		icmp_pkt_err_last = 0;
3590 		icmp_pkt_err_sent = 0;
3591 	}
3592 	/*
3593 	 * If we are in a burst update the token bucket filter.
3594 	 * Update the "last" time to be close to "now" but make sure
3595 	 * we don't loose precision.
3596 	 */
3597 	if (icmp_pkt_err_sent != 0) {
3598 		refilled = (now - icmp_pkt_err_last)/err_interval;
3599 		if (refilled > icmp_pkt_err_sent) {
3600 			icmp_pkt_err_sent = 0;
3601 		} else {
3602 			icmp_pkt_err_sent -= refilled;
3603 			icmp_pkt_err_last += refilled * err_interval;
3604 		}
3605 	}
3606 	if (icmp_pkt_err_sent == 0) {
3607 		/* Start of new burst */
3608 		icmp_pkt_err_last = now;
3609 	}
3610 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3611 		icmp_pkt_err_sent++;
3612 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3613 		    icmp_pkt_err_sent));
3614 		return (B_FALSE);
3615 	}
3616 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3617 	return (B_TRUE);
3618 }
3619 
3620 /*
3621  * Check if it is ok to send an IPv4 ICMP error packet in
3622  * response to the IPv4 packet in mp.
3623  * Free the message and return null if no
3624  * ICMP error packet should be sent.
3625  */
3626 static mblk_t *
3627 icmp_pkt_err_ok(mblk_t *mp)
3628 {
3629 	icmph_t	*icmph;
3630 	ipha_t	*ipha;
3631 	uint_t	len_needed;
3632 	ire_t	*src_ire;
3633 	ire_t	*dst_ire;
3634 
3635 	if (!mp)
3636 		return (NULL);
3637 	ipha = (ipha_t *)mp->b_rptr;
3638 	if (ip_csum_hdr(ipha)) {
3639 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3640 		freemsg(mp);
3641 		return (NULL);
3642 	}
3643 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3644 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3645 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3646 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3647 	if (src_ire != NULL || dst_ire != NULL ||
3648 	    CLASSD(ipha->ipha_dst) ||
3649 	    CLASSD(ipha->ipha_src) ||
3650 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3651 		/* Note: only errors to the fragment with offset 0 */
3652 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3653 		freemsg(mp);
3654 		if (src_ire != NULL)
3655 			ire_refrele(src_ire);
3656 		if (dst_ire != NULL)
3657 			ire_refrele(dst_ire);
3658 		return (NULL);
3659 	}
3660 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3661 		/*
3662 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3663 		 * errors in response to any ICMP errors.
3664 		 */
3665 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3666 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3667 			if (!pullupmsg(mp, len_needed)) {
3668 				BUMP_MIB(&icmp_mib, icmpInErrors);
3669 				freemsg(mp);
3670 				return (NULL);
3671 			}
3672 			ipha = (ipha_t *)mp->b_rptr;
3673 		}
3674 		icmph = (icmph_t *)
3675 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3676 		switch (icmph->icmph_type) {
3677 		case ICMP_DEST_UNREACHABLE:
3678 		case ICMP_SOURCE_QUENCH:
3679 		case ICMP_TIME_EXCEEDED:
3680 		case ICMP_PARAM_PROBLEM:
3681 		case ICMP_REDIRECT:
3682 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3683 			freemsg(mp);
3684 			return (NULL);
3685 		default:
3686 			break;
3687 		}
3688 	}
3689 	/*
3690 	 * If this is a labeled system, then check to see if we're allowed to
3691 	 * send a response to this particular sender.  If not, then just drop.
3692 	 */
3693 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3694 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3695 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3696 		freemsg(mp);
3697 		return (NULL);
3698 	}
3699 	if (icmp_err_rate_limit()) {
3700 		/*
3701 		 * Only send ICMP error packets every so often.
3702 		 * This should be done on a per port/source basis,
3703 		 * but for now this will suffice.
3704 		 */
3705 		freemsg(mp);
3706 		return (NULL);
3707 	}
3708 	return (mp);
3709 }
3710 
3711 /*
3712  * Generate an ICMP redirect message.
3713  */
3714 static void
3715 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3716 {
3717 	icmph_t	icmph;
3718 
3719 	/*
3720 	 * We are called from ip_rput where we could
3721 	 * not have attached an IPSEC_IN.
3722 	 */
3723 	ASSERT(mp->b_datap->db_type == M_DATA);
3724 
3725 	if (!(mp = icmp_pkt_err_ok(mp))) {
3726 		return;
3727 	}
3728 
3729 	bzero(&icmph, sizeof (icmph_t));
3730 	icmph.icmph_type = ICMP_REDIRECT;
3731 	icmph.icmph_code = 1;
3732 	icmph.icmph_rd_gateway = gateway;
3733 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3734 	/* Redirects sent by router, and router is global zone */
3735 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID);
3736 }
3737 
3738 /*
3739  * Generate an ICMP time exceeded message.
3740  */
3741 void
3742 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3743 {
3744 	icmph_t	icmph;
3745 	boolean_t mctl_present;
3746 	mblk_t *first_mp;
3747 
3748 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3749 
3750 	if (!(mp = icmp_pkt_err_ok(mp))) {
3751 		if (mctl_present)
3752 			freeb(first_mp);
3753 		return;
3754 	}
3755 
3756 	bzero(&icmph, sizeof (icmph_t));
3757 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3758 	icmph.icmph_code = code;
3759 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3760 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3761 }
3762 
3763 /*
3764  * Generate an ICMP unreachable message.
3765  */
3766 void
3767 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3768 {
3769 	icmph_t	icmph;
3770 	mblk_t *first_mp;
3771 	boolean_t mctl_present;
3772 
3773 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3774 
3775 	if (!(mp = icmp_pkt_err_ok(mp))) {
3776 		if (mctl_present)
3777 			freeb(first_mp);
3778 		return;
3779 	}
3780 
3781 	bzero(&icmph, sizeof (icmph_t));
3782 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3783 	icmph.icmph_code = code;
3784 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3785 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3786 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3787 	    zoneid);
3788 }
3789 
3790 /*
3791  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3792  * duplicate.  As long as someone else holds the address, the interface will
3793  * stay down.  When that conflict goes away, the interface is brought back up.
3794  * This is done so that accidental shutdowns of addresses aren't made
3795  * permanent.  Your server will recover from a failure.
3796  *
3797  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3798  * user space process (dhcpagent).
3799  *
3800  * Recovery completes if ARP reports that the address is now ours (via
3801  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3802  *
3803  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3804  */
3805 static void
3806 ipif_dup_recovery(void *arg)
3807 {
3808 	ipif_t *ipif = arg;
3809 	ill_t *ill = ipif->ipif_ill;
3810 	mblk_t *arp_add_mp;
3811 	mblk_t *arp_del_mp;
3812 	area_t *area;
3813 
3814 	ipif->ipif_recovery_id = 0;
3815 
3816 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3817 	    (ipif->ipif_flags & IPIF_POINTOPOINT)) {
3818 		/* No reason to try to bring this address back. */
3819 		return;
3820 	}
3821 
3822 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3823 		goto alloc_fail;
3824 
3825 	if (ipif->ipif_arp_del_mp == NULL) {
3826 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3827 			goto alloc_fail;
3828 		ipif->ipif_arp_del_mp = arp_del_mp;
3829 	}
3830 
3831 	/* Setting the 'unverified' flag restarts DAD */
3832 	area = (area_t *)arp_add_mp->b_rptr;
3833 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3834 	    ACE_F_UNVERIFIED;
3835 	putnext(ill->ill_rq, arp_add_mp);
3836 	return;
3837 
3838 alloc_fail:
3839 	/* On allocation failure, just restart the timer */
3840 	freemsg(arp_add_mp);
3841 	if (ip_dup_recovery > 0) {
3842 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3843 		    MSEC_TO_TICK(ip_dup_recovery));
3844 	}
3845 }
3846 
3847 /*
3848  * This is for exclusive changes due to ARP.  Either tear down an interface due
3849  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3850  */
3851 /* ARGSUSED */
3852 static void
3853 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3854 {
3855 	ill_t	*ill = rq->q_ptr;
3856 	arh_t *arh;
3857 	ipaddr_t src;
3858 	ipif_t	*ipif;
3859 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3860 	char hbuf[MAC_STR_LEN];
3861 	char sbuf[INET_ADDRSTRLEN];
3862 	const char *failtype;
3863 	boolean_t bring_up;
3864 
3865 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3866 	case AR_CN_READY:
3867 		failtype = NULL;
3868 		bring_up = B_TRUE;
3869 		break;
3870 	case AR_CN_FAILED:
3871 		failtype = "in use";
3872 		bring_up = B_FALSE;
3873 		break;
3874 	default:
3875 		failtype = "claimed";
3876 		bring_up = B_FALSE;
3877 		break;
3878 	}
3879 
3880 	arh = (arh_t *)mp->b_cont->b_rptr;
3881 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3882 
3883 	/* Handle failures due to probes */
3884 	if (src == 0) {
3885 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3886 		    IP_ADDR_LEN);
3887 	}
3888 
3889 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3890 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3891 	    sizeof (hbuf));
3892 	(void) ip_dot_addr(src, sbuf);
3893 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3894 
3895 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3896 		    ipif->ipif_lcl_addr != src) {
3897 			continue;
3898 		}
3899 
3900 		/*
3901 		 * If we failed on a recovery probe, then restart the timer to
3902 		 * try again later.
3903 		 */
3904 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3905 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3906 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3907 		    ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0) {
3908 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3909 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3910 			continue;
3911 		}
3912 
3913 		/*
3914 		 * If what we're trying to do has already been done, then do
3915 		 * nothing.
3916 		 */
3917 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3918 			continue;
3919 
3920 		if (ipif->ipif_id != 0) {
3921 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3922 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3923 			    ipif->ipif_id);
3924 		}
3925 		if (failtype == NULL) {
3926 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3927 			    ibuf);
3928 		} else {
3929 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3930 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3931 		}
3932 
3933 		if (bring_up) {
3934 			ASSERT(ill->ill_dl_up);
3935 			/*
3936 			 * Free up the ARP delete message so we can allocate
3937 			 * a fresh one through the normal path.
3938 			 */
3939 			freemsg(ipif->ipif_arp_del_mp);
3940 			ipif->ipif_arp_del_mp = NULL;
3941 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3942 			    EINPROGRESS) {
3943 				ipif->ipif_addr_ready = 1;
3944 				(void) ipif_up_done(ipif);
3945 			}
3946 			continue;
3947 		}
3948 
3949 		mutex_enter(&ill->ill_lock);
3950 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3951 		ipif->ipif_flags |= IPIF_DUPLICATE;
3952 		ill->ill_ipif_dup_count++;
3953 		mutex_exit(&ill->ill_lock);
3954 		/*
3955 		 * Already exclusive on the ill; no need to handle deferred
3956 		 * processing here.
3957 		 */
3958 		(void) ipif_down(ipif, NULL, NULL);
3959 		ipif_down_tail(ipif);
3960 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3961 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3962 		    ip_dup_recovery > 0) {
3963 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3964 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3965 		}
3966 	}
3967 	freemsg(mp);
3968 }
3969 
3970 /* ARGSUSED */
3971 static void
3972 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3973 {
3974 	ill_t	*ill = rq->q_ptr;
3975 	arh_t *arh;
3976 	ipaddr_t src;
3977 	ipif_t	*ipif;
3978 
3979 	arh = (arh_t *)mp->b_cont->b_rptr;
3980 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3981 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3982 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3983 			(void) ipif_resolver_up(ipif, Res_act_defend);
3984 	}
3985 	freemsg(mp);
3986 }
3987 
3988 /*
3989  * News from ARP.  ARP sends notification of interesting events down
3990  * to its clients using M_CTL messages with the interesting ARP packet
3991  * attached via b_cont.
3992  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3993  * queue as opposed to ARP sending the message to all the clients, i.e. all
3994  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3995  * table if a cache IRE is found to delete all the entries for the address in
3996  * the packet.
3997  */
3998 static void
3999 ip_arp_news(queue_t *q, mblk_t *mp)
4000 {
4001 	arcn_t		*arcn;
4002 	arh_t		*arh;
4003 	ire_t		*ire = NULL;
4004 	char		hbuf[MAC_STR_LEN];
4005 	char		sbuf[INET_ADDRSTRLEN];
4006 	ipaddr_t	src;
4007 	in6_addr_t	v6src;
4008 	boolean_t	isv6 = B_FALSE;
4009 	ipif_t		*ipif;
4010 	ill_t		*ill;
4011 
4012 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
4013 		if (q->q_next) {
4014 			putnext(q, mp);
4015 		} else
4016 			freemsg(mp);
4017 		return;
4018 	}
4019 	arh = (arh_t *)mp->b_cont->b_rptr;
4020 	/* Is it one we are interested in? */
4021 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
4022 		isv6 = B_TRUE;
4023 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
4024 		    IPV6_ADDR_LEN);
4025 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
4026 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
4027 		    IP_ADDR_LEN);
4028 	} else {
4029 		freemsg(mp);
4030 		return;
4031 	}
4032 
4033 	ill = q->q_ptr;
4034 
4035 	arcn = (arcn_t *)mp->b_rptr;
4036 	switch (arcn->arcn_code) {
4037 	case AR_CN_BOGON:
4038 		/*
4039 		 * Someone is sending ARP packets with a source protocol
4040 		 * address that we have published and for which we believe our
4041 		 * entry is authoritative and (when ill_arp_extend is set)
4042 		 * verified to be unique on the network.
4043 		 *
4044 		 * The ARP module internally handles the cases where the sender
4045 		 * is just probing (for DAD) and where the hardware address of
4046 		 * a non-authoritative entry has changed.  Thus, these are the
4047 		 * real conflicts, and we have to do resolution.
4048 		 *
4049 		 * We back away quickly from the address if it's from DHCP or
4050 		 * otherwise temporary and hasn't been used recently (or at
4051 		 * all).  We'd like to include "deprecated" addresses here as
4052 		 * well (as there's no real reason to defend something we're
4053 		 * discarding), but IPMP "reuses" this flag to mean something
4054 		 * other than the standard meaning.
4055 		 *
4056 		 * If the ARP module above is not extended (meaning that it
4057 		 * doesn't know how to defend the address), then we just log
4058 		 * the problem as we always did and continue on.  It's not
4059 		 * right, but there's little else we can do, and those old ATM
4060 		 * users are going away anyway.
4061 		 */
4062 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4063 		    hbuf, sizeof (hbuf));
4064 		(void) ip_dot_addr(src, sbuf);
4065 		if (isv6)
4066 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
4067 		else
4068 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
4069 
4070 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4071 			uint32_t now;
4072 			uint32_t maxage;
4073 			clock_t lused;
4074 			uint_t maxdefense;
4075 			uint_t defs;
4076 
4077 			/*
4078 			 * First, figure out if this address hasn't been used
4079 			 * in a while.  If it hasn't, then it's a better
4080 			 * candidate for abandoning.
4081 			 */
4082 			ipif = ire->ire_ipif;
4083 			ASSERT(ipif != NULL);
4084 			now = gethrestime_sec();
4085 			maxage = now - ire->ire_create_time;
4086 			if (maxage > ip_max_temp_idle)
4087 				maxage = ip_max_temp_idle;
4088 			lused = drv_hztousec(ddi_get_lbolt() -
4089 			    ire->ire_last_used_time) / MICROSEC + 1;
4090 			if (lused >= maxage && (ipif->ipif_flags &
4091 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4092 				maxdefense = ip_max_temp_defend;
4093 			else
4094 				maxdefense = ip_max_defend;
4095 
4096 			/*
4097 			 * Now figure out how many times we've defended
4098 			 * ourselves.  Ignore defenses that happened long in
4099 			 * the past.
4100 			 */
4101 			mutex_enter(&ire->ire_lock);
4102 			if ((defs = ire->ire_defense_count) > 0 &&
4103 			    now - ire->ire_defense_time > ip_defend_interval) {
4104 				ire->ire_defense_count = defs = 0;
4105 			}
4106 			ire->ire_defense_count++;
4107 			ire->ire_defense_time = now;
4108 			mutex_exit(&ire->ire_lock);
4109 			ill_refhold(ill);
4110 			ire_refrele(ire);
4111 
4112 			/*
4113 			 * If we've defended ourselves too many times already,
4114 			 * then give up and tear down the interface(s) using
4115 			 * this address.  Otherwise, defend by sending out a
4116 			 * gratuitous ARP.
4117 			 */
4118 			if (defs >= maxdefense && ill->ill_arp_extend) {
4119 				(void) qwriter_ip(NULL, ill, q, mp,
4120 				    ip_arp_excl, CUR_OP, B_FALSE);
4121 			} else {
4122 				cmn_err(CE_WARN,
4123 				    "node %s is using our IP address %s on %s",
4124 				    hbuf, sbuf, ill->ill_name);
4125 				/*
4126 				 * If this is an old (ATM) ARP module, then
4127 				 * don't try to defend the address.  Remain
4128 				 * compatible with the old behavior.  Defend
4129 				 * only with new ARP.
4130 				 */
4131 				if (ill->ill_arp_extend) {
4132 					(void) qwriter_ip(NULL, ill, q, mp,
4133 					    ip_arp_defend, CUR_OP, B_FALSE);
4134 				} else {
4135 					ill_refrele(ill);
4136 				}
4137 			}
4138 			return;
4139 		}
4140 		cmn_err(CE_WARN,
4141 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4142 		    hbuf, sbuf, ill->ill_name);
4143 		if (ire != NULL)
4144 			ire_refrele(ire);
4145 		break;
4146 	case AR_CN_ANNOUNCE:
4147 		if (isv6) {
4148 			/*
4149 			 * For XRESOLV interfaces.
4150 			 * Delete the IRE cache entry and NCE for this
4151 			 * v6 address
4152 			 */
4153 			ip_ire_clookup_and_delete_v6(&v6src);
4154 			/*
4155 			 * If v6src is a non-zero, it's a router address
4156 			 * as below. Do the same sort of thing to clean
4157 			 * out off-net IRE_CACHE entries that go through
4158 			 * the router.
4159 			 */
4160 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4161 				ire_walk_v6(ire_delete_cache_gw_v6,
4162 				    (char *)&v6src, ALL_ZONES);
4163 			}
4164 		} else {
4165 			nce_hw_map_t hwm;
4166 
4167 			/*
4168 			 * ARP gives us a copy of any packet where it thinks
4169 			 * the address has changed, so that we can update our
4170 			 * caches.  We're responsible for caching known answers
4171 			 * in the current design.  We check whether the
4172 			 * hardware address really has changed in all of our
4173 			 * entries that have cached this mapping, and if so, we
4174 			 * blow them away.  This way we will immediately pick
4175 			 * up the rare case of a host changing hardware
4176 			 * address.
4177 			 */
4178 			if (src == 0)
4179 				break;
4180 			hwm.hwm_addr = src;
4181 			hwm.hwm_hwlen = arh->arh_hlen;
4182 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4183 			ndp_walk_common(&ndp4, NULL,
4184 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4185 		}
4186 		break;
4187 	case AR_CN_READY:
4188 		/* No external v6 resolver has a contract to use this */
4189 		if (isv6)
4190 			break;
4191 		/* If the link is down, we'll retry this later */
4192 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4193 			break;
4194 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4195 		    NULL, NULL);
4196 		if (ipif != NULL) {
4197 			/*
4198 			 * If this is a duplicate recovery, then we now need to
4199 			 * go exclusive to bring this thing back up.
4200 			 */
4201 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4202 			    IPIF_DUPLICATE) {
4203 				ipif_refrele(ipif);
4204 				ill_refhold(ill);
4205 				(void) qwriter_ip(NULL, ill, q, mp,
4206 				    ip_arp_excl, CUR_OP, B_FALSE);
4207 				return;
4208 			}
4209 			/*
4210 			 * If this is the first notice that this address is
4211 			 * ready, then let the user know now.
4212 			 */
4213 			if ((ipif->ipif_flags & IPIF_UP) &&
4214 			    !ipif->ipif_addr_ready) {
4215 				ipif_mask_reply(ipif);
4216 				ip_rts_ifmsg(ipif);
4217 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4218 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4219 			}
4220 			ipif->ipif_addr_ready = 1;
4221 			ipif_refrele(ipif);
4222 		}
4223 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp));
4224 		if (ire != NULL) {
4225 			ire->ire_defense_count = 0;
4226 			ire_refrele(ire);
4227 		}
4228 		break;
4229 	case AR_CN_FAILED:
4230 		/* No external v6 resolver has a contract to use this */
4231 		if (isv6)
4232 			break;
4233 		ill_refhold(ill);
4234 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4235 		    B_FALSE);
4236 		return;
4237 	}
4238 	freemsg(mp);
4239 }
4240 
4241 /*
4242  * Create a mblk suitable for carrying the interface index and/or source link
4243  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4244  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4245  * application.
4246  */
4247 mblk_t *
4248 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
4249 {
4250 	mblk_t		*mp;
4251 	in_pktinfo_t	*pinfo;
4252 	ipha_t *ipha;
4253 	struct ether_header *pether;
4254 
4255 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
4256 	if (mp == NULL) {
4257 		ip1dbg(("ip_add_info: allocation failure.\n"));
4258 		return (data_mp);
4259 	}
4260 
4261 	ipha	= (ipha_t *)data_mp->b_rptr;
4262 	pinfo = (in_pktinfo_t *)mp->b_rptr;
4263 	bzero(pinfo, sizeof (in_pktinfo_t));
4264 	pinfo->in_pkt_flags = (uchar_t)flags;
4265 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4266 
4267 	if (flags & IPF_RECVIF)
4268 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4269 
4270 	pether = (struct ether_header *)((char *)ipha
4271 	    - sizeof (struct ether_header));
4272 	/*
4273 	 * Make sure the interface is an ethernet type, since this option
4274 	 * is currently supported only on this type of interface. Also make
4275 	 * sure we are pointing correctly above db_base.
4276 	 */
4277 
4278 	if ((flags & IPF_RECVSLLA) &&
4279 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4280 	    (ill->ill_type == IFT_ETHER) &&
4281 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4282 
4283 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
4284 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4285 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
4286 	} else {
4287 		/*
4288 		 * Clear the bit. Indicate to upper layer that IP is not
4289 		 * sending this ancillary info.
4290 		 */
4291 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
4292 	}
4293 
4294 	mp->b_datap->db_type = M_CTL;
4295 	mp->b_wptr += sizeof (in_pktinfo_t);
4296 	mp->b_cont = data_mp;
4297 
4298 	return (mp);
4299 }
4300 
4301 /*
4302  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4303  * part of the bind request.
4304  */
4305 
4306 boolean_t
4307 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4308 {
4309 	ipsec_in_t *ii;
4310 
4311 	ASSERT(policy_mp != NULL);
4312 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4313 
4314 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4315 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4316 
4317 	connp->conn_policy = ii->ipsec_in_policy;
4318 	ii->ipsec_in_policy = NULL;
4319 
4320 	if (ii->ipsec_in_action != NULL) {
4321 		if (connp->conn_latch == NULL) {
4322 			connp->conn_latch = iplatch_create();
4323 			if (connp->conn_latch == NULL)
4324 				return (B_FALSE);
4325 		}
4326 		ipsec_latch_inbound(connp->conn_latch, ii);
4327 	}
4328 	return (B_TRUE);
4329 }
4330 
4331 /*
4332  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4333  * and to arrange for power-fanout assist.  The ULP is identified by
4334  * adding a single byte at the end of the original bind message.
4335  * A ULP other than UDP or TCP that wishes to be recognized passes
4336  * down a bind with a zero length address.
4337  *
4338  * The binding works as follows:
4339  * - A zero byte address means just bind to the protocol.
4340  * - A four byte address is treated as a request to validate
4341  *   that the address is a valid local address, appropriate for
4342  *   an application to bind to. This does not affect any fanout
4343  *   information in IP.
4344  * - A sizeof sin_t byte address is used to bind to only the local address
4345  *   and port.
4346  * - A sizeof ipa_conn_t byte address contains complete fanout information
4347  *   consisting of local and remote addresses and ports.  In
4348  *   this case, the addresses are both validated as appropriate
4349  *   for this operation, and, if so, the information is retained
4350  *   for use in the inbound fanout.
4351  *
4352  * The ULP (except in the zero-length bind) can append an
4353  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4354  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4355  * a copy of the source or destination IRE (source for local bind;
4356  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4357  * policy information contained should be copied on to the conn.
4358  *
4359  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4360  */
4361 mblk_t *
4362 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4363 {
4364 	ssize_t		len;
4365 	struct T_bind_req	*tbr;
4366 	sin_t		*sin;
4367 	ipa_conn_t	*ac;
4368 	uchar_t		*ucp;
4369 	mblk_t		*mp1;
4370 	boolean_t	ire_requested;
4371 	boolean_t	ipsec_policy_set = B_FALSE;
4372 	int		error = 0;
4373 	int		protocol;
4374 	ipa_conn_x_t	*acx;
4375 
4376 	ASSERT(!connp->conn_af_isv6);
4377 	connp->conn_pkt_isv6 = B_FALSE;
4378 
4379 	len = MBLKL(mp);
4380 	if (len < (sizeof (*tbr) + 1)) {
4381 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4382 		    "ip_bind: bogus msg, len %ld", len);
4383 		/* XXX: Need to return something better */
4384 		goto bad_addr;
4385 	}
4386 	/* Back up and extract the protocol identifier. */
4387 	mp->b_wptr--;
4388 	protocol = *mp->b_wptr & 0xFF;
4389 	tbr = (struct T_bind_req *)mp->b_rptr;
4390 	/* Reset the message type in preparation for shipping it back. */
4391 	DB_TYPE(mp) = M_PCPROTO;
4392 
4393 	connp->conn_ulp = (uint8_t)protocol;
4394 
4395 	/*
4396 	 * Check for a zero length address.  This is from a protocol that
4397 	 * wants to register to receive all packets of its type.
4398 	 */
4399 	if (tbr->ADDR_length == 0) {
4400 		/*
4401 		 * These protocols are now intercepted in ip_bind_v6().
4402 		 * Reject protocol-level binds here for now.
4403 		 *
4404 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4405 		 * so that the protocol type cannot be SCTP.
4406 		 */
4407 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4408 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4409 			goto bad_addr;
4410 		}
4411 
4412 		/*
4413 		 *
4414 		 * The udp module never sends down a zero-length address,
4415 		 * and allowing this on a labeled system will break MLP
4416 		 * functionality.
4417 		 */
4418 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4419 			goto bad_addr;
4420 
4421 		if (connp->conn_mac_exempt)
4422 			goto bad_addr;
4423 
4424 		/* No hash here really.  The table is big enough. */
4425 		connp->conn_srcv6 = ipv6_all_zeros;
4426 
4427 		ipcl_proto_insert(connp, protocol);
4428 
4429 		tbr->PRIM_type = T_BIND_ACK;
4430 		return (mp);
4431 	}
4432 
4433 	/* Extract the address pointer from the message. */
4434 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4435 	    tbr->ADDR_length);
4436 	if (ucp == NULL) {
4437 		ip1dbg(("ip_bind: no address\n"));
4438 		goto bad_addr;
4439 	}
4440 	if (!OK_32PTR(ucp)) {
4441 		ip1dbg(("ip_bind: unaligned address\n"));
4442 		goto bad_addr;
4443 	}
4444 	/*
4445 	 * Check for trailing mps.
4446 	 */
4447 
4448 	mp1 = mp->b_cont;
4449 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4450 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4451 
4452 	switch (tbr->ADDR_length) {
4453 	default:
4454 		ip1dbg(("ip_bind: bad address length %d\n",
4455 		    (int)tbr->ADDR_length));
4456 		goto bad_addr;
4457 
4458 	case IP_ADDR_LEN:
4459 		/* Verification of local address only */
4460 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4461 		    ire_requested, ipsec_policy_set, B_FALSE);
4462 		break;
4463 
4464 	case sizeof (sin_t):
4465 		sin = (sin_t *)ucp;
4466 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4467 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4468 		if (protocol == IPPROTO_TCP)
4469 			connp->conn_recv = tcp_conn_request;
4470 		break;
4471 
4472 	case sizeof (ipa_conn_t):
4473 		ac = (ipa_conn_t *)ucp;
4474 		/* For raw socket, the local port is not set. */
4475 		if (ac->ac_lport == 0)
4476 			ac->ac_lport = connp->conn_lport;
4477 		/* Always verify destination reachability. */
4478 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4479 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4480 		    ipsec_policy_set, B_TRUE, B_TRUE);
4481 		if (protocol == IPPROTO_TCP)
4482 			connp->conn_recv = tcp_input;
4483 		break;
4484 
4485 	case sizeof (ipa_conn_x_t):
4486 		acx = (ipa_conn_x_t *)ucp;
4487 		/*
4488 		 * Whether or not to verify destination reachability depends
4489 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4490 		 */
4491 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4492 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4493 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4494 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4495 		if (protocol == IPPROTO_TCP)
4496 			connp->conn_recv = tcp_input;
4497 		break;
4498 	}
4499 	if (error == EINPROGRESS)
4500 		return (NULL);
4501 	else if (error != 0)
4502 		goto bad_addr;
4503 	/*
4504 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4505 	 * We can't do this in ip_bind_insert_ire because the policy
4506 	 * may not have been inherited at that point in time and hence
4507 	 * conn_out_enforce_policy may not be set.
4508 	 */
4509 	mp1 = mp->b_cont;
4510 	if (ire_requested && connp->conn_out_enforce_policy &&
4511 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4512 		ire_t *ire = (ire_t *)mp1->b_rptr;
4513 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4514 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4515 	}
4516 
4517 	/* Send it home. */
4518 	mp->b_datap->db_type = M_PCPROTO;
4519 	tbr->PRIM_type = T_BIND_ACK;
4520 	return (mp);
4521 
4522 bad_addr:
4523 	/*
4524 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4525 	 * a unix errno.
4526 	 */
4527 	if (error > 0)
4528 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4529 	else
4530 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4531 	return (mp);
4532 }
4533 
4534 /*
4535  * Here address is verified to be a valid local address.
4536  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4537  * address is also considered a valid local address.
4538  * In the case of a broadcast/multicast address, however, the
4539  * upper protocol is expected to reset the src address
4540  * to 0 if it sees a IRE_BROADCAST type returned so that
4541  * no packets are emitted with broadcast/multicast address as
4542  * source address (that violates hosts requirements RFC1122)
4543  * The addresses valid for bind are:
4544  *	(1) - INADDR_ANY (0)
4545  *	(2) - IP address of an UP interface
4546  *	(3) - IP address of a DOWN interface
4547  *	(4) - valid local IP broadcast addresses. In this case
4548  *	the conn will only receive packets destined to
4549  *	the specified broadcast address.
4550  *	(5) - a multicast address. In this case
4551  *	the conn will only receive packets destined to
4552  *	the specified multicast address. Note: the
4553  *	application still has to issue an
4554  *	IP_ADD_MEMBERSHIP socket option.
4555  *
4556  * On error, return -1 for TBADADDR otherwise pass the
4557  * errno with TSYSERR reply.
4558  *
4559  * In all the above cases, the bound address must be valid in the current zone.
4560  * When the address is loopback, multicast or broadcast, there might be many
4561  * matching IREs so bind has to look up based on the zone.
4562  *
4563  * Note: lport is in network byte order.
4564  */
4565 int
4566 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4567     boolean_t ire_requested, boolean_t ipsec_policy_set,
4568     boolean_t fanout_insert)
4569 {
4570 	int		error = 0;
4571 	ire_t		*src_ire;
4572 	mblk_t		*policy_mp;
4573 	ipif_t		*ipif;
4574 	zoneid_t	zoneid;
4575 
4576 	if (ipsec_policy_set) {
4577 		policy_mp = mp->b_cont;
4578 	}
4579 
4580 	/*
4581 	 * If it was previously connected, conn_fully_bound would have
4582 	 * been set.
4583 	 */
4584 	connp->conn_fully_bound = B_FALSE;
4585 
4586 	src_ire = NULL;
4587 	ipif = NULL;
4588 
4589 	zoneid = IPCL_ZONEID(connp);
4590 
4591 	if (src_addr) {
4592 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4593 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4594 		/*
4595 		 * If an address other than 0.0.0.0 is requested,
4596 		 * we verify that it is a valid address for bind
4597 		 * Note: Following code is in if-else-if form for
4598 		 * readability compared to a condition check.
4599 		 */
4600 		/* LINTED - statement has no consequent */
4601 		if (IRE_IS_LOCAL(src_ire)) {
4602 			/*
4603 			 * (2) Bind to address of local UP interface
4604 			 */
4605 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4606 			/*
4607 			 * (4) Bind to broadcast address
4608 			 * Note: permitted only from transports that
4609 			 * request IRE
4610 			 */
4611 			if (!ire_requested)
4612 				error = EADDRNOTAVAIL;
4613 		} else {
4614 			/*
4615 			 * (3) Bind to address of local DOWN interface
4616 			 * (ipif_lookup_addr() looks up all interfaces
4617 			 * but we do not get here for UP interfaces
4618 			 * - case (2) above)
4619 			 * We put the protocol byte back into the mblk
4620 			 * since we may come back via ip_wput_nondata()
4621 			 * later with this mblk if ipif_lookup_addr chooses
4622 			 * to defer processing.
4623 			 */
4624 			*mp->b_wptr++ = (char)connp->conn_ulp;
4625 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4626 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4627 			    &error)) != NULL) {
4628 				ipif_refrele(ipif);
4629 			} else if (error == EINPROGRESS) {
4630 				if (src_ire != NULL)
4631 					ire_refrele(src_ire);
4632 				return (EINPROGRESS);
4633 			} else if (CLASSD(src_addr)) {
4634 				error = 0;
4635 				if (src_ire != NULL)
4636 					ire_refrele(src_ire);
4637 				/*
4638 				 * (5) bind to multicast address.
4639 				 * Fake out the IRE returned to upper
4640 				 * layer to be a broadcast IRE.
4641 				 */
4642 				src_ire = ire_ctable_lookup(
4643 				    INADDR_BROADCAST, INADDR_ANY,
4644 				    IRE_BROADCAST, NULL, zoneid, NULL,
4645 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4646 				if (src_ire == NULL || !ire_requested)
4647 					error = EADDRNOTAVAIL;
4648 			} else {
4649 				/*
4650 				 * Not a valid address for bind
4651 				 */
4652 				error = EADDRNOTAVAIL;
4653 			}
4654 			/*
4655 			 * Just to keep it consistent with the processing in
4656 			 * ip_bind_v4()
4657 			 */
4658 			mp->b_wptr--;
4659 		}
4660 		if (error) {
4661 			/* Red Alert!  Attempting to be a bogon! */
4662 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4663 			    ntohl(src_addr)));
4664 			goto bad_addr;
4665 		}
4666 	}
4667 
4668 	/*
4669 	 * Allow setting new policies. For example, disconnects come
4670 	 * down as ipa_t bind. As we would have set conn_policy_cached
4671 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4672 	 * can change after the disconnect.
4673 	 */
4674 	connp->conn_policy_cached = B_FALSE;
4675 
4676 	/*
4677 	 * If not fanout_insert this was just an address verification
4678 	 */
4679 	if (fanout_insert) {
4680 		/*
4681 		 * The addresses have been verified. Time to insert in
4682 		 * the correct fanout list.
4683 		 */
4684 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4685 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4686 		connp->conn_lport = lport;
4687 		connp->conn_fport = 0;
4688 		/*
4689 		 * Do we need to add a check to reject Multicast packets
4690 		 */
4691 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4692 	}
4693 
4694 	if (error == 0) {
4695 		if (ire_requested) {
4696 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4697 				error = -1;
4698 				/* Falls through to bad_addr */
4699 			}
4700 		} else if (ipsec_policy_set) {
4701 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4702 				error = -1;
4703 				/* Falls through to bad_addr */
4704 			}
4705 		}
4706 	}
4707 bad_addr:
4708 	if (error != 0) {
4709 		if (connp->conn_anon_port) {
4710 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4711 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4712 			    B_FALSE);
4713 		}
4714 		connp->conn_mlp_type = mlptSingle;
4715 	}
4716 	if (src_ire != NULL)
4717 		IRE_REFRELE(src_ire);
4718 	if (ipsec_policy_set) {
4719 		ASSERT(policy_mp == mp->b_cont);
4720 		ASSERT(policy_mp != NULL);
4721 		freeb(policy_mp);
4722 		/*
4723 		 * As of now assume that nothing else accompanies
4724 		 * IPSEC_POLICY_SET.
4725 		 */
4726 		mp->b_cont = NULL;
4727 	}
4728 	return (error);
4729 }
4730 
4731 /*
4732  * Verify that both the source and destination addresses
4733  * are valid.  If verify_dst is false, then the destination address may be
4734  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4735  * destination reachability, while tunnels do not.
4736  * Note that we allow connect to broadcast and multicast
4737  * addresses when ire_requested is set. Thus the ULP
4738  * has to check for IRE_BROADCAST and multicast.
4739  *
4740  * Returns zero if ok.
4741  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4742  * (for use with TSYSERR reply).
4743  *
4744  * Note: lport and fport are in network byte order.
4745  */
4746 int
4747 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4748     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4749     boolean_t ire_requested, boolean_t ipsec_policy_set,
4750     boolean_t fanout_insert, boolean_t verify_dst)
4751 {
4752 	ire_t		*src_ire;
4753 	ire_t		*dst_ire;
4754 	int		error = 0;
4755 	int 		protocol;
4756 	mblk_t		*policy_mp;
4757 	ire_t		*sire = NULL;
4758 	ire_t		*md_dst_ire = NULL;
4759 	ill_t		*md_ill = NULL;
4760 	zoneid_t	zoneid;
4761 	ipaddr_t	src_addr = *src_addrp;
4762 
4763 	src_ire = dst_ire = NULL;
4764 	protocol = *mp->b_wptr & 0xFF;
4765 
4766 	/*
4767 	 * If we never got a disconnect before, clear it now.
4768 	 */
4769 	connp->conn_fully_bound = B_FALSE;
4770 
4771 	if (ipsec_policy_set) {
4772 		policy_mp = mp->b_cont;
4773 	}
4774 
4775 	zoneid = IPCL_ZONEID(connp);
4776 
4777 	if (CLASSD(dst_addr)) {
4778 		/* Pick up an IRE_BROADCAST */
4779 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4780 		    NULL, zoneid, MBLK_GETLABEL(mp),
4781 		    (MATCH_IRE_RECURSIVE |
4782 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4783 		    MATCH_IRE_SECATTR));
4784 	} else {
4785 		/*
4786 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4787 		 * and onlink ipif is not found set ENETUNREACH error.
4788 		 */
4789 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4790 			ipif_t *ipif;
4791 
4792 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4793 			    dst_addr : connp->conn_nexthop_v4, zoneid);
4794 			if (ipif == NULL) {
4795 				error = ENETUNREACH;
4796 				goto bad_addr;
4797 			}
4798 			ipif_refrele(ipif);
4799 		}
4800 
4801 		if (connp->conn_nexthop_set) {
4802 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4803 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4804 			    MATCH_IRE_SECATTR);
4805 		} else {
4806 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4807 			    &sire, zoneid, MBLK_GETLABEL(mp),
4808 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4809 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4810 			    MATCH_IRE_SECATTR));
4811 		}
4812 	}
4813 	/*
4814 	 * dst_ire can't be a broadcast when not ire_requested.
4815 	 * We also prevent ire's with src address INADDR_ANY to
4816 	 * be used, which are created temporarily for
4817 	 * sending out packets from endpoints that have
4818 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4819 	 * reachable.  If verify_dst is false, the destination needn't be
4820 	 * reachable.
4821 	 *
4822 	 * If we match on a reject or black hole, then we've got a
4823 	 * local failure.  May as well fail out the connect() attempt,
4824 	 * since it's never going to succeed.
4825 	 */
4826 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4827 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4828 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4829 		/*
4830 		 * If we're verifying destination reachability, we always want
4831 		 * to complain here.
4832 		 *
4833 		 * If we're not verifying destination reachability but the
4834 		 * destination has a route, we still want to fail on the
4835 		 * temporary address and broadcast address tests.
4836 		 */
4837 		if (verify_dst || (dst_ire != NULL)) {
4838 			if (ip_debug > 2) {
4839 				pr_addr_dbg("ip_bind_connected: bad connected "
4840 				    "dst %s\n", AF_INET, &dst_addr);
4841 			}
4842 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4843 				error = ENETUNREACH;
4844 			else
4845 				error = EHOSTUNREACH;
4846 			goto bad_addr;
4847 		}
4848 	}
4849 
4850 	/*
4851 	 * We now know that routing will allow us to reach the destination.
4852 	 * Check whether Trusted Solaris policy allows communication with this
4853 	 * host, and pretend that the destination is unreachable if not.
4854 	 *
4855 	 * This is never a problem for TCP, since that transport is known to
4856 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4857 	 * handling.  If the remote is unreachable, it will be detected at that
4858 	 * point, so there's no reason to check it here.
4859 	 *
4860 	 * Note that for sendto (and other datagram-oriented friends), this
4861 	 * check is done as part of the data path label computation instead.
4862 	 * The check here is just to make non-TCP connect() report the right
4863 	 * error.
4864 	 */
4865 	if (dst_ire != NULL && is_system_labeled() &&
4866 	    !IPCL_IS_TCP(connp) &&
4867 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4868 	    connp->conn_mac_exempt) != 0) {
4869 		error = EHOSTUNREACH;
4870 		if (ip_debug > 2) {
4871 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4872 			    AF_INET, &dst_addr);
4873 		}
4874 		goto bad_addr;
4875 	}
4876 
4877 	/*
4878 	 * If the app does a connect(), it means that it will most likely
4879 	 * send more than 1 packet to the destination.  It makes sense
4880 	 * to clear the temporary flag.
4881 	 */
4882 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4883 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4884 		irb_t *irb = dst_ire->ire_bucket;
4885 
4886 		rw_enter(&irb->irb_lock, RW_WRITER);
4887 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4888 		irb->irb_tmp_ire_cnt--;
4889 		rw_exit(&irb->irb_lock);
4890 	}
4891 
4892 	/*
4893 	 * See if we should notify ULP about MDT; we do this whether or not
4894 	 * ire_requested is TRUE, in order to handle active connects; MDT
4895 	 * eligibility tests for passive connects are handled separately
4896 	 * through tcp_adapt_ire().  We do this before the source address
4897 	 * selection, because dst_ire may change after a call to
4898 	 * ipif_select_source().  This is a best-effort check, as the
4899 	 * packet for this connection may not actually go through
4900 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4901 	 * calling ip_newroute().  This is why we further check on the
4902 	 * IRE during Multidata packet transmission in tcp_multisend().
4903 	 */
4904 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4905 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4906 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4907 	    ILL_MDT_CAPABLE(md_ill)) {
4908 		md_dst_ire = dst_ire;
4909 		IRE_REFHOLD(md_dst_ire);
4910 	}
4911 
4912 	if (dst_ire != NULL &&
4913 	    dst_ire->ire_type == IRE_LOCAL &&
4914 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4915 		/*
4916 		 * If the IRE belongs to a different zone, look for a matching
4917 		 * route in the forwarding table and use the source address from
4918 		 * that route.
4919 		 */
4920 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4921 		    zoneid, 0, NULL,
4922 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4923 		    MATCH_IRE_RJ_BHOLE);
4924 		if (src_ire == NULL) {
4925 			error = EHOSTUNREACH;
4926 			goto bad_addr;
4927 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4928 			if (!(src_ire->ire_type & IRE_HOST))
4929 				error = ENETUNREACH;
4930 			else
4931 				error = EHOSTUNREACH;
4932 			goto bad_addr;
4933 		}
4934 		if (src_addr == INADDR_ANY)
4935 			src_addr = src_ire->ire_src_addr;
4936 		ire_refrele(src_ire);
4937 		src_ire = NULL;
4938 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4939 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4940 			src_addr = sire->ire_src_addr;
4941 			ire_refrele(dst_ire);
4942 			dst_ire = sire;
4943 			sire = NULL;
4944 		} else {
4945 			/*
4946 			 * Pick a source address so that a proper inbound
4947 			 * load spreading would happen.
4948 			 */
4949 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4950 			ipif_t *src_ipif = NULL;
4951 			ire_t *ipif_ire;
4952 
4953 			/*
4954 			 * Supply a local source address such that inbound
4955 			 * load spreading happens.
4956 			 *
4957 			 * Determine the best source address on this ill for
4958 			 * the destination.
4959 			 *
4960 			 * 1) For broadcast, we should return a broadcast ire
4961 			 *    found above so that upper layers know that the
4962 			 *    destination address is a broadcast address.
4963 			 *
4964 			 * 2) If this is part of a group, select a better
4965 			 *    source address so that better inbound load
4966 			 *    balancing happens. Do the same if the ipif
4967 			 *    is DEPRECATED.
4968 			 *
4969 			 * 3) If the outgoing interface is part of a usesrc
4970 			 *    group, then try selecting a source address from
4971 			 *    the usesrc ILL.
4972 			 */
4973 			if ((dst_ire->ire_zoneid != zoneid &&
4974 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4975 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4976 			    ((dst_ill->ill_group != NULL) ||
4977 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4978 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4979 				/*
4980 				 * If the destination is reachable via a
4981 				 * given gateway, the selected source address
4982 				 * should be in the same subnet as the gateway.
4983 				 * Otherwise, the destination is not reachable.
4984 				 *
4985 				 * If there are no interfaces on the same subnet
4986 				 * as the destination, ipif_select_source gives
4987 				 * first non-deprecated interface which might be
4988 				 * on a different subnet than the gateway.
4989 				 * This is not desirable. Hence pass the dst_ire
4990 				 * source address to ipif_select_source.
4991 				 * It is sure that the destination is reachable
4992 				 * with the dst_ire source address subnet.
4993 				 * So passing dst_ire source address to
4994 				 * ipif_select_source will make sure that the
4995 				 * selected source will be on the same subnet
4996 				 * as dst_ire source address.
4997 				 */
4998 				ipaddr_t saddr =
4999 				    dst_ire->ire_ipif->ipif_src_addr;
5000 				src_ipif = ipif_select_source(dst_ill,
5001 				    saddr, zoneid);
5002 				if (src_ipif != NULL) {
5003 					if (IS_VNI(src_ipif->ipif_ill)) {
5004 						/*
5005 						 * For VNI there is no
5006 						 * interface route
5007 						 */
5008 						src_addr =
5009 						    src_ipif->ipif_src_addr;
5010 					} else {
5011 						ipif_ire =
5012 						    ipif_to_ire(src_ipif);
5013 						if (ipif_ire != NULL) {
5014 							IRE_REFRELE(dst_ire);
5015 							dst_ire = ipif_ire;
5016 						}
5017 						src_addr =
5018 						    dst_ire->ire_src_addr;
5019 					}
5020 					ipif_refrele(src_ipif);
5021 				} else {
5022 					src_addr = dst_ire->ire_src_addr;
5023 				}
5024 			} else {
5025 				src_addr = dst_ire->ire_src_addr;
5026 			}
5027 		}
5028 	}
5029 
5030 	/*
5031 	 * We do ire_route_lookup() here (and not
5032 	 * interface lookup as we assert that
5033 	 * src_addr should only come from an
5034 	 * UP interface for hard binding.
5035 	 */
5036 	ASSERT(src_ire == NULL);
5037 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5038 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
5039 	/* src_ire must be a local|loopback */
5040 	if (!IRE_IS_LOCAL(src_ire)) {
5041 		if (ip_debug > 2) {
5042 			pr_addr_dbg("ip_bind_connected: bad connected "
5043 			    "src %s\n", AF_INET, &src_addr);
5044 		}
5045 		error = EADDRNOTAVAIL;
5046 		goto bad_addr;
5047 	}
5048 
5049 	/*
5050 	 * If the source address is a loopback address, the
5051 	 * destination had best be local or multicast.
5052 	 * The transports that can't handle multicast will reject
5053 	 * those addresses.
5054 	 */
5055 	if (src_ire->ire_type == IRE_LOOPBACK &&
5056 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5057 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5058 		error = -1;
5059 		goto bad_addr;
5060 	}
5061 
5062 	/*
5063 	 * Allow setting new policies. For example, disconnects come
5064 	 * down as ipa_t bind. As we would have set conn_policy_cached
5065 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5066 	 * can change after the disconnect.
5067 	 */
5068 	connp->conn_policy_cached = B_FALSE;
5069 
5070 	/*
5071 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5072 	 * can handle their passed-in conn's.
5073 	 */
5074 
5075 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5076 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5077 	connp->conn_lport = lport;
5078 	connp->conn_fport = fport;
5079 	*src_addrp = src_addr;
5080 
5081 	ASSERT(!(ipsec_policy_set && ire_requested));
5082 	if (ire_requested) {
5083 		iulp_t *ulp_info = NULL;
5084 
5085 		/*
5086 		 * Note that sire will not be NULL if this is an off-link
5087 		 * connection and there is not cache for that dest yet.
5088 		 *
5089 		 * XXX Because of an existing bug, if there are multiple
5090 		 * default routes, the IRE returned now may not be the actual
5091 		 * default route used (default routes are chosen in a
5092 		 * round robin fashion).  So if the metrics for different
5093 		 * default routes are different, we may return the wrong
5094 		 * metrics.  This will not be a problem if the existing
5095 		 * bug is fixed.
5096 		 */
5097 		if (sire != NULL) {
5098 			ulp_info = &(sire->ire_uinfo);
5099 		}
5100 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5101 			error = -1;
5102 			goto bad_addr;
5103 		}
5104 	} else if (ipsec_policy_set) {
5105 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5106 			error = -1;
5107 			goto bad_addr;
5108 		}
5109 	}
5110 
5111 	/*
5112 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5113 	 * we'll cache that.  If we don't, we'll inherit global policy.
5114 	 *
5115 	 * We can't insert until the conn reflects the policy. Note that
5116 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5117 	 * connections where we don't have a policy. This is to prevent
5118 	 * global policy lookups in the inbound path.
5119 	 *
5120 	 * If we insert before we set conn_policy_cached,
5121 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5122 	 * because global policy cound be non-empty. We normally call
5123 	 * ipsec_check_policy() for conn_policy_cached connections only if
5124 	 * ipc_in_enforce_policy is set. But in this case,
5125 	 * conn_policy_cached can get set anytime since we made the
5126 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5127 	 * called, which will make the above assumption false.  Thus, we
5128 	 * need to insert after we set conn_policy_cached.
5129 	 */
5130 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5131 		goto bad_addr;
5132 
5133 	if (fanout_insert) {
5134 		/*
5135 		 * The addresses have been verified. Time to insert in
5136 		 * the correct fanout list.
5137 		 */
5138 		error = ipcl_conn_insert(connp, protocol, src_addr,
5139 		    dst_addr, connp->conn_ports);
5140 	}
5141 
5142 	if (error == 0) {
5143 		connp->conn_fully_bound = B_TRUE;
5144 		/*
5145 		 * Our initial checks for MDT have passed; the IRE is not
5146 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5147 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
5148 		 * ip_mdinfo_return(), which performs further checks
5149 		 * against them and upon success, returns the MDT info
5150 		 * mblk which we will attach to the bind acknowledgment.
5151 		 */
5152 		if (md_dst_ire != NULL) {
5153 			mblk_t *mdinfo_mp;
5154 
5155 			ASSERT(md_ill != NULL);
5156 			ASSERT(md_ill->ill_mdt_capab != NULL);
5157 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5158 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
5159 				linkb(mp, mdinfo_mp);
5160 		}
5161 	}
5162 bad_addr:
5163 	if (ipsec_policy_set) {
5164 		ASSERT(policy_mp == mp->b_cont);
5165 		ASSERT(policy_mp != NULL);
5166 		freeb(policy_mp);
5167 		/*
5168 		 * As of now assume that nothing else accompanies
5169 		 * IPSEC_POLICY_SET.
5170 		 */
5171 		mp->b_cont = NULL;
5172 	}
5173 	if (src_ire != NULL)
5174 		IRE_REFRELE(src_ire);
5175 	if (dst_ire != NULL)
5176 		IRE_REFRELE(dst_ire);
5177 	if (sire != NULL)
5178 		IRE_REFRELE(sire);
5179 	if (md_dst_ire != NULL)
5180 		IRE_REFRELE(md_dst_ire);
5181 	return (error);
5182 }
5183 
5184 /*
5185  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5186  * Prefers dst_ire over src_ire.
5187  */
5188 static boolean_t
5189 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5190 {
5191 	mblk_t	*mp1;
5192 	ire_t *ret_ire = NULL;
5193 
5194 	mp1 = mp->b_cont;
5195 	ASSERT(mp1 != NULL);
5196 
5197 	if (ire != NULL) {
5198 		/*
5199 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5200 		 * appended mblk. Its <upper protocol>'s
5201 		 * job to make sure there is room.
5202 		 */
5203 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5204 			return (0);
5205 
5206 		mp1->b_datap->db_type = IRE_DB_TYPE;
5207 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5208 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5209 		ret_ire = (ire_t *)mp1->b_rptr;
5210 		/*
5211 		 * Pass the latest setting of the ip_path_mtu_discovery and
5212 		 * copy the ulp info if any.
5213 		 */
5214 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5215 		    IPH_DF : 0;
5216 		if (ulp_info != NULL) {
5217 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5218 			    sizeof (iulp_t));
5219 		}
5220 		ret_ire->ire_mp = mp1;
5221 	} else {
5222 		/*
5223 		 * No IRE was found. Remove IRE mblk.
5224 		 */
5225 		mp->b_cont = mp1->b_cont;
5226 		freeb(mp1);
5227 	}
5228 
5229 	return (1);
5230 }
5231 
5232 /*
5233  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5234  * the final piece where we don't.  Return a pointer to the first mblk in the
5235  * result, and update the pointer to the next mblk to chew on.  If anything
5236  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5237  * NULL pointer.
5238  */
5239 mblk_t *
5240 ip_carve_mp(mblk_t **mpp, ssize_t len)
5241 {
5242 	mblk_t	*mp0;
5243 	mblk_t	*mp1;
5244 	mblk_t	*mp2;
5245 
5246 	if (!len || !mpp || !(mp0 = *mpp))
5247 		return (NULL);
5248 	/* If we aren't going to consume the first mblk, we need a dup. */
5249 	if (mp0->b_wptr - mp0->b_rptr > len) {
5250 		mp1 = dupb(mp0);
5251 		if (mp1) {
5252 			/* Partition the data between the two mblks. */
5253 			mp1->b_wptr = mp1->b_rptr + len;
5254 			mp0->b_rptr = mp1->b_wptr;
5255 			/*
5256 			 * after adjustments if mblk not consumed is now
5257 			 * unaligned, try to align it. If this fails free
5258 			 * all messages and let upper layer recover.
5259 			 */
5260 			if (!OK_32PTR(mp0->b_rptr)) {
5261 				if (!pullupmsg(mp0, -1)) {
5262 					freemsg(mp0);
5263 					freemsg(mp1);
5264 					*mpp = NULL;
5265 					return (NULL);
5266 				}
5267 			}
5268 		}
5269 		return (mp1);
5270 	}
5271 	/* Eat through as many mblks as we need to get len bytes. */
5272 	len -= mp0->b_wptr - mp0->b_rptr;
5273 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5274 		if (mp2->b_wptr - mp2->b_rptr > len) {
5275 			/*
5276 			 * We won't consume the entire last mblk.  Like
5277 			 * above, dup and partition it.
5278 			 */
5279 			mp1->b_cont = dupb(mp2);
5280 			mp1 = mp1->b_cont;
5281 			if (!mp1) {
5282 				/*
5283 				 * Trouble.  Rather than go to a lot of
5284 				 * trouble to clean up, we free the messages.
5285 				 * This won't be any worse than losing it on
5286 				 * the wire.
5287 				 */
5288 				freemsg(mp0);
5289 				freemsg(mp2);
5290 				*mpp = NULL;
5291 				return (NULL);
5292 			}
5293 			mp1->b_wptr = mp1->b_rptr + len;
5294 			mp2->b_rptr = mp1->b_wptr;
5295 			/*
5296 			 * after adjustments if mblk not consumed is now
5297 			 * unaligned, try to align it. If this fails free
5298 			 * all messages and let upper layer recover.
5299 			 */
5300 			if (!OK_32PTR(mp2->b_rptr)) {
5301 				if (!pullupmsg(mp2, -1)) {
5302 					freemsg(mp0);
5303 					freemsg(mp2);
5304 					*mpp = NULL;
5305 					return (NULL);
5306 				}
5307 			}
5308 			*mpp = mp2;
5309 			return (mp0);
5310 		}
5311 		/* Decrement len by the amount we just got. */
5312 		len -= mp2->b_wptr - mp2->b_rptr;
5313 	}
5314 	/*
5315 	 * len should be reduced to zero now.  If not our caller has
5316 	 * screwed up.
5317 	 */
5318 	if (len) {
5319 		/* Shouldn't happen! */
5320 		freemsg(mp0);
5321 		*mpp = NULL;
5322 		return (NULL);
5323 	}
5324 	/*
5325 	 * We consumed up to exactly the end of an mblk.  Detach the part
5326 	 * we are returning from the rest of the chain.
5327 	 */
5328 	mp1->b_cont = NULL;
5329 	*mpp = mp2;
5330 	return (mp0);
5331 }
5332 
5333 /* The ill stream is being unplumbed. Called from ip_close */
5334 int
5335 ip_modclose(ill_t *ill)
5336 {
5337 
5338 	boolean_t success;
5339 	ipsq_t	*ipsq;
5340 	ipif_t	*ipif;
5341 	queue_t	*q = ill->ill_rq;
5342 
5343 	/*
5344 	 * Forcibly enter the ipsq after some delay. This is to take
5345 	 * care of the case when some ioctl does not complete because
5346 	 * we sent a control message to the driver and it did not
5347 	 * send us a reply. We want to be able to at least unplumb
5348 	 * and replumb rather than force the user to reboot the system.
5349 	 */
5350 	success = ipsq_enter(ill, B_FALSE);
5351 
5352 	/*
5353 	 * Open/close/push/pop is guaranteed to be single threaded
5354 	 * per stream by STREAMS. FS guarantees that all references
5355 	 * from top are gone before close is called. So there can't
5356 	 * be another close thread that has set CONDEMNED on this ill.
5357 	 * and cause ipsq_enter to return failure.
5358 	 */
5359 	ASSERT(success);
5360 	ipsq = ill->ill_phyint->phyint_ipsq;
5361 
5362 	/*
5363 	 * Mark it condemned. No new reference will be made to this ill.
5364 	 * Lookup functions will return an error. Threads that try to
5365 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5366 	 * that the refcnt will drop down to zero.
5367 	 */
5368 	mutex_enter(&ill->ill_lock);
5369 	ill->ill_state_flags |= ILL_CONDEMNED;
5370 	for (ipif = ill->ill_ipif; ipif != NULL;
5371 	    ipif = ipif->ipif_next) {
5372 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5373 	}
5374 	/*
5375 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5376 	 * returns  error if ILL_CONDEMNED is set
5377 	 */
5378 	cv_broadcast(&ill->ill_cv);
5379 	mutex_exit(&ill->ill_lock);
5380 
5381 	/*
5382 	 * Shut down fragmentation reassembly.
5383 	 * ill_frag_timer won't start a timer again.
5384 	 * Now cancel any existing timer
5385 	 */
5386 	(void) untimeout(ill->ill_frag_timer_id);
5387 	(void) ill_frag_timeout(ill, 0);
5388 
5389 	/*
5390 	 * If MOVE was in progress, clear the
5391 	 * move_in_progress fields also.
5392 	 */
5393 	if (ill->ill_move_in_progress) {
5394 		ILL_CLEAR_MOVE(ill);
5395 	}
5396 
5397 	/*
5398 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5399 	 * this ill. Then wait for the refcnts to drop to zero.
5400 	 * ill_is_quiescent checks whether the ill is really quiescent.
5401 	 * Then make sure that threads that are waiting to enter the
5402 	 * ipsq have seen the error returned by ipsq_enter and have
5403 	 * gone away. Then we call ill_delete_tail which does the
5404 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5405 	 */
5406 	ill_delete(ill);
5407 	mutex_enter(&ill->ill_lock);
5408 	while (!ill_is_quiescent(ill))
5409 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5410 	while (ill->ill_waiters)
5411 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5412 
5413 	mutex_exit(&ill->ill_lock);
5414 
5415 	/* qprocsoff is called in ill_delete_tail */
5416 	ill_delete_tail(ill);
5417 
5418 	/*
5419 	 * Walk through all upper (conn) streams and qenable
5420 	 * those that have queued data.
5421 	 * close synchronization needs this to
5422 	 * be done to ensure that all upper layers blocked
5423 	 * due to flow control to the closing device
5424 	 * get unblocked.
5425 	 */
5426 	ip1dbg(("ip_wsrv: walking\n"));
5427 	conn_walk_drain();
5428 
5429 	mutex_enter(&ip_mi_lock);
5430 	mi_close_unlink(&ip_g_head, (IDP)ill);
5431 	mutex_exit(&ip_mi_lock);
5432 
5433 	/*
5434 	 * credp could be null if the open didn't succeed and ip_modopen
5435 	 * itself calls ip_close.
5436 	 */
5437 	if (ill->ill_credp != NULL)
5438 		crfree(ill->ill_credp);
5439 
5440 	mi_close_free((IDP)ill);
5441 	q->q_ptr = WR(q)->q_ptr = NULL;
5442 
5443 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5444 
5445 	return (0);
5446 }
5447 
5448 /*
5449  * This is called as part of close() for both IP and UDP
5450  * in order to quiesce the conn.
5451  */
5452 void
5453 ip_quiesce_conn(conn_t *connp)
5454 {
5455 	boolean_t	drain_cleanup_reqd = B_FALSE;
5456 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5457 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5458 
5459 	ASSERT(!IPCL_IS_TCP(connp));
5460 
5461 	/*
5462 	 * Mark the conn as closing, and this conn must not be
5463 	 * inserted in future into any list. Eg. conn_drain_insert(),
5464 	 * won't insert this conn into the conn_drain_list.
5465 	 * Similarly ill_pending_mp_add() will not add any mp to
5466 	 * the pending mp list, after this conn has started closing.
5467 	 *
5468 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5469 	 * cannot get set henceforth.
5470 	 */
5471 	mutex_enter(&connp->conn_lock);
5472 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5473 	connp->conn_state_flags |= CONN_CLOSING;
5474 	if (connp->conn_idl != NULL)
5475 		drain_cleanup_reqd = B_TRUE;
5476 	if (connp->conn_oper_pending_ill != NULL)
5477 		conn_ioctl_cleanup_reqd = B_TRUE;
5478 	if (connp->conn_ilg_inuse != 0)
5479 		ilg_cleanup_reqd = B_TRUE;
5480 	mutex_exit(&connp->conn_lock);
5481 
5482 	if (IPCL_IS_UDP(connp))
5483 		udp_quiesce_conn(connp);
5484 
5485 	if (conn_ioctl_cleanup_reqd)
5486 		conn_ioctl_cleanup(connp);
5487 
5488 	if (is_system_labeled() && connp->conn_anon_port) {
5489 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5490 		    connp->conn_mlp_type, connp->conn_ulp,
5491 		    ntohs(connp->conn_lport), B_FALSE);
5492 		connp->conn_anon_port = 0;
5493 	}
5494 	connp->conn_mlp_type = mlptSingle;
5495 
5496 	/*
5497 	 * Remove this conn from any fanout list it is on.
5498 	 * and then wait for any threads currently operating
5499 	 * on this endpoint to finish
5500 	 */
5501 	ipcl_hash_remove(connp);
5502 
5503 	/*
5504 	 * Remove this conn from the drain list, and do
5505 	 * any other cleanup that may be required.
5506 	 * (Only non-tcp streams may have a non-null conn_idl.
5507 	 * TCP streams are never flow controlled, and
5508 	 * conn_idl will be null)
5509 	 */
5510 	if (drain_cleanup_reqd)
5511 		conn_drain_tail(connp, B_TRUE);
5512 
5513 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5514 		(void) ip_mrouter_done(NULL);
5515 
5516 	if (ilg_cleanup_reqd)
5517 		ilg_delete_all(connp);
5518 
5519 	conn_delete_ire(connp, NULL);
5520 
5521 	/*
5522 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5523 	 * callers from write side can't be there now because close
5524 	 * is in progress. The only other caller is ipcl_walk
5525 	 * which checks for the condemned flag.
5526 	 */
5527 	mutex_enter(&connp->conn_lock);
5528 	connp->conn_state_flags |= CONN_CONDEMNED;
5529 	while (connp->conn_ref != 1)
5530 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5531 	connp->conn_state_flags |= CONN_QUIESCED;
5532 	mutex_exit(&connp->conn_lock);
5533 }
5534 
5535 /* ARGSUSED */
5536 int
5537 ip_close(queue_t *q, int flags)
5538 {
5539 	conn_t		*connp;
5540 
5541 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5542 
5543 	/*
5544 	 * Call the appropriate delete routine depending on whether this is
5545 	 * a module or device.
5546 	 */
5547 	if (WR(q)->q_next != NULL) {
5548 		/* This is a module close */
5549 		return (ip_modclose((ill_t *)q->q_ptr));
5550 	}
5551 
5552 	connp = q->q_ptr;
5553 	ip_quiesce_conn(connp);
5554 
5555 	qprocsoff(q);
5556 
5557 	/*
5558 	 * Now we are truly single threaded on this stream, and can
5559 	 * delete the things hanging off the connp, and finally the connp.
5560 	 * We removed this connp from the fanout list, it cannot be
5561 	 * accessed thru the fanouts, and we already waited for the
5562 	 * conn_ref to drop to 0. We are already in close, so
5563 	 * there cannot be any other thread from the top. qprocsoff
5564 	 * has completed, and service has completed or won't run in
5565 	 * future.
5566 	 */
5567 	ASSERT(connp->conn_ref == 1);
5568 
5569 	/*
5570 	 * A conn which was previously marked as IPCL_UDP cannot
5571 	 * retain the flag because it would have been cleared by
5572 	 * udp_close().
5573 	 */
5574 	ASSERT(!IPCL_IS_UDP(connp));
5575 
5576 	if (connp->conn_latch != NULL) {
5577 		IPLATCH_REFRELE(connp->conn_latch);
5578 		connp->conn_latch = NULL;
5579 	}
5580 	if (connp->conn_policy != NULL) {
5581 		IPPH_REFRELE(connp->conn_policy);
5582 		connp->conn_policy = NULL;
5583 	}
5584 	if (connp->conn_ipsec_opt_mp != NULL) {
5585 		freemsg(connp->conn_ipsec_opt_mp);
5586 		connp->conn_ipsec_opt_mp = NULL;
5587 	}
5588 
5589 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5590 
5591 	connp->conn_ref--;
5592 	ipcl_conn_destroy(connp);
5593 
5594 	q->q_ptr = WR(q)->q_ptr = NULL;
5595 	return (0);
5596 }
5597 
5598 int
5599 ip_snmpmod_close(queue_t *q)
5600 {
5601 	conn_t *connp = Q_TO_CONN(q);
5602 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5603 
5604 	qprocsoff(q);
5605 
5606 	if (connp->conn_flags & IPCL_UDPMOD)
5607 		udp_close_free(connp);
5608 
5609 	if (connp->conn_cred != NULL) {
5610 		crfree(connp->conn_cred);
5611 		connp->conn_cred = NULL;
5612 	}
5613 	CONN_DEC_REF(connp);
5614 	q->q_ptr = WR(q)->q_ptr = NULL;
5615 	return (0);
5616 }
5617 
5618 /*
5619  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5620  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5621  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5622  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5623  * queues as we never enqueue messages there and we don't handle any ioctls.
5624  * Everything else is freed.
5625  */
5626 void
5627 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5628 {
5629 	conn_t	*connp = q->q_ptr;
5630 	pfi_t	setfn;
5631 	pfi_t	getfn;
5632 
5633 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5634 
5635 	switch (DB_TYPE(mp)) {
5636 	case M_PROTO:
5637 	case M_PCPROTO:
5638 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5639 		    ((((union T_primitives *)mp->b_rptr)->type ==
5640 			T_SVR4_OPTMGMT_REQ) ||
5641 		    (((union T_primitives *)mp->b_rptr)->type ==
5642 			T_OPTMGMT_REQ))) {
5643 			/*
5644 			 * This is the only TPI primitive supported. Its
5645 			 * handling does not require tcp_t, but it does require
5646 			 * conn_t to check permissions.
5647 			 */
5648 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5649 
5650 			if (connp->conn_flags & IPCL_TCPMOD) {
5651 				setfn = tcp_snmp_set;
5652 				getfn = tcp_snmp_get;
5653 			} else {
5654 				setfn = udp_snmp_set;
5655 				getfn = udp_snmp_get;
5656 			}
5657 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5658 				freemsg(mp);
5659 				return;
5660 			}
5661 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5662 		    != NULL)
5663 			qreply(q, mp);
5664 		break;
5665 	case M_FLUSH:
5666 	case M_IOCTL:
5667 		putnext(q, mp);
5668 		break;
5669 	default:
5670 		freemsg(mp);
5671 		break;
5672 	}
5673 }
5674 
5675 /* Return the IP checksum for the IP header at "iph". */
5676 uint16_t
5677 ip_csum_hdr(ipha_t *ipha)
5678 {
5679 	uint16_t	*uph;
5680 	uint32_t	sum;
5681 	int		opt_len;
5682 
5683 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5684 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5685 	uph = (uint16_t *)ipha;
5686 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5687 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5688 	if (opt_len > 0) {
5689 		do {
5690 			sum += uph[10];
5691 			sum += uph[11];
5692 			uph += 2;
5693 		} while (--opt_len);
5694 	}
5695 	sum = (sum & 0xFFFF) + (sum >> 16);
5696 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5697 	if (sum == 0xffff)
5698 		sum = 0;
5699 	return ((uint16_t)sum);
5700 }
5701 
5702 void
5703 ip_ddi_destroy(void)
5704 {
5705 	tnet_fini();
5706 	tcp_ddi_destroy();
5707 	sctp_ddi_destroy();
5708 	ipsec_loader_destroy();
5709 	ipsec_policy_destroy();
5710 	ipsec_kstat_destroy();
5711 	nd_free(&ip_g_nd);
5712 	mutex_destroy(&igmp_timer_lock);
5713 	mutex_destroy(&mld_timer_lock);
5714 	mutex_destroy(&igmp_slowtimeout_lock);
5715 	mutex_destroy(&mld_slowtimeout_lock);
5716 	mutex_destroy(&ip_mi_lock);
5717 	mutex_destroy(&rts_clients.connf_lock);
5718 	ip_ire_fini();
5719 	ip6_asp_free();
5720 	conn_drain_fini();
5721 	ipcl_destroy();
5722 	inet_minor_destroy(ip_minor_arena);
5723 	icmp_kstat_fini();
5724 	ip_kstat_fini();
5725 	rw_destroy(&ipsec_capab_ills_lock);
5726 	rw_destroy(&ill_g_usesrc_lock);
5727 	ip_drop_unregister(&ip_dropper);
5728 }
5729 
5730 
5731 void
5732 ip_ddi_init(void)
5733 {
5734 	TCP6_MAJ = ddi_name_to_major(TCP6);
5735 	TCP_MAJ	= ddi_name_to_major(TCP);
5736 	SCTP_MAJ = ddi_name_to_major(SCTP);
5737 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5738 
5739 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5740 
5741 	/* IP's IPsec code calls the packet dropper */
5742 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5743 
5744 	if (!ip_g_nd) {
5745 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5746 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5747 			nd_free(&ip_g_nd);
5748 		}
5749 	}
5750 
5751 	ipsec_loader_init();
5752 	ipsec_policy_init();
5753 	ipsec_kstat_init();
5754 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5755 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5756 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5757 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5758 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5759 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5760 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5761 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5762 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5763 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5764 
5765 	/*
5766 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5767 	 * initial devices: ip, ip6, tcp, tcp6.
5768 	 */
5769 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5770 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5771 		cmn_err(CE_PANIC,
5772 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5773 	}
5774 
5775 	ipcl_init();
5776 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5777 	ip_ire_init();
5778 	ip6_asp_init();
5779 	ipif_init();
5780 	conn_drain_init();
5781 	tcp_ddi_init();
5782 	sctp_ddi_init();
5783 
5784 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5785 
5786 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5787 		"net", KSTAT_TYPE_NAMED,
5788 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5789 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5790 		ip_kstat->ks_data = &ip_statistics;
5791 		kstat_install(ip_kstat);
5792 	}
5793 	ip_kstat_init();
5794 	ip6_kstat_init();
5795 	icmp_kstat_init();
5796 	ipsec_loader_start();
5797 	tnet_init();
5798 }
5799 
5800 /*
5801  * Allocate and initialize a DLPI template of the specified length.  (May be
5802  * called as writer.)
5803  */
5804 mblk_t *
5805 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5806 {
5807 	mblk_t	*mp;
5808 
5809 	mp = allocb(len, BPRI_MED);
5810 	if (!mp)
5811 		return (NULL);
5812 
5813 	/*
5814 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5815 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5816 	 * that other DLPI are M_PROTO.
5817 	 */
5818 	if (prim == DL_INFO_REQ) {
5819 		mp->b_datap->db_type = M_PCPROTO;
5820 	} else {
5821 		mp->b_datap->db_type = M_PROTO;
5822 	}
5823 
5824 	mp->b_wptr = mp->b_rptr + len;
5825 	bzero(mp->b_rptr, len);
5826 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5827 	return (mp);
5828 }
5829 
5830 const char *
5831 dlpi_prim_str(int prim)
5832 {
5833 	switch (prim) {
5834 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5835 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5836 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5837 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5838 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5839 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5840 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5841 	case DL_OK_ACK:		return ("DL_OK_ACK");
5842 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5843 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5844 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5845 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5846 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5847 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5848 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5849 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5850 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5851 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5852 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5853 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5854 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5855 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5856 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5857 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5858 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5859 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5860 	default:		return ("<unknown primitive>");
5861 	}
5862 }
5863 
5864 const char *
5865 dlpi_err_str(int err)
5866 {
5867 	switch (err) {
5868 	case DL_ACCESS:		return ("DL_ACCESS");
5869 	case DL_BADADDR:	return ("DL_BADADDR");
5870 	case DL_BADCORR:	return ("DL_BADCORR");
5871 	case DL_BADDATA:	return ("DL_BADDATA");
5872 	case DL_BADPPA:		return ("DL_BADPPA");
5873 	case DL_BADPRIM:	return ("DL_BADPRIM");
5874 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5875 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5876 	case DL_BADSAP:		return ("DL_BADSAP");
5877 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5878 	case DL_BOUND:		return ("DL_BOUND");
5879 	case DL_INITFAILED:	return ("DL_INITFAILED");
5880 	case DL_NOADDR:		return ("DL_NOADDR");
5881 	case DL_NOTINIT:	return ("DL_NOTINIT");
5882 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5883 	case DL_SYSERR:		return ("DL_SYSERR");
5884 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5885 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5886 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5887 	case DL_TOOMANY:	return ("DL_TOOMANY");
5888 	case DL_NOTENAB:	return ("DL_NOTENAB");
5889 	case DL_BUSY:		return ("DL_BUSY");
5890 	case DL_NOAUTO:		return ("DL_NOAUTO");
5891 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5892 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5893 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5894 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5895 	case DL_PENDING:	return ("DL_PENDING");
5896 	default:		return ("<unknown error>");
5897 	}
5898 }
5899 
5900 /*
5901  * Debug formatting routine.  Returns a character string representation of the
5902  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5903  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5904  *
5905  * Once the ndd table-printing interfaces are removed, this can be changed to
5906  * standard dotted-decimal form.
5907  */
5908 char *
5909 ip_dot_addr(ipaddr_t addr, char *buf)
5910 {
5911 	uint8_t *ap = (uint8_t *)&addr;
5912 
5913 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5914 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
5915 	return (buf);
5916 }
5917 
5918 /*
5919  * Write the given MAC address as a printable string in the usual colon-
5920  * separated format.
5921  */
5922 const char *
5923 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
5924 {
5925 	char *bp;
5926 
5927 	if (alen == 0 || buflen < 4)
5928 		return ("?");
5929 	bp = buf;
5930 	for (;;) {
5931 		/*
5932 		 * If there are more MAC address bytes available, but we won't
5933 		 * have any room to print them, then add "..." to the string
5934 		 * instead.  See below for the 'magic number' explanation.
5935 		 */
5936 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
5937 			(void) strcpy(bp, "...");
5938 			break;
5939 		}
5940 		(void) sprintf(bp, "%02x", *addr++);
5941 		bp += 2;
5942 		if (--alen == 0)
5943 			break;
5944 		*bp++ = ':';
5945 		buflen -= 3;
5946 		/*
5947 		 * At this point, based on the first 'if' statement above,
5948 		 * either alen == 1 and buflen >= 3, or alen > 1 and
5949 		 * buflen >= 4.  The first case leaves room for the final "xx"
5950 		 * number and trailing NUL byte.  The second leaves room for at
5951 		 * least "...".  Thus the apparently 'magic' numbers chosen for
5952 		 * that statement.
5953 		 */
5954 	}
5955 	return (buf);
5956 }
5957 
5958 /*
5959  * Send an ICMP error after patching up the packet appropriately.  Returns
5960  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5961  */
5962 static boolean_t
5963 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5964     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5965 {
5966 	ipha_t *ipha;
5967 	mblk_t *first_mp;
5968 	boolean_t secure;
5969 	unsigned char db_type;
5970 
5971 	first_mp = mp;
5972 	if (mctl_present) {
5973 		mp = mp->b_cont;
5974 		secure = ipsec_in_is_secure(first_mp);
5975 		ASSERT(mp != NULL);
5976 	} else {
5977 		/*
5978 		 * If this is an ICMP error being reported - which goes
5979 		 * up as M_CTLs, we need to convert them to M_DATA till
5980 		 * we finish checking with global policy because
5981 		 * ipsec_check_global_policy() assumes M_DATA as clear
5982 		 * and M_CTL as secure.
5983 		 */
5984 		db_type = DB_TYPE(mp);
5985 		DB_TYPE(mp) = M_DATA;
5986 		secure = B_FALSE;
5987 	}
5988 	/*
5989 	 * We are generating an icmp error for some inbound packet.
5990 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
5991 	 * Before we generate an error, check with global policy
5992 	 * to see whether this is allowed to enter the system. As
5993 	 * there is no "conn", we are checking with global policy.
5994 	 */
5995 	ipha = (ipha_t *)mp->b_rptr;
5996 	if (secure || ipsec_inbound_v4_policy_present) {
5997 		first_mp = ipsec_check_global_policy(first_mp, NULL,
5998 		    ipha, NULL, mctl_present);
5999 		if (first_mp == NULL)
6000 			return (B_FALSE);
6001 	}
6002 
6003 	if (!mctl_present)
6004 		DB_TYPE(mp) = db_type;
6005 
6006 	if (flags & IP_FF_SEND_ICMP) {
6007 		if (flags & IP_FF_HDR_COMPLETE) {
6008 			if (ip_hdr_complete(ipha, zoneid)) {
6009 				freemsg(first_mp);
6010 				return (B_TRUE);
6011 			}
6012 		}
6013 		if (flags & IP_FF_CKSUM) {
6014 			/*
6015 			 * Have to correct checksum since
6016 			 * the packet might have been
6017 			 * fragmented and the reassembly code in ip_rput
6018 			 * does not restore the IP checksum.
6019 			 */
6020 			ipha->ipha_hdr_checksum = 0;
6021 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6022 		}
6023 		switch (icmp_type) {
6024 		case ICMP_DEST_UNREACHABLE:
6025 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid);
6026 			break;
6027 		default:
6028 			freemsg(first_mp);
6029 			break;
6030 		}
6031 	} else {
6032 		freemsg(first_mp);
6033 		return (B_FALSE);
6034 	}
6035 
6036 	return (B_TRUE);
6037 }
6038 
6039 /*
6040  * Used to send an ICMP error message when a packet is received for
6041  * a protocol that is not supported. The mblk passed as argument
6042  * is consumed by this function.
6043  */
6044 void
6045 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
6046 {
6047 	mblk_t *mp;
6048 	ipha_t *ipha;
6049 	ill_t *ill;
6050 	ipsec_in_t *ii;
6051 
6052 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6053 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6054 
6055 	mp = ipsec_mp->b_cont;
6056 	ipsec_mp->b_cont = NULL;
6057 	ipha = (ipha_t *)mp->b_rptr;
6058 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6059 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
6060 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6061 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
6062 		}
6063 	} else {
6064 		/* Get ill from index in ipsec_in_t. */
6065 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6066 		    B_TRUE, NULL, NULL, NULL, NULL);
6067 		if (ill != NULL) {
6068 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6069 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6070 			    0, B_FALSE, zoneid)) {
6071 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
6072 			}
6073 
6074 			ill_refrele(ill);
6075 		} else { /* re-link for the freemsg() below. */
6076 			ipsec_mp->b_cont = mp;
6077 		}
6078 	}
6079 
6080 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6081 	freemsg(ipsec_mp);
6082 }
6083 
6084 /*
6085  * See if the inbound datagram has had IPsec processing applied to it.
6086  */
6087 boolean_t
6088 ipsec_in_is_secure(mblk_t *ipsec_mp)
6089 {
6090 	ipsec_in_t *ii;
6091 
6092 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6093 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6094 
6095 	if (ii->ipsec_in_loopback) {
6096 		return (ii->ipsec_in_secure);
6097 	} else {
6098 		return (ii->ipsec_in_ah_sa != NULL ||
6099 		    ii->ipsec_in_esp_sa != NULL ||
6100 		    ii->ipsec_in_decaps);
6101 	}
6102 }
6103 
6104 /*
6105  * Handle protocols with which IP is less intimate.  There
6106  * can be more than one stream bound to a particular
6107  * protocol.  When this is the case, normally each one gets a copy
6108  * of any incoming packets.
6109  *
6110  * IPSEC NOTE :
6111  *
6112  * Don't allow a secure packet going up a non-secure connection.
6113  * We don't allow this because
6114  *
6115  * 1) Reply might go out in clear which will be dropped at
6116  *    the sending side.
6117  * 2) If the reply goes out in clear it will give the
6118  *    adversary enough information for getting the key in
6119  *    most of the cases.
6120  *
6121  * Moreover getting a secure packet when we expect clear
6122  * implies that SA's were added without checking for
6123  * policy on both ends. This should not happen once ISAKMP
6124  * is used to negotiate SAs as SAs will be added only after
6125  * verifying the policy.
6126  *
6127  * NOTE : If the packet was tunneled and not multicast we only send
6128  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6129  * back to delivering packets to AF_INET6 raw sockets.
6130  *
6131  * IPQoS Notes:
6132  * Once we have determined the client, invoke IPPF processing.
6133  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6134  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6135  * ip_policy will be false.
6136  *
6137  * Zones notes:
6138  * Currently only applications in the global zone can create raw sockets for
6139  * protocols other than ICMP. So unlike the broadcast / multicast case of
6140  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6141  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6142  */
6143 static void
6144 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6145     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6146     zoneid_t zoneid)
6147 {
6148 	queue_t	*rq;
6149 	mblk_t	*mp1, *first_mp1;
6150 	uint_t	protocol = ipha->ipha_protocol;
6151 	ipaddr_t dst;
6152 	boolean_t one_only;
6153 	mblk_t *first_mp = mp;
6154 	boolean_t secure;
6155 	uint32_t ill_index;
6156 	conn_t	*connp, *first_connp, *next_connp;
6157 	connf_t	*connfp;
6158 	boolean_t shared_addr;
6159 
6160 	if (mctl_present) {
6161 		mp = first_mp->b_cont;
6162 		secure = ipsec_in_is_secure(first_mp);
6163 		ASSERT(mp != NULL);
6164 	} else {
6165 		secure = B_FALSE;
6166 	}
6167 	dst = ipha->ipha_dst;
6168 	/*
6169 	 * If the packet was tunneled and not multicast we only send to it
6170 	 * the first match.
6171 	 */
6172 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6173 	    !CLASSD(dst));
6174 
6175 	shared_addr = (zoneid == ALL_ZONES);
6176 	if (shared_addr) {
6177 		/*
6178 		 * We don't allow multilevel ports for raw IP, so no need to
6179 		 * check for that here.
6180 		 */
6181 		zoneid = tsol_packet_to_zoneid(mp);
6182 	}
6183 
6184 	connfp = &ipcl_proto_fanout[protocol];
6185 	mutex_enter(&connfp->connf_lock);
6186 	connp = connfp->connf_head;
6187 	for (connp = connfp->connf_head; connp != NULL;
6188 		connp = connp->conn_next) {
6189 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6190 		    zoneid) &&
6191 		    (!is_system_labeled() ||
6192 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6193 		    connp)))
6194 			break;
6195 	}
6196 
6197 	if (connp == NULL || connp->conn_upq == NULL) {
6198 		/*
6199 		 * No one bound to these addresses.  Is
6200 		 * there a client that wants all
6201 		 * unclaimed datagrams?
6202 		 */
6203 		mutex_exit(&connfp->connf_lock);
6204 		/*
6205 		 * Check for IPPROTO_ENCAP...
6206 		 */
6207 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6208 			/*
6209 			 * XXX If an IPsec mblk is here on a multicast
6210 			 * tunnel (using ip_mroute stuff), what should
6211 			 * I do?
6212 			 *
6213 			 * For now, just free the IPsec mblk before
6214 			 * passing it up to the multicast routing
6215 			 * stuff.
6216 			 *
6217 			 * BTW,  If I match a configured IP-in-IP
6218 			 * tunnel, ip_mroute_decap will never be
6219 			 * called.
6220 			 */
6221 			if (mp != first_mp)
6222 				freeb(first_mp);
6223 			ip_mroute_decap(q, mp);
6224 		} else {
6225 			/*
6226 			 * Otherwise send an ICMP protocol unreachable.
6227 			 */
6228 			if (ip_fanout_send_icmp(q, first_mp, flags,
6229 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6230 			    mctl_present, zoneid)) {
6231 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
6232 			}
6233 		}
6234 		return;
6235 	}
6236 	CONN_INC_REF(connp);
6237 	first_connp = connp;
6238 
6239 	/*
6240 	 * Only send message to one tunnel driver by immediately
6241 	 * terminating the loop.
6242 	 */
6243 	connp = one_only ? NULL : connp->conn_next;
6244 
6245 	for (;;) {
6246 		while (connp != NULL) {
6247 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6248 			    flags, zoneid) &&
6249 			    (!is_system_labeled() ||
6250 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6251 			    shared_addr, connp)))
6252 				break;
6253 			connp = connp->conn_next;
6254 		}
6255 
6256 		/*
6257 		 * Copy the packet.
6258 		 */
6259 		if (connp == NULL || connp->conn_upq == NULL ||
6260 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6261 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6262 			/*
6263 			 * No more interested clients or memory
6264 			 * allocation failed
6265 			 */
6266 			connp = first_connp;
6267 			break;
6268 		}
6269 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6270 		CONN_INC_REF(connp);
6271 		mutex_exit(&connfp->connf_lock);
6272 		rq = connp->conn_rq;
6273 		if (!canputnext(rq)) {
6274 			if (flags & IP_FF_RAWIP) {
6275 				BUMP_MIB(&ip_mib, rawipInOverflows);
6276 			} else {
6277 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6278 			}
6279 
6280 			freemsg(first_mp1);
6281 		} else {
6282 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6283 				first_mp1 = ipsec_check_inbound_policy
6284 				    (first_mp1, connp, ipha, NULL,
6285 				    mctl_present);
6286 			}
6287 			if (first_mp1 != NULL) {
6288 				/*
6289 				 * ip_fanout_proto also gets called from
6290 				 * icmp_inbound_error_fanout, in which case
6291 				 * the msg type is M_CTL.  Don't add info
6292 				 * in this case for the time being. In future
6293 				 * when there is a need for knowing the
6294 				 * inbound iface index for ICMP error msgs,
6295 				 * then this can be changed.
6296 				 */
6297 				if ((connp->conn_recvif != 0) &&
6298 				    (mp->b_datap->db_type != M_CTL)) {
6299 					/*
6300 					 * the actual data will be
6301 					 * contained in b_cont upon
6302 					 * successful return of the
6303 					 * following call else
6304 					 * original mblk is returned
6305 					 */
6306 					ASSERT(recv_ill != NULL);
6307 					mp1 = ip_add_info(mp1, recv_ill,
6308 						IPF_RECVIF);
6309 				}
6310 				BUMP_MIB(&ip_mib, ipInDelivers);
6311 				if (mctl_present)
6312 					freeb(first_mp1);
6313 				putnext(rq, mp1);
6314 			}
6315 		}
6316 		mutex_enter(&connfp->connf_lock);
6317 		/* Follow the next pointer before releasing the conn. */
6318 		next_connp = connp->conn_next;
6319 		CONN_DEC_REF(connp);
6320 		connp = next_connp;
6321 	}
6322 
6323 	/* Last one.  Send it upstream. */
6324 	mutex_exit(&connfp->connf_lock);
6325 
6326 	/*
6327 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6328 	 * will be set to false.
6329 	 */
6330 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6331 		ill_index = ill->ill_phyint->phyint_ifindex;
6332 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6333 		if (mp == NULL) {
6334 			CONN_DEC_REF(connp);
6335 			if (mctl_present) {
6336 				freeb(first_mp);
6337 			}
6338 			return;
6339 		}
6340 	}
6341 
6342 	rq = connp->conn_rq;
6343 	if (!canputnext(rq)) {
6344 		if (flags & IP_FF_RAWIP) {
6345 			BUMP_MIB(&ip_mib, rawipInOverflows);
6346 		} else {
6347 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6348 		}
6349 
6350 		freemsg(first_mp);
6351 	} else {
6352 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6353 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6354 			    ipha, NULL, mctl_present);
6355 		}
6356 		if (first_mp != NULL) {
6357 			/*
6358 			 * ip_fanout_proto also gets called
6359 			 * from icmp_inbound_error_fanout, in
6360 			 * which case the msg type is M_CTL.
6361 			 * Don't add info in this case for time
6362 			 * being. In future when there is a
6363 			 * need for knowing the inbound iface
6364 			 * index for ICMP error msgs, then this
6365 			 * can be changed
6366 			 */
6367 			if ((connp->conn_recvif != 0) &&
6368 			    (mp->b_datap->db_type != M_CTL)) {
6369 				/*
6370 				 * the actual data will be contained in
6371 				 * b_cont upon successful return
6372 				 * of the following call else original
6373 				 * mblk is returned
6374 				 */
6375 				ASSERT(recv_ill != NULL);
6376 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6377 			}
6378 			BUMP_MIB(&ip_mib, ipInDelivers);
6379 			putnext(rq, mp);
6380 			if (mctl_present)
6381 				freeb(first_mp);
6382 		}
6383 	}
6384 	CONN_DEC_REF(connp);
6385 }
6386 
6387 /*
6388  * Fanout for TCP packets
6389  * The caller puts <fport, lport> in the ports parameter.
6390  *
6391  * IPQoS Notes
6392  * Before sending it to the client, invoke IPPF processing.
6393  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6394  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6395  * ip_policy is false.
6396  */
6397 static void
6398 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6399     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6400 {
6401 	mblk_t  *first_mp;
6402 	boolean_t secure;
6403 	uint32_t ill_index;
6404 	int	ip_hdr_len;
6405 	tcph_t	*tcph;
6406 	boolean_t syn_present = B_FALSE;
6407 	conn_t	*connp;
6408 
6409 	first_mp = mp;
6410 	if (mctl_present) {
6411 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6412 		mp = first_mp->b_cont;
6413 		secure = ipsec_in_is_secure(first_mp);
6414 		ASSERT(mp != NULL);
6415 	} else {
6416 		secure = B_FALSE;
6417 	}
6418 
6419 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6420 
6421 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6422 	    NULL) {
6423 		/*
6424 		 * No connected connection or listener. Send a
6425 		 * TH_RST via tcp_xmit_listeners_reset.
6426 		 */
6427 
6428 		/* Initiate IPPf processing, if needed. */
6429 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6430 			uint32_t ill_index;
6431 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6432 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6433 			if (first_mp == NULL)
6434 				return;
6435 		}
6436 		BUMP_MIB(&ip_mib, ipInDelivers);
6437 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6438 		    zoneid));
6439 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6440 		return;
6441 	}
6442 
6443 	/*
6444 	 * Allocate the SYN for the TCP connection here itself
6445 	 */
6446 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6447 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6448 		if (IPCL_IS_TCP(connp)) {
6449 			squeue_t *sqp;
6450 
6451 			/*
6452 			 * For fused tcp loopback, assign the eager's
6453 			 * squeue to be that of the active connect's.
6454 			 * Note that we don't check for IP_FF_LOOPBACK
6455 			 * here since this routine gets called only
6456 			 * for loopback (unlike the IPv6 counterpart).
6457 			 */
6458 			ASSERT(Q_TO_CONN(q) != NULL);
6459 			if (do_tcp_fusion &&
6460 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6461 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6462 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6463 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6464 				sqp = Q_TO_CONN(q)->conn_sqp;
6465 			} else {
6466 				sqp = IP_SQUEUE_GET(lbolt);
6467 			}
6468 
6469 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6470 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6471 			syn_present = B_TRUE;
6472 		}
6473 	}
6474 
6475 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6476 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6477 		if ((flags & TH_RST) || (flags & TH_URG)) {
6478 			CONN_DEC_REF(connp);
6479 			freemsg(first_mp);
6480 			return;
6481 		}
6482 		if (flags & TH_ACK) {
6483 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6484 			CONN_DEC_REF(connp);
6485 			return;
6486 		}
6487 
6488 		CONN_DEC_REF(connp);
6489 		freemsg(first_mp);
6490 		return;
6491 	}
6492 
6493 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6494 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6495 		    NULL, mctl_present);
6496 		if (first_mp == NULL) {
6497 			CONN_DEC_REF(connp);
6498 			return;
6499 		}
6500 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6501 			ASSERT(syn_present);
6502 			if (mctl_present) {
6503 				ASSERT(first_mp != mp);
6504 				first_mp->b_datap->db_struioflag |=
6505 				    STRUIO_POLICY;
6506 			} else {
6507 				ASSERT(first_mp == mp);
6508 				mp->b_datap->db_struioflag &=
6509 				    ~STRUIO_EAGER;
6510 				mp->b_datap->db_struioflag |=
6511 				    STRUIO_POLICY;
6512 			}
6513 		} else {
6514 			/*
6515 			 * Discard first_mp early since we're dealing with a
6516 			 * fully-connected conn_t and tcp doesn't do policy in
6517 			 * this case.
6518 			 */
6519 			if (mctl_present) {
6520 				freeb(first_mp);
6521 				mctl_present = B_FALSE;
6522 			}
6523 			first_mp = mp;
6524 		}
6525 	}
6526 
6527 	/*
6528 	 * Initiate policy processing here if needed. If we get here from
6529 	 * icmp_inbound_error_fanout, ip_policy is false.
6530 	 */
6531 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6532 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6533 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6534 		if (mp == NULL) {
6535 			CONN_DEC_REF(connp);
6536 			if (mctl_present)
6537 				freeb(first_mp);
6538 			return;
6539 		} else if (mctl_present) {
6540 			ASSERT(first_mp != mp);
6541 			first_mp->b_cont = mp;
6542 		} else {
6543 			first_mp = mp;
6544 		}
6545 	}
6546 
6547 
6548 
6549 	/* Handle IPv6 socket options. */
6550 	if (!syn_present &&
6551 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6552 		/* Add header */
6553 		ASSERT(recv_ill != NULL);
6554 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6555 		if (mp == NULL) {
6556 			CONN_DEC_REF(connp);
6557 			if (mctl_present)
6558 				freeb(first_mp);
6559 			return;
6560 		} else if (mctl_present) {
6561 			/*
6562 			 * ip_add_info might return a new mp.
6563 			 */
6564 			ASSERT(first_mp != mp);
6565 			first_mp->b_cont = mp;
6566 		} else {
6567 			first_mp = mp;
6568 		}
6569 	}
6570 
6571 	BUMP_MIB(&ip_mib, ipInDelivers);
6572 	if (IPCL_IS_TCP(connp)) {
6573 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6574 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6575 	} else {
6576 		putnext(connp->conn_rq, first_mp);
6577 		CONN_DEC_REF(connp);
6578 	}
6579 }
6580 
6581 /*
6582  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6583  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6584  * Caller is responsible for dropping references to the conn, and freeing
6585  * first_mp.
6586  *
6587  * IPQoS Notes
6588  * Before sending it to the client, invoke IPPF processing. Policy processing
6589  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6590  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6591  * ip_wput_local, ip_policy is false.
6592  */
6593 static void
6594 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6595     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6596     boolean_t ip_policy)
6597 {
6598 	boolean_t	mctl_present = (first_mp != NULL);
6599 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6600 	uint32_t	ill_index;
6601 
6602 	if (mctl_present)
6603 		first_mp->b_cont = mp;
6604 	else
6605 		first_mp = mp;
6606 
6607 	if (CONN_UDP_FLOWCTLD(connp)) {
6608 		BUMP_MIB(&ip_mib, udpInOverflows);
6609 		freemsg(first_mp);
6610 		return;
6611 	}
6612 
6613 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6614 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6615 		    NULL, mctl_present);
6616 		if (first_mp == NULL)
6617 			return;	/* Freed by ipsec_check_inbound_policy(). */
6618 	}
6619 	if (mctl_present)
6620 		freeb(first_mp);
6621 
6622 	if (connp->conn_recvif)
6623 		in_flags = IPF_RECVIF;
6624 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6625 		in_flags |= IPF_RECVSLLA;
6626 
6627 	/* Handle IPv6 options. */
6628 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6629 		in_flags |= IPF_RECVIF;
6630 
6631 	/*
6632 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6633 	 * freed if the packet is dropped. The caller will do so.
6634 	 */
6635 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6636 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6637 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6638 		if (mp == NULL) {
6639 			return;
6640 		}
6641 	}
6642 	if ((in_flags != 0) &&
6643 	    (mp->b_datap->db_type != M_CTL)) {
6644 		/*
6645 		 * The actual data will be contained in b_cont
6646 		 * upon successful return of the following call
6647 		 * else original mblk is returned
6648 		 */
6649 		ASSERT(recv_ill != NULL);
6650 		mp = ip_add_info(mp, recv_ill, in_flags);
6651 	}
6652 	BUMP_MIB(&ip_mib, ipInDelivers);
6653 
6654 	/* Send it upstream */
6655 	CONN_UDP_RECV(connp, mp);
6656 }
6657 
6658 /*
6659  * Fanout for UDP packets.
6660  * The caller puts <fport, lport> in the ports parameter.
6661  *
6662  * If SO_REUSEADDR is set all multicast and broadcast packets
6663  * will be delivered to all streams bound to the same port.
6664  *
6665  * Zones notes:
6666  * Multicast and broadcast packets will be distributed to streams in all zones.
6667  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6668  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6669  * packets. To maintain this behavior with multiple zones, the conns are grouped
6670  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6671  * each zone. If unset, all the following conns in the same zone are skipped.
6672  */
6673 static void
6674 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6675     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6676     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6677 {
6678 	uint32_t	dstport, srcport;
6679 	ipaddr_t	dst;
6680 	mblk_t		*first_mp;
6681 	boolean_t	secure;
6682 	in6_addr_t	v6src;
6683 	conn_t		*connp;
6684 	connf_t		*connfp;
6685 	conn_t		*first_connp;
6686 	conn_t		*next_connp;
6687 	mblk_t		*mp1, *first_mp1;
6688 	ipaddr_t	src;
6689 	zoneid_t	last_zoneid;
6690 	boolean_t	reuseaddr;
6691 	boolean_t	shared_addr;
6692 
6693 	first_mp = mp;
6694 	if (mctl_present) {
6695 		mp = first_mp->b_cont;
6696 		first_mp->b_cont = NULL;
6697 		secure = ipsec_in_is_secure(first_mp);
6698 		ASSERT(mp != NULL);
6699 	} else {
6700 		first_mp = NULL;
6701 		secure = B_FALSE;
6702 	}
6703 
6704 	/* Extract ports in net byte order */
6705 	dstport = htons(ntohl(ports) & 0xFFFF);
6706 	srcport = htons(ntohl(ports) >> 16);
6707 	dst = ipha->ipha_dst;
6708 	src = ipha->ipha_src;
6709 
6710 	shared_addr = (zoneid == ALL_ZONES);
6711 	if (shared_addr) {
6712 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6713 		if (zoneid == ALL_ZONES)
6714 			zoneid = tsol_packet_to_zoneid(mp);
6715 	}
6716 
6717 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6718 	mutex_enter(&connfp->connf_lock);
6719 	connp = connfp->connf_head;
6720 	if (!broadcast && !CLASSD(dst)) {
6721 		/*
6722 		 * Not broadcast or multicast. Send to the one (first)
6723 		 * client we find. No need to check conn_wantpacket()
6724 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6725 		 * IPv4 unicast packets.
6726 		 */
6727 		while ((connp != NULL) &&
6728 		    (!IPCL_UDP_MATCH(connp, dstport, dst,
6729 		    srcport, src) ||
6730 		    (connp->conn_zoneid != zoneid && !connp->conn_allzones))) {
6731 			connp = connp->conn_next;
6732 		}
6733 
6734 		if (connp == NULL || connp->conn_upq == NULL)
6735 			goto notfound;
6736 
6737 		if (is_system_labeled() &&
6738 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6739 		    connp))
6740 			goto notfound;
6741 
6742 		CONN_INC_REF(connp);
6743 		mutex_exit(&connfp->connf_lock);
6744 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6745 		    recv_ill, ip_policy);
6746 		IP_STAT(ip_udp_fannorm);
6747 		CONN_DEC_REF(connp);
6748 		return;
6749 	}
6750 
6751 	/*
6752 	 * Broadcast and multicast case
6753 	 *
6754 	 * Need to check conn_wantpacket().
6755 	 * If SO_REUSEADDR has been set on the first we send the
6756 	 * packet to all clients that have joined the group and
6757 	 * match the port.
6758 	 */
6759 
6760 	while (connp != NULL) {
6761 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6762 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6763 		    (!is_system_labeled() ||
6764 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6765 		    connp)))
6766 			break;
6767 		connp = connp->conn_next;
6768 	}
6769 
6770 	if (connp == NULL || connp->conn_upq == NULL)
6771 		goto notfound;
6772 
6773 	first_connp = connp;
6774 	/*
6775 	 * When SO_REUSEADDR is not set, send the packet only to the first
6776 	 * matching connection in its zone by keeping track of the zoneid.
6777 	 */
6778 	reuseaddr = first_connp->conn_reuseaddr;
6779 	last_zoneid = first_connp->conn_zoneid;
6780 
6781 	CONN_INC_REF(connp);
6782 	connp = connp->conn_next;
6783 	for (;;) {
6784 		while (connp != NULL) {
6785 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6786 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6787 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6788 			    (!is_system_labeled() ||
6789 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6790 			    shared_addr, connp)))
6791 				break;
6792 			connp = connp->conn_next;
6793 		}
6794 		/*
6795 		 * Just copy the data part alone. The mctl part is
6796 		 * needed just for verifying policy and it is never
6797 		 * sent up.
6798 		 */
6799 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6800 		    ((mp1 = copymsg(mp)) == NULL))) {
6801 			/*
6802 			 * No more interested clients or memory
6803 			 * allocation failed
6804 			 */
6805 			connp = first_connp;
6806 			break;
6807 		}
6808 		if (connp->conn_zoneid != last_zoneid) {
6809 			/*
6810 			 * Update the zoneid so that the packet isn't sent to
6811 			 * any more conns in the same zone unless SO_REUSEADDR
6812 			 * is set.
6813 			 */
6814 			reuseaddr = connp->conn_reuseaddr;
6815 			last_zoneid = connp->conn_zoneid;
6816 		}
6817 		if (first_mp != NULL) {
6818 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6819 			    ipsec_info_type == IPSEC_IN);
6820 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6821 			if (first_mp1 == NULL) {
6822 				freemsg(mp1);
6823 				connp = first_connp;
6824 				break;
6825 			}
6826 		} else {
6827 			first_mp1 = NULL;
6828 		}
6829 		CONN_INC_REF(connp);
6830 		mutex_exit(&connfp->connf_lock);
6831 		/*
6832 		 * IPQoS notes: We don't send the packet for policy
6833 		 * processing here, will do it for the last one (below).
6834 		 * i.e. we do it per-packet now, but if we do policy
6835 		 * processing per-conn, then we would need to do it
6836 		 * here too.
6837 		 */
6838 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6839 		    ipha, flags, recv_ill, B_FALSE);
6840 		mutex_enter(&connfp->connf_lock);
6841 		/* Follow the next pointer before releasing the conn. */
6842 		next_connp = connp->conn_next;
6843 		IP_STAT(ip_udp_fanmb);
6844 		CONN_DEC_REF(connp);
6845 		connp = next_connp;
6846 	}
6847 
6848 	/* Last one.  Send it upstream. */
6849 	mutex_exit(&connfp->connf_lock);
6850 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6851 	    ip_policy);
6852 	IP_STAT(ip_udp_fanmb);
6853 	CONN_DEC_REF(connp);
6854 	return;
6855 
6856 notfound:
6857 
6858 	mutex_exit(&connfp->connf_lock);
6859 	IP_STAT(ip_udp_fanothers);
6860 	/*
6861 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6862 	 * have already been matched above, since they live in the IPv4
6863 	 * fanout tables. This implies we only need to
6864 	 * check for IPv6 in6addr_any endpoints here.
6865 	 * Thus we compare using ipv6_all_zeros instead of the destination
6866 	 * address, except for the multicast group membership lookup which
6867 	 * uses the IPv4 destination.
6868 	 */
6869 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6870 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6871 	mutex_enter(&connfp->connf_lock);
6872 	connp = connfp->connf_head;
6873 	if (!broadcast && !CLASSD(dst)) {
6874 		while (connp != NULL) {
6875 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6876 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6877 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6878 			    !connp->conn_ipv6_v6only)
6879 				break;
6880 			connp = connp->conn_next;
6881 		}
6882 
6883 		if (connp != NULL && is_system_labeled() &&
6884 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6885 		    connp))
6886 			connp = NULL;
6887 
6888 		if (connp == NULL || connp->conn_upq == NULL) {
6889 			/*
6890 			 * No one bound to this port.  Is
6891 			 * there a client that wants all
6892 			 * unclaimed datagrams?
6893 			 */
6894 			mutex_exit(&connfp->connf_lock);
6895 
6896 			if (mctl_present)
6897 				first_mp->b_cont = mp;
6898 			else
6899 				first_mp = mp;
6900 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6901 				ip_fanout_proto(q, first_mp, ill, ipha,
6902 				    flags | IP_FF_RAWIP, mctl_present,
6903 				    ip_policy, recv_ill, zoneid);
6904 			} else {
6905 				if (ip_fanout_send_icmp(q, first_mp, flags,
6906 				    ICMP_DEST_UNREACHABLE,
6907 				    ICMP_PORT_UNREACHABLE,
6908 				    mctl_present, zoneid)) {
6909 					BUMP_MIB(&ip_mib, udpNoPorts);
6910 				}
6911 			}
6912 			return;
6913 		}
6914 
6915 		CONN_INC_REF(connp);
6916 		mutex_exit(&connfp->connf_lock);
6917 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6918 		    recv_ill, ip_policy);
6919 		CONN_DEC_REF(connp);
6920 		return;
6921 	}
6922 	/*
6923 	 * IPv4 multicast packet being delivered to an AF_INET6
6924 	 * in6addr_any endpoint.
6925 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6926 	 * and not conn_wantpacket_v6() since any multicast membership is
6927 	 * for an IPv4-mapped multicast address.
6928 	 * The packet is sent to all clients in all zones that have joined the
6929 	 * group and match the port.
6930 	 */
6931 	while (connp != NULL) {
6932 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6933 		    srcport, v6src) &&
6934 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6935 		    (!is_system_labeled() ||
6936 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6937 		    connp)))
6938 			break;
6939 		connp = connp->conn_next;
6940 	}
6941 
6942 	if (connp == NULL || connp->conn_upq == NULL) {
6943 		/*
6944 		 * No one bound to this port.  Is
6945 		 * there a client that wants all
6946 		 * unclaimed datagrams?
6947 		 */
6948 		mutex_exit(&connfp->connf_lock);
6949 
6950 		if (mctl_present)
6951 			first_mp->b_cont = mp;
6952 		else
6953 			first_mp = mp;
6954 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6955 			ip_fanout_proto(q, first_mp, ill, ipha,
6956 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6957 			    recv_ill, zoneid);
6958 		} else {
6959 			/*
6960 			 * We used to attempt to send an icmp error here, but
6961 			 * since this is known to be a multicast packet
6962 			 * and we don't send icmp errors in response to
6963 			 * multicast, just drop the packet and give up sooner.
6964 			 */
6965 			BUMP_MIB(&ip_mib, udpNoPorts);
6966 			freemsg(first_mp);
6967 		}
6968 		return;
6969 	}
6970 
6971 	first_connp = connp;
6972 
6973 	CONN_INC_REF(connp);
6974 	connp = connp->conn_next;
6975 	for (;;) {
6976 		while (connp != NULL) {
6977 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6978 			    ipv6_all_zeros, srcport, v6src) &&
6979 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6980 			    (!is_system_labeled() ||
6981 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6982 			    shared_addr, connp)))
6983 				break;
6984 			connp = connp->conn_next;
6985 		}
6986 		/*
6987 		 * Just copy the data part alone. The mctl part is
6988 		 * needed just for verifying policy and it is never
6989 		 * sent up.
6990 		 */
6991 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6992 		    ((mp1 = copymsg(mp)) == NULL))) {
6993 			/*
6994 			 * No more intested clients or memory
6995 			 * allocation failed
6996 			 */
6997 			connp = first_connp;
6998 			break;
6999 		}
7000 		if (first_mp != NULL) {
7001 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7002 			    ipsec_info_type == IPSEC_IN);
7003 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7004 			if (first_mp1 == NULL) {
7005 				freemsg(mp1);
7006 				connp = first_connp;
7007 				break;
7008 			}
7009 		} else {
7010 			first_mp1 = NULL;
7011 		}
7012 		CONN_INC_REF(connp);
7013 		mutex_exit(&connfp->connf_lock);
7014 		/*
7015 		 * IPQoS notes: We don't send the packet for policy
7016 		 * processing here, will do it for the last one (below).
7017 		 * i.e. we do it per-packet now, but if we do policy
7018 		 * processing per-conn, then we would need to do it
7019 		 * here too.
7020 		 */
7021 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
7022 		    ipha, flags, recv_ill, B_FALSE);
7023 		mutex_enter(&connfp->connf_lock);
7024 		/* Follow the next pointer before releasing the conn. */
7025 		next_connp = connp->conn_next;
7026 		CONN_DEC_REF(connp);
7027 		connp = next_connp;
7028 	}
7029 
7030 	/* Last one.  Send it upstream. */
7031 	mutex_exit(&connfp->connf_lock);
7032 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
7033 	    ip_policy);
7034 	CONN_DEC_REF(connp);
7035 }
7036 
7037 /*
7038  * Complete the ip_wput header so that it
7039  * is possible to generate ICMP
7040  * errors.
7041  */
7042 int
7043 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
7044 {
7045 	ire_t *ire;
7046 
7047 	if (ipha->ipha_src == INADDR_ANY) {
7048 		ire = ire_lookup_local(zoneid);
7049 		if (ire == NULL) {
7050 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7051 			return (1);
7052 		}
7053 		ipha->ipha_src = ire->ire_addr;
7054 		ire_refrele(ire);
7055 	}
7056 	ipha->ipha_ttl = ip_def_ttl;
7057 	ipha->ipha_hdr_checksum = 0;
7058 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7059 	return (0);
7060 }
7061 
7062 /*
7063  * Nobody should be sending
7064  * packets up this stream
7065  */
7066 static void
7067 ip_lrput(queue_t *q, mblk_t *mp)
7068 {
7069 	mblk_t *mp1;
7070 
7071 	switch (mp->b_datap->db_type) {
7072 	case M_FLUSH:
7073 		/* Turn around */
7074 		if (*mp->b_rptr & FLUSHW) {
7075 			*mp->b_rptr &= ~FLUSHR;
7076 			qreply(q, mp);
7077 			return;
7078 		}
7079 		break;
7080 	}
7081 	/* Could receive messages that passed through ar_rput */
7082 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7083 		mp1->b_prev = mp1->b_next = NULL;
7084 	freemsg(mp);
7085 }
7086 
7087 /* Nobody should be sending packets down this stream */
7088 /* ARGSUSED */
7089 void
7090 ip_lwput(queue_t *q, mblk_t *mp)
7091 {
7092 	freemsg(mp);
7093 }
7094 
7095 /*
7096  * Move the first hop in any source route to ipha_dst and remove that part of
7097  * the source route.  Called by other protocols.  Errors in option formatting
7098  * are ignored - will be handled by ip_wput_options Return the final
7099  * destination (either ipha_dst or the last entry in a source route.)
7100  */
7101 ipaddr_t
7102 ip_massage_options(ipha_t *ipha)
7103 {
7104 	ipoptp_t	opts;
7105 	uchar_t		*opt;
7106 	uint8_t		optval;
7107 	uint8_t		optlen;
7108 	ipaddr_t	dst;
7109 	int		i;
7110 	ire_t		*ire;
7111 
7112 	ip2dbg(("ip_massage_options\n"));
7113 	dst = ipha->ipha_dst;
7114 	for (optval = ipoptp_first(&opts, ipha);
7115 	    optval != IPOPT_EOL;
7116 	    optval = ipoptp_next(&opts)) {
7117 		opt = opts.ipoptp_cur;
7118 		switch (optval) {
7119 			uint8_t off;
7120 		case IPOPT_SSRR:
7121 		case IPOPT_LSRR:
7122 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7123 				ip1dbg(("ip_massage_options: bad src route\n"));
7124 				break;
7125 			}
7126 			optlen = opts.ipoptp_len;
7127 			off = opt[IPOPT_OFFSET];
7128 			off--;
7129 		redo_srr:
7130 			if (optlen < IP_ADDR_LEN ||
7131 			    off > optlen - IP_ADDR_LEN) {
7132 				/* End of source route */
7133 				ip1dbg(("ip_massage_options: end of SR\n"));
7134 				break;
7135 			}
7136 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7137 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7138 			    ntohl(dst)));
7139 			/*
7140 			 * Check if our address is present more than
7141 			 * once as consecutive hops in source route.
7142 			 * XXX verify per-interface ip_forwarding
7143 			 * for source route?
7144 			 */
7145 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7146 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
7147 			if (ire != NULL) {
7148 				ire_refrele(ire);
7149 				off += IP_ADDR_LEN;
7150 				goto redo_srr;
7151 			}
7152 			if (dst == htonl(INADDR_LOOPBACK)) {
7153 				ip1dbg(("ip_massage_options: loopback addr in "
7154 				    "source route!\n"));
7155 				break;
7156 			}
7157 			/*
7158 			 * Update ipha_dst to be the first hop and remove the
7159 			 * first hop from the source route (by overwriting
7160 			 * part of the option with NOP options).
7161 			 */
7162 			ipha->ipha_dst = dst;
7163 			/* Put the last entry in dst */
7164 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7165 			    3;
7166 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7167 
7168 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7169 			    ntohl(dst)));
7170 			/* Move down and overwrite */
7171 			opt[IP_ADDR_LEN] = opt[0];
7172 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7173 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7174 			for (i = 0; i < IP_ADDR_LEN; i++)
7175 				opt[i] = IPOPT_NOP;
7176 			break;
7177 		}
7178 	}
7179 	return (dst);
7180 }
7181 
7182 /*
7183  * This function's job is to forward data to the reverse tunnel (FA->HA)
7184  * after doing a few checks. It is assumed that the incoming interface
7185  * of the packet is always different than the outgoing interface and the
7186  * ire_type of the found ire has to be a non-resolver type.
7187  *
7188  * IPQoS notes
7189  * IP policy is invoked twice for a forwarded packet, once on the read side
7190  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7191  * enabled.
7192  */
7193 static void
7194 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7195 {
7196 	ipha_t		*ipha;
7197 	queue_t		*q;
7198 	uint32_t 	pkt_len;
7199 #define	rptr    ((uchar_t *)ipha)
7200 	uint32_t 	sum;
7201 	uint32_t 	max_frag;
7202 	mblk_t		*first_mp;
7203 	uint32_t	ill_index;
7204 	ipxmit_state_t	pktxmit_state;
7205 
7206 	ASSERT(ire != NULL);
7207 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7208 	ASSERT(ire->ire_stq != NULL);
7209 
7210 	/* Initiate read side IPPF processing */
7211 	if (IPP_ENABLED(IPP_FWD_IN)) {
7212 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7213 		ip_process(IPP_FWD_IN, &mp, ill_index);
7214 		if (mp == NULL) {
7215 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7216 			    "dropped during IPPF processing\n"));
7217 			return;
7218 		}
7219 	}
7220 
7221 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7222 		ILLF_ROUTER) == 0) ||
7223 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7224 		BUMP_MIB(&ip_mib, ipForwProhibits);
7225 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7226 		    "forwarding is not turned on\n"));
7227 		goto drop_pkt;
7228 	}
7229 
7230 	/*
7231 	 * Don't forward if the interface is down
7232 	 */
7233 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7234 		BUMP_MIB(&ip_mib, ipInDiscards);
7235 		goto drop_pkt;
7236 	}
7237 
7238 	ipha = (ipha_t *)mp->b_rptr;
7239 	pkt_len = ntohs(ipha->ipha_length);
7240 	/* Adjust the checksum to reflect the ttl decrement. */
7241 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7242 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7243 	if (ipha->ipha_ttl-- <= 1) {
7244 		if (ip_csum_hdr(ipha)) {
7245 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7246 			goto drop_pkt;
7247 		}
7248 		q = ire->ire_stq;
7249 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7250 		    BPRI_HI)) == NULL) {
7251 			goto drop_pkt;
7252 		}
7253 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7254 		/* Sent by forwarding path, and router is global zone */
7255 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7256 		    GLOBAL_ZONEID);
7257 		return;
7258 	}
7259 
7260 	/* Get the ill_index of the ILL */
7261 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7262 
7263 	/*
7264 	 * ip_mrtun_forward is only used by foreign agent to reverse
7265 	 * tunnel the incoming packet. So it does not do any option
7266 	 * processing for source routing.
7267 	 */
7268 	max_frag = ire->ire_max_frag;
7269 	if (pkt_len > max_frag) {
7270 		/*
7271 		 * It needs fragging on its way out.  We haven't
7272 		 * verified the header checksum yet.  Since we
7273 		 * are going to put a surely good checksum in the
7274 		 * outgoing header, we have to make sure that it
7275 		 * was good coming in.
7276 		 */
7277 		if (ip_csum_hdr(ipha)) {
7278 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7279 			goto drop_pkt;
7280 		}
7281 
7282 		/* Initiate write side IPPF processing */
7283 		if (IPP_ENABLED(IPP_FWD_OUT)) {
7284 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7285 			if (mp == NULL) {
7286 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7287 				    "dropped/deferred during ip policy "\
7288 				    "processing\n"));
7289 				return;
7290 			}
7291 		}
7292 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7293 		    BPRI_HI)) == NULL) {
7294 			goto drop_pkt;
7295 		}
7296 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7297 		mp = first_mp;
7298 
7299 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
7300 		return;
7301 	}
7302 
7303 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7304 
7305 	ASSERT(ire->ire_ipif != NULL);
7306 
7307 	/* Now send the packet to the tunnel interface */
7308 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7309 	q = ire->ire_stq;
7310 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7311 	if ((pktxmit_state == SEND_FAILED) ||
7312 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7313 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7314 		    q->q_ptr));
7315 	}
7316 
7317 	return;
7318 
7319 drop_pkt:;
7320 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7321 	freemsg(mp);
7322 #undef	rptr
7323 }
7324 
7325 /*
7326  * Fills the ipsec_out_t data structure with appropriate fields and
7327  * prepends it to mp which contains the IP hdr + data that was meant
7328  * to be forwarded. Please note that ipsec_out_info data structure
7329  * is used here to communicate the outgoing ill path at ip_wput()
7330  * for the ICMP error packet. This has nothing to do with ipsec IP
7331  * security. ipsec_out_t is really used to pass the info to the module
7332  * IP where this information cannot be extracted from conn.
7333  * This functions is called by ip_mrtun_forward().
7334  */
7335 void
7336 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7337 {
7338 	ipsec_out_t	*io;
7339 
7340 	ASSERT(xmit_ill != NULL);
7341 	first_mp->b_datap->db_type = M_CTL;
7342 	first_mp->b_wptr += sizeof (ipsec_info_t);
7343 	/*
7344 	 * This is to pass info to ip_wput in absence of conn.
7345 	 * ipsec_out_secure will be B_FALSE because of this.
7346 	 * Thus ipsec_out_secure being B_FALSE indicates that
7347 	 * this is not IPSEC security related information.
7348 	 */
7349 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7350 	io = (ipsec_out_t *)first_mp->b_rptr;
7351 	io->ipsec_out_type = IPSEC_OUT;
7352 	io->ipsec_out_len = sizeof (ipsec_out_t);
7353 	first_mp->b_cont = mp;
7354 	io->ipsec_out_ill_index =
7355 	    xmit_ill->ill_phyint->phyint_ifindex;
7356 	io->ipsec_out_xmit_if = B_TRUE;
7357 }
7358 
7359 /*
7360  * Return the network mask
7361  * associated with the specified address.
7362  */
7363 ipaddr_t
7364 ip_net_mask(ipaddr_t addr)
7365 {
7366 	uchar_t	*up = (uchar_t *)&addr;
7367 	ipaddr_t mask = 0;
7368 	uchar_t	*maskp = (uchar_t *)&mask;
7369 
7370 #if defined(__i386) || defined(__amd64)
7371 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7372 #endif
7373 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7374 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7375 #endif
7376 	if (CLASSD(addr)) {
7377 		maskp[0] = 0xF0;
7378 		return (mask);
7379 	}
7380 	if (addr == 0)
7381 		return (0);
7382 	maskp[0] = 0xFF;
7383 	if ((up[0] & 0x80) == 0)
7384 		return (mask);
7385 
7386 	maskp[1] = 0xFF;
7387 	if ((up[0] & 0xC0) == 0x80)
7388 		return (mask);
7389 
7390 	maskp[2] = 0xFF;
7391 	if ((up[0] & 0xE0) == 0xC0)
7392 		return (mask);
7393 
7394 	/* Must be experimental or multicast, indicate as much */
7395 	return ((ipaddr_t)0);
7396 }
7397 
7398 /*
7399  * Select an ill for the packet by considering load spreading across
7400  * a different ill in the group if dst_ill is part of some group.
7401  */
7402 ill_t *
7403 ip_newroute_get_dst_ill(ill_t *dst_ill)
7404 {
7405 	ill_t *ill;
7406 
7407 	/*
7408 	 * We schedule irrespective of whether the source address is
7409 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7410 	 */
7411 	ill = illgrp_scheduler(dst_ill);
7412 	if (ill == NULL)
7413 		return (NULL);
7414 
7415 	/*
7416 	 * For groups with names ip_sioctl_groupname ensures that all
7417 	 * ills are of same type. For groups without names, ifgrp_insert
7418 	 * ensures this.
7419 	 */
7420 	ASSERT(dst_ill->ill_type == ill->ill_type);
7421 
7422 	return (ill);
7423 }
7424 
7425 /*
7426  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7427  */
7428 ill_t *
7429 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7430 {
7431 	ill_t *ret_ill;
7432 
7433 	ASSERT(ifindex != 0);
7434 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7435 	if (ret_ill == NULL ||
7436 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7437 		if (isv6) {
7438 			if (ill != NULL) {
7439 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7440 			} else {
7441 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7442 			}
7443 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7444 			    "bad ifindex %d.\n", ifindex));
7445 		} else {
7446 			BUMP_MIB(&ip_mib, ipOutDiscards);
7447 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7448 			    "bad ifindex %d.\n", ifindex));
7449 		}
7450 		if (ret_ill != NULL)
7451 			ill_refrele(ret_ill);
7452 		freemsg(first_mp);
7453 		return (NULL);
7454 	}
7455 
7456 	return (ret_ill);
7457 }
7458 
7459 /*
7460  * IPv4 -
7461  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7462  * out a packet to a destination address for which we do not have specific
7463  * (or sufficient) routing information.
7464  *
7465  * NOTE : These are the scopes of some of the variables that point at IRE,
7466  *	  which needs to be followed while making any future modifications
7467  *	  to avoid memory leaks.
7468  *
7469  *	- ire and sire are the entries looked up initially by
7470  *	  ire_ftable_lookup.
7471  *	- ipif_ire is used to hold the interface ire associated with
7472  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7473  *	  it before branching out to error paths.
7474  *	- save_ire is initialized before ire_create, so that ire returned
7475  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7476  *	  before breaking out of the switch.
7477  *
7478  *	Thus on failures, we have to REFRELE only ire and sire, if they
7479  *	are not NULL.
7480  */
7481 void
7482 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7483     zoneid_t zoneid)
7484 {
7485 	areq_t	*areq;
7486 	ipaddr_t gw = 0;
7487 	ire_t	*ire = NULL;
7488 	mblk_t	*res_mp;
7489 	ipaddr_t *addrp;
7490 	ipaddr_t nexthop_addr;
7491 	ipif_t  *src_ipif = NULL;
7492 	ill_t	*dst_ill = NULL;
7493 	ipha_t  *ipha;
7494 	ire_t	*sire = NULL;
7495 	mblk_t	*first_mp;
7496 	ire_t	*save_ire;
7497 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7498 	ushort_t ire_marks = 0;
7499 	boolean_t mctl_present;
7500 	ipsec_out_t *io;
7501 	mblk_t	*saved_mp;
7502 	ire_t	*first_sire = NULL;
7503 	mblk_t	*copy_mp = NULL;
7504 	mblk_t	*xmit_mp = NULL;
7505 	ipaddr_t save_dst;
7506 	uint32_t multirt_flags =
7507 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7508 	boolean_t multirt_is_resolvable;
7509 	boolean_t multirt_resolve_next;
7510 	boolean_t do_attach_ill = B_FALSE;
7511 	boolean_t ip_nexthop = B_FALSE;
7512 	tsol_ire_gw_secattr_t *attrp = NULL;
7513 	tsol_gcgrp_t *gcgrp = NULL;
7514 	tsol_gcgrp_addr_t ga;
7515 
7516 	if (ip_debug > 2) {
7517 		/* ip1dbg */
7518 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7519 	}
7520 
7521 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7522 	if (mctl_present) {
7523 		io = (ipsec_out_t *)first_mp->b_rptr;
7524 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7525 		ASSERT(zoneid == io->ipsec_out_zoneid);
7526 		ASSERT(zoneid != ALL_ZONES);
7527 	}
7528 
7529 	ipha = (ipha_t *)mp->b_rptr;
7530 
7531 	/* All multicast lookups come through ip_newroute_ipif() */
7532 	if (CLASSD(dst)) {
7533 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7534 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7535 		freemsg(first_mp);
7536 		return;
7537 	}
7538 
7539 	if (mctl_present && io->ipsec_out_attach_if) {
7540 		/* ip_grab_attach_ill returns a held ill */
7541 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7542 		    io->ipsec_out_ill_index, B_FALSE);
7543 
7544 		/* Failure case frees things for us. */
7545 		if (attach_ill == NULL)
7546 			return;
7547 
7548 		/*
7549 		 * Check if we need an ire that will not be
7550 		 * looked up by anybody else i.e. HIDDEN.
7551 		 */
7552 		if (ill_is_probeonly(attach_ill))
7553 			ire_marks = IRE_MARK_HIDDEN;
7554 	}
7555 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7556 		ip_nexthop = B_TRUE;
7557 		nexthop_addr = io->ipsec_out_nexthop_addr;
7558 	}
7559 	/*
7560 	 * If this IRE is created for forwarding or it is not for
7561 	 * traffic for congestion controlled protocols, mark it as temporary.
7562 	 */
7563 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7564 		ire_marks |= IRE_MARK_TEMPORARY;
7565 
7566 	/*
7567 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7568 	 * chain until it gets the most specific information available.
7569 	 * For example, we know that there is no IRE_CACHE for this dest,
7570 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7571 	 * ire_ftable_lookup will look up the gateway, etc.
7572 	 * Check if in_ill != NULL. If it is true, the packet must be
7573 	 * from an incoming interface where RTA_SRCIFP is set.
7574 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7575 	 * to the destination, of equal netmask length in the forward table,
7576 	 * will be recursively explored. If no information is available
7577 	 * for the final gateway of that route, we force the returned ire
7578 	 * to be equal to sire using MATCH_IRE_PARENT.
7579 	 * At least, in this case we have a starting point (in the buckets)
7580 	 * to look for other routes to the destination in the forward table.
7581 	 * This is actually used only for multirouting, where a list
7582 	 * of routes has to be processed in sequence.
7583 	 *
7584 	 * In the process of coming up with the most specific information,
7585 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7586 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7587 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7588 	 * Two caveats when handling incomplete ire's in ip_newroute:
7589 	 * - we should be careful when accessing its ire_nce (specifically
7590 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7591 	 * - not all legacy code path callers are prepared to handle
7592 	 *   incomplete ire's, so we should not create/add incomplete
7593 	 *   ire_cache entries here. (See discussion about temporary solution
7594 	 *   further below).
7595 	 *
7596 	 * In order to minimize packet dropping, and to preserve existing
7597 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7598 	 * gateway, and instead use the IF_RESOLVER ire to send out
7599 	 * another request to ARP (this is achieved by passing the
7600 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7601 	 * arp response comes back in ip_wput_nondata, we will create
7602 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7603 	 *
7604 	 * Note that this is a temporary solution; the correct solution is
7605 	 * to create an incomplete  per-dst ire_cache entry, and send the
7606 	 * packet out when the gw's nce is resolved. In order to achieve this,
7607 	 * all packet processing must have been completed prior to calling
7608 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7609 	 * to be modified to accomodate this solution.
7610 	 */
7611 	if (in_ill != NULL) {
7612 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7613 		    in_ill, MATCH_IRE_TYPE);
7614 	} else if (ip_nexthop) {
7615 		/*
7616 		 * The first time we come here, we look for an IRE_INTERFACE
7617 		 * entry for the specified nexthop, set the dst to be the
7618 		 * nexthop address and create an IRE_CACHE entry for the
7619 		 * nexthop. The next time around, we are able to find an
7620 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7621 		 * nexthop address and create an IRE_CACHE entry for the
7622 		 * destination address via the specified nexthop.
7623 		 */
7624 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7625 		    MBLK_GETLABEL(mp));
7626 		if (ire != NULL) {
7627 			gw = nexthop_addr;
7628 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7629 		} else {
7630 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7631 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7632 			    MBLK_GETLABEL(mp),
7633 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7634 			if (ire != NULL) {
7635 				dst = nexthop_addr;
7636 			}
7637 		}
7638 	} else if (attach_ill == NULL) {
7639 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7640 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7641 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7642 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7643 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7644 	} else {
7645 		/*
7646 		 * attach_ill is set only for communicating with
7647 		 * on-link hosts. So, don't look for DEFAULT.
7648 		 */
7649 		ipif_t	*attach_ipif;
7650 
7651 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7652 		if (attach_ipif == NULL) {
7653 			ill_refrele(attach_ill);
7654 			goto icmp_err_ret;
7655 		}
7656 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7657 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7658 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7659 		    MATCH_IRE_SECATTR);
7660 		ipif_refrele(attach_ipif);
7661 	}
7662 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7663 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7664 
7665 	/*
7666 	 * This loop is run only once in most cases.
7667 	 * We loop to resolve further routes only when the destination
7668 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7669 	 */
7670 	do {
7671 		/* Clear the previous iteration's values */
7672 		if (src_ipif != NULL) {
7673 			ipif_refrele(src_ipif);
7674 			src_ipif = NULL;
7675 		}
7676 		if (dst_ill != NULL) {
7677 			ill_refrele(dst_ill);
7678 			dst_ill = NULL;
7679 		}
7680 
7681 		multirt_resolve_next = B_FALSE;
7682 		/*
7683 		 * We check if packets have to be multirouted.
7684 		 * In this case, given the current <ire, sire> couple,
7685 		 * we look for the next suitable <ire, sire>.
7686 		 * This check is done in ire_multirt_lookup(),
7687 		 * which applies various criteria to find the next route
7688 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7689 		 * unchanged if it detects it has not been tried yet.
7690 		 */
7691 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7692 			ip3dbg(("ip_newroute: starting next_resolution "
7693 			    "with first_mp %p, tag %d\n",
7694 			    (void *)first_mp,
7695 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7696 
7697 			ASSERT(sire != NULL);
7698 			multirt_is_resolvable =
7699 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7700 				MBLK_GETLABEL(mp));
7701 
7702 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7703 			    "ire %p, sire %p\n",
7704 			    multirt_is_resolvable,
7705 			    (void *)ire, (void *)sire));
7706 
7707 			if (!multirt_is_resolvable) {
7708 				/*
7709 				 * No more multirt route to resolve; give up
7710 				 * (all routes resolved or no more
7711 				 * resolvable routes).
7712 				 */
7713 				if (ire != NULL) {
7714 					ire_refrele(ire);
7715 					ire = NULL;
7716 				}
7717 			} else {
7718 				ASSERT(sire != NULL);
7719 				ASSERT(ire != NULL);
7720 				/*
7721 				 * We simply use first_sire as a flag that
7722 				 * indicates if a resolvable multirt route
7723 				 * has already been found.
7724 				 * If it is not the case, we may have to send
7725 				 * an ICMP error to report that the
7726 				 * destination is unreachable.
7727 				 * We do not IRE_REFHOLD first_sire.
7728 				 */
7729 				if (first_sire == NULL) {
7730 					first_sire = sire;
7731 				}
7732 			}
7733 		}
7734 		if (ire == NULL) {
7735 			if (ip_debug > 3) {
7736 				/* ip2dbg */
7737 				pr_addr_dbg("ip_newroute: "
7738 				    "can't resolve %s\n", AF_INET, &dst);
7739 			}
7740 			ip3dbg(("ip_newroute: "
7741 			    "ire %p, sire %p, first_sire %p\n",
7742 			    (void *)ire, (void *)sire, (void *)first_sire));
7743 
7744 			if (sire != NULL) {
7745 				ire_refrele(sire);
7746 				sire = NULL;
7747 			}
7748 
7749 			if (first_sire != NULL) {
7750 				/*
7751 				 * At least one multirt route has been found
7752 				 * in the same call to ip_newroute();
7753 				 * there is no need to report an ICMP error.
7754 				 * first_sire was not IRE_REFHOLDed.
7755 				 */
7756 				MULTIRT_DEBUG_UNTAG(first_mp);
7757 				freemsg(first_mp);
7758 				return;
7759 			}
7760 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7761 			    RTA_DST);
7762 			if (attach_ill != NULL)
7763 				ill_refrele(attach_ill);
7764 			goto icmp_err_ret;
7765 		}
7766 
7767 		/*
7768 		 * When RTA_SRCIFP is used to add a route, then an interface
7769 		 * route is added in the source interface's routing table.
7770 		 * If the outgoing interface of this route is of type
7771 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7772 		 * ire_nce->nce_res_mp is set to NULL.
7773 		 * Later, when this route is first used for forwarding
7774 		 * a packet, ip_newroute() is called
7775 		 * to resolve the hardware address of the outgoing ipif.
7776 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7777 		 * source interface based table. We only come here if the
7778 		 * outgoing interface is a resolver interface and we don't
7779 		 * have the ire_nce->nce_res_mp information yet.
7780 		 * If in_ill is not null that means it is called from
7781 		 * ip_rput.
7782 		 */
7783 
7784 		ASSERT(ire->ire_in_ill == NULL ||
7785 		    (ire->ire_type == IRE_IF_RESOLVER &&
7786 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
7787 
7788 		/*
7789 		 * Verify that the returned IRE does not have either
7790 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7791 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7792 		 */
7793 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7794 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7795 			if (attach_ill != NULL)
7796 				ill_refrele(attach_ill);
7797 			goto icmp_err_ret;
7798 		}
7799 		/*
7800 		 * Increment the ire_ob_pkt_count field for ire if it is an
7801 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7802 		 * increment the same for the parent IRE, sire, if it is some
7803 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7804 		 * and HOST_REDIRECT).
7805 		 */
7806 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7807 			UPDATE_OB_PKT_COUNT(ire);
7808 			ire->ire_last_used_time = lbolt;
7809 		}
7810 
7811 		if (sire != NULL) {
7812 			gw = sire->ire_gateway_addr;
7813 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7814 			    IRE_INTERFACE)) == 0);
7815 			UPDATE_OB_PKT_COUNT(sire);
7816 			sire->ire_last_used_time = lbolt;
7817 		}
7818 		/*
7819 		 * We have a route to reach the destination.
7820 		 *
7821 		 * 1) If the interface is part of ill group, try to get a new
7822 		 *    ill taking load spreading into account.
7823 		 *
7824 		 * 2) After selecting the ill, get a source address that
7825 		 *    might create good inbound load spreading.
7826 		 *    ipif_select_source does this for us.
7827 		 *
7828 		 * If the application specified the ill (ifindex), we still
7829 		 * load spread. Only if the packets needs to go out
7830 		 * specifically on a given ill e.g. binding to
7831 		 * IPIF_NOFAILOVER address, then we don't try to use a
7832 		 * different ill for load spreading.
7833 		 */
7834 		if (attach_ill == NULL) {
7835 			/*
7836 			 * Don't perform outbound load spreading in the
7837 			 * case of an RTF_MULTIRT route, as we actually
7838 			 * typically want to replicate outgoing packets
7839 			 * through particular interfaces.
7840 			 */
7841 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7842 				dst_ill = ire->ire_ipif->ipif_ill;
7843 				/* for uniformity */
7844 				ill_refhold(dst_ill);
7845 			} else {
7846 				/*
7847 				 * If we are here trying to create an IRE_CACHE
7848 				 * for an offlink destination and have the
7849 				 * IRE_CACHE for the next hop and the latter is
7850 				 * using virtual IP source address selection i.e
7851 				 * it's ire->ire_ipif is pointing to a virtual
7852 				 * network interface (vni) then
7853 				 * ip_newroute_get_dst_ll() will return the vni
7854 				 * interface as the dst_ill. Since the vni is
7855 				 * virtual i.e not associated with any physical
7856 				 * interface, it cannot be the dst_ill, hence
7857 				 * in such a case call ip_newroute_get_dst_ll()
7858 				 * with the stq_ill instead of the ire_ipif ILL.
7859 				 * The function returns a refheld ill.
7860 				 */
7861 				if ((ire->ire_type == IRE_CACHE) &&
7862 				    IS_VNI(ire->ire_ipif->ipif_ill))
7863 					dst_ill = ip_newroute_get_dst_ill(
7864 						ire->ire_stq->q_ptr);
7865 				else
7866 					dst_ill = ip_newroute_get_dst_ill(
7867 						ire->ire_ipif->ipif_ill);
7868 			}
7869 			if (dst_ill == NULL) {
7870 				if (ip_debug > 2) {
7871 					pr_addr_dbg("ip_newroute: "
7872 					    "no dst ill for dst"
7873 					    " %s\n", AF_INET, &dst);
7874 				}
7875 				goto icmp_err_ret;
7876 			}
7877 		} else {
7878 			dst_ill = ire->ire_ipif->ipif_ill;
7879 			/* for uniformity */
7880 			ill_refhold(dst_ill);
7881 			/*
7882 			 * We should have found a route matching ill as we
7883 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7884 			 * Rather than asserting, when there is a mismatch,
7885 			 * we just drop the packet.
7886 			 */
7887 			if (dst_ill != attach_ill) {
7888 				ip0dbg(("ip_newroute: Packet dropped as "
7889 				    "IPIF_NOFAILOVER ill is %s, "
7890 				    "ire->ire_ipif->ipif_ill is %s\n",
7891 				    attach_ill->ill_name,
7892 				    dst_ill->ill_name));
7893 				ill_refrele(attach_ill);
7894 				goto icmp_err_ret;
7895 			}
7896 		}
7897 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7898 		if (attach_ill != NULL) {
7899 			ill_refrele(attach_ill);
7900 			attach_ill = NULL;
7901 			do_attach_ill = B_TRUE;
7902 		}
7903 		ASSERT(dst_ill != NULL);
7904 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7905 
7906 		/*
7907 		 * Pick the best source address from dst_ill.
7908 		 *
7909 		 * 1) If it is part of a multipathing group, we would
7910 		 *    like to spread the inbound packets across different
7911 		 *    interfaces. ipif_select_source picks a random source
7912 		 *    across the different ills in the group.
7913 		 *
7914 		 * 2) If it is not part of a multipathing group, we try
7915 		 *    to pick the source address from the destination
7916 		 *    route. Clustering assumes that when we have multiple
7917 		 *    prefixes hosted on an interface, the prefix of the
7918 		 *    source address matches the prefix of the destination
7919 		 *    route. We do this only if the address is not
7920 		 *    DEPRECATED.
7921 		 *
7922 		 * 3) If the conn is in a different zone than the ire, we
7923 		 *    need to pick a source address from the right zone.
7924 		 *
7925 		 * NOTE : If we hit case (1) above, the prefix of the source
7926 		 *	  address picked may not match the prefix of the
7927 		 *	  destination routes prefix as ipif_select_source
7928 		 *	  does not look at "dst" while picking a source
7929 		 *	  address.
7930 		 *	  If we want the same behavior as (2), we will need
7931 		 *	  to change the behavior of ipif_select_source.
7932 		 */
7933 		ASSERT(src_ipif == NULL);
7934 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7935 			/*
7936 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7937 			 * Check that the ipif matching the requested source
7938 			 * address still exists.
7939 			 */
7940 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7941 			    zoneid, NULL, NULL, NULL, NULL);
7942 		}
7943 		if (src_ipif == NULL) {
7944 			ire_marks |= IRE_MARK_USESRC_CHECK;
7945 			if ((dst_ill->ill_group != NULL) ||
7946 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
7947 			    (connp != NULL && ire->ire_zoneid != zoneid &&
7948 			    ire->ire_zoneid != ALL_ZONES) ||
7949 			    (dst_ill->ill_usesrc_ifindex != 0)) {
7950 				/*
7951 				 * If the destination is reachable via a
7952 				 * given gateway, the selected source address
7953 				 * should be in the same subnet as the gateway.
7954 				 * Otherwise, the destination is not reachable.
7955 				 *
7956 				 * If there are no interfaces on the same subnet
7957 				 * as the destination, ipif_select_source gives
7958 				 * first non-deprecated interface which might be
7959 				 * on a different subnet than the gateway.
7960 				 * This is not desirable. Hence pass the dst_ire
7961 				 * source address to ipif_select_source.
7962 				 * It is sure that the destination is reachable
7963 				 * with the dst_ire source address subnet.
7964 				 * So passing dst_ire source address to
7965 				 * ipif_select_source will make sure that the
7966 				 * selected source will be on the same subnet
7967 				 * as dst_ire source address.
7968 				 */
7969 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
7970 				src_ipif = ipif_select_source(dst_ill, saddr,
7971 				    zoneid);
7972 				if (src_ipif == NULL) {
7973 					if (ip_debug > 2) {
7974 						pr_addr_dbg("ip_newroute: "
7975 						    "no src for dst %s ",
7976 						    AF_INET, &dst);
7977 						printf("through interface %s\n",
7978 						    dst_ill->ill_name);
7979 					}
7980 					goto icmp_err_ret;
7981 				}
7982 			} else {
7983 				src_ipif = ire->ire_ipif;
7984 				ASSERT(src_ipif != NULL);
7985 				/* hold src_ipif for uniformity */
7986 				ipif_refhold(src_ipif);
7987 			}
7988 		}
7989 
7990 		/*
7991 		 * Assign a source address while we have the conn.
7992 		 * We can't have ip_wput_ire pick a source address when the
7993 		 * packet returns from arp since we need to look at
7994 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7995 		 * going through arp.
7996 		 *
7997 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7998 		 *	  it uses ip6i to store this information.
7999 		 */
8000 		if (ipha->ipha_src == INADDR_ANY &&
8001 		    (connp == NULL || !connp->conn_unspec_src)) {
8002 			ipha->ipha_src = src_ipif->ipif_src_addr;
8003 		}
8004 		if (ip_debug > 3) {
8005 			/* ip2dbg */
8006 			pr_addr_dbg("ip_newroute: first hop %s\n",
8007 			    AF_INET, &gw);
8008 		}
8009 		ip2dbg(("\tire type %s (%d)\n",
8010 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8011 
8012 		/*
8013 		 * The TTL of multirouted packets is bounded by the
8014 		 * ip_multirt_ttl ndd variable.
8015 		 */
8016 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8017 			/* Force TTL of multirouted packets */
8018 			if ((ip_multirt_ttl > 0) &&
8019 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
8020 				ip2dbg(("ip_newroute: forcing multirt TTL "
8021 				    "to %d (was %d), dst 0x%08x\n",
8022 				    ip_multirt_ttl, ipha->ipha_ttl,
8023 				    ntohl(sire->ire_addr)));
8024 				ipha->ipha_ttl = ip_multirt_ttl;
8025 			}
8026 		}
8027 		/*
8028 		 * At this point in ip_newroute(), ire is either the
8029 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8030 		 * destination or an IRE_INTERFACE type that should be used
8031 		 * to resolve an on-subnet destination or an on-subnet
8032 		 * next-hop gateway.
8033 		 *
8034 		 * In the IRE_CACHE case, we have the following :
8035 		 *
8036 		 * 1) src_ipif - used for getting a source address.
8037 		 *
8038 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8039 		 *    means packets using this IRE_CACHE will go out on
8040 		 *    dst_ill.
8041 		 *
8042 		 * 3) The IRE sire will point to the prefix that is the
8043 		 *    longest  matching route for the destination. These
8044 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
8045 		 *    and IRE_HOST_REDIRECT.
8046 		 *
8047 		 *    The newly created IRE_CACHE entry for the off-subnet
8048 		 *    destination is tied to both the prefix route and the
8049 		 *    interface route used to resolve the next-hop gateway
8050 		 *    via the ire_phandle and ire_ihandle fields,
8051 		 *    respectively.
8052 		 *
8053 		 * In the IRE_INTERFACE case, we have the following :
8054 		 *
8055 		 * 1) src_ipif - used for getting a source address.
8056 		 *
8057 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8058 		 *    means packets using the IRE_CACHE that we will build
8059 		 *    here will go out on dst_ill.
8060 		 *
8061 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8062 		 *    to be created will only be tied to the IRE_INTERFACE
8063 		 *    that was derived from the ire_ihandle field.
8064 		 *
8065 		 *    If sire is non-NULL, it means the destination is
8066 		 *    off-link and we will first create the IRE_CACHE for the
8067 		 *    gateway. Next time through ip_newroute, we will create
8068 		 *    the IRE_CACHE for the final destination as described
8069 		 *    above.
8070 		 *
8071 		 * In both cases, after the current resolution has been
8072 		 * completed (or possibly initialised, in the IRE_INTERFACE
8073 		 * case), the loop may be re-entered to attempt the resolution
8074 		 * of another RTF_MULTIRT route.
8075 		 *
8076 		 * When an IRE_CACHE entry for the off-subnet destination is
8077 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8078 		 * for further processing in emission loops.
8079 		 */
8080 		save_ire = ire;
8081 		switch (ire->ire_type) {
8082 		case IRE_CACHE: {
8083 			ire_t	*ipif_ire;
8084 			mblk_t	*ire_fp_mp;
8085 
8086 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8087 			if (gw == 0)
8088 				gw = ire->ire_gateway_addr;
8089 			/*
8090 			 * We need 3 ire's to create a new cache ire for an
8091 			 * off-link destination from the cache ire of the
8092 			 * gateway.
8093 			 *
8094 			 *	1. The prefix ire 'sire' (Note that this does
8095 			 *	   not apply to the conn_nexthop_set case)
8096 			 *	2. The cache ire of the gateway 'ire'
8097 			 *	3. The interface ire 'ipif_ire'
8098 			 *
8099 			 * We have (1) and (2). We lookup (3) below.
8100 			 *
8101 			 * If there is no interface route to the gateway,
8102 			 * it is a race condition, where we found the cache
8103 			 * but the interface route has been deleted.
8104 			 */
8105 			if (ip_nexthop) {
8106 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8107 			} else {
8108 				ipif_ire =
8109 				    ire_ihandle_lookup_offlink(ire, sire);
8110 			}
8111 			if (ipif_ire == NULL) {
8112 				ip1dbg(("ip_newroute: "
8113 				    "ire_ihandle_lookup_offlink failed\n"));
8114 				goto icmp_err_ret;
8115 			}
8116 			/*
8117 			 * XXX We are using the same res_mp
8118 			 * (DL_UNITDATA_REQ) though the save_ire is not
8119 			 * pointing at the same ill.
8120 			 * This is incorrect. We need to send it up to the
8121 			 * resolver to get the right res_mp. For ethernets
8122 			 * this may be okay (ill_type == DL_ETHER).
8123 			 */
8124 			res_mp = save_ire->ire_nce->nce_res_mp;
8125 			ire_fp_mp = NULL;
8126 			/*
8127 			 * save_ire's nce_fp_mp can't change since it is
8128 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8129 			 * LOCK_IRE_FP_MP does not do any useful work in
8130 			 * the case of IRE_CACHE. So we don't use it below.
8131 			 */
8132 			if (save_ire->ire_stq == dst_ill->ill_wq)
8133 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8134 
8135 			/*
8136 			 * Check cached gateway IRE for any security
8137 			 * attributes; if found, associate the gateway
8138 			 * credentials group to the destination IRE.
8139 			 */
8140 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8141 				mutex_enter(&attrp->igsa_lock);
8142 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8143 					GCGRP_REFHOLD(gcgrp);
8144 				mutex_exit(&attrp->igsa_lock);
8145 			}
8146 
8147 			ire = ire_create(
8148 			    (uchar_t *)&dst,		/* dest address */
8149 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8150 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8151 			    (uchar_t *)&gw,		/* gateway address */
8152 			    NULL,
8153 			    &save_ire->ire_max_frag,
8154 			    ire_fp_mp,			/* Fast Path header */
8155 			    dst_ill->ill_rq,		/* recv-from queue */
8156 			    dst_ill->ill_wq,		/* send-to queue */
8157 			    IRE_CACHE,			/* IRE type */
8158 			    res_mp,
8159 			    src_ipif,
8160 			    in_ill,			/* incoming ill */
8161 			    (sire != NULL) ?
8162 				sire->ire_mask : 0, 	/* Parent mask */
8163 			    (sire != NULL) ?
8164 				sire->ire_phandle : 0,  /* Parent handle */
8165 			    ipif_ire->ire_ihandle,	/* Interface handle */
8166 			    (sire != NULL) ? (sire->ire_flags &
8167 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8168 			    (sire != NULL) ?
8169 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8170 			    NULL,
8171 			    gcgrp);
8172 
8173 			if (ire == NULL) {
8174 				if (gcgrp != NULL) {
8175 					GCGRP_REFRELE(gcgrp);
8176 					gcgrp = NULL;
8177 				}
8178 				ire_refrele(ipif_ire);
8179 				ire_refrele(save_ire);
8180 				break;
8181 			}
8182 
8183 			/* reference now held by IRE */
8184 			gcgrp = NULL;
8185 
8186 			ire->ire_marks |= ire_marks;
8187 
8188 			/*
8189 			 * Prevent sire and ipif_ire from getting deleted.
8190 			 * The newly created ire is tied to both of them via
8191 			 * the phandle and ihandle respectively.
8192 			 */
8193 			if (sire != NULL) {
8194 				IRB_REFHOLD(sire->ire_bucket);
8195 				/* Has it been removed already ? */
8196 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8197 					IRB_REFRELE(sire->ire_bucket);
8198 					ire_refrele(ipif_ire);
8199 					ire_refrele(save_ire);
8200 					break;
8201 				}
8202 			}
8203 
8204 			IRB_REFHOLD(ipif_ire->ire_bucket);
8205 			/* Has it been removed already ? */
8206 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8207 				IRB_REFRELE(ipif_ire->ire_bucket);
8208 				if (sire != NULL)
8209 					IRB_REFRELE(sire->ire_bucket);
8210 				ire_refrele(ipif_ire);
8211 				ire_refrele(save_ire);
8212 				break;
8213 			}
8214 
8215 			xmit_mp = first_mp;
8216 			/*
8217 			 * In the case of multirouting, a copy
8218 			 * of the packet is done before its sending.
8219 			 * The copy is used to attempt another
8220 			 * route resolution, in a next loop.
8221 			 */
8222 			if (ire->ire_flags & RTF_MULTIRT) {
8223 				copy_mp = copymsg(first_mp);
8224 				if (copy_mp != NULL) {
8225 					xmit_mp = copy_mp;
8226 					MULTIRT_DEBUG_TAG(first_mp);
8227 				}
8228 			}
8229 			ire_add_then_send(q, ire, xmit_mp);
8230 			ire_refrele(save_ire);
8231 
8232 			/* Assert that sire is not deleted yet. */
8233 			if (sire != NULL) {
8234 				ASSERT(sire->ire_ptpn != NULL);
8235 				IRB_REFRELE(sire->ire_bucket);
8236 			}
8237 
8238 			/* Assert that ipif_ire is not deleted yet. */
8239 			ASSERT(ipif_ire->ire_ptpn != NULL);
8240 			IRB_REFRELE(ipif_ire->ire_bucket);
8241 			ire_refrele(ipif_ire);
8242 
8243 			/*
8244 			 * If copy_mp is not NULL, multirouting was
8245 			 * requested. We loop to initiate a next
8246 			 * route resolution attempt, starting from sire.
8247 			 */
8248 			if (copy_mp != NULL) {
8249 				/*
8250 				 * Search for the next unresolved
8251 				 * multirt route.
8252 				 */
8253 				copy_mp = NULL;
8254 				ipif_ire = NULL;
8255 				ire = NULL;
8256 				multirt_resolve_next = B_TRUE;
8257 				continue;
8258 			}
8259 			if (sire != NULL)
8260 				ire_refrele(sire);
8261 			ipif_refrele(src_ipif);
8262 			ill_refrele(dst_ill);
8263 			return;
8264 		}
8265 		case IRE_IF_NORESOLVER: {
8266 			/*
8267 			 * We have what we need to build an IRE_CACHE.
8268 			 *
8269 			 * Create a new res_mp with the IP gateway address
8270 			 * in destination address in the DLPI hdr if the
8271 			 * physical length is exactly 4 bytes.
8272 			 */
8273 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8274 				uchar_t *addr;
8275 
8276 				if (gw)
8277 					addr = (uchar_t *)&gw;
8278 				else
8279 					addr = (uchar_t *)&dst;
8280 
8281 				res_mp = ill_dlur_gen(addr,
8282 				    dst_ill->ill_phys_addr_length,
8283 				    dst_ill->ill_sap,
8284 				    dst_ill->ill_sap_length);
8285 
8286 				if (res_mp == NULL) {
8287 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8288 					break;
8289 				}
8290 			} else {
8291 				res_mp = NULL;
8292 			}
8293 
8294 			/*
8295 			 * TSol note: We are creating the ire cache for the
8296 			 * destination 'dst'. If 'dst' is offlink, going
8297 			 * through the first hop 'gw', the security attributes
8298 			 * of 'dst' must be set to point to the gateway
8299 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8300 			 * is possible that 'dst' is a potential gateway that is
8301 			 * referenced by some route that has some security
8302 			 * attributes. Thus in the former case, we need to do a
8303 			 * gcgrp_lookup of 'gw' while in the latter case we
8304 			 * need to do gcgrp_lookup of 'dst' itself.
8305 			 */
8306 			ga.ga_af = AF_INET;
8307 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8308 			    &ga.ga_addr);
8309 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8310 
8311 			ire = ire_create(
8312 			    (uchar_t *)&dst,		/* dest address */
8313 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8314 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8315 			    (uchar_t *)&gw,		/* gateway address */
8316 			    NULL,
8317 			    &save_ire->ire_max_frag,
8318 			    NULL,			/* Fast Path header */
8319 			    dst_ill->ill_rq,		/* recv-from queue */
8320 			    dst_ill->ill_wq,		/* send-to queue */
8321 			    IRE_CACHE,
8322 			    res_mp,
8323 			    src_ipif,
8324 			    in_ill,			/* Incoming ill */
8325 			    save_ire->ire_mask,		/* Parent mask */
8326 			    (sire != NULL) ?		/* Parent handle */
8327 				sire->ire_phandle : 0,
8328 			    save_ire->ire_ihandle,	/* Interface handle */
8329 			    (sire != NULL) ? sire->ire_flags &
8330 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8331 			    &(save_ire->ire_uinfo),
8332 			    NULL,
8333 			    gcgrp);
8334 
8335 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8336 				freeb(res_mp);
8337 
8338 			if (ire == NULL) {
8339 				if (gcgrp != NULL) {
8340 					GCGRP_REFRELE(gcgrp);
8341 					gcgrp = NULL;
8342 				}
8343 				ire_refrele(save_ire);
8344 				break;
8345 			}
8346 
8347 			/* reference now held by IRE */
8348 			gcgrp = NULL;
8349 
8350 			ire->ire_marks |= ire_marks;
8351 
8352 			/* Prevent save_ire from getting deleted */
8353 			IRB_REFHOLD(save_ire->ire_bucket);
8354 			/* Has it been removed already ? */
8355 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8356 				IRB_REFRELE(save_ire->ire_bucket);
8357 				ire_refrele(save_ire);
8358 				break;
8359 			}
8360 
8361 			/*
8362 			 * In the case of multirouting, a copy
8363 			 * of the packet is made before it is sent.
8364 			 * The copy is used in the next
8365 			 * loop to attempt another resolution.
8366 			 */
8367 			xmit_mp = first_mp;
8368 			if ((sire != NULL) &&
8369 			    (sire->ire_flags & RTF_MULTIRT)) {
8370 				copy_mp = copymsg(first_mp);
8371 				if (copy_mp != NULL) {
8372 					xmit_mp = copy_mp;
8373 					MULTIRT_DEBUG_TAG(first_mp);
8374 				}
8375 			}
8376 			ire_add_then_send(q, ire, xmit_mp);
8377 
8378 			/* Assert that it is not deleted yet. */
8379 			ASSERT(save_ire->ire_ptpn != NULL);
8380 			IRB_REFRELE(save_ire->ire_bucket);
8381 			ire_refrele(save_ire);
8382 
8383 			if (copy_mp != NULL) {
8384 				/*
8385 				 * If we found a (no)resolver, we ignore any
8386 				 * trailing top priority IRE_CACHE in further
8387 				 * loops. This ensures that we do not omit any
8388 				 * (no)resolver.
8389 				 * This IRE_CACHE, if any, will be processed
8390 				 * by another thread entering ip_newroute().
8391 				 * IRE_CACHE entries, if any, will be processed
8392 				 * by another thread entering ip_newroute(),
8393 				 * (upon resolver response, for instance).
8394 				 * This aims to force parallel multirt
8395 				 * resolutions as soon as a packet must be sent.
8396 				 * In the best case, after the tx of only one
8397 				 * packet, all reachable routes are resolved.
8398 				 * Otherwise, the resolution of all RTF_MULTIRT
8399 				 * routes would require several emissions.
8400 				 */
8401 				multirt_flags &= ~MULTIRT_CACHEGW;
8402 
8403 				/*
8404 				 * Search for the next unresolved multirt
8405 				 * route.
8406 				 */
8407 				copy_mp = NULL;
8408 				save_ire = NULL;
8409 				ire = NULL;
8410 				multirt_resolve_next = B_TRUE;
8411 				continue;
8412 			}
8413 
8414 			/*
8415 			 * Don't need sire anymore
8416 			 */
8417 			if (sire != NULL)
8418 				ire_refrele(sire);
8419 
8420 			ipif_refrele(src_ipif);
8421 			ill_refrele(dst_ill);
8422 			return;
8423 		}
8424 		case IRE_IF_RESOLVER:
8425 			/*
8426 			 * We can't build an IRE_CACHE yet, but at least we
8427 			 * found a resolver that can help.
8428 			 */
8429 			res_mp = dst_ill->ill_resolver_mp;
8430 			if (!OK_RESOLVER_MP(res_mp))
8431 				break;
8432 
8433 			/*
8434 			 * To be at this point in the code with a non-zero gw
8435 			 * means that dst is reachable through a gateway that
8436 			 * we have never resolved.  By changing dst to the gw
8437 			 * addr we resolve the gateway first.
8438 			 * When ire_add_then_send() tries to put the IP dg
8439 			 * to dst, it will reenter ip_newroute() at which
8440 			 * time we will find the IRE_CACHE for the gw and
8441 			 * create another IRE_CACHE in case IRE_CACHE above.
8442 			 */
8443 			if (gw != INADDR_ANY) {
8444 				/*
8445 				 * The source ipif that was determined above was
8446 				 * relative to the destination address, not the
8447 				 * gateway's. If src_ipif was not taken out of
8448 				 * the IRE_IF_RESOLVER entry, we'll need to call
8449 				 * ipif_select_source() again.
8450 				 */
8451 				if (src_ipif != ire->ire_ipif) {
8452 					ipif_refrele(src_ipif);
8453 					src_ipif = ipif_select_source(dst_ill,
8454 					    gw, zoneid);
8455 					if (src_ipif == NULL) {
8456 						if (ip_debug > 2) {
8457 							pr_addr_dbg(
8458 							    "ip_newroute: no "
8459 							    "src for gw %s ",
8460 							    AF_INET, &gw);
8461 							printf("through "
8462 							    "interface %s\n",
8463 							    dst_ill->ill_name);
8464 						}
8465 						goto icmp_err_ret;
8466 					}
8467 				}
8468 				save_dst = dst;
8469 				dst = gw;
8470 				gw = INADDR_ANY;
8471 			}
8472 
8473 			/*
8474 			 * We obtain a partial IRE_CACHE which we will pass
8475 			 * along with the resolver query.  When the response
8476 			 * comes back it will be there ready for us to add.
8477 			 * The ire_max_frag is atomically set under the
8478 			 * irebucket lock in ire_add_v[46].
8479 			 */
8480 
8481 			ire = ire_create_mp(
8482 			    (uchar_t *)&dst,		/* dest address */
8483 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8484 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8485 			    (uchar_t *)&gw,		/* gateway address */
8486 			    NULL,			/* no in_src_addr */
8487 			    NULL,			/* ire_max_frag */
8488 			    NULL,			/* Fast Path header */
8489 			    dst_ill->ill_rq,		/* recv-from queue */
8490 			    dst_ill->ill_wq,		/* send-to queue */
8491 			    IRE_CACHE,
8492 			    NULL,
8493 			    src_ipif,			/* Interface ipif */
8494 			    in_ill,			/* Incoming ILL */
8495 			    save_ire->ire_mask,		/* Parent mask */
8496 			    0,
8497 			    save_ire->ire_ihandle,	/* Interface handle */
8498 			    0,				/* flags if any */
8499 			    &(save_ire->ire_uinfo),
8500 			    NULL,
8501 			    NULL);
8502 
8503 			if (ire == NULL) {
8504 				ire_refrele(save_ire);
8505 				break;
8506 			}
8507 
8508 			if ((sire != NULL) &&
8509 			    (sire->ire_flags & RTF_MULTIRT)) {
8510 				copy_mp = copymsg(first_mp);
8511 				if (copy_mp != NULL)
8512 					MULTIRT_DEBUG_TAG(copy_mp);
8513 			}
8514 
8515 			ire->ire_marks |= ire_marks;
8516 
8517 			/*
8518 			 * Construct message chain for the resolver
8519 			 * of the form:
8520 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8521 			 * Packet could contain a IPSEC_OUT mp.
8522 			 *
8523 			 * NOTE : ire will be added later when the response
8524 			 * comes back from ARP. If the response does not
8525 			 * come back, ARP frees the packet. For this reason,
8526 			 * we can't REFHOLD the bucket of save_ire to prevent
8527 			 * deletions. We may not be able to REFRELE the bucket
8528 			 * if the response never comes back. Thus, before
8529 			 * adding the ire, ire_add_v4 will make sure that the
8530 			 * interface route does not get deleted. This is the
8531 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8532 			 * where we can always prevent deletions because of
8533 			 * the synchronous nature of adding IRES i.e
8534 			 * ire_add_then_send is called after creating the IRE.
8535 			 */
8536 			ASSERT(ire->ire_mp != NULL);
8537 			ire->ire_mp->b_cont = first_mp;
8538 			/* Have saved_mp handy, for cleanup if canput fails */
8539 			saved_mp = mp;
8540 			mp = copyb(res_mp);
8541 			ASSERT(mp != NULL);
8542 			linkb(mp, ire->ire_mp);
8543 
8544 
8545 			/*
8546 			 * Fill in the source and dest addrs for the resolver.
8547 			 * NOTE: this depends on memory layouts imposed by
8548 			 * ill_init().
8549 			 */
8550 			areq = (areq_t *)mp->b_rptr;
8551 			addrp = (ipaddr_t *)((char *)areq +
8552 			    areq->areq_sender_addr_offset);
8553 			if (do_attach_ill) {
8554 				/*
8555 				 * This is bind to no failover case.
8556 				 * arp packet also must go out on attach_ill.
8557 				 */
8558 				ASSERT(ipha->ipha_src != NULL);
8559 				*addrp = ipha->ipha_src;
8560 			} else {
8561 				*addrp = save_ire->ire_src_addr;
8562 			}
8563 
8564 			ire_refrele(save_ire);
8565 			addrp = (ipaddr_t *)((char *)areq +
8566 			    areq->areq_target_addr_offset);
8567 			*addrp = dst;
8568 			/* Up to the resolver. */
8569 			if (canputnext(dst_ill->ill_rq) &&
8570 			    !(dst_ill->ill_arp_closing)) {
8571 				putnext(dst_ill->ill_rq, mp);
8572 				ire = NULL;
8573 				if (copy_mp != NULL) {
8574 					/*
8575 					 * If we found a resolver, we ignore
8576 					 * any trailing top priority IRE_CACHE
8577 					 * in the further loops. This ensures
8578 					 * that we do not omit any resolver.
8579 					 * IRE_CACHE entries, if any, will be
8580 					 * processed next time we enter
8581 					 * ip_newroute().
8582 					 */
8583 					multirt_flags &= ~MULTIRT_CACHEGW;
8584 					/*
8585 					 * Search for the next unresolved
8586 					 * multirt route.
8587 					 */
8588 					first_mp = copy_mp;
8589 					copy_mp = NULL;
8590 					/* Prepare the next resolution loop. */
8591 					mp = first_mp;
8592 					EXTRACT_PKT_MP(mp, first_mp,
8593 					    mctl_present);
8594 					if (mctl_present)
8595 						io = (ipsec_out_t *)
8596 						    first_mp->b_rptr;
8597 					ipha = (ipha_t *)mp->b_rptr;
8598 
8599 					ASSERT(sire != NULL);
8600 
8601 					dst = save_dst;
8602 					multirt_resolve_next = B_TRUE;
8603 					continue;
8604 				}
8605 
8606 				if (sire != NULL)
8607 					ire_refrele(sire);
8608 
8609 				/*
8610 				 * The response will come back in ip_wput
8611 				 * with db_type IRE_DB_TYPE.
8612 				 */
8613 				ipif_refrele(src_ipif);
8614 				ill_refrele(dst_ill);
8615 				return;
8616 			} else {
8617 				/* Prepare for cleanup */
8618 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8619 				    mp);
8620 				mp->b_cont = NULL;
8621 				freeb(mp); /* areq */
8622 				/*
8623 				 * this is an ire that is not added to the
8624 				 * cache. ire_freemblk will handle the release
8625 				 * of any resources associated with the ire.
8626 				 */
8627 				ire_delete(ire); /* ire_mp */
8628 				mp = saved_mp; /* pkt */
8629 				ire = NULL;
8630 				if (copy_mp != NULL) {
8631 					MULTIRT_DEBUG_UNTAG(copy_mp);
8632 					freemsg(copy_mp);
8633 					copy_mp = NULL;
8634 				}
8635 				break;
8636 			}
8637 		default:
8638 			break;
8639 		}
8640 	} while (multirt_resolve_next);
8641 
8642 	ip1dbg(("ip_newroute: dropped\n"));
8643 	/* Did this packet originate externally? */
8644 	if (mp->b_prev) {
8645 		mp->b_next = NULL;
8646 		mp->b_prev = NULL;
8647 		BUMP_MIB(&ip_mib, ipInDiscards);
8648 	} else {
8649 		BUMP_MIB(&ip_mib, ipOutDiscards);
8650 	}
8651 	ASSERT(copy_mp == NULL);
8652 	MULTIRT_DEBUG_UNTAG(first_mp);
8653 	freemsg(first_mp);
8654 	if (ire != NULL)
8655 		ire_refrele(ire);
8656 	if (sire != NULL)
8657 		ire_refrele(sire);
8658 	if (src_ipif != NULL)
8659 		ipif_refrele(src_ipif);
8660 	if (dst_ill != NULL)
8661 		ill_refrele(dst_ill);
8662 	return;
8663 
8664 icmp_err_ret:
8665 	ip1dbg(("ip_newroute: no route\n"));
8666 	if (src_ipif != NULL)
8667 		ipif_refrele(src_ipif);
8668 	if (dst_ill != NULL)
8669 		ill_refrele(dst_ill);
8670 	if (sire != NULL)
8671 		ire_refrele(sire);
8672 	/* Did this packet originate externally? */
8673 	if (mp->b_prev) {
8674 		mp->b_next = NULL;
8675 		mp->b_prev = NULL;
8676 		/* XXX ipInNoRoutes */
8677 		q = WR(q);
8678 	} else {
8679 		/*
8680 		 * Since ip_wput() isn't close to finished, we fill
8681 		 * in enough of the header for credible error reporting.
8682 		 */
8683 		if (ip_hdr_complete(ipha, zoneid)) {
8684 			/* Failed */
8685 			MULTIRT_DEBUG_UNTAG(first_mp);
8686 			freemsg(first_mp);
8687 			if (ire != NULL)
8688 				ire_refrele(ire);
8689 			return;
8690 		}
8691 	}
8692 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8693 
8694 	/*
8695 	 * At this point we will have ire only if RTF_BLACKHOLE
8696 	 * or RTF_REJECT flags are set on the IRE. It will not
8697 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8698 	 */
8699 	if (ire != NULL) {
8700 		if (ire->ire_flags & RTF_BLACKHOLE) {
8701 			ire_refrele(ire);
8702 			MULTIRT_DEBUG_UNTAG(first_mp);
8703 			freemsg(first_mp);
8704 			return;
8705 		}
8706 		ire_refrele(ire);
8707 	}
8708 	if (ip_source_routed(ipha)) {
8709 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8710 		    zoneid);
8711 		return;
8712 	}
8713 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
8714 }
8715 
8716 /*
8717  * IPv4 -
8718  * ip_newroute_ipif is called by ip_wput_multicast and
8719  * ip_rput_forward_multicast whenever we need to send
8720  * out a packet to a destination address for which we do not have specific
8721  * routing information. It is used when the packet will be sent out
8722  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8723  * socket option is set or icmp error message wants to go out on a particular
8724  * interface for a unicast packet.
8725  *
8726  * In most cases, the destination address is resolved thanks to the ipif
8727  * intrinsic resolver. However, there are some cases where the call to
8728  * ip_newroute_ipif must take into account the potential presence of
8729  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8730  * that uses the interface. This is specified through flags,
8731  * which can be a combination of:
8732  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8733  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8734  *   and flags. Additionally, the packet source address has to be set to
8735  *   the specified address. The caller is thus expected to set this flag
8736  *   if the packet has no specific source address yet.
8737  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8738  *   flag, the resulting ire will inherit the flag. All unresolved routes
8739  *   to the destination must be explored in the same call to
8740  *   ip_newroute_ipif().
8741  */
8742 static void
8743 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8744     conn_t *connp, uint32_t flags, zoneid_t zoneid)
8745 {
8746 	areq_t	*areq;
8747 	ire_t	*ire = NULL;
8748 	mblk_t	*res_mp;
8749 	ipaddr_t *addrp;
8750 	mblk_t *first_mp;
8751 	ire_t	*save_ire = NULL;
8752 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8753 	ipif_t	*src_ipif = NULL;
8754 	ushort_t ire_marks = 0;
8755 	ill_t	*dst_ill = NULL;
8756 	boolean_t mctl_present;
8757 	ipsec_out_t *io;
8758 	ipha_t *ipha;
8759 	int	ihandle = 0;
8760 	mblk_t	*saved_mp;
8761 	ire_t   *fire = NULL;
8762 	mblk_t  *copy_mp = NULL;
8763 	boolean_t multirt_resolve_next;
8764 	ipaddr_t ipha_dst;
8765 
8766 	/*
8767 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8768 	 * here for uniformity
8769 	 */
8770 	ipif_refhold(ipif);
8771 
8772 	/*
8773 	 * This loop is run only once in most cases.
8774 	 * We loop to resolve further routes only when the destination
8775 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8776 	 */
8777 	do {
8778 		if (dst_ill != NULL) {
8779 			ill_refrele(dst_ill);
8780 			dst_ill = NULL;
8781 		}
8782 		if (src_ipif != NULL) {
8783 			ipif_refrele(src_ipif);
8784 			src_ipif = NULL;
8785 		}
8786 		multirt_resolve_next = B_FALSE;
8787 
8788 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8789 		    ipif->ipif_ill->ill_name));
8790 
8791 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8792 		if (mctl_present)
8793 			io = (ipsec_out_t *)first_mp->b_rptr;
8794 
8795 		ipha = (ipha_t *)mp->b_rptr;
8796 
8797 		/*
8798 		 * Save the packet destination address, we may need it after
8799 		 * the packet has been consumed.
8800 		 */
8801 		ipha_dst = ipha->ipha_dst;
8802 
8803 		/*
8804 		 * If the interface is a pt-pt interface we look for an
8805 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8806 		 * local_address and the pt-pt destination address. Otherwise
8807 		 * we just match the local address.
8808 		 * NOTE: dst could be different than ipha->ipha_dst in case
8809 		 * of sending igmp multicast packets over a point-to-point
8810 		 * connection.
8811 		 * Thus we must be careful enough to check ipha_dst to be a
8812 		 * multicast address, otherwise it will take xmit_if path for
8813 		 * multicast packets resulting into kernel stack overflow by
8814 		 * repeated calls to ip_newroute_ipif from ire_send().
8815 		 */
8816 		if (CLASSD(ipha_dst) &&
8817 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8818 			goto err_ret;
8819 		}
8820 
8821 		/*
8822 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8823 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8824 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8825 		 * propagate its flags to the new ire.
8826 		 */
8827 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8828 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8829 			ip2dbg(("ip_newroute_ipif: "
8830 			    "ipif_lookup_multi_ire("
8831 			    "ipif %p, dst %08x) = fire %p\n",
8832 			    (void *)ipif, ntohl(dst), (void *)fire));
8833 		}
8834 
8835 		if (mctl_present && io->ipsec_out_attach_if) {
8836 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8837 			    io->ipsec_out_ill_index, B_FALSE);
8838 
8839 			/* Failure case frees things for us. */
8840 			if (attach_ill == NULL) {
8841 				ipif_refrele(ipif);
8842 				if (fire != NULL)
8843 					ire_refrele(fire);
8844 				return;
8845 			}
8846 
8847 			/*
8848 			 * Check if we need an ire that will not be
8849 			 * looked up by anybody else i.e. HIDDEN.
8850 			 */
8851 			if (ill_is_probeonly(attach_ill)) {
8852 				ire_marks = IRE_MARK_HIDDEN;
8853 			}
8854 			/*
8855 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8856 			 * case.
8857 			 */
8858 			dst_ill = ipif->ipif_ill;
8859 			/* attach_ill has been refheld by ip_grab_attach_ill */
8860 			ASSERT(dst_ill == attach_ill);
8861 		} else {
8862 			/*
8863 			 * If this is set by IP_XMIT_IF, then make sure that
8864 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8865 			 * specified ill.
8866 			 */
8867 			ASSERT((connp == NULL) ||
8868 			    (connp->conn_xmit_if_ill == NULL) ||
8869 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8870 			/*
8871 			 * If the interface belongs to an interface group,
8872 			 * make sure the next possible interface in the group
8873 			 * is used.  This encourages load spreading among
8874 			 * peers in an interface group.
8875 			 * Note: load spreading is disabled for RTF_MULTIRT
8876 			 * routes.
8877 			 */
8878 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8879 			    (fire->ire_flags & RTF_MULTIRT)) {
8880 				/*
8881 				 * Don't perform outbound load spreading
8882 				 * in the case of an RTF_MULTIRT issued route,
8883 				 * we actually typically want to replicate
8884 				 * outgoing packets through particular
8885 				 * interfaces.
8886 				 */
8887 				dst_ill = ipif->ipif_ill;
8888 				ill_refhold(dst_ill);
8889 			} else {
8890 				dst_ill = ip_newroute_get_dst_ill(
8891 				    ipif->ipif_ill);
8892 			}
8893 			if (dst_ill == NULL) {
8894 				if (ip_debug > 2) {
8895 					pr_addr_dbg("ip_newroute_ipif: "
8896 					    "no dst ill for dst %s\n",
8897 					    AF_INET, &dst);
8898 				}
8899 				goto err_ret;
8900 			}
8901 		}
8902 
8903 		/*
8904 		 * Pick a source address preferring non-deprecated ones.
8905 		 * Unlike ip_newroute, we don't do any source address
8906 		 * selection here since for multicast it really does not help
8907 		 * in inbound load spreading as in the unicast case.
8908 		 */
8909 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8910 		    (fire->ire_flags & RTF_SETSRC)) {
8911 			/*
8912 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8913 			 * on that interface. This ire has RTF_SETSRC flag, so
8914 			 * the source address of the packet must be changed.
8915 			 * Check that the ipif matching the requested source
8916 			 * address still exists.
8917 			 */
8918 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8919 			    zoneid, NULL, NULL, NULL, NULL);
8920 		}
8921 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8922 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
8923 		    ipif->ipif_zoneid != ALL_ZONES)) &&
8924 		    (src_ipif == NULL)) {
8925 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8926 			if (src_ipif == NULL) {
8927 				if (ip_debug > 2) {
8928 					/* ip1dbg */
8929 					pr_addr_dbg("ip_newroute_ipif: "
8930 					    "no src for dst %s",
8931 					    AF_INET, &dst);
8932 				}
8933 				ip1dbg((" through interface %s\n",
8934 				    dst_ill->ill_name));
8935 				goto err_ret;
8936 			}
8937 			ipif_refrele(ipif);
8938 			ipif = src_ipif;
8939 			ipif_refhold(ipif);
8940 		}
8941 		if (src_ipif == NULL) {
8942 			src_ipif = ipif;
8943 			ipif_refhold(src_ipif);
8944 		}
8945 
8946 		/*
8947 		 * Assign a source address while we have the conn.
8948 		 * We can't have ip_wput_ire pick a source address when the
8949 		 * packet returns from arp since conn_unspec_src might be set
8950 		 * and we loose the conn when going through arp.
8951 		 */
8952 		if (ipha->ipha_src == INADDR_ANY &&
8953 		    (connp == NULL || !connp->conn_unspec_src)) {
8954 			ipha->ipha_src = src_ipif->ipif_src_addr;
8955 		}
8956 
8957 		/*
8958 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8959 		 * interface does not have an interface ire.
8960 		 * Example: Thousands of mobileip PPP interfaces to mobile
8961 		 * nodes. We don't want to create interface ires because
8962 		 * packets from other mobile nodes must not take the route
8963 		 * via interface ires to the visiting mobile node without
8964 		 * going through the home agent, in absence of mobileip
8965 		 * route optimization.
8966 		 */
8967 		if (CLASSD(ipha_dst) && (connp == NULL ||
8968 		    connp->conn_xmit_if_ill == NULL)) {
8969 			/* ipif_to_ire returns an held ire */
8970 			ire = ipif_to_ire(ipif);
8971 			if (ire == NULL)
8972 				goto err_ret;
8973 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8974 				goto err_ret;
8975 			/*
8976 			 * ihandle is needed when the ire is added to
8977 			 * cache table.
8978 			 */
8979 			save_ire = ire;
8980 			ihandle = save_ire->ire_ihandle;
8981 
8982 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8983 			    "flags %04x\n",
8984 			    (void *)ire, (void *)ipif, flags));
8985 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8986 			    (fire->ire_flags & RTF_MULTIRT)) {
8987 				/*
8988 				 * As requested by flags, an IRE_OFFSUBNET was
8989 				 * looked up on that interface. This ire has
8990 				 * RTF_MULTIRT flag, so the resolution loop will
8991 				 * be re-entered to resolve additional routes on
8992 				 * other interfaces. For that purpose, a copy of
8993 				 * the packet is performed at this point.
8994 				 */
8995 				fire->ire_last_used_time = lbolt;
8996 				copy_mp = copymsg(first_mp);
8997 				if (copy_mp) {
8998 					MULTIRT_DEBUG_TAG(copy_mp);
8999 				}
9000 			}
9001 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9002 			    (fire->ire_flags & RTF_SETSRC)) {
9003 				/*
9004 				 * As requested by flags, an IRE_OFFSUBET was
9005 				 * looked up on that interface. This ire has
9006 				 * RTF_SETSRC flag, so the source address of the
9007 				 * packet must be changed.
9008 				 */
9009 				ipha->ipha_src = fire->ire_src_addr;
9010 			}
9011 		} else {
9012 			ASSERT((connp == NULL) ||
9013 			    (connp->conn_xmit_if_ill != NULL) ||
9014 			    (connp->conn_dontroute));
9015 			/*
9016 			 * The only ways we can come here are:
9017 			 * 1) IP_XMIT_IF socket option is set
9018 			 * 2) ICMP error message generated from
9019 			 *    ip_mrtun_forward() routine and it needs
9020 			 *    to go through the specified ill.
9021 			 * 3) SO_DONTROUTE socket option is set
9022 			 * In all cases, the new ire will not be added
9023 			 * into cache table.
9024 			 */
9025 			ire_marks |= IRE_MARK_NOADD;
9026 		}
9027 
9028 		switch (ipif->ipif_net_type) {
9029 		case IRE_IF_NORESOLVER: {
9030 			/* We have what we need to build an IRE_CACHE. */
9031 			mblk_t	*res_mp;
9032 
9033 			/*
9034 			 * Create a new res_mp with the
9035 			 * IP gateway address as destination address in the
9036 			 * DLPI hdr if the physical length is exactly 4 bytes.
9037 			 */
9038 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9039 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9040 				    dst_ill->ill_phys_addr_length,
9041 				    dst_ill->ill_sap,
9042 				    dst_ill->ill_sap_length);
9043 			} else {
9044 				/* use the value set in ip_ll_subnet_defaults */
9045 				res_mp = ill_dlur_gen(NULL,
9046 				    dst_ill->ill_phys_addr_length,
9047 				    dst_ill->ill_sap,
9048 				    dst_ill->ill_sap_length);
9049 			}
9050 
9051 			if (res_mp == NULL)
9052 				break;
9053 			/*
9054 			 * The new ire inherits the IRE_OFFSUBNET flags
9055 			 * and source address, if this was requested.
9056 			 */
9057 			ire = ire_create(
9058 			    (uchar_t *)&dst,		/* dest address */
9059 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9060 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9061 			    NULL,			/* gateway address */
9062 			    NULL,
9063 			    &ipif->ipif_mtu,
9064 			    NULL,			/* Fast Path header */
9065 			    dst_ill->ill_rq,		/* recv-from queue */
9066 			    dst_ill->ill_wq,		/* send-to queue */
9067 			    IRE_CACHE,
9068 			    res_mp,
9069 			    src_ipif,
9070 			    NULL,
9071 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9072 			    (fire != NULL) ?		/* Parent handle */
9073 				fire->ire_phandle : 0,
9074 			    ihandle,			/* Interface handle */
9075 			    (fire != NULL) ?
9076 				(fire->ire_flags &
9077 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9078 			    (save_ire == NULL ? &ire_uinfo_null :
9079 				&save_ire->ire_uinfo),
9080 			    NULL,
9081 			    NULL);
9082 
9083 			freeb(res_mp);
9084 
9085 			if (ire == NULL) {
9086 				if (save_ire != NULL)
9087 					ire_refrele(save_ire);
9088 				break;
9089 			}
9090 
9091 			ire->ire_marks |= ire_marks;
9092 
9093 			/*
9094 			 * If IRE_MARK_NOADD is set then we need to convert
9095 			 * the max_fragp to a useable value now. This is
9096 			 * normally done in ire_add_v[46]. We also need to
9097 			 * associate the ire with an nce (normally would be
9098 			 * done in ip_wput_nondata()).
9099 			 *
9100 			 * Note that IRE_MARK_NOADD packets created here
9101 			 * do not have a non-null ire_mp pointer. The null
9102 			 * value of ire_bucket indicates that they were
9103 			 * never added.
9104 			 */
9105 			if (ire->ire_marks & IRE_MARK_NOADD) {
9106 				uint_t  max_frag;
9107 
9108 				max_frag = *ire->ire_max_fragp;
9109 				ire->ire_max_fragp = NULL;
9110 				ire->ire_max_frag = max_frag;
9111 
9112 				if ((ire->ire_nce = ndp_lookup_v4(
9113 				    ire_to_ill(ire),
9114 				    (ire->ire_gateway_addr != INADDR_ANY ?
9115 				    &ire->ire_gateway_addr : &ire->ire_addr),
9116 				    B_FALSE)) == NULL) {
9117 					if (save_ire != NULL)
9118 						ire_refrele(save_ire);
9119 					break;
9120 				}
9121 				ASSERT(ire->ire_nce->nce_state ==
9122 				    ND_REACHABLE);
9123 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9124 			}
9125 
9126 			/* Prevent save_ire from getting deleted */
9127 			if (save_ire != NULL) {
9128 				IRB_REFHOLD(save_ire->ire_bucket);
9129 				/* Has it been removed already ? */
9130 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9131 					IRB_REFRELE(save_ire->ire_bucket);
9132 					ire_refrele(save_ire);
9133 					break;
9134 				}
9135 			}
9136 
9137 			ire_add_then_send(q, ire, first_mp);
9138 
9139 			/* Assert that save_ire is not deleted yet. */
9140 			if (save_ire != NULL) {
9141 				ASSERT(save_ire->ire_ptpn != NULL);
9142 				IRB_REFRELE(save_ire->ire_bucket);
9143 				ire_refrele(save_ire);
9144 				save_ire = NULL;
9145 			}
9146 			if (fire != NULL) {
9147 				ire_refrele(fire);
9148 				fire = NULL;
9149 			}
9150 
9151 			/*
9152 			 * the resolution loop is re-entered if this
9153 			 * was requested through flags and if we
9154 			 * actually are in a multirouting case.
9155 			 */
9156 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9157 				boolean_t need_resolve =
9158 				    ire_multirt_need_resolve(ipha_dst,
9159 					MBLK_GETLABEL(copy_mp));
9160 				if (!need_resolve) {
9161 					MULTIRT_DEBUG_UNTAG(copy_mp);
9162 					freemsg(copy_mp);
9163 					copy_mp = NULL;
9164 				} else {
9165 					/*
9166 					 * ipif_lookup_group() calls
9167 					 * ire_lookup_multi() that uses
9168 					 * ire_ftable_lookup() to find
9169 					 * an IRE_INTERFACE for the group.
9170 					 * In the multirt case,
9171 					 * ire_lookup_multi() then invokes
9172 					 * ire_multirt_lookup() to find
9173 					 * the next resolvable ire.
9174 					 * As a result, we obtain an new
9175 					 * interface, derived from the
9176 					 * next ire.
9177 					 */
9178 					ipif_refrele(ipif);
9179 					ipif = ipif_lookup_group(ipha_dst,
9180 					    zoneid);
9181 					ip2dbg(("ip_newroute_ipif: "
9182 					    "multirt dst %08x, ipif %p\n",
9183 					    htonl(dst), (void *)ipif));
9184 					if (ipif != NULL) {
9185 						mp = copy_mp;
9186 						copy_mp = NULL;
9187 						multirt_resolve_next = B_TRUE;
9188 						continue;
9189 					} else {
9190 						freemsg(copy_mp);
9191 					}
9192 				}
9193 			}
9194 			if (ipif != NULL)
9195 				ipif_refrele(ipif);
9196 			ill_refrele(dst_ill);
9197 			ipif_refrele(src_ipif);
9198 			return;
9199 		}
9200 		case IRE_IF_RESOLVER:
9201 			/*
9202 			 * We can't build an IRE_CACHE yet, but at least
9203 			 * we found a resolver that can help.
9204 			 */
9205 			res_mp = dst_ill->ill_resolver_mp;
9206 			if (!OK_RESOLVER_MP(res_mp))
9207 				break;
9208 
9209 			/*
9210 			 * We obtain a partial IRE_CACHE which we will pass
9211 			 * along with the resolver query.  When the response
9212 			 * comes back it will be there ready for us to add.
9213 			 * The new ire inherits the IRE_OFFSUBNET flags
9214 			 * and source address, if this was requested.
9215 			 * The ire_max_frag is atomically set under the
9216 			 * irebucket lock in ire_add_v[46]. Only in the
9217 			 * case of IRE_MARK_NOADD, we set it here itself.
9218 			 */
9219 			ire = ire_create_mp(
9220 			    (uchar_t *)&dst,		/* dest address */
9221 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9222 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9223 			    NULL,			/* gateway address */
9224 			    NULL,			/* no in_src_addr */
9225 			    (ire_marks & IRE_MARK_NOADD) ?
9226 				ipif->ipif_mtu : 0,	/* max_frag */
9227 			    NULL,			/* Fast path header */
9228 			    dst_ill->ill_rq,		/* recv-from queue */
9229 			    dst_ill->ill_wq,		/* send-to queue */
9230 			    IRE_CACHE,
9231 			    NULL,	/* let ire_nce_init figure res_mp out */
9232 			    src_ipif,
9233 			    NULL,
9234 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9235 			    (fire != NULL) ?		/* Parent handle */
9236 				fire->ire_phandle : 0,
9237 			    ihandle,			/* Interface handle */
9238 			    (fire != NULL) ?		/* flags if any */
9239 				(fire->ire_flags &
9240 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9241 			    (save_ire == NULL ? &ire_uinfo_null :
9242 				&save_ire->ire_uinfo),
9243 			    NULL,
9244 			    NULL);
9245 
9246 			if (save_ire != NULL) {
9247 				ire_refrele(save_ire);
9248 				save_ire = NULL;
9249 			}
9250 			if (ire == NULL)
9251 				break;
9252 
9253 			ire->ire_marks |= ire_marks;
9254 			/*
9255 			 * Construct message chain for the resolver of the
9256 			 * form:
9257 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9258 			 *
9259 			 * NOTE : ire will be added later when the response
9260 			 * comes back from ARP. If the response does not
9261 			 * come back, ARP frees the packet. For this reason,
9262 			 * we can't REFHOLD the bucket of save_ire to prevent
9263 			 * deletions. We may not be able to REFRELE the
9264 			 * bucket if the response never comes back.
9265 			 * Thus, before adding the ire, ire_add_v4 will make
9266 			 * sure that the interface route does not get deleted.
9267 			 * This is the only case unlike ip_newroute_v6,
9268 			 * ip_newroute_ipif_v6 where we can always prevent
9269 			 * deletions because ire_add_then_send is called after
9270 			 * creating the IRE.
9271 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9272 			 * does not add this IRE into the IRE CACHE.
9273 			 */
9274 			ASSERT(ire->ire_mp != NULL);
9275 			ire->ire_mp->b_cont = first_mp;
9276 			/* Have saved_mp handy, for cleanup if canput fails */
9277 			saved_mp = mp;
9278 			mp = copyb(res_mp);
9279 			ASSERT(mp != NULL);
9280 			linkb(mp, ire->ire_mp);
9281 
9282 			/*
9283 			 * Fill in the source and dest addrs for the resolver.
9284 			 * NOTE: this depends on memory layouts imposed by
9285 			 * ill_init().
9286 			 */
9287 			areq = (areq_t *)mp->b_rptr;
9288 			addrp = (ipaddr_t *)((char *)areq +
9289 			    areq->areq_sender_addr_offset);
9290 			*addrp = ire->ire_src_addr;
9291 			addrp = (ipaddr_t *)((char *)areq +
9292 			    areq->areq_target_addr_offset);
9293 			*addrp = dst;
9294 			/* Up to the resolver. */
9295 			if (canputnext(dst_ill->ill_rq) &&
9296 			    !(dst_ill->ill_arp_closing)) {
9297 				putnext(dst_ill->ill_rq, mp);
9298 				/*
9299 				 * The response will come back in ip_wput
9300 				 * with db_type IRE_DB_TYPE.
9301 				 */
9302 			} else {
9303 				mp->b_cont = NULL;
9304 				freeb(mp); /* areq */
9305 				ire_delete(ire); /* ire_mp */
9306 				saved_mp->b_next = NULL;
9307 				saved_mp->b_prev = NULL;
9308 				freemsg(first_mp); /* pkt */
9309 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9310 			}
9311 
9312 			if (fire != NULL) {
9313 				ire_refrele(fire);
9314 				fire = NULL;
9315 			}
9316 
9317 
9318 			/*
9319 			 * The resolution loop is re-entered if this was
9320 			 * requested through flags and we actually are
9321 			 * in a multirouting case.
9322 			 */
9323 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9324 				boolean_t need_resolve =
9325 				    ire_multirt_need_resolve(ipha_dst,
9326 					MBLK_GETLABEL(copy_mp));
9327 				if (!need_resolve) {
9328 					MULTIRT_DEBUG_UNTAG(copy_mp);
9329 					freemsg(copy_mp);
9330 					copy_mp = NULL;
9331 				} else {
9332 					/*
9333 					 * ipif_lookup_group() calls
9334 					 * ire_lookup_multi() that uses
9335 					 * ire_ftable_lookup() to find
9336 					 * an IRE_INTERFACE for the group.
9337 					 * In the multirt case,
9338 					 * ire_lookup_multi() then invokes
9339 					 * ire_multirt_lookup() to find
9340 					 * the next resolvable ire.
9341 					 * As a result, we obtain an new
9342 					 * interface, derived from the
9343 					 * next ire.
9344 					 */
9345 					ipif_refrele(ipif);
9346 					ipif = ipif_lookup_group(ipha_dst,
9347 					    zoneid);
9348 					if (ipif != NULL) {
9349 						mp = copy_mp;
9350 						copy_mp = NULL;
9351 						multirt_resolve_next = B_TRUE;
9352 						continue;
9353 					} else {
9354 						freemsg(copy_mp);
9355 					}
9356 				}
9357 			}
9358 			if (ipif != NULL)
9359 				ipif_refrele(ipif);
9360 			ill_refrele(dst_ill);
9361 			ipif_refrele(src_ipif);
9362 			return;
9363 		default:
9364 			break;
9365 		}
9366 	} while (multirt_resolve_next);
9367 
9368 err_ret:
9369 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9370 	if (fire != NULL)
9371 		ire_refrele(fire);
9372 	ipif_refrele(ipif);
9373 	/* Did this packet originate externally? */
9374 	if (dst_ill != NULL)
9375 		ill_refrele(dst_ill);
9376 	if (src_ipif != NULL)
9377 		ipif_refrele(src_ipif);
9378 	if (mp->b_prev || mp->b_next) {
9379 		mp->b_next = NULL;
9380 		mp->b_prev = NULL;
9381 	} else {
9382 		/*
9383 		 * Since ip_wput() isn't close to finished, we fill
9384 		 * in enough of the header for credible error reporting.
9385 		 */
9386 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9387 			/* Failed */
9388 			freemsg(first_mp);
9389 			if (ire != NULL)
9390 				ire_refrele(ire);
9391 			return;
9392 		}
9393 	}
9394 	/*
9395 	 * At this point we will have ire only if RTF_BLACKHOLE
9396 	 * or RTF_REJECT flags are set on the IRE. It will not
9397 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9398 	 */
9399 	if (ire != NULL) {
9400 		if (ire->ire_flags & RTF_BLACKHOLE) {
9401 			ire_refrele(ire);
9402 			freemsg(first_mp);
9403 			return;
9404 		}
9405 		ire_refrele(ire);
9406 	}
9407 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9408 }
9409 
9410 /* Name/Value Table Lookup Routine */
9411 char *
9412 ip_nv_lookup(nv_t *nv, int value)
9413 {
9414 	if (!nv)
9415 		return (NULL);
9416 	for (; nv->nv_name; nv++) {
9417 		if (nv->nv_value == value)
9418 			return (nv->nv_name);
9419 	}
9420 	return ("unknown");
9421 }
9422 
9423 /*
9424  * one day it can be patched to 1 from /etc/system for machines that have few
9425  * fast network interfaces feeding multiple cpus.
9426  */
9427 int ill_stream_putlocks = 0;
9428 
9429 /*
9430  * This is a module open, i.e. this is a control stream for access
9431  * to a DLPI device.  We allocate an ill_t as the instance data in
9432  * this case.
9433  */
9434 int
9435 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9436 {
9437 	uint32_t mem_cnt;
9438 	uint32_t cpu_cnt;
9439 	uint32_t min_cnt;
9440 	pgcnt_t mem_avail;
9441 	ill_t	*ill;
9442 	int	err;
9443 
9444 	/*
9445 	 * Prevent unprivileged processes from pushing IP so that
9446 	 * they can't send raw IP.
9447 	 */
9448 	if (secpolicy_net_rawaccess(credp) != 0)
9449 		return (EPERM);
9450 
9451 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9452 	q->q_ptr = WR(q)->q_ptr = ill;
9453 
9454 	/*
9455 	 * ill_init initializes the ill fields and then sends down
9456 	 * down a DL_INFO_REQ after calling qprocson.
9457 	 */
9458 	err = ill_init(q, ill);
9459 	if (err != 0) {
9460 		mi_free(ill);
9461 		q->q_ptr = NULL;
9462 		WR(q)->q_ptr = NULL;
9463 		return (err);
9464 	}
9465 
9466 	/* ill_init initializes the ipsq marking this thread as writer */
9467 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9468 	/* Wait for the DL_INFO_ACK */
9469 	mutex_enter(&ill->ill_lock);
9470 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9471 		/*
9472 		 * Return value of 0 indicates a pending signal.
9473 		 */
9474 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9475 		if (err == 0) {
9476 			mutex_exit(&ill->ill_lock);
9477 			(void) ip_close(q, 0);
9478 			return (EINTR);
9479 		}
9480 	}
9481 	mutex_exit(&ill->ill_lock);
9482 
9483 	/*
9484 	 * ip_rput_other could have set an error  in ill_error on
9485 	 * receipt of M_ERROR.
9486 	 */
9487 
9488 	err = ill->ill_error;
9489 	if (err != 0) {
9490 		(void) ip_close(q, 0);
9491 		return (err);
9492 	}
9493 
9494 	/*
9495 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9496 	 * size and the cpu speed of the machine. This is upper
9497 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9498 	 * and is lower bounded by the compile time value of
9499 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9500 	 * ip6_ire_max_bucket_cnt.
9501 	 */
9502 	mem_avail = kmem_avail();
9503 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9504 	    ip_cache_table_size / sizeof (ire_t);
9505 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9506 
9507 	min_cnt = MIN(cpu_cnt, mem_cnt);
9508 	if (min_cnt < ip_ire_min_bucket_cnt)
9509 		min_cnt = ip_ire_min_bucket_cnt;
9510 	if (ip_ire_max_bucket_cnt > min_cnt) {
9511 		ip_ire_max_bucket_cnt = min_cnt;
9512 	}
9513 
9514 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9515 	    ip6_cache_table_size / sizeof (ire_t);
9516 	min_cnt = MIN(cpu_cnt, mem_cnt);
9517 	if (min_cnt < ip6_ire_min_bucket_cnt)
9518 		min_cnt = ip6_ire_min_bucket_cnt;
9519 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9520 		ip6_ire_max_bucket_cnt = min_cnt;
9521 	}
9522 
9523 	ill->ill_credp = credp;
9524 	crhold(credp);
9525 
9526 	mutex_enter(&ip_mi_lock);
9527 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9528 	mutex_exit(&ip_mi_lock);
9529 	if (err) {
9530 		(void) ip_close(q, 0);
9531 		return (err);
9532 	}
9533 	return (0);
9534 }
9535 
9536 /* IP open routine. */
9537 int
9538 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9539 {
9540 	conn_t 		*connp;
9541 	major_t		maj;
9542 
9543 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9544 
9545 	/* Allow reopen. */
9546 	if (q->q_ptr != NULL)
9547 		return (0);
9548 
9549 	if (sflag & MODOPEN) {
9550 		/* This is a module open */
9551 		return (ip_modopen(q, devp, flag, sflag, credp));
9552 	}
9553 
9554 	/*
9555 	 * We are opening as a device. This is an IP client stream, and we
9556 	 * allocate an conn_t as the instance data.
9557 	 */
9558 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9559 	connp->conn_upq = q;
9560 	q->q_ptr = WR(q)->q_ptr = connp;
9561 
9562 	if (flag & SO_SOCKSTR)
9563 		connp->conn_flags |= IPCL_SOCKET;
9564 
9565 	/* Minor tells us which /dev entry was opened */
9566 	if (geteminor(*devp) == IPV6_MINOR) {
9567 		connp->conn_flags |= IPCL_ISV6;
9568 		connp->conn_af_isv6 = B_TRUE;
9569 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9570 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9571 	} else {
9572 		connp->conn_af_isv6 = B_FALSE;
9573 		connp->conn_pkt_isv6 = B_FALSE;
9574 	}
9575 
9576 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9577 		q->q_ptr = WR(q)->q_ptr = NULL;
9578 		CONN_DEC_REF(connp);
9579 		return (EBUSY);
9580 	}
9581 
9582 	maj = getemajor(*devp);
9583 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9584 
9585 	/*
9586 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9587 	 */
9588 	connp->conn_cred = credp;
9589 	crhold(connp->conn_cred);
9590 
9591 	/*
9592 	 * If the caller has the process-wide flag set, then default to MAC
9593 	 * exempt mode.  This allows read-down to unlabeled hosts.
9594 	 */
9595 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9596 		connp->conn_mac_exempt = B_TRUE;
9597 
9598 	connp->conn_zoneid = getzoneid();
9599 
9600 	/*
9601 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9602 	 * administrative ops.  In these cases, we just need a normal conn_t
9603 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9604 	 * an error will be returned.
9605 	 */
9606 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9607 		connp->conn_rq = q;
9608 		connp->conn_wq = WR(q);
9609 	} else {
9610 		connp->conn_ulp = IPPROTO_SCTP;
9611 		connp->conn_rq = connp->conn_wq = NULL;
9612 	}
9613 	/* Non-zero default values */
9614 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9615 
9616 	/*
9617 	 * Make the conn globally visible to walkers
9618 	 */
9619 	mutex_enter(&connp->conn_lock);
9620 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9621 	mutex_exit(&connp->conn_lock);
9622 	ASSERT(connp->conn_ref == 1);
9623 
9624 	qprocson(q);
9625 
9626 	return (0);
9627 }
9628 
9629 /*
9630  * Change q_qinfo based on the value of isv6.
9631  * This can not called on an ill queue.
9632  * Note that there is no race since either q_qinfo works for conn queues - it
9633  * is just an optimization to enter the best wput routine directly.
9634  */
9635 void
9636 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9637 {
9638 	ASSERT(q->q_flag & QREADR);
9639 	ASSERT(WR(q)->q_next == NULL);
9640 	ASSERT(q->q_ptr != NULL);
9641 
9642 	if (minor == IPV6_MINOR)  {
9643 		if (bump_mib)
9644 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9645 		q->q_qinfo = &rinit_ipv6;
9646 		WR(q)->q_qinfo = &winit_ipv6;
9647 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9648 	} else {
9649 		if (bump_mib)
9650 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9651 		q->q_qinfo = &iprinit;
9652 		WR(q)->q_qinfo = &ipwinit;
9653 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9654 	}
9655 
9656 }
9657 
9658 /*
9659  * See if IPsec needs loading because of the options in mp.
9660  */
9661 static boolean_t
9662 ipsec_opt_present(mblk_t *mp)
9663 {
9664 	uint8_t *optcp, *next_optcp, *opt_endcp;
9665 	struct opthdr *opt;
9666 	struct T_opthdr *topt;
9667 	int opthdr_len;
9668 	t_uscalar_t optname, optlevel;
9669 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9670 	ipsec_req_t *ipsr;
9671 
9672 	/*
9673 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9674 	 * return TRUE.
9675 	 */
9676 
9677 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9678 	opt_endcp = optcp + tor->OPT_length;
9679 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9680 		opthdr_len = sizeof (struct T_opthdr);
9681 	} else {		/* O_OPTMGMT_REQ */
9682 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9683 		opthdr_len = sizeof (struct opthdr);
9684 	}
9685 	for (; optcp < opt_endcp; optcp = next_optcp) {
9686 		if (optcp + opthdr_len > opt_endcp)
9687 			return (B_FALSE);	/* Not enough option header. */
9688 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9689 			topt = (struct T_opthdr *)optcp;
9690 			optlevel = topt->level;
9691 			optname = topt->name;
9692 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9693 		} else {
9694 			opt = (struct opthdr *)optcp;
9695 			optlevel = opt->level;
9696 			optname = opt->name;
9697 			next_optcp = optcp + opthdr_len +
9698 			    _TPI_ALIGN_OPT(opt->len);
9699 		}
9700 		if ((next_optcp < optcp) || /* wraparound pointer space */
9701 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9702 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9703 			return (B_FALSE); /* bad option buffer */
9704 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9705 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9706 			/*
9707 			 * Check to see if it's an all-bypass or all-zeroes
9708 			 * IPsec request.  Don't bother loading IPsec if
9709 			 * the socket doesn't want to use it.  (A good example
9710 			 * is a bypass request.)
9711 			 *
9712 			 * Basically, if any of the non-NEVER bits are set,
9713 			 * load IPsec.
9714 			 */
9715 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9716 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9717 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9718 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9719 			    != 0)
9720 				return (B_TRUE);
9721 		}
9722 	}
9723 	return (B_FALSE);
9724 }
9725 
9726 /*
9727  * If conn is is waiting for ipsec to finish loading, kick it.
9728  */
9729 /* ARGSUSED */
9730 static void
9731 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9732 {
9733 	t_scalar_t	optreq_prim;
9734 	mblk_t		*mp;
9735 	cred_t		*cr;
9736 	int		err = 0;
9737 
9738 	/*
9739 	 * This function is called, after ipsec loading is complete.
9740 	 * Since IP checks exclusively and atomically (i.e it prevents
9741 	 * ipsec load from completing until ip_optcom_req completes)
9742 	 * whether ipsec load is complete, there cannot be a race with IP
9743 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9744 	 */
9745 	mutex_enter(&connp->conn_lock);
9746 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9747 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9748 		mp = connp->conn_ipsec_opt_mp;
9749 		connp->conn_ipsec_opt_mp = NULL;
9750 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9751 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9752 		mutex_exit(&connp->conn_lock);
9753 
9754 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9755 
9756 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9757 		if (optreq_prim == T_OPTMGMT_REQ) {
9758 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9759 			    &ip_opt_obj);
9760 		} else {
9761 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9762 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9763 			    &ip_opt_obj);
9764 		}
9765 		if (err != EINPROGRESS)
9766 			CONN_OPER_PENDING_DONE(connp);
9767 		return;
9768 	}
9769 	mutex_exit(&connp->conn_lock);
9770 }
9771 
9772 /*
9773  * Called from the ipsec_loader thread, outside any perimeter, to tell
9774  * ip qenable any of the queues waiting for the ipsec loader to
9775  * complete.
9776  *
9777  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9778  * are done with this lock held, so it's guaranteed that none of the
9779  * links will change along the way.
9780  */
9781 void
9782 ip_ipsec_load_complete()
9783 {
9784 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9785 }
9786 
9787 /*
9788  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9789  * determines the grp on which it has to become exclusive, queues the mp
9790  * and sq draining restarts the optmgmt
9791  */
9792 static boolean_t
9793 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9794 {
9795 	conn_t *connp;
9796 
9797 	/*
9798 	 * Take IPsec requests and treat them special.
9799 	 */
9800 	if (ipsec_opt_present(mp)) {
9801 		/* First check if IPsec is loaded. */
9802 		mutex_enter(&ipsec_loader_lock);
9803 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9804 			mutex_exit(&ipsec_loader_lock);
9805 			return (B_FALSE);
9806 		}
9807 		connp = Q_TO_CONN(q);
9808 		mutex_enter(&connp->conn_lock);
9809 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9810 
9811 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9812 		connp->conn_ipsec_opt_mp = mp;
9813 		mutex_exit(&connp->conn_lock);
9814 		mutex_exit(&ipsec_loader_lock);
9815 
9816 		ipsec_loader_loadnow();
9817 		return (B_TRUE);
9818 	}
9819 	return (B_FALSE);
9820 }
9821 
9822 /*
9823  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9824  * all of them are copied to the conn_t. If the req is "zero", the policy is
9825  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9826  * fields.
9827  * We keep only the latest setting of the policy and thus policy setting
9828  * is not incremental/cumulative.
9829  *
9830  * Requests to set policies with multiple alternative actions will
9831  * go through a different API.
9832  */
9833 int
9834 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9835 {
9836 	uint_t ah_req = 0;
9837 	uint_t esp_req = 0;
9838 	uint_t se_req = 0;
9839 	ipsec_selkey_t sel;
9840 	ipsec_act_t *actp = NULL;
9841 	uint_t nact;
9842 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9843 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9844 	ipsec_policy_root_t *pr;
9845 	ipsec_policy_head_t *ph;
9846 	int fam;
9847 	boolean_t is_pol_reset;
9848 	int error = 0;
9849 
9850 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9851 
9852 	/*
9853 	 * The IP_SEC_OPT option does not allow variable length parameters,
9854 	 * hence a request cannot be NULL.
9855 	 */
9856 	if (req == NULL)
9857 		return (EINVAL);
9858 
9859 	ah_req = req->ipsr_ah_req;
9860 	esp_req = req->ipsr_esp_req;
9861 	se_req = req->ipsr_self_encap_req;
9862 
9863 	/*
9864 	 * Are we dealing with a request to reset the policy (i.e.
9865 	 * zero requests).
9866 	 */
9867 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9868 	    (esp_req & REQ_MASK) == 0 &&
9869 	    (se_req & REQ_MASK) == 0);
9870 
9871 	if (!is_pol_reset) {
9872 		/*
9873 		 * If we couldn't load IPsec, fail with "protocol
9874 		 * not supported".
9875 		 * IPsec may not have been loaded for a request with zero
9876 		 * policies, so we don't fail in this case.
9877 		 */
9878 		mutex_enter(&ipsec_loader_lock);
9879 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9880 			mutex_exit(&ipsec_loader_lock);
9881 			return (EPROTONOSUPPORT);
9882 		}
9883 		mutex_exit(&ipsec_loader_lock);
9884 
9885 		/*
9886 		 * Test for valid requests. Invalid algorithms
9887 		 * need to be tested by IPSEC code because new
9888 		 * algorithms can be added dynamically.
9889 		 */
9890 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9891 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9892 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9893 			return (EINVAL);
9894 		}
9895 
9896 		/*
9897 		 * Only privileged users can issue these
9898 		 * requests.
9899 		 */
9900 		if (((ah_req & IPSEC_PREF_NEVER) ||
9901 		    (esp_req & IPSEC_PREF_NEVER) ||
9902 		    (se_req & IPSEC_PREF_NEVER)) &&
9903 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9904 			return (EPERM);
9905 		}
9906 
9907 		/*
9908 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9909 		 * are mutually exclusive.
9910 		 */
9911 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9912 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9913 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9914 			/* Both of them are set */
9915 			return (EINVAL);
9916 		}
9917 	}
9918 
9919 	mutex_enter(&connp->conn_lock);
9920 
9921 	/*
9922 	 * If we have already cached policies in ip_bind_connected*(), don't
9923 	 * let them change now. We cache policies for connections
9924 	 * whose src,dst [addr, port] is known.  The exception to this is
9925 	 * tunnels.  Tunnels are allowed to change policies after having
9926 	 * become fully bound.
9927 	 */
9928 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
9929 		mutex_exit(&connp->conn_lock);
9930 		return (EINVAL);
9931 	}
9932 
9933 	/*
9934 	 * We have a zero policies, reset the connection policy if already
9935 	 * set. This will cause the connection to inherit the
9936 	 * global policy, if any.
9937 	 */
9938 	if (is_pol_reset) {
9939 		if (connp->conn_policy != NULL) {
9940 			IPPH_REFRELE(connp->conn_policy);
9941 			connp->conn_policy = NULL;
9942 		}
9943 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
9944 		connp->conn_in_enforce_policy = B_FALSE;
9945 		connp->conn_out_enforce_policy = B_FALSE;
9946 		mutex_exit(&connp->conn_lock);
9947 		return (0);
9948 	}
9949 
9950 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
9951 	if (ph == NULL)
9952 		goto enomem;
9953 
9954 	ipsec_actvec_from_req(req, &actp, &nact);
9955 	if (actp == NULL)
9956 		goto enomem;
9957 
9958 	/*
9959 	 * Always allocate IPv4 policy entries, since they can also
9960 	 * apply to ipv6 sockets being used in ipv4-compat mode.
9961 	 */
9962 	bzero(&sel, sizeof (sel));
9963 	sel.ipsl_valid = IPSL_IPV4;
9964 
9965 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9966 	if (pin4 == NULL)
9967 		goto enomem;
9968 
9969 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9970 	if (pout4 == NULL)
9971 		goto enomem;
9972 
9973 	if (connp->conn_pkt_isv6) {
9974 		/*
9975 		 * We're looking at a v6 socket, also allocate the
9976 		 * v6-specific entries...
9977 		 */
9978 		sel.ipsl_valid = IPSL_IPV6;
9979 		pin6 = ipsec_policy_create(&sel, actp, nact,
9980 		    IPSEC_PRIO_SOCKET);
9981 		if (pin6 == NULL)
9982 			goto enomem;
9983 
9984 		pout6 = ipsec_policy_create(&sel, actp, nact,
9985 		    IPSEC_PRIO_SOCKET);
9986 		if (pout6 == NULL)
9987 			goto enomem;
9988 
9989 		/*
9990 		 * .. and file them away in the right place.
9991 		 */
9992 		fam = IPSEC_AF_V6;
9993 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9994 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
9995 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
9996 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9997 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
9998 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
9999 	}
10000 
10001 	ipsec_actvec_free(actp, nact);
10002 
10003 	/*
10004 	 * File the v4 policies.
10005 	 */
10006 	fam = IPSEC_AF_V4;
10007 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10008 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10009 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10010 
10011 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10012 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10013 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10014 
10015 	/*
10016 	 * If the requests need security, set enforce_policy.
10017 	 * If the requests are IPSEC_PREF_NEVER, one should
10018 	 * still set conn_out_enforce_policy so that an ipsec_out
10019 	 * gets attached in ip_wput. This is needed so that
10020 	 * for connections that we don't cache policy in ip_bind,
10021 	 * if global policy matches in ip_wput_attach_policy, we
10022 	 * don't wrongly inherit global policy. Similarly, we need
10023 	 * to set conn_in_enforce_policy also so that we don't verify
10024 	 * policy wrongly.
10025 	 */
10026 	if ((ah_req & REQ_MASK) != 0 ||
10027 	    (esp_req & REQ_MASK) != 0 ||
10028 	    (se_req & REQ_MASK) != 0) {
10029 		connp->conn_in_enforce_policy = B_TRUE;
10030 		connp->conn_out_enforce_policy = B_TRUE;
10031 		connp->conn_flags |= IPCL_CHECK_POLICY;
10032 	}
10033 
10034 	/*
10035 	 * Tunnels are allowed to set policy after having been fully bound.
10036 	 * If that's the case, cache policy here.
10037 	 */
10038 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
10039 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
10040 
10041 	mutex_exit(&connp->conn_lock);
10042 	return (error);
10043 #undef REQ_MASK
10044 
10045 	/*
10046 	 * Common memory-allocation-failure exit path.
10047 	 */
10048 enomem:
10049 	mutex_exit(&connp->conn_lock);
10050 	if (actp != NULL)
10051 		ipsec_actvec_free(actp, nact);
10052 	if (pin4 != NULL)
10053 		IPPOL_REFRELE(pin4);
10054 	if (pout4 != NULL)
10055 		IPPOL_REFRELE(pout4);
10056 	if (pin6 != NULL)
10057 		IPPOL_REFRELE(pin6);
10058 	if (pout6 != NULL)
10059 		IPPOL_REFRELE(pout6);
10060 	return (ENOMEM);
10061 }
10062 
10063 /*
10064  * Only for options that pass in an IP addr. Currently only V4 options
10065  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10066  * So this function assumes level is IPPROTO_IP
10067  */
10068 int
10069 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10070     mblk_t *first_mp)
10071 {
10072 	ipif_t *ipif = NULL;
10073 	int error;
10074 	ill_t *ill;
10075 	int zoneid;
10076 
10077 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10078 
10079 	if (addr != INADDR_ANY || checkonly) {
10080 		ASSERT(connp != NULL);
10081 		zoneid = IPCL_ZONEID(connp);
10082 		if (option == IP_NEXTHOP) {
10083 			ipif = ipif_lookup_onlink_addr(addr, zoneid);
10084 		} else {
10085 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10086 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10087 			    &error);
10088 		}
10089 		if (ipif == NULL) {
10090 			if (error == EINPROGRESS)
10091 				return (error);
10092 			else if ((option == IP_MULTICAST_IF) ||
10093 			    (option == IP_NEXTHOP))
10094 				return (EHOSTUNREACH);
10095 			else
10096 				return (EINVAL);
10097 		} else if (checkonly) {
10098 			if (option == IP_MULTICAST_IF) {
10099 				ill = ipif->ipif_ill;
10100 				/* not supported by the virtual network iface */
10101 				if (IS_VNI(ill)) {
10102 					ipif_refrele(ipif);
10103 					return (EINVAL);
10104 				}
10105 			}
10106 			ipif_refrele(ipif);
10107 			return (0);
10108 		}
10109 		ill = ipif->ipif_ill;
10110 		mutex_enter(&connp->conn_lock);
10111 		mutex_enter(&ill->ill_lock);
10112 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10113 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10114 			mutex_exit(&ill->ill_lock);
10115 			mutex_exit(&connp->conn_lock);
10116 			ipif_refrele(ipif);
10117 			return (option == IP_MULTICAST_IF ?
10118 			    EHOSTUNREACH : EINVAL);
10119 		}
10120 	} else {
10121 		mutex_enter(&connp->conn_lock);
10122 	}
10123 
10124 	/* None of the options below are supported on the VNI */
10125 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10126 		mutex_exit(&ill->ill_lock);
10127 		mutex_exit(&connp->conn_lock);
10128 		ipif_refrele(ipif);
10129 		return (EINVAL);
10130 	}
10131 
10132 	switch (option) {
10133 	case IP_DONTFAILOVER_IF:
10134 		/*
10135 		 * This option is used by in.mpathd to ensure
10136 		 * that IPMP probe packets only go out on the
10137 		 * test interfaces. in.mpathd sets this option
10138 		 * on the non-failover interfaces.
10139 		 * For backward compatibility, this option
10140 		 * implicitly sets IP_MULTICAST_IF, as used
10141 		 * be done in bind(), so that ip_wput gets
10142 		 * this ipif to send mcast packets.
10143 		 */
10144 		if (ipif != NULL) {
10145 			ASSERT(addr != INADDR_ANY);
10146 			connp->conn_nofailover_ill = ipif->ipif_ill;
10147 			connp->conn_multicast_ipif = ipif;
10148 		} else {
10149 			ASSERT(addr == INADDR_ANY);
10150 			connp->conn_nofailover_ill = NULL;
10151 			connp->conn_multicast_ipif = NULL;
10152 		}
10153 		break;
10154 
10155 	case IP_MULTICAST_IF:
10156 		connp->conn_multicast_ipif = ipif;
10157 		break;
10158 	case IP_NEXTHOP:
10159 		connp->conn_nexthop_v4 = addr;
10160 		connp->conn_nexthop_set = B_TRUE;
10161 		break;
10162 	}
10163 
10164 	if (ipif != NULL) {
10165 		mutex_exit(&ill->ill_lock);
10166 		mutex_exit(&connp->conn_lock);
10167 		ipif_refrele(ipif);
10168 		return (0);
10169 	}
10170 	mutex_exit(&connp->conn_lock);
10171 	/* We succeded in cleared the option */
10172 	return (0);
10173 }
10174 
10175 /*
10176  * For options that pass in an ifindex specifying the ill. V6 options always
10177  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10178  */
10179 int
10180 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10181     int level, int option, mblk_t *first_mp)
10182 {
10183 	ill_t *ill = NULL;
10184 	int error = 0;
10185 
10186 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10187 	if (ifindex != 0) {
10188 		ASSERT(connp != NULL);
10189 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10190 		    first_mp, ip_restart_optmgmt, &error);
10191 		if (ill != NULL) {
10192 			if (checkonly) {
10193 				/* not supported by the virtual network iface */
10194 				if (IS_VNI(ill)) {
10195 					ill_refrele(ill);
10196 					return (EINVAL);
10197 				}
10198 				ill_refrele(ill);
10199 				return (0);
10200 			}
10201 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10202 			    0, NULL)) {
10203 				ill_refrele(ill);
10204 				ill = NULL;
10205 				mutex_enter(&connp->conn_lock);
10206 				goto setit;
10207 			}
10208 			mutex_enter(&connp->conn_lock);
10209 			mutex_enter(&ill->ill_lock);
10210 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10211 				mutex_exit(&ill->ill_lock);
10212 				mutex_exit(&connp->conn_lock);
10213 				ill_refrele(ill);
10214 				ill = NULL;
10215 				mutex_enter(&connp->conn_lock);
10216 			}
10217 			goto setit;
10218 		} else if (error == EINPROGRESS) {
10219 			return (error);
10220 		} else {
10221 			error = 0;
10222 		}
10223 	}
10224 	mutex_enter(&connp->conn_lock);
10225 setit:
10226 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10227 
10228 	/*
10229 	 * The options below assume that the ILL (if any) transmits and/or
10230 	 * receives traffic. Neither of which is true for the virtual network
10231 	 * interface, so fail setting these on a VNI.
10232 	 */
10233 	if (IS_VNI(ill)) {
10234 		ASSERT(ill != NULL);
10235 		mutex_exit(&ill->ill_lock);
10236 		mutex_exit(&connp->conn_lock);
10237 		ill_refrele(ill);
10238 		return (EINVAL);
10239 	}
10240 
10241 	if (level == IPPROTO_IP) {
10242 		switch (option) {
10243 		case IP_BOUND_IF:
10244 			connp->conn_incoming_ill = ill;
10245 			connp->conn_outgoing_ill = ill;
10246 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10247 			    0 : ifindex;
10248 			break;
10249 
10250 		case IP_XMIT_IF:
10251 			/*
10252 			 * Similar to IP_BOUND_IF, but this only
10253 			 * determines the outgoing interface for
10254 			 * unicast packets. Also no IRE_CACHE entry
10255 			 * is added for the destination of the
10256 			 * outgoing packets. This feature is needed
10257 			 * for mobile IP.
10258 			 */
10259 			connp->conn_xmit_if_ill = ill;
10260 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10261 			    0 : ifindex;
10262 			break;
10263 
10264 		case IP_MULTICAST_IF:
10265 			/*
10266 			 * This option is an internal special. The socket
10267 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10268 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10269 			 * specifies an ifindex and we try first on V6 ill's.
10270 			 * If we don't find one, we they try using on v4 ill's
10271 			 * intenally and we come here.
10272 			 */
10273 			if (!checkonly && ill != NULL) {
10274 				ipif_t	*ipif;
10275 				ipif = ill->ill_ipif;
10276 
10277 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10278 					mutex_exit(&ill->ill_lock);
10279 					mutex_exit(&connp->conn_lock);
10280 					ill_refrele(ill);
10281 					ill = NULL;
10282 					mutex_enter(&connp->conn_lock);
10283 				} else {
10284 					connp->conn_multicast_ipif = ipif;
10285 				}
10286 			}
10287 			break;
10288 		}
10289 	} else {
10290 		switch (option) {
10291 		case IPV6_BOUND_IF:
10292 			connp->conn_incoming_ill = ill;
10293 			connp->conn_outgoing_ill = ill;
10294 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10295 			    0 : ifindex;
10296 			break;
10297 
10298 		case IPV6_BOUND_PIF:
10299 			/*
10300 			 * Limit all transmit to this ill.
10301 			 * Unlike IPV6_BOUND_IF, using this option
10302 			 * prevents load spreading and failover from
10303 			 * happening when the interface is part of the
10304 			 * group. That's why we don't need to remember
10305 			 * the ifindex in orig_bound_ifindex as in
10306 			 * IPV6_BOUND_IF.
10307 			 */
10308 			connp->conn_outgoing_pill = ill;
10309 			break;
10310 
10311 		case IPV6_DONTFAILOVER_IF:
10312 			/*
10313 			 * This option is used by in.mpathd to ensure
10314 			 * that IPMP probe packets only go out on the
10315 			 * test interfaces. in.mpathd sets this option
10316 			 * on the non-failover interfaces.
10317 			 */
10318 			connp->conn_nofailover_ill = ill;
10319 			/*
10320 			 * For backward compatibility, this option
10321 			 * implicitly sets ip_multicast_ill as used in
10322 			 * IP_MULTICAST_IF so that ip_wput gets
10323 			 * this ipif to send mcast packets.
10324 			 */
10325 			connp->conn_multicast_ill = ill;
10326 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10327 			    0 : ifindex;
10328 			break;
10329 
10330 		case IPV6_MULTICAST_IF:
10331 			/*
10332 			 * Set conn_multicast_ill to be the IPv6 ill.
10333 			 * Set conn_multicast_ipif to be an IPv4 ipif
10334 			 * for ifindex to make IPv4 mapped addresses
10335 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10336 			 * Even if no IPv6 ill exists for the ifindex
10337 			 * we need to check for an IPv4 ifindex in order
10338 			 * for this to work with mapped addresses. In that
10339 			 * case only set conn_multicast_ipif.
10340 			 */
10341 			if (!checkonly) {
10342 				if (ifindex == 0) {
10343 					connp->conn_multicast_ill = NULL;
10344 					connp->conn_orig_multicast_ifindex = 0;
10345 					connp->conn_multicast_ipif = NULL;
10346 				} else if (ill != NULL) {
10347 					connp->conn_multicast_ill = ill;
10348 					connp->conn_orig_multicast_ifindex =
10349 					    ifindex;
10350 				}
10351 			}
10352 			break;
10353 		}
10354 	}
10355 
10356 	if (ill != NULL) {
10357 		mutex_exit(&ill->ill_lock);
10358 		mutex_exit(&connp->conn_lock);
10359 		ill_refrele(ill);
10360 		return (0);
10361 	}
10362 	mutex_exit(&connp->conn_lock);
10363 	/*
10364 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10365 	 * locate the ill and could not set the option (ifindex != 0)
10366 	 */
10367 	return (ifindex == 0 ? 0 : EINVAL);
10368 }
10369 
10370 /* This routine sets socket options. */
10371 /* ARGSUSED */
10372 int
10373 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10374     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10375     void *dummy, cred_t *cr, mblk_t *first_mp)
10376 {
10377 	int		*i1 = (int *)invalp;
10378 	conn_t		*connp = Q_TO_CONN(q);
10379 	int		error = 0;
10380 	boolean_t	checkonly;
10381 	ire_t		*ire;
10382 	boolean_t	found;
10383 
10384 	switch (optset_context) {
10385 
10386 	case SETFN_OPTCOM_CHECKONLY:
10387 		checkonly = B_TRUE;
10388 		/*
10389 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10390 		 * inlen != 0 implies value supplied and
10391 		 * 	we have to "pretend" to set it.
10392 		 * inlen == 0 implies that there is no
10393 		 * 	value part in T_CHECK request and just validation
10394 		 * done elsewhere should be enough, we just return here.
10395 		 */
10396 		if (inlen == 0) {
10397 			*outlenp = 0;
10398 			return (0);
10399 		}
10400 		break;
10401 	case SETFN_OPTCOM_NEGOTIATE:
10402 	case SETFN_UD_NEGOTIATE:
10403 	case SETFN_CONN_NEGOTIATE:
10404 		checkonly = B_FALSE;
10405 		break;
10406 	default:
10407 		/*
10408 		 * We should never get here
10409 		 */
10410 		*outlenp = 0;
10411 		return (EINVAL);
10412 	}
10413 
10414 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10415 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10416 
10417 	/*
10418 	 * For fixed length options, no sanity check
10419 	 * of passed in length is done. It is assumed *_optcom_req()
10420 	 * routines do the right thing.
10421 	 */
10422 
10423 	switch (level) {
10424 	case SOL_SOCKET:
10425 		/*
10426 		 * conn_lock protects the bitfields, and is used to
10427 		 * set the fields atomically.
10428 		 */
10429 		switch (name) {
10430 		case SO_BROADCAST:
10431 			if (!checkonly) {
10432 				/* TODO: use value someplace? */
10433 				mutex_enter(&connp->conn_lock);
10434 				connp->conn_broadcast = *i1 ? 1 : 0;
10435 				mutex_exit(&connp->conn_lock);
10436 			}
10437 			break;	/* goto sizeof (int) option return */
10438 		case SO_USELOOPBACK:
10439 			if (!checkonly) {
10440 				/* TODO: use value someplace? */
10441 				mutex_enter(&connp->conn_lock);
10442 				connp->conn_loopback = *i1 ? 1 : 0;
10443 				mutex_exit(&connp->conn_lock);
10444 			}
10445 			break;	/* goto sizeof (int) option return */
10446 		case SO_DONTROUTE:
10447 			if (!checkonly) {
10448 				mutex_enter(&connp->conn_lock);
10449 				connp->conn_dontroute = *i1 ? 1 : 0;
10450 				mutex_exit(&connp->conn_lock);
10451 			}
10452 			break;	/* goto sizeof (int) option return */
10453 		case SO_REUSEADDR:
10454 			if (!checkonly) {
10455 				mutex_enter(&connp->conn_lock);
10456 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10457 				mutex_exit(&connp->conn_lock);
10458 			}
10459 			break;	/* goto sizeof (int) option return */
10460 		case SO_PROTOTYPE:
10461 			if (!checkonly) {
10462 				mutex_enter(&connp->conn_lock);
10463 				connp->conn_proto = *i1;
10464 				mutex_exit(&connp->conn_lock);
10465 			}
10466 			break;	/* goto sizeof (int) option return */
10467 		case SO_ALLZONES:
10468 			if (!checkonly) {
10469 				mutex_enter(&connp->conn_lock);
10470 				if (IPCL_IS_BOUND(connp)) {
10471 					mutex_exit(&connp->conn_lock);
10472 					return (EINVAL);
10473 				}
10474 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10475 				mutex_exit(&connp->conn_lock);
10476 			}
10477 			break;	/* goto sizeof (int) option return */
10478 		case SO_ANON_MLP:
10479 			if (!checkonly) {
10480 				mutex_enter(&connp->conn_lock);
10481 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10482 				mutex_exit(&connp->conn_lock);
10483 			}
10484 			break;	/* goto sizeof (int) option return */
10485 		case SO_MAC_EXEMPT:
10486 			if (secpolicy_net_mac_aware(cr) != 0 ||
10487 			    IPCL_IS_BOUND(connp))
10488 				return (EACCES);
10489 			if (!checkonly) {
10490 				mutex_enter(&connp->conn_lock);
10491 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10492 				mutex_exit(&connp->conn_lock);
10493 			}
10494 			break;	/* goto sizeof (int) option return */
10495 		default:
10496 			/*
10497 			 * "soft" error (negative)
10498 			 * option not handled at this level
10499 			 * Note: Do not modify *outlenp
10500 			 */
10501 			return (-EINVAL);
10502 		}
10503 		break;
10504 	case IPPROTO_IP:
10505 		switch (name) {
10506 		case IP_NEXTHOP:
10507 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10508 				return (EPERM);
10509 			/* FALLTHRU */
10510 		case IP_MULTICAST_IF:
10511 		case IP_DONTFAILOVER_IF: {
10512 			ipaddr_t addr = *i1;
10513 
10514 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10515 			    first_mp);
10516 			if (error != 0)
10517 				return (error);
10518 			break;	/* goto sizeof (int) option return */
10519 		}
10520 
10521 		case IP_MULTICAST_TTL:
10522 			/* Recorded in transport above IP */
10523 			*outvalp = *invalp;
10524 			*outlenp = sizeof (uchar_t);
10525 			return (0);
10526 		case IP_MULTICAST_LOOP:
10527 			if (!checkonly) {
10528 				mutex_enter(&connp->conn_lock);
10529 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10530 				mutex_exit(&connp->conn_lock);
10531 			}
10532 			*outvalp = *invalp;
10533 			*outlenp = sizeof (uchar_t);
10534 			return (0);
10535 		case IP_ADD_MEMBERSHIP:
10536 		case MCAST_JOIN_GROUP:
10537 		case IP_DROP_MEMBERSHIP:
10538 		case MCAST_LEAVE_GROUP: {
10539 			struct ip_mreq *mreqp;
10540 			struct group_req *greqp;
10541 			ire_t *ire;
10542 			boolean_t done = B_FALSE;
10543 			ipaddr_t group, ifaddr;
10544 			struct sockaddr_in *sin;
10545 			uint32_t *ifindexp;
10546 			boolean_t mcast_opt = B_TRUE;
10547 			mcast_record_t fmode;
10548 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10549 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10550 
10551 			switch (name) {
10552 			case IP_ADD_MEMBERSHIP:
10553 				mcast_opt = B_FALSE;
10554 				/* FALLTHRU */
10555 			case MCAST_JOIN_GROUP:
10556 				fmode = MODE_IS_EXCLUDE;
10557 				optfn = ip_opt_add_group;
10558 				break;
10559 
10560 			case IP_DROP_MEMBERSHIP:
10561 				mcast_opt = B_FALSE;
10562 				/* FALLTHRU */
10563 			case MCAST_LEAVE_GROUP:
10564 				fmode = MODE_IS_INCLUDE;
10565 				optfn = ip_opt_delete_group;
10566 				break;
10567 			}
10568 
10569 			if (mcast_opt) {
10570 				greqp = (struct group_req *)i1;
10571 				sin = (struct sockaddr_in *)&greqp->gr_group;
10572 				if (sin->sin_family != AF_INET) {
10573 					*outlenp = 0;
10574 					return (ENOPROTOOPT);
10575 				}
10576 				group = (ipaddr_t)sin->sin_addr.s_addr;
10577 				ifaddr = INADDR_ANY;
10578 				ifindexp = &greqp->gr_interface;
10579 			} else {
10580 				mreqp = (struct ip_mreq *)i1;
10581 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10582 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10583 				ifindexp = NULL;
10584 			}
10585 
10586 			/*
10587 			 * In the multirouting case, we need to replicate
10588 			 * the request on all interfaces that will take part
10589 			 * in replication.  We do so because multirouting is
10590 			 * reflective, thus we will probably receive multi-
10591 			 * casts on those interfaces.
10592 			 * The ip_multirt_apply_membership() succeeds if the
10593 			 * operation succeeds on at least one interface.
10594 			 */
10595 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10596 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10597 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10598 			if (ire != NULL) {
10599 				if (ire->ire_flags & RTF_MULTIRT) {
10600 					error = ip_multirt_apply_membership(
10601 					    optfn, ire, connp, checkonly, group,
10602 					    fmode, INADDR_ANY, first_mp);
10603 					done = B_TRUE;
10604 				}
10605 				ire_refrele(ire);
10606 			}
10607 			if (!done) {
10608 				error = optfn(connp, checkonly, group, ifaddr,
10609 				    ifindexp, fmode, INADDR_ANY, first_mp);
10610 			}
10611 			if (error) {
10612 				/*
10613 				 * EINPROGRESS is a soft error, needs retry
10614 				 * so don't make *outlenp zero.
10615 				 */
10616 				if (error != EINPROGRESS)
10617 					*outlenp = 0;
10618 				return (error);
10619 			}
10620 			/* OK return - copy input buffer into output buffer */
10621 			if (invalp != outvalp) {
10622 				/* don't trust bcopy for identical src/dst */
10623 				bcopy(invalp, outvalp, inlen);
10624 			}
10625 			*outlenp = inlen;
10626 			return (0);
10627 		}
10628 		case IP_BLOCK_SOURCE:
10629 		case IP_UNBLOCK_SOURCE:
10630 		case IP_ADD_SOURCE_MEMBERSHIP:
10631 		case IP_DROP_SOURCE_MEMBERSHIP:
10632 		case MCAST_BLOCK_SOURCE:
10633 		case MCAST_UNBLOCK_SOURCE:
10634 		case MCAST_JOIN_SOURCE_GROUP:
10635 		case MCAST_LEAVE_SOURCE_GROUP: {
10636 			struct ip_mreq_source *imreqp;
10637 			struct group_source_req *gsreqp;
10638 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10639 			uint32_t ifindex = 0;
10640 			mcast_record_t fmode;
10641 			struct sockaddr_in *sin;
10642 			ire_t *ire;
10643 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10644 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10645 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10646 
10647 			switch (name) {
10648 			case IP_BLOCK_SOURCE:
10649 				mcast_opt = B_FALSE;
10650 				/* FALLTHRU */
10651 			case MCAST_BLOCK_SOURCE:
10652 				fmode = MODE_IS_EXCLUDE;
10653 				optfn = ip_opt_add_group;
10654 				break;
10655 
10656 			case IP_UNBLOCK_SOURCE:
10657 				mcast_opt = B_FALSE;
10658 				/* FALLTHRU */
10659 			case MCAST_UNBLOCK_SOURCE:
10660 				fmode = MODE_IS_EXCLUDE;
10661 				optfn = ip_opt_delete_group;
10662 				break;
10663 
10664 			case IP_ADD_SOURCE_MEMBERSHIP:
10665 				mcast_opt = B_FALSE;
10666 				/* FALLTHRU */
10667 			case MCAST_JOIN_SOURCE_GROUP:
10668 				fmode = MODE_IS_INCLUDE;
10669 				optfn = ip_opt_add_group;
10670 				break;
10671 
10672 			case IP_DROP_SOURCE_MEMBERSHIP:
10673 				mcast_opt = B_FALSE;
10674 				/* FALLTHRU */
10675 			case MCAST_LEAVE_SOURCE_GROUP:
10676 				fmode = MODE_IS_INCLUDE;
10677 				optfn = ip_opt_delete_group;
10678 				break;
10679 			}
10680 
10681 			if (mcast_opt) {
10682 				gsreqp = (struct group_source_req *)i1;
10683 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10684 					*outlenp = 0;
10685 					return (ENOPROTOOPT);
10686 				}
10687 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10688 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10689 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10690 				src = (ipaddr_t)sin->sin_addr.s_addr;
10691 				ifindex = gsreqp->gsr_interface;
10692 			} else {
10693 				imreqp = (struct ip_mreq_source *)i1;
10694 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10695 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10696 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10697 			}
10698 
10699 			/*
10700 			 * In the multirouting case, we need to replicate
10701 			 * the request as noted in the mcast cases above.
10702 			 */
10703 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10704 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10705 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10706 			if (ire != NULL) {
10707 				if (ire->ire_flags & RTF_MULTIRT) {
10708 					error = ip_multirt_apply_membership(
10709 					    optfn, ire, connp, checkonly, grp,
10710 					    fmode, src, first_mp);
10711 					done = B_TRUE;
10712 				}
10713 				ire_refrele(ire);
10714 			}
10715 			if (!done) {
10716 				error = optfn(connp, checkonly, grp, ifaddr,
10717 				    &ifindex, fmode, src, first_mp);
10718 			}
10719 			if (error != 0) {
10720 				/*
10721 				 * EINPROGRESS is a soft error, needs retry
10722 				 * so don't make *outlenp zero.
10723 				 */
10724 				if (error != EINPROGRESS)
10725 					*outlenp = 0;
10726 				return (error);
10727 			}
10728 			/* OK return - copy input buffer into output buffer */
10729 			if (invalp != outvalp) {
10730 				bcopy(invalp, outvalp, inlen);
10731 			}
10732 			*outlenp = inlen;
10733 			return (0);
10734 		}
10735 		case IP_SEC_OPT:
10736 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10737 			if (error != 0) {
10738 				*outlenp = 0;
10739 				return (error);
10740 			}
10741 			break;
10742 		case IP_HDRINCL:
10743 		case IP_OPTIONS:
10744 		case T_IP_OPTIONS:
10745 		case IP_TOS:
10746 		case T_IP_TOS:
10747 		case IP_TTL:
10748 		case IP_RECVDSTADDR:
10749 		case IP_RECVOPTS:
10750 			/* OK return - copy input buffer into output buffer */
10751 			if (invalp != outvalp) {
10752 				/* don't trust bcopy for identical src/dst */
10753 				bcopy(invalp, outvalp, inlen);
10754 			}
10755 			*outlenp = inlen;
10756 			return (0);
10757 		case IP_RECVIF:
10758 			/* Retrieve the inbound interface index */
10759 			if (!checkonly) {
10760 				mutex_enter(&connp->conn_lock);
10761 				connp->conn_recvif = *i1 ? 1 : 0;
10762 				mutex_exit(&connp->conn_lock);
10763 			}
10764 			break;	/* goto sizeof (int) option return */
10765 		case IP_RECVSLLA:
10766 			/* Retrieve the source link layer address */
10767 			if (!checkonly) {
10768 				mutex_enter(&connp->conn_lock);
10769 				connp->conn_recvslla = *i1 ? 1 : 0;
10770 				mutex_exit(&connp->conn_lock);
10771 			}
10772 			break;	/* goto sizeof (int) option return */
10773 		case MRT_INIT:
10774 		case MRT_DONE:
10775 		case MRT_ADD_VIF:
10776 		case MRT_DEL_VIF:
10777 		case MRT_ADD_MFC:
10778 		case MRT_DEL_MFC:
10779 		case MRT_ASSERT:
10780 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10781 				*outlenp = 0;
10782 				return (error);
10783 			}
10784 			error = ip_mrouter_set((int)name, q, checkonly,
10785 			    (uchar_t *)invalp, inlen, first_mp);
10786 			if (error) {
10787 				*outlenp = 0;
10788 				return (error);
10789 			}
10790 			/* OK return - copy input buffer into output buffer */
10791 			if (invalp != outvalp) {
10792 				/* don't trust bcopy for identical src/dst */
10793 				bcopy(invalp, outvalp, inlen);
10794 			}
10795 			*outlenp = inlen;
10796 			return (0);
10797 		case IP_BOUND_IF:
10798 		case IP_XMIT_IF:
10799 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10800 			    level, name, first_mp);
10801 			if (error != 0)
10802 				return (error);
10803 			break; 		/* goto sizeof (int) option return */
10804 
10805 		case IP_UNSPEC_SRC:
10806 			/* Allow sending with a zero source address */
10807 			if (!checkonly) {
10808 				mutex_enter(&connp->conn_lock);
10809 				connp->conn_unspec_src = *i1 ? 1 : 0;
10810 				mutex_exit(&connp->conn_lock);
10811 			}
10812 			break;	/* goto sizeof (int) option return */
10813 		default:
10814 			/*
10815 			 * "soft" error (negative)
10816 			 * option not handled at this level
10817 			 * Note: Do not modify *outlenp
10818 			 */
10819 			return (-EINVAL);
10820 		}
10821 		break;
10822 	case IPPROTO_IPV6:
10823 		switch (name) {
10824 		case IPV6_BOUND_IF:
10825 		case IPV6_BOUND_PIF:
10826 		case IPV6_DONTFAILOVER_IF:
10827 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10828 			    level, name, first_mp);
10829 			if (error != 0)
10830 				return (error);
10831 			break; 		/* goto sizeof (int) option return */
10832 
10833 		case IPV6_MULTICAST_IF:
10834 			/*
10835 			 * The only possible errors are EINPROGRESS and
10836 			 * EINVAL. EINPROGRESS will be restarted and is not
10837 			 * a hard error. We call this option on both V4 and V6
10838 			 * If both return EINVAL, then this call returns
10839 			 * EINVAL. If at least one of them succeeds we
10840 			 * return success.
10841 			 */
10842 			found = B_FALSE;
10843 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10844 			    level, name, first_mp);
10845 			if (error == EINPROGRESS)
10846 				return (error);
10847 			if (error == 0)
10848 				found = B_TRUE;
10849 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10850 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10851 			if (error == 0)
10852 				found = B_TRUE;
10853 			if (!found)
10854 				return (error);
10855 			break; 		/* goto sizeof (int) option return */
10856 
10857 		case IPV6_MULTICAST_HOPS:
10858 			/* Recorded in transport above IP */
10859 			break;	/* goto sizeof (int) option return */
10860 		case IPV6_MULTICAST_LOOP:
10861 			if (!checkonly) {
10862 				mutex_enter(&connp->conn_lock);
10863 				connp->conn_multicast_loop = *i1;
10864 				mutex_exit(&connp->conn_lock);
10865 			}
10866 			break;	/* goto sizeof (int) option return */
10867 		case IPV6_JOIN_GROUP:
10868 		case MCAST_JOIN_GROUP:
10869 		case IPV6_LEAVE_GROUP:
10870 		case MCAST_LEAVE_GROUP: {
10871 			struct ipv6_mreq *ip_mreqp;
10872 			struct group_req *greqp;
10873 			ire_t *ire;
10874 			boolean_t done = B_FALSE;
10875 			in6_addr_t groupv6;
10876 			uint32_t ifindex;
10877 			boolean_t mcast_opt = B_TRUE;
10878 			mcast_record_t fmode;
10879 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10880 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10881 
10882 			switch (name) {
10883 			case IPV6_JOIN_GROUP:
10884 				mcast_opt = B_FALSE;
10885 				/* FALLTHRU */
10886 			case MCAST_JOIN_GROUP:
10887 				fmode = MODE_IS_EXCLUDE;
10888 				optfn = ip_opt_add_group_v6;
10889 				break;
10890 
10891 			case IPV6_LEAVE_GROUP:
10892 				mcast_opt = B_FALSE;
10893 				/* FALLTHRU */
10894 			case MCAST_LEAVE_GROUP:
10895 				fmode = MODE_IS_INCLUDE;
10896 				optfn = ip_opt_delete_group_v6;
10897 				break;
10898 			}
10899 
10900 			if (mcast_opt) {
10901 				struct sockaddr_in *sin;
10902 				struct sockaddr_in6 *sin6;
10903 				greqp = (struct group_req *)i1;
10904 				if (greqp->gr_group.ss_family == AF_INET) {
10905 					sin = (struct sockaddr_in *)
10906 					    &(greqp->gr_group);
10907 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10908 					    &groupv6);
10909 				} else {
10910 					sin6 = (struct sockaddr_in6 *)
10911 					    &(greqp->gr_group);
10912 					groupv6 = sin6->sin6_addr;
10913 				}
10914 				ifindex = greqp->gr_interface;
10915 			} else {
10916 				ip_mreqp = (struct ipv6_mreq *)i1;
10917 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10918 				ifindex = ip_mreqp->ipv6mr_interface;
10919 			}
10920 			/*
10921 			 * In the multirouting case, we need to replicate
10922 			 * the request on all interfaces that will take part
10923 			 * in replication.  We do so because multirouting is
10924 			 * reflective, thus we will probably receive multi-
10925 			 * casts on those interfaces.
10926 			 * The ip_multirt_apply_membership_v6() succeeds if
10927 			 * the operation succeeds on at least one interface.
10928 			 */
10929 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
10930 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10931 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10932 			if (ire != NULL) {
10933 				if (ire->ire_flags & RTF_MULTIRT) {
10934 					error = ip_multirt_apply_membership_v6(
10935 					    optfn, ire, connp, checkonly,
10936 					    &groupv6, fmode, &ipv6_all_zeros,
10937 					    first_mp);
10938 					done = B_TRUE;
10939 				}
10940 				ire_refrele(ire);
10941 			}
10942 			if (!done) {
10943 				error = optfn(connp, checkonly, &groupv6,
10944 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10945 			}
10946 			if (error) {
10947 				/*
10948 				 * EINPROGRESS is a soft error, needs retry
10949 				 * so don't make *outlenp zero.
10950 				 */
10951 				if (error != EINPROGRESS)
10952 					*outlenp = 0;
10953 				return (error);
10954 			}
10955 			/* OK return - copy input buffer into output buffer */
10956 			if (invalp != outvalp) {
10957 				/* don't trust bcopy for identical src/dst */
10958 				bcopy(invalp, outvalp, inlen);
10959 			}
10960 			*outlenp = inlen;
10961 			return (0);
10962 		}
10963 		case MCAST_BLOCK_SOURCE:
10964 		case MCAST_UNBLOCK_SOURCE:
10965 		case MCAST_JOIN_SOURCE_GROUP:
10966 		case MCAST_LEAVE_SOURCE_GROUP: {
10967 			struct group_source_req *gsreqp;
10968 			in6_addr_t v6grp, v6src;
10969 			uint32_t ifindex;
10970 			mcast_record_t fmode;
10971 			ire_t *ire;
10972 			boolean_t done = B_FALSE;
10973 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10974 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10975 
10976 			switch (name) {
10977 			case MCAST_BLOCK_SOURCE:
10978 				fmode = MODE_IS_EXCLUDE;
10979 				optfn = ip_opt_add_group_v6;
10980 				break;
10981 			case MCAST_UNBLOCK_SOURCE:
10982 				fmode = MODE_IS_EXCLUDE;
10983 				optfn = ip_opt_delete_group_v6;
10984 				break;
10985 			case MCAST_JOIN_SOURCE_GROUP:
10986 				fmode = MODE_IS_INCLUDE;
10987 				optfn = ip_opt_add_group_v6;
10988 				break;
10989 			case MCAST_LEAVE_SOURCE_GROUP:
10990 				fmode = MODE_IS_INCLUDE;
10991 				optfn = ip_opt_delete_group_v6;
10992 				break;
10993 			}
10994 
10995 			gsreqp = (struct group_source_req *)i1;
10996 			ifindex = gsreqp->gsr_interface;
10997 			if (gsreqp->gsr_group.ss_family == AF_INET) {
10998 				struct sockaddr_in *s;
10999 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11000 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11001 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11002 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11003 			} else {
11004 				struct sockaddr_in6 *s6;
11005 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11006 				v6grp = s6->sin6_addr;
11007 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11008 				v6src = s6->sin6_addr;
11009 			}
11010 
11011 			/*
11012 			 * In the multirouting case, we need to replicate
11013 			 * the request as noted in the mcast cases above.
11014 			 */
11015 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11016 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11017 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11018 			if (ire != NULL) {
11019 				if (ire->ire_flags & RTF_MULTIRT) {
11020 					error = ip_multirt_apply_membership_v6(
11021 					    optfn, ire, connp, checkonly,
11022 					    &v6grp, fmode, &v6src, first_mp);
11023 					done = B_TRUE;
11024 				}
11025 				ire_refrele(ire);
11026 			}
11027 			if (!done) {
11028 				error = optfn(connp, checkonly, &v6grp,
11029 				    ifindex, fmode, &v6src, first_mp);
11030 			}
11031 			if (error != 0) {
11032 				/*
11033 				 * EINPROGRESS is a soft error, needs retry
11034 				 * so don't make *outlenp zero.
11035 				 */
11036 				if (error != EINPROGRESS)
11037 					*outlenp = 0;
11038 				return (error);
11039 			}
11040 			/* OK return - copy input buffer into output buffer */
11041 			if (invalp != outvalp) {
11042 				bcopy(invalp, outvalp, inlen);
11043 			}
11044 			*outlenp = inlen;
11045 			return (0);
11046 		}
11047 		case IPV6_UNICAST_HOPS:
11048 			/* Recorded in transport above IP */
11049 			break;	/* goto sizeof (int) option return */
11050 		case IPV6_UNSPEC_SRC:
11051 			/* Allow sending with a zero source address */
11052 			if (!checkonly) {
11053 				mutex_enter(&connp->conn_lock);
11054 				connp->conn_unspec_src = *i1 ? 1 : 0;
11055 				mutex_exit(&connp->conn_lock);
11056 			}
11057 			break;	/* goto sizeof (int) option return */
11058 		case IPV6_RECVPKTINFO:
11059 			if (!checkonly) {
11060 				mutex_enter(&connp->conn_lock);
11061 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
11062 				mutex_exit(&connp->conn_lock);
11063 			}
11064 			break;	/* goto sizeof (int) option return */
11065 		case IPV6_RECVTCLASS:
11066 			if (!checkonly) {
11067 				if (*i1 < 0 || *i1 > 1) {
11068 					return (EINVAL);
11069 				}
11070 				mutex_enter(&connp->conn_lock);
11071 				connp->conn_ipv6_recvtclass = *i1;
11072 				mutex_exit(&connp->conn_lock);
11073 			}
11074 			break;
11075 		case IPV6_RECVPATHMTU:
11076 			if (!checkonly) {
11077 				if (*i1 < 0 || *i1 > 1) {
11078 					return (EINVAL);
11079 				}
11080 				mutex_enter(&connp->conn_lock);
11081 				connp->conn_ipv6_recvpathmtu = *i1;
11082 				mutex_exit(&connp->conn_lock);
11083 			}
11084 			break;
11085 		case IPV6_RECVHOPLIMIT:
11086 			if (!checkonly) {
11087 				mutex_enter(&connp->conn_lock);
11088 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11089 				mutex_exit(&connp->conn_lock);
11090 			}
11091 			break;	/* goto sizeof (int) option return */
11092 		case IPV6_RECVHOPOPTS:
11093 			if (!checkonly) {
11094 				mutex_enter(&connp->conn_lock);
11095 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11096 				mutex_exit(&connp->conn_lock);
11097 			}
11098 			break;	/* goto sizeof (int) option return */
11099 		case IPV6_RECVDSTOPTS:
11100 			if (!checkonly) {
11101 				mutex_enter(&connp->conn_lock);
11102 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11103 				mutex_exit(&connp->conn_lock);
11104 			}
11105 			break;	/* goto sizeof (int) option return */
11106 		case IPV6_RECVRTHDR:
11107 			if (!checkonly) {
11108 				mutex_enter(&connp->conn_lock);
11109 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11110 				mutex_exit(&connp->conn_lock);
11111 			}
11112 			break;	/* goto sizeof (int) option return */
11113 		case IPV6_RECVRTHDRDSTOPTS:
11114 			if (!checkonly) {
11115 				mutex_enter(&connp->conn_lock);
11116 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11117 				mutex_exit(&connp->conn_lock);
11118 			}
11119 			break;	/* goto sizeof (int) option return */
11120 		case IPV6_PKTINFO:
11121 			if (inlen == 0)
11122 				return (-EINVAL);	/* clearing option */
11123 			error = ip6_set_pktinfo(cr, connp,
11124 			    (struct in6_pktinfo *)invalp, first_mp);
11125 			if (error != 0)
11126 				*outlenp = 0;
11127 			else
11128 				*outlenp = inlen;
11129 			return (error);
11130 		case IPV6_NEXTHOP: {
11131 			struct sockaddr_in6 *sin6;
11132 
11133 			/* Verify that the nexthop is reachable */
11134 			if (inlen == 0)
11135 				return (-EINVAL);	/* clearing option */
11136 
11137 			sin6 = (struct sockaddr_in6 *)invalp;
11138 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11139 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11140 			    NULL, MATCH_IRE_DEFAULT);
11141 
11142 			if (ire == NULL) {
11143 				*outlenp = 0;
11144 				return (EHOSTUNREACH);
11145 			}
11146 			ire_refrele(ire);
11147 			return (-EINVAL);
11148 		}
11149 		case IPV6_SEC_OPT:
11150 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11151 			if (error != 0) {
11152 				*outlenp = 0;
11153 				return (error);
11154 			}
11155 			break;
11156 		case IPV6_SRC_PREFERENCES: {
11157 			/*
11158 			 * This is implemented strictly in the ip module
11159 			 * (here and in tcp_opt_*() to accomodate tcp
11160 			 * sockets).  Modules above ip pass this option
11161 			 * down here since ip is the only one that needs to
11162 			 * be aware of source address preferences.
11163 			 *
11164 			 * This socket option only affects connected
11165 			 * sockets that haven't already bound to a specific
11166 			 * IPv6 address.  In other words, sockets that
11167 			 * don't call bind() with an address other than the
11168 			 * unspecified address and that call connect().
11169 			 * ip_bind_connected_v6() passes these preferences
11170 			 * to the ipif_select_source_v6() function.
11171 			 */
11172 			if (inlen != sizeof (uint32_t))
11173 				return (EINVAL);
11174 			error = ip6_set_src_preferences(connp,
11175 			    *(uint32_t *)invalp);
11176 			if (error != 0) {
11177 				*outlenp = 0;
11178 				return (error);
11179 			} else {
11180 				*outlenp = sizeof (uint32_t);
11181 			}
11182 			break;
11183 		}
11184 		case IPV6_V6ONLY:
11185 			if (*i1 < 0 || *i1 > 1) {
11186 				return (EINVAL);
11187 			}
11188 			mutex_enter(&connp->conn_lock);
11189 			connp->conn_ipv6_v6only = *i1;
11190 			mutex_exit(&connp->conn_lock);
11191 			break;
11192 		default:
11193 			return (-EINVAL);
11194 		}
11195 		break;
11196 	default:
11197 		/*
11198 		 * "soft" error (negative)
11199 		 * option not handled at this level
11200 		 * Note: Do not modify *outlenp
11201 		 */
11202 		return (-EINVAL);
11203 	}
11204 	/*
11205 	 * Common case of return from an option that is sizeof (int)
11206 	 */
11207 	*(int *)outvalp = *i1;
11208 	*outlenp = sizeof (int);
11209 	return (0);
11210 }
11211 
11212 /*
11213  * This routine gets default values of certain options whose default
11214  * values are maintained by protocol specific code
11215  */
11216 /* ARGSUSED */
11217 int
11218 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11219 {
11220 	int *i1 = (int *)ptr;
11221 
11222 	switch (level) {
11223 	case IPPROTO_IP:
11224 		switch (name) {
11225 		case IP_MULTICAST_TTL:
11226 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11227 			return (sizeof (uchar_t));
11228 		case IP_MULTICAST_LOOP:
11229 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11230 			return (sizeof (uchar_t));
11231 		default:
11232 			return (-1);
11233 		}
11234 	case IPPROTO_IPV6:
11235 		switch (name) {
11236 		case IPV6_UNICAST_HOPS:
11237 			*i1 = ipv6_def_hops;
11238 			return (sizeof (int));
11239 		case IPV6_MULTICAST_HOPS:
11240 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11241 			return (sizeof (int));
11242 		case IPV6_MULTICAST_LOOP:
11243 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11244 			return (sizeof (int));
11245 		case IPV6_V6ONLY:
11246 			*i1 = 1;
11247 			return (sizeof (int));
11248 		default:
11249 			return (-1);
11250 		}
11251 	default:
11252 		return (-1);
11253 	}
11254 	/* NOTREACHED */
11255 }
11256 
11257 /*
11258  * Given a destination address and a pointer to where to put the information
11259  * this routine fills in the mtuinfo.
11260  */
11261 int
11262 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11263     struct ip6_mtuinfo *mtuinfo)
11264 {
11265 	ire_t *ire;
11266 
11267 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11268 		return (-1);
11269 
11270 	bzero(mtuinfo, sizeof (*mtuinfo));
11271 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11272 	mtuinfo->ip6m_addr.sin6_port = port;
11273 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11274 
11275 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11276 	if (ire != NULL) {
11277 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11278 		ire_refrele(ire);
11279 	} else {
11280 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11281 	}
11282 	return (sizeof (struct ip6_mtuinfo));
11283 }
11284 
11285 /*
11286  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11287  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11288  * isn't.  This doesn't matter as the error checking is done properly for the
11289  * other MRT options coming in through ip_opt_set.
11290  */
11291 int
11292 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11293 {
11294 	conn_t		*connp = Q_TO_CONN(q);
11295 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11296 
11297 	switch (level) {
11298 	case IPPROTO_IP:
11299 		switch (name) {
11300 		case MRT_VERSION:
11301 		case MRT_ASSERT:
11302 			(void) ip_mrouter_get(name, q, ptr);
11303 			return (sizeof (int));
11304 		case IP_SEC_OPT:
11305 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11306 		case IP_NEXTHOP:
11307 			if (connp->conn_nexthop_set) {
11308 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11309 				return (sizeof (ipaddr_t));
11310 			} else
11311 				return (0);
11312 		default:
11313 			break;
11314 		}
11315 		break;
11316 	case IPPROTO_IPV6:
11317 		switch (name) {
11318 		case IPV6_SEC_OPT:
11319 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11320 		case IPV6_SRC_PREFERENCES: {
11321 			return (ip6_get_src_preferences(connp,
11322 			    (uint32_t *)ptr));
11323 		}
11324 		case IPV6_V6ONLY:
11325 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11326 			return (sizeof (int));
11327 		case IPV6_PATHMTU:
11328 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11329 				(struct ip6_mtuinfo *)ptr));
11330 		default:
11331 			break;
11332 		}
11333 		break;
11334 	default:
11335 		break;
11336 	}
11337 	return (-1);
11338 }
11339 
11340 /* Named Dispatch routine to get a current value out of our parameter table. */
11341 /* ARGSUSED */
11342 static int
11343 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11344 {
11345 	ipparam_t *ippa = (ipparam_t *)cp;
11346 
11347 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11348 	return (0);
11349 }
11350 
11351 /* ARGSUSED */
11352 static int
11353 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11354 {
11355 
11356 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11357 	return (0);
11358 }
11359 
11360 /*
11361  * Set ip{,6}_forwarding values.  This means walking through all of the
11362  * ill's and toggling their forwarding values.
11363  */
11364 /* ARGSUSED */
11365 static int
11366 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11367 {
11368 	long new_value;
11369 	int *forwarding_value = (int *)cp;
11370 	ill_t *walker;
11371 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11372 	ill_walk_context_t ctx;
11373 
11374 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11375 	    new_value < 0 || new_value > 1) {
11376 		return (EINVAL);
11377 	}
11378 
11379 	*forwarding_value = new_value;
11380 
11381 	/*
11382 	 * Regardless of the current value of ip_forwarding, set all per-ill
11383 	 * values of ip_forwarding to the value being set.
11384 	 *
11385 	 * Bring all the ill's up to date with the new global value.
11386 	 */
11387 	rw_enter(&ill_g_lock, RW_READER);
11388 
11389 	if (isv6)
11390 		walker = ILL_START_WALK_V6(&ctx);
11391 	else
11392 		walker = ILL_START_WALK_V4(&ctx);
11393 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11394 		(void) ill_forward_set(q, mp, (new_value != 0),
11395 		    (caddr_t)walker);
11396 	}
11397 	rw_exit(&ill_g_lock);
11398 
11399 	return (0);
11400 }
11401 
11402 /*
11403  * Walk through the param array specified registering each element with the
11404  * Named Dispatch handler. This is called only during init. So it is ok
11405  * not to acquire any locks
11406  */
11407 static boolean_t
11408 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11409     ipndp_t *ipnd, size_t ipnd_cnt)
11410 {
11411 	for (; ippa_cnt-- > 0; ippa++) {
11412 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11413 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11414 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11415 				nd_free(&ip_g_nd);
11416 				return (B_FALSE);
11417 			}
11418 		}
11419 	}
11420 
11421 	for (; ipnd_cnt-- > 0; ipnd++) {
11422 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11423 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11424 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11425 			    ipnd->ip_ndp_data)) {
11426 				nd_free(&ip_g_nd);
11427 				return (B_FALSE);
11428 			}
11429 		}
11430 	}
11431 
11432 	return (B_TRUE);
11433 }
11434 
11435 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11436 /* ARGSUSED */
11437 static int
11438 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11439 {
11440 	long		new_value;
11441 	ipparam_t	*ippa = (ipparam_t *)cp;
11442 
11443 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11444 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11445 		return (EINVAL);
11446 	}
11447 	ippa->ip_param_value = new_value;
11448 	return (0);
11449 }
11450 
11451 /*
11452  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11453  * When an ipf is passed here for the first time, if
11454  * we already have in-order fragments on the queue, we convert from the fast-
11455  * path reassembly scheme to the hard-case scheme.  From then on, additional
11456  * fragments are reassembled here.  We keep track of the start and end offsets
11457  * of each piece, and the number of holes in the chain.  When the hole count
11458  * goes to zero, we are done!
11459  *
11460  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11461  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11462  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11463  * after the call to ip_reassemble().
11464  */
11465 int
11466 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11467     size_t msg_len)
11468 {
11469 	uint_t	end;
11470 	mblk_t	*next_mp;
11471 	mblk_t	*mp1;
11472 	uint_t	offset;
11473 	boolean_t incr_dups = B_TRUE;
11474 	boolean_t offset_zero_seen = B_FALSE;
11475 	boolean_t pkt_boundary_checked = B_FALSE;
11476 
11477 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11478 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11479 
11480 	/* Add in byte count */
11481 	ipf->ipf_count += msg_len;
11482 	if (ipf->ipf_end) {
11483 		/*
11484 		 * We were part way through in-order reassembly, but now there
11485 		 * is a hole.  We walk through messages already queued, and
11486 		 * mark them for hard case reassembly.  We know that up till
11487 		 * now they were in order starting from offset zero.
11488 		 */
11489 		offset = 0;
11490 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11491 			IP_REASS_SET_START(mp1, offset);
11492 			if (offset == 0) {
11493 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11494 				offset = -ipf->ipf_nf_hdr_len;
11495 			}
11496 			offset += mp1->b_wptr - mp1->b_rptr;
11497 			IP_REASS_SET_END(mp1, offset);
11498 		}
11499 		/* One hole at the end. */
11500 		ipf->ipf_hole_cnt = 1;
11501 		/* Brand it as a hard case, forever. */
11502 		ipf->ipf_end = 0;
11503 	}
11504 	/* Walk through all the new pieces. */
11505 	do {
11506 		end = start + (mp->b_wptr - mp->b_rptr);
11507 		/*
11508 		 * If start is 0, decrease 'end' only for the first mblk of
11509 		 * the fragment. Otherwise 'end' can get wrong value in the
11510 		 * second pass of the loop if first mblk is exactly the
11511 		 * size of ipf_nf_hdr_len.
11512 		 */
11513 		if (start == 0 && !offset_zero_seen) {
11514 			/* First segment */
11515 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11516 			end -= ipf->ipf_nf_hdr_len;
11517 			offset_zero_seen = B_TRUE;
11518 		}
11519 		next_mp = mp->b_cont;
11520 		/*
11521 		 * We are checking to see if there is any interesing data
11522 		 * to process.  If there isn't and the mblk isn't the
11523 		 * one which carries the unfragmentable header then we
11524 		 * drop it.  It's possible to have just the unfragmentable
11525 		 * header come through without any data.  That needs to be
11526 		 * saved.
11527 		 *
11528 		 * If the assert at the top of this function holds then the
11529 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11530 		 * is infrequently traveled enough that the test is left in
11531 		 * to protect against future code changes which break that
11532 		 * invariant.
11533 		 */
11534 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11535 			/* Empty.  Blast it. */
11536 			IP_REASS_SET_START(mp, 0);
11537 			IP_REASS_SET_END(mp, 0);
11538 			/*
11539 			 * If the ipf points to the mblk we are about to free,
11540 			 * update ipf to point to the next mblk (or NULL
11541 			 * if none).
11542 			 */
11543 			if (ipf->ipf_mp->b_cont == mp)
11544 				ipf->ipf_mp->b_cont = next_mp;
11545 			freeb(mp);
11546 			continue;
11547 		}
11548 		mp->b_cont = NULL;
11549 		IP_REASS_SET_START(mp, start);
11550 		IP_REASS_SET_END(mp, end);
11551 		if (!ipf->ipf_tail_mp) {
11552 			ipf->ipf_tail_mp = mp;
11553 			ipf->ipf_mp->b_cont = mp;
11554 			if (start == 0 || !more) {
11555 				ipf->ipf_hole_cnt = 1;
11556 				/*
11557 				 * if the first fragment comes in more than one
11558 				 * mblk, this loop will be executed for each
11559 				 * mblk. Need to adjust hole count so exiting
11560 				 * this routine will leave hole count at 1.
11561 				 */
11562 				if (next_mp)
11563 					ipf->ipf_hole_cnt++;
11564 			} else
11565 				ipf->ipf_hole_cnt = 2;
11566 			continue;
11567 		} else if (ipf->ipf_last_frag_seen && !more &&
11568 			    !pkt_boundary_checked) {
11569 			/*
11570 			 * We check datagram boundary only if this fragment
11571 			 * claims to be the last fragment and we have seen a
11572 			 * last fragment in the past too. We do this only
11573 			 * once for a given fragment.
11574 			 *
11575 			 * start cannot be 0 here as fragments with start=0
11576 			 * and MF=0 gets handled as a complete packet. These
11577 			 * fragments should not reach here.
11578 			 */
11579 
11580 			if (start + msgdsize(mp) !=
11581 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11582 				/*
11583 				 * We have two fragments both of which claim
11584 				 * to be the last fragment but gives conflicting
11585 				 * information about the whole datagram size.
11586 				 * Something fishy is going on. Drop the
11587 				 * fragment and free up the reassembly list.
11588 				 */
11589 				return (IP_REASS_FAILED);
11590 			}
11591 
11592 			/*
11593 			 * We shouldn't come to this code block again for this
11594 			 * particular fragment.
11595 			 */
11596 			pkt_boundary_checked = B_TRUE;
11597 		}
11598 
11599 		/* New stuff at or beyond tail? */
11600 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11601 		if (start >= offset) {
11602 			if (ipf->ipf_last_frag_seen) {
11603 				/* current fragment is beyond last fragment */
11604 				return (IP_REASS_FAILED);
11605 			}
11606 			/* Link it on end. */
11607 			ipf->ipf_tail_mp->b_cont = mp;
11608 			ipf->ipf_tail_mp = mp;
11609 			if (more) {
11610 				if (start != offset)
11611 					ipf->ipf_hole_cnt++;
11612 			} else if (start == offset && next_mp == NULL)
11613 					ipf->ipf_hole_cnt--;
11614 			continue;
11615 		}
11616 		mp1 = ipf->ipf_mp->b_cont;
11617 		offset = IP_REASS_START(mp1);
11618 		/* New stuff at the front? */
11619 		if (start < offset) {
11620 			if (start == 0) {
11621 				if (end >= offset) {
11622 					/* Nailed the hole at the begining. */
11623 					ipf->ipf_hole_cnt--;
11624 				}
11625 			} else if (end < offset) {
11626 				/*
11627 				 * A hole, stuff, and a hole where there used
11628 				 * to be just a hole.
11629 				 */
11630 				ipf->ipf_hole_cnt++;
11631 			}
11632 			mp->b_cont = mp1;
11633 			/* Check for overlap. */
11634 			while (end > offset) {
11635 				if (end < IP_REASS_END(mp1)) {
11636 					mp->b_wptr -= end - offset;
11637 					IP_REASS_SET_END(mp, offset);
11638 					if (ill->ill_isv6) {
11639 						BUMP_MIB(ill->ill_ip6_mib,
11640 						    ipv6ReasmPartDups);
11641 					} else {
11642 						BUMP_MIB(&ip_mib,
11643 						    ipReasmPartDups);
11644 					}
11645 					break;
11646 				}
11647 				/* Did we cover another hole? */
11648 				if ((mp1->b_cont &&
11649 				    IP_REASS_END(mp1) !=
11650 				    IP_REASS_START(mp1->b_cont) &&
11651 				    end >= IP_REASS_START(mp1->b_cont)) ||
11652 				    (!ipf->ipf_last_frag_seen && !more)) {
11653 					ipf->ipf_hole_cnt--;
11654 				}
11655 				/* Clip out mp1. */
11656 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11657 					/*
11658 					 * After clipping out mp1, this guy
11659 					 * is now hanging off the end.
11660 					 */
11661 					ipf->ipf_tail_mp = mp;
11662 				}
11663 				IP_REASS_SET_START(mp1, 0);
11664 				IP_REASS_SET_END(mp1, 0);
11665 				/* Subtract byte count */
11666 				ipf->ipf_count -= mp1->b_datap->db_lim -
11667 				    mp1->b_datap->db_base;
11668 				freeb(mp1);
11669 				if (ill->ill_isv6) {
11670 					BUMP_MIB(ill->ill_ip6_mib,
11671 					    ipv6ReasmPartDups);
11672 				} else {
11673 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11674 				}
11675 				mp1 = mp->b_cont;
11676 				if (!mp1)
11677 					break;
11678 				offset = IP_REASS_START(mp1);
11679 			}
11680 			ipf->ipf_mp->b_cont = mp;
11681 			continue;
11682 		}
11683 		/*
11684 		 * The new piece starts somewhere between the start of the head
11685 		 * and before the end of the tail.
11686 		 */
11687 		for (; mp1; mp1 = mp1->b_cont) {
11688 			offset = IP_REASS_END(mp1);
11689 			if (start < offset) {
11690 				if (end <= offset) {
11691 					/* Nothing new. */
11692 					IP_REASS_SET_START(mp, 0);
11693 					IP_REASS_SET_END(mp, 0);
11694 					/* Subtract byte count */
11695 					ipf->ipf_count -= mp->b_datap->db_lim -
11696 					    mp->b_datap->db_base;
11697 					if (incr_dups) {
11698 						ipf->ipf_num_dups++;
11699 						incr_dups = B_FALSE;
11700 					}
11701 					freeb(mp);
11702 					if (ill->ill_isv6) {
11703 						BUMP_MIB(ill->ill_ip6_mib,
11704 						    ipv6ReasmDuplicates);
11705 					} else {
11706 						BUMP_MIB(&ip_mib,
11707 						    ipReasmDuplicates);
11708 					}
11709 					break;
11710 				}
11711 				/*
11712 				 * Trim redundant stuff off beginning of new
11713 				 * piece.
11714 				 */
11715 				IP_REASS_SET_START(mp, offset);
11716 				mp->b_rptr += offset - start;
11717 				if (ill->ill_isv6) {
11718 					BUMP_MIB(ill->ill_ip6_mib,
11719 					    ipv6ReasmPartDups);
11720 				} else {
11721 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11722 				}
11723 				start = offset;
11724 				if (!mp1->b_cont) {
11725 					/*
11726 					 * After trimming, this guy is now
11727 					 * hanging off the end.
11728 					 */
11729 					mp1->b_cont = mp;
11730 					ipf->ipf_tail_mp = mp;
11731 					if (!more) {
11732 						ipf->ipf_hole_cnt--;
11733 					}
11734 					break;
11735 				}
11736 			}
11737 			if (start >= IP_REASS_START(mp1->b_cont))
11738 				continue;
11739 			/* Fill a hole */
11740 			if (start > offset)
11741 				ipf->ipf_hole_cnt++;
11742 			mp->b_cont = mp1->b_cont;
11743 			mp1->b_cont = mp;
11744 			mp1 = mp->b_cont;
11745 			offset = IP_REASS_START(mp1);
11746 			if (end >= offset) {
11747 				ipf->ipf_hole_cnt--;
11748 				/* Check for overlap. */
11749 				while (end > offset) {
11750 					if (end < IP_REASS_END(mp1)) {
11751 						mp->b_wptr -= end - offset;
11752 						IP_REASS_SET_END(mp, offset);
11753 						/*
11754 						 * TODO we might bump
11755 						 * this up twice if there is
11756 						 * overlap at both ends.
11757 						 */
11758 						if (ill->ill_isv6) {
11759 							BUMP_MIB(
11760 							    ill->ill_ip6_mib,
11761 							    ipv6ReasmPartDups);
11762 						} else {
11763 							BUMP_MIB(&ip_mib,
11764 							    ipReasmPartDups);
11765 						}
11766 						break;
11767 					}
11768 					/* Did we cover another hole? */
11769 					if ((mp1->b_cont &&
11770 					    IP_REASS_END(mp1)
11771 					    != IP_REASS_START(mp1->b_cont) &&
11772 					    end >=
11773 					    IP_REASS_START(mp1->b_cont)) ||
11774 					    (!ipf->ipf_last_frag_seen &&
11775 					    !more)) {
11776 						ipf->ipf_hole_cnt--;
11777 					}
11778 					/* Clip out mp1. */
11779 					if ((mp->b_cont = mp1->b_cont) ==
11780 					    NULL) {
11781 						/*
11782 						 * After clipping out mp1,
11783 						 * this guy is now hanging
11784 						 * off the end.
11785 						 */
11786 						ipf->ipf_tail_mp = mp;
11787 					}
11788 					IP_REASS_SET_START(mp1, 0);
11789 					IP_REASS_SET_END(mp1, 0);
11790 					/* Subtract byte count */
11791 					ipf->ipf_count -=
11792 					    mp1->b_datap->db_lim -
11793 					    mp1->b_datap->db_base;
11794 					freeb(mp1);
11795 					if (ill->ill_isv6) {
11796 						BUMP_MIB(ill->ill_ip6_mib,
11797 						    ipv6ReasmPartDups);
11798 					} else {
11799 						BUMP_MIB(&ip_mib,
11800 						    ipReasmPartDups);
11801 					}
11802 					mp1 = mp->b_cont;
11803 					if (!mp1)
11804 						break;
11805 					offset = IP_REASS_START(mp1);
11806 				}
11807 			}
11808 			break;
11809 		}
11810 	} while (start = end, mp = next_mp);
11811 
11812 	/* Fragment just processed could be the last one. Remember this fact */
11813 	if (!more)
11814 		ipf->ipf_last_frag_seen = B_TRUE;
11815 
11816 	/* Still got holes? */
11817 	if (ipf->ipf_hole_cnt)
11818 		return (IP_REASS_PARTIAL);
11819 	/* Clean up overloaded fields to avoid upstream disasters. */
11820 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11821 		IP_REASS_SET_START(mp1, 0);
11822 		IP_REASS_SET_END(mp1, 0);
11823 	}
11824 	return (IP_REASS_COMPLETE);
11825 }
11826 
11827 /*
11828  * ipsec processing for the fast path, used for input UDP Packets
11829  */
11830 static boolean_t
11831 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11832     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11833 {
11834 	uint32_t	ill_index;
11835 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11836 
11837 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11838 	/* The ill_index of the incoming ILL */
11839 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11840 
11841 	/* pass packet up to the transport */
11842 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11843 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11844 		    NULL, mctl_present);
11845 		if (*first_mpp == NULL) {
11846 			return (B_FALSE);
11847 		}
11848 	}
11849 
11850 	/* Initiate IPPF processing for fastpath UDP */
11851 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11852 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11853 		if (*mpp == NULL) {
11854 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11855 			    "deferred/dropped during IPPF processing\n"));
11856 			return (B_FALSE);
11857 		}
11858 	}
11859 	/*
11860 	 * We make the checks as below since we are in the fast path
11861 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11862 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11863 	 */
11864 	if (connp->conn_recvif || connp->conn_recvslla ||
11865 	    connp->conn_ipv6_recvpktinfo) {
11866 		if (connp->conn_recvif ||
11867 		    connp->conn_ipv6_recvpktinfo) {
11868 			in_flags = IPF_RECVIF;
11869 		}
11870 		if (connp->conn_recvslla) {
11871 			in_flags |= IPF_RECVSLLA;
11872 		}
11873 		/*
11874 		 * since in_flags are being set ill will be
11875 		 * referenced in ip_add_info, so it better not
11876 		 * be NULL.
11877 		 */
11878 		/*
11879 		 * the actual data will be contained in b_cont
11880 		 * upon successful return of the following call.
11881 		 * If the call fails then the original mblk is
11882 		 * returned.
11883 		 */
11884 		*mpp = ip_add_info(*mpp, ill, in_flags);
11885 	}
11886 
11887 	return (B_TRUE);
11888 }
11889 
11890 /*
11891  * Fragmentation reassembly.  Each ILL has a hash table for
11892  * queuing packets undergoing reassembly for all IPIFs
11893  * associated with the ILL.  The hash is based on the packet
11894  * IP ident field.  The ILL frag hash table was allocated
11895  * as a timer block at the time the ILL was created.  Whenever
11896  * there is anything on the reassembly queue, the timer will
11897  * be running.  Returns B_TRUE if successful else B_FALSE;
11898  * frees mp on failure.
11899  */
11900 static boolean_t
11901 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11902     uint32_t *cksum_val, uint16_t *cksum_flags)
11903 {
11904 	uint32_t	frag_offset_flags;
11905 	ill_t		*ill = (ill_t *)q->q_ptr;
11906 	mblk_t		*mp = *mpp;
11907 	mblk_t		*t_mp;
11908 	ipaddr_t	dst;
11909 	uint8_t		proto = ipha->ipha_protocol;
11910 	uint32_t	sum_val;
11911 	uint16_t	sum_flags;
11912 	ipf_t		*ipf;
11913 	ipf_t		**ipfp;
11914 	ipfb_t		*ipfb;
11915 	uint16_t	ident;
11916 	uint32_t	offset;
11917 	ipaddr_t	src;
11918 	uint_t		hdr_length;
11919 	uint32_t	end;
11920 	mblk_t		*mp1;
11921 	mblk_t		*tail_mp;
11922 	size_t		count;
11923 	size_t		msg_len;
11924 	uint8_t		ecn_info = 0;
11925 	uint32_t	packet_size;
11926 	boolean_t	pruned = B_FALSE;
11927 
11928 	if (cksum_val != NULL)
11929 		*cksum_val = 0;
11930 	if (cksum_flags != NULL)
11931 		*cksum_flags = 0;
11932 
11933 	/*
11934 	 * Drop the fragmented as early as possible, if
11935 	 * we don't have resource(s) to re-assemble.
11936 	 */
11937 	if (ip_reass_queue_bytes == 0) {
11938 		freemsg(mp);
11939 		return (B_FALSE);
11940 	}
11941 
11942 	/* Check for fragmentation offset; return if there's none */
11943 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
11944 	    (IPH_MF | IPH_OFFSET)) == 0)
11945 		return (B_TRUE);
11946 
11947 	/*
11948 	 * We utilize hardware computed checksum info only for UDP since
11949 	 * IP fragmentation is a normal occurence for the protocol.  In
11950 	 * addition, checksum offload support for IP fragments carrying
11951 	 * UDP payload is commonly implemented across network adapters.
11952 	 */
11953 	ASSERT(ill != NULL);
11954 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
11955 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
11956 		mblk_t *mp1 = mp->b_cont;
11957 		int32_t len;
11958 
11959 		/* Record checksum information from the packet */
11960 		sum_val = (uint32_t)DB_CKSUM16(mp);
11961 		sum_flags = DB_CKSUMFLAGS(mp);
11962 
11963 		/* IP payload offset from beginning of mblk */
11964 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
11965 
11966 		if ((sum_flags & HCK_PARTIALCKSUM) &&
11967 		    (mp1 == NULL || mp1->b_cont == NULL) &&
11968 		    offset >= DB_CKSUMSTART(mp) &&
11969 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
11970 			uint32_t adj;
11971 			/*
11972 			 * Partial checksum has been calculated by hardware
11973 			 * and attached to the packet; in addition, any
11974 			 * prepended extraneous data is even byte aligned.
11975 			 * If any such data exists, we adjust the checksum;
11976 			 * this would also handle any postpended data.
11977 			 */
11978 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
11979 			    mp, mp1, len, adj);
11980 
11981 			/* One's complement subtract extraneous checksum */
11982 			if (adj >= sum_val)
11983 				sum_val = ~(adj - sum_val) & 0xFFFF;
11984 			else
11985 				sum_val -= adj;
11986 		}
11987 	} else {
11988 		sum_val = 0;
11989 		sum_flags = 0;
11990 	}
11991 
11992 	/* Clear hardware checksumming flag */
11993 	DB_CKSUMFLAGS(mp) = 0;
11994 
11995 	ident = ipha->ipha_ident;
11996 	offset = (frag_offset_flags << 3) & 0xFFFF;
11997 	src = ipha->ipha_src;
11998 	dst = ipha->ipha_dst;
11999 	hdr_length = IPH_HDR_LENGTH(ipha);
12000 	end = ntohs(ipha->ipha_length) - hdr_length;
12001 
12002 	/* If end == 0 then we have a packet with no data, so just free it */
12003 	if (end == 0) {
12004 		freemsg(mp);
12005 		return (B_FALSE);
12006 	}
12007 
12008 	/* Record the ECN field info. */
12009 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12010 	if (offset != 0) {
12011 		/*
12012 		 * If this isn't the first piece, strip the header, and
12013 		 * add the offset to the end value.
12014 		 */
12015 		mp->b_rptr += hdr_length;
12016 		end += offset;
12017 	}
12018 
12019 	msg_len = MBLKSIZE(mp);
12020 	tail_mp = mp;
12021 	while (tail_mp->b_cont != NULL) {
12022 		tail_mp = tail_mp->b_cont;
12023 		msg_len += MBLKSIZE(tail_mp);
12024 	}
12025 
12026 	/* If the reassembly list for this ILL will get too big, prune it */
12027 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12028 	    ip_reass_queue_bytes) {
12029 		ill_frag_prune(ill,
12030 		    (ip_reass_queue_bytes < msg_len) ? 0 :
12031 		    (ip_reass_queue_bytes - msg_len));
12032 		pruned = B_TRUE;
12033 	}
12034 
12035 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12036 	mutex_enter(&ipfb->ipfb_lock);
12037 
12038 	ipfp = &ipfb->ipfb_ipf;
12039 	/* Try to find an existing fragment queue for this packet. */
12040 	for (;;) {
12041 		ipf = ipfp[0];
12042 		if (ipf != NULL) {
12043 			/*
12044 			 * It has to match on ident and src/dst address.
12045 			 */
12046 			if (ipf->ipf_ident == ident &&
12047 			    ipf->ipf_src == src &&
12048 			    ipf->ipf_dst == dst &&
12049 			    ipf->ipf_protocol == proto) {
12050 				/*
12051 				 * If we have received too many
12052 				 * duplicate fragments for this packet
12053 				 * free it.
12054 				 */
12055 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12056 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12057 					freemsg(mp);
12058 					mutex_exit(&ipfb->ipfb_lock);
12059 					return (B_FALSE);
12060 				}
12061 				/* Found it. */
12062 				break;
12063 			}
12064 			ipfp = &ipf->ipf_hash_next;
12065 			continue;
12066 		}
12067 
12068 		/*
12069 		 * If we pruned the list, do we want to store this new
12070 		 * fragment?. We apply an optimization here based on the
12071 		 * fact that most fragments will be received in order.
12072 		 * So if the offset of this incoming fragment is zero,
12073 		 * it is the first fragment of a new packet. We will
12074 		 * keep it.  Otherwise drop the fragment, as we have
12075 		 * probably pruned the packet already (since the
12076 		 * packet cannot be found).
12077 		 */
12078 		if (pruned && offset != 0) {
12079 			mutex_exit(&ipfb->ipfb_lock);
12080 			freemsg(mp);
12081 			return (B_FALSE);
12082 		}
12083 
12084 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12085 			/*
12086 			 * Too many fragmented packets in this hash
12087 			 * bucket. Free the oldest.
12088 			 */
12089 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12090 		}
12091 
12092 		/* New guy.  Allocate a frag message. */
12093 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12094 		if (mp1 == NULL) {
12095 			BUMP_MIB(&ip_mib, ipInDiscards);
12096 			freemsg(mp);
12097 reass_done:
12098 			mutex_exit(&ipfb->ipfb_lock);
12099 			return (B_FALSE);
12100 		}
12101 
12102 
12103 		BUMP_MIB(&ip_mib, ipReasmReqds);
12104 		mp1->b_cont = mp;
12105 
12106 		/* Initialize the fragment header. */
12107 		ipf = (ipf_t *)mp1->b_rptr;
12108 		ipf->ipf_mp = mp1;
12109 		ipf->ipf_ptphn = ipfp;
12110 		ipfp[0] = ipf;
12111 		ipf->ipf_hash_next = NULL;
12112 		ipf->ipf_ident = ident;
12113 		ipf->ipf_protocol = proto;
12114 		ipf->ipf_src = src;
12115 		ipf->ipf_dst = dst;
12116 		ipf->ipf_nf_hdr_len = 0;
12117 		/* Record reassembly start time. */
12118 		ipf->ipf_timestamp = gethrestime_sec();
12119 		/* Record ipf generation and account for frag header */
12120 		ipf->ipf_gen = ill->ill_ipf_gen++;
12121 		ipf->ipf_count = MBLKSIZE(mp1);
12122 		ipf->ipf_last_frag_seen = B_FALSE;
12123 		ipf->ipf_ecn = ecn_info;
12124 		ipf->ipf_num_dups = 0;
12125 		ipfb->ipfb_frag_pkts++;
12126 		ipf->ipf_checksum = 0;
12127 		ipf->ipf_checksum_flags = 0;
12128 
12129 		/* Store checksum value in fragment header */
12130 		if (sum_flags != 0) {
12131 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12132 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12133 			ipf->ipf_checksum = sum_val;
12134 			ipf->ipf_checksum_flags = sum_flags;
12135 		}
12136 
12137 		/*
12138 		 * We handle reassembly two ways.  In the easy case,
12139 		 * where all the fragments show up in order, we do
12140 		 * minimal bookkeeping, and just clip new pieces on
12141 		 * the end.  If we ever see a hole, then we go off
12142 		 * to ip_reassemble which has to mark the pieces and
12143 		 * keep track of the number of holes, etc.  Obviously,
12144 		 * the point of having both mechanisms is so we can
12145 		 * handle the easy case as efficiently as possible.
12146 		 */
12147 		if (offset == 0) {
12148 			/* Easy case, in-order reassembly so far. */
12149 			ipf->ipf_count += msg_len;
12150 			ipf->ipf_tail_mp = tail_mp;
12151 			/*
12152 			 * Keep track of next expected offset in
12153 			 * ipf_end.
12154 			 */
12155 			ipf->ipf_end = end;
12156 			ipf->ipf_nf_hdr_len = hdr_length;
12157 		} else {
12158 			/* Hard case, hole at the beginning. */
12159 			ipf->ipf_tail_mp = NULL;
12160 			/*
12161 			 * ipf_end == 0 means that we have given up
12162 			 * on easy reassembly.
12163 			 */
12164 			ipf->ipf_end = 0;
12165 
12166 			/* Forget checksum offload from now on */
12167 			ipf->ipf_checksum_flags = 0;
12168 
12169 			/*
12170 			 * ipf_hole_cnt is set by ip_reassemble.
12171 			 * ipf_count is updated by ip_reassemble.
12172 			 * No need to check for return value here
12173 			 * as we don't expect reassembly to complete
12174 			 * or fail for the first fragment itself.
12175 			 */
12176 			(void) ip_reassemble(mp, ipf,
12177 			    (frag_offset_flags & IPH_OFFSET) << 3,
12178 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12179 		}
12180 		/* Update per ipfb and ill byte counts */
12181 		ipfb->ipfb_count += ipf->ipf_count;
12182 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12183 		ill->ill_frag_count += ipf->ipf_count;
12184 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12185 		/* If the frag timer wasn't already going, start it. */
12186 		mutex_enter(&ill->ill_lock);
12187 		ill_frag_timer_start(ill);
12188 		mutex_exit(&ill->ill_lock);
12189 		goto reass_done;
12190 	}
12191 
12192 	/*
12193 	 * If the packet's flag has changed (it could be coming up
12194 	 * from an interface different than the previous, therefore
12195 	 * possibly different checksum capability), then forget about
12196 	 * any stored checksum states.  Otherwise add the value to
12197 	 * the existing one stored in the fragment header.
12198 	 */
12199 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12200 		sum_val += ipf->ipf_checksum;
12201 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12202 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12203 		ipf->ipf_checksum = sum_val;
12204 	} else if (ipf->ipf_checksum_flags != 0) {
12205 		/* Forget checksum offload from now on */
12206 		ipf->ipf_checksum_flags = 0;
12207 	}
12208 
12209 	/*
12210 	 * We have a new piece of a datagram which is already being
12211 	 * reassembled.  Update the ECN info if all IP fragments
12212 	 * are ECN capable.  If there is one which is not, clear
12213 	 * all the info.  If there is at least one which has CE
12214 	 * code point, IP needs to report that up to transport.
12215 	 */
12216 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12217 		if (ecn_info == IPH_ECN_CE)
12218 			ipf->ipf_ecn = IPH_ECN_CE;
12219 	} else {
12220 		ipf->ipf_ecn = IPH_ECN_NECT;
12221 	}
12222 	if (offset && ipf->ipf_end == offset) {
12223 		/* The new fragment fits at the end */
12224 		ipf->ipf_tail_mp->b_cont = mp;
12225 		/* Update the byte count */
12226 		ipf->ipf_count += msg_len;
12227 		/* Update per ipfb and ill byte counts */
12228 		ipfb->ipfb_count += msg_len;
12229 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12230 		ill->ill_frag_count += msg_len;
12231 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12232 		if (frag_offset_flags & IPH_MF) {
12233 			/* More to come. */
12234 			ipf->ipf_end = end;
12235 			ipf->ipf_tail_mp = tail_mp;
12236 			goto reass_done;
12237 		}
12238 	} else {
12239 		/* Go do the hard cases. */
12240 		int ret;
12241 
12242 		if (offset == 0)
12243 			ipf->ipf_nf_hdr_len = hdr_length;
12244 
12245 		/* Save current byte count */
12246 		count = ipf->ipf_count;
12247 		ret = ip_reassemble(mp, ipf,
12248 		    (frag_offset_flags & IPH_OFFSET) << 3,
12249 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12250 		/* Count of bytes added and subtracted (freeb()ed) */
12251 		count = ipf->ipf_count - count;
12252 		if (count) {
12253 			/* Update per ipfb and ill byte counts */
12254 			ipfb->ipfb_count += count;
12255 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12256 			ill->ill_frag_count += count;
12257 			ASSERT(ill->ill_frag_count > 0);
12258 		}
12259 		if (ret == IP_REASS_PARTIAL) {
12260 			goto reass_done;
12261 		} else if (ret == IP_REASS_FAILED) {
12262 			/* Reassembly failed. Free up all resources */
12263 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12264 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12265 				IP_REASS_SET_START(t_mp, 0);
12266 				IP_REASS_SET_END(t_mp, 0);
12267 			}
12268 			freemsg(mp);
12269 			goto reass_done;
12270 		}
12271 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12272 	}
12273 	/*
12274 	 * We have completed reassembly.  Unhook the frag header from
12275 	 * the reassembly list.
12276 	 *
12277 	 * Before we free the frag header, record the ECN info
12278 	 * to report back to the transport.
12279 	 */
12280 	ecn_info = ipf->ipf_ecn;
12281 	BUMP_MIB(&ip_mib, ipReasmOKs);
12282 	ipfp = ipf->ipf_ptphn;
12283 
12284 	/* We need to supply these to caller */
12285 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12286 		sum_val = ipf->ipf_checksum;
12287 	else
12288 		sum_val = 0;
12289 
12290 	mp1 = ipf->ipf_mp;
12291 	count = ipf->ipf_count;
12292 	ipf = ipf->ipf_hash_next;
12293 	if (ipf != NULL)
12294 		ipf->ipf_ptphn = ipfp;
12295 	ipfp[0] = ipf;
12296 	ill->ill_frag_count -= count;
12297 	ASSERT(ipfb->ipfb_count >= count);
12298 	ipfb->ipfb_count -= count;
12299 	ipfb->ipfb_frag_pkts--;
12300 	mutex_exit(&ipfb->ipfb_lock);
12301 	/* Ditch the frag header. */
12302 	mp = mp1->b_cont;
12303 
12304 	freeb(mp1);
12305 
12306 	/* Restore original IP length in header. */
12307 	packet_size = (uint32_t)msgdsize(mp);
12308 	if (packet_size > IP_MAXPACKET) {
12309 		freemsg(mp);
12310 		BUMP_MIB(&ip_mib, ipInHdrErrors);
12311 		return (B_FALSE);
12312 	}
12313 
12314 	if (DB_REF(mp) > 1) {
12315 		mblk_t *mp2 = copymsg(mp);
12316 
12317 		freemsg(mp);
12318 		if (mp2 == NULL) {
12319 			BUMP_MIB(&ip_mib, ipInDiscards);
12320 			return (B_FALSE);
12321 		}
12322 		mp = mp2;
12323 	}
12324 	ipha = (ipha_t *)mp->b_rptr;
12325 
12326 	ipha->ipha_length = htons((uint16_t)packet_size);
12327 	/* We're now complete, zip the frag state */
12328 	ipha->ipha_fragment_offset_and_flags = 0;
12329 	/* Record the ECN info. */
12330 	ipha->ipha_type_of_service &= 0xFC;
12331 	ipha->ipha_type_of_service |= ecn_info;
12332 	*mpp = mp;
12333 
12334 	/* Reassembly is successful; return checksum information if needed */
12335 	if (cksum_val != NULL)
12336 		*cksum_val = sum_val;
12337 	if (cksum_flags != NULL)
12338 		*cksum_flags = sum_flags;
12339 
12340 	return (B_TRUE);
12341 }
12342 
12343 /*
12344  * Perform ip header check sum update local options.
12345  * return B_TRUE if all is well, else return B_FALSE and release
12346  * the mp. caller is responsible for decrementing ire ref cnt.
12347  */
12348 static boolean_t
12349 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12350 {
12351 	mblk_t		*first_mp;
12352 	boolean_t	mctl_present;
12353 	uint16_t	sum;
12354 
12355 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12356 	/*
12357 	 * Don't do the checksum if it has gone through AH/ESP
12358 	 * processing.
12359 	 */
12360 	if (!mctl_present) {
12361 		sum = ip_csum_hdr(ipha);
12362 		if (sum != 0) {
12363 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12364 			freemsg(first_mp);
12365 			return (B_FALSE);
12366 		}
12367 	}
12368 
12369 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12370 		if (mctl_present)
12371 			freeb(first_mp);
12372 		return (B_FALSE);
12373 	}
12374 
12375 	return (B_TRUE);
12376 }
12377 
12378 /*
12379  * All udp packet are delivered to the local host via this routine.
12380  */
12381 void
12382 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12383     ill_t *recv_ill)
12384 {
12385 	uint32_t	sum;
12386 	uint32_t	u1;
12387 	boolean_t	mctl_present;
12388 	conn_t		*connp;
12389 	mblk_t		*first_mp;
12390 	uint16_t	*up;
12391 	ill_t		*ill = (ill_t *)q->q_ptr;
12392 	uint16_t	reass_hck_flags = 0;
12393 
12394 #define	rptr    ((uchar_t *)ipha)
12395 
12396 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12397 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12398 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12399 
12400 	/*
12401 	 * FAST PATH for udp packets
12402 	 */
12403 
12404 	/* u1 is # words of IP options */
12405 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12406 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12407 
12408 	/* IP options present */
12409 	if (u1 != 0)
12410 		goto ipoptions;
12411 
12412 	/* Check the IP header checksum.  */
12413 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12414 		/* Clear the IP header h/w cksum flag */
12415 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12416 	} else {
12417 #define	uph	((uint16_t *)ipha)
12418 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12419 		    uph[6] + uph[7] + uph[8] + uph[9];
12420 #undef	uph
12421 		/* finish doing IP checksum */
12422 		sum = (sum & 0xFFFF) + (sum >> 16);
12423 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12424 		/*
12425 		 * Don't verify header checksum if this packet is coming
12426 		 * back from AH/ESP as we already did it.
12427 		 */
12428 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12429 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12430 			freemsg(first_mp);
12431 			return;
12432 		}
12433 	}
12434 
12435 	/*
12436 	 * Count for SNMP of inbound packets for ire.
12437 	 * if mctl is present this might be a secure packet and
12438 	 * has already been counted for in ip_proto_input().
12439 	 */
12440 	if (!mctl_present) {
12441 		UPDATE_IB_PKT_COUNT(ire);
12442 		ire->ire_last_used_time = lbolt;
12443 	}
12444 
12445 	/* packet part of fragmented IP packet? */
12446 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12447 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12448 		goto fragmented;
12449 	}
12450 
12451 	/* u1 = IP header length (20 bytes) */
12452 	u1 = IP_SIMPLE_HDR_LENGTH;
12453 
12454 	/* packet does not contain complete IP & UDP headers */
12455 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12456 		goto udppullup;
12457 
12458 	/* up points to UDP header */
12459 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12460 #define	iphs    ((uint16_t *)ipha)
12461 
12462 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12463 	if (up[3] != 0) {
12464 		mblk_t *mp1 = mp->b_cont;
12465 		boolean_t cksum_err;
12466 		uint16_t hck_flags = 0;
12467 
12468 		/* Pseudo-header checksum */
12469 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12470 		    iphs[9] + up[2];
12471 
12472 		/*
12473 		 * Revert to software checksum calculation if the interface
12474 		 * isn't capable of checksum offload or if IPsec is present.
12475 		 */
12476 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12477 			hck_flags = DB_CKSUMFLAGS(mp);
12478 
12479 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12480 			IP_STAT(ip_in_sw_cksum);
12481 
12482 		IP_CKSUM_RECV(hck_flags, u1,
12483 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12484 		    (int32_t)((uchar_t *)up - rptr),
12485 		    mp, mp1, cksum_err);
12486 
12487 		if (cksum_err) {
12488 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12489 
12490 			if (hck_flags & HCK_FULLCKSUM)
12491 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12492 			else if (hck_flags & HCK_PARTIALCKSUM)
12493 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12494 			else
12495 				IP_STAT(ip_udp_in_sw_cksum_err);
12496 
12497 			freemsg(first_mp);
12498 			return;
12499 		}
12500 	}
12501 
12502 	/* Non-fragmented broadcast or multicast packet? */
12503 	if (ire->ire_type == IRE_BROADCAST)
12504 		goto udpslowpath;
12505 
12506 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12507 	    ire->ire_zoneid)) != NULL) {
12508 		ASSERT(connp->conn_upq != NULL);
12509 		IP_STAT(ip_udp_fast_path);
12510 
12511 		if (CONN_UDP_FLOWCTLD(connp)) {
12512 			freemsg(mp);
12513 			BUMP_MIB(&ip_mib, udpInOverflows);
12514 		} else {
12515 			if (!mctl_present) {
12516 				BUMP_MIB(&ip_mib, ipInDelivers);
12517 			}
12518 			/*
12519 			 * mp and first_mp can change.
12520 			 */
12521 			if (ip_udp_check(q, connp, recv_ill,
12522 			    ipha, &mp, &first_mp, mctl_present)) {
12523 				/* Send it upstream */
12524 				CONN_UDP_RECV(connp, mp);
12525 			}
12526 		}
12527 		/*
12528 		 * freeb() cannot deal with null mblk being passed
12529 		 * in and first_mp can be set to null in the call
12530 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12531 		 */
12532 		if (mctl_present && first_mp != NULL) {
12533 			freeb(first_mp);
12534 		}
12535 		CONN_DEC_REF(connp);
12536 		return;
12537 	}
12538 
12539 	/*
12540 	 * if we got here we know the packet is not fragmented and
12541 	 * has no options. The classifier could not find a conn_t and
12542 	 * most likely its an icmp packet so send it through slow path.
12543 	 */
12544 
12545 	goto udpslowpath;
12546 
12547 ipoptions:
12548 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12549 		goto slow_done;
12550 	}
12551 
12552 	UPDATE_IB_PKT_COUNT(ire);
12553 	ire->ire_last_used_time = lbolt;
12554 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12555 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12556 fragmented:
12557 		/*
12558 		 * "sum" and "reass_hck_flags" are non-zero if the
12559 		 * reassembled packet has a valid hardware computed
12560 		 * checksum information associated with it.
12561 		 */
12562 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12563 			goto slow_done;
12564 		/*
12565 		 * Make sure that first_mp points back to mp as
12566 		 * the mp we came in with could have changed in
12567 		 * ip_rput_fragment().
12568 		 */
12569 		ASSERT(!mctl_present);
12570 		ipha = (ipha_t *)mp->b_rptr;
12571 		first_mp = mp;
12572 	}
12573 
12574 	/* Now we have a complete datagram, destined for this machine. */
12575 	u1 = IPH_HDR_LENGTH(ipha);
12576 	/* Pull up the UDP header, if necessary. */
12577 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12578 udppullup:
12579 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12580 			BUMP_MIB(&ip_mib, ipInDiscards);
12581 			freemsg(first_mp);
12582 			goto slow_done;
12583 		}
12584 		ipha = (ipha_t *)mp->b_rptr;
12585 	}
12586 
12587 	/*
12588 	 * Validate the checksum for the reassembled packet; for the
12589 	 * pullup case we calculate the payload checksum in software.
12590 	 */
12591 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12592 	if (up[3] != 0) {
12593 		boolean_t cksum_err;
12594 
12595 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12596 			IP_STAT(ip_in_sw_cksum);
12597 
12598 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12599 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12600 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12601 		    iphs[9] + up[2], sum, cksum_err);
12602 
12603 		if (cksum_err) {
12604 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12605 
12606 			if (reass_hck_flags & HCK_FULLCKSUM)
12607 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12608 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12609 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12610 			else
12611 				IP_STAT(ip_udp_in_sw_cksum_err);
12612 
12613 			freemsg(first_mp);
12614 			goto slow_done;
12615 		}
12616 	}
12617 udpslowpath:
12618 
12619 	/* Clear hardware checksum flag to be safe */
12620 	DB_CKSUMFLAGS(mp) = 0;
12621 
12622 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12623 	    (ire->ire_type == IRE_BROADCAST),
12624 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12625 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12626 
12627 slow_done:
12628 	IP_STAT(ip_udp_slow_path);
12629 	return;
12630 
12631 #undef  iphs
12632 #undef  rptr
12633 }
12634 
12635 /* ARGSUSED */
12636 static mblk_t *
12637 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12638     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12639     ill_rx_ring_t *ill_ring)
12640 {
12641 	conn_t		*connp;
12642 	uint32_t	sum;
12643 	uint32_t	u1;
12644 	uint16_t	*up;
12645 	int		offset;
12646 	ssize_t		len;
12647 	mblk_t		*mp1;
12648 	boolean_t	syn_present = B_FALSE;
12649 	tcph_t		*tcph;
12650 	uint_t		ip_hdr_len;
12651 	ill_t		*ill = (ill_t *)q->q_ptr;
12652 	zoneid_t	zoneid = ire->ire_zoneid;
12653 	boolean_t	cksum_err;
12654 	uint16_t	hck_flags = 0;
12655 
12656 #define	rptr	((uchar_t *)ipha)
12657 
12658 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12659 
12660 	/*
12661 	 * FAST PATH for tcp packets
12662 	 */
12663 
12664 	/* u1 is # words of IP options */
12665 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12666 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12667 
12668 	/* IP options present */
12669 	if (u1) {
12670 		goto ipoptions;
12671 	} else {
12672 		/* Check the IP header checksum.  */
12673 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12674 			/* Clear the IP header h/w cksum flag */
12675 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12676 		} else {
12677 #define	uph	((uint16_t *)ipha)
12678 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12679 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12680 #undef	uph
12681 			/* finish doing IP checksum */
12682 			sum = (sum & 0xFFFF) + (sum >> 16);
12683 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12684 			/*
12685 			 * Don't verify header checksum if this packet
12686 			 * is coming back from AH/ESP as we already did it.
12687 			 */
12688 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12689 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12690 				goto error;
12691 			}
12692 		}
12693 	}
12694 
12695 	if (!mctl_present) {
12696 		UPDATE_IB_PKT_COUNT(ire);
12697 		ire->ire_last_used_time = lbolt;
12698 	}
12699 
12700 	/* packet part of fragmented IP packet? */
12701 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12702 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12703 		goto fragmented;
12704 	}
12705 
12706 	/* u1 = IP header length (20 bytes) */
12707 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12708 
12709 	/* does packet contain IP+TCP headers? */
12710 	len = mp->b_wptr - rptr;
12711 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12712 		IP_STAT(ip_tcppullup);
12713 		goto tcppullup;
12714 	}
12715 
12716 	/* TCP options present? */
12717 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12718 
12719 	/*
12720 	 * If options need to be pulled up, then goto tcpoptions.
12721 	 * otherwise we are still in the fast path
12722 	 */
12723 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12724 		IP_STAT(ip_tcpoptions);
12725 		goto tcpoptions;
12726 	}
12727 
12728 	/* multiple mblks of tcp data? */
12729 	if ((mp1 = mp->b_cont) != NULL) {
12730 		/* more then two? */
12731 		if (mp1->b_cont != NULL) {
12732 			IP_STAT(ip_multipkttcp);
12733 			goto multipkttcp;
12734 		}
12735 		len += mp1->b_wptr - mp1->b_rptr;
12736 	}
12737 
12738 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12739 
12740 	/* part of pseudo checksum */
12741 
12742 	/* TCP datagram length */
12743 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12744 
12745 #define	iphs    ((uint16_t *)ipha)
12746 
12747 #ifdef	_BIG_ENDIAN
12748 	u1 += IPPROTO_TCP;
12749 #else
12750 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12751 #endif
12752 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12753 
12754 	/*
12755 	 * Revert to software checksum calculation if the interface
12756 	 * isn't capable of checksum offload or if IPsec is present.
12757 	 */
12758 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12759 		hck_flags = DB_CKSUMFLAGS(mp);
12760 
12761 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12762 		IP_STAT(ip_in_sw_cksum);
12763 
12764 	IP_CKSUM_RECV(hck_flags, u1,
12765 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12766 	    (int32_t)((uchar_t *)up - rptr),
12767 	    mp, mp1, cksum_err);
12768 
12769 	if (cksum_err) {
12770 		BUMP_MIB(&ip_mib, tcpInErrs);
12771 
12772 		if (hck_flags & HCK_FULLCKSUM)
12773 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12774 		else if (hck_flags & HCK_PARTIALCKSUM)
12775 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12776 		else
12777 			IP_STAT(ip_tcp_in_sw_cksum_err);
12778 
12779 		goto error;
12780 	}
12781 
12782 try_again:
12783 
12784 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12785 	    NULL) {
12786 		/* Send the TH_RST */
12787 		goto no_conn;
12788 	}
12789 
12790 	/*
12791 	 * TCP FAST PATH for AF_INET socket.
12792 	 *
12793 	 * TCP fast path to avoid extra work. An AF_INET socket type
12794 	 * does not have facility to receive extra information via
12795 	 * ip_process or ip_add_info. Also, when the connection was
12796 	 * established, we made a check if this connection is impacted
12797 	 * by any global IPSec policy or per connection policy (a
12798 	 * policy that comes in effect later will not apply to this
12799 	 * connection). Since all this can be determined at the
12800 	 * connection establishment time, a quick check of flags
12801 	 * can avoid extra work.
12802 	 */
12803 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12804 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12805 		ASSERT(first_mp == mp);
12806 		SET_SQUEUE(mp, tcp_rput_data, connp);
12807 		return (mp);
12808 	}
12809 
12810 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12811 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12812 		if (IPCL_IS_TCP(connp)) {
12813 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12814 			DB_CKSUMSTART(mp) =
12815 			    (intptr_t)ip_squeue_get(ill_ring);
12816 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12817 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12818 				SET_SQUEUE(mp, connp->conn_recv, connp);
12819 				return (mp);
12820 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12821 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12822 				ip_squeue_enter_unbound++;
12823 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12824 				    connp);
12825 				return (mp);
12826 			}
12827 			syn_present = B_TRUE;
12828 		}
12829 
12830 	}
12831 
12832 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12833 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12834 
12835 		/* No need to send this packet to TCP */
12836 		if ((flags & TH_RST) || (flags & TH_URG)) {
12837 			CONN_DEC_REF(connp);
12838 			freemsg(first_mp);
12839 			return (NULL);
12840 		}
12841 		if (flags & TH_ACK) {
12842 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
12843 			CONN_DEC_REF(connp);
12844 			return (NULL);
12845 		}
12846 
12847 		CONN_DEC_REF(connp);
12848 		freemsg(first_mp);
12849 		return (NULL);
12850 	}
12851 
12852 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12853 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12854 		    ipha, NULL, mctl_present);
12855 		if (first_mp == NULL) {
12856 			CONN_DEC_REF(connp);
12857 			return (NULL);
12858 		}
12859 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12860 			ASSERT(syn_present);
12861 			if (mctl_present) {
12862 				ASSERT(first_mp != mp);
12863 				first_mp->b_datap->db_struioflag |=
12864 				    STRUIO_POLICY;
12865 			} else {
12866 				ASSERT(first_mp == mp);
12867 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12868 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12869 			}
12870 		} else {
12871 			/*
12872 			 * Discard first_mp early since we're dealing with a
12873 			 * fully-connected conn_t and tcp doesn't do policy in
12874 			 * this case.
12875 			 */
12876 			if (mctl_present) {
12877 				freeb(first_mp);
12878 				mctl_present = B_FALSE;
12879 			}
12880 			first_mp = mp;
12881 		}
12882 	}
12883 
12884 	/* Initiate IPPF processing for fastpath */
12885 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12886 		uint32_t	ill_index;
12887 
12888 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12889 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12890 		if (mp == NULL) {
12891 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12892 			    "deferred/dropped during IPPF processing\n"));
12893 			CONN_DEC_REF(connp);
12894 			if (mctl_present)
12895 				freeb(first_mp);
12896 			return (NULL);
12897 		} else if (mctl_present) {
12898 			/*
12899 			 * ip_process might return a new mp.
12900 			 */
12901 			ASSERT(first_mp != mp);
12902 			first_mp->b_cont = mp;
12903 		} else {
12904 			first_mp = mp;
12905 		}
12906 
12907 	}
12908 
12909 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12910 		mp = ip_add_info(mp, recv_ill, flags);
12911 		if (mp == NULL) {
12912 			CONN_DEC_REF(connp);
12913 			if (mctl_present)
12914 				freeb(first_mp);
12915 			return (NULL);
12916 		} else if (mctl_present) {
12917 			/*
12918 			 * ip_add_info might return a new mp.
12919 			 */
12920 			ASSERT(first_mp != mp);
12921 			first_mp->b_cont = mp;
12922 		} else {
12923 			first_mp = mp;
12924 		}
12925 	}
12926 
12927 	if (IPCL_IS_TCP(connp)) {
12928 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
12929 		return (first_mp);
12930 	} else {
12931 		putnext(connp->conn_rq, first_mp);
12932 		CONN_DEC_REF(connp);
12933 		return (NULL);
12934 	}
12935 
12936 no_conn:
12937 	/* Initiate IPPf processing, if needed. */
12938 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12939 		uint32_t ill_index;
12940 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12941 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
12942 		if (first_mp == NULL) {
12943 			return (NULL);
12944 		}
12945 	}
12946 	BUMP_MIB(&ip_mib, ipInDelivers);
12947 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid);
12948 	return (NULL);
12949 ipoptions:
12950 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
12951 		goto slow_done;
12952 	}
12953 
12954 	UPDATE_IB_PKT_COUNT(ire);
12955 	ire->ire_last_used_time = lbolt;
12956 
12957 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12958 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12959 fragmented:
12960 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
12961 			if (mctl_present)
12962 				freeb(first_mp);
12963 			goto slow_done;
12964 		}
12965 		/*
12966 		 * Make sure that first_mp points back to mp as
12967 		 * the mp we came in with could have changed in
12968 		 * ip_rput_fragment().
12969 		 */
12970 		ASSERT(!mctl_present);
12971 		ipha = (ipha_t *)mp->b_rptr;
12972 		first_mp = mp;
12973 	}
12974 
12975 	/* Now we have a complete datagram, destined for this machine. */
12976 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12977 
12978 	len = mp->b_wptr - mp->b_rptr;
12979 	/* Pull up a minimal TCP header, if necessary. */
12980 	if (len < (u1 + 20)) {
12981 tcppullup:
12982 		if (!pullupmsg(mp, u1 + 20)) {
12983 			BUMP_MIB(&ip_mib, ipInDiscards);
12984 			goto error;
12985 		}
12986 		ipha = (ipha_t *)mp->b_rptr;
12987 		len = mp->b_wptr - mp->b_rptr;
12988 	}
12989 
12990 	/*
12991 	 * Extract the offset field from the TCP header.  As usual, we
12992 	 * try to help the compiler more than the reader.
12993 	 */
12994 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
12995 	if (offset != 5) {
12996 tcpoptions:
12997 		if (offset < 5) {
12998 			BUMP_MIB(&ip_mib, ipInDiscards);
12999 			goto error;
13000 		}
13001 		/*
13002 		 * There must be TCP options.
13003 		 * Make sure we can grab them.
13004 		 */
13005 		offset <<= 2;
13006 		offset += u1;
13007 		if (len < offset) {
13008 			if (!pullupmsg(mp, offset)) {
13009 				BUMP_MIB(&ip_mib, ipInDiscards);
13010 				goto error;
13011 			}
13012 			ipha = (ipha_t *)mp->b_rptr;
13013 			len = mp->b_wptr - rptr;
13014 		}
13015 	}
13016 
13017 	/* Get the total packet length in len, including headers. */
13018 	if (mp->b_cont) {
13019 multipkttcp:
13020 		len = msgdsize(mp);
13021 	}
13022 
13023 	/*
13024 	 * Check the TCP checksum by pulling together the pseudo-
13025 	 * header checksum, and passing it to ip_csum to be added in
13026 	 * with the TCP datagram.
13027 	 *
13028 	 * Since we are not using the hwcksum if available we must
13029 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13030 	 * If either of these fails along the way the mblk is freed.
13031 	 * If this logic ever changes and mblk is reused to say send
13032 	 * ICMP's back, then this flag may need to be cleared in
13033 	 * other places as well.
13034 	 */
13035 	DB_CKSUMFLAGS(mp) = 0;
13036 
13037 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13038 
13039 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13040 #ifdef	_BIG_ENDIAN
13041 	u1 += IPPROTO_TCP;
13042 #else
13043 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13044 #endif
13045 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13046 	/*
13047 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13048 	 */
13049 	IP_STAT(ip_in_sw_cksum);
13050 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13051 		BUMP_MIB(&ip_mib, tcpInErrs);
13052 		goto error;
13053 	}
13054 
13055 	IP_STAT(ip_tcp_slow_path);
13056 	goto try_again;
13057 #undef  iphs
13058 #undef  rptr
13059 
13060 error:
13061 	freemsg(first_mp);
13062 slow_done:
13063 	return (NULL);
13064 }
13065 
13066 /* ARGSUSED */
13067 static void
13068 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13069     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13070 {
13071 	conn_t		*connp;
13072 	uint32_t	sum;
13073 	uint32_t	u1;
13074 	ssize_t		len;
13075 	sctp_hdr_t	*sctph;
13076 	zoneid_t	zoneid = ire->ire_zoneid;
13077 	uint32_t	pktsum;
13078 	uint32_t	calcsum;
13079 	uint32_t	ports;
13080 	uint_t		ipif_seqid;
13081 	in6_addr_t	map_src, map_dst;
13082 	ill_t		*ill = (ill_t *)q->q_ptr;
13083 
13084 #define	rptr	((uchar_t *)ipha)
13085 
13086 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13087 
13088 	/* u1 is # words of IP options */
13089 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13090 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13091 
13092 	/* IP options present */
13093 	if (u1 > 0) {
13094 		goto ipoptions;
13095 	} else {
13096 		/* Check the IP header checksum.  */
13097 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13098 #define	uph	((uint16_t *)ipha)
13099 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13100 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13101 #undef	uph
13102 			/* finish doing IP checksum */
13103 			sum = (sum & 0xFFFF) + (sum >> 16);
13104 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13105 			/*
13106 			 * Don't verify header checksum if this packet
13107 			 * is coming back from AH/ESP as we already did it.
13108 			 */
13109 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13110 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13111 				goto error;
13112 			}
13113 		}
13114 		/*
13115 		 * Since there is no SCTP h/w cksum support yet, just
13116 		 * clear the flag.
13117 		 */
13118 		DB_CKSUMFLAGS(mp) = 0;
13119 	}
13120 
13121 	/*
13122 	 * Don't verify header checksum if this packet is coming
13123 	 * back from AH/ESP as we already did it.
13124 	 */
13125 	if (!mctl_present) {
13126 		UPDATE_IB_PKT_COUNT(ire);
13127 		ire->ire_last_used_time = lbolt;
13128 	}
13129 
13130 	/* packet part of fragmented IP packet? */
13131 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13132 	if (u1 & (IPH_MF | IPH_OFFSET))
13133 		goto fragmented;
13134 
13135 	/* u1 = IP header length (20 bytes) */
13136 	u1 = IP_SIMPLE_HDR_LENGTH;
13137 
13138 find_sctp_client:
13139 	/* Pullup if we don't have the sctp common header. */
13140 	len = MBLKL(mp);
13141 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13142 		if (mp->b_cont == NULL ||
13143 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13144 			BUMP_MIB(&ip_mib, ipInDiscards);
13145 			goto error;
13146 		}
13147 		ipha = (ipha_t *)mp->b_rptr;
13148 		len = MBLKL(mp);
13149 	}
13150 
13151 	sctph = (sctp_hdr_t *)(rptr + u1);
13152 #ifdef	DEBUG
13153 	if (!skip_sctp_cksum) {
13154 #endif
13155 		pktsum = sctph->sh_chksum;
13156 		sctph->sh_chksum = 0;
13157 		calcsum = sctp_cksum(mp, u1);
13158 		if (calcsum != pktsum) {
13159 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13160 			goto error;
13161 		}
13162 		sctph->sh_chksum = pktsum;
13163 #ifdef	DEBUG	/* skip_sctp_cksum */
13164 	}
13165 #endif
13166 	/* get the ports */
13167 	ports = *(uint32_t *)&sctph->sh_sport;
13168 
13169 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13170 	IRE_REFRELE(ire);
13171 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13172 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13173 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13174 	    mp)) == NULL) {
13175 		/* Check for raw socket or OOTB handling */
13176 		goto no_conn;
13177 	}
13178 
13179 	/* Found a client; up it goes */
13180 	BUMP_MIB(&ip_mib, ipInDelivers);
13181 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13182 	return;
13183 
13184 no_conn:
13185 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13186 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13187 	return;
13188 
13189 ipoptions:
13190 	DB_CKSUMFLAGS(mp) = 0;
13191 	if (!ip_options_cksum(q, first_mp, ipha, ire))
13192 		goto slow_done;
13193 
13194 	UPDATE_IB_PKT_COUNT(ire);
13195 	ire->ire_last_used_time = lbolt;
13196 
13197 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13198 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13199 fragmented:
13200 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13201 			goto slow_done;
13202 		/*
13203 		 * Make sure that first_mp points back to mp as
13204 		 * the mp we came in with could have changed in
13205 		 * ip_rput_fragment().
13206 		 */
13207 		ASSERT(!mctl_present);
13208 		ipha = (ipha_t *)mp->b_rptr;
13209 		first_mp = mp;
13210 	}
13211 
13212 	/* Now we have a complete datagram, destined for this machine. */
13213 	u1 = IPH_HDR_LENGTH(ipha);
13214 	goto find_sctp_client;
13215 #undef  iphs
13216 #undef  rptr
13217 
13218 error:
13219 	freemsg(first_mp);
13220 slow_done:
13221 	IRE_REFRELE(ire);
13222 }
13223 
13224 #define	VER_BITS	0xF0
13225 #define	VERSION_6	0x60
13226 
13227 static boolean_t
13228 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
13229     ipaddr_t *dstp)
13230 {
13231 	uint_t	opt_len;
13232 	ipha_t *ipha;
13233 	ssize_t len;
13234 	uint_t	pkt_len;
13235 
13236 	IP_STAT(ip_ipoptions);
13237 	ipha = *iphapp;
13238 
13239 #define	rptr    ((uchar_t *)ipha)
13240 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13241 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13242 		BUMP_MIB(&ip_mib, ipInIPv6);
13243 		freemsg(mp);
13244 		return (B_FALSE);
13245 	}
13246 
13247 	/* multiple mblk or too short */
13248 	pkt_len = ntohs(ipha->ipha_length);
13249 
13250 	/* Get the number of words of IP options in the IP header. */
13251 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13252 	if (opt_len) {
13253 		/* IP Options present!  Validate and process. */
13254 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13255 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13256 			goto done;
13257 		}
13258 		/*
13259 		 * Recompute complete header length and make sure we
13260 		 * have access to all of it.
13261 		 */
13262 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13263 		if (len > (mp->b_wptr - rptr)) {
13264 			if (len > pkt_len) {
13265 				BUMP_MIB(&ip_mib, ipInHdrErrors);
13266 				goto done;
13267 			}
13268 			if (!pullupmsg(mp, len)) {
13269 				BUMP_MIB(&ip_mib, ipInDiscards);
13270 				goto done;
13271 			}
13272 			ipha = (ipha_t *)mp->b_rptr;
13273 		}
13274 		/*
13275 		 * Go off to ip_rput_options which returns the next hop
13276 		 * destination address, which may have been affected
13277 		 * by source routing.
13278 		 */
13279 		IP_STAT(ip_opt);
13280 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13281 			return (B_FALSE);
13282 		}
13283 	}
13284 	*iphapp = ipha;
13285 	return (B_TRUE);
13286 done:
13287 	/* clear b_prev - used by ip_mroute_decap */
13288 	mp->b_prev = NULL;
13289 	freemsg(mp);
13290 	return (B_FALSE);
13291 #undef  rptr
13292 }
13293 
13294 /*
13295  * Deal with the fact that there is no ire for the destination.
13296  * The incoming ill (in_ill) is passed in to ip_newroute only
13297  * in the case of packets coming from mobile ip forward tunnel.
13298  * It must be null otherwise.
13299  */
13300 static ire_t *
13301 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13302     ipaddr_t dst)
13303 {
13304 	ipha_t	*ipha;
13305 	ill_t	*ill;
13306 	ire_t	*ire;
13307 	boolean_t	check_multirt = B_FALSE;
13308 
13309 	ipha = (ipha_t *)mp->b_rptr;
13310 	ill = (ill_t *)q->q_ptr;
13311 
13312 	ASSERT(ill != NULL);
13313 	/*
13314 	 * No IRE for this destination, so it can't be for us.
13315 	 * Unless we are forwarding, drop the packet.
13316 	 * We have to let source routed packets through
13317 	 * since we don't yet know if they are 'ping -l'
13318 	 * packets i.e. if they will go out over the
13319 	 * same interface as they came in on.
13320 	 */
13321 	if (ll_multicast) {
13322 		freemsg(mp);
13323 		return (NULL);
13324 	}
13325 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13326 		BUMP_MIB(&ip_mib, ipForwProhibits);
13327 		freemsg(mp);
13328 		return (NULL);
13329 	}
13330 
13331 	/*
13332 	 * Mark this packet as having originated externally.
13333 	 *
13334 	 * For non-forwarding code path, ire_send later double
13335 	 * checks this interface to see if it is still exists
13336 	 * post-ARP resolution.
13337 	 *
13338 	 * Also, IPQOS uses this to differentiate between
13339 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13340 	 * QOS packet processing in ip_wput_attach_llhdr().
13341 	 * The QoS module can mark the b_band for a fastpath message
13342 	 * or the dl_priority field in a unitdata_req header for
13343 	 * CoS marking. This info can only be found in
13344 	 * ip_wput_attach_llhdr().
13345 	 */
13346 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13347 	/*
13348 	 * Clear the indication that this may have a hardware checksum
13349 	 * as we are not using it
13350 	 */
13351 	DB_CKSUMFLAGS(mp) = 0;
13352 
13353 	if (in_ill != NULL) {
13354 		/*
13355 		 * Now hand the packet to ip_newroute.
13356 		 */
13357 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13358 		return (NULL);
13359 	}
13360 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13361 	    MBLK_GETLABEL(mp));
13362 
13363 	if (ire == NULL && check_multirt) {
13364 		/* Let ip_newroute handle CGTP  */
13365 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13366 		return (NULL);
13367 	}
13368 
13369 	if (ire != NULL)
13370 		return (ire);
13371 
13372 	mp->b_prev = mp->b_next = 0;
13373 	/* send icmp unreachable */
13374 	q = WR(q);
13375 	/* Sent by forwarding path, and router is global zone */
13376 	if (ip_source_routed(ipha)) {
13377 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13378 		    GLOBAL_ZONEID);
13379 	} else {
13380 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13381 	}
13382 
13383 	return (NULL);
13384 
13385 }
13386 
13387 /*
13388  * check ip header length and align it.
13389  */
13390 static boolean_t
13391 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13392 {
13393 	ssize_t len;
13394 	ill_t *ill;
13395 	ipha_t	*ipha;
13396 
13397 	len = MBLKL(mp);
13398 
13399 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13400 		if (!OK_32PTR(mp->b_rptr))
13401 			IP_STAT(ip_notaligned1);
13402 		else
13403 			IP_STAT(ip_notaligned2);
13404 		/* Guard against bogus device drivers */
13405 		if (len < 0) {
13406 			/* clear b_prev - used by ip_mroute_decap */
13407 			mp->b_prev = NULL;
13408 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13409 			freemsg(mp);
13410 			return (B_FALSE);
13411 		}
13412 
13413 		if (ip_rput_pullups++ == 0) {
13414 			ill = (ill_t *)q->q_ptr;
13415 			ipha = (ipha_t *)mp->b_rptr;
13416 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13417 			    "ip_check_and_align_header: %s forced us to "
13418 			    " pullup pkt, hdr len %ld, hdr addr %p",
13419 			    ill->ill_name, len, ipha);
13420 		}
13421 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13422 			/* clear b_prev - used by ip_mroute_decap */
13423 			mp->b_prev = NULL;
13424 			BUMP_MIB(&ip_mib, ipInDiscards);
13425 			freemsg(mp);
13426 			return (B_FALSE);
13427 		}
13428 	}
13429 	return (B_TRUE);
13430 }
13431 
13432 static boolean_t
13433 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13434 {
13435 	ill_group_t	*ill_group;
13436 	ill_group_t	*ire_group;
13437 	queue_t 	*q;
13438 	ill_t		*ire_ill;
13439 	uint_t		ill_ifindex;
13440 
13441 	q = *qp;
13442 	/*
13443 	 * We need to check to make sure the packet came in
13444 	 * on the queue associated with the destination IRE.
13445 	 * Note that for multicast packets and broadcast packets sent to
13446 	 * a broadcast address which is shared between multiple interfaces
13447 	 * we should not do this since we just got a random broadcast ire.
13448 	 */
13449 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13450 		boolean_t check_multi = B_TRUE;
13451 
13452 		/*
13453 		 * This packet came in on an interface other than the
13454 		 * one associated with the destination address.
13455 		 * "Gateway" it to the appropriate interface here.
13456 		 * As long as the ills belong to the same group,
13457 		 * we don't consider them to arriving on the wrong
13458 		 * interface. Thus, when the switch is doing inbound
13459 		 * load spreading, we won't drop packets when we
13460 		 * are doing strict multihoming checks. Note, the
13461 		 * same holds true for 'usesrc groups' where the
13462 		 * destination address may belong to another interface
13463 		 * to allow multipathing to happen
13464 		 */
13465 		ill_group = ill->ill_group;
13466 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13467 		ill_ifindex = ill->ill_usesrc_ifindex;
13468 		ire_group = ire_ill->ill_group;
13469 
13470 		/*
13471 		 * If it's part of the same IPMP group, or if it's a legal
13472 		 * address on the 'usesrc' interface, then bypass strict
13473 		 * checks.
13474 		 */
13475 		if (ill_group != NULL && ill_group == ire_group) {
13476 			check_multi = B_FALSE;
13477 		} else if (ill_ifindex != 0 &&
13478 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13479 			check_multi = B_FALSE;
13480 		}
13481 
13482 		if (check_multi &&
13483 		    ip_strict_dst_multihoming &&
13484 		    ((ill->ill_flags &
13485 		    ire->ire_ipif->ipif_ill->ill_flags &
13486 		    ILLF_ROUTER) == 0)) {
13487 			/* Drop packet */
13488 			BUMP_MIB(&ip_mib, ipForwProhibits);
13489 			freemsg(mp);
13490 			return (B_TRUE);
13491 		}
13492 
13493 		/*
13494 		 * Change the queue (for non-virtual destination network
13495 		 * interfaces) and ip_rput_local will be called with the right
13496 		 * queue
13497 		 */
13498 		q = ire->ire_rfq;
13499 	}
13500 	/* Must be broadcast.  We'll take it. */
13501 	*qp = q;
13502 	return (B_FALSE);
13503 }
13504 
13505 #define	SEND_PKT(ire, mp)			\
13506 {						\
13507 	UPDATE_IB_PKT_COUNT(ire);		\
13508 	(ire)->ire_last_used_time = lbolt;	\
13509 	BUMP_MIB(&ip_mib, ipForwDatagrams);	\
13510 	putnext((ire)->ire_stq, mp);		\
13511 }
13512 
13513 ire_t *
13514 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13515 {
13516 	ipha_t	*ipha;
13517 	ipaddr_t ip_dst, ip_src;
13518 	ire_t	*src_ire = NULL;
13519 	ill_t	*stq_ill;
13520 	uint_t	hlen;
13521 	uint32_t sum;
13522 	queue_t	*dev_q;
13523 	boolean_t check_multirt = B_FALSE;
13524 
13525 
13526 	ipha = (ipha_t *)mp->b_rptr;
13527 
13528 	/*
13529 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13530 	 * The loopback address check for both src and dst has already
13531 	 * been checked in ip_input
13532 	 */
13533 	ip_dst = ntohl(dst);
13534 	ip_src = ntohl(ipha->ipha_src);
13535 
13536 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13537 	    IN_CLASSD(ip_src)) {
13538 		BUMP_MIB(&ip_mib, ipForwProhibits);
13539 		goto drop;
13540 	}
13541 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13542 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13543 
13544 	if (src_ire != NULL) {
13545 		BUMP_MIB(&ip_mib, ipForwProhibits);
13546 		goto drop;
13547 	}
13548 
13549 	/* No ire cache of nexthop. So first create one  */
13550 	if (ire == NULL) {
13551 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13552 		/*
13553 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13554 		 * is not set. So upon return from ire_forward
13555 		 * check_multirt should remain as false.
13556 		 */
13557 		ASSERT(!check_multirt);
13558 		if (ire == NULL) {
13559 			BUMP_MIB(&ip_mib, ipInDiscards);
13560 			mp->b_prev = mp->b_next = 0;
13561 			/* send icmp unreachable */
13562 			/* Sent by forwarding path, and router is global zone */
13563 			if (ip_source_routed(ipha)) {
13564 				icmp_unreachable(ill->ill_wq, mp,
13565 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13566 			} else {
13567 				icmp_unreachable(ill->ill_wq, mp,
13568 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13569 			}
13570 			return (ire);
13571 		}
13572 	}
13573 
13574 	/*
13575 	 * Forwarding fastpath exception case:
13576 	 * If either of the follwoing case is true, we take
13577 	 * the slowpath
13578 	 *	o forwarding is not enabled
13579 	 *	o IPMP is enabled
13580 	 *	o corresponding ire is in incomplete state
13581 	 *	o packet needs fragmentation
13582 	 *
13583 	 * The codeflow from here on is thus:
13584 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13585 	 */
13586 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13587 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13588 	    !(ill->ill_flags & ILLF_ROUTER) || SAME_IPMP_GROUP(ill, stq_ill) ||
13589 	    (ire->ire_nce == NULL) ||
13590 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13591 	    (ntohs(ipha->ipha_length) > ire->ire_max_frag) ||
13592 	    ipha->ipha_ttl <= 1) {
13593 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13594 		    ipha, ill, B_FALSE);
13595 		return (ire);
13596 	}
13597 
13598 	mp->b_datap->db_struioun.cksum.flags = 0;
13599 	/* Adjust the checksum to reflect the ttl decrement. */
13600 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13601 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13602 	ipha->ipha_ttl--;
13603 
13604 	dev_q = ire->ire_stq->q_next;
13605 	if ((dev_q->q_next != NULL ||
13606 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13607 		goto indiscard;
13608 	}
13609 
13610 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13611 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13612 
13613 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13614 		mp = ip_wput_attach_llhdr(mp, ire, 0, 0);
13615 		if (mp != NULL) {
13616 			SEND_PKT(ire, mp);
13617 			return (ire);
13618 		}
13619 	}
13620 
13621 indiscard:
13622 	BUMP_MIB(&ip_mib, ipInDiscards);
13623 drop:
13624 	if (mp != NULL)
13625 		freemsg(mp);
13626 	if (src_ire != NULL)
13627 		ire_refrele(src_ire);
13628 	return (ire);
13629 
13630 }
13631 
13632 /*
13633  * This function is called in the forwarding slowpath, when
13634  * either the ire lacks the link-layer address, or the packet needs
13635  * further processing(eg. fragmentation), before transmission.
13636  */
13637 static void
13638 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13639     ill_t *ill, boolean_t ll_multicast)
13640 {
13641 	ill_group_t	*ill_group;
13642 	ill_group_t	*ire_group;
13643 	queue_t		*dev_q;
13644 	ire_t		*src_ire;
13645 
13646 	ASSERT(ire->ire_stq != NULL);
13647 
13648 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13649 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13650 
13651 	if (ll_multicast != 0)
13652 		goto drop_pkt;
13653 
13654 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13655 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13656 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13657 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13658 		if (src_ire != NULL)
13659 			ire_refrele(src_ire);
13660 		BUMP_MIB(&ip_mib, ipForwProhibits);
13661 		ip2dbg(("ip_rput_process_forward: Received packet with"
13662 		    " bad src/dst address on %s\n", ill->ill_name));
13663 	}
13664 
13665 	ill_group = ill->ill_group;
13666 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13667 	/*
13668 	 * Check if we want to forward this one at this time.
13669 	 * We allow source routed packets on a host provided that
13670 	 * they go out the same interface or same interface group
13671 	 * as they came in on.
13672 	 *
13673 	 * XXX To be quicker, we may wish to not chase pointers to
13674 	 * get the ILLF_ROUTER flag and instead store the
13675 	 * forwarding policy in the ire.  An unfortunate
13676 	 * side-effect of that would be requiring an ire flush
13677 	 * whenever the ILLF_ROUTER flag changes.
13678 	 */
13679 	if (((ill->ill_flags &
13680 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13681 	    ILLF_ROUTER) == 0) &&
13682 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13683 	    (ill_group != NULL && ill_group == ire_group)))) {
13684 		BUMP_MIB(&ip_mib, ipForwProhibits);
13685 		if (ip_source_routed(ipha)) {
13686 			q = WR(q);
13687 			/*
13688 			 * Clear the indication that this may have
13689 			 * hardware checksum as we are not using it.
13690 			 */
13691 			DB_CKSUMFLAGS(mp) = 0;
13692 			/* Sent by forwarding path, and router is global zone */
13693 			icmp_unreachable(q, mp,
13694 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13695 			return;
13696 		}
13697 		goto drop_pkt;
13698 	}
13699 
13700 	/* Packet is being forwarded. Turning off hwcksum flag. */
13701 	DB_CKSUMFLAGS(mp) = 0;
13702 	if (ip_g_send_redirects) {
13703 		/*
13704 		 * Check whether the incoming interface and outgoing
13705 		 * interface is part of the same group. If so,
13706 		 * send redirects.
13707 		 *
13708 		 * Check the source address to see if it originated
13709 		 * on the same logical subnet it is going back out on.
13710 		 * If so, we should be able to send it a redirect.
13711 		 * Avoid sending a redirect if the destination
13712 		 * is directly connected (gw_addr == 0),
13713 		 * or if the packet was source routed out this
13714 		 * interface.
13715 		 */
13716 		ipaddr_t src;
13717 		mblk_t	*mp1;
13718 		ire_t	*src_ire = NULL;
13719 
13720 		/*
13721 		 * Check whether ire_rfq and q are from the same ill
13722 		 * or if they are not same, they at least belong
13723 		 * to the same group. If so, send redirects.
13724 		 */
13725 		if ((ire->ire_rfq == q ||
13726 		    (ill_group != NULL && ill_group == ire_group)) &&
13727 		    (ire->ire_gateway_addr != 0) &&
13728 		    !ip_source_routed(ipha)) {
13729 
13730 			src = ipha->ipha_src;
13731 			src_ire = ire_ftable_lookup(src, 0, 0,
13732 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
13733 			    0, NULL, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
13734 
13735 			if (src_ire != NULL) {
13736 				/*
13737 				 * The source is directly connected.
13738 				 * Just copy the ip header (which is
13739 				 * in the first mblk)
13740 				 */
13741 				mp1 = copyb(mp);
13742 				if (mp1 != NULL) {
13743 					icmp_send_redirect(WR(q), mp1,
13744 					    ire->ire_gateway_addr);
13745 				}
13746 				ire_refrele(src_ire);
13747 			}
13748 		}
13749 	}
13750 
13751 	dev_q = ire->ire_stq->q_next;
13752 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13753 		BUMP_MIB(&ip_mib, ipInDiscards);
13754 		freemsg(mp);
13755 		return;
13756 	}
13757 
13758 	ip_rput_forward(ire, ipha, mp, ill);
13759 	return;
13760 
13761 drop_pkt:
13762 	ip2dbg(("ip_rput_forward: drop pkt\n"));
13763 	freemsg(mp);
13764 }
13765 
13766 ire_t *
13767 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13768     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13769 {
13770 	queue_t		*q;
13771 	uint16_t	hcksumflags;
13772 
13773 	q = *qp;
13774 
13775 	/*
13776 	 * Clear the indication that this may have hardware
13777 	 * checksum as we are not using it for forwarding.
13778 	 */
13779 	hcksumflags = DB_CKSUMFLAGS(mp);
13780 	DB_CKSUMFLAGS(mp) = 0;
13781 
13782 	/*
13783 	 * Directed broadcast forwarding: if the packet came in over a
13784 	 * different interface then it is routed out over we can forward it.
13785 	 */
13786 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13787 		ire_refrele(ire);
13788 		freemsg(mp);
13789 		BUMP_MIB(&ip_mib, ipInDiscards);
13790 		return (NULL);
13791 	}
13792 	/*
13793 	 * For multicast we have set dst to be INADDR_BROADCAST
13794 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13795 	 * only for broadcast packets.
13796 	 */
13797 	if (!CLASSD(ipha->ipha_dst)) {
13798 		ire_t *new_ire;
13799 		ipif_t *ipif;
13800 		/*
13801 		 * For ill groups, as the switch duplicates broadcasts
13802 		 * across all the ports, we need to filter out and
13803 		 * send up only one copy. There is one copy for every
13804 		 * broadcast address on each ill. Thus, we look for a
13805 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13806 		 * later to see whether this ill is eligible to receive
13807 		 * them or not. ill_nominate_bcast_rcv() nominates only
13808 		 * one set of IREs for receiving.
13809 		 */
13810 
13811 		ipif = ipif_get_next_ipif(NULL, ill);
13812 		if (ipif == NULL) {
13813 			ire_refrele(ire);
13814 			freemsg(mp);
13815 			BUMP_MIB(&ip_mib, ipInDiscards);
13816 			return (NULL);
13817 		}
13818 		new_ire = ire_ctable_lookup(dst, 0, 0,
13819 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13820 		ipif_refrele(ipif);
13821 
13822 		if (new_ire != NULL) {
13823 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13824 				ire_refrele(ire);
13825 				ire_refrele(new_ire);
13826 				freemsg(mp);
13827 				BUMP_MIB(&ip_mib, ipInDiscards);
13828 				return (NULL);
13829 			}
13830 			/*
13831 			 * In the special case of multirouted broadcast
13832 			 * packets, we unconditionally need to "gateway"
13833 			 * them to the appropriate interface here.
13834 			 * In the normal case, this cannot happen, because
13835 			 * there is no broadcast IRE tagged with the
13836 			 * RTF_MULTIRT flag.
13837 			 */
13838 			if (new_ire->ire_flags & RTF_MULTIRT) {
13839 				ire_refrele(new_ire);
13840 				if (ire->ire_rfq != NULL) {
13841 					q = ire->ire_rfq;
13842 					*qp = q;
13843 				}
13844 			} else {
13845 				ire_refrele(ire);
13846 				ire = new_ire;
13847 			}
13848 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
13849 			if (!ip_g_forward_directed_bcast) {
13850 				/*
13851 				 * Free the message if
13852 				 * ip_g_forward_directed_bcast is turned
13853 				 * off for non-local broadcast.
13854 				 */
13855 				ire_refrele(ire);
13856 				freemsg(mp);
13857 				BUMP_MIB(&ip_mib, ipInDiscards);
13858 				return (NULL);
13859 			}
13860 		} else {
13861 			/*
13862 			 * This CGTP packet successfully passed the
13863 			 * CGTP filter, but the related CGTP
13864 			 * broadcast IRE has not been found,
13865 			 * meaning that the redundant ipif is
13866 			 * probably down. However, if we discarded
13867 			 * this packet, its duplicate would be
13868 			 * filtered out by the CGTP filter so none
13869 			 * of them would get through. So we keep
13870 			 * going with this one.
13871 			 */
13872 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
13873 			if (ire->ire_rfq != NULL) {
13874 				q = ire->ire_rfq;
13875 				*qp = q;
13876 			}
13877 		}
13878 	}
13879 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
13880 		/*
13881 		 * Verify that there are not more then one
13882 		 * IRE_BROADCAST with this broadcast address which
13883 		 * has ire_stq set.
13884 		 * TODO: simplify, loop over all IRE's
13885 		 */
13886 		ire_t	*ire1;
13887 		int	num_stq = 0;
13888 		mblk_t	*mp1;
13889 
13890 		/* Find the first one with ire_stq set */
13891 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
13892 		for (ire1 = ire; ire1 &&
13893 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
13894 		    ire1 = ire1->ire_next)
13895 			;
13896 		if (ire1) {
13897 			ire_refrele(ire);
13898 			ire = ire1;
13899 			IRE_REFHOLD(ire);
13900 		}
13901 
13902 		/* Check if there are additional ones with stq set */
13903 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
13904 			if (ire->ire_addr != ire1->ire_addr)
13905 				break;
13906 			if (ire1->ire_stq) {
13907 				num_stq++;
13908 				break;
13909 			}
13910 		}
13911 		rw_exit(&ire->ire_bucket->irb_lock);
13912 		if (num_stq == 1 && ire->ire_stq != NULL) {
13913 			ip1dbg(("ip_rput_process_broadcast: directed "
13914 			    "broadcast to 0x%x\n",
13915 			    ntohl(ire->ire_addr)));
13916 			mp1 = copymsg(mp);
13917 			if (mp1) {
13918 				switch (ipha->ipha_protocol) {
13919 				case IPPROTO_UDP:
13920 					ip_udp_input(q, mp1, ipha, ire, ill);
13921 					break;
13922 				default:
13923 					ip_proto_input(q, mp1, ipha, ire, ill);
13924 					break;
13925 				}
13926 			}
13927 			/*
13928 			 * Adjust ttl to 2 (1+1 - the forward engine
13929 			 * will decrement it by one.
13930 			 */
13931 			if (ip_csum_hdr(ipha)) {
13932 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13933 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
13934 				freemsg(mp);
13935 				ire_refrele(ire);
13936 				return (NULL);
13937 			}
13938 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
13939 			ipha->ipha_hdr_checksum = 0;
13940 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
13941 			ip_rput_process_forward(q, mp, ire, ipha,
13942 			    ill, ll_multicast);
13943 			ire_refrele(ire);
13944 			return (NULL);
13945 		}
13946 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
13947 		    ntohl(ire->ire_addr)));
13948 	}
13949 
13950 
13951 	/* Restore any hardware checksum flags */
13952 	DB_CKSUMFLAGS(mp) = hcksumflags;
13953 	return (ire);
13954 }
13955 
13956 /* ARGSUSED */
13957 static boolean_t
13958 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
13959     int *ll_multicast, ipaddr_t *dstp)
13960 {
13961 	/*
13962 	 * Forward packets only if we have joined the allmulti
13963 	 * group on this interface.
13964 	 */
13965 	if (ip_g_mrouter && ill->ill_join_allmulti) {
13966 		int retval;
13967 
13968 		/*
13969 		 * Clear the indication that this may have hardware
13970 		 * checksum as we are not using it.
13971 		 */
13972 		DB_CKSUMFLAGS(mp) = 0;
13973 		retval = ip_mforward(ill, ipha, mp);
13974 		/* ip_mforward updates mib variables if needed */
13975 		/* clear b_prev - used by ip_mroute_decap */
13976 		mp->b_prev = NULL;
13977 
13978 		switch (retval) {
13979 		case 0:
13980 			/*
13981 			 * pkt is okay and arrived on phyint.
13982 			 *
13983 			 * If we are running as a multicast router
13984 			 * we need to see all IGMP and/or PIM packets.
13985 			 */
13986 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
13987 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
13988 				goto done;
13989 			}
13990 			break;
13991 		case -1:
13992 			/* pkt is mal-formed, toss it */
13993 			goto drop_pkt;
13994 		case 1:
13995 			/* pkt is okay and arrived on a tunnel */
13996 			/*
13997 			 * If we are running a multicast router
13998 			 *  we need to see all igmp packets.
13999 			 */
14000 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14001 				*dstp = INADDR_BROADCAST;
14002 				*ll_multicast = 1;
14003 				return (B_FALSE);
14004 			}
14005 
14006 			goto drop_pkt;
14007 		}
14008 	}
14009 
14010 	ILM_WALKER_HOLD(ill);
14011 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14012 		/*
14013 		 * This might just be caused by the fact that
14014 		 * multiple IP Multicast addresses map to the same
14015 		 * link layer multicast - no need to increment counter!
14016 		 */
14017 		ILM_WALKER_RELE(ill);
14018 		freemsg(mp);
14019 		return (B_TRUE);
14020 	}
14021 	ILM_WALKER_RELE(ill);
14022 done:
14023 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14024 	/*
14025 	 * This assumes the we deliver to all streams for multicast
14026 	 * and broadcast packets.
14027 	 */
14028 	*dstp = INADDR_BROADCAST;
14029 	*ll_multicast = 1;
14030 	return (B_FALSE);
14031 drop_pkt:
14032 	ip2dbg(("ip_rput: drop pkt\n"));
14033 	freemsg(mp);
14034 	return (B_TRUE);
14035 }
14036 
14037 static boolean_t
14038 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14039     int *ll_multicast, mblk_t **mpp)
14040 {
14041 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14042 	boolean_t must_copy = B_FALSE;
14043 	struct iocblk   *iocp;
14044 	ipha_t		*ipha;
14045 
14046 #define	rptr    ((uchar_t *)ipha)
14047 
14048 	first_mp = *first_mpp;
14049 	mp = *mpp;
14050 
14051 	ASSERT(first_mp == mp);
14052 
14053 	/*
14054 	 * if db_ref > 1 then copymsg and free original. Packet may be
14055 	 * changed and do not want other entity who has a reference to this
14056 	 * message to trip over the changes. This is a blind change because
14057 	 * trying to catch all places that might change packet is too
14058 	 * difficult (since it may be a module above this one)
14059 	 *
14060 	 * This corresponds to the non-fast path case. We walk down the full
14061 	 * chain in this case, and check the db_ref count of all the dblks,
14062 	 * and do a copymsg if required. It is possible that the db_ref counts
14063 	 * of the data blocks in the mblk chain can be different.
14064 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14065 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14066 	 * 'snoop' is running.
14067 	 */
14068 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14069 		if (mp1->b_datap->db_ref > 1) {
14070 			must_copy = B_TRUE;
14071 			break;
14072 		}
14073 	}
14074 
14075 	if (must_copy) {
14076 		mp1 = copymsg(mp);
14077 		if (mp1 == NULL) {
14078 			for (mp1 = mp; mp1 != NULL;
14079 			    mp1 = mp1->b_cont) {
14080 				mp1->b_next = NULL;
14081 				mp1->b_prev = NULL;
14082 			}
14083 			freemsg(mp);
14084 			BUMP_MIB(&ip_mib, ipInDiscards);
14085 			return (B_TRUE);
14086 		}
14087 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14088 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14089 			/* Copy b_prev - used by ip_mroute_decap */
14090 			to_mp->b_prev = from_mp->b_prev;
14091 			from_mp->b_prev = NULL;
14092 		}
14093 		*first_mpp = first_mp = mp1;
14094 		freemsg(mp);
14095 		mp = mp1;
14096 		*mpp = mp1;
14097 	}
14098 
14099 	ipha = (ipha_t *)mp->b_rptr;
14100 
14101 	/*
14102 	 * previous code has a case for M_DATA.
14103 	 * We want to check how that happens.
14104 	 */
14105 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14106 	switch (first_mp->b_datap->db_type) {
14107 	case M_PROTO:
14108 	case M_PCPROTO:
14109 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14110 		    DL_UNITDATA_IND) {
14111 			/* Go handle anything other than data elsewhere. */
14112 			ip_rput_dlpi(q, mp);
14113 			return (B_TRUE);
14114 		}
14115 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14116 		/* Ditch the DLPI header. */
14117 		mp1 = mp->b_cont;
14118 		ASSERT(first_mp == mp);
14119 		*first_mpp = mp1;
14120 		freeb(mp);
14121 		*mpp = mp1;
14122 		return (B_FALSE);
14123 	case M_IOCACK:
14124 		ip1dbg(("got iocack "));
14125 		iocp = (struct iocblk *)mp->b_rptr;
14126 		switch (iocp->ioc_cmd) {
14127 		case DL_IOC_HDR_INFO:
14128 			ill = (ill_t *)q->q_ptr;
14129 			ill_fastpath_ack(ill, mp);
14130 			return (B_TRUE);
14131 		case SIOCSTUNPARAM:
14132 		case OSIOCSTUNPARAM:
14133 			/* Go through qwriter_ip */
14134 			break;
14135 		case SIOCGTUNPARAM:
14136 		case OSIOCGTUNPARAM:
14137 			ip_rput_other(NULL, q, mp, NULL);
14138 			return (B_TRUE);
14139 		default:
14140 			putnext(q, mp);
14141 			return (B_TRUE);
14142 		}
14143 		/* FALLTHRU */
14144 	case M_ERROR:
14145 	case M_HANGUP:
14146 		/*
14147 		 * Since this is on the ill stream we unconditionally
14148 		 * bump up the refcount
14149 		 */
14150 		ill_refhold(ill);
14151 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14152 		    B_FALSE);
14153 		return (B_TRUE);
14154 	case M_CTL:
14155 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14156 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14157 			IPHADA_M_CTL)) {
14158 			/*
14159 			 * It's an IPsec accelerated packet.
14160 			 * Make sure that the ill from which we received the
14161 			 * packet has enabled IPsec hardware acceleration.
14162 			 */
14163 			if (!(ill->ill_capabilities &
14164 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14165 				/* IPsec kstats: bean counter */
14166 				freemsg(mp);
14167 				return (B_TRUE);
14168 			}
14169 
14170 			/*
14171 			 * Make mp point to the mblk following the M_CTL,
14172 			 * then process according to type of mp.
14173 			 * After this processing, first_mp will point to
14174 			 * the data-attributes and mp to the pkt following
14175 			 * the M_CTL.
14176 			 */
14177 			mp = first_mp->b_cont;
14178 			if (mp == NULL) {
14179 				freemsg(first_mp);
14180 				return (B_TRUE);
14181 			}
14182 			/*
14183 			 * A Hardware Accelerated packet can only be M_DATA
14184 			 * ESP or AH packet.
14185 			 */
14186 			if (mp->b_datap->db_type != M_DATA) {
14187 				/* non-M_DATA IPsec accelerated packet */
14188 				IPSECHW_DEBUG(IPSECHW_PKT,
14189 				    ("non-M_DATA IPsec accelerated pkt\n"));
14190 				freemsg(first_mp);
14191 				return (B_TRUE);
14192 			}
14193 			ipha = (ipha_t *)mp->b_rptr;
14194 			if (ipha->ipha_protocol != IPPROTO_AH &&
14195 			    ipha->ipha_protocol != IPPROTO_ESP) {
14196 				IPSECHW_DEBUG(IPSECHW_PKT,
14197 				    ("non-M_DATA IPsec accelerated pkt\n"));
14198 				freemsg(first_mp);
14199 				return (B_TRUE);
14200 			}
14201 			*mpp = mp;
14202 			return (B_FALSE);
14203 		}
14204 		putnext(q, mp);
14205 		return (B_TRUE);
14206 	case M_FLUSH:
14207 		if (*mp->b_rptr & FLUSHW) {
14208 			*mp->b_rptr &= ~FLUSHR;
14209 			qreply(q, mp);
14210 			return (B_TRUE);
14211 		}
14212 		freemsg(mp);
14213 		return (B_TRUE);
14214 	case M_IOCNAK:
14215 		ip1dbg(("got iocnak "));
14216 		iocp = (struct iocblk *)mp->b_rptr;
14217 		switch (iocp->ioc_cmd) {
14218 		case DL_IOC_HDR_INFO:
14219 		case SIOCSTUNPARAM:
14220 		case OSIOCSTUNPARAM:
14221 			/*
14222 			 * Since this is on the ill stream we unconditionally
14223 			 * bump up the refcount
14224 			 */
14225 			ill_refhold(ill);
14226 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14227 			    CUR_OP, B_FALSE);
14228 			return (B_TRUE);
14229 		case SIOCGTUNPARAM:
14230 		case OSIOCGTUNPARAM:
14231 			ip_rput_other(NULL, q, mp, NULL);
14232 			return (B_TRUE);
14233 		default:
14234 			break;
14235 		}
14236 		/* FALLTHRU */
14237 	default:
14238 		putnext(q, mp);
14239 		return (B_TRUE);
14240 	}
14241 }
14242 
14243 /* Read side put procedure.  Packets coming from the wire arrive here. */
14244 void
14245 ip_rput(queue_t *q, mblk_t *mp)
14246 {
14247 	ill_t	*ill;
14248 	mblk_t	 *dmp = NULL;
14249 
14250 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14251 
14252 	ill = (ill_t *)q->q_ptr;
14253 
14254 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14255 		union DL_primitives *dl;
14256 
14257 		/*
14258 		 * Things are opening or closing. Only accept DLPI control
14259 		 * messages. In the open case, the ill->ill_ipif has not yet
14260 		 * been created. In the close case, things hanging off the
14261 		 * ill could have been freed already. In either case it
14262 		 * may not be safe to proceed further.
14263 		 */
14264 
14265 		dl = (union DL_primitives *)mp->b_rptr;
14266 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14267 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14268 			/*
14269 			 * Also SIOC[GS]TUN* ioctls can come here.
14270 			 */
14271 			inet_freemsg(mp);
14272 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14273 			    "ip_input_end: q %p (%S)", q, "uninit");
14274 			return;
14275 		}
14276 	}
14277 
14278 	/*
14279 	 * if db_ref > 1 then copymsg and free original. Packet may be
14280 	 * changed and we do not want the other entity who has a reference to
14281 	 * this message to trip over the changes. This is a blind change because
14282 	 * trying to catch all places that might change the packet is too
14283 	 * difficult.
14284 	 *
14285 	 * This corresponds to the fast path case, where we have a chain of
14286 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14287 	 * in the mblk chain. There doesn't seem to be a reason why a device
14288 	 * driver would send up data with varying db_ref counts in the mblk
14289 	 * chain. In any case the Fast path is a private interface, and our
14290 	 * drivers don't do such a thing. Given the above assumption, there is
14291 	 * no need to walk down the entire mblk chain (which could have a
14292 	 * potential performance problem)
14293 	 */
14294 	if (mp->b_datap->db_ref > 1) {
14295 		mblk_t  *mp1;
14296 		boolean_t adjusted = B_FALSE;
14297 		IP_STAT(ip_db_ref);
14298 
14299 		/*
14300 		 * The IP_RECVSLLA option depends on having the link layer
14301 		 * header. First check that:
14302 		 * a> the underlying device is of type ether, since this
14303 		 * option is currently supported only over ethernet.
14304 		 * b> there is enough room to copy over the link layer header.
14305 		 *
14306 		 * Once the checks are done, adjust rptr so that the link layer
14307 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14308 		 * be returned by some non-ethernet drivers but in this case the
14309 		 * second check will fail.
14310 		 */
14311 		if (ill->ill_type == IFT_ETHER &&
14312 		    (mp->b_rptr - mp->b_datap->db_base) >=
14313 		    sizeof (struct ether_header)) {
14314 			mp->b_rptr -= sizeof (struct ether_header);
14315 			adjusted = B_TRUE;
14316 		}
14317 		mp1 = copymsg(mp);
14318 		if (mp1 == NULL) {
14319 			mp->b_next = NULL;
14320 			/* clear b_prev - used by ip_mroute_decap */
14321 			mp->b_prev = NULL;
14322 			freemsg(mp);
14323 			BUMP_MIB(&ip_mib, ipInDiscards);
14324 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14325 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14326 			return;
14327 		}
14328 		if (adjusted) {
14329 			/*
14330 			 * Copy is done. Restore the pointer in the _new_ mblk
14331 			 */
14332 			mp1->b_rptr += sizeof (struct ether_header);
14333 		}
14334 		/* Copy b_prev - used by ip_mroute_decap */
14335 		mp1->b_prev = mp->b_prev;
14336 		mp->b_prev = NULL;
14337 		freemsg(mp);
14338 		mp = mp1;
14339 	}
14340 	if (DB_TYPE(mp) == M_DATA) {
14341 		dmp = mp;
14342 	} else if (DB_TYPE(mp) == M_PROTO &&
14343 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14344 		dmp = mp->b_cont;
14345 	}
14346 	if (dmp != NULL) {
14347 		/*
14348 		 * IP header ptr not aligned?
14349 		 * OR IP header not complete in first mblk
14350 		 */
14351 		if (!OK_32PTR(dmp->b_rptr) ||
14352 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14353 			if (!ip_check_and_align_header(q, dmp))
14354 				return;
14355 		}
14356 	}
14357 
14358 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14359 	    "ip_rput_end: q %p (%S)", q, "end");
14360 
14361 	ip_input(ill, NULL, mp, 0);
14362 }
14363 
14364 /*
14365  * Direct read side procedure capable of dealing with chains. GLDv3 based
14366  * drivers call this function directly with mblk chains while STREAMS
14367  * read side procedure ip_rput() calls this for single packet with ip_ring
14368  * set to NULL to process one packet at a time.
14369  *
14370  * The ill will always be valid if this function is called directly from
14371  * the driver.
14372  */
14373 /* ARGSUSED */
14374 void
14375 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
14376 {
14377 	ipaddr_t		dst = NULL;
14378 	ipaddr_t		prev_dst;
14379 	ire_t			*ire = NULL;
14380 	ipha_t			*ipha;
14381 	uint_t			pkt_len;
14382 	ssize_t			len;
14383 	uint_t			opt_len;
14384 	int			ll_multicast;
14385 	int			cgtp_flt_pkt;
14386 	queue_t			*q = ill->ill_rq;
14387 	squeue_t		*curr_sqp = NULL;
14388 	mblk_t 			*head = NULL;
14389 	mblk_t			*tail = NULL;
14390 	mblk_t			*first_mp;
14391 	mblk_t 			*mp;
14392 	int			cnt = 0;
14393 
14394 	ASSERT(mp_chain != NULL);
14395 	ASSERT(ill != NULL);
14396 
14397 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14398 
14399 #define	rptr	((uchar_t *)ipha)
14400 
14401 	while (mp_chain != NULL) {
14402 		first_mp = mp = mp_chain;
14403 		mp_chain = mp_chain->b_next;
14404 		mp->b_next = NULL;
14405 		ll_multicast = 0;
14406 
14407 		/*
14408 		 * We do ire caching from one iteration to
14409 		 * another. In the event the packet chain contains
14410 		 * all packets from the same dst, this caching saves
14411 		 * an ire_cache_lookup for each of the succeeding
14412 		 * packets in a packet chain.
14413 		 */
14414 		prev_dst = dst;
14415 
14416 		/*
14417 		 * ip_input fast path
14418 		 */
14419 
14420 		/* mblk type is not M_DATA */
14421 		if (mp->b_datap->db_type != M_DATA) {
14422 			if (ip_rput_process_notdata(q, &first_mp, ill,
14423 			    &ll_multicast, &mp))
14424 				continue;
14425 		}
14426 
14427 		/* Make sure its an M_DATA and that its aligned */
14428 		ASSERT(mp->b_datap->db_type == M_DATA);
14429 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14430 
14431 		ipha = (ipha_t *)mp->b_rptr;
14432 		len = mp->b_wptr - rptr;
14433 
14434 		BUMP_MIB(&ip_mib, ipInReceives);
14435 
14436 
14437 		/* multiple mblk or too short */
14438 		pkt_len = ntohs(ipha->ipha_length);
14439 		len -= pkt_len;
14440 		if (len != 0) {
14441 			/*
14442 			 * Make sure we have data length consistent
14443 			 * with the IP header.
14444 			 */
14445 			if (mp->b_cont == NULL) {
14446 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14447 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14448 					ip2dbg(("ip_input: drop pkt\n"));
14449 					freemsg(mp);
14450 					continue;
14451 				}
14452 				mp->b_wptr = rptr + pkt_len;
14453 			} else if (len += msgdsize(mp->b_cont)) {
14454 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14455 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14456 					ip2dbg(("ip_input: drop pkt\n"));
14457 					freemsg(mp);
14458 					continue;
14459 				}
14460 				(void) adjmsg(mp, -len);
14461 				IP_STAT(ip_multimblk3);
14462 			}
14463 		}
14464 
14465 		/* Obtain the dst of the current packet */
14466 		dst = ipha->ipha_dst;
14467 
14468 		if (IP_LOOPBACK_ADDR(dst) ||
14469 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14470 			BUMP_MIB(&ip_mib, ipInAddrErrors);
14471 			cmn_err(CE_CONT, "dst %X src %X\n",
14472 			    dst, ipha->ipha_src);
14473 			freemsg(mp);
14474 			continue;
14475 		}
14476 
14477 		/*
14478 		 * Attach any necessary label information to
14479 		 * this packet
14480 		 */
14481 		if (is_system_labeled() &&
14482 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14483 			BUMP_MIB(&ip_mib, ipInDiscards);
14484 			freemsg(mp);
14485 			continue;
14486 		}
14487 
14488 		/*
14489 		 * Reuse the cached ire only if the ipha_dst of the previous
14490 		 * packet is the same as the current packet AND it is not
14491 		 * INADDR_ANY.
14492 		 */
14493 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14494 		    (ire != NULL)) {
14495 			ire_refrele(ire);
14496 			ire = NULL;
14497 		}
14498 		opt_len = ipha->ipha_version_and_hdr_length -
14499 		    IP_SIMPLE_HDR_VERSION;
14500 
14501 		/*
14502 		 * Check to see if we can take the fastpath.
14503 		 * That is possible if the following conditions are met
14504 		 *	o Tsol disabled
14505 		 *	o CGTP disabled
14506 		 *	o ipp_action_count is 0
14507 		 *	o Mobile IP not running
14508 		 *	o no options in the packet
14509 		 *	o not a RSVP packet
14510 		 * 	o not a multicast packet
14511 		 */
14512 		if (!is_system_labeled() &&
14513 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14514 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14515 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14516 		    !ll_multicast && !CLASSD(dst)) {
14517 			if (ire == NULL)
14518 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14519 
14520 			/* incoming packet is for forwarding */
14521 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14522 				ire = ip_fast_forward(ire, dst, ill, mp);
14523 				continue;
14524 			}
14525 			/* incoming packet is for local consumption */
14526 			if (ire->ire_type & IRE_LOCAL)
14527 				goto local;
14528 		}
14529 
14530 		/*
14531 		 * Disable ire caching for anything more complex
14532 		 * than the simple fast path case we checked for above.
14533 		 */
14534 		if (ire != NULL) {
14535 			ire_refrele(ire);
14536 			ire = NULL;
14537 		}
14538 
14539 		/* Full-blown slow path */
14540 		if (opt_len != 0) {
14541 			if (len != 0)
14542 				IP_STAT(ip_multimblk4);
14543 			else
14544 				IP_STAT(ip_ipoptions);
14545 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
14546 				continue;
14547 		}
14548 
14549 		/*
14550 		 * Invoke the CGTP (multirouting) filtering module to process
14551 		 * the incoming packet. Packets identified as duplicates
14552 		 * must be discarded. Filtering is active only if the
14553 		 * the ip_cgtp_filter ndd variable is non-zero.
14554 		 */
14555 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14556 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
14557 			cgtp_flt_pkt =
14558 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14559 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14560 				freemsg(first_mp);
14561 				continue;
14562 			}
14563 		}
14564 
14565 		/*
14566 		 * If rsvpd is running, let RSVP daemon handle its processing
14567 		 * and forwarding of RSVP multicast/unicast packets.
14568 		 * If rsvpd is not running but mrouted is running, RSVP
14569 		 * multicast packets are forwarded as multicast traffic
14570 		 * and RSVP unicast packets are forwarded by unicast router.
14571 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14572 		 * packets are not forwarded, but the unicast packets are
14573 		 * forwarded like unicast traffic.
14574 		 */
14575 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14576 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
14577 			/* RSVP packet and rsvpd running. Treat as ours */
14578 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14579 			/*
14580 			 * This assumes that we deliver to all streams for
14581 			 * multicast and broadcast packets.
14582 			 * We have to force ll_multicast to 1 to handle the
14583 			 * M_DATA messages passed in from ip_mroute_decap.
14584 			 */
14585 			dst = INADDR_BROADCAST;
14586 			ll_multicast = 1;
14587 		} else if (CLASSD(dst)) {
14588 			/* packet is multicast */
14589 			mp->b_next = NULL;
14590 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14591 			    &ll_multicast, &dst))
14592 				continue;
14593 		}
14594 
14595 
14596 		/*
14597 		 * Check if the packet is coming from the Mobile IP
14598 		 * forward tunnel interface
14599 		 */
14600 		if (ill->ill_srcif_refcnt > 0) {
14601 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
14602 			    NULL, ill, MATCH_IRE_TYPE);
14603 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
14604 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
14605 
14606 				/* We need to resolve the link layer info */
14607 				ire_refrele(ire);
14608 				ire = NULL;
14609 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
14610 				    ll_multicast, dst);
14611 				continue;
14612 			}
14613 		}
14614 
14615 		if (ire == NULL) {
14616 			ire = ire_cache_lookup(dst, ALL_ZONES,
14617 			    MBLK_GETLABEL(mp));
14618 		}
14619 
14620 		/*
14621 		 * If mipagent is running and reverse tunnel is created as per
14622 		 * mobile node request, then any packet coming through the
14623 		 * incoming interface from the mobile-node, should be reverse
14624 		 * tunneled to it's home agent except those that are destined
14625 		 * to foreign agent only.
14626 		 * This needs source address based ire lookup. The routing
14627 		 * entries for source address based lookup are only created by
14628 		 * mipagent program only when a reverse tunnel is created.
14629 		 * Reference : RFC2002, RFC2344
14630 		 */
14631 		if (ill->ill_mrtun_refcnt > 0) {
14632 			ipaddr_t	srcaddr;
14633 			ire_t		*tmp_ire;
14634 
14635 			tmp_ire = ire;	/* Save, we might need it later */
14636 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14637 			    ire->ire_type != IRE_BROADCAST)) {
14638 				srcaddr = ipha->ipha_src;
14639 				ire = ire_mrtun_lookup(srcaddr, ill);
14640 				if (ire != NULL) {
14641 					/*
14642 					 * Should not be getting iphada packet
14643 					 * here. we should only get those for
14644 					 * IRE_LOCAL traffic, excluded above.
14645 					 * Fail-safe (drop packet) in the event
14646 					 * hardware is misbehaving.
14647 					 */
14648 					if (first_mp != mp) {
14649 						/* IPsec KSTATS: beancount me */
14650 						freemsg(first_mp);
14651 					} else {
14652 						/*
14653 						 * This packet must be forwarded
14654 						 * to Reverse Tunnel
14655 						 */
14656 						ip_mrtun_forward(ire, ill, mp);
14657 					}
14658 					ire_refrele(ire);
14659 					ire = NULL;
14660 					if (tmp_ire != NULL) {
14661 						ire_refrele(tmp_ire);
14662 						tmp_ire = NULL;
14663 					}
14664 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14665 					    "ip_input_end: q %p (%S)",
14666 					    q, "uninit");
14667 					continue;
14668 				}
14669 			}
14670 			/*
14671 			 * If this packet is from a non-mobilenode  or a
14672 			 * mobile-node which does not request reverse
14673 			 * tunnel service
14674 			 */
14675 			ire = tmp_ire;
14676 		}
14677 
14678 
14679 		/*
14680 		 * If we reach here that means the incoming packet satisfies
14681 		 * one of the following conditions:
14682 		 *   - packet is from a mobile node which does not request
14683 		 *	reverse tunnel
14684 		 *   - packet is from a non-mobile node, which is the most
14685 		 *	common case
14686 		 *   - packet is from a reverse tunnel enabled mobile node
14687 		 *	and destined to foreign agent only
14688 		 */
14689 
14690 		if (ire == NULL) {
14691 			/*
14692 			 * No IRE for this destination, so it can't be for us.
14693 			 * Unless we are forwarding, drop the packet.
14694 			 * We have to let source routed packets through
14695 			 * since we don't yet know if they are 'ping -l'
14696 			 * packets i.e. if they will go out over the
14697 			 * same interface as they came in on.
14698 			 */
14699 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14700 			if (ire == NULL)
14701 				continue;
14702 		}
14703 
14704 		/*
14705 		 * Broadcast IRE may indicate either broadcast or
14706 		 * multicast packet
14707 		 */
14708 		if (ire->ire_type == IRE_BROADCAST) {
14709 			/*
14710 			 * Skip broadcast checks if packet is UDP multicast;
14711 			 * we'd rather not enter ip_rput_process_broadcast()
14712 			 * unless the packet is broadcast for real, since
14713 			 * that routine is a no-op for multicast.
14714 			 */
14715 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14716 			    !CLASSD(ipha->ipha_dst)) {
14717 				ire = ip_rput_process_broadcast(&q, mp,
14718 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14719 				    ll_multicast);
14720 				if (ire == NULL)
14721 					continue;
14722 			}
14723 		} else if (ire->ire_stq != NULL) {
14724 			/* fowarding? */
14725 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14726 			    ll_multicast);
14727 			/* ip_rput_process_forward consumed the packet */
14728 			continue;
14729 		}
14730 
14731 local:
14732 		/* packet not for us */
14733 		if (ire->ire_rfq != q) {
14734 			if (ip_rput_notforus(&q, mp, ire, ill))
14735 				continue;
14736 		}
14737 
14738 		switch (ipha->ipha_protocol) {
14739 		case IPPROTO_TCP:
14740 			ASSERT(first_mp == mp);
14741 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14742 				mp, 0, q, ip_ring)) != NULL) {
14743 				if (curr_sqp == NULL) {
14744 					curr_sqp = GET_SQUEUE(mp);
14745 					ASSERT(cnt == 0);
14746 					cnt++;
14747 					head = tail = mp;
14748 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14749 					ASSERT(tail != NULL);
14750 					cnt++;
14751 					tail->b_next = mp;
14752 					tail = mp;
14753 				} else {
14754 					/*
14755 					 * A different squeue. Send the
14756 					 * chain for the previous squeue on
14757 					 * its way. This shouldn't happen
14758 					 * often unless interrupt binding
14759 					 * changes.
14760 					 */
14761 					IP_STAT(ip_input_multi_squeue);
14762 					squeue_enter_chain(curr_sqp, head,
14763 					    tail, cnt, SQTAG_IP_INPUT);
14764 					curr_sqp = GET_SQUEUE(mp);
14765 					head = mp;
14766 					tail = mp;
14767 					cnt = 1;
14768 				}
14769 			}
14770 			continue;
14771 		case IPPROTO_UDP:
14772 			ASSERT(first_mp == mp);
14773 			ip_udp_input(q, mp, ipha, ire, ill);
14774 			continue;
14775 		case IPPROTO_SCTP:
14776 			ASSERT(first_mp == mp);
14777 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14778 			    q, dst);
14779 			/* ire has been released by ip_sctp_input */
14780 			ire = NULL;
14781 			continue;
14782 		default:
14783 			ip_proto_input(q, first_mp, ipha, ire, ill);
14784 			continue;
14785 		}
14786 	}
14787 
14788 	if (ire != NULL)
14789 		ire_refrele(ire);
14790 
14791 	if (head != NULL)
14792 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14793 
14794 	/*
14795 	 * This code is there just to make netperf/ttcp look good.
14796 	 *
14797 	 * Its possible that after being in polling mode (and having cleared
14798 	 * the backlog), squeues have turned the interrupt frequency higher
14799 	 * to improve latency at the expense of more CPU utilization (less
14800 	 * packets per interrupts or more number of interrupts). Workloads
14801 	 * like ttcp/netperf do manage to tickle polling once in a while
14802 	 * but for the remaining time, stay in higher interrupt mode since
14803 	 * their packet arrival rate is pretty uniform and this shows up
14804 	 * as higher CPU utilization. Since people care about CPU utilization
14805 	 * while running netperf/ttcp, turn the interrupt frequency back to
14806 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14807 	 */
14808 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14809 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14810 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14811 			ip_ring->rr_blank(ip_ring->rr_handle,
14812 			    ip_ring->rr_normal_blank_time,
14813 			    ip_ring->rr_normal_pkt_cnt);
14814 		}
14815 	}
14816 
14817 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14818 	    "ip_input_end: q %p (%S)", q, "end");
14819 #undef	rptr
14820 }
14821 
14822 static void
14823 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
14824     t_uscalar_t err)
14825 {
14826 	if (dl_err == DL_SYSERR) {
14827 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14828 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
14829 		    ill->ill_name, dlpi_prim_str(prim), err);
14830 		return;
14831 	}
14832 
14833 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14834 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
14835 	    dlpi_err_str(dl_err));
14836 }
14837 
14838 /*
14839  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
14840  * than DL_UNITDATA_IND messages. If we need to process this message
14841  * exclusively, we call qwriter_ip, in which case we also need to call
14842  * ill_refhold before that, since qwriter_ip does an ill_refrele.
14843  */
14844 void
14845 ip_rput_dlpi(queue_t *q, mblk_t *mp)
14846 {
14847 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14848 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14849 	ill_t		*ill;
14850 
14851 	ip1dbg(("ip_rput_dlpi"));
14852 	ill = (ill_t *)q->q_ptr;
14853 	switch (dloa->dl_primitive) {
14854 	case DL_ERROR_ACK:
14855 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
14856 		    "%s (0x%x), unix %u\n", ill->ill_name,
14857 		    dlpi_prim_str(dlea->dl_error_primitive),
14858 		    dlea->dl_error_primitive,
14859 		    dlpi_err_str(dlea->dl_errno),
14860 		    dlea->dl_errno,
14861 		    dlea->dl_unix_errno));
14862 		switch (dlea->dl_error_primitive) {
14863 		case DL_UNBIND_REQ:
14864 			mutex_enter(&ill->ill_lock);
14865 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14866 			cv_signal(&ill->ill_cv);
14867 			mutex_exit(&ill->ill_lock);
14868 			/* FALLTHRU */
14869 		case DL_NOTIFY_REQ:
14870 		case DL_ATTACH_REQ:
14871 		case DL_DETACH_REQ:
14872 		case DL_INFO_REQ:
14873 		case DL_BIND_REQ:
14874 		case DL_ENABMULTI_REQ:
14875 		case DL_PHYS_ADDR_REQ:
14876 		case DL_CAPABILITY_REQ:
14877 		case DL_CONTROL_REQ:
14878 			/*
14879 			 * Refhold the ill to match qwriter_ip which does a
14880 			 * refrele. Since this is on the ill stream we
14881 			 * unconditionally bump up the refcount without
14882 			 * checking for ILL_CAN_LOOKUP
14883 			 */
14884 			ill_refhold(ill);
14885 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14886 			    CUR_OP, B_FALSE);
14887 			return;
14888 		case DL_DISABMULTI_REQ:
14889 			freemsg(mp);	/* Don't want to pass this up */
14890 			return;
14891 		default:
14892 			break;
14893 		}
14894 		ip_dlpi_error(ill, dlea->dl_error_primitive,
14895 		    dlea->dl_errno, dlea->dl_unix_errno);
14896 		freemsg(mp);
14897 		return;
14898 	case DL_INFO_ACK:
14899 	case DL_BIND_ACK:
14900 	case DL_PHYS_ADDR_ACK:
14901 	case DL_NOTIFY_ACK:
14902 	case DL_CAPABILITY_ACK:
14903 	case DL_CONTROL_ACK:
14904 		/*
14905 		 * Refhold the ill to match qwriter_ip which does a refrele
14906 		 * Since this is on the ill stream we unconditionally
14907 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
14908 		 */
14909 		ill_refhold(ill);
14910 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14911 		    CUR_OP, B_FALSE);
14912 		return;
14913 	case DL_NOTIFY_IND:
14914 		ill_refhold(ill);
14915 		/*
14916 		 * The DL_NOTIFY_IND is an asynchronous message that has no
14917 		 * relation to the current ioctl in progress (if any). Hence we
14918 		 * pass in NEW_OP in this case.
14919 		 */
14920 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14921 		    NEW_OP, B_FALSE);
14922 		return;
14923 	case DL_OK_ACK:
14924 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
14925 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
14926 		switch (dloa->dl_correct_primitive) {
14927 		case DL_UNBIND_REQ:
14928 			mutex_enter(&ill->ill_lock);
14929 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14930 			cv_signal(&ill->ill_cv);
14931 			mutex_exit(&ill->ill_lock);
14932 			/* FALLTHRU */
14933 		case DL_ATTACH_REQ:
14934 		case DL_DETACH_REQ:
14935 			/*
14936 			 * Refhold the ill to match qwriter_ip which does a
14937 			 * refrele. Since this is on the ill stream we
14938 			 * unconditionally bump up the refcount
14939 			 */
14940 			ill_refhold(ill);
14941 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14942 			    CUR_OP, B_FALSE);
14943 			return;
14944 		case DL_ENABMULTI_REQ:
14945 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14946 				ill->ill_dlpi_multicast_state = IDMS_OK;
14947 			break;
14948 
14949 		}
14950 		break;
14951 	default:
14952 		break;
14953 	}
14954 	freemsg(mp);
14955 }
14956 
14957 /*
14958  * Handling of DLPI messages that require exclusive access to the ipsq.
14959  *
14960  * Need to do ill_pending_mp_release on ioctl completion, which could
14961  * happen here. (along with mi_copy_done)
14962  */
14963 /* ARGSUSED */
14964 static void
14965 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14966 {
14967 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14968 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14969 	int		err = 0;
14970 	ill_t		*ill;
14971 	ipif_t		*ipif = NULL;
14972 	mblk_t		*mp1 = NULL;
14973 	conn_t		*connp = NULL;
14974 	t_uscalar_t	physaddr_req;
14975 	mblk_t		*mp_hw;
14976 	union DL_primitives *dlp;
14977 	boolean_t	success;
14978 	boolean_t	ioctl_aborted = B_FALSE;
14979 	boolean_t	log = B_TRUE;
14980 
14981 	ip1dbg(("ip_rput_dlpi_writer .."));
14982 	ill = (ill_t *)q->q_ptr;
14983 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14984 
14985 	ASSERT(IAM_WRITER_ILL(ill));
14986 
14987 	/*
14988 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
14989 	 * both are null or non-null. However we can assert that only
14990 	 * after grabbing the ipsq_lock. So we don't make any assertion
14991 	 * here and in other places in the code.
14992 	 */
14993 	ipif = ipsq->ipsq_pending_ipif;
14994 	/*
14995 	 * The current ioctl could have been aborted by the user and a new
14996 	 * ioctl to bring up another ill could have started. We could still
14997 	 * get a response from the driver later.
14998 	 */
14999 	if (ipif != NULL && ipif->ipif_ill != ill)
15000 		ioctl_aborted = B_TRUE;
15001 
15002 	switch (dloa->dl_primitive) {
15003 	case DL_ERROR_ACK:
15004 		switch (dlea->dl_error_primitive) {
15005 		case DL_UNBIND_REQ:
15006 		case DL_ATTACH_REQ:
15007 		case DL_DETACH_REQ:
15008 		case DL_INFO_REQ:
15009 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15010 			break;
15011 		case DL_NOTIFY_REQ:
15012 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15013 			log = B_FALSE;
15014 			break;
15015 		case DL_PHYS_ADDR_REQ:
15016 			/*
15017 			 * For IPv6 only, there are two additional
15018 			 * phys_addr_req's sent to the driver to get the
15019 			 * IPv6 token and lla. This allows IP to acquire
15020 			 * the hardware address format for a given interface
15021 			 * without having built in knowledge of the hardware
15022 			 * address. ill_phys_addr_pend keeps track of the last
15023 			 * DL_PAR sent so we know which response we are
15024 			 * dealing with. ill_dlpi_done will update
15025 			 * ill_phys_addr_pend when it sends the next req.
15026 			 * We don't complete the IOCTL until all three DL_PARs
15027 			 * have been attempted, so set *_len to 0 and break.
15028 			 */
15029 			physaddr_req = ill->ill_phys_addr_pend;
15030 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15031 			if (physaddr_req == DL_IPV6_TOKEN) {
15032 				ill->ill_token_length = 0;
15033 				log = B_FALSE;
15034 				break;
15035 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15036 				ill->ill_nd_lla_len = 0;
15037 				log = B_FALSE;
15038 				break;
15039 			}
15040 			/*
15041 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15042 			 * We presumably have an IOCTL hanging out waiting
15043 			 * for completion. Find it and complete the IOCTL
15044 			 * with the error noted.
15045 			 * However, ill_dl_phys was called on an ill queue
15046 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15047 			 * set. But the ioctl is known to be pending on ill_wq.
15048 			 */
15049 			if (!ill->ill_ifname_pending)
15050 				break;
15051 			ill->ill_ifname_pending = 0;
15052 			if (!ioctl_aborted)
15053 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15054 			if (mp1 != NULL) {
15055 				/*
15056 				 * This operation (SIOCSLIFNAME) must have
15057 				 * happened on the ill. Assert there is no conn
15058 				 */
15059 				ASSERT(connp == NULL);
15060 				q = ill->ill_wq;
15061 			}
15062 			break;
15063 		case DL_BIND_REQ:
15064 			ill_dlpi_done(ill, DL_BIND_REQ);
15065 			if (ill->ill_ifname_pending)
15066 				break;
15067 			/*
15068 			 * Something went wrong with the bind.  We presumably
15069 			 * have an IOCTL hanging out waiting for completion.
15070 			 * Find it, take down the interface that was coming
15071 			 * up, and complete the IOCTL with the error noted.
15072 			 */
15073 			if (!ioctl_aborted)
15074 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15075 			if (mp1 != NULL) {
15076 				/*
15077 				 * This operation (SIOCSLIFFLAGS) must have
15078 				 * happened from a conn.
15079 				 */
15080 				ASSERT(connp != NULL);
15081 				q = CONNP_TO_WQ(connp);
15082 				if (ill->ill_move_in_progress) {
15083 					ILL_CLEAR_MOVE(ill);
15084 				}
15085 				(void) ipif_down(ipif, NULL, NULL);
15086 				/* error is set below the switch */
15087 			}
15088 			break;
15089 		case DL_ENABMULTI_REQ:
15090 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15091 
15092 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
15093 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
15094 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
15095 				ipif_t *ipif;
15096 
15097 				log = B_FALSE;
15098 				printf("ip: joining multicasts failed (%d)"
15099 				    " on %s - will use link layer "
15100 				    "broadcasts for multicast\n",
15101 				    dlea->dl_errno, ill->ill_name);
15102 
15103 				/*
15104 				 * Set up the multicast mapping alone.
15105 				 * writer, so ok to access ill->ill_ipif
15106 				 * without any lock.
15107 				 */
15108 				ipif = ill->ill_ipif;
15109 				mutex_enter(&ill->ill_phyint->phyint_lock);
15110 				ill->ill_phyint->phyint_flags |=
15111 				    PHYI_MULTI_BCAST;
15112 				mutex_exit(&ill->ill_phyint->phyint_lock);
15113 
15114 				if (!ill->ill_isv6) {
15115 					(void) ipif_arp_setup_multicast(ipif,
15116 					    NULL);
15117 				} else {
15118 					(void) ipif_ndp_setup_multicast(ipif,
15119 					    NULL);
15120 				}
15121 			}
15122 			freemsg(mp);	/* Don't want to pass this up */
15123 			return;
15124 		case DL_CAPABILITY_REQ:
15125 		case DL_CONTROL_REQ:
15126 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15127 			    "DL_CAPABILITY/CONTROL REQ\n"));
15128 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15129 			ill->ill_capab_state = IDMS_FAILED;
15130 			freemsg(mp);
15131 			return;
15132 		}
15133 		/*
15134 		 * Note the error for IOCTL completion (mp1 is set when
15135 		 * ready to complete ioctl). If ill_ifname_pending_err is
15136 		 * set, an error occured during plumbing (ill_ifname_pending),
15137 		 * so we want to report that error.
15138 		 *
15139 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15140 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15141 		 * expected to get errack'd if the driver doesn't support
15142 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15143 		 * if these error conditions are encountered.
15144 		 */
15145 		if (mp1 != NULL) {
15146 			if (ill->ill_ifname_pending_err != 0)  {
15147 				err = ill->ill_ifname_pending_err;
15148 				ill->ill_ifname_pending_err = 0;
15149 			} else {
15150 				err = dlea->dl_unix_errno ?
15151 				    dlea->dl_unix_errno : ENXIO;
15152 			}
15153 		/*
15154 		 * If we're plumbing an interface and an error hasn't already
15155 		 * been saved, set ill_ifname_pending_err to the error passed
15156 		 * up. Ignore the error if log is B_FALSE (see comment above).
15157 		 */
15158 		} else if (log && ill->ill_ifname_pending &&
15159 		    ill->ill_ifname_pending_err == 0) {
15160 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15161 			dlea->dl_unix_errno : ENXIO;
15162 		}
15163 
15164 		if (log)
15165 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15166 			    dlea->dl_errno, dlea->dl_unix_errno);
15167 		break;
15168 	case DL_CAPABILITY_ACK: {
15169 		boolean_t reneg_flag = B_FALSE;
15170 		/* Call a routine to handle this one. */
15171 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15172 		/*
15173 		 * Check if the ACK is due to renegotiation case since we
15174 		 * will need to send a new CAPABILITY_REQ later.
15175 		 */
15176 		if (ill->ill_capab_state == IDMS_RENEG) {
15177 			/* This is the ack for a renogiation case */
15178 			reneg_flag = B_TRUE;
15179 			ill->ill_capab_state = IDMS_UNKNOWN;
15180 		}
15181 		ill_capability_ack(ill, mp);
15182 		if (reneg_flag)
15183 			ill_capability_probe(ill);
15184 		break;
15185 	}
15186 	case DL_CONTROL_ACK:
15187 		/* We treat all of these as "fire and forget" */
15188 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15189 		break;
15190 	case DL_INFO_ACK:
15191 		/* Call a routine to handle this one. */
15192 		ill_dlpi_done(ill, DL_INFO_REQ);
15193 		ip_ll_subnet_defaults(ill, mp);
15194 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15195 		return;
15196 	case DL_BIND_ACK:
15197 		/*
15198 		 * We should have an IOCTL waiting on this unless
15199 		 * sent by ill_dl_phys, in which case just return
15200 		 */
15201 		ill_dlpi_done(ill, DL_BIND_REQ);
15202 		if (ill->ill_ifname_pending)
15203 			break;
15204 
15205 		if (!ioctl_aborted)
15206 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15207 		if (mp1 == NULL)
15208 			break;
15209 		ASSERT(connp != NULL);
15210 		q = CONNP_TO_WQ(connp);
15211 
15212 		/*
15213 		 * We are exclusive. So nothing can change even after
15214 		 * we get the pending mp. If need be we can put it back
15215 		 * and restart, as in calling ipif_arp_up()  below.
15216 		 */
15217 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15218 
15219 		mutex_enter(&ill->ill_lock);
15220 		ill->ill_dl_up = 1;
15221 		mutex_exit(&ill->ill_lock);
15222 
15223 		/*
15224 		 * Now bring up the resolver; when that is complete, we'll
15225 		 * create IREs.  Note that we intentionally mirror what
15226 		 * ipif_up() would have done, because we got here by way of
15227 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15228 		 */
15229 		if (ill->ill_isv6) {
15230 			/*
15231 			 * v6 interfaces.
15232 			 * Unlike ARP which has to do another bind
15233 			 * and attach, once we get here we are
15234 			 * done with NDP. Except in the case of
15235 			 * ILLF_XRESOLV, in which case we send an
15236 			 * AR_INTERFACE_UP to the external resolver.
15237 			 * If all goes well, the ioctl will complete
15238 			 * in ip_rput(). If there's an error, we
15239 			 * complete it here.
15240 			 */
15241 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15242 			    B_FALSE);
15243 			if (err == 0) {
15244 				if (ill->ill_flags & ILLF_XRESOLV) {
15245 					mutex_enter(&connp->conn_lock);
15246 					mutex_enter(&ill->ill_lock);
15247 					success = ipsq_pending_mp_add(
15248 					    connp, ipif, q, mp1, 0);
15249 					mutex_exit(&ill->ill_lock);
15250 					mutex_exit(&connp->conn_lock);
15251 					if (success) {
15252 						err = ipif_resolver_up(ipif,
15253 						    Res_act_initial);
15254 						if (err == EINPROGRESS) {
15255 							freemsg(mp);
15256 							return;
15257 						}
15258 						ASSERT(err != 0);
15259 						mp1 = ipsq_pending_mp_get(ipsq,
15260 						    &connp);
15261 						ASSERT(mp1 != NULL);
15262 					} else {
15263 						/* conn has started closing */
15264 						err = EINTR;
15265 					}
15266 				} else { /* Non XRESOLV interface */
15267 					(void) ipif_resolver_up(ipif,
15268 					    Res_act_initial);
15269 					err = ipif_up_done_v6(ipif);
15270 				}
15271 			}
15272 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15273 			/*
15274 			 * ARP and other v4 external resolvers.
15275 			 * Leave the pending mblk intact so that
15276 			 * the ioctl completes in ip_rput().
15277 			 */
15278 			mutex_enter(&connp->conn_lock);
15279 			mutex_enter(&ill->ill_lock);
15280 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15281 			mutex_exit(&ill->ill_lock);
15282 			mutex_exit(&connp->conn_lock);
15283 			if (success) {
15284 				err = ipif_resolver_up(ipif, Res_act_initial);
15285 				if (err == EINPROGRESS) {
15286 					freemsg(mp);
15287 					return;
15288 				}
15289 				ASSERT(err != 0);
15290 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15291 			} else {
15292 				/* The conn has started closing */
15293 				err = EINTR;
15294 			}
15295 		} else {
15296 			/*
15297 			 * This one is complete. Reply to pending ioctl.
15298 			 */
15299 			(void) ipif_resolver_up(ipif, Res_act_initial);
15300 			err = ipif_up_done(ipif);
15301 		}
15302 
15303 		if ((err == 0) && (ill->ill_up_ipifs)) {
15304 			err = ill_up_ipifs(ill, q, mp1);
15305 			if (err == EINPROGRESS) {
15306 				freemsg(mp);
15307 				return;
15308 			}
15309 		}
15310 
15311 		if (ill->ill_up_ipifs) {
15312 			ill_group_cleanup(ill);
15313 		}
15314 
15315 		break;
15316 	case DL_NOTIFY_IND: {
15317 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15318 		ire_t *ire;
15319 		boolean_t need_ire_walk_v4 = B_FALSE;
15320 		boolean_t need_ire_walk_v6 = B_FALSE;
15321 
15322 		/*
15323 		 * Change the address everywhere we need to.
15324 		 * What we're getting here is a link-level addr or phys addr.
15325 		 * The new addr is at notify + notify->dl_addr_offset
15326 		 * The address length is notify->dl_addr_length;
15327 		 */
15328 		switch (notify->dl_notification) {
15329 		case DL_NOTE_PHYS_ADDR:
15330 			mp_hw = copyb(mp);
15331 			if (mp_hw == NULL) {
15332 				err = ENOMEM;
15333 				break;
15334 			}
15335 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15336 			/*
15337 			 * We currently don't support changing
15338 			 * the token via DL_NOTIFY_IND.
15339 			 * When we do support it, we have to consider
15340 			 * what the implications are with respect to
15341 			 * the token and the link local address.
15342 			 */
15343 			mutex_enter(&ill->ill_lock);
15344 			if (dlp->notify_ind.dl_data ==
15345 			    DL_IPV6_LINK_LAYER_ADDR) {
15346 				if (ill->ill_nd_lla_mp != NULL)
15347 					freemsg(ill->ill_nd_lla_mp);
15348 				ill->ill_nd_lla_mp = mp_hw;
15349 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15350 				    dlp->notify_ind.dl_addr_offset;
15351 				ill->ill_nd_lla_len =
15352 				    dlp->notify_ind.dl_addr_length -
15353 				    ABS(ill->ill_sap_length);
15354 				mutex_exit(&ill->ill_lock);
15355 				break;
15356 			} else if (dlp->notify_ind.dl_data ==
15357 			    DL_CURR_PHYS_ADDR) {
15358 				if (ill->ill_phys_addr_mp != NULL)
15359 					freemsg(ill->ill_phys_addr_mp);
15360 				ill->ill_phys_addr_mp = mp_hw;
15361 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15362 				    dlp->notify_ind.dl_addr_offset;
15363 				ill->ill_phys_addr_length =
15364 				    dlp->notify_ind.dl_addr_length -
15365 				    ABS(ill->ill_sap_length);
15366 				if (ill->ill_isv6 &&
15367 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15368 					if (ill->ill_nd_lla_mp != NULL)
15369 						freemsg(ill->ill_nd_lla_mp);
15370 					ill->ill_nd_lla_mp = copyb(mp_hw);
15371 					ill->ill_nd_lla = (uchar_t *)
15372 					    ill->ill_nd_lla_mp->b_rptr +
15373 					    dlp->notify_ind.dl_addr_offset;
15374 					ill->ill_nd_lla_len =
15375 					    ill->ill_phys_addr_length;
15376 				}
15377 			}
15378 			mutex_exit(&ill->ill_lock);
15379 			/*
15380 			 * Send out gratuitous arp request for our new
15381 			 * hardware address.
15382 			 */
15383 			for (ipif = ill->ill_ipif; ipif != NULL;
15384 			    ipif = ipif->ipif_next) {
15385 				if (!(ipif->ipif_flags & IPIF_UP))
15386 					continue;
15387 				if (ill->ill_isv6) {
15388 					ipif_ndp_down(ipif);
15389 					/*
15390 					 * Set B_TRUE to enable
15391 					 * ipif_ndp_up() to send out
15392 					 * unsolicited advertisements.
15393 					 */
15394 					err = ipif_ndp_up(ipif,
15395 					    &ipif->ipif_v6lcl_addr,
15396 					    B_TRUE);
15397 					if (err) {
15398 						ip1dbg((
15399 						    "ip_rput_dlpi_writer: "
15400 						    "Failed to update ndp "
15401 						    "err %d\n", err));
15402 					}
15403 				} else {
15404 					/*
15405 					 * IPv4 ARP case
15406 					 *
15407 					 * Set Res_act_move, as we only want
15408 					 * ipif_resolver_up to send an
15409 					 * AR_ENTRY_ADD request up to
15410 					 * ARP.
15411 					 */
15412 					err = ipif_resolver_up(ipif,
15413 					    Res_act_move);
15414 					if (err) {
15415 						ip1dbg((
15416 						    "ip_rput_dlpi_writer: "
15417 						    "Failed to update arp "
15418 						    "err %d\n", err));
15419 					}
15420 				}
15421 			}
15422 			/*
15423 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15424 			 * case so that all old fastpath information can be
15425 			 * purged from IRE caches.
15426 			 */
15427 		/* FALLTHRU */
15428 		case DL_NOTE_FASTPATH_FLUSH:
15429 			/*
15430 			 * Any fastpath probe sent henceforth will get the
15431 			 * new fp mp. So we first delete any ires that are
15432 			 * waiting for the fastpath. Then walk all ires and
15433 			 * delete the ire or delete the fp mp. In the case of
15434 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15435 			 * recreate the ire's without going through a complex
15436 			 * ipif up/down dance. So we don't delete the ire
15437 			 * itself, but just the nce_fp_mp for these 2 ire's
15438 			 * In the case of the other ire's we delete the ire's
15439 			 * themselves. Access to nce_fp_mp is completely
15440 			 * protected by ire_lock for IRE_MIPRTUN and
15441 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15442 			 * other cases for performance.
15443 			 */
15444 			if (ill->ill_isv6) {
15445 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15446 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15447 				    NULL);
15448 			} else {
15449 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15450 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15451 				    IRE_CACHE | IRE_BROADCAST,
15452 				    ire_fastpath_flush, NULL, ill);
15453 				mutex_enter(&ire_mrtun_lock);
15454 				if (ire_mrtun_count != 0) {
15455 					mutex_exit(&ire_mrtun_lock);
15456 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15457 					    IRE_MIPRTUN, ire_fastpath_flush,
15458 					    NULL, ill);
15459 				} else {
15460 					mutex_exit(&ire_mrtun_lock);
15461 				}
15462 			}
15463 			break;
15464 		case DL_NOTE_SDU_SIZE:
15465 			/*
15466 			 * Change the MTU size of the interface, of all
15467 			 * attached ipif's, and of all relevant ire's.  The
15468 			 * new value's a uint32_t at notify->dl_data.
15469 			 * Mtu change Vs. new ire creation - protocol below.
15470 			 *
15471 			 * a Mark the ipif as IPIF_CHANGING.
15472 			 * b Set the new mtu in the ipif.
15473 			 * c Change the ire_max_frag on all affected ires
15474 			 * d Unmark the IPIF_CHANGING
15475 			 *
15476 			 * To see how the protocol works, assume an interface
15477 			 * route is also being added simultaneously by
15478 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15479 			 * the ire. If the ire is created before step a,
15480 			 * it will be cleaned up by step c. If the ire is
15481 			 * created after step d, it will see the new value of
15482 			 * ipif_mtu. Any attempt to create the ire between
15483 			 * steps a to d will fail because of the IPIF_CHANGING
15484 			 * flag. Note that ire_create() is passed a pointer to
15485 			 * the ipif_mtu, and not the value. During ire_add
15486 			 * under the bucket lock, the ire_max_frag of the
15487 			 * new ire being created is set from the ipif/ire from
15488 			 * which it is being derived.
15489 			 */
15490 			mutex_enter(&ill->ill_lock);
15491 			ill->ill_max_frag = (uint_t)notify->dl_data;
15492 
15493 			/*
15494 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15495 			 * leave it alone
15496 			 */
15497 			if (ill->ill_mtu_userspecified) {
15498 				mutex_exit(&ill->ill_lock);
15499 				break;
15500 			}
15501 			ill->ill_max_mtu = ill->ill_max_frag;
15502 			if (ill->ill_isv6) {
15503 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15504 					ill->ill_max_mtu = IPV6_MIN_MTU;
15505 			} else {
15506 				if (ill->ill_max_mtu < IP_MIN_MTU)
15507 					ill->ill_max_mtu = IP_MIN_MTU;
15508 			}
15509 			for (ipif = ill->ill_ipif; ipif != NULL;
15510 			    ipif = ipif->ipif_next) {
15511 				/*
15512 				 * Don't override the mtu if the user
15513 				 * has explicitly set it.
15514 				 */
15515 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15516 					continue;
15517 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15518 				if (ipif->ipif_isv6)
15519 					ire = ipif_to_ire_v6(ipif);
15520 				else
15521 					ire = ipif_to_ire(ipif);
15522 				if (ire != NULL) {
15523 					ire->ire_max_frag = ipif->ipif_mtu;
15524 					ire_refrele(ire);
15525 				}
15526 				if (ipif->ipif_flags & IPIF_UP) {
15527 					if (ill->ill_isv6)
15528 						need_ire_walk_v6 = B_TRUE;
15529 					else
15530 						need_ire_walk_v4 = B_TRUE;
15531 				}
15532 			}
15533 			mutex_exit(&ill->ill_lock);
15534 			if (need_ire_walk_v4)
15535 				ire_walk_v4(ill_mtu_change, (char *)ill,
15536 				    ALL_ZONES);
15537 			if (need_ire_walk_v6)
15538 				ire_walk_v6(ill_mtu_change, (char *)ill,
15539 				    ALL_ZONES);
15540 			break;
15541 		case DL_NOTE_LINK_UP:
15542 		case DL_NOTE_LINK_DOWN: {
15543 			/*
15544 			 * We are writer. ill / phyint / ipsq assocs stable.
15545 			 * The RUNNING flag reflects the state of the link.
15546 			 */
15547 			phyint_t *phyint = ill->ill_phyint;
15548 			uint64_t new_phyint_flags;
15549 			boolean_t changed = B_FALSE;
15550 			boolean_t went_up;
15551 
15552 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15553 			mutex_enter(&phyint->phyint_lock);
15554 			new_phyint_flags = went_up ?
15555 			    phyint->phyint_flags | PHYI_RUNNING :
15556 			    phyint->phyint_flags & ~PHYI_RUNNING;
15557 			if (new_phyint_flags != phyint->phyint_flags) {
15558 				phyint->phyint_flags = new_phyint_flags;
15559 				changed = B_TRUE;
15560 			}
15561 			mutex_exit(&phyint->phyint_lock);
15562 			/*
15563 			 * ill_restart_dad handles the DAD restart and routing
15564 			 * socket notification logic.
15565 			 */
15566 			if (changed) {
15567 				ill_restart_dad(phyint->phyint_illv4, went_up);
15568 				ill_restart_dad(phyint->phyint_illv6, went_up);
15569 			}
15570 			break;
15571 		}
15572 		case DL_NOTE_PROMISC_ON_PHYS:
15573 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15574 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15575 			mutex_enter(&ill->ill_lock);
15576 			ill->ill_promisc_on_phys = B_TRUE;
15577 			mutex_exit(&ill->ill_lock);
15578 			break;
15579 		case DL_NOTE_PROMISC_OFF_PHYS:
15580 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15581 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15582 			mutex_enter(&ill->ill_lock);
15583 			ill->ill_promisc_on_phys = B_FALSE;
15584 			mutex_exit(&ill->ill_lock);
15585 			break;
15586 		case DL_NOTE_CAPAB_RENEG:
15587 			/*
15588 			 * Something changed on the driver side.
15589 			 * It wants us to renegotiate the capabilities
15590 			 * on this ill. The most likely cause is the
15591 			 * aggregation interface under us where a
15592 			 * port got added or went away.
15593 			 *
15594 			 * We reset the capabilities and set the
15595 			 * state to IDMS_RENG so that when the ack
15596 			 * comes back, we can start the
15597 			 * renegotiation process.
15598 			 */
15599 			ill_capability_reset(ill);
15600 			ill->ill_capab_state = IDMS_RENEG;
15601 			break;
15602 		default:
15603 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15604 			    "type 0x%x for DL_NOTIFY_IND\n",
15605 			    notify->dl_notification));
15606 			break;
15607 		}
15608 
15609 		/*
15610 		 * As this is an asynchronous operation, we
15611 		 * should not call ill_dlpi_done
15612 		 */
15613 		break;
15614 	}
15615 	case DL_NOTIFY_ACK: {
15616 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15617 
15618 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15619 			ill->ill_note_link = 1;
15620 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15621 		break;
15622 	}
15623 	case DL_PHYS_ADDR_ACK: {
15624 		/*
15625 		 * We should have an IOCTL waiting on this when request
15626 		 * sent by ill_dl_phys.
15627 		 * However, ill_dl_phys was called on an ill queue (from
15628 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15629 		 * ioctl is known to be pending on ill_wq.
15630 		 * There are two additional phys_addr_req's sent to the
15631 		 * driver to get the token and lla. ill_phys_addr_pend
15632 		 * keeps track of the last one sent so we know which
15633 		 * response we are dealing with. ill_dlpi_done will
15634 		 * update ill_phys_addr_pend when it sends the next req.
15635 		 * We don't complete the IOCTL until all three DL_PARs
15636 		 * have been attempted.
15637 		 *
15638 		 * We don't need any lock to update ill_nd_lla* fields,
15639 		 * since the ill is not yet up, We grab the lock just
15640 		 * for uniformity with other code that accesses ill_nd_lla.
15641 		 */
15642 		physaddr_req = ill->ill_phys_addr_pend;
15643 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15644 		if (physaddr_req == DL_IPV6_TOKEN ||
15645 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15646 			if (physaddr_req == DL_IPV6_TOKEN) {
15647 				/*
15648 				 * bcopy to low-order bits of ill_token
15649 				 *
15650 				 * XXX Temporary hack - currently,
15651 				 * all known tokens are 64 bits,
15652 				 * so I'll cheat for the moment.
15653 				 */
15654 				dlp = (union DL_primitives *)mp->b_rptr;
15655 
15656 				mutex_enter(&ill->ill_lock);
15657 				bcopy((uchar_t *)(mp->b_rptr +
15658 				dlp->physaddr_ack.dl_addr_offset),
15659 				(void *)&ill->ill_token.s6_addr32[2],
15660 				dlp->physaddr_ack.dl_addr_length);
15661 				ill->ill_token_length =
15662 					dlp->physaddr_ack.dl_addr_length;
15663 				mutex_exit(&ill->ill_lock);
15664 			} else {
15665 				ASSERT(ill->ill_nd_lla_mp == NULL);
15666 				mp_hw = copyb(mp);
15667 				if (mp_hw == NULL) {
15668 					err = ENOMEM;
15669 					break;
15670 				}
15671 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15672 				mutex_enter(&ill->ill_lock);
15673 				ill->ill_nd_lla_mp = mp_hw;
15674 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15675 				dlp->physaddr_ack.dl_addr_offset;
15676 				ill->ill_nd_lla_len =
15677 					dlp->physaddr_ack.dl_addr_length;
15678 				mutex_exit(&ill->ill_lock);
15679 			}
15680 			break;
15681 		}
15682 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15683 		ASSERT(ill->ill_phys_addr_mp == NULL);
15684 		if (!ill->ill_ifname_pending)
15685 			break;
15686 		ill->ill_ifname_pending = 0;
15687 		if (!ioctl_aborted)
15688 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15689 		if (mp1 != NULL) {
15690 			ASSERT(connp == NULL);
15691 			q = ill->ill_wq;
15692 		}
15693 		/*
15694 		 * If any error acks received during the plumbing sequence,
15695 		 * ill_ifname_pending_err will be set. Break out and send up
15696 		 * the error to the pending ioctl.
15697 		 */
15698 		if (ill->ill_ifname_pending_err != 0) {
15699 			err = ill->ill_ifname_pending_err;
15700 			ill->ill_ifname_pending_err = 0;
15701 			break;
15702 		}
15703 		/*
15704 		 * Get the interface token.  If the zeroth interface
15705 		 * address is zero then set the address to the link local
15706 		 * address
15707 		 */
15708 		mp_hw = copyb(mp);
15709 		if (mp_hw == NULL) {
15710 			err = ENOMEM;
15711 			break;
15712 		}
15713 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15714 		ill->ill_phys_addr_mp = mp_hw;
15715 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15716 				dlp->physaddr_ack.dl_addr_offset;
15717 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15718 		    ill->ill_phys_addr_length == 0 ||
15719 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15720 			/*
15721 			 * Compatibility: atun driver returns a length of 0.
15722 			 * ipdptp has an ill_phys_addr_length of zero(from
15723 			 * DL_BIND_ACK) but a non-zero length here.
15724 			 * ipd has an ill_phys_addr_length of 4(from
15725 			 * DL_BIND_ACK) but a non-zero length here.
15726 			 */
15727 			ill->ill_phys_addr = NULL;
15728 		} else if (dlp->physaddr_ack.dl_addr_length !=
15729 		    ill->ill_phys_addr_length) {
15730 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15731 			    "Address length mismatch %d %d\n",
15732 			    dlp->physaddr_ack.dl_addr_length,
15733 			    ill->ill_phys_addr_length));
15734 			err = EINVAL;
15735 			break;
15736 		}
15737 		mutex_enter(&ill->ill_lock);
15738 		if (ill->ill_nd_lla_mp == NULL) {
15739 			ill->ill_nd_lla_mp = copyb(mp_hw);
15740 			if (ill->ill_nd_lla_mp == NULL) {
15741 				err = ENOMEM;
15742 				mutex_exit(&ill->ill_lock);
15743 				break;
15744 			}
15745 			ill->ill_nd_lla =
15746 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15747 			    dlp->physaddr_ack.dl_addr_offset;
15748 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15749 		}
15750 		mutex_exit(&ill->ill_lock);
15751 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15752 			(void) ill_setdefaulttoken(ill);
15753 
15754 		/*
15755 		 * If the ill zero interface has a zero address assign
15756 		 * it the proper link local address.
15757 		 */
15758 		ASSERT(ill->ill_ipif->ipif_id == 0);
15759 		if (ipif != NULL &&
15760 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15761 			(void) ipif_setlinklocal(ipif);
15762 		break;
15763 	}
15764 	case DL_OK_ACK:
15765 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15766 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15767 		    dloa->dl_correct_primitive));
15768 		switch (dloa->dl_correct_primitive) {
15769 		case DL_UNBIND_REQ:
15770 		case DL_ATTACH_REQ:
15771 		case DL_DETACH_REQ:
15772 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15773 			break;
15774 		}
15775 		break;
15776 	default:
15777 		break;
15778 	}
15779 
15780 	freemsg(mp);
15781 	if (mp1) {
15782 		struct iocblk *iocp;
15783 		int mode;
15784 
15785 		/*
15786 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15787 		 * SIOCSLIFNAME do a copyout.
15788 		 */
15789 		iocp = (struct iocblk *)mp1->b_rptr;
15790 
15791 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
15792 		    iocp->ioc_cmd == SIOCSLIFNAME)
15793 			mode = COPYOUT;
15794 		else
15795 			mode = NO_COPYOUT;
15796 		/*
15797 		 * The ioctl must complete now without EINPROGRESS
15798 		 * since ipsq_pending_mp_get has removed the ioctl mblk
15799 		 * from ipsq_pending_mp. Otherwise the ioctl will be
15800 		 * stuck for ever in the ipsq.
15801 		 */
15802 		ASSERT(err != EINPROGRESS);
15803 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
15804 
15805 	}
15806 }
15807 
15808 /*
15809  * ip_rput_other is called by ip_rput to handle messages modifying the global
15810  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15811  */
15812 /* ARGSUSED */
15813 void
15814 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15815 {
15816 	ill_t		*ill;
15817 	struct iocblk	*iocp;
15818 	mblk_t		*mp1;
15819 	conn_t		*connp = NULL;
15820 
15821 	ip1dbg(("ip_rput_other "));
15822 	ill = (ill_t *)q->q_ptr;
15823 	/*
15824 	 * This routine is not a writer in the case of SIOCGTUNPARAM
15825 	 * in which case ipsq is NULL.
15826 	 */
15827 	if (ipsq != NULL) {
15828 		ASSERT(IAM_WRITER_IPSQ(ipsq));
15829 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15830 	}
15831 
15832 	switch (mp->b_datap->db_type) {
15833 	case M_ERROR:
15834 	case M_HANGUP:
15835 		/*
15836 		 * The device has a problem.  We force the ILL down.  It can
15837 		 * be brought up again manually using SIOCSIFFLAGS (via
15838 		 * ifconfig or equivalent).
15839 		 */
15840 		ASSERT(ipsq != NULL);
15841 		if (mp->b_rptr < mp->b_wptr)
15842 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
15843 		if (ill->ill_error == 0)
15844 			ill->ill_error = ENXIO;
15845 		if (!ill_down_start(q, mp))
15846 			return;
15847 		ipif_all_down_tail(ipsq, q, mp, NULL);
15848 		break;
15849 	case M_IOCACK:
15850 		iocp = (struct iocblk *)mp->b_rptr;
15851 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
15852 		switch (iocp->ioc_cmd) {
15853 		case SIOCSTUNPARAM:
15854 		case OSIOCSTUNPARAM:
15855 			ASSERT(ipsq != NULL);
15856 			/*
15857 			 * Finish socket ioctl passed through to tun.
15858 			 * We should have an IOCTL waiting on this.
15859 			 */
15860 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15861 			if (ill->ill_isv6) {
15862 				struct iftun_req *ta;
15863 
15864 				/*
15865 				 * if a source or destination is
15866 				 * being set, try and set the link
15867 				 * local address for the tunnel
15868 				 */
15869 				ta = (struct iftun_req *)mp->b_cont->
15870 				    b_cont->b_rptr;
15871 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
15872 					ipif_set_tun_llink(ill, ta);
15873 				}
15874 
15875 			}
15876 			if (mp1 != NULL) {
15877 				/*
15878 				 * Now copy back the b_next/b_prev used by
15879 				 * mi code for the mi_copy* functions.
15880 				 * See ip_sioctl_tunparam() for the reason.
15881 				 * Also protect against missing b_cont.
15882 				 */
15883 				if (mp->b_cont != NULL) {
15884 					mp->b_cont->b_next =
15885 					    mp1->b_cont->b_next;
15886 					mp->b_cont->b_prev =
15887 					    mp1->b_cont->b_prev;
15888 				}
15889 				inet_freemsg(mp1);
15890 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15891 				ASSERT(connp != NULL);
15892 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15893 				    iocp->ioc_error, NO_COPYOUT,
15894 				    ipsq->ipsq_current_ipif, ipsq);
15895 			} else {
15896 				ASSERT(connp == NULL);
15897 				putnext(q, mp);
15898 			}
15899 			break;
15900 		case SIOCGTUNPARAM:
15901 		case OSIOCGTUNPARAM:
15902 			/*
15903 			 * This is really M_IOCDATA from the tunnel driver.
15904 			 * convert back and complete the ioctl.
15905 			 * We should have an IOCTL waiting on this.
15906 			 */
15907 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
15908 			if (mp1) {
15909 				/*
15910 				 * Now copy back the b_next/b_prev used by
15911 				 * mi code for the mi_copy* functions.
15912 				 * See ip_sioctl_tunparam() for the reason.
15913 				 * Also protect against missing b_cont.
15914 				 */
15915 				if (mp->b_cont != NULL) {
15916 					mp->b_cont->b_next =
15917 					    mp1->b_cont->b_next;
15918 					mp->b_cont->b_prev =
15919 					    mp1->b_cont->b_prev;
15920 				}
15921 				inet_freemsg(mp1);
15922 				if (iocp->ioc_error == 0)
15923 					mp->b_datap->db_type = M_IOCDATA;
15924 				ASSERT(connp != NULL);
15925 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15926 				    iocp->ioc_error, COPYOUT, NULL, NULL);
15927 			} else {
15928 				ASSERT(connp == NULL);
15929 				putnext(q, mp);
15930 			}
15931 			break;
15932 		default:
15933 			break;
15934 		}
15935 		break;
15936 	case M_IOCNAK:
15937 		iocp = (struct iocblk *)mp->b_rptr;
15938 
15939 		switch (iocp->ioc_cmd) {
15940 		int mode;
15941 		ipif_t	*ipif;
15942 
15943 		case DL_IOC_HDR_INFO:
15944 			/*
15945 			 * If this was the first attempt turn of the
15946 			 * fastpath probing.
15947 			 */
15948 			mutex_enter(&ill->ill_lock);
15949 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
15950 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
15951 				mutex_exit(&ill->ill_lock);
15952 				ill_fastpath_nack(ill);
15953 				ip1dbg(("ip_rput: DLPI fastpath off on "
15954 				    "interface %s\n",
15955 				    ill->ill_name));
15956 			} else {
15957 				mutex_exit(&ill->ill_lock);
15958 			}
15959 			freemsg(mp);
15960 			break;
15961 		case SIOCSTUNPARAM:
15962 		case OSIOCSTUNPARAM:
15963 			ASSERT(ipsq != NULL);
15964 			/*
15965 			 * Finish socket ioctl passed through to tun
15966 			 * We should have an IOCTL waiting on this.
15967 			 */
15968 			/* FALLTHRU */
15969 		case SIOCGTUNPARAM:
15970 		case OSIOCGTUNPARAM:
15971 			/*
15972 			 * This is really M_IOCDATA from the tunnel driver.
15973 			 * convert back and complete the ioctl.
15974 			 * We should have an IOCTL waiting on this.
15975 			 */
15976 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
15977 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
15978 				mp1 = ill_pending_mp_get(ill, &connp,
15979 				    iocp->ioc_id);
15980 				mode = COPYOUT;
15981 				ipsq = NULL;
15982 				ipif = NULL;
15983 			} else {
15984 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15985 				mode = NO_COPYOUT;
15986 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15987 				ipif = ipsq->ipsq_current_ipif;
15988 			}
15989 			if (mp1 != NULL) {
15990 				/*
15991 				 * Now copy back the b_next/b_prev used by
15992 				 * mi code for the mi_copy* functions.
15993 				 * See ip_sioctl_tunparam() for the reason.
15994 				 * Also protect against missing b_cont.
15995 				 */
15996 				if (mp->b_cont != NULL) {
15997 					mp->b_cont->b_next =
15998 					    mp1->b_cont->b_next;
15999 					mp->b_cont->b_prev =
16000 					    mp1->b_cont->b_prev;
16001 				}
16002 				inet_freemsg(mp1);
16003 				if (iocp->ioc_error == 0)
16004 					iocp->ioc_error = EINVAL;
16005 				ASSERT(connp != NULL);
16006 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16007 				    iocp->ioc_error, mode, ipif, ipsq);
16008 			} else {
16009 				ASSERT(connp == NULL);
16010 				putnext(q, mp);
16011 			}
16012 			break;
16013 		default:
16014 			break;
16015 		}
16016 	default:
16017 		break;
16018 	}
16019 }
16020 
16021 /*
16022  * NOTE : This function does not ire_refrele the ire argument passed in.
16023  *
16024  * IPQoS notes
16025  * IP policy is invoked twice for a forwarded packet, once on the read side
16026  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16027  * enabled. An additional parameter, in_ill, has been added for this purpose.
16028  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16029  * because ip_mroute drops this information.
16030  *
16031  */
16032 void
16033 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16034 {
16035 	uint32_t	pkt_len;
16036 	queue_t	*q;
16037 	uint32_t	sum;
16038 #define	rptr	((uchar_t *)ipha)
16039 	uint32_t	max_frag;
16040 	uint32_t	ill_index;
16041 
16042 	/* Get the ill_index of the incoming ILL */
16043 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16044 
16045 	/* Initiate Read side IPPF processing */
16046 	if (IPP_ENABLED(IPP_FWD_IN)) {
16047 		ip_process(IPP_FWD_IN, &mp, ill_index);
16048 		if (mp == NULL) {
16049 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16050 			    "during IPPF processing\n"));
16051 			return;
16052 		}
16053 	}
16054 
16055 	pkt_len = ntohs(ipha->ipha_length);
16056 
16057 	/* Adjust the checksum to reflect the ttl decrement. */
16058 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16059 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16060 
16061 	if (ipha->ipha_ttl-- <= 1) {
16062 		if (ip_csum_hdr(ipha)) {
16063 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16064 			goto drop_pkt;
16065 		}
16066 		/*
16067 		 * Note: ire_stq this will be NULL for multicast
16068 		 * datagrams using the long path through arp (the IRE
16069 		 * is not an IRE_CACHE). This should not cause
16070 		 * problems since we don't generate ICMP errors for
16071 		 * multicast packets.
16072 		 */
16073 		q = ire->ire_stq;
16074 		if (q != NULL) {
16075 			/* Sent by forwarding path, and router is global zone */
16076 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16077 			    GLOBAL_ZONEID);
16078 		} else
16079 			freemsg(mp);
16080 		return;
16081 	}
16082 
16083 	/*
16084 	 * Don't forward if the interface is down
16085 	 */
16086 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16087 		BUMP_MIB(&ip_mib, ipInDiscards);
16088 		ip2dbg(("ip_rput_forward:interface is down\n"));
16089 		goto drop_pkt;
16090 	}
16091 
16092 	/* Get the ill_index of the outgoing ILL */
16093 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16094 
16095 	if (is_system_labeled()) {
16096 		mblk_t *mp1;
16097 
16098 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16099 			BUMP_MIB(&ip_mib, ipForwProhibits);
16100 			goto drop_pkt;
16101 		}
16102 		/* Size may have changed */
16103 		mp = mp1;
16104 		ipha = (ipha_t *)mp->b_rptr;
16105 		pkt_len = ntohs(ipha->ipha_length);
16106 	}
16107 
16108 	/* Check if there are options to update */
16109 	if (!IS_SIMPLE_IPH(ipha)) {
16110 		if (ip_csum_hdr(ipha)) {
16111 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16112 			goto drop_pkt;
16113 		}
16114 		if (ip_rput_forward_options(mp, ipha, ire)) {
16115 			return;
16116 		}
16117 
16118 		ipha->ipha_hdr_checksum = 0;
16119 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16120 	}
16121 	max_frag = ire->ire_max_frag;
16122 	if (pkt_len > max_frag) {
16123 		/*
16124 		 * It needs fragging on its way out.  We haven't
16125 		 * verified the header checksum yet.  Since we
16126 		 * are going to put a surely good checksum in the
16127 		 * outgoing header, we have to make sure that it
16128 		 * was good coming in.
16129 		 */
16130 		if (ip_csum_hdr(ipha)) {
16131 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16132 			goto drop_pkt;
16133 		}
16134 		/* Initiate Write side IPPF processing */
16135 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16136 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16137 			if (mp == NULL) {
16138 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16139 				    " during IPPF processing\n"));
16140 				return;
16141 			}
16142 		}
16143 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
16144 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16145 		return;
16146 	}
16147 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16148 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16149 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16150 	/* ip_xmit_v4 always consumes the packet */
16151 	return;
16152 
16153 drop_pkt:;
16154 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16155 	freemsg(mp);
16156 #undef	rptr
16157 }
16158 
16159 void
16160 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16161 {
16162 	ire_t	*ire;
16163 
16164 	ASSERT(!ipif->ipif_isv6);
16165 	/*
16166 	 * Find an IRE which matches the destination and the outgoing
16167 	 * queue in the cache table. All we need is an IRE_CACHE which
16168 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16169 	 * then it is enough to have some IRE_CACHE in the group.
16170 	 */
16171 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16172 		dst = ipif->ipif_pp_dst_addr;
16173 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16174 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16175 	if (ire == NULL) {
16176 		/*
16177 		 * Mark this packet to make it be delivered to
16178 		 * ip_rput_forward after the new ire has been
16179 		 * created.
16180 		 */
16181 		mp->b_prev = NULL;
16182 		mp->b_next = mp;
16183 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16184 		    NULL, 0, GLOBAL_ZONEID);
16185 	} else {
16186 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16187 		IRE_REFRELE(ire);
16188 	}
16189 }
16190 
16191 /* Update any source route, record route or timestamp options */
16192 static int
16193 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16194 {
16195 	ipoptp_t	opts;
16196 	uchar_t		*opt;
16197 	uint8_t		optval;
16198 	uint8_t		optlen;
16199 	ipaddr_t	dst;
16200 	uint32_t	ts;
16201 	ire_t		*dst_ire = NULL;
16202 	ire_t		*tmp_ire = NULL;
16203 	timestruc_t	now;
16204 
16205 	ip2dbg(("ip_rput_forward_options\n"));
16206 	dst = ipha->ipha_dst;
16207 	for (optval = ipoptp_first(&opts, ipha);
16208 	    optval != IPOPT_EOL;
16209 	    optval = ipoptp_next(&opts)) {
16210 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16211 		opt = opts.ipoptp_cur;
16212 		optlen = opts.ipoptp_len;
16213 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16214 		    optval, opts.ipoptp_len));
16215 		switch (optval) {
16216 			uint32_t off;
16217 		case IPOPT_SSRR:
16218 		case IPOPT_LSRR:
16219 			/* Check if adminstratively disabled */
16220 			if (!ip_forward_src_routed) {
16221 				BUMP_MIB(&ip_mib, ipForwProhibits);
16222 				if (ire->ire_stq != NULL) {
16223 					/*
16224 					 * Sent by forwarding path, and router
16225 					 * is global zone
16226 					 */
16227 					icmp_unreachable(ire->ire_stq, mp,
16228 					    ICMP_SOURCE_ROUTE_FAILED,
16229 					    GLOBAL_ZONEID);
16230 				} else {
16231 					ip0dbg(("ip_rput_forward_options: "
16232 					    "unable to send unreach\n"));
16233 					freemsg(mp);
16234 				}
16235 				return (-1);
16236 			}
16237 
16238 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16239 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16240 			if (dst_ire == NULL) {
16241 				/*
16242 				 * Must be partial since ip_rput_options
16243 				 * checked for strict.
16244 				 */
16245 				break;
16246 			}
16247 			off = opt[IPOPT_OFFSET];
16248 			off--;
16249 		redo_srr:
16250 			if (optlen < IP_ADDR_LEN ||
16251 			    off > optlen - IP_ADDR_LEN) {
16252 				/* End of source route */
16253 				ip1dbg((
16254 				    "ip_rput_forward_options: end of SR\n"));
16255 				ire_refrele(dst_ire);
16256 				break;
16257 			}
16258 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16259 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16260 			    IP_ADDR_LEN);
16261 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16262 			    ntohl(dst)));
16263 
16264 			/*
16265 			 * Check if our address is present more than
16266 			 * once as consecutive hops in source route.
16267 			 */
16268 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16269 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16270 			if (tmp_ire != NULL) {
16271 				ire_refrele(tmp_ire);
16272 				off += IP_ADDR_LEN;
16273 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16274 				goto redo_srr;
16275 			}
16276 			ipha->ipha_dst = dst;
16277 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16278 			ire_refrele(dst_ire);
16279 			break;
16280 		case IPOPT_RR:
16281 			off = opt[IPOPT_OFFSET];
16282 			off--;
16283 			if (optlen < IP_ADDR_LEN ||
16284 			    off > optlen - IP_ADDR_LEN) {
16285 				/* No more room - ignore */
16286 				ip1dbg((
16287 				    "ip_rput_forward_options: end of RR\n"));
16288 				break;
16289 			}
16290 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16291 			    IP_ADDR_LEN);
16292 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16293 			break;
16294 		case IPOPT_TS:
16295 			/* Insert timestamp if there is room */
16296 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16297 			case IPOPT_TS_TSONLY:
16298 				off = IPOPT_TS_TIMELEN;
16299 				break;
16300 			case IPOPT_TS_PRESPEC:
16301 			case IPOPT_TS_PRESPEC_RFC791:
16302 				/* Verify that the address matched */
16303 				off = opt[IPOPT_OFFSET] - 1;
16304 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16305 				dst_ire = ire_ctable_lookup(dst, 0,
16306 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16307 				    MATCH_IRE_TYPE);
16308 
16309 				if (dst_ire == NULL) {
16310 					/* Not for us */
16311 					break;
16312 				}
16313 				ire_refrele(dst_ire);
16314 				/* FALLTHRU */
16315 			case IPOPT_TS_TSANDADDR:
16316 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16317 				break;
16318 			default:
16319 				/*
16320 				 * ip_*put_options should have already
16321 				 * dropped this packet.
16322 				 */
16323 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16324 				    "unknown IT - bug in ip_rput_options?\n");
16325 				return (0);	/* Keep "lint" happy */
16326 			}
16327 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16328 				/* Increase overflow counter */
16329 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16330 				opt[IPOPT_POS_OV_FLG] =
16331 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16332 				    (off << 4));
16333 				break;
16334 			}
16335 			off = opt[IPOPT_OFFSET] - 1;
16336 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16337 			case IPOPT_TS_PRESPEC:
16338 			case IPOPT_TS_PRESPEC_RFC791:
16339 			case IPOPT_TS_TSANDADDR:
16340 				bcopy(&ire->ire_src_addr,
16341 				    (char *)opt + off, IP_ADDR_LEN);
16342 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16343 				/* FALLTHRU */
16344 			case IPOPT_TS_TSONLY:
16345 				off = opt[IPOPT_OFFSET] - 1;
16346 				/* Compute # of milliseconds since midnight */
16347 				gethrestime(&now);
16348 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16349 				    now.tv_nsec / (NANOSEC / MILLISEC);
16350 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16351 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16352 				break;
16353 			}
16354 			break;
16355 		}
16356 	}
16357 	return (0);
16358 }
16359 
16360 /*
16361  * This is called after processing at least one of AH/ESP headers.
16362  *
16363  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16364  * the actual, physical interface on which the packet was received,
16365  * but, when ip_strict_dst_multihoming is set to 1, could be the
16366  * interface which had the ipha_dst configured when the packet went
16367  * through ip_rput. The ill_index corresponding to the recv_ill
16368  * is saved in ipsec_in_rill_index
16369  */
16370 void
16371 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16372 {
16373 	mblk_t *mp;
16374 	ipaddr_t dst;
16375 	in6_addr_t *v6dstp;
16376 	ipha_t *ipha;
16377 	ip6_t *ip6h;
16378 	ipsec_in_t *ii;
16379 	boolean_t ill_need_rele = B_FALSE;
16380 	boolean_t rill_need_rele = B_FALSE;
16381 	boolean_t ire_need_rele = B_FALSE;
16382 
16383 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16384 	ASSERT(ii->ipsec_in_ill_index != 0);
16385 
16386 	mp = ipsec_mp->b_cont;
16387 	ASSERT(mp != NULL);
16388 
16389 
16390 	if (ill == NULL) {
16391 		ASSERT(recv_ill == NULL);
16392 		/*
16393 		 * We need to get the original queue on which ip_rput_local
16394 		 * or ip_rput_data_v6 was called.
16395 		 */
16396 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16397 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16398 		ill_need_rele = B_TRUE;
16399 
16400 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16401 			recv_ill = ill_lookup_on_ifindex(
16402 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16403 			    NULL, NULL, NULL, NULL);
16404 			rill_need_rele = B_TRUE;
16405 		} else {
16406 			recv_ill = ill;
16407 		}
16408 
16409 		if ((ill == NULL) || (recv_ill == NULL)) {
16410 			ip0dbg(("ip_fanout_proto_again: interface "
16411 			    "disappeared\n"));
16412 			if (ill != NULL)
16413 				ill_refrele(ill);
16414 			if (recv_ill != NULL)
16415 				ill_refrele(recv_ill);
16416 			freemsg(ipsec_mp);
16417 			return;
16418 		}
16419 	}
16420 
16421 	ASSERT(ill != NULL && recv_ill != NULL);
16422 
16423 	if (mp->b_datap->db_type == M_CTL) {
16424 		/*
16425 		 * AH/ESP is returning the ICMP message after
16426 		 * removing their headers. Fanout again till
16427 		 * it gets to the right protocol.
16428 		 */
16429 		if (ii->ipsec_in_v4) {
16430 			icmph_t *icmph;
16431 			int iph_hdr_length;
16432 			int hdr_length;
16433 
16434 			ipha = (ipha_t *)mp->b_rptr;
16435 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16436 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16437 			ipha = (ipha_t *)&icmph[1];
16438 			hdr_length = IPH_HDR_LENGTH(ipha);
16439 			/*
16440 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16441 			 * Reset the type to M_DATA.
16442 			 */
16443 			mp->b_datap->db_type = M_DATA;
16444 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16445 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16446 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16447 		} else {
16448 			icmp6_t *icmp6;
16449 			int hdr_length;
16450 
16451 			ip6h = (ip6_t *)mp->b_rptr;
16452 			/* Don't call hdr_length_v6() unless you have to. */
16453 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16454 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16455 			else
16456 				hdr_length = IPV6_HDR_LEN;
16457 
16458 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16459 			/*
16460 			 * icmp_inbound_error_fanout_v6 may need to do
16461 			 * pullupmsg.  Reset the type to M_DATA.
16462 			 */
16463 			mp->b_datap->db_type = M_DATA;
16464 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16465 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16466 		}
16467 		if (ill_need_rele)
16468 			ill_refrele(ill);
16469 		if (rill_need_rele)
16470 			ill_refrele(recv_ill);
16471 		return;
16472 	}
16473 
16474 	if (ii->ipsec_in_v4) {
16475 		ipha = (ipha_t *)mp->b_rptr;
16476 		dst = ipha->ipha_dst;
16477 		if (CLASSD(dst)) {
16478 			/*
16479 			 * Multicast has to be delivered to all streams.
16480 			 */
16481 			dst = INADDR_BROADCAST;
16482 		}
16483 
16484 		if (ire == NULL) {
16485 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16486 			    MBLK_GETLABEL(mp));
16487 			if (ire == NULL) {
16488 				if (ill_need_rele)
16489 					ill_refrele(ill);
16490 				if (rill_need_rele)
16491 					ill_refrele(recv_ill);
16492 				ip1dbg(("ip_fanout_proto_again: "
16493 				    "IRE not found"));
16494 				freemsg(ipsec_mp);
16495 				return;
16496 			}
16497 			ire_need_rele = B_TRUE;
16498 		}
16499 
16500 		switch (ipha->ipha_protocol) {
16501 			case IPPROTO_UDP:
16502 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16503 				    recv_ill);
16504 				if (ire_need_rele)
16505 					ire_refrele(ire);
16506 				break;
16507 			case IPPROTO_TCP:
16508 				if (!ire_need_rele)
16509 					IRE_REFHOLD(ire);
16510 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16511 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16512 				IRE_REFRELE(ire);
16513 				if (mp != NULL)
16514 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16515 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16516 				break;
16517 			case IPPROTO_SCTP:
16518 				if (!ire_need_rele)
16519 					IRE_REFHOLD(ire);
16520 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16521 				    ipsec_mp, 0, ill->ill_rq, dst);
16522 				break;
16523 			default:
16524 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16525 				    recv_ill);
16526 				if (ire_need_rele)
16527 					ire_refrele(ire);
16528 				break;
16529 		}
16530 	} else {
16531 		uint32_t rput_flags = 0;
16532 
16533 		ip6h = (ip6_t *)mp->b_rptr;
16534 		v6dstp = &ip6h->ip6_dst;
16535 		/*
16536 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16537 		 * address.
16538 		 *
16539 		 * Currently, we don't store that state in the IPSEC_IN
16540 		 * message, and we may need to.
16541 		 */
16542 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16543 		    IP6_IN_LLMCAST : 0);
16544 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16545 		    NULL, NULL);
16546 	}
16547 	if (ill_need_rele)
16548 		ill_refrele(ill);
16549 	if (rill_need_rele)
16550 		ill_refrele(recv_ill);
16551 }
16552 
16553 /*
16554  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16555  * returns 'true' if there are still fragments left on the queue, in
16556  * which case we restart the timer.
16557  */
16558 void
16559 ill_frag_timer(void *arg)
16560 {
16561 	ill_t	*ill = (ill_t *)arg;
16562 	boolean_t frag_pending;
16563 
16564 	mutex_enter(&ill->ill_lock);
16565 	ASSERT(!ill->ill_fragtimer_executing);
16566 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16567 		ill->ill_frag_timer_id = 0;
16568 		mutex_exit(&ill->ill_lock);
16569 		return;
16570 	}
16571 	ill->ill_fragtimer_executing = 1;
16572 	mutex_exit(&ill->ill_lock);
16573 
16574 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16575 
16576 	/*
16577 	 * Restart the timer, if we have fragments pending or if someone
16578 	 * wanted us to be scheduled again.
16579 	 */
16580 	mutex_enter(&ill->ill_lock);
16581 	ill->ill_fragtimer_executing = 0;
16582 	ill->ill_frag_timer_id = 0;
16583 	if (frag_pending || ill->ill_fragtimer_needrestart)
16584 		ill_frag_timer_start(ill);
16585 	mutex_exit(&ill->ill_lock);
16586 }
16587 
16588 void
16589 ill_frag_timer_start(ill_t *ill)
16590 {
16591 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16592 
16593 	/* If the ill is closing or opening don't proceed */
16594 	if (ill->ill_state_flags & ILL_CONDEMNED)
16595 		return;
16596 
16597 	if (ill->ill_fragtimer_executing) {
16598 		/*
16599 		 * ill_frag_timer is currently executing. Just record the
16600 		 * the fact that we want the timer to be restarted.
16601 		 * ill_frag_timer will post a timeout before it returns,
16602 		 * ensuring it will be called again.
16603 		 */
16604 		ill->ill_fragtimer_needrestart = 1;
16605 		return;
16606 	}
16607 
16608 	if (ill->ill_frag_timer_id == 0) {
16609 		/*
16610 		 * The timer is neither running nor is the timeout handler
16611 		 * executing. Post a timeout so that ill_frag_timer will be
16612 		 * called
16613 		 */
16614 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16615 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16616 		ill->ill_fragtimer_needrestart = 0;
16617 	}
16618 }
16619 
16620 /*
16621  * This routine is needed for loopback when forwarding multicasts.
16622  *
16623  * IPQoS Notes:
16624  * IPPF processing is done in fanout routines.
16625  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16626  * processing for IPSec packets is done when it comes back in clear.
16627  * NOTE : The callers of this function need to do the ire_refrele for the
16628  *	  ire that is being passed in.
16629  */
16630 void
16631 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16632     ill_t *recv_ill)
16633 {
16634 	ill_t	*ill = (ill_t *)q->q_ptr;
16635 	uint32_t	sum;
16636 	uint32_t	u1;
16637 	uint32_t	u2;
16638 	int		hdr_length;
16639 	boolean_t	mctl_present;
16640 	mblk_t		*first_mp = mp;
16641 	mblk_t		*hada_mp = NULL;
16642 	ipha_t		*inner_ipha;
16643 
16644 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16645 	    "ip_rput_locl_start: q %p", q);
16646 
16647 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16648 
16649 
16650 #define	rptr	((uchar_t *)ipha)
16651 #define	iphs	((uint16_t *)ipha)
16652 
16653 	/*
16654 	 * no UDP or TCP packet should come here anymore.
16655 	 */
16656 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16657 	    (ipha->ipha_protocol != IPPROTO_UDP));
16658 
16659 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16660 	if (mctl_present &&
16661 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16662 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16663 
16664 		/*
16665 		 * It's an IPsec accelerated packet.
16666 		 * Keep a pointer to the data attributes around until
16667 		 * we allocate the ipsec_info_t.
16668 		 */
16669 		IPSECHW_DEBUG(IPSECHW_PKT,
16670 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16671 		hada_mp = first_mp;
16672 		hada_mp->b_cont = NULL;
16673 		/*
16674 		 * Since it is accelerated, it comes directly from
16675 		 * the ill and the data attributes is followed by
16676 		 * the packet data.
16677 		 */
16678 		ASSERT(mp->b_datap->db_type != M_CTL);
16679 		first_mp = mp;
16680 		mctl_present = B_FALSE;
16681 	}
16682 
16683 	/*
16684 	 * IF M_CTL is not present, then ipsec_in_is_secure
16685 	 * should return B_TRUE. There is a case where loopback
16686 	 * packets has an M_CTL in the front with all the
16687 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16688 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16689 	 * packets never comes here, it is safe to ASSERT the
16690 	 * following.
16691 	 */
16692 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16693 
16694 
16695 	/* u1 is # words of IP options */
16696 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16697 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16698 
16699 	if (u1) {
16700 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16701 			if (hada_mp != NULL)
16702 				freemsg(hada_mp);
16703 			return;
16704 		}
16705 	} else {
16706 		/* Check the IP header checksum.  */
16707 #define	uph	((uint16_t *)ipha)
16708 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16709 		    uph[6] + uph[7] + uph[8] + uph[9];
16710 #undef  uph
16711 		/* finish doing IP checksum */
16712 		sum = (sum & 0xFFFF) + (sum >> 16);
16713 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16714 		/*
16715 		 * Don't verify header checksum if this packet is coming
16716 		 * back from AH/ESP as we already did it.
16717 		 */
16718 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16719 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16720 			goto drop_pkt;
16721 		}
16722 	}
16723 
16724 	/*
16725 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16726 	 * might be called more than once for secure packets, count only
16727 	 * the first time.
16728 	 */
16729 	if (!mctl_present) {
16730 		UPDATE_IB_PKT_COUNT(ire);
16731 		ire->ire_last_used_time = lbolt;
16732 	}
16733 
16734 	/* Check for fragmentation offset. */
16735 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16736 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16737 	if (u1) {
16738 		/*
16739 		 * We re-assemble fragments before we do the AH/ESP
16740 		 * processing. Thus, M_CTL should not be present
16741 		 * while we are re-assembling.
16742 		 */
16743 		ASSERT(!mctl_present);
16744 		ASSERT(first_mp == mp);
16745 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16746 			return;
16747 		}
16748 		/*
16749 		 * Make sure that first_mp points back to mp as
16750 		 * the mp we came in with could have changed in
16751 		 * ip_rput_fragment().
16752 		 */
16753 		ipha = (ipha_t *)mp->b_rptr;
16754 		first_mp = mp;
16755 	}
16756 
16757 	/*
16758 	 * Clear hardware checksumming flag as it is currently only
16759 	 * used by TCP and UDP.
16760 	 */
16761 	DB_CKSUMFLAGS(mp) = 0;
16762 
16763 	/* Now we have a complete datagram, destined for this machine. */
16764 	u1 = IPH_HDR_LENGTH(ipha);
16765 	switch (ipha->ipha_protocol) {
16766 	case IPPROTO_ICMP: {
16767 		ire_t		*ire_zone;
16768 		ilm_t		*ilm;
16769 		mblk_t		*mp1;
16770 		zoneid_t	last_zoneid;
16771 
16772 		if (CLASSD(ipha->ipha_dst) &&
16773 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
16774 			ASSERT(ire->ire_type == IRE_BROADCAST);
16775 			/*
16776 			 * In the multicast case, applications may have joined
16777 			 * the group from different zones, so we need to deliver
16778 			 * the packet to each of them. Loop through the
16779 			 * multicast memberships structures (ilm) on the receive
16780 			 * ill and send a copy of the packet up each matching
16781 			 * one. However, we don't do this for multicasts sent on
16782 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16783 			 * they must stay in the sender's zone.
16784 			 *
16785 			 * ilm_add_v6() ensures that ilms in the same zone are
16786 			 * contiguous in the ill_ilm list. We use this property
16787 			 * to avoid sending duplicates needed when two
16788 			 * applications in the same zone join the same group on
16789 			 * different logical interfaces: we ignore the ilm if
16790 			 * its zoneid is the same as the last matching one.
16791 			 * In addition, the sending of the packet for
16792 			 * ire_zoneid is delayed until all of the other ilms
16793 			 * have been exhausted.
16794 			 */
16795 			last_zoneid = -1;
16796 			ILM_WALKER_HOLD(recv_ill);
16797 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
16798 			    ilm = ilm->ilm_next) {
16799 				if ((ilm->ilm_flags & ILM_DELETED) ||
16800 				    ipha->ipha_dst != ilm->ilm_addr ||
16801 				    ilm->ilm_zoneid == last_zoneid ||
16802 				    ilm->ilm_zoneid == ire->ire_zoneid ||
16803 				    ilm->ilm_zoneid == ALL_ZONES ||
16804 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
16805 					continue;
16806 				mp1 = ip_copymsg(first_mp);
16807 				if (mp1 == NULL)
16808 					continue;
16809 				icmp_inbound(q, mp1, B_TRUE, ill,
16810 				    0, sum, mctl_present, B_TRUE,
16811 				    recv_ill, ilm->ilm_zoneid);
16812 				last_zoneid = ilm->ilm_zoneid;
16813 			}
16814 			ILM_WALKER_RELE(recv_ill);
16815 		} else if (ire->ire_type == IRE_BROADCAST) {
16816 			/*
16817 			 * In the broadcast case, there may be many zones
16818 			 * which need a copy of the packet delivered to them.
16819 			 * There is one IRE_BROADCAST per broadcast address
16820 			 * and per zone; we walk those using a helper function.
16821 			 * In addition, the sending of the packet for ire is
16822 			 * delayed until all of the other ires have been
16823 			 * processed.
16824 			 */
16825 			IRB_REFHOLD(ire->ire_bucket);
16826 			ire_zone = NULL;
16827 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
16828 			    ire)) != NULL) {
16829 				mp1 = ip_copymsg(first_mp);
16830 				if (mp1 == NULL)
16831 					continue;
16832 
16833 				UPDATE_IB_PKT_COUNT(ire_zone);
16834 				ire_zone->ire_last_used_time = lbolt;
16835 				icmp_inbound(q, mp1, B_TRUE, ill,
16836 				    0, sum, mctl_present, B_TRUE,
16837 				    recv_ill, ire_zone->ire_zoneid);
16838 			}
16839 			IRB_REFRELE(ire->ire_bucket);
16840 		}
16841 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
16842 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
16843 		    ire->ire_zoneid);
16844 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16845 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
16846 		return;
16847 	}
16848 	case IPPROTO_IGMP:
16849 		/*
16850 		 * If we are not willing to accept IGMP packets in clear,
16851 		 * then check with global policy.
16852 		 */
16853 		if (igmp_accept_clear_messages == 0) {
16854 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16855 			    ipha, NULL, mctl_present);
16856 			if (first_mp == NULL)
16857 				return;
16858 		}
16859 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16860 			freemsg(first_mp);
16861 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
16862 			BUMP_MIB(&ip_mib, ipInDiscards);
16863 			return;
16864 		}
16865 		if (igmp_input(q, mp, ill)) {
16866 			/* Bad packet - discarded by igmp_input */
16867 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16868 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
16869 			if (mctl_present)
16870 				freeb(first_mp);
16871 			return;
16872 		}
16873 		/*
16874 		 * igmp_input() may have pulled up the message so ipha needs to
16875 		 * be reinitialized.
16876 		 */
16877 		ipha = (ipha_t *)mp->b_rptr;
16878 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16879 			/* No user-level listener for IGMP packets */
16880 			goto drop_pkt;
16881 		}
16882 		/* deliver to local raw users */
16883 		break;
16884 	case IPPROTO_PIM:
16885 		/*
16886 		 * If we are not willing to accept PIM packets in clear,
16887 		 * then check with global policy.
16888 		 */
16889 		if (pim_accept_clear_messages == 0) {
16890 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16891 			    ipha, NULL, mctl_present);
16892 			if (first_mp == NULL)
16893 				return;
16894 		}
16895 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16896 			freemsg(first_mp);
16897 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
16898 			BUMP_MIB(&ip_mib, ipInDiscards);
16899 			return;
16900 		}
16901 		if (pim_input(q, mp) != 0) {
16902 			/* Bad packet - discarded by pim_input */
16903 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16904 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
16905 			if (mctl_present)
16906 				freeb(first_mp);
16907 			return;
16908 		}
16909 
16910 		/*
16911 		 * pim_input() may have pulled up the message so ipha needs to
16912 		 * be reinitialized.
16913 		 */
16914 		ipha = (ipha_t *)mp->b_rptr;
16915 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16916 			/* No user-level listener for PIM packets */
16917 			goto drop_pkt;
16918 		}
16919 		/* deliver to local raw users */
16920 		break;
16921 	case IPPROTO_ENCAP:
16922 		/*
16923 		 * Handle self-encapsulated packets (IP-in-IP where
16924 		 * the inner addresses == the outer addresses).
16925 		 */
16926 		hdr_length = IPH_HDR_LENGTH(ipha);
16927 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
16928 		    mp->b_wptr) {
16929 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
16930 			    sizeof (ipha_t) - mp->b_rptr)) {
16931 				BUMP_MIB(&ip_mib, ipInDiscards);
16932 				freemsg(first_mp);
16933 				return;
16934 			}
16935 			ipha = (ipha_t *)mp->b_rptr;
16936 		}
16937 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
16938 		/*
16939 		 * Check the sanity of the inner IP header.
16940 		 */
16941 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
16942 			BUMP_MIB(&ip_mib, ipInDiscards);
16943 			freemsg(first_mp);
16944 			return;
16945 		}
16946 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
16947 			BUMP_MIB(&ip_mib, ipInDiscards);
16948 			freemsg(first_mp);
16949 			return;
16950 		}
16951 		if (inner_ipha->ipha_src == ipha->ipha_src &&
16952 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
16953 			ipsec_in_t *ii;
16954 
16955 			/*
16956 			 * Self-encapsulated tunnel packet. Remove
16957 			 * the outer IP header and fanout again.
16958 			 * We also need to make sure that the inner
16959 			 * header is pulled up until options.
16960 			 */
16961 			mp->b_rptr = (uchar_t *)inner_ipha;
16962 			ipha = inner_ipha;
16963 			hdr_length = IPH_HDR_LENGTH(ipha);
16964 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
16965 				if (!pullupmsg(mp, (uchar_t *)ipha +
16966 				    + hdr_length - mp->b_rptr)) {
16967 					freemsg(first_mp);
16968 					return;
16969 				}
16970 				ipha = (ipha_t *)mp->b_rptr;
16971 			}
16972 			if (!mctl_present) {
16973 				ASSERT(first_mp == mp);
16974 				/*
16975 				 * This means that somebody is sending
16976 				 * Self-encapsualted packets without AH/ESP.
16977 				 * If AH/ESP was present, we would have already
16978 				 * allocated the first_mp.
16979 				 */
16980 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
16981 				    NULL) {
16982 					ip1dbg(("ip_proto_input: IPSEC_IN "
16983 					    "allocation failure.\n"));
16984 					BUMP_MIB(&ip_mib, ipInDiscards);
16985 					freemsg(mp);
16986 					return;
16987 				}
16988 				first_mp->b_cont = mp;
16989 			}
16990 			/*
16991 			 * We generally store the ill_index if we need to
16992 			 * do IPSEC processing as we lose the ill queue when
16993 			 * we come back. But in this case, we never should
16994 			 * have to store the ill_index here as it should have
16995 			 * been stored previously when we processed the
16996 			 * AH/ESP header in this routine or for non-ipsec
16997 			 * cases, we still have the queue. But for some bad
16998 			 * packets from the wire, we can get to IPSEC after
16999 			 * this and we better store the index for that case.
17000 			 */
17001 			ill = (ill_t *)q->q_ptr;
17002 			ii = (ipsec_in_t *)first_mp->b_rptr;
17003 			ii->ipsec_in_ill_index =
17004 			    ill->ill_phyint->phyint_ifindex;
17005 			ii->ipsec_in_rill_index =
17006 			    recv_ill->ill_phyint->phyint_ifindex;
17007 			if (ii->ipsec_in_decaps) {
17008 				/*
17009 				 * This packet is self-encapsulated multiple
17010 				 * times. We don't want to recurse infinitely.
17011 				 * To keep it simple, drop the packet.
17012 				 */
17013 				BUMP_MIB(&ip_mib, ipInDiscards);
17014 				freemsg(first_mp);
17015 				return;
17016 			}
17017 			ii->ipsec_in_decaps = B_TRUE;
17018 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
17019 			return;
17020 		}
17021 		break;
17022 	case IPPROTO_AH:
17023 	case IPPROTO_ESP: {
17024 		/*
17025 		 * Fast path for AH/ESP. If this is the first time
17026 		 * we are sending a datagram to AH/ESP, allocate
17027 		 * a IPSEC_IN message and prepend it. Otherwise,
17028 		 * just fanout.
17029 		 */
17030 
17031 		int ipsec_rc;
17032 		ipsec_in_t *ii;
17033 
17034 		IP_STAT(ipsec_proto_ahesp);
17035 		if (!mctl_present) {
17036 			ASSERT(first_mp == mp);
17037 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
17038 				ip1dbg(("ip_proto_input: IPSEC_IN "
17039 				    "allocation failure.\n"));
17040 				freemsg(hada_mp); /* okay ifnull */
17041 				BUMP_MIB(&ip_mib, ipInDiscards);
17042 				freemsg(mp);
17043 				return;
17044 			}
17045 			/*
17046 			 * Store the ill_index so that when we come back
17047 			 * from IPSEC we ride on the same queue.
17048 			 */
17049 			ill = (ill_t *)q->q_ptr;
17050 			ii = (ipsec_in_t *)first_mp->b_rptr;
17051 			ii->ipsec_in_ill_index =
17052 			    ill->ill_phyint->phyint_ifindex;
17053 			ii->ipsec_in_rill_index =
17054 			    recv_ill->ill_phyint->phyint_ifindex;
17055 			first_mp->b_cont = mp;
17056 			/*
17057 			 * Cache hardware acceleration info.
17058 			 */
17059 			if (hada_mp != NULL) {
17060 				IPSECHW_DEBUG(IPSECHW_PKT,
17061 				    ("ip_rput_local: caching data attr.\n"));
17062 				ii->ipsec_in_accelerated = B_TRUE;
17063 				ii->ipsec_in_da = hada_mp;
17064 				hada_mp = NULL;
17065 			}
17066 		} else {
17067 			ii = (ipsec_in_t *)first_mp->b_rptr;
17068 		}
17069 
17070 		if (!ipsec_loaded()) {
17071 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17072 			    ire->ire_zoneid);
17073 			return;
17074 		}
17075 
17076 		/* select inbound SA and have IPsec process the pkt */
17077 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17078 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17079 			if (esph == NULL)
17080 				return;
17081 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17082 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17083 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17084 			    first_mp, esph);
17085 		} else {
17086 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17087 			if (ah == NULL)
17088 				return;
17089 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17090 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17091 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17092 			    first_mp, ah);
17093 		}
17094 
17095 		switch (ipsec_rc) {
17096 		case IPSEC_STATUS_SUCCESS:
17097 			break;
17098 		case IPSEC_STATUS_FAILED:
17099 			BUMP_MIB(&ip_mib, ipInDiscards);
17100 			/* FALLTHRU */
17101 		case IPSEC_STATUS_PENDING:
17102 			return;
17103 		}
17104 		/* we're done with IPsec processing, send it up */
17105 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17106 		return;
17107 	}
17108 	default:
17109 		break;
17110 	}
17111 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17112 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17113 		    ire->ire_zoneid));
17114 		goto drop_pkt;
17115 	}
17116 	/*
17117 	 * Handle protocols with which IP is less intimate.  There
17118 	 * can be more than one stream bound to a particular
17119 	 * protocol.  When this is the case, each one gets a copy
17120 	 * of any incoming packets.
17121 	 */
17122 	ip_fanout_proto(q, first_mp, ill, ipha,
17123 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17124 	    B_TRUE, recv_ill, ire->ire_zoneid);
17125 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17126 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17127 	return;
17128 
17129 drop_pkt:
17130 	freemsg(first_mp);
17131 	if (hada_mp != NULL)
17132 		freeb(hada_mp);
17133 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17134 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17135 #undef	rptr
17136 #undef  iphs
17137 
17138 }
17139 
17140 /*
17141  * Update any source route, record route or timestamp options.
17142  * Check that we are at end of strict source route.
17143  * The options have already been checked for sanity in ip_rput_options().
17144  */
17145 static boolean_t
17146 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17147 {
17148 	ipoptp_t	opts;
17149 	uchar_t		*opt;
17150 	uint8_t		optval;
17151 	uint8_t		optlen;
17152 	ipaddr_t	dst;
17153 	uint32_t	ts;
17154 	ire_t		*dst_ire;
17155 	timestruc_t	now;
17156 	zoneid_t	zoneid;
17157 	ill_t		*ill;
17158 
17159 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17160 
17161 	ip2dbg(("ip_rput_local_options\n"));
17162 
17163 	for (optval = ipoptp_first(&opts, ipha);
17164 	    optval != IPOPT_EOL;
17165 	    optval = ipoptp_next(&opts)) {
17166 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17167 		opt = opts.ipoptp_cur;
17168 		optlen = opts.ipoptp_len;
17169 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17170 		    optval, optlen));
17171 		switch (optval) {
17172 			uint32_t off;
17173 		case IPOPT_SSRR:
17174 		case IPOPT_LSRR:
17175 			off = opt[IPOPT_OFFSET];
17176 			off--;
17177 			if (optlen < IP_ADDR_LEN ||
17178 			    off > optlen - IP_ADDR_LEN) {
17179 				/* End of source route */
17180 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17181 				break;
17182 			}
17183 			/*
17184 			 * This will only happen if two consecutive entries
17185 			 * in the source route contains our address or if
17186 			 * it is a packet with a loose source route which
17187 			 * reaches us before consuming the whole source route
17188 			 */
17189 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17190 			if (optval == IPOPT_SSRR) {
17191 				goto bad_src_route;
17192 			}
17193 			/*
17194 			 * Hack: instead of dropping the packet truncate the
17195 			 * source route to what has been used by filling the
17196 			 * rest with IPOPT_NOP.
17197 			 */
17198 			opt[IPOPT_OLEN] = (uint8_t)off;
17199 			while (off < optlen) {
17200 				opt[off++] = IPOPT_NOP;
17201 			}
17202 			break;
17203 		case IPOPT_RR:
17204 			off = opt[IPOPT_OFFSET];
17205 			off--;
17206 			if (optlen < IP_ADDR_LEN ||
17207 			    off > optlen - IP_ADDR_LEN) {
17208 				/* No more room - ignore */
17209 				ip1dbg((
17210 				    "ip_rput_local_options: end of RR\n"));
17211 				break;
17212 			}
17213 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17214 			    IP_ADDR_LEN);
17215 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17216 			break;
17217 		case IPOPT_TS:
17218 			/* Insert timestamp if there is romm */
17219 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17220 			case IPOPT_TS_TSONLY:
17221 				off = IPOPT_TS_TIMELEN;
17222 				break;
17223 			case IPOPT_TS_PRESPEC:
17224 			case IPOPT_TS_PRESPEC_RFC791:
17225 				/* Verify that the address matched */
17226 				off = opt[IPOPT_OFFSET] - 1;
17227 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17228 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17229 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17230 				if (dst_ire == NULL) {
17231 					/* Not for us */
17232 					break;
17233 				}
17234 				ire_refrele(dst_ire);
17235 				/* FALLTHRU */
17236 			case IPOPT_TS_TSANDADDR:
17237 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17238 				break;
17239 			default:
17240 				/*
17241 				 * ip_*put_options should have already
17242 				 * dropped this packet.
17243 				 */
17244 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17245 				    "unknown IT - bug in ip_rput_options?\n");
17246 				return (B_TRUE);	/* Keep "lint" happy */
17247 			}
17248 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17249 				/* Increase overflow counter */
17250 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17251 				opt[IPOPT_POS_OV_FLG] =
17252 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17253 				    (off << 4));
17254 				break;
17255 			}
17256 			off = opt[IPOPT_OFFSET] - 1;
17257 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17258 			case IPOPT_TS_PRESPEC:
17259 			case IPOPT_TS_PRESPEC_RFC791:
17260 			case IPOPT_TS_TSANDADDR:
17261 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17262 				    IP_ADDR_LEN);
17263 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17264 				/* FALLTHRU */
17265 			case IPOPT_TS_TSONLY:
17266 				off = opt[IPOPT_OFFSET] - 1;
17267 				/* Compute # of milliseconds since midnight */
17268 				gethrestime(&now);
17269 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17270 				    now.tv_nsec / (NANOSEC / MILLISEC);
17271 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17272 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17273 				break;
17274 			}
17275 			break;
17276 		}
17277 	}
17278 	return (B_TRUE);
17279 
17280 bad_src_route:
17281 	q = WR(q);
17282 	if (q->q_next != NULL)
17283 		ill = q->q_ptr;
17284 	else
17285 		ill = NULL;
17286 
17287 	/* make sure we clear any indication of a hardware checksum */
17288 	DB_CKSUMFLAGS(mp) = 0;
17289 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill);
17290 	if (zoneid == ALL_ZONES)
17291 		freemsg(mp);
17292 	else
17293 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17294 	return (B_FALSE);
17295 
17296 }
17297 
17298 /*
17299  * Process IP options in an inbound packet.  If an option affects the
17300  * effective destination address, return the next hop address via dstp.
17301  * Returns -1 if something fails in which case an ICMP error has been sent
17302  * and mp freed.
17303  */
17304 static int
17305 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17306 {
17307 	ipoptp_t	opts;
17308 	uchar_t		*opt;
17309 	uint8_t		optval;
17310 	uint8_t		optlen;
17311 	ipaddr_t	dst;
17312 	intptr_t	code = 0;
17313 	ire_t		*ire = NULL;
17314 	zoneid_t	zoneid;
17315 	ill_t		*ill;
17316 
17317 	ip2dbg(("ip_rput_options\n"));
17318 	dst = ipha->ipha_dst;
17319 	for (optval = ipoptp_first(&opts, ipha);
17320 	    optval != IPOPT_EOL;
17321 	    optval = ipoptp_next(&opts)) {
17322 		opt = opts.ipoptp_cur;
17323 		optlen = opts.ipoptp_len;
17324 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17325 		    optval, optlen));
17326 		/*
17327 		 * Note: we need to verify the checksum before we
17328 		 * modify anything thus this routine only extracts the next
17329 		 * hop dst from any source route.
17330 		 */
17331 		switch (optval) {
17332 			uint32_t off;
17333 		case IPOPT_SSRR:
17334 		case IPOPT_LSRR:
17335 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17336 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17337 			if (ire == NULL) {
17338 				if (optval == IPOPT_SSRR) {
17339 					ip1dbg(("ip_rput_options: not next"
17340 					    " strict source route 0x%x\n",
17341 					    ntohl(dst)));
17342 					code = (char *)&ipha->ipha_dst -
17343 					    (char *)ipha;
17344 					goto param_prob; /* RouterReq's */
17345 				}
17346 				ip2dbg(("ip_rput_options: "
17347 				    "not next source route 0x%x\n",
17348 				    ntohl(dst)));
17349 				break;
17350 			}
17351 			ire_refrele(ire);
17352 
17353 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17354 				ip1dbg((
17355 				    "ip_rput_options: bad option offset\n"));
17356 				code = (char *)&opt[IPOPT_OLEN] -
17357 				    (char *)ipha;
17358 				goto param_prob;
17359 			}
17360 			off = opt[IPOPT_OFFSET];
17361 			off--;
17362 		redo_srr:
17363 			if (optlen < IP_ADDR_LEN ||
17364 			    off > optlen - IP_ADDR_LEN) {
17365 				/* End of source route */
17366 				ip1dbg(("ip_rput_options: end of SR\n"));
17367 				break;
17368 			}
17369 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17370 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17371 			    ntohl(dst)));
17372 
17373 			/*
17374 			 * Check if our address is present more than
17375 			 * once as consecutive hops in source route.
17376 			 * XXX verify per-interface ip_forwarding
17377 			 * for source route?
17378 			 */
17379 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17380 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17381 
17382 			if (ire != NULL) {
17383 				ire_refrele(ire);
17384 				off += IP_ADDR_LEN;
17385 				goto redo_srr;
17386 			}
17387 
17388 			if (dst == htonl(INADDR_LOOPBACK)) {
17389 				ip1dbg(("ip_rput_options: loopback addr in "
17390 				    "source route!\n"));
17391 				goto bad_src_route;
17392 			}
17393 			/*
17394 			 * For strict: verify that dst is directly
17395 			 * reachable.
17396 			 */
17397 			if (optval == IPOPT_SSRR) {
17398 				ire = ire_ftable_lookup(dst, 0, 0,
17399 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17400 				    MBLK_GETLABEL(mp),
17401 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17402 				if (ire == NULL) {
17403 					ip1dbg(("ip_rput_options: SSRR not "
17404 					    "directly reachable: 0x%x\n",
17405 					    ntohl(dst)));
17406 					goto bad_src_route;
17407 				}
17408 				ire_refrele(ire);
17409 			}
17410 			/*
17411 			 * Defer update of the offset and the record route
17412 			 * until the packet is forwarded.
17413 			 */
17414 			break;
17415 		case IPOPT_RR:
17416 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17417 				ip1dbg((
17418 				    "ip_rput_options: bad option offset\n"));
17419 				code = (char *)&opt[IPOPT_OLEN] -
17420 				    (char *)ipha;
17421 				goto param_prob;
17422 			}
17423 			break;
17424 		case IPOPT_TS:
17425 			/*
17426 			 * Verify that length >= 5 and that there is either
17427 			 * room for another timestamp or that the overflow
17428 			 * counter is not maxed out.
17429 			 */
17430 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17431 			if (optlen < IPOPT_MINLEN_IT) {
17432 				goto param_prob;
17433 			}
17434 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17435 				ip1dbg((
17436 				    "ip_rput_options: bad option offset\n"));
17437 				code = (char *)&opt[IPOPT_OFFSET] -
17438 				    (char *)ipha;
17439 				goto param_prob;
17440 			}
17441 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17442 			case IPOPT_TS_TSONLY:
17443 				off = IPOPT_TS_TIMELEN;
17444 				break;
17445 			case IPOPT_TS_TSANDADDR:
17446 			case IPOPT_TS_PRESPEC:
17447 			case IPOPT_TS_PRESPEC_RFC791:
17448 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17449 				break;
17450 			default:
17451 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17452 				    (char *)ipha;
17453 				goto param_prob;
17454 			}
17455 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17456 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17457 				/*
17458 				 * No room and the overflow counter is 15
17459 				 * already.
17460 				 */
17461 				goto param_prob;
17462 			}
17463 			break;
17464 		}
17465 	}
17466 
17467 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17468 		*dstp = dst;
17469 		return (0);
17470 	}
17471 
17472 	ip1dbg(("ip_rput_options: error processing IP options."));
17473 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17474 
17475 param_prob:
17476 	q = WR(q);
17477 	if (q->q_next != NULL)
17478 		ill = q->q_ptr;
17479 	else
17480 		ill = NULL;
17481 
17482 	/* make sure we clear any indication of a hardware checksum */
17483 	DB_CKSUMFLAGS(mp) = 0;
17484 	/* Don't know whether this is for non-global or global/forwarding */
17485 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17486 	if (zoneid == ALL_ZONES)
17487 		freemsg(mp);
17488 	else
17489 		icmp_param_problem(q, mp, (uint8_t)code, zoneid);
17490 	return (-1);
17491 
17492 bad_src_route:
17493 	q = WR(q);
17494 	if (q->q_next != NULL)
17495 		ill = q->q_ptr;
17496 	else
17497 		ill = NULL;
17498 
17499 	/* make sure we clear any indication of a hardware checksum */
17500 	DB_CKSUMFLAGS(mp) = 0;
17501 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17502 	if (zoneid == ALL_ZONES)
17503 		freemsg(mp);
17504 	else
17505 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17506 	return (-1);
17507 }
17508 
17509 /*
17510  * IP & ICMP info in >=14 msg's ...
17511  *  - ip fixed part (mib2_ip_t)
17512  *  - icmp fixed part (mib2_icmp_t)
17513  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17514  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17515  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
17516  *  - ipRouteAttributeTable (ip 102)	labeled routes
17517  *  - ip multicast membership (ip_member_t)
17518  *  - ip multicast source filtering (ip_grpsrc_t)
17519  *  - igmp fixed part (struct igmpstat)
17520  *  - multicast routing stats (struct mrtstat)
17521  *  - multicast routing vifs (array of struct vifctl)
17522  *  - multicast routing routes (array of struct mfcctl)
17523  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17524  *					One per ill plus one generic
17525  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17526  *					One per ill plus one generic
17527  *  - ipv6RouteEntry			all IPv6 IREs
17528  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17529  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17530  *  - ipv6AddrEntry			all IPv6 ipifs
17531  *  - ipv6 multicast membership (ipv6_member_t)
17532  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17533  *
17534  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
17535  * already present.
17536  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17537  * already filled in by the caller.
17538  * Return value of 0 indicates that no messages were sent and caller
17539  * should free mpctl.
17540  */
17541 int
17542 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17543 {
17544 
17545 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17546 		return (0);
17547 	}
17548 
17549 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
17550 		return (1);
17551 	}
17552 
17553 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17554 		return (1);
17555 	}
17556 
17557 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17558 		return (1);
17559 	}
17560 
17561 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17562 		return (1);
17563 	}
17564 
17565 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17566 		return (1);
17567 	}
17568 
17569 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17570 		return (1);
17571 	}
17572 
17573 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17574 		return (1);
17575 	}
17576 
17577 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17578 		return (1);
17579 	}
17580 
17581 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17582 		return (1);
17583 	}
17584 
17585 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17586 		return (1);
17587 	}
17588 
17589 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17590 		return (1);
17591 	}
17592 
17593 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17594 		return (1);
17595 	}
17596 
17597 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17598 		return (1);
17599 	}
17600 
17601 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17602 		return (1);
17603 	}
17604 
17605 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17606 		return (1);
17607 	}
17608 
17609 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17610 		return (1);
17611 	}
17612 
17613 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17614 		return (1);
17615 	}
17616 	freemsg(mpctl);
17617 	return (1);
17618 }
17619 
17620 
17621 /* Get global IPv4 statistics */
17622 static mblk_t *
17623 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
17624 {
17625 	struct opthdr		*optp;
17626 	mblk_t			*mp2ctl;
17627 
17628 	/*
17629 	 * make a copy of the original message
17630 	 */
17631 	mp2ctl = copymsg(mpctl);
17632 
17633 	/* fixed length IP structure... */
17634 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17635 	optp->level = MIB2_IP;
17636 	optp->name = 0;
17637 	SET_MIB(ip_mib.ipForwarding,
17638 	    (WE_ARE_FORWARDING ? 1 : 2));
17639 	SET_MIB(ip_mib.ipDefaultTTL,
17640 	    (uint32_t)ip_def_ttl);
17641 	SET_MIB(ip_mib.ipReasmTimeout,
17642 	    ip_g_frag_timeout);
17643 	SET_MIB(ip_mib.ipAddrEntrySize,
17644 	    sizeof (mib2_ipAddrEntry_t));
17645 	SET_MIB(ip_mib.ipRouteEntrySize,
17646 	    sizeof (mib2_ipRouteEntry_t));
17647 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
17648 	    sizeof (mib2_ipNetToMediaEntry_t));
17649 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17650 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17651 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
17652 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17653 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
17654 	    (int)sizeof (ip_mib))) {
17655 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17656 		    (uint_t)sizeof (ip_mib)));
17657 	}
17658 
17659 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17660 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17661 	    (int)optp->level, (int)optp->name, (int)optp->len));
17662 	qreply(q, mpctl);
17663 	return (mp2ctl);
17664 }
17665 
17666 /* Global IPv4 ICMP statistics */
17667 static mblk_t *
17668 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
17669 {
17670 	struct opthdr		*optp;
17671 	mblk_t			*mp2ctl;
17672 
17673 	/*
17674 	 * Make a copy of the original message
17675 	 */
17676 	mp2ctl = copymsg(mpctl);
17677 
17678 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17679 	optp->level = MIB2_ICMP;
17680 	optp->name = 0;
17681 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17682 	    (int)sizeof (icmp_mib))) {
17683 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17684 		    (uint_t)sizeof (icmp_mib)));
17685 	}
17686 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17687 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17688 	    (int)optp->level, (int)optp->name, (int)optp->len));
17689 	qreply(q, mpctl);
17690 	return (mp2ctl);
17691 }
17692 
17693 /* Global IPv4 IGMP statistics */
17694 static mblk_t *
17695 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17696 {
17697 	struct opthdr		*optp;
17698 	mblk_t			*mp2ctl;
17699 
17700 	/*
17701 	 * make a copy of the original message
17702 	 */
17703 	mp2ctl = copymsg(mpctl);
17704 
17705 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17706 	optp->level = EXPER_IGMP;
17707 	optp->name = 0;
17708 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17709 	    (int)sizeof (igmpstat))) {
17710 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17711 		    (uint_t)sizeof (igmpstat)));
17712 	}
17713 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17714 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17715 	    (int)optp->level, (int)optp->name, (int)optp->len));
17716 	qreply(q, mpctl);
17717 	return (mp2ctl);
17718 }
17719 
17720 /* Global IPv4 Multicast Routing statistics */
17721 static mblk_t *
17722 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17723 {
17724 	struct opthdr		*optp;
17725 	mblk_t			*mp2ctl;
17726 
17727 	/*
17728 	 * make a copy of the original message
17729 	 */
17730 	mp2ctl = copymsg(mpctl);
17731 
17732 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17733 	optp->level = EXPER_DVMRP;
17734 	optp->name = 0;
17735 	if (!ip_mroute_stats(mpctl->b_cont)) {
17736 		ip0dbg(("ip_mroute_stats: failed\n"));
17737 	}
17738 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17739 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17740 	    (int)optp->level, (int)optp->name, (int)optp->len));
17741 	qreply(q, mpctl);
17742 	return (mp2ctl);
17743 }
17744 
17745 /* IPv4 address information */
17746 static mblk_t *
17747 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17748 {
17749 	struct opthdr		*optp;
17750 	mblk_t			*mp2ctl;
17751 	mblk_t			*mp_tail = NULL;
17752 	ill_t			*ill;
17753 	ipif_t			*ipif;
17754 	uint_t			bitval;
17755 	mib2_ipAddrEntry_t	mae;
17756 	zoneid_t		zoneid;
17757 	ill_walk_context_t ctx;
17758 
17759 	/*
17760 	 * make a copy of the original message
17761 	 */
17762 	mp2ctl = copymsg(mpctl);
17763 
17764 	/* ipAddrEntryTable */
17765 
17766 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17767 	optp->level = MIB2_IP;
17768 	optp->name = MIB2_IP_ADDR;
17769 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17770 
17771 	rw_enter(&ill_g_lock, RW_READER);
17772 	ill = ILL_START_WALK_V4(&ctx);
17773 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17774 		for (ipif = ill->ill_ipif; ipif != NULL;
17775 		    ipif = ipif->ipif_next) {
17776 			if (ipif->ipif_zoneid != zoneid &&
17777 			    ipif->ipif_zoneid != ALL_ZONES)
17778 				continue;
17779 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17780 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17781 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17782 
17783 			(void) ipif_get_name(ipif,
17784 			    mae.ipAdEntIfIndex.o_bytes,
17785 			    OCTET_LENGTH);
17786 			mae.ipAdEntIfIndex.o_length =
17787 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
17788 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
17789 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
17790 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
17791 			mae.ipAdEntInfo.ae_subnet_len =
17792 			    ip_mask_to_plen(ipif->ipif_net_mask);
17793 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
17794 			for (bitval = 1;
17795 			    bitval &&
17796 			    !(bitval & ipif->ipif_brd_addr);
17797 			    bitval <<= 1)
17798 				noop;
17799 			mae.ipAdEntBcastAddr = bitval;
17800 			mae.ipAdEntReasmMaxSize = 65535;
17801 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
17802 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
17803 			mae.ipAdEntInfo.ae_broadcast_addr =
17804 			    ipif->ipif_brd_addr;
17805 			mae.ipAdEntInfo.ae_pp_dst_addr =
17806 			    ipif->ipif_pp_dst_addr;
17807 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
17808 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17809 
17810 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17811 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
17812 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
17813 				    "allocate %u bytes\n",
17814 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
17815 			}
17816 		}
17817 	}
17818 	rw_exit(&ill_g_lock);
17819 
17820 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17821 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
17822 	    (int)optp->level, (int)optp->name, (int)optp->len));
17823 	qreply(q, mpctl);
17824 	return (mp2ctl);
17825 }
17826 
17827 /* IPv6 address information */
17828 static mblk_t *
17829 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
17830 {
17831 	struct opthdr		*optp;
17832 	mblk_t			*mp2ctl;
17833 	mblk_t			*mp_tail = NULL;
17834 	ill_t			*ill;
17835 	ipif_t			*ipif;
17836 	mib2_ipv6AddrEntry_t	mae6;
17837 	zoneid_t		zoneid;
17838 	ill_walk_context_t	ctx;
17839 
17840 	/*
17841 	 * make a copy of the original message
17842 	 */
17843 	mp2ctl = copymsg(mpctl);
17844 
17845 	/* ipv6AddrEntryTable */
17846 
17847 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17848 	optp->level = MIB2_IP6;
17849 	optp->name = MIB2_IP6_ADDR;
17850 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17851 
17852 	rw_enter(&ill_g_lock, RW_READER);
17853 	ill = ILL_START_WALK_V6(&ctx);
17854 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17855 		for (ipif = ill->ill_ipif; ipif != NULL;
17856 		    ipif = ipif->ipif_next) {
17857 			if (ipif->ipif_zoneid != zoneid &&
17858 			    ipif->ipif_zoneid != ALL_ZONES)
17859 				continue;
17860 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17861 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17862 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17863 
17864 			(void) ipif_get_name(ipif,
17865 			    mae6.ipv6AddrIfIndex.o_bytes,
17866 			    OCTET_LENGTH);
17867 			mae6.ipv6AddrIfIndex.o_length =
17868 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
17869 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
17870 			mae6.ipv6AddrPfxLength =
17871 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
17872 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
17873 			mae6.ipv6AddrInfo.ae_subnet_len =
17874 			    mae6.ipv6AddrPfxLength;
17875 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
17876 
17877 			/* Type: stateless(1), stateful(2), unknown(3) */
17878 			if (ipif->ipif_flags & IPIF_ADDRCONF)
17879 				mae6.ipv6AddrType = 1;
17880 			else
17881 				mae6.ipv6AddrType = 2;
17882 			/* Anycast: true(1), false(2) */
17883 			if (ipif->ipif_flags & IPIF_ANYCAST)
17884 				mae6.ipv6AddrAnycastFlag = 1;
17885 			else
17886 				mae6.ipv6AddrAnycastFlag = 2;
17887 
17888 			/*
17889 			 * Address status: preferred(1), deprecated(2),
17890 			 * invalid(3), inaccessible(4), unknown(5)
17891 			 */
17892 			if (ipif->ipif_flags & IPIF_NOLOCAL)
17893 				mae6.ipv6AddrStatus = 3;
17894 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
17895 				mae6.ipv6AddrStatus = 2;
17896 			else
17897 				mae6.ipv6AddrStatus = 1;
17898 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
17899 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
17900 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
17901 						ipif->ipif_v6pp_dst_addr;
17902 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
17903 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17904 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17905 				(char *)&mae6,
17906 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
17907 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
17908 				    "allocate %u bytes\n",
17909 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
17910 			}
17911 		}
17912 	}
17913 	rw_exit(&ill_g_lock);
17914 
17915 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17916 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
17917 	    (int)optp->level, (int)optp->name, (int)optp->len));
17918 	qreply(q, mpctl);
17919 	return (mp2ctl);
17920 }
17921 
17922 /* IPv4 multicast group membership. */
17923 static mblk_t *
17924 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
17925 {
17926 	struct opthdr		*optp;
17927 	mblk_t			*mp2ctl;
17928 	ill_t			*ill;
17929 	ipif_t			*ipif;
17930 	ilm_t			*ilm;
17931 	ip_member_t		ipm;
17932 	mblk_t			*mp_tail = NULL;
17933 	ill_walk_context_t	ctx;
17934 	zoneid_t		zoneid;
17935 
17936 	/*
17937 	 * make a copy of the original message
17938 	 */
17939 	mp2ctl = copymsg(mpctl);
17940 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17941 
17942 	/* ipGroupMember table */
17943 	optp = (struct opthdr *)&mpctl->b_rptr[
17944 	    sizeof (struct T_optmgmt_ack)];
17945 	optp->level = MIB2_IP;
17946 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
17947 
17948 	rw_enter(&ill_g_lock, RW_READER);
17949 	ill = ILL_START_WALK_V4(&ctx);
17950 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17951 		ILM_WALKER_HOLD(ill);
17952 		for (ipif = ill->ill_ipif; ipif != NULL;
17953 		    ipif = ipif->ipif_next) {
17954 			if (ipif->ipif_zoneid != zoneid &&
17955 			    ipif->ipif_zoneid != ALL_ZONES)
17956 				continue;	/* not this zone */
17957 			(void) ipif_get_name(ipif,
17958 			    ipm.ipGroupMemberIfIndex.o_bytes,
17959 			    OCTET_LENGTH);
17960 			ipm.ipGroupMemberIfIndex.o_length =
17961 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
17962 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17963 				ASSERT(ilm->ilm_ipif != NULL);
17964 				ASSERT(ilm->ilm_ill == NULL);
17965 				if (ilm->ilm_ipif != ipif)
17966 					continue;
17967 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
17968 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
17969 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
17970 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17971 				    (char *)&ipm, (int)sizeof (ipm))) {
17972 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
17973 					    "failed to allocate %u bytes\n",
17974 						(uint_t)sizeof (ipm)));
17975 				}
17976 			}
17977 		}
17978 		ILM_WALKER_RELE(ill);
17979 	}
17980 	rw_exit(&ill_g_lock);
17981 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17982 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17983 	    (int)optp->level, (int)optp->name, (int)optp->len));
17984 	qreply(q, mpctl);
17985 	return (mp2ctl);
17986 }
17987 
17988 /* IPv6 multicast group membership. */
17989 static mblk_t *
17990 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
17991 {
17992 	struct opthdr		*optp;
17993 	mblk_t			*mp2ctl;
17994 	ill_t			*ill;
17995 	ilm_t			*ilm;
17996 	ipv6_member_t		ipm6;
17997 	mblk_t			*mp_tail = NULL;
17998 	ill_walk_context_t	ctx;
17999 	zoneid_t		zoneid;
18000 
18001 	/*
18002 	 * make a copy of the original message
18003 	 */
18004 	mp2ctl = copymsg(mpctl);
18005 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18006 
18007 	/* ip6GroupMember table */
18008 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18009 	optp->level = MIB2_IP6;
18010 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18011 
18012 	rw_enter(&ill_g_lock, RW_READER);
18013 	ill = ILL_START_WALK_V6(&ctx);
18014 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18015 		ILM_WALKER_HOLD(ill);
18016 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18017 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18018 			ASSERT(ilm->ilm_ipif == NULL);
18019 			ASSERT(ilm->ilm_ill != NULL);
18020 			if (ilm->ilm_zoneid != zoneid)
18021 				continue;	/* not this zone */
18022 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18023 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18024 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18025 			if (!snmp_append_data2(mpctl->b_cont,
18026 			    &mp_tail,
18027 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18028 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18029 				    "failed to allocate %u bytes\n",
18030 				    (uint_t)sizeof (ipm6)));
18031 			}
18032 		}
18033 		ILM_WALKER_RELE(ill);
18034 	}
18035 	rw_exit(&ill_g_lock);
18036 
18037 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18038 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18039 	    (int)optp->level, (int)optp->name, (int)optp->len));
18040 	qreply(q, mpctl);
18041 	return (mp2ctl);
18042 }
18043 
18044 /* IP multicast filtered sources */
18045 static mblk_t *
18046 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
18047 {
18048 	struct opthdr		*optp;
18049 	mblk_t			*mp2ctl;
18050 	ill_t			*ill;
18051 	ipif_t			*ipif;
18052 	ilm_t			*ilm;
18053 	ip_grpsrc_t		ips;
18054 	mblk_t			*mp_tail = NULL;
18055 	ill_walk_context_t	ctx;
18056 	zoneid_t		zoneid;
18057 	int			i;
18058 	slist_t			*sl;
18059 
18060 	/*
18061 	 * make a copy of the original message
18062 	 */
18063 	mp2ctl = copymsg(mpctl);
18064 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18065 
18066 	/* ipGroupSource table */
18067 	optp = (struct opthdr *)&mpctl->b_rptr[
18068 	    sizeof (struct T_optmgmt_ack)];
18069 	optp->level = MIB2_IP;
18070 	optp->name = EXPER_IP_GROUP_SOURCES;
18071 
18072 	rw_enter(&ill_g_lock, RW_READER);
18073 	ill = ILL_START_WALK_V4(&ctx);
18074 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18075 		ILM_WALKER_HOLD(ill);
18076 		for (ipif = ill->ill_ipif; ipif != NULL;
18077 		    ipif = ipif->ipif_next) {
18078 			if (ipif->ipif_zoneid != zoneid)
18079 				continue;	/* not this zone */
18080 			(void) ipif_get_name(ipif,
18081 			    ips.ipGroupSourceIfIndex.o_bytes,
18082 			    OCTET_LENGTH);
18083 			ips.ipGroupSourceIfIndex.o_length =
18084 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18085 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18086 				ASSERT(ilm->ilm_ipif != NULL);
18087 				ASSERT(ilm->ilm_ill == NULL);
18088 				sl = ilm->ilm_filter;
18089 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18090 					continue;
18091 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18092 				for (i = 0; i < sl->sl_numsrc; i++) {
18093 					if (!IN6_IS_ADDR_V4MAPPED(
18094 					    &sl->sl_addr[i]))
18095 						continue;
18096 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18097 					    ips.ipGroupSourceAddress);
18098 					if (snmp_append_data2(mpctl->b_cont,
18099 					    &mp_tail, (char *)&ips,
18100 					    (int)sizeof (ips)) == 0) {
18101 						ip1dbg(("ip_snmp_get_mib2_"
18102 						    "ip_group_src: failed to "
18103 						    "allocate %u bytes\n",
18104 						    (uint_t)sizeof (ips)));
18105 					}
18106 				}
18107 			}
18108 		}
18109 		ILM_WALKER_RELE(ill);
18110 	}
18111 	rw_exit(&ill_g_lock);
18112 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18113 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18114 	    (int)optp->level, (int)optp->name, (int)optp->len));
18115 	qreply(q, mpctl);
18116 	return (mp2ctl);
18117 }
18118 
18119 /* IPv6 multicast filtered sources. */
18120 static mblk_t *
18121 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18122 {
18123 	struct opthdr		*optp;
18124 	mblk_t			*mp2ctl;
18125 	ill_t			*ill;
18126 	ilm_t			*ilm;
18127 	ipv6_grpsrc_t		ips6;
18128 	mblk_t			*mp_tail = NULL;
18129 	ill_walk_context_t	ctx;
18130 	zoneid_t		zoneid;
18131 	int			i;
18132 	slist_t			*sl;
18133 
18134 	/*
18135 	 * make a copy of the original message
18136 	 */
18137 	mp2ctl = copymsg(mpctl);
18138 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18139 
18140 	/* ip6GroupMember table */
18141 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18142 	optp->level = MIB2_IP6;
18143 	optp->name = EXPER_IP6_GROUP_SOURCES;
18144 
18145 	rw_enter(&ill_g_lock, RW_READER);
18146 	ill = ILL_START_WALK_V6(&ctx);
18147 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18148 		ILM_WALKER_HOLD(ill);
18149 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18150 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18151 			ASSERT(ilm->ilm_ipif == NULL);
18152 			ASSERT(ilm->ilm_ill != NULL);
18153 			sl = ilm->ilm_filter;
18154 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18155 				continue;
18156 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18157 			for (i = 0; i < sl->sl_numsrc; i++) {
18158 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18159 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18160 				    (char *)&ips6, (int)sizeof (ips6))) {
18161 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18162 					    "group_src: failed to allocate "
18163 					    "%u bytes\n",
18164 					    (uint_t)sizeof (ips6)));
18165 				}
18166 			}
18167 		}
18168 		ILM_WALKER_RELE(ill);
18169 	}
18170 	rw_exit(&ill_g_lock);
18171 
18172 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18173 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18174 	    (int)optp->level, (int)optp->name, (int)optp->len));
18175 	qreply(q, mpctl);
18176 	return (mp2ctl);
18177 }
18178 
18179 /* Multicast routing virtual interface table. */
18180 static mblk_t *
18181 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18182 {
18183 	struct opthdr		*optp;
18184 	mblk_t			*mp2ctl;
18185 
18186 	/*
18187 	 * make a copy of the original message
18188 	 */
18189 	mp2ctl = copymsg(mpctl);
18190 
18191 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18192 	optp->level = EXPER_DVMRP;
18193 	optp->name = EXPER_DVMRP_VIF;
18194 	if (!ip_mroute_vif(mpctl->b_cont)) {
18195 		ip0dbg(("ip_mroute_vif: failed\n"));
18196 	}
18197 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18198 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18199 	    (int)optp->level, (int)optp->name, (int)optp->len));
18200 	qreply(q, mpctl);
18201 	return (mp2ctl);
18202 }
18203 
18204 /* Multicast routing table. */
18205 static mblk_t *
18206 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18207 {
18208 	struct opthdr		*optp;
18209 	mblk_t			*mp2ctl;
18210 
18211 	/*
18212 	 * make a copy of the original message
18213 	 */
18214 	mp2ctl = copymsg(mpctl);
18215 
18216 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18217 	optp->level = EXPER_DVMRP;
18218 	optp->name = EXPER_DVMRP_MRT;
18219 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18220 		ip0dbg(("ip_mroute_mrt: failed\n"));
18221 	}
18222 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18223 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18224 	    (int)optp->level, (int)optp->name, (int)optp->len));
18225 	qreply(q, mpctl);
18226 	return (mp2ctl);
18227 }
18228 
18229 /*
18230  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18231  * in one IRE walk.
18232  */
18233 static mblk_t *
18234 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18235 {
18236 	struct opthdr	*optp;
18237 	mblk_t		*mp2ctl;	/* Returned */
18238 	mblk_t		*mp3ctl;	/* nettomedia */
18239 	mblk_t		*mp4ctl;	/* routeattrs */
18240 	iproutedata_t	ird;
18241 	zoneid_t	zoneid;
18242 
18243 	/*
18244 	 * make copies of the original message
18245 	 *	- mp2ctl is returned unchanged to the caller for his use
18246 	 *	- mpctl is sent upstream as ipRouteEntryTable
18247 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18248 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18249 	 */
18250 	mp2ctl = copymsg(mpctl);
18251 	mp3ctl = copymsg(mpctl);
18252 	mp4ctl = copymsg(mpctl);
18253 	if (mp3ctl == NULL || mp4ctl == NULL) {
18254 		freemsg(mp4ctl);
18255 		freemsg(mp3ctl);
18256 		freemsg(mp2ctl);
18257 		freemsg(mpctl);
18258 		return (NULL);
18259 	}
18260 
18261 	bzero(&ird, sizeof (ird));
18262 
18263 	ird.ird_route.lp_head = mpctl->b_cont;
18264 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18265 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18266 
18267 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18268 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18269 	if (zoneid == GLOBAL_ZONEID) {
18270 		/*
18271 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18272 		 * the sys_net_config privilege, it can only run in the global
18273 		 * zone, so we don't display these IREs in the other zones.
18274 		 */
18275 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18276 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18277 	}
18278 
18279 	/* ipRouteEntryTable in mpctl */
18280 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18281 	optp->level = MIB2_IP;
18282 	optp->name = MIB2_IP_ROUTE;
18283 	optp->len = msgdsize(ird.ird_route.lp_head);
18284 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18285 	    (int)optp->level, (int)optp->name, (int)optp->len));
18286 	qreply(q, mpctl);
18287 
18288 	/* ipNetToMediaEntryTable in mp3ctl */
18289 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18290 	optp->level = MIB2_IP;
18291 	optp->name = MIB2_IP_MEDIA;
18292 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18293 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18294 	    (int)optp->level, (int)optp->name, (int)optp->len));
18295 	qreply(q, mp3ctl);
18296 
18297 	/* ipRouteAttributeTable in mp4ctl */
18298 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18299 	optp->level = MIB2_IP;
18300 	optp->name = EXPER_IP_RTATTR;
18301 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18302 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18303 	    (int)optp->level, (int)optp->name, (int)optp->len));
18304 	if (optp->len == 0)
18305 		freemsg(mp4ctl);
18306 	else
18307 		qreply(q, mp4ctl);
18308 
18309 	return (mp2ctl);
18310 }
18311 
18312 /*
18313  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18314  * ipv6NetToMediaEntryTable in an NDP walk.
18315  */
18316 static mblk_t *
18317 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18318 {
18319 	struct opthdr	*optp;
18320 	mblk_t		*mp2ctl;	/* Returned */
18321 	mblk_t		*mp3ctl;	/* nettomedia */
18322 	mblk_t		*mp4ctl;	/* routeattrs */
18323 	iproutedata_t	ird;
18324 	zoneid_t	zoneid;
18325 
18326 	/*
18327 	 * make copies of the original message
18328 	 *	- mp2ctl is returned unchanged to the caller for his use
18329 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18330 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18331 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18332 	 */
18333 	mp2ctl = copymsg(mpctl);
18334 	mp3ctl = copymsg(mpctl);
18335 	mp4ctl = copymsg(mpctl);
18336 	if (mp3ctl == NULL || mp4ctl == NULL) {
18337 		freemsg(mp4ctl);
18338 		freemsg(mp3ctl);
18339 		freemsg(mp2ctl);
18340 		freemsg(mpctl);
18341 		return (NULL);
18342 	}
18343 
18344 	bzero(&ird, sizeof (ird));
18345 
18346 	ird.ird_route.lp_head = mpctl->b_cont;
18347 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18348 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18349 
18350 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18351 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18352 
18353 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18354 	optp->level = MIB2_IP6;
18355 	optp->name = MIB2_IP6_ROUTE;
18356 	optp->len = msgdsize(ird.ird_route.lp_head);
18357 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18358 	    (int)optp->level, (int)optp->name, (int)optp->len));
18359 	qreply(q, mpctl);
18360 
18361 	/* ipv6NetToMediaEntryTable in mp3ctl */
18362 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18363 
18364 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18365 	optp->level = MIB2_IP6;
18366 	optp->name = MIB2_IP6_MEDIA;
18367 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18368 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18369 	    (int)optp->level, (int)optp->name, (int)optp->len));
18370 	qreply(q, mp3ctl);
18371 
18372 	/* ipv6RouteAttributeTable in mp4ctl */
18373 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18374 	optp->level = MIB2_IP6;
18375 	optp->name = EXPER_IP_RTATTR;
18376 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18377 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18378 	    (int)optp->level, (int)optp->name, (int)optp->len));
18379 	if (optp->len == 0)
18380 		freemsg(mp4ctl);
18381 	else
18382 		qreply(q, mp4ctl);
18383 
18384 	return (mp2ctl);
18385 }
18386 
18387 /*
18388  * ICMPv6 mib: One per ill
18389  */
18390 static mblk_t *
18391 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18392 {
18393 	struct opthdr		*optp;
18394 	mblk_t			*mp2ctl;
18395 	ill_t			*ill;
18396 	ill_walk_context_t	ctx;
18397 	mblk_t			*mp_tail = NULL;
18398 
18399 	/*
18400 	 * Make a copy of the original message
18401 	 */
18402 	mp2ctl = copymsg(mpctl);
18403 
18404 	/* fixed length IPv6 structure ... */
18405 
18406 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18407 	optp->level = MIB2_IP6;
18408 	optp->name = 0;
18409 	/* Include "unknown interface" ip6_mib */
18410 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
18411 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
18412 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
18413 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
18414 	    sizeof (mib2_ipv6IfStatsEntry_t));
18415 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18416 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
18417 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
18418 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18419 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
18420 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18421 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18422 	    (int)sizeof (ip6_mib))) {
18423 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18424 		    (uint_t)sizeof (ip6_mib)));
18425 	}
18426 
18427 	rw_enter(&ill_g_lock, RW_READER);
18428 	ill = ILL_START_WALK_V6(&ctx);
18429 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18430 		ill->ill_ip6_mib->ipv6IfIndex =
18431 		    ill->ill_phyint->phyint_ifindex;
18432 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
18433 		    ipv6_forward ? 1 : 2);
18434 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
18435 		    ill->ill_max_hops);
18436 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
18437 		    sizeof (mib2_ipv6IfStatsEntry_t));
18438 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
18439 		    sizeof (mib2_ipv6AddrEntry_t));
18440 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
18441 		    sizeof (mib2_ipv6RouteEntry_t));
18442 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
18443 		    sizeof (mib2_ipv6NetToMediaEntry_t));
18444 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
18445 		    sizeof (ipv6_member_t));
18446 
18447 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18448 		    (char *)ill->ill_ip6_mib,
18449 		    (int)sizeof (*ill->ill_ip6_mib))) {
18450 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18451 				"%u bytes\n",
18452 				(uint_t)sizeof (*ill->ill_ip6_mib)));
18453 		}
18454 	}
18455 	rw_exit(&ill_g_lock);
18456 
18457 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18458 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18459 	    (int)optp->level, (int)optp->name, (int)optp->len));
18460 	qreply(q, mpctl);
18461 	return (mp2ctl);
18462 }
18463 
18464 /*
18465  * ICMPv6 mib: One per ill
18466  */
18467 static mblk_t *
18468 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18469 {
18470 	struct opthdr		*optp;
18471 	mblk_t			*mp2ctl;
18472 	ill_t			*ill;
18473 	ill_walk_context_t	ctx;
18474 	mblk_t			*mp_tail = NULL;
18475 	/*
18476 	 * Make a copy of the original message
18477 	 */
18478 	mp2ctl = copymsg(mpctl);
18479 
18480 	/* fixed length ICMPv6 structure ... */
18481 
18482 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18483 	optp->level = MIB2_ICMP6;
18484 	optp->name = 0;
18485 	/* Include "unknown interface" icmp6_mib */
18486 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
18487 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18488 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18489 	    (int)sizeof (icmp6_mib))) {
18490 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18491 		    (uint_t)sizeof (icmp6_mib)));
18492 	}
18493 
18494 	rw_enter(&ill_g_lock, RW_READER);
18495 	ill = ILL_START_WALK_V6(&ctx);
18496 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18497 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18498 		    ill->ill_phyint->phyint_ifindex;
18499 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
18500 		    sizeof (mib2_ipv6IfIcmpEntry_t);
18501 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18502 		    (char *)ill->ill_icmp6_mib,
18503 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18504 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18505 			    "%u bytes\n",
18506 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18507 		}
18508 	}
18509 	rw_exit(&ill_g_lock);
18510 
18511 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18512 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18513 	    (int)optp->level, (int)optp->name, (int)optp->len));
18514 	qreply(q, mpctl);
18515 	return (mp2ctl);
18516 }
18517 
18518 /*
18519  * ire_walk routine to create both ipRouteEntryTable and
18520  * ipNetToMediaEntryTable in one IRE walk
18521  */
18522 static void
18523 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18524 {
18525 	ill_t				*ill;
18526 	ipif_t				*ipif;
18527 	mblk_t				*llmp;
18528 	dl_unitdata_req_t		*dlup;
18529 	mib2_ipRouteEntry_t		*re;
18530 	mib2_ipNetToMediaEntry_t	ntme;
18531 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18532 	ipaddr_t			gw_addr;
18533 	tsol_ire_gw_secattr_t		*attrp;
18534 	tsol_gc_t			*gc = NULL;
18535 	tsol_gcgrp_t			*gcgrp = NULL;
18536 	uint_t				sacnt = 0;
18537 	int				i;
18538 
18539 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18540 
18541 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18542 		return;
18543 
18544 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18545 		mutex_enter(&attrp->igsa_lock);
18546 		if ((gc = attrp->igsa_gc) != NULL) {
18547 			gcgrp = gc->gc_grp;
18548 			ASSERT(gcgrp != NULL);
18549 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18550 			sacnt = 1;
18551 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18552 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18553 			gc = gcgrp->gcgrp_head;
18554 			sacnt = gcgrp->gcgrp_count;
18555 		}
18556 		mutex_exit(&attrp->igsa_lock);
18557 
18558 		/* do nothing if there's no gc to report */
18559 		if (gc == NULL) {
18560 			ASSERT(sacnt == 0);
18561 			if (gcgrp != NULL) {
18562 				/* we might as well drop the lock now */
18563 				rw_exit(&gcgrp->gcgrp_rwlock);
18564 				gcgrp = NULL;
18565 			}
18566 			attrp = NULL;
18567 		}
18568 
18569 		ASSERT(gc == NULL || (gcgrp != NULL &&
18570 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18571 	}
18572 	ASSERT(sacnt == 0 || gc != NULL);
18573 
18574 	if (sacnt != 0 &&
18575 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18576 		kmem_free(re, sizeof (*re));
18577 		rw_exit(&gcgrp->gcgrp_rwlock);
18578 		return;
18579 	}
18580 
18581 	/*
18582 	 * Return all IRE types for route table... let caller pick and choose
18583 	 */
18584 	re->ipRouteDest = ire->ire_addr;
18585 	ipif = ire->ire_ipif;
18586 	re->ipRouteIfIndex.o_length = 0;
18587 	if (ire->ire_type == IRE_CACHE) {
18588 		ill = (ill_t *)ire->ire_stq->q_ptr;
18589 		re->ipRouteIfIndex.o_length =
18590 		    ill->ill_name_length == 0 ? 0 :
18591 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18592 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18593 		    re->ipRouteIfIndex.o_length);
18594 	} else if (ipif != NULL) {
18595 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18596 		    OCTET_LENGTH);
18597 		re->ipRouteIfIndex.o_length =
18598 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18599 	}
18600 	re->ipRouteMetric1 = -1;
18601 	re->ipRouteMetric2 = -1;
18602 	re->ipRouteMetric3 = -1;
18603 	re->ipRouteMetric4 = -1;
18604 
18605 	gw_addr = ire->ire_gateway_addr;
18606 
18607 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18608 		re->ipRouteNextHop = ire->ire_src_addr;
18609 	else
18610 		re->ipRouteNextHop = gw_addr;
18611 	/* indirect(4), direct(3), or invalid(2) */
18612 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18613 		re->ipRouteType = 2;
18614 	else
18615 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18616 	re->ipRouteProto = -1;
18617 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18618 	re->ipRouteMask = ire->ire_mask;
18619 	re->ipRouteMetric5 = -1;
18620 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
18621 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
18622 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
18623 	if (ire->ire_nce &&
18624 	    ire->ire_nce->nce_state == ND_REACHABLE)
18625 		llmp = ire->ire_nce->nce_res_mp;
18626 	else
18627 		llmp = NULL;
18628 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
18629 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
18630 	re->ipRouteInfo.re_ire_type	= ire->ire_type;
18631 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18632 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18633 	re->ipRouteInfo.re_flags	= ire->ire_flags;
18634 	re->ipRouteInfo.re_in_ill.o_length = 0;
18635 	if (ire->ire_in_ill != NULL) {
18636 		re->ipRouteInfo.re_in_ill.o_length =
18637 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
18638 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
18639 		bcopy(ire->ire_in_ill->ill_name,
18640 		    re->ipRouteInfo.re_in_ill.o_bytes,
18641 		    re->ipRouteInfo.re_in_ill.o_length);
18642 	}
18643 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
18644 
18645 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18646 	    (char *)re, (int)sizeof (*re))) {
18647 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18648 		    (uint_t)sizeof (*re)));
18649 	}
18650 
18651 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18652 		iaeptr->iae_routeidx = ird->ird_idx;
18653 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18654 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18655 	}
18656 
18657 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18658 	    (char *)iae, sacnt * sizeof (*iae))) {
18659 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18660 		    (unsigned)(sacnt * sizeof (*iae))));
18661 	}
18662 
18663 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
18664 		goto done;
18665 	/*
18666 	 * only IRE_CACHE entries that are for a directly connected subnet
18667 	 * get appended to net -> phys addr table
18668 	 * (others in arp)
18669 	 */
18670 	ntme.ipNetToMediaIfIndex.o_length = 0;
18671 	ill = ire_to_ill(ire);
18672 	ASSERT(ill != NULL);
18673 	ntme.ipNetToMediaIfIndex.o_length =
18674 	    ill->ill_name_length == 0 ? 0 :
18675 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18676 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
18677 		    ntme.ipNetToMediaIfIndex.o_length);
18678 
18679 	ntme.ipNetToMediaPhysAddress.o_length = 0;
18680 	if (llmp) {
18681 		uchar_t *addr;
18682 
18683 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
18684 		/* Remove sap from  address */
18685 		if (ill->ill_sap_length < 0)
18686 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
18687 		else
18688 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
18689 			    ill->ill_sap_length;
18690 
18691 		ntme.ipNetToMediaPhysAddress.o_length =
18692 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18693 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18694 		    ntme.ipNetToMediaPhysAddress.o_length);
18695 	}
18696 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18697 	/* assume dynamic (may be changed in arp) */
18698 	ntme.ipNetToMediaType = 3;
18699 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18700 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18701 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18702 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18703 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18704 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18705 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18706 		    (uint_t)sizeof (ntme)));
18707 	}
18708 done:
18709 	/* bump route index for next pass */
18710 	ird->ird_idx++;
18711 
18712 	kmem_free(re, sizeof (*re));
18713 	if (sacnt != 0)
18714 		kmem_free(iae, sacnt * sizeof (*iae));
18715 
18716 	if (gcgrp != NULL)
18717 		rw_exit(&gcgrp->gcgrp_rwlock);
18718 }
18719 
18720 /*
18721  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18722  */
18723 static void
18724 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18725 {
18726 	ill_t				*ill;
18727 	ipif_t				*ipif;
18728 	mib2_ipv6RouteEntry_t		*re;
18729 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18730 	in6_addr_t			gw_addr_v6;
18731 	tsol_ire_gw_secattr_t		*attrp;
18732 	tsol_gc_t			*gc = NULL;
18733 	tsol_gcgrp_t			*gcgrp = NULL;
18734 	uint_t				sacnt = 0;
18735 	int				i;
18736 
18737 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18738 
18739 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18740 		return;
18741 
18742 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18743 		mutex_enter(&attrp->igsa_lock);
18744 		if ((gc = attrp->igsa_gc) != NULL) {
18745 			gcgrp = gc->gc_grp;
18746 			ASSERT(gcgrp != NULL);
18747 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18748 			sacnt = 1;
18749 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18750 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18751 			gc = gcgrp->gcgrp_head;
18752 			sacnt = gcgrp->gcgrp_count;
18753 		}
18754 		mutex_exit(&attrp->igsa_lock);
18755 
18756 		/* do nothing if there's no gc to report */
18757 		if (gc == NULL) {
18758 			ASSERT(sacnt == 0);
18759 			if (gcgrp != NULL) {
18760 				/* we might as well drop the lock now */
18761 				rw_exit(&gcgrp->gcgrp_rwlock);
18762 				gcgrp = NULL;
18763 			}
18764 			attrp = NULL;
18765 		}
18766 
18767 		ASSERT(gc == NULL || (gcgrp != NULL &&
18768 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18769 	}
18770 	ASSERT(sacnt == 0 || gc != NULL);
18771 
18772 	if (sacnt != 0 &&
18773 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18774 		kmem_free(re, sizeof (*re));
18775 		rw_exit(&gcgrp->gcgrp_rwlock);
18776 		return;
18777 	}
18778 
18779 	/*
18780 	 * Return all IRE types for route table... let caller pick and choose
18781 	 */
18782 	re->ipv6RouteDest = ire->ire_addr_v6;
18783 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18784 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18785 	re->ipv6RouteIfIndex.o_length = 0;
18786 	ipif = ire->ire_ipif;
18787 	if (ire->ire_type == IRE_CACHE) {
18788 		ill = (ill_t *)ire->ire_stq->q_ptr;
18789 		re->ipv6RouteIfIndex.o_length =
18790 		    ill->ill_name_length == 0 ? 0 :
18791 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18792 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
18793 		    re->ipv6RouteIfIndex.o_length);
18794 	} else if (ipif != NULL) {
18795 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
18796 		    OCTET_LENGTH);
18797 		re->ipv6RouteIfIndex.o_length =
18798 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
18799 	}
18800 
18801 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18802 
18803 	mutex_enter(&ire->ire_lock);
18804 	gw_addr_v6 = ire->ire_gateway_addr_v6;
18805 	mutex_exit(&ire->ire_lock);
18806 
18807 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
18808 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
18809 	else
18810 		re->ipv6RouteNextHop = gw_addr_v6;
18811 
18812 	/* remote(4), local(3), or discard(2) */
18813 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18814 		re->ipv6RouteType = 2;
18815 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
18816 		re->ipv6RouteType = 3;
18817 	else
18818 		re->ipv6RouteType = 4;
18819 
18820 	re->ipv6RouteProtocol	= -1;
18821 	re->ipv6RoutePolicy	= 0;
18822 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
18823 	re->ipv6RouteNextHopRDI	= 0;
18824 	re->ipv6RouteWeight	= 0;
18825 	re->ipv6RouteMetric	= 0;
18826 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
18827 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
18828 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
18829 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
18830 	re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
18831 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18832 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18833 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
18834 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
18835 
18836 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18837 	    (char *)re, (int)sizeof (*re))) {
18838 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18839 		    (uint_t)sizeof (*re)));
18840 	}
18841 
18842 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18843 		iaeptr->iae_routeidx = ird->ird_idx;
18844 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18845 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18846 	}
18847 
18848 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18849 	    (char *)iae, sacnt * sizeof (*iae))) {
18850 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18851 		    (unsigned)(sacnt * sizeof (*iae))));
18852 	}
18853 
18854 	/* bump route index for next pass */
18855 	ird->ird_idx++;
18856 
18857 	kmem_free(re, sizeof (*re));
18858 	if (sacnt != 0)
18859 		kmem_free(iae, sacnt * sizeof (*iae));
18860 
18861 	if (gcgrp != NULL)
18862 		rw_exit(&gcgrp->gcgrp_rwlock);
18863 }
18864 
18865 /*
18866  * ndp_walk routine to create ipv6NetToMediaEntryTable
18867  */
18868 static int
18869 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
18870 {
18871 	ill_t				*ill;
18872 	mib2_ipv6NetToMediaEntry_t	ntme;
18873 	dl_unitdata_req_t		*dl;
18874 
18875 	ill = nce->nce_ill;
18876 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
18877 		return (0);
18878 
18879 	/*
18880 	 * Neighbor cache entry attached to IRE with on-link
18881 	 * destination.
18882 	 */
18883 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
18884 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
18885 	if ((ill->ill_flags & ILLF_XRESOLV) &&
18886 	    (nce->nce_res_mp != NULL)) {
18887 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
18888 		ntme.ipv6NetToMediaPhysAddress.o_length =
18889 		    dl->dl_dest_addr_length;
18890 	} else {
18891 		ntme.ipv6NetToMediaPhysAddress.o_length =
18892 		    ill->ill_phys_addr_length;
18893 	}
18894 	if (nce->nce_res_mp != NULL) {
18895 		bcopy((char *)nce->nce_res_mp->b_rptr +
18896 		    NCE_LL_ADDR_OFFSET(ill),
18897 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
18898 		    ntme.ipv6NetToMediaPhysAddress.o_length);
18899 	} else {
18900 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
18901 		    ill->ill_phys_addr_length);
18902 	}
18903 	/*
18904 	 * Note: Returns ND_* states. Should be:
18905 	 * reachable(1), stale(2), delay(3), probe(4),
18906 	 * invalid(5), unknown(6)
18907 	 */
18908 	ntme.ipv6NetToMediaState = nce->nce_state;
18909 	ntme.ipv6NetToMediaLastUpdated = 0;
18910 
18911 	/* other(1), dynamic(2), static(3), local(4) */
18912 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
18913 		ntme.ipv6NetToMediaType = 4;
18914 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
18915 		ntme.ipv6NetToMediaType = 1;
18916 	} else {
18917 		ntme.ipv6NetToMediaType = 2;
18918 	}
18919 
18920 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18921 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18922 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
18923 		    (uint_t)sizeof (ntme)));
18924 	}
18925 	return (0);
18926 }
18927 
18928 /*
18929  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
18930  */
18931 /* ARGSUSED */
18932 int
18933 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
18934 {
18935 	switch (level) {
18936 	case MIB2_IP:
18937 	case MIB2_ICMP:
18938 		switch (name) {
18939 		default:
18940 			break;
18941 		}
18942 		return (1);
18943 	default:
18944 		return (1);
18945 	}
18946 }
18947 
18948 /*
18949  * Called before the options are updated to check if this packet will
18950  * be source routed from here.
18951  * This routine assumes that the options are well formed i.e. that they
18952  * have already been checked.
18953  */
18954 static boolean_t
18955 ip_source_routed(ipha_t *ipha)
18956 {
18957 	ipoptp_t	opts;
18958 	uchar_t		*opt;
18959 	uint8_t		optval;
18960 	uint8_t		optlen;
18961 	ipaddr_t	dst;
18962 	ire_t		*ire;
18963 
18964 	if (IS_SIMPLE_IPH(ipha)) {
18965 		ip2dbg(("not source routed\n"));
18966 		return (B_FALSE);
18967 	}
18968 	dst = ipha->ipha_dst;
18969 	for (optval = ipoptp_first(&opts, ipha);
18970 	    optval != IPOPT_EOL;
18971 	    optval = ipoptp_next(&opts)) {
18972 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18973 		opt = opts.ipoptp_cur;
18974 		optlen = opts.ipoptp_len;
18975 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
18976 		    optval, optlen));
18977 		switch (optval) {
18978 			uint32_t off;
18979 		case IPOPT_SSRR:
18980 		case IPOPT_LSRR:
18981 			/*
18982 			 * If dst is one of our addresses and there are some
18983 			 * entries left in the source route return (true).
18984 			 */
18985 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18986 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
18987 			if (ire == NULL) {
18988 				ip2dbg(("ip_source_routed: not next"
18989 				    " source route 0x%x\n",
18990 				    ntohl(dst)));
18991 				return (B_FALSE);
18992 			}
18993 			ire_refrele(ire);
18994 			off = opt[IPOPT_OFFSET];
18995 			off--;
18996 			if (optlen < IP_ADDR_LEN ||
18997 			    off > optlen - IP_ADDR_LEN) {
18998 				/* End of source route */
18999 				ip1dbg(("ip_source_routed: end of SR\n"));
19000 				return (B_FALSE);
19001 			}
19002 			return (B_TRUE);
19003 		}
19004 	}
19005 	ip2dbg(("not source routed\n"));
19006 	return (B_FALSE);
19007 }
19008 
19009 /*
19010  * Check if the packet contains any source route.
19011  */
19012 static boolean_t
19013 ip_source_route_included(ipha_t *ipha)
19014 {
19015 	ipoptp_t	opts;
19016 	uint8_t		optval;
19017 
19018 	if (IS_SIMPLE_IPH(ipha))
19019 		return (B_FALSE);
19020 	for (optval = ipoptp_first(&opts, ipha);
19021 	    optval != IPOPT_EOL;
19022 	    optval = ipoptp_next(&opts)) {
19023 		switch (optval) {
19024 		case IPOPT_SSRR:
19025 		case IPOPT_LSRR:
19026 			return (B_TRUE);
19027 		}
19028 	}
19029 	return (B_FALSE);
19030 }
19031 
19032 /*
19033  * Called when the IRE expiration timer fires.
19034  */
19035 /* ARGSUSED */
19036 void
19037 ip_trash_timer_expire(void *args)
19038 {
19039 	int	flush_flag = 0;
19040 
19041 	/*
19042 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19043 	 * This lock makes sure that a new invocation of this function
19044 	 * that occurs due to an almost immediate timer firing will not
19045 	 * progress beyond this point until the current invocation is done
19046 	 */
19047 	mutex_enter(&ip_trash_timer_lock);
19048 	ip_ire_expire_id = 0;
19049 	mutex_exit(&ip_trash_timer_lock);
19050 
19051 	/* Periodic timer */
19052 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
19053 		/*
19054 		 * Remove all IRE_CACHE entries since they might
19055 		 * contain arp information.
19056 		 */
19057 		flush_flag |= FLUSH_ARP_TIME;
19058 		ip_ire_arp_time_elapsed = 0;
19059 		IP_STAT(ip_ire_arp_timer_expired);
19060 	}
19061 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
19062 		/* Remove all redirects */
19063 		flush_flag |= FLUSH_REDIRECT_TIME;
19064 		ip_ire_rd_time_elapsed = 0;
19065 		IP_STAT(ip_ire_redirect_timer_expired);
19066 	}
19067 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
19068 		/* Increase path mtu */
19069 		flush_flag |= FLUSH_MTU_TIME;
19070 		ip_ire_pmtu_time_elapsed = 0;
19071 		IP_STAT(ip_ire_pmtu_timer_expired);
19072 	}
19073 
19074 	/*
19075 	 * Optimize for the case when there are no redirects in the
19076 	 * ftable, that is, no need to walk the ftable in that case.
19077 	 */
19078 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19079 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19080 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
19081 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
19082 	}
19083 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
19084 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19085 		    ire_expire, (char *)(uintptr_t)flush_flag,
19086 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
19087 	}
19088 	if (flush_flag & FLUSH_MTU_TIME) {
19089 		/*
19090 		 * Walk all IPv6 IRE's and update them
19091 		 * Note that ARP and redirect timers are not
19092 		 * needed since NUD handles stale entries.
19093 		 */
19094 		flush_flag = FLUSH_MTU_TIME;
19095 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
19096 		    ALL_ZONES);
19097 	}
19098 
19099 	ip_ire_arp_time_elapsed += ip_timer_interval;
19100 	ip_ire_rd_time_elapsed += ip_timer_interval;
19101 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19102 
19103 	/*
19104 	 * Hold the lock to serialize timeout calls and prevent
19105 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19106 	 * for the timer to fire and a new invocation of this function
19107 	 * to start before the return value of timeout has been stored
19108 	 * in ip_ire_expire_id by the current invocation.
19109 	 */
19110 	mutex_enter(&ip_trash_timer_lock);
19111 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19112 	    MSEC_TO_TICK(ip_timer_interval));
19113 	mutex_exit(&ip_trash_timer_lock);
19114 }
19115 
19116 /*
19117  * Called by the memory allocator subsystem directly, when the system
19118  * is running low on memory.
19119  */
19120 /* ARGSUSED */
19121 void
19122 ip_trash_ire_reclaim(void *args)
19123 {
19124 	ire_cache_count_t icc;
19125 	ire_cache_reclaim_t icr;
19126 	ncc_cache_count_t ncc;
19127 	nce_cache_reclaim_t ncr;
19128 	uint_t delete_cnt;
19129 	/*
19130 	 * Memory reclaim call back.
19131 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19132 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19133 	 * entries, determine what fraction to free for
19134 	 * each category of IRE_CACHE entries giving absolute priority
19135 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19136 	 * entry will be freed unless all offlink entries are freed).
19137 	 */
19138 	icc.icc_total = 0;
19139 	icc.icc_unused = 0;
19140 	icc.icc_offlink = 0;
19141 	icc.icc_pmtu = 0;
19142 	icc.icc_onlink = 0;
19143 	ire_walk(ire_cache_count, (char *)&icc);
19144 
19145 	/*
19146 	 * Free NCEs for IPv6 like the onlink ires.
19147 	 */
19148 	ncc.ncc_total = 0;
19149 	ncc.ncc_host = 0;
19150 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19151 
19152 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19153 	    icc.icc_pmtu + icc.icc_onlink);
19154 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19155 	IP_STAT(ip_trash_ire_reclaim_calls);
19156 	if (delete_cnt == 0)
19157 		return;
19158 	IP_STAT(ip_trash_ire_reclaim_success);
19159 	/* Always delete all unused offlink entries */
19160 	icr.icr_unused = 1;
19161 	if (delete_cnt <= icc.icc_unused) {
19162 		/*
19163 		 * Only need to free unused entries.  In other words,
19164 		 * there are enough unused entries to free to meet our
19165 		 * target number of freed ire cache entries.
19166 		 */
19167 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19168 		ncr.ncr_host = 0;
19169 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19170 		/*
19171 		 * Only need to free unused entries, plus a fraction of offlink
19172 		 * entries.  It follows from the first if statement that
19173 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19174 		 */
19175 		delete_cnt -= icc.icc_unused;
19176 		/* Round up # deleted by truncating fraction */
19177 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19178 		icr.icr_pmtu = icr.icr_onlink = 0;
19179 		ncr.ncr_host = 0;
19180 	} else if (delete_cnt <=
19181 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19182 		/*
19183 		 * Free all unused and offlink entries, plus a fraction of
19184 		 * pmtu entries.  It follows from the previous if statement
19185 		 * that icc_pmtu is non-zero, and that
19186 		 * delete_cnt != icc_unused + icc_offlink.
19187 		 */
19188 		icr.icr_offlink = 1;
19189 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19190 		/* Round up # deleted by truncating fraction */
19191 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19192 		icr.icr_onlink = 0;
19193 		ncr.ncr_host = 0;
19194 	} else {
19195 		/*
19196 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19197 		 * of onlink entries.  If we're here, then we know that
19198 		 * icc_onlink is non-zero, and that
19199 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19200 		 */
19201 		icr.icr_offlink = icr.icr_pmtu = 1;
19202 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19203 		    icc.icc_pmtu;
19204 		/* Round up # deleted by truncating fraction */
19205 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19206 		/* Using the same delete fraction as for onlink IREs */
19207 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19208 	}
19209 #ifdef DEBUG
19210 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19211 	    "fractions %d/%d/%d/%d\n",
19212 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19213 	    icc.icc_unused, icc.icc_offlink,
19214 	    icc.icc_pmtu, icc.icc_onlink,
19215 	    icr.icr_unused, icr.icr_offlink,
19216 	    icr.icr_pmtu, icr.icr_onlink));
19217 #endif
19218 	ire_walk(ire_cache_reclaim, (char *)&icr);
19219 	if (ncr.ncr_host != 0)
19220 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19221 		    (uchar_t *)&ncr);
19222 #ifdef DEBUG
19223 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19224 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19225 	ire_walk(ire_cache_count, (char *)&icc);
19226 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19227 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19228 	    icc.icc_pmtu, icc.icc_onlink));
19229 #endif
19230 }
19231 
19232 /*
19233  * ip_unbind is called when a copy of an unbind request is received from the
19234  * upper level protocol.  We remove this conn from any fanout hash list it is
19235  * on, and zero out the bind information.  No reply is expected up above.
19236  */
19237 mblk_t *
19238 ip_unbind(queue_t *q, mblk_t *mp)
19239 {
19240 	conn_t	*connp = Q_TO_CONN(q);
19241 
19242 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19243 
19244 	if (is_system_labeled() && connp->conn_anon_port) {
19245 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19246 		    connp->conn_mlp_type, connp->conn_ulp,
19247 		    ntohs(connp->conn_lport), B_FALSE);
19248 		connp->conn_anon_port = 0;
19249 	}
19250 	connp->conn_mlp_type = mlptSingle;
19251 
19252 	ipcl_hash_remove(connp);
19253 
19254 	ASSERT(mp->b_cont == NULL);
19255 	/*
19256 	 * Convert mp into a T_OK_ACK
19257 	 */
19258 	mp = mi_tpi_ok_ack_alloc(mp);
19259 
19260 	/*
19261 	 * should not happen in practice... T_OK_ACK is smaller than the
19262 	 * original message.
19263 	 */
19264 	if (mp == NULL)
19265 		return (NULL);
19266 
19267 	/*
19268 	 * Don't bzero the ports if its TCP since TCP still needs the
19269 	 * lport to remove it from its own bind hash. TCP will do the
19270 	 * cleanup.
19271 	 */
19272 	if (!IPCL_IS_TCP(connp))
19273 		bzero(&connp->u_port, sizeof (connp->u_port));
19274 
19275 	return (mp);
19276 }
19277 
19278 /*
19279  * Write side put procedure.  Outbound data, IOCTLs, responses from
19280  * resolvers, etc, come down through here.
19281  *
19282  * arg2 is always a queue_t *.
19283  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19284  * the zoneid.
19285  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19286  */
19287 void
19288 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19289 {
19290 	conn_t		*connp = NULL;
19291 	queue_t		*q = (queue_t *)arg2;
19292 	ipha_t		*ipha;
19293 #define	rptr	((uchar_t *)ipha)
19294 	ire_t		*ire = NULL;
19295 	ire_t		*sctp_ire = NULL;
19296 	uint32_t	v_hlen_tos_len;
19297 	ipaddr_t	dst;
19298 	mblk_t		*first_mp = NULL;
19299 	boolean_t	mctl_present;
19300 	ipsec_out_t	*io;
19301 	int		match_flags;
19302 	ill_t		*attach_ill = NULL;
19303 					/* Bind to IPIF_NOFAILOVER ill etc. */
19304 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19305 	ipif_t		*dst_ipif;
19306 	boolean_t	multirt_need_resolve = B_FALSE;
19307 	mblk_t		*copy_mp = NULL;
19308 	int		err;
19309 	zoneid_t	zoneid;
19310 	int	adjust;
19311 	uint16_t iplen;
19312 	boolean_t	need_decref = B_FALSE;
19313 	boolean_t	ignore_dontroute = B_FALSE;
19314 	boolean_t	ignore_nexthop = B_FALSE;
19315 	boolean_t	ip_nexthop = B_FALSE;
19316 	ipaddr_t	nexthop_addr;
19317 
19318 #ifdef	_BIG_ENDIAN
19319 #define	V_HLEN	(v_hlen_tos_len >> 24)
19320 #else
19321 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19322 #endif
19323 
19324 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19325 	    "ip_wput_start: q %p", q);
19326 
19327 	/*
19328 	 * ip_wput fast path
19329 	 */
19330 
19331 	/* is packet from ARP ? */
19332 	if (q->q_next != NULL) {
19333 		zoneid = (zoneid_t)(uintptr_t)arg;
19334 		goto qnext;
19335 	}
19336 
19337 	connp = (conn_t *)arg;
19338 	ASSERT(connp != NULL);
19339 	zoneid = connp->conn_zoneid;
19340 
19341 	/* is queue flow controlled? */
19342 	if ((q->q_first != NULL || connp->conn_draining) &&
19343 	    (caller == IP_WPUT)) {
19344 		ASSERT(!need_decref);
19345 		(void) putq(q, mp);
19346 		return;
19347 	}
19348 
19349 	/* Multidata transmit? */
19350 	if (DB_TYPE(mp) == M_MULTIDATA) {
19351 		/*
19352 		 * We should never get here, since all Multidata messages
19353 		 * originating from tcp should have been directed over to
19354 		 * tcp_multisend() in the first place.
19355 		 */
19356 		BUMP_MIB(&ip_mib, ipOutDiscards);
19357 		freemsg(mp);
19358 		return;
19359 	} else if (DB_TYPE(mp) != M_DATA)
19360 		goto notdata;
19361 
19362 	if (mp->b_flag & MSGHASREF) {
19363 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19364 		mp->b_flag &= ~MSGHASREF;
19365 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19366 		need_decref = B_TRUE;
19367 	}
19368 	ipha = (ipha_t *)mp->b_rptr;
19369 
19370 	/* is IP header non-aligned or mblk smaller than basic IP header */
19371 #ifndef SAFETY_BEFORE_SPEED
19372 	if (!OK_32PTR(rptr) ||
19373 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19374 		goto hdrtoosmall;
19375 #endif
19376 
19377 	ASSERT(OK_32PTR(ipha));
19378 
19379 	/*
19380 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19381 	 * wrong version, we'll catch it again in ip_output_v6.
19382 	 *
19383 	 * Note that this is *only* locally-generated output here, and never
19384 	 * forwarded data, and that we need to deal only with transports that
19385 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19386 	 * label.)
19387 	 */
19388 	if (is_system_labeled() &&
19389 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19390 	    !connp->conn_ulp_labeled) {
19391 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19392 		    connp->conn_mac_exempt);
19393 		ipha = (ipha_t *)mp->b_rptr;
19394 		if (err != 0) {
19395 			first_mp = mp;
19396 			if (err == EINVAL)
19397 				goto icmp_parameter_problem;
19398 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19399 			goto drop_pkt;
19400 		}
19401 		iplen = ntohs(ipha->ipha_length) + adjust;
19402 		ipha->ipha_length = htons(iplen);
19403 	}
19404 
19405 	/*
19406 	 * If there is a policy, try to attach an ipsec_out in
19407 	 * the front. At the end, first_mp either points to a
19408 	 * M_DATA message or IPSEC_OUT message linked to a
19409 	 * M_DATA message. We have to do it now as we might
19410 	 * lose the "conn" if we go through ip_newroute.
19411 	 */
19412 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19413 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
19414 		    ipha->ipha_protocol)) == NULL)) {
19415 			if (need_decref)
19416 				CONN_DEC_REF(connp);
19417 			return;
19418 		} else {
19419 			ASSERT(mp->b_datap->db_type == M_CTL);
19420 			first_mp = mp;
19421 			mp = mp->b_cont;
19422 			mctl_present = B_TRUE;
19423 		}
19424 	} else {
19425 		first_mp = mp;
19426 		mctl_present = B_FALSE;
19427 	}
19428 
19429 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19430 
19431 	/* is wrong version or IP options present */
19432 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19433 		goto version_hdrlen_check;
19434 	dst = ipha->ipha_dst;
19435 
19436 	if (connp->conn_nofailover_ill != NULL) {
19437 		attach_ill = conn_get_held_ill(connp,
19438 		    &connp->conn_nofailover_ill, &err);
19439 		if (err == ILL_LOOKUP_FAILED) {
19440 			if (need_decref)
19441 				CONN_DEC_REF(connp);
19442 			freemsg(first_mp);
19443 			return;
19444 		}
19445 	}
19446 
19447 	/* is packet multicast? */
19448 	if (CLASSD(dst))
19449 		goto multicast;
19450 
19451 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19452 	    (connp->conn_nexthop_set)) {
19453 		/*
19454 		 * If the destination is a broadcast or a loopback
19455 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
19456 		 * through the standard path. But in the case of local
19457 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
19458 		 * the standard path not IP_XMIT_IF.
19459 		 */
19460 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19461 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
19462 		    (ire->ire_type != IRE_LOOPBACK))) {
19463 			if ((connp->conn_dontroute ||
19464 			    connp->conn_nexthop_set) && (ire != NULL) &&
19465 			    (ire->ire_type == IRE_LOCAL))
19466 				goto standard_path;
19467 
19468 			if (ire != NULL) {
19469 				ire_refrele(ire);
19470 				/* No more access to ire */
19471 				ire = NULL;
19472 			}
19473 			/*
19474 			 * bypass routing checks and go directly to
19475 			 * interface.
19476 			 */
19477 			if (connp->conn_dontroute) {
19478 				goto dontroute;
19479 			} else if (connp->conn_nexthop_set) {
19480 				ip_nexthop = B_TRUE;
19481 				nexthop_addr = connp->conn_nexthop_v4;
19482 				goto send_from_ill;
19483 			}
19484 
19485 			/*
19486 			 * If IP_XMIT_IF socket option is set,
19487 			 * then we allow unicast and multicast
19488 			 * packets to go through the ill. It is
19489 			 * quite possible that the destination
19490 			 * is not in the ire cache table and we
19491 			 * do not want to go to ip_newroute()
19492 			 * instead we call ip_newroute_ipif.
19493 			 */
19494 			xmit_ill = conn_get_held_ill(connp,
19495 			    &connp->conn_xmit_if_ill, &err);
19496 			if (err == ILL_LOOKUP_FAILED) {
19497 				if (attach_ill != NULL)
19498 					ill_refrele(attach_ill);
19499 				if (need_decref)
19500 					CONN_DEC_REF(connp);
19501 				freemsg(first_mp);
19502 				return;
19503 			}
19504 			goto send_from_ill;
19505 		}
19506 standard_path:
19507 		/* Must be a broadcast, a loopback or a local ire */
19508 		if (ire != NULL) {
19509 			ire_refrele(ire);
19510 			/* No more access to ire */
19511 			ire = NULL;
19512 		}
19513 	}
19514 
19515 	if (attach_ill != NULL)
19516 		goto send_from_ill;
19517 
19518 	/*
19519 	 * We cache IRE_CACHEs to avoid lookups. We don't do
19520 	 * this for the tcp global queue and listen end point
19521 	 * as it does not really have a real destination to
19522 	 * talk to.  This is also true for SCTP.
19523 	 */
19524 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
19525 	    !connp->conn_fully_bound) {
19526 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19527 		if (ire == NULL)
19528 			goto noirefound;
19529 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19530 		    "ip_wput_end: q %p (%S)", q, "end");
19531 
19532 		/*
19533 		 * Check if the ire has the RTF_MULTIRT flag, inherited
19534 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19535 		 */
19536 		if (ire->ire_flags & RTF_MULTIRT) {
19537 
19538 			/*
19539 			 * Force the TTL of multirouted packets if required.
19540 			 * The TTL of such packets is bounded by the
19541 			 * ip_multirt_ttl ndd variable.
19542 			 */
19543 			if ((ip_multirt_ttl > 0) &&
19544 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
19545 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
19546 				    "(was %d), dst 0x%08x\n",
19547 				    ip_multirt_ttl, ipha->ipha_ttl,
19548 				    ntohl(ire->ire_addr)));
19549 				ipha->ipha_ttl = ip_multirt_ttl;
19550 			}
19551 			/*
19552 			 * We look at this point if there are pending
19553 			 * unresolved routes. ire_multirt_resolvable()
19554 			 * checks in O(n) that all IRE_OFFSUBNET ire
19555 			 * entries for the packet's destination and
19556 			 * flagged RTF_MULTIRT are currently resolved.
19557 			 * If some remain unresolved, we make a copy
19558 			 * of the current message. It will be used
19559 			 * to initiate additional route resolutions.
19560 			 */
19561 			multirt_need_resolve =
19562 			    ire_multirt_need_resolve(ire->ire_addr,
19563 			    MBLK_GETLABEL(first_mp));
19564 			ip2dbg(("ip_wput[TCP]: ire %p, "
19565 			    "multirt_need_resolve %d, first_mp %p\n",
19566 			    (void *)ire, multirt_need_resolve,
19567 			    (void *)first_mp));
19568 			if (multirt_need_resolve) {
19569 				copy_mp = copymsg(first_mp);
19570 				if (copy_mp != NULL) {
19571 					MULTIRT_DEBUG_TAG(copy_mp);
19572 				}
19573 			}
19574 		}
19575 
19576 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19577 
19578 		/*
19579 		 * Try to resolve another multiroute if
19580 		 * ire_multirt_need_resolve() deemed it necessary.
19581 		 */
19582 		if (copy_mp != NULL) {
19583 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19584 		}
19585 		if (need_decref)
19586 			CONN_DEC_REF(connp);
19587 		return;
19588 	}
19589 
19590 	/*
19591 	 * Access to conn_ire_cache. (protected by conn_lock)
19592 	 *
19593 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
19594 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
19595 	 * send a packet or two with the IRE_CACHE that is going away.
19596 	 * Access to the ire requires an ire refhold on the ire prior to
19597 	 * its use since an interface unplumb thread may delete the cached
19598 	 * ire and release the refhold at any time.
19599 	 *
19600 	 * Caching an ire in the conn_ire_cache
19601 	 *
19602 	 * o Caching an ire pointer in the conn requires a strict check for
19603 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
19604 	 * ires  before cleaning up the conns. So the caching of an ire pointer
19605 	 * in the conn is done after making sure under the bucket lock that the
19606 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
19607 	 * caching an ire after the unplumb thread has cleaned up the conn.
19608 	 * If the conn does not send a packet subsequently the unplumb thread
19609 	 * will be hanging waiting for the ire count to drop to zero.
19610 	 *
19611 	 * o We also need to atomically test for a null conn_ire_cache and
19612 	 * set the conn_ire_cache under the the protection of the conn_lock
19613 	 * to avoid races among concurrent threads trying to simultaneously
19614 	 * cache an ire in the conn_ire_cache.
19615 	 */
19616 	mutex_enter(&connp->conn_lock);
19617 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
19618 
19619 	if (ire != NULL && ire->ire_addr == dst &&
19620 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19621 
19622 		IRE_REFHOLD(ire);
19623 		mutex_exit(&connp->conn_lock);
19624 
19625 	} else {
19626 		boolean_t cached = B_FALSE;
19627 		connp->conn_ire_cache = NULL;
19628 		mutex_exit(&connp->conn_lock);
19629 		/* Release the old ire */
19630 		if (ire != NULL && sctp_ire == NULL)
19631 			IRE_REFRELE_NOTR(ire);
19632 
19633 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19634 		if (ire == NULL)
19635 			goto noirefound;
19636 		IRE_REFHOLD_NOTR(ire);
19637 
19638 		mutex_enter(&connp->conn_lock);
19639 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
19640 		    connp->conn_ire_cache == NULL) {
19641 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19642 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19643 				connp->conn_ire_cache = ire;
19644 				cached = B_TRUE;
19645 			}
19646 			rw_exit(&ire->ire_bucket->irb_lock);
19647 		}
19648 		mutex_exit(&connp->conn_lock);
19649 
19650 		/*
19651 		 * We can continue to use the ire but since it was
19652 		 * not cached, we should drop the extra reference.
19653 		 */
19654 		if (!cached)
19655 			IRE_REFRELE_NOTR(ire);
19656 	}
19657 
19658 
19659 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19660 	    "ip_wput_end: q %p (%S)", q, "end");
19661 
19662 	/*
19663 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19664 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19665 	 */
19666 	if (ire->ire_flags & RTF_MULTIRT) {
19667 
19668 		/*
19669 		 * Force the TTL of multirouted packets if required.
19670 		 * The TTL of such packets is bounded by the
19671 		 * ip_multirt_ttl ndd variable.
19672 		 */
19673 		if ((ip_multirt_ttl > 0) &&
19674 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19675 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19676 			    "(was %d), dst 0x%08x\n",
19677 			    ip_multirt_ttl, ipha->ipha_ttl,
19678 			    ntohl(ire->ire_addr)));
19679 			ipha->ipha_ttl = ip_multirt_ttl;
19680 		}
19681 
19682 		/*
19683 		 * At this point, we check to see if there are any pending
19684 		 * unresolved routes. ire_multirt_resolvable()
19685 		 * checks in O(n) that all IRE_OFFSUBNET ire
19686 		 * entries for the packet's destination and
19687 		 * flagged RTF_MULTIRT are currently resolved.
19688 		 * If some remain unresolved, we make a copy
19689 		 * of the current message. It will be used
19690 		 * to initiate additional route resolutions.
19691 		 */
19692 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19693 		    MBLK_GETLABEL(first_mp));
19694 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19695 		    "multirt_need_resolve %d, first_mp %p\n",
19696 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19697 		if (multirt_need_resolve) {
19698 			copy_mp = copymsg(first_mp);
19699 			if (copy_mp != NULL) {
19700 				MULTIRT_DEBUG_TAG(copy_mp);
19701 			}
19702 		}
19703 	}
19704 
19705 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19706 
19707 	/*
19708 	 * Try to resolve another multiroute if
19709 	 * ire_multirt_resolvable() deemed it necessary
19710 	 */
19711 	if (copy_mp != NULL) {
19712 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19713 	}
19714 	if (need_decref)
19715 		CONN_DEC_REF(connp);
19716 	return;
19717 
19718 qnext:
19719 	/*
19720 	 * Upper Level Protocols pass down complete IP datagrams
19721 	 * as M_DATA messages.	Everything else is a sideshow.
19722 	 *
19723 	 * 1) We could be re-entering ip_wput because of ip_neworute
19724 	 *    in which case we could have a IPSEC_OUT message. We
19725 	 *    need to pass through ip_wput like other datagrams and
19726 	 *    hence cannot branch to ip_wput_nondata.
19727 	 *
19728 	 * 2) ARP, AH, ESP, and other clients who are on the module
19729 	 *    instance of IP stream, give us something to deal with.
19730 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19731 	 *
19732 	 * 3) ICMP replies also could come here.
19733 	 */
19734 	if (DB_TYPE(mp) != M_DATA) {
19735 	    notdata:
19736 		if (DB_TYPE(mp) == M_CTL) {
19737 			/*
19738 			 * M_CTL messages are used by ARP, AH and ESP to
19739 			 * communicate with IP. We deal with IPSEC_IN and
19740 			 * IPSEC_OUT here. ip_wput_nondata handles other
19741 			 * cases.
19742 			 */
19743 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19744 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19745 				first_mp = mp->b_cont;
19746 				first_mp->b_flag &= ~MSGHASREF;
19747 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19748 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19749 				CONN_DEC_REF(connp);
19750 				connp = NULL;
19751 			}
19752 			if (ii->ipsec_info_type == IPSEC_IN) {
19753 				/*
19754 				 * Either this message goes back to
19755 				 * IPSEC for further processing or to
19756 				 * ULP after policy checks.
19757 				 */
19758 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19759 				return;
19760 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19761 				io = (ipsec_out_t *)ii;
19762 				if (io->ipsec_out_proc_begin) {
19763 					/*
19764 					 * IPSEC processing has already started.
19765 					 * Complete it.
19766 					 * IPQoS notes: We don't care what is
19767 					 * in ipsec_out_ill_index since this
19768 					 * won't be processed for IPQoS policies
19769 					 * in ipsec_out_process.
19770 					 */
19771 					ipsec_out_process(q, mp, NULL,
19772 					    io->ipsec_out_ill_index);
19773 					return;
19774 				} else {
19775 					connp = (q->q_next != NULL) ?
19776 					    NULL : Q_TO_CONN(q);
19777 					first_mp = mp;
19778 					mp = mp->b_cont;
19779 					mctl_present = B_TRUE;
19780 				}
19781 				zoneid = io->ipsec_out_zoneid;
19782 				ASSERT(zoneid != ALL_ZONES);
19783 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
19784 				/*
19785 				 * It's an IPsec control message requesting
19786 				 * an SADB update to be sent to the IPsec
19787 				 * hardware acceleration capable ills.
19788 				 */
19789 				ipsec_ctl_t *ipsec_ctl =
19790 				    (ipsec_ctl_t *)mp->b_rptr;
19791 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
19792 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
19793 				mblk_t *cmp = mp->b_cont;
19794 
19795 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
19796 				ASSERT(cmp != NULL);
19797 
19798 				freeb(mp);
19799 				ill_ipsec_capab_send_all(satype, cmp, sa);
19800 				return;
19801 			} else {
19802 				/*
19803 				 * This must be ARP or special TSOL signaling.
19804 				 */
19805 				ip_wput_nondata(NULL, q, mp, NULL);
19806 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19807 				    "ip_wput_end: q %p (%S)", q, "nondata");
19808 				return;
19809 			}
19810 		} else {
19811 			/*
19812 			 * This must be non-(ARP/AH/ESP) messages.
19813 			 */
19814 			ASSERT(!need_decref);
19815 			ip_wput_nondata(NULL, q, mp, NULL);
19816 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19817 			    "ip_wput_end: q %p (%S)", q, "nondata");
19818 			return;
19819 		}
19820 	} else {
19821 		first_mp = mp;
19822 		mctl_present = B_FALSE;
19823 	}
19824 
19825 	ASSERT(first_mp != NULL);
19826 	/*
19827 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
19828 	 * to make sure that this packet goes out on the same interface it
19829 	 * came in. We handle that here.
19830 	 */
19831 	if (mctl_present) {
19832 		uint_t ifindex;
19833 
19834 		io = (ipsec_out_t *)first_mp->b_rptr;
19835 		if (io->ipsec_out_attach_if ||
19836 		    io->ipsec_out_xmit_if ||
19837 		    io->ipsec_out_ip_nexthop) {
19838 			ill_t	*ill;
19839 
19840 			/*
19841 			 * We may have lost the conn context if we are
19842 			 * coming here from ip_newroute(). Copy the
19843 			 * nexthop information.
19844 			 */
19845 			if (io->ipsec_out_ip_nexthop) {
19846 				ip_nexthop = B_TRUE;
19847 				nexthop_addr = io->ipsec_out_nexthop_addr;
19848 
19849 				ipha = (ipha_t *)mp->b_rptr;
19850 				dst = ipha->ipha_dst;
19851 				goto send_from_ill;
19852 			} else {
19853 				ASSERT(io->ipsec_out_ill_index != 0);
19854 				ifindex = io->ipsec_out_ill_index;
19855 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
19856 				    NULL, NULL, NULL, NULL);
19857 				/*
19858 				 * ipsec_out_xmit_if bit is used to tell
19859 				 * ip_wput to use the ill to send outgoing data
19860 				 * as we have no conn when data comes from ICMP
19861 				 * error msg routines. Currently this feature is
19862 				 * only used by ip_mrtun_forward routine.
19863 				 */
19864 				if (io->ipsec_out_xmit_if) {
19865 					xmit_ill = ill;
19866 					if (xmit_ill == NULL) {
19867 						ip1dbg(("ip_output:bad ifindex "
19868 						    "for xmit_ill %d\n",
19869 						    ifindex));
19870 						freemsg(first_mp);
19871 						BUMP_MIB(&ip_mib,
19872 						    ipOutDiscards);
19873 						ASSERT(!need_decref);
19874 						return;
19875 					}
19876 					/* Free up the ipsec_out_t mblk */
19877 					ASSERT(first_mp->b_cont == mp);
19878 					first_mp->b_cont = NULL;
19879 					freeb(first_mp);
19880 					/* Just send the IP header+ICMP+data */
19881 					first_mp = mp;
19882 					ipha = (ipha_t *)mp->b_rptr;
19883 					dst = ipha->ipha_dst;
19884 					goto send_from_ill;
19885 				} else {
19886 					attach_ill = ill;
19887 				}
19888 
19889 				if (attach_ill == NULL) {
19890 					ASSERT(xmit_ill == NULL);
19891 					ip1dbg(("ip_output: bad ifindex for "
19892 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
19893 					    ifindex));
19894 					freemsg(first_mp);
19895 					BUMP_MIB(&ip_mib, ipOutDiscards);
19896 					ASSERT(!need_decref);
19897 					return;
19898 				}
19899 			}
19900 		}
19901 	}
19902 
19903 	ASSERT(xmit_ill == NULL);
19904 
19905 	/* We have a complete IP datagram heading outbound. */
19906 	ipha = (ipha_t *)mp->b_rptr;
19907 
19908 #ifndef SPEED_BEFORE_SAFETY
19909 	/*
19910 	 * Make sure we have a full-word aligned message and that at least
19911 	 * a simple IP header is accessible in the first message.  If not,
19912 	 * try a pullup.
19913 	 */
19914 	if (!OK_32PTR(rptr) ||
19915 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
19916 	    hdrtoosmall:
19917 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
19918 			BUMP_MIB(&ip_mib, ipOutDiscards);
19919 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19920 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
19921 			if (first_mp == NULL)
19922 				first_mp = mp;
19923 			goto drop_pkt;
19924 		}
19925 
19926 		/* This function assumes that mp points to an IPv4 packet. */
19927 		if (is_system_labeled() && q->q_next == NULL &&
19928 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
19929 		    !connp->conn_ulp_labeled) {
19930 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
19931 			    &adjust, connp->conn_mac_exempt);
19932 			ipha = (ipha_t *)mp->b_rptr;
19933 			if (first_mp != NULL)
19934 				first_mp->b_cont = mp;
19935 			if (err != 0) {
19936 				if (first_mp == NULL)
19937 					first_mp = mp;
19938 				if (err == EINVAL)
19939 					goto icmp_parameter_problem;
19940 				ip2dbg(("ip_wput: label check failed (%d)\n",
19941 				    err));
19942 				goto drop_pkt;
19943 			}
19944 			iplen = ntohs(ipha->ipha_length) + adjust;
19945 			ipha->ipha_length = htons(iplen);
19946 		}
19947 
19948 		ipha = (ipha_t *)mp->b_rptr;
19949 		if (first_mp == NULL) {
19950 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
19951 			/*
19952 			 * If we got here because of "goto hdrtoosmall"
19953 			 * We need to attach a IPSEC_OUT.
19954 			 */
19955 			if (connp->conn_out_enforce_policy) {
19956 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
19957 				    NULL, ipha->ipha_protocol)) == NULL)) {
19958 					if (need_decref)
19959 						CONN_DEC_REF(connp);
19960 					return;
19961 				} else {
19962 					ASSERT(mp->b_datap->db_type == M_CTL);
19963 					first_mp = mp;
19964 					mp = mp->b_cont;
19965 					mctl_present = B_TRUE;
19966 				}
19967 			} else {
19968 				first_mp = mp;
19969 				mctl_present = B_FALSE;
19970 			}
19971 		}
19972 	}
19973 #endif
19974 
19975 	/* Most of the code below is written for speed, not readability */
19976 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19977 
19978 	/*
19979 	 * If ip_newroute() fails, we're going to need a full
19980 	 * header for the icmp wraparound.
19981 	 */
19982 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
19983 		uint_t	v_hlen;
19984 	    version_hdrlen_check:
19985 		ASSERT(first_mp != NULL);
19986 		v_hlen = V_HLEN;
19987 		/*
19988 		 * siphon off IPv6 packets coming down from transport
19989 		 * layer modules here.
19990 		 * Note: high-order bit carries NUD reachability confirmation
19991 		 */
19992 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
19993 			/*
19994 			 * XXX implement a IPv4 and IPv6 packet counter per
19995 			 * conn and switch when ratio exceeds e.g. 10:1
19996 			 */
19997 #ifdef notyet
19998 			if (q->q_next == NULL) /* Avoid ill queue */
19999 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
20000 #endif
20001 			BUMP_MIB(&ip_mib, ipOutIPv6);
20002 			ASSERT(xmit_ill == NULL);
20003 			if (attach_ill != NULL)
20004 				ill_refrele(attach_ill);
20005 			if (need_decref)
20006 				mp->b_flag |= MSGHASREF;
20007 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20008 			return;
20009 		}
20010 
20011 		if ((v_hlen >> 4) != IP_VERSION) {
20012 			BUMP_MIB(&ip_mib, ipOutDiscards);
20013 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20014 			    "ip_wput_end: q %p (%S)", q, "badvers");
20015 			goto drop_pkt;
20016 		}
20017 		/*
20018 		 * Is the header length at least 20 bytes?
20019 		 *
20020 		 * Are there enough bytes accessible in the header?  If
20021 		 * not, try a pullup.
20022 		 */
20023 		v_hlen &= 0xF;
20024 		v_hlen <<= 2;
20025 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20026 			BUMP_MIB(&ip_mib, ipOutDiscards);
20027 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20028 			    "ip_wput_end: q %p (%S)", q, "badlen");
20029 			goto drop_pkt;
20030 		}
20031 		if (v_hlen > (mp->b_wptr - rptr)) {
20032 			if (!pullupmsg(mp, v_hlen)) {
20033 				BUMP_MIB(&ip_mib, ipOutDiscards);
20034 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20035 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20036 				goto drop_pkt;
20037 			}
20038 			ipha = (ipha_t *)mp->b_rptr;
20039 		}
20040 		/*
20041 		 * Move first entry from any source route into ipha_dst and
20042 		 * verify the options
20043 		 */
20044 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
20045 			ASSERT(xmit_ill == NULL);
20046 			if (attach_ill != NULL)
20047 				ill_refrele(attach_ill);
20048 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20049 			    "ip_wput_end: q %p (%S)", q, "badopts");
20050 			if (need_decref)
20051 				CONN_DEC_REF(connp);
20052 			return;
20053 		}
20054 	}
20055 	dst = ipha->ipha_dst;
20056 
20057 	/*
20058 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20059 	 * we have to run the packet through ip_newroute which will take
20060 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20061 	 * a resolver, or assigning a default gateway, etc.
20062 	 */
20063 	if (CLASSD(dst)) {
20064 		ipif_t	*ipif;
20065 		uint32_t setsrc = 0;
20066 
20067 	    multicast:
20068 		ASSERT(first_mp != NULL);
20069 		ASSERT(xmit_ill == NULL);
20070 		ip2dbg(("ip_wput: CLASSD\n"));
20071 		if (connp == NULL) {
20072 			/*
20073 			 * Use the first good ipif on the ill.
20074 			 * XXX Should this ever happen? (Appears
20075 			 * to show up with just ppp and no ethernet due
20076 			 * to in.rdisc.)
20077 			 * However, ire_send should be able to
20078 			 * call ip_wput_ire directly.
20079 			 *
20080 			 * XXX Also, this can happen for ICMP and other packets
20081 			 * with multicast source addresses.  Perhaps we should
20082 			 * fix things so that we drop the packet in question,
20083 			 * but for now, just run with it.
20084 			 */
20085 			ill_t *ill = (ill_t *)q->q_ptr;
20086 
20087 			/*
20088 			 * Don't honor attach_if for this case. If ill
20089 			 * is part of the group, ipif could belong to
20090 			 * any ill and we cannot maintain attach_ill
20091 			 * and ipif_ill same anymore and the assert
20092 			 * below would fail.
20093 			 */
20094 			if (mctl_present) {
20095 				io->ipsec_out_ill_index = 0;
20096 				io->ipsec_out_attach_if = B_FALSE;
20097 				ASSERT(attach_ill != NULL);
20098 				ill_refrele(attach_ill);
20099 				attach_ill = NULL;
20100 			}
20101 
20102 			ASSERT(attach_ill == NULL);
20103 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20104 			if (ipif == NULL) {
20105 				if (need_decref)
20106 					CONN_DEC_REF(connp);
20107 				freemsg(first_mp);
20108 				return;
20109 			}
20110 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20111 			    ntohl(dst), ill->ill_name));
20112 		} else {
20113 			/*
20114 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
20115 			 * IP_XMIT_IF is honoured.
20116 			 * Block comment above this function explains the
20117 			 * locking mechanism used here
20118 			 */
20119 			xmit_ill = conn_get_held_ill(connp,
20120 			    &connp->conn_xmit_if_ill, &err);
20121 			if (err == ILL_LOOKUP_FAILED) {
20122 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
20123 				goto drop_pkt;
20124 			}
20125 			if (xmit_ill == NULL) {
20126 				ipif = conn_get_held_ipif(connp,
20127 				    &connp->conn_multicast_ipif, &err);
20128 				if (err == IPIF_LOOKUP_FAILED) {
20129 					ip1dbg(("ip_wput: No ipif for "
20130 					    "multicast\n"));
20131 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20132 					goto drop_pkt;
20133 				}
20134 			}
20135 			if (xmit_ill != NULL) {
20136 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20137 				if (ipif == NULL) {
20138 					ip1dbg(("ip_wput: No ipif for "
20139 					    "IP_XMIT_IF\n"));
20140 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20141 					goto drop_pkt;
20142 				}
20143 			} else if (ipif == NULL || ipif->ipif_isv6) {
20144 				/*
20145 				 * We must do this ipif determination here
20146 				 * else we could pass through ip_newroute
20147 				 * and come back here without the conn context.
20148 				 *
20149 				 * Note: we do late binding i.e. we bind to
20150 				 * the interface when the first packet is sent.
20151 				 * For performance reasons we do not rebind on
20152 				 * each packet but keep the binding until the
20153 				 * next IP_MULTICAST_IF option.
20154 				 *
20155 				 * conn_multicast_{ipif,ill} are shared between
20156 				 * IPv4 and IPv6 and AF_INET6 sockets can
20157 				 * send both IPv4 and IPv6 packets. Hence
20158 				 * we have to check that "isv6" matches above.
20159 				 */
20160 				if (ipif != NULL)
20161 					ipif_refrele(ipif);
20162 				ipif = ipif_lookup_group(dst, zoneid);
20163 				if (ipif == NULL) {
20164 					ip1dbg(("ip_wput: No ipif for "
20165 					    "multicast\n"));
20166 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20167 					goto drop_pkt;
20168 				}
20169 				err = conn_set_held_ipif(connp,
20170 				    &connp->conn_multicast_ipif, ipif);
20171 				if (err == IPIF_LOOKUP_FAILED) {
20172 					ipif_refrele(ipif);
20173 					ip1dbg(("ip_wput: No ipif for "
20174 					    "multicast\n"));
20175 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20176 					goto drop_pkt;
20177 				}
20178 			}
20179 		}
20180 		ASSERT(!ipif->ipif_isv6);
20181 		/*
20182 		 * As we may lose the conn by the time we reach ip_wput_ire,
20183 		 * we copy conn_multicast_loop and conn_dontroute on to an
20184 		 * ipsec_out. In case if this datagram goes out secure,
20185 		 * we need the ill_index also. Copy that also into the
20186 		 * ipsec_out.
20187 		 */
20188 		if (mctl_present) {
20189 			io = (ipsec_out_t *)first_mp->b_rptr;
20190 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20191 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20192 		} else {
20193 			ASSERT(mp == first_mp);
20194 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20195 			    BPRI_HI)) == NULL) {
20196 				ipif_refrele(ipif);
20197 				first_mp = mp;
20198 				goto drop_pkt;
20199 			}
20200 			first_mp->b_datap->db_type = M_CTL;
20201 			first_mp->b_wptr += sizeof (ipsec_info_t);
20202 			/* ipsec_out_secure is B_FALSE now */
20203 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20204 			io = (ipsec_out_t *)first_mp->b_rptr;
20205 			io->ipsec_out_type = IPSEC_OUT;
20206 			io->ipsec_out_len = sizeof (ipsec_out_t);
20207 			io->ipsec_out_use_global_policy = B_TRUE;
20208 			first_mp->b_cont = mp;
20209 			mctl_present = B_TRUE;
20210 		}
20211 		if (attach_ill != NULL) {
20212 			ASSERT(attach_ill == ipif->ipif_ill);
20213 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20214 
20215 			/*
20216 			 * Check if we need an ire that will not be
20217 			 * looked up by anybody else i.e. HIDDEN.
20218 			 */
20219 			if (ill_is_probeonly(attach_ill)) {
20220 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20221 			}
20222 			io->ipsec_out_ill_index =
20223 			    attach_ill->ill_phyint->phyint_ifindex;
20224 			io->ipsec_out_attach_if = B_TRUE;
20225 		} else {
20226 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20227 			io->ipsec_out_ill_index =
20228 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20229 		}
20230 		if (connp != NULL) {
20231 			io->ipsec_out_multicast_loop =
20232 			    connp->conn_multicast_loop;
20233 			io->ipsec_out_dontroute = connp->conn_dontroute;
20234 			io->ipsec_out_zoneid = connp->conn_zoneid;
20235 		}
20236 		/*
20237 		 * If the application uses IP_MULTICAST_IF with
20238 		 * different logical addresses of the same ILL, we
20239 		 * need to make sure that the soruce address of
20240 		 * the packet matches the logical IP address used
20241 		 * in the option. We do it by initializing ipha_src
20242 		 * here. This should keep IPSEC also happy as
20243 		 * when we return from IPSEC processing, we don't
20244 		 * have to worry about getting the right address on
20245 		 * the packet. Thus it is sufficient to look for
20246 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20247 		 * MATCH_IRE_IPIF.
20248 		 *
20249 		 * NOTE : We need to do it for non-secure case also as
20250 		 * this might go out secure if there is a global policy
20251 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20252 		 * address, the source should be initialized already and
20253 		 * hence we won't be initializing here.
20254 		 *
20255 		 * As we do not have the ire yet, it is possible that
20256 		 * we set the source address here and then later discover
20257 		 * that the ire implies the source address to be assigned
20258 		 * through the RTF_SETSRC flag.
20259 		 * In that case, the setsrc variable will remind us
20260 		 * that overwritting the source address by the one
20261 		 * of the RTF_SETSRC-flagged ire is allowed.
20262 		 */
20263 		if (ipha->ipha_src == INADDR_ANY &&
20264 		    (connp == NULL || !connp->conn_unspec_src)) {
20265 			ipha->ipha_src = ipif->ipif_src_addr;
20266 			setsrc = RTF_SETSRC;
20267 		}
20268 		/*
20269 		 * Find an IRE which matches the destination and the outgoing
20270 		 * queue (i.e. the outgoing interface.)
20271 		 * For loopback use a unicast IP address for
20272 		 * the ire lookup.
20273 		 */
20274 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20275 		    PHYI_LOOPBACK) {
20276 			dst = ipif->ipif_lcl_addr;
20277 		}
20278 		/*
20279 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20280 		 * We don't need to lookup ire in ctable as the packet
20281 		 * needs to be sent to the destination through the specified
20282 		 * ill irrespective of ires in the cache table.
20283 		 */
20284 		ire = NULL;
20285 		if (xmit_ill == NULL) {
20286 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20287 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20288 		}
20289 
20290 		/*
20291 		 * refrele attach_ill as its not needed anymore.
20292 		 */
20293 		if (attach_ill != NULL) {
20294 			ill_refrele(attach_ill);
20295 			attach_ill = NULL;
20296 		}
20297 
20298 		if (ire == NULL) {
20299 			/*
20300 			 * Multicast loopback and multicast forwarding is
20301 			 * done in ip_wput_ire.
20302 			 *
20303 			 * Mark this packet to make it be delivered to
20304 			 * ip_wput_ire after the new ire has been
20305 			 * created.
20306 			 *
20307 			 * The call to ip_newroute_ipif takes into account
20308 			 * the setsrc reminder. In any case, we take care
20309 			 * of the RTF_MULTIRT flag.
20310 			 */
20311 			mp->b_prev = mp->b_next = NULL;
20312 			if (xmit_ill == NULL ||
20313 			    xmit_ill->ill_ipif_up_count > 0) {
20314 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20315 				    setsrc | RTF_MULTIRT, zoneid);
20316 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20317 				    "ip_wput_end: q %p (%S)", q, "noire");
20318 			} else {
20319 				freemsg(first_mp);
20320 			}
20321 			ipif_refrele(ipif);
20322 			if (xmit_ill != NULL)
20323 				ill_refrele(xmit_ill);
20324 			if (need_decref)
20325 				CONN_DEC_REF(connp);
20326 			return;
20327 		}
20328 
20329 		ipif_refrele(ipif);
20330 		ipif = NULL;
20331 		ASSERT(xmit_ill == NULL);
20332 
20333 		/*
20334 		 * Honor the RTF_SETSRC flag for multicast packets,
20335 		 * if allowed by the setsrc reminder.
20336 		 */
20337 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20338 			ipha->ipha_src = ire->ire_src_addr;
20339 		}
20340 
20341 		/*
20342 		 * Unconditionally force the TTL to 1 for
20343 		 * multirouted multicast packets:
20344 		 * multirouted multicast should not cross
20345 		 * multicast routers.
20346 		 */
20347 		if (ire->ire_flags & RTF_MULTIRT) {
20348 			if (ipha->ipha_ttl > 1) {
20349 				ip2dbg(("ip_wput: forcing multicast "
20350 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20351 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20352 				ipha->ipha_ttl = 1;
20353 			}
20354 		}
20355 	} else {
20356 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20357 		if ((ire != NULL) && (ire->ire_type &
20358 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20359 			ignore_dontroute = B_TRUE;
20360 			ignore_nexthop = B_TRUE;
20361 		}
20362 		if (ire != NULL) {
20363 			ire_refrele(ire);
20364 			ire = NULL;
20365 		}
20366 		/*
20367 		 * Guard against coming in from arp in which case conn is NULL.
20368 		 * Also guard against non M_DATA with dontroute set but
20369 		 * destined to local, loopback or broadcast addresses.
20370 		 */
20371 		if (connp != NULL && connp->conn_dontroute &&
20372 		    !ignore_dontroute) {
20373 dontroute:
20374 			/*
20375 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20376 			 * routing protocols from seeing false direct
20377 			 * connectivity.
20378 			 */
20379 			ipha->ipha_ttl = 1;
20380 			/*
20381 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20382 			 * along with SO_DONTROUTE, higher precedence is
20383 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20384 			 */
20385 			if (connp->conn_xmit_if_ill == NULL) {
20386 				/* If suitable ipif not found, drop packet */
20387 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20388 				if (dst_ipif == NULL) {
20389 					ip1dbg(("ip_wput: no route for "
20390 					    "dst using SO_DONTROUTE\n"));
20391 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20392 					mp->b_prev = mp->b_next = NULL;
20393 					if (first_mp == NULL)
20394 						first_mp = mp;
20395 					goto drop_pkt;
20396 				} else {
20397 					/*
20398 					 * If suitable ipif has been found, set
20399 					 * xmit_ill to the corresponding
20400 					 * ipif_ill because we'll be following
20401 					 * the IP_XMIT_IF logic.
20402 					 */
20403 					ASSERT(xmit_ill == NULL);
20404 					xmit_ill = dst_ipif->ipif_ill;
20405 					mutex_enter(&xmit_ill->ill_lock);
20406 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20407 						mutex_exit(&xmit_ill->ill_lock);
20408 						xmit_ill = NULL;
20409 						ipif_refrele(dst_ipif);
20410 						ip1dbg(("ip_wput: no route for"
20411 						    " dst using"
20412 						    " SO_DONTROUTE\n"));
20413 						BUMP_MIB(&ip_mib,
20414 						    ipOutNoRoutes);
20415 						mp->b_prev = mp->b_next = NULL;
20416 						if (first_mp == NULL)
20417 							first_mp = mp;
20418 						goto drop_pkt;
20419 					}
20420 					ill_refhold_locked(xmit_ill);
20421 					mutex_exit(&xmit_ill->ill_lock);
20422 					ipif_refrele(dst_ipif);
20423 				}
20424 			}
20425 
20426 		}
20427 		/*
20428 		 * If we are bound to IPIF_NOFAILOVER address, look for
20429 		 * an IRE_CACHE matching the ill.
20430 		 */
20431 send_from_ill:
20432 		if (attach_ill != NULL) {
20433 			ipif_t	*attach_ipif;
20434 
20435 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20436 
20437 			/*
20438 			 * Check if we need an ire that will not be
20439 			 * looked up by anybody else i.e. HIDDEN.
20440 			 */
20441 			if (ill_is_probeonly(attach_ill)) {
20442 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20443 			}
20444 
20445 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20446 			if (attach_ipif == NULL) {
20447 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20448 				goto drop_pkt;
20449 			}
20450 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20451 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20452 			ipif_refrele(attach_ipif);
20453 		} else if (xmit_ill != NULL || (connp != NULL &&
20454 			    connp->conn_xmit_if_ill != NULL)) {
20455 			/*
20456 			 * Mark this packet as originated locally
20457 			 */
20458 			mp->b_prev = mp->b_next = NULL;
20459 			/*
20460 			 * xmit_ill could be NULL if SO_DONTROUTE
20461 			 * is also set.
20462 			 */
20463 			if (xmit_ill == NULL) {
20464 				xmit_ill = conn_get_held_ill(connp,
20465 				    &connp->conn_xmit_if_ill, &err);
20466 				if (err == ILL_LOOKUP_FAILED) {
20467 					if (need_decref)
20468 						CONN_DEC_REF(connp);
20469 					freemsg(first_mp);
20470 					return;
20471 				}
20472 				if (xmit_ill == NULL) {
20473 					if (connp->conn_dontroute)
20474 						goto dontroute;
20475 					goto send_from_ill;
20476 				}
20477 			}
20478 			/*
20479 			 * could be SO_DONTROUTE case also.
20480 			 * check at least one interface is UP as
20481 			 * spcified by this ILL, and then call
20482 			 * ip_newroute_ipif()
20483 			 */
20484 			if (xmit_ill->ill_ipif_up_count > 0) {
20485 				ipif_t *ipif;
20486 
20487 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20488 				if (ipif != NULL) {
20489 					ip_newroute_ipif(q, first_mp, ipif,
20490 					    dst, connp, 0, zoneid);
20491 					ipif_refrele(ipif);
20492 					ip1dbg(("ip_wput: ip_unicast_if\n"));
20493 				}
20494 			} else {
20495 				freemsg(first_mp);
20496 			}
20497 			ill_refrele(xmit_ill);
20498 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20499 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
20500 			if (need_decref)
20501 				CONN_DEC_REF(connp);
20502 			return;
20503 		} else if (ip_nexthop || (connp != NULL &&
20504 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
20505 			if (!ip_nexthop) {
20506 				ip_nexthop = B_TRUE;
20507 				nexthop_addr = connp->conn_nexthop_v4;
20508 			}
20509 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
20510 			    MATCH_IRE_GW;
20511 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
20512 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
20513 		} else {
20514 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20515 		}
20516 		if (!ire) {
20517 			/*
20518 			 * Make sure we don't load spread if this
20519 			 * is IPIF_NOFAILOVER case.
20520 			 */
20521 			if ((attach_ill != NULL) ||
20522 			    (ip_nexthop && !ignore_nexthop)) {
20523 				if (mctl_present) {
20524 					io = (ipsec_out_t *)first_mp->b_rptr;
20525 					ASSERT(first_mp->b_datap->db_type ==
20526 					    M_CTL);
20527 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
20528 				} else {
20529 					ASSERT(mp == first_mp);
20530 					first_mp = allocb(
20531 					    sizeof (ipsec_info_t), BPRI_HI);
20532 					if (first_mp == NULL) {
20533 						first_mp = mp;
20534 						goto drop_pkt;
20535 					}
20536 					first_mp->b_datap->db_type = M_CTL;
20537 					first_mp->b_wptr +=
20538 					    sizeof (ipsec_info_t);
20539 					/* ipsec_out_secure is B_FALSE now */
20540 					bzero(first_mp->b_rptr,
20541 					    sizeof (ipsec_info_t));
20542 					io = (ipsec_out_t *)first_mp->b_rptr;
20543 					io->ipsec_out_type = IPSEC_OUT;
20544 					io->ipsec_out_len =
20545 					    sizeof (ipsec_out_t);
20546 					io->ipsec_out_use_global_policy =
20547 					    B_TRUE;
20548 					first_mp->b_cont = mp;
20549 					mctl_present = B_TRUE;
20550 				}
20551 				if (attach_ill != NULL) {
20552 					io->ipsec_out_ill_index = attach_ill->
20553 					    ill_phyint->phyint_ifindex;
20554 					io->ipsec_out_attach_if = B_TRUE;
20555 				} else {
20556 					io->ipsec_out_ip_nexthop = ip_nexthop;
20557 					io->ipsec_out_nexthop_addr =
20558 					    nexthop_addr;
20559 				}
20560 			}
20561 noirefound:
20562 			/*
20563 			 * Mark this packet as having originated on
20564 			 * this machine.  This will be noted in
20565 			 * ire_add_then_send, which needs to know
20566 			 * whether to run it back through ip_wput or
20567 			 * ip_rput following successful resolution.
20568 			 */
20569 			mp->b_prev = NULL;
20570 			mp->b_next = NULL;
20571 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid);
20572 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20573 			    "ip_wput_end: q %p (%S)", q, "newroute");
20574 			if (attach_ill != NULL)
20575 				ill_refrele(attach_ill);
20576 			if (xmit_ill != NULL)
20577 				ill_refrele(xmit_ill);
20578 			if (need_decref)
20579 				CONN_DEC_REF(connp);
20580 			return;
20581 		}
20582 	}
20583 
20584 	/* We now know where we are going with it. */
20585 
20586 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20587 	    "ip_wput_end: q %p (%S)", q, "end");
20588 
20589 	/*
20590 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20591 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
20592 	 */
20593 	if (ire->ire_flags & RTF_MULTIRT) {
20594 		/*
20595 		 * Force the TTL of multirouted packets if required.
20596 		 * The TTL of such packets is bounded by the
20597 		 * ip_multirt_ttl ndd variable.
20598 		 */
20599 		if ((ip_multirt_ttl > 0) &&
20600 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20601 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20602 			    "(was %d), dst 0x%08x\n",
20603 			    ip_multirt_ttl, ipha->ipha_ttl,
20604 			    ntohl(ire->ire_addr)));
20605 			ipha->ipha_ttl = ip_multirt_ttl;
20606 		}
20607 		/*
20608 		 * At this point, we check to see if there are any pending
20609 		 * unresolved routes. ire_multirt_resolvable()
20610 		 * checks in O(n) that all IRE_OFFSUBNET ire
20611 		 * entries for the packet's destination and
20612 		 * flagged RTF_MULTIRT are currently resolved.
20613 		 * If some remain unresolved, we make a copy
20614 		 * of the current message. It will be used
20615 		 * to initiate additional route resolutions.
20616 		 */
20617 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20618 		    MBLK_GETLABEL(first_mp));
20619 		ip2dbg(("ip_wput[noirefound]: ire %p, "
20620 		    "multirt_need_resolve %d, first_mp %p\n",
20621 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20622 		if (multirt_need_resolve) {
20623 			copy_mp = copymsg(first_mp);
20624 			if (copy_mp != NULL) {
20625 				MULTIRT_DEBUG_TAG(copy_mp);
20626 			}
20627 		}
20628 	}
20629 
20630 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20631 	/*
20632 	 * Try to resolve another multiroute if
20633 	 * ire_multirt_resolvable() deemed it necessary.
20634 	 * At this point, we need to distinguish
20635 	 * multicasts from other packets. For multicasts,
20636 	 * we call ip_newroute_ipif() and request that both
20637 	 * multirouting and setsrc flags are checked.
20638 	 */
20639 	if (copy_mp != NULL) {
20640 		if (CLASSD(dst)) {
20641 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
20642 			if (ipif) {
20643 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
20644 				    RTF_SETSRC | RTF_MULTIRT, zoneid);
20645 				ipif_refrele(ipif);
20646 			} else {
20647 				MULTIRT_DEBUG_UNTAG(copy_mp);
20648 				freemsg(copy_mp);
20649 				copy_mp = NULL;
20650 			}
20651 		} else {
20652 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20653 		}
20654 	}
20655 	if (attach_ill != NULL)
20656 		ill_refrele(attach_ill);
20657 	if (xmit_ill != NULL)
20658 		ill_refrele(xmit_ill);
20659 	if (need_decref)
20660 		CONN_DEC_REF(connp);
20661 	return;
20662 
20663 icmp_parameter_problem:
20664 	/* could not have originated externally */
20665 	ASSERT(mp->b_prev == NULL);
20666 	if (ip_hdr_complete(ipha, zoneid) == 0) {
20667 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
20668 		/* it's the IP header length that's in trouble */
20669 		icmp_param_problem(q, first_mp, 0, zoneid);
20670 		first_mp = NULL;
20671 	}
20672 
20673 drop_pkt:
20674 	ip1dbg(("ip_wput: dropped packet\n"));
20675 	if (ire != NULL)
20676 		ire_refrele(ire);
20677 	if (need_decref)
20678 		CONN_DEC_REF(connp);
20679 	freemsg(first_mp);
20680 	if (attach_ill != NULL)
20681 		ill_refrele(attach_ill);
20682 	if (xmit_ill != NULL)
20683 		ill_refrele(xmit_ill);
20684 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20685 	    "ip_wput_end: q %p (%S)", q, "droppkt");
20686 }
20687 
20688 /*
20689  * If this is a conn_t queue, then we pass in the conn. This includes the
20690  * zoneid.
20691  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
20692  * in which case we use the global zoneid since those are all part of
20693  * the global zone.
20694  */
20695 void
20696 ip_wput(queue_t *q, mblk_t *mp)
20697 {
20698 	if (CONN_Q(q))
20699 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20700 	else
20701 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
20702 }
20703 
20704 /*
20705  *
20706  * The following rules must be observed when accessing any ipif or ill
20707  * that has been cached in the conn. Typically conn_nofailover_ill,
20708  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20709  *
20710  * Access: The ipif or ill pointed to from the conn can be accessed under
20711  * the protection of the conn_lock or after it has been refheld under the
20712  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20713  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20714  * The reason for this is that a concurrent unplumb could actually be
20715  * cleaning up these cached pointers by walking the conns and might have
20716  * finished cleaning up the conn in question. The macros check that an
20717  * unplumb has not yet started on the ipif or ill.
20718  *
20719  * Caching: An ipif or ill pointer may be cached in the conn only after
20720  * making sure that an unplumb has not started. So the caching is done
20721  * while holding both the conn_lock and the ill_lock and after using the
20722  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20723  * flag before starting the cleanup of conns.
20724  *
20725  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20726  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20727  * or a reference to the ipif or a reference to an ire that references the
20728  * ipif. An ipif does not change its ill except for failover/failback. Since
20729  * failover/failback happens only after bringing down the ipif and making sure
20730  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20731  * the above holds.
20732  */
20733 ipif_t *
20734 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20735 {
20736 	ipif_t	*ipif;
20737 	ill_t	*ill;
20738 
20739 	*err = 0;
20740 	rw_enter(&ill_g_lock, RW_READER);
20741 	mutex_enter(&connp->conn_lock);
20742 	ipif = *ipifp;
20743 	if (ipif != NULL) {
20744 		ill = ipif->ipif_ill;
20745 		mutex_enter(&ill->ill_lock);
20746 		if (IPIF_CAN_LOOKUP(ipif)) {
20747 			ipif_refhold_locked(ipif);
20748 			mutex_exit(&ill->ill_lock);
20749 			mutex_exit(&connp->conn_lock);
20750 			rw_exit(&ill_g_lock);
20751 			return (ipif);
20752 		} else {
20753 			*err = IPIF_LOOKUP_FAILED;
20754 		}
20755 		mutex_exit(&ill->ill_lock);
20756 	}
20757 	mutex_exit(&connp->conn_lock);
20758 	rw_exit(&ill_g_lock);
20759 	return (NULL);
20760 }
20761 
20762 ill_t *
20763 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20764 {
20765 	ill_t	*ill;
20766 
20767 	*err = 0;
20768 	mutex_enter(&connp->conn_lock);
20769 	ill = *illp;
20770 	if (ill != NULL) {
20771 		mutex_enter(&ill->ill_lock);
20772 		if (ILL_CAN_LOOKUP(ill)) {
20773 			ill_refhold_locked(ill);
20774 			mutex_exit(&ill->ill_lock);
20775 			mutex_exit(&connp->conn_lock);
20776 			return (ill);
20777 		} else {
20778 			*err = ILL_LOOKUP_FAILED;
20779 		}
20780 		mutex_exit(&ill->ill_lock);
20781 	}
20782 	mutex_exit(&connp->conn_lock);
20783 	return (NULL);
20784 }
20785 
20786 static int
20787 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
20788 {
20789 	ill_t	*ill;
20790 
20791 	ill = ipif->ipif_ill;
20792 	mutex_enter(&connp->conn_lock);
20793 	mutex_enter(&ill->ill_lock);
20794 	if (IPIF_CAN_LOOKUP(ipif)) {
20795 		*ipifp = ipif;
20796 		mutex_exit(&ill->ill_lock);
20797 		mutex_exit(&connp->conn_lock);
20798 		return (0);
20799 	}
20800 	mutex_exit(&ill->ill_lock);
20801 	mutex_exit(&connp->conn_lock);
20802 	return (IPIF_LOOKUP_FAILED);
20803 }
20804 
20805 /*
20806  * This is called if the outbound datagram needs fragmentation.
20807  *
20808  * NOTE : This function does not ire_refrele the ire argument passed in.
20809  */
20810 static void
20811 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid)
20812 {
20813 	ipha_t		*ipha;
20814 	mblk_t		*mp;
20815 	uint32_t	v_hlen_tos_len;
20816 	uint32_t	max_frag;
20817 	uint32_t	frag_flag;
20818 	boolean_t	dont_use;
20819 
20820 	if (ipsec_mp->b_datap->db_type == M_CTL) {
20821 		mp = ipsec_mp->b_cont;
20822 	} else {
20823 		mp = ipsec_mp;
20824 	}
20825 
20826 	ipha = (ipha_t *)mp->b_rptr;
20827 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20828 
20829 #ifdef	_BIG_ENDIAN
20830 #define	V_HLEN	(v_hlen_tos_len >> 24)
20831 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20832 #else
20833 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20834 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20835 #endif
20836 
20837 #ifndef SPEED_BEFORE_SAFETY
20838 	/*
20839 	 * Check that ipha_length is consistent with
20840 	 * the mblk length
20841 	 */
20842 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
20843 		ip0dbg(("Packet length mismatch: %d, %ld\n",
20844 		    LENGTH, msgdsize(mp)));
20845 		freemsg(ipsec_mp);
20846 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20847 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
20848 		    "packet length mismatch");
20849 		return;
20850 	}
20851 #endif
20852 	/*
20853 	 * Don't use frag_flag if pre-built packet or source
20854 	 * routed or if multicast (since multicast packets do not solicit
20855 	 * ICMP "packet too big" messages). Get the values of
20856 	 * max_frag and frag_flag atomically by acquiring the
20857 	 * ire_lock.
20858 	 */
20859 	mutex_enter(&ire->ire_lock);
20860 	max_frag = ire->ire_max_frag;
20861 	frag_flag = ire->ire_frag_flag;
20862 	mutex_exit(&ire->ire_lock);
20863 
20864 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
20865 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
20866 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
20867 
20868 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
20869 	    (dont_use ? 0 : frag_flag), zoneid);
20870 }
20871 
20872 /*
20873  * Used for deciding the MSS size for the upper layer. Thus
20874  * we need to check the outbound policy values in the conn.
20875  */
20876 int
20877 conn_ipsec_length(conn_t *connp)
20878 {
20879 	ipsec_latch_t *ipl;
20880 
20881 	ipl = connp->conn_latch;
20882 	if (ipl == NULL)
20883 		return (0);
20884 
20885 	if (ipl->ipl_out_policy == NULL)
20886 		return (0);
20887 
20888 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
20889 }
20890 
20891 /*
20892  * Returns an estimate of the IPSEC headers size. This is used if
20893  * we don't want to call into IPSEC to get the exact size.
20894  */
20895 int
20896 ipsec_out_extra_length(mblk_t *ipsec_mp)
20897 {
20898 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
20899 	ipsec_action_t *a;
20900 
20901 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
20902 	if (!io->ipsec_out_secure)
20903 		return (0);
20904 
20905 	a = io->ipsec_out_act;
20906 
20907 	if (a == NULL) {
20908 		ASSERT(io->ipsec_out_policy != NULL);
20909 		a = io->ipsec_out_policy->ipsp_act;
20910 	}
20911 	ASSERT(a != NULL);
20912 
20913 	return (a->ipa_ovhd);
20914 }
20915 
20916 /*
20917  * Returns an estimate of the IPSEC headers size. This is used if
20918  * we don't want to call into IPSEC to get the exact size.
20919  */
20920 int
20921 ipsec_in_extra_length(mblk_t *ipsec_mp)
20922 {
20923 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
20924 	ipsec_action_t *a;
20925 
20926 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
20927 
20928 	a = ii->ipsec_in_action;
20929 	return (a == NULL ? 0 : a->ipa_ovhd);
20930 }
20931 
20932 /*
20933  * If there are any source route options, return the true final
20934  * destination. Otherwise, return the destination.
20935  */
20936 ipaddr_t
20937 ip_get_dst(ipha_t *ipha)
20938 {
20939 	ipoptp_t	opts;
20940 	uchar_t		*opt;
20941 	uint8_t		optval;
20942 	uint8_t		optlen;
20943 	ipaddr_t	dst;
20944 	uint32_t off;
20945 
20946 	dst = ipha->ipha_dst;
20947 
20948 	if (IS_SIMPLE_IPH(ipha))
20949 		return (dst);
20950 
20951 	for (optval = ipoptp_first(&opts, ipha);
20952 	    optval != IPOPT_EOL;
20953 	    optval = ipoptp_next(&opts)) {
20954 		opt = opts.ipoptp_cur;
20955 		optlen = opts.ipoptp_len;
20956 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20957 		switch (optval) {
20958 		case IPOPT_SSRR:
20959 		case IPOPT_LSRR:
20960 			off = opt[IPOPT_OFFSET];
20961 			/*
20962 			 * If one of the conditions is true, it means
20963 			 * end of options and dst already has the right
20964 			 * value.
20965 			 */
20966 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
20967 				off = optlen - IP_ADDR_LEN;
20968 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
20969 			}
20970 			return (dst);
20971 		default:
20972 			break;
20973 		}
20974 	}
20975 
20976 	return (dst);
20977 }
20978 
20979 mblk_t *
20980 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
20981     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
20982 {
20983 	ipsec_out_t	*io;
20984 	mblk_t		*first_mp;
20985 	boolean_t policy_present;
20986 
20987 	first_mp = mp;
20988 	if (mp->b_datap->db_type == M_CTL) {
20989 		io = (ipsec_out_t *)first_mp->b_rptr;
20990 		/*
20991 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
20992 		 *
20993 		 * 1) There is per-socket policy (including cached global
20994 		 *    policy).
20995 		 * 2) There is no per-socket policy, but it is
20996 		 *    a multicast packet that needs to go out
20997 		 *    on a specific interface. This is the case
20998 		 *    where (ip_wput and ip_wput_multicast) attaches
20999 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21000 		 *
21001 		 * In case (2) we check with global policy to
21002 		 * see if there is a match and set the ill_index
21003 		 * appropriately so that we can lookup the ire
21004 		 * properly in ip_wput_ipsec_out.
21005 		 */
21006 
21007 		/*
21008 		 * ipsec_out_use_global_policy is set to B_FALSE
21009 		 * in ipsec_in_to_out(). Refer to that function for
21010 		 * details.
21011 		 */
21012 		if ((io->ipsec_out_latch == NULL) &&
21013 		    (io->ipsec_out_use_global_policy)) {
21014 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21015 				    ire, connp, unspec_src, zoneid));
21016 		}
21017 		if (!io->ipsec_out_secure) {
21018 			/*
21019 			 * If this is not a secure packet, drop
21020 			 * the IPSEC_OUT mp and treat it as a clear
21021 			 * packet. This happens when we are sending
21022 			 * a ICMP reply back to a clear packet. See
21023 			 * ipsec_in_to_out() for details.
21024 			 */
21025 			mp = first_mp->b_cont;
21026 			freeb(first_mp);
21027 		}
21028 		return (mp);
21029 	}
21030 	/*
21031 	 * See whether we need to attach a global policy here. We
21032 	 * don't depend on the conn (as it could be null) for deciding
21033 	 * what policy this datagram should go through because it
21034 	 * should have happened in ip_wput if there was some
21035 	 * policy. This normally happens for connections which are not
21036 	 * fully bound preventing us from caching policies in
21037 	 * ip_bind. Packets coming from the TCP listener/global queue
21038 	 * - which are non-hard_bound - could also be affected by
21039 	 * applying policy here.
21040 	 *
21041 	 * If this packet is coming from tcp global queue or listener,
21042 	 * we will be applying policy here.  This may not be *right*
21043 	 * if these packets are coming from the detached connection as
21044 	 * it could have gone in clear before. This happens only if a
21045 	 * TCP connection started when there is no policy and somebody
21046 	 * added policy before it became detached. Thus packets of the
21047 	 * detached connection could go out secure and the other end
21048 	 * would drop it because it will be expecting in clear. The
21049 	 * converse is not true i.e if somebody starts a TCP
21050 	 * connection and deletes the policy, all the packets will
21051 	 * still go out with the policy that existed before deleting
21052 	 * because ip_unbind sends up policy information which is used
21053 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21054 	 * TCP to attach a dummy IPSEC_OUT and set
21055 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21056 	 * affect performance for normal cases, we are not doing it.
21057 	 * Thus, set policy before starting any TCP connections.
21058 	 *
21059 	 * NOTE - We might apply policy even for a hard bound connection
21060 	 * - for which we cached policy in ip_bind - if somebody added
21061 	 * global policy after we inherited the policy in ip_bind.
21062 	 * This means that the packets that were going out in clear
21063 	 * previously would start going secure and hence get dropped
21064 	 * on the other side. To fix this, TCP attaches a dummy
21065 	 * ipsec_out and make sure that we don't apply global policy.
21066 	 */
21067 	if (ipha != NULL)
21068 		policy_present = ipsec_outbound_v4_policy_present;
21069 	else
21070 		policy_present = ipsec_outbound_v6_policy_present;
21071 	if (!policy_present)
21072 		return (mp);
21073 
21074 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21075 		    zoneid));
21076 }
21077 
21078 ire_t *
21079 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21080 {
21081 	ipaddr_t addr;
21082 	ire_t *save_ire;
21083 	irb_t *irb;
21084 	ill_group_t *illgrp;
21085 	int	err;
21086 
21087 	save_ire = ire;
21088 	addr = ire->ire_addr;
21089 
21090 	ASSERT(ire->ire_type == IRE_BROADCAST);
21091 
21092 	illgrp = connp->conn_outgoing_ill->ill_group;
21093 	if (illgrp == NULL) {
21094 		*conn_outgoing_ill = conn_get_held_ill(connp,
21095 		    &connp->conn_outgoing_ill, &err);
21096 		if (err == ILL_LOOKUP_FAILED) {
21097 			ire_refrele(save_ire);
21098 			return (NULL);
21099 		}
21100 		return (save_ire);
21101 	}
21102 	/*
21103 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21104 	 * If it is part of the group, we need to send on the ire
21105 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21106 	 * to this group. This is okay as IP_BOUND_IF really means
21107 	 * any ill in the group. We depend on the fact that the
21108 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21109 	 * if such an ire exists. This is possible only if you have
21110 	 * at least one ill in the group that has not failed.
21111 	 *
21112 	 * First get to the ire that matches the address and group.
21113 	 *
21114 	 * We don't look for an ire with a matching zoneid because a given zone
21115 	 * won't always have broadcast ires on all ills in the group.
21116 	 */
21117 	irb = ire->ire_bucket;
21118 	rw_enter(&irb->irb_lock, RW_READER);
21119 	if (ire->ire_marks & IRE_MARK_NORECV) {
21120 		/*
21121 		 * If the current zone only has an ire broadcast for this
21122 		 * address marked NORECV, the ire we want is ahead in the
21123 		 * bucket, so we look it up deliberately ignoring the zoneid.
21124 		 */
21125 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21126 			if (ire->ire_addr != addr)
21127 				continue;
21128 			/* skip over deleted ires */
21129 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21130 				continue;
21131 		}
21132 	}
21133 	while (ire != NULL) {
21134 		/*
21135 		 * If a new interface is coming up, we could end up
21136 		 * seeing the loopback ire and the non-loopback ire
21137 		 * may not have been added yet. So check for ire_stq
21138 		 */
21139 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21140 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21141 			break;
21142 		}
21143 		ire = ire->ire_next;
21144 	}
21145 	if (ire != NULL && ire->ire_addr == addr &&
21146 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21147 		IRE_REFHOLD(ire);
21148 		rw_exit(&irb->irb_lock);
21149 		ire_refrele(save_ire);
21150 		*conn_outgoing_ill = ire_to_ill(ire);
21151 		/*
21152 		 * Refhold the ill to make the conn_outgoing_ill
21153 		 * independent of the ire. ip_wput_ire goes in a loop
21154 		 * and may refrele the ire. Since we have an ire at this
21155 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21156 		 */
21157 		ill_refhold(*conn_outgoing_ill);
21158 		return (ire);
21159 	}
21160 	rw_exit(&irb->irb_lock);
21161 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21162 	/*
21163 	 * If we can't find a suitable ire, return the original ire.
21164 	 */
21165 	return (save_ire);
21166 }
21167 
21168 /*
21169  * This function does the ire_refrele of the ire passed in as the
21170  * argument. As this function looks up more ires i.e broadcast ires,
21171  * it needs to REFRELE them. Currently, for simplicity we don't
21172  * differentiate the one passed in and looked up here. We always
21173  * REFRELE.
21174  * IPQoS Notes:
21175  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21176  * IPSec packets are done in ipsec_out_process.
21177  *
21178  */
21179 void
21180 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21181     zoneid_t zoneid)
21182 {
21183 	ipha_t		*ipha;
21184 #define	rptr	((uchar_t *)ipha)
21185 	queue_t		*stq;
21186 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21187 	uint32_t	v_hlen_tos_len;
21188 	uint32_t	ttl_protocol;
21189 	ipaddr_t	src;
21190 	ipaddr_t	dst;
21191 	uint32_t	cksum;
21192 	ipaddr_t	orig_src;
21193 	ire_t		*ire1;
21194 	mblk_t		*next_mp;
21195 	uint_t		hlen;
21196 	uint16_t	*up;
21197 	uint32_t	max_frag = ire->ire_max_frag;
21198 	ill_t		*ill = ire_to_ill(ire);
21199 	int		clusterwide;
21200 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21201 	int		ipsec_len;
21202 	mblk_t		*first_mp;
21203 	ipsec_out_t	*io;
21204 	boolean_t	conn_dontroute;		/* conn value for multicast */
21205 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21206 	boolean_t	multicast_forward;	/* Should we forward ? */
21207 	boolean_t	unspec_src;
21208 	ill_t		*conn_outgoing_ill = NULL;
21209 	ill_t		*ire_ill;
21210 	ill_t		*ire1_ill;
21211 	uint32_t 	ill_index = 0;
21212 	boolean_t	multirt_send = B_FALSE;
21213 	int		err;
21214 	ipxmit_state_t	pktxmit_state;
21215 
21216 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21217 	    "ip_wput_ire_start: q %p", q);
21218 
21219 	multicast_forward = B_FALSE;
21220 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21221 
21222 	if (ire->ire_flags & RTF_MULTIRT) {
21223 		/*
21224 		 * Multirouting case. The bucket where ire is stored
21225 		 * probably holds other RTF_MULTIRT flagged ire
21226 		 * to the destination. In this call to ip_wput_ire,
21227 		 * we attempt to send the packet through all
21228 		 * those ires. Thus, we first ensure that ire is the
21229 		 * first RTF_MULTIRT ire in the bucket,
21230 		 * before walking the ire list.
21231 		 */
21232 		ire_t *first_ire;
21233 		irb_t *irb = ire->ire_bucket;
21234 		ASSERT(irb != NULL);
21235 
21236 		/* Make sure we do not omit any multiroute ire. */
21237 		IRB_REFHOLD(irb);
21238 		for (first_ire = irb->irb_ire;
21239 		    first_ire != NULL;
21240 		    first_ire = first_ire->ire_next) {
21241 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21242 			    (first_ire->ire_addr == ire->ire_addr) &&
21243 			    !(first_ire->ire_marks &
21244 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21245 				break;
21246 		}
21247 
21248 		if ((first_ire != NULL) && (first_ire != ire)) {
21249 			IRE_REFHOLD(first_ire);
21250 			ire_refrele(ire);
21251 			ire = first_ire;
21252 			ill = ire_to_ill(ire);
21253 		}
21254 		IRB_REFRELE(irb);
21255 	}
21256 
21257 	/*
21258 	 * conn_outgoing_ill is used only in the broadcast loop.
21259 	 * for performance we don't grab the mutexs in the fastpath
21260 	 */
21261 	if ((connp != NULL) &&
21262 	    (connp->conn_xmit_if_ill == NULL) &&
21263 	    (ire->ire_type == IRE_BROADCAST) &&
21264 	    ((connp->conn_nofailover_ill != NULL) ||
21265 	    (connp->conn_outgoing_ill != NULL))) {
21266 		/*
21267 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21268 		 * option. So, see if this endpoint is bound to a
21269 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21270 		 * that if the interface is failed, we will still send
21271 		 * the packet on the same ill which is what we want.
21272 		 */
21273 		conn_outgoing_ill = conn_get_held_ill(connp,
21274 		    &connp->conn_nofailover_ill, &err);
21275 		if (err == ILL_LOOKUP_FAILED) {
21276 			ire_refrele(ire);
21277 			freemsg(mp);
21278 			return;
21279 		}
21280 		if (conn_outgoing_ill == NULL) {
21281 			/*
21282 			 * Choose a good ill in the group to send the
21283 			 * packets on.
21284 			 */
21285 			ire = conn_set_outgoing_ill(connp, ire,
21286 			    &conn_outgoing_ill);
21287 			if (ire == NULL) {
21288 				freemsg(mp);
21289 				return;
21290 			}
21291 		}
21292 	}
21293 
21294 	if (mp->b_datap->db_type != M_CTL) {
21295 		ipha = (ipha_t *)mp->b_rptr;
21296 	} else {
21297 		io = (ipsec_out_t *)mp->b_rptr;
21298 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21299 		ASSERT(zoneid == io->ipsec_out_zoneid);
21300 		ASSERT(zoneid != ALL_ZONES);
21301 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21302 		dst = ipha->ipha_dst;
21303 		/*
21304 		 * For the multicast case, ipsec_out carries conn_dontroute and
21305 		 * conn_multicast_loop as conn may not be available here. We
21306 		 * need this for multicast loopback and forwarding which is done
21307 		 * later in the code.
21308 		 */
21309 		if (CLASSD(dst)) {
21310 			conn_dontroute = io->ipsec_out_dontroute;
21311 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21312 			/*
21313 			 * If conn_dontroute is not set or conn_multicast_loop
21314 			 * is set, we need to do forwarding/loopback. For
21315 			 * datagrams from ip_wput_multicast, conn_dontroute is
21316 			 * set to B_TRUE and conn_multicast_loop is set to
21317 			 * B_FALSE so that we neither do forwarding nor
21318 			 * loopback.
21319 			 */
21320 			if (!conn_dontroute || conn_multicast_loop)
21321 				multicast_forward = B_TRUE;
21322 		}
21323 	}
21324 
21325 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21326 	    ire->ire_zoneid != ALL_ZONES) {
21327 		/*
21328 		 * When a zone sends a packet to another zone, we try to deliver
21329 		 * the packet under the same conditions as if the destination
21330 		 * was a real node on the network. To do so, we look for a
21331 		 * matching route in the forwarding table.
21332 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21333 		 * ip_newroute() does.
21334 		 * Note that IRE_LOCAL are special, since they are used
21335 		 * when the zoneid doesn't match in some cases. This means that
21336 		 * we need to handle ipha_src differently since ire_src_addr
21337 		 * belongs to the receiving zone instead of the sending zone.
21338 		 * When ip_restrict_interzone_loopback is set, then
21339 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
21340 		 * for loopback between zones when the logical "Ethernet" would
21341 		 * have looped them back.
21342 		 */
21343 		ire_t *src_ire;
21344 
21345 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21346 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21347 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
21348 		if (src_ire != NULL &&
21349 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
21350 		    (!ip_restrict_interzone_loopback ||
21351 		    ire_local_same_ill_group(ire, src_ire))) {
21352 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21353 				ipha->ipha_src = src_ire->ire_src_addr;
21354 			ire_refrele(src_ire);
21355 		} else {
21356 			ire_refrele(ire);
21357 			if (conn_outgoing_ill != NULL)
21358 				ill_refrele(conn_outgoing_ill);
21359 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
21360 			if (src_ire != NULL) {
21361 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21362 					ire_refrele(src_ire);
21363 					freemsg(mp);
21364 					return;
21365 				}
21366 				ire_refrele(src_ire);
21367 			}
21368 			if (ip_hdr_complete(ipha, zoneid)) {
21369 				/* Failed */
21370 				freemsg(mp);
21371 				return;
21372 			}
21373 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid);
21374 			return;
21375 		}
21376 	}
21377 
21378 	if (mp->b_datap->db_type == M_CTL ||
21379 	    ipsec_outbound_v4_policy_present) {
21380 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21381 		    unspec_src, zoneid);
21382 		if (mp == NULL) {
21383 			ire_refrele(ire);
21384 			if (conn_outgoing_ill != NULL)
21385 				ill_refrele(conn_outgoing_ill);
21386 			return;
21387 		}
21388 	}
21389 
21390 	first_mp = mp;
21391 	ipsec_len = 0;
21392 
21393 	if (first_mp->b_datap->db_type == M_CTL) {
21394 		io = (ipsec_out_t *)first_mp->b_rptr;
21395 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21396 		mp = first_mp->b_cont;
21397 		ipsec_len = ipsec_out_extra_length(first_mp);
21398 		ASSERT(ipsec_len >= 0);
21399 		/* We already picked up the zoneid from the M_CTL above */
21400 		ASSERT(zoneid == io->ipsec_out_zoneid);
21401 		ASSERT(zoneid != ALL_ZONES);
21402 
21403 		/*
21404 		 * Drop M_CTL here if IPsec processing is not needed.
21405 		 * (Non-IPsec use of M_CTL extracted any information it
21406 		 * needed above).
21407 		 */
21408 		if (ipsec_len == 0) {
21409 			freeb(first_mp);
21410 			first_mp = mp;
21411 		}
21412 	}
21413 
21414 	/*
21415 	 * Fast path for ip_wput_ire
21416 	 */
21417 
21418 	ipha = (ipha_t *)mp->b_rptr;
21419 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21420 	dst = ipha->ipha_dst;
21421 
21422 	/*
21423 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21424 	 * if the socket is a SOCK_RAW type. The transport checksum should
21425 	 * be provided in the pre-built packet, so we don't need to compute it.
21426 	 * Also, other application set flags, like DF, should not be altered.
21427 	 * Other transport MUST pass down zero.
21428 	 */
21429 	ip_hdr_included = ipha->ipha_ident;
21430 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21431 
21432 	if (CLASSD(dst)) {
21433 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
21434 		    ntohl(dst),
21435 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
21436 		    ntohl(ire->ire_addr)));
21437 	}
21438 
21439 /* Macros to extract header fields from data already in registers */
21440 #ifdef	_BIG_ENDIAN
21441 #define	V_HLEN	(v_hlen_tos_len >> 24)
21442 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21443 #define	PROTO	(ttl_protocol & 0xFF)
21444 #else
21445 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21446 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21447 #define	PROTO	(ttl_protocol >> 8)
21448 #endif
21449 
21450 
21451 	orig_src = src = ipha->ipha_src;
21452 	/* (The loop back to "another" is explained down below.) */
21453 another:;
21454 	/*
21455 	 * Assign an ident value for this packet.  We assign idents on
21456 	 * a per destination basis out of the IRE.  There could be
21457 	 * other threads targeting the same destination, so we have to
21458 	 * arrange for a atomic increment.  Note that we use a 32-bit
21459 	 * atomic add because it has better performance than its
21460 	 * 16-bit sibling.
21461 	 *
21462 	 * If running in cluster mode and if the source address
21463 	 * belongs to a replicated service then vector through
21464 	 * cl_inet_ipident vector to allocate ip identifier
21465 	 * NOTE: This is a contract private interface with the
21466 	 * clustering group.
21467 	 */
21468 	clusterwide = 0;
21469 	if (cl_inet_ipident) {
21470 		ASSERT(cl_inet_isclusterwide);
21471 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21472 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
21473 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
21474 			    AF_INET, (uint8_t *)(uintptr_t)src,
21475 			    (uint8_t *)(uintptr_t)dst);
21476 			clusterwide = 1;
21477 		}
21478 	}
21479 	if (!clusterwide) {
21480 		ipha->ipha_ident =
21481 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
21482 	}
21483 
21484 #ifndef _BIG_ENDIAN
21485 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21486 #endif
21487 
21488 	/*
21489 	 * Set source address unless sent on an ill or conn_unspec_src is set.
21490 	 * This is needed to obey conn_unspec_src when packets go through
21491 	 * ip_newroute + arp.
21492 	 * Assumes ip_newroute{,_multi} sets the source address as well.
21493 	 */
21494 	if (src == INADDR_ANY && !unspec_src) {
21495 		/*
21496 		 * Assign the appropriate source address from the IRE if none
21497 		 * was specified.
21498 		 */
21499 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
21500 
21501 		/*
21502 		 * With IP multipathing, broadcast packets are sent on the ire
21503 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
21504 		 * the group. However, this ire might not be in the same zone so
21505 		 * we can't always use its source address. We look for a
21506 		 * broadcast ire in the same group and in the right zone.
21507 		 */
21508 		if (ire->ire_type == IRE_BROADCAST &&
21509 		    ire->ire_zoneid != zoneid) {
21510 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
21511 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
21512 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
21513 			if (src_ire != NULL) {
21514 				src = src_ire->ire_src_addr;
21515 				ire_refrele(src_ire);
21516 			} else {
21517 				ire_refrele(ire);
21518 				if (conn_outgoing_ill != NULL)
21519 					ill_refrele(conn_outgoing_ill);
21520 				freemsg(first_mp);
21521 				BUMP_MIB(&ip_mib, ipOutDiscards);
21522 				return;
21523 			}
21524 		} else {
21525 			src = ire->ire_src_addr;
21526 		}
21527 
21528 		if (connp == NULL) {
21529 			ip1dbg(("ip_wput_ire: no connp and no src "
21530 			    "address for dst 0x%x, using src 0x%x\n",
21531 			    ntohl(dst),
21532 			    ntohl(src)));
21533 		}
21534 		ipha->ipha_src = src;
21535 	}
21536 	stq = ire->ire_stq;
21537 
21538 	/*
21539 	 * We only allow ire chains for broadcasts since there will
21540 	 * be multiple IRE_CACHE entries for the same multicast
21541 	 * address (one per ipif).
21542 	 */
21543 	next_mp = NULL;
21544 
21545 	/* broadcast packet */
21546 	if (ire->ire_type == IRE_BROADCAST)
21547 		goto broadcast;
21548 
21549 	/* loopback ? */
21550 	if (stq == NULL)
21551 		goto nullstq;
21552 
21553 	/* The ill_index for outbound ILL */
21554 	ill_index = Q_TO_INDEX(stq);
21555 
21556 	BUMP_MIB(&ip_mib, ipOutRequests);
21557 	ttl_protocol = ((uint16_t *)ipha)[4];
21558 
21559 	/* pseudo checksum (do it in parts for IP header checksum) */
21560 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21561 
21562 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
21563 		queue_t *dev_q = stq->q_next;
21564 
21565 		/* flow controlled */
21566 		if ((dev_q->q_next || dev_q->q_first) &&
21567 		    !canput(dev_q))
21568 			goto blocked;
21569 		if ((PROTO == IPPROTO_UDP) &&
21570 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21571 			hlen = (V_HLEN & 0xF) << 2;
21572 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21573 			if (*up != 0) {
21574 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
21575 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
21576 				/* Software checksum? */
21577 				if (DB_CKSUMFLAGS(mp) == 0) {
21578 					IP_STAT(ip_out_sw_cksum);
21579 					IP_STAT_UPDATE(
21580 					    ip_udp_out_sw_cksum_bytes,
21581 					    LENGTH - hlen);
21582 				}
21583 			}
21584 		}
21585 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
21586 		hlen = (V_HLEN & 0xF) << 2;
21587 		if (PROTO == IPPROTO_TCP) {
21588 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21589 			/*
21590 			 * The packet header is processed once and for all, even
21591 			 * in the multirouting case. We disable hardware
21592 			 * checksum if the packet is multirouted, as it will be
21593 			 * replicated via several interfaces, and not all of
21594 			 * them may have this capability.
21595 			 */
21596 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
21597 			    LENGTH, max_frag, ipsec_len, cksum);
21598 			/* Software checksum? */
21599 			if (DB_CKSUMFLAGS(mp) == 0) {
21600 				IP_STAT(ip_out_sw_cksum);
21601 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21602 				    LENGTH - hlen);
21603 			}
21604 		} else {
21605 			sctp_hdr_t	*sctph;
21606 
21607 			ASSERT(PROTO == IPPROTO_SCTP);
21608 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21609 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21610 			/*
21611 			 * Zero out the checksum field to ensure proper
21612 			 * checksum calculation.
21613 			 */
21614 			sctph->sh_chksum = 0;
21615 #ifdef	DEBUG
21616 			if (!skip_sctp_cksum)
21617 #endif
21618 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21619 		}
21620 	}
21621 
21622 	/*
21623 	 * If this is a multicast packet and originated from ip_wput
21624 	 * we need to do loopback and forwarding checks. If it comes
21625 	 * from ip_wput_multicast, we SHOULD not do this.
21626 	 */
21627 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
21628 
21629 	/* checksum */
21630 	cksum += ttl_protocol;
21631 
21632 	/* fragment the packet */
21633 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
21634 		goto fragmentit;
21635 	/*
21636 	 * Don't use frag_flag if packet is pre-built or source
21637 	 * routed or if multicast (since multicast packets do
21638 	 * not solicit ICMP "packet too big" messages).
21639 	 */
21640 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21641 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21642 	    !ip_source_route_included(ipha)) &&
21643 	    !CLASSD(ipha->ipha_dst))
21644 		ipha->ipha_fragment_offset_and_flags |=
21645 		    htons(ire->ire_frag_flag);
21646 
21647 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21648 		/* calculate IP header checksum */
21649 		cksum += ipha->ipha_ident;
21650 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
21651 		cksum += ipha->ipha_fragment_offset_and_flags;
21652 
21653 		/* IP options present */
21654 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21655 		if (hlen)
21656 			goto checksumoptions;
21657 
21658 		/* calculate hdr checksum */
21659 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21660 		cksum = ~(cksum + (cksum >> 16));
21661 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
21662 	}
21663 	if (ipsec_len != 0) {
21664 		/*
21665 		 * We will do the rest of the processing after
21666 		 * we come back from IPSEC in ip_wput_ipsec_out().
21667 		 */
21668 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
21669 
21670 		io = (ipsec_out_t *)first_mp->b_rptr;
21671 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
21672 				ill_phyint->phyint_ifindex;
21673 
21674 		ipsec_out_process(q, first_mp, ire, ill_index);
21675 		ire_refrele(ire);
21676 		if (conn_outgoing_ill != NULL)
21677 			ill_refrele(conn_outgoing_ill);
21678 		return;
21679 	}
21680 
21681 	/*
21682 	 * In most cases, the emission loop below is entered only
21683 	 * once. Only in the case where the ire holds the
21684 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
21685 	 * flagged ires in the bucket, and send the packet
21686 	 * through all crossed RTF_MULTIRT routes.
21687 	 */
21688 	if (ire->ire_flags & RTF_MULTIRT) {
21689 		multirt_send = B_TRUE;
21690 	}
21691 	do {
21692 		if (multirt_send) {
21693 			irb_t *irb;
21694 			/*
21695 			 * We are in a multiple send case, need to get
21696 			 * the next ire and make a duplicate of the packet.
21697 			 * ire1 holds here the next ire to process in the
21698 			 * bucket. If multirouting is expected,
21699 			 * any non-RTF_MULTIRT ire that has the
21700 			 * right destination address is ignored.
21701 			 */
21702 			irb = ire->ire_bucket;
21703 			ASSERT(irb != NULL);
21704 
21705 			IRB_REFHOLD(irb);
21706 			for (ire1 = ire->ire_next;
21707 			    ire1 != NULL;
21708 			    ire1 = ire1->ire_next) {
21709 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21710 					continue;
21711 				if (ire1->ire_addr != ire->ire_addr)
21712 					continue;
21713 				if (ire1->ire_marks &
21714 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21715 					continue;
21716 
21717 				/* Got one */
21718 				IRE_REFHOLD(ire1);
21719 				break;
21720 			}
21721 			IRB_REFRELE(irb);
21722 
21723 			if (ire1 != NULL) {
21724 				next_mp = copyb(mp);
21725 				if ((next_mp == NULL) ||
21726 				    ((mp->b_cont != NULL) &&
21727 				    ((next_mp->b_cont =
21728 				    dupmsg(mp->b_cont)) == NULL))) {
21729 					freemsg(next_mp);
21730 					next_mp = NULL;
21731 					ire_refrele(ire1);
21732 					ire1 = NULL;
21733 				}
21734 			}
21735 
21736 			/* Last multiroute ire; don't loop anymore. */
21737 			if (ire1 == NULL) {
21738 				multirt_send = B_FALSE;
21739 			}
21740 		}
21741 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
21742 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
21743 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
21744 		if ((pktxmit_state == SEND_FAILED) ||
21745 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
21746 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
21747 			    "- packet dropped\n"));
21748 			ire_refrele(ire);
21749 			if (next_mp != NULL) {
21750 				freemsg(next_mp);
21751 				ire_refrele(ire1);
21752 			}
21753 			if (conn_outgoing_ill != NULL)
21754 				ill_refrele(conn_outgoing_ill);
21755 			return;
21756 		}
21757 
21758 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21759 		    "ip_wput_ire_end: q %p (%S)",
21760 		    q, "last copy out");
21761 		IRE_REFRELE(ire);
21762 
21763 		if (multirt_send) {
21764 			ASSERT(ire1);
21765 			/*
21766 			 * Proceed with the next RTF_MULTIRT ire,
21767 			 * Also set up the send-to queue accordingly.
21768 			 */
21769 			ire = ire1;
21770 			ire1 = NULL;
21771 			stq = ire->ire_stq;
21772 			mp = next_mp;
21773 			next_mp = NULL;
21774 			ipha = (ipha_t *)mp->b_rptr;
21775 			ill_index = Q_TO_INDEX(stq);
21776 		}
21777 	} while (multirt_send);
21778 	if (conn_outgoing_ill != NULL)
21779 		ill_refrele(conn_outgoing_ill);
21780 	return;
21781 
21782 	/*
21783 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
21784 	 */
21785 broadcast:
21786 	{
21787 		/*
21788 		 * Avoid broadcast storms by setting the ttl to 1
21789 		 * for broadcasts. This parameter can be set
21790 		 * via ndd, so make sure that for the SO_DONTROUTE
21791 		 * case that ipha_ttl is always set to 1.
21792 		 * In the event that we are replying to incoming
21793 		 * ICMP packets, conn could be NULL.
21794 		 */
21795 		if ((connp != NULL) && connp->conn_dontroute)
21796 			ipha->ipha_ttl = 1;
21797 		else
21798 			ipha->ipha_ttl = ip_broadcast_ttl;
21799 
21800 		/*
21801 		 * Note that we are not doing a IRB_REFHOLD here.
21802 		 * Actually we don't care if the list changes i.e
21803 		 * if somebody deletes an IRE from the list while
21804 		 * we drop the lock, the next time we come around
21805 		 * ire_next will be NULL and hence we won't send
21806 		 * out multiple copies which is fine.
21807 		 */
21808 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
21809 		ire1 = ire->ire_next;
21810 		if (conn_outgoing_ill != NULL) {
21811 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
21812 				ASSERT(ire1 == ire->ire_next);
21813 				if (ire1 != NULL && ire1->ire_addr == dst) {
21814 					ire_refrele(ire);
21815 					ire = ire1;
21816 					IRE_REFHOLD(ire);
21817 					ire1 = ire->ire_next;
21818 					continue;
21819 				}
21820 				rw_exit(&ire->ire_bucket->irb_lock);
21821 				/* Did not find a matching ill */
21822 				ip1dbg(("ip_wput_ire: broadcast with no "
21823 				    "matching IP_BOUND_IF ill %s\n",
21824 				    conn_outgoing_ill->ill_name));
21825 				freemsg(first_mp);
21826 				if (ire != NULL)
21827 					ire_refrele(ire);
21828 				ill_refrele(conn_outgoing_ill);
21829 				return;
21830 			}
21831 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
21832 			/*
21833 			 * If the next IRE has the same address and is not one
21834 			 * of the two copies that we need to send, try to see
21835 			 * whether this copy should be sent at all. This
21836 			 * assumes that we insert loopbacks first and then
21837 			 * non-loopbacks. This is acheived by inserting the
21838 			 * loopback always before non-loopback.
21839 			 * This is used to send a single copy of a broadcast
21840 			 * packet out all physical interfaces that have an
21841 			 * matching IRE_BROADCAST while also looping
21842 			 * back one copy (to ip_wput_local) for each
21843 			 * matching physical interface. However, we avoid
21844 			 * sending packets out different logical that match by
21845 			 * having ipif_up/ipif_down supress duplicate
21846 			 * IRE_BROADCASTS.
21847 			 *
21848 			 * This feature is currently used to get broadcasts
21849 			 * sent to multiple interfaces, when the broadcast
21850 			 * address being used applies to multiple interfaces.
21851 			 * For example, a whole net broadcast will be
21852 			 * replicated on every connected subnet of
21853 			 * the target net.
21854 			 *
21855 			 * Each zone has its own set of IRE_BROADCASTs, so that
21856 			 * we're able to distribute inbound packets to multiple
21857 			 * zones who share a broadcast address. We avoid looping
21858 			 * back outbound packets in different zones but on the
21859 			 * same ill, as the application would see duplicates.
21860 			 *
21861 			 * If the interfaces are part of the same group,
21862 			 * we would want to send only one copy out for
21863 			 * whole group.
21864 			 *
21865 			 * This logic assumes that ire_add_v4() groups the
21866 			 * IRE_BROADCAST entries so that those with the same
21867 			 * ire_addr and ill_group are kept together.
21868 			 */
21869 			ire_ill = ire->ire_ipif->ipif_ill;
21870 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
21871 				if (ire_ill->ill_group != NULL &&
21872 				    (ire->ire_marks & IRE_MARK_NORECV)) {
21873 					/*
21874 					 * If the current zone only has an ire
21875 					 * broadcast for this address marked
21876 					 * NORECV, the ire we want is ahead in
21877 					 * the bucket, so we look it up
21878 					 * deliberately ignoring the zoneid.
21879 					 */
21880 					for (ire1 = ire->ire_bucket->irb_ire;
21881 					    ire1 != NULL;
21882 					    ire1 = ire1->ire_next) {
21883 						ire1_ill =
21884 						    ire1->ire_ipif->ipif_ill;
21885 						if (ire1->ire_addr != dst)
21886 							continue;
21887 						/* skip over the current ire */
21888 						if (ire1 == ire)
21889 							continue;
21890 						/* skip over deleted ires */
21891 						if (ire1->ire_marks &
21892 						    IRE_MARK_CONDEMNED)
21893 							continue;
21894 						/*
21895 						 * non-loopback ire in our
21896 						 * group: use it for the next
21897 						 * pass in the loop
21898 						 */
21899 						if (ire1->ire_stq != NULL &&
21900 						    ire1_ill->ill_group ==
21901 						    ire_ill->ill_group)
21902 							break;
21903 					}
21904 				}
21905 			} else {
21906 				while (ire1 != NULL && ire1->ire_addr == dst) {
21907 					ire1_ill = ire1->ire_ipif->ipif_ill;
21908 					/*
21909 					 * We can have two broadcast ires on the
21910 					 * same ill in different zones; here
21911 					 * we'll send a copy of the packet on
21912 					 * each ill and the fanout code will
21913 					 * call conn_wantpacket() to check that
21914 					 * the zone has the broadcast address
21915 					 * configured on the ill. If the two
21916 					 * ires are in the same group we only
21917 					 * send one copy up.
21918 					 */
21919 					if (ire1_ill != ire_ill &&
21920 					    (ire1_ill->ill_group == NULL ||
21921 					    ire_ill->ill_group == NULL ||
21922 					    ire1_ill->ill_group !=
21923 					    ire_ill->ill_group)) {
21924 						break;
21925 					}
21926 					ire1 = ire1->ire_next;
21927 				}
21928 			}
21929 		}
21930 		ASSERT(multirt_send == B_FALSE);
21931 		if (ire1 != NULL && ire1->ire_addr == dst) {
21932 			if ((ire->ire_flags & RTF_MULTIRT) &&
21933 			    (ire1->ire_flags & RTF_MULTIRT)) {
21934 				/*
21935 				 * We are in the multirouting case.
21936 				 * The message must be sent at least
21937 				 * on both ires. These ires have been
21938 				 * inserted AFTER the standard ones
21939 				 * in ip_rt_add(). There are thus no
21940 				 * other ire entries for the destination
21941 				 * address in the rest of the bucket
21942 				 * that do not have the RTF_MULTIRT
21943 				 * flag. We don't process a copy
21944 				 * of the message here. This will be
21945 				 * done in the final sending loop.
21946 				 */
21947 				multirt_send = B_TRUE;
21948 			} else {
21949 				next_mp = ip_copymsg(first_mp);
21950 				if (next_mp != NULL)
21951 					IRE_REFHOLD(ire1);
21952 			}
21953 		}
21954 		rw_exit(&ire->ire_bucket->irb_lock);
21955 	}
21956 
21957 	if (stq) {
21958 		/*
21959 		 * A non-NULL send-to queue means this packet is going
21960 		 * out of this machine.
21961 		 */
21962 
21963 		BUMP_MIB(&ip_mib, ipOutRequests);
21964 		ttl_protocol = ((uint16_t *)ipha)[4];
21965 		/*
21966 		 * We accumulate the pseudo header checksum in cksum.
21967 		 * This is pretty hairy code, so watch close.  One
21968 		 * thing to keep in mind is that UDP and TCP have
21969 		 * stored their respective datagram lengths in their
21970 		 * checksum fields.  This lines things up real nice.
21971 		 */
21972 		cksum = (dst >> 16) + (dst & 0xFFFF) +
21973 		    (src >> 16) + (src & 0xFFFF);
21974 		/*
21975 		 * We assume the udp checksum field contains the
21976 		 * length, so to compute the pseudo header checksum,
21977 		 * all we need is the protocol number and src/dst.
21978 		 */
21979 		/* Provide the checksums for UDP and TCP. */
21980 		if ((PROTO == IPPROTO_TCP) &&
21981 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21982 			/* hlen gets the number of uchar_ts in the IP header */
21983 			hlen = (V_HLEN & 0xF) << 2;
21984 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21985 			IP_STAT(ip_out_sw_cksum);
21986 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21987 			    LENGTH - hlen);
21988 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
21989 			if (*up == 0)
21990 				*up = 0xFFFF;
21991 		} else if (PROTO == IPPROTO_SCTP &&
21992 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21993 			sctp_hdr_t	*sctph;
21994 
21995 			hlen = (V_HLEN & 0xF) << 2;
21996 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21997 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21998 			sctph->sh_chksum = 0;
21999 #ifdef	DEBUG
22000 			if (!skip_sctp_cksum)
22001 #endif
22002 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22003 		} else {
22004 			queue_t *dev_q = stq->q_next;
22005 
22006 			if ((dev_q->q_next || dev_q->q_first) &&
22007 			    !canput(dev_q)) {
22008 			    blocked:
22009 				ipha->ipha_ident = ip_hdr_included;
22010 				/*
22011 				 * If we don't have a conn to apply
22012 				 * backpressure, free the message.
22013 				 * In the ire_send path, we don't know
22014 				 * the position to requeue the packet. Rather
22015 				 * than reorder packets, we just drop this
22016 				 * packet.
22017 				 */
22018 				if (ip_output_queue && connp != NULL &&
22019 				    caller != IRE_SEND) {
22020 					if (caller == IP_WSRV) {
22021 						connp->conn_did_putbq = 1;
22022 						(void) putbq(connp->conn_wq,
22023 						    first_mp);
22024 						conn_drain_insert(connp);
22025 						/*
22026 						 * This is the service thread,
22027 						 * and the queue is already
22028 						 * noenabled. The check for
22029 						 * canput and the putbq is not
22030 						 * atomic. So we need to check
22031 						 * again.
22032 						 */
22033 						if (canput(stq->q_next))
22034 							connp->conn_did_putbq
22035 							    = 0;
22036 						IP_STAT(ip_conn_flputbq);
22037 					} else {
22038 						/*
22039 						 * We are not the service proc.
22040 						 * ip_wsrv will be scheduled or
22041 						 * is already running.
22042 						 */
22043 						(void) putq(connp->conn_wq,
22044 						    first_mp);
22045 					}
22046 				} else {
22047 					BUMP_MIB(&ip_mib, ipOutDiscards);
22048 					freemsg(first_mp);
22049 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22050 					    "ip_wput_ire_end: q %p (%S)",
22051 					    q, "discard");
22052 				}
22053 				ire_refrele(ire);
22054 				if (next_mp) {
22055 					ire_refrele(ire1);
22056 					freemsg(next_mp);
22057 				}
22058 				if (conn_outgoing_ill != NULL)
22059 					ill_refrele(conn_outgoing_ill);
22060 				return;
22061 			}
22062 			if ((PROTO == IPPROTO_UDP) &&
22063 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22064 				/*
22065 				 * hlen gets the number of uchar_ts in the
22066 				 * IP header
22067 				 */
22068 				hlen = (V_HLEN & 0xF) << 2;
22069 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22070 				max_frag = ire->ire_max_frag;
22071 				if (*up != 0) {
22072 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22073 					    up, PROTO, hlen, LENGTH, max_frag,
22074 					    ipsec_len, cksum);
22075 					/* Software checksum? */
22076 					if (DB_CKSUMFLAGS(mp) == 0) {
22077 						IP_STAT(ip_out_sw_cksum);
22078 						IP_STAT_UPDATE(
22079 						    ip_udp_out_sw_cksum_bytes,
22080 						    LENGTH - hlen);
22081 					}
22082 				}
22083 			}
22084 		}
22085 		/*
22086 		 * Need to do this even when fragmenting. The local
22087 		 * loopback can be done without computing checksums
22088 		 * but forwarding out other interface must be done
22089 		 * after the IP checksum (and ULP checksums) have been
22090 		 * computed.
22091 		 *
22092 		 * NOTE : multicast_forward is set only if this packet
22093 		 * originated from ip_wput. For packets originating from
22094 		 * ip_wput_multicast, it is not set.
22095 		 */
22096 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22097 		    multi_loopback:
22098 			ip2dbg(("ip_wput: multicast, loop %d\n",
22099 			    conn_multicast_loop));
22100 
22101 			/*  Forget header checksum offload */
22102 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22103 
22104 			/*
22105 			 * Local loopback of multicasts?  Check the
22106 			 * ill.
22107 			 *
22108 			 * Note that the loopback function will not come
22109 			 * in through ip_rput - it will only do the
22110 			 * client fanout thus we need to do an mforward
22111 			 * as well.  The is different from the BSD
22112 			 * logic.
22113 			 */
22114 			if (ill != NULL) {
22115 				ilm_t	*ilm;
22116 
22117 				ILM_WALKER_HOLD(ill);
22118 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22119 				    ALL_ZONES);
22120 				ILM_WALKER_RELE(ill);
22121 				if (ilm != NULL) {
22122 					/*
22123 					 * Pass along the virtual output q.
22124 					 * ip_wput_local() will distribute the
22125 					 * packet to all the matching zones,
22126 					 * except the sending zone when
22127 					 * IP_MULTICAST_LOOP is false.
22128 					 */
22129 					ip_multicast_loopback(q, ill, first_mp,
22130 					    conn_multicast_loop ? 0 :
22131 					    IP_FF_NO_MCAST_LOOP, zoneid);
22132 				}
22133 			}
22134 			if (ipha->ipha_ttl == 0) {
22135 				/*
22136 				 * 0 => only to this host i.e. we are
22137 				 * done. We are also done if this was the
22138 				 * loopback interface since it is sufficient
22139 				 * to loopback one copy of a multicast packet.
22140 				 */
22141 				freemsg(first_mp);
22142 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22143 				    "ip_wput_ire_end: q %p (%S)",
22144 				    q, "loopback");
22145 				ire_refrele(ire);
22146 				if (conn_outgoing_ill != NULL)
22147 					ill_refrele(conn_outgoing_ill);
22148 				return;
22149 			}
22150 			/*
22151 			 * ILLF_MULTICAST is checked in ip_newroute
22152 			 * i.e. we don't need to check it here since
22153 			 * all IRE_CACHEs come from ip_newroute.
22154 			 * For multicast traffic, SO_DONTROUTE is interpreted
22155 			 * to mean only send the packet out the interface
22156 			 * (optionally specified with IP_MULTICAST_IF)
22157 			 * and do not forward it out additional interfaces.
22158 			 * RSVP and the rsvp daemon is an example of a
22159 			 * protocol and user level process that
22160 			 * handles it's own routing. Hence, it uses the
22161 			 * SO_DONTROUTE option to accomplish this.
22162 			 */
22163 
22164 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22165 				/* Unconditionally redo the checksum */
22166 				ipha->ipha_hdr_checksum = 0;
22167 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22168 
22169 				/*
22170 				 * If this needs to go out secure, we need
22171 				 * to wait till we finish the IPSEC
22172 				 * processing.
22173 				 */
22174 				if (ipsec_len == 0 &&
22175 				    ip_mforward(ill, ipha, mp)) {
22176 					freemsg(first_mp);
22177 					ip1dbg(("ip_wput: mforward failed\n"));
22178 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22179 					    "ip_wput_ire_end: q %p (%S)",
22180 					    q, "mforward failed");
22181 					ire_refrele(ire);
22182 					if (conn_outgoing_ill != NULL)
22183 						ill_refrele(conn_outgoing_ill);
22184 					return;
22185 				}
22186 			}
22187 		}
22188 		max_frag = ire->ire_max_frag;
22189 		cksum += ttl_protocol;
22190 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22191 			/* No fragmentation required for this one. */
22192 			/*
22193 			 * Don't use frag_flag if packet is pre-built or source
22194 			 * routed or if multicast (since multicast packets do
22195 			 * not solicit ICMP "packet too big" messages).
22196 			 */
22197 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22198 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22199 			    !ip_source_route_included(ipha)) &&
22200 			    !CLASSD(ipha->ipha_dst))
22201 				ipha->ipha_fragment_offset_and_flags |=
22202 				    htons(ire->ire_frag_flag);
22203 
22204 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22205 				/* Complete the IP header checksum. */
22206 				cksum += ipha->ipha_ident;
22207 				cksum += (v_hlen_tos_len >> 16)+
22208 				    (v_hlen_tos_len & 0xFFFF);
22209 				cksum += ipha->ipha_fragment_offset_and_flags;
22210 				hlen = (V_HLEN & 0xF) -
22211 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22212 				if (hlen) {
22213 				    checksumoptions:
22214 					/*
22215 					 * Account for the IP Options in the IP
22216 					 * header checksum.
22217 					 */
22218 					up = (uint16_t *)(rptr+
22219 					    IP_SIMPLE_HDR_LENGTH);
22220 					do {
22221 						cksum += up[0];
22222 						cksum += up[1];
22223 						up += 2;
22224 					} while (--hlen);
22225 				}
22226 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22227 				cksum = ~(cksum + (cksum >> 16));
22228 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22229 			}
22230 			if (ipsec_len != 0) {
22231 				ipsec_out_process(q, first_mp, ire, ill_index);
22232 				if (!next_mp) {
22233 					ire_refrele(ire);
22234 					if (conn_outgoing_ill != NULL)
22235 						ill_refrele(conn_outgoing_ill);
22236 					return;
22237 				}
22238 				goto next;
22239 			}
22240 
22241 			/*
22242 			 * multirt_send has already been handled
22243 			 * for broadcast, but not yet for multicast
22244 			 * or IP options.
22245 			 */
22246 			if (next_mp == NULL) {
22247 				if (ire->ire_flags & RTF_MULTIRT) {
22248 					multirt_send = B_TRUE;
22249 				}
22250 			}
22251 
22252 			/*
22253 			 * In most cases, the emission loop below is
22254 			 * entered only once. Only in the case where
22255 			 * the ire holds the RTF_MULTIRT flag, do we loop
22256 			 * to process all RTF_MULTIRT ires in the bucket,
22257 			 * and send the packet through all crossed
22258 			 * RTF_MULTIRT routes.
22259 			 */
22260 			do {
22261 				if (multirt_send) {
22262 					irb_t *irb;
22263 
22264 					irb = ire->ire_bucket;
22265 					ASSERT(irb != NULL);
22266 					/*
22267 					 * We are in a multiple send case,
22268 					 * need to get the next IRE and make
22269 					 * a duplicate of the packet.
22270 					 */
22271 					IRB_REFHOLD(irb);
22272 					for (ire1 = ire->ire_next;
22273 					    ire1 != NULL;
22274 					    ire1 = ire1->ire_next) {
22275 						if (!(ire1->ire_flags &
22276 						    RTF_MULTIRT))
22277 							continue;
22278 						if (ire1->ire_addr !=
22279 						    ire->ire_addr)
22280 							continue;
22281 						if (ire1->ire_marks &
22282 						    (IRE_MARK_CONDEMNED|
22283 							IRE_MARK_HIDDEN))
22284 							continue;
22285 
22286 						/* Got one */
22287 						IRE_REFHOLD(ire1);
22288 						break;
22289 					}
22290 					IRB_REFRELE(irb);
22291 
22292 					if (ire1 != NULL) {
22293 						next_mp = copyb(mp);
22294 						if ((next_mp == NULL) ||
22295 						    ((mp->b_cont != NULL) &&
22296 						    ((next_mp->b_cont =
22297 						    dupmsg(mp->b_cont))
22298 						    == NULL))) {
22299 							freemsg(next_mp);
22300 							next_mp = NULL;
22301 							ire_refrele(ire1);
22302 							ire1 = NULL;
22303 						}
22304 					}
22305 
22306 					/*
22307 					 * Last multiroute ire; don't loop
22308 					 * anymore. The emission is over
22309 					 * and next_mp is NULL.
22310 					 */
22311 					if (ire1 == NULL) {
22312 						multirt_send = B_FALSE;
22313 					}
22314 				}
22315 
22316 				ASSERT(ipsec_len == 0);
22317 				mp->b_prev =
22318 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22319 				DTRACE_PROBE2(ip__xmit__2,
22320 				    mblk_t *, mp, ire_t *, ire);
22321 				pktxmit_state = ip_xmit_v4(mp, ire,
22322 				    NULL, B_TRUE);
22323 				if ((pktxmit_state == SEND_FAILED) ||
22324 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22325 					if (next_mp) {
22326 						freemsg(next_mp);
22327 						ire_refrele(ire1);
22328 					}
22329 					ire_refrele(ire);
22330 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22331 					    "ip_wput_ire_end: q %p (%S)",
22332 					    q, "discard MDATA");
22333 					if (conn_outgoing_ill != NULL)
22334 						ill_refrele(conn_outgoing_ill);
22335 					return;
22336 				}
22337 
22338 				if (multirt_send) {
22339 					/*
22340 					 * We are in a multiple send case,
22341 					 * need to re-enter the sending loop
22342 					 * using the next ire.
22343 					 */
22344 					ire_refrele(ire);
22345 					ire = ire1;
22346 					stq = ire->ire_stq;
22347 					mp = next_mp;
22348 					next_mp = NULL;
22349 					ipha = (ipha_t *)mp->b_rptr;
22350 					ill_index = Q_TO_INDEX(stq);
22351 				}
22352 			} while (multirt_send);
22353 
22354 			if (!next_mp) {
22355 				/*
22356 				 * Last copy going out (the ultra-common
22357 				 * case).  Note that we intentionally replicate
22358 				 * the putnext rather than calling it before
22359 				 * the next_mp check in hopes of a little
22360 				 * tail-call action out of the compiler.
22361 				 */
22362 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22363 				    "ip_wput_ire_end: q %p (%S)",
22364 				    q, "last copy out(1)");
22365 				ire_refrele(ire);
22366 				if (conn_outgoing_ill != NULL)
22367 					ill_refrele(conn_outgoing_ill);
22368 				return;
22369 			}
22370 			/* More copies going out below. */
22371 		} else {
22372 			int offset;
22373 		    fragmentit:
22374 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22375 			/*
22376 			 * If this would generate a icmp_frag_needed message,
22377 			 * we need to handle it before we do the IPSEC
22378 			 * processing. Otherwise, we need to strip the IPSEC
22379 			 * headers before we send up the message to the ULPs
22380 			 * which becomes messy and difficult.
22381 			 */
22382 			if (ipsec_len != 0) {
22383 				if ((max_frag < (unsigned int)(LENGTH +
22384 				    ipsec_len)) && (offset & IPH_DF)) {
22385 
22386 					BUMP_MIB(&ip_mib, ipFragFails);
22387 					ipha->ipha_hdr_checksum = 0;
22388 					ipha->ipha_hdr_checksum =
22389 					    (uint16_t)ip_csum_hdr(ipha);
22390 					icmp_frag_needed(ire->ire_stq, first_mp,
22391 					    max_frag, zoneid);
22392 					if (!next_mp) {
22393 						ire_refrele(ire);
22394 						if (conn_outgoing_ill != NULL) {
22395 							ill_refrele(
22396 							    conn_outgoing_ill);
22397 						}
22398 						return;
22399 					}
22400 				} else {
22401 					/*
22402 					 * This won't cause a icmp_frag_needed
22403 					 * message. to be gnerated. Send it on
22404 					 * the wire. Note that this could still
22405 					 * cause fragmentation and all we
22406 					 * do is the generation of the message
22407 					 * to the ULP if needed before IPSEC.
22408 					 */
22409 					if (!next_mp) {
22410 						ipsec_out_process(q, first_mp,
22411 						    ire, ill_index);
22412 						TRACE_2(TR_FAC_IP,
22413 						    TR_IP_WPUT_IRE_END,
22414 						    "ip_wput_ire_end: q %p "
22415 						    "(%S)", q,
22416 						    "last ipsec_out_process");
22417 						ire_refrele(ire);
22418 						if (conn_outgoing_ill != NULL) {
22419 							ill_refrele(
22420 							    conn_outgoing_ill);
22421 						}
22422 						return;
22423 					}
22424 					ipsec_out_process(q, first_mp,
22425 					    ire, ill_index);
22426 				}
22427 			} else {
22428 				/*
22429 				 * Initiate IPPF processing. For
22430 				 * fragmentable packets we finish
22431 				 * all QOS packet processing before
22432 				 * calling:
22433 				 * ip_wput_ire_fragmentit->ip_wput_frag
22434 				 */
22435 
22436 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22437 					ip_process(IPP_LOCAL_OUT, &mp,
22438 					    ill_index);
22439 					if (mp == NULL) {
22440 						BUMP_MIB(&ip_mib,
22441 						    ipOutDiscards);
22442 						if (next_mp != NULL) {
22443 							freemsg(next_mp);
22444 							ire_refrele(ire1);
22445 						}
22446 						ire_refrele(ire);
22447 						TRACE_2(TR_FAC_IP,
22448 						    TR_IP_WPUT_IRE_END,
22449 						    "ip_wput_ire: q %p (%S)",
22450 						    q, "discard MDATA");
22451 						if (conn_outgoing_ill != NULL) {
22452 							ill_refrele(
22453 							    conn_outgoing_ill);
22454 						}
22455 						return;
22456 					}
22457 				}
22458 				if (!next_mp) {
22459 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22460 					    "ip_wput_ire_end: q %p (%S)",
22461 					    q, "last fragmentation");
22462 					ip_wput_ire_fragmentit(mp, ire,
22463 					    zoneid);
22464 					ire_refrele(ire);
22465 					if (conn_outgoing_ill != NULL)
22466 						ill_refrele(conn_outgoing_ill);
22467 					return;
22468 				}
22469 				ip_wput_ire_fragmentit(mp, ire, zoneid);
22470 			}
22471 		}
22472 	} else {
22473 	    nullstq:
22474 		/* A NULL stq means the destination address is local. */
22475 		UPDATE_OB_PKT_COUNT(ire);
22476 		ire->ire_last_used_time = lbolt;
22477 		ASSERT(ire->ire_ipif != NULL);
22478 		if (!next_mp) {
22479 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22480 			    "ip_wput_ire_end: q %p (%S)",
22481 			    q, "local address");
22482 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
22483 			    first_mp, ire, 0, ire->ire_zoneid);
22484 			ire_refrele(ire);
22485 			if (conn_outgoing_ill != NULL)
22486 				ill_refrele(conn_outgoing_ill);
22487 			return;
22488 		}
22489 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
22490 		    ire, 0, ire->ire_zoneid);
22491 	}
22492 next:
22493 	/*
22494 	 * More copies going out to additional interfaces.
22495 	 * ire1 has already been held. We don't need the
22496 	 * "ire" anymore.
22497 	 */
22498 	ire_refrele(ire);
22499 	ire = ire1;
22500 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
22501 	mp = next_mp;
22502 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
22503 	ill = ire_to_ill(ire);
22504 	first_mp = mp;
22505 	if (ipsec_len != 0) {
22506 		ASSERT(first_mp->b_datap->db_type == M_CTL);
22507 		mp = mp->b_cont;
22508 	}
22509 	dst = ire->ire_addr;
22510 	ipha = (ipha_t *)mp->b_rptr;
22511 	/*
22512 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
22513 	 * Restore ipha_ident "no checksum" flag.
22514 	 */
22515 	src = orig_src;
22516 	ipha->ipha_ident = ip_hdr_included;
22517 	goto another;
22518 
22519 #undef	rptr
22520 #undef	Q_TO_INDEX
22521 }
22522 
22523 /*
22524  * Routine to allocate a message that is used to notify the ULP about MDT.
22525  * The caller may provide a pointer to the link-layer MDT capabilities,
22526  * or NULL if MDT is to be disabled on the stream.
22527  */
22528 mblk_t *
22529 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
22530 {
22531 	mblk_t *mp;
22532 	ip_mdt_info_t *mdti;
22533 	ill_mdt_capab_t *idst;
22534 
22535 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
22536 		DB_TYPE(mp) = M_CTL;
22537 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
22538 		mdti = (ip_mdt_info_t *)mp->b_rptr;
22539 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
22540 		idst = &(mdti->mdt_capab);
22541 
22542 		/*
22543 		 * If the caller provides us with the capability, copy
22544 		 * it over into our notification message; otherwise
22545 		 * we zero out the capability portion.
22546 		 */
22547 		if (isrc != NULL)
22548 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22549 		else
22550 			bzero((caddr_t)idst, sizeof (*idst));
22551 	}
22552 	return (mp);
22553 }
22554 
22555 /*
22556  * Routine which determines whether MDT can be enabled on the destination
22557  * IRE and IPC combination, and if so, allocates and returns the MDT
22558  * notification mblk that may be used by ULP.  We also check if we need to
22559  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
22560  * MDT usage in the past have been lifted.  This gets called during IP
22561  * and ULP binding.
22562  */
22563 mblk_t *
22564 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22565     ill_mdt_capab_t *mdt_cap)
22566 {
22567 	mblk_t *mp;
22568 	boolean_t rc = B_FALSE;
22569 
22570 	ASSERT(dst_ire != NULL);
22571 	ASSERT(connp != NULL);
22572 	ASSERT(mdt_cap != NULL);
22573 
22574 	/*
22575 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
22576 	 * Multidata, which is handled in tcp_multisend().  This
22577 	 * is the reason why we do all these checks here, to ensure
22578 	 * that we don't enable Multidata for the cases which we
22579 	 * can't handle at the moment.
22580 	 */
22581 	do {
22582 		/* Only do TCP at the moment */
22583 		if (connp->conn_ulp != IPPROTO_TCP)
22584 			break;
22585 
22586 		/*
22587 		 * IPSEC outbound policy present?  Note that we get here
22588 		 * after calling ipsec_conn_cache_policy() where the global
22589 		 * policy checking is performed.  conn_latch will be
22590 		 * non-NULL as long as there's a policy defined,
22591 		 * i.e. conn_out_enforce_policy may be NULL in such case
22592 		 * when the connection is non-secure, and hence we check
22593 		 * further if the latch refers to an outbound policy.
22594 		 */
22595 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
22596 			break;
22597 
22598 		/* CGTP (multiroute) is enabled? */
22599 		if (dst_ire->ire_flags & RTF_MULTIRT)
22600 			break;
22601 
22602 		/* Outbound IPQoS enabled? */
22603 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22604 			/*
22605 			 * In this case, we disable MDT for this and all
22606 			 * future connections going over the interface.
22607 			 */
22608 			mdt_cap->ill_mdt_on = 0;
22609 			break;
22610 		}
22611 
22612 		/* socket option(s) present? */
22613 		if (!CONN_IS_MD_FASTPATH(connp))
22614 			break;
22615 
22616 		rc = B_TRUE;
22617 	/* CONSTCOND */
22618 	} while (0);
22619 
22620 	/* Remember the result */
22621 	connp->conn_mdt_ok = rc;
22622 
22623 	if (!rc)
22624 		return (NULL);
22625 	else if (!mdt_cap->ill_mdt_on) {
22626 		/*
22627 		 * If MDT has been previously turned off in the past, and we
22628 		 * currently can do MDT (due to IPQoS policy removal, etc.)
22629 		 * then enable it for this interface.
22630 		 */
22631 		mdt_cap->ill_mdt_on = 1;
22632 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
22633 		    "interface %s\n", ill_name));
22634 	}
22635 
22636 	/* Allocate the MDT info mblk */
22637 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
22638 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
22639 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
22640 		return (NULL);
22641 	}
22642 	return (mp);
22643 }
22644 
22645 /*
22646  * Create destination address attribute, and fill it with the physical
22647  * destination address and SAP taken from the template DL_UNITDATA_REQ
22648  * message block.
22649  */
22650 boolean_t
22651 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
22652 {
22653 	dl_unitdata_req_t *dlurp;
22654 	pattr_t *pa;
22655 	pattrinfo_t pa_info;
22656 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
22657 	uint_t das_len, das_off;
22658 
22659 	ASSERT(dlmp != NULL);
22660 
22661 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
22662 	das_len = dlurp->dl_dest_addr_length;
22663 	das_off = dlurp->dl_dest_addr_offset;
22664 
22665 	pa_info.type = PATTR_DSTADDRSAP;
22666 	pa_info.len = sizeof (**das) + das_len - 1;
22667 
22668 	/* create and associate the attribute */
22669 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22670 	if (pa != NULL) {
22671 		ASSERT(*das != NULL);
22672 		(*das)->addr_is_group = 0;
22673 		(*das)->addr_len = (uint8_t)das_len;
22674 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
22675 	}
22676 
22677 	return (pa != NULL);
22678 }
22679 
22680 /*
22681  * Create hardware checksum attribute and fill it with the values passed.
22682  */
22683 boolean_t
22684 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
22685     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
22686 {
22687 	pattr_t *pa;
22688 	pattrinfo_t pa_info;
22689 
22690 	ASSERT(mmd != NULL);
22691 
22692 	pa_info.type = PATTR_HCKSUM;
22693 	pa_info.len = sizeof (pattr_hcksum_t);
22694 
22695 	/* create and associate the attribute */
22696 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22697 	if (pa != NULL) {
22698 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
22699 
22700 		hck->hcksum_start_offset = start_offset;
22701 		hck->hcksum_stuff_offset = stuff_offset;
22702 		hck->hcksum_end_offset = end_offset;
22703 		hck->hcksum_flags = flags;
22704 	}
22705 	return (pa != NULL);
22706 }
22707 
22708 /*
22709  * Create zerocopy attribute and fill it with the specified flags
22710  */
22711 boolean_t
22712 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
22713 {
22714 	pattr_t *pa;
22715 	pattrinfo_t pa_info;
22716 
22717 	ASSERT(mmd != NULL);
22718 	pa_info.type = PATTR_ZCOPY;
22719 	pa_info.len = sizeof (pattr_zcopy_t);
22720 
22721 	/* create and associate the attribute */
22722 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22723 	if (pa != NULL) {
22724 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
22725 
22726 		zcopy->zcopy_flags = flags;
22727 	}
22728 	return (pa != NULL);
22729 }
22730 
22731 /*
22732  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
22733  * block chain. We could rewrite to handle arbitrary message block chains but
22734  * that would make the code complicated and slow. Right now there three
22735  * restrictions:
22736  *
22737  *   1. The first message block must contain the complete IP header and
22738  *	at least 1 byte of payload data.
22739  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
22740  *	so that we can use a single Multidata message.
22741  *   3. No frag must be distributed over two or more message blocks so
22742  *	that we don't need more than two packet descriptors per frag.
22743  *
22744  * The above restrictions allow us to support userland applications (which
22745  * will send down a single message block) and NFS over UDP (which will
22746  * send down a chain of at most three message blocks).
22747  *
22748  * We also don't use MDT for payloads with less than or equal to
22749  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
22750  */
22751 boolean_t
22752 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
22753 {
22754 	int	blocks;
22755 	ssize_t	total, missing, size;
22756 
22757 	ASSERT(mp != NULL);
22758 	ASSERT(hdr_len > 0);
22759 
22760 	size = MBLKL(mp) - hdr_len;
22761 	if (size <= 0)
22762 		return (B_FALSE);
22763 
22764 	/* The first mblk contains the header and some payload. */
22765 	blocks = 1;
22766 	total = size;
22767 	size %= len;
22768 	missing = (size == 0) ? 0 : (len - size);
22769 	mp = mp->b_cont;
22770 
22771 	while (mp != NULL) {
22772 		/*
22773 		 * Give up if we encounter a zero length message block.
22774 		 * In practice, this should rarely happen and therefore
22775 		 * not worth the trouble of freeing and re-linking the
22776 		 * mblk from the chain to handle such case.
22777 		 */
22778 		if ((size = MBLKL(mp)) == 0)
22779 			return (B_FALSE);
22780 
22781 		/* Too many payload buffers for a single Multidata message? */
22782 		if (++blocks > MULTIDATA_MAX_PBUFS)
22783 			return (B_FALSE);
22784 
22785 		total += size;
22786 		/* Is a frag distributed over two or more message blocks? */
22787 		if (missing > size)
22788 			return (B_FALSE);
22789 		size -= missing;
22790 
22791 		size %= len;
22792 		missing = (size == 0) ? 0 : (len - size);
22793 
22794 		mp = mp->b_cont;
22795 	}
22796 
22797 	return (total > ip_wput_frag_mdt_min);
22798 }
22799 
22800 /*
22801  * Outbound IPv4 fragmentation routine using MDT.
22802  */
22803 static void
22804 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
22805     uint32_t frag_flag, int offset)
22806 {
22807 	ipha_t		*ipha_orig;
22808 	int		i1, ip_data_end;
22809 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
22810 	mblk_t		*hdr_mp, *md_mp = NULL;
22811 	unsigned char	*hdr_ptr, *pld_ptr;
22812 	multidata_t	*mmd;
22813 	ip_pdescinfo_t	pdi;
22814 
22815 	ASSERT(DB_TYPE(mp) == M_DATA);
22816 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
22817 
22818 	ipha_orig = (ipha_t *)mp->b_rptr;
22819 	mp->b_rptr += sizeof (ipha_t);
22820 
22821 	/* Calculate how many packets we will send out */
22822 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
22823 	pkts = (i1 + len - 1) / len;
22824 	ASSERT(pkts > 1);
22825 
22826 	/* Allocate a message block which will hold all the IP Headers. */
22827 	wroff = ip_wroff_extra;
22828 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
22829 
22830 	i1 = pkts * hdr_chunk_len;
22831 	/*
22832 	 * Create the header buffer, Multidata and destination address
22833 	 * and SAP attribute that should be associated with it.
22834 	 */
22835 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
22836 	    ((hdr_mp->b_wptr += i1),
22837 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
22838 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
22839 		freemsg(mp);
22840 		if (md_mp == NULL) {
22841 			freemsg(hdr_mp);
22842 		} else {
22843 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
22844 			freemsg(md_mp);
22845 		}
22846 		IP_STAT(ip_frag_mdt_allocfail);
22847 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
22848 		return;
22849 	}
22850 	IP_STAT(ip_frag_mdt_allocd);
22851 
22852 	/*
22853 	 * Add a payload buffer to the Multidata; this operation must not
22854 	 * fail, or otherwise our logic in this routine is broken.  There
22855 	 * is no memory allocation done by the routine, so any returned
22856 	 * failure simply tells us that we've done something wrong.
22857 	 *
22858 	 * A failure tells us that either we're adding the same payload
22859 	 * buffer more than once, or we're trying to add more buffers than
22860 	 * allowed.  None of the above cases should happen, and we panic
22861 	 * because either there's horrible heap corruption, and/or
22862 	 * programming mistake.
22863 	 */
22864 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22865 		goto pbuf_panic;
22866 
22867 	hdr_ptr = hdr_mp->b_rptr;
22868 	pld_ptr = mp->b_rptr;
22869 
22870 	/* Establish the ending byte offset, based on the starting offset. */
22871 	offset <<= 3;
22872 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
22873 	    IP_SIMPLE_HDR_LENGTH;
22874 
22875 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
22876 
22877 	while (pld_ptr < mp->b_wptr) {
22878 		ipha_t		*ipha;
22879 		uint16_t	offset_and_flags;
22880 		uint16_t	ip_len;
22881 		int		error;
22882 
22883 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
22884 		ipha = (ipha_t *)(hdr_ptr + wroff);
22885 		ASSERT(OK_32PTR(ipha));
22886 		*ipha = *ipha_orig;
22887 
22888 		if (ip_data_end - offset > len) {
22889 			offset_and_flags = IPH_MF;
22890 		} else {
22891 			/*
22892 			 * Last frag. Set len to the length of this last piece.
22893 			 */
22894 			len = ip_data_end - offset;
22895 			/* A frag of a frag might have IPH_MF non-zero */
22896 			offset_and_flags =
22897 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22898 			    IPH_MF;
22899 		}
22900 		offset_and_flags |= (uint16_t)(offset >> 3);
22901 		offset_and_flags |= (uint16_t)frag_flag;
22902 		/* Store the offset and flags in the IP header. */
22903 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22904 
22905 		/* Store the length in the IP header. */
22906 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
22907 		ipha->ipha_length = htons(ip_len);
22908 
22909 		/*
22910 		 * Set the IP header checksum.  Note that mp is just
22911 		 * the header, so this is easy to pass to ip_csum.
22912 		 */
22913 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22914 
22915 		/*
22916 		 * Record offset and size of header and data of the next packet
22917 		 * in the multidata message.
22918 		 */
22919 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
22920 		PDESC_PLD_INIT(&pdi);
22921 		i1 = MIN(mp->b_wptr - pld_ptr, len);
22922 		ASSERT(i1 > 0);
22923 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
22924 		if (i1 == len) {
22925 			pld_ptr += len;
22926 		} else {
22927 			i1 = len - i1;
22928 			mp = mp->b_cont;
22929 			ASSERT(mp != NULL);
22930 			ASSERT(MBLKL(mp) >= i1);
22931 			/*
22932 			 * Attach the next payload message block to the
22933 			 * multidata message.
22934 			 */
22935 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22936 				goto pbuf_panic;
22937 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
22938 			pld_ptr = mp->b_rptr + i1;
22939 		}
22940 
22941 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
22942 		    KM_NOSLEEP)) == NULL) {
22943 			/*
22944 			 * Any failure other than ENOMEM indicates that we
22945 			 * have passed in invalid pdesc info or parameters
22946 			 * to mmd_addpdesc, which must not happen.
22947 			 *
22948 			 * EINVAL is a result of failure on boundary checks
22949 			 * against the pdesc info contents.  It should not
22950 			 * happen, and we panic because either there's
22951 			 * horrible heap corruption, and/or programming
22952 			 * mistake.
22953 			 */
22954 			if (error != ENOMEM) {
22955 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
22956 				    "pdesc logic error detected for "
22957 				    "mmd %p pinfo %p (%d)\n",
22958 				    (void *)mmd, (void *)&pdi, error);
22959 				/* NOTREACHED */
22960 			}
22961 			IP_STAT(ip_frag_mdt_addpdescfail);
22962 			/* Free unattached payload message blocks as well */
22963 			md_mp->b_cont = mp->b_cont;
22964 			goto free_mmd;
22965 		}
22966 
22967 		/* Advance fragment offset. */
22968 		offset += len;
22969 
22970 		/* Advance to location for next header in the buffer. */
22971 		hdr_ptr += hdr_chunk_len;
22972 
22973 		/* Did we reach the next payload message block? */
22974 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
22975 			mp = mp->b_cont;
22976 			/*
22977 			 * Attach the next message block with payload
22978 			 * data to the multidata message.
22979 			 */
22980 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22981 				goto pbuf_panic;
22982 			pld_ptr = mp->b_rptr;
22983 		}
22984 	}
22985 
22986 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
22987 	ASSERT(mp->b_wptr == pld_ptr);
22988 
22989 	/* Update IP statistics */
22990 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
22991 	BUMP_MIB(&ip_mib, ipFragOKs);
22992 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
22993 
22994 	if (pkt_type == OB_PKT) {
22995 		ire->ire_ob_pkt_count += pkts;
22996 		if (ire->ire_ipif != NULL)
22997 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
22998 	} else {
22999 		/*
23000 		 * The type is IB_PKT in the forwarding path and in
23001 		 * the mobile IP case when the packet is being reverse-
23002 		 * tunneled to the home agent.
23003 		 */
23004 		ire->ire_ib_pkt_count += pkts;
23005 		ASSERT(!IRE_IS_LOCAL(ire));
23006 		if (ire->ire_type & IRE_BROADCAST)
23007 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23008 		else
23009 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23010 	}
23011 	ire->ire_last_used_time = lbolt;
23012 	/* Send it down */
23013 	putnext(ire->ire_stq, md_mp);
23014 	return;
23015 
23016 pbuf_panic:
23017 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23018 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23019 	    pbuf_idx);
23020 	/* NOTREACHED */
23021 }
23022 
23023 /*
23024  * Outbound IP fragmentation routine.
23025  *
23026  * NOTE : This routine does not ire_refrele the ire that is passed in
23027  * as the argument.
23028  */
23029 static void
23030 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23031     uint32_t frag_flag, zoneid_t zoneid)
23032 {
23033 	int		i1;
23034 	mblk_t		*ll_hdr_mp;
23035 	int 		ll_hdr_len;
23036 	int		hdr_len;
23037 	mblk_t		*hdr_mp;
23038 	ipha_t		*ipha;
23039 	int		ip_data_end;
23040 	int		len;
23041 	mblk_t		*mp = mp_orig;
23042 	int		offset;
23043 	queue_t		*q;
23044 	uint32_t	v_hlen_tos_len;
23045 	mblk_t		*first_mp;
23046 	boolean_t	mctl_present;
23047 	ill_t		*ill;
23048 	mblk_t		*xmit_mp;
23049 	mblk_t		*carve_mp;
23050 	ire_t		*ire1 = NULL;
23051 	ire_t		*save_ire = NULL;
23052 	mblk_t  	*next_mp = NULL;
23053 	boolean_t	last_frag = B_FALSE;
23054 	boolean_t	multirt_send = B_FALSE;
23055 	ire_t		*first_ire = NULL;
23056 	irb_t		*irb = NULL;
23057 
23058 	/*
23059 	 * IPSEC does not allow hw accelerated packets to be fragmented
23060 	 * This check is made in ip_wput_ipsec_out prior to coming here
23061 	 * via ip_wput_ire_fragmentit.
23062 	 *
23063 	 * If at this point we have an ire whose ARP request has not
23064 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23065 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23066 	 * This packet and all fragmentable packets for this ire will
23067 	 * continue to get dropped while ire_nce->nce_state remains in
23068 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23069 	 * ND_REACHABLE, all subsquent large packets for this ire will
23070 	 * get fragemented and sent out by this function.
23071 	 */
23072 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23073 		/* If nce_state is ND_INITIAL, trigger ARP query */
23074 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23075 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23076 		    " -  dropping packet\n"));
23077 		BUMP_MIB(&ip_mib, ipFragFails);
23078 		freemsg(mp);
23079 		return;
23080 	}
23081 
23082 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23083 	    "ip_wput_frag_start:");
23084 
23085 	if (mp->b_datap->db_type == M_CTL) {
23086 		first_mp = mp;
23087 		mp_orig = mp = mp->b_cont;
23088 		mctl_present = B_TRUE;
23089 	} else {
23090 		first_mp = mp;
23091 		mctl_present = B_FALSE;
23092 	}
23093 
23094 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23095 	ipha = (ipha_t *)mp->b_rptr;
23096 
23097 	/*
23098 	 * If the Don't Fragment flag is on, generate an ICMP destination
23099 	 * unreachable, fragmentation needed.
23100 	 */
23101 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23102 	if (offset & IPH_DF) {
23103 		BUMP_MIB(&ip_mib, ipFragFails);
23104 		/*
23105 		 * Need to compute hdr checksum if called from ip_wput_ire.
23106 		 * Note that ip_rput_forward verifies the checksum before
23107 		 * calling this routine so in that case this is a noop.
23108 		 */
23109 		ipha->ipha_hdr_checksum = 0;
23110 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23111 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid);
23112 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23113 		    "ip_wput_frag_end:(%S)",
23114 		    "don't fragment");
23115 		return;
23116 	}
23117 	if (mctl_present)
23118 		freeb(first_mp);
23119 	/*
23120 	 * Establish the starting offset.  May not be zero if we are fragging
23121 	 * a fragment that is being forwarded.
23122 	 */
23123 	offset = offset & IPH_OFFSET;
23124 
23125 	/* TODO why is this test needed? */
23126 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23127 	if (((max_frag - LENGTH) & ~7) < 8) {
23128 		/* TODO: notify ulp somehow */
23129 		BUMP_MIB(&ip_mib, ipFragFails);
23130 		freemsg(mp);
23131 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23132 		    "ip_wput_frag_end:(%S)",
23133 		    "len < 8");
23134 		return;
23135 	}
23136 
23137 	hdr_len = (V_HLEN & 0xF) << 2;
23138 
23139 	ipha->ipha_hdr_checksum = 0;
23140 
23141 	/*
23142 	 * Establish the number of bytes maximum per frag, after putting
23143 	 * in the header.
23144 	 */
23145 	len = (max_frag - hdr_len) & ~7;
23146 
23147 	/* Check if we can use MDT to send out the frags. */
23148 	ASSERT(!IRE_IS_LOCAL(ire));
23149 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
23150 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
23151 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
23152 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23153 		ASSERT(ill->ill_mdt_capab != NULL);
23154 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23155 			/*
23156 			 * If MDT has been previously turned off in the past,
23157 			 * and we currently can do MDT (due to IPQoS policy
23158 			 * removal, etc.) then enable it for this interface.
23159 			 */
23160 			ill->ill_mdt_capab->ill_mdt_on = 1;
23161 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23162 			    ill->ill_name));
23163 		}
23164 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23165 		    offset);
23166 		return;
23167 	}
23168 
23169 	/* Get a copy of the header for the trailing frags */
23170 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
23171 	if (!hdr_mp) {
23172 		BUMP_MIB(&ip_mib, ipOutDiscards);
23173 		freemsg(mp);
23174 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23175 		    "ip_wput_frag_end:(%S)",
23176 		    "couldn't copy hdr");
23177 		return;
23178 	}
23179 	if (DB_CRED(mp) != NULL)
23180 		mblk_setcred(hdr_mp, DB_CRED(mp));
23181 
23182 	/* Store the starting offset, with the MoreFrags flag. */
23183 	i1 = offset | IPH_MF | frag_flag;
23184 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23185 
23186 	/* Establish the ending byte offset, based on the starting offset. */
23187 	offset <<= 3;
23188 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23189 
23190 	/* Store the length of the first fragment in the IP header. */
23191 	i1 = len + hdr_len;
23192 	ASSERT(i1 <= IP_MAXPACKET);
23193 	ipha->ipha_length = htons((uint16_t)i1);
23194 
23195 	/*
23196 	 * Compute the IP header checksum for the first frag.  We have to
23197 	 * watch out that we stop at the end of the header.
23198 	 */
23199 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23200 
23201 	/*
23202 	 * Now carve off the first frag.  Note that this will include the
23203 	 * original IP header.
23204 	 */
23205 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
23206 		BUMP_MIB(&ip_mib, ipOutDiscards);
23207 		freeb(hdr_mp);
23208 		freemsg(mp_orig);
23209 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23210 		    "ip_wput_frag_end:(%S)",
23211 		    "couldn't carve first");
23212 		return;
23213 	}
23214 
23215 	/*
23216 	 * Multirouting case. Each fragment is replicated
23217 	 * via all non-condemned RTF_MULTIRT routes
23218 	 * currently resolved.
23219 	 * We ensure that first_ire is the first RTF_MULTIRT
23220 	 * ire in the bucket.
23221 	 */
23222 	if (ire->ire_flags & RTF_MULTIRT) {
23223 		irb = ire->ire_bucket;
23224 		ASSERT(irb != NULL);
23225 
23226 		multirt_send = B_TRUE;
23227 
23228 		/* Make sure we do not omit any multiroute ire. */
23229 		IRB_REFHOLD(irb);
23230 		for (first_ire = irb->irb_ire;
23231 		    first_ire != NULL;
23232 		    first_ire = first_ire->ire_next) {
23233 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23234 			    (first_ire->ire_addr == ire->ire_addr) &&
23235 			    !(first_ire->ire_marks &
23236 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23237 				break;
23238 		}
23239 
23240 		if (first_ire != NULL) {
23241 			if (first_ire != ire) {
23242 				IRE_REFHOLD(first_ire);
23243 				/*
23244 				 * Do not release the ire passed in
23245 				 * as the argument.
23246 				 */
23247 				ire = first_ire;
23248 			} else {
23249 				first_ire = NULL;
23250 			}
23251 		}
23252 		IRB_REFRELE(irb);
23253 
23254 		/*
23255 		 * Save the first ire; we will need to restore it
23256 		 * for the trailing frags.
23257 		 * We REFHOLD save_ire, as each iterated ire will be
23258 		 * REFRELEd.
23259 		 */
23260 		save_ire = ire;
23261 		IRE_REFHOLD(save_ire);
23262 	}
23263 
23264 	/*
23265 	 * First fragment emission loop.
23266 	 * In most cases, the emission loop below is entered only
23267 	 * once. Only in the case where the ire holds the RTF_MULTIRT
23268 	 * flag, do we loop to process all RTF_MULTIRT ires in the
23269 	 * bucket, and send the fragment through all crossed
23270 	 * RTF_MULTIRT routes.
23271 	 */
23272 	do {
23273 		if (ire->ire_flags & RTF_MULTIRT) {
23274 			/*
23275 			 * We are in a multiple send case, need to get
23276 			 * the next ire and make a copy of the packet.
23277 			 * ire1 holds here the next ire to process in the
23278 			 * bucket. If multirouting is expected,
23279 			 * any non-RTF_MULTIRT ire that has the
23280 			 * right destination address is ignored.
23281 			 *
23282 			 * We have to take into account the MTU of
23283 			 * each walked ire. max_frag is set by the
23284 			 * the caller and generally refers to
23285 			 * the primary ire entry. Here we ensure that
23286 			 * no route with a lower MTU will be used, as
23287 			 * fragments are carved once for all ires,
23288 			 * then replicated.
23289 			 */
23290 			ASSERT(irb != NULL);
23291 			IRB_REFHOLD(irb);
23292 			for (ire1 = ire->ire_next;
23293 			    ire1 != NULL;
23294 			    ire1 = ire1->ire_next) {
23295 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23296 					continue;
23297 				if (ire1->ire_addr != ire->ire_addr)
23298 					continue;
23299 				if (ire1->ire_marks &
23300 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23301 					continue;
23302 				/*
23303 				 * Ensure we do not exceed the MTU
23304 				 * of the next route.
23305 				 */
23306 				if (ire1->ire_max_frag < max_frag) {
23307 					ip_multirt_bad_mtu(ire1, max_frag);
23308 					continue;
23309 				}
23310 
23311 				/* Got one. */
23312 				IRE_REFHOLD(ire1);
23313 				break;
23314 			}
23315 			IRB_REFRELE(irb);
23316 
23317 			if (ire1 != NULL) {
23318 				next_mp = copyb(mp);
23319 				if ((next_mp == NULL) ||
23320 				    ((mp->b_cont != NULL) &&
23321 				    ((next_mp->b_cont =
23322 				    dupmsg(mp->b_cont)) == NULL))) {
23323 					freemsg(next_mp);
23324 					next_mp = NULL;
23325 					ire_refrele(ire1);
23326 					ire1 = NULL;
23327 				}
23328 			}
23329 
23330 			/* Last multiroute ire; don't loop anymore. */
23331 			if (ire1 == NULL) {
23332 				multirt_send = B_FALSE;
23333 			}
23334 		}
23335 
23336 		ll_hdr_len = 0;
23337 		LOCK_IRE_FP_MP(ire);
23338 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23339 		if (ll_hdr_mp != NULL) {
23340 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23341 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
23342 		} else {
23343 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
23344 		}
23345 
23346 		/* If there is a transmit header, get a copy for this frag. */
23347 		/*
23348 		 * TODO: should check db_ref before calling ip_carve_mp since
23349 		 * it might give us a dup.
23350 		 */
23351 		if (!ll_hdr_mp) {
23352 			/* No xmit header. */
23353 			xmit_mp = mp;
23354 
23355 		/* We have a link-layer header that can fit in our mblk. */
23356 		} else if (mp->b_datap->db_ref == 1 &&
23357 		    ll_hdr_len != 0 &&
23358 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23359 			/* M_DATA fastpath */
23360 			mp->b_rptr -= ll_hdr_len;
23361 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
23362 			xmit_mp = mp;
23363 
23364 		/* Corner case if copyb has failed */
23365 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
23366 			UNLOCK_IRE_FP_MP(ire);
23367 			BUMP_MIB(&ip_mib, ipOutDiscards);
23368 			freeb(hdr_mp);
23369 			freemsg(mp);
23370 			freemsg(mp_orig);
23371 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23372 			    "ip_wput_frag_end:(%S)",
23373 			    "discard");
23374 
23375 			if (multirt_send) {
23376 				ASSERT(ire1);
23377 				ASSERT(next_mp);
23378 
23379 				freemsg(next_mp);
23380 				ire_refrele(ire1);
23381 			}
23382 			if (save_ire != NULL)
23383 				IRE_REFRELE(save_ire);
23384 
23385 			if (first_ire != NULL)
23386 				ire_refrele(first_ire);
23387 			return;
23388 
23389 		/*
23390 		 * Case of res_mp OR the fastpath mp can't fit
23391 		 * in the mblk
23392 		 */
23393 		} else {
23394 			xmit_mp->b_cont = mp;
23395 			if (DB_CRED(mp) != NULL)
23396 				mblk_setcred(xmit_mp, DB_CRED(mp));
23397 			/*
23398 			 * Get priority marking, if any.
23399 			 * We propagate the CoS marking from the
23400 			 * original packet that went to QoS processing
23401 			 * in ip_wput_ire to the newly carved mp.
23402 			 */
23403 			if (DB_TYPE(xmit_mp) == M_DATA)
23404 				xmit_mp->b_band = mp->b_band;
23405 		}
23406 		UNLOCK_IRE_FP_MP(ire);
23407 		q = ire->ire_stq;
23408 		BUMP_MIB(&ip_mib, ipFragCreates);
23409 		putnext(q, xmit_mp);
23410 		if (pkt_type != OB_PKT) {
23411 			/*
23412 			 * Update the packet count of trailing
23413 			 * RTF_MULTIRT ires.
23414 			 */
23415 			UPDATE_OB_PKT_COUNT(ire);
23416 		}
23417 
23418 		if (multirt_send) {
23419 			/*
23420 			 * We are in a multiple send case; look for
23421 			 * the next ire and re-enter the loop.
23422 			 */
23423 			ASSERT(ire1);
23424 			ASSERT(next_mp);
23425 			/* REFRELE the current ire before looping */
23426 			ire_refrele(ire);
23427 			ire = ire1;
23428 			ire1 = NULL;
23429 			mp = next_mp;
23430 			next_mp = NULL;
23431 		}
23432 	} while (multirt_send);
23433 
23434 	ASSERT(ire1 == NULL);
23435 
23436 	/* Restore the original ire; we need it for the trailing frags */
23437 	if (save_ire != NULL) {
23438 		/* REFRELE the last iterated ire */
23439 		ire_refrele(ire);
23440 		/* save_ire has been REFHOLDed */
23441 		ire = save_ire;
23442 		save_ire = NULL;
23443 		q = ire->ire_stq;
23444 	}
23445 
23446 	if (pkt_type == OB_PKT) {
23447 		UPDATE_OB_PKT_COUNT(ire);
23448 	} else {
23449 		UPDATE_IB_PKT_COUNT(ire);
23450 	}
23451 
23452 	/* Advance the offset to the second frag starting point. */
23453 	offset += len;
23454 	/*
23455 	 * Update hdr_len from the copied header - there might be less options
23456 	 * in the later fragments.
23457 	 */
23458 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
23459 	/* Loop until done. */
23460 	for (;;) {
23461 		uint16_t	offset_and_flags;
23462 		uint16_t	ip_len;
23463 
23464 		if (ip_data_end - offset > len) {
23465 			/*
23466 			 * Carve off the appropriate amount from the original
23467 			 * datagram.
23468 			 */
23469 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23470 				mp = NULL;
23471 				break;
23472 			}
23473 			/*
23474 			 * More frags after this one.  Get another copy
23475 			 * of the header.
23476 			 */
23477 			if (carve_mp->b_datap->db_ref == 1 &&
23478 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23479 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23480 				/* Inline IP header */
23481 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23482 				    hdr_mp->b_rptr;
23483 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23484 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23485 				mp = carve_mp;
23486 			} else {
23487 				if (!(mp = copyb(hdr_mp))) {
23488 					freemsg(carve_mp);
23489 					break;
23490 				}
23491 				/* Get priority marking, if any. */
23492 				mp->b_band = carve_mp->b_band;
23493 				mp->b_cont = carve_mp;
23494 			}
23495 			ipha = (ipha_t *)mp->b_rptr;
23496 			offset_and_flags = IPH_MF;
23497 		} else {
23498 			/*
23499 			 * Last frag.  Consume the header. Set len to
23500 			 * the length of this last piece.
23501 			 */
23502 			len = ip_data_end - offset;
23503 
23504 			/*
23505 			 * Carve off the appropriate amount from the original
23506 			 * datagram.
23507 			 */
23508 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23509 				mp = NULL;
23510 				break;
23511 			}
23512 			if (carve_mp->b_datap->db_ref == 1 &&
23513 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23514 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23515 				/* Inline IP header */
23516 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23517 				    hdr_mp->b_rptr;
23518 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23519 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23520 				mp = carve_mp;
23521 				freeb(hdr_mp);
23522 				hdr_mp = mp;
23523 			} else {
23524 				mp = hdr_mp;
23525 				/* Get priority marking, if any. */
23526 				mp->b_band = carve_mp->b_band;
23527 				mp->b_cont = carve_mp;
23528 			}
23529 			ipha = (ipha_t *)mp->b_rptr;
23530 			/* A frag of a frag might have IPH_MF non-zero */
23531 			offset_and_flags =
23532 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23533 			    IPH_MF;
23534 		}
23535 		offset_and_flags |= (uint16_t)(offset >> 3);
23536 		offset_and_flags |= (uint16_t)frag_flag;
23537 		/* Store the offset and flags in the IP header. */
23538 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23539 
23540 		/* Store the length in the IP header. */
23541 		ip_len = (uint16_t)(len + hdr_len);
23542 		ipha->ipha_length = htons(ip_len);
23543 
23544 		/*
23545 		 * Set the IP header checksum.	Note that mp is just
23546 		 * the header, so this is easy to pass to ip_csum.
23547 		 */
23548 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23549 
23550 		/* Attach a transmit header, if any, and ship it. */
23551 		if (pkt_type == OB_PKT) {
23552 			UPDATE_OB_PKT_COUNT(ire);
23553 		} else {
23554 			UPDATE_IB_PKT_COUNT(ire);
23555 		}
23556 
23557 		if (ire->ire_flags & RTF_MULTIRT) {
23558 			irb = ire->ire_bucket;
23559 			ASSERT(irb != NULL);
23560 
23561 			multirt_send = B_TRUE;
23562 
23563 			/*
23564 			 * Save the original ire; we will need to restore it
23565 			 * for the tailing frags.
23566 			 */
23567 			save_ire = ire;
23568 			IRE_REFHOLD(save_ire);
23569 		}
23570 		/*
23571 		 * Emission loop for this fragment, similar
23572 		 * to what is done for the first fragment.
23573 		 */
23574 		do {
23575 			if (multirt_send) {
23576 				/*
23577 				 * We are in a multiple send case, need to get
23578 				 * the next ire and make a copy of the packet.
23579 				 */
23580 				ASSERT(irb != NULL);
23581 				IRB_REFHOLD(irb);
23582 				for (ire1 = ire->ire_next;
23583 				    ire1 != NULL;
23584 				    ire1 = ire1->ire_next) {
23585 					if (!(ire1->ire_flags & RTF_MULTIRT))
23586 						continue;
23587 					if (ire1->ire_addr != ire->ire_addr)
23588 						continue;
23589 					if (ire1->ire_marks &
23590 					    (IRE_MARK_CONDEMNED|
23591 						IRE_MARK_HIDDEN))
23592 						continue;
23593 					/*
23594 					 * Ensure we do not exceed the MTU
23595 					 * of the next route.
23596 					 */
23597 					if (ire1->ire_max_frag < max_frag) {
23598 						ip_multirt_bad_mtu(ire1,
23599 						    max_frag);
23600 						continue;
23601 					}
23602 
23603 					/* Got one. */
23604 					IRE_REFHOLD(ire1);
23605 					break;
23606 				}
23607 				IRB_REFRELE(irb);
23608 
23609 				if (ire1 != NULL) {
23610 					next_mp = copyb(mp);
23611 					if ((next_mp == NULL) ||
23612 					    ((mp->b_cont != NULL) &&
23613 					    ((next_mp->b_cont =
23614 					    dupmsg(mp->b_cont)) == NULL))) {
23615 						freemsg(next_mp);
23616 						next_mp = NULL;
23617 						ire_refrele(ire1);
23618 						ire1 = NULL;
23619 					}
23620 				}
23621 
23622 				/* Last multiroute ire; don't loop anymore. */
23623 				if (ire1 == NULL) {
23624 					multirt_send = B_FALSE;
23625 				}
23626 			}
23627 
23628 			/* Update transmit header */
23629 			ll_hdr_len = 0;
23630 			LOCK_IRE_FP_MP(ire);
23631 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23632 			if (ll_hdr_mp != NULL) {
23633 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23634 				ll_hdr_len = MBLKL(ll_hdr_mp);
23635 			} else {
23636 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
23637 			}
23638 
23639 			if (!ll_hdr_mp) {
23640 				xmit_mp = mp;
23641 
23642 			/*
23643 			 * We have link-layer header that can fit in
23644 			 * our mblk.
23645 			 */
23646 			} else if (mp->b_datap->db_ref == 1 &&
23647 			    ll_hdr_len != 0 &&
23648 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23649 				/* M_DATA fastpath */
23650 				mp->b_rptr -= ll_hdr_len;
23651 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
23652 				    ll_hdr_len);
23653 				xmit_mp = mp;
23654 
23655 			/*
23656 			 * Case of res_mp OR the fastpath mp can't fit
23657 			 * in the mblk
23658 			 */
23659 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
23660 				xmit_mp->b_cont = mp;
23661 				if (DB_CRED(mp) != NULL)
23662 					mblk_setcred(xmit_mp, DB_CRED(mp));
23663 				/* Get priority marking, if any. */
23664 				if (DB_TYPE(xmit_mp) == M_DATA)
23665 					xmit_mp->b_band = mp->b_band;
23666 
23667 			/* Corner case if copyb failed */
23668 			} else {
23669 				/*
23670 				 * Exit both the replication and
23671 				 * fragmentation loops.
23672 				 */
23673 				UNLOCK_IRE_FP_MP(ire);
23674 				goto drop_pkt;
23675 			}
23676 			UNLOCK_IRE_FP_MP(ire);
23677 			BUMP_MIB(&ip_mib, ipFragCreates);
23678 			putnext(q, xmit_mp);
23679 
23680 			if (pkt_type != OB_PKT) {
23681 				/*
23682 				 * Update the packet count of trailing
23683 				 * RTF_MULTIRT ires.
23684 				 */
23685 				UPDATE_OB_PKT_COUNT(ire);
23686 			}
23687 
23688 			/* All done if we just consumed the hdr_mp. */
23689 			if (mp == hdr_mp) {
23690 				last_frag = B_TRUE;
23691 			}
23692 
23693 			if (multirt_send) {
23694 				/*
23695 				 * We are in a multiple send case; look for
23696 				 * the next ire and re-enter the loop.
23697 				 */
23698 				ASSERT(ire1);
23699 				ASSERT(next_mp);
23700 				/* REFRELE the current ire before looping */
23701 				ire_refrele(ire);
23702 				ire = ire1;
23703 				ire1 = NULL;
23704 				q = ire->ire_stq;
23705 				mp = next_mp;
23706 				next_mp = NULL;
23707 			}
23708 		} while (multirt_send);
23709 		/*
23710 		 * Restore the original ire; we need it for the
23711 		 * trailing frags
23712 		 */
23713 		if (save_ire != NULL) {
23714 			ASSERT(ire1 == NULL);
23715 			/* REFRELE the last iterated ire */
23716 			ire_refrele(ire);
23717 			/* save_ire has been REFHOLDed */
23718 			ire = save_ire;
23719 			q = ire->ire_stq;
23720 			save_ire = NULL;
23721 		}
23722 
23723 		if (last_frag) {
23724 			BUMP_MIB(&ip_mib, ipFragOKs);
23725 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23726 			    "ip_wput_frag_end:(%S)",
23727 			    "consumed hdr_mp");
23728 
23729 			if (first_ire != NULL)
23730 				ire_refrele(first_ire);
23731 			return;
23732 		}
23733 		/* Otherwise, advance and loop. */
23734 		offset += len;
23735 	}
23736 
23737 drop_pkt:
23738 	/* Clean up following allocation failure. */
23739 	BUMP_MIB(&ip_mib, ipOutDiscards);
23740 	freemsg(mp);
23741 	if (mp != hdr_mp)
23742 		freeb(hdr_mp);
23743 	if (mp != mp_orig)
23744 		freemsg(mp_orig);
23745 
23746 	if (save_ire != NULL)
23747 		IRE_REFRELE(save_ire);
23748 	if (first_ire != NULL)
23749 		ire_refrele(first_ire);
23750 
23751 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23752 	    "ip_wput_frag_end:(%S)",
23753 	    "end--alloc failure");
23754 }
23755 
23756 /*
23757  * Copy the header plus those options which have the copy bit set
23758  */
23759 static mblk_t *
23760 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
23761 {
23762 	mblk_t	*mp;
23763 	uchar_t	*up;
23764 
23765 	/*
23766 	 * Quick check if we need to look for options without the copy bit
23767 	 * set
23768 	 */
23769 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
23770 	if (!mp)
23771 		return (mp);
23772 	mp->b_rptr += ip_wroff_extra;
23773 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
23774 		bcopy(rptr, mp->b_rptr, hdr_len);
23775 		mp->b_wptr += hdr_len + ip_wroff_extra;
23776 		return (mp);
23777 	}
23778 	up  = mp->b_rptr;
23779 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
23780 	up += IP_SIMPLE_HDR_LENGTH;
23781 	rptr += IP_SIMPLE_HDR_LENGTH;
23782 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
23783 	while (hdr_len > 0) {
23784 		uint32_t optval;
23785 		uint32_t optlen;
23786 
23787 		optval = *rptr;
23788 		if (optval == IPOPT_EOL)
23789 			break;
23790 		if (optval == IPOPT_NOP)
23791 			optlen = 1;
23792 		else
23793 			optlen = rptr[1];
23794 		if (optval & IPOPT_COPY) {
23795 			bcopy(rptr, up, optlen);
23796 			up += optlen;
23797 		}
23798 		rptr += optlen;
23799 		hdr_len -= optlen;
23800 	}
23801 	/*
23802 	 * Make sure that we drop an even number of words by filling
23803 	 * with EOL to the next word boundary.
23804 	 */
23805 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
23806 	    hdr_len & 0x3; hdr_len++)
23807 		*up++ = IPOPT_EOL;
23808 	mp->b_wptr = up;
23809 	/* Update header length */
23810 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
23811 	return (mp);
23812 }
23813 
23814 /*
23815  * Delivery to local recipients including fanout to multiple recipients.
23816  * Does not do checksumming of UDP/TCP.
23817  * Note: q should be the read side queue for either the ill or conn.
23818  * Note: rq should be the read side q for the lower (ill) stream.
23819  * We don't send packets to IPPF processing, thus the last argument
23820  * to all the fanout calls are B_FALSE.
23821  */
23822 void
23823 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
23824     int fanout_flags, zoneid_t zoneid)
23825 {
23826 	uint32_t	protocol;
23827 	mblk_t		*first_mp;
23828 	boolean_t	mctl_present;
23829 	int		ire_type;
23830 #define	rptr	((uchar_t *)ipha)
23831 
23832 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
23833 	    "ip_wput_local_start: q %p", q);
23834 
23835 	if (ire != NULL) {
23836 		ire_type = ire->ire_type;
23837 	} else {
23838 		/*
23839 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
23840 		 * packet is not multicast, we can't tell the ire type.
23841 		 */
23842 		ASSERT(CLASSD(ipha->ipha_dst));
23843 		ire_type = IRE_BROADCAST;
23844 	}
23845 
23846 	first_mp = mp;
23847 	if (first_mp->b_datap->db_type == M_CTL) {
23848 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
23849 		if (!io->ipsec_out_secure) {
23850 			/*
23851 			 * This ipsec_out_t was allocated in ip_wput
23852 			 * for multicast packets to store the ill_index.
23853 			 * As this is being delivered locally, we don't
23854 			 * need this anymore.
23855 			 */
23856 			mp = first_mp->b_cont;
23857 			freeb(first_mp);
23858 			first_mp = mp;
23859 			mctl_present = B_FALSE;
23860 		} else {
23861 			mctl_present = B_TRUE;
23862 			mp = first_mp->b_cont;
23863 			ASSERT(mp != NULL);
23864 			ipsec_out_to_in(first_mp);
23865 		}
23866 	} else {
23867 		mctl_present = B_FALSE;
23868 	}
23869 
23870 	loopback_packets++;
23871 
23872 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
23873 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
23874 	if (!IS_SIMPLE_IPH(ipha)) {
23875 		ip_wput_local_options(ipha);
23876 	}
23877 
23878 	protocol = ipha->ipha_protocol;
23879 	switch (protocol) {
23880 	case IPPROTO_ICMP: {
23881 		ire_t		*ire_zone;
23882 		ilm_t		*ilm;
23883 		mblk_t		*mp1;
23884 		zoneid_t	last_zoneid;
23885 
23886 		if (CLASSD(ipha->ipha_dst) &&
23887 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
23888 			ASSERT(ire_type == IRE_BROADCAST);
23889 			/*
23890 			 * In the multicast case, applications may have joined
23891 			 * the group from different zones, so we need to deliver
23892 			 * the packet to each of them. Loop through the
23893 			 * multicast memberships structures (ilm) on the receive
23894 			 * ill and send a copy of the packet up each matching
23895 			 * one. However, we don't do this for multicasts sent on
23896 			 * the loopback interface (PHYI_LOOPBACK flag set) as
23897 			 * they must stay in the sender's zone.
23898 			 *
23899 			 * ilm_add_v6() ensures that ilms in the same zone are
23900 			 * contiguous in the ill_ilm list. We use this property
23901 			 * to avoid sending duplicates needed when two
23902 			 * applications in the same zone join the same group on
23903 			 * different logical interfaces: we ignore the ilm if
23904 			 * it's zoneid is the same as the last matching one.
23905 			 * In addition, the sending of the packet for
23906 			 * ire_zoneid is delayed until all of the other ilms
23907 			 * have been exhausted.
23908 			 */
23909 			last_zoneid = -1;
23910 			ILM_WALKER_HOLD(ill);
23911 			for (ilm = ill->ill_ilm; ilm != NULL;
23912 			    ilm = ilm->ilm_next) {
23913 				if ((ilm->ilm_flags & ILM_DELETED) ||
23914 				    ipha->ipha_dst != ilm->ilm_addr ||
23915 				    ilm->ilm_zoneid == last_zoneid ||
23916 				    ilm->ilm_zoneid == zoneid ||
23917 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
23918 					continue;
23919 				mp1 = ip_copymsg(first_mp);
23920 				if (mp1 == NULL)
23921 					continue;
23922 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23923 				    mctl_present, B_FALSE, ill,
23924 				    ilm->ilm_zoneid);
23925 				last_zoneid = ilm->ilm_zoneid;
23926 			}
23927 			ILM_WALKER_RELE(ill);
23928 			/*
23929 			 * Loopback case: the sending endpoint has
23930 			 * IP_MULTICAST_LOOP disabled, therefore we don't
23931 			 * dispatch the multicast packet to the sending zone.
23932 			 */
23933 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
23934 				freemsg(first_mp);
23935 				return;
23936 			}
23937 		} else if (ire_type == IRE_BROADCAST) {
23938 			/*
23939 			 * In the broadcast case, there may be many zones
23940 			 * which need a copy of the packet delivered to them.
23941 			 * There is one IRE_BROADCAST per broadcast address
23942 			 * and per zone; we walk those using a helper function.
23943 			 * In addition, the sending of the packet for zoneid is
23944 			 * delayed until all of the other ires have been
23945 			 * processed.
23946 			 */
23947 			IRB_REFHOLD(ire->ire_bucket);
23948 			ire_zone = NULL;
23949 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
23950 			    ire)) != NULL) {
23951 				mp1 = ip_copymsg(first_mp);
23952 				if (mp1 == NULL)
23953 					continue;
23954 
23955 				UPDATE_IB_PKT_COUNT(ire_zone);
23956 				ire_zone->ire_last_used_time = lbolt;
23957 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23958 				    mctl_present, B_FALSE, ill,
23959 				    ire_zone->ire_zoneid);
23960 			}
23961 			IRB_REFRELE(ire->ire_bucket);
23962 		}
23963 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
23964 		    0, mctl_present, B_FALSE, ill, zoneid);
23965 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23966 		    "ip_wput_local_end: q %p (%S)",
23967 		    q, "icmp");
23968 		return;
23969 	}
23970 	case IPPROTO_IGMP:
23971 		if (igmp_input(q, mp, ill)) {
23972 			/* Bad packet - discarded by igmp_input */
23973 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23974 			    "ip_wput_local_end: q %p (%S)",
23975 			    q, "igmp_input--bad packet");
23976 			if (mctl_present)
23977 				freeb(first_mp);
23978 			return;
23979 		}
23980 		/*
23981 		 * igmp_input() may have pulled up the message so ipha needs to
23982 		 * be reinitialized.
23983 		 */
23984 		ipha = (ipha_t *)mp->b_rptr;
23985 		/* deliver to local raw users */
23986 		break;
23987 	case IPPROTO_ENCAP:
23988 		/*
23989 		 * This case is covered by either ip_fanout_proto, or by
23990 		 * the above security processing for self-tunneled packets.
23991 		 */
23992 		break;
23993 	case IPPROTO_UDP: {
23994 		uint16_t	*up;
23995 		uint32_t	ports;
23996 
23997 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
23998 		    UDP_PORTS_OFFSET);
23999 		/* Force a 'valid' checksum. */
24000 		up[3] = 0;
24001 
24002 		ports = *(uint32_t *)up;
24003 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24004 		    (ire_type == IRE_BROADCAST),
24005 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24006 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
24007 		    ill, zoneid);
24008 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24009 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24010 		return;
24011 	}
24012 	case IPPROTO_TCP: {
24013 
24014 		/*
24015 		 * For TCP, discard broadcast packets.
24016 		 */
24017 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24018 			freemsg(first_mp);
24019 			BUMP_MIB(&ip_mib, ipInDiscards);
24020 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24021 			return;
24022 		}
24023 
24024 		if (mp->b_datap->db_type == M_DATA) {
24025 			/*
24026 			 * M_DATA mblk, so init mblk (chain) for no struio().
24027 			 */
24028 			mblk_t	*mp1 = mp;
24029 
24030 			do
24031 				mp1->b_datap->db_struioflag = 0;
24032 			while ((mp1 = mp1->b_cont) != NULL);
24033 		}
24034 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24035 		    <= mp->b_wptr);
24036 		ip_fanout_tcp(q, first_mp, ill, ipha,
24037 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24038 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
24039 		    mctl_present, B_FALSE, zoneid);
24040 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24041 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24042 		return;
24043 	}
24044 	case IPPROTO_SCTP:
24045 	{
24046 		uint32_t	ports;
24047 
24048 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24049 		ip_fanout_sctp(first_mp, ill, ipha, ports,
24050 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24051 		    IP_FF_IP6INFO,
24052 		    mctl_present, B_FALSE, 0, zoneid);
24053 		return;
24054 	}
24055 
24056 	default:
24057 		break;
24058 	}
24059 	/*
24060 	 * Find a client for some other protocol.  We give
24061 	 * copies to multiple clients, if more than one is
24062 	 * bound.
24063 	 */
24064 	ip_fanout_proto(q, first_mp, ill, ipha,
24065 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
24066 	    mctl_present, B_FALSE, ill, zoneid);
24067 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24068 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
24069 #undef	rptr
24070 }
24071 
24072 /*
24073  * Update any source route, record route, or timestamp options.
24074  * Check that we are at end of strict source route.
24075  * The options have been sanity checked by ip_wput_options().
24076  */
24077 static void
24078 ip_wput_local_options(ipha_t *ipha)
24079 {
24080 	ipoptp_t	opts;
24081 	uchar_t		*opt;
24082 	uint8_t		optval;
24083 	uint8_t		optlen;
24084 	ipaddr_t	dst;
24085 	uint32_t	ts;
24086 	ire_t		*ire;
24087 	timestruc_t	now;
24088 
24089 	ip2dbg(("ip_wput_local_options\n"));
24090 	for (optval = ipoptp_first(&opts, ipha);
24091 	    optval != IPOPT_EOL;
24092 	    optval = ipoptp_next(&opts)) {
24093 		opt = opts.ipoptp_cur;
24094 		optlen = opts.ipoptp_len;
24095 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
24096 		switch (optval) {
24097 			uint32_t off;
24098 		case IPOPT_SSRR:
24099 		case IPOPT_LSRR:
24100 			off = opt[IPOPT_OFFSET];
24101 			off--;
24102 			if (optlen < IP_ADDR_LEN ||
24103 			    off > optlen - IP_ADDR_LEN) {
24104 				/* End of source route */
24105 				break;
24106 			}
24107 			/*
24108 			 * This will only happen if two consecutive entries
24109 			 * in the source route contains our address or if
24110 			 * it is a packet with a loose source route which
24111 			 * reaches us before consuming the whole source route
24112 			 */
24113 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
24114 			if (optval == IPOPT_SSRR) {
24115 				return;
24116 			}
24117 			/*
24118 			 * Hack: instead of dropping the packet truncate the
24119 			 * source route to what has been used by filling the
24120 			 * rest with IPOPT_NOP.
24121 			 */
24122 			opt[IPOPT_OLEN] = (uint8_t)off;
24123 			while (off < optlen) {
24124 				opt[off++] = IPOPT_NOP;
24125 			}
24126 			break;
24127 		case IPOPT_RR:
24128 			off = opt[IPOPT_OFFSET];
24129 			off--;
24130 			if (optlen < IP_ADDR_LEN ||
24131 			    off > optlen - IP_ADDR_LEN) {
24132 				/* No more room - ignore */
24133 				ip1dbg((
24134 				    "ip_wput_forward_options: end of RR\n"));
24135 				break;
24136 			}
24137 			dst = htonl(INADDR_LOOPBACK);
24138 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24139 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24140 			break;
24141 		case IPOPT_TS:
24142 			/* Insert timestamp if there is romm */
24143 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24144 			case IPOPT_TS_TSONLY:
24145 				off = IPOPT_TS_TIMELEN;
24146 				break;
24147 			case IPOPT_TS_PRESPEC:
24148 			case IPOPT_TS_PRESPEC_RFC791:
24149 				/* Verify that the address matched */
24150 				off = opt[IPOPT_OFFSET] - 1;
24151 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
24152 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
24153 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
24154 				if (ire == NULL) {
24155 					/* Not for us */
24156 					break;
24157 				}
24158 				ire_refrele(ire);
24159 				/* FALLTHRU */
24160 			case IPOPT_TS_TSANDADDR:
24161 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24162 				break;
24163 			default:
24164 				/*
24165 				 * ip_*put_options should have already
24166 				 * dropped this packet.
24167 				 */
24168 				cmn_err(CE_PANIC, "ip_wput_local_options: "
24169 				    "unknown IT - bug in ip_wput_options?\n");
24170 				return;	/* Keep "lint" happy */
24171 			}
24172 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
24173 				/* Increase overflow counter */
24174 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
24175 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
24176 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
24177 				    (off << 4);
24178 				break;
24179 			}
24180 			off = opt[IPOPT_OFFSET] - 1;
24181 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24182 			case IPOPT_TS_PRESPEC:
24183 			case IPOPT_TS_PRESPEC_RFC791:
24184 			case IPOPT_TS_TSANDADDR:
24185 				dst = htonl(INADDR_LOOPBACK);
24186 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24187 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24188 				/* FALLTHRU */
24189 			case IPOPT_TS_TSONLY:
24190 				off = opt[IPOPT_OFFSET] - 1;
24191 				/* Compute # of milliseconds since midnight */
24192 				gethrestime(&now);
24193 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
24194 				    now.tv_nsec / (NANOSEC / MILLISEC);
24195 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
24196 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
24197 				break;
24198 			}
24199 			break;
24200 		}
24201 	}
24202 }
24203 
24204 /*
24205  * Send out a multicast packet on interface ipif.
24206  * The sender does not have an conn.
24207  * Caller verifies that this isn't a PHYI_LOOPBACK.
24208  */
24209 void
24210 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
24211 {
24212 	ipha_t	*ipha;
24213 	ire_t	*ire;
24214 	ipaddr_t	dst;
24215 	mblk_t		*first_mp;
24216 
24217 	/* igmp_sendpkt always allocates a ipsec_out_t */
24218 	ASSERT(mp->b_datap->db_type == M_CTL);
24219 	ASSERT(!ipif->ipif_isv6);
24220 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
24221 
24222 	first_mp = mp;
24223 	mp = first_mp->b_cont;
24224 	ASSERT(mp->b_datap->db_type == M_DATA);
24225 	ipha = (ipha_t *)mp->b_rptr;
24226 
24227 	/*
24228 	 * Find an IRE which matches the destination and the outgoing
24229 	 * queue (i.e. the outgoing interface.)
24230 	 */
24231 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
24232 		dst = ipif->ipif_pp_dst_addr;
24233 	else
24234 		dst = ipha->ipha_dst;
24235 	/*
24236 	 * The source address has already been initialized by the
24237 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
24238 	 * be sufficient rather than MATCH_IRE_IPIF.
24239 	 *
24240 	 * This function is used for sending IGMP packets. We need
24241 	 * to make sure that we send the packet out of the interface
24242 	 * (ipif->ipif_ill) where we joined the group. This is to
24243 	 * prevent from switches doing IGMP snooping to send us multicast
24244 	 * packets for a given group on the interface we have joined.
24245 	 * If we can't find an ire, igmp_sendpkt has already initialized
24246 	 * ipsec_out_attach_if so that this will not be load spread in
24247 	 * ip_newroute_ipif.
24248 	 */
24249 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
24250 	    MATCH_IRE_ILL);
24251 	if (!ire) {
24252 		/*
24253 		 * Mark this packet to make it be delivered to
24254 		 * ip_wput_ire after the new ire has been
24255 		 * created.
24256 		 */
24257 		mp->b_prev = NULL;
24258 		mp->b_next = NULL;
24259 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
24260 		    zoneid);
24261 		return;
24262 	}
24263 
24264 	/*
24265 	 * Honor the RTF_SETSRC flag; this is the only case
24266 	 * where we force this addr whatever the current src addr is,
24267 	 * because this address is set by igmp_sendpkt(), and
24268 	 * cannot be specified by any user.
24269 	 */
24270 	if (ire->ire_flags & RTF_SETSRC) {
24271 		ipha->ipha_src = ire->ire_src_addr;
24272 	}
24273 
24274 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
24275 }
24276 
24277 /*
24278  * NOTE : This function does not ire_refrele the ire argument passed in.
24279  *
24280  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
24281  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
24282  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
24283  * the ire_lock to access the nce_fp_mp in this case.
24284  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
24285  * prepending a fastpath message IPQoS processing must precede it, we also set
24286  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
24287  * (IPQoS might have set the b_band for CoS marking).
24288  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
24289  * must follow it so that IPQoS can mark the dl_priority field for CoS
24290  * marking, if needed.
24291  */
24292 static mblk_t *
24293 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
24294 {
24295 	uint_t	hlen;
24296 	ipha_t *ipha;
24297 	mblk_t *mp1;
24298 	boolean_t qos_done = B_FALSE;
24299 	uchar_t	*ll_hdr;
24300 
24301 #define	rptr	((uchar_t *)ipha)
24302 
24303 	ipha = (ipha_t *)mp->b_rptr;
24304 	hlen = 0;
24305 	LOCK_IRE_FP_MP(ire);
24306 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
24307 		ASSERT(DB_TYPE(mp1) == M_DATA);
24308 		/* Initiate IPPF processing */
24309 		if ((proc != 0) && IPP_ENABLED(proc)) {
24310 			UNLOCK_IRE_FP_MP(ire);
24311 			ip_process(proc, &mp, ill_index);
24312 			if (mp == NULL)
24313 				return (NULL);
24314 
24315 			ipha = (ipha_t *)mp->b_rptr;
24316 			LOCK_IRE_FP_MP(ire);
24317 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
24318 				qos_done = B_TRUE;
24319 				goto no_fp_mp;
24320 			}
24321 			ASSERT(DB_TYPE(mp1) == M_DATA);
24322 		}
24323 		hlen = MBLKL(mp1);
24324 		/*
24325 		 * Check if we have enough room to prepend fastpath
24326 		 * header
24327 		 */
24328 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
24329 			ll_hdr = rptr - hlen;
24330 			bcopy(mp1->b_rptr, ll_hdr, hlen);
24331 			/*
24332 			 * Set the b_rptr to the start of the link layer
24333 			 * header
24334 			 */
24335 			mp->b_rptr = ll_hdr;
24336 			mp1 = mp;
24337 		} else {
24338 			mp1 = copyb(mp1);
24339 			if (mp1 == NULL)
24340 				goto unlock_err;
24341 			mp1->b_band = mp->b_band;
24342 			mp1->b_cont = mp;
24343 			/*
24344 			 * certain system generated traffic may not
24345 			 * have cred/label in ip header block. This
24346 			 * is true even for a labeled system. But for
24347 			 * labeled traffic, inherit the label in the
24348 			 * new header.
24349 			 */
24350 			if (DB_CRED(mp) != NULL)
24351 				mblk_setcred(mp1, DB_CRED(mp));
24352 			/*
24353 			 * XXX disable ICK_VALID and compute checksum
24354 			 * here; can happen if nce_fp_mp changes and
24355 			 * it can't be copied now due to insufficient
24356 			 * space. (unlikely, fp mp can change, but it
24357 			 * does not increase in length)
24358 			 */
24359 		}
24360 		UNLOCK_IRE_FP_MP(ire);
24361 	} else {
24362 no_fp_mp:
24363 		mp1 = copyb(ire->ire_nce->nce_res_mp);
24364 		if (mp1 == NULL) {
24365 unlock_err:
24366 			UNLOCK_IRE_FP_MP(ire);
24367 			freemsg(mp);
24368 			return (NULL);
24369 		}
24370 		UNLOCK_IRE_FP_MP(ire);
24371 		mp1->b_cont = mp;
24372 		/*
24373 		 * certain system generated traffic may not
24374 		 * have cred/label in ip header block. This
24375 		 * is true even for a labeled system. But for
24376 		 * labeled traffic, inherit the label in the
24377 		 * new header.
24378 		 */
24379 		if (DB_CRED(mp) != NULL)
24380 			mblk_setcred(mp1, DB_CRED(mp));
24381 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
24382 			ip_process(proc, &mp1, ill_index);
24383 			if (mp1 == NULL)
24384 				return (NULL);
24385 		}
24386 	}
24387 	return (mp1);
24388 #undef rptr
24389 }
24390 
24391 /*
24392  * Finish the outbound IPsec processing for an IPv6 packet. This function
24393  * is called from ipsec_out_process() if the IPsec packet was processed
24394  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24395  * asynchronously.
24396  */
24397 void
24398 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
24399     ire_t *ire_arg)
24400 {
24401 	in6_addr_t *v6dstp;
24402 	ire_t *ire;
24403 	mblk_t *mp;
24404 	uint_t	ill_index;
24405 	ipsec_out_t *io;
24406 	boolean_t attach_if, hwaccel;
24407 	uint32_t flags = IP6_NO_IPPOLICY;
24408 	int match_flags;
24409 	zoneid_t zoneid;
24410 	boolean_t ill_need_rele = B_FALSE;
24411 	boolean_t ire_need_rele = B_FALSE;
24412 
24413 	mp = ipsec_mp->b_cont;
24414 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24415 	ill_index = io->ipsec_out_ill_index;
24416 	if (io->ipsec_out_reachable) {
24417 		flags |= IPV6_REACHABILITY_CONFIRMATION;
24418 	}
24419 	attach_if = io->ipsec_out_attach_if;
24420 	hwaccel = io->ipsec_out_accelerated;
24421 	zoneid = io->ipsec_out_zoneid;
24422 	ASSERT(zoneid != ALL_ZONES);
24423 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24424 	/* Multicast addresses should have non-zero ill_index. */
24425 	v6dstp = &ip6h->ip6_dst;
24426 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
24427 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
24428 	ASSERT(!attach_if || ill_index != 0);
24429 	if (ill_index != 0) {
24430 		if (ill == NULL) {
24431 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
24432 			    B_TRUE);
24433 
24434 			/* Failure case frees things for us. */
24435 			if (ill == NULL)
24436 				return;
24437 
24438 			ill_need_rele = B_TRUE;
24439 		}
24440 		/*
24441 		 * If this packet needs to go out on a particular interface
24442 		 * honor it.
24443 		 */
24444 		if (attach_if) {
24445 			match_flags = MATCH_IRE_ILL;
24446 
24447 			/*
24448 			 * Check if we need an ire that will not be
24449 			 * looked up by anybody else i.e. HIDDEN.
24450 			 */
24451 			if (ill_is_probeonly(ill)) {
24452 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24453 			}
24454 		}
24455 	}
24456 	ASSERT(mp != NULL);
24457 
24458 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
24459 		boolean_t unspec_src;
24460 		ipif_t	*ipif;
24461 
24462 		/*
24463 		 * Use the ill_index to get the right ill.
24464 		 */
24465 		unspec_src = io->ipsec_out_unspec_src;
24466 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24467 		if (ipif == NULL) {
24468 			if (ill_need_rele)
24469 				ill_refrele(ill);
24470 			freemsg(ipsec_mp);
24471 			return;
24472 		}
24473 
24474 		if (ire_arg != NULL) {
24475 			ire = ire_arg;
24476 		} else {
24477 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24478 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24479 			ire_need_rele = B_TRUE;
24480 		}
24481 		if (ire != NULL) {
24482 			ipif_refrele(ipif);
24483 			/*
24484 			 * XXX Do the multicast forwarding now, as the IPSEC
24485 			 * processing has been done.
24486 			 */
24487 			goto send;
24488 		}
24489 
24490 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
24491 		mp->b_prev = NULL;
24492 		mp->b_next = NULL;
24493 
24494 		/*
24495 		 * If the IPsec packet was processed asynchronously,
24496 		 * drop it now.
24497 		 */
24498 		if (q == NULL) {
24499 			if (ill_need_rele)
24500 				ill_refrele(ill);
24501 			freemsg(ipsec_mp);
24502 			return;
24503 		}
24504 
24505 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
24506 		    unspec_src, zoneid);
24507 		ipif_refrele(ipif);
24508 	} else {
24509 		if (attach_if) {
24510 			ipif_t	*ipif;
24511 
24512 			ipif = ipif_get_next_ipif(NULL, ill);
24513 			if (ipif == NULL) {
24514 				if (ill_need_rele)
24515 					ill_refrele(ill);
24516 				freemsg(ipsec_mp);
24517 				return;
24518 			}
24519 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24520 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24521 			ire_need_rele = B_TRUE;
24522 			ipif_refrele(ipif);
24523 		} else {
24524 			if (ire_arg != NULL) {
24525 				ire = ire_arg;
24526 			} else {
24527 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
24528 				ire_need_rele = B_TRUE;
24529 			}
24530 		}
24531 		if (ire != NULL)
24532 			goto send;
24533 		/*
24534 		 * ire disappeared underneath.
24535 		 *
24536 		 * What we need to do here is the ip_newroute
24537 		 * logic to get the ire without doing the IPSEC
24538 		 * processing. Follow the same old path. But this
24539 		 * time, ip_wput or ire_add_then_send will call us
24540 		 * directly as all the IPSEC operations are done.
24541 		 */
24542 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
24543 		mp->b_prev = NULL;
24544 		mp->b_next = NULL;
24545 
24546 		/*
24547 		 * If the IPsec packet was processed asynchronously,
24548 		 * drop it now.
24549 		 */
24550 		if (q == NULL) {
24551 			if (ill_need_rele)
24552 				ill_refrele(ill);
24553 			freemsg(ipsec_mp);
24554 			return;
24555 		}
24556 
24557 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
24558 		    zoneid);
24559 	}
24560 	if (ill != NULL && ill_need_rele)
24561 		ill_refrele(ill);
24562 	return;
24563 send:
24564 	if (ill != NULL && ill_need_rele)
24565 		ill_refrele(ill);
24566 
24567 	/* Local delivery */
24568 	if (ire->ire_stq == NULL) {
24569 		ASSERT(q != NULL);
24570 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
24571 		    ire, 0);
24572 		if (ire_need_rele)
24573 			ire_refrele(ire);
24574 		return;
24575 	}
24576 	/*
24577 	 * Everything is done. Send it out on the wire.
24578 	 * We force the insertion of a fragment header using the
24579 	 * IPH_FRAG_HDR flag in two cases:
24580 	 * - after reception of an ICMPv6 "packet too big" message
24581 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
24582 	 * - for multirouted IPv6 packets, so that the receiver can
24583 	 *   discard duplicates according to their fragment identifier
24584 	 */
24585 	/* XXX fix flow control problems. */
24586 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
24587 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
24588 		if (hwaccel) {
24589 			/*
24590 			 * hardware acceleration does not handle these
24591 			 * "slow path" cases.
24592 			 */
24593 			/* IPsec KSTATS: should bump bean counter here. */
24594 			if (ire_need_rele)
24595 				ire_refrele(ire);
24596 			freemsg(ipsec_mp);
24597 			return;
24598 		}
24599 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
24600 		    (mp->b_cont ? msgdsize(mp) :
24601 		    mp->b_wptr - (uchar_t *)ip6h)) {
24602 			/* IPsec KSTATS: should bump bean counter here. */
24603 			ip0dbg(("Packet length mismatch: %d, %ld\n",
24604 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
24605 			    msgdsize(mp)));
24606 			if (ire_need_rele)
24607 				ire_refrele(ire);
24608 			freemsg(ipsec_mp);
24609 			return;
24610 		}
24611 		ASSERT(mp->b_prev == NULL);
24612 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
24613 		    ntohs(ip6h->ip6_plen) +
24614 		    IPV6_HDR_LEN, ire->ire_max_frag));
24615 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
24616 		    ire->ire_max_frag);
24617 	} else {
24618 		UPDATE_OB_PKT_COUNT(ire);
24619 		ire->ire_last_used_time = lbolt;
24620 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
24621 	}
24622 	if (ire_need_rele)
24623 		ire_refrele(ire);
24624 	freeb(ipsec_mp);
24625 }
24626 
24627 void
24628 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
24629 {
24630 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
24631 	da_ipsec_t *hada;	/* data attributes */
24632 	ill_t *ill = (ill_t *)q->q_ptr;
24633 
24634 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
24635 
24636 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
24637 		/* IPsec KSTATS: Bump lose counter here! */
24638 		freemsg(mp);
24639 		return;
24640 	}
24641 
24642 	/*
24643 	 * It's an IPsec packet that must be
24644 	 * accelerated by the Provider, and the
24645 	 * outbound ill is IPsec acceleration capable.
24646 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
24647 	 * to the ill.
24648 	 * IPsec KSTATS: should bump packet counter here.
24649 	 */
24650 
24651 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
24652 	if (hada_mp == NULL) {
24653 		/* IPsec KSTATS: should bump packet counter here. */
24654 		freemsg(mp);
24655 		return;
24656 	}
24657 
24658 	hada_mp->b_datap->db_type = M_CTL;
24659 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
24660 	hada_mp->b_cont = mp;
24661 
24662 	hada = (da_ipsec_t *)hada_mp->b_rptr;
24663 	bzero(hada, sizeof (da_ipsec_t));
24664 	hada->da_type = IPHADA_M_CTL;
24665 
24666 	putnext(q, hada_mp);
24667 }
24668 
24669 /*
24670  * Finish the outbound IPsec processing. This function is called from
24671  * ipsec_out_process() if the IPsec packet was processed
24672  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24673  * asynchronously.
24674  */
24675 void
24676 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
24677     ire_t *ire_arg)
24678 {
24679 	uint32_t v_hlen_tos_len;
24680 	ipaddr_t	dst;
24681 	ipif_t	*ipif = NULL;
24682 	ire_t *ire;
24683 	ire_t *ire1 = NULL;
24684 	mblk_t *next_mp = NULL;
24685 	uint32_t max_frag;
24686 	boolean_t multirt_send = B_FALSE;
24687 	mblk_t *mp;
24688 	mblk_t *mp1;
24689 	uint_t	ill_index;
24690 	ipsec_out_t *io;
24691 	boolean_t attach_if;
24692 	int match_flags, offset;
24693 	irb_t *irb = NULL;
24694 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
24695 	zoneid_t zoneid;
24696 	uint32_t cksum;
24697 	uint16_t *up;
24698 	ipxmit_state_t	pktxmit_state;
24699 #ifdef	_BIG_ENDIAN
24700 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
24701 #else
24702 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
24703 #endif
24704 
24705 	mp = ipsec_mp->b_cont;
24706 	ASSERT(mp != NULL);
24707 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24708 	dst = ipha->ipha_dst;
24709 
24710 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24711 	ill_index = io->ipsec_out_ill_index;
24712 	attach_if = io->ipsec_out_attach_if;
24713 	zoneid = io->ipsec_out_zoneid;
24714 	ASSERT(zoneid != ALL_ZONES);
24715 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24716 	if (ill_index != 0) {
24717 		if (ill == NULL) {
24718 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
24719 			    ill_index, B_FALSE);
24720 
24721 			/* Failure case frees things for us. */
24722 			if (ill == NULL)
24723 				return;
24724 
24725 			ill_need_rele = B_TRUE;
24726 		}
24727 		/*
24728 		 * If this packet needs to go out on a particular interface
24729 		 * honor it.
24730 		 */
24731 		if (attach_if) {
24732 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
24733 
24734 			/*
24735 			 * Check if we need an ire that will not be
24736 			 * looked up by anybody else i.e. HIDDEN.
24737 			 */
24738 			if (ill_is_probeonly(ill)) {
24739 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24740 			}
24741 		}
24742 	}
24743 
24744 	if (CLASSD(dst)) {
24745 		boolean_t conn_dontroute;
24746 		/*
24747 		 * Use the ill_index to get the right ipif.
24748 		 */
24749 		conn_dontroute = io->ipsec_out_dontroute;
24750 		if (ill_index == 0)
24751 			ipif = ipif_lookup_group(dst, zoneid);
24752 		else
24753 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24754 		if (ipif == NULL) {
24755 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
24756 			    " multicast\n"));
24757 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
24758 			freemsg(ipsec_mp);
24759 			goto done;
24760 		}
24761 		/*
24762 		 * ipha_src has already been intialized with the
24763 		 * value of the ipif in ip_wput. All we need now is
24764 		 * an ire to send this downstream.
24765 		 */
24766 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
24767 		    MBLK_GETLABEL(mp), match_flags);
24768 		if (ire != NULL) {
24769 			ill_t *ill1;
24770 			/*
24771 			 * Do the multicast forwarding now, as the IPSEC
24772 			 * processing has been done.
24773 			 */
24774 			if (ip_g_mrouter && !conn_dontroute &&
24775 			    (ill1 = ire_to_ill(ire))) {
24776 				if (ip_mforward(ill1, ipha, mp)) {
24777 					freemsg(ipsec_mp);
24778 					ip1dbg(("ip_wput_ipsec_out: mforward "
24779 					    "failed\n"));
24780 					ire_refrele(ire);
24781 					goto done;
24782 				}
24783 			}
24784 			goto send;
24785 		}
24786 
24787 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
24788 		mp->b_prev = NULL;
24789 		mp->b_next = NULL;
24790 
24791 		/*
24792 		 * If the IPsec packet was processed asynchronously,
24793 		 * drop it now.
24794 		 */
24795 		if (q == NULL) {
24796 			freemsg(ipsec_mp);
24797 			goto done;
24798 		}
24799 
24800 		/*
24801 		 * We may be using a wrong ipif to create the ire.
24802 		 * But it is okay as the source address is assigned
24803 		 * for the packet already. Next outbound packet would
24804 		 * create the IRE with the right IPIF in ip_wput.
24805 		 *
24806 		 * Also handle RTF_MULTIRT routes.
24807 		 */
24808 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
24809 		    zoneid);
24810 	} else {
24811 		if (attach_if) {
24812 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
24813 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24814 		} else {
24815 			if (ire_arg != NULL) {
24816 				ire = ire_arg;
24817 				ire_need_rele = B_FALSE;
24818 			} else {
24819 				ire = ire_cache_lookup(dst, zoneid,
24820 				    MBLK_GETLABEL(mp));
24821 			}
24822 		}
24823 		if (ire != NULL) {
24824 			goto send;
24825 		}
24826 
24827 		/*
24828 		 * ire disappeared underneath.
24829 		 *
24830 		 * What we need to do here is the ip_newroute
24831 		 * logic to get the ire without doing the IPSEC
24832 		 * processing. Follow the same old path. But this
24833 		 * time, ip_wput or ire_add_then_put will call us
24834 		 * directly as all the IPSEC operations are done.
24835 		 */
24836 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
24837 		mp->b_prev = NULL;
24838 		mp->b_next = NULL;
24839 
24840 		/*
24841 		 * If the IPsec packet was processed asynchronously,
24842 		 * drop it now.
24843 		 */
24844 		if (q == NULL) {
24845 			freemsg(ipsec_mp);
24846 			goto done;
24847 		}
24848 
24849 		/*
24850 		 * Since we're going through ip_newroute() again, we
24851 		 * need to make sure we don't:
24852 		 *
24853 		 *	1.) Trigger the ASSERT() with the ipha_ident
24854 		 *	    overloading.
24855 		 *	2.) Redo transport-layer checksumming, since we've
24856 		 *	    already done all that to get this far.
24857 		 *
24858 		 * The easiest way not do either of the above is to set
24859 		 * the ipha_ident field to IP_HDR_INCLUDED.
24860 		 */
24861 		ipha->ipha_ident = IP_HDR_INCLUDED;
24862 		ip_newroute(q, ipsec_mp, dst, NULL,
24863 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid);
24864 	}
24865 	goto done;
24866 send:
24867 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
24868 		/*
24869 		 * ESP NAT-Traversal packet.
24870 		 *
24871 		 * Just do software checksum for now.
24872 		 */
24873 
24874 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
24875 		IP_STAT(ip_out_sw_cksum);
24876 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
24877 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
24878 #define	iphs	((uint16_t *)ipha)
24879 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
24880 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
24881 		    IP_SIMPLE_HDR_LENGTH);
24882 #undef iphs
24883 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
24884 			cksum = 0xFFFF;
24885 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
24886 			if (mp1->b_wptr - mp1->b_rptr >=
24887 			    offset + sizeof (uint16_t)) {
24888 				up = (uint16_t *)(mp1->b_rptr + offset);
24889 				*up = cksum;
24890 				break;	/* out of for loop */
24891 			} else {
24892 				offset -= (mp->b_wptr - mp->b_rptr);
24893 			}
24894 	} /* Otherwise, just keep the all-zero checksum. */
24895 
24896 	if (ire->ire_stq == NULL) {
24897 		/*
24898 		 * Loopbacks go through ip_wput_local except for one case.
24899 		 * We come here if we generate a icmp_frag_needed message
24900 		 * after IPSEC processing is over. When this function calls
24901 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
24902 		 * icmp_frag_needed. The message generated comes back here
24903 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
24904 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
24905 		 * source address as it is usually set in ip_wput_ire. As
24906 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
24907 		 * and we end up here. We can't enter ip_wput_ire once the
24908 		 * IPSEC processing is over and hence we need to do it here.
24909 		 */
24910 		ASSERT(q != NULL);
24911 		UPDATE_OB_PKT_COUNT(ire);
24912 		ire->ire_last_used_time = lbolt;
24913 		if (ipha->ipha_src == 0)
24914 			ipha->ipha_src = ire->ire_src_addr;
24915 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
24916 		    ire, 0, zoneid);
24917 		if (ire_need_rele)
24918 			ire_refrele(ire);
24919 		goto done;
24920 	}
24921 
24922 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
24923 		/*
24924 		 * We are through with IPSEC processing.
24925 		 * Fragment this and send it on the wire.
24926 		 */
24927 		if (io->ipsec_out_accelerated) {
24928 			/*
24929 			 * The packet has been accelerated but must
24930 			 * be fragmented. This should not happen
24931 			 * since AH and ESP must not accelerate
24932 			 * packets that need fragmentation, however
24933 			 * the configuration could have changed
24934 			 * since the AH or ESP processing.
24935 			 * Drop packet.
24936 			 * IPsec KSTATS: bump bean counter here.
24937 			 */
24938 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
24939 			    "fragmented accelerated packet!\n"));
24940 			freemsg(ipsec_mp);
24941 		} else {
24942 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid);
24943 		}
24944 		if (ire_need_rele)
24945 			ire_refrele(ire);
24946 		goto done;
24947 	}
24948 
24949 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
24950 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
24951 	    (void *)ire->ire_ipif, (void *)ipif));
24952 
24953 	/*
24954 	 * Multiroute the secured packet, unless IPsec really
24955 	 * requires the packet to go out only through a particular
24956 	 * interface.
24957 	 */
24958 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
24959 		ire_t *first_ire;
24960 		irb = ire->ire_bucket;
24961 		ASSERT(irb != NULL);
24962 		/*
24963 		 * This ire has been looked up as the one that
24964 		 * goes through the given ipif;
24965 		 * make sure we do not omit any other multiroute ire
24966 		 * that may be present in the bucket before this one.
24967 		 */
24968 		IRB_REFHOLD(irb);
24969 		for (first_ire = irb->irb_ire;
24970 		    first_ire != NULL;
24971 		    first_ire = first_ire->ire_next) {
24972 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24973 			    (first_ire->ire_addr == ire->ire_addr) &&
24974 			    !(first_ire->ire_marks &
24975 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24976 				break;
24977 		}
24978 
24979 		if ((first_ire != NULL) && (first_ire != ire)) {
24980 			/*
24981 			 * Don't change the ire if the packet must
24982 			 * be fragmented if sent via this new one.
24983 			 */
24984 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
24985 				IRE_REFHOLD(first_ire);
24986 				if (ire_need_rele)
24987 					ire_refrele(ire);
24988 				else
24989 					ire_need_rele = B_TRUE;
24990 				ire = first_ire;
24991 			}
24992 		}
24993 		IRB_REFRELE(irb);
24994 
24995 		multirt_send = B_TRUE;
24996 		max_frag = ire->ire_max_frag;
24997 	} else {
24998 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
24999 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25000 			    "flag, attach_if %d\n", attach_if));
25001 		}
25002 	}
25003 
25004 	/*
25005 	 * In most cases, the emission loop below is entered only once.
25006 	 * Only in the case where the ire holds the RTF_MULTIRT
25007 	 * flag, we loop to process all RTF_MULTIRT ires in the
25008 	 * bucket, and send the packet through all crossed
25009 	 * RTF_MULTIRT routes.
25010 	 */
25011 	do {
25012 		if (multirt_send) {
25013 			/*
25014 			 * ire1 holds here the next ire to process in the
25015 			 * bucket. If multirouting is expected,
25016 			 * any non-RTF_MULTIRT ire that has the
25017 			 * right destination address is ignored.
25018 			 */
25019 			ASSERT(irb != NULL);
25020 			IRB_REFHOLD(irb);
25021 			for (ire1 = ire->ire_next;
25022 			    ire1 != NULL;
25023 			    ire1 = ire1->ire_next) {
25024 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
25025 					continue;
25026 				if (ire1->ire_addr != ire->ire_addr)
25027 					continue;
25028 				if (ire1->ire_marks &
25029 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
25030 					continue;
25031 				/* No loopback here */
25032 				if (ire1->ire_stq == NULL)
25033 					continue;
25034 				/*
25035 				 * Ensure we do not exceed the MTU
25036 				 * of the next route.
25037 				 */
25038 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
25039 					ip_multirt_bad_mtu(ire1, max_frag);
25040 					continue;
25041 				}
25042 
25043 				IRE_REFHOLD(ire1);
25044 				break;
25045 			}
25046 			IRB_REFRELE(irb);
25047 			if (ire1 != NULL) {
25048 				/*
25049 				 * We are in a multiple send case, need to
25050 				 * make a copy of the packet.
25051 				 */
25052 				next_mp = copymsg(ipsec_mp);
25053 				if (next_mp == NULL) {
25054 					ire_refrele(ire1);
25055 					ire1 = NULL;
25056 				}
25057 			}
25058 		}
25059 		/*
25060 		 * Everything is done. Send it out on the wire
25061 		 *
25062 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
25063 		 * either send it on the wire or, in the case of
25064 		 * HW acceleration, call ipsec_hw_putnext.
25065 		 */
25066 		if (ire->ire_nce &&
25067 		    ire->ire_nce->nce_state != ND_REACHABLE) {
25068 			DTRACE_PROBE2(ip__wput__ipsec__bail,
25069 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
25070 			/*
25071 			 * If ire's link-layer is unresolved (this
25072 			 * would only happen if the incomplete ire
25073 			 * was added to cachetable via forwarding path)
25074 			 * don't bother going to ip_xmit_v4. Just drop the
25075 			 * packet.
25076 			 * There is a slight risk here, in that, if we
25077 			 * have the forwarding path create an incomplete
25078 			 * IRE, then until the IRE is completed, any
25079 			 * transmitted IPSEC packets will be dropped
25080 			 * instead of being queued waiting for resolution.
25081 			 *
25082 			 * But the likelihood of a forwarding packet and a wput
25083 			 * packet sending to the same dst at the same time
25084 			 * and there not yet be an ARP entry for it is small.
25085 			 * Furthermore, if this actually happens, it might
25086 			 * be likely that wput would generate multiple
25087 			 * packets (and forwarding would also have a train
25088 			 * of packets) for that destination. If this is
25089 			 * the case, some of them would have been dropped
25090 			 * anyway, since ARP only queues a few packets while
25091 			 * waiting for resolution
25092 			 *
25093 			 * NOTE: We should really call ip_xmit_v4,
25094 			 * and let it queue the packet and send the
25095 			 * ARP query and have ARP come back thus:
25096 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
25097 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
25098 			 * hw accel work. But it's too complex to get
25099 			 * the IPsec hw  acceleration approach to fit
25100 			 * well with ip_xmit_v4 doing ARP without
25101 			 * doing IPSEC simplification. For now, we just
25102 			 * poke ip_xmit_v4 to trigger the arp resolve, so
25103 			 * that we can continue with the send on the next
25104 			 * attempt.
25105 			 *
25106 			 * XXX THis should be revisited, when
25107 			 * the IPsec/IP interaction is cleaned up
25108 			 */
25109 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
25110 			    " - dropping packet\n"));
25111 			freemsg(ipsec_mp);
25112 			/*
25113 			 * Call ip_xmit_v4() to trigger ARP query
25114 			 * in case the nce_state is ND_INITIAL
25115 			 */
25116 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
25117 			goto drop_pkt;
25118 		}
25119 
25120 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
25121 		pktxmit_state = ip_xmit_v4(mp, ire,
25122 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
25123 
25124 		if ((pktxmit_state ==  SEND_FAILED) ||
25125 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
25126 
25127 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
25128 drop_pkt:
25129 			BUMP_MIB(&ip_mib, ipOutDiscards);
25130 			if (ire_need_rele)
25131 				ire_refrele(ire);
25132 			if (ire1 != NULL) {
25133 				ire_refrele(ire1);
25134 				freemsg(next_mp);
25135 			}
25136 			goto done;
25137 		}
25138 
25139 		freeb(ipsec_mp);
25140 		if (ire_need_rele)
25141 			ire_refrele(ire);
25142 
25143 		if (ire1 != NULL) {
25144 			ire = ire1;
25145 			ire_need_rele = B_TRUE;
25146 			ASSERT(next_mp);
25147 			ipsec_mp = next_mp;
25148 			mp = ipsec_mp->b_cont;
25149 			ire1 = NULL;
25150 			next_mp = NULL;
25151 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
25152 		} else {
25153 			multirt_send = B_FALSE;
25154 		}
25155 	} while (multirt_send);
25156 done:
25157 	if (ill != NULL && ill_need_rele)
25158 		ill_refrele(ill);
25159 	if (ipif != NULL)
25160 		ipif_refrele(ipif);
25161 }
25162 
25163 /*
25164  * Get the ill corresponding to the specified ire, and compare its
25165  * capabilities with the protocol and algorithms specified by the
25166  * the SA obtained from ipsec_out. If they match, annotate the
25167  * ipsec_out structure to indicate that the packet needs acceleration.
25168  *
25169  *
25170  * A packet is eligible for outbound hardware acceleration if the
25171  * following conditions are satisfied:
25172  *
25173  * 1. the packet will not be fragmented
25174  * 2. the provider supports the algorithm
25175  * 3. there is no pending control message being exchanged
25176  * 4. snoop is not attached
25177  * 5. the destination address is not a broadcast or multicast address.
25178  *
25179  * Rationale:
25180  *	- Hardware drivers do not support fragmentation with
25181  *	  the current interface.
25182  *	- snoop, multicast, and broadcast may result in exposure of
25183  *	  a cleartext datagram.
25184  * We check all five of these conditions here.
25185  *
25186  * XXX would like to nuke "ire_t *" parameter here; problem is that
25187  * IRE is only way to figure out if a v4 address is a broadcast and
25188  * thus ineligible for acceleration...
25189  */
25190 static void
25191 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
25192 {
25193 	ipsec_out_t *io;
25194 	mblk_t *data_mp;
25195 	uint_t plen, overhead;
25196 
25197 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
25198 		return;
25199 
25200 	if (ill == NULL)
25201 		return;
25202 
25203 	/*
25204 	 * Destination address is a broadcast or multicast.  Punt.
25205 	 */
25206 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
25207 	    IRE_LOCAL)))
25208 		return;
25209 
25210 	data_mp = ipsec_mp->b_cont;
25211 
25212 	if (ill->ill_isv6) {
25213 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
25214 
25215 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
25216 			return;
25217 
25218 		plen = ip6h->ip6_plen;
25219 	} else {
25220 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
25221 
25222 		if (CLASSD(ipha->ipha_dst))
25223 			return;
25224 
25225 		plen = ipha->ipha_length;
25226 	}
25227 	/*
25228 	 * Is there a pending DLPI control message being exchanged
25229 	 * between IP/IPsec and the DLS Provider? If there is, it
25230 	 * could be a SADB update, and the state of the DLS Provider
25231 	 * SADB might not be in sync with the SADB maintained by
25232 	 * IPsec. To avoid dropping packets or using the wrong keying
25233 	 * material, we do not accelerate this packet.
25234 	 */
25235 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
25236 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25237 		    "ill_dlpi_pending! don't accelerate packet\n"));
25238 		return;
25239 	}
25240 
25241 	/*
25242 	 * Is the Provider in promiscous mode? If it does, we don't
25243 	 * accelerate the packet since it will bounce back up to the
25244 	 * listeners in the clear.
25245 	 */
25246 	if (ill->ill_promisc_on_phys) {
25247 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25248 		    "ill in promiscous mode, don't accelerate packet\n"));
25249 		return;
25250 	}
25251 
25252 	/*
25253 	 * Will the packet require fragmentation?
25254 	 */
25255 
25256 	/*
25257 	 * IPsec ESP note: this is a pessimistic estimate, but the same
25258 	 * as is used elsewhere.
25259 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
25260 	 *	+ 2-byte trailer
25261 	 */
25262 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
25263 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
25264 
25265 	if ((plen + overhead) > ill->ill_max_mtu)
25266 		return;
25267 
25268 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25269 
25270 	/*
25271 	 * Can the ill accelerate this IPsec protocol and algorithm
25272 	 * specified by the SA?
25273 	 */
25274 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
25275 	    ill->ill_isv6, sa)) {
25276 		return;
25277 	}
25278 
25279 	/*
25280 	 * Tell AH or ESP that the outbound ill is capable of
25281 	 * accelerating this packet.
25282 	 */
25283 	io->ipsec_out_is_capab_ill = B_TRUE;
25284 }
25285 
25286 /*
25287  * Select which AH & ESP SA's to use (if any) for the outbound packet.
25288  *
25289  * If this function returns B_TRUE, the requested SA's have been filled
25290  * into the ipsec_out_*_sa pointers.
25291  *
25292  * If the function returns B_FALSE, the packet has been "consumed", most
25293  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
25294  *
25295  * The SA references created by the protocol-specific "select"
25296  * function will be released when the ipsec_mp is freed, thanks to the
25297  * ipsec_out_free destructor -- see spd.c.
25298  */
25299 static boolean_t
25300 ipsec_out_select_sa(mblk_t *ipsec_mp)
25301 {
25302 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
25303 	ipsec_out_t *io;
25304 	ipsec_policy_t *pp;
25305 	ipsec_action_t *ap;
25306 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25307 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25308 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25309 
25310 	if (!io->ipsec_out_secure) {
25311 		/*
25312 		 * We came here by mistake.
25313 		 * Don't bother with ipsec processing
25314 		 * We should "discourage" this path in the future.
25315 		 */
25316 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25317 		return (B_FALSE);
25318 	}
25319 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25320 	ASSERT((io->ipsec_out_policy != NULL) ||
25321 	    (io->ipsec_out_act != NULL));
25322 
25323 	ASSERT(io->ipsec_out_failed == B_FALSE);
25324 
25325 	/*
25326 	 * IPSEC processing has started.
25327 	 */
25328 	io->ipsec_out_proc_begin = B_TRUE;
25329 	ap = io->ipsec_out_act;
25330 	if (ap == NULL) {
25331 		pp = io->ipsec_out_policy;
25332 		ASSERT(pp != NULL);
25333 		ap = pp->ipsp_act;
25334 		ASSERT(ap != NULL);
25335 	}
25336 
25337 	/*
25338 	 * We have an action.  now, let's select SA's.
25339 	 * (In the future, we can cache this in the conn_t..)
25340 	 */
25341 	if (ap->ipa_want_esp) {
25342 		if (io->ipsec_out_esp_sa == NULL) {
25343 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
25344 			    IPPROTO_ESP);
25345 		}
25346 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
25347 	}
25348 
25349 	if (ap->ipa_want_ah) {
25350 		if (io->ipsec_out_ah_sa == NULL) {
25351 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
25352 			    IPPROTO_AH);
25353 		}
25354 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
25355 		/*
25356 		 * The ESP and AH processing order needs to be preserved
25357 		 * when both protocols are required (ESP should be applied
25358 		 * before AH for an outbound packet). Force an ESP ACQUIRE
25359 		 * when both ESP and AH are required, and an AH ACQUIRE
25360 		 * is needed.
25361 		 */
25362 		if (ap->ipa_want_esp && need_ah_acquire)
25363 			need_esp_acquire = B_TRUE;
25364 	}
25365 
25366 	/*
25367 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
25368 	 * Release SAs that got referenced, but will not be used until we
25369 	 * acquire _all_ of the SAs we need.
25370 	 */
25371 	if (need_ah_acquire || need_esp_acquire) {
25372 		if (io->ipsec_out_ah_sa != NULL) {
25373 			IPSA_REFRELE(io->ipsec_out_ah_sa);
25374 			io->ipsec_out_ah_sa = NULL;
25375 		}
25376 		if (io->ipsec_out_esp_sa != NULL) {
25377 			IPSA_REFRELE(io->ipsec_out_esp_sa);
25378 			io->ipsec_out_esp_sa = NULL;
25379 		}
25380 
25381 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
25382 		return (B_FALSE);
25383 	}
25384 
25385 	return (B_TRUE);
25386 }
25387 
25388 /*
25389  * Process an IPSEC_OUT message and see what you can
25390  * do with it.
25391  * IPQoS Notes:
25392  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
25393  * IPSec.
25394  * XXX would like to nuke ire_t.
25395  * XXX ill_index better be "real"
25396  */
25397 void
25398 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
25399 {
25400 	ipsec_out_t *io;
25401 	ipsec_policy_t *pp;
25402 	ipsec_action_t *ap;
25403 	ipha_t *ipha;
25404 	ip6_t *ip6h;
25405 	mblk_t *mp;
25406 	ill_t *ill;
25407 	zoneid_t zoneid;
25408 	ipsec_status_t ipsec_rc;
25409 	boolean_t ill_need_rele = B_FALSE;
25410 
25411 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25412 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25413 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25414 	mp = ipsec_mp->b_cont;
25415 
25416 	/*
25417 	 * Initiate IPPF processing. We do it here to account for packets
25418 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
25419 	 * We can check for ipsec_out_proc_begin even for such packets, as
25420 	 * they will always be false (asserted below).
25421 	 */
25422 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
25423 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
25424 		    io->ipsec_out_ill_index : ill_index);
25425 		if (mp == NULL) {
25426 			ip2dbg(("ipsec_out_process: packet dropped "\
25427 			    "during IPPF processing\n"));
25428 			freeb(ipsec_mp);
25429 			BUMP_MIB(&ip_mib, ipOutDiscards);
25430 			return;
25431 		}
25432 	}
25433 
25434 	if (!io->ipsec_out_secure) {
25435 		/*
25436 		 * We came here by mistake.
25437 		 * Don't bother with ipsec processing
25438 		 * Should "discourage" this path in the future.
25439 		 */
25440 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25441 		goto done;
25442 	}
25443 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25444 	ASSERT((io->ipsec_out_policy != NULL) ||
25445 	    (io->ipsec_out_act != NULL));
25446 	ASSERT(io->ipsec_out_failed == B_FALSE);
25447 
25448 	if (!ipsec_loaded()) {
25449 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
25450 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25451 			BUMP_MIB(&ip_mib, ipOutDiscards);
25452 		} else {
25453 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
25454 		}
25455 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
25456 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
25457 		return;
25458 	}
25459 
25460 	/*
25461 	 * IPSEC processing has started.
25462 	 */
25463 	io->ipsec_out_proc_begin = B_TRUE;
25464 	ap = io->ipsec_out_act;
25465 	if (ap == NULL) {
25466 		pp = io->ipsec_out_policy;
25467 		ASSERT(pp != NULL);
25468 		ap = pp->ipsp_act;
25469 		ASSERT(ap != NULL);
25470 	}
25471 
25472 	/*
25473 	 * Save the outbound ill index. When the packet comes back
25474 	 * from IPsec, we make sure the ill hasn't changed or disappeared
25475 	 * before sending it the accelerated packet.
25476 	 */
25477 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
25478 		int ifindex;
25479 		ill = ire_to_ill(ire);
25480 		ifindex = ill->ill_phyint->phyint_ifindex;
25481 		io->ipsec_out_capab_ill_index = ifindex;
25482 	}
25483 
25484 	/*
25485 	 * The order of processing is first insert a IP header if needed.
25486 	 * Then insert the ESP header and then the AH header.
25487 	 */
25488 	if ((io->ipsec_out_se_done == B_FALSE) &&
25489 	    (ap->ipa_want_se)) {
25490 		/*
25491 		 * First get the outer IP header before sending
25492 		 * it to ESP.
25493 		 */
25494 		ipha_t *oipha, *iipha;
25495 		mblk_t *outer_mp, *inner_mp;
25496 
25497 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
25498 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
25499 			    "ipsec_out_process: "
25500 			    "Self-Encapsulation failed: Out of memory\n");
25501 			freemsg(ipsec_mp);
25502 			BUMP_MIB(&ip_mib, ipOutDiscards);
25503 			return;
25504 		}
25505 		inner_mp = ipsec_mp->b_cont;
25506 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
25507 		oipha = (ipha_t *)outer_mp->b_rptr;
25508 		iipha = (ipha_t *)inner_mp->b_rptr;
25509 		*oipha = *iipha;
25510 		outer_mp->b_wptr += sizeof (ipha_t);
25511 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
25512 		    sizeof (ipha_t));
25513 		oipha->ipha_protocol = IPPROTO_ENCAP;
25514 		oipha->ipha_version_and_hdr_length =
25515 		    IP_SIMPLE_HDR_VERSION;
25516 		oipha->ipha_hdr_checksum = 0;
25517 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
25518 		outer_mp->b_cont = inner_mp;
25519 		ipsec_mp->b_cont = outer_mp;
25520 
25521 		io->ipsec_out_se_done = B_TRUE;
25522 		io->ipsec_out_encaps = B_TRUE;
25523 	}
25524 
25525 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
25526 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
25527 	    !ipsec_out_select_sa(ipsec_mp))
25528 		return;
25529 
25530 	/*
25531 	 * By now, we know what SA's to use.  Toss over to ESP & AH
25532 	 * to do the heavy lifting.
25533 	 */
25534 	zoneid = io->ipsec_out_zoneid;
25535 	ASSERT(zoneid != ALL_ZONES);
25536 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
25537 		ASSERT(io->ipsec_out_esp_sa != NULL);
25538 		io->ipsec_out_esp_done = B_TRUE;
25539 		/*
25540 		 * Note that since hw accel can only apply one transform,
25541 		 * not two, we skip hw accel for ESP if we also have AH
25542 		 * This is an design limitation of the interface
25543 		 * which should be revisited.
25544 		 */
25545 		ASSERT(ire != NULL);
25546 		if (io->ipsec_out_ah_sa == NULL) {
25547 			ill = (ill_t *)ire->ire_stq->q_ptr;
25548 			ipsec_out_is_accelerated(ipsec_mp,
25549 			    io->ipsec_out_esp_sa, ill, ire);
25550 		}
25551 
25552 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
25553 		switch (ipsec_rc) {
25554 		case IPSEC_STATUS_SUCCESS:
25555 			break;
25556 		case IPSEC_STATUS_FAILED:
25557 			BUMP_MIB(&ip_mib, ipOutDiscards);
25558 			/* FALLTHRU */
25559 		case IPSEC_STATUS_PENDING:
25560 			return;
25561 		}
25562 	}
25563 
25564 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
25565 		ASSERT(io->ipsec_out_ah_sa != NULL);
25566 		io->ipsec_out_ah_done = B_TRUE;
25567 		if (ire == NULL) {
25568 			int idx = io->ipsec_out_capab_ill_index;
25569 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
25570 			    NULL, NULL, NULL, NULL);
25571 			ill_need_rele = B_TRUE;
25572 		} else {
25573 			ill = (ill_t *)ire->ire_stq->q_ptr;
25574 		}
25575 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
25576 		    ire);
25577 
25578 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
25579 		switch (ipsec_rc) {
25580 		case IPSEC_STATUS_SUCCESS:
25581 			break;
25582 		case IPSEC_STATUS_FAILED:
25583 			BUMP_MIB(&ip_mib, ipOutDiscards);
25584 			/* FALLTHRU */
25585 		case IPSEC_STATUS_PENDING:
25586 			if (ill != NULL && ill_need_rele)
25587 				ill_refrele(ill);
25588 			return;
25589 		}
25590 	}
25591 	/*
25592 	 * We are done with IPSEC processing. Send it over
25593 	 * the wire.
25594 	 */
25595 done:
25596 	mp = ipsec_mp->b_cont;
25597 	ipha = (ipha_t *)mp->b_rptr;
25598 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25599 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
25600 	} else {
25601 		ip6h = (ip6_t *)ipha;
25602 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
25603 	}
25604 	if (ill != NULL && ill_need_rele)
25605 		ill_refrele(ill);
25606 }
25607 
25608 /* ARGSUSED */
25609 void
25610 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
25611 {
25612 	opt_restart_t	*or;
25613 	int	err;
25614 	conn_t	*connp;
25615 
25616 	ASSERT(CONN_Q(q));
25617 	connp = Q_TO_CONN(q);
25618 
25619 	ASSERT(first_mp->b_datap->db_type == M_CTL);
25620 	or = (opt_restart_t *)first_mp->b_rptr;
25621 	/*
25622 	 * We don't need to pass any credentials here since this is just
25623 	 * a restart. The credentials are passed in when svr4_optcom_req
25624 	 * is called the first time (from ip_wput_nondata).
25625 	 */
25626 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
25627 		err = svr4_optcom_req(q, first_mp, NULL,
25628 		    &ip_opt_obj);
25629 	} else {
25630 		ASSERT(or->or_type == T_OPTMGMT_REQ);
25631 		err = tpi_optcom_req(q, first_mp, NULL,
25632 		    &ip_opt_obj);
25633 	}
25634 	if (err != EINPROGRESS) {
25635 		/* operation is done */
25636 		CONN_OPER_PENDING_DONE(connp);
25637 	}
25638 }
25639 
25640 /*
25641  * ioctls that go through a down/up sequence may need to wait for the down
25642  * to complete. This involves waiting for the ire and ipif refcnts to go down
25643  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
25644  */
25645 /* ARGSUSED */
25646 void
25647 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25648 {
25649 	struct iocblk *iocp;
25650 	mblk_t *mp1;
25651 	ipif_t	*ipif;
25652 	ip_ioctl_cmd_t *ipip;
25653 	int err;
25654 	sin_t	*sin;
25655 	struct lifreq *lifr;
25656 	struct ifreq *ifr;
25657 
25658 	iocp = (struct iocblk *)mp->b_rptr;
25659 	ASSERT(ipsq != NULL);
25660 	/* Existence of mp1 verified in ip_wput_nondata */
25661 	mp1 = mp->b_cont->b_cont;
25662 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25663 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
25664 		ill_t *ill;
25665 		/*
25666 		 * Special case where ipsq_current_ipif may not be set.
25667 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
25668 		 * ill could also have become part of a ipmp group in the
25669 		 * process, we are here as were not able to complete the
25670 		 * operation in ipif_set_values because we could not become
25671 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
25672 		 * will not be set so we need to set it.
25673 		 */
25674 		ill = (ill_t *)q->q_ptr;
25675 		ipsq->ipsq_current_ipif = ill->ill_ipif;
25676 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25677 	}
25678 
25679 	ipif = ipsq->ipsq_current_ipif;
25680 	ASSERT(ipif != NULL);
25681 	if (ipip->ipi_cmd_type == IF_CMD) {
25682 		/* This a old style SIOC[GS]IF* command */
25683 		ifr = (struct ifreq *)mp1->b_rptr;
25684 		sin = (sin_t *)&ifr->ifr_addr;
25685 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
25686 		/* This a new style SIOC[GS]LIF* command */
25687 		lifr = (struct lifreq *)mp1->b_rptr;
25688 		sin = (sin_t *)&lifr->lifr_addr;
25689 	} else {
25690 		sin = NULL;
25691 	}
25692 
25693 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
25694 	    (void *)mp1->b_rptr);
25695 
25696 	/* SIOCLIFREMOVEIF could have removed the ipif */
25697 	ip_ioctl_finish(q, mp, err,
25698 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25699 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
25700 }
25701 
25702 /*
25703  * ioctl processing
25704  *
25705  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
25706  * the ioctl command in the ioctl tables and determines the copyin data size
25707  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
25708  * size.
25709  *
25710  * ioctl processing then continues when the M_IOCDATA makes its way down.
25711  * Now the ioctl is looked up again in the ioctl table, and its properties are
25712  * extracted. The associated 'conn' is then refheld till the end of the ioctl
25713  * and the general ioctl processing function ip_process_ioctl is called.
25714  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
25715  * so goes thru the serialization primitive ipsq_try_enter. Then the
25716  * appropriate function to handle the ioctl is called based on the entry in
25717  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
25718  * which also refreleases the 'conn' that was refheld at the start of the
25719  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
25720  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
25721  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
25722  *
25723  * Many exclusive ioctls go thru an internal down up sequence as part of
25724  * the operation. For example an attempt to change the IP address of an
25725  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
25726  * does all the cleanup such as deleting all ires that use this address.
25727  * Then we need to wait till all references to the interface go away.
25728  */
25729 void
25730 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
25731 {
25732 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
25733 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
25734 	cmd_info_t ci;
25735 	int err;
25736 	boolean_t entered_ipsq = B_FALSE;
25737 
25738 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
25739 
25740 	if (ipip == NULL)
25741 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25742 
25743 	/*
25744 	 * SIOCLIFADDIF needs to go thru a special path since the
25745 	 * ill may not exist yet. This happens in the case of lo0
25746 	 * which is created using this ioctl.
25747 	 */
25748 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
25749 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
25750 		ip_ioctl_finish(q, mp, err,
25751 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25752 		    NULL, NULL);
25753 		return;
25754 	}
25755 
25756 	ci.ci_ipif = NULL;
25757 	switch (ipip->ipi_cmd_type) {
25758 	case IF_CMD:
25759 	case LIF_CMD:
25760 		/*
25761 		 * ioctls that pass in a [l]ifreq appear here.
25762 		 * ip_extract_lifreq_cmn returns a refheld ipif in
25763 		 * ci.ci_ipif
25764 		 */
25765 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
25766 		    ipip->ipi_flags, &ci, ip_process_ioctl);
25767 		if (err != 0) {
25768 			ip_ioctl_finish(q, mp, err,
25769 			    ipip->ipi_flags & IPI_GET_CMD ?
25770 			    COPYOUT : NO_COPYOUT, NULL, NULL);
25771 			return;
25772 		}
25773 		ASSERT(ci.ci_ipif != NULL);
25774 		break;
25775 
25776 	case TUN_CMD:
25777 		/*
25778 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
25779 		 * a refheld ipif in ci.ci_ipif
25780 		 */
25781 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
25782 		if (err != 0) {
25783 			ip_ioctl_finish(q, mp, err,
25784 			    ipip->ipi_flags & IPI_GET_CMD ?
25785 			    COPYOUT : NO_COPYOUT, NULL, NULL);
25786 			return;
25787 		}
25788 		ASSERT(ci.ci_ipif != NULL);
25789 		break;
25790 
25791 	case MISC_CMD:
25792 		/*
25793 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
25794 		 * For eg. SIOCGLIFCONF will appear here.
25795 		 */
25796 		switch (ipip->ipi_cmd) {
25797 		case IF_UNITSEL:
25798 			/* ioctl comes down the ill */
25799 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
25800 			ipif_refhold(ci.ci_ipif);
25801 			break;
25802 		case SIOCGMSFILTER:
25803 		case SIOCSMSFILTER:
25804 		case SIOCGIPMSFILTER:
25805 		case SIOCSIPMSFILTER:
25806 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
25807 			    ip_process_ioctl);
25808 			if (err != 0) {
25809 				ip_ioctl_finish(q, mp, err,
25810 				    ipip->ipi_flags & IPI_GET_CMD ?
25811 				    COPYOUT : NO_COPYOUT, NULL, NULL);
25812 				return;
25813 			}
25814 			break;
25815 		}
25816 		err = 0;
25817 		ci.ci_sin = NULL;
25818 		ci.ci_sin6 = NULL;
25819 		ci.ci_lifr = NULL;
25820 		break;
25821 	}
25822 
25823 	/*
25824 	 * If ipsq is non-null, we are already being called exclusively
25825 	 */
25826 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
25827 	if (!(ipip->ipi_flags & IPI_WR)) {
25828 		/*
25829 		 * A return value of EINPROGRESS means the ioctl is
25830 		 * either queued and waiting for some reason or has
25831 		 * already completed.
25832 		 */
25833 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25834 		    ci.ci_lifr);
25835 		if (ci.ci_ipif != NULL)
25836 			ipif_refrele(ci.ci_ipif);
25837 		ip_ioctl_finish(q, mp, err,
25838 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25839 		    NULL, NULL);
25840 		return;
25841 	}
25842 
25843 	ASSERT(ci.ci_ipif != NULL);
25844 
25845 	if (ipsq == NULL) {
25846 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
25847 		    ip_process_ioctl, NEW_OP, B_TRUE);
25848 		entered_ipsq = B_TRUE;
25849 	}
25850 	/*
25851 	 * Release the ipif so that ipif_down and friends that wait for
25852 	 * references to go away are not misled about the current ipif_refcnt
25853 	 * values. We are writer so we can access the ipif even after releasing
25854 	 * the ipif.
25855 	 */
25856 	ipif_refrele(ci.ci_ipif);
25857 	if (ipsq == NULL)
25858 		return;
25859 
25860 	mutex_enter(&ipsq->ipsq_lock);
25861 	ASSERT(ipsq->ipsq_current_ipif == NULL);
25862 	ipsq->ipsq_current_ipif = ci.ci_ipif;
25863 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25864 	mutex_exit(&ipsq->ipsq_lock);
25865 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
25866 	/*
25867 	 * For most set ioctls that come here, this serves as a single point
25868 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
25869 	 * be any new references to the ipif. This helps functions that go
25870 	 * through this path and end up trying to wait for the refcnts
25871 	 * associated with the ipif to go down to zero. Some exceptions are
25872 	 * Failover, Failback, and Groupname commands that operate on more than
25873 	 * just the ci.ci_ipif. These commands internally determine the
25874 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
25875 	 * flags on that set. Another exception is the Removeif command that
25876 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
25877 	 * ipif to operate on.
25878 	 */
25879 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
25880 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
25881 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
25882 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
25883 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
25884 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
25885 
25886 	/*
25887 	 * A return value of EINPROGRESS means the ioctl is
25888 	 * either queued and waiting for some reason or has
25889 	 * already completed.
25890 	 */
25891 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25892 	    ci.ci_lifr);
25893 
25894 	/* SIOCLIFREMOVEIF could have removed the ipif */
25895 	ip_ioctl_finish(q, mp, err,
25896 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25897 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
25898 
25899 	if (entered_ipsq)
25900 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
25901 }
25902 
25903 /*
25904  * Complete the ioctl. Typically ioctls use the mi package and need to
25905  * do mi_copyout/mi_copy_done.
25906  */
25907 void
25908 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
25909     ipif_t *ipif, ipsq_t *ipsq)
25910 {
25911 	conn_t	*connp = NULL;
25912 
25913 	if (err == EINPROGRESS)
25914 		return;
25915 
25916 	if (CONN_Q(q)) {
25917 		connp = Q_TO_CONN(q);
25918 		ASSERT(connp->conn_ref >= 2);
25919 	}
25920 
25921 	switch (mode) {
25922 	case COPYOUT:
25923 		if (err == 0)
25924 			mi_copyout(q, mp);
25925 		else
25926 			mi_copy_done(q, mp, err);
25927 		break;
25928 
25929 	case NO_COPYOUT:
25930 		mi_copy_done(q, mp, err);
25931 		break;
25932 
25933 	default:
25934 		/* An ioctl aborted through a conn close would take this path */
25935 		break;
25936 	}
25937 
25938 	/*
25939 	 * The refhold placed at the start of the ioctl is released here.
25940 	 */
25941 	if (connp != NULL)
25942 		CONN_OPER_PENDING_DONE(connp);
25943 
25944 	/*
25945 	 * If the ioctl were an exclusive ioctl it would have set
25946 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
25947 	 */
25948 	if (ipif != NULL) {
25949 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
25950 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
25951 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
25952 	}
25953 
25954 	/*
25955 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
25956 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
25957 	 * entering the ipsq
25958 	 */
25959 	if (ipsq != NULL) {
25960 		mutex_enter(&ipsq->ipsq_lock);
25961 		ipsq->ipsq_current_ipif = NULL;
25962 		mutex_exit(&ipsq->ipsq_lock);
25963 	}
25964 }
25965 
25966 /*
25967  * This is called from ip_wput_nondata to resume a deferred TCP bind.
25968  */
25969 /* ARGSUSED */
25970 void
25971 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
25972 {
25973 	conn_t *connp = arg;
25974 	tcp_t	*tcp;
25975 
25976 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
25977 	tcp = connp->conn_tcp;
25978 
25979 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
25980 		freemsg(mp);
25981 	else
25982 		tcp_rput_other(tcp, mp);
25983 	CONN_OPER_PENDING_DONE(connp);
25984 }
25985 
25986 /* Called from ip_wput for all non data messages */
25987 /* ARGSUSED */
25988 void
25989 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25990 {
25991 	mblk_t		*mp1;
25992 	ire_t		*ire, *fake_ire;
25993 	ill_t		*ill;
25994 	struct iocblk	*iocp;
25995 	ip_ioctl_cmd_t	*ipip;
25996 	cred_t		*cr;
25997 	conn_t		*connp = NULL;
25998 	int		cmd, err;
25999 	nce_t		*nce;
26000 	ipif_t		*ipif;
26001 
26002 	if (CONN_Q(q))
26003 		connp = Q_TO_CONN(q);
26004 
26005 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26006 
26007 	/* Check if it is a queue to /dev/sctp. */
26008 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26009 	    connp->conn_rq == NULL) {
26010 		sctp_wput(q, mp);
26011 		return;
26012 	}
26013 
26014 	switch (DB_TYPE(mp)) {
26015 	case M_IOCTL:
26016 		/*
26017 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26018 		 * will arrange to copy in associated control structures.
26019 		 */
26020 		ip_sioctl_copyin_setup(q, mp);
26021 		return;
26022 	case M_IOCDATA:
26023 		/*
26024 		 * Ensure that this is associated with one of our trans-
26025 		 * parent ioctls.  If it's not ours, discard it if we're
26026 		 * running as a driver, or pass it on if we're a module.
26027 		 */
26028 		iocp = (struct iocblk *)mp->b_rptr;
26029 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26030 		if (ipip == NULL) {
26031 			if (q->q_next == NULL) {
26032 				goto nak;
26033 			} else {
26034 				putnext(q, mp);
26035 			}
26036 			return;
26037 		} else if ((q->q_next != NULL) &&
26038 		    !(ipip->ipi_flags & IPI_MODOK)) {
26039 			/*
26040 			 * the ioctl is one we recognise, but is not
26041 			 * consumed by IP as a module, pass M_IOCDATA
26042 			 * for processing downstream, but only for
26043 			 * common Streams ioctls.
26044 			 */
26045 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26046 				putnext(q, mp);
26047 				return;
26048 			} else {
26049 				goto nak;
26050 			}
26051 		}
26052 
26053 		/* IOCTL continuation following copyin or copyout. */
26054 		if (mi_copy_state(q, mp, NULL) == -1) {
26055 			/*
26056 			 * The copy operation failed.  mi_copy_state already
26057 			 * cleaned up, so we're out of here.
26058 			 */
26059 			return;
26060 		}
26061 		/*
26062 		 * If we just completed a copy in, we become writer and
26063 		 * continue processing in ip_sioctl_copyin_done.  If it
26064 		 * was a copy out, we call mi_copyout again.  If there is
26065 		 * nothing more to copy out, it will complete the IOCTL.
26066 		 */
26067 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
26068 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
26069 				mi_copy_done(q, mp, EPROTO);
26070 				return;
26071 			}
26072 			/*
26073 			 * Check for cases that need more copying.  A return
26074 			 * value of 0 means a second copyin has been started,
26075 			 * so we return; a return value of 1 means no more
26076 			 * copying is needed, so we continue.
26077 			 */
26078 			cmd = iocp->ioc_cmd;
26079 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
26080 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
26081 			    MI_COPY_COUNT(mp) == 1) {
26082 				if (ip_copyin_msfilter(q, mp) == 0)
26083 					return;
26084 			}
26085 			/*
26086 			 * Refhold the conn, till the ioctl completes. This is
26087 			 * needed in case the ioctl ends up in the pending mp
26088 			 * list. Every mp in the ill_pending_mp list and
26089 			 * the ipsq_pending_mp must have a refhold on the conn
26090 			 * to resume processing. The refhold is released when
26091 			 * the ioctl completes. (normally or abnormally)
26092 			 * In all cases ip_ioctl_finish is called to finish
26093 			 * the ioctl.
26094 			 */
26095 			if (connp != NULL) {
26096 				/* This is not a reentry */
26097 				ASSERT(ipsq == NULL);
26098 				CONN_INC_REF(connp);
26099 			} else {
26100 				if (!(ipip->ipi_flags & IPI_MODOK)) {
26101 					mi_copy_done(q, mp, EINVAL);
26102 					return;
26103 				}
26104 			}
26105 
26106 			ip_process_ioctl(ipsq, q, mp, ipip);
26107 
26108 		} else {
26109 			mi_copyout(q, mp);
26110 		}
26111 		return;
26112 nak:
26113 		iocp->ioc_error = EINVAL;
26114 		mp->b_datap->db_type = M_IOCNAK;
26115 		iocp->ioc_count = 0;
26116 		qreply(q, mp);
26117 		return;
26118 
26119 	case M_IOCNAK:
26120 		/*
26121 		 * The only way we could get here is if a resolver didn't like
26122 		 * an IOCTL we sent it.	 This shouldn't happen.
26123 		 */
26124 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
26125 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
26126 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
26127 		freemsg(mp);
26128 		return;
26129 	case M_IOCACK:
26130 		/* Finish socket ioctls passed through to ARP. */
26131 		ip_sioctl_iocack(q, mp);
26132 		return;
26133 	case M_FLUSH:
26134 		if (*mp->b_rptr & FLUSHW)
26135 			flushq(q, FLUSHALL);
26136 		if (q->q_next) {
26137 			/*
26138 			 * M_FLUSH is sent up to IP by some drivers during
26139 			 * unbind. ip_rput has already replied to it. We are
26140 			 * here for the M_FLUSH that we originated in IP
26141 			 * before sending the unbind request to the driver.
26142 			 * Just free it as we don't queue packets in IP
26143 			 * on the write side of the device instance.
26144 			 */
26145 			freemsg(mp);
26146 			return;
26147 		}
26148 		if (*mp->b_rptr & FLUSHR) {
26149 			*mp->b_rptr &= ~FLUSHW;
26150 			qreply(q, mp);
26151 			return;
26152 		}
26153 		freemsg(mp);
26154 		return;
26155 	case IRE_DB_REQ_TYPE:
26156 		/* An Upper Level Protocol wants a copy of an IRE. */
26157 		ip_ire_req(q, mp);
26158 		return;
26159 	case M_CTL:
26160 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
26161 			break;
26162 
26163 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
26164 		    IP_ULP_OUT_LABELED) {
26165 			out_labeled_t *olp;
26166 
26167 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
26168 				break;
26169 			olp = (out_labeled_t *)mp->b_rptr;
26170 			connp->conn_ulp_labeled = olp->out_qnext == q;
26171 			freemsg(mp);
26172 			return;
26173 		}
26174 
26175 		/* M_CTL messages are used by ARP to tell us things. */
26176 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
26177 			break;
26178 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
26179 		case AR_ENTRY_SQUERY:
26180 			ip_wput_ctl(q, mp);
26181 			return;
26182 		case AR_CLIENT_NOTIFY:
26183 			ip_arp_news(q, mp);
26184 			return;
26185 		case AR_DLPIOP_DONE:
26186 			ASSERT(q->q_next != NULL);
26187 			ill = (ill_t *)q->q_ptr;
26188 			/* qwriter_ip releases the refhold */
26189 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
26190 			ill_refhold(ill);
26191 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
26192 			    CUR_OP, B_FALSE);
26193 			return;
26194 		case AR_ARP_CLOSING:
26195 			/*
26196 			 * ARP (above us) is closing. If no ARP bringup is
26197 			 * currently pending, ack the message so that ARP
26198 			 * can complete its close. Also mark ill_arp_closing
26199 			 * so that new ARP bringups will fail. If any
26200 			 * ARP bringup is currently in progress, we will
26201 			 * ack this when the current ARP bringup completes.
26202 			 */
26203 			ASSERT(q->q_next != NULL);
26204 			ill = (ill_t *)q->q_ptr;
26205 			mutex_enter(&ill->ill_lock);
26206 			ill->ill_arp_closing = 1;
26207 			if (!ill->ill_arp_bringup_pending) {
26208 				mutex_exit(&ill->ill_lock);
26209 				qreply(q, mp);
26210 			} else {
26211 				mutex_exit(&ill->ill_lock);
26212 				freemsg(mp);
26213 			}
26214 			return;
26215 		case AR_ARP_EXTEND:
26216 			/*
26217 			 * The ARP module above us is capable of duplicate
26218 			 * address detection.  Old ATM drivers will not send
26219 			 * this message.
26220 			 */
26221 			ASSERT(q->q_next != NULL);
26222 			ill = (ill_t *)q->q_ptr;
26223 			ill->ill_arp_extend = B_TRUE;
26224 			freemsg(mp);
26225 			return;
26226 		default:
26227 			break;
26228 		}
26229 		break;
26230 	case M_PROTO:
26231 	case M_PCPROTO:
26232 		/*
26233 		 * The only PROTO messages we expect are ULP binds and
26234 		 * copies of option negotiation acknowledgements.
26235 		 */
26236 		switch (((union T_primitives *)mp->b_rptr)->type) {
26237 		case O_T_BIND_REQ:
26238 		case T_BIND_REQ: {
26239 			/* Request can get queued in bind */
26240 			ASSERT(connp != NULL);
26241 			/*
26242 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
26243 			 * instead of going through this path.  We only get
26244 			 * here in the following cases:
26245 			 *
26246 			 * a. Bind retries, where ipsq is non-NULL.
26247 			 * b. T_BIND_REQ is issued from non TCP/UDP
26248 			 *    transport, e.g. icmp for raw socket,
26249 			 *    in which case ipsq will be NULL.
26250 			 */
26251 			ASSERT(ipsq != NULL ||
26252 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
26253 
26254 			/* Don't increment refcnt if this is a re-entry */
26255 			if (ipsq == NULL)
26256 				CONN_INC_REF(connp);
26257 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
26258 			    connp, NULL) : ip_bind_v4(q, mp, connp);
26259 			if (mp == NULL)
26260 				return;
26261 			if (IPCL_IS_TCP(connp)) {
26262 				/*
26263 				 * In the case of TCP endpoint we
26264 				 * come here only for bind retries
26265 				 */
26266 				ASSERT(ipsq != NULL);
26267 				CONN_INC_REF(connp);
26268 				squeue_fill(connp->conn_sqp, mp,
26269 				    ip_resume_tcp_bind, connp,
26270 				    SQTAG_BIND_RETRY);
26271 				return;
26272 			} else if (IPCL_IS_UDP(connp)) {
26273 				/*
26274 				 * In the case of UDP endpoint we
26275 				 * come here only for bind retries
26276 				 */
26277 				ASSERT(ipsq != NULL);
26278 				udp_resume_bind(connp, mp);
26279 				return;
26280 			}
26281 			qreply(q, mp);
26282 			CONN_OPER_PENDING_DONE(connp);
26283 			return;
26284 		}
26285 		case T_SVR4_OPTMGMT_REQ:
26286 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
26287 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
26288 
26289 			ASSERT(connp != NULL);
26290 			if (!snmpcom_req(q, mp, ip_snmp_set,
26291 			    ip_snmp_get, cr)) {
26292 				/*
26293 				 * Call svr4_optcom_req so that it can
26294 				 * generate the ack. We don't come here
26295 				 * if this operation is being restarted.
26296 				 * ip_restart_optmgmt will drop the conn ref.
26297 				 * In the case of ipsec option after the ipsec
26298 				 * load is complete conn_restart_ipsec_waiter
26299 				 * drops the conn ref.
26300 				 */
26301 				ASSERT(ipsq == NULL);
26302 				CONN_INC_REF(connp);
26303 				if (ip_check_for_ipsec_opt(q, mp))
26304 					return;
26305 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
26306 				if (err != EINPROGRESS) {
26307 					/* Operation is done */
26308 					CONN_OPER_PENDING_DONE(connp);
26309 				}
26310 			}
26311 			return;
26312 		case T_OPTMGMT_REQ:
26313 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
26314 			/*
26315 			 * Note: No snmpcom_req support through new
26316 			 * T_OPTMGMT_REQ.
26317 			 * Call tpi_optcom_req so that it can
26318 			 * generate the ack.
26319 			 */
26320 			ASSERT(connp != NULL);
26321 			ASSERT(ipsq == NULL);
26322 			/*
26323 			 * We don't come here for restart. ip_restart_optmgmt
26324 			 * will drop the conn ref. In the case of ipsec option
26325 			 * after the ipsec load is complete
26326 			 * conn_restart_ipsec_waiter drops the conn ref.
26327 			 */
26328 			CONN_INC_REF(connp);
26329 			if (ip_check_for_ipsec_opt(q, mp))
26330 				return;
26331 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
26332 			if (err != EINPROGRESS) {
26333 				/* Operation is done */
26334 				CONN_OPER_PENDING_DONE(connp);
26335 			}
26336 			return;
26337 		case T_UNBIND_REQ:
26338 			mp = ip_unbind(q, mp);
26339 			qreply(q, mp);
26340 			return;
26341 		default:
26342 			/*
26343 			 * Have to drop any DLPI messages coming down from
26344 			 * arp (such as an info_req which would cause ip
26345 			 * to receive an extra info_ack if it was passed
26346 			 * through.
26347 			 */
26348 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
26349 			    (int)*(uint_t *)mp->b_rptr));
26350 			freemsg(mp);
26351 			return;
26352 		}
26353 		/* NOTREACHED */
26354 	case IRE_DB_TYPE: {
26355 		nce_t		*nce;
26356 		ill_t		*ill;
26357 		in6_addr_t	gw_addr_v6;
26358 
26359 
26360 		/*
26361 		 * This is a response back from a resolver.  It
26362 		 * consists of a message chain containing:
26363 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
26364 		 * The IRE_MBLK is the one we allocated in ip_newroute.
26365 		 * The LL_HDR_MBLK is the DLPI header to use to get
26366 		 * the attached packet, and subsequent ones for the
26367 		 * same destination, transmitted.
26368 		 */
26369 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
26370 			break;
26371 		/*
26372 		 * First, check to make sure the resolution succeeded.
26373 		 * If it failed, the second mblk will be empty.
26374 		 * If it is, free the chain, dropping the packet.
26375 		 * (We must ire_delete the ire; that frees the ire mblk)
26376 		 * We're doing this now to support PVCs for ATM; it's
26377 		 * a partial xresolv implementation. When we fully implement
26378 		 * xresolv interfaces, instead of freeing everything here
26379 		 * we'll initiate neighbor discovery.
26380 		 *
26381 		 * For v4 (ARP and other external resolvers) the resolver
26382 		 * frees the message, so no check is needed. This check
26383 		 * is required, though, for a full xresolve implementation.
26384 		 * Including this code here now both shows how external
26385 		 * resolvers can NACK a resolution request using an
26386 		 * existing design that has no specific provisions for NACKs,
26387 		 * and also takes into account that the current non-ARP
26388 		 * external resolver has been coded to use this method of
26389 		 * NACKing for all IPv6 (xresolv) cases,
26390 		 * whether our xresolv implementation is complete or not.
26391 		 *
26392 		 */
26393 		ire = (ire_t *)mp->b_rptr;
26394 		ill = ire_to_ill(ire);
26395 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26396 		if (mp1->b_rptr == mp1->b_wptr) {
26397 			if (ire->ire_ipversion == IPV6_VERSION) {
26398 				/*
26399 				 * XRESOLV interface.
26400 				 */
26401 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
26402 				mutex_enter(&ire->ire_lock);
26403 				gw_addr_v6 = ire->ire_gateway_addr_v6;
26404 				mutex_exit(&ire->ire_lock);
26405 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26406 					nce = ndp_lookup_v6(ill,
26407 					    &ire->ire_addr_v6, B_FALSE);
26408 				} else {
26409 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
26410 					    B_FALSE);
26411 				}
26412 				if (nce != NULL) {
26413 					nce_resolv_failed(nce);
26414 					ndp_delete(nce);
26415 					NCE_REFRELE(nce);
26416 				}
26417 			}
26418 			mp->b_cont = NULL;
26419 			freemsg(mp1);		/* frees the pkt as well */
26420 			ASSERT(ire->ire_nce == NULL);
26421 			ire_delete((ire_t *)mp->b_rptr);
26422 			return;
26423 		}
26424 
26425 		/*
26426 		 * Split them into IRE_MBLK and pkt and feed it into
26427 		 * ire_add_then_send. Then in ire_add_then_send
26428 		 * the IRE will be added, and then the packet will be
26429 		 * run back through ip_wput. This time it will make
26430 		 * it to the wire.
26431 		 */
26432 		mp->b_cont = NULL;
26433 		mp = mp1->b_cont;		/* now, mp points to pkt */
26434 		mp1->b_cont = NULL;
26435 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
26436 		if (ire->ire_ipversion == IPV6_VERSION) {
26437 			/*
26438 			 * XRESOLV interface. Find the nce and put a copy
26439 			 * of the dl_unitdata_req in nce_res_mp
26440 			 */
26441 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
26442 			mutex_enter(&ire->ire_lock);
26443 			gw_addr_v6 = ire->ire_gateway_addr_v6;
26444 			mutex_exit(&ire->ire_lock);
26445 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26446 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
26447 				    B_FALSE);
26448 			} else {
26449 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
26450 			}
26451 			if (nce != NULL) {
26452 				/*
26453 				 * We have to protect nce_res_mp here
26454 				 * from being accessed by other threads
26455 				 * while we change the mblk pointer.
26456 				 * Other functions will also lock the nce when
26457 				 * accessing nce_res_mp.
26458 				 *
26459 				 * The reason we change the mblk pointer
26460 				 * here rather than copying the resolved address
26461 				 * into the template is that, unlike with
26462 				 * ethernet, we have no guarantee that the
26463 				 * resolved address length will be
26464 				 * smaller than or equal to the lla length
26465 				 * with which the template was allocated,
26466 				 * (for ethernet, they're equal)
26467 				 * so we have to use the actual resolved
26468 				 * address mblk - which holds the real
26469 				 * dl_unitdata_req with the resolved address.
26470 				 *
26471 				 * Doing this is the same behavior as was
26472 				 * previously used in the v4 ARP case.
26473 				 */
26474 				mutex_enter(&nce->nce_lock);
26475 				if (nce->nce_res_mp != NULL)
26476 					freemsg(nce->nce_res_mp);
26477 				nce->nce_res_mp = mp1;
26478 				mutex_exit(&nce->nce_lock);
26479 				/*
26480 				 * We do a fastpath probe here because
26481 				 * we have resolved the address without
26482 				 * using Neighbor Discovery.
26483 				 * In the non-XRESOLV v6 case, the fastpath
26484 				 * probe is done right after neighbor
26485 				 * discovery completes.
26486 				 */
26487 				if (nce->nce_res_mp != NULL) {
26488 					int res;
26489 					nce_fastpath_list_add(nce);
26490 					res = ill_fastpath_probe(ill,
26491 					    nce->nce_res_mp);
26492 					if (res != 0 && res != EAGAIN)
26493 						nce_fastpath_list_delete(nce);
26494 				}
26495 
26496 				ire_add_then_send(q, ire, mp);
26497 				/*
26498 				 * Now we have to clean out any packets
26499 				 * that may have been queued on the nce
26500 				 * while it was waiting for address resolution
26501 				 * to complete.
26502 				 */
26503 				mutex_enter(&nce->nce_lock);
26504 				mp1 = nce->nce_qd_mp;
26505 				nce->nce_qd_mp = NULL;
26506 				mutex_exit(&nce->nce_lock);
26507 				while (mp1 != NULL) {
26508 					mblk_t *nxt_mp;
26509 					queue_t *fwdq = NULL;
26510 					ill_t   *inbound_ill;
26511 					uint_t ifindex;
26512 
26513 					nxt_mp = mp1->b_next;
26514 					mp1->b_next = NULL;
26515 					/*
26516 					 * Retrieve ifindex stored in
26517 					 * ip_rput_data_v6()
26518 					 */
26519 					ifindex =
26520 					    (uint_t)(uintptr_t)mp1->b_prev;
26521 					inbound_ill =
26522 						ill_lookup_on_ifindex(ifindex,
26523 						    B_TRUE, NULL, NULL, NULL,
26524 						    NULL);
26525 					mp1->b_prev = NULL;
26526 					if (inbound_ill != NULL)
26527 						fwdq = inbound_ill->ill_rq;
26528 
26529 					if (fwdq != NULL) {
26530 						put(fwdq, mp1);
26531 						ill_refrele(inbound_ill);
26532 					} else
26533 						put(WR(ill->ill_rq), mp1);
26534 					mp1 = nxt_mp;
26535 				}
26536 				NCE_REFRELE(nce);
26537 			} else {	/* nce is NULL; clean up */
26538 				ire_delete(ire);
26539 				freemsg(mp);
26540 				freemsg(mp1);
26541 				return;
26542 			}
26543 		} else {
26544 			nce_t *arpce;
26545 			/*
26546 			 * Link layer resolution succeeded. Recompute the
26547 			 * ire_nce.
26548 			 */
26549 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
26550 			if ((arpce = ndp_lookup_v4(ill,
26551 			    (ire->ire_gateway_addr != INADDR_ANY ?
26552 			    &ire->ire_gateway_addr : &ire->ire_addr),
26553 			    B_FALSE)) == NULL) {
26554 				freeb(ire->ire_mp);
26555 				freeb(mp1);
26556 				freemsg(mp);
26557 				return;
26558 			}
26559 			mutex_enter(&arpce->nce_lock);
26560 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
26561 			if (arpce->nce_state == ND_REACHABLE) {
26562 				/*
26563 				 * Someone resolved this before us;
26564 				 * cleanup the res_mp. Since ire has
26565 				 * not been added yet, the call to ire_add_v4
26566 				 * from ire_add_then_send (when a dup is
26567 				 * detected) will clean up the ire.
26568 				 */
26569 				freeb(mp1);
26570 			} else {
26571 				if (arpce->nce_res_mp != NULL)
26572 					freemsg(arpce->nce_res_mp);
26573 				arpce->nce_res_mp = mp1;
26574 				arpce->nce_state = ND_REACHABLE;
26575 			}
26576 			mutex_exit(&arpce->nce_lock);
26577 			if (ire->ire_marks & IRE_MARK_NOADD) {
26578 				/*
26579 				 * this ire will not be added to the ire
26580 				 * cache table, so we can set the ire_nce
26581 				 * here, as there are no atomicity constraints.
26582 				 */
26583 				ire->ire_nce = arpce;
26584 				/*
26585 				 * We are associating this nce with the ire
26586 				 * so change the nce ref taken in
26587 				 * ndp_lookup_v4() from
26588 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
26589 				 */
26590 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
26591 			} else {
26592 				NCE_REFRELE(arpce);
26593 			}
26594 			ire_add_then_send(q, ire, mp);
26595 		}
26596 		return;	/* All is well, the packet has been sent. */
26597 	}
26598 	case IRE_ARPRESOLVE_TYPE: {
26599 
26600 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
26601 			break;
26602 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26603 		mp->b_cont = NULL;
26604 		/*
26605 		 * First, check to make sure the resolution succeeded.
26606 		 * If it failed, the second mblk will be empty.
26607 		 */
26608 		if (mp1->b_rptr == mp1->b_wptr) {
26609 			/* cleanup  the incomplete ire, free queued packets */
26610 			freemsg(mp); /* fake ire */
26611 			freeb(mp1);  /* dl_unitdata response */
26612 			return;
26613 		}
26614 
26615 		/*
26616 		 * update any incomplete nce_t found. we lookup the ctable
26617 		 * and find the nce from the ire->ire_nce because we need
26618 		 * to pass the ire to ip_xmit_v4 later, and can find both
26619 		 * ire and nce in one lookup from the ctable.
26620 		 */
26621 		fake_ire = (ire_t *)mp->b_rptr;
26622 		/*
26623 		 * By the time we come back here from ARP
26624 		 * the logical outgoing interface  of the incomplete ire
26625 		 * we added in ire_forward could have disappeared,
26626 		 * causing the incomplete ire to also have
26627 		 * dissapeared. So we need to retreive the
26628 		 * proper ipif for the ire  before looking
26629 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
26630 		 */
26631 		ill = q->q_ptr;
26632 
26633 		/* Get the outgoing ipif */
26634 		mutex_enter(&ill->ill_lock);
26635 		if (ill->ill_state_flags & ILL_CONDEMNED) {
26636 			mutex_exit(&ill->ill_lock);
26637 			freemsg(mp); /* fake ire */
26638 			freeb(mp1);  /* dl_unitdata response */
26639 			return;
26640 		}
26641 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
26642 
26643 		if (ipif == NULL) {
26644 			mutex_exit(&ill->ill_lock);
26645 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
26646 			freemsg(mp);
26647 			freeb(mp1);
26648 			return;
26649 		}
26650 		ipif_refhold_locked(ipif);
26651 		mutex_exit(&ill->ill_lock);
26652 		ire = ire_ctable_lookup(fake_ire->ire_addr,
26653 		    fake_ire->ire_gateway_addr, IRE_CACHE,
26654 		    ipif, fake_ire->ire_zoneid, NULL,
26655 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
26656 		ipif_refrele(ipif);
26657 		if (ire == NULL) {
26658 			/*
26659 			 * no ire was found; check if there is an nce
26660 			 * for this lookup; if it has no ire's pointing at it
26661 			 * cleanup.
26662 			 */
26663 			if ((nce = ndp_lookup_v4(ill,
26664 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
26665 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
26666 			    B_FALSE)) != NULL) {
26667 				/*
26668 				 * cleanup: just reset nce.
26669 				 * We check for refcnt 2 (one for the nce
26670 				 * hash list + 1 for the ref taken by
26671 				 * ndp_lookup_v4) to ensure that there are
26672 				 * no ire's pointing at the nce.
26673 				 */
26674 				if (nce->nce_refcnt == 2) {
26675 					nce = nce_reinit(nce);
26676 				}
26677 				if (nce != NULL)
26678 					NCE_REFRELE(nce);
26679 			}
26680 			freeb(mp1);  /* dl_unitdata response */
26681 			freemsg(mp); /* fake ire */
26682 			return;
26683 		}
26684 		nce = ire->ire_nce;
26685 		DTRACE_PROBE2(ire__arpresolve__type,
26686 		    ire_t *, ire, nce_t *, nce);
26687 		ASSERT(nce->nce_state != ND_INITIAL);
26688 		mutex_enter(&nce->nce_lock);
26689 		nce->nce_last = TICK_TO_MSEC(lbolt64);
26690 		if (nce->nce_state == ND_REACHABLE) {
26691 			/*
26692 			 * Someone resolved this before us;
26693 			 * our response is not needed any more.
26694 			 */
26695 			mutex_exit(&nce->nce_lock);
26696 			freeb(mp1);  /* dl_unitdata response */
26697 		} else {
26698 			if (nce->nce_res_mp != NULL) {
26699 				freemsg(nce->nce_res_mp);
26700 				/* existing dl_unitdata template */
26701 			}
26702 			nce->nce_res_mp = mp1;
26703 			nce->nce_state = ND_REACHABLE;
26704 			mutex_exit(&nce->nce_lock);
26705 			ire_fastpath(ire);
26706 		}
26707 		/*
26708 		 * The cached nce_t has been updated to be reachable;
26709 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
26710 		 */
26711 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
26712 		freemsg(mp);
26713 		/*
26714 		 * send out queued packets.
26715 		 */
26716 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26717 
26718 		IRE_REFRELE(ire);
26719 		return;
26720 	}
26721 	default:
26722 		break;
26723 	}
26724 	if (q->q_next) {
26725 		putnext(q, mp);
26726 	} else
26727 		freemsg(mp);
26728 }
26729 
26730 /*
26731  * Process IP options in an outbound packet.  Modify the destination if there
26732  * is a source route option.
26733  * Returns non-zero if something fails in which case an ICMP error has been
26734  * sent and mp freed.
26735  */
26736 static int
26737 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
26738     boolean_t mctl_present, zoneid_t zoneid)
26739 {
26740 	ipoptp_t	opts;
26741 	uchar_t		*opt;
26742 	uint8_t		optval;
26743 	uint8_t		optlen;
26744 	ipaddr_t	dst;
26745 	intptr_t	code = 0;
26746 	mblk_t		*mp;
26747 	ire_t		*ire = NULL;
26748 
26749 	ip2dbg(("ip_wput_options\n"));
26750 	mp = ipsec_mp;
26751 	if (mctl_present) {
26752 		mp = ipsec_mp->b_cont;
26753 	}
26754 
26755 	dst = ipha->ipha_dst;
26756 	for (optval = ipoptp_first(&opts, ipha);
26757 	    optval != IPOPT_EOL;
26758 	    optval = ipoptp_next(&opts)) {
26759 		opt = opts.ipoptp_cur;
26760 		optlen = opts.ipoptp_len;
26761 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
26762 		    optval, optlen));
26763 		switch (optval) {
26764 			uint32_t off;
26765 		case IPOPT_SSRR:
26766 		case IPOPT_LSRR:
26767 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26768 				ip1dbg((
26769 				    "ip_wput_options: bad option offset\n"));
26770 				code = (char *)&opt[IPOPT_OLEN] -
26771 				    (char *)ipha;
26772 				goto param_prob;
26773 			}
26774 			off = opt[IPOPT_OFFSET];
26775 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
26776 			    ntohl(dst)));
26777 			/*
26778 			 * For strict: verify that dst is directly
26779 			 * reachable.
26780 			 */
26781 			if (optval == IPOPT_SSRR) {
26782 				ire = ire_ftable_lookup(dst, 0, 0,
26783 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
26784 				    MBLK_GETLABEL(mp),
26785 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
26786 				if (ire == NULL) {
26787 					ip1dbg(("ip_wput_options: SSRR not"
26788 					    " directly reachable: 0x%x\n",
26789 					    ntohl(dst)));
26790 					goto bad_src_route;
26791 				}
26792 				ire_refrele(ire);
26793 			}
26794 			break;
26795 		case IPOPT_RR:
26796 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26797 				ip1dbg((
26798 				    "ip_wput_options: bad option offset\n"));
26799 				code = (char *)&opt[IPOPT_OLEN] -
26800 				    (char *)ipha;
26801 				goto param_prob;
26802 			}
26803 			break;
26804 		case IPOPT_TS:
26805 			/*
26806 			 * Verify that length >=5 and that there is either
26807 			 * room for another timestamp or that the overflow
26808 			 * counter is not maxed out.
26809 			 */
26810 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
26811 			if (optlen < IPOPT_MINLEN_IT) {
26812 				goto param_prob;
26813 			}
26814 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26815 				ip1dbg((
26816 				    "ip_wput_options: bad option offset\n"));
26817 				code = (char *)&opt[IPOPT_OFFSET] -
26818 				    (char *)ipha;
26819 				goto param_prob;
26820 			}
26821 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
26822 			case IPOPT_TS_TSONLY:
26823 				off = IPOPT_TS_TIMELEN;
26824 				break;
26825 			case IPOPT_TS_TSANDADDR:
26826 			case IPOPT_TS_PRESPEC:
26827 			case IPOPT_TS_PRESPEC_RFC791:
26828 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
26829 				break;
26830 			default:
26831 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
26832 				    (char *)ipha;
26833 				goto param_prob;
26834 			}
26835 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
26836 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
26837 				/*
26838 				 * No room and the overflow counter is 15
26839 				 * already.
26840 				 */
26841 				goto param_prob;
26842 			}
26843 			break;
26844 		}
26845 	}
26846 
26847 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
26848 		return (0);
26849 
26850 	ip1dbg(("ip_wput_options: error processing IP options."));
26851 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
26852 
26853 param_prob:
26854 	/*
26855 	 * Since ip_wput() isn't close to finished, we fill
26856 	 * in enough of the header for credible error reporting.
26857 	 */
26858 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
26859 		/* Failed */
26860 		freemsg(ipsec_mp);
26861 		return (-1);
26862 	}
26863 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid);
26864 	return (-1);
26865 
26866 bad_src_route:
26867 	/*
26868 	 * Since ip_wput() isn't close to finished, we fill
26869 	 * in enough of the header for credible error reporting.
26870 	 */
26871 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
26872 		/* Failed */
26873 		freemsg(ipsec_mp);
26874 		return (-1);
26875 	}
26876 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
26877 	return (-1);
26878 }
26879 
26880 /*
26881  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
26882  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
26883  * thru /etc/system.
26884  */
26885 #define	CONN_MAXDRAINCNT	64
26886 
26887 static void
26888 conn_drain_init(void)
26889 {
26890 	int i;
26891 
26892 	conn_drain_list_cnt = conn_drain_nthreads;
26893 
26894 	if ((conn_drain_list_cnt == 0) ||
26895 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
26896 		/*
26897 		 * Default value of the number of drainers is the
26898 		 * number of cpus, subject to maximum of 8 drainers.
26899 		 */
26900 		if (boot_max_ncpus != -1)
26901 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
26902 		else
26903 			conn_drain_list_cnt = MIN(max_ncpus, 8);
26904 	}
26905 
26906 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
26907 	    KM_SLEEP);
26908 
26909 	for (i = 0; i < conn_drain_list_cnt; i++) {
26910 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
26911 		    MUTEX_DEFAULT, NULL);
26912 	}
26913 }
26914 
26915 static void
26916 conn_drain_fini(void)
26917 {
26918 	int i;
26919 
26920 	for (i = 0; i < conn_drain_list_cnt; i++)
26921 		mutex_destroy(&conn_drain_list[i].idl_lock);
26922 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
26923 	conn_drain_list = NULL;
26924 }
26925 
26926 /*
26927  * Note: For an overview of how flowcontrol is handled in IP please see the
26928  * IP Flowcontrol notes at the top of this file.
26929  *
26930  * Flow control has blocked us from proceeding. Insert the given conn in one
26931  * of the conn drain lists. These conn wq's will be qenabled later on when
26932  * STREAMS flow control does a backenable. conn_walk_drain will enable
26933  * the first conn in each of these drain lists. Each of these qenabled conns
26934  * in turn enables the next in the list, after it runs, or when it closes,
26935  * thus sustaining the drain process.
26936  *
26937  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
26938  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
26939  * running at any time, on a given conn, since there can be only 1 service proc
26940  * running on a queue at any time.
26941  */
26942 void
26943 conn_drain_insert(conn_t *connp)
26944 {
26945 	idl_t	*idl;
26946 	uint_t	index;
26947 
26948 	mutex_enter(&connp->conn_lock);
26949 	if (connp->conn_state_flags & CONN_CLOSING) {
26950 		/*
26951 		 * The conn is closing as a result of which CONN_CLOSING
26952 		 * is set. Return.
26953 		 */
26954 		mutex_exit(&connp->conn_lock);
26955 		return;
26956 	} else if (connp->conn_idl == NULL) {
26957 		/*
26958 		 * Assign the next drain list round robin. We dont' use
26959 		 * a lock, and thus it may not be strictly round robin.
26960 		 * Atomicity of load/stores is enough to make sure that
26961 		 * conn_drain_list_index is always within bounds.
26962 		 */
26963 		index = conn_drain_list_index;
26964 		ASSERT(index < conn_drain_list_cnt);
26965 		connp->conn_idl = &conn_drain_list[index];
26966 		index++;
26967 		if (index == conn_drain_list_cnt)
26968 			index = 0;
26969 		conn_drain_list_index = index;
26970 	}
26971 	mutex_exit(&connp->conn_lock);
26972 
26973 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
26974 	if ((connp->conn_drain_prev != NULL) ||
26975 	    (connp->conn_state_flags & CONN_CLOSING)) {
26976 		/*
26977 		 * The conn is already in the drain list, OR
26978 		 * the conn is closing. We need to check again for
26979 		 * the closing case again since close can happen
26980 		 * after we drop the conn_lock, and before we
26981 		 * acquire the CONN_DRAIN_LIST_LOCK.
26982 		 */
26983 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26984 		return;
26985 	} else {
26986 		idl = connp->conn_idl;
26987 	}
26988 
26989 	/*
26990 	 * The conn is not in the drain list. Insert it at the
26991 	 * tail of the drain list. The drain list is circular
26992 	 * and doubly linked. idl_conn points to the 1st element
26993 	 * in the list.
26994 	 */
26995 	if (idl->idl_conn == NULL) {
26996 		idl->idl_conn = connp;
26997 		connp->conn_drain_next = connp;
26998 		connp->conn_drain_prev = connp;
26999 	} else {
27000 		conn_t *head = idl->idl_conn;
27001 
27002 		connp->conn_drain_next = head;
27003 		connp->conn_drain_prev = head->conn_drain_prev;
27004 		head->conn_drain_prev->conn_drain_next = connp;
27005 		head->conn_drain_prev = connp;
27006 	}
27007 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27008 }
27009 
27010 /*
27011  * This conn is closing, and we are called from ip_close. OR
27012  * This conn has been serviced by ip_wsrv, and we need to do the tail
27013  * processing.
27014  * If this conn is part of the drain list, we may need to sustain the drain
27015  * process by qenabling the next conn in the drain list. We may also need to
27016  * remove this conn from the list, if it is done.
27017  */
27018 static void
27019 conn_drain_tail(conn_t *connp, boolean_t closing)
27020 {
27021 	idl_t *idl;
27022 
27023 	/*
27024 	 * connp->conn_idl is stable at this point, and no lock is needed
27025 	 * to check it. If we are called from ip_close, close has already
27026 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27027 	 * called us only because conn_idl is non-null. If we are called thru
27028 	 * service, conn_idl could be null, but it cannot change because
27029 	 * service is single-threaded per queue, and there cannot be another
27030 	 * instance of service trying to call conn_drain_insert on this conn
27031 	 * now.
27032 	 */
27033 	ASSERT(!closing || (connp->conn_idl != NULL));
27034 
27035 	/*
27036 	 * If connp->conn_idl is null, the conn has not been inserted into any
27037 	 * drain list even once since creation of the conn. Just return.
27038 	 */
27039 	if (connp->conn_idl == NULL)
27040 		return;
27041 
27042 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27043 
27044 	if (connp->conn_drain_prev == NULL) {
27045 		/* This conn is currently not in the drain list.  */
27046 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27047 		return;
27048 	}
27049 	idl = connp->conn_idl;
27050 	if (idl->idl_conn_draining == connp) {
27051 		/*
27052 		 * This conn is the current drainer. If this is the last conn
27053 		 * in the drain list, we need to do more checks, in the 'if'
27054 		 * below. Otherwwise we need to just qenable the next conn,
27055 		 * to sustain the draining, and is handled in the 'else'
27056 		 * below.
27057 		 */
27058 		if (connp->conn_drain_next == idl->idl_conn) {
27059 			/*
27060 			 * This conn is the last in this list. This round
27061 			 * of draining is complete. If idl_repeat is set,
27062 			 * it means another flow enabling has happened from
27063 			 * the driver/streams and we need to another round
27064 			 * of draining.
27065 			 * If there are more than 2 conns in the drain list,
27066 			 * do a left rotate by 1, so that all conns except the
27067 			 * conn at the head move towards the head by 1, and the
27068 			 * the conn at the head goes to the tail. This attempts
27069 			 * a more even share for all queues that are being
27070 			 * drained.
27071 			 */
27072 			if ((connp->conn_drain_next != connp) &&
27073 			    (idl->idl_conn->conn_drain_next != connp)) {
27074 				idl->idl_conn = idl->idl_conn->conn_drain_next;
27075 			}
27076 			if (idl->idl_repeat) {
27077 				qenable(idl->idl_conn->conn_wq);
27078 				idl->idl_conn_draining = idl->idl_conn;
27079 				idl->idl_repeat = 0;
27080 			} else {
27081 				idl->idl_conn_draining = NULL;
27082 			}
27083 		} else {
27084 			/*
27085 			 * If the next queue that we are now qenable'ing,
27086 			 * is closing, it will remove itself from this list
27087 			 * and qenable the subsequent queue in ip_close().
27088 			 * Serialization is acheived thru idl_lock.
27089 			 */
27090 			qenable(connp->conn_drain_next->conn_wq);
27091 			idl->idl_conn_draining = connp->conn_drain_next;
27092 		}
27093 	}
27094 	if (!connp->conn_did_putbq || closing) {
27095 		/*
27096 		 * Remove ourself from the drain list, if we did not do
27097 		 * a putbq, or if the conn is closing.
27098 		 * Note: It is possible that q->q_first is non-null. It means
27099 		 * that these messages landed after we did a enableok() in
27100 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
27101 		 * service them.
27102 		 */
27103 		if (connp->conn_drain_next == connp) {
27104 			/* Singleton in the list */
27105 			ASSERT(connp->conn_drain_prev == connp);
27106 			idl->idl_conn = NULL;
27107 			idl->idl_conn_draining = NULL;
27108 		} else {
27109 			connp->conn_drain_prev->conn_drain_next =
27110 			    connp->conn_drain_next;
27111 			connp->conn_drain_next->conn_drain_prev =
27112 			    connp->conn_drain_prev;
27113 			if (idl->idl_conn == connp)
27114 				idl->idl_conn = connp->conn_drain_next;
27115 			ASSERT(idl->idl_conn_draining != connp);
27116 
27117 		}
27118 		connp->conn_drain_next = NULL;
27119 		connp->conn_drain_prev = NULL;
27120 	}
27121 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27122 }
27123 
27124 /*
27125  * Write service routine. Shared perimeter entry point.
27126  * ip_wsrv can be called in any of the following ways.
27127  * 1. The device queue's messages has fallen below the low water mark
27128  *    and STREAMS has backenabled the ill_wq. We walk thru all the
27129  *    the drain lists and backenable the first conn in each list.
27130  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
27131  *    qenabled non-tcp upper layers. We start dequeing messages and call
27132  *    ip_wput for each message.
27133  */
27134 
27135 void
27136 ip_wsrv(queue_t *q)
27137 {
27138 	conn_t	*connp;
27139 	ill_t	*ill;
27140 	mblk_t	*mp;
27141 
27142 	if (q->q_next) {
27143 		ill = (ill_t *)q->q_ptr;
27144 		if (ill->ill_state_flags == 0) {
27145 			/*
27146 			 * The device flow control has opened up.
27147 			 * Walk through conn drain lists and qenable the
27148 			 * first conn in each list. This makes sense only
27149 			 * if the stream is fully plumbed and setup.
27150 			 * Hence the if check above.
27151 			 */
27152 			ip1dbg(("ip_wsrv: walking\n"));
27153 			conn_walk_drain();
27154 		}
27155 		return;
27156 	}
27157 
27158 	connp = Q_TO_CONN(q);
27159 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
27160 
27161 	/*
27162 	 * 1. Set conn_draining flag to signal that service is active.
27163 	 *
27164 	 * 2. ip_output determines whether it has been called from service,
27165 	 *    based on the last parameter. If it is IP_WSRV it concludes it
27166 	 *    has been called from service.
27167 	 *
27168 	 * 3. Message ordering is preserved by the following logic.
27169 	 *    i. A directly called ip_output (i.e. not thru service) will queue
27170 	 *    the message at the tail, if conn_draining is set (i.e. service
27171 	 *    is running) or if q->q_first is non-null.
27172 	 *
27173 	 *    ii. If ip_output is called from service, and if ip_output cannot
27174 	 *    putnext due to flow control, it does a putbq.
27175 	 *
27176 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
27177 	 *    (causing an infinite loop).
27178 	 */
27179 	ASSERT(!connp->conn_did_putbq);
27180 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
27181 		connp->conn_draining = 1;
27182 		noenable(q);
27183 		while ((mp = getq(q)) != NULL) {
27184 			ASSERT(CONN_Q(q));
27185 
27186 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
27187 			if (connp->conn_did_putbq) {
27188 				/* ip_wput did a putbq */
27189 				break;
27190 			}
27191 		}
27192 		/*
27193 		 * At this point, a thread coming down from top, calling
27194 		 * ip_wput, may end up queueing the message. We have not yet
27195 		 * enabled the queue, so ip_wsrv won't be called again.
27196 		 * To avoid this race, check q->q_first again (in the loop)
27197 		 * If the other thread queued the message before we call
27198 		 * enableok(), we will catch it in the q->q_first check.
27199 		 * If the other thread queues the message after we call
27200 		 * enableok(), ip_wsrv will be called again by STREAMS.
27201 		 */
27202 		connp->conn_draining = 0;
27203 		enableok(q);
27204 	}
27205 
27206 	/* Enable the next conn for draining */
27207 	conn_drain_tail(connp, B_FALSE);
27208 
27209 	connp->conn_did_putbq = 0;
27210 }
27211 
27212 /*
27213  * Walk the list of all conn's calling the function provided with the
27214  * specified argument for each.	 Note that this only walks conn's that
27215  * have been bound.
27216  * Applies to both IPv4 and IPv6.
27217  */
27218 static void
27219 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
27220 {
27221 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
27222 	    func, arg, zoneid);
27223 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
27224 	    func, arg, zoneid);
27225 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
27226 	    func, arg, zoneid);
27227 	conn_walk_fanout_table(ipcl_proto_fanout,
27228 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
27229 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
27230 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
27231 }
27232 
27233 /*
27234  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
27235  * of conns that need to be drained, check if drain is already in progress.
27236  * If so set the idl_repeat bit, indicating that the last conn in the list
27237  * needs to reinitiate the drain once again, for the list. If drain is not
27238  * in progress for the list, initiate the draining, by qenabling the 1st
27239  * conn in the list. The drain is self-sustaining, each qenabled conn will
27240  * in turn qenable the next conn, when it is done/blocked/closing.
27241  */
27242 static void
27243 conn_walk_drain(void)
27244 {
27245 	int i;
27246 	idl_t *idl;
27247 
27248 	IP_STAT(ip_conn_walk_drain);
27249 
27250 	for (i = 0; i < conn_drain_list_cnt; i++) {
27251 		idl = &conn_drain_list[i];
27252 		mutex_enter(&idl->idl_lock);
27253 		if (idl->idl_conn == NULL) {
27254 			mutex_exit(&idl->idl_lock);
27255 			continue;
27256 		}
27257 		/*
27258 		 * If this list is not being drained currently by
27259 		 * an ip_wsrv thread, start the process.
27260 		 */
27261 		if (idl->idl_conn_draining == NULL) {
27262 			ASSERT(idl->idl_repeat == 0);
27263 			qenable(idl->idl_conn->conn_wq);
27264 			idl->idl_conn_draining = idl->idl_conn;
27265 		} else {
27266 			idl->idl_repeat = 1;
27267 		}
27268 		mutex_exit(&idl->idl_lock);
27269 	}
27270 }
27271 
27272 /*
27273  * Walk an conn hash table of `count' buckets, calling func for each entry.
27274  */
27275 static void
27276 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
27277     zoneid_t zoneid)
27278 {
27279 	conn_t	*connp;
27280 
27281 	while (count-- > 0) {
27282 		mutex_enter(&connfp->connf_lock);
27283 		for (connp = connfp->connf_head; connp != NULL;
27284 		    connp = connp->conn_next) {
27285 			if (zoneid == GLOBAL_ZONEID ||
27286 			    zoneid == connp->conn_zoneid) {
27287 				CONN_INC_REF(connp);
27288 				mutex_exit(&connfp->connf_lock);
27289 				(*func)(connp, arg);
27290 				mutex_enter(&connfp->connf_lock);
27291 				CONN_DEC_REF(connp);
27292 			}
27293 		}
27294 		mutex_exit(&connfp->connf_lock);
27295 		connfp++;
27296 	}
27297 }
27298 
27299 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
27300 static void
27301 conn_report1(conn_t *connp, void *mp)
27302 {
27303 	char	buf1[INET6_ADDRSTRLEN];
27304 	char	buf2[INET6_ADDRSTRLEN];
27305 	uint_t	print_len, buf_len;
27306 
27307 	ASSERT(connp != NULL);
27308 
27309 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
27310 	if (buf_len <= 0)
27311 		return;
27312 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
27313 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
27314 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
27315 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
27316 	    "%5d %s/%05d %s/%05d\n",
27317 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
27318 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
27319 	    buf1, connp->conn_lport,
27320 	    buf2, connp->conn_fport);
27321 	if (print_len < buf_len) {
27322 		((mblk_t *)mp)->b_wptr += print_len;
27323 	} else {
27324 		((mblk_t *)mp)->b_wptr += buf_len;
27325 	}
27326 }
27327 
27328 /*
27329  * Named Dispatch routine to produce a formatted report on all conns
27330  * that are listed in one of the fanout tables.
27331  * This report is accessed by using the ndd utility to "get" ND variable
27332  * "ip_conn_status".
27333  */
27334 /* ARGSUSED */
27335 static int
27336 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
27337 {
27338 	(void) mi_mpprintf(mp,
27339 	    "CONN      " MI_COL_HDRPAD_STR
27340 	    "rfq      " MI_COL_HDRPAD_STR
27341 	    "stq      " MI_COL_HDRPAD_STR
27342 	    " zone local                 remote");
27343 
27344 	/*
27345 	 * Because of the ndd constraint, at most we can have 64K buffer
27346 	 * to put in all conn info.  So to be more efficient, just
27347 	 * allocate a 64K buffer here, assuming we need that large buffer.
27348 	 * This should be OK as only privileged processes can do ndd /dev/ip.
27349 	 */
27350 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
27351 		/* The following may work even if we cannot get a large buf. */
27352 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
27353 		return (0);
27354 	}
27355 
27356 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
27357 	return (0);
27358 }
27359 
27360 /*
27361  * Determine if the ill and multicast aspects of that packets
27362  * "matches" the conn.
27363  */
27364 boolean_t
27365 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
27366     zoneid_t zoneid)
27367 {
27368 	ill_t *in_ill;
27369 	boolean_t found;
27370 	ipif_t *ipif;
27371 	ire_t *ire;
27372 	ipaddr_t dst, src;
27373 
27374 	dst = ipha->ipha_dst;
27375 	src = ipha->ipha_src;
27376 
27377 	/*
27378 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
27379 	 * unicast, broadcast and multicast reception to
27380 	 * conn_incoming_ill. conn_wantpacket itself is called
27381 	 * only for BROADCAST and multicast.
27382 	 *
27383 	 * 1) ip_rput supresses duplicate broadcasts if the ill
27384 	 *    is part of a group. Hence, we should be receiving
27385 	 *    just one copy of broadcast for the whole group.
27386 	 *    Thus, if it is part of the group the packet could
27387 	 *    come on any ill of the group and hence we need a
27388 	 *    match on the group. Otherwise, match on ill should
27389 	 *    be sufficient.
27390 	 *
27391 	 * 2) ip_rput does not suppress duplicate multicast packets.
27392 	 *    If there are two interfaces in a ill group and we have
27393 	 *    2 applications (conns) joined a multicast group G on
27394 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
27395 	 *    will give us two packets because we join G on both the
27396 	 *    interfaces rather than nominating just one interface
27397 	 *    for receiving multicast like broadcast above. So,
27398 	 *    we have to call ilg_lookup_ill to filter out duplicate
27399 	 *    copies, if ill is part of a group.
27400 	 */
27401 	in_ill = connp->conn_incoming_ill;
27402 	if (in_ill != NULL) {
27403 		if (in_ill->ill_group == NULL) {
27404 			if (in_ill != ill)
27405 				return (B_FALSE);
27406 		} else if (in_ill->ill_group != ill->ill_group) {
27407 			return (B_FALSE);
27408 		}
27409 	}
27410 
27411 	if (!CLASSD(dst)) {
27412 		if (IPCL_ZONE_MATCH(connp, zoneid))
27413 			return (B_TRUE);
27414 		/*
27415 		 * The conn is in a different zone; we need to check that this
27416 		 * broadcast address is configured in the application's zone and
27417 		 * on one ill in the group.
27418 		 */
27419 		ipif = ipif_get_next_ipif(NULL, ill);
27420 		if (ipif == NULL)
27421 			return (B_FALSE);
27422 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
27423 		    connp->conn_zoneid, NULL,
27424 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
27425 		ipif_refrele(ipif);
27426 		if (ire != NULL) {
27427 			ire_refrele(ire);
27428 			return (B_TRUE);
27429 		} else {
27430 			return (B_FALSE);
27431 		}
27432 	}
27433 
27434 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
27435 	    connp->conn_zoneid == zoneid) {
27436 		/*
27437 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
27438 		 * disabled, therefore we don't dispatch the multicast packet to
27439 		 * the sending zone.
27440 		 */
27441 		return (B_FALSE);
27442 	}
27443 
27444 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
27445 	    connp->conn_zoneid != zoneid) {
27446 		/*
27447 		 * Multicast packet on the loopback interface: we only match
27448 		 * conns who joined the group in the specified zone.
27449 		 */
27450 		return (B_FALSE);
27451 	}
27452 
27453 	if (connp->conn_multi_router) {
27454 		/* multicast packet and multicast router socket: send up */
27455 		return (B_TRUE);
27456 	}
27457 
27458 	mutex_enter(&connp->conn_lock);
27459 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
27460 	mutex_exit(&connp->conn_lock);
27461 	return (found);
27462 }
27463 
27464 /*
27465  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
27466  */
27467 /* ARGSUSED */
27468 static void
27469 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
27470 {
27471 	ill_t *ill = (ill_t *)q->q_ptr;
27472 	mblk_t	*mp1, *mp2;
27473 	ipif_t  *ipif;
27474 	int err = 0;
27475 	conn_t *connp = NULL;
27476 	ipsq_t	*ipsq;
27477 	arc_t	*arc;
27478 
27479 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
27480 
27481 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
27482 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
27483 
27484 	ASSERT(IAM_WRITER_ILL(ill));
27485 	mp2 = mp->b_cont;
27486 	mp->b_cont = NULL;
27487 
27488 	/*
27489 	 * We have now received the arp bringup completion message
27490 	 * from ARP. Mark the arp bringup as done. Also if the arp
27491 	 * stream has already started closing, send up the AR_ARP_CLOSING
27492 	 * ack now since ARP is waiting in close for this ack.
27493 	 */
27494 	mutex_enter(&ill->ill_lock);
27495 	ill->ill_arp_bringup_pending = 0;
27496 	if (ill->ill_arp_closing) {
27497 		mutex_exit(&ill->ill_lock);
27498 		/* Let's reuse the mp for sending the ack */
27499 		arc = (arc_t *)mp->b_rptr;
27500 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
27501 		arc->arc_cmd = AR_ARP_CLOSING;
27502 		qreply(q, mp);
27503 	} else {
27504 		mutex_exit(&ill->ill_lock);
27505 		freeb(mp);
27506 	}
27507 
27508 	/* We should have an IOCTL waiting on this. */
27509 	ipsq = ill->ill_phyint->phyint_ipsq;
27510 	ipif = ipsq->ipsq_pending_ipif;
27511 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
27512 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
27513 	if (mp1 == NULL) {
27514 		/* bringup was aborted by the user */
27515 		freemsg(mp2);
27516 		return;
27517 	}
27518 	ASSERT(connp != NULL);
27519 	q = CONNP_TO_WQ(connp);
27520 	/*
27521 	 * If the DL_BIND_REQ fails, it is noted
27522 	 * in arc_name_offset.
27523 	 */
27524 	err = *((int *)mp2->b_rptr);
27525 	if (err == 0) {
27526 		if (ipif->ipif_isv6) {
27527 			if ((err = ipif_up_done_v6(ipif)) != 0)
27528 				ip0dbg(("ip_arp_done: init failed\n"));
27529 		} else {
27530 			if ((err = ipif_up_done(ipif)) != 0)
27531 				ip0dbg(("ip_arp_done: init failed\n"));
27532 		}
27533 	} else {
27534 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
27535 	}
27536 
27537 	freemsg(mp2);
27538 
27539 	if ((err == 0) && (ill->ill_up_ipifs)) {
27540 		err = ill_up_ipifs(ill, q, mp1);
27541 		if (err == EINPROGRESS)
27542 			return;
27543 	}
27544 
27545 	if (ill->ill_up_ipifs) {
27546 		ill_group_cleanup(ill);
27547 	}
27548 
27549 	/*
27550 	 * The ioctl must complete now without EINPROGRESS
27551 	 * since ipsq_pending_mp_get has removed the ioctl mblk
27552 	 * from ipsq_pending_mp. Otherwise the ioctl will be
27553 	 * stuck for ever in the ipsq.
27554 	 */
27555 	ASSERT(err != EINPROGRESS);
27556 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
27557 }
27558 
27559 /* Allocate the private structure */
27560 static int
27561 ip_priv_alloc(void **bufp)
27562 {
27563 	void	*buf;
27564 
27565 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
27566 		return (ENOMEM);
27567 
27568 	*bufp = buf;
27569 	return (0);
27570 }
27571 
27572 /* Function to delete the private structure */
27573 void
27574 ip_priv_free(void *buf)
27575 {
27576 	ASSERT(buf != NULL);
27577 	kmem_free(buf, sizeof (ip_priv_t));
27578 }
27579 
27580 /*
27581  * The entry point for IPPF processing.
27582  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
27583  * routine just returns.
27584  *
27585  * When called, ip_process generates an ipp_packet_t structure
27586  * which holds the state information for this packet and invokes the
27587  * the classifier (via ipp_packet_process). The classification, depending on
27588  * configured filters, results in a list of actions for this packet. Invoking
27589  * an action may cause the packet to be dropped, in which case the resulting
27590  * mblk (*mpp) is NULL. proc indicates the callout position for
27591  * this packet and ill_index is the interface this packet on or will leave
27592  * on (inbound and outbound resp.).
27593  */
27594 void
27595 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
27596 {
27597 	mblk_t		*mp;
27598 	ip_priv_t	*priv;
27599 	ipp_action_id_t	aid;
27600 	int		rc = 0;
27601 	ipp_packet_t	*pp;
27602 #define	IP_CLASS	"ip"
27603 
27604 	/* If the classifier is not loaded, return  */
27605 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
27606 		return;
27607 	}
27608 
27609 	mp = *mpp;
27610 	ASSERT(mp != NULL);
27611 
27612 	/* Allocate the packet structure */
27613 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
27614 	if (rc != 0) {
27615 		*mpp = NULL;
27616 		freemsg(mp);
27617 		return;
27618 	}
27619 
27620 	/* Allocate the private structure */
27621 	rc = ip_priv_alloc((void **)&priv);
27622 	if (rc != 0) {
27623 		*mpp = NULL;
27624 		freemsg(mp);
27625 		ipp_packet_free(pp);
27626 		return;
27627 	}
27628 	priv->proc = proc;
27629 	priv->ill_index = ill_index;
27630 	ipp_packet_set_private(pp, priv, ip_priv_free);
27631 	ipp_packet_set_data(pp, mp);
27632 
27633 	/* Invoke the classifier */
27634 	rc = ipp_packet_process(&pp);
27635 	if (pp != NULL) {
27636 		mp = ipp_packet_get_data(pp);
27637 		ipp_packet_free(pp);
27638 		if (rc != 0) {
27639 			freemsg(mp);
27640 			*mpp = NULL;
27641 		}
27642 	} else {
27643 		*mpp = NULL;
27644 	}
27645 #undef	IP_CLASS
27646 }
27647 
27648 /*
27649  * Propagate a multicast group membership operation (add/drop) on
27650  * all the interfaces crossed by the related multirt routes.
27651  * The call is considered successful if the operation succeeds
27652  * on at least one interface.
27653  */
27654 static int
27655 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
27656     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
27657     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
27658     mblk_t *first_mp)
27659 {
27660 	ire_t		*ire_gw;
27661 	irb_t		*irb;
27662 	int		error = 0;
27663 	opt_restart_t	*or;
27664 
27665 	irb = ire->ire_bucket;
27666 	ASSERT(irb != NULL);
27667 
27668 	ASSERT(DB_TYPE(first_mp) == M_CTL);
27669 
27670 	or = (opt_restart_t *)first_mp->b_rptr;
27671 	IRB_REFHOLD(irb);
27672 	for (; ire != NULL; ire = ire->ire_next) {
27673 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
27674 			continue;
27675 		if (ire->ire_addr != group)
27676 			continue;
27677 
27678 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
27679 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
27680 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
27681 		/* No resolver exists for the gateway; skip this ire. */
27682 		if (ire_gw == NULL)
27683 			continue;
27684 
27685 		/*
27686 		 * This function can return EINPROGRESS. If so the operation
27687 		 * will be restarted from ip_restart_optmgmt which will
27688 		 * call ip_opt_set and option processing will restart for
27689 		 * this option. So we may end up calling 'fn' more than once.
27690 		 * This requires that 'fn' is idempotent except for the
27691 		 * return value. The operation is considered a success if
27692 		 * it succeeds at least once on any one interface.
27693 		 */
27694 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
27695 		    NULL, fmode, src, first_mp);
27696 		if (error == 0)
27697 			or->or_private = CGTP_MCAST_SUCCESS;
27698 
27699 		if (ip_debug > 0) {
27700 			ulong_t	off;
27701 			char	*ksym;
27702 			ksym = kobj_getsymname((uintptr_t)fn, &off);
27703 			ip2dbg(("ip_multirt_apply_membership: "
27704 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
27705 			    "error %d [success %u]\n",
27706 			    ksym ? ksym : "?",
27707 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
27708 			    error, or->or_private));
27709 		}
27710 
27711 		ire_refrele(ire_gw);
27712 		if (error == EINPROGRESS) {
27713 			IRB_REFRELE(irb);
27714 			return (error);
27715 		}
27716 	}
27717 	IRB_REFRELE(irb);
27718 	/*
27719 	 * Consider the call as successful if we succeeded on at least
27720 	 * one interface. Otherwise, return the last encountered error.
27721 	 */
27722 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
27723 }
27724 
27725 
27726 /*
27727  * Issue a warning regarding a route crossing an interface with an
27728  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
27729  * amount of time is logged.
27730  */
27731 static void
27732 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
27733 {
27734 	hrtime_t	current = gethrtime();
27735 	char		buf[INET_ADDRSTRLEN];
27736 
27737 	/* Convert interval in ms to hrtime in ns */
27738 	if (multirt_bad_mtu_last_time +
27739 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
27740 	    current) {
27741 		cmn_err(CE_WARN, "ip: ignoring multiroute "
27742 		    "to %s, incorrect MTU %u (expected %u)\n",
27743 		    ip_dot_addr(ire->ire_addr, buf),
27744 		    ire->ire_max_frag, max_frag);
27745 
27746 		multirt_bad_mtu_last_time = current;
27747 	}
27748 }
27749 
27750 
27751 /*
27752  * Get the CGTP (multirouting) filtering status.
27753  * If 0, the CGTP hooks are transparent.
27754  */
27755 /* ARGSUSED */
27756 static int
27757 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
27758 {
27759 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
27760 
27761 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
27762 	return (0);
27763 }
27764 
27765 
27766 /*
27767  * Set the CGTP (multirouting) filtering status.
27768  * If the status is changed from active to transparent
27769  * or from transparent to active, forward the new status
27770  * to the filtering module (if loaded).
27771  */
27772 /* ARGSUSED */
27773 static int
27774 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
27775     cred_t *ioc_cr)
27776 {
27777 	long		new_value;
27778 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
27779 
27780 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
27781 	    new_value < 0 || new_value > 1) {
27782 		return (EINVAL);
27783 	}
27784 
27785 	/*
27786 	 * Do not enable CGTP filtering - thus preventing the hooks
27787 	 * from being invoked - if the version number of the
27788 	 * filtering module hooks does not match.
27789 	 */
27790 	if ((ip_cgtp_filter_ops != NULL) &&
27791 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
27792 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
27793 		    "(module hooks version %d, expecting %d)\n",
27794 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
27795 		return (ENOTSUP);
27796 	}
27797 
27798 	if ((!*ip_cgtp_filter_value) && new_value) {
27799 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
27800 		    ip_cgtp_filter_ops == NULL ?
27801 		    " (module not loaded)" : "");
27802 	}
27803 	if (*ip_cgtp_filter_value && (!new_value)) {
27804 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
27805 		    ip_cgtp_filter_ops == NULL ?
27806 		    " (module not loaded)" : "");
27807 	}
27808 
27809 	if (ip_cgtp_filter_ops != NULL) {
27810 		int	res;
27811 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
27812 			return (res);
27813 		}
27814 	}
27815 
27816 	*ip_cgtp_filter_value = (boolean_t)new_value;
27817 
27818 	return (0);
27819 }
27820 
27821 
27822 /*
27823  * Return the expected CGTP hooks version number.
27824  */
27825 int
27826 ip_cgtp_filter_supported(void)
27827 {
27828 	return (ip_cgtp_filter_rev);
27829 }
27830 
27831 
27832 /*
27833  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
27834  * or by invoking this function. In the first case, the version number
27835  * of the registered structure is checked at hooks activation time
27836  * in ip_cgtp_filter_set().
27837  */
27838 int
27839 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
27840 {
27841 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
27842 		return (ENOTSUP);
27843 
27844 	ip_cgtp_filter_ops = ops;
27845 	return (0);
27846 }
27847 
27848 static squeue_func_t
27849 ip_squeue_switch(int val)
27850 {
27851 	squeue_func_t rval = squeue_fill;
27852 
27853 	switch (val) {
27854 	case IP_SQUEUE_ENTER_NODRAIN:
27855 		rval = squeue_enter_nodrain;
27856 		break;
27857 	case IP_SQUEUE_ENTER:
27858 		rval = squeue_enter;
27859 		break;
27860 	default:
27861 		break;
27862 	}
27863 	return (rval);
27864 }
27865 
27866 /* ARGSUSED */
27867 static int
27868 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
27869     caddr_t addr, cred_t *cr)
27870 {
27871 	int *v = (int *)addr;
27872 	long new_value;
27873 
27874 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
27875 		return (EINVAL);
27876 
27877 	ip_input_proc = ip_squeue_switch(new_value);
27878 	*v = new_value;
27879 	return (0);
27880 }
27881 
27882 /* ARGSUSED */
27883 static int
27884 ip_int_set(queue_t *q, mblk_t *mp, char *value,
27885     caddr_t addr, cred_t *cr)
27886 {
27887 	int *v = (int *)addr;
27888 	long new_value;
27889 
27890 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
27891 		return (EINVAL);
27892 
27893 	*v = new_value;
27894 	return (0);
27895 }
27896 
27897 static void
27898 ip_kstat_init(void)
27899 {
27900 	ip_named_kstat_t template = {
27901 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
27902 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
27903 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
27904 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
27905 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
27906 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
27907 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
27908 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
27909 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
27910 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
27911 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
27912 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
27913 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
27914 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
27915 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
27916 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
27917 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
27918 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
27919 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
27920 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
27921 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
27922 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
27923 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
27924 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
27925 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
27926 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
27927 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
27928 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
27929 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
27930 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
27931 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
27932 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
27933 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
27934 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
27935 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
27936 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
27937 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
27938 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
27939 	};
27940 
27941 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
27942 					NUM_OF_FIELDS(ip_named_kstat_t),
27943 					0);
27944 	if (!ip_mibkp)
27945 		return;
27946 
27947 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
27948 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
27949 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
27950 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
27951 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
27952 
27953 	template.netToMediaEntrySize.value.i32 =
27954 		sizeof (mib2_ipNetToMediaEntry_t);
27955 
27956 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
27957 
27958 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
27959 
27960 	ip_mibkp->ks_update = ip_kstat_update;
27961 
27962 	kstat_install(ip_mibkp);
27963 }
27964 
27965 static void
27966 ip_kstat_fini(void)
27967 {
27968 
27969 	if (ip_mibkp != NULL) {
27970 		kstat_delete(ip_mibkp);
27971 		ip_mibkp = NULL;
27972 	}
27973 }
27974 
27975 static int
27976 ip_kstat_update(kstat_t *kp, int rw)
27977 {
27978 	ip_named_kstat_t *ipkp;
27979 
27980 	if (!kp || !kp->ks_data)
27981 		return (EIO);
27982 
27983 	if (rw == KSTAT_WRITE)
27984 		return (EACCES);
27985 
27986 	ipkp = (ip_named_kstat_t *)kp->ks_data;
27987 
27988 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
27989 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
27990 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
27991 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
27992 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
27993 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
27994 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
27995 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
27996 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
27997 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
27998 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
27999 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
28000 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
28001 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
28002 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
28003 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
28004 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
28005 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
28006 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
28007 
28008 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
28009 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
28010 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
28011 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
28012 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
28013 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
28014 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
28015 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
28016 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
28017 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
28018 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
28019 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
28020 
28021 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
28022 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
28023 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
28024 
28025 	return (0);
28026 }
28027 
28028 static void
28029 icmp_kstat_init(void)
28030 {
28031 	icmp_named_kstat_t template = {
28032 		{ "inMsgs",		KSTAT_DATA_UINT32 },
28033 		{ "inErrors",		KSTAT_DATA_UINT32 },
28034 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
28035 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
28036 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
28037 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
28038 		{ "inRedirects",	KSTAT_DATA_UINT32 },
28039 		{ "inEchos",		KSTAT_DATA_UINT32 },
28040 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
28041 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
28042 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
28043 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
28044 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
28045 		{ "outMsgs",		KSTAT_DATA_UINT32 },
28046 		{ "outErrors",		KSTAT_DATA_UINT32 },
28047 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
28048 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
28049 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
28050 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
28051 		{ "outRedirects",	KSTAT_DATA_UINT32 },
28052 		{ "outEchos",		KSTAT_DATA_UINT32 },
28053 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
28054 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
28055 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
28056 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
28057 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
28058 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
28059 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
28060 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
28061 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
28062 		{ "outDrops",		KSTAT_DATA_UINT32 },
28063 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
28064 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
28065 	};
28066 
28067 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
28068 					NUM_OF_FIELDS(icmp_named_kstat_t),
28069 					0);
28070 	if (icmp_mibkp == NULL)
28071 		return;
28072 
28073 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
28074 
28075 	icmp_mibkp->ks_update = icmp_kstat_update;
28076 
28077 	kstat_install(icmp_mibkp);
28078 }
28079 
28080 static void
28081 icmp_kstat_fini(void)
28082 {
28083 
28084 	if (icmp_mibkp != NULL) {
28085 		kstat_delete(icmp_mibkp);
28086 		icmp_mibkp = NULL;
28087 	}
28088 }
28089 
28090 static int
28091 icmp_kstat_update(kstat_t *kp, int rw)
28092 {
28093 	icmp_named_kstat_t *icmpkp;
28094 
28095 	if ((kp == NULL) || (kp->ks_data == NULL))
28096 		return (EIO);
28097 
28098 	if (rw == KSTAT_WRITE)
28099 		return (EACCES);
28100 
28101 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
28102 
28103 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
28104 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
28105 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
28106 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
28107 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
28108 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
28109 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
28110 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
28111 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
28112 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
28113 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
28114 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
28115 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
28116 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
28117 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
28118 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
28119 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
28120 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
28121 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
28122 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
28123 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
28124 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
28125 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
28126 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
28127 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
28128 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
28129 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
28130 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
28131 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
28132 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
28133 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
28134 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
28135 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
28136 
28137 	return (0);
28138 }
28139 
28140 /*
28141  * This is the fanout function for raw socket opened for SCTP.  Note
28142  * that it is called after SCTP checks that there is no socket which
28143  * wants a packet.  Then before SCTP handles this out of the blue packet,
28144  * this function is called to see if there is any raw socket for SCTP.
28145  * If there is and it is bound to the correct address, the packet will
28146  * be sent to that socket.  Note that only one raw socket can be bound to
28147  * a port.  This is assured in ipcl_sctp_hash_insert();
28148  */
28149 void
28150 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
28151     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
28152     uint_t ipif_seqid, zoneid_t zoneid)
28153 {
28154 	conn_t		*connp;
28155 	queue_t		*rq;
28156 	mblk_t		*first_mp;
28157 	boolean_t	secure;
28158 	ip6_t		*ip6h;
28159 
28160 	first_mp = mp;
28161 	if (mctl_present) {
28162 		mp = first_mp->b_cont;
28163 		secure = ipsec_in_is_secure(first_mp);
28164 		ASSERT(mp != NULL);
28165 	} else {
28166 		secure = B_FALSE;
28167 	}
28168 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
28169 
28170 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
28171 	if (connp == NULL) {
28172 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
28173 		    mctl_present);
28174 		return;
28175 	}
28176 	rq = connp->conn_rq;
28177 	if (!canputnext(rq)) {
28178 		CONN_DEC_REF(connp);
28179 		BUMP_MIB(&ip_mib, rawipInOverflows);
28180 		freemsg(first_mp);
28181 		return;
28182 	}
28183 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
28184 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
28185 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
28186 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
28187 		if (first_mp == NULL) {
28188 			CONN_DEC_REF(connp);
28189 			return;
28190 		}
28191 	}
28192 	/*
28193 	 * We probably should not send M_CTL message up to
28194 	 * raw socket.
28195 	 */
28196 	if (mctl_present)
28197 		freeb(first_mp);
28198 
28199 	/* Initiate IPPF processing here if needed. */
28200 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
28201 	    (!isv4 && IP6_IN_IPP(flags))) {
28202 		ip_process(IPP_LOCAL_IN, &mp,
28203 		    recv_ill->ill_phyint->phyint_ifindex);
28204 		if (mp == NULL) {
28205 			CONN_DEC_REF(connp);
28206 			return;
28207 		}
28208 	}
28209 
28210 	if (connp->conn_recvif || connp->conn_recvslla ||
28211 	    ((connp->conn_ipv6_recvpktinfo ||
28212 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
28213 	    (flags & IP_FF_IP6INFO))) {
28214 		int in_flags = 0;
28215 
28216 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
28217 			in_flags = IPF_RECVIF;
28218 		}
28219 		if (connp->conn_recvslla) {
28220 			in_flags |= IPF_RECVSLLA;
28221 		}
28222 		if (isv4) {
28223 			mp = ip_add_info(mp, recv_ill, in_flags);
28224 		} else {
28225 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
28226 			if (mp == NULL) {
28227 				CONN_DEC_REF(connp);
28228 				return;
28229 			}
28230 		}
28231 	}
28232 
28233 	BUMP_MIB(&ip_mib, ipInDelivers);
28234 	/*
28235 	 * We are sending the IPSEC_IN message also up. Refer
28236 	 * to comments above this function.
28237 	 */
28238 	putnext(rq, mp);
28239 	CONN_DEC_REF(connp);
28240 }
28241 
28242 /*
28243  * This function should be called only if all packet processing
28244  * including fragmentation is complete. Callers of this function
28245  * must set mp->b_prev to one of these values:
28246  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
28247  * prior to handing over the mp as first argument to this function.
28248  *
28249  * If the ire passed by caller is incomplete, this function
28250  * queues the packet and if necessary, sends ARP request and bails.
28251  * If the ire passed is fully resolved, we simply prepend
28252  * the link-layer header to the packet, do ipsec hw acceleration
28253  * work if necessary, and send the packet out on the wire.
28254  *
28255  * NOTE: IPSEC will only call this function with fully resolved
28256  * ires if hw acceleration is involved.
28257  * TODO list :
28258  * 	a Handle M_MULTIDATA so that
28259  *	  tcp_multisend->tcp_multisend_data can
28260  *	  call ip_xmit_v4 directly
28261  *	b Handle post-ARP work for fragments so that
28262  *	  ip_wput_frag can call this function.
28263  */
28264 ipxmit_state_t
28265 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
28266 {
28267 	nce_t		*arpce;
28268 	queue_t		*q;
28269 	int		ill_index;
28270 	mblk_t		*nxt_mp;
28271 	boolean_t	xmit_drop = B_FALSE;
28272 	ip_proc_t	proc;
28273 
28274 	arpce = ire->ire_nce;
28275 	ASSERT(arpce != NULL);
28276 
28277 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
28278 
28279 	mutex_enter(&arpce->nce_lock);
28280 	switch (arpce->nce_state) {
28281 	case ND_REACHABLE:
28282 		/* If there are other queued packets, queue this packet */
28283 		if (arpce->nce_qd_mp != NULL) {
28284 			if (mp != NULL)
28285 				nce_queue_mp_common(arpce, mp, B_FALSE);
28286 			mp = arpce->nce_qd_mp;
28287 		}
28288 		arpce->nce_qd_mp = NULL;
28289 		mutex_exit(&arpce->nce_lock);
28290 
28291 		/*
28292 		 * Flush the queue.  In the common case, where the
28293 		 * ARP is already resolved,  it will go through the
28294 		 * while loop only once.
28295 		 */
28296 		while (mp != NULL) {
28297 
28298 			nxt_mp = mp->b_next;
28299 			mp->b_next = NULL;
28300 			/*
28301 			 * This info is needed for IPQOS to do COS marking
28302 			 * in ip_wput_attach_llhdr->ip_process.
28303 			 */
28304 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
28305 			mp->b_prev = NULL;
28306 
28307 			/* set up ill index for outbound qos processing */
28308 			ill_index =
28309 			    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
28310 			mp = ip_wput_attach_llhdr(mp, ire, proc, ill_index);
28311 			if (mp == NULL) {
28312 				xmit_drop = B_TRUE;
28313 				if (proc == IPP_FWD_OUT) {
28314 					BUMP_MIB(&ip_mib, ipInDiscards);
28315 				} else {
28316 					BUMP_MIB(&ip_mib, ipOutDiscards);
28317 				}
28318 				goto next_mp;
28319 			}
28320 			/* non-ipsec hw accel case */
28321 			if (io == NULL || !io->ipsec_out_accelerated) {
28322 				/* send it */
28323 				q = ire->ire_stq;
28324 				if (proc == IPP_FWD_OUT) {
28325 					UPDATE_IB_PKT_COUNT(ire);
28326 				} else {
28327 					UPDATE_OB_PKT_COUNT(ire);
28328 				}
28329 				ire->ire_last_used_time = lbolt;
28330 
28331 				if (flow_ctl_enabled) {
28332 					/*
28333 					 * We are here from ip_wout_ire
28334 					 * which has already done canput
28335 					 * check and has enabled flow
28336 					 * control, so skip the canputnext
28337 					 * check.
28338 					 */
28339 					putnext(q, mp);
28340 					goto next_mp;
28341 				}
28342 				if (canputnext(q))  {
28343 					if (proc == IPP_FWD_OUT) {
28344 						BUMP_MIB(&ip_mib,
28345 						    ipForwDatagrams);
28346 					}
28347 					putnext(q, mp);
28348 				} else {
28349 					BUMP_MIB(&ip_mib,
28350 					    ipOutDiscards);
28351 					xmit_drop = B_TRUE;
28352 					freemsg(mp);
28353 				}
28354 			} else {
28355 				/*
28356 				 * Safety Pup says: make sure this
28357 				 *  is going to the right interface!
28358 				 */
28359 				ill_t *ill1 =
28360 				    (ill_t *)ire->ire_stq->q_ptr;
28361 				int ifindex =
28362 				    ill1->ill_phyint->phyint_ifindex;
28363 				if (ifindex !=
28364 				    io->ipsec_out_capab_ill_index) {
28365 					xmit_drop = B_TRUE;
28366 					freemsg(mp);
28367 				} else {
28368 					ipsec_hw_putnext(ire->ire_stq,
28369 					    mp);
28370 				}
28371 			}
28372 next_mp:
28373 			mp = nxt_mp;
28374 		} /* while (mp != NULL) */
28375 		if (xmit_drop)
28376 			return (SEND_FAILED);
28377 		else
28378 			return (SEND_PASSED);
28379 
28380 	case ND_INITIAL:
28381 	case ND_INCOMPLETE:
28382 
28383 		/*
28384 		 * While we do send off packets to dests that
28385 		 * use fully-resolved CGTP routes, we do not
28386 		 * handle unresolved CGTP routes.
28387 		 */
28388 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
28389 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
28390 
28391 		if (mp != NULL) {
28392 			/* queue the packet */
28393 			nce_queue_mp_common(arpce, mp, B_FALSE);
28394 		}
28395 
28396 		if (arpce->nce_state == ND_INCOMPLETE) {
28397 			mutex_exit(&arpce->nce_lock);
28398 			DTRACE_PROBE3(ip__xmit__incomplete,
28399 			    (ire_t *), ire, (mblk_t *), mp,
28400 			    (ipsec_out_t *), io);
28401 			return (LOOKUP_IN_PROGRESS);
28402 		}
28403 
28404 		arpce->nce_state = ND_INCOMPLETE;
28405 		mutex_exit(&arpce->nce_lock);
28406 		/*
28407 		 * Note that ire_add() (called from ire_forward())
28408 		 * holds a ref on the ire until ARP is completed.
28409 		 */
28410 
28411 		ire_arpresolve(ire, ire->ire_ipif->ipif_ill);
28412 		return (LOOKUP_IN_PROGRESS);
28413 	default:
28414 		ASSERT(0);
28415 		mutex_exit(&arpce->nce_lock);
28416 		return (LLHDR_RESLV_FAILED);
28417 	}
28418 }
28419 
28420 /*
28421  * Return B_TRUE if the buffers differ in length or content.
28422  * This is used for comparing extension header buffers.
28423  * Note that an extension header would be declared different
28424  * even if all that changed was the next header value in that header i.e.
28425  * what really changed is the next extension header.
28426  */
28427 boolean_t
28428 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
28429     uint_t blen)
28430 {
28431 	if (!b_valid)
28432 		blen = 0;
28433 
28434 	if (alen != blen)
28435 		return (B_TRUE);
28436 	if (alen == 0)
28437 		return (B_FALSE);	/* Both zero length */
28438 	return (bcmp(abuf, bbuf, alen));
28439 }
28440 
28441 /*
28442  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
28443  * Return B_FALSE if memory allocation fails - don't change any state!
28444  */
28445 boolean_t
28446 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28447     const void *src, uint_t srclen)
28448 {
28449 	void *dst;
28450 
28451 	if (!src_valid)
28452 		srclen = 0;
28453 
28454 	ASSERT(*dstlenp == 0);
28455 	if (src != NULL && srclen != 0) {
28456 		dst = mi_alloc(srclen, BPRI_MED);
28457 		if (dst == NULL)
28458 			return (B_FALSE);
28459 	} else {
28460 		dst = NULL;
28461 	}
28462 	if (*dstp != NULL)
28463 		mi_free(*dstp);
28464 	*dstp = dst;
28465 	*dstlenp = dst == NULL ? 0 : srclen;
28466 	return (B_TRUE);
28467 }
28468 
28469 /*
28470  * Replace what is in *dst, *dstlen with the source.
28471  * Assumes ip_allocbuf has already been called.
28472  */
28473 void
28474 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28475     const void *src, uint_t srclen)
28476 {
28477 	if (!src_valid)
28478 		srclen = 0;
28479 
28480 	ASSERT(*dstlenp == srclen);
28481 	if (src != NULL && srclen != 0)
28482 		bcopy(src, *dstp, srclen);
28483 }
28484 
28485 /*
28486  * Free the storage pointed to by the members of an ip6_pkt_t.
28487  */
28488 void
28489 ip6_pkt_free(ip6_pkt_t *ipp)
28490 {
28491 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
28492 
28493 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
28494 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
28495 		ipp->ipp_hopopts = NULL;
28496 		ipp->ipp_hopoptslen = 0;
28497 	}
28498 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
28499 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
28500 		ipp->ipp_rtdstopts = NULL;
28501 		ipp->ipp_rtdstoptslen = 0;
28502 	}
28503 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
28504 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
28505 		ipp->ipp_dstopts = NULL;
28506 		ipp->ipp_dstoptslen = 0;
28507 	}
28508 	if (ipp->ipp_fields & IPPF_RTHDR) {
28509 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
28510 		ipp->ipp_rthdr = NULL;
28511 		ipp->ipp_rthdrlen = 0;
28512 	}
28513 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
28514 	    IPPF_RTHDR);
28515 }
28516