xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision 4c8a46c19290e68300bde1e62329c3ff413a21b7)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /* Copyright (c) 1990 Mentat Inc. */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/stream.h>
31 #include <sys/dlpi.h>
32 #include <sys/stropts.h>
33 #include <sys/sysmacros.h>
34 #include <sys/strsubr.h>
35 #include <sys/strlog.h>
36 #include <sys/strsun.h>
37 #include <sys/zone.h>
38 #define	_SUN_TPI_VERSION 2
39 #include <sys/tihdr.h>
40 #include <sys/xti_inet.h>
41 #include <sys/ddi.h>
42 #include <sys/sunddi.h>
43 #include <sys/cmn_err.h>
44 #include <sys/debug.h>
45 #include <sys/kobj.h>
46 #include <sys/modctl.h>
47 #include <sys/atomic.h>
48 #include <sys/policy.h>
49 #include <sys/priv.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/sdt.h>
55 #include <sys/socket.h>
56 #include <sys/vtrace.h>
57 #include <sys/isa_defs.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/kstatcom.h>
72 
73 #include <netinet/igmp_var.h>
74 #include <netinet/ip6.h>
75 #include <netinet/icmp6.h>
76 #include <netinet/sctp.h>
77 
78 #include <inet/ip.h>
79 #include <inet/ip_impl.h>
80 #include <inet/ip6.h>
81 #include <inet/ip6_asp.h>
82 #include <inet/tcp.h>
83 #include <inet/tcp_impl.h>
84 #include <inet/ip_multi.h>
85 #include <inet/ip_if.h>
86 #include <inet/ip_ire.h>
87 #include <inet/ip_ftable.h>
88 #include <inet/ip_rts.h>
89 #include <inet/optcom.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <sys/sunddi.h>
121 
122 #include <sys/tsol/label.h>
123 #include <sys/tsol/tnet.h>
124 
125 #include <rpc/pmap_prot.h>
126 
127 /*
128  * Values for squeue switch:
129  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
130  * IP_SQUEUE_ENTER: squeue_enter
131  * IP_SQUEUE_FILL: squeue_fill
132  */
133 int ip_squeue_enter = 2;
134 squeue_func_t ip_input_proc;
135 /*
136  * IP statistics.
137  */
138 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
139 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
140 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
141 
142 typedef struct ip_stat {
143 	kstat_named_t	ipsec_fanout_proto;
144 	kstat_named_t	ip_udp_fannorm;
145 	kstat_named_t	ip_udp_fanmb;
146 	kstat_named_t	ip_udp_fanothers;
147 	kstat_named_t	ip_udp_fast_path;
148 	kstat_named_t	ip_udp_slow_path;
149 	kstat_named_t	ip_udp_input_err;
150 	kstat_named_t	ip_tcppullup;
151 	kstat_named_t	ip_tcpoptions;
152 	kstat_named_t	ip_multipkttcp;
153 	kstat_named_t	ip_tcp_fast_path;
154 	kstat_named_t	ip_tcp_slow_path;
155 	kstat_named_t	ip_tcp_input_error;
156 	kstat_named_t	ip_db_ref;
157 	kstat_named_t	ip_notaligned1;
158 	kstat_named_t	ip_notaligned2;
159 	kstat_named_t	ip_multimblk3;
160 	kstat_named_t	ip_multimblk4;
161 	kstat_named_t	ip_ipoptions;
162 	kstat_named_t	ip_classify_fail;
163 	kstat_named_t	ip_opt;
164 	kstat_named_t	ip_udp_rput_local;
165 	kstat_named_t	ipsec_proto_ahesp;
166 	kstat_named_t	ip_conn_flputbq;
167 	kstat_named_t	ip_conn_walk_drain;
168 	kstat_named_t   ip_out_sw_cksum;
169 	kstat_named_t   ip_in_sw_cksum;
170 	kstat_named_t   ip_trash_ire_reclaim_calls;
171 	kstat_named_t   ip_trash_ire_reclaim_success;
172 	kstat_named_t   ip_ire_arp_timer_expired;
173 	kstat_named_t   ip_ire_redirect_timer_expired;
174 	kstat_named_t	ip_ire_pmtu_timer_expired;
175 	kstat_named_t	ip_input_multi_squeue;
176 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
177 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
178 	kstat_named_t	ip_tcp_in_sw_cksum_err;
179 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
180 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
181 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
182 	kstat_named_t	ip_udp_in_sw_cksum_err;
183 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
184 	kstat_named_t	ip_frag_mdt_pkt_out;
185 	kstat_named_t	ip_frag_mdt_discarded;
186 	kstat_named_t	ip_frag_mdt_allocfail;
187 	kstat_named_t	ip_frag_mdt_addpdescfail;
188 	kstat_named_t	ip_frag_mdt_allocd;
189 } ip_stat_t;
190 
191 static ip_stat_t ip_statistics = {
192 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
193 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
194 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
195 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
196 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
197 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
198 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
199 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
200 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
201 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
202 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
203 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
204 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
205 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
206 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
207 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
208 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
209 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
210 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
211 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
212 	{ "ip_opt",				KSTAT_DATA_UINT64 },
213 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
214 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
215 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
216 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
217 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
218 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
219 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
220 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
221 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
222 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
223 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
224 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
225 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
226 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
227 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
228 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
229 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
230 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
231 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
232 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
233 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
234 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
235 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
236 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
237 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
238 };
239 
240 static kstat_t *ip_kstat;
241 
242 #define	TCP6 "tcp6"
243 #define	TCP "tcp"
244 #define	SCTP "sctp"
245 #define	SCTP6 "sctp6"
246 
247 major_t TCP6_MAJ;
248 major_t TCP_MAJ;
249 major_t SCTP_MAJ;
250 major_t SCTP6_MAJ;
251 
252 int ip_poll_normal_ms = 100;
253 int ip_poll_normal_ticks = 0;
254 
255 /*
256  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
257  */
258 
259 struct listptr_s {
260 	mblk_t	*lp_head;	/* pointer to the head of the list */
261 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
262 };
263 
264 typedef struct listptr_s listptr_t;
265 
266 /*
267  * This is used by ip_snmp_get_mib2_ip_route_media and
268  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
269  */
270 typedef struct iproutedata_s {
271 	uint_t		ird_idx;
272 	listptr_t	ird_route;	/* ipRouteEntryTable */
273 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
274 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
275 } iproutedata_t;
276 
277 /*
278  * Cluster specific hooks. These should be NULL when booted as a non-cluster
279  */
280 
281 /*
282  * Hook functions to enable cluster networking
283  * On non-clustered systems these vectors must always be NULL.
284  *
285  * Hook function to Check ip specified ip address is a shared ip address
286  * in the cluster
287  *
288  */
289 int (*cl_inet_isclusterwide)(uint8_t protocol,
290     sa_family_t addr_family, uint8_t *laddrp) = NULL;
291 
292 /*
293  * Hook function to generate cluster wide ip fragment identifier
294  */
295 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
296     uint8_t *laddrp, uint8_t *faddrp) = NULL;
297 
298 /*
299  * Synchronization notes:
300  *
301  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
302  * MT level protection given by STREAMS. IP uses a combination of its own
303  * internal serialization mechanism and standard Solaris locking techniques.
304  * The internal serialization is per phyint (no IPMP) or per IPMP group.
305  * This is used to serialize plumbing operations, IPMP operations, certain
306  * multicast operations, most set ioctls, igmp/mld timers etc.
307  *
308  * Plumbing is a long sequence of operations involving message
309  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
310  * involved in plumbing operations. A natural model is to serialize these
311  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
312  * parallel without any interference. But various set ioctls on hme0 are best
313  * serialized. However if the system uses IPMP, the operations are easier if
314  * they are serialized on a per IPMP group basis since IPMP operations
315  * happen across ill's of a group. Thus the lowest common denominator is to
316  * serialize most set ioctls, multicast join/leave operations, IPMP operations
317  * igmp/mld timer operations, and processing of DLPI control messages received
318  * from drivers on a per IPMP group basis. If the system does not employ
319  * IPMP the serialization is on a per phyint basis. This serialization is
320  * provided by the ipsq_t and primitives operating on this. Details can
321  * be found in ip_if.c above the core primitives operating on ipsq_t.
322  *
323  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
324  * Simiarly lookup of an ire by a thread also returns a refheld ire.
325  * In addition ipif's and ill's referenced by the ire are also indirectly
326  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
327  * the ipif's address or netmask change as long as an ipif is refheld
328  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
329  * address of an ipif has to go through the ipsq_t. This ensures that only
330  * 1 such exclusive operation proceeds at any time on the ipif. It then
331  * deletes all ires associated with this ipif, and waits for all refcnts
332  * associated with this ipif to come down to zero. The address is changed
333  * only after the ipif has been quiesced. Then the ipif is brought up again.
334  * More details are described above the comment in ip_sioctl_flags.
335  *
336  * Packet processing is based mostly on IREs and are fully multi-threaded
337  * using standard Solaris MT techniques.
338  *
339  * There are explicit locks in IP to handle:
340  * - The ip_g_head list maintained by mi_open_link() and friends.
341  *
342  * - The reassembly data structures (one lock per hash bucket)
343  *
344  * - conn_lock is meant to protect conn_t fields. The fields actually
345  *   protected by conn_lock are documented in the conn_t definition.
346  *
347  * - ire_lock to protect some of the fields of the ire, IRE tables
348  *   (one lock per hash bucket). Refer to ip_ire.c for details.
349  *
350  * - ndp_g_lock and nce_lock for protecting NCEs.
351  *
352  * - ill_lock protects fields of the ill and ipif. Details in ip.h
353  *
354  * - ill_g_lock: This is a global reader/writer lock. Protects the following
355  *	* The AVL tree based global multi list of all ills.
356  *	* The linked list of all ipifs of an ill
357  *	* The <ill-ipsq> mapping
358  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
359  *	* The illgroup list threaded by ill_group_next.
360  *	* <ill-phyint> association
361  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
362  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
363  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
364  *   will all have to hold the ill_g_lock as writer for the actual duration
365  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
366  *   may be found in the IPMP section.
367  *
368  * - ill_lock:  This is a per ill mutex.
369  *   It protects some members of the ill and is documented below.
370  *   It also protects the <ill-ipsq> mapping
371  *   It also protects the illgroup list threaded by ill_group_next.
372  *   It also protects the <ill-phyint> assoc.
373  *   It also protects the list of ipifs hanging off the ill.
374  *
375  * - ipsq_lock: This is a per ipsq_t mutex lock.
376  *   This protects all the other members of the ipsq struct except
377  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
378  *
379  * - illgrp_lock: This is a per ill_group mutex lock.
380  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
381  *   which dictates which is the next ill in an ill_group that is to be chosen
382  *   for sending outgoing packets, through creation of an IRE_CACHE that
383  *   references this ill.
384  *
385  * - phyint_lock: This is a per phyint mutex lock. Protects just the
386  *   phyint_flags
387  *
388  * - ip_g_nd_lock: This is a global reader/writer lock.
389  *   Any call to nd_load to load a new parameter to the ND table must hold the
390  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
391  *   as reader.
392  *
393  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
394  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
395  *   uniqueness check also done atomically.
396  *
397  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
398  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
399  *   as a writer when adding or deleting elements from these lists, and
400  *   as a reader when walking these lists to send a SADB update to the
401  *   IPsec capable ills.
402  *
403  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
404  *   group list linked by ill_usesrc_grp_next. It also protects the
405  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
406  *   group is being added or deleted.  This lock is taken as a reader when
407  *   walking the list/group(eg: to get the number of members in a usesrc group).
408  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
409  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
410  *   example, it is not necessary to take this lock in the initial portion
411  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
412  *   ip_sioctl_flags since the these operations are executed exclusively and
413  *   that ensures that the "usesrc group state" cannot change. The "usesrc
414  *   group state" change can happen only in the latter part of
415  *   ip_sioctl_slifusesrc and in ill_delete.
416  *
417  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
418  *
419  * To change the <ill-phyint> association, the ill_g_lock must be held
420  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
421  * must be held.
422  *
423  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
424  * and the ill_lock of the ill in question must be held.
425  *
426  * To change the <ill-illgroup> association the ill_g_lock must be held as
427  * writer and the ill_lock of the ill in question must be held.
428  *
429  * To add or delete an ipif from the list of ipifs hanging off the ill,
430  * ill_g_lock (writer) and ill_lock must be held and the thread must be
431  * a writer on the associated ipsq,.
432  *
433  * To add or delete an ill to the system, the ill_g_lock must be held as
434  * writer and the thread must be a writer on the associated ipsq.
435  *
436  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
437  * must be a writer on the associated ipsq.
438  *
439  * Lock hierarchy
440  *
441  * Some lock hierarchy scenarios are listed below.
442  *
443  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
444  * ill_g_lock -> illgrp_lock -> ill_lock
445  * ill_g_lock -> ill_lock(s) -> phyint_lock
446  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
447  * ill_g_lock -> ip_addr_avail_lock
448  * conn_lock -> irb_lock -> ill_lock -> ire_lock
449  * ill_g_lock -> ip_g_nd_lock
450  *
451  * When more than 1 ill lock is needed to be held, all ill lock addresses
452  * are sorted on address and locked starting from highest addressed lock
453  * downward.
454  *
455  * Mobile-IP scenarios
456  *
457  * irb_lock -> ill_lock -> ire_mrtun_lock
458  * irb_lock -> ill_lock -> ire_srcif_table_lock
459  *
460  * IPsec scenarios
461  *
462  * ipsa_lock -> ill_g_lock -> ill_lock
463  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
464  * ipsec_capab_ills_lock -> ipsa_lock
465  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
466  *
467  * Trusted Solaris scenarios
468  *
469  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
470  * igsa_lock -> gcdb_lock
471  * gcgrp_rwlock -> ire_lock
472  * gcgrp_rwlock -> gcdb_lock
473  *
474  *
475  * Routing/forwarding table locking notes:
476  *
477  * Lock acquisition order: Radix tree lock, irb_lock.
478  * Requirements:
479  * i.  Walker must not hold any locks during the walker callback.
480  * ii  Walker must not see a truncated tree during the walk because of any node
481  *     deletion.
482  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
483  *     in many places in the code to walk the irb list. Thus even if all the
484  *     ires in a bucket have been deleted, we still can't free the radix node
485  *     until the ires have actually been inactive'd (freed).
486  *
487  * Tree traversal - Need to hold the global tree lock in read mode.
488  * Before dropping the global tree lock, need to either increment the ire_refcnt
489  * to ensure that the radix node can't be deleted.
490  *
491  * Tree add - Need to hold the global tree lock in write mode to add a
492  * radix node. To prevent the node from being deleted, increment the
493  * irb_refcnt, after the node is added to the tree. The ire itself is
494  * added later while holding the irb_lock, but not the tree lock.
495  *
496  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
497  * All associated ires must be inactive (i.e. freed), and irb_refcnt
498  * must be zero.
499  *
500  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
501  * global tree lock (read mode) for traversal.
502  *
503  * IPSEC notes :
504  *
505  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
506  * in front of the actual packet. For outbound datagrams, the M_CTL
507  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
508  * information used by the IPSEC code for applying the right level of
509  * protection. The information initialized by IP in the ipsec_out_t
510  * is determined by the per-socket policy or global policy in the system.
511  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
512  * ipsec_info.h) which starts out with nothing in it. It gets filled
513  * with the right information if it goes through the AH/ESP code, which
514  * happens if the incoming packet is secure. The information initialized
515  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
516  * the policy requirements needed by per-socket policy or global policy
517  * is met or not.
518  *
519  * If there is both per-socket policy (set using setsockopt) and there
520  * is also global policy match for the 5 tuples of the socket,
521  * ipsec_override_policy() makes the decision of which one to use.
522  *
523  * For fully connected sockets i.e dst, src [addr, port] is known,
524  * conn_policy_cached is set indicating that policy has been cached.
525  * conn_in_enforce_policy may or may not be set depending on whether
526  * there is a global policy match or per-socket policy match.
527  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
528  * Once the right policy is set on the conn_t, policy cannot change for
529  * this socket. This makes life simpler for TCP (UDP ?) where
530  * re-transmissions go out with the same policy. For symmetry, policy
531  * is cached for fully connected UDP sockets also. Thus if policy is cached,
532  * it also implies that policy is latched i.e policy cannot change
533  * on these sockets. As we have the right policy on the conn, we don't
534  * have to lookup global policy for every outbound and inbound datagram
535  * and thus serving as an optimization. Note that a global policy change
536  * does not affect fully connected sockets if they have policy. If fully
537  * connected sockets did not have any policy associated with it, global
538  * policy change may affect them.
539  *
540  * IP Flow control notes:
541  *
542  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
543  * cannot be sent down to the driver by IP, because of a canput failure, IP
544  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
545  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
546  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
547  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
548  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
549  * the queued messages, and removes the conn from the drain list, if all
550  * messages were drained. It also qenables the next conn in the drain list to
551  * continue the drain process.
552  *
553  * In reality the drain list is not a single list, but a configurable number
554  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
555  * list. If the ip_wsrv of the next qenabled conn does not run, because the
556  * stream closes, ip_close takes responsibility to qenable the next conn in
557  * the drain list. The directly called ip_wput path always does a putq, if
558  * it cannot putnext. Thus synchronization problems are handled between
559  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
560  * functions that manipulate this drain list. Furthermore conn_drain_insert
561  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
562  * running on a queue at any time. conn_drain_tail can be simultaneously called
563  * from both ip_wsrv and ip_close.
564  *
565  * IPQOS notes:
566  *
567  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
568  * and IPQoS modules. IPPF includes hooks in IP at different control points
569  * (callout positions) which direct packets to IPQoS modules for policy
570  * processing. Policies, if present, are global.
571  *
572  * The callout positions are located in the following paths:
573  *		o local_in (packets destined for this host)
574  *		o local_out (packets orginating from this host )
575  *		o fwd_in  (packets forwarded by this m/c - inbound)
576  *		o fwd_out (packets forwarded by this m/c - outbound)
577  * Hooks at these callout points can be enabled/disabled using the ndd variable
578  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
579  * By default all the callout positions are enabled.
580  *
581  * Outbound (local_out)
582  * Hooks are placed in ip_wput_ire and ipsec_out_process.
583  *
584  * Inbound (local_in)
585  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
586  * TCP and UDP fanout routines.
587  *
588  * Forwarding (in and out)
589  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
590  *
591  * IP Policy Framework processing (IPPF processing)
592  * Policy processing for a packet is initiated by ip_process, which ascertains
593  * that the classifier (ipgpc) is loaded and configured, failing which the
594  * packet resumes normal processing in IP. If the clasifier is present, the
595  * packet is acted upon by one or more IPQoS modules (action instances), per
596  * filters configured in ipgpc and resumes normal IP processing thereafter.
597  * An action instance can drop a packet in course of its processing.
598  *
599  * A boolean variable, ip_policy, is used in all the fanout routines that can
600  * invoke ip_process for a packet. This variable indicates if the packet should
601  * to be sent for policy processing. The variable is set to B_TRUE by default,
602  * i.e. when the routines are invoked in the normal ip procesing path for a
603  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
604  * ip_policy is set to B_FALSE for all the routines called in these two
605  * functions because, in the former case,  we don't process loopback traffic
606  * currently while in the latter, the packets have already been processed in
607  * icmp_inbound.
608  *
609  * Zones notes:
610  *
611  * The partitioning rules for networking are as follows:
612  * 1) Packets coming from a zone must have a source address belonging to that
613  * zone.
614  * 2) Packets coming from a zone can only be sent on a physical interface on
615  * which the zone has an IP address.
616  * 3) Between two zones on the same machine, packet delivery is only allowed if
617  * there's a matching route for the destination and zone in the forwarding
618  * table.
619  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
620  * different zones can bind to the same port with the wildcard address
621  * (INADDR_ANY).
622  *
623  * The granularity of interface partitioning is at the logical interface level.
624  * Therefore, every zone has its own IP addresses, and incoming packets can be
625  * attributed to a zone unambiguously. A logical interface is placed into a zone
626  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
627  * structure. Rule (1) is implemented by modifying the source address selection
628  * algorithm so that the list of eligible addresses is filtered based on the
629  * sending process zone.
630  *
631  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
632  * across all zones, depending on their type. Here is the break-up:
633  *
634  * IRE type				Shared/exclusive
635  * --------				----------------
636  * IRE_BROADCAST			Exclusive
637  * IRE_DEFAULT (default routes)		Shared (*)
638  * IRE_LOCAL				Exclusive (x)
639  * IRE_LOOPBACK				Exclusive
640  * IRE_PREFIX (net routes)		Shared (*)
641  * IRE_CACHE				Exclusive
642  * IRE_IF_NORESOLVER (interface routes)	Exclusive
643  * IRE_IF_RESOLVER (interface routes)	Exclusive
644  * IRE_HOST (host routes)		Shared (*)
645  *
646  * (*) A zone can only use a default or off-subnet route if the gateway is
647  * directly reachable from the zone, that is, if the gateway's address matches
648  * one of the zone's logical interfaces.
649  *
650  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
651  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
652  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
653  * address of the zone itself (the destination). Since IRE_LOCAL is used
654  * for communication between zones, ip_wput_ire has special logic to set
655  * the right source address when sending using an IRE_LOCAL.
656  *
657  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
658  * ire_cache_lookup restricts loopback using an IRE_LOCAL
659  * between zone to the case when L2 would have conceptually looped the packet
660  * back, i.e. the loopback which is required since neither Ethernet drivers
661  * nor Ethernet hardware loops them back. This is the case when the normal
662  * routes (ignoring IREs with different zoneids) would send out the packet on
663  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
664  * associated.
665  *
666  * Multiple zones can share a common broadcast address; typically all zones
667  * share the 255.255.255.255 address. Incoming as well as locally originated
668  * broadcast packets must be dispatched to all the zones on the broadcast
669  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
670  * since some zones may not be on the 10.16.72/24 network. To handle this, each
671  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
672  * sent to every zone that has an IRE_BROADCAST entry for the destination
673  * address on the input ill, see conn_wantpacket().
674  *
675  * Applications in different zones can join the same multicast group address.
676  * For IPv4, group memberships are per-logical interface, so they're already
677  * inherently part of a zone. For IPv6, group memberships are per-physical
678  * interface, so we distinguish IPv6 group memberships based on group address,
679  * interface and zoneid. In both cases, received multicast packets are sent to
680  * every zone for which a group membership entry exists. On IPv6 we need to
681  * check that the target zone still has an address on the receiving physical
682  * interface; it could have been removed since the application issued the
683  * IPV6_JOIN_GROUP.
684  */
685 
686 /*
687  * Squeue Fanout flags:
688  *	0: No fanout.
689  *	1: Fanout across all squeues
690  */
691 boolean_t	ip_squeue_fanout = 0;
692 
693 /*
694  * Maximum dups allowed per packet.
695  */
696 uint_t ip_max_frag_dups = 10;
697 
698 #define	IS_SIMPLE_IPH(ipha)						\
699 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
700 
701 /* RFC1122 Conformance */
702 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
703 
704 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
705 
706 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
707 
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
709 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t);
712 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
713     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
714 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
715 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
716 		    mblk_t *, int);
717 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
718 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
719 		    ill_t *, zoneid_t);
720 static void	icmp_options_update(ipha_t *);
721 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t);
722 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
723 		    zoneid_t zoneid);
724 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
725 static void	icmp_redirect(mblk_t *);
726 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
727 
728 static void	ip_arp_news(queue_t *, mblk_t *);
729 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
730 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
731 char		*ip_dot_addr(ipaddr_t, char *);
732 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
733 int		ip_close(queue_t *, int);
734 static char	*ip_dot_saddr(uchar_t *, char *);
735 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
736 		    boolean_t, boolean_t, ill_t *, zoneid_t);
737 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
738 		    boolean_t, boolean_t, zoneid_t);
739 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
740 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
741 static void	ip_lrput(queue_t *, mblk_t *);
742 ipaddr_t	ip_massage_options(ipha_t *);
743 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
744 ipaddr_t	ip_net_mask(ipaddr_t);
745 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
746 		    zoneid_t);
747 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
748 		    conn_t *, uint32_t, zoneid_t);
749 char		*ip_nv_lookup(nv_t *, int);
750 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
751 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
752 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
754 			    size_t);
755 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
756 void	ip_rput(queue_t *, mblk_t *);
757 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
758 		    void *dummy_arg);
759 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
760 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
761 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
762 			    ire_t *);
763 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
764 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
765 		    uint16_t *);
766 int		ip_snmp_get(queue_t *, mblk_t *);
767 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
768 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
769 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
770 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
771 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
772 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
773 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
775 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
777 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
778 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
779 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
780 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
781 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
782 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
783 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
784 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
785 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
786 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
787 static boolean_t	ip_source_routed(ipha_t *);
788 static boolean_t	ip_source_route_included(ipha_t *);
789 
790 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
791 		    zoneid_t);
792 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
793 static void	ip_wput_local_options(ipha_t *);
794 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
795 		    zoneid_t);
796 
797 static void	conn_drain_init(void);
798 static void	conn_drain_fini(void);
799 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
800 
801 static void	conn_walk_drain(void);
802 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
803     zoneid_t);
804 
805 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
806     zoneid_t);
807 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
808     void *dummy_arg);
809 
810 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
811 
812 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
813     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
814     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
815 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
816 
817 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
818 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
819     caddr_t, cred_t *);
820 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
821     caddr_t cp, cred_t *cr);
822 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
823     cred_t *);
824 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
825     caddr_t cp, cred_t *cr);
826 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
827     cred_t *);
828 static squeue_func_t ip_squeue_switch(int);
829 
830 static void	ip_kstat_init(void);
831 static void	ip_kstat_fini(void);
832 static int	ip_kstat_update(kstat_t *kp, int rw);
833 static void	icmp_kstat_init(void);
834 static void	icmp_kstat_fini(void);
835 static int	icmp_kstat_update(kstat_t *kp, int rw);
836 
837 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
838 
839 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
840     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
841 
842 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
843     ipha_t *, ill_t *, boolean_t);
844 
845 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
846 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
847 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
848 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
849 
850 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
851 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
852 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
853 
854 /* How long, in seconds, we allow frags to hang around. */
855 #define	IP_FRAG_TIMEOUT	60
856 
857 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
858 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
859 
860 /*
861  * Threshold which determines whether MDT should be used when
862  * generating IP fragments; payload size must be greater than
863  * this threshold for MDT to take place.
864  */
865 #define	IP_WPUT_FRAG_MDT_MIN	32768
866 
867 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
868 
869 /* Protected by ip_mi_lock */
870 static void	*ip_g_head;		/* Instance Data List Head */
871 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
872 
873 /* Only modified during _init and _fini thus no locking is needed. */
874 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
875 
876 
877 static long ip_rput_pullups;
878 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
879 
880 vmem_t *ip_minor_arena;
881 
882 /*
883  * MIB-2 stuff for SNMP (both IP and ICMP)
884  */
885 mib2_ip_t	ip_mib;
886 mib2_icmp_t	icmp_mib;
887 
888 #ifdef DEBUG
889 uint32_t ipsechw_debug = 0;
890 #endif
891 
892 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
893 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
894 
895 uint_t	loopback_packets = 0;
896 
897 /*
898  * Multirouting/CGTP stuff
899  */
900 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
901 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
902 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
903 /* Interval (in ms) between consecutive 'bad MTU' warnings */
904 hrtime_t ip_multirt_log_interval = 1000;
905 /* Time since last warning issued. */
906 static hrtime_t	multirt_bad_mtu_last_time = 0;
907 
908 kmutex_t ip_trash_timer_lock;
909 krwlock_t ip_g_nd_lock;
910 
911 /*
912  * XXX following really should only be in a header. Would need more
913  * header and .c clean up first.
914  */
915 extern optdb_obj_t	ip_opt_obj;
916 
917 ulong_t ip_squeue_enter_unbound = 0;
918 
919 /*
920  * Named Dispatch Parameter Table.
921  * All of these are alterable, within the min/max values given, at run time.
922  */
923 static ipparam_t	lcl_param_arr[] = {
924 	/* min	max	value	name */
925 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
926 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
927 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
928 	{  0,	1,	0,	"ip_respond_to_timestamp"},
929 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
930 	{  0,	1,	1,	"ip_send_redirects"},
931 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
932 	{  0,	10,	0,	"ip_debug"},
933 	{  0,	10,	0,	"ip_mrtdebug"},
934 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
935 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
936 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
937 	{  1,	255,	255,	"ip_def_ttl" },
938 	{  0,	1,	0,	"ip_forward_src_routed"},
939 	{  0,	256,	32,	"ip_wroff_extra" },
940 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
941 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
942 	{  0,	1,	1,	"ip_path_mtu_discovery" },
943 	{  0,	240,	30,	"ip_ignore_delete_time" },
944 	{  0,	1,	0,	"ip_ignore_redirect" },
945 	{  0,	1,	1,	"ip_output_queue" },
946 	{  1,	254,	1,	"ip_broadcast_ttl" },
947 	{  0,	99999,	100,	"ip_icmp_err_interval" },
948 	{  1,	99999,	10,	"ip_icmp_err_burst" },
949 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
950 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
951 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
952 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
953 	{  0,	1,	1,	"icmp_accept_clear_messages" },
954 	{  0,	1,	1,	"igmp_accept_clear_messages" },
955 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
956 				"ip_ndp_delay_first_probe_time"},
957 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
958 				"ip_ndp_max_unicast_solicit"},
959 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
960 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
961 	{  0,	1,	0,	"ip6_forward_src_routed"},
962 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
963 	{  0,	1,	1,	"ip6_send_redirects"},
964 	{  0,	1,	0,	"ip6_ignore_redirect" },
965 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
966 
967 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
968 
969 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
970 
971 	{  0,	1,	1,	"pim_accept_clear_messages" },
972 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
973 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
974 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
975 	{  0,	15,	0,	"ip_policy_mask" },
976 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
977 	{  0,	255,	1,	"ip_multirt_ttl" },
978 	{  0,	1,	1,	"ip_multidata_outbound" },
979 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
980 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
981 	{  0,	1000,	1,	"ip_max_temp_defend" },
982 	{  0,	1000,	3,	"ip_max_defend" },
983 	{  0,	999999,	30,	"ip_defend_interval" },
984 	{  0,	3600000, 300000, "ip_dup_recovery" },
985 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
986 #ifdef DEBUG
987 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
988 #endif
989 };
990 
991 ipparam_t	*ip_param_arr = lcl_param_arr;
992 
993 /* Extended NDP table */
994 static ipndp_t	lcl_ndp_arr[] = {
995 	/* getf			setf		data			name */
996 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
997 	    "ip_forwarding" },
998 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
999 	    "ip6_forwarding" },
1000 	{  ip_ill_report,	NULL,		NULL,
1001 	    "ip_ill_status" },
1002 	{  ip_ipif_report,	NULL,		NULL,
1003 	    "ip_ipif_status" },
1004 	{  ip_ire_report,	NULL,		NULL,
1005 	    "ipv4_ire_status" },
1006 	{  ip_ire_report_mrtun,	NULL,		NULL,
1007 	    "ipv4_mrtun_ire_status" },
1008 	{  ip_ire_report_srcif,	NULL,		NULL,
1009 	    "ipv4_srcif_ire_status" },
1010 	{  ip_ire_report_v6,	NULL,		NULL,
1011 	    "ipv6_ire_status" },
1012 	{  ip_conn_report,	NULL,		NULL,
1013 	    "ip_conn_status" },
1014 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1015 	    "ip_rput_pullups" },
1016 	{  ndp_report,		NULL,		NULL,
1017 	    "ip_ndp_cache_report" },
1018 	{  ip_srcid_report,	NULL,		NULL,
1019 	    "ip_srcid_status" },
1020 	{ ip_param_generic_get, ip_squeue_profile_set,
1021 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
1022 	{ ip_param_generic_get, ip_squeue_bind_set,
1023 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
1024 	{ ip_param_generic_get, ip_input_proc_set,
1025 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1026 	{ ip_param_generic_get, ip_int_set,
1027 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1028 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
1029 	    "ip_cgtp_filter" },
1030 	{ ip_param_generic_get, ip_int_set,
1031 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
1032 };
1033 
1034 /*
1035  * ip_g_forward controls IP forwarding.  It takes two values:
1036  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
1037  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
1038  *
1039  * RFC1122 says there must be a configuration switch to control forwarding,
1040  * but that the default MUST be to not forward packets ever.  Implicit
1041  * control based on configuration of multiple interfaces MUST NOT be
1042  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
1043  * and, in fact, it was the default.  That capability is now provided in the
1044  * /etc/rc2.d/S69inet script.
1045  */
1046 int ip_g_forward = IP_FORWARD_DEFAULT;
1047 
1048 /* It also has an IPv6 counterpart. */
1049 
1050 int ipv6_forward = IP_FORWARD_DEFAULT;
1051 
1052 /*
1053  * Table of IP ioctls encoding the various properties of the ioctl and
1054  * indexed based on the last byte of the ioctl command. Occasionally there
1055  * is a clash, and there is more than 1 ioctl with the same last byte.
1056  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1057  * ioctls are encoded in the misc table. An entry in the ndx table is
1058  * retrieved by indexing on the last byte of the ioctl command and comparing
1059  * the ioctl command with the value in the ndx table. In the event of a
1060  * mismatch the misc table is then searched sequentially for the desired
1061  * ioctl command.
1062  *
1063  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1064  */
1065 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1066 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 
1077 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1078 			MISC_CMD, ip_siocaddrt, NULL },
1079 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1080 			MISC_CMD, ip_siocdelrt, NULL },
1081 
1082 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1083 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1084 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1085 			IF_CMD, ip_sioctl_get_addr, NULL },
1086 
1087 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1088 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1089 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1090 			IPI_GET_CMD | IPI_REPL,
1091 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1092 
1093 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1094 			IPI_PRIV | IPI_WR | IPI_REPL,
1095 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1096 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1097 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1098 			IF_CMD, ip_sioctl_get_flags, NULL },
1099 
1100 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 
1103 	/* copyin size cannot be coded for SIOCGIFCONF */
1104 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1105 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1106 
1107 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1108 			IF_CMD, ip_sioctl_mtu, NULL },
1109 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1110 			IF_CMD, ip_sioctl_get_mtu, NULL },
1111 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1112 			IPI_GET_CMD | IPI_REPL,
1113 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1114 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1115 			IF_CMD, ip_sioctl_brdaddr, NULL },
1116 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1117 			IPI_GET_CMD | IPI_REPL,
1118 			IF_CMD, ip_sioctl_get_netmask, NULL },
1119 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1120 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1121 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1122 			IPI_GET_CMD | IPI_REPL,
1123 			IF_CMD, ip_sioctl_get_metric, NULL },
1124 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1125 			IF_CMD, ip_sioctl_metric, NULL },
1126 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 
1128 	/* See 166-168 below for extended SIOC*XARP ioctls */
1129 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1130 			MISC_CMD, ip_sioctl_arp, NULL },
1131 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1132 			MISC_CMD, ip_sioctl_arp, NULL },
1133 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1134 			MISC_CMD, ip_sioctl_arp, NULL },
1135 
1136 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 
1158 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1159 			MISC_CMD, if_unitsel, if_unitsel_restart },
1160 
1161 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 
1180 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1181 			IPI_PRIV | IPI_WR | IPI_MODOK,
1182 			IF_CMD, ip_sioctl_sifname, NULL },
1183 
1184 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1190 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 
1198 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1199 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1200 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1201 			IF_CMD, ip_sioctl_get_muxid, NULL },
1202 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1203 			IPI_PRIV | IPI_WR | IPI_REPL,
1204 			IF_CMD, ip_sioctl_muxid, NULL },
1205 
1206 	/* Both if and lif variants share same func */
1207 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1208 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1209 	/* Both if and lif variants share same func */
1210 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1211 			IPI_PRIV | IPI_WR | IPI_REPL,
1212 			IF_CMD, ip_sioctl_slifindex, NULL },
1213 
1214 	/* copyin size cannot be coded for SIOCGIFCONF */
1215 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1216 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1217 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1218 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1219 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1220 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1221 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1222 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1223 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1226 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1227 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1228 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1229 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1230 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1231 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1232 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1233 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1234 
1235 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1236 			IPI_PRIV | IPI_WR | IPI_REPL,
1237 			LIF_CMD, ip_sioctl_removeif,
1238 			ip_sioctl_removeif_restart },
1239 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1240 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1241 			LIF_CMD, ip_sioctl_addif, NULL },
1242 #define	SIOCLIFADDR_NDX 112
1243 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1244 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1245 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1246 			IPI_GET_CMD | IPI_REPL,
1247 			LIF_CMD, ip_sioctl_get_addr, NULL },
1248 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1249 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1250 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1251 			IPI_GET_CMD | IPI_REPL,
1252 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1253 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1254 			IPI_PRIV | IPI_WR | IPI_REPL,
1255 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1256 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1257 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1258 			LIF_CMD, ip_sioctl_get_flags, NULL },
1259 
1260 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1261 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1262 
1263 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1264 			ip_sioctl_get_lifconf, NULL },
1265 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1266 			LIF_CMD, ip_sioctl_mtu, NULL },
1267 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1268 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1269 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1270 			IPI_GET_CMD | IPI_REPL,
1271 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1272 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1273 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1274 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1275 			IPI_GET_CMD | IPI_REPL,
1276 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1277 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1278 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1279 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1280 			IPI_GET_CMD | IPI_REPL,
1281 			LIF_CMD, ip_sioctl_get_metric, NULL },
1282 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1283 			LIF_CMD, ip_sioctl_metric, NULL },
1284 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1285 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1286 			LIF_CMD, ip_sioctl_slifname,
1287 			ip_sioctl_slifname_restart },
1288 
1289 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1290 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1291 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1292 			IPI_GET_CMD | IPI_REPL,
1293 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1294 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1295 			IPI_PRIV | IPI_WR | IPI_REPL,
1296 			LIF_CMD, ip_sioctl_muxid, NULL },
1297 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1298 			IPI_GET_CMD | IPI_REPL,
1299 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1300 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1301 			IPI_PRIV | IPI_WR | IPI_REPL,
1302 			LIF_CMD, ip_sioctl_slifindex, 0 },
1303 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1304 			LIF_CMD, ip_sioctl_token, NULL },
1305 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1306 			IPI_GET_CMD | IPI_REPL,
1307 			LIF_CMD, ip_sioctl_get_token, NULL },
1308 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1309 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1310 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1311 			IPI_GET_CMD | IPI_REPL,
1312 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1313 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1314 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1315 
1316 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1317 			IPI_GET_CMD | IPI_REPL,
1318 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1319 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1320 			LIF_CMD, ip_siocdelndp_v6, NULL },
1321 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1322 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1323 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1324 			LIF_CMD, ip_siocsetndp_v6, NULL },
1325 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1326 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1327 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1328 			MISC_CMD, ip_sioctl_tonlink, NULL },
1329 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1330 			MISC_CMD, ip_sioctl_tmysite, NULL },
1331 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1332 			TUN_CMD, ip_sioctl_tunparam, NULL },
1333 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1334 			IPI_PRIV | IPI_WR,
1335 			TUN_CMD, ip_sioctl_tunparam, NULL },
1336 
1337 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1338 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1339 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1340 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1341 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1342 
1343 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1344 			IPI_PRIV | IPI_WR | IPI_REPL,
1345 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1346 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1347 			IPI_PRIV | IPI_WR | IPI_REPL,
1348 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1349 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1350 			IPI_PRIV | IPI_WR,
1351 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1352 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1353 			IPI_GET_CMD | IPI_REPL,
1354 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1355 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1356 			IPI_GET_CMD | IPI_REPL,
1357 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1358 
1359 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1360 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1361 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1362 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1363 
1364 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1365 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1366 
1367 	/* These are handled in ip_sioctl_copyin_setup itself */
1368 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1369 			MISC_CMD, NULL, NULL },
1370 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1371 			MISC_CMD, NULL, NULL },
1372 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1373 
1374 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1375 			ip_sioctl_get_lifconf, NULL },
1376 
1377 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1378 			MISC_CMD, ip_sioctl_xarp, NULL },
1379 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1380 			MISC_CMD, ip_sioctl_xarp, NULL },
1381 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1382 			MISC_CMD, ip_sioctl_xarp, NULL },
1383 
1384 	/* SIOCPOPSOCKFS is not handled by IP */
1385 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1386 
1387 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1388 			IPI_GET_CMD | IPI_REPL,
1389 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1390 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1391 			IPI_PRIV | IPI_WR | IPI_REPL,
1392 			LIF_CMD, ip_sioctl_slifzone,
1393 			ip_sioctl_slifzone_restart },
1394 	/* 172-174 are SCTP ioctls and not handled by IP */
1395 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1396 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1397 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1398 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1399 			IPI_GET_CMD, LIF_CMD,
1400 			ip_sioctl_get_lifusesrc, 0 },
1401 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1402 			IPI_PRIV | IPI_WR,
1403 			LIF_CMD, ip_sioctl_slifusesrc,
1404 			NULL },
1405 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1406 			ip_sioctl_get_lifsrcof, NULL },
1407 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1408 			MISC_CMD, ip_sioctl_msfilter, NULL },
1409 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1410 			MISC_CMD, ip_sioctl_msfilter, NULL },
1411 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1412 			MISC_CMD, ip_sioctl_msfilter, NULL },
1413 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1414 			MISC_CMD, ip_sioctl_msfilter, NULL },
1415 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1416 			ip_sioctl_set_ipmpfailback, NULL }
1417 };
1418 
1419 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1420 
1421 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1422 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1423 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1424 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1425 		TUN_CMD, ip_sioctl_tunparam, NULL },
1426 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1427 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1428 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1429 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1430 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1431 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1432 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1433 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1434 		MISC_CMD, mrt_ioctl},
1435 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1436 		MISC_CMD, mrt_ioctl},
1437 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1438 		MISC_CMD, mrt_ioctl}
1439 };
1440 
1441 int ip_misc_ioctl_count =
1442     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1443 
1444 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1445 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1446 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1447 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1448 					/* Settable in /etc/system */
1449 uint_t	ip_redirect_cnt;		/* Num of redirect routes in ftable */
1450 
1451 /* Defined in ip_ire.c */
1452 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1453 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1454 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1455 
1456 static nv_t	ire_nv_arr[] = {
1457 	{ IRE_BROADCAST, "BROADCAST" },
1458 	{ IRE_LOCAL, "LOCAL" },
1459 	{ IRE_LOOPBACK, "LOOPBACK" },
1460 	{ IRE_CACHE, "CACHE" },
1461 	{ IRE_DEFAULT, "DEFAULT" },
1462 	{ IRE_PREFIX, "PREFIX" },
1463 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1464 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1465 	{ IRE_HOST, "HOST" },
1466 	{ 0 }
1467 };
1468 
1469 nv_t	*ire_nv_tbl = ire_nv_arr;
1470 
1471 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1472 extern krwlock_t ipsec_capab_ills_lock;
1473 
1474 /* Defined in ip_netinfo.c */
1475 extern ddi_taskq_t	*eventq_queue_nic;
1476 
1477 /* Packet dropper for IP IPsec processing failures */
1478 ipdropper_t ip_dropper;
1479 
1480 /* Simple ICMP IP Header Template */
1481 static ipha_t icmp_ipha = {
1482 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1483 };
1484 
1485 struct module_info ip_mod_info = {
1486 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1487 };
1488 
1489 /*
1490  * Duplicate static symbols within a module confuses mdb; so we avoid the
1491  * problem by making the symbols here distinct from those in udp.c.
1492  */
1493 
1494 static struct qinit iprinit = {
1495 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1496 	&ip_mod_info
1497 };
1498 
1499 static struct qinit ipwinit = {
1500 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1501 	&ip_mod_info
1502 };
1503 
1504 static struct qinit iplrinit = {
1505 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1506 	&ip_mod_info
1507 };
1508 
1509 static struct qinit iplwinit = {
1510 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1511 	&ip_mod_info
1512 };
1513 
1514 struct streamtab ipinfo = {
1515 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1516 };
1517 
1518 #ifdef	DEBUG
1519 static boolean_t skip_sctp_cksum = B_FALSE;
1520 #endif
1521 
1522 /*
1523  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1524  * ip_rput_v6(), ip_output(), etc.  If the message
1525  * block already has a M_CTL at the front of it, then simply set the zoneid
1526  * appropriately.
1527  */
1528 mblk_t *
1529 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid)
1530 {
1531 	mblk_t		*first_mp;
1532 	ipsec_out_t	*io;
1533 
1534 	ASSERT(zoneid != ALL_ZONES);
1535 	if (mp->b_datap->db_type == M_CTL) {
1536 		io = (ipsec_out_t *)mp->b_rptr;
1537 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1538 		io->ipsec_out_zoneid = zoneid;
1539 		return (mp);
1540 	}
1541 
1542 	first_mp = ipsec_alloc_ipsec_out();
1543 	if (first_mp == NULL)
1544 		return (NULL);
1545 	io = (ipsec_out_t *)first_mp->b_rptr;
1546 	/* This is not a secure packet */
1547 	io->ipsec_out_secure = B_FALSE;
1548 	io->ipsec_out_zoneid = zoneid;
1549 	first_mp->b_cont = mp;
1550 	return (first_mp);
1551 }
1552 
1553 /*
1554  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1555  */
1556 mblk_t *
1557 ip_copymsg(mblk_t *mp)
1558 {
1559 	mblk_t *nmp;
1560 	ipsec_info_t *in;
1561 
1562 	if (mp->b_datap->db_type != M_CTL)
1563 		return (copymsg(mp));
1564 
1565 	in = (ipsec_info_t *)mp->b_rptr;
1566 
1567 	/*
1568 	 * Note that M_CTL is also used for delivering ICMP error messages
1569 	 * upstream to transport layers.
1570 	 */
1571 	if (in->ipsec_info_type != IPSEC_OUT &&
1572 	    in->ipsec_info_type != IPSEC_IN)
1573 		return (copymsg(mp));
1574 
1575 	nmp = copymsg(mp->b_cont);
1576 
1577 	if (in->ipsec_info_type == IPSEC_OUT)
1578 		return (ipsec_out_tag(mp, nmp));
1579 	else
1580 		return (ipsec_in_tag(mp, nmp));
1581 }
1582 
1583 /* Generate an ICMP fragmentation needed message. */
1584 static void
1585 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid)
1586 {
1587 	icmph_t	icmph;
1588 	mblk_t *first_mp;
1589 	boolean_t mctl_present;
1590 
1591 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1592 
1593 	if (!(mp = icmp_pkt_err_ok(mp))) {
1594 		if (mctl_present)
1595 			freeb(first_mp);
1596 		return;
1597 	}
1598 
1599 	bzero(&icmph, sizeof (icmph_t));
1600 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1601 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1602 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1603 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1604 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1605 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
1606 }
1607 
1608 /*
1609  * icmp_inbound deals with ICMP messages in the following ways.
1610  *
1611  * 1) It needs to send a reply back and possibly delivering it
1612  *    to the "interested" upper clients.
1613  * 2) It needs to send it to the upper clients only.
1614  * 3) It needs to change some values in IP only.
1615  * 4) It needs to change some values in IP and upper layers e.g TCP.
1616  *
1617  * We need to accomodate icmp messages coming in clear until we get
1618  * everything secure from the wire. If icmp_accept_clear_messages
1619  * is zero we check with the global policy and act accordingly. If
1620  * it is non-zero, we accept the message without any checks. But
1621  * *this does not mean* that this will be delivered to the upper
1622  * clients. By accepting we might send replies back, change our MTU
1623  * value etc. but delivery to the ULP/clients depends on their policy
1624  * dispositions.
1625  *
1626  * We handle the above 4 cases in the context of IPSEC in the
1627  * following way :
1628  *
1629  * 1) Send the reply back in the same way as the request came in.
1630  *    If it came in encrypted, it goes out encrypted. If it came in
1631  *    clear, it goes out in clear. Thus, this will prevent chosen
1632  *    plain text attack.
1633  * 2) The client may or may not expect things to come in secure.
1634  *    If it comes in secure, the policy constraints are checked
1635  *    before delivering it to the upper layers. If it comes in
1636  *    clear, ipsec_inbound_accept_clear will decide whether to
1637  *    accept this in clear or not. In both the cases, if the returned
1638  *    message (IP header + 8 bytes) that caused the icmp message has
1639  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1640  *    sending up. If there are only 8 bytes of returned message, then
1641  *    upper client will not be notified.
1642  * 3) Check with global policy to see whether it matches the constaints.
1643  *    But this will be done only if icmp_accept_messages_in_clear is
1644  *    zero.
1645  * 4) If we need to change both in IP and ULP, then the decision taken
1646  *    while affecting the values in IP and while delivering up to TCP
1647  *    should be the same.
1648  *
1649  * 	There are two cases.
1650  *
1651  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1652  *	   failed), we will not deliver it to the ULP, even though they
1653  *	   are *willing* to accept in *clear*. This is fine as our global
1654  *	   disposition to icmp messages asks us reject the datagram.
1655  *
1656  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1657  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1658  *	   to deliver it to ULP (policy failed), it can lead to
1659  *	   consistency problems. The cases known at this time are
1660  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1661  *	   values :
1662  *
1663  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1664  *	     and Upper layer rejects. Then the communication will
1665  *	     come to a stop. This is solved by making similar decisions
1666  *	     at both levels. Currently, when we are unable to deliver
1667  *	     to the Upper Layer (due to policy failures) while IP has
1668  *	     adjusted ire_max_frag, the next outbound datagram would
1669  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1670  *	     will be with the right level of protection. Thus the right
1671  *	     value will be communicated even if we are not able to
1672  *	     communicate when we get from the wire initially. But this
1673  *	     assumes there would be at least one outbound datagram after
1674  *	     IP has adjusted its ire_max_frag value. To make things
1675  *	     simpler, we accept in clear after the validation of
1676  *	     AH/ESP headers.
1677  *
1678  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1679  *	     upper layer depending on the level of protection the upper
1680  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1681  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1682  *	     should be accepted in clear when the Upper layer expects secure.
1683  *	     Thus the communication may get aborted by some bad ICMP
1684  *	     packets.
1685  *
1686  * IPQoS Notes:
1687  * The only instance when a packet is sent for processing is when there
1688  * isn't an ICMP client and if we are interested in it.
1689  * If there is a client, IPPF processing will take place in the
1690  * ip_fanout_proto routine.
1691  *
1692  * Zones notes:
1693  * The packet is only processed in the context of the specified zone: typically
1694  * only this zone will reply to an echo request, and only interested clients in
1695  * this zone will receive a copy of the packet. This means that the caller must
1696  * call icmp_inbound() for each relevant zone.
1697  */
1698 static void
1699 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1700     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1701     ill_t *recv_ill, zoneid_t zoneid)
1702 {
1703 	icmph_t	*icmph;
1704 	ipha_t	*ipha;
1705 	int	iph_hdr_length;
1706 	int	hdr_length;
1707 	boolean_t	interested;
1708 	uint32_t	ts;
1709 	uchar_t	*wptr;
1710 	ipif_t	*ipif;
1711 	mblk_t *first_mp;
1712 	ipsec_in_t *ii;
1713 	ire_t *src_ire;
1714 	boolean_t onlink;
1715 	timestruc_t now;
1716 	uint32_t ill_index;
1717 
1718 	ASSERT(ill != NULL);
1719 
1720 	first_mp = mp;
1721 	if (mctl_present) {
1722 		mp = first_mp->b_cont;
1723 		ASSERT(mp != NULL);
1724 	}
1725 
1726 	ipha = (ipha_t *)mp->b_rptr;
1727 	if (icmp_accept_clear_messages == 0) {
1728 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1729 		    ipha, NULL, mctl_present);
1730 		if (first_mp == NULL)
1731 			return;
1732 	}
1733 
1734 	/*
1735 	 * On a labeled system, we have to check whether the zone itself is
1736 	 * permitted to receive raw traffic.
1737 	 */
1738 	if (is_system_labeled()) {
1739 		if (zoneid == ALL_ZONES)
1740 			zoneid = tsol_packet_to_zoneid(mp);
1741 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1742 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1743 			    zoneid));
1744 			BUMP_MIB(&icmp_mib, icmpInErrors);
1745 			freemsg(first_mp);
1746 			return;
1747 		}
1748 	}
1749 
1750 	/*
1751 	 * We have accepted the ICMP message. It means that we will
1752 	 * respond to the packet if needed. It may not be delivered
1753 	 * to the upper client depending on the policy constraints
1754 	 * and the disposition in ipsec_inbound_accept_clear.
1755 	 */
1756 
1757 	ASSERT(ill != NULL);
1758 
1759 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1760 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1761 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1762 		/* Last chance to get real. */
1763 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1764 			BUMP_MIB(&icmp_mib, icmpInErrors);
1765 			freemsg(first_mp);
1766 			return;
1767 		}
1768 		/* Refresh iph following the pullup. */
1769 		ipha = (ipha_t *)mp->b_rptr;
1770 	}
1771 	/* ICMP header checksum, including checksum field, should be zero. */
1772 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1773 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1774 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1775 		freemsg(first_mp);
1776 		return;
1777 	}
1778 	/* The IP header will always be a multiple of four bytes */
1779 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1780 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1781 	    icmph->icmph_code));
1782 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1783 	/* We will set "interested" to "true" if we want a copy */
1784 	interested = B_FALSE;
1785 	switch (icmph->icmph_type) {
1786 	case ICMP_ECHO_REPLY:
1787 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1788 		break;
1789 	case ICMP_DEST_UNREACHABLE:
1790 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1791 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1792 		interested = B_TRUE;	/* Pass up to transport */
1793 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1794 		break;
1795 	case ICMP_SOURCE_QUENCH:
1796 		interested = B_TRUE;	/* Pass up to transport */
1797 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1798 		break;
1799 	case ICMP_REDIRECT:
1800 		if (!ip_ignore_redirect)
1801 			interested = B_TRUE;
1802 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1803 		break;
1804 	case ICMP_ECHO_REQUEST:
1805 		/*
1806 		 * Whether to respond to echo requests that come in as IP
1807 		 * broadcasts or as IP multicast is subject to debate
1808 		 * (what isn't?).  We aim to please, you pick it.
1809 		 * Default is do it.
1810 		 */
1811 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1812 			/* unicast: always respond */
1813 			interested = B_TRUE;
1814 		} else if (CLASSD(ipha->ipha_dst)) {
1815 			/* multicast: respond based on tunable */
1816 			interested = ip_g_resp_to_echo_mcast;
1817 		} else if (broadcast) {
1818 			/* broadcast: respond based on tunable */
1819 			interested = ip_g_resp_to_echo_bcast;
1820 		}
1821 		BUMP_MIB(&icmp_mib, icmpInEchos);
1822 		break;
1823 	case ICMP_ROUTER_ADVERTISEMENT:
1824 	case ICMP_ROUTER_SOLICITATION:
1825 		break;
1826 	case ICMP_TIME_EXCEEDED:
1827 		interested = B_TRUE;	/* Pass up to transport */
1828 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1829 		break;
1830 	case ICMP_PARAM_PROBLEM:
1831 		interested = B_TRUE;	/* Pass up to transport */
1832 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1833 		break;
1834 	case ICMP_TIME_STAMP_REQUEST:
1835 		/* Response to Time Stamp Requests is local policy. */
1836 		if (ip_g_resp_to_timestamp &&
1837 		    /* So is whether to respond if it was an IP broadcast. */
1838 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1839 			int tstamp_len = 3 * sizeof (uint32_t);
1840 
1841 			if (wptr +  tstamp_len > mp->b_wptr) {
1842 				if (!pullupmsg(mp, wptr + tstamp_len -
1843 				    mp->b_rptr)) {
1844 					BUMP_MIB(&ip_mib, ipInDiscards);
1845 					freemsg(first_mp);
1846 					return;
1847 				}
1848 				/* Refresh ipha following the pullup. */
1849 				ipha = (ipha_t *)mp->b_rptr;
1850 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1851 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1852 			}
1853 			interested = B_TRUE;
1854 		}
1855 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1856 		break;
1857 	case ICMP_TIME_STAMP_REPLY:
1858 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1859 		break;
1860 	case ICMP_INFO_REQUEST:
1861 		/* Per RFC 1122 3.2.2.7, ignore this. */
1862 	case ICMP_INFO_REPLY:
1863 		break;
1864 	case ICMP_ADDRESS_MASK_REQUEST:
1865 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1866 		    /* TODO m_pullup of complete header? */
1867 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1868 			interested = B_TRUE;
1869 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1870 		break;
1871 	case ICMP_ADDRESS_MASK_REPLY:
1872 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1873 		break;
1874 	default:
1875 		interested = B_TRUE;	/* Pass up to transport */
1876 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1877 		break;
1878 	}
1879 	/* See if there is an ICMP client. */
1880 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1881 		/* If there is an ICMP client and we want one too, copy it. */
1882 		mblk_t *first_mp1;
1883 
1884 		if (!interested) {
1885 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1886 			    ip_policy, recv_ill, zoneid);
1887 			return;
1888 		}
1889 		first_mp1 = ip_copymsg(first_mp);
1890 		if (first_mp1 != NULL) {
1891 			ip_fanout_proto(q, first_mp1, ill, ipha,
1892 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1893 		}
1894 	} else if (!interested) {
1895 		freemsg(first_mp);
1896 		return;
1897 	} else {
1898 		/*
1899 		 * Initiate policy processing for this packet if ip_policy
1900 		 * is true.
1901 		 */
1902 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1903 			ill_index = ill->ill_phyint->phyint_ifindex;
1904 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1905 			if (mp == NULL) {
1906 				if (mctl_present) {
1907 					freeb(first_mp);
1908 				}
1909 				BUMP_MIB(&icmp_mib, icmpInErrors);
1910 				return;
1911 			}
1912 		}
1913 	}
1914 	/* We want to do something with it. */
1915 	/* Check db_ref to make sure we can modify the packet. */
1916 	if (mp->b_datap->db_ref > 1) {
1917 		mblk_t	*first_mp1;
1918 
1919 		first_mp1 = ip_copymsg(first_mp);
1920 		freemsg(first_mp);
1921 		if (!first_mp1) {
1922 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1923 			return;
1924 		}
1925 		first_mp = first_mp1;
1926 		if (mctl_present) {
1927 			mp = first_mp->b_cont;
1928 			ASSERT(mp != NULL);
1929 		} else {
1930 			mp = first_mp;
1931 		}
1932 		ipha = (ipha_t *)mp->b_rptr;
1933 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1934 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1935 	}
1936 	switch (icmph->icmph_type) {
1937 	case ICMP_ADDRESS_MASK_REQUEST:
1938 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1939 		if (ipif == NULL) {
1940 			freemsg(first_mp);
1941 			return;
1942 		}
1943 		/*
1944 		 * outging interface must be IPv4
1945 		 */
1946 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1947 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1948 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1949 		ipif_refrele(ipif);
1950 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1951 		break;
1952 	case ICMP_ECHO_REQUEST:
1953 		icmph->icmph_type = ICMP_ECHO_REPLY;
1954 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1955 		break;
1956 	case ICMP_TIME_STAMP_REQUEST: {
1957 		uint32_t *tsp;
1958 
1959 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1960 		tsp = (uint32_t *)wptr;
1961 		tsp++;		/* Skip past 'originate time' */
1962 		/* Compute # of milliseconds since midnight */
1963 		gethrestime(&now);
1964 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1965 		    now.tv_nsec / (NANOSEC / MILLISEC);
1966 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1967 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1968 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1969 		break;
1970 	}
1971 	default:
1972 		ipha = (ipha_t *)&icmph[1];
1973 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1974 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1975 				BUMP_MIB(&ip_mib, ipInDiscards);
1976 				freemsg(first_mp);
1977 				return;
1978 			}
1979 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1980 			ipha = (ipha_t *)&icmph[1];
1981 		}
1982 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1983 			BUMP_MIB(&ip_mib, ipInDiscards);
1984 			freemsg(first_mp);
1985 			return;
1986 		}
1987 		hdr_length = IPH_HDR_LENGTH(ipha);
1988 		if (hdr_length < sizeof (ipha_t)) {
1989 			BUMP_MIB(&ip_mib, ipInDiscards);
1990 			freemsg(first_mp);
1991 			return;
1992 		}
1993 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1994 			if (!pullupmsg(mp,
1995 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1996 				BUMP_MIB(&ip_mib, ipInDiscards);
1997 				freemsg(first_mp);
1998 				return;
1999 			}
2000 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2001 			ipha = (ipha_t *)&icmph[1];
2002 		}
2003 		switch (icmph->icmph_type) {
2004 		case ICMP_REDIRECT:
2005 			/*
2006 			 * As there is no upper client to deliver, we don't
2007 			 * need the first_mp any more.
2008 			 */
2009 			if (mctl_present) {
2010 				freeb(first_mp);
2011 			}
2012 			icmp_redirect(mp);
2013 			return;
2014 		case ICMP_DEST_UNREACHABLE:
2015 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
2016 				if (!icmp_inbound_too_big(icmph, ipha, ill,
2017 				    zoneid, mp, iph_hdr_length)) {
2018 					freemsg(first_mp);
2019 					return;
2020 				}
2021 				/*
2022 				 * icmp_inbound_too_big() may alter mp.
2023 				 * Resynch ipha and icmph accordingly.
2024 				 */
2025 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2026 				ipha = (ipha_t *)&icmph[1];
2027 			}
2028 			/* FALLTHRU */
2029 		default :
2030 			/*
2031 			 * IPQoS notes: Since we have already done IPQoS
2032 			 * processing we don't want to do it again in
2033 			 * the fanout routines called by
2034 			 * icmp_inbound_error_fanout, hence the last
2035 			 * argument, ip_policy, is B_FALSE.
2036 			 */
2037 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2038 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2039 			    B_FALSE, recv_ill, zoneid);
2040 		}
2041 		return;
2042 	}
2043 	/* Send out an ICMP packet */
2044 	icmph->icmph_checksum = 0;
2045 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2046 	if (icmph->icmph_checksum == 0)
2047 		icmph->icmph_checksum = 0xFFFF;
2048 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2049 		ipif_t	*ipif_chosen;
2050 		/*
2051 		 * Make it look like it was directed to us, so we don't look
2052 		 * like a fool with a broadcast or multicast source address.
2053 		 */
2054 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2055 		/*
2056 		 * Make sure that we haven't grabbed an interface that's DOWN.
2057 		 */
2058 		if (ipif != NULL) {
2059 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2060 			    ipha->ipha_src, zoneid);
2061 			if (ipif_chosen != NULL) {
2062 				ipif_refrele(ipif);
2063 				ipif = ipif_chosen;
2064 			}
2065 		}
2066 		if (ipif == NULL) {
2067 			ip0dbg(("icmp_inbound: "
2068 			    "No source for broadcast/multicast:\n"
2069 			    "\tsrc 0x%x dst 0x%x ill %p "
2070 			    "ipif_lcl_addr 0x%x\n",
2071 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2072 			    (void *)ill,
2073 			    ill->ill_ipif->ipif_lcl_addr));
2074 			freemsg(first_mp);
2075 			return;
2076 		}
2077 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2078 		ipha->ipha_dst = ipif->ipif_src_addr;
2079 		ipif_refrele(ipif);
2080 	}
2081 	/* Reset time to live. */
2082 	ipha->ipha_ttl = ip_def_ttl;
2083 	{
2084 		/* Swap source and destination addresses */
2085 		ipaddr_t tmp;
2086 
2087 		tmp = ipha->ipha_src;
2088 		ipha->ipha_src = ipha->ipha_dst;
2089 		ipha->ipha_dst = tmp;
2090 	}
2091 	ipha->ipha_ident = 0;
2092 	if (!IS_SIMPLE_IPH(ipha))
2093 		icmp_options_update(ipha);
2094 
2095 	/*
2096 	 * ICMP echo replies should go out on the same interface
2097 	 * the request came on as probes used by in.mpathd for detecting
2098 	 * NIC failures are ECHO packets. We turn-off load spreading
2099 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2100 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2101 	 * function. This is in turn handled by ip_wput and ip_newroute
2102 	 * to make sure that the packet goes out on the interface it came
2103 	 * in on. If we don't turnoff load spreading, the packets might get
2104 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2105 	 * to go out and in.mpathd would wrongly detect a failure or
2106 	 * mis-detect a NIC failure for link failure. As load spreading
2107 	 * can happen only if ill_group is not NULL, we do only for
2108 	 * that case and this does not affect the normal case.
2109 	 *
2110 	 * We turn off load spreading only on echo packets that came from
2111 	 * on-link hosts. If the interface route has been deleted, this will
2112 	 * not be enforced as we can't do much. For off-link hosts, as the
2113 	 * default routes in IPv4 does not typically have an ire_ipif
2114 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2115 	 * Moreover, expecting a default route through this interface may
2116 	 * not be correct. We use ipha_dst because of the swap above.
2117 	 */
2118 	onlink = B_FALSE;
2119 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2120 		/*
2121 		 * First, we need to make sure that it is not one of our
2122 		 * local addresses. If we set onlink when it is one of
2123 		 * our local addresses, we will end up creating IRE_CACHES
2124 		 * for one of our local addresses. Then, we will never
2125 		 * accept packets for them afterwards.
2126 		 */
2127 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2128 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2129 		if (src_ire == NULL) {
2130 			ipif = ipif_get_next_ipif(NULL, ill);
2131 			if (ipif == NULL) {
2132 				BUMP_MIB(&ip_mib, ipInDiscards);
2133 				freemsg(mp);
2134 				return;
2135 			}
2136 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2137 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2138 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2139 			ipif_refrele(ipif);
2140 			if (src_ire != NULL) {
2141 				onlink = B_TRUE;
2142 				ire_refrele(src_ire);
2143 			}
2144 		} else {
2145 			ire_refrele(src_ire);
2146 		}
2147 	}
2148 	if (!mctl_present) {
2149 		/*
2150 		 * This packet should go out the same way as it
2151 		 * came in i.e in clear. To make sure that global
2152 		 * policy will not be applied to this in ip_wput_ire,
2153 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2154 		 */
2155 		ASSERT(first_mp == mp);
2156 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2157 			BUMP_MIB(&ip_mib, ipInDiscards);
2158 			freemsg(mp);
2159 			return;
2160 		}
2161 		ii = (ipsec_in_t *)first_mp->b_rptr;
2162 
2163 		/* This is not a secure packet */
2164 		ii->ipsec_in_secure = B_FALSE;
2165 		if (onlink) {
2166 			ii->ipsec_in_attach_if = B_TRUE;
2167 			ii->ipsec_in_ill_index =
2168 			    ill->ill_phyint->phyint_ifindex;
2169 			ii->ipsec_in_rill_index =
2170 			    recv_ill->ill_phyint->phyint_ifindex;
2171 		}
2172 		first_mp->b_cont = mp;
2173 	} else if (onlink) {
2174 		ii = (ipsec_in_t *)first_mp->b_rptr;
2175 		ii->ipsec_in_attach_if = B_TRUE;
2176 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2177 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2178 	} else {
2179 		ii = (ipsec_in_t *)first_mp->b_rptr;
2180 	}
2181 	ii->ipsec_in_zoneid = zoneid;
2182 	ASSERT(zoneid != ALL_ZONES);
2183 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2184 		BUMP_MIB(&ip_mib, ipInDiscards);
2185 		return;
2186 	}
2187 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2188 	put(WR(q), first_mp);
2189 }
2190 
2191 static ipaddr_t
2192 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2193 {
2194 	conn_t *connp;
2195 	connf_t *connfp;
2196 	ipaddr_t nexthop_addr = INADDR_ANY;
2197 	int hdr_length = IPH_HDR_LENGTH(ipha);
2198 	uint16_t *up;
2199 	uint32_t ports;
2200 
2201 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2202 	switch (ipha->ipha_protocol) {
2203 		case IPPROTO_TCP:
2204 		{
2205 			tcph_t *tcph;
2206 
2207 			/* do a reverse lookup */
2208 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2209 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2210 			    TCPS_LISTEN);
2211 			break;
2212 		}
2213 		case IPPROTO_UDP:
2214 		{
2215 			uint32_t dstport, srcport;
2216 
2217 			((uint16_t *)&ports)[0] = up[1];
2218 			((uint16_t *)&ports)[1] = up[0];
2219 
2220 			/* Extract ports in net byte order */
2221 			dstport = htons(ntohl(ports) & 0xFFFF);
2222 			srcport = htons(ntohl(ports) >> 16);
2223 
2224 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2225 			mutex_enter(&connfp->connf_lock);
2226 			connp = connfp->connf_head;
2227 
2228 			/* do a reverse lookup */
2229 			while ((connp != NULL) &&
2230 			    (!IPCL_UDP_MATCH(connp, dstport,
2231 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2232 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2233 				connp = connp->conn_next;
2234 			}
2235 			if (connp != NULL)
2236 				CONN_INC_REF(connp);
2237 			mutex_exit(&connfp->connf_lock);
2238 			break;
2239 		}
2240 		case IPPROTO_SCTP:
2241 		{
2242 			in6_addr_t map_src, map_dst;
2243 
2244 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2245 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2246 			((uint16_t *)&ports)[0] = up[1];
2247 			((uint16_t *)&ports)[1] = up[0];
2248 
2249 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2250 			    0, zoneid)) == NULL) {
2251 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2252 				    zoneid, ports, ipha);
2253 			} else {
2254 				CONN_INC_REF(connp);
2255 				SCTP_REFRELE(CONN2SCTP(connp));
2256 			}
2257 			break;
2258 		}
2259 		default:
2260 		{
2261 			ipha_t ripha;
2262 
2263 			ripha.ipha_src = ipha->ipha_dst;
2264 			ripha.ipha_dst = ipha->ipha_src;
2265 			ripha.ipha_protocol = ipha->ipha_protocol;
2266 
2267 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2268 			mutex_enter(&connfp->connf_lock);
2269 			connp = connfp->connf_head;
2270 			for (connp = connfp->connf_head; connp != NULL;
2271 			    connp = connp->conn_next) {
2272 				if (IPCL_PROTO_MATCH(connp,
2273 				    ipha->ipha_protocol, &ripha, ill,
2274 				    0, zoneid)) {
2275 					CONN_INC_REF(connp);
2276 					break;
2277 				}
2278 			}
2279 			mutex_exit(&connfp->connf_lock);
2280 		}
2281 	}
2282 	if (connp != NULL) {
2283 		if (connp->conn_nexthop_set)
2284 			nexthop_addr = connp->conn_nexthop_v4;
2285 		CONN_DEC_REF(connp);
2286 	}
2287 	return (nexthop_addr);
2288 }
2289 
2290 /* Table from RFC 1191 */
2291 static int icmp_frag_size_table[] =
2292 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2293 
2294 /*
2295  * Process received ICMP Packet too big.
2296  * After updating any IRE it does the fanout to any matching transport streams.
2297  * Assumes the message has been pulled up till the IP header that caused
2298  * the error.
2299  *
2300  * Returns B_FALSE on failure and B_TRUE on success.
2301  */
2302 static boolean_t
2303 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2304     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2305 {
2306 	ire_t	*ire, *first_ire;
2307 	int	mtu;
2308 	int	hdr_length;
2309 	ipaddr_t nexthop_addr;
2310 
2311 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2312 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2313 
2314 	hdr_length = IPH_HDR_LENGTH(ipha);
2315 
2316 	/* Drop if the original packet contained a source route */
2317 	if (ip_source_route_included(ipha)) {
2318 		return (B_FALSE);
2319 	}
2320 	/*
2321 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2322 	 * header.
2323 	 */
2324 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2325 	    mp->b_wptr) {
2326 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2327 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2328 			BUMP_MIB(&ip_mib, ipInDiscards);
2329 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2330 			return (B_FALSE);
2331 		}
2332 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2333 		ipha = (ipha_t *)&icmph[1];
2334 	}
2335 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2336 	if (nexthop_addr != INADDR_ANY) {
2337 		/* nexthop set */
2338 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2339 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2340 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2341 	} else {
2342 		/* nexthop not set */
2343 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2344 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2345 	}
2346 
2347 	if (!first_ire) {
2348 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2349 		    ntohl(ipha->ipha_dst)));
2350 		return (B_FALSE);
2351 	}
2352 	/* Check for MTU discovery advice as described in RFC 1191 */
2353 	mtu = ntohs(icmph->icmph_du_mtu);
2354 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2355 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2356 	    ire = ire->ire_next) {
2357 		/*
2358 		 * Look for the connection to which this ICMP message is
2359 		 * directed. If it has the IP_NEXTHOP option set, then the
2360 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2361 		 * option. Else the search is limited to regular IREs.
2362 		 */
2363 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2364 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2365 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2366 		    (nexthop_addr != INADDR_ANY)))
2367 			continue;
2368 
2369 		mutex_enter(&ire->ire_lock);
2370 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2371 			/* Reduce the IRE max frag value as advised. */
2372 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2373 			    mtu, ire->ire_max_frag));
2374 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2375 		} else {
2376 			uint32_t length;
2377 			int	i;
2378 
2379 			/*
2380 			 * Use the table from RFC 1191 to figure out
2381 			 * the next "plateau" based on the length in
2382 			 * the original IP packet.
2383 			 */
2384 			length = ntohs(ipha->ipha_length);
2385 			if (ire->ire_max_frag <= length &&
2386 			    ire->ire_max_frag >= length - hdr_length) {
2387 				/*
2388 				 * Handle broken BSD 4.2 systems that
2389 				 * return the wrong iph_length in ICMP
2390 				 * errors.
2391 				 */
2392 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2393 				    length, ire->ire_max_frag));
2394 				length -= hdr_length;
2395 			}
2396 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2397 				if (length > icmp_frag_size_table[i])
2398 					break;
2399 			}
2400 			if (i == A_CNT(icmp_frag_size_table)) {
2401 				/* Smaller than 68! */
2402 				ip1dbg(("Too big for packet size %d\n",
2403 				    length));
2404 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2405 				ire->ire_frag_flag = 0;
2406 			} else {
2407 				mtu = icmp_frag_size_table[i];
2408 				ip1dbg(("Calculated mtu %d, packet size %d, "
2409 				    "before %d", mtu, length,
2410 				    ire->ire_max_frag));
2411 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2412 				ip1dbg((", after %d\n", ire->ire_max_frag));
2413 			}
2414 			/* Record the new max frag size for the ULP. */
2415 			icmph->icmph_du_zero = 0;
2416 			icmph->icmph_du_mtu =
2417 			    htons((uint16_t)ire->ire_max_frag);
2418 		}
2419 		mutex_exit(&ire->ire_lock);
2420 	}
2421 	rw_exit(&first_ire->ire_bucket->irb_lock);
2422 	ire_refrele(first_ire);
2423 	return (B_TRUE);
2424 }
2425 
2426 /*
2427  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2428  * calls this function.
2429  */
2430 static mblk_t *
2431 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2432 {
2433 	ipha_t *ipha;
2434 	icmph_t *icmph;
2435 	ipha_t *in_ipha;
2436 	int length;
2437 
2438 	ASSERT(mp->b_datap->db_type == M_DATA);
2439 
2440 	/*
2441 	 * For Self-encapsulated packets, we added an extra IP header
2442 	 * without the options. Inner IP header is the one from which
2443 	 * the outer IP header was formed. Thus, we need to remove the
2444 	 * outer IP header. To do this, we pullup the whole message
2445 	 * and overlay whatever follows the outer IP header over the
2446 	 * outer IP header.
2447 	 */
2448 
2449 	if (!pullupmsg(mp, -1)) {
2450 		BUMP_MIB(&ip_mib, ipInDiscards);
2451 		return (NULL);
2452 	}
2453 
2454 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2455 	ipha = (ipha_t *)&icmph[1];
2456 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2457 
2458 	/*
2459 	 * The length that we want to overlay is following the inner
2460 	 * IP header. Subtracting the IP header + icmp header + outer
2461 	 * IP header's length should give us the length that we want to
2462 	 * overlay.
2463 	 */
2464 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2465 	    hdr_length;
2466 	/*
2467 	 * Overlay whatever follows the inner header over the
2468 	 * outer header.
2469 	 */
2470 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2471 
2472 	/* Set the wptr to account for the outer header */
2473 	mp->b_wptr -= hdr_length;
2474 	return (mp);
2475 }
2476 
2477 /*
2478  * Try to pass the ICMP message upstream in case the ULP cares.
2479  *
2480  * If the packet that caused the ICMP error is secure, we send
2481  * it to AH/ESP to make sure that the attached packet has a
2482  * valid association. ipha in the code below points to the
2483  * IP header of the packet that caused the error.
2484  *
2485  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2486  * in the context of IPSEC. Normally we tell the upper layer
2487  * whenever we send the ire (including ip_bind), the IPSEC header
2488  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2489  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2490  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2491  * same thing. As TCP has the IPSEC options size that needs to be
2492  * adjusted, we just pass the MTU unchanged.
2493  *
2494  * IFN could have been generated locally or by some router.
2495  *
2496  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2497  *	    This happens because IP adjusted its value of MTU on an
2498  *	    earlier IFN message and could not tell the upper layer,
2499  *	    the new adjusted value of MTU e.g. Packet was encrypted
2500  *	    or there was not enough information to fanout to upper
2501  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2502  *	    generates the IFN, where IPSEC processing has *not* been
2503  *	    done.
2504  *
2505  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2506  *	    could have generated this. This happens because ire_max_frag
2507  *	    value in IP was set to a new value, while the IPSEC processing
2508  *	    was being done and after we made the fragmentation check in
2509  *	    ip_wput_ire. Thus on return from IPSEC processing,
2510  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2511  *	    and generates the IFN. As IPSEC processing is over, we fanout
2512  *	    to AH/ESP to remove the header.
2513  *
2514  *	    In both these cases, ipsec_in_loopback will be set indicating
2515  *	    that IFN was generated locally.
2516  *
2517  * ROUTER : IFN could be secure or non-secure.
2518  *
2519  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2520  *	      packet in error has AH/ESP headers to validate the AH/ESP
2521  *	      headers. AH/ESP will verify whether there is a valid SA or
2522  *	      not and send it back. We will fanout again if we have more
2523  *	      data in the packet.
2524  *
2525  *	      If the packet in error does not have AH/ESP, we handle it
2526  *	      like any other case.
2527  *
2528  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2529  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2530  *	      for validation. AH/ESP will verify whether there is a
2531  *	      valid SA or not and send it back. We will fanout again if
2532  *	      we have more data in the packet.
2533  *
2534  *	      If the packet in error does not have AH/ESP, we handle it
2535  *	      like any other case.
2536  */
2537 static void
2538 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2539     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2540     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2541     zoneid_t zoneid)
2542 {
2543 	uint16_t *up;	/* Pointer to ports in ULP header */
2544 	uint32_t ports;	/* reversed ports for fanout */
2545 	ipha_t ripha;	/* With reversed addresses */
2546 	mblk_t *first_mp;
2547 	ipsec_in_t *ii;
2548 	tcph_t	*tcph;
2549 	conn_t	*connp;
2550 
2551 	first_mp = mp;
2552 	if (mctl_present) {
2553 		mp = first_mp->b_cont;
2554 		ASSERT(mp != NULL);
2555 
2556 		ii = (ipsec_in_t *)first_mp->b_rptr;
2557 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2558 	} else {
2559 		ii = NULL;
2560 	}
2561 
2562 	switch (ipha->ipha_protocol) {
2563 	case IPPROTO_UDP:
2564 		/*
2565 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2566 		 * transport header.
2567 		 */
2568 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2569 		    mp->b_wptr) {
2570 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2571 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2572 				BUMP_MIB(&ip_mib, ipInDiscards);
2573 				goto drop_pkt;
2574 			}
2575 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2576 			ipha = (ipha_t *)&icmph[1];
2577 		}
2578 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2579 
2580 		/*
2581 		 * Attempt to find a client stream based on port.
2582 		 * Note that we do a reverse lookup since the header is
2583 		 * in the form we sent it out.
2584 		 * The ripha header is only used for the IP_UDP_MATCH and we
2585 		 * only set the src and dst addresses and protocol.
2586 		 */
2587 		ripha.ipha_src = ipha->ipha_dst;
2588 		ripha.ipha_dst = ipha->ipha_src;
2589 		ripha.ipha_protocol = ipha->ipha_protocol;
2590 		((uint16_t *)&ports)[0] = up[1];
2591 		((uint16_t *)&ports)[1] = up[0];
2592 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2593 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2594 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2595 		    icmph->icmph_type, icmph->icmph_code));
2596 
2597 		/* Have to change db_type after any pullupmsg */
2598 		DB_TYPE(mp) = M_CTL;
2599 
2600 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2601 		    mctl_present, ip_policy, recv_ill, zoneid);
2602 		return;
2603 
2604 	case IPPROTO_TCP:
2605 		/*
2606 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2607 		 * transport header.
2608 		 */
2609 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2610 		    mp->b_wptr) {
2611 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2612 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2613 				BUMP_MIB(&ip_mib, ipInDiscards);
2614 				goto drop_pkt;
2615 			}
2616 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2617 			ipha = (ipha_t *)&icmph[1];
2618 		}
2619 		/*
2620 		 * Find a TCP client stream for this packet.
2621 		 * Note that we do a reverse lookup since the header is
2622 		 * in the form we sent it out.
2623 		 */
2624 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2625 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2626 		if (connp == NULL) {
2627 			BUMP_MIB(&ip_mib, ipInDiscards);
2628 			goto drop_pkt;
2629 		}
2630 
2631 		/* Have to change db_type after any pullupmsg */
2632 		DB_TYPE(mp) = M_CTL;
2633 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2634 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2635 		return;
2636 
2637 	case IPPROTO_SCTP:
2638 		/*
2639 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2640 		 * transport header.
2641 		 */
2642 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2643 		    mp->b_wptr) {
2644 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2645 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2646 				BUMP_MIB(&ip_mib, ipInDiscards);
2647 				goto drop_pkt;
2648 			}
2649 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2650 			ipha = (ipha_t *)&icmph[1];
2651 		}
2652 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2653 		/*
2654 		 * Find a SCTP client stream for this packet.
2655 		 * Note that we do a reverse lookup since the header is
2656 		 * in the form we sent it out.
2657 		 * The ripha header is only used for the matching and we
2658 		 * only set the src and dst addresses, protocol, and version.
2659 		 */
2660 		ripha.ipha_src = ipha->ipha_dst;
2661 		ripha.ipha_dst = ipha->ipha_src;
2662 		ripha.ipha_protocol = ipha->ipha_protocol;
2663 		ripha.ipha_version_and_hdr_length =
2664 		    ipha->ipha_version_and_hdr_length;
2665 		((uint16_t *)&ports)[0] = up[1];
2666 		((uint16_t *)&ports)[1] = up[0];
2667 
2668 		/* Have to change db_type after any pullupmsg */
2669 		DB_TYPE(mp) = M_CTL;
2670 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2671 		    mctl_present, ip_policy, 0, zoneid);
2672 		return;
2673 
2674 	case IPPROTO_ESP:
2675 	case IPPROTO_AH: {
2676 		int ipsec_rc;
2677 
2678 		/*
2679 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2680 		 * We will re-use the IPSEC_IN if it is already present as
2681 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2682 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2683 		 * one and attach it in the front.
2684 		 */
2685 		if (ii != NULL) {
2686 			/*
2687 			 * ip_fanout_proto_again converts the ICMP errors
2688 			 * that come back from AH/ESP to M_DATA so that
2689 			 * if it is non-AH/ESP and we do a pullupmsg in
2690 			 * this function, it would work. Convert it back
2691 			 * to M_CTL before we send up as this is a ICMP
2692 			 * error. This could have been generated locally or
2693 			 * by some router. Validate the inner IPSEC
2694 			 * headers.
2695 			 *
2696 			 * NOTE : ill_index is used by ip_fanout_proto_again
2697 			 * to locate the ill.
2698 			 */
2699 			ASSERT(ill != NULL);
2700 			ii->ipsec_in_ill_index =
2701 			    ill->ill_phyint->phyint_ifindex;
2702 			ii->ipsec_in_rill_index =
2703 			    recv_ill->ill_phyint->phyint_ifindex;
2704 			DB_TYPE(first_mp->b_cont) = M_CTL;
2705 		} else {
2706 			/*
2707 			 * IPSEC_IN is not present. We attach a ipsec_in
2708 			 * message and send up to IPSEC for validating
2709 			 * and removing the IPSEC headers. Clear
2710 			 * ipsec_in_secure so that when we return
2711 			 * from IPSEC, we don't mistakenly think that this
2712 			 * is a secure packet came from the network.
2713 			 *
2714 			 * NOTE : ill_index is used by ip_fanout_proto_again
2715 			 * to locate the ill.
2716 			 */
2717 			ASSERT(first_mp == mp);
2718 			first_mp = ipsec_in_alloc(B_TRUE);
2719 			if (first_mp == NULL) {
2720 				freemsg(mp);
2721 				BUMP_MIB(&ip_mib, ipInDiscards);
2722 				return;
2723 			}
2724 			ii = (ipsec_in_t *)first_mp->b_rptr;
2725 
2726 			/* This is not a secure packet */
2727 			ii->ipsec_in_secure = B_FALSE;
2728 			first_mp->b_cont = mp;
2729 			DB_TYPE(mp) = M_CTL;
2730 			ASSERT(ill != NULL);
2731 			ii->ipsec_in_ill_index =
2732 			    ill->ill_phyint->phyint_ifindex;
2733 			ii->ipsec_in_rill_index =
2734 			    recv_ill->ill_phyint->phyint_ifindex;
2735 		}
2736 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2737 
2738 		if (!ipsec_loaded()) {
2739 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2740 			return;
2741 		}
2742 
2743 		if (ipha->ipha_protocol == IPPROTO_ESP)
2744 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2745 		else
2746 			ipsec_rc = ipsecah_icmp_error(first_mp);
2747 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2748 			return;
2749 
2750 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2751 		return;
2752 	}
2753 	default:
2754 		/*
2755 		 * The ripha header is only used for the lookup and we
2756 		 * only set the src and dst addresses and protocol.
2757 		 */
2758 		ripha.ipha_src = ipha->ipha_dst;
2759 		ripha.ipha_dst = ipha->ipha_src;
2760 		ripha.ipha_protocol = ipha->ipha_protocol;
2761 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2762 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2763 		    ntohl(ipha->ipha_dst),
2764 		    icmph->icmph_type, icmph->icmph_code));
2765 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2766 			ipha_t *in_ipha;
2767 
2768 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2769 			    mp->b_wptr) {
2770 				if (!pullupmsg(mp, (uchar_t *)ipha +
2771 				    hdr_length + sizeof (ipha_t) -
2772 				    mp->b_rptr)) {
2773 
2774 					BUMP_MIB(&ip_mib, ipInDiscards);
2775 					goto drop_pkt;
2776 				}
2777 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2778 				ipha = (ipha_t *)&icmph[1];
2779 			}
2780 			/*
2781 			 * Caller has verified that length has to be
2782 			 * at least the size of IP header.
2783 			 */
2784 			ASSERT(hdr_length >= sizeof (ipha_t));
2785 			/*
2786 			 * Check the sanity of the inner IP header like
2787 			 * we did for the outer header.
2788 			 */
2789 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2790 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2791 				BUMP_MIB(&ip_mib, ipInDiscards);
2792 				goto drop_pkt;
2793 			}
2794 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2795 				BUMP_MIB(&ip_mib, ipInDiscards);
2796 				goto drop_pkt;
2797 			}
2798 			/* Check for Self-encapsulated tunnels */
2799 			if (in_ipha->ipha_src == ipha->ipha_src &&
2800 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2801 
2802 				mp = icmp_inbound_self_encap_error(mp,
2803 				    iph_hdr_length, hdr_length);
2804 				if (mp == NULL)
2805 					goto drop_pkt;
2806 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2807 				ipha = (ipha_t *)&icmph[1];
2808 				hdr_length = IPH_HDR_LENGTH(ipha);
2809 				/*
2810 				 * The packet in error is self-encapsualted.
2811 				 * And we are finding it further encapsulated
2812 				 * which we could not have possibly generated.
2813 				 */
2814 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2815 					BUMP_MIB(&ip_mib, ipInDiscards);
2816 					goto drop_pkt;
2817 				}
2818 				icmp_inbound_error_fanout(q, ill, first_mp,
2819 				    icmph, ipha, iph_hdr_length, hdr_length,
2820 				    mctl_present, ip_policy, recv_ill, zoneid);
2821 				return;
2822 			}
2823 		}
2824 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2825 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2826 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2827 		    ii != NULL &&
2828 		    ii->ipsec_in_loopback &&
2829 		    ii->ipsec_in_secure) {
2830 			/*
2831 			 * For IP tunnels that get a looped-back
2832 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2833 			 * reported new MTU to take into account the IPsec
2834 			 * headers protecting this configured tunnel.
2835 			 *
2836 			 * This allows the tunnel module (tun.c) to blindly
2837 			 * accept the MTU reported in an ICMP "too big"
2838 			 * message.
2839 			 *
2840 			 * Non-looped back ICMP messages will just be
2841 			 * handled by the security protocols (if needed),
2842 			 * and the first subsequent packet will hit this
2843 			 * path.
2844 			 */
2845 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2846 			    ipsec_in_extra_length(first_mp));
2847 		}
2848 		/* Have to change db_type after any pullupmsg */
2849 		DB_TYPE(mp) = M_CTL;
2850 
2851 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2852 		    ip_policy, recv_ill, zoneid);
2853 		return;
2854 	}
2855 	/* NOTREACHED */
2856 drop_pkt:;
2857 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2858 	freemsg(first_mp);
2859 }
2860 
2861 /*
2862  * Common IP options parser.
2863  *
2864  * Setup routine: fill in *optp with options-parsing state, then
2865  * tail-call ipoptp_next to return the first option.
2866  */
2867 uint8_t
2868 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2869 {
2870 	uint32_t totallen; /* total length of all options */
2871 
2872 	totallen = ipha->ipha_version_and_hdr_length -
2873 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2874 	totallen <<= 2;
2875 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2876 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2877 	optp->ipoptp_flags = 0;
2878 	return (ipoptp_next(optp));
2879 }
2880 
2881 /*
2882  * Common IP options parser: extract next option.
2883  */
2884 uint8_t
2885 ipoptp_next(ipoptp_t *optp)
2886 {
2887 	uint8_t *end = optp->ipoptp_end;
2888 	uint8_t *cur = optp->ipoptp_next;
2889 	uint8_t opt, len, pointer;
2890 
2891 	/*
2892 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2893 	 * has been corrupted.
2894 	 */
2895 	ASSERT(cur <= end);
2896 
2897 	if (cur == end)
2898 		return (IPOPT_EOL);
2899 
2900 	opt = cur[IPOPT_OPTVAL];
2901 
2902 	/*
2903 	 * Skip any NOP options.
2904 	 */
2905 	while (opt == IPOPT_NOP) {
2906 		cur++;
2907 		if (cur == end)
2908 			return (IPOPT_EOL);
2909 		opt = cur[IPOPT_OPTVAL];
2910 	}
2911 
2912 	if (opt == IPOPT_EOL)
2913 		return (IPOPT_EOL);
2914 
2915 	/*
2916 	 * Option requiring a length.
2917 	 */
2918 	if ((cur + 1) >= end) {
2919 		optp->ipoptp_flags |= IPOPTP_ERROR;
2920 		return (IPOPT_EOL);
2921 	}
2922 	len = cur[IPOPT_OLEN];
2923 	if (len < 2) {
2924 		optp->ipoptp_flags |= IPOPTP_ERROR;
2925 		return (IPOPT_EOL);
2926 	}
2927 	optp->ipoptp_cur = cur;
2928 	optp->ipoptp_len = len;
2929 	optp->ipoptp_next = cur + len;
2930 	if (cur + len > end) {
2931 		optp->ipoptp_flags |= IPOPTP_ERROR;
2932 		return (IPOPT_EOL);
2933 	}
2934 
2935 	/*
2936 	 * For the options which require a pointer field, make sure
2937 	 * its there, and make sure it points to either something
2938 	 * inside this option, or the end of the option.
2939 	 */
2940 	switch (opt) {
2941 	case IPOPT_RR:
2942 	case IPOPT_TS:
2943 	case IPOPT_LSRR:
2944 	case IPOPT_SSRR:
2945 		if (len <= IPOPT_OFFSET) {
2946 			optp->ipoptp_flags |= IPOPTP_ERROR;
2947 			return (opt);
2948 		}
2949 		pointer = cur[IPOPT_OFFSET];
2950 		if (pointer - 1 > len) {
2951 			optp->ipoptp_flags |= IPOPTP_ERROR;
2952 			return (opt);
2953 		}
2954 		break;
2955 	}
2956 
2957 	/*
2958 	 * Sanity check the pointer field based on the type of the
2959 	 * option.
2960 	 */
2961 	switch (opt) {
2962 	case IPOPT_RR:
2963 	case IPOPT_SSRR:
2964 	case IPOPT_LSRR:
2965 		if (pointer < IPOPT_MINOFF_SR)
2966 			optp->ipoptp_flags |= IPOPTP_ERROR;
2967 		break;
2968 	case IPOPT_TS:
2969 		if (pointer < IPOPT_MINOFF_IT)
2970 			optp->ipoptp_flags |= IPOPTP_ERROR;
2971 		/*
2972 		 * Note that the Internet Timestamp option also
2973 		 * contains two four bit fields (the Overflow field,
2974 		 * and the Flag field), which follow the pointer
2975 		 * field.  We don't need to check that these fields
2976 		 * fall within the length of the option because this
2977 		 * was implicitely done above.  We've checked that the
2978 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2979 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2980 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2981 		 */
2982 		ASSERT(len > IPOPT_POS_OV_FLG);
2983 		break;
2984 	}
2985 
2986 	return (opt);
2987 }
2988 
2989 /*
2990  * Use the outgoing IP header to create an IP_OPTIONS option the way
2991  * it was passed down from the application.
2992  */
2993 int
2994 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2995 {
2996 	ipoptp_t	opts;
2997 	const uchar_t	*opt;
2998 	uint8_t		optval;
2999 	uint8_t		optlen;
3000 	uint32_t	len = 0;
3001 	uchar_t	*buf1 = buf;
3002 
3003 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
3004 	len += IP_ADDR_LEN;
3005 	bzero(buf1, IP_ADDR_LEN);
3006 
3007 	/*
3008 	 * OK to cast away const here, as we don't store through the returned
3009 	 * opts.ipoptp_cur pointer.
3010 	 */
3011 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
3012 	    optval != IPOPT_EOL;
3013 	    optval = ipoptp_next(&opts)) {
3014 		int	off;
3015 
3016 		opt = opts.ipoptp_cur;
3017 		optlen = opts.ipoptp_len;
3018 		switch (optval) {
3019 		case IPOPT_SSRR:
3020 		case IPOPT_LSRR:
3021 
3022 			/*
3023 			 * Insert ipha_dst as the first entry in the source
3024 			 * route and move down the entries on step.
3025 			 * The last entry gets placed at buf1.
3026 			 */
3027 			buf[IPOPT_OPTVAL] = optval;
3028 			buf[IPOPT_OLEN] = optlen;
3029 			buf[IPOPT_OFFSET] = optlen;
3030 
3031 			off = optlen - IP_ADDR_LEN;
3032 			if (off < 0) {
3033 				/* No entries in source route */
3034 				break;
3035 			}
3036 			/* Last entry in source route */
3037 			bcopy(opt + off, buf1, IP_ADDR_LEN);
3038 			off -= IP_ADDR_LEN;
3039 
3040 			while (off > 0) {
3041 				bcopy(opt + off,
3042 				    buf + off + IP_ADDR_LEN,
3043 				    IP_ADDR_LEN);
3044 				off -= IP_ADDR_LEN;
3045 			}
3046 			/* ipha_dst into first slot */
3047 			bcopy(&ipha->ipha_dst,
3048 			    buf + off + IP_ADDR_LEN,
3049 			    IP_ADDR_LEN);
3050 			buf += optlen;
3051 			len += optlen;
3052 			break;
3053 
3054 		case IPOPT_COMSEC:
3055 		case IPOPT_SECURITY:
3056 			/* if passing up a label is not ok, then remove */
3057 			if (is_system_labeled())
3058 				break;
3059 			/* FALLTHROUGH */
3060 		default:
3061 			bcopy(opt, buf, optlen);
3062 			buf += optlen;
3063 			len += optlen;
3064 			break;
3065 		}
3066 	}
3067 done:
3068 	/* Pad the resulting options */
3069 	while (len & 0x3) {
3070 		*buf++ = IPOPT_EOL;
3071 		len++;
3072 	}
3073 	return (len);
3074 }
3075 
3076 /*
3077  * Update any record route or timestamp options to include this host.
3078  * Reverse any source route option.
3079  * This routine assumes that the options are well formed i.e. that they
3080  * have already been checked.
3081  */
3082 static void
3083 icmp_options_update(ipha_t *ipha)
3084 {
3085 	ipoptp_t	opts;
3086 	uchar_t		*opt;
3087 	uint8_t		optval;
3088 	ipaddr_t	src;		/* Our local address */
3089 	ipaddr_t	dst;
3090 
3091 	ip2dbg(("icmp_options_update\n"));
3092 	src = ipha->ipha_src;
3093 	dst = ipha->ipha_dst;
3094 
3095 	for (optval = ipoptp_first(&opts, ipha);
3096 	    optval != IPOPT_EOL;
3097 	    optval = ipoptp_next(&opts)) {
3098 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3099 		opt = opts.ipoptp_cur;
3100 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3101 		    optval, opts.ipoptp_len));
3102 		switch (optval) {
3103 			int off1, off2;
3104 		case IPOPT_SSRR:
3105 		case IPOPT_LSRR:
3106 			/*
3107 			 * Reverse the source route.  The first entry
3108 			 * should be the next to last one in the current
3109 			 * source route (the last entry is our address).
3110 			 * The last entry should be the final destination.
3111 			 */
3112 			off1 = IPOPT_MINOFF_SR - 1;
3113 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3114 			if (off2 < 0) {
3115 				/* No entries in source route */
3116 				ip1dbg((
3117 				    "icmp_options_update: bad src route\n"));
3118 				break;
3119 			}
3120 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3121 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3122 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3123 			off2 -= IP_ADDR_LEN;
3124 
3125 			while (off1 < off2) {
3126 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3127 				bcopy((char *)opt + off2, (char *)opt + off1,
3128 				    IP_ADDR_LEN);
3129 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3130 				off1 += IP_ADDR_LEN;
3131 				off2 -= IP_ADDR_LEN;
3132 			}
3133 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3134 			break;
3135 		}
3136 	}
3137 }
3138 
3139 /*
3140  * Process received ICMP Redirect messages.
3141  */
3142 /* ARGSUSED */
3143 static void
3144 icmp_redirect(mblk_t *mp)
3145 {
3146 	ipha_t	*ipha;
3147 	int	iph_hdr_length;
3148 	icmph_t	*icmph;
3149 	ipha_t	*ipha_err;
3150 	ire_t	*ire;
3151 	ire_t	*prev_ire;
3152 	ire_t	*save_ire;
3153 	ipaddr_t  src, dst, gateway;
3154 	iulp_t	ulp_info = { 0 };
3155 	int	error;
3156 
3157 	ipha = (ipha_t *)mp->b_rptr;
3158 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3159 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3160 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3161 		BUMP_MIB(&icmp_mib, icmpInErrors);
3162 		freemsg(mp);
3163 		return;
3164 	}
3165 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3166 	ipha_err = (ipha_t *)&icmph[1];
3167 	src = ipha->ipha_src;
3168 	dst = ipha_err->ipha_dst;
3169 	gateway = icmph->icmph_rd_gateway;
3170 	/* Make sure the new gateway is reachable somehow. */
3171 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3172 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3173 	/*
3174 	 * Make sure we had a route for the dest in question and that
3175 	 * that route was pointing to the old gateway (the source of the
3176 	 * redirect packet.)
3177 	 */
3178 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3179 	    NULL, MATCH_IRE_GW);
3180 	/*
3181 	 * Check that
3182 	 *	the redirect was not from ourselves
3183 	 *	the new gateway and the old gateway are directly reachable
3184 	 */
3185 	if (!prev_ire ||
3186 	    !ire ||
3187 	    ire->ire_type == IRE_LOCAL) {
3188 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3189 		freemsg(mp);
3190 		if (ire != NULL)
3191 			ire_refrele(ire);
3192 		if (prev_ire != NULL)
3193 			ire_refrele(prev_ire);
3194 		return;
3195 	}
3196 
3197 	/*
3198 	 * Should we use the old ULP info to create the new gateway?  From
3199 	 * a user's perspective, we should inherit the info so that it
3200 	 * is a "smooth" transition.  If we do not do that, then new
3201 	 * connections going thru the new gateway will have no route metrics,
3202 	 * which is counter-intuitive to user.  From a network point of
3203 	 * view, this may or may not make sense even though the new gateway
3204 	 * is still directly connected to us so the route metrics should not
3205 	 * change much.
3206 	 *
3207 	 * But if the old ire_uinfo is not initialized, we do another
3208 	 * recursive lookup on the dest using the new gateway.  There may
3209 	 * be a route to that.  If so, use it to initialize the redirect
3210 	 * route.
3211 	 */
3212 	if (prev_ire->ire_uinfo.iulp_set) {
3213 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3214 	} else {
3215 		ire_t *tmp_ire;
3216 		ire_t *sire;
3217 
3218 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3219 		    ALL_ZONES, 0, NULL,
3220 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3221 		if (sire != NULL) {
3222 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3223 			/*
3224 			 * If sire != NULL, ire_ftable_lookup() should not
3225 			 * return a NULL value.
3226 			 */
3227 			ASSERT(tmp_ire != NULL);
3228 			ire_refrele(tmp_ire);
3229 			ire_refrele(sire);
3230 		} else if (tmp_ire != NULL) {
3231 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3232 			    sizeof (iulp_t));
3233 			ire_refrele(tmp_ire);
3234 		}
3235 	}
3236 	if (prev_ire->ire_type == IRE_CACHE)
3237 		ire_delete(prev_ire);
3238 	ire_refrele(prev_ire);
3239 	/*
3240 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3241 	 * require TOS routing
3242 	 */
3243 	switch (icmph->icmph_code) {
3244 	case 0:
3245 	case 1:
3246 		/* TODO: TOS specificity for cases 2 and 3 */
3247 	case 2:
3248 	case 3:
3249 		break;
3250 	default:
3251 		freemsg(mp);
3252 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3253 		ire_refrele(ire);
3254 		return;
3255 	}
3256 	/*
3257 	 * Create a Route Association.  This will allow us to remember that
3258 	 * someone we believe told us to use the particular gateway.
3259 	 */
3260 	save_ire = ire;
3261 	ire = ire_create(
3262 		(uchar_t *)&dst,			/* dest addr */
3263 		(uchar_t *)&ip_g_all_ones,		/* mask */
3264 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3265 		(uchar_t *)&gateway,			/* gateway addr */
3266 		NULL,					/* no in_srcaddr */
3267 		&save_ire->ire_max_frag,		/* max frag */
3268 		NULL,					/* Fast Path header */
3269 		NULL,					/* no rfq */
3270 		NULL,					/* no stq */
3271 		IRE_HOST,
3272 		NULL,
3273 		NULL,
3274 		NULL,
3275 		0,
3276 		0,
3277 		0,
3278 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3279 		&ulp_info,
3280 		NULL,
3281 		NULL);
3282 
3283 	if (ire == NULL) {
3284 		freemsg(mp);
3285 		ire_refrele(save_ire);
3286 		return;
3287 	}
3288 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3289 	ire_refrele(save_ire);
3290 	atomic_inc_32(&ip_redirect_cnt);
3291 
3292 	if (error == 0) {
3293 		ire_refrele(ire);		/* Held in ire_add_v4 */
3294 		/* tell routing sockets that we received a redirect */
3295 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3296 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3297 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3298 	}
3299 
3300 	/*
3301 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3302 	 * This together with the added IRE has the effect of
3303 	 * modifying an existing redirect.
3304 	 */
3305 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3306 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3307 	if (prev_ire != NULL) {
3308 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3309 			ire_delete(prev_ire);
3310 		ire_refrele(prev_ire);
3311 	}
3312 
3313 	freemsg(mp);
3314 }
3315 
3316 /*
3317  * Generate an ICMP parameter problem message.
3318  */
3319 static void
3320 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid)
3321 {
3322 	icmph_t	icmph;
3323 	boolean_t mctl_present;
3324 	mblk_t *first_mp;
3325 
3326 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3327 
3328 	if (!(mp = icmp_pkt_err_ok(mp))) {
3329 		if (mctl_present)
3330 			freeb(first_mp);
3331 		return;
3332 	}
3333 
3334 	bzero(&icmph, sizeof (icmph_t));
3335 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3336 	icmph.icmph_pp_ptr = ptr;
3337 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3338 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3339 }
3340 
3341 /*
3342  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3343  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3344  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3345  * an icmp error packet can be sent.
3346  * Assigns an appropriate source address to the packet. If ipha_dst is
3347  * one of our addresses use it for source. Otherwise pick a source based
3348  * on a route lookup back to ipha_src.
3349  * Note that ipha_src must be set here since the
3350  * packet is likely to arrive on an ill queue in ip_wput() which will
3351  * not set a source address.
3352  */
3353 static void
3354 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3355     boolean_t mctl_present, zoneid_t zoneid)
3356 {
3357 	ipaddr_t dst;
3358 	icmph_t	*icmph;
3359 	ipha_t	*ipha;
3360 	uint_t	len_needed;
3361 	size_t	msg_len;
3362 	mblk_t	*mp1;
3363 	ipaddr_t src;
3364 	ire_t	*ire;
3365 	mblk_t *ipsec_mp;
3366 	ipsec_out_t	*io = NULL;
3367 	boolean_t xmit_if_on = B_FALSE;
3368 
3369 	if (mctl_present) {
3370 		/*
3371 		 * If it is :
3372 		 *
3373 		 * 1) a IPSEC_OUT, then this is caused by outbound
3374 		 *    datagram originating on this host. IPSEC processing
3375 		 *    may or may not have been done. Refer to comments above
3376 		 *    icmp_inbound_error_fanout for details.
3377 		 *
3378 		 * 2) a IPSEC_IN if we are generating a icmp_message
3379 		 *    for an incoming datagram destined for us i.e called
3380 		 *    from ip_fanout_send_icmp.
3381 		 */
3382 		ipsec_info_t *in;
3383 		ipsec_mp = mp;
3384 		mp = ipsec_mp->b_cont;
3385 
3386 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3387 		ipha = (ipha_t *)mp->b_rptr;
3388 
3389 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3390 		    in->ipsec_info_type == IPSEC_IN);
3391 
3392 		if (in->ipsec_info_type == IPSEC_IN) {
3393 			/*
3394 			 * Convert the IPSEC_IN to IPSEC_OUT.
3395 			 */
3396 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3397 				BUMP_MIB(&ip_mib, ipOutDiscards);
3398 				return;
3399 			}
3400 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3401 		} else {
3402 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3403 			io = (ipsec_out_t *)in;
3404 			if (io->ipsec_out_xmit_if)
3405 				xmit_if_on = B_TRUE;
3406 			/*
3407 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3408 			 * ire lookup.
3409 			 */
3410 			io->ipsec_out_proc_begin = B_FALSE;
3411 		}
3412 		ASSERT(zoneid == io->ipsec_out_zoneid);
3413 		ASSERT(zoneid != ALL_ZONES);
3414 	} else {
3415 		/*
3416 		 * This is in clear. The icmp message we are building
3417 		 * here should go out in clear.
3418 		 *
3419 		 * Pardon the convolution of it all, but it's easier to
3420 		 * allocate a "use cleartext" IPSEC_IN message and convert
3421 		 * it than it is to allocate a new one.
3422 		 */
3423 		ipsec_in_t *ii;
3424 		ASSERT(DB_TYPE(mp) == M_DATA);
3425 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3426 			freemsg(mp);
3427 			BUMP_MIB(&ip_mib, ipOutDiscards);
3428 			return;
3429 		}
3430 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3431 
3432 		/* This is not a secure packet */
3433 		ii->ipsec_in_secure = B_FALSE;
3434 		/*
3435 		 * For trusted extensions using a shared IP address we can
3436 		 * send using any zoneid.
3437 		 */
3438 		if (zoneid == ALL_ZONES)
3439 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3440 		else
3441 			ii->ipsec_in_zoneid = zoneid;
3442 		ipsec_mp->b_cont = mp;
3443 		ipha = (ipha_t *)mp->b_rptr;
3444 		/*
3445 		 * Convert the IPSEC_IN to IPSEC_OUT.
3446 		 */
3447 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3448 			BUMP_MIB(&ip_mib, ipOutDiscards);
3449 			return;
3450 		}
3451 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3452 	}
3453 
3454 	/* Remember our eventual destination */
3455 	dst = ipha->ipha_src;
3456 
3457 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3458 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3459 	if (ire != NULL &&
3460 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3461 		src = ipha->ipha_dst;
3462 	} else if (!xmit_if_on) {
3463 		if (ire != NULL)
3464 			ire_refrele(ire);
3465 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3466 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3467 		if (ire == NULL) {
3468 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3469 			freemsg(ipsec_mp);
3470 			return;
3471 		}
3472 		src = ire->ire_src_addr;
3473 	} else {
3474 		ipif_t	*ipif = NULL;
3475 		ill_t	*ill;
3476 		/*
3477 		 * This must be an ICMP error coming from
3478 		 * ip_mrtun_forward(). The src addr should
3479 		 * be equal to the IP-addr of the outgoing
3480 		 * interface.
3481 		 */
3482 		if (io == NULL) {
3483 			/* This is not a IPSEC_OUT type control msg */
3484 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3485 			freemsg(ipsec_mp);
3486 			return;
3487 		}
3488 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3489 		    NULL, NULL, NULL, NULL);
3490 		if (ill != NULL) {
3491 			ipif = ipif_get_next_ipif(NULL, ill);
3492 			ill_refrele(ill);
3493 		}
3494 		if (ipif == NULL) {
3495 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3496 			freemsg(ipsec_mp);
3497 			return;
3498 		}
3499 		src = ipif->ipif_src_addr;
3500 		ipif_refrele(ipif);
3501 	}
3502 
3503 	if (ire != NULL)
3504 		ire_refrele(ire);
3505 
3506 	/*
3507 	 * Check if we can send back more then 8 bytes in addition
3508 	 * to the IP header. We will include as much as 64 bytes.
3509 	 */
3510 	len_needed = IPH_HDR_LENGTH(ipha);
3511 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3512 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3513 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3514 	}
3515 	len_needed += ip_icmp_return;
3516 	msg_len = msgdsize(mp);
3517 	if (msg_len > len_needed) {
3518 		(void) adjmsg(mp, len_needed - msg_len);
3519 		msg_len = len_needed;
3520 	}
3521 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3522 	if (mp1 == NULL) {
3523 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3524 		freemsg(ipsec_mp);
3525 		return;
3526 	}
3527 	/*
3528 	 * On an unlabeled system, dblks don't necessarily have creds.
3529 	 */
3530 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3531 	if (DB_CRED(mp) != NULL)
3532 		mblk_setcred(mp1, DB_CRED(mp));
3533 	mp1->b_cont = mp;
3534 	mp = mp1;
3535 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3536 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3537 	    io->ipsec_out_type == IPSEC_OUT);
3538 	ipsec_mp->b_cont = mp;
3539 
3540 	/*
3541 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3542 	 * node generates be accepted in peace by all on-host destinations.
3543 	 * If we do NOT assume that all on-host destinations trust
3544 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3545 	 * (Look for ipsec_out_icmp_loopback).
3546 	 */
3547 	io->ipsec_out_icmp_loopback = B_TRUE;
3548 
3549 	ipha = (ipha_t *)mp->b_rptr;
3550 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3551 	*ipha = icmp_ipha;
3552 	ipha->ipha_src = src;
3553 	ipha->ipha_dst = dst;
3554 	ipha->ipha_ttl = ip_def_ttl;
3555 	msg_len += sizeof (icmp_ipha) + len;
3556 	if (msg_len > IP_MAXPACKET) {
3557 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3558 		msg_len = IP_MAXPACKET;
3559 	}
3560 	ipha->ipha_length = htons((uint16_t)msg_len);
3561 	icmph = (icmph_t *)&ipha[1];
3562 	bcopy(stuff, icmph, len);
3563 	icmph->icmph_checksum = 0;
3564 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3565 	if (icmph->icmph_checksum == 0)
3566 		icmph->icmph_checksum = 0xFFFF;
3567 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3568 	put(q, ipsec_mp);
3569 }
3570 
3571 /*
3572  * Determine if an ICMP error packet can be sent given the rate limit.
3573  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3574  * in milliseconds) and a burst size. Burst size number of packets can
3575  * be sent arbitrarely closely spaced.
3576  * The state is tracked using two variables to implement an approximate
3577  * token bucket filter:
3578  *	icmp_pkt_err_last - lbolt value when the last burst started
3579  *	icmp_pkt_err_sent - number of packets sent in current burst
3580  */
3581 boolean_t
3582 icmp_err_rate_limit(void)
3583 {
3584 	clock_t now = TICK_TO_MSEC(lbolt);
3585 	uint_t refilled; /* Number of packets refilled in tbf since last */
3586 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3587 
3588 	if (err_interval == 0)
3589 		return (B_FALSE);
3590 
3591 	if (icmp_pkt_err_last > now) {
3592 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3593 		icmp_pkt_err_last = 0;
3594 		icmp_pkt_err_sent = 0;
3595 	}
3596 	/*
3597 	 * If we are in a burst update the token bucket filter.
3598 	 * Update the "last" time to be close to "now" but make sure
3599 	 * we don't loose precision.
3600 	 */
3601 	if (icmp_pkt_err_sent != 0) {
3602 		refilled = (now - icmp_pkt_err_last)/err_interval;
3603 		if (refilled > icmp_pkt_err_sent) {
3604 			icmp_pkt_err_sent = 0;
3605 		} else {
3606 			icmp_pkt_err_sent -= refilled;
3607 			icmp_pkt_err_last += refilled * err_interval;
3608 		}
3609 	}
3610 	if (icmp_pkt_err_sent == 0) {
3611 		/* Start of new burst */
3612 		icmp_pkt_err_last = now;
3613 	}
3614 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3615 		icmp_pkt_err_sent++;
3616 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3617 		    icmp_pkt_err_sent));
3618 		return (B_FALSE);
3619 	}
3620 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3621 	return (B_TRUE);
3622 }
3623 
3624 /*
3625  * Check if it is ok to send an IPv4 ICMP error packet in
3626  * response to the IPv4 packet in mp.
3627  * Free the message and return null if no
3628  * ICMP error packet should be sent.
3629  */
3630 static mblk_t *
3631 icmp_pkt_err_ok(mblk_t *mp)
3632 {
3633 	icmph_t	*icmph;
3634 	ipha_t	*ipha;
3635 	uint_t	len_needed;
3636 	ire_t	*src_ire;
3637 	ire_t	*dst_ire;
3638 
3639 	if (!mp)
3640 		return (NULL);
3641 	ipha = (ipha_t *)mp->b_rptr;
3642 	if (ip_csum_hdr(ipha)) {
3643 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3644 		freemsg(mp);
3645 		return (NULL);
3646 	}
3647 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3648 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3649 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3650 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3651 	if (src_ire != NULL || dst_ire != NULL ||
3652 	    CLASSD(ipha->ipha_dst) ||
3653 	    CLASSD(ipha->ipha_src) ||
3654 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3655 		/* Note: only errors to the fragment with offset 0 */
3656 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3657 		freemsg(mp);
3658 		if (src_ire != NULL)
3659 			ire_refrele(src_ire);
3660 		if (dst_ire != NULL)
3661 			ire_refrele(dst_ire);
3662 		return (NULL);
3663 	}
3664 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3665 		/*
3666 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3667 		 * errors in response to any ICMP errors.
3668 		 */
3669 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3670 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3671 			if (!pullupmsg(mp, len_needed)) {
3672 				BUMP_MIB(&icmp_mib, icmpInErrors);
3673 				freemsg(mp);
3674 				return (NULL);
3675 			}
3676 			ipha = (ipha_t *)mp->b_rptr;
3677 		}
3678 		icmph = (icmph_t *)
3679 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3680 		switch (icmph->icmph_type) {
3681 		case ICMP_DEST_UNREACHABLE:
3682 		case ICMP_SOURCE_QUENCH:
3683 		case ICMP_TIME_EXCEEDED:
3684 		case ICMP_PARAM_PROBLEM:
3685 		case ICMP_REDIRECT:
3686 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3687 			freemsg(mp);
3688 			return (NULL);
3689 		default:
3690 			break;
3691 		}
3692 	}
3693 	/*
3694 	 * If this is a labeled system, then check to see if we're allowed to
3695 	 * send a response to this particular sender.  If not, then just drop.
3696 	 */
3697 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3698 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3699 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3700 		freemsg(mp);
3701 		return (NULL);
3702 	}
3703 	if (icmp_err_rate_limit()) {
3704 		/*
3705 		 * Only send ICMP error packets every so often.
3706 		 * This should be done on a per port/source basis,
3707 		 * but for now this will suffice.
3708 		 */
3709 		freemsg(mp);
3710 		return (NULL);
3711 	}
3712 	return (mp);
3713 }
3714 
3715 /*
3716  * Generate an ICMP redirect message.
3717  */
3718 static void
3719 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3720 {
3721 	icmph_t	icmph;
3722 
3723 	/*
3724 	 * We are called from ip_rput where we could
3725 	 * not have attached an IPSEC_IN.
3726 	 */
3727 	ASSERT(mp->b_datap->db_type == M_DATA);
3728 
3729 	if (!(mp = icmp_pkt_err_ok(mp))) {
3730 		return;
3731 	}
3732 
3733 	bzero(&icmph, sizeof (icmph_t));
3734 	icmph.icmph_type = ICMP_REDIRECT;
3735 	icmph.icmph_code = 1;
3736 	icmph.icmph_rd_gateway = gateway;
3737 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3738 	/* Redirects sent by router, and router is global zone */
3739 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID);
3740 }
3741 
3742 /*
3743  * Generate an ICMP time exceeded message.
3744  */
3745 void
3746 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3747 {
3748 	icmph_t	icmph;
3749 	boolean_t mctl_present;
3750 	mblk_t *first_mp;
3751 
3752 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3753 
3754 	if (!(mp = icmp_pkt_err_ok(mp))) {
3755 		if (mctl_present)
3756 			freeb(first_mp);
3757 		return;
3758 	}
3759 
3760 	bzero(&icmph, sizeof (icmph_t));
3761 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3762 	icmph.icmph_code = code;
3763 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3764 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3765 }
3766 
3767 /*
3768  * Generate an ICMP unreachable message.
3769  */
3770 void
3771 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3772 {
3773 	icmph_t	icmph;
3774 	mblk_t *first_mp;
3775 	boolean_t mctl_present;
3776 
3777 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3778 
3779 	if (!(mp = icmp_pkt_err_ok(mp))) {
3780 		if (mctl_present)
3781 			freeb(first_mp);
3782 		return;
3783 	}
3784 
3785 	bzero(&icmph, sizeof (icmph_t));
3786 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3787 	icmph.icmph_code = code;
3788 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3789 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3790 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3791 	    zoneid);
3792 }
3793 
3794 /*
3795  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3796  * duplicate.  As long as someone else holds the address, the interface will
3797  * stay down.  When that conflict goes away, the interface is brought back up.
3798  * This is done so that accidental shutdowns of addresses aren't made
3799  * permanent.  Your server will recover from a failure.
3800  *
3801  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3802  * user space process (dhcpagent).
3803  *
3804  * Recovery completes if ARP reports that the address is now ours (via
3805  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3806  *
3807  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3808  */
3809 static void
3810 ipif_dup_recovery(void *arg)
3811 {
3812 	ipif_t *ipif = arg;
3813 	ill_t *ill = ipif->ipif_ill;
3814 	mblk_t *arp_add_mp;
3815 	mblk_t *arp_del_mp;
3816 	area_t *area;
3817 
3818 	ipif->ipif_recovery_id = 0;
3819 
3820 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3821 	    (ipif->ipif_flags & IPIF_POINTOPOINT)) {
3822 		/* No reason to try to bring this address back. */
3823 		return;
3824 	}
3825 
3826 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3827 		goto alloc_fail;
3828 
3829 	if (ipif->ipif_arp_del_mp == NULL) {
3830 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3831 			goto alloc_fail;
3832 		ipif->ipif_arp_del_mp = arp_del_mp;
3833 	}
3834 
3835 	/* Setting the 'unverified' flag restarts DAD */
3836 	area = (area_t *)arp_add_mp->b_rptr;
3837 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3838 	    ACE_F_UNVERIFIED;
3839 	putnext(ill->ill_rq, arp_add_mp);
3840 	return;
3841 
3842 alloc_fail:
3843 	/* On allocation failure, just restart the timer */
3844 	freemsg(arp_add_mp);
3845 	if (ip_dup_recovery > 0) {
3846 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3847 		    MSEC_TO_TICK(ip_dup_recovery));
3848 	}
3849 }
3850 
3851 /*
3852  * This is for exclusive changes due to ARP.  Either tear down an interface due
3853  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3854  */
3855 /* ARGSUSED */
3856 static void
3857 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3858 {
3859 	ill_t	*ill = rq->q_ptr;
3860 	arh_t *arh;
3861 	ipaddr_t src;
3862 	ipif_t	*ipif;
3863 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3864 	char hbuf[MAC_STR_LEN];
3865 	char sbuf[INET_ADDRSTRLEN];
3866 	const char *failtype;
3867 	boolean_t bring_up;
3868 
3869 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3870 	case AR_CN_READY:
3871 		failtype = NULL;
3872 		bring_up = B_TRUE;
3873 		break;
3874 	case AR_CN_FAILED:
3875 		failtype = "in use";
3876 		bring_up = B_FALSE;
3877 		break;
3878 	default:
3879 		failtype = "claimed";
3880 		bring_up = B_FALSE;
3881 		break;
3882 	}
3883 
3884 	arh = (arh_t *)mp->b_cont->b_rptr;
3885 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3886 
3887 	/* Handle failures due to probes */
3888 	if (src == 0) {
3889 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3890 		    IP_ADDR_LEN);
3891 	}
3892 
3893 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3894 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3895 	    sizeof (hbuf));
3896 	(void) ip_dot_addr(src, sbuf);
3897 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3898 
3899 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3900 		    ipif->ipif_lcl_addr != src) {
3901 			continue;
3902 		}
3903 
3904 		/*
3905 		 * If we failed on a recovery probe, then restart the timer to
3906 		 * try again later.
3907 		 */
3908 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3909 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3910 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3911 		    ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0) {
3912 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3913 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3914 			continue;
3915 		}
3916 
3917 		/*
3918 		 * If what we're trying to do has already been done, then do
3919 		 * nothing.
3920 		 */
3921 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3922 			continue;
3923 
3924 		if (ipif->ipif_id != 0) {
3925 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3926 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3927 			    ipif->ipif_id);
3928 		}
3929 		if (failtype == NULL) {
3930 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3931 			    ibuf);
3932 		} else {
3933 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3934 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3935 		}
3936 
3937 		if (bring_up) {
3938 			ASSERT(ill->ill_dl_up);
3939 			/*
3940 			 * Free up the ARP delete message so we can allocate
3941 			 * a fresh one through the normal path.
3942 			 */
3943 			freemsg(ipif->ipif_arp_del_mp);
3944 			ipif->ipif_arp_del_mp = NULL;
3945 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3946 			    EINPROGRESS) {
3947 				ipif->ipif_addr_ready = 1;
3948 				(void) ipif_up_done(ipif);
3949 			}
3950 			continue;
3951 		}
3952 
3953 		mutex_enter(&ill->ill_lock);
3954 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3955 		ipif->ipif_flags |= IPIF_DUPLICATE;
3956 		ill->ill_ipif_dup_count++;
3957 		mutex_exit(&ill->ill_lock);
3958 		/*
3959 		 * Already exclusive on the ill; no need to handle deferred
3960 		 * processing here.
3961 		 */
3962 		(void) ipif_down(ipif, NULL, NULL);
3963 		ipif_down_tail(ipif);
3964 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3965 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3966 		    ip_dup_recovery > 0) {
3967 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3968 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3969 		}
3970 	}
3971 	freemsg(mp);
3972 }
3973 
3974 /* ARGSUSED */
3975 static void
3976 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3977 {
3978 	ill_t	*ill = rq->q_ptr;
3979 	arh_t *arh;
3980 	ipaddr_t src;
3981 	ipif_t	*ipif;
3982 
3983 	arh = (arh_t *)mp->b_cont->b_rptr;
3984 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3985 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3986 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3987 			(void) ipif_resolver_up(ipif, Res_act_defend);
3988 	}
3989 	freemsg(mp);
3990 }
3991 
3992 /*
3993  * News from ARP.  ARP sends notification of interesting events down
3994  * to its clients using M_CTL messages with the interesting ARP packet
3995  * attached via b_cont.
3996  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3997  * queue as opposed to ARP sending the message to all the clients, i.e. all
3998  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3999  * table if a cache IRE is found to delete all the entries for the address in
4000  * the packet.
4001  */
4002 static void
4003 ip_arp_news(queue_t *q, mblk_t *mp)
4004 {
4005 	arcn_t		*arcn;
4006 	arh_t		*arh;
4007 	ire_t		*ire = NULL;
4008 	char		hbuf[MAC_STR_LEN];
4009 	char		sbuf[INET_ADDRSTRLEN];
4010 	ipaddr_t	src;
4011 	in6_addr_t	v6src;
4012 	boolean_t	isv6 = B_FALSE;
4013 	ipif_t		*ipif;
4014 	ill_t		*ill;
4015 
4016 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
4017 		if (q->q_next) {
4018 			putnext(q, mp);
4019 		} else
4020 			freemsg(mp);
4021 		return;
4022 	}
4023 	arh = (arh_t *)mp->b_cont->b_rptr;
4024 	/* Is it one we are interested in? */
4025 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
4026 		isv6 = B_TRUE;
4027 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
4028 		    IPV6_ADDR_LEN);
4029 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
4030 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
4031 		    IP_ADDR_LEN);
4032 	} else {
4033 		freemsg(mp);
4034 		return;
4035 	}
4036 
4037 	ill = q->q_ptr;
4038 
4039 	arcn = (arcn_t *)mp->b_rptr;
4040 	switch (arcn->arcn_code) {
4041 	case AR_CN_BOGON:
4042 		/*
4043 		 * Someone is sending ARP packets with a source protocol
4044 		 * address that we have published and for which we believe our
4045 		 * entry is authoritative and (when ill_arp_extend is set)
4046 		 * verified to be unique on the network.
4047 		 *
4048 		 * The ARP module internally handles the cases where the sender
4049 		 * is just probing (for DAD) and where the hardware address of
4050 		 * a non-authoritative entry has changed.  Thus, these are the
4051 		 * real conflicts, and we have to do resolution.
4052 		 *
4053 		 * We back away quickly from the address if it's from DHCP or
4054 		 * otherwise temporary and hasn't been used recently (or at
4055 		 * all).  We'd like to include "deprecated" addresses here as
4056 		 * well (as there's no real reason to defend something we're
4057 		 * discarding), but IPMP "reuses" this flag to mean something
4058 		 * other than the standard meaning.
4059 		 *
4060 		 * If the ARP module above is not extended (meaning that it
4061 		 * doesn't know how to defend the address), then we just log
4062 		 * the problem as we always did and continue on.  It's not
4063 		 * right, but there's little else we can do, and those old ATM
4064 		 * users are going away anyway.
4065 		 */
4066 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4067 		    hbuf, sizeof (hbuf));
4068 		(void) ip_dot_addr(src, sbuf);
4069 		if (isv6)
4070 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
4071 		else
4072 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
4073 
4074 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4075 			uint32_t now;
4076 			uint32_t maxage;
4077 			clock_t lused;
4078 			uint_t maxdefense;
4079 			uint_t defs;
4080 
4081 			/*
4082 			 * First, figure out if this address hasn't been used
4083 			 * in a while.  If it hasn't, then it's a better
4084 			 * candidate for abandoning.
4085 			 */
4086 			ipif = ire->ire_ipif;
4087 			ASSERT(ipif != NULL);
4088 			now = gethrestime_sec();
4089 			maxage = now - ire->ire_create_time;
4090 			if (maxage > ip_max_temp_idle)
4091 				maxage = ip_max_temp_idle;
4092 			lused = drv_hztousec(ddi_get_lbolt() -
4093 			    ire->ire_last_used_time) / MICROSEC + 1;
4094 			if (lused >= maxage && (ipif->ipif_flags &
4095 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4096 				maxdefense = ip_max_temp_defend;
4097 			else
4098 				maxdefense = ip_max_defend;
4099 
4100 			/*
4101 			 * Now figure out how many times we've defended
4102 			 * ourselves.  Ignore defenses that happened long in
4103 			 * the past.
4104 			 */
4105 			mutex_enter(&ire->ire_lock);
4106 			if ((defs = ire->ire_defense_count) > 0 &&
4107 			    now - ire->ire_defense_time > ip_defend_interval) {
4108 				ire->ire_defense_count = defs = 0;
4109 			}
4110 			ire->ire_defense_count++;
4111 			ire->ire_defense_time = now;
4112 			mutex_exit(&ire->ire_lock);
4113 			ill_refhold(ill);
4114 			ire_refrele(ire);
4115 
4116 			/*
4117 			 * If we've defended ourselves too many times already,
4118 			 * then give up and tear down the interface(s) using
4119 			 * this address.  Otherwise, defend by sending out a
4120 			 * gratuitous ARP.
4121 			 */
4122 			if (defs >= maxdefense && ill->ill_arp_extend) {
4123 				(void) qwriter_ip(NULL, ill, q, mp,
4124 				    ip_arp_excl, CUR_OP, B_FALSE);
4125 			} else {
4126 				cmn_err(CE_WARN,
4127 				    "node %s is using our IP address %s on %s",
4128 				    hbuf, sbuf, ill->ill_name);
4129 				/*
4130 				 * If this is an old (ATM) ARP module, then
4131 				 * don't try to defend the address.  Remain
4132 				 * compatible with the old behavior.  Defend
4133 				 * only with new ARP.
4134 				 */
4135 				if (ill->ill_arp_extend) {
4136 					(void) qwriter_ip(NULL, ill, q, mp,
4137 					    ip_arp_defend, CUR_OP, B_FALSE);
4138 				} else {
4139 					ill_refrele(ill);
4140 				}
4141 			}
4142 			return;
4143 		}
4144 		cmn_err(CE_WARN,
4145 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4146 		    hbuf, sbuf, ill->ill_name);
4147 		if (ire != NULL)
4148 			ire_refrele(ire);
4149 		break;
4150 	case AR_CN_ANNOUNCE:
4151 		if (isv6) {
4152 			/*
4153 			 * For XRESOLV interfaces.
4154 			 * Delete the IRE cache entry and NCE for this
4155 			 * v6 address
4156 			 */
4157 			ip_ire_clookup_and_delete_v6(&v6src);
4158 			/*
4159 			 * If v6src is a non-zero, it's a router address
4160 			 * as below. Do the same sort of thing to clean
4161 			 * out off-net IRE_CACHE entries that go through
4162 			 * the router.
4163 			 */
4164 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4165 				ire_walk_v6(ire_delete_cache_gw_v6,
4166 				    (char *)&v6src, ALL_ZONES);
4167 			}
4168 		} else {
4169 			nce_hw_map_t hwm;
4170 
4171 			/*
4172 			 * ARP gives us a copy of any packet where it thinks
4173 			 * the address has changed, so that we can update our
4174 			 * caches.  We're responsible for caching known answers
4175 			 * in the current design.  We check whether the
4176 			 * hardware address really has changed in all of our
4177 			 * entries that have cached this mapping, and if so, we
4178 			 * blow them away.  This way we will immediately pick
4179 			 * up the rare case of a host changing hardware
4180 			 * address.
4181 			 */
4182 			if (src == 0)
4183 				break;
4184 			hwm.hwm_addr = src;
4185 			hwm.hwm_hwlen = arh->arh_hlen;
4186 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4187 			ndp_walk_common(&ndp4, NULL,
4188 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4189 		}
4190 		break;
4191 	case AR_CN_READY:
4192 		/* No external v6 resolver has a contract to use this */
4193 		if (isv6)
4194 			break;
4195 		/* If the link is down, we'll retry this later */
4196 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4197 			break;
4198 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4199 		    NULL, NULL);
4200 		if (ipif != NULL) {
4201 			/*
4202 			 * If this is a duplicate recovery, then we now need to
4203 			 * go exclusive to bring this thing back up.
4204 			 */
4205 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4206 			    IPIF_DUPLICATE) {
4207 				ipif_refrele(ipif);
4208 				ill_refhold(ill);
4209 				(void) qwriter_ip(NULL, ill, q, mp,
4210 				    ip_arp_excl, CUR_OP, B_FALSE);
4211 				return;
4212 			}
4213 			/*
4214 			 * If this is the first notice that this address is
4215 			 * ready, then let the user know now.
4216 			 */
4217 			if ((ipif->ipif_flags & IPIF_UP) &&
4218 			    !ipif->ipif_addr_ready) {
4219 				ipif_mask_reply(ipif);
4220 				ip_rts_ifmsg(ipif);
4221 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4222 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4223 			}
4224 			ipif->ipif_addr_ready = 1;
4225 			ipif_refrele(ipif);
4226 		}
4227 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp));
4228 		if (ire != NULL) {
4229 			ire->ire_defense_count = 0;
4230 			ire_refrele(ire);
4231 		}
4232 		break;
4233 	case AR_CN_FAILED:
4234 		/* No external v6 resolver has a contract to use this */
4235 		if (isv6)
4236 			break;
4237 		ill_refhold(ill);
4238 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4239 		    B_FALSE);
4240 		return;
4241 	}
4242 	freemsg(mp);
4243 }
4244 
4245 /*
4246  * Create a mblk suitable for carrying the interface index and/or source link
4247  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4248  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4249  * application.
4250  */
4251 mblk_t *
4252 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
4253 {
4254 	mblk_t		*mp;
4255 	in_pktinfo_t	*pinfo;
4256 	ipha_t *ipha;
4257 	struct ether_header *pether;
4258 
4259 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
4260 	if (mp == NULL) {
4261 		ip1dbg(("ip_add_info: allocation failure.\n"));
4262 		return (data_mp);
4263 	}
4264 
4265 	ipha	= (ipha_t *)data_mp->b_rptr;
4266 	pinfo = (in_pktinfo_t *)mp->b_rptr;
4267 	bzero(pinfo, sizeof (in_pktinfo_t));
4268 	pinfo->in_pkt_flags = (uchar_t)flags;
4269 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4270 
4271 	if (flags & IPF_RECVIF)
4272 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4273 
4274 	pether = (struct ether_header *)((char *)ipha
4275 	    - sizeof (struct ether_header));
4276 	/*
4277 	 * Make sure the interface is an ethernet type, since this option
4278 	 * is currently supported only on this type of interface. Also make
4279 	 * sure we are pointing correctly above db_base.
4280 	 */
4281 
4282 	if ((flags & IPF_RECVSLLA) &&
4283 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4284 	    (ill->ill_type == IFT_ETHER) &&
4285 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4286 
4287 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
4288 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4289 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
4290 	} else {
4291 		/*
4292 		 * Clear the bit. Indicate to upper layer that IP is not
4293 		 * sending this ancillary info.
4294 		 */
4295 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
4296 	}
4297 
4298 	mp->b_datap->db_type = M_CTL;
4299 	mp->b_wptr += sizeof (in_pktinfo_t);
4300 	mp->b_cont = data_mp;
4301 
4302 	return (mp);
4303 }
4304 
4305 /*
4306  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4307  * part of the bind request.
4308  */
4309 
4310 boolean_t
4311 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4312 {
4313 	ipsec_in_t *ii;
4314 
4315 	ASSERT(policy_mp != NULL);
4316 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4317 
4318 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4319 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4320 
4321 	connp->conn_policy = ii->ipsec_in_policy;
4322 	ii->ipsec_in_policy = NULL;
4323 
4324 	if (ii->ipsec_in_action != NULL) {
4325 		if (connp->conn_latch == NULL) {
4326 			connp->conn_latch = iplatch_create();
4327 			if (connp->conn_latch == NULL)
4328 				return (B_FALSE);
4329 		}
4330 		ipsec_latch_inbound(connp->conn_latch, ii);
4331 	}
4332 	return (B_TRUE);
4333 }
4334 
4335 /*
4336  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4337  * and to arrange for power-fanout assist.  The ULP is identified by
4338  * adding a single byte at the end of the original bind message.
4339  * A ULP other than UDP or TCP that wishes to be recognized passes
4340  * down a bind with a zero length address.
4341  *
4342  * The binding works as follows:
4343  * - A zero byte address means just bind to the protocol.
4344  * - A four byte address is treated as a request to validate
4345  *   that the address is a valid local address, appropriate for
4346  *   an application to bind to. This does not affect any fanout
4347  *   information in IP.
4348  * - A sizeof sin_t byte address is used to bind to only the local address
4349  *   and port.
4350  * - A sizeof ipa_conn_t byte address contains complete fanout information
4351  *   consisting of local and remote addresses and ports.  In
4352  *   this case, the addresses are both validated as appropriate
4353  *   for this operation, and, if so, the information is retained
4354  *   for use in the inbound fanout.
4355  *
4356  * The ULP (except in the zero-length bind) can append an
4357  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4358  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4359  * a copy of the source or destination IRE (source for local bind;
4360  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4361  * policy information contained should be copied on to the conn.
4362  *
4363  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4364  */
4365 mblk_t *
4366 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4367 {
4368 	ssize_t		len;
4369 	struct T_bind_req	*tbr;
4370 	sin_t		*sin;
4371 	ipa_conn_t	*ac;
4372 	uchar_t		*ucp;
4373 	mblk_t		*mp1;
4374 	boolean_t	ire_requested;
4375 	boolean_t	ipsec_policy_set = B_FALSE;
4376 	int		error = 0;
4377 	int		protocol;
4378 	ipa_conn_x_t	*acx;
4379 
4380 	ASSERT(!connp->conn_af_isv6);
4381 	connp->conn_pkt_isv6 = B_FALSE;
4382 
4383 	len = MBLKL(mp);
4384 	if (len < (sizeof (*tbr) + 1)) {
4385 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4386 		    "ip_bind: bogus msg, len %ld", len);
4387 		/* XXX: Need to return something better */
4388 		goto bad_addr;
4389 	}
4390 	/* Back up and extract the protocol identifier. */
4391 	mp->b_wptr--;
4392 	protocol = *mp->b_wptr & 0xFF;
4393 	tbr = (struct T_bind_req *)mp->b_rptr;
4394 	/* Reset the message type in preparation for shipping it back. */
4395 	DB_TYPE(mp) = M_PCPROTO;
4396 
4397 	connp->conn_ulp = (uint8_t)protocol;
4398 
4399 	/*
4400 	 * Check for a zero length address.  This is from a protocol that
4401 	 * wants to register to receive all packets of its type.
4402 	 */
4403 	if (tbr->ADDR_length == 0) {
4404 		/*
4405 		 * These protocols are now intercepted in ip_bind_v6().
4406 		 * Reject protocol-level binds here for now.
4407 		 *
4408 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4409 		 * so that the protocol type cannot be SCTP.
4410 		 */
4411 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4412 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4413 			goto bad_addr;
4414 		}
4415 
4416 		/*
4417 		 *
4418 		 * The udp module never sends down a zero-length address,
4419 		 * and allowing this on a labeled system will break MLP
4420 		 * functionality.
4421 		 */
4422 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4423 			goto bad_addr;
4424 
4425 		if (connp->conn_mac_exempt)
4426 			goto bad_addr;
4427 
4428 		/* No hash here really.  The table is big enough. */
4429 		connp->conn_srcv6 = ipv6_all_zeros;
4430 
4431 		ipcl_proto_insert(connp, protocol);
4432 
4433 		tbr->PRIM_type = T_BIND_ACK;
4434 		return (mp);
4435 	}
4436 
4437 	/* Extract the address pointer from the message. */
4438 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4439 	    tbr->ADDR_length);
4440 	if (ucp == NULL) {
4441 		ip1dbg(("ip_bind: no address\n"));
4442 		goto bad_addr;
4443 	}
4444 	if (!OK_32PTR(ucp)) {
4445 		ip1dbg(("ip_bind: unaligned address\n"));
4446 		goto bad_addr;
4447 	}
4448 	/*
4449 	 * Check for trailing mps.
4450 	 */
4451 
4452 	mp1 = mp->b_cont;
4453 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4454 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4455 
4456 	switch (tbr->ADDR_length) {
4457 	default:
4458 		ip1dbg(("ip_bind: bad address length %d\n",
4459 		    (int)tbr->ADDR_length));
4460 		goto bad_addr;
4461 
4462 	case IP_ADDR_LEN:
4463 		/* Verification of local address only */
4464 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4465 		    ire_requested, ipsec_policy_set, B_FALSE);
4466 		break;
4467 
4468 	case sizeof (sin_t):
4469 		sin = (sin_t *)ucp;
4470 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4471 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4472 		if (protocol == IPPROTO_TCP)
4473 			connp->conn_recv = tcp_conn_request;
4474 		break;
4475 
4476 	case sizeof (ipa_conn_t):
4477 		ac = (ipa_conn_t *)ucp;
4478 		/* For raw socket, the local port is not set. */
4479 		if (ac->ac_lport == 0)
4480 			ac->ac_lport = connp->conn_lport;
4481 		/* Always verify destination reachability. */
4482 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4483 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4484 		    ipsec_policy_set, B_TRUE, B_TRUE);
4485 		if (protocol == IPPROTO_TCP)
4486 			connp->conn_recv = tcp_input;
4487 		break;
4488 
4489 	case sizeof (ipa_conn_x_t):
4490 		acx = (ipa_conn_x_t *)ucp;
4491 		/*
4492 		 * Whether or not to verify destination reachability depends
4493 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4494 		 */
4495 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4496 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4497 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4498 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4499 		if (protocol == IPPROTO_TCP)
4500 			connp->conn_recv = tcp_input;
4501 		break;
4502 	}
4503 	if (error == EINPROGRESS)
4504 		return (NULL);
4505 	else if (error != 0)
4506 		goto bad_addr;
4507 	/*
4508 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4509 	 * We can't do this in ip_bind_insert_ire because the policy
4510 	 * may not have been inherited at that point in time and hence
4511 	 * conn_out_enforce_policy may not be set.
4512 	 */
4513 	mp1 = mp->b_cont;
4514 	if (ire_requested && connp->conn_out_enforce_policy &&
4515 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4516 		ire_t *ire = (ire_t *)mp1->b_rptr;
4517 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4518 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4519 	}
4520 
4521 	/* Send it home. */
4522 	mp->b_datap->db_type = M_PCPROTO;
4523 	tbr->PRIM_type = T_BIND_ACK;
4524 	return (mp);
4525 
4526 bad_addr:
4527 	/*
4528 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4529 	 * a unix errno.
4530 	 */
4531 	if (error > 0)
4532 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4533 	else
4534 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4535 	return (mp);
4536 }
4537 
4538 /*
4539  * Here address is verified to be a valid local address.
4540  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4541  * address is also considered a valid local address.
4542  * In the case of a broadcast/multicast address, however, the
4543  * upper protocol is expected to reset the src address
4544  * to 0 if it sees a IRE_BROADCAST type returned so that
4545  * no packets are emitted with broadcast/multicast address as
4546  * source address (that violates hosts requirements RFC1122)
4547  * The addresses valid for bind are:
4548  *	(1) - INADDR_ANY (0)
4549  *	(2) - IP address of an UP interface
4550  *	(3) - IP address of a DOWN interface
4551  *	(4) - valid local IP broadcast addresses. In this case
4552  *	the conn will only receive packets destined to
4553  *	the specified broadcast address.
4554  *	(5) - a multicast address. In this case
4555  *	the conn will only receive packets destined to
4556  *	the specified multicast address. Note: the
4557  *	application still has to issue an
4558  *	IP_ADD_MEMBERSHIP socket option.
4559  *
4560  * On error, return -1 for TBADADDR otherwise pass the
4561  * errno with TSYSERR reply.
4562  *
4563  * In all the above cases, the bound address must be valid in the current zone.
4564  * When the address is loopback, multicast or broadcast, there might be many
4565  * matching IREs so bind has to look up based on the zone.
4566  *
4567  * Note: lport is in network byte order.
4568  */
4569 int
4570 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4571     boolean_t ire_requested, boolean_t ipsec_policy_set,
4572     boolean_t fanout_insert)
4573 {
4574 	int		error = 0;
4575 	ire_t		*src_ire;
4576 	mblk_t		*policy_mp;
4577 	ipif_t		*ipif;
4578 	zoneid_t	zoneid;
4579 
4580 	if (ipsec_policy_set) {
4581 		policy_mp = mp->b_cont;
4582 	}
4583 
4584 	/*
4585 	 * If it was previously connected, conn_fully_bound would have
4586 	 * been set.
4587 	 */
4588 	connp->conn_fully_bound = B_FALSE;
4589 
4590 	src_ire = NULL;
4591 	ipif = NULL;
4592 
4593 	zoneid = IPCL_ZONEID(connp);
4594 
4595 	if (src_addr) {
4596 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4597 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4598 		/*
4599 		 * If an address other than 0.0.0.0 is requested,
4600 		 * we verify that it is a valid address for bind
4601 		 * Note: Following code is in if-else-if form for
4602 		 * readability compared to a condition check.
4603 		 */
4604 		/* LINTED - statement has no consequent */
4605 		if (IRE_IS_LOCAL(src_ire)) {
4606 			/*
4607 			 * (2) Bind to address of local UP interface
4608 			 */
4609 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4610 			/*
4611 			 * (4) Bind to broadcast address
4612 			 * Note: permitted only from transports that
4613 			 * request IRE
4614 			 */
4615 			if (!ire_requested)
4616 				error = EADDRNOTAVAIL;
4617 		} else {
4618 			/*
4619 			 * (3) Bind to address of local DOWN interface
4620 			 * (ipif_lookup_addr() looks up all interfaces
4621 			 * but we do not get here for UP interfaces
4622 			 * - case (2) above)
4623 			 * We put the protocol byte back into the mblk
4624 			 * since we may come back via ip_wput_nondata()
4625 			 * later with this mblk if ipif_lookup_addr chooses
4626 			 * to defer processing.
4627 			 */
4628 			*mp->b_wptr++ = (char)connp->conn_ulp;
4629 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4630 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4631 			    &error)) != NULL) {
4632 				ipif_refrele(ipif);
4633 			} else if (error == EINPROGRESS) {
4634 				if (src_ire != NULL)
4635 					ire_refrele(src_ire);
4636 				return (EINPROGRESS);
4637 			} else if (CLASSD(src_addr)) {
4638 				error = 0;
4639 				if (src_ire != NULL)
4640 					ire_refrele(src_ire);
4641 				/*
4642 				 * (5) bind to multicast address.
4643 				 * Fake out the IRE returned to upper
4644 				 * layer to be a broadcast IRE.
4645 				 */
4646 				src_ire = ire_ctable_lookup(
4647 				    INADDR_BROADCAST, INADDR_ANY,
4648 				    IRE_BROADCAST, NULL, zoneid, NULL,
4649 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4650 				if (src_ire == NULL || !ire_requested)
4651 					error = EADDRNOTAVAIL;
4652 			} else {
4653 				/*
4654 				 * Not a valid address for bind
4655 				 */
4656 				error = EADDRNOTAVAIL;
4657 			}
4658 			/*
4659 			 * Just to keep it consistent with the processing in
4660 			 * ip_bind_v4()
4661 			 */
4662 			mp->b_wptr--;
4663 		}
4664 		if (error) {
4665 			/* Red Alert!  Attempting to be a bogon! */
4666 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4667 			    ntohl(src_addr)));
4668 			goto bad_addr;
4669 		}
4670 	}
4671 
4672 	/*
4673 	 * Allow setting new policies. For example, disconnects come
4674 	 * down as ipa_t bind. As we would have set conn_policy_cached
4675 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4676 	 * can change after the disconnect.
4677 	 */
4678 	connp->conn_policy_cached = B_FALSE;
4679 
4680 	/*
4681 	 * If not fanout_insert this was just an address verification
4682 	 */
4683 	if (fanout_insert) {
4684 		/*
4685 		 * The addresses have been verified. Time to insert in
4686 		 * the correct fanout list.
4687 		 */
4688 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4689 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4690 		connp->conn_lport = lport;
4691 		connp->conn_fport = 0;
4692 		/*
4693 		 * Do we need to add a check to reject Multicast packets
4694 		 */
4695 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4696 	}
4697 
4698 	if (error == 0) {
4699 		if (ire_requested) {
4700 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4701 				error = -1;
4702 				/* Falls through to bad_addr */
4703 			}
4704 		} else if (ipsec_policy_set) {
4705 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4706 				error = -1;
4707 				/* Falls through to bad_addr */
4708 			}
4709 		}
4710 	}
4711 bad_addr:
4712 	if (error != 0) {
4713 		if (connp->conn_anon_port) {
4714 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4715 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4716 			    B_FALSE);
4717 		}
4718 		connp->conn_mlp_type = mlptSingle;
4719 	}
4720 	if (src_ire != NULL)
4721 		IRE_REFRELE(src_ire);
4722 	if (ipsec_policy_set) {
4723 		ASSERT(policy_mp == mp->b_cont);
4724 		ASSERT(policy_mp != NULL);
4725 		freeb(policy_mp);
4726 		/*
4727 		 * As of now assume that nothing else accompanies
4728 		 * IPSEC_POLICY_SET.
4729 		 */
4730 		mp->b_cont = NULL;
4731 	}
4732 	return (error);
4733 }
4734 
4735 /*
4736  * Verify that both the source and destination addresses
4737  * are valid.  If verify_dst is false, then the destination address may be
4738  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4739  * destination reachability, while tunnels do not.
4740  * Note that we allow connect to broadcast and multicast
4741  * addresses when ire_requested is set. Thus the ULP
4742  * has to check for IRE_BROADCAST and multicast.
4743  *
4744  * Returns zero if ok.
4745  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4746  * (for use with TSYSERR reply).
4747  *
4748  * Note: lport and fport are in network byte order.
4749  */
4750 int
4751 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4752     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4753     boolean_t ire_requested, boolean_t ipsec_policy_set,
4754     boolean_t fanout_insert, boolean_t verify_dst)
4755 {
4756 	ire_t		*src_ire;
4757 	ire_t		*dst_ire;
4758 	int		error = 0;
4759 	int 		protocol;
4760 	mblk_t		*policy_mp;
4761 	ire_t		*sire = NULL;
4762 	ire_t		*md_dst_ire = NULL;
4763 	ill_t		*md_ill = NULL;
4764 	zoneid_t	zoneid;
4765 	ipaddr_t	src_addr = *src_addrp;
4766 
4767 	src_ire = dst_ire = NULL;
4768 	protocol = *mp->b_wptr & 0xFF;
4769 
4770 	/*
4771 	 * If we never got a disconnect before, clear it now.
4772 	 */
4773 	connp->conn_fully_bound = B_FALSE;
4774 
4775 	if (ipsec_policy_set) {
4776 		policy_mp = mp->b_cont;
4777 	}
4778 
4779 	zoneid = IPCL_ZONEID(connp);
4780 
4781 	if (CLASSD(dst_addr)) {
4782 		/* Pick up an IRE_BROADCAST */
4783 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4784 		    NULL, zoneid, MBLK_GETLABEL(mp),
4785 		    (MATCH_IRE_RECURSIVE |
4786 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4787 		    MATCH_IRE_SECATTR));
4788 	} else {
4789 		/*
4790 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4791 		 * and onlink ipif is not found set ENETUNREACH error.
4792 		 */
4793 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4794 			ipif_t *ipif;
4795 
4796 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4797 			    dst_addr : connp->conn_nexthop_v4,
4798 			    connp->conn_zoneid);
4799 			if (ipif == NULL) {
4800 				error = ENETUNREACH;
4801 				goto bad_addr;
4802 			}
4803 			ipif_refrele(ipif);
4804 		}
4805 
4806 		if (connp->conn_nexthop_set) {
4807 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4808 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4809 			    MATCH_IRE_SECATTR);
4810 		} else {
4811 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4812 			    &sire, zoneid, MBLK_GETLABEL(mp),
4813 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4814 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4815 			    MATCH_IRE_SECATTR));
4816 		}
4817 	}
4818 	/*
4819 	 * dst_ire can't be a broadcast when not ire_requested.
4820 	 * We also prevent ire's with src address INADDR_ANY to
4821 	 * be used, which are created temporarily for
4822 	 * sending out packets from endpoints that have
4823 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4824 	 * reachable.  If verify_dst is false, the destination needn't be
4825 	 * reachable.
4826 	 *
4827 	 * If we match on a reject or black hole, then we've got a
4828 	 * local failure.  May as well fail out the connect() attempt,
4829 	 * since it's never going to succeed.
4830 	 */
4831 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4832 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4833 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4834 		/*
4835 		 * If we're verifying destination reachability, we always want
4836 		 * to complain here.
4837 		 *
4838 		 * If we're not verifying destination reachability but the
4839 		 * destination has a route, we still want to fail on the
4840 		 * temporary address and broadcast address tests.
4841 		 */
4842 		if (verify_dst || (dst_ire != NULL)) {
4843 			if (ip_debug > 2) {
4844 				pr_addr_dbg("ip_bind_connected: bad connected "
4845 				    "dst %s\n", AF_INET, &dst_addr);
4846 			}
4847 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4848 				error = ENETUNREACH;
4849 			else
4850 				error = EHOSTUNREACH;
4851 			goto bad_addr;
4852 		}
4853 	}
4854 
4855 	/*
4856 	 * We now know that routing will allow us to reach the destination.
4857 	 * Check whether Trusted Solaris policy allows communication with this
4858 	 * host, and pretend that the destination is unreachable if not.
4859 	 *
4860 	 * This is never a problem for TCP, since that transport is known to
4861 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4862 	 * handling.  If the remote is unreachable, it will be detected at that
4863 	 * point, so there's no reason to check it here.
4864 	 *
4865 	 * Note that for sendto (and other datagram-oriented friends), this
4866 	 * check is done as part of the data path label computation instead.
4867 	 * The check here is just to make non-TCP connect() report the right
4868 	 * error.
4869 	 */
4870 	if (dst_ire != NULL && is_system_labeled() &&
4871 	    !IPCL_IS_TCP(connp) &&
4872 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4873 	    connp->conn_mac_exempt) != 0) {
4874 		error = EHOSTUNREACH;
4875 		if (ip_debug > 2) {
4876 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4877 			    AF_INET, &dst_addr);
4878 		}
4879 		goto bad_addr;
4880 	}
4881 
4882 	/*
4883 	 * If the app does a connect(), it means that it will most likely
4884 	 * send more than 1 packet to the destination.  It makes sense
4885 	 * to clear the temporary flag.
4886 	 */
4887 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4888 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4889 		irb_t *irb = dst_ire->ire_bucket;
4890 
4891 		rw_enter(&irb->irb_lock, RW_WRITER);
4892 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4893 		irb->irb_tmp_ire_cnt--;
4894 		rw_exit(&irb->irb_lock);
4895 	}
4896 
4897 	/*
4898 	 * See if we should notify ULP about MDT; we do this whether or not
4899 	 * ire_requested is TRUE, in order to handle active connects; MDT
4900 	 * eligibility tests for passive connects are handled separately
4901 	 * through tcp_adapt_ire().  We do this before the source address
4902 	 * selection, because dst_ire may change after a call to
4903 	 * ipif_select_source().  This is a best-effort check, as the
4904 	 * packet for this connection may not actually go through
4905 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4906 	 * calling ip_newroute().  This is why we further check on the
4907 	 * IRE during Multidata packet transmission in tcp_multisend().
4908 	 */
4909 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4910 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4911 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4912 	    ILL_MDT_CAPABLE(md_ill)) {
4913 		md_dst_ire = dst_ire;
4914 		IRE_REFHOLD(md_dst_ire);
4915 	}
4916 
4917 	if (dst_ire != NULL &&
4918 	    dst_ire->ire_type == IRE_LOCAL &&
4919 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4920 		/*
4921 		 * If the IRE belongs to a different zone, look for a matching
4922 		 * route in the forwarding table and use the source address from
4923 		 * that route.
4924 		 */
4925 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4926 		    zoneid, 0, NULL,
4927 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4928 		    MATCH_IRE_RJ_BHOLE);
4929 		if (src_ire == NULL) {
4930 			error = EHOSTUNREACH;
4931 			goto bad_addr;
4932 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4933 			if (!(src_ire->ire_type & IRE_HOST))
4934 				error = ENETUNREACH;
4935 			else
4936 				error = EHOSTUNREACH;
4937 			goto bad_addr;
4938 		}
4939 		if (src_addr == INADDR_ANY)
4940 			src_addr = src_ire->ire_src_addr;
4941 		ire_refrele(src_ire);
4942 		src_ire = NULL;
4943 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4944 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4945 			src_addr = sire->ire_src_addr;
4946 			ire_refrele(dst_ire);
4947 			dst_ire = sire;
4948 			sire = NULL;
4949 		} else {
4950 			/*
4951 			 * Pick a source address so that a proper inbound
4952 			 * load spreading would happen.
4953 			 */
4954 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4955 			ipif_t *src_ipif = NULL;
4956 			ire_t *ipif_ire;
4957 
4958 			/*
4959 			 * Supply a local source address such that inbound
4960 			 * load spreading happens.
4961 			 *
4962 			 * Determine the best source address on this ill for
4963 			 * the destination.
4964 			 *
4965 			 * 1) For broadcast, we should return a broadcast ire
4966 			 *    found above so that upper layers know that the
4967 			 *    destination address is a broadcast address.
4968 			 *
4969 			 * 2) If this is part of a group, select a better
4970 			 *    source address so that better inbound load
4971 			 *    balancing happens. Do the same if the ipif
4972 			 *    is DEPRECATED.
4973 			 *
4974 			 * 3) If the outgoing interface is part of a usesrc
4975 			 *    group, then try selecting a source address from
4976 			 *    the usesrc ILL.
4977 			 */
4978 			if ((dst_ire->ire_zoneid != zoneid &&
4979 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4980 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4981 			    ((dst_ill->ill_group != NULL) ||
4982 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4983 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4984 				/*
4985 				 * If the destination is reachable via a
4986 				 * given gateway, the selected source address
4987 				 * should be in the same subnet as the gateway.
4988 				 * Otherwise, the destination is not reachable.
4989 				 *
4990 				 * If there are no interfaces on the same subnet
4991 				 * as the destination, ipif_select_source gives
4992 				 * first non-deprecated interface which might be
4993 				 * on a different subnet than the gateway.
4994 				 * This is not desirable. Hence pass the dst_ire
4995 				 * source address to ipif_select_source.
4996 				 * It is sure that the destination is reachable
4997 				 * with the dst_ire source address subnet.
4998 				 * So passing dst_ire source address to
4999 				 * ipif_select_source will make sure that the
5000 				 * selected source will be on the same subnet
5001 				 * as dst_ire source address.
5002 				 */
5003 				ipaddr_t saddr =
5004 				    dst_ire->ire_ipif->ipif_src_addr;
5005 				src_ipif = ipif_select_source(dst_ill,
5006 				    saddr, zoneid);
5007 				if (src_ipif != NULL) {
5008 					if (IS_VNI(src_ipif->ipif_ill)) {
5009 						/*
5010 						 * For VNI there is no
5011 						 * interface route
5012 						 */
5013 						src_addr =
5014 						    src_ipif->ipif_src_addr;
5015 					} else {
5016 						ipif_ire =
5017 						    ipif_to_ire(src_ipif);
5018 						if (ipif_ire != NULL) {
5019 							IRE_REFRELE(dst_ire);
5020 							dst_ire = ipif_ire;
5021 						}
5022 						src_addr =
5023 						    dst_ire->ire_src_addr;
5024 					}
5025 					ipif_refrele(src_ipif);
5026 				} else {
5027 					src_addr = dst_ire->ire_src_addr;
5028 				}
5029 			} else {
5030 				src_addr = dst_ire->ire_src_addr;
5031 			}
5032 		}
5033 	}
5034 
5035 	/*
5036 	 * We do ire_route_lookup() here (and not
5037 	 * interface lookup as we assert that
5038 	 * src_addr should only come from an
5039 	 * UP interface for hard binding.
5040 	 */
5041 	ASSERT(src_ire == NULL);
5042 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5043 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
5044 	/* src_ire must be a local|loopback */
5045 	if (!IRE_IS_LOCAL(src_ire)) {
5046 		if (ip_debug > 2) {
5047 			pr_addr_dbg("ip_bind_connected: bad connected "
5048 			    "src %s\n", AF_INET, &src_addr);
5049 		}
5050 		error = EADDRNOTAVAIL;
5051 		goto bad_addr;
5052 	}
5053 
5054 	/*
5055 	 * If the source address is a loopback address, the
5056 	 * destination had best be local or multicast.
5057 	 * The transports that can't handle multicast will reject
5058 	 * those addresses.
5059 	 */
5060 	if (src_ire->ire_type == IRE_LOOPBACK &&
5061 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5062 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5063 		error = -1;
5064 		goto bad_addr;
5065 	}
5066 
5067 	/*
5068 	 * Allow setting new policies. For example, disconnects come
5069 	 * down as ipa_t bind. As we would have set conn_policy_cached
5070 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5071 	 * can change after the disconnect.
5072 	 */
5073 	connp->conn_policy_cached = B_FALSE;
5074 
5075 	/*
5076 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5077 	 * can handle their passed-in conn's.
5078 	 */
5079 
5080 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5081 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5082 	connp->conn_lport = lport;
5083 	connp->conn_fport = fport;
5084 	*src_addrp = src_addr;
5085 
5086 	ASSERT(!(ipsec_policy_set && ire_requested));
5087 	if (ire_requested) {
5088 		iulp_t *ulp_info = NULL;
5089 
5090 		/*
5091 		 * Note that sire will not be NULL if this is an off-link
5092 		 * connection and there is not cache for that dest yet.
5093 		 *
5094 		 * XXX Because of an existing bug, if there are multiple
5095 		 * default routes, the IRE returned now may not be the actual
5096 		 * default route used (default routes are chosen in a
5097 		 * round robin fashion).  So if the metrics for different
5098 		 * default routes are different, we may return the wrong
5099 		 * metrics.  This will not be a problem if the existing
5100 		 * bug is fixed.
5101 		 */
5102 		if (sire != NULL) {
5103 			ulp_info = &(sire->ire_uinfo);
5104 		}
5105 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5106 			error = -1;
5107 			goto bad_addr;
5108 		}
5109 	} else if (ipsec_policy_set) {
5110 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5111 			error = -1;
5112 			goto bad_addr;
5113 		}
5114 	}
5115 
5116 	/*
5117 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5118 	 * we'll cache that.  If we don't, we'll inherit global policy.
5119 	 *
5120 	 * We can't insert until the conn reflects the policy. Note that
5121 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5122 	 * connections where we don't have a policy. This is to prevent
5123 	 * global policy lookups in the inbound path.
5124 	 *
5125 	 * If we insert before we set conn_policy_cached,
5126 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5127 	 * because global policy cound be non-empty. We normally call
5128 	 * ipsec_check_policy() for conn_policy_cached connections only if
5129 	 * ipc_in_enforce_policy is set. But in this case,
5130 	 * conn_policy_cached can get set anytime since we made the
5131 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5132 	 * called, which will make the above assumption false.  Thus, we
5133 	 * need to insert after we set conn_policy_cached.
5134 	 */
5135 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5136 		goto bad_addr;
5137 
5138 	if (fanout_insert) {
5139 		/*
5140 		 * The addresses have been verified. Time to insert in
5141 		 * the correct fanout list.
5142 		 */
5143 		error = ipcl_conn_insert(connp, protocol, src_addr,
5144 		    dst_addr, connp->conn_ports);
5145 	}
5146 
5147 	if (error == 0) {
5148 		connp->conn_fully_bound = B_TRUE;
5149 		/*
5150 		 * Our initial checks for MDT have passed; the IRE is not
5151 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5152 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
5153 		 * ip_mdinfo_return(), which performs further checks
5154 		 * against them and upon success, returns the MDT info
5155 		 * mblk which we will attach to the bind acknowledgment.
5156 		 */
5157 		if (md_dst_ire != NULL) {
5158 			mblk_t *mdinfo_mp;
5159 
5160 			ASSERT(md_ill != NULL);
5161 			ASSERT(md_ill->ill_mdt_capab != NULL);
5162 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5163 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
5164 				linkb(mp, mdinfo_mp);
5165 		}
5166 	}
5167 bad_addr:
5168 	if (ipsec_policy_set) {
5169 		ASSERT(policy_mp == mp->b_cont);
5170 		ASSERT(policy_mp != NULL);
5171 		freeb(policy_mp);
5172 		/*
5173 		 * As of now assume that nothing else accompanies
5174 		 * IPSEC_POLICY_SET.
5175 		 */
5176 		mp->b_cont = NULL;
5177 	}
5178 	if (src_ire != NULL)
5179 		IRE_REFRELE(src_ire);
5180 	if (dst_ire != NULL)
5181 		IRE_REFRELE(dst_ire);
5182 	if (sire != NULL)
5183 		IRE_REFRELE(sire);
5184 	if (md_dst_ire != NULL)
5185 		IRE_REFRELE(md_dst_ire);
5186 	return (error);
5187 }
5188 
5189 /*
5190  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5191  * Prefers dst_ire over src_ire.
5192  */
5193 static boolean_t
5194 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5195 {
5196 	mblk_t	*mp1;
5197 	ire_t *ret_ire = NULL;
5198 
5199 	mp1 = mp->b_cont;
5200 	ASSERT(mp1 != NULL);
5201 
5202 	if (ire != NULL) {
5203 		/*
5204 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5205 		 * appended mblk. Its <upper protocol>'s
5206 		 * job to make sure there is room.
5207 		 */
5208 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5209 			return (0);
5210 
5211 		mp1->b_datap->db_type = IRE_DB_TYPE;
5212 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5213 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5214 		ret_ire = (ire_t *)mp1->b_rptr;
5215 		/*
5216 		 * Pass the latest setting of the ip_path_mtu_discovery and
5217 		 * copy the ulp info if any.
5218 		 */
5219 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5220 		    IPH_DF : 0;
5221 		if (ulp_info != NULL) {
5222 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5223 			    sizeof (iulp_t));
5224 		}
5225 		ret_ire->ire_mp = mp1;
5226 	} else {
5227 		/*
5228 		 * No IRE was found. Remove IRE mblk.
5229 		 */
5230 		mp->b_cont = mp1->b_cont;
5231 		freeb(mp1);
5232 	}
5233 
5234 	return (1);
5235 }
5236 
5237 /*
5238  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5239  * the final piece where we don't.  Return a pointer to the first mblk in the
5240  * result, and update the pointer to the next mblk to chew on.  If anything
5241  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5242  * NULL pointer.
5243  */
5244 mblk_t *
5245 ip_carve_mp(mblk_t **mpp, ssize_t len)
5246 {
5247 	mblk_t	*mp0;
5248 	mblk_t	*mp1;
5249 	mblk_t	*mp2;
5250 
5251 	if (!len || !mpp || !(mp0 = *mpp))
5252 		return (NULL);
5253 	/* If we aren't going to consume the first mblk, we need a dup. */
5254 	if (mp0->b_wptr - mp0->b_rptr > len) {
5255 		mp1 = dupb(mp0);
5256 		if (mp1) {
5257 			/* Partition the data between the two mblks. */
5258 			mp1->b_wptr = mp1->b_rptr + len;
5259 			mp0->b_rptr = mp1->b_wptr;
5260 			/*
5261 			 * after adjustments if mblk not consumed is now
5262 			 * unaligned, try to align it. If this fails free
5263 			 * all messages and let upper layer recover.
5264 			 */
5265 			if (!OK_32PTR(mp0->b_rptr)) {
5266 				if (!pullupmsg(mp0, -1)) {
5267 					freemsg(mp0);
5268 					freemsg(mp1);
5269 					*mpp = NULL;
5270 					return (NULL);
5271 				}
5272 			}
5273 		}
5274 		return (mp1);
5275 	}
5276 	/* Eat through as many mblks as we need to get len bytes. */
5277 	len -= mp0->b_wptr - mp0->b_rptr;
5278 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5279 		if (mp2->b_wptr - mp2->b_rptr > len) {
5280 			/*
5281 			 * We won't consume the entire last mblk.  Like
5282 			 * above, dup and partition it.
5283 			 */
5284 			mp1->b_cont = dupb(mp2);
5285 			mp1 = mp1->b_cont;
5286 			if (!mp1) {
5287 				/*
5288 				 * Trouble.  Rather than go to a lot of
5289 				 * trouble to clean up, we free the messages.
5290 				 * This won't be any worse than losing it on
5291 				 * the wire.
5292 				 */
5293 				freemsg(mp0);
5294 				freemsg(mp2);
5295 				*mpp = NULL;
5296 				return (NULL);
5297 			}
5298 			mp1->b_wptr = mp1->b_rptr + len;
5299 			mp2->b_rptr = mp1->b_wptr;
5300 			/*
5301 			 * after adjustments if mblk not consumed is now
5302 			 * unaligned, try to align it. If this fails free
5303 			 * all messages and let upper layer recover.
5304 			 */
5305 			if (!OK_32PTR(mp2->b_rptr)) {
5306 				if (!pullupmsg(mp2, -1)) {
5307 					freemsg(mp0);
5308 					freemsg(mp2);
5309 					*mpp = NULL;
5310 					return (NULL);
5311 				}
5312 			}
5313 			*mpp = mp2;
5314 			return (mp0);
5315 		}
5316 		/* Decrement len by the amount we just got. */
5317 		len -= mp2->b_wptr - mp2->b_rptr;
5318 	}
5319 	/*
5320 	 * len should be reduced to zero now.  If not our caller has
5321 	 * screwed up.
5322 	 */
5323 	if (len) {
5324 		/* Shouldn't happen! */
5325 		freemsg(mp0);
5326 		*mpp = NULL;
5327 		return (NULL);
5328 	}
5329 	/*
5330 	 * We consumed up to exactly the end of an mblk.  Detach the part
5331 	 * we are returning from the rest of the chain.
5332 	 */
5333 	mp1->b_cont = NULL;
5334 	*mpp = mp2;
5335 	return (mp0);
5336 }
5337 
5338 /* The ill stream is being unplumbed. Called from ip_close */
5339 int
5340 ip_modclose(ill_t *ill)
5341 {
5342 
5343 	boolean_t success;
5344 	ipsq_t	*ipsq;
5345 	ipif_t	*ipif;
5346 	queue_t	*q = ill->ill_rq;
5347 	hook_nic_event_t *info;
5348 
5349 	/*
5350 	 * Forcibly enter the ipsq after some delay. This is to take
5351 	 * care of the case when some ioctl does not complete because
5352 	 * we sent a control message to the driver and it did not
5353 	 * send us a reply. We want to be able to at least unplumb
5354 	 * and replumb rather than force the user to reboot the system.
5355 	 */
5356 	success = ipsq_enter(ill, B_FALSE);
5357 
5358 	/*
5359 	 * Open/close/push/pop is guaranteed to be single threaded
5360 	 * per stream by STREAMS. FS guarantees that all references
5361 	 * from top are gone before close is called. So there can't
5362 	 * be another close thread that has set CONDEMNED on this ill.
5363 	 * and cause ipsq_enter to return failure.
5364 	 */
5365 	ASSERT(success);
5366 	ipsq = ill->ill_phyint->phyint_ipsq;
5367 
5368 	/*
5369 	 * Mark it condemned. No new reference will be made to this ill.
5370 	 * Lookup functions will return an error. Threads that try to
5371 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5372 	 * that the refcnt will drop down to zero.
5373 	 */
5374 	mutex_enter(&ill->ill_lock);
5375 	ill->ill_state_flags |= ILL_CONDEMNED;
5376 	for (ipif = ill->ill_ipif; ipif != NULL;
5377 	    ipif = ipif->ipif_next) {
5378 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5379 	}
5380 	/*
5381 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5382 	 * returns  error if ILL_CONDEMNED is set
5383 	 */
5384 	cv_broadcast(&ill->ill_cv);
5385 	mutex_exit(&ill->ill_lock);
5386 
5387 	/*
5388 	 * Shut down fragmentation reassembly.
5389 	 * ill_frag_timer won't start a timer again.
5390 	 * Now cancel any existing timer
5391 	 */
5392 	(void) untimeout(ill->ill_frag_timer_id);
5393 	(void) ill_frag_timeout(ill, 0);
5394 
5395 	/*
5396 	 * If MOVE was in progress, clear the
5397 	 * move_in_progress fields also.
5398 	 */
5399 	if (ill->ill_move_in_progress) {
5400 		ILL_CLEAR_MOVE(ill);
5401 	}
5402 
5403 	/*
5404 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5405 	 * this ill. Then wait for the refcnts to drop to zero.
5406 	 * ill_is_quiescent checks whether the ill is really quiescent.
5407 	 * Then make sure that threads that are waiting to enter the
5408 	 * ipsq have seen the error returned by ipsq_enter and have
5409 	 * gone away. Then we call ill_delete_tail which does the
5410 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5411 	 */
5412 	ill_delete(ill);
5413 	mutex_enter(&ill->ill_lock);
5414 	while (!ill_is_quiescent(ill))
5415 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5416 	while (ill->ill_waiters)
5417 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5418 
5419 	mutex_exit(&ill->ill_lock);
5420 
5421 	/* qprocsoff is called in ill_delete_tail */
5422 	ill_delete_tail(ill);
5423 
5424 	/*
5425 	 * Walk through all upper (conn) streams and qenable
5426 	 * those that have queued data.
5427 	 * close synchronization needs this to
5428 	 * be done to ensure that all upper layers blocked
5429 	 * due to flow control to the closing device
5430 	 * get unblocked.
5431 	 */
5432 	ip1dbg(("ip_wsrv: walking\n"));
5433 	conn_walk_drain();
5434 
5435 	mutex_enter(&ip_mi_lock);
5436 	mi_close_unlink(&ip_g_head, (IDP)ill);
5437 	mutex_exit(&ip_mi_lock);
5438 
5439 	/*
5440 	 * credp could be null if the open didn't succeed and ip_modopen
5441 	 * itself calls ip_close.
5442 	 */
5443 	if (ill->ill_credp != NULL)
5444 		crfree(ill->ill_credp);
5445 
5446 	/*
5447 	 * Unhook the nic event message from the ill and enqueue it into the nic
5448 	 * event taskq.
5449 	 */
5450 	if ((info = ill->ill_nic_event_info) != NULL) {
5451 		if (ddi_taskq_dispatch(eventq_queue_nic, ip_ne_queue_func,
5452 		    (void *)info, DDI_SLEEP) == DDI_FAILURE) {
5453 			ip2dbg(("ip_ioctl_finish:ddi_taskq_dispatch failed\n"));
5454 			if (info->hne_data != NULL)
5455 				kmem_free(info->hne_data, info->hne_datalen);
5456 			kmem_free(info, sizeof (hook_nic_event_t));
5457 		}
5458 		ill->ill_nic_event_info = NULL;
5459 	}
5460 
5461 	mi_close_free((IDP)ill);
5462 	q->q_ptr = WR(q)->q_ptr = NULL;
5463 
5464 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5465 
5466 	return (0);
5467 }
5468 
5469 /*
5470  * This is called as part of close() for both IP and UDP
5471  * in order to quiesce the conn.
5472  */
5473 void
5474 ip_quiesce_conn(conn_t *connp)
5475 {
5476 	boolean_t	drain_cleanup_reqd = B_FALSE;
5477 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5478 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5479 
5480 	ASSERT(!IPCL_IS_TCP(connp));
5481 
5482 	/*
5483 	 * Mark the conn as closing, and this conn must not be
5484 	 * inserted in future into any list. Eg. conn_drain_insert(),
5485 	 * won't insert this conn into the conn_drain_list.
5486 	 * Similarly ill_pending_mp_add() will not add any mp to
5487 	 * the pending mp list, after this conn has started closing.
5488 	 *
5489 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5490 	 * cannot get set henceforth.
5491 	 */
5492 	mutex_enter(&connp->conn_lock);
5493 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5494 	connp->conn_state_flags |= CONN_CLOSING;
5495 	if (connp->conn_idl != NULL)
5496 		drain_cleanup_reqd = B_TRUE;
5497 	if (connp->conn_oper_pending_ill != NULL)
5498 		conn_ioctl_cleanup_reqd = B_TRUE;
5499 	if (connp->conn_ilg_inuse != 0)
5500 		ilg_cleanup_reqd = B_TRUE;
5501 	mutex_exit(&connp->conn_lock);
5502 
5503 	if (IPCL_IS_UDP(connp))
5504 		udp_quiesce_conn(connp);
5505 
5506 	if (conn_ioctl_cleanup_reqd)
5507 		conn_ioctl_cleanup(connp);
5508 
5509 	if (is_system_labeled() && connp->conn_anon_port) {
5510 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5511 		    connp->conn_mlp_type, connp->conn_ulp,
5512 		    ntohs(connp->conn_lport), B_FALSE);
5513 		connp->conn_anon_port = 0;
5514 	}
5515 	connp->conn_mlp_type = mlptSingle;
5516 
5517 	/*
5518 	 * Remove this conn from any fanout list it is on.
5519 	 * and then wait for any threads currently operating
5520 	 * on this endpoint to finish
5521 	 */
5522 	ipcl_hash_remove(connp);
5523 
5524 	/*
5525 	 * Remove this conn from the drain list, and do
5526 	 * any other cleanup that may be required.
5527 	 * (Only non-tcp streams may have a non-null conn_idl.
5528 	 * TCP streams are never flow controlled, and
5529 	 * conn_idl will be null)
5530 	 */
5531 	if (drain_cleanup_reqd)
5532 		conn_drain_tail(connp, B_TRUE);
5533 
5534 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5535 		(void) ip_mrouter_done(NULL);
5536 
5537 	if (ilg_cleanup_reqd)
5538 		ilg_delete_all(connp);
5539 
5540 	conn_delete_ire(connp, NULL);
5541 
5542 	/*
5543 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5544 	 * callers from write side can't be there now because close
5545 	 * is in progress. The only other caller is ipcl_walk
5546 	 * which checks for the condemned flag.
5547 	 */
5548 	mutex_enter(&connp->conn_lock);
5549 	connp->conn_state_flags |= CONN_CONDEMNED;
5550 	while (connp->conn_ref != 1)
5551 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5552 	connp->conn_state_flags |= CONN_QUIESCED;
5553 	mutex_exit(&connp->conn_lock);
5554 }
5555 
5556 /* ARGSUSED */
5557 int
5558 ip_close(queue_t *q, int flags)
5559 {
5560 	conn_t		*connp;
5561 
5562 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5563 
5564 	/*
5565 	 * Call the appropriate delete routine depending on whether this is
5566 	 * a module or device.
5567 	 */
5568 	if (WR(q)->q_next != NULL) {
5569 		/* This is a module close */
5570 		return (ip_modclose((ill_t *)q->q_ptr));
5571 	}
5572 
5573 	connp = q->q_ptr;
5574 	ip_quiesce_conn(connp);
5575 
5576 	qprocsoff(q);
5577 
5578 	/*
5579 	 * Now we are truly single threaded on this stream, and can
5580 	 * delete the things hanging off the connp, and finally the connp.
5581 	 * We removed this connp from the fanout list, it cannot be
5582 	 * accessed thru the fanouts, and we already waited for the
5583 	 * conn_ref to drop to 0. We are already in close, so
5584 	 * there cannot be any other thread from the top. qprocsoff
5585 	 * has completed, and service has completed or won't run in
5586 	 * future.
5587 	 */
5588 	ASSERT(connp->conn_ref == 1);
5589 
5590 	/*
5591 	 * A conn which was previously marked as IPCL_UDP cannot
5592 	 * retain the flag because it would have been cleared by
5593 	 * udp_close().
5594 	 */
5595 	ASSERT(!IPCL_IS_UDP(connp));
5596 
5597 	if (connp->conn_latch != NULL) {
5598 		IPLATCH_REFRELE(connp->conn_latch);
5599 		connp->conn_latch = NULL;
5600 	}
5601 	if (connp->conn_policy != NULL) {
5602 		IPPH_REFRELE(connp->conn_policy);
5603 		connp->conn_policy = NULL;
5604 	}
5605 	if (connp->conn_ipsec_opt_mp != NULL) {
5606 		freemsg(connp->conn_ipsec_opt_mp);
5607 		connp->conn_ipsec_opt_mp = NULL;
5608 	}
5609 
5610 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5611 
5612 	connp->conn_ref--;
5613 	ipcl_conn_destroy(connp);
5614 
5615 	q->q_ptr = WR(q)->q_ptr = NULL;
5616 	return (0);
5617 }
5618 
5619 int
5620 ip_snmpmod_close(queue_t *q)
5621 {
5622 	conn_t *connp = Q_TO_CONN(q);
5623 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5624 
5625 	qprocsoff(q);
5626 
5627 	if (connp->conn_flags & IPCL_UDPMOD)
5628 		udp_close_free(connp);
5629 
5630 	if (connp->conn_cred != NULL) {
5631 		crfree(connp->conn_cred);
5632 		connp->conn_cred = NULL;
5633 	}
5634 	CONN_DEC_REF(connp);
5635 	q->q_ptr = WR(q)->q_ptr = NULL;
5636 	return (0);
5637 }
5638 
5639 /*
5640  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5641  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5642  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5643  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5644  * queues as we never enqueue messages there and we don't handle any ioctls.
5645  * Everything else is freed.
5646  */
5647 void
5648 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5649 {
5650 	conn_t	*connp = q->q_ptr;
5651 	pfi_t	setfn;
5652 	pfi_t	getfn;
5653 
5654 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5655 
5656 	switch (DB_TYPE(mp)) {
5657 	case M_PROTO:
5658 	case M_PCPROTO:
5659 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5660 		    ((((union T_primitives *)mp->b_rptr)->type ==
5661 			T_SVR4_OPTMGMT_REQ) ||
5662 		    (((union T_primitives *)mp->b_rptr)->type ==
5663 			T_OPTMGMT_REQ))) {
5664 			/*
5665 			 * This is the only TPI primitive supported. Its
5666 			 * handling does not require tcp_t, but it does require
5667 			 * conn_t to check permissions.
5668 			 */
5669 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5670 
5671 			if (connp->conn_flags & IPCL_TCPMOD) {
5672 				setfn = tcp_snmp_set;
5673 				getfn = tcp_snmp_get;
5674 			} else {
5675 				setfn = udp_snmp_set;
5676 				getfn = udp_snmp_get;
5677 			}
5678 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5679 				freemsg(mp);
5680 				return;
5681 			}
5682 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5683 		    != NULL)
5684 			qreply(q, mp);
5685 		break;
5686 	case M_FLUSH:
5687 	case M_IOCTL:
5688 		putnext(q, mp);
5689 		break;
5690 	default:
5691 		freemsg(mp);
5692 		break;
5693 	}
5694 }
5695 
5696 /* Return the IP checksum for the IP header at "iph". */
5697 uint16_t
5698 ip_csum_hdr(ipha_t *ipha)
5699 {
5700 	uint16_t	*uph;
5701 	uint32_t	sum;
5702 	int		opt_len;
5703 
5704 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5705 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5706 	uph = (uint16_t *)ipha;
5707 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5708 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5709 	if (opt_len > 0) {
5710 		do {
5711 			sum += uph[10];
5712 			sum += uph[11];
5713 			uph += 2;
5714 		} while (--opt_len);
5715 	}
5716 	sum = (sum & 0xFFFF) + (sum >> 16);
5717 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5718 	if (sum == 0xffff)
5719 		sum = 0;
5720 	return ((uint16_t)sum);
5721 }
5722 
5723 void
5724 ip_ddi_destroy(void)
5725 {
5726 	ipv4_hook_destroy();
5727 	ipv6_hook_destroy();
5728 	ip_net_destroy();
5729 
5730 	tnet_fini();
5731 	tcp_ddi_destroy();
5732 	sctp_ddi_destroy();
5733 	ipsec_loader_destroy();
5734 	ipsec_policy_destroy();
5735 	ipsec_kstat_destroy();
5736 	nd_free(&ip_g_nd);
5737 	mutex_destroy(&igmp_timer_lock);
5738 	mutex_destroy(&mld_timer_lock);
5739 	mutex_destroy(&igmp_slowtimeout_lock);
5740 	mutex_destroy(&mld_slowtimeout_lock);
5741 	mutex_destroy(&ip_mi_lock);
5742 	mutex_destroy(&rts_clients.connf_lock);
5743 	ip_ire_fini();
5744 	ip6_asp_free();
5745 	conn_drain_fini();
5746 	ipcl_destroy();
5747 	inet_minor_destroy(ip_minor_arena);
5748 	icmp_kstat_fini();
5749 	ip_kstat_fini();
5750 	rw_destroy(&ipsec_capab_ills_lock);
5751 	rw_destroy(&ill_g_usesrc_lock);
5752 	ip_drop_unregister(&ip_dropper);
5753 }
5754 
5755 
5756 void
5757 ip_ddi_init(void)
5758 {
5759 	TCP6_MAJ = ddi_name_to_major(TCP6);
5760 	TCP_MAJ	= ddi_name_to_major(TCP);
5761 	SCTP_MAJ = ddi_name_to_major(SCTP);
5762 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5763 
5764 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5765 
5766 	/* IP's IPsec code calls the packet dropper */
5767 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5768 
5769 	if (!ip_g_nd) {
5770 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5771 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5772 			nd_free(&ip_g_nd);
5773 		}
5774 	}
5775 
5776 	ipsec_loader_init();
5777 	ipsec_policy_init();
5778 	ipsec_kstat_init();
5779 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5780 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5781 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5782 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5783 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5784 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5785 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5786 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5787 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5788 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5789 
5790 	/*
5791 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5792 	 * initial devices: ip, ip6, tcp, tcp6.
5793 	 */
5794 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5795 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5796 		cmn_err(CE_PANIC,
5797 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5798 	}
5799 
5800 	ipcl_init();
5801 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5802 	ip_ire_init();
5803 	ip6_asp_init();
5804 	ipif_init();
5805 	conn_drain_init();
5806 	tcp_ddi_init();
5807 	sctp_ddi_init();
5808 
5809 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5810 
5811 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5812 		"net", KSTAT_TYPE_NAMED,
5813 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5814 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5815 		ip_kstat->ks_data = &ip_statistics;
5816 		kstat_install(ip_kstat);
5817 	}
5818 	ip_kstat_init();
5819 	ip6_kstat_init();
5820 	icmp_kstat_init();
5821 	ipsec_loader_start();
5822 	tnet_init();
5823 
5824 	ip_net_init();
5825 	ipv4_hook_init();
5826 	ipv6_hook_init();
5827 }
5828 
5829 /*
5830  * Allocate and initialize a DLPI template of the specified length.  (May be
5831  * called as writer.)
5832  */
5833 mblk_t *
5834 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5835 {
5836 	mblk_t	*mp;
5837 
5838 	mp = allocb(len, BPRI_MED);
5839 	if (!mp)
5840 		return (NULL);
5841 
5842 	/*
5843 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5844 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5845 	 * that other DLPI are M_PROTO.
5846 	 */
5847 	if (prim == DL_INFO_REQ) {
5848 		mp->b_datap->db_type = M_PCPROTO;
5849 	} else {
5850 		mp->b_datap->db_type = M_PROTO;
5851 	}
5852 
5853 	mp->b_wptr = mp->b_rptr + len;
5854 	bzero(mp->b_rptr, len);
5855 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5856 	return (mp);
5857 }
5858 
5859 const char *
5860 dlpi_prim_str(int prim)
5861 {
5862 	switch (prim) {
5863 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5864 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5865 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5866 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5867 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5868 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5869 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5870 	case DL_OK_ACK:		return ("DL_OK_ACK");
5871 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5872 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5873 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5874 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5875 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5876 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5877 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5878 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5879 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5880 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5881 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5882 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5883 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5884 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5885 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5886 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5887 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5888 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5889 	default:		return ("<unknown primitive>");
5890 	}
5891 }
5892 
5893 const char *
5894 dlpi_err_str(int err)
5895 {
5896 	switch (err) {
5897 	case DL_ACCESS:		return ("DL_ACCESS");
5898 	case DL_BADADDR:	return ("DL_BADADDR");
5899 	case DL_BADCORR:	return ("DL_BADCORR");
5900 	case DL_BADDATA:	return ("DL_BADDATA");
5901 	case DL_BADPPA:		return ("DL_BADPPA");
5902 	case DL_BADPRIM:	return ("DL_BADPRIM");
5903 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5904 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5905 	case DL_BADSAP:		return ("DL_BADSAP");
5906 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5907 	case DL_BOUND:		return ("DL_BOUND");
5908 	case DL_INITFAILED:	return ("DL_INITFAILED");
5909 	case DL_NOADDR:		return ("DL_NOADDR");
5910 	case DL_NOTINIT:	return ("DL_NOTINIT");
5911 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5912 	case DL_SYSERR:		return ("DL_SYSERR");
5913 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5914 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5915 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5916 	case DL_TOOMANY:	return ("DL_TOOMANY");
5917 	case DL_NOTENAB:	return ("DL_NOTENAB");
5918 	case DL_BUSY:		return ("DL_BUSY");
5919 	case DL_NOAUTO:		return ("DL_NOAUTO");
5920 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5921 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5922 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5923 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5924 	case DL_PENDING:	return ("DL_PENDING");
5925 	default:		return ("<unknown error>");
5926 	}
5927 }
5928 
5929 /*
5930  * Debug formatting routine.  Returns a character string representation of the
5931  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5932  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5933  *
5934  * Once the ndd table-printing interfaces are removed, this can be changed to
5935  * standard dotted-decimal form.
5936  */
5937 char *
5938 ip_dot_addr(ipaddr_t addr, char *buf)
5939 {
5940 	uint8_t *ap = (uint8_t *)&addr;
5941 
5942 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5943 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
5944 	return (buf);
5945 }
5946 
5947 /*
5948  * Write the given MAC address as a printable string in the usual colon-
5949  * separated format.
5950  */
5951 const char *
5952 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
5953 {
5954 	char *bp;
5955 
5956 	if (alen == 0 || buflen < 4)
5957 		return ("?");
5958 	bp = buf;
5959 	for (;;) {
5960 		/*
5961 		 * If there are more MAC address bytes available, but we won't
5962 		 * have any room to print them, then add "..." to the string
5963 		 * instead.  See below for the 'magic number' explanation.
5964 		 */
5965 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
5966 			(void) strcpy(bp, "...");
5967 			break;
5968 		}
5969 		(void) sprintf(bp, "%02x", *addr++);
5970 		bp += 2;
5971 		if (--alen == 0)
5972 			break;
5973 		*bp++ = ':';
5974 		buflen -= 3;
5975 		/*
5976 		 * At this point, based on the first 'if' statement above,
5977 		 * either alen == 1 and buflen >= 3, or alen > 1 and
5978 		 * buflen >= 4.  The first case leaves room for the final "xx"
5979 		 * number and trailing NUL byte.  The second leaves room for at
5980 		 * least "...".  Thus the apparently 'magic' numbers chosen for
5981 		 * that statement.
5982 		 */
5983 	}
5984 	return (buf);
5985 }
5986 
5987 /*
5988  * Send an ICMP error after patching up the packet appropriately.  Returns
5989  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5990  */
5991 static boolean_t
5992 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5993     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5994 {
5995 	ipha_t *ipha;
5996 	mblk_t *first_mp;
5997 	boolean_t secure;
5998 	unsigned char db_type;
5999 
6000 	first_mp = mp;
6001 	if (mctl_present) {
6002 		mp = mp->b_cont;
6003 		secure = ipsec_in_is_secure(first_mp);
6004 		ASSERT(mp != NULL);
6005 	} else {
6006 		/*
6007 		 * If this is an ICMP error being reported - which goes
6008 		 * up as M_CTLs, we need to convert them to M_DATA till
6009 		 * we finish checking with global policy because
6010 		 * ipsec_check_global_policy() assumes M_DATA as clear
6011 		 * and M_CTL as secure.
6012 		 */
6013 		db_type = DB_TYPE(mp);
6014 		DB_TYPE(mp) = M_DATA;
6015 		secure = B_FALSE;
6016 	}
6017 	/*
6018 	 * We are generating an icmp error for some inbound packet.
6019 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6020 	 * Before we generate an error, check with global policy
6021 	 * to see whether this is allowed to enter the system. As
6022 	 * there is no "conn", we are checking with global policy.
6023 	 */
6024 	ipha = (ipha_t *)mp->b_rptr;
6025 	if (secure || ipsec_inbound_v4_policy_present) {
6026 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6027 		    ipha, NULL, mctl_present);
6028 		if (first_mp == NULL)
6029 			return (B_FALSE);
6030 	}
6031 
6032 	if (!mctl_present)
6033 		DB_TYPE(mp) = db_type;
6034 
6035 	if (flags & IP_FF_SEND_ICMP) {
6036 		if (flags & IP_FF_HDR_COMPLETE) {
6037 			if (ip_hdr_complete(ipha, zoneid)) {
6038 				freemsg(first_mp);
6039 				return (B_TRUE);
6040 			}
6041 		}
6042 		if (flags & IP_FF_CKSUM) {
6043 			/*
6044 			 * Have to correct checksum since
6045 			 * the packet might have been
6046 			 * fragmented and the reassembly code in ip_rput
6047 			 * does not restore the IP checksum.
6048 			 */
6049 			ipha->ipha_hdr_checksum = 0;
6050 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6051 		}
6052 		switch (icmp_type) {
6053 		case ICMP_DEST_UNREACHABLE:
6054 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid);
6055 			break;
6056 		default:
6057 			freemsg(first_mp);
6058 			break;
6059 		}
6060 	} else {
6061 		freemsg(first_mp);
6062 		return (B_FALSE);
6063 	}
6064 
6065 	return (B_TRUE);
6066 }
6067 
6068 /*
6069  * Used to send an ICMP error message when a packet is received for
6070  * a protocol that is not supported. The mblk passed as argument
6071  * is consumed by this function.
6072  */
6073 void
6074 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
6075 {
6076 	mblk_t *mp;
6077 	ipha_t *ipha;
6078 	ill_t *ill;
6079 	ipsec_in_t *ii;
6080 
6081 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6082 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6083 
6084 	mp = ipsec_mp->b_cont;
6085 	ipsec_mp->b_cont = NULL;
6086 	ipha = (ipha_t *)mp->b_rptr;
6087 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6088 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
6089 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6090 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
6091 		}
6092 	} else {
6093 		/* Get ill from index in ipsec_in_t. */
6094 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6095 		    B_TRUE, NULL, NULL, NULL, NULL);
6096 		if (ill != NULL) {
6097 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6098 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6099 			    0, B_FALSE, zoneid)) {
6100 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
6101 			}
6102 
6103 			ill_refrele(ill);
6104 		} else { /* re-link for the freemsg() below. */
6105 			ipsec_mp->b_cont = mp;
6106 		}
6107 	}
6108 
6109 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6110 	freemsg(ipsec_mp);
6111 }
6112 
6113 /*
6114  * See if the inbound datagram has had IPsec processing applied to it.
6115  */
6116 boolean_t
6117 ipsec_in_is_secure(mblk_t *ipsec_mp)
6118 {
6119 	ipsec_in_t *ii;
6120 
6121 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6122 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6123 
6124 	if (ii->ipsec_in_loopback) {
6125 		return (ii->ipsec_in_secure);
6126 	} else {
6127 		return (ii->ipsec_in_ah_sa != NULL ||
6128 		    ii->ipsec_in_esp_sa != NULL ||
6129 		    ii->ipsec_in_decaps);
6130 	}
6131 }
6132 
6133 /*
6134  * Handle protocols with which IP is less intimate.  There
6135  * can be more than one stream bound to a particular
6136  * protocol.  When this is the case, normally each one gets a copy
6137  * of any incoming packets.
6138  *
6139  * IPSEC NOTE :
6140  *
6141  * Don't allow a secure packet going up a non-secure connection.
6142  * We don't allow this because
6143  *
6144  * 1) Reply might go out in clear which will be dropped at
6145  *    the sending side.
6146  * 2) If the reply goes out in clear it will give the
6147  *    adversary enough information for getting the key in
6148  *    most of the cases.
6149  *
6150  * Moreover getting a secure packet when we expect clear
6151  * implies that SA's were added without checking for
6152  * policy on both ends. This should not happen once ISAKMP
6153  * is used to negotiate SAs as SAs will be added only after
6154  * verifying the policy.
6155  *
6156  * NOTE : If the packet was tunneled and not multicast we only send
6157  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6158  * back to delivering packets to AF_INET6 raw sockets.
6159  *
6160  * IPQoS Notes:
6161  * Once we have determined the client, invoke IPPF processing.
6162  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6163  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6164  * ip_policy will be false.
6165  *
6166  * Zones notes:
6167  * Currently only applications in the global zone can create raw sockets for
6168  * protocols other than ICMP. So unlike the broadcast / multicast case of
6169  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6170  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6171  */
6172 static void
6173 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6174     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6175     zoneid_t zoneid)
6176 {
6177 	queue_t	*rq;
6178 	mblk_t	*mp1, *first_mp1;
6179 	uint_t	protocol = ipha->ipha_protocol;
6180 	ipaddr_t dst;
6181 	boolean_t one_only;
6182 	mblk_t *first_mp = mp;
6183 	boolean_t secure;
6184 	uint32_t ill_index;
6185 	conn_t	*connp, *first_connp, *next_connp;
6186 	connf_t	*connfp;
6187 	boolean_t shared_addr;
6188 
6189 	if (mctl_present) {
6190 		mp = first_mp->b_cont;
6191 		secure = ipsec_in_is_secure(first_mp);
6192 		ASSERT(mp != NULL);
6193 	} else {
6194 		secure = B_FALSE;
6195 	}
6196 	dst = ipha->ipha_dst;
6197 	/*
6198 	 * If the packet was tunneled and not multicast we only send to it
6199 	 * the first match.
6200 	 */
6201 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6202 	    !CLASSD(dst));
6203 
6204 	shared_addr = (zoneid == ALL_ZONES);
6205 	if (shared_addr) {
6206 		/*
6207 		 * We don't allow multilevel ports for raw IP, so no need to
6208 		 * check for that here.
6209 		 */
6210 		zoneid = tsol_packet_to_zoneid(mp);
6211 	}
6212 
6213 	connfp = &ipcl_proto_fanout[protocol];
6214 	mutex_enter(&connfp->connf_lock);
6215 	connp = connfp->connf_head;
6216 	for (connp = connfp->connf_head; connp != NULL;
6217 		connp = connp->conn_next) {
6218 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6219 		    zoneid) &&
6220 		    (!is_system_labeled() ||
6221 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6222 		    connp)))
6223 			break;
6224 	}
6225 
6226 	if (connp == NULL || connp->conn_upq == NULL) {
6227 		/*
6228 		 * No one bound to these addresses.  Is
6229 		 * there a client that wants all
6230 		 * unclaimed datagrams?
6231 		 */
6232 		mutex_exit(&connfp->connf_lock);
6233 		/*
6234 		 * Check for IPPROTO_ENCAP...
6235 		 */
6236 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6237 			/*
6238 			 * XXX If an IPsec mblk is here on a multicast
6239 			 * tunnel (using ip_mroute stuff), what should
6240 			 * I do?
6241 			 *
6242 			 * For now, just free the IPsec mblk before
6243 			 * passing it up to the multicast routing
6244 			 * stuff.
6245 			 *
6246 			 * BTW,  If I match a configured IP-in-IP
6247 			 * tunnel, ip_mroute_decap will never be
6248 			 * called.
6249 			 */
6250 			if (mp != first_mp)
6251 				freeb(first_mp);
6252 			ip_mroute_decap(q, mp);
6253 		} else {
6254 			/*
6255 			 * Otherwise send an ICMP protocol unreachable.
6256 			 */
6257 			if (ip_fanout_send_icmp(q, first_mp, flags,
6258 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6259 			    mctl_present, zoneid)) {
6260 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
6261 			}
6262 		}
6263 		return;
6264 	}
6265 	CONN_INC_REF(connp);
6266 	first_connp = connp;
6267 
6268 	/*
6269 	 * Only send message to one tunnel driver by immediately
6270 	 * terminating the loop.
6271 	 */
6272 	connp = one_only ? NULL : connp->conn_next;
6273 
6274 	for (;;) {
6275 		while (connp != NULL) {
6276 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6277 			    flags, zoneid) &&
6278 			    (!is_system_labeled() ||
6279 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6280 			    shared_addr, connp)))
6281 				break;
6282 			connp = connp->conn_next;
6283 		}
6284 
6285 		/*
6286 		 * Copy the packet.
6287 		 */
6288 		if (connp == NULL || connp->conn_upq == NULL ||
6289 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6290 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6291 			/*
6292 			 * No more interested clients or memory
6293 			 * allocation failed
6294 			 */
6295 			connp = first_connp;
6296 			break;
6297 		}
6298 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6299 		CONN_INC_REF(connp);
6300 		mutex_exit(&connfp->connf_lock);
6301 		rq = connp->conn_rq;
6302 		if (!canputnext(rq)) {
6303 			if (flags & IP_FF_RAWIP) {
6304 				BUMP_MIB(&ip_mib, rawipInOverflows);
6305 			} else {
6306 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6307 			}
6308 
6309 			freemsg(first_mp1);
6310 		} else {
6311 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6312 				first_mp1 = ipsec_check_inbound_policy
6313 				    (first_mp1, connp, ipha, NULL,
6314 				    mctl_present);
6315 			}
6316 			if (first_mp1 != NULL) {
6317 				/*
6318 				 * ip_fanout_proto also gets called from
6319 				 * icmp_inbound_error_fanout, in which case
6320 				 * the msg type is M_CTL.  Don't add info
6321 				 * in this case for the time being. In future
6322 				 * when there is a need for knowing the
6323 				 * inbound iface index for ICMP error msgs,
6324 				 * then this can be changed.
6325 				 */
6326 				if ((connp->conn_recvif != 0) &&
6327 				    (mp->b_datap->db_type != M_CTL)) {
6328 					/*
6329 					 * the actual data will be
6330 					 * contained in b_cont upon
6331 					 * successful return of the
6332 					 * following call else
6333 					 * original mblk is returned
6334 					 */
6335 					ASSERT(recv_ill != NULL);
6336 					mp1 = ip_add_info(mp1, recv_ill,
6337 						IPF_RECVIF);
6338 				}
6339 				BUMP_MIB(&ip_mib, ipInDelivers);
6340 				if (mctl_present)
6341 					freeb(first_mp1);
6342 				putnext(rq, mp1);
6343 			}
6344 		}
6345 		mutex_enter(&connfp->connf_lock);
6346 		/* Follow the next pointer before releasing the conn. */
6347 		next_connp = connp->conn_next;
6348 		CONN_DEC_REF(connp);
6349 		connp = next_connp;
6350 	}
6351 
6352 	/* Last one.  Send it upstream. */
6353 	mutex_exit(&connfp->connf_lock);
6354 
6355 	/*
6356 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6357 	 * will be set to false.
6358 	 */
6359 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6360 		ill_index = ill->ill_phyint->phyint_ifindex;
6361 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6362 		if (mp == NULL) {
6363 			CONN_DEC_REF(connp);
6364 			if (mctl_present) {
6365 				freeb(first_mp);
6366 			}
6367 			return;
6368 		}
6369 	}
6370 
6371 	rq = connp->conn_rq;
6372 	if (!canputnext(rq)) {
6373 		if (flags & IP_FF_RAWIP) {
6374 			BUMP_MIB(&ip_mib, rawipInOverflows);
6375 		} else {
6376 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6377 		}
6378 
6379 		freemsg(first_mp);
6380 	} else {
6381 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6382 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6383 			    ipha, NULL, mctl_present);
6384 		}
6385 		if (first_mp != NULL) {
6386 			/*
6387 			 * ip_fanout_proto also gets called
6388 			 * from icmp_inbound_error_fanout, in
6389 			 * which case the msg type is M_CTL.
6390 			 * Don't add info in this case for time
6391 			 * being. In future when there is a
6392 			 * need for knowing the inbound iface
6393 			 * index for ICMP error msgs, then this
6394 			 * can be changed
6395 			 */
6396 			if ((connp->conn_recvif != 0) &&
6397 			    (mp->b_datap->db_type != M_CTL)) {
6398 				/*
6399 				 * the actual data will be contained in
6400 				 * b_cont upon successful return
6401 				 * of the following call else original
6402 				 * mblk is returned
6403 				 */
6404 				ASSERT(recv_ill != NULL);
6405 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6406 			}
6407 			BUMP_MIB(&ip_mib, ipInDelivers);
6408 			putnext(rq, mp);
6409 			if (mctl_present)
6410 				freeb(first_mp);
6411 		}
6412 	}
6413 	CONN_DEC_REF(connp);
6414 }
6415 
6416 /*
6417  * Fanout for TCP packets
6418  * The caller puts <fport, lport> in the ports parameter.
6419  *
6420  * IPQoS Notes
6421  * Before sending it to the client, invoke IPPF processing.
6422  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6423  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6424  * ip_policy is false.
6425  */
6426 static void
6427 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6428     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6429 {
6430 	mblk_t  *first_mp;
6431 	boolean_t secure;
6432 	uint32_t ill_index;
6433 	int	ip_hdr_len;
6434 	tcph_t	*tcph;
6435 	boolean_t syn_present = B_FALSE;
6436 	conn_t	*connp;
6437 
6438 	first_mp = mp;
6439 	if (mctl_present) {
6440 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6441 		mp = first_mp->b_cont;
6442 		secure = ipsec_in_is_secure(first_mp);
6443 		ASSERT(mp != NULL);
6444 	} else {
6445 		secure = B_FALSE;
6446 	}
6447 
6448 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6449 
6450 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6451 	    NULL) {
6452 		/*
6453 		 * No connected connection or listener. Send a
6454 		 * TH_RST via tcp_xmit_listeners_reset.
6455 		 */
6456 
6457 		/* Initiate IPPf processing, if needed. */
6458 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6459 			uint32_t ill_index;
6460 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6461 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6462 			if (first_mp == NULL)
6463 				return;
6464 		}
6465 		BUMP_MIB(&ip_mib, ipInDelivers);
6466 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6467 		    zoneid));
6468 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6469 		return;
6470 	}
6471 
6472 	/*
6473 	 * Allocate the SYN for the TCP connection here itself
6474 	 */
6475 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6476 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6477 		if (IPCL_IS_TCP(connp)) {
6478 			squeue_t *sqp;
6479 
6480 			/*
6481 			 * For fused tcp loopback, assign the eager's
6482 			 * squeue to be that of the active connect's.
6483 			 * Note that we don't check for IP_FF_LOOPBACK
6484 			 * here since this routine gets called only
6485 			 * for loopback (unlike the IPv6 counterpart).
6486 			 */
6487 			ASSERT(Q_TO_CONN(q) != NULL);
6488 			if (do_tcp_fusion &&
6489 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6490 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6491 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6492 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6493 				sqp = Q_TO_CONN(q)->conn_sqp;
6494 			} else {
6495 				sqp = IP_SQUEUE_GET(lbolt);
6496 			}
6497 
6498 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6499 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6500 			syn_present = B_TRUE;
6501 		}
6502 	}
6503 
6504 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6505 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6506 		if ((flags & TH_RST) || (flags & TH_URG)) {
6507 			CONN_DEC_REF(connp);
6508 			freemsg(first_mp);
6509 			return;
6510 		}
6511 		if (flags & TH_ACK) {
6512 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6513 			CONN_DEC_REF(connp);
6514 			return;
6515 		}
6516 
6517 		CONN_DEC_REF(connp);
6518 		freemsg(first_mp);
6519 		return;
6520 	}
6521 
6522 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6523 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6524 		    NULL, mctl_present);
6525 		if (first_mp == NULL) {
6526 			CONN_DEC_REF(connp);
6527 			return;
6528 		}
6529 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6530 			ASSERT(syn_present);
6531 			if (mctl_present) {
6532 				ASSERT(first_mp != mp);
6533 				first_mp->b_datap->db_struioflag |=
6534 				    STRUIO_POLICY;
6535 			} else {
6536 				ASSERT(first_mp == mp);
6537 				mp->b_datap->db_struioflag &=
6538 				    ~STRUIO_EAGER;
6539 				mp->b_datap->db_struioflag |=
6540 				    STRUIO_POLICY;
6541 			}
6542 		} else {
6543 			/*
6544 			 * Discard first_mp early since we're dealing with a
6545 			 * fully-connected conn_t and tcp doesn't do policy in
6546 			 * this case.
6547 			 */
6548 			if (mctl_present) {
6549 				freeb(first_mp);
6550 				mctl_present = B_FALSE;
6551 			}
6552 			first_mp = mp;
6553 		}
6554 	}
6555 
6556 	/*
6557 	 * Initiate policy processing here if needed. If we get here from
6558 	 * icmp_inbound_error_fanout, ip_policy is false.
6559 	 */
6560 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6561 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6562 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6563 		if (mp == NULL) {
6564 			CONN_DEC_REF(connp);
6565 			if (mctl_present)
6566 				freeb(first_mp);
6567 			return;
6568 		} else if (mctl_present) {
6569 			ASSERT(first_mp != mp);
6570 			first_mp->b_cont = mp;
6571 		} else {
6572 			first_mp = mp;
6573 		}
6574 	}
6575 
6576 
6577 
6578 	/* Handle IPv6 socket options. */
6579 	if (!syn_present &&
6580 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6581 		/* Add header */
6582 		ASSERT(recv_ill != NULL);
6583 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6584 		if (mp == NULL) {
6585 			CONN_DEC_REF(connp);
6586 			if (mctl_present)
6587 				freeb(first_mp);
6588 			return;
6589 		} else if (mctl_present) {
6590 			/*
6591 			 * ip_add_info might return a new mp.
6592 			 */
6593 			ASSERT(first_mp != mp);
6594 			first_mp->b_cont = mp;
6595 		} else {
6596 			first_mp = mp;
6597 		}
6598 	}
6599 
6600 	BUMP_MIB(&ip_mib, ipInDelivers);
6601 	if (IPCL_IS_TCP(connp)) {
6602 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6603 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6604 	} else {
6605 		putnext(connp->conn_rq, first_mp);
6606 		CONN_DEC_REF(connp);
6607 	}
6608 }
6609 
6610 /*
6611  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6612  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6613  * Caller is responsible for dropping references to the conn, and freeing
6614  * first_mp.
6615  *
6616  * IPQoS Notes
6617  * Before sending it to the client, invoke IPPF processing. Policy processing
6618  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6619  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6620  * ip_wput_local, ip_policy is false.
6621  */
6622 static void
6623 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6624     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6625     boolean_t ip_policy)
6626 {
6627 	boolean_t	mctl_present = (first_mp != NULL);
6628 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6629 	uint32_t	ill_index;
6630 
6631 	if (mctl_present)
6632 		first_mp->b_cont = mp;
6633 	else
6634 		first_mp = mp;
6635 
6636 	if (CONN_UDP_FLOWCTLD(connp)) {
6637 		BUMP_MIB(&ip_mib, udpInOverflows);
6638 		freemsg(first_mp);
6639 		return;
6640 	}
6641 
6642 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6643 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6644 		    NULL, mctl_present);
6645 		if (first_mp == NULL)
6646 			return;	/* Freed by ipsec_check_inbound_policy(). */
6647 	}
6648 	if (mctl_present)
6649 		freeb(first_mp);
6650 
6651 	if (connp->conn_recvif)
6652 		in_flags = IPF_RECVIF;
6653 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6654 		in_flags |= IPF_RECVSLLA;
6655 
6656 	/* Handle IPv6 options. */
6657 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6658 		in_flags |= IPF_RECVIF;
6659 
6660 	/*
6661 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6662 	 * freed if the packet is dropped. The caller will do so.
6663 	 */
6664 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6665 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6666 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6667 		if (mp == NULL) {
6668 			return;
6669 		}
6670 	}
6671 	if ((in_flags != 0) &&
6672 	    (mp->b_datap->db_type != M_CTL)) {
6673 		/*
6674 		 * The actual data will be contained in b_cont
6675 		 * upon successful return of the following call
6676 		 * else original mblk is returned
6677 		 */
6678 		ASSERT(recv_ill != NULL);
6679 		mp = ip_add_info(mp, recv_ill, in_flags);
6680 	}
6681 	BUMP_MIB(&ip_mib, ipInDelivers);
6682 
6683 	/* Send it upstream */
6684 	CONN_UDP_RECV(connp, mp);
6685 }
6686 
6687 /*
6688  * Fanout for UDP packets.
6689  * The caller puts <fport, lport> in the ports parameter.
6690  *
6691  * If SO_REUSEADDR is set all multicast and broadcast packets
6692  * will be delivered to all streams bound to the same port.
6693  *
6694  * Zones notes:
6695  * Multicast and broadcast packets will be distributed to streams in all zones.
6696  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6697  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6698  * packets. To maintain this behavior with multiple zones, the conns are grouped
6699  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6700  * each zone. If unset, all the following conns in the same zone are skipped.
6701  */
6702 static void
6703 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6704     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6705     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6706 {
6707 	uint32_t	dstport, srcport;
6708 	ipaddr_t	dst;
6709 	mblk_t		*first_mp;
6710 	boolean_t	secure;
6711 	in6_addr_t	v6src;
6712 	conn_t		*connp;
6713 	connf_t		*connfp;
6714 	conn_t		*first_connp;
6715 	conn_t		*next_connp;
6716 	mblk_t		*mp1, *first_mp1;
6717 	ipaddr_t	src;
6718 	zoneid_t	last_zoneid;
6719 	boolean_t	reuseaddr;
6720 	boolean_t	shared_addr;
6721 
6722 	first_mp = mp;
6723 	if (mctl_present) {
6724 		mp = first_mp->b_cont;
6725 		first_mp->b_cont = NULL;
6726 		secure = ipsec_in_is_secure(first_mp);
6727 		ASSERT(mp != NULL);
6728 	} else {
6729 		first_mp = NULL;
6730 		secure = B_FALSE;
6731 	}
6732 
6733 	/* Extract ports in net byte order */
6734 	dstport = htons(ntohl(ports) & 0xFFFF);
6735 	srcport = htons(ntohl(ports) >> 16);
6736 	dst = ipha->ipha_dst;
6737 	src = ipha->ipha_src;
6738 
6739 	shared_addr = (zoneid == ALL_ZONES);
6740 	if (shared_addr) {
6741 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6742 		if (zoneid == ALL_ZONES)
6743 			zoneid = tsol_packet_to_zoneid(mp);
6744 	}
6745 
6746 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6747 	mutex_enter(&connfp->connf_lock);
6748 	connp = connfp->connf_head;
6749 	if (!broadcast && !CLASSD(dst)) {
6750 		/*
6751 		 * Not broadcast or multicast. Send to the one (first)
6752 		 * client we find. No need to check conn_wantpacket()
6753 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6754 		 * IPv4 unicast packets.
6755 		 */
6756 		while ((connp != NULL) &&
6757 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
6758 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
6759 			connp = connp->conn_next;
6760 		}
6761 
6762 		if (connp == NULL || connp->conn_upq == NULL)
6763 			goto notfound;
6764 
6765 		if (is_system_labeled() &&
6766 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6767 		    connp))
6768 			goto notfound;
6769 
6770 		CONN_INC_REF(connp);
6771 		mutex_exit(&connfp->connf_lock);
6772 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6773 		    recv_ill, ip_policy);
6774 		IP_STAT(ip_udp_fannorm);
6775 		CONN_DEC_REF(connp);
6776 		return;
6777 	}
6778 
6779 	/*
6780 	 * Broadcast and multicast case
6781 	 *
6782 	 * Need to check conn_wantpacket().
6783 	 * If SO_REUSEADDR has been set on the first we send the
6784 	 * packet to all clients that have joined the group and
6785 	 * match the port.
6786 	 */
6787 
6788 	while (connp != NULL) {
6789 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6790 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6791 		    (!is_system_labeled() ||
6792 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6793 		    connp)))
6794 			break;
6795 		connp = connp->conn_next;
6796 	}
6797 
6798 	if (connp == NULL || connp->conn_upq == NULL)
6799 		goto notfound;
6800 
6801 	first_connp = connp;
6802 	/*
6803 	 * When SO_REUSEADDR is not set, send the packet only to the first
6804 	 * matching connection in its zone by keeping track of the zoneid.
6805 	 */
6806 	reuseaddr = first_connp->conn_reuseaddr;
6807 	last_zoneid = first_connp->conn_zoneid;
6808 
6809 	CONN_INC_REF(connp);
6810 	connp = connp->conn_next;
6811 	for (;;) {
6812 		while (connp != NULL) {
6813 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6814 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6815 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6816 			    (!is_system_labeled() ||
6817 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6818 			    shared_addr, connp)))
6819 				break;
6820 			connp = connp->conn_next;
6821 		}
6822 		/*
6823 		 * Just copy the data part alone. The mctl part is
6824 		 * needed just for verifying policy and it is never
6825 		 * sent up.
6826 		 */
6827 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6828 		    ((mp1 = copymsg(mp)) == NULL))) {
6829 			/*
6830 			 * No more interested clients or memory
6831 			 * allocation failed
6832 			 */
6833 			connp = first_connp;
6834 			break;
6835 		}
6836 		if (connp->conn_zoneid != last_zoneid) {
6837 			/*
6838 			 * Update the zoneid so that the packet isn't sent to
6839 			 * any more conns in the same zone unless SO_REUSEADDR
6840 			 * is set.
6841 			 */
6842 			reuseaddr = connp->conn_reuseaddr;
6843 			last_zoneid = connp->conn_zoneid;
6844 		}
6845 		if (first_mp != NULL) {
6846 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6847 			    ipsec_info_type == IPSEC_IN);
6848 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6849 			if (first_mp1 == NULL) {
6850 				freemsg(mp1);
6851 				connp = first_connp;
6852 				break;
6853 			}
6854 		} else {
6855 			first_mp1 = NULL;
6856 		}
6857 		CONN_INC_REF(connp);
6858 		mutex_exit(&connfp->connf_lock);
6859 		/*
6860 		 * IPQoS notes: We don't send the packet for policy
6861 		 * processing here, will do it for the last one (below).
6862 		 * i.e. we do it per-packet now, but if we do policy
6863 		 * processing per-conn, then we would need to do it
6864 		 * here too.
6865 		 */
6866 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6867 		    ipha, flags, recv_ill, B_FALSE);
6868 		mutex_enter(&connfp->connf_lock);
6869 		/* Follow the next pointer before releasing the conn. */
6870 		next_connp = connp->conn_next;
6871 		IP_STAT(ip_udp_fanmb);
6872 		CONN_DEC_REF(connp);
6873 		connp = next_connp;
6874 	}
6875 
6876 	/* Last one.  Send it upstream. */
6877 	mutex_exit(&connfp->connf_lock);
6878 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6879 	    ip_policy);
6880 	IP_STAT(ip_udp_fanmb);
6881 	CONN_DEC_REF(connp);
6882 	return;
6883 
6884 notfound:
6885 
6886 	mutex_exit(&connfp->connf_lock);
6887 	IP_STAT(ip_udp_fanothers);
6888 	/*
6889 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6890 	 * have already been matched above, since they live in the IPv4
6891 	 * fanout tables. This implies we only need to
6892 	 * check for IPv6 in6addr_any endpoints here.
6893 	 * Thus we compare using ipv6_all_zeros instead of the destination
6894 	 * address, except for the multicast group membership lookup which
6895 	 * uses the IPv4 destination.
6896 	 */
6897 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6898 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6899 	mutex_enter(&connfp->connf_lock);
6900 	connp = connfp->connf_head;
6901 	if (!broadcast && !CLASSD(dst)) {
6902 		while (connp != NULL) {
6903 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6904 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6905 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6906 			    !connp->conn_ipv6_v6only)
6907 				break;
6908 			connp = connp->conn_next;
6909 		}
6910 
6911 		if (connp != NULL && is_system_labeled() &&
6912 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6913 		    connp))
6914 			connp = NULL;
6915 
6916 		if (connp == NULL || connp->conn_upq == NULL) {
6917 			/*
6918 			 * No one bound to this port.  Is
6919 			 * there a client that wants all
6920 			 * unclaimed datagrams?
6921 			 */
6922 			mutex_exit(&connfp->connf_lock);
6923 
6924 			if (mctl_present)
6925 				first_mp->b_cont = mp;
6926 			else
6927 				first_mp = mp;
6928 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6929 				ip_fanout_proto(q, first_mp, ill, ipha,
6930 				    flags | IP_FF_RAWIP, mctl_present,
6931 				    ip_policy, recv_ill, zoneid);
6932 			} else {
6933 				if (ip_fanout_send_icmp(q, first_mp, flags,
6934 				    ICMP_DEST_UNREACHABLE,
6935 				    ICMP_PORT_UNREACHABLE,
6936 				    mctl_present, zoneid)) {
6937 					BUMP_MIB(&ip_mib, udpNoPorts);
6938 				}
6939 			}
6940 			return;
6941 		}
6942 
6943 		CONN_INC_REF(connp);
6944 		mutex_exit(&connfp->connf_lock);
6945 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6946 		    recv_ill, ip_policy);
6947 		CONN_DEC_REF(connp);
6948 		return;
6949 	}
6950 	/*
6951 	 * IPv4 multicast packet being delivered to an AF_INET6
6952 	 * in6addr_any endpoint.
6953 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6954 	 * and not conn_wantpacket_v6() since any multicast membership is
6955 	 * for an IPv4-mapped multicast address.
6956 	 * The packet is sent to all clients in all zones that have joined the
6957 	 * group and match the port.
6958 	 */
6959 	while (connp != NULL) {
6960 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6961 		    srcport, v6src) &&
6962 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6963 		    (!is_system_labeled() ||
6964 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6965 		    connp)))
6966 			break;
6967 		connp = connp->conn_next;
6968 	}
6969 
6970 	if (connp == NULL || connp->conn_upq == NULL) {
6971 		/*
6972 		 * No one bound to this port.  Is
6973 		 * there a client that wants all
6974 		 * unclaimed datagrams?
6975 		 */
6976 		mutex_exit(&connfp->connf_lock);
6977 
6978 		if (mctl_present)
6979 			first_mp->b_cont = mp;
6980 		else
6981 			first_mp = mp;
6982 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6983 			ip_fanout_proto(q, first_mp, ill, ipha,
6984 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6985 			    recv_ill, zoneid);
6986 		} else {
6987 			/*
6988 			 * We used to attempt to send an icmp error here, but
6989 			 * since this is known to be a multicast packet
6990 			 * and we don't send icmp errors in response to
6991 			 * multicast, just drop the packet and give up sooner.
6992 			 */
6993 			BUMP_MIB(&ip_mib, udpNoPorts);
6994 			freemsg(first_mp);
6995 		}
6996 		return;
6997 	}
6998 
6999 	first_connp = connp;
7000 
7001 	CONN_INC_REF(connp);
7002 	connp = connp->conn_next;
7003 	for (;;) {
7004 		while (connp != NULL) {
7005 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7006 			    ipv6_all_zeros, srcport, v6src) &&
7007 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7008 			    (!is_system_labeled() ||
7009 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7010 			    shared_addr, connp)))
7011 				break;
7012 			connp = connp->conn_next;
7013 		}
7014 		/*
7015 		 * Just copy the data part alone. The mctl part is
7016 		 * needed just for verifying policy and it is never
7017 		 * sent up.
7018 		 */
7019 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7020 		    ((mp1 = copymsg(mp)) == NULL))) {
7021 			/*
7022 			 * No more intested clients or memory
7023 			 * allocation failed
7024 			 */
7025 			connp = first_connp;
7026 			break;
7027 		}
7028 		if (first_mp != NULL) {
7029 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7030 			    ipsec_info_type == IPSEC_IN);
7031 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7032 			if (first_mp1 == NULL) {
7033 				freemsg(mp1);
7034 				connp = first_connp;
7035 				break;
7036 			}
7037 		} else {
7038 			first_mp1 = NULL;
7039 		}
7040 		CONN_INC_REF(connp);
7041 		mutex_exit(&connfp->connf_lock);
7042 		/*
7043 		 * IPQoS notes: We don't send the packet for policy
7044 		 * processing here, will do it for the last one (below).
7045 		 * i.e. we do it per-packet now, but if we do policy
7046 		 * processing per-conn, then we would need to do it
7047 		 * here too.
7048 		 */
7049 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
7050 		    ipha, flags, recv_ill, B_FALSE);
7051 		mutex_enter(&connfp->connf_lock);
7052 		/* Follow the next pointer before releasing the conn. */
7053 		next_connp = connp->conn_next;
7054 		CONN_DEC_REF(connp);
7055 		connp = next_connp;
7056 	}
7057 
7058 	/* Last one.  Send it upstream. */
7059 	mutex_exit(&connfp->connf_lock);
7060 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
7061 	    ip_policy);
7062 	CONN_DEC_REF(connp);
7063 }
7064 
7065 /*
7066  * Complete the ip_wput header so that it
7067  * is possible to generate ICMP
7068  * errors.
7069  */
7070 int
7071 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
7072 {
7073 	ire_t *ire;
7074 
7075 	if (ipha->ipha_src == INADDR_ANY) {
7076 		ire = ire_lookup_local(zoneid);
7077 		if (ire == NULL) {
7078 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7079 			return (1);
7080 		}
7081 		ipha->ipha_src = ire->ire_addr;
7082 		ire_refrele(ire);
7083 	}
7084 	ipha->ipha_ttl = ip_def_ttl;
7085 	ipha->ipha_hdr_checksum = 0;
7086 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7087 	return (0);
7088 }
7089 
7090 /*
7091  * Nobody should be sending
7092  * packets up this stream
7093  */
7094 static void
7095 ip_lrput(queue_t *q, mblk_t *mp)
7096 {
7097 	mblk_t *mp1;
7098 
7099 	switch (mp->b_datap->db_type) {
7100 	case M_FLUSH:
7101 		/* Turn around */
7102 		if (*mp->b_rptr & FLUSHW) {
7103 			*mp->b_rptr &= ~FLUSHR;
7104 			qreply(q, mp);
7105 			return;
7106 		}
7107 		break;
7108 	}
7109 	/* Could receive messages that passed through ar_rput */
7110 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7111 		mp1->b_prev = mp1->b_next = NULL;
7112 	freemsg(mp);
7113 }
7114 
7115 /* Nobody should be sending packets down this stream */
7116 /* ARGSUSED */
7117 void
7118 ip_lwput(queue_t *q, mblk_t *mp)
7119 {
7120 	freemsg(mp);
7121 }
7122 
7123 /*
7124  * Move the first hop in any source route to ipha_dst and remove that part of
7125  * the source route.  Called by other protocols.  Errors in option formatting
7126  * are ignored - will be handled by ip_wput_options Return the final
7127  * destination (either ipha_dst or the last entry in a source route.)
7128  */
7129 ipaddr_t
7130 ip_massage_options(ipha_t *ipha)
7131 {
7132 	ipoptp_t	opts;
7133 	uchar_t		*opt;
7134 	uint8_t		optval;
7135 	uint8_t		optlen;
7136 	ipaddr_t	dst;
7137 	int		i;
7138 	ire_t		*ire;
7139 
7140 	ip2dbg(("ip_massage_options\n"));
7141 	dst = ipha->ipha_dst;
7142 	for (optval = ipoptp_first(&opts, ipha);
7143 	    optval != IPOPT_EOL;
7144 	    optval = ipoptp_next(&opts)) {
7145 		opt = opts.ipoptp_cur;
7146 		switch (optval) {
7147 			uint8_t off;
7148 		case IPOPT_SSRR:
7149 		case IPOPT_LSRR:
7150 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7151 				ip1dbg(("ip_massage_options: bad src route\n"));
7152 				break;
7153 			}
7154 			optlen = opts.ipoptp_len;
7155 			off = opt[IPOPT_OFFSET];
7156 			off--;
7157 		redo_srr:
7158 			if (optlen < IP_ADDR_LEN ||
7159 			    off > optlen - IP_ADDR_LEN) {
7160 				/* End of source route */
7161 				ip1dbg(("ip_massage_options: end of SR\n"));
7162 				break;
7163 			}
7164 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7165 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7166 			    ntohl(dst)));
7167 			/*
7168 			 * Check if our address is present more than
7169 			 * once as consecutive hops in source route.
7170 			 * XXX verify per-interface ip_forwarding
7171 			 * for source route?
7172 			 */
7173 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7174 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
7175 			if (ire != NULL) {
7176 				ire_refrele(ire);
7177 				off += IP_ADDR_LEN;
7178 				goto redo_srr;
7179 			}
7180 			if (dst == htonl(INADDR_LOOPBACK)) {
7181 				ip1dbg(("ip_massage_options: loopback addr in "
7182 				    "source route!\n"));
7183 				break;
7184 			}
7185 			/*
7186 			 * Update ipha_dst to be the first hop and remove the
7187 			 * first hop from the source route (by overwriting
7188 			 * part of the option with NOP options).
7189 			 */
7190 			ipha->ipha_dst = dst;
7191 			/* Put the last entry in dst */
7192 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7193 			    3;
7194 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7195 
7196 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7197 			    ntohl(dst)));
7198 			/* Move down and overwrite */
7199 			opt[IP_ADDR_LEN] = opt[0];
7200 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7201 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7202 			for (i = 0; i < IP_ADDR_LEN; i++)
7203 				opt[i] = IPOPT_NOP;
7204 			break;
7205 		}
7206 	}
7207 	return (dst);
7208 }
7209 
7210 /*
7211  * This function's job is to forward data to the reverse tunnel (FA->HA)
7212  * after doing a few checks. It is assumed that the incoming interface
7213  * of the packet is always different than the outgoing interface and the
7214  * ire_type of the found ire has to be a non-resolver type.
7215  *
7216  * IPQoS notes
7217  * IP policy is invoked twice for a forwarded packet, once on the read side
7218  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7219  * enabled.
7220  */
7221 static void
7222 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7223 {
7224 	ipha_t		*ipha;
7225 	queue_t		*q;
7226 	uint32_t 	pkt_len;
7227 #define	rptr    ((uchar_t *)ipha)
7228 	uint32_t 	sum;
7229 	uint32_t 	max_frag;
7230 	mblk_t		*first_mp;
7231 	uint32_t	ill_index;
7232 	ipxmit_state_t	pktxmit_state;
7233 	ill_t		*out_ill;
7234 
7235 	ASSERT(ire != NULL);
7236 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7237 	ASSERT(ire->ire_stq != NULL);
7238 
7239 	/* Initiate read side IPPF processing */
7240 	if (IPP_ENABLED(IPP_FWD_IN)) {
7241 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7242 		ip_process(IPP_FWD_IN, &mp, ill_index);
7243 		if (mp == NULL) {
7244 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7245 			    "dropped during IPPF processing\n"));
7246 			return;
7247 		}
7248 	}
7249 
7250 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7251 		ILLF_ROUTER) == 0) ||
7252 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7253 		BUMP_MIB(&ip_mib, ipForwProhibits);
7254 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7255 		    "forwarding is not turned on\n"));
7256 		goto drop_pkt;
7257 	}
7258 
7259 	/*
7260 	 * Don't forward if the interface is down
7261 	 */
7262 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7263 		BUMP_MIB(&ip_mib, ipInDiscards);
7264 		goto drop_pkt;
7265 	}
7266 
7267 	ipha = (ipha_t *)mp->b_rptr;
7268 	pkt_len = ntohs(ipha->ipha_length);
7269 	/* Adjust the checksum to reflect the ttl decrement. */
7270 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7271 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7272 	if (ipha->ipha_ttl-- <= 1) {
7273 		if (ip_csum_hdr(ipha)) {
7274 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7275 			goto drop_pkt;
7276 		}
7277 		q = ire->ire_stq;
7278 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7279 		    BPRI_HI)) == NULL) {
7280 			goto drop_pkt;
7281 		}
7282 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7283 		/* Sent by forwarding path, and router is global zone */
7284 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7285 		    GLOBAL_ZONEID);
7286 		return;
7287 	}
7288 
7289 	/* Get the ill_index of the ILL */
7290 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7291 
7292 	/*
7293 	 * This location is chosen for the placement of the forwarding hook
7294 	 * because at this point we know that we have a path out for the
7295 	 * packet but haven't yet applied any logic (such as fragmenting)
7296 	 * that happen as part of transmitting the packet out.
7297 	 */
7298 	out_ill = ire->ire_ipif->ipif_ill;
7299 
7300 	DTRACE_PROBE4(ip4__forwarding__start,
7301 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7302 
7303 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
7304 	    in_ill, out_ill, ipha, mp, mp);
7305 
7306 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7307 
7308 	if (mp == NULL)
7309 		return;
7310 	pkt_len = ntohs(ipha->ipha_length);
7311 
7312 	/*
7313 	 * ip_mrtun_forward is only used by foreign agent to reverse
7314 	 * tunnel the incoming packet. So it does not do any option
7315 	 * processing for source routing.
7316 	 */
7317 	max_frag = ire->ire_max_frag;
7318 	if (pkt_len > max_frag) {
7319 		/*
7320 		 * It needs fragging on its way out.  We haven't
7321 		 * verified the header checksum yet.  Since we
7322 		 * are going to put a surely good checksum in the
7323 		 * outgoing header, we have to make sure that it
7324 		 * was good coming in.
7325 		 */
7326 		if (ip_csum_hdr(ipha)) {
7327 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7328 			goto drop_pkt;
7329 		}
7330 
7331 		/* Initiate write side IPPF processing */
7332 		if (IPP_ENABLED(IPP_FWD_OUT)) {
7333 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7334 			if (mp == NULL) {
7335 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7336 				    "dropped/deferred during ip policy "\
7337 				    "processing\n"));
7338 				return;
7339 			}
7340 		}
7341 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7342 		    BPRI_HI)) == NULL) {
7343 			goto drop_pkt;
7344 		}
7345 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7346 		mp = first_mp;
7347 
7348 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
7349 		return;
7350 	}
7351 
7352 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7353 
7354 	ASSERT(ire->ire_ipif != NULL);
7355 
7356 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7357 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7358 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
7359 	    NULL, out_ill, ipha, mp, mp);
7360 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7361 	if (mp == NULL)
7362 		return;
7363 
7364 	/* Now send the packet to the tunnel interface */
7365 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7366 	q = ire->ire_stq;
7367 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7368 	if ((pktxmit_state == SEND_FAILED) ||
7369 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7370 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7371 		    q->q_ptr));
7372 	}
7373 
7374 	return;
7375 
7376 drop_pkt:;
7377 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7378 	freemsg(mp);
7379 #undef	rptr
7380 }
7381 
7382 /*
7383  * Fills the ipsec_out_t data structure with appropriate fields and
7384  * prepends it to mp which contains the IP hdr + data that was meant
7385  * to be forwarded. Please note that ipsec_out_info data structure
7386  * is used here to communicate the outgoing ill path at ip_wput()
7387  * for the ICMP error packet. This has nothing to do with ipsec IP
7388  * security. ipsec_out_t is really used to pass the info to the module
7389  * IP where this information cannot be extracted from conn.
7390  * This functions is called by ip_mrtun_forward().
7391  */
7392 void
7393 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7394 {
7395 	ipsec_out_t	*io;
7396 
7397 	ASSERT(xmit_ill != NULL);
7398 	first_mp->b_datap->db_type = M_CTL;
7399 	first_mp->b_wptr += sizeof (ipsec_info_t);
7400 	/*
7401 	 * This is to pass info to ip_wput in absence of conn.
7402 	 * ipsec_out_secure will be B_FALSE because of this.
7403 	 * Thus ipsec_out_secure being B_FALSE indicates that
7404 	 * this is not IPSEC security related information.
7405 	 */
7406 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7407 	io = (ipsec_out_t *)first_mp->b_rptr;
7408 	io->ipsec_out_type = IPSEC_OUT;
7409 	io->ipsec_out_len = sizeof (ipsec_out_t);
7410 	first_mp->b_cont = mp;
7411 	io->ipsec_out_ill_index =
7412 	    xmit_ill->ill_phyint->phyint_ifindex;
7413 	io->ipsec_out_xmit_if = B_TRUE;
7414 }
7415 
7416 /*
7417  * Return the network mask
7418  * associated with the specified address.
7419  */
7420 ipaddr_t
7421 ip_net_mask(ipaddr_t addr)
7422 {
7423 	uchar_t	*up = (uchar_t *)&addr;
7424 	ipaddr_t mask = 0;
7425 	uchar_t	*maskp = (uchar_t *)&mask;
7426 
7427 #if defined(__i386) || defined(__amd64)
7428 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7429 #endif
7430 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7431 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7432 #endif
7433 	if (CLASSD(addr)) {
7434 		maskp[0] = 0xF0;
7435 		return (mask);
7436 	}
7437 	if (addr == 0)
7438 		return (0);
7439 	maskp[0] = 0xFF;
7440 	if ((up[0] & 0x80) == 0)
7441 		return (mask);
7442 
7443 	maskp[1] = 0xFF;
7444 	if ((up[0] & 0xC0) == 0x80)
7445 		return (mask);
7446 
7447 	maskp[2] = 0xFF;
7448 	if ((up[0] & 0xE0) == 0xC0)
7449 		return (mask);
7450 
7451 	/* Must be experimental or multicast, indicate as much */
7452 	return ((ipaddr_t)0);
7453 }
7454 
7455 /*
7456  * Select an ill for the packet by considering load spreading across
7457  * a different ill in the group if dst_ill is part of some group.
7458  */
7459 ill_t *
7460 ip_newroute_get_dst_ill(ill_t *dst_ill)
7461 {
7462 	ill_t *ill;
7463 
7464 	/*
7465 	 * We schedule irrespective of whether the source address is
7466 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7467 	 */
7468 	ill = illgrp_scheduler(dst_ill);
7469 	if (ill == NULL)
7470 		return (NULL);
7471 
7472 	/*
7473 	 * For groups with names ip_sioctl_groupname ensures that all
7474 	 * ills are of same type. For groups without names, ifgrp_insert
7475 	 * ensures this.
7476 	 */
7477 	ASSERT(dst_ill->ill_type == ill->ill_type);
7478 
7479 	return (ill);
7480 }
7481 
7482 /*
7483  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7484  */
7485 ill_t *
7486 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7487 {
7488 	ill_t *ret_ill;
7489 
7490 	ASSERT(ifindex != 0);
7491 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7492 	if (ret_ill == NULL ||
7493 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7494 		if (isv6) {
7495 			if (ill != NULL) {
7496 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7497 			} else {
7498 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7499 			}
7500 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7501 			    "bad ifindex %d.\n", ifindex));
7502 		} else {
7503 			BUMP_MIB(&ip_mib, ipOutDiscards);
7504 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7505 			    "bad ifindex %d.\n", ifindex));
7506 		}
7507 		if (ret_ill != NULL)
7508 			ill_refrele(ret_ill);
7509 		freemsg(first_mp);
7510 		return (NULL);
7511 	}
7512 
7513 	return (ret_ill);
7514 }
7515 
7516 /*
7517  * IPv4 -
7518  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7519  * out a packet to a destination address for which we do not have specific
7520  * (or sufficient) routing information.
7521  *
7522  * NOTE : These are the scopes of some of the variables that point at IRE,
7523  *	  which needs to be followed while making any future modifications
7524  *	  to avoid memory leaks.
7525  *
7526  *	- ire and sire are the entries looked up initially by
7527  *	  ire_ftable_lookup.
7528  *	- ipif_ire is used to hold the interface ire associated with
7529  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7530  *	  it before branching out to error paths.
7531  *	- save_ire is initialized before ire_create, so that ire returned
7532  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7533  *	  before breaking out of the switch.
7534  *
7535  *	Thus on failures, we have to REFRELE only ire and sire, if they
7536  *	are not NULL.
7537  */
7538 void
7539 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7540     zoneid_t zoneid)
7541 {
7542 	areq_t	*areq;
7543 	ipaddr_t gw = 0;
7544 	ire_t	*ire = NULL;
7545 	mblk_t	*res_mp;
7546 	ipaddr_t *addrp;
7547 	ipaddr_t nexthop_addr;
7548 	ipif_t  *src_ipif = NULL;
7549 	ill_t	*dst_ill = NULL;
7550 	ipha_t  *ipha;
7551 	ire_t	*sire = NULL;
7552 	mblk_t	*first_mp;
7553 	ire_t	*save_ire;
7554 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7555 	ushort_t ire_marks = 0;
7556 	boolean_t mctl_present;
7557 	ipsec_out_t *io;
7558 	mblk_t	*saved_mp;
7559 	ire_t	*first_sire = NULL;
7560 	mblk_t	*copy_mp = NULL;
7561 	mblk_t	*xmit_mp = NULL;
7562 	ipaddr_t save_dst;
7563 	uint32_t multirt_flags =
7564 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7565 	boolean_t multirt_is_resolvable;
7566 	boolean_t multirt_resolve_next;
7567 	boolean_t do_attach_ill = B_FALSE;
7568 	boolean_t ip_nexthop = B_FALSE;
7569 	tsol_ire_gw_secattr_t *attrp = NULL;
7570 	tsol_gcgrp_t *gcgrp = NULL;
7571 	tsol_gcgrp_addr_t ga;
7572 
7573 	if (ip_debug > 2) {
7574 		/* ip1dbg */
7575 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7576 	}
7577 
7578 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7579 	if (mctl_present) {
7580 		io = (ipsec_out_t *)first_mp->b_rptr;
7581 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7582 		ASSERT(zoneid == io->ipsec_out_zoneid);
7583 		ASSERT(zoneid != ALL_ZONES);
7584 	}
7585 
7586 	ipha = (ipha_t *)mp->b_rptr;
7587 
7588 	/* All multicast lookups come through ip_newroute_ipif() */
7589 	if (CLASSD(dst)) {
7590 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7591 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7592 		freemsg(first_mp);
7593 		return;
7594 	}
7595 
7596 	if (mctl_present && io->ipsec_out_attach_if) {
7597 		/* ip_grab_attach_ill returns a held ill */
7598 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7599 		    io->ipsec_out_ill_index, B_FALSE);
7600 
7601 		/* Failure case frees things for us. */
7602 		if (attach_ill == NULL)
7603 			return;
7604 
7605 		/*
7606 		 * Check if we need an ire that will not be
7607 		 * looked up by anybody else i.e. HIDDEN.
7608 		 */
7609 		if (ill_is_probeonly(attach_ill))
7610 			ire_marks = IRE_MARK_HIDDEN;
7611 	}
7612 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7613 		ip_nexthop = B_TRUE;
7614 		nexthop_addr = io->ipsec_out_nexthop_addr;
7615 	}
7616 	/*
7617 	 * If this IRE is created for forwarding or it is not for
7618 	 * traffic for congestion controlled protocols, mark it as temporary.
7619 	 */
7620 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7621 		ire_marks |= IRE_MARK_TEMPORARY;
7622 
7623 	/*
7624 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7625 	 * chain until it gets the most specific information available.
7626 	 * For example, we know that there is no IRE_CACHE for this dest,
7627 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7628 	 * ire_ftable_lookup will look up the gateway, etc.
7629 	 * Check if in_ill != NULL. If it is true, the packet must be
7630 	 * from an incoming interface where RTA_SRCIFP is set.
7631 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7632 	 * to the destination, of equal netmask length in the forward table,
7633 	 * will be recursively explored. If no information is available
7634 	 * for the final gateway of that route, we force the returned ire
7635 	 * to be equal to sire using MATCH_IRE_PARENT.
7636 	 * At least, in this case we have a starting point (in the buckets)
7637 	 * to look for other routes to the destination in the forward table.
7638 	 * This is actually used only for multirouting, where a list
7639 	 * of routes has to be processed in sequence.
7640 	 *
7641 	 * In the process of coming up with the most specific information,
7642 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7643 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7644 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7645 	 * Two caveats when handling incomplete ire's in ip_newroute:
7646 	 * - we should be careful when accessing its ire_nce (specifically
7647 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7648 	 * - not all legacy code path callers are prepared to handle
7649 	 *   incomplete ire's, so we should not create/add incomplete
7650 	 *   ire_cache entries here. (See discussion about temporary solution
7651 	 *   further below).
7652 	 *
7653 	 * In order to minimize packet dropping, and to preserve existing
7654 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7655 	 * gateway, and instead use the IF_RESOLVER ire to send out
7656 	 * another request to ARP (this is achieved by passing the
7657 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7658 	 * arp response comes back in ip_wput_nondata, we will create
7659 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7660 	 *
7661 	 * Note that this is a temporary solution; the correct solution is
7662 	 * to create an incomplete  per-dst ire_cache entry, and send the
7663 	 * packet out when the gw's nce is resolved. In order to achieve this,
7664 	 * all packet processing must have been completed prior to calling
7665 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7666 	 * to be modified to accomodate this solution.
7667 	 */
7668 	if (in_ill != NULL) {
7669 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7670 		    in_ill, MATCH_IRE_TYPE);
7671 	} else if (ip_nexthop) {
7672 		/*
7673 		 * The first time we come here, we look for an IRE_INTERFACE
7674 		 * entry for the specified nexthop, set the dst to be the
7675 		 * nexthop address and create an IRE_CACHE entry for the
7676 		 * nexthop. The next time around, we are able to find an
7677 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7678 		 * nexthop address and create an IRE_CACHE entry for the
7679 		 * destination address via the specified nexthop.
7680 		 */
7681 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7682 		    MBLK_GETLABEL(mp));
7683 		if (ire != NULL) {
7684 			gw = nexthop_addr;
7685 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7686 		} else {
7687 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7688 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7689 			    MBLK_GETLABEL(mp),
7690 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7691 			if (ire != NULL) {
7692 				dst = nexthop_addr;
7693 			}
7694 		}
7695 	} else if (attach_ill == NULL) {
7696 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7697 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7698 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7699 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7700 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7701 	} else {
7702 		/*
7703 		 * attach_ill is set only for communicating with
7704 		 * on-link hosts. So, don't look for DEFAULT.
7705 		 */
7706 		ipif_t	*attach_ipif;
7707 
7708 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7709 		if (attach_ipif == NULL) {
7710 			ill_refrele(attach_ill);
7711 			goto icmp_err_ret;
7712 		}
7713 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7714 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7715 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7716 		    MATCH_IRE_SECATTR);
7717 		ipif_refrele(attach_ipif);
7718 	}
7719 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7720 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7721 
7722 	/*
7723 	 * This loop is run only once in most cases.
7724 	 * We loop to resolve further routes only when the destination
7725 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7726 	 */
7727 	do {
7728 		/* Clear the previous iteration's values */
7729 		if (src_ipif != NULL) {
7730 			ipif_refrele(src_ipif);
7731 			src_ipif = NULL;
7732 		}
7733 		if (dst_ill != NULL) {
7734 			ill_refrele(dst_ill);
7735 			dst_ill = NULL;
7736 		}
7737 
7738 		multirt_resolve_next = B_FALSE;
7739 		/*
7740 		 * We check if packets have to be multirouted.
7741 		 * In this case, given the current <ire, sire> couple,
7742 		 * we look for the next suitable <ire, sire>.
7743 		 * This check is done in ire_multirt_lookup(),
7744 		 * which applies various criteria to find the next route
7745 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7746 		 * unchanged if it detects it has not been tried yet.
7747 		 */
7748 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7749 			ip3dbg(("ip_newroute: starting next_resolution "
7750 			    "with first_mp %p, tag %d\n",
7751 			    (void *)first_mp,
7752 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7753 
7754 			ASSERT(sire != NULL);
7755 			multirt_is_resolvable =
7756 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7757 				MBLK_GETLABEL(mp));
7758 
7759 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7760 			    "ire %p, sire %p\n",
7761 			    multirt_is_resolvable,
7762 			    (void *)ire, (void *)sire));
7763 
7764 			if (!multirt_is_resolvable) {
7765 				/*
7766 				 * No more multirt route to resolve; give up
7767 				 * (all routes resolved or no more
7768 				 * resolvable routes).
7769 				 */
7770 				if (ire != NULL) {
7771 					ire_refrele(ire);
7772 					ire = NULL;
7773 				}
7774 			} else {
7775 				ASSERT(sire != NULL);
7776 				ASSERT(ire != NULL);
7777 				/*
7778 				 * We simply use first_sire as a flag that
7779 				 * indicates if a resolvable multirt route
7780 				 * has already been found.
7781 				 * If it is not the case, we may have to send
7782 				 * an ICMP error to report that the
7783 				 * destination is unreachable.
7784 				 * We do not IRE_REFHOLD first_sire.
7785 				 */
7786 				if (first_sire == NULL) {
7787 					first_sire = sire;
7788 				}
7789 			}
7790 		}
7791 		if (ire == NULL) {
7792 			if (ip_debug > 3) {
7793 				/* ip2dbg */
7794 				pr_addr_dbg("ip_newroute: "
7795 				    "can't resolve %s\n", AF_INET, &dst);
7796 			}
7797 			ip3dbg(("ip_newroute: "
7798 			    "ire %p, sire %p, first_sire %p\n",
7799 			    (void *)ire, (void *)sire, (void *)first_sire));
7800 
7801 			if (sire != NULL) {
7802 				ire_refrele(sire);
7803 				sire = NULL;
7804 			}
7805 
7806 			if (first_sire != NULL) {
7807 				/*
7808 				 * At least one multirt route has been found
7809 				 * in the same call to ip_newroute();
7810 				 * there is no need to report an ICMP error.
7811 				 * first_sire was not IRE_REFHOLDed.
7812 				 */
7813 				MULTIRT_DEBUG_UNTAG(first_mp);
7814 				freemsg(first_mp);
7815 				return;
7816 			}
7817 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7818 			    RTA_DST);
7819 			if (attach_ill != NULL)
7820 				ill_refrele(attach_ill);
7821 			goto icmp_err_ret;
7822 		}
7823 
7824 		/*
7825 		 * When RTA_SRCIFP is used to add a route, then an interface
7826 		 * route is added in the source interface's routing table.
7827 		 * If the outgoing interface of this route is of type
7828 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7829 		 * ire_nce->nce_res_mp is set to NULL.
7830 		 * Later, when this route is first used for forwarding
7831 		 * a packet, ip_newroute() is called
7832 		 * to resolve the hardware address of the outgoing ipif.
7833 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7834 		 * source interface based table. We only come here if the
7835 		 * outgoing interface is a resolver interface and we don't
7836 		 * have the ire_nce->nce_res_mp information yet.
7837 		 * If in_ill is not null that means it is called from
7838 		 * ip_rput.
7839 		 */
7840 
7841 		ASSERT(ire->ire_in_ill == NULL ||
7842 		    (ire->ire_type == IRE_IF_RESOLVER &&
7843 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
7844 
7845 		/*
7846 		 * Verify that the returned IRE does not have either
7847 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7848 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7849 		 */
7850 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7851 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7852 			if (attach_ill != NULL)
7853 				ill_refrele(attach_ill);
7854 			goto icmp_err_ret;
7855 		}
7856 		/*
7857 		 * Increment the ire_ob_pkt_count field for ire if it is an
7858 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7859 		 * increment the same for the parent IRE, sire, if it is some
7860 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7861 		 * and HOST_REDIRECT).
7862 		 */
7863 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7864 			UPDATE_OB_PKT_COUNT(ire);
7865 			ire->ire_last_used_time = lbolt;
7866 		}
7867 
7868 		if (sire != NULL) {
7869 			gw = sire->ire_gateway_addr;
7870 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7871 			    IRE_INTERFACE)) == 0);
7872 			UPDATE_OB_PKT_COUNT(sire);
7873 			sire->ire_last_used_time = lbolt;
7874 		}
7875 		/*
7876 		 * We have a route to reach the destination.
7877 		 *
7878 		 * 1) If the interface is part of ill group, try to get a new
7879 		 *    ill taking load spreading into account.
7880 		 *
7881 		 * 2) After selecting the ill, get a source address that
7882 		 *    might create good inbound load spreading.
7883 		 *    ipif_select_source does this for us.
7884 		 *
7885 		 * If the application specified the ill (ifindex), we still
7886 		 * load spread. Only if the packets needs to go out
7887 		 * specifically on a given ill e.g. binding to
7888 		 * IPIF_NOFAILOVER address, then we don't try to use a
7889 		 * different ill for load spreading.
7890 		 */
7891 		if (attach_ill == NULL) {
7892 			/*
7893 			 * Don't perform outbound load spreading in the
7894 			 * case of an RTF_MULTIRT route, as we actually
7895 			 * typically want to replicate outgoing packets
7896 			 * through particular interfaces.
7897 			 */
7898 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7899 				dst_ill = ire->ire_ipif->ipif_ill;
7900 				/* for uniformity */
7901 				ill_refhold(dst_ill);
7902 			} else {
7903 				/*
7904 				 * If we are here trying to create an IRE_CACHE
7905 				 * for an offlink destination and have the
7906 				 * IRE_CACHE for the next hop and the latter is
7907 				 * using virtual IP source address selection i.e
7908 				 * it's ire->ire_ipif is pointing to a virtual
7909 				 * network interface (vni) then
7910 				 * ip_newroute_get_dst_ll() will return the vni
7911 				 * interface as the dst_ill. Since the vni is
7912 				 * virtual i.e not associated with any physical
7913 				 * interface, it cannot be the dst_ill, hence
7914 				 * in such a case call ip_newroute_get_dst_ll()
7915 				 * with the stq_ill instead of the ire_ipif ILL.
7916 				 * The function returns a refheld ill.
7917 				 */
7918 				if ((ire->ire_type == IRE_CACHE) &&
7919 				    IS_VNI(ire->ire_ipif->ipif_ill))
7920 					dst_ill = ip_newroute_get_dst_ill(
7921 						ire->ire_stq->q_ptr);
7922 				else
7923 					dst_ill = ip_newroute_get_dst_ill(
7924 						ire->ire_ipif->ipif_ill);
7925 			}
7926 			if (dst_ill == NULL) {
7927 				if (ip_debug > 2) {
7928 					pr_addr_dbg("ip_newroute: "
7929 					    "no dst ill for dst"
7930 					    " %s\n", AF_INET, &dst);
7931 				}
7932 				goto icmp_err_ret;
7933 			}
7934 		} else {
7935 			dst_ill = ire->ire_ipif->ipif_ill;
7936 			/* for uniformity */
7937 			ill_refhold(dst_ill);
7938 			/*
7939 			 * We should have found a route matching ill as we
7940 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7941 			 * Rather than asserting, when there is a mismatch,
7942 			 * we just drop the packet.
7943 			 */
7944 			if (dst_ill != attach_ill) {
7945 				ip0dbg(("ip_newroute: Packet dropped as "
7946 				    "IPIF_NOFAILOVER ill is %s, "
7947 				    "ire->ire_ipif->ipif_ill is %s\n",
7948 				    attach_ill->ill_name,
7949 				    dst_ill->ill_name));
7950 				ill_refrele(attach_ill);
7951 				goto icmp_err_ret;
7952 			}
7953 		}
7954 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7955 		if (attach_ill != NULL) {
7956 			ill_refrele(attach_ill);
7957 			attach_ill = NULL;
7958 			do_attach_ill = B_TRUE;
7959 		}
7960 		ASSERT(dst_ill != NULL);
7961 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7962 
7963 		/*
7964 		 * Pick the best source address from dst_ill.
7965 		 *
7966 		 * 1) If it is part of a multipathing group, we would
7967 		 *    like to spread the inbound packets across different
7968 		 *    interfaces. ipif_select_source picks a random source
7969 		 *    across the different ills in the group.
7970 		 *
7971 		 * 2) If it is not part of a multipathing group, we try
7972 		 *    to pick the source address from the destination
7973 		 *    route. Clustering assumes that when we have multiple
7974 		 *    prefixes hosted on an interface, the prefix of the
7975 		 *    source address matches the prefix of the destination
7976 		 *    route. We do this only if the address is not
7977 		 *    DEPRECATED.
7978 		 *
7979 		 * 3) If the conn is in a different zone than the ire, we
7980 		 *    need to pick a source address from the right zone.
7981 		 *
7982 		 * NOTE : If we hit case (1) above, the prefix of the source
7983 		 *	  address picked may not match the prefix of the
7984 		 *	  destination routes prefix as ipif_select_source
7985 		 *	  does not look at "dst" while picking a source
7986 		 *	  address.
7987 		 *	  If we want the same behavior as (2), we will need
7988 		 *	  to change the behavior of ipif_select_source.
7989 		 */
7990 		ASSERT(src_ipif == NULL);
7991 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7992 			/*
7993 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7994 			 * Check that the ipif matching the requested source
7995 			 * address still exists.
7996 			 */
7997 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7998 			    zoneid, NULL, NULL, NULL, NULL);
7999 		}
8000 		if (src_ipif == NULL) {
8001 			ire_marks |= IRE_MARK_USESRC_CHECK;
8002 			if ((dst_ill->ill_group != NULL) ||
8003 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8004 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8005 			    ire->ire_zoneid != ALL_ZONES) ||
8006 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8007 				/*
8008 				 * If the destination is reachable via a
8009 				 * given gateway, the selected source address
8010 				 * should be in the same subnet as the gateway.
8011 				 * Otherwise, the destination is not reachable.
8012 				 *
8013 				 * If there are no interfaces on the same subnet
8014 				 * as the destination, ipif_select_source gives
8015 				 * first non-deprecated interface which might be
8016 				 * on a different subnet than the gateway.
8017 				 * This is not desirable. Hence pass the dst_ire
8018 				 * source address to ipif_select_source.
8019 				 * It is sure that the destination is reachable
8020 				 * with the dst_ire source address subnet.
8021 				 * So passing dst_ire source address to
8022 				 * ipif_select_source will make sure that the
8023 				 * selected source will be on the same subnet
8024 				 * as dst_ire source address.
8025 				 */
8026 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8027 				src_ipif = ipif_select_source(dst_ill, saddr,
8028 				    zoneid);
8029 				if (src_ipif == NULL) {
8030 					if (ip_debug > 2) {
8031 						pr_addr_dbg("ip_newroute: "
8032 						    "no src for dst %s ",
8033 						    AF_INET, &dst);
8034 						printf("through interface %s\n",
8035 						    dst_ill->ill_name);
8036 					}
8037 					goto icmp_err_ret;
8038 				}
8039 			} else {
8040 				src_ipif = ire->ire_ipif;
8041 				ASSERT(src_ipif != NULL);
8042 				/* hold src_ipif for uniformity */
8043 				ipif_refhold(src_ipif);
8044 			}
8045 		}
8046 
8047 		/*
8048 		 * Assign a source address while we have the conn.
8049 		 * We can't have ip_wput_ire pick a source address when the
8050 		 * packet returns from arp since we need to look at
8051 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8052 		 * going through arp.
8053 		 *
8054 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8055 		 *	  it uses ip6i to store this information.
8056 		 */
8057 		if (ipha->ipha_src == INADDR_ANY &&
8058 		    (connp == NULL || !connp->conn_unspec_src)) {
8059 			ipha->ipha_src = src_ipif->ipif_src_addr;
8060 		}
8061 		if (ip_debug > 3) {
8062 			/* ip2dbg */
8063 			pr_addr_dbg("ip_newroute: first hop %s\n",
8064 			    AF_INET, &gw);
8065 		}
8066 		ip2dbg(("\tire type %s (%d)\n",
8067 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8068 
8069 		/*
8070 		 * The TTL of multirouted packets is bounded by the
8071 		 * ip_multirt_ttl ndd variable.
8072 		 */
8073 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8074 			/* Force TTL of multirouted packets */
8075 			if ((ip_multirt_ttl > 0) &&
8076 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
8077 				ip2dbg(("ip_newroute: forcing multirt TTL "
8078 				    "to %d (was %d), dst 0x%08x\n",
8079 				    ip_multirt_ttl, ipha->ipha_ttl,
8080 				    ntohl(sire->ire_addr)));
8081 				ipha->ipha_ttl = ip_multirt_ttl;
8082 			}
8083 		}
8084 		/*
8085 		 * At this point in ip_newroute(), ire is either the
8086 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8087 		 * destination or an IRE_INTERFACE type that should be used
8088 		 * to resolve an on-subnet destination or an on-subnet
8089 		 * next-hop gateway.
8090 		 *
8091 		 * In the IRE_CACHE case, we have the following :
8092 		 *
8093 		 * 1) src_ipif - used for getting a source address.
8094 		 *
8095 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8096 		 *    means packets using this IRE_CACHE will go out on
8097 		 *    dst_ill.
8098 		 *
8099 		 * 3) The IRE sire will point to the prefix that is the
8100 		 *    longest  matching route for the destination. These
8101 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8102 		 *
8103 		 *    The newly created IRE_CACHE entry for the off-subnet
8104 		 *    destination is tied to both the prefix route and the
8105 		 *    interface route used to resolve the next-hop gateway
8106 		 *    via the ire_phandle and ire_ihandle fields,
8107 		 *    respectively.
8108 		 *
8109 		 * In the IRE_INTERFACE case, we have the following :
8110 		 *
8111 		 * 1) src_ipif - used for getting a source address.
8112 		 *
8113 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8114 		 *    means packets using the IRE_CACHE that we will build
8115 		 *    here will go out on dst_ill.
8116 		 *
8117 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8118 		 *    to be created will only be tied to the IRE_INTERFACE
8119 		 *    that was derived from the ire_ihandle field.
8120 		 *
8121 		 *    If sire is non-NULL, it means the destination is
8122 		 *    off-link and we will first create the IRE_CACHE for the
8123 		 *    gateway. Next time through ip_newroute, we will create
8124 		 *    the IRE_CACHE for the final destination as described
8125 		 *    above.
8126 		 *
8127 		 * In both cases, after the current resolution has been
8128 		 * completed (or possibly initialised, in the IRE_INTERFACE
8129 		 * case), the loop may be re-entered to attempt the resolution
8130 		 * of another RTF_MULTIRT route.
8131 		 *
8132 		 * When an IRE_CACHE entry for the off-subnet destination is
8133 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8134 		 * for further processing in emission loops.
8135 		 */
8136 		save_ire = ire;
8137 		switch (ire->ire_type) {
8138 		case IRE_CACHE: {
8139 			ire_t	*ipif_ire;
8140 			mblk_t	*ire_fp_mp;
8141 
8142 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8143 			if (gw == 0)
8144 				gw = ire->ire_gateway_addr;
8145 			/*
8146 			 * We need 3 ire's to create a new cache ire for an
8147 			 * off-link destination from the cache ire of the
8148 			 * gateway.
8149 			 *
8150 			 *	1. The prefix ire 'sire' (Note that this does
8151 			 *	   not apply to the conn_nexthop_set case)
8152 			 *	2. The cache ire of the gateway 'ire'
8153 			 *	3. The interface ire 'ipif_ire'
8154 			 *
8155 			 * We have (1) and (2). We lookup (3) below.
8156 			 *
8157 			 * If there is no interface route to the gateway,
8158 			 * it is a race condition, where we found the cache
8159 			 * but the interface route has been deleted.
8160 			 */
8161 			if (ip_nexthop) {
8162 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8163 			} else {
8164 				ipif_ire =
8165 				    ire_ihandle_lookup_offlink(ire, sire);
8166 			}
8167 			if (ipif_ire == NULL) {
8168 				ip1dbg(("ip_newroute: "
8169 				    "ire_ihandle_lookup_offlink failed\n"));
8170 				goto icmp_err_ret;
8171 			}
8172 			/*
8173 			 * XXX We are using the same res_mp
8174 			 * (DL_UNITDATA_REQ) though the save_ire is not
8175 			 * pointing at the same ill.
8176 			 * This is incorrect. We need to send it up to the
8177 			 * resolver to get the right res_mp. For ethernets
8178 			 * this may be okay (ill_type == DL_ETHER).
8179 			 */
8180 			res_mp = save_ire->ire_nce->nce_res_mp;
8181 			ire_fp_mp = NULL;
8182 			/*
8183 			 * save_ire's nce_fp_mp can't change since it is
8184 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8185 			 * LOCK_IRE_FP_MP does not do any useful work in
8186 			 * the case of IRE_CACHE. So we don't use it below.
8187 			 */
8188 			if (save_ire->ire_stq == dst_ill->ill_wq)
8189 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8190 
8191 			/*
8192 			 * Check cached gateway IRE for any security
8193 			 * attributes; if found, associate the gateway
8194 			 * credentials group to the destination IRE.
8195 			 */
8196 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8197 				mutex_enter(&attrp->igsa_lock);
8198 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8199 					GCGRP_REFHOLD(gcgrp);
8200 				mutex_exit(&attrp->igsa_lock);
8201 			}
8202 
8203 			ire = ire_create(
8204 			    (uchar_t *)&dst,		/* dest address */
8205 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8206 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8207 			    (uchar_t *)&gw,		/* gateway address */
8208 			    NULL,
8209 			    &save_ire->ire_max_frag,
8210 			    ire_fp_mp,			/* Fast Path header */
8211 			    dst_ill->ill_rq,		/* recv-from queue */
8212 			    dst_ill->ill_wq,		/* send-to queue */
8213 			    IRE_CACHE,			/* IRE type */
8214 			    res_mp,
8215 			    src_ipif,
8216 			    in_ill,			/* incoming ill */
8217 			    (sire != NULL) ?
8218 				sire->ire_mask : 0, 	/* Parent mask */
8219 			    (sire != NULL) ?
8220 				sire->ire_phandle : 0,  /* Parent handle */
8221 			    ipif_ire->ire_ihandle,	/* Interface handle */
8222 			    (sire != NULL) ? (sire->ire_flags &
8223 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8224 			    (sire != NULL) ?
8225 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8226 			    NULL,
8227 			    gcgrp);
8228 
8229 			if (ire == NULL) {
8230 				if (gcgrp != NULL) {
8231 					GCGRP_REFRELE(gcgrp);
8232 					gcgrp = NULL;
8233 				}
8234 				ire_refrele(ipif_ire);
8235 				ire_refrele(save_ire);
8236 				break;
8237 			}
8238 
8239 			/* reference now held by IRE */
8240 			gcgrp = NULL;
8241 
8242 			ire->ire_marks |= ire_marks;
8243 
8244 			/*
8245 			 * Prevent sire and ipif_ire from getting deleted.
8246 			 * The newly created ire is tied to both of them via
8247 			 * the phandle and ihandle respectively.
8248 			 */
8249 			if (sire != NULL) {
8250 				IRB_REFHOLD(sire->ire_bucket);
8251 				/* Has it been removed already ? */
8252 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8253 					IRB_REFRELE(sire->ire_bucket);
8254 					ire_refrele(ipif_ire);
8255 					ire_refrele(save_ire);
8256 					break;
8257 				}
8258 			}
8259 
8260 			IRB_REFHOLD(ipif_ire->ire_bucket);
8261 			/* Has it been removed already ? */
8262 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8263 				IRB_REFRELE(ipif_ire->ire_bucket);
8264 				if (sire != NULL)
8265 					IRB_REFRELE(sire->ire_bucket);
8266 				ire_refrele(ipif_ire);
8267 				ire_refrele(save_ire);
8268 				break;
8269 			}
8270 
8271 			xmit_mp = first_mp;
8272 			/*
8273 			 * In the case of multirouting, a copy
8274 			 * of the packet is done before its sending.
8275 			 * The copy is used to attempt another
8276 			 * route resolution, in a next loop.
8277 			 */
8278 			if (ire->ire_flags & RTF_MULTIRT) {
8279 				copy_mp = copymsg(first_mp);
8280 				if (copy_mp != NULL) {
8281 					xmit_mp = copy_mp;
8282 					MULTIRT_DEBUG_TAG(first_mp);
8283 				}
8284 			}
8285 			ire_add_then_send(q, ire, xmit_mp);
8286 			ire_refrele(save_ire);
8287 
8288 			/* Assert that sire is not deleted yet. */
8289 			if (sire != NULL) {
8290 				ASSERT(sire->ire_ptpn != NULL);
8291 				IRB_REFRELE(sire->ire_bucket);
8292 			}
8293 
8294 			/* Assert that ipif_ire is not deleted yet. */
8295 			ASSERT(ipif_ire->ire_ptpn != NULL);
8296 			IRB_REFRELE(ipif_ire->ire_bucket);
8297 			ire_refrele(ipif_ire);
8298 
8299 			/*
8300 			 * If copy_mp is not NULL, multirouting was
8301 			 * requested. We loop to initiate a next
8302 			 * route resolution attempt, starting from sire.
8303 			 */
8304 			if (copy_mp != NULL) {
8305 				/*
8306 				 * Search for the next unresolved
8307 				 * multirt route.
8308 				 */
8309 				copy_mp = NULL;
8310 				ipif_ire = NULL;
8311 				ire = NULL;
8312 				multirt_resolve_next = B_TRUE;
8313 				continue;
8314 			}
8315 			if (sire != NULL)
8316 				ire_refrele(sire);
8317 			ipif_refrele(src_ipif);
8318 			ill_refrele(dst_ill);
8319 			return;
8320 		}
8321 		case IRE_IF_NORESOLVER: {
8322 			/*
8323 			 * We have what we need to build an IRE_CACHE.
8324 			 *
8325 			 * Create a new res_mp with the IP gateway address
8326 			 * in destination address in the DLPI hdr if the
8327 			 * physical length is exactly 4 bytes.
8328 			 */
8329 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8330 				uchar_t *addr;
8331 
8332 				if (gw)
8333 					addr = (uchar_t *)&gw;
8334 				else
8335 					addr = (uchar_t *)&dst;
8336 
8337 				res_mp = ill_dlur_gen(addr,
8338 				    dst_ill->ill_phys_addr_length,
8339 				    dst_ill->ill_sap,
8340 				    dst_ill->ill_sap_length);
8341 
8342 				if (res_mp == NULL) {
8343 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8344 					break;
8345 				}
8346 			} else {
8347 				res_mp = NULL;
8348 			}
8349 
8350 			/*
8351 			 * TSol note: We are creating the ire cache for the
8352 			 * destination 'dst'. If 'dst' is offlink, going
8353 			 * through the first hop 'gw', the security attributes
8354 			 * of 'dst' must be set to point to the gateway
8355 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8356 			 * is possible that 'dst' is a potential gateway that is
8357 			 * referenced by some route that has some security
8358 			 * attributes. Thus in the former case, we need to do a
8359 			 * gcgrp_lookup of 'gw' while in the latter case we
8360 			 * need to do gcgrp_lookup of 'dst' itself.
8361 			 */
8362 			ga.ga_af = AF_INET;
8363 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8364 			    &ga.ga_addr);
8365 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8366 
8367 			ire = ire_create(
8368 			    (uchar_t *)&dst,		/* dest address */
8369 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8370 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8371 			    (uchar_t *)&gw,		/* gateway address */
8372 			    NULL,
8373 			    &save_ire->ire_max_frag,
8374 			    NULL,			/* Fast Path header */
8375 			    dst_ill->ill_rq,		/* recv-from queue */
8376 			    dst_ill->ill_wq,		/* send-to queue */
8377 			    IRE_CACHE,
8378 			    res_mp,
8379 			    src_ipif,
8380 			    in_ill,			/* Incoming ill */
8381 			    save_ire->ire_mask,		/* Parent mask */
8382 			    (sire != NULL) ?		/* Parent handle */
8383 				sire->ire_phandle : 0,
8384 			    save_ire->ire_ihandle,	/* Interface handle */
8385 			    (sire != NULL) ? sire->ire_flags &
8386 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8387 			    &(save_ire->ire_uinfo),
8388 			    NULL,
8389 			    gcgrp);
8390 
8391 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8392 				freeb(res_mp);
8393 
8394 			if (ire == NULL) {
8395 				if (gcgrp != NULL) {
8396 					GCGRP_REFRELE(gcgrp);
8397 					gcgrp = NULL;
8398 				}
8399 				ire_refrele(save_ire);
8400 				break;
8401 			}
8402 
8403 			/* reference now held by IRE */
8404 			gcgrp = NULL;
8405 
8406 			ire->ire_marks |= ire_marks;
8407 
8408 			/* Prevent save_ire from getting deleted */
8409 			IRB_REFHOLD(save_ire->ire_bucket);
8410 			/* Has it been removed already ? */
8411 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8412 				IRB_REFRELE(save_ire->ire_bucket);
8413 				ire_refrele(save_ire);
8414 				break;
8415 			}
8416 
8417 			/*
8418 			 * In the case of multirouting, a copy
8419 			 * of the packet is made before it is sent.
8420 			 * The copy is used in the next
8421 			 * loop to attempt another resolution.
8422 			 */
8423 			xmit_mp = first_mp;
8424 			if ((sire != NULL) &&
8425 			    (sire->ire_flags & RTF_MULTIRT)) {
8426 				copy_mp = copymsg(first_mp);
8427 				if (copy_mp != NULL) {
8428 					xmit_mp = copy_mp;
8429 					MULTIRT_DEBUG_TAG(first_mp);
8430 				}
8431 			}
8432 			ire_add_then_send(q, ire, xmit_mp);
8433 
8434 			/* Assert that it is not deleted yet. */
8435 			ASSERT(save_ire->ire_ptpn != NULL);
8436 			IRB_REFRELE(save_ire->ire_bucket);
8437 			ire_refrele(save_ire);
8438 
8439 			if (copy_mp != NULL) {
8440 				/*
8441 				 * If we found a (no)resolver, we ignore any
8442 				 * trailing top priority IRE_CACHE in further
8443 				 * loops. This ensures that we do not omit any
8444 				 * (no)resolver.
8445 				 * This IRE_CACHE, if any, will be processed
8446 				 * by another thread entering ip_newroute().
8447 				 * IRE_CACHE entries, if any, will be processed
8448 				 * by another thread entering ip_newroute(),
8449 				 * (upon resolver response, for instance).
8450 				 * This aims to force parallel multirt
8451 				 * resolutions as soon as a packet must be sent.
8452 				 * In the best case, after the tx of only one
8453 				 * packet, all reachable routes are resolved.
8454 				 * Otherwise, the resolution of all RTF_MULTIRT
8455 				 * routes would require several emissions.
8456 				 */
8457 				multirt_flags &= ~MULTIRT_CACHEGW;
8458 
8459 				/*
8460 				 * Search for the next unresolved multirt
8461 				 * route.
8462 				 */
8463 				copy_mp = NULL;
8464 				save_ire = NULL;
8465 				ire = NULL;
8466 				multirt_resolve_next = B_TRUE;
8467 				continue;
8468 			}
8469 
8470 			/*
8471 			 * Don't need sire anymore
8472 			 */
8473 			if (sire != NULL)
8474 				ire_refrele(sire);
8475 
8476 			ipif_refrele(src_ipif);
8477 			ill_refrele(dst_ill);
8478 			return;
8479 		}
8480 		case IRE_IF_RESOLVER:
8481 			/*
8482 			 * We can't build an IRE_CACHE yet, but at least we
8483 			 * found a resolver that can help.
8484 			 */
8485 			res_mp = dst_ill->ill_resolver_mp;
8486 			if (!OK_RESOLVER_MP(res_mp))
8487 				break;
8488 
8489 			/*
8490 			 * To be at this point in the code with a non-zero gw
8491 			 * means that dst is reachable through a gateway that
8492 			 * we have never resolved.  By changing dst to the gw
8493 			 * addr we resolve the gateway first.
8494 			 * When ire_add_then_send() tries to put the IP dg
8495 			 * to dst, it will reenter ip_newroute() at which
8496 			 * time we will find the IRE_CACHE for the gw and
8497 			 * create another IRE_CACHE in case IRE_CACHE above.
8498 			 */
8499 			if (gw != INADDR_ANY) {
8500 				/*
8501 				 * The source ipif that was determined above was
8502 				 * relative to the destination address, not the
8503 				 * gateway's. If src_ipif was not taken out of
8504 				 * the IRE_IF_RESOLVER entry, we'll need to call
8505 				 * ipif_select_source() again.
8506 				 */
8507 				if (src_ipif != ire->ire_ipif) {
8508 					ipif_refrele(src_ipif);
8509 					src_ipif = ipif_select_source(dst_ill,
8510 					    gw, zoneid);
8511 					if (src_ipif == NULL) {
8512 						if (ip_debug > 2) {
8513 							pr_addr_dbg(
8514 							    "ip_newroute: no "
8515 							    "src for gw %s ",
8516 							    AF_INET, &gw);
8517 							printf("through "
8518 							    "interface %s\n",
8519 							    dst_ill->ill_name);
8520 						}
8521 						goto icmp_err_ret;
8522 					}
8523 				}
8524 				save_dst = dst;
8525 				dst = gw;
8526 				gw = INADDR_ANY;
8527 			}
8528 
8529 			/*
8530 			 * We obtain a partial IRE_CACHE which we will pass
8531 			 * along with the resolver query.  When the response
8532 			 * comes back it will be there ready for us to add.
8533 			 * The ire_max_frag is atomically set under the
8534 			 * irebucket lock in ire_add_v[46].
8535 			 */
8536 
8537 			ire = ire_create_mp(
8538 			    (uchar_t *)&dst,		/* dest address */
8539 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8540 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8541 			    (uchar_t *)&gw,		/* gateway address */
8542 			    NULL,			/* no in_src_addr */
8543 			    NULL,			/* ire_max_frag */
8544 			    NULL,			/* Fast Path header */
8545 			    dst_ill->ill_rq,		/* recv-from queue */
8546 			    dst_ill->ill_wq,		/* send-to queue */
8547 			    IRE_CACHE,
8548 			    NULL,
8549 			    src_ipif,			/* Interface ipif */
8550 			    in_ill,			/* Incoming ILL */
8551 			    save_ire->ire_mask,		/* Parent mask */
8552 			    0,
8553 			    save_ire->ire_ihandle,	/* Interface handle */
8554 			    0,				/* flags if any */
8555 			    &(save_ire->ire_uinfo),
8556 			    NULL,
8557 			    NULL);
8558 
8559 			if (ire == NULL) {
8560 				ire_refrele(save_ire);
8561 				break;
8562 			}
8563 
8564 			if ((sire != NULL) &&
8565 			    (sire->ire_flags & RTF_MULTIRT)) {
8566 				copy_mp = copymsg(first_mp);
8567 				if (copy_mp != NULL)
8568 					MULTIRT_DEBUG_TAG(copy_mp);
8569 			}
8570 
8571 			ire->ire_marks |= ire_marks;
8572 
8573 			/*
8574 			 * Construct message chain for the resolver
8575 			 * of the form:
8576 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8577 			 * Packet could contain a IPSEC_OUT mp.
8578 			 *
8579 			 * NOTE : ire will be added later when the response
8580 			 * comes back from ARP. If the response does not
8581 			 * come back, ARP frees the packet. For this reason,
8582 			 * we can't REFHOLD the bucket of save_ire to prevent
8583 			 * deletions. We may not be able to REFRELE the bucket
8584 			 * if the response never comes back. Thus, before
8585 			 * adding the ire, ire_add_v4 will make sure that the
8586 			 * interface route does not get deleted. This is the
8587 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8588 			 * where we can always prevent deletions because of
8589 			 * the synchronous nature of adding IRES i.e
8590 			 * ire_add_then_send is called after creating the IRE.
8591 			 */
8592 			ASSERT(ire->ire_mp != NULL);
8593 			ire->ire_mp->b_cont = first_mp;
8594 			/* Have saved_mp handy, for cleanup if canput fails */
8595 			saved_mp = mp;
8596 			mp = copyb(res_mp);
8597 			if (mp == NULL) {
8598 				/* Prepare for cleanup */
8599 				mp = saved_mp; /* pkt */
8600 				ire_delete(ire); /* ire_mp */
8601 				ire = NULL;
8602 				ire_refrele(save_ire);
8603 				if (copy_mp != NULL) {
8604 					MULTIRT_DEBUG_UNTAG(copy_mp);
8605 					freemsg(copy_mp);
8606 					copy_mp = NULL;
8607 				}
8608 				break;
8609 			}
8610 			linkb(mp, ire->ire_mp);
8611 
8612 			/*
8613 			 * Fill in the source and dest addrs for the resolver.
8614 			 * NOTE: this depends on memory layouts imposed by
8615 			 * ill_init().
8616 			 */
8617 			areq = (areq_t *)mp->b_rptr;
8618 			addrp = (ipaddr_t *)((char *)areq +
8619 			    areq->areq_sender_addr_offset);
8620 			if (do_attach_ill) {
8621 				/*
8622 				 * This is bind to no failover case.
8623 				 * arp packet also must go out on attach_ill.
8624 				 */
8625 				ASSERT(ipha->ipha_src != NULL);
8626 				*addrp = ipha->ipha_src;
8627 			} else {
8628 				*addrp = save_ire->ire_src_addr;
8629 			}
8630 
8631 			ire_refrele(save_ire);
8632 			addrp = (ipaddr_t *)((char *)areq +
8633 			    areq->areq_target_addr_offset);
8634 			*addrp = dst;
8635 			/* Up to the resolver. */
8636 			if (canputnext(dst_ill->ill_rq) &&
8637 			    !(dst_ill->ill_arp_closing)) {
8638 				putnext(dst_ill->ill_rq, mp);
8639 				ire = NULL;
8640 				if (copy_mp != NULL) {
8641 					/*
8642 					 * If we found a resolver, we ignore
8643 					 * any trailing top priority IRE_CACHE
8644 					 * in the further loops. This ensures
8645 					 * that we do not omit any resolver.
8646 					 * IRE_CACHE entries, if any, will be
8647 					 * processed next time we enter
8648 					 * ip_newroute().
8649 					 */
8650 					multirt_flags &= ~MULTIRT_CACHEGW;
8651 					/*
8652 					 * Search for the next unresolved
8653 					 * multirt route.
8654 					 */
8655 					first_mp = copy_mp;
8656 					copy_mp = NULL;
8657 					/* Prepare the next resolution loop. */
8658 					mp = first_mp;
8659 					EXTRACT_PKT_MP(mp, first_mp,
8660 					    mctl_present);
8661 					if (mctl_present)
8662 						io = (ipsec_out_t *)
8663 						    first_mp->b_rptr;
8664 					ipha = (ipha_t *)mp->b_rptr;
8665 
8666 					ASSERT(sire != NULL);
8667 
8668 					dst = save_dst;
8669 					multirt_resolve_next = B_TRUE;
8670 					continue;
8671 				}
8672 
8673 				if (sire != NULL)
8674 					ire_refrele(sire);
8675 
8676 				/*
8677 				 * The response will come back in ip_wput
8678 				 * with db_type IRE_DB_TYPE.
8679 				 */
8680 				ipif_refrele(src_ipif);
8681 				ill_refrele(dst_ill);
8682 				return;
8683 			} else {
8684 				/* Prepare for cleanup */
8685 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8686 				    mp);
8687 				mp->b_cont = NULL;
8688 				freeb(mp); /* areq */
8689 				/*
8690 				 * this is an ire that is not added to the
8691 				 * cache. ire_freemblk will handle the release
8692 				 * of any resources associated with the ire.
8693 				 */
8694 				ire_delete(ire); /* ire_mp */
8695 				mp = saved_mp; /* pkt */
8696 				ire = NULL;
8697 				if (copy_mp != NULL) {
8698 					MULTIRT_DEBUG_UNTAG(copy_mp);
8699 					freemsg(copy_mp);
8700 					copy_mp = NULL;
8701 				}
8702 				break;
8703 			}
8704 		default:
8705 			break;
8706 		}
8707 	} while (multirt_resolve_next);
8708 
8709 	ip1dbg(("ip_newroute: dropped\n"));
8710 	/* Did this packet originate externally? */
8711 	if (mp->b_prev) {
8712 		mp->b_next = NULL;
8713 		mp->b_prev = NULL;
8714 		BUMP_MIB(&ip_mib, ipInDiscards);
8715 	} else {
8716 		BUMP_MIB(&ip_mib, ipOutDiscards);
8717 	}
8718 	ASSERT(copy_mp == NULL);
8719 	MULTIRT_DEBUG_UNTAG(first_mp);
8720 	freemsg(first_mp);
8721 	if (ire != NULL)
8722 		ire_refrele(ire);
8723 	if (sire != NULL)
8724 		ire_refrele(sire);
8725 	if (src_ipif != NULL)
8726 		ipif_refrele(src_ipif);
8727 	if (dst_ill != NULL)
8728 		ill_refrele(dst_ill);
8729 	return;
8730 
8731 icmp_err_ret:
8732 	ip1dbg(("ip_newroute: no route\n"));
8733 	if (src_ipif != NULL)
8734 		ipif_refrele(src_ipif);
8735 	if (dst_ill != NULL)
8736 		ill_refrele(dst_ill);
8737 	if (sire != NULL)
8738 		ire_refrele(sire);
8739 	/* Did this packet originate externally? */
8740 	if (mp->b_prev) {
8741 		mp->b_next = NULL;
8742 		mp->b_prev = NULL;
8743 		/* XXX ipInNoRoutes */
8744 		q = WR(q);
8745 	} else {
8746 		/*
8747 		 * Since ip_wput() isn't close to finished, we fill
8748 		 * in enough of the header for credible error reporting.
8749 		 */
8750 		if (ip_hdr_complete(ipha, zoneid)) {
8751 			/* Failed */
8752 			MULTIRT_DEBUG_UNTAG(first_mp);
8753 			freemsg(first_mp);
8754 			if (ire != NULL)
8755 				ire_refrele(ire);
8756 			return;
8757 		}
8758 	}
8759 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8760 
8761 	/*
8762 	 * At this point we will have ire only if RTF_BLACKHOLE
8763 	 * or RTF_REJECT flags are set on the IRE. It will not
8764 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8765 	 */
8766 	if (ire != NULL) {
8767 		if (ire->ire_flags & RTF_BLACKHOLE) {
8768 			ire_refrele(ire);
8769 			MULTIRT_DEBUG_UNTAG(first_mp);
8770 			freemsg(first_mp);
8771 			return;
8772 		}
8773 		ire_refrele(ire);
8774 	}
8775 	if (ip_source_routed(ipha)) {
8776 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8777 		    zoneid);
8778 		return;
8779 	}
8780 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
8781 }
8782 
8783 /*
8784  * IPv4 -
8785  * ip_newroute_ipif is called by ip_wput_multicast and
8786  * ip_rput_forward_multicast whenever we need to send
8787  * out a packet to a destination address for which we do not have specific
8788  * routing information. It is used when the packet will be sent out
8789  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8790  * socket option is set or icmp error message wants to go out on a particular
8791  * interface for a unicast packet.
8792  *
8793  * In most cases, the destination address is resolved thanks to the ipif
8794  * intrinsic resolver. However, there are some cases where the call to
8795  * ip_newroute_ipif must take into account the potential presence of
8796  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8797  * that uses the interface. This is specified through flags,
8798  * which can be a combination of:
8799  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8800  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8801  *   and flags. Additionally, the packet source address has to be set to
8802  *   the specified address. The caller is thus expected to set this flag
8803  *   if the packet has no specific source address yet.
8804  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8805  *   flag, the resulting ire will inherit the flag. All unresolved routes
8806  *   to the destination must be explored in the same call to
8807  *   ip_newroute_ipif().
8808  */
8809 static void
8810 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8811     conn_t *connp, uint32_t flags, zoneid_t zoneid)
8812 {
8813 	areq_t	*areq;
8814 	ire_t	*ire = NULL;
8815 	mblk_t	*res_mp;
8816 	ipaddr_t *addrp;
8817 	mblk_t *first_mp;
8818 	ire_t	*save_ire = NULL;
8819 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8820 	ipif_t	*src_ipif = NULL;
8821 	ushort_t ire_marks = 0;
8822 	ill_t	*dst_ill = NULL;
8823 	boolean_t mctl_present;
8824 	ipsec_out_t *io;
8825 	ipha_t *ipha;
8826 	int	ihandle = 0;
8827 	mblk_t	*saved_mp;
8828 	ire_t   *fire = NULL;
8829 	mblk_t  *copy_mp = NULL;
8830 	boolean_t multirt_resolve_next;
8831 	ipaddr_t ipha_dst;
8832 
8833 	/*
8834 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8835 	 * here for uniformity
8836 	 */
8837 	ipif_refhold(ipif);
8838 
8839 	/*
8840 	 * This loop is run only once in most cases.
8841 	 * We loop to resolve further routes only when the destination
8842 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8843 	 */
8844 	do {
8845 		if (dst_ill != NULL) {
8846 			ill_refrele(dst_ill);
8847 			dst_ill = NULL;
8848 		}
8849 		if (src_ipif != NULL) {
8850 			ipif_refrele(src_ipif);
8851 			src_ipif = NULL;
8852 		}
8853 		multirt_resolve_next = B_FALSE;
8854 
8855 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8856 		    ipif->ipif_ill->ill_name));
8857 
8858 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8859 		if (mctl_present)
8860 			io = (ipsec_out_t *)first_mp->b_rptr;
8861 
8862 		ipha = (ipha_t *)mp->b_rptr;
8863 
8864 		/*
8865 		 * Save the packet destination address, we may need it after
8866 		 * the packet has been consumed.
8867 		 */
8868 		ipha_dst = ipha->ipha_dst;
8869 
8870 		/*
8871 		 * If the interface is a pt-pt interface we look for an
8872 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8873 		 * local_address and the pt-pt destination address. Otherwise
8874 		 * we just match the local address.
8875 		 * NOTE: dst could be different than ipha->ipha_dst in case
8876 		 * of sending igmp multicast packets over a point-to-point
8877 		 * connection.
8878 		 * Thus we must be careful enough to check ipha_dst to be a
8879 		 * multicast address, otherwise it will take xmit_if path for
8880 		 * multicast packets resulting into kernel stack overflow by
8881 		 * repeated calls to ip_newroute_ipif from ire_send().
8882 		 */
8883 		if (CLASSD(ipha_dst) &&
8884 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8885 			goto err_ret;
8886 		}
8887 
8888 		/*
8889 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8890 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8891 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8892 		 * propagate its flags to the new ire.
8893 		 */
8894 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8895 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8896 			ip2dbg(("ip_newroute_ipif: "
8897 			    "ipif_lookup_multi_ire("
8898 			    "ipif %p, dst %08x) = fire %p\n",
8899 			    (void *)ipif, ntohl(dst), (void *)fire));
8900 		}
8901 
8902 		if (mctl_present && io->ipsec_out_attach_if) {
8903 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8904 			    io->ipsec_out_ill_index, B_FALSE);
8905 
8906 			/* Failure case frees things for us. */
8907 			if (attach_ill == NULL) {
8908 				ipif_refrele(ipif);
8909 				if (fire != NULL)
8910 					ire_refrele(fire);
8911 				return;
8912 			}
8913 
8914 			/*
8915 			 * Check if we need an ire that will not be
8916 			 * looked up by anybody else i.e. HIDDEN.
8917 			 */
8918 			if (ill_is_probeonly(attach_ill)) {
8919 				ire_marks = IRE_MARK_HIDDEN;
8920 			}
8921 			/*
8922 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8923 			 * case.
8924 			 */
8925 			dst_ill = ipif->ipif_ill;
8926 			/* attach_ill has been refheld by ip_grab_attach_ill */
8927 			ASSERT(dst_ill == attach_ill);
8928 		} else {
8929 			/*
8930 			 * If this is set by IP_XMIT_IF, then make sure that
8931 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8932 			 * specified ill.
8933 			 */
8934 			ASSERT((connp == NULL) ||
8935 			    (connp->conn_xmit_if_ill == NULL) ||
8936 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8937 			/*
8938 			 * If the interface belongs to an interface group,
8939 			 * make sure the next possible interface in the group
8940 			 * is used.  This encourages load spreading among
8941 			 * peers in an interface group.
8942 			 * Note: load spreading is disabled for RTF_MULTIRT
8943 			 * routes.
8944 			 */
8945 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8946 			    (fire->ire_flags & RTF_MULTIRT)) {
8947 				/*
8948 				 * Don't perform outbound load spreading
8949 				 * in the case of an RTF_MULTIRT issued route,
8950 				 * we actually typically want to replicate
8951 				 * outgoing packets through particular
8952 				 * interfaces.
8953 				 */
8954 				dst_ill = ipif->ipif_ill;
8955 				ill_refhold(dst_ill);
8956 			} else {
8957 				dst_ill = ip_newroute_get_dst_ill(
8958 				    ipif->ipif_ill);
8959 			}
8960 			if (dst_ill == NULL) {
8961 				if (ip_debug > 2) {
8962 					pr_addr_dbg("ip_newroute_ipif: "
8963 					    "no dst ill for dst %s\n",
8964 					    AF_INET, &dst);
8965 				}
8966 				goto err_ret;
8967 			}
8968 		}
8969 
8970 		/*
8971 		 * Pick a source address preferring non-deprecated ones.
8972 		 * Unlike ip_newroute, we don't do any source address
8973 		 * selection here since for multicast it really does not help
8974 		 * in inbound load spreading as in the unicast case.
8975 		 */
8976 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8977 		    (fire->ire_flags & RTF_SETSRC)) {
8978 			/*
8979 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8980 			 * on that interface. This ire has RTF_SETSRC flag, so
8981 			 * the source address of the packet must be changed.
8982 			 * Check that the ipif matching the requested source
8983 			 * address still exists.
8984 			 */
8985 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8986 			    zoneid, NULL, NULL, NULL, NULL);
8987 		}
8988 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8989 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
8990 		    ipif->ipif_zoneid != ALL_ZONES)) &&
8991 		    (src_ipif == NULL)) {
8992 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8993 			if (src_ipif == NULL) {
8994 				if (ip_debug > 2) {
8995 					/* ip1dbg */
8996 					pr_addr_dbg("ip_newroute_ipif: "
8997 					    "no src for dst %s",
8998 					    AF_INET, &dst);
8999 				}
9000 				ip1dbg((" through interface %s\n",
9001 				    dst_ill->ill_name));
9002 				goto err_ret;
9003 			}
9004 			ipif_refrele(ipif);
9005 			ipif = src_ipif;
9006 			ipif_refhold(ipif);
9007 		}
9008 		if (src_ipif == NULL) {
9009 			src_ipif = ipif;
9010 			ipif_refhold(src_ipif);
9011 		}
9012 
9013 		/*
9014 		 * Assign a source address while we have the conn.
9015 		 * We can't have ip_wput_ire pick a source address when the
9016 		 * packet returns from arp since conn_unspec_src might be set
9017 		 * and we loose the conn when going through arp.
9018 		 */
9019 		if (ipha->ipha_src == INADDR_ANY &&
9020 		    (connp == NULL || !connp->conn_unspec_src)) {
9021 			ipha->ipha_src = src_ipif->ipif_src_addr;
9022 		}
9023 
9024 		/*
9025 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9026 		 * interface does not have an interface ire.
9027 		 * Example: Thousands of mobileip PPP interfaces to mobile
9028 		 * nodes. We don't want to create interface ires because
9029 		 * packets from other mobile nodes must not take the route
9030 		 * via interface ires to the visiting mobile node without
9031 		 * going through the home agent, in absence of mobileip
9032 		 * route optimization.
9033 		 */
9034 		if (CLASSD(ipha_dst) && (connp == NULL ||
9035 		    connp->conn_xmit_if_ill == NULL)) {
9036 			/* ipif_to_ire returns an held ire */
9037 			ire = ipif_to_ire(ipif);
9038 			if (ire == NULL)
9039 				goto err_ret;
9040 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9041 				goto err_ret;
9042 			/*
9043 			 * ihandle is needed when the ire is added to
9044 			 * cache table.
9045 			 */
9046 			save_ire = ire;
9047 			ihandle = save_ire->ire_ihandle;
9048 
9049 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9050 			    "flags %04x\n",
9051 			    (void *)ire, (void *)ipif, flags));
9052 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9053 			    (fire->ire_flags & RTF_MULTIRT)) {
9054 				/*
9055 				 * As requested by flags, an IRE_OFFSUBNET was
9056 				 * looked up on that interface. This ire has
9057 				 * RTF_MULTIRT flag, so the resolution loop will
9058 				 * be re-entered to resolve additional routes on
9059 				 * other interfaces. For that purpose, a copy of
9060 				 * the packet is performed at this point.
9061 				 */
9062 				fire->ire_last_used_time = lbolt;
9063 				copy_mp = copymsg(first_mp);
9064 				if (copy_mp) {
9065 					MULTIRT_DEBUG_TAG(copy_mp);
9066 				}
9067 			}
9068 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9069 			    (fire->ire_flags & RTF_SETSRC)) {
9070 				/*
9071 				 * As requested by flags, an IRE_OFFSUBET was
9072 				 * looked up on that interface. This ire has
9073 				 * RTF_SETSRC flag, so the source address of the
9074 				 * packet must be changed.
9075 				 */
9076 				ipha->ipha_src = fire->ire_src_addr;
9077 			}
9078 		} else {
9079 			ASSERT((connp == NULL) ||
9080 			    (connp->conn_xmit_if_ill != NULL) ||
9081 			    (connp->conn_dontroute));
9082 			/*
9083 			 * The only ways we can come here are:
9084 			 * 1) IP_XMIT_IF socket option is set
9085 			 * 2) ICMP error message generated from
9086 			 *    ip_mrtun_forward() routine and it needs
9087 			 *    to go through the specified ill.
9088 			 * 3) SO_DONTROUTE socket option is set
9089 			 * In all cases, the new ire will not be added
9090 			 * into cache table.
9091 			 */
9092 			ire_marks |= IRE_MARK_NOADD;
9093 		}
9094 
9095 		switch (ipif->ipif_net_type) {
9096 		case IRE_IF_NORESOLVER: {
9097 			/* We have what we need to build an IRE_CACHE. */
9098 			mblk_t	*res_mp;
9099 
9100 			/*
9101 			 * Create a new res_mp with the
9102 			 * IP gateway address as destination address in the
9103 			 * DLPI hdr if the physical length is exactly 4 bytes.
9104 			 */
9105 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9106 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9107 				    dst_ill->ill_phys_addr_length,
9108 				    dst_ill->ill_sap,
9109 				    dst_ill->ill_sap_length);
9110 			} else {
9111 				/* use the value set in ip_ll_subnet_defaults */
9112 				res_mp = ill_dlur_gen(NULL,
9113 				    dst_ill->ill_phys_addr_length,
9114 				    dst_ill->ill_sap,
9115 				    dst_ill->ill_sap_length);
9116 			}
9117 
9118 			if (res_mp == NULL)
9119 				break;
9120 			/*
9121 			 * The new ire inherits the IRE_OFFSUBNET flags
9122 			 * and source address, if this was requested.
9123 			 */
9124 			ire = ire_create(
9125 			    (uchar_t *)&dst,		/* dest address */
9126 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9127 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9128 			    NULL,			/* gateway address */
9129 			    NULL,
9130 			    &ipif->ipif_mtu,
9131 			    NULL,			/* Fast Path header */
9132 			    dst_ill->ill_rq,		/* recv-from queue */
9133 			    dst_ill->ill_wq,		/* send-to queue */
9134 			    IRE_CACHE,
9135 			    res_mp,
9136 			    src_ipif,
9137 			    NULL,
9138 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9139 			    (fire != NULL) ?		/* Parent handle */
9140 				fire->ire_phandle : 0,
9141 			    ihandle,			/* Interface handle */
9142 			    (fire != NULL) ?
9143 				(fire->ire_flags &
9144 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9145 			    (save_ire == NULL ? &ire_uinfo_null :
9146 				&save_ire->ire_uinfo),
9147 			    NULL,
9148 			    NULL);
9149 
9150 			freeb(res_mp);
9151 
9152 			if (ire == NULL) {
9153 				if (save_ire != NULL)
9154 					ire_refrele(save_ire);
9155 				break;
9156 			}
9157 
9158 			ire->ire_marks |= ire_marks;
9159 
9160 			/*
9161 			 * If IRE_MARK_NOADD is set then we need to convert
9162 			 * the max_fragp to a useable value now. This is
9163 			 * normally done in ire_add_v[46]. We also need to
9164 			 * associate the ire with an nce (normally would be
9165 			 * done in ip_wput_nondata()).
9166 			 *
9167 			 * Note that IRE_MARK_NOADD packets created here
9168 			 * do not have a non-null ire_mp pointer. The null
9169 			 * value of ire_bucket indicates that they were
9170 			 * never added.
9171 			 */
9172 			if (ire->ire_marks & IRE_MARK_NOADD) {
9173 				uint_t  max_frag;
9174 
9175 				max_frag = *ire->ire_max_fragp;
9176 				ire->ire_max_fragp = NULL;
9177 				ire->ire_max_frag = max_frag;
9178 
9179 				if ((ire->ire_nce = ndp_lookup_v4(
9180 				    ire_to_ill(ire),
9181 				    (ire->ire_gateway_addr != INADDR_ANY ?
9182 				    &ire->ire_gateway_addr : &ire->ire_addr),
9183 				    B_FALSE)) == NULL) {
9184 					if (save_ire != NULL)
9185 						ire_refrele(save_ire);
9186 					break;
9187 				}
9188 				ASSERT(ire->ire_nce->nce_state ==
9189 				    ND_REACHABLE);
9190 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9191 			}
9192 
9193 			/* Prevent save_ire from getting deleted */
9194 			if (save_ire != NULL) {
9195 				IRB_REFHOLD(save_ire->ire_bucket);
9196 				/* Has it been removed already ? */
9197 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9198 					IRB_REFRELE(save_ire->ire_bucket);
9199 					ire_refrele(save_ire);
9200 					break;
9201 				}
9202 			}
9203 
9204 			ire_add_then_send(q, ire, first_mp);
9205 
9206 			/* Assert that save_ire is not deleted yet. */
9207 			if (save_ire != NULL) {
9208 				ASSERT(save_ire->ire_ptpn != NULL);
9209 				IRB_REFRELE(save_ire->ire_bucket);
9210 				ire_refrele(save_ire);
9211 				save_ire = NULL;
9212 			}
9213 			if (fire != NULL) {
9214 				ire_refrele(fire);
9215 				fire = NULL;
9216 			}
9217 
9218 			/*
9219 			 * the resolution loop is re-entered if this
9220 			 * was requested through flags and if we
9221 			 * actually are in a multirouting case.
9222 			 */
9223 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9224 				boolean_t need_resolve =
9225 				    ire_multirt_need_resolve(ipha_dst,
9226 					MBLK_GETLABEL(copy_mp));
9227 				if (!need_resolve) {
9228 					MULTIRT_DEBUG_UNTAG(copy_mp);
9229 					freemsg(copy_mp);
9230 					copy_mp = NULL;
9231 				} else {
9232 					/*
9233 					 * ipif_lookup_group() calls
9234 					 * ire_lookup_multi() that uses
9235 					 * ire_ftable_lookup() to find
9236 					 * an IRE_INTERFACE for the group.
9237 					 * In the multirt case,
9238 					 * ire_lookup_multi() then invokes
9239 					 * ire_multirt_lookup() to find
9240 					 * the next resolvable ire.
9241 					 * As a result, we obtain an new
9242 					 * interface, derived from the
9243 					 * next ire.
9244 					 */
9245 					ipif_refrele(ipif);
9246 					ipif = ipif_lookup_group(ipha_dst,
9247 					    zoneid);
9248 					ip2dbg(("ip_newroute_ipif: "
9249 					    "multirt dst %08x, ipif %p\n",
9250 					    htonl(dst), (void *)ipif));
9251 					if (ipif != NULL) {
9252 						mp = copy_mp;
9253 						copy_mp = NULL;
9254 						multirt_resolve_next = B_TRUE;
9255 						continue;
9256 					} else {
9257 						freemsg(copy_mp);
9258 					}
9259 				}
9260 			}
9261 			if (ipif != NULL)
9262 				ipif_refrele(ipif);
9263 			ill_refrele(dst_ill);
9264 			ipif_refrele(src_ipif);
9265 			return;
9266 		}
9267 		case IRE_IF_RESOLVER:
9268 			/*
9269 			 * We can't build an IRE_CACHE yet, but at least
9270 			 * we found a resolver that can help.
9271 			 */
9272 			res_mp = dst_ill->ill_resolver_mp;
9273 			if (!OK_RESOLVER_MP(res_mp))
9274 				break;
9275 
9276 			/*
9277 			 * We obtain a partial IRE_CACHE which we will pass
9278 			 * along with the resolver query.  When the response
9279 			 * comes back it will be there ready for us to add.
9280 			 * The new ire inherits the IRE_OFFSUBNET flags
9281 			 * and source address, if this was requested.
9282 			 * The ire_max_frag is atomically set under the
9283 			 * irebucket lock in ire_add_v[46]. Only in the
9284 			 * case of IRE_MARK_NOADD, we set it here itself.
9285 			 */
9286 			ire = ire_create_mp(
9287 			    (uchar_t *)&dst,		/* dest address */
9288 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9289 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9290 			    NULL,			/* gateway address */
9291 			    NULL,			/* no in_src_addr */
9292 			    (ire_marks & IRE_MARK_NOADD) ?
9293 				ipif->ipif_mtu : 0,	/* max_frag */
9294 			    NULL,			/* Fast path header */
9295 			    dst_ill->ill_rq,		/* recv-from queue */
9296 			    dst_ill->ill_wq,		/* send-to queue */
9297 			    IRE_CACHE,
9298 			    NULL,	/* let ire_nce_init figure res_mp out */
9299 			    src_ipif,
9300 			    NULL,
9301 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9302 			    (fire != NULL) ?		/* Parent handle */
9303 				fire->ire_phandle : 0,
9304 			    ihandle,			/* Interface handle */
9305 			    (fire != NULL) ?		/* flags if any */
9306 				(fire->ire_flags &
9307 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9308 			    (save_ire == NULL ? &ire_uinfo_null :
9309 				&save_ire->ire_uinfo),
9310 			    NULL,
9311 			    NULL);
9312 
9313 			if (save_ire != NULL) {
9314 				ire_refrele(save_ire);
9315 				save_ire = NULL;
9316 			}
9317 			if (ire == NULL)
9318 				break;
9319 
9320 			ire->ire_marks |= ire_marks;
9321 			/*
9322 			 * Construct message chain for the resolver of the
9323 			 * form:
9324 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9325 			 *
9326 			 * NOTE : ire will be added later when the response
9327 			 * comes back from ARP. If the response does not
9328 			 * come back, ARP frees the packet. For this reason,
9329 			 * we can't REFHOLD the bucket of save_ire to prevent
9330 			 * deletions. We may not be able to REFRELE the
9331 			 * bucket if the response never comes back.
9332 			 * Thus, before adding the ire, ire_add_v4 will make
9333 			 * sure that the interface route does not get deleted.
9334 			 * This is the only case unlike ip_newroute_v6,
9335 			 * ip_newroute_ipif_v6 where we can always prevent
9336 			 * deletions because ire_add_then_send is called after
9337 			 * creating the IRE.
9338 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9339 			 * does not add this IRE into the IRE CACHE.
9340 			 */
9341 			ASSERT(ire->ire_mp != NULL);
9342 			ire->ire_mp->b_cont = first_mp;
9343 			/* Have saved_mp handy, for cleanup if canput fails */
9344 			saved_mp = mp;
9345 			mp = copyb(res_mp);
9346 			if (mp == NULL) {
9347 				/* Prepare for cleanup */
9348 				mp = saved_mp; /* pkt */
9349 				ire_delete(ire); /* ire_mp */
9350 				ire = NULL;
9351 				if (copy_mp != NULL) {
9352 					MULTIRT_DEBUG_UNTAG(copy_mp);
9353 					freemsg(copy_mp);
9354 					copy_mp = NULL;
9355 				}
9356 				break;
9357 			}
9358 			linkb(mp, ire->ire_mp);
9359 
9360 			/*
9361 			 * Fill in the source and dest addrs for the resolver.
9362 			 * NOTE: this depends on memory layouts imposed by
9363 			 * ill_init().
9364 			 */
9365 			areq = (areq_t *)mp->b_rptr;
9366 			addrp = (ipaddr_t *)((char *)areq +
9367 			    areq->areq_sender_addr_offset);
9368 			*addrp = ire->ire_src_addr;
9369 			addrp = (ipaddr_t *)((char *)areq +
9370 			    areq->areq_target_addr_offset);
9371 			*addrp = dst;
9372 			/* Up to the resolver. */
9373 			if (canputnext(dst_ill->ill_rq) &&
9374 			    !(dst_ill->ill_arp_closing)) {
9375 				putnext(dst_ill->ill_rq, mp);
9376 				/*
9377 				 * The response will come back in ip_wput
9378 				 * with db_type IRE_DB_TYPE.
9379 				 */
9380 			} else {
9381 				mp->b_cont = NULL;
9382 				freeb(mp); /* areq */
9383 				ire_delete(ire); /* ire_mp */
9384 				saved_mp->b_next = NULL;
9385 				saved_mp->b_prev = NULL;
9386 				freemsg(first_mp); /* pkt */
9387 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9388 			}
9389 
9390 			if (fire != NULL) {
9391 				ire_refrele(fire);
9392 				fire = NULL;
9393 			}
9394 
9395 
9396 			/*
9397 			 * The resolution loop is re-entered if this was
9398 			 * requested through flags and we actually are
9399 			 * in a multirouting case.
9400 			 */
9401 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9402 				boolean_t need_resolve =
9403 				    ire_multirt_need_resolve(ipha_dst,
9404 					MBLK_GETLABEL(copy_mp));
9405 				if (!need_resolve) {
9406 					MULTIRT_DEBUG_UNTAG(copy_mp);
9407 					freemsg(copy_mp);
9408 					copy_mp = NULL;
9409 				} else {
9410 					/*
9411 					 * ipif_lookup_group() calls
9412 					 * ire_lookup_multi() that uses
9413 					 * ire_ftable_lookup() to find
9414 					 * an IRE_INTERFACE for the group.
9415 					 * In the multirt case,
9416 					 * ire_lookup_multi() then invokes
9417 					 * ire_multirt_lookup() to find
9418 					 * the next resolvable ire.
9419 					 * As a result, we obtain an new
9420 					 * interface, derived from the
9421 					 * next ire.
9422 					 */
9423 					ipif_refrele(ipif);
9424 					ipif = ipif_lookup_group(ipha_dst,
9425 					    zoneid);
9426 					if (ipif != NULL) {
9427 						mp = copy_mp;
9428 						copy_mp = NULL;
9429 						multirt_resolve_next = B_TRUE;
9430 						continue;
9431 					} else {
9432 						freemsg(copy_mp);
9433 					}
9434 				}
9435 			}
9436 			if (ipif != NULL)
9437 				ipif_refrele(ipif);
9438 			ill_refrele(dst_ill);
9439 			ipif_refrele(src_ipif);
9440 			return;
9441 		default:
9442 			break;
9443 		}
9444 	} while (multirt_resolve_next);
9445 
9446 err_ret:
9447 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9448 	if (fire != NULL)
9449 		ire_refrele(fire);
9450 	ipif_refrele(ipif);
9451 	/* Did this packet originate externally? */
9452 	if (dst_ill != NULL)
9453 		ill_refrele(dst_ill);
9454 	if (src_ipif != NULL)
9455 		ipif_refrele(src_ipif);
9456 	if (mp->b_prev || mp->b_next) {
9457 		mp->b_next = NULL;
9458 		mp->b_prev = NULL;
9459 	} else {
9460 		/*
9461 		 * Since ip_wput() isn't close to finished, we fill
9462 		 * in enough of the header for credible error reporting.
9463 		 */
9464 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9465 			/* Failed */
9466 			freemsg(first_mp);
9467 			if (ire != NULL)
9468 				ire_refrele(ire);
9469 			return;
9470 		}
9471 	}
9472 	/*
9473 	 * At this point we will have ire only if RTF_BLACKHOLE
9474 	 * or RTF_REJECT flags are set on the IRE. It will not
9475 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9476 	 */
9477 	if (ire != NULL) {
9478 		if (ire->ire_flags & RTF_BLACKHOLE) {
9479 			ire_refrele(ire);
9480 			freemsg(first_mp);
9481 			return;
9482 		}
9483 		ire_refrele(ire);
9484 	}
9485 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9486 }
9487 
9488 /* Name/Value Table Lookup Routine */
9489 char *
9490 ip_nv_lookup(nv_t *nv, int value)
9491 {
9492 	if (!nv)
9493 		return (NULL);
9494 	for (; nv->nv_name; nv++) {
9495 		if (nv->nv_value == value)
9496 			return (nv->nv_name);
9497 	}
9498 	return ("unknown");
9499 }
9500 
9501 /*
9502  * one day it can be patched to 1 from /etc/system for machines that have few
9503  * fast network interfaces feeding multiple cpus.
9504  */
9505 int ill_stream_putlocks = 0;
9506 
9507 /*
9508  * This is a module open, i.e. this is a control stream for access
9509  * to a DLPI device.  We allocate an ill_t as the instance data in
9510  * this case.
9511  */
9512 int
9513 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9514 {
9515 	uint32_t mem_cnt;
9516 	uint32_t cpu_cnt;
9517 	uint32_t min_cnt;
9518 	pgcnt_t mem_avail;
9519 	ill_t	*ill;
9520 	int	err;
9521 
9522 	/*
9523 	 * Prevent unprivileged processes from pushing IP so that
9524 	 * they can't send raw IP.
9525 	 */
9526 	if (secpolicy_net_rawaccess(credp) != 0)
9527 		return (EPERM);
9528 
9529 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9530 	q->q_ptr = WR(q)->q_ptr = ill;
9531 
9532 	/*
9533 	 * ill_init initializes the ill fields and then sends down
9534 	 * down a DL_INFO_REQ after calling qprocson.
9535 	 */
9536 	err = ill_init(q, ill);
9537 	if (err != 0) {
9538 		mi_free(ill);
9539 		q->q_ptr = NULL;
9540 		WR(q)->q_ptr = NULL;
9541 		return (err);
9542 	}
9543 
9544 	/* ill_init initializes the ipsq marking this thread as writer */
9545 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9546 	/* Wait for the DL_INFO_ACK */
9547 	mutex_enter(&ill->ill_lock);
9548 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9549 		/*
9550 		 * Return value of 0 indicates a pending signal.
9551 		 */
9552 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9553 		if (err == 0) {
9554 			mutex_exit(&ill->ill_lock);
9555 			(void) ip_close(q, 0);
9556 			return (EINTR);
9557 		}
9558 	}
9559 	mutex_exit(&ill->ill_lock);
9560 
9561 	/*
9562 	 * ip_rput_other could have set an error  in ill_error on
9563 	 * receipt of M_ERROR.
9564 	 */
9565 
9566 	err = ill->ill_error;
9567 	if (err != 0) {
9568 		(void) ip_close(q, 0);
9569 		return (err);
9570 	}
9571 
9572 	/*
9573 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9574 	 * size and the cpu speed of the machine. This is upper
9575 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9576 	 * and is lower bounded by the compile time value of
9577 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9578 	 * ip6_ire_max_bucket_cnt.
9579 	 */
9580 	mem_avail = kmem_avail();
9581 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9582 	    ip_cache_table_size / sizeof (ire_t);
9583 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9584 
9585 	min_cnt = MIN(cpu_cnt, mem_cnt);
9586 	if (min_cnt < ip_ire_min_bucket_cnt)
9587 		min_cnt = ip_ire_min_bucket_cnt;
9588 	if (ip_ire_max_bucket_cnt > min_cnt) {
9589 		ip_ire_max_bucket_cnt = min_cnt;
9590 	}
9591 
9592 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9593 	    ip6_cache_table_size / sizeof (ire_t);
9594 	min_cnt = MIN(cpu_cnt, mem_cnt);
9595 	if (min_cnt < ip6_ire_min_bucket_cnt)
9596 		min_cnt = ip6_ire_min_bucket_cnt;
9597 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9598 		ip6_ire_max_bucket_cnt = min_cnt;
9599 	}
9600 
9601 	ill->ill_credp = credp;
9602 	crhold(credp);
9603 
9604 	mutex_enter(&ip_mi_lock);
9605 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9606 	mutex_exit(&ip_mi_lock);
9607 	if (err) {
9608 		(void) ip_close(q, 0);
9609 		return (err);
9610 	}
9611 	return (0);
9612 }
9613 
9614 /* IP open routine. */
9615 int
9616 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9617 {
9618 	conn_t 		*connp;
9619 	major_t		maj;
9620 
9621 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9622 
9623 	/* Allow reopen. */
9624 	if (q->q_ptr != NULL)
9625 		return (0);
9626 
9627 	if (sflag & MODOPEN) {
9628 		/* This is a module open */
9629 		return (ip_modopen(q, devp, flag, sflag, credp));
9630 	}
9631 
9632 	/*
9633 	 * We are opening as a device. This is an IP client stream, and we
9634 	 * allocate an conn_t as the instance data.
9635 	 */
9636 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9637 	connp->conn_upq = q;
9638 	q->q_ptr = WR(q)->q_ptr = connp;
9639 
9640 	if (flag & SO_SOCKSTR)
9641 		connp->conn_flags |= IPCL_SOCKET;
9642 
9643 	/* Minor tells us which /dev entry was opened */
9644 	if (geteminor(*devp) == IPV6_MINOR) {
9645 		connp->conn_flags |= IPCL_ISV6;
9646 		connp->conn_af_isv6 = B_TRUE;
9647 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9648 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9649 	} else {
9650 		connp->conn_af_isv6 = B_FALSE;
9651 		connp->conn_pkt_isv6 = B_FALSE;
9652 	}
9653 
9654 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9655 		q->q_ptr = WR(q)->q_ptr = NULL;
9656 		CONN_DEC_REF(connp);
9657 		return (EBUSY);
9658 	}
9659 
9660 	maj = getemajor(*devp);
9661 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9662 
9663 	/*
9664 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9665 	 */
9666 	connp->conn_cred = credp;
9667 	crhold(connp->conn_cred);
9668 
9669 	/*
9670 	 * If the caller has the process-wide flag set, then default to MAC
9671 	 * exempt mode.  This allows read-down to unlabeled hosts.
9672 	 */
9673 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9674 		connp->conn_mac_exempt = B_TRUE;
9675 
9676 	connp->conn_zoneid = getzoneid();
9677 
9678 	/*
9679 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9680 	 * administrative ops.  In these cases, we just need a normal conn_t
9681 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9682 	 * an error will be returned.
9683 	 */
9684 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9685 		connp->conn_rq = q;
9686 		connp->conn_wq = WR(q);
9687 	} else {
9688 		connp->conn_ulp = IPPROTO_SCTP;
9689 		connp->conn_rq = connp->conn_wq = NULL;
9690 	}
9691 	/* Non-zero default values */
9692 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9693 
9694 	/*
9695 	 * Make the conn globally visible to walkers
9696 	 */
9697 	mutex_enter(&connp->conn_lock);
9698 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9699 	mutex_exit(&connp->conn_lock);
9700 	ASSERT(connp->conn_ref == 1);
9701 
9702 	qprocson(q);
9703 
9704 	return (0);
9705 }
9706 
9707 /*
9708  * Change q_qinfo based on the value of isv6.
9709  * This can not called on an ill queue.
9710  * Note that there is no race since either q_qinfo works for conn queues - it
9711  * is just an optimization to enter the best wput routine directly.
9712  */
9713 void
9714 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9715 {
9716 	ASSERT(q->q_flag & QREADR);
9717 	ASSERT(WR(q)->q_next == NULL);
9718 	ASSERT(q->q_ptr != NULL);
9719 
9720 	if (minor == IPV6_MINOR)  {
9721 		if (bump_mib)
9722 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9723 		q->q_qinfo = &rinit_ipv6;
9724 		WR(q)->q_qinfo = &winit_ipv6;
9725 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9726 	} else {
9727 		if (bump_mib)
9728 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9729 		q->q_qinfo = &iprinit;
9730 		WR(q)->q_qinfo = &ipwinit;
9731 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9732 	}
9733 
9734 }
9735 
9736 /*
9737  * See if IPsec needs loading because of the options in mp.
9738  */
9739 static boolean_t
9740 ipsec_opt_present(mblk_t *mp)
9741 {
9742 	uint8_t *optcp, *next_optcp, *opt_endcp;
9743 	struct opthdr *opt;
9744 	struct T_opthdr *topt;
9745 	int opthdr_len;
9746 	t_uscalar_t optname, optlevel;
9747 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9748 	ipsec_req_t *ipsr;
9749 
9750 	/*
9751 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9752 	 * return TRUE.
9753 	 */
9754 
9755 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9756 	opt_endcp = optcp + tor->OPT_length;
9757 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9758 		opthdr_len = sizeof (struct T_opthdr);
9759 	} else {		/* O_OPTMGMT_REQ */
9760 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9761 		opthdr_len = sizeof (struct opthdr);
9762 	}
9763 	for (; optcp < opt_endcp; optcp = next_optcp) {
9764 		if (optcp + opthdr_len > opt_endcp)
9765 			return (B_FALSE);	/* Not enough option header. */
9766 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9767 			topt = (struct T_opthdr *)optcp;
9768 			optlevel = topt->level;
9769 			optname = topt->name;
9770 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9771 		} else {
9772 			opt = (struct opthdr *)optcp;
9773 			optlevel = opt->level;
9774 			optname = opt->name;
9775 			next_optcp = optcp + opthdr_len +
9776 			    _TPI_ALIGN_OPT(opt->len);
9777 		}
9778 		if ((next_optcp < optcp) || /* wraparound pointer space */
9779 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9780 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9781 			return (B_FALSE); /* bad option buffer */
9782 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9783 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9784 			/*
9785 			 * Check to see if it's an all-bypass or all-zeroes
9786 			 * IPsec request.  Don't bother loading IPsec if
9787 			 * the socket doesn't want to use it.  (A good example
9788 			 * is a bypass request.)
9789 			 *
9790 			 * Basically, if any of the non-NEVER bits are set,
9791 			 * load IPsec.
9792 			 */
9793 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9794 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9795 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9796 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9797 			    != 0)
9798 				return (B_TRUE);
9799 		}
9800 	}
9801 	return (B_FALSE);
9802 }
9803 
9804 /*
9805  * If conn is is waiting for ipsec to finish loading, kick it.
9806  */
9807 /* ARGSUSED */
9808 static void
9809 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9810 {
9811 	t_scalar_t	optreq_prim;
9812 	mblk_t		*mp;
9813 	cred_t		*cr;
9814 	int		err = 0;
9815 
9816 	/*
9817 	 * This function is called, after ipsec loading is complete.
9818 	 * Since IP checks exclusively and atomically (i.e it prevents
9819 	 * ipsec load from completing until ip_optcom_req completes)
9820 	 * whether ipsec load is complete, there cannot be a race with IP
9821 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9822 	 */
9823 	mutex_enter(&connp->conn_lock);
9824 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9825 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9826 		mp = connp->conn_ipsec_opt_mp;
9827 		connp->conn_ipsec_opt_mp = NULL;
9828 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9829 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9830 		mutex_exit(&connp->conn_lock);
9831 
9832 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9833 
9834 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9835 		if (optreq_prim == T_OPTMGMT_REQ) {
9836 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9837 			    &ip_opt_obj);
9838 		} else {
9839 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9840 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9841 			    &ip_opt_obj);
9842 		}
9843 		if (err != EINPROGRESS)
9844 			CONN_OPER_PENDING_DONE(connp);
9845 		return;
9846 	}
9847 	mutex_exit(&connp->conn_lock);
9848 }
9849 
9850 /*
9851  * Called from the ipsec_loader thread, outside any perimeter, to tell
9852  * ip qenable any of the queues waiting for the ipsec loader to
9853  * complete.
9854  *
9855  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9856  * are done with this lock held, so it's guaranteed that none of the
9857  * links will change along the way.
9858  */
9859 void
9860 ip_ipsec_load_complete()
9861 {
9862 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9863 }
9864 
9865 /*
9866  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9867  * determines the grp on which it has to become exclusive, queues the mp
9868  * and sq draining restarts the optmgmt
9869  */
9870 static boolean_t
9871 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9872 {
9873 	conn_t *connp;
9874 
9875 	/*
9876 	 * Take IPsec requests and treat them special.
9877 	 */
9878 	if (ipsec_opt_present(mp)) {
9879 		/* First check if IPsec is loaded. */
9880 		mutex_enter(&ipsec_loader_lock);
9881 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9882 			mutex_exit(&ipsec_loader_lock);
9883 			return (B_FALSE);
9884 		}
9885 		connp = Q_TO_CONN(q);
9886 		mutex_enter(&connp->conn_lock);
9887 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9888 
9889 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9890 		connp->conn_ipsec_opt_mp = mp;
9891 		mutex_exit(&connp->conn_lock);
9892 		mutex_exit(&ipsec_loader_lock);
9893 
9894 		ipsec_loader_loadnow();
9895 		return (B_TRUE);
9896 	}
9897 	return (B_FALSE);
9898 }
9899 
9900 /*
9901  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9902  * all of them are copied to the conn_t. If the req is "zero", the policy is
9903  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9904  * fields.
9905  * We keep only the latest setting of the policy and thus policy setting
9906  * is not incremental/cumulative.
9907  *
9908  * Requests to set policies with multiple alternative actions will
9909  * go through a different API.
9910  */
9911 int
9912 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9913 {
9914 	uint_t ah_req = 0;
9915 	uint_t esp_req = 0;
9916 	uint_t se_req = 0;
9917 	ipsec_selkey_t sel;
9918 	ipsec_act_t *actp = NULL;
9919 	uint_t nact;
9920 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9921 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9922 	ipsec_policy_root_t *pr;
9923 	ipsec_policy_head_t *ph;
9924 	int fam;
9925 	boolean_t is_pol_reset;
9926 	int error = 0;
9927 
9928 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9929 
9930 	/*
9931 	 * The IP_SEC_OPT option does not allow variable length parameters,
9932 	 * hence a request cannot be NULL.
9933 	 */
9934 	if (req == NULL)
9935 		return (EINVAL);
9936 
9937 	ah_req = req->ipsr_ah_req;
9938 	esp_req = req->ipsr_esp_req;
9939 	se_req = req->ipsr_self_encap_req;
9940 
9941 	/*
9942 	 * Are we dealing with a request to reset the policy (i.e.
9943 	 * zero requests).
9944 	 */
9945 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9946 	    (esp_req & REQ_MASK) == 0 &&
9947 	    (se_req & REQ_MASK) == 0);
9948 
9949 	if (!is_pol_reset) {
9950 		/*
9951 		 * If we couldn't load IPsec, fail with "protocol
9952 		 * not supported".
9953 		 * IPsec may not have been loaded for a request with zero
9954 		 * policies, so we don't fail in this case.
9955 		 */
9956 		mutex_enter(&ipsec_loader_lock);
9957 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9958 			mutex_exit(&ipsec_loader_lock);
9959 			return (EPROTONOSUPPORT);
9960 		}
9961 		mutex_exit(&ipsec_loader_lock);
9962 
9963 		/*
9964 		 * Test for valid requests. Invalid algorithms
9965 		 * need to be tested by IPSEC code because new
9966 		 * algorithms can be added dynamically.
9967 		 */
9968 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9969 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9970 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9971 			return (EINVAL);
9972 		}
9973 
9974 		/*
9975 		 * Only privileged users can issue these
9976 		 * requests.
9977 		 */
9978 		if (((ah_req & IPSEC_PREF_NEVER) ||
9979 		    (esp_req & IPSEC_PREF_NEVER) ||
9980 		    (se_req & IPSEC_PREF_NEVER)) &&
9981 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9982 			return (EPERM);
9983 		}
9984 
9985 		/*
9986 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9987 		 * are mutually exclusive.
9988 		 */
9989 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9990 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9991 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9992 			/* Both of them are set */
9993 			return (EINVAL);
9994 		}
9995 	}
9996 
9997 	mutex_enter(&connp->conn_lock);
9998 
9999 	/*
10000 	 * If we have already cached policies in ip_bind_connected*(), don't
10001 	 * let them change now. We cache policies for connections
10002 	 * whose src,dst [addr, port] is known.  The exception to this is
10003 	 * tunnels.  Tunnels are allowed to change policies after having
10004 	 * become fully bound.
10005 	 */
10006 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
10007 		mutex_exit(&connp->conn_lock);
10008 		return (EINVAL);
10009 	}
10010 
10011 	/*
10012 	 * We have a zero policies, reset the connection policy if already
10013 	 * set. This will cause the connection to inherit the
10014 	 * global policy, if any.
10015 	 */
10016 	if (is_pol_reset) {
10017 		if (connp->conn_policy != NULL) {
10018 			IPPH_REFRELE(connp->conn_policy);
10019 			connp->conn_policy = NULL;
10020 		}
10021 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10022 		connp->conn_in_enforce_policy = B_FALSE;
10023 		connp->conn_out_enforce_policy = B_FALSE;
10024 		mutex_exit(&connp->conn_lock);
10025 		return (0);
10026 	}
10027 
10028 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
10029 	if (ph == NULL)
10030 		goto enomem;
10031 
10032 	ipsec_actvec_from_req(req, &actp, &nact);
10033 	if (actp == NULL)
10034 		goto enomem;
10035 
10036 	/*
10037 	 * Always allocate IPv4 policy entries, since they can also
10038 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10039 	 */
10040 	bzero(&sel, sizeof (sel));
10041 	sel.ipsl_valid = IPSL_IPV4;
10042 
10043 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
10044 	if (pin4 == NULL)
10045 		goto enomem;
10046 
10047 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
10048 	if (pout4 == NULL)
10049 		goto enomem;
10050 
10051 	if (connp->conn_pkt_isv6) {
10052 		/*
10053 		 * We're looking at a v6 socket, also allocate the
10054 		 * v6-specific entries...
10055 		 */
10056 		sel.ipsl_valid = IPSL_IPV6;
10057 		pin6 = ipsec_policy_create(&sel, actp, nact,
10058 		    IPSEC_PRIO_SOCKET);
10059 		if (pin6 == NULL)
10060 			goto enomem;
10061 
10062 		pout6 = ipsec_policy_create(&sel, actp, nact,
10063 		    IPSEC_PRIO_SOCKET);
10064 		if (pout6 == NULL)
10065 			goto enomem;
10066 
10067 		/*
10068 		 * .. and file them away in the right place.
10069 		 */
10070 		fam = IPSEC_AF_V6;
10071 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10072 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10073 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10074 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10075 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10076 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10077 	}
10078 
10079 	ipsec_actvec_free(actp, nact);
10080 
10081 	/*
10082 	 * File the v4 policies.
10083 	 */
10084 	fam = IPSEC_AF_V4;
10085 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10086 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10087 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10088 
10089 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10090 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10091 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10092 
10093 	/*
10094 	 * If the requests need security, set enforce_policy.
10095 	 * If the requests are IPSEC_PREF_NEVER, one should
10096 	 * still set conn_out_enforce_policy so that an ipsec_out
10097 	 * gets attached in ip_wput. This is needed so that
10098 	 * for connections that we don't cache policy in ip_bind,
10099 	 * if global policy matches in ip_wput_attach_policy, we
10100 	 * don't wrongly inherit global policy. Similarly, we need
10101 	 * to set conn_in_enforce_policy also so that we don't verify
10102 	 * policy wrongly.
10103 	 */
10104 	if ((ah_req & REQ_MASK) != 0 ||
10105 	    (esp_req & REQ_MASK) != 0 ||
10106 	    (se_req & REQ_MASK) != 0) {
10107 		connp->conn_in_enforce_policy = B_TRUE;
10108 		connp->conn_out_enforce_policy = B_TRUE;
10109 		connp->conn_flags |= IPCL_CHECK_POLICY;
10110 	}
10111 
10112 	/*
10113 	 * Tunnels are allowed to set policy after having been fully bound.
10114 	 * If that's the case, cache policy here.
10115 	 */
10116 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
10117 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
10118 
10119 	mutex_exit(&connp->conn_lock);
10120 	return (error);
10121 #undef REQ_MASK
10122 
10123 	/*
10124 	 * Common memory-allocation-failure exit path.
10125 	 */
10126 enomem:
10127 	mutex_exit(&connp->conn_lock);
10128 	if (actp != NULL)
10129 		ipsec_actvec_free(actp, nact);
10130 	if (pin4 != NULL)
10131 		IPPOL_REFRELE(pin4);
10132 	if (pout4 != NULL)
10133 		IPPOL_REFRELE(pout4);
10134 	if (pin6 != NULL)
10135 		IPPOL_REFRELE(pin6);
10136 	if (pout6 != NULL)
10137 		IPPOL_REFRELE(pout6);
10138 	return (ENOMEM);
10139 }
10140 
10141 /*
10142  * Only for options that pass in an IP addr. Currently only V4 options
10143  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10144  * So this function assumes level is IPPROTO_IP
10145  */
10146 int
10147 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10148     mblk_t *first_mp)
10149 {
10150 	ipif_t *ipif = NULL;
10151 	int error;
10152 	ill_t *ill;
10153 	int zoneid;
10154 
10155 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10156 
10157 	if (addr != INADDR_ANY || checkonly) {
10158 		ASSERT(connp != NULL);
10159 		zoneid = IPCL_ZONEID(connp);
10160 		if (option == IP_NEXTHOP) {
10161 			ipif = ipif_lookup_onlink_addr(addr,
10162 			    connp->conn_zoneid);
10163 		} else {
10164 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10165 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10166 			    &error);
10167 		}
10168 		if (ipif == NULL) {
10169 			if (error == EINPROGRESS)
10170 				return (error);
10171 			else if ((option == IP_MULTICAST_IF) ||
10172 			    (option == IP_NEXTHOP))
10173 				return (EHOSTUNREACH);
10174 			else
10175 				return (EINVAL);
10176 		} else if (checkonly) {
10177 			if (option == IP_MULTICAST_IF) {
10178 				ill = ipif->ipif_ill;
10179 				/* not supported by the virtual network iface */
10180 				if (IS_VNI(ill)) {
10181 					ipif_refrele(ipif);
10182 					return (EINVAL);
10183 				}
10184 			}
10185 			ipif_refrele(ipif);
10186 			return (0);
10187 		}
10188 		ill = ipif->ipif_ill;
10189 		mutex_enter(&connp->conn_lock);
10190 		mutex_enter(&ill->ill_lock);
10191 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10192 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10193 			mutex_exit(&ill->ill_lock);
10194 			mutex_exit(&connp->conn_lock);
10195 			ipif_refrele(ipif);
10196 			return (option == IP_MULTICAST_IF ?
10197 			    EHOSTUNREACH : EINVAL);
10198 		}
10199 	} else {
10200 		mutex_enter(&connp->conn_lock);
10201 	}
10202 
10203 	/* None of the options below are supported on the VNI */
10204 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10205 		mutex_exit(&ill->ill_lock);
10206 		mutex_exit(&connp->conn_lock);
10207 		ipif_refrele(ipif);
10208 		return (EINVAL);
10209 	}
10210 
10211 	switch (option) {
10212 	case IP_DONTFAILOVER_IF:
10213 		/*
10214 		 * This option is used by in.mpathd to ensure
10215 		 * that IPMP probe packets only go out on the
10216 		 * test interfaces. in.mpathd sets this option
10217 		 * on the non-failover interfaces.
10218 		 * For backward compatibility, this option
10219 		 * implicitly sets IP_MULTICAST_IF, as used
10220 		 * be done in bind(), so that ip_wput gets
10221 		 * this ipif to send mcast packets.
10222 		 */
10223 		if (ipif != NULL) {
10224 			ASSERT(addr != INADDR_ANY);
10225 			connp->conn_nofailover_ill = ipif->ipif_ill;
10226 			connp->conn_multicast_ipif = ipif;
10227 		} else {
10228 			ASSERT(addr == INADDR_ANY);
10229 			connp->conn_nofailover_ill = NULL;
10230 			connp->conn_multicast_ipif = NULL;
10231 		}
10232 		break;
10233 
10234 	case IP_MULTICAST_IF:
10235 		connp->conn_multicast_ipif = ipif;
10236 		break;
10237 	case IP_NEXTHOP:
10238 		connp->conn_nexthop_v4 = addr;
10239 		connp->conn_nexthop_set = B_TRUE;
10240 		break;
10241 	}
10242 
10243 	if (ipif != NULL) {
10244 		mutex_exit(&ill->ill_lock);
10245 		mutex_exit(&connp->conn_lock);
10246 		ipif_refrele(ipif);
10247 		return (0);
10248 	}
10249 	mutex_exit(&connp->conn_lock);
10250 	/* We succeded in cleared the option */
10251 	return (0);
10252 }
10253 
10254 /*
10255  * For options that pass in an ifindex specifying the ill. V6 options always
10256  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10257  */
10258 int
10259 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10260     int level, int option, mblk_t *first_mp)
10261 {
10262 	ill_t *ill = NULL;
10263 	int error = 0;
10264 
10265 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10266 	if (ifindex != 0) {
10267 		ASSERT(connp != NULL);
10268 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10269 		    first_mp, ip_restart_optmgmt, &error);
10270 		if (ill != NULL) {
10271 			if (checkonly) {
10272 				/* not supported by the virtual network iface */
10273 				if (IS_VNI(ill)) {
10274 					ill_refrele(ill);
10275 					return (EINVAL);
10276 				}
10277 				ill_refrele(ill);
10278 				return (0);
10279 			}
10280 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10281 			    0, NULL)) {
10282 				ill_refrele(ill);
10283 				ill = NULL;
10284 				mutex_enter(&connp->conn_lock);
10285 				goto setit;
10286 			}
10287 			mutex_enter(&connp->conn_lock);
10288 			mutex_enter(&ill->ill_lock);
10289 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10290 				mutex_exit(&ill->ill_lock);
10291 				mutex_exit(&connp->conn_lock);
10292 				ill_refrele(ill);
10293 				ill = NULL;
10294 				mutex_enter(&connp->conn_lock);
10295 			}
10296 			goto setit;
10297 		} else if (error == EINPROGRESS) {
10298 			return (error);
10299 		} else {
10300 			error = 0;
10301 		}
10302 	}
10303 	mutex_enter(&connp->conn_lock);
10304 setit:
10305 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10306 
10307 	/*
10308 	 * The options below assume that the ILL (if any) transmits and/or
10309 	 * receives traffic. Neither of which is true for the virtual network
10310 	 * interface, so fail setting these on a VNI.
10311 	 */
10312 	if (IS_VNI(ill)) {
10313 		ASSERT(ill != NULL);
10314 		mutex_exit(&ill->ill_lock);
10315 		mutex_exit(&connp->conn_lock);
10316 		ill_refrele(ill);
10317 		return (EINVAL);
10318 	}
10319 
10320 	if (level == IPPROTO_IP) {
10321 		switch (option) {
10322 		case IP_BOUND_IF:
10323 			connp->conn_incoming_ill = ill;
10324 			connp->conn_outgoing_ill = ill;
10325 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10326 			    0 : ifindex;
10327 			break;
10328 
10329 		case IP_XMIT_IF:
10330 			/*
10331 			 * Similar to IP_BOUND_IF, but this only
10332 			 * determines the outgoing interface for
10333 			 * unicast packets. Also no IRE_CACHE entry
10334 			 * is added for the destination of the
10335 			 * outgoing packets. This feature is needed
10336 			 * for mobile IP.
10337 			 */
10338 			connp->conn_xmit_if_ill = ill;
10339 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10340 			    0 : ifindex;
10341 			break;
10342 
10343 		case IP_MULTICAST_IF:
10344 			/*
10345 			 * This option is an internal special. The socket
10346 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10347 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10348 			 * specifies an ifindex and we try first on V6 ill's.
10349 			 * If we don't find one, we they try using on v4 ill's
10350 			 * intenally and we come here.
10351 			 */
10352 			if (!checkonly && ill != NULL) {
10353 				ipif_t	*ipif;
10354 				ipif = ill->ill_ipif;
10355 
10356 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10357 					mutex_exit(&ill->ill_lock);
10358 					mutex_exit(&connp->conn_lock);
10359 					ill_refrele(ill);
10360 					ill = NULL;
10361 					mutex_enter(&connp->conn_lock);
10362 				} else {
10363 					connp->conn_multicast_ipif = ipif;
10364 				}
10365 			}
10366 			break;
10367 		}
10368 	} else {
10369 		switch (option) {
10370 		case IPV6_BOUND_IF:
10371 			connp->conn_incoming_ill = ill;
10372 			connp->conn_outgoing_ill = ill;
10373 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10374 			    0 : ifindex;
10375 			break;
10376 
10377 		case IPV6_BOUND_PIF:
10378 			/*
10379 			 * Limit all transmit to this ill.
10380 			 * Unlike IPV6_BOUND_IF, using this option
10381 			 * prevents load spreading and failover from
10382 			 * happening when the interface is part of the
10383 			 * group. That's why we don't need to remember
10384 			 * the ifindex in orig_bound_ifindex as in
10385 			 * IPV6_BOUND_IF.
10386 			 */
10387 			connp->conn_outgoing_pill = ill;
10388 			break;
10389 
10390 		case IPV6_DONTFAILOVER_IF:
10391 			/*
10392 			 * This option is used by in.mpathd to ensure
10393 			 * that IPMP probe packets only go out on the
10394 			 * test interfaces. in.mpathd sets this option
10395 			 * on the non-failover interfaces.
10396 			 */
10397 			connp->conn_nofailover_ill = ill;
10398 			/*
10399 			 * For backward compatibility, this option
10400 			 * implicitly sets ip_multicast_ill as used in
10401 			 * IP_MULTICAST_IF so that ip_wput gets
10402 			 * this ipif to send mcast packets.
10403 			 */
10404 			connp->conn_multicast_ill = ill;
10405 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10406 			    0 : ifindex;
10407 			break;
10408 
10409 		case IPV6_MULTICAST_IF:
10410 			/*
10411 			 * Set conn_multicast_ill to be the IPv6 ill.
10412 			 * Set conn_multicast_ipif to be an IPv4 ipif
10413 			 * for ifindex to make IPv4 mapped addresses
10414 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10415 			 * Even if no IPv6 ill exists for the ifindex
10416 			 * we need to check for an IPv4 ifindex in order
10417 			 * for this to work with mapped addresses. In that
10418 			 * case only set conn_multicast_ipif.
10419 			 */
10420 			if (!checkonly) {
10421 				if (ifindex == 0) {
10422 					connp->conn_multicast_ill = NULL;
10423 					connp->conn_orig_multicast_ifindex = 0;
10424 					connp->conn_multicast_ipif = NULL;
10425 				} else if (ill != NULL) {
10426 					connp->conn_multicast_ill = ill;
10427 					connp->conn_orig_multicast_ifindex =
10428 					    ifindex;
10429 				}
10430 			}
10431 			break;
10432 		}
10433 	}
10434 
10435 	if (ill != NULL) {
10436 		mutex_exit(&ill->ill_lock);
10437 		mutex_exit(&connp->conn_lock);
10438 		ill_refrele(ill);
10439 		return (0);
10440 	}
10441 	mutex_exit(&connp->conn_lock);
10442 	/*
10443 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10444 	 * locate the ill and could not set the option (ifindex != 0)
10445 	 */
10446 	return (ifindex == 0 ? 0 : EINVAL);
10447 }
10448 
10449 /* This routine sets socket options. */
10450 /* ARGSUSED */
10451 int
10452 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10453     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10454     void *dummy, cred_t *cr, mblk_t *first_mp)
10455 {
10456 	int		*i1 = (int *)invalp;
10457 	conn_t		*connp = Q_TO_CONN(q);
10458 	int		error = 0;
10459 	boolean_t	checkonly;
10460 	ire_t		*ire;
10461 	boolean_t	found;
10462 
10463 	switch (optset_context) {
10464 
10465 	case SETFN_OPTCOM_CHECKONLY:
10466 		checkonly = B_TRUE;
10467 		/*
10468 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10469 		 * inlen != 0 implies value supplied and
10470 		 * 	we have to "pretend" to set it.
10471 		 * inlen == 0 implies that there is no
10472 		 * 	value part in T_CHECK request and just validation
10473 		 * done elsewhere should be enough, we just return here.
10474 		 */
10475 		if (inlen == 0) {
10476 			*outlenp = 0;
10477 			return (0);
10478 		}
10479 		break;
10480 	case SETFN_OPTCOM_NEGOTIATE:
10481 	case SETFN_UD_NEGOTIATE:
10482 	case SETFN_CONN_NEGOTIATE:
10483 		checkonly = B_FALSE;
10484 		break;
10485 	default:
10486 		/*
10487 		 * We should never get here
10488 		 */
10489 		*outlenp = 0;
10490 		return (EINVAL);
10491 	}
10492 
10493 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10494 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10495 
10496 	/*
10497 	 * For fixed length options, no sanity check
10498 	 * of passed in length is done. It is assumed *_optcom_req()
10499 	 * routines do the right thing.
10500 	 */
10501 
10502 	switch (level) {
10503 	case SOL_SOCKET:
10504 		/*
10505 		 * conn_lock protects the bitfields, and is used to
10506 		 * set the fields atomically.
10507 		 */
10508 		switch (name) {
10509 		case SO_BROADCAST:
10510 			if (!checkonly) {
10511 				/* TODO: use value someplace? */
10512 				mutex_enter(&connp->conn_lock);
10513 				connp->conn_broadcast = *i1 ? 1 : 0;
10514 				mutex_exit(&connp->conn_lock);
10515 			}
10516 			break;	/* goto sizeof (int) option return */
10517 		case SO_USELOOPBACK:
10518 			if (!checkonly) {
10519 				/* TODO: use value someplace? */
10520 				mutex_enter(&connp->conn_lock);
10521 				connp->conn_loopback = *i1 ? 1 : 0;
10522 				mutex_exit(&connp->conn_lock);
10523 			}
10524 			break;	/* goto sizeof (int) option return */
10525 		case SO_DONTROUTE:
10526 			if (!checkonly) {
10527 				mutex_enter(&connp->conn_lock);
10528 				connp->conn_dontroute = *i1 ? 1 : 0;
10529 				mutex_exit(&connp->conn_lock);
10530 			}
10531 			break;	/* goto sizeof (int) option return */
10532 		case SO_REUSEADDR:
10533 			if (!checkonly) {
10534 				mutex_enter(&connp->conn_lock);
10535 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10536 				mutex_exit(&connp->conn_lock);
10537 			}
10538 			break;	/* goto sizeof (int) option return */
10539 		case SO_PROTOTYPE:
10540 			if (!checkonly) {
10541 				mutex_enter(&connp->conn_lock);
10542 				connp->conn_proto = *i1;
10543 				mutex_exit(&connp->conn_lock);
10544 			}
10545 			break;	/* goto sizeof (int) option return */
10546 		case SO_ALLZONES:
10547 			if (!checkonly) {
10548 				mutex_enter(&connp->conn_lock);
10549 				if (IPCL_IS_BOUND(connp)) {
10550 					mutex_exit(&connp->conn_lock);
10551 					return (EINVAL);
10552 				}
10553 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10554 				mutex_exit(&connp->conn_lock);
10555 			}
10556 			break;	/* goto sizeof (int) option return */
10557 		case SO_ANON_MLP:
10558 			if (!checkonly) {
10559 				mutex_enter(&connp->conn_lock);
10560 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10561 				mutex_exit(&connp->conn_lock);
10562 			}
10563 			break;	/* goto sizeof (int) option return */
10564 		case SO_MAC_EXEMPT:
10565 			if (secpolicy_net_mac_aware(cr) != 0 ||
10566 			    IPCL_IS_BOUND(connp))
10567 				return (EACCES);
10568 			if (!checkonly) {
10569 				mutex_enter(&connp->conn_lock);
10570 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10571 				mutex_exit(&connp->conn_lock);
10572 			}
10573 			break;	/* goto sizeof (int) option return */
10574 		default:
10575 			/*
10576 			 * "soft" error (negative)
10577 			 * option not handled at this level
10578 			 * Note: Do not modify *outlenp
10579 			 */
10580 			return (-EINVAL);
10581 		}
10582 		break;
10583 	case IPPROTO_IP:
10584 		switch (name) {
10585 		case IP_NEXTHOP:
10586 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10587 				return (EPERM);
10588 			/* FALLTHRU */
10589 		case IP_MULTICAST_IF:
10590 		case IP_DONTFAILOVER_IF: {
10591 			ipaddr_t addr = *i1;
10592 
10593 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10594 			    first_mp);
10595 			if (error != 0)
10596 				return (error);
10597 			break;	/* goto sizeof (int) option return */
10598 		}
10599 
10600 		case IP_MULTICAST_TTL:
10601 			/* Recorded in transport above IP */
10602 			*outvalp = *invalp;
10603 			*outlenp = sizeof (uchar_t);
10604 			return (0);
10605 		case IP_MULTICAST_LOOP:
10606 			if (!checkonly) {
10607 				mutex_enter(&connp->conn_lock);
10608 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10609 				mutex_exit(&connp->conn_lock);
10610 			}
10611 			*outvalp = *invalp;
10612 			*outlenp = sizeof (uchar_t);
10613 			return (0);
10614 		case IP_ADD_MEMBERSHIP:
10615 		case MCAST_JOIN_GROUP:
10616 		case IP_DROP_MEMBERSHIP:
10617 		case MCAST_LEAVE_GROUP: {
10618 			struct ip_mreq *mreqp;
10619 			struct group_req *greqp;
10620 			ire_t *ire;
10621 			boolean_t done = B_FALSE;
10622 			ipaddr_t group, ifaddr;
10623 			struct sockaddr_in *sin;
10624 			uint32_t *ifindexp;
10625 			boolean_t mcast_opt = B_TRUE;
10626 			mcast_record_t fmode;
10627 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10628 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10629 
10630 			switch (name) {
10631 			case IP_ADD_MEMBERSHIP:
10632 				mcast_opt = B_FALSE;
10633 				/* FALLTHRU */
10634 			case MCAST_JOIN_GROUP:
10635 				fmode = MODE_IS_EXCLUDE;
10636 				optfn = ip_opt_add_group;
10637 				break;
10638 
10639 			case IP_DROP_MEMBERSHIP:
10640 				mcast_opt = B_FALSE;
10641 				/* FALLTHRU */
10642 			case MCAST_LEAVE_GROUP:
10643 				fmode = MODE_IS_INCLUDE;
10644 				optfn = ip_opt_delete_group;
10645 				break;
10646 			}
10647 
10648 			if (mcast_opt) {
10649 				greqp = (struct group_req *)i1;
10650 				sin = (struct sockaddr_in *)&greqp->gr_group;
10651 				if (sin->sin_family != AF_INET) {
10652 					*outlenp = 0;
10653 					return (ENOPROTOOPT);
10654 				}
10655 				group = (ipaddr_t)sin->sin_addr.s_addr;
10656 				ifaddr = INADDR_ANY;
10657 				ifindexp = &greqp->gr_interface;
10658 			} else {
10659 				mreqp = (struct ip_mreq *)i1;
10660 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10661 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10662 				ifindexp = NULL;
10663 			}
10664 
10665 			/*
10666 			 * In the multirouting case, we need to replicate
10667 			 * the request on all interfaces that will take part
10668 			 * in replication.  We do so because multirouting is
10669 			 * reflective, thus we will probably receive multi-
10670 			 * casts on those interfaces.
10671 			 * The ip_multirt_apply_membership() succeeds if the
10672 			 * operation succeeds on at least one interface.
10673 			 */
10674 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10675 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10676 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10677 			if (ire != NULL) {
10678 				if (ire->ire_flags & RTF_MULTIRT) {
10679 					error = ip_multirt_apply_membership(
10680 					    optfn, ire, connp, checkonly, group,
10681 					    fmode, INADDR_ANY, first_mp);
10682 					done = B_TRUE;
10683 				}
10684 				ire_refrele(ire);
10685 			}
10686 			if (!done) {
10687 				error = optfn(connp, checkonly, group, ifaddr,
10688 				    ifindexp, fmode, INADDR_ANY, first_mp);
10689 			}
10690 			if (error) {
10691 				/*
10692 				 * EINPROGRESS is a soft error, needs retry
10693 				 * so don't make *outlenp zero.
10694 				 */
10695 				if (error != EINPROGRESS)
10696 					*outlenp = 0;
10697 				return (error);
10698 			}
10699 			/* OK return - copy input buffer into output buffer */
10700 			if (invalp != outvalp) {
10701 				/* don't trust bcopy for identical src/dst */
10702 				bcopy(invalp, outvalp, inlen);
10703 			}
10704 			*outlenp = inlen;
10705 			return (0);
10706 		}
10707 		case IP_BLOCK_SOURCE:
10708 		case IP_UNBLOCK_SOURCE:
10709 		case IP_ADD_SOURCE_MEMBERSHIP:
10710 		case IP_DROP_SOURCE_MEMBERSHIP:
10711 		case MCAST_BLOCK_SOURCE:
10712 		case MCAST_UNBLOCK_SOURCE:
10713 		case MCAST_JOIN_SOURCE_GROUP:
10714 		case MCAST_LEAVE_SOURCE_GROUP: {
10715 			struct ip_mreq_source *imreqp;
10716 			struct group_source_req *gsreqp;
10717 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10718 			uint32_t ifindex = 0;
10719 			mcast_record_t fmode;
10720 			struct sockaddr_in *sin;
10721 			ire_t *ire;
10722 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10723 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10724 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10725 
10726 			switch (name) {
10727 			case IP_BLOCK_SOURCE:
10728 				mcast_opt = B_FALSE;
10729 				/* FALLTHRU */
10730 			case MCAST_BLOCK_SOURCE:
10731 				fmode = MODE_IS_EXCLUDE;
10732 				optfn = ip_opt_add_group;
10733 				break;
10734 
10735 			case IP_UNBLOCK_SOURCE:
10736 				mcast_opt = B_FALSE;
10737 				/* FALLTHRU */
10738 			case MCAST_UNBLOCK_SOURCE:
10739 				fmode = MODE_IS_EXCLUDE;
10740 				optfn = ip_opt_delete_group;
10741 				break;
10742 
10743 			case IP_ADD_SOURCE_MEMBERSHIP:
10744 				mcast_opt = B_FALSE;
10745 				/* FALLTHRU */
10746 			case MCAST_JOIN_SOURCE_GROUP:
10747 				fmode = MODE_IS_INCLUDE;
10748 				optfn = ip_opt_add_group;
10749 				break;
10750 
10751 			case IP_DROP_SOURCE_MEMBERSHIP:
10752 				mcast_opt = B_FALSE;
10753 				/* FALLTHRU */
10754 			case MCAST_LEAVE_SOURCE_GROUP:
10755 				fmode = MODE_IS_INCLUDE;
10756 				optfn = ip_opt_delete_group;
10757 				break;
10758 			}
10759 
10760 			if (mcast_opt) {
10761 				gsreqp = (struct group_source_req *)i1;
10762 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10763 					*outlenp = 0;
10764 					return (ENOPROTOOPT);
10765 				}
10766 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10767 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10768 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10769 				src = (ipaddr_t)sin->sin_addr.s_addr;
10770 				ifindex = gsreqp->gsr_interface;
10771 			} else {
10772 				imreqp = (struct ip_mreq_source *)i1;
10773 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10774 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10775 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10776 			}
10777 
10778 			/*
10779 			 * In the multirouting case, we need to replicate
10780 			 * the request as noted in the mcast cases above.
10781 			 */
10782 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10783 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10784 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10785 			if (ire != NULL) {
10786 				if (ire->ire_flags & RTF_MULTIRT) {
10787 					error = ip_multirt_apply_membership(
10788 					    optfn, ire, connp, checkonly, grp,
10789 					    fmode, src, first_mp);
10790 					done = B_TRUE;
10791 				}
10792 				ire_refrele(ire);
10793 			}
10794 			if (!done) {
10795 				error = optfn(connp, checkonly, grp, ifaddr,
10796 				    &ifindex, fmode, src, first_mp);
10797 			}
10798 			if (error != 0) {
10799 				/*
10800 				 * EINPROGRESS is a soft error, needs retry
10801 				 * so don't make *outlenp zero.
10802 				 */
10803 				if (error != EINPROGRESS)
10804 					*outlenp = 0;
10805 				return (error);
10806 			}
10807 			/* OK return - copy input buffer into output buffer */
10808 			if (invalp != outvalp) {
10809 				bcopy(invalp, outvalp, inlen);
10810 			}
10811 			*outlenp = inlen;
10812 			return (0);
10813 		}
10814 		case IP_SEC_OPT:
10815 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10816 			if (error != 0) {
10817 				*outlenp = 0;
10818 				return (error);
10819 			}
10820 			break;
10821 		case IP_HDRINCL:
10822 		case IP_OPTIONS:
10823 		case T_IP_OPTIONS:
10824 		case IP_TOS:
10825 		case T_IP_TOS:
10826 		case IP_TTL:
10827 		case IP_RECVDSTADDR:
10828 		case IP_RECVOPTS:
10829 			/* OK return - copy input buffer into output buffer */
10830 			if (invalp != outvalp) {
10831 				/* don't trust bcopy for identical src/dst */
10832 				bcopy(invalp, outvalp, inlen);
10833 			}
10834 			*outlenp = inlen;
10835 			return (0);
10836 		case IP_RECVIF:
10837 			/* Retrieve the inbound interface index */
10838 			if (!checkonly) {
10839 				mutex_enter(&connp->conn_lock);
10840 				connp->conn_recvif = *i1 ? 1 : 0;
10841 				mutex_exit(&connp->conn_lock);
10842 			}
10843 			break;	/* goto sizeof (int) option return */
10844 		case IP_RECVSLLA:
10845 			/* Retrieve the source link layer address */
10846 			if (!checkonly) {
10847 				mutex_enter(&connp->conn_lock);
10848 				connp->conn_recvslla = *i1 ? 1 : 0;
10849 				mutex_exit(&connp->conn_lock);
10850 			}
10851 			break;	/* goto sizeof (int) option return */
10852 		case MRT_INIT:
10853 		case MRT_DONE:
10854 		case MRT_ADD_VIF:
10855 		case MRT_DEL_VIF:
10856 		case MRT_ADD_MFC:
10857 		case MRT_DEL_MFC:
10858 		case MRT_ASSERT:
10859 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10860 				*outlenp = 0;
10861 				return (error);
10862 			}
10863 			error = ip_mrouter_set((int)name, q, checkonly,
10864 			    (uchar_t *)invalp, inlen, first_mp);
10865 			if (error) {
10866 				*outlenp = 0;
10867 				return (error);
10868 			}
10869 			/* OK return - copy input buffer into output buffer */
10870 			if (invalp != outvalp) {
10871 				/* don't trust bcopy for identical src/dst */
10872 				bcopy(invalp, outvalp, inlen);
10873 			}
10874 			*outlenp = inlen;
10875 			return (0);
10876 		case IP_BOUND_IF:
10877 		case IP_XMIT_IF:
10878 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10879 			    level, name, first_mp);
10880 			if (error != 0)
10881 				return (error);
10882 			break; 		/* goto sizeof (int) option return */
10883 
10884 		case IP_UNSPEC_SRC:
10885 			/* Allow sending with a zero source address */
10886 			if (!checkonly) {
10887 				mutex_enter(&connp->conn_lock);
10888 				connp->conn_unspec_src = *i1 ? 1 : 0;
10889 				mutex_exit(&connp->conn_lock);
10890 			}
10891 			break;	/* goto sizeof (int) option return */
10892 		default:
10893 			/*
10894 			 * "soft" error (negative)
10895 			 * option not handled at this level
10896 			 * Note: Do not modify *outlenp
10897 			 */
10898 			return (-EINVAL);
10899 		}
10900 		break;
10901 	case IPPROTO_IPV6:
10902 		switch (name) {
10903 		case IPV6_BOUND_IF:
10904 		case IPV6_BOUND_PIF:
10905 		case IPV6_DONTFAILOVER_IF:
10906 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10907 			    level, name, first_mp);
10908 			if (error != 0)
10909 				return (error);
10910 			break; 		/* goto sizeof (int) option return */
10911 
10912 		case IPV6_MULTICAST_IF:
10913 			/*
10914 			 * The only possible errors are EINPROGRESS and
10915 			 * EINVAL. EINPROGRESS will be restarted and is not
10916 			 * a hard error. We call this option on both V4 and V6
10917 			 * If both return EINVAL, then this call returns
10918 			 * EINVAL. If at least one of them succeeds we
10919 			 * return success.
10920 			 */
10921 			found = B_FALSE;
10922 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10923 			    level, name, first_mp);
10924 			if (error == EINPROGRESS)
10925 				return (error);
10926 			if (error == 0)
10927 				found = B_TRUE;
10928 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10929 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10930 			if (error == 0)
10931 				found = B_TRUE;
10932 			if (!found)
10933 				return (error);
10934 			break; 		/* goto sizeof (int) option return */
10935 
10936 		case IPV6_MULTICAST_HOPS:
10937 			/* Recorded in transport above IP */
10938 			break;	/* goto sizeof (int) option return */
10939 		case IPV6_MULTICAST_LOOP:
10940 			if (!checkonly) {
10941 				mutex_enter(&connp->conn_lock);
10942 				connp->conn_multicast_loop = *i1;
10943 				mutex_exit(&connp->conn_lock);
10944 			}
10945 			break;	/* goto sizeof (int) option return */
10946 		case IPV6_JOIN_GROUP:
10947 		case MCAST_JOIN_GROUP:
10948 		case IPV6_LEAVE_GROUP:
10949 		case MCAST_LEAVE_GROUP: {
10950 			struct ipv6_mreq *ip_mreqp;
10951 			struct group_req *greqp;
10952 			ire_t *ire;
10953 			boolean_t done = B_FALSE;
10954 			in6_addr_t groupv6;
10955 			uint32_t ifindex;
10956 			boolean_t mcast_opt = B_TRUE;
10957 			mcast_record_t fmode;
10958 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10959 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10960 
10961 			switch (name) {
10962 			case IPV6_JOIN_GROUP:
10963 				mcast_opt = B_FALSE;
10964 				/* FALLTHRU */
10965 			case MCAST_JOIN_GROUP:
10966 				fmode = MODE_IS_EXCLUDE;
10967 				optfn = ip_opt_add_group_v6;
10968 				break;
10969 
10970 			case IPV6_LEAVE_GROUP:
10971 				mcast_opt = B_FALSE;
10972 				/* FALLTHRU */
10973 			case MCAST_LEAVE_GROUP:
10974 				fmode = MODE_IS_INCLUDE;
10975 				optfn = ip_opt_delete_group_v6;
10976 				break;
10977 			}
10978 
10979 			if (mcast_opt) {
10980 				struct sockaddr_in *sin;
10981 				struct sockaddr_in6 *sin6;
10982 				greqp = (struct group_req *)i1;
10983 				if (greqp->gr_group.ss_family == AF_INET) {
10984 					sin = (struct sockaddr_in *)
10985 					    &(greqp->gr_group);
10986 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10987 					    &groupv6);
10988 				} else {
10989 					sin6 = (struct sockaddr_in6 *)
10990 					    &(greqp->gr_group);
10991 					groupv6 = sin6->sin6_addr;
10992 				}
10993 				ifindex = greqp->gr_interface;
10994 			} else {
10995 				ip_mreqp = (struct ipv6_mreq *)i1;
10996 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10997 				ifindex = ip_mreqp->ipv6mr_interface;
10998 			}
10999 			/*
11000 			 * In the multirouting case, we need to replicate
11001 			 * the request on all interfaces that will take part
11002 			 * in replication.  We do so because multirouting is
11003 			 * reflective, thus we will probably receive multi-
11004 			 * casts on those interfaces.
11005 			 * The ip_multirt_apply_membership_v6() succeeds if
11006 			 * the operation succeeds on at least one interface.
11007 			 */
11008 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11009 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11010 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11011 			if (ire != NULL) {
11012 				if (ire->ire_flags & RTF_MULTIRT) {
11013 					error = ip_multirt_apply_membership_v6(
11014 					    optfn, ire, connp, checkonly,
11015 					    &groupv6, fmode, &ipv6_all_zeros,
11016 					    first_mp);
11017 					done = B_TRUE;
11018 				}
11019 				ire_refrele(ire);
11020 			}
11021 			if (!done) {
11022 				error = optfn(connp, checkonly, &groupv6,
11023 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11024 			}
11025 			if (error) {
11026 				/*
11027 				 * EINPROGRESS is a soft error, needs retry
11028 				 * so don't make *outlenp zero.
11029 				 */
11030 				if (error != EINPROGRESS)
11031 					*outlenp = 0;
11032 				return (error);
11033 			}
11034 			/* OK return - copy input buffer into output buffer */
11035 			if (invalp != outvalp) {
11036 				/* don't trust bcopy for identical src/dst */
11037 				bcopy(invalp, outvalp, inlen);
11038 			}
11039 			*outlenp = inlen;
11040 			return (0);
11041 		}
11042 		case MCAST_BLOCK_SOURCE:
11043 		case MCAST_UNBLOCK_SOURCE:
11044 		case MCAST_JOIN_SOURCE_GROUP:
11045 		case MCAST_LEAVE_SOURCE_GROUP: {
11046 			struct group_source_req *gsreqp;
11047 			in6_addr_t v6grp, v6src;
11048 			uint32_t ifindex;
11049 			mcast_record_t fmode;
11050 			ire_t *ire;
11051 			boolean_t done = B_FALSE;
11052 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11053 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11054 
11055 			switch (name) {
11056 			case MCAST_BLOCK_SOURCE:
11057 				fmode = MODE_IS_EXCLUDE;
11058 				optfn = ip_opt_add_group_v6;
11059 				break;
11060 			case MCAST_UNBLOCK_SOURCE:
11061 				fmode = MODE_IS_EXCLUDE;
11062 				optfn = ip_opt_delete_group_v6;
11063 				break;
11064 			case MCAST_JOIN_SOURCE_GROUP:
11065 				fmode = MODE_IS_INCLUDE;
11066 				optfn = ip_opt_add_group_v6;
11067 				break;
11068 			case MCAST_LEAVE_SOURCE_GROUP:
11069 				fmode = MODE_IS_INCLUDE;
11070 				optfn = ip_opt_delete_group_v6;
11071 				break;
11072 			}
11073 
11074 			gsreqp = (struct group_source_req *)i1;
11075 			ifindex = gsreqp->gsr_interface;
11076 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11077 				struct sockaddr_in *s;
11078 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11079 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11080 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11081 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11082 			} else {
11083 				struct sockaddr_in6 *s6;
11084 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11085 				v6grp = s6->sin6_addr;
11086 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11087 				v6src = s6->sin6_addr;
11088 			}
11089 
11090 			/*
11091 			 * In the multirouting case, we need to replicate
11092 			 * the request as noted in the mcast cases above.
11093 			 */
11094 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11095 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11096 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11097 			if (ire != NULL) {
11098 				if (ire->ire_flags & RTF_MULTIRT) {
11099 					error = ip_multirt_apply_membership_v6(
11100 					    optfn, ire, connp, checkonly,
11101 					    &v6grp, fmode, &v6src, first_mp);
11102 					done = B_TRUE;
11103 				}
11104 				ire_refrele(ire);
11105 			}
11106 			if (!done) {
11107 				error = optfn(connp, checkonly, &v6grp,
11108 				    ifindex, fmode, &v6src, first_mp);
11109 			}
11110 			if (error != 0) {
11111 				/*
11112 				 * EINPROGRESS is a soft error, needs retry
11113 				 * so don't make *outlenp zero.
11114 				 */
11115 				if (error != EINPROGRESS)
11116 					*outlenp = 0;
11117 				return (error);
11118 			}
11119 			/* OK return - copy input buffer into output buffer */
11120 			if (invalp != outvalp) {
11121 				bcopy(invalp, outvalp, inlen);
11122 			}
11123 			*outlenp = inlen;
11124 			return (0);
11125 		}
11126 		case IPV6_UNICAST_HOPS:
11127 			/* Recorded in transport above IP */
11128 			break;	/* goto sizeof (int) option return */
11129 		case IPV6_UNSPEC_SRC:
11130 			/* Allow sending with a zero source address */
11131 			if (!checkonly) {
11132 				mutex_enter(&connp->conn_lock);
11133 				connp->conn_unspec_src = *i1 ? 1 : 0;
11134 				mutex_exit(&connp->conn_lock);
11135 			}
11136 			break;	/* goto sizeof (int) option return */
11137 		case IPV6_RECVPKTINFO:
11138 			if (!checkonly) {
11139 				mutex_enter(&connp->conn_lock);
11140 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
11141 				mutex_exit(&connp->conn_lock);
11142 			}
11143 			break;	/* goto sizeof (int) option return */
11144 		case IPV6_RECVTCLASS:
11145 			if (!checkonly) {
11146 				if (*i1 < 0 || *i1 > 1) {
11147 					return (EINVAL);
11148 				}
11149 				mutex_enter(&connp->conn_lock);
11150 				connp->conn_ipv6_recvtclass = *i1;
11151 				mutex_exit(&connp->conn_lock);
11152 			}
11153 			break;
11154 		case IPV6_RECVPATHMTU:
11155 			if (!checkonly) {
11156 				if (*i1 < 0 || *i1 > 1) {
11157 					return (EINVAL);
11158 				}
11159 				mutex_enter(&connp->conn_lock);
11160 				connp->conn_ipv6_recvpathmtu = *i1;
11161 				mutex_exit(&connp->conn_lock);
11162 			}
11163 			break;
11164 		case IPV6_RECVHOPLIMIT:
11165 			if (!checkonly) {
11166 				mutex_enter(&connp->conn_lock);
11167 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11168 				mutex_exit(&connp->conn_lock);
11169 			}
11170 			break;	/* goto sizeof (int) option return */
11171 		case IPV6_RECVHOPOPTS:
11172 			if (!checkonly) {
11173 				mutex_enter(&connp->conn_lock);
11174 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11175 				mutex_exit(&connp->conn_lock);
11176 			}
11177 			break;	/* goto sizeof (int) option return */
11178 		case IPV6_RECVDSTOPTS:
11179 			if (!checkonly) {
11180 				mutex_enter(&connp->conn_lock);
11181 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11182 				mutex_exit(&connp->conn_lock);
11183 			}
11184 			break;	/* goto sizeof (int) option return */
11185 		case IPV6_RECVRTHDR:
11186 			if (!checkonly) {
11187 				mutex_enter(&connp->conn_lock);
11188 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11189 				mutex_exit(&connp->conn_lock);
11190 			}
11191 			break;	/* goto sizeof (int) option return */
11192 		case IPV6_RECVRTHDRDSTOPTS:
11193 			if (!checkonly) {
11194 				mutex_enter(&connp->conn_lock);
11195 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11196 				mutex_exit(&connp->conn_lock);
11197 			}
11198 			break;	/* goto sizeof (int) option return */
11199 		case IPV6_PKTINFO:
11200 			if (inlen == 0)
11201 				return (-EINVAL);	/* clearing option */
11202 			error = ip6_set_pktinfo(cr, connp,
11203 			    (struct in6_pktinfo *)invalp, first_mp);
11204 			if (error != 0)
11205 				*outlenp = 0;
11206 			else
11207 				*outlenp = inlen;
11208 			return (error);
11209 		case IPV6_NEXTHOP: {
11210 			struct sockaddr_in6 *sin6;
11211 
11212 			/* Verify that the nexthop is reachable */
11213 			if (inlen == 0)
11214 				return (-EINVAL);	/* clearing option */
11215 
11216 			sin6 = (struct sockaddr_in6 *)invalp;
11217 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11218 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11219 			    NULL, MATCH_IRE_DEFAULT);
11220 
11221 			if (ire == NULL) {
11222 				*outlenp = 0;
11223 				return (EHOSTUNREACH);
11224 			}
11225 			ire_refrele(ire);
11226 			return (-EINVAL);
11227 		}
11228 		case IPV6_SEC_OPT:
11229 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11230 			if (error != 0) {
11231 				*outlenp = 0;
11232 				return (error);
11233 			}
11234 			break;
11235 		case IPV6_SRC_PREFERENCES: {
11236 			/*
11237 			 * This is implemented strictly in the ip module
11238 			 * (here and in tcp_opt_*() to accomodate tcp
11239 			 * sockets).  Modules above ip pass this option
11240 			 * down here since ip is the only one that needs to
11241 			 * be aware of source address preferences.
11242 			 *
11243 			 * This socket option only affects connected
11244 			 * sockets that haven't already bound to a specific
11245 			 * IPv6 address.  In other words, sockets that
11246 			 * don't call bind() with an address other than the
11247 			 * unspecified address and that call connect().
11248 			 * ip_bind_connected_v6() passes these preferences
11249 			 * to the ipif_select_source_v6() function.
11250 			 */
11251 			if (inlen != sizeof (uint32_t))
11252 				return (EINVAL);
11253 			error = ip6_set_src_preferences(connp,
11254 			    *(uint32_t *)invalp);
11255 			if (error != 0) {
11256 				*outlenp = 0;
11257 				return (error);
11258 			} else {
11259 				*outlenp = sizeof (uint32_t);
11260 			}
11261 			break;
11262 		}
11263 		case IPV6_V6ONLY:
11264 			if (*i1 < 0 || *i1 > 1) {
11265 				return (EINVAL);
11266 			}
11267 			mutex_enter(&connp->conn_lock);
11268 			connp->conn_ipv6_v6only = *i1;
11269 			mutex_exit(&connp->conn_lock);
11270 			break;
11271 		default:
11272 			return (-EINVAL);
11273 		}
11274 		break;
11275 	default:
11276 		/*
11277 		 * "soft" error (negative)
11278 		 * option not handled at this level
11279 		 * Note: Do not modify *outlenp
11280 		 */
11281 		return (-EINVAL);
11282 	}
11283 	/*
11284 	 * Common case of return from an option that is sizeof (int)
11285 	 */
11286 	*(int *)outvalp = *i1;
11287 	*outlenp = sizeof (int);
11288 	return (0);
11289 }
11290 
11291 /*
11292  * This routine gets default values of certain options whose default
11293  * values are maintained by protocol specific code
11294  */
11295 /* ARGSUSED */
11296 int
11297 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11298 {
11299 	int *i1 = (int *)ptr;
11300 
11301 	switch (level) {
11302 	case IPPROTO_IP:
11303 		switch (name) {
11304 		case IP_MULTICAST_TTL:
11305 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11306 			return (sizeof (uchar_t));
11307 		case IP_MULTICAST_LOOP:
11308 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11309 			return (sizeof (uchar_t));
11310 		default:
11311 			return (-1);
11312 		}
11313 	case IPPROTO_IPV6:
11314 		switch (name) {
11315 		case IPV6_UNICAST_HOPS:
11316 			*i1 = ipv6_def_hops;
11317 			return (sizeof (int));
11318 		case IPV6_MULTICAST_HOPS:
11319 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11320 			return (sizeof (int));
11321 		case IPV6_MULTICAST_LOOP:
11322 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11323 			return (sizeof (int));
11324 		case IPV6_V6ONLY:
11325 			*i1 = 1;
11326 			return (sizeof (int));
11327 		default:
11328 			return (-1);
11329 		}
11330 	default:
11331 		return (-1);
11332 	}
11333 	/* NOTREACHED */
11334 }
11335 
11336 /*
11337  * Given a destination address and a pointer to where to put the information
11338  * this routine fills in the mtuinfo.
11339  */
11340 int
11341 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11342     struct ip6_mtuinfo *mtuinfo)
11343 {
11344 	ire_t *ire;
11345 
11346 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11347 		return (-1);
11348 
11349 	bzero(mtuinfo, sizeof (*mtuinfo));
11350 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11351 	mtuinfo->ip6m_addr.sin6_port = port;
11352 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11353 
11354 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11355 	if (ire != NULL) {
11356 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11357 		ire_refrele(ire);
11358 	} else {
11359 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11360 	}
11361 	return (sizeof (struct ip6_mtuinfo));
11362 }
11363 
11364 /*
11365  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11366  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11367  * isn't.  This doesn't matter as the error checking is done properly for the
11368  * other MRT options coming in through ip_opt_set.
11369  */
11370 int
11371 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11372 {
11373 	conn_t		*connp = Q_TO_CONN(q);
11374 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11375 
11376 	switch (level) {
11377 	case IPPROTO_IP:
11378 		switch (name) {
11379 		case MRT_VERSION:
11380 		case MRT_ASSERT:
11381 			(void) ip_mrouter_get(name, q, ptr);
11382 			return (sizeof (int));
11383 		case IP_SEC_OPT:
11384 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11385 		case IP_NEXTHOP:
11386 			if (connp->conn_nexthop_set) {
11387 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11388 				return (sizeof (ipaddr_t));
11389 			} else
11390 				return (0);
11391 		default:
11392 			break;
11393 		}
11394 		break;
11395 	case IPPROTO_IPV6:
11396 		switch (name) {
11397 		case IPV6_SEC_OPT:
11398 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11399 		case IPV6_SRC_PREFERENCES: {
11400 			return (ip6_get_src_preferences(connp,
11401 			    (uint32_t *)ptr));
11402 		}
11403 		case IPV6_V6ONLY:
11404 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11405 			return (sizeof (int));
11406 		case IPV6_PATHMTU:
11407 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11408 				(struct ip6_mtuinfo *)ptr));
11409 		default:
11410 			break;
11411 		}
11412 		break;
11413 	default:
11414 		break;
11415 	}
11416 	return (-1);
11417 }
11418 
11419 /* Named Dispatch routine to get a current value out of our parameter table. */
11420 /* ARGSUSED */
11421 static int
11422 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11423 {
11424 	ipparam_t *ippa = (ipparam_t *)cp;
11425 
11426 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11427 	return (0);
11428 }
11429 
11430 /* ARGSUSED */
11431 static int
11432 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11433 {
11434 
11435 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11436 	return (0);
11437 }
11438 
11439 /*
11440  * Set ip{,6}_forwarding values.  This means walking through all of the
11441  * ill's and toggling their forwarding values.
11442  */
11443 /* ARGSUSED */
11444 static int
11445 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11446 {
11447 	long new_value;
11448 	int *forwarding_value = (int *)cp;
11449 	ill_t *walker;
11450 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11451 	ill_walk_context_t ctx;
11452 
11453 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11454 	    new_value < 0 || new_value > 1) {
11455 		return (EINVAL);
11456 	}
11457 
11458 	*forwarding_value = new_value;
11459 
11460 	/*
11461 	 * Regardless of the current value of ip_forwarding, set all per-ill
11462 	 * values of ip_forwarding to the value being set.
11463 	 *
11464 	 * Bring all the ill's up to date with the new global value.
11465 	 */
11466 	rw_enter(&ill_g_lock, RW_READER);
11467 
11468 	if (isv6)
11469 		walker = ILL_START_WALK_V6(&ctx);
11470 	else
11471 		walker = ILL_START_WALK_V4(&ctx);
11472 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11473 		(void) ill_forward_set(q, mp, (new_value != 0),
11474 		    (caddr_t)walker);
11475 	}
11476 	rw_exit(&ill_g_lock);
11477 
11478 	return (0);
11479 }
11480 
11481 /*
11482  * Walk through the param array specified registering each element with the
11483  * Named Dispatch handler. This is called only during init. So it is ok
11484  * not to acquire any locks
11485  */
11486 static boolean_t
11487 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11488     ipndp_t *ipnd, size_t ipnd_cnt)
11489 {
11490 	for (; ippa_cnt-- > 0; ippa++) {
11491 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11492 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11493 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11494 				nd_free(&ip_g_nd);
11495 				return (B_FALSE);
11496 			}
11497 		}
11498 	}
11499 
11500 	for (; ipnd_cnt-- > 0; ipnd++) {
11501 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11502 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11503 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11504 			    ipnd->ip_ndp_data)) {
11505 				nd_free(&ip_g_nd);
11506 				return (B_FALSE);
11507 			}
11508 		}
11509 	}
11510 
11511 	return (B_TRUE);
11512 }
11513 
11514 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11515 /* ARGSUSED */
11516 static int
11517 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11518 {
11519 	long		new_value;
11520 	ipparam_t	*ippa = (ipparam_t *)cp;
11521 
11522 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11523 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11524 		return (EINVAL);
11525 	}
11526 	ippa->ip_param_value = new_value;
11527 	return (0);
11528 }
11529 
11530 /*
11531  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11532  * When an ipf is passed here for the first time, if
11533  * we already have in-order fragments on the queue, we convert from the fast-
11534  * path reassembly scheme to the hard-case scheme.  From then on, additional
11535  * fragments are reassembled here.  We keep track of the start and end offsets
11536  * of each piece, and the number of holes in the chain.  When the hole count
11537  * goes to zero, we are done!
11538  *
11539  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11540  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11541  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11542  * after the call to ip_reassemble().
11543  */
11544 int
11545 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11546     size_t msg_len)
11547 {
11548 	uint_t	end;
11549 	mblk_t	*next_mp;
11550 	mblk_t	*mp1;
11551 	uint_t	offset;
11552 	boolean_t incr_dups = B_TRUE;
11553 	boolean_t offset_zero_seen = B_FALSE;
11554 	boolean_t pkt_boundary_checked = B_FALSE;
11555 
11556 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11557 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11558 
11559 	/* Add in byte count */
11560 	ipf->ipf_count += msg_len;
11561 	if (ipf->ipf_end) {
11562 		/*
11563 		 * We were part way through in-order reassembly, but now there
11564 		 * is a hole.  We walk through messages already queued, and
11565 		 * mark them for hard case reassembly.  We know that up till
11566 		 * now they were in order starting from offset zero.
11567 		 */
11568 		offset = 0;
11569 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11570 			IP_REASS_SET_START(mp1, offset);
11571 			if (offset == 0) {
11572 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11573 				offset = -ipf->ipf_nf_hdr_len;
11574 			}
11575 			offset += mp1->b_wptr - mp1->b_rptr;
11576 			IP_REASS_SET_END(mp1, offset);
11577 		}
11578 		/* One hole at the end. */
11579 		ipf->ipf_hole_cnt = 1;
11580 		/* Brand it as a hard case, forever. */
11581 		ipf->ipf_end = 0;
11582 	}
11583 	/* Walk through all the new pieces. */
11584 	do {
11585 		end = start + (mp->b_wptr - mp->b_rptr);
11586 		/*
11587 		 * If start is 0, decrease 'end' only for the first mblk of
11588 		 * the fragment. Otherwise 'end' can get wrong value in the
11589 		 * second pass of the loop if first mblk is exactly the
11590 		 * size of ipf_nf_hdr_len.
11591 		 */
11592 		if (start == 0 && !offset_zero_seen) {
11593 			/* First segment */
11594 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11595 			end -= ipf->ipf_nf_hdr_len;
11596 			offset_zero_seen = B_TRUE;
11597 		}
11598 		next_mp = mp->b_cont;
11599 		/*
11600 		 * We are checking to see if there is any interesing data
11601 		 * to process.  If there isn't and the mblk isn't the
11602 		 * one which carries the unfragmentable header then we
11603 		 * drop it.  It's possible to have just the unfragmentable
11604 		 * header come through without any data.  That needs to be
11605 		 * saved.
11606 		 *
11607 		 * If the assert at the top of this function holds then the
11608 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11609 		 * is infrequently traveled enough that the test is left in
11610 		 * to protect against future code changes which break that
11611 		 * invariant.
11612 		 */
11613 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11614 			/* Empty.  Blast it. */
11615 			IP_REASS_SET_START(mp, 0);
11616 			IP_REASS_SET_END(mp, 0);
11617 			/*
11618 			 * If the ipf points to the mblk we are about to free,
11619 			 * update ipf to point to the next mblk (or NULL
11620 			 * if none).
11621 			 */
11622 			if (ipf->ipf_mp->b_cont == mp)
11623 				ipf->ipf_mp->b_cont = next_mp;
11624 			freeb(mp);
11625 			continue;
11626 		}
11627 		mp->b_cont = NULL;
11628 		IP_REASS_SET_START(mp, start);
11629 		IP_REASS_SET_END(mp, end);
11630 		if (!ipf->ipf_tail_mp) {
11631 			ipf->ipf_tail_mp = mp;
11632 			ipf->ipf_mp->b_cont = mp;
11633 			if (start == 0 || !more) {
11634 				ipf->ipf_hole_cnt = 1;
11635 				/*
11636 				 * if the first fragment comes in more than one
11637 				 * mblk, this loop will be executed for each
11638 				 * mblk. Need to adjust hole count so exiting
11639 				 * this routine will leave hole count at 1.
11640 				 */
11641 				if (next_mp)
11642 					ipf->ipf_hole_cnt++;
11643 			} else
11644 				ipf->ipf_hole_cnt = 2;
11645 			continue;
11646 		} else if (ipf->ipf_last_frag_seen && !more &&
11647 			    !pkt_boundary_checked) {
11648 			/*
11649 			 * We check datagram boundary only if this fragment
11650 			 * claims to be the last fragment and we have seen a
11651 			 * last fragment in the past too. We do this only
11652 			 * once for a given fragment.
11653 			 *
11654 			 * start cannot be 0 here as fragments with start=0
11655 			 * and MF=0 gets handled as a complete packet. These
11656 			 * fragments should not reach here.
11657 			 */
11658 
11659 			if (start + msgdsize(mp) !=
11660 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11661 				/*
11662 				 * We have two fragments both of which claim
11663 				 * to be the last fragment but gives conflicting
11664 				 * information about the whole datagram size.
11665 				 * Something fishy is going on. Drop the
11666 				 * fragment and free up the reassembly list.
11667 				 */
11668 				return (IP_REASS_FAILED);
11669 			}
11670 
11671 			/*
11672 			 * We shouldn't come to this code block again for this
11673 			 * particular fragment.
11674 			 */
11675 			pkt_boundary_checked = B_TRUE;
11676 		}
11677 
11678 		/* New stuff at or beyond tail? */
11679 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11680 		if (start >= offset) {
11681 			if (ipf->ipf_last_frag_seen) {
11682 				/* current fragment is beyond last fragment */
11683 				return (IP_REASS_FAILED);
11684 			}
11685 			/* Link it on end. */
11686 			ipf->ipf_tail_mp->b_cont = mp;
11687 			ipf->ipf_tail_mp = mp;
11688 			if (more) {
11689 				if (start != offset)
11690 					ipf->ipf_hole_cnt++;
11691 			} else if (start == offset && next_mp == NULL)
11692 					ipf->ipf_hole_cnt--;
11693 			continue;
11694 		}
11695 		mp1 = ipf->ipf_mp->b_cont;
11696 		offset = IP_REASS_START(mp1);
11697 		/* New stuff at the front? */
11698 		if (start < offset) {
11699 			if (start == 0) {
11700 				if (end >= offset) {
11701 					/* Nailed the hole at the begining. */
11702 					ipf->ipf_hole_cnt--;
11703 				}
11704 			} else if (end < offset) {
11705 				/*
11706 				 * A hole, stuff, and a hole where there used
11707 				 * to be just a hole.
11708 				 */
11709 				ipf->ipf_hole_cnt++;
11710 			}
11711 			mp->b_cont = mp1;
11712 			/* Check for overlap. */
11713 			while (end > offset) {
11714 				if (end < IP_REASS_END(mp1)) {
11715 					mp->b_wptr -= end - offset;
11716 					IP_REASS_SET_END(mp, offset);
11717 					if (ill->ill_isv6) {
11718 						BUMP_MIB(ill->ill_ip6_mib,
11719 						    ipv6ReasmPartDups);
11720 					} else {
11721 						BUMP_MIB(&ip_mib,
11722 						    ipReasmPartDups);
11723 					}
11724 					break;
11725 				}
11726 				/* Did we cover another hole? */
11727 				if ((mp1->b_cont &&
11728 				    IP_REASS_END(mp1) !=
11729 				    IP_REASS_START(mp1->b_cont) &&
11730 				    end >= IP_REASS_START(mp1->b_cont)) ||
11731 				    (!ipf->ipf_last_frag_seen && !more)) {
11732 					ipf->ipf_hole_cnt--;
11733 				}
11734 				/* Clip out mp1. */
11735 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11736 					/*
11737 					 * After clipping out mp1, this guy
11738 					 * is now hanging off the end.
11739 					 */
11740 					ipf->ipf_tail_mp = mp;
11741 				}
11742 				IP_REASS_SET_START(mp1, 0);
11743 				IP_REASS_SET_END(mp1, 0);
11744 				/* Subtract byte count */
11745 				ipf->ipf_count -= mp1->b_datap->db_lim -
11746 				    mp1->b_datap->db_base;
11747 				freeb(mp1);
11748 				if (ill->ill_isv6) {
11749 					BUMP_MIB(ill->ill_ip6_mib,
11750 					    ipv6ReasmPartDups);
11751 				} else {
11752 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11753 				}
11754 				mp1 = mp->b_cont;
11755 				if (!mp1)
11756 					break;
11757 				offset = IP_REASS_START(mp1);
11758 			}
11759 			ipf->ipf_mp->b_cont = mp;
11760 			continue;
11761 		}
11762 		/*
11763 		 * The new piece starts somewhere between the start of the head
11764 		 * and before the end of the tail.
11765 		 */
11766 		for (; mp1; mp1 = mp1->b_cont) {
11767 			offset = IP_REASS_END(mp1);
11768 			if (start < offset) {
11769 				if (end <= offset) {
11770 					/* Nothing new. */
11771 					IP_REASS_SET_START(mp, 0);
11772 					IP_REASS_SET_END(mp, 0);
11773 					/* Subtract byte count */
11774 					ipf->ipf_count -= mp->b_datap->db_lim -
11775 					    mp->b_datap->db_base;
11776 					if (incr_dups) {
11777 						ipf->ipf_num_dups++;
11778 						incr_dups = B_FALSE;
11779 					}
11780 					freeb(mp);
11781 					if (ill->ill_isv6) {
11782 						BUMP_MIB(ill->ill_ip6_mib,
11783 						    ipv6ReasmDuplicates);
11784 					} else {
11785 						BUMP_MIB(&ip_mib,
11786 						    ipReasmDuplicates);
11787 					}
11788 					break;
11789 				}
11790 				/*
11791 				 * Trim redundant stuff off beginning of new
11792 				 * piece.
11793 				 */
11794 				IP_REASS_SET_START(mp, offset);
11795 				mp->b_rptr += offset - start;
11796 				if (ill->ill_isv6) {
11797 					BUMP_MIB(ill->ill_ip6_mib,
11798 					    ipv6ReasmPartDups);
11799 				} else {
11800 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11801 				}
11802 				start = offset;
11803 				if (!mp1->b_cont) {
11804 					/*
11805 					 * After trimming, this guy is now
11806 					 * hanging off the end.
11807 					 */
11808 					mp1->b_cont = mp;
11809 					ipf->ipf_tail_mp = mp;
11810 					if (!more) {
11811 						ipf->ipf_hole_cnt--;
11812 					}
11813 					break;
11814 				}
11815 			}
11816 			if (start >= IP_REASS_START(mp1->b_cont))
11817 				continue;
11818 			/* Fill a hole */
11819 			if (start > offset)
11820 				ipf->ipf_hole_cnt++;
11821 			mp->b_cont = mp1->b_cont;
11822 			mp1->b_cont = mp;
11823 			mp1 = mp->b_cont;
11824 			offset = IP_REASS_START(mp1);
11825 			if (end >= offset) {
11826 				ipf->ipf_hole_cnt--;
11827 				/* Check for overlap. */
11828 				while (end > offset) {
11829 					if (end < IP_REASS_END(mp1)) {
11830 						mp->b_wptr -= end - offset;
11831 						IP_REASS_SET_END(mp, offset);
11832 						/*
11833 						 * TODO we might bump
11834 						 * this up twice if there is
11835 						 * overlap at both ends.
11836 						 */
11837 						if (ill->ill_isv6) {
11838 							BUMP_MIB(
11839 							    ill->ill_ip6_mib,
11840 							    ipv6ReasmPartDups);
11841 						} else {
11842 							BUMP_MIB(&ip_mib,
11843 							    ipReasmPartDups);
11844 						}
11845 						break;
11846 					}
11847 					/* Did we cover another hole? */
11848 					if ((mp1->b_cont &&
11849 					    IP_REASS_END(mp1)
11850 					    != IP_REASS_START(mp1->b_cont) &&
11851 					    end >=
11852 					    IP_REASS_START(mp1->b_cont)) ||
11853 					    (!ipf->ipf_last_frag_seen &&
11854 					    !more)) {
11855 						ipf->ipf_hole_cnt--;
11856 					}
11857 					/* Clip out mp1. */
11858 					if ((mp->b_cont = mp1->b_cont) ==
11859 					    NULL) {
11860 						/*
11861 						 * After clipping out mp1,
11862 						 * this guy is now hanging
11863 						 * off the end.
11864 						 */
11865 						ipf->ipf_tail_mp = mp;
11866 					}
11867 					IP_REASS_SET_START(mp1, 0);
11868 					IP_REASS_SET_END(mp1, 0);
11869 					/* Subtract byte count */
11870 					ipf->ipf_count -=
11871 					    mp1->b_datap->db_lim -
11872 					    mp1->b_datap->db_base;
11873 					freeb(mp1);
11874 					if (ill->ill_isv6) {
11875 						BUMP_MIB(ill->ill_ip6_mib,
11876 						    ipv6ReasmPartDups);
11877 					} else {
11878 						BUMP_MIB(&ip_mib,
11879 						    ipReasmPartDups);
11880 					}
11881 					mp1 = mp->b_cont;
11882 					if (!mp1)
11883 						break;
11884 					offset = IP_REASS_START(mp1);
11885 				}
11886 			}
11887 			break;
11888 		}
11889 	} while (start = end, mp = next_mp);
11890 
11891 	/* Fragment just processed could be the last one. Remember this fact */
11892 	if (!more)
11893 		ipf->ipf_last_frag_seen = B_TRUE;
11894 
11895 	/* Still got holes? */
11896 	if (ipf->ipf_hole_cnt)
11897 		return (IP_REASS_PARTIAL);
11898 	/* Clean up overloaded fields to avoid upstream disasters. */
11899 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11900 		IP_REASS_SET_START(mp1, 0);
11901 		IP_REASS_SET_END(mp1, 0);
11902 	}
11903 	return (IP_REASS_COMPLETE);
11904 }
11905 
11906 /*
11907  * ipsec processing for the fast path, used for input UDP Packets
11908  */
11909 static boolean_t
11910 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11911     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11912 {
11913 	uint32_t	ill_index;
11914 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11915 
11916 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11917 	/* The ill_index of the incoming ILL */
11918 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11919 
11920 	/* pass packet up to the transport */
11921 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11922 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11923 		    NULL, mctl_present);
11924 		if (*first_mpp == NULL) {
11925 			return (B_FALSE);
11926 		}
11927 	}
11928 
11929 	/* Initiate IPPF processing for fastpath UDP */
11930 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11931 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11932 		if (*mpp == NULL) {
11933 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11934 			    "deferred/dropped during IPPF processing\n"));
11935 			return (B_FALSE);
11936 		}
11937 	}
11938 	/*
11939 	 * We make the checks as below since we are in the fast path
11940 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11941 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11942 	 */
11943 	if (connp->conn_recvif || connp->conn_recvslla ||
11944 	    connp->conn_ipv6_recvpktinfo) {
11945 		if (connp->conn_recvif ||
11946 		    connp->conn_ipv6_recvpktinfo) {
11947 			in_flags = IPF_RECVIF;
11948 		}
11949 		if (connp->conn_recvslla) {
11950 			in_flags |= IPF_RECVSLLA;
11951 		}
11952 		/*
11953 		 * since in_flags are being set ill will be
11954 		 * referenced in ip_add_info, so it better not
11955 		 * be NULL.
11956 		 */
11957 		/*
11958 		 * the actual data will be contained in b_cont
11959 		 * upon successful return of the following call.
11960 		 * If the call fails then the original mblk is
11961 		 * returned.
11962 		 */
11963 		*mpp = ip_add_info(*mpp, ill, in_flags);
11964 	}
11965 
11966 	return (B_TRUE);
11967 }
11968 
11969 /*
11970  * Fragmentation reassembly.  Each ILL has a hash table for
11971  * queuing packets undergoing reassembly for all IPIFs
11972  * associated with the ILL.  The hash is based on the packet
11973  * IP ident field.  The ILL frag hash table was allocated
11974  * as a timer block at the time the ILL was created.  Whenever
11975  * there is anything on the reassembly queue, the timer will
11976  * be running.  Returns B_TRUE if successful else B_FALSE;
11977  * frees mp on failure.
11978  */
11979 static boolean_t
11980 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11981     uint32_t *cksum_val, uint16_t *cksum_flags)
11982 {
11983 	uint32_t	frag_offset_flags;
11984 	ill_t		*ill = (ill_t *)q->q_ptr;
11985 	mblk_t		*mp = *mpp;
11986 	mblk_t		*t_mp;
11987 	ipaddr_t	dst;
11988 	uint8_t		proto = ipha->ipha_protocol;
11989 	uint32_t	sum_val;
11990 	uint16_t	sum_flags;
11991 	ipf_t		*ipf;
11992 	ipf_t		**ipfp;
11993 	ipfb_t		*ipfb;
11994 	uint16_t	ident;
11995 	uint32_t	offset;
11996 	ipaddr_t	src;
11997 	uint_t		hdr_length;
11998 	uint32_t	end;
11999 	mblk_t		*mp1;
12000 	mblk_t		*tail_mp;
12001 	size_t		count;
12002 	size_t		msg_len;
12003 	uint8_t		ecn_info = 0;
12004 	uint32_t	packet_size;
12005 	boolean_t	pruned = B_FALSE;
12006 
12007 	if (cksum_val != NULL)
12008 		*cksum_val = 0;
12009 	if (cksum_flags != NULL)
12010 		*cksum_flags = 0;
12011 
12012 	/*
12013 	 * Drop the fragmented as early as possible, if
12014 	 * we don't have resource(s) to re-assemble.
12015 	 */
12016 	if (ip_reass_queue_bytes == 0) {
12017 		freemsg(mp);
12018 		return (B_FALSE);
12019 	}
12020 
12021 	/* Check for fragmentation offset; return if there's none */
12022 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12023 	    (IPH_MF | IPH_OFFSET)) == 0)
12024 		return (B_TRUE);
12025 
12026 	/*
12027 	 * We utilize hardware computed checksum info only for UDP since
12028 	 * IP fragmentation is a normal occurence for the protocol.  In
12029 	 * addition, checksum offload support for IP fragments carrying
12030 	 * UDP payload is commonly implemented across network adapters.
12031 	 */
12032 	ASSERT(ill != NULL);
12033 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12034 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12035 		mblk_t *mp1 = mp->b_cont;
12036 		int32_t len;
12037 
12038 		/* Record checksum information from the packet */
12039 		sum_val = (uint32_t)DB_CKSUM16(mp);
12040 		sum_flags = DB_CKSUMFLAGS(mp);
12041 
12042 		/* IP payload offset from beginning of mblk */
12043 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12044 
12045 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12046 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12047 		    offset >= DB_CKSUMSTART(mp) &&
12048 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12049 			uint32_t adj;
12050 			/*
12051 			 * Partial checksum has been calculated by hardware
12052 			 * and attached to the packet; in addition, any
12053 			 * prepended extraneous data is even byte aligned.
12054 			 * If any such data exists, we adjust the checksum;
12055 			 * this would also handle any postpended data.
12056 			 */
12057 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12058 			    mp, mp1, len, adj);
12059 
12060 			/* One's complement subtract extraneous checksum */
12061 			if (adj >= sum_val)
12062 				sum_val = ~(adj - sum_val) & 0xFFFF;
12063 			else
12064 				sum_val -= adj;
12065 		}
12066 	} else {
12067 		sum_val = 0;
12068 		sum_flags = 0;
12069 	}
12070 
12071 	/* Clear hardware checksumming flag */
12072 	DB_CKSUMFLAGS(mp) = 0;
12073 
12074 	ident = ipha->ipha_ident;
12075 	offset = (frag_offset_flags << 3) & 0xFFFF;
12076 	src = ipha->ipha_src;
12077 	dst = ipha->ipha_dst;
12078 	hdr_length = IPH_HDR_LENGTH(ipha);
12079 	end = ntohs(ipha->ipha_length) - hdr_length;
12080 
12081 	/* If end == 0 then we have a packet with no data, so just free it */
12082 	if (end == 0) {
12083 		freemsg(mp);
12084 		return (B_FALSE);
12085 	}
12086 
12087 	/* Record the ECN field info. */
12088 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12089 	if (offset != 0) {
12090 		/*
12091 		 * If this isn't the first piece, strip the header, and
12092 		 * add the offset to the end value.
12093 		 */
12094 		mp->b_rptr += hdr_length;
12095 		end += offset;
12096 	}
12097 
12098 	msg_len = MBLKSIZE(mp);
12099 	tail_mp = mp;
12100 	while (tail_mp->b_cont != NULL) {
12101 		tail_mp = tail_mp->b_cont;
12102 		msg_len += MBLKSIZE(tail_mp);
12103 	}
12104 
12105 	/* If the reassembly list for this ILL will get too big, prune it */
12106 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12107 	    ip_reass_queue_bytes) {
12108 		ill_frag_prune(ill,
12109 		    (ip_reass_queue_bytes < msg_len) ? 0 :
12110 		    (ip_reass_queue_bytes - msg_len));
12111 		pruned = B_TRUE;
12112 	}
12113 
12114 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12115 	mutex_enter(&ipfb->ipfb_lock);
12116 
12117 	ipfp = &ipfb->ipfb_ipf;
12118 	/* Try to find an existing fragment queue for this packet. */
12119 	for (;;) {
12120 		ipf = ipfp[0];
12121 		if (ipf != NULL) {
12122 			/*
12123 			 * It has to match on ident and src/dst address.
12124 			 */
12125 			if (ipf->ipf_ident == ident &&
12126 			    ipf->ipf_src == src &&
12127 			    ipf->ipf_dst == dst &&
12128 			    ipf->ipf_protocol == proto) {
12129 				/*
12130 				 * If we have received too many
12131 				 * duplicate fragments for this packet
12132 				 * free it.
12133 				 */
12134 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12135 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12136 					freemsg(mp);
12137 					mutex_exit(&ipfb->ipfb_lock);
12138 					return (B_FALSE);
12139 				}
12140 				/* Found it. */
12141 				break;
12142 			}
12143 			ipfp = &ipf->ipf_hash_next;
12144 			continue;
12145 		}
12146 
12147 		/*
12148 		 * If we pruned the list, do we want to store this new
12149 		 * fragment?. We apply an optimization here based on the
12150 		 * fact that most fragments will be received in order.
12151 		 * So if the offset of this incoming fragment is zero,
12152 		 * it is the first fragment of a new packet. We will
12153 		 * keep it.  Otherwise drop the fragment, as we have
12154 		 * probably pruned the packet already (since the
12155 		 * packet cannot be found).
12156 		 */
12157 		if (pruned && offset != 0) {
12158 			mutex_exit(&ipfb->ipfb_lock);
12159 			freemsg(mp);
12160 			return (B_FALSE);
12161 		}
12162 
12163 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12164 			/*
12165 			 * Too many fragmented packets in this hash
12166 			 * bucket. Free the oldest.
12167 			 */
12168 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12169 		}
12170 
12171 		/* New guy.  Allocate a frag message. */
12172 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12173 		if (mp1 == NULL) {
12174 			BUMP_MIB(&ip_mib, ipInDiscards);
12175 			freemsg(mp);
12176 reass_done:
12177 			mutex_exit(&ipfb->ipfb_lock);
12178 			return (B_FALSE);
12179 		}
12180 
12181 
12182 		BUMP_MIB(&ip_mib, ipReasmReqds);
12183 		mp1->b_cont = mp;
12184 
12185 		/* Initialize the fragment header. */
12186 		ipf = (ipf_t *)mp1->b_rptr;
12187 		ipf->ipf_mp = mp1;
12188 		ipf->ipf_ptphn = ipfp;
12189 		ipfp[0] = ipf;
12190 		ipf->ipf_hash_next = NULL;
12191 		ipf->ipf_ident = ident;
12192 		ipf->ipf_protocol = proto;
12193 		ipf->ipf_src = src;
12194 		ipf->ipf_dst = dst;
12195 		ipf->ipf_nf_hdr_len = 0;
12196 		/* Record reassembly start time. */
12197 		ipf->ipf_timestamp = gethrestime_sec();
12198 		/* Record ipf generation and account for frag header */
12199 		ipf->ipf_gen = ill->ill_ipf_gen++;
12200 		ipf->ipf_count = MBLKSIZE(mp1);
12201 		ipf->ipf_last_frag_seen = B_FALSE;
12202 		ipf->ipf_ecn = ecn_info;
12203 		ipf->ipf_num_dups = 0;
12204 		ipfb->ipfb_frag_pkts++;
12205 		ipf->ipf_checksum = 0;
12206 		ipf->ipf_checksum_flags = 0;
12207 
12208 		/* Store checksum value in fragment header */
12209 		if (sum_flags != 0) {
12210 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12211 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12212 			ipf->ipf_checksum = sum_val;
12213 			ipf->ipf_checksum_flags = sum_flags;
12214 		}
12215 
12216 		/*
12217 		 * We handle reassembly two ways.  In the easy case,
12218 		 * where all the fragments show up in order, we do
12219 		 * minimal bookkeeping, and just clip new pieces on
12220 		 * the end.  If we ever see a hole, then we go off
12221 		 * to ip_reassemble which has to mark the pieces and
12222 		 * keep track of the number of holes, etc.  Obviously,
12223 		 * the point of having both mechanisms is so we can
12224 		 * handle the easy case as efficiently as possible.
12225 		 */
12226 		if (offset == 0) {
12227 			/* Easy case, in-order reassembly so far. */
12228 			ipf->ipf_count += msg_len;
12229 			ipf->ipf_tail_mp = tail_mp;
12230 			/*
12231 			 * Keep track of next expected offset in
12232 			 * ipf_end.
12233 			 */
12234 			ipf->ipf_end = end;
12235 			ipf->ipf_nf_hdr_len = hdr_length;
12236 		} else {
12237 			/* Hard case, hole at the beginning. */
12238 			ipf->ipf_tail_mp = NULL;
12239 			/*
12240 			 * ipf_end == 0 means that we have given up
12241 			 * on easy reassembly.
12242 			 */
12243 			ipf->ipf_end = 0;
12244 
12245 			/* Forget checksum offload from now on */
12246 			ipf->ipf_checksum_flags = 0;
12247 
12248 			/*
12249 			 * ipf_hole_cnt is set by ip_reassemble.
12250 			 * ipf_count is updated by ip_reassemble.
12251 			 * No need to check for return value here
12252 			 * as we don't expect reassembly to complete
12253 			 * or fail for the first fragment itself.
12254 			 */
12255 			(void) ip_reassemble(mp, ipf,
12256 			    (frag_offset_flags & IPH_OFFSET) << 3,
12257 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12258 		}
12259 		/* Update per ipfb and ill byte counts */
12260 		ipfb->ipfb_count += ipf->ipf_count;
12261 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12262 		ill->ill_frag_count += ipf->ipf_count;
12263 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12264 		/* If the frag timer wasn't already going, start it. */
12265 		mutex_enter(&ill->ill_lock);
12266 		ill_frag_timer_start(ill);
12267 		mutex_exit(&ill->ill_lock);
12268 		goto reass_done;
12269 	}
12270 
12271 	/*
12272 	 * If the packet's flag has changed (it could be coming up
12273 	 * from an interface different than the previous, therefore
12274 	 * possibly different checksum capability), then forget about
12275 	 * any stored checksum states.  Otherwise add the value to
12276 	 * the existing one stored in the fragment header.
12277 	 */
12278 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12279 		sum_val += ipf->ipf_checksum;
12280 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12281 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12282 		ipf->ipf_checksum = sum_val;
12283 	} else if (ipf->ipf_checksum_flags != 0) {
12284 		/* Forget checksum offload from now on */
12285 		ipf->ipf_checksum_flags = 0;
12286 	}
12287 
12288 	/*
12289 	 * We have a new piece of a datagram which is already being
12290 	 * reassembled.  Update the ECN info if all IP fragments
12291 	 * are ECN capable.  If there is one which is not, clear
12292 	 * all the info.  If there is at least one which has CE
12293 	 * code point, IP needs to report that up to transport.
12294 	 */
12295 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12296 		if (ecn_info == IPH_ECN_CE)
12297 			ipf->ipf_ecn = IPH_ECN_CE;
12298 	} else {
12299 		ipf->ipf_ecn = IPH_ECN_NECT;
12300 	}
12301 	if (offset && ipf->ipf_end == offset) {
12302 		/* The new fragment fits at the end */
12303 		ipf->ipf_tail_mp->b_cont = mp;
12304 		/* Update the byte count */
12305 		ipf->ipf_count += msg_len;
12306 		/* Update per ipfb and ill byte counts */
12307 		ipfb->ipfb_count += msg_len;
12308 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12309 		ill->ill_frag_count += msg_len;
12310 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12311 		if (frag_offset_flags & IPH_MF) {
12312 			/* More to come. */
12313 			ipf->ipf_end = end;
12314 			ipf->ipf_tail_mp = tail_mp;
12315 			goto reass_done;
12316 		}
12317 	} else {
12318 		/* Go do the hard cases. */
12319 		int ret;
12320 
12321 		if (offset == 0)
12322 			ipf->ipf_nf_hdr_len = hdr_length;
12323 
12324 		/* Save current byte count */
12325 		count = ipf->ipf_count;
12326 		ret = ip_reassemble(mp, ipf,
12327 		    (frag_offset_flags & IPH_OFFSET) << 3,
12328 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12329 		/* Count of bytes added and subtracted (freeb()ed) */
12330 		count = ipf->ipf_count - count;
12331 		if (count) {
12332 			/* Update per ipfb and ill byte counts */
12333 			ipfb->ipfb_count += count;
12334 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12335 			ill->ill_frag_count += count;
12336 			ASSERT(ill->ill_frag_count > 0);
12337 		}
12338 		if (ret == IP_REASS_PARTIAL) {
12339 			goto reass_done;
12340 		} else if (ret == IP_REASS_FAILED) {
12341 			/* Reassembly failed. Free up all resources */
12342 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12343 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12344 				IP_REASS_SET_START(t_mp, 0);
12345 				IP_REASS_SET_END(t_mp, 0);
12346 			}
12347 			freemsg(mp);
12348 			goto reass_done;
12349 		}
12350 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12351 	}
12352 	/*
12353 	 * We have completed reassembly.  Unhook the frag header from
12354 	 * the reassembly list.
12355 	 *
12356 	 * Before we free the frag header, record the ECN info
12357 	 * to report back to the transport.
12358 	 */
12359 	ecn_info = ipf->ipf_ecn;
12360 	BUMP_MIB(&ip_mib, ipReasmOKs);
12361 	ipfp = ipf->ipf_ptphn;
12362 
12363 	/* We need to supply these to caller */
12364 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12365 		sum_val = ipf->ipf_checksum;
12366 	else
12367 		sum_val = 0;
12368 
12369 	mp1 = ipf->ipf_mp;
12370 	count = ipf->ipf_count;
12371 	ipf = ipf->ipf_hash_next;
12372 	if (ipf != NULL)
12373 		ipf->ipf_ptphn = ipfp;
12374 	ipfp[0] = ipf;
12375 	ill->ill_frag_count -= count;
12376 	ASSERT(ipfb->ipfb_count >= count);
12377 	ipfb->ipfb_count -= count;
12378 	ipfb->ipfb_frag_pkts--;
12379 	mutex_exit(&ipfb->ipfb_lock);
12380 	/* Ditch the frag header. */
12381 	mp = mp1->b_cont;
12382 
12383 	freeb(mp1);
12384 
12385 	/* Restore original IP length in header. */
12386 	packet_size = (uint32_t)msgdsize(mp);
12387 	if (packet_size > IP_MAXPACKET) {
12388 		freemsg(mp);
12389 		BUMP_MIB(&ip_mib, ipInHdrErrors);
12390 		return (B_FALSE);
12391 	}
12392 
12393 	if (DB_REF(mp) > 1) {
12394 		mblk_t *mp2 = copymsg(mp);
12395 
12396 		freemsg(mp);
12397 		if (mp2 == NULL) {
12398 			BUMP_MIB(&ip_mib, ipInDiscards);
12399 			return (B_FALSE);
12400 		}
12401 		mp = mp2;
12402 	}
12403 	ipha = (ipha_t *)mp->b_rptr;
12404 
12405 	ipha->ipha_length = htons((uint16_t)packet_size);
12406 	/* We're now complete, zip the frag state */
12407 	ipha->ipha_fragment_offset_and_flags = 0;
12408 	/* Record the ECN info. */
12409 	ipha->ipha_type_of_service &= 0xFC;
12410 	ipha->ipha_type_of_service |= ecn_info;
12411 	*mpp = mp;
12412 
12413 	/* Reassembly is successful; return checksum information if needed */
12414 	if (cksum_val != NULL)
12415 		*cksum_val = sum_val;
12416 	if (cksum_flags != NULL)
12417 		*cksum_flags = sum_flags;
12418 
12419 	return (B_TRUE);
12420 }
12421 
12422 /*
12423  * Perform ip header check sum update local options.
12424  * return B_TRUE if all is well, else return B_FALSE and release
12425  * the mp. caller is responsible for decrementing ire ref cnt.
12426  */
12427 static boolean_t
12428 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12429 {
12430 	mblk_t		*first_mp;
12431 	boolean_t	mctl_present;
12432 	uint16_t	sum;
12433 
12434 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12435 	/*
12436 	 * Don't do the checksum if it has gone through AH/ESP
12437 	 * processing.
12438 	 */
12439 	if (!mctl_present) {
12440 		sum = ip_csum_hdr(ipha);
12441 		if (sum != 0) {
12442 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12443 			freemsg(first_mp);
12444 			return (B_FALSE);
12445 		}
12446 	}
12447 
12448 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12449 		if (mctl_present)
12450 			freeb(first_mp);
12451 		return (B_FALSE);
12452 	}
12453 
12454 	return (B_TRUE);
12455 }
12456 
12457 /*
12458  * All udp packet are delivered to the local host via this routine.
12459  */
12460 void
12461 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12462     ill_t *recv_ill)
12463 {
12464 	uint32_t	sum;
12465 	uint32_t	u1;
12466 	boolean_t	mctl_present;
12467 	conn_t		*connp;
12468 	mblk_t		*first_mp;
12469 	uint16_t	*up;
12470 	ill_t		*ill = (ill_t *)q->q_ptr;
12471 	uint16_t	reass_hck_flags = 0;
12472 
12473 #define	rptr    ((uchar_t *)ipha)
12474 
12475 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12476 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12477 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12478 
12479 	/*
12480 	 * FAST PATH for udp packets
12481 	 */
12482 
12483 	/* u1 is # words of IP options */
12484 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12485 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12486 
12487 	/* IP options present */
12488 	if (u1 != 0)
12489 		goto ipoptions;
12490 
12491 	/* Check the IP header checksum.  */
12492 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12493 		/* Clear the IP header h/w cksum flag */
12494 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12495 	} else {
12496 #define	uph	((uint16_t *)ipha)
12497 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12498 		    uph[6] + uph[7] + uph[8] + uph[9];
12499 #undef	uph
12500 		/* finish doing IP checksum */
12501 		sum = (sum & 0xFFFF) + (sum >> 16);
12502 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12503 		/*
12504 		 * Don't verify header checksum if this packet is coming
12505 		 * back from AH/ESP as we already did it.
12506 		 */
12507 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12508 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12509 			freemsg(first_mp);
12510 			return;
12511 		}
12512 	}
12513 
12514 	/*
12515 	 * Count for SNMP of inbound packets for ire.
12516 	 * if mctl is present this might be a secure packet and
12517 	 * has already been counted for in ip_proto_input().
12518 	 */
12519 	if (!mctl_present) {
12520 		UPDATE_IB_PKT_COUNT(ire);
12521 		ire->ire_last_used_time = lbolt;
12522 	}
12523 
12524 	/* packet part of fragmented IP packet? */
12525 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12526 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12527 		goto fragmented;
12528 	}
12529 
12530 	/* u1 = IP header length (20 bytes) */
12531 	u1 = IP_SIMPLE_HDR_LENGTH;
12532 
12533 	/* packet does not contain complete IP & UDP headers */
12534 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12535 		goto udppullup;
12536 
12537 	/* up points to UDP header */
12538 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12539 #define	iphs    ((uint16_t *)ipha)
12540 
12541 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12542 	if (up[3] != 0) {
12543 		mblk_t *mp1 = mp->b_cont;
12544 		boolean_t cksum_err;
12545 		uint16_t hck_flags = 0;
12546 
12547 		/* Pseudo-header checksum */
12548 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12549 		    iphs[9] + up[2];
12550 
12551 		/*
12552 		 * Revert to software checksum calculation if the interface
12553 		 * isn't capable of checksum offload or if IPsec is present.
12554 		 */
12555 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12556 			hck_flags = DB_CKSUMFLAGS(mp);
12557 
12558 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12559 			IP_STAT(ip_in_sw_cksum);
12560 
12561 		IP_CKSUM_RECV(hck_flags, u1,
12562 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12563 		    (int32_t)((uchar_t *)up - rptr),
12564 		    mp, mp1, cksum_err);
12565 
12566 		if (cksum_err) {
12567 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12568 
12569 			if (hck_flags & HCK_FULLCKSUM)
12570 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12571 			else if (hck_flags & HCK_PARTIALCKSUM)
12572 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12573 			else
12574 				IP_STAT(ip_udp_in_sw_cksum_err);
12575 
12576 			freemsg(first_mp);
12577 			return;
12578 		}
12579 	}
12580 
12581 	/* Non-fragmented broadcast or multicast packet? */
12582 	if (ire->ire_type == IRE_BROADCAST)
12583 		goto udpslowpath;
12584 
12585 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12586 	    ire->ire_zoneid)) != NULL) {
12587 		ASSERT(connp->conn_upq != NULL);
12588 		IP_STAT(ip_udp_fast_path);
12589 
12590 		if (CONN_UDP_FLOWCTLD(connp)) {
12591 			freemsg(mp);
12592 			BUMP_MIB(&ip_mib, udpInOverflows);
12593 		} else {
12594 			if (!mctl_present) {
12595 				BUMP_MIB(&ip_mib, ipInDelivers);
12596 			}
12597 			/*
12598 			 * mp and first_mp can change.
12599 			 */
12600 			if (ip_udp_check(q, connp, recv_ill,
12601 			    ipha, &mp, &first_mp, mctl_present)) {
12602 				/* Send it upstream */
12603 				CONN_UDP_RECV(connp, mp);
12604 			}
12605 		}
12606 		/*
12607 		 * freeb() cannot deal with null mblk being passed
12608 		 * in and first_mp can be set to null in the call
12609 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12610 		 */
12611 		if (mctl_present && first_mp != NULL) {
12612 			freeb(first_mp);
12613 		}
12614 		CONN_DEC_REF(connp);
12615 		return;
12616 	}
12617 
12618 	/*
12619 	 * if we got here we know the packet is not fragmented and
12620 	 * has no options. The classifier could not find a conn_t and
12621 	 * most likely its an icmp packet so send it through slow path.
12622 	 */
12623 
12624 	goto udpslowpath;
12625 
12626 ipoptions:
12627 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12628 		goto slow_done;
12629 	}
12630 
12631 	UPDATE_IB_PKT_COUNT(ire);
12632 	ire->ire_last_used_time = lbolt;
12633 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12634 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12635 fragmented:
12636 		/*
12637 		 * "sum" and "reass_hck_flags" are non-zero if the
12638 		 * reassembled packet has a valid hardware computed
12639 		 * checksum information associated with it.
12640 		 */
12641 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12642 			goto slow_done;
12643 		/*
12644 		 * Make sure that first_mp points back to mp as
12645 		 * the mp we came in with could have changed in
12646 		 * ip_rput_fragment().
12647 		 */
12648 		ASSERT(!mctl_present);
12649 		ipha = (ipha_t *)mp->b_rptr;
12650 		first_mp = mp;
12651 	}
12652 
12653 	/* Now we have a complete datagram, destined for this machine. */
12654 	u1 = IPH_HDR_LENGTH(ipha);
12655 	/* Pull up the UDP header, if necessary. */
12656 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12657 udppullup:
12658 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12659 			BUMP_MIB(&ip_mib, ipInDiscards);
12660 			freemsg(first_mp);
12661 			goto slow_done;
12662 		}
12663 		ipha = (ipha_t *)mp->b_rptr;
12664 	}
12665 
12666 	/*
12667 	 * Validate the checksum for the reassembled packet; for the
12668 	 * pullup case we calculate the payload checksum in software.
12669 	 */
12670 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12671 	if (up[3] != 0) {
12672 		boolean_t cksum_err;
12673 
12674 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12675 			IP_STAT(ip_in_sw_cksum);
12676 
12677 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12678 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12679 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12680 		    iphs[9] + up[2], sum, cksum_err);
12681 
12682 		if (cksum_err) {
12683 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12684 
12685 			if (reass_hck_flags & HCK_FULLCKSUM)
12686 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12687 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12688 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12689 			else
12690 				IP_STAT(ip_udp_in_sw_cksum_err);
12691 
12692 			freemsg(first_mp);
12693 			goto slow_done;
12694 		}
12695 	}
12696 udpslowpath:
12697 
12698 	/* Clear hardware checksum flag to be safe */
12699 	DB_CKSUMFLAGS(mp) = 0;
12700 
12701 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12702 	    (ire->ire_type == IRE_BROADCAST),
12703 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12704 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12705 
12706 slow_done:
12707 	IP_STAT(ip_udp_slow_path);
12708 	return;
12709 
12710 #undef  iphs
12711 #undef  rptr
12712 }
12713 
12714 /* ARGSUSED */
12715 static mblk_t *
12716 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12717     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12718     ill_rx_ring_t *ill_ring)
12719 {
12720 	conn_t		*connp;
12721 	uint32_t	sum;
12722 	uint32_t	u1;
12723 	uint16_t	*up;
12724 	int		offset;
12725 	ssize_t		len;
12726 	mblk_t		*mp1;
12727 	boolean_t	syn_present = B_FALSE;
12728 	tcph_t		*tcph;
12729 	uint_t		ip_hdr_len;
12730 	ill_t		*ill = (ill_t *)q->q_ptr;
12731 	zoneid_t	zoneid = ire->ire_zoneid;
12732 	boolean_t	cksum_err;
12733 	uint16_t	hck_flags = 0;
12734 
12735 #define	rptr	((uchar_t *)ipha)
12736 
12737 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12738 
12739 	/*
12740 	 * FAST PATH for tcp packets
12741 	 */
12742 
12743 	/* u1 is # words of IP options */
12744 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12745 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12746 
12747 	/* IP options present */
12748 	if (u1) {
12749 		goto ipoptions;
12750 	} else {
12751 		/* Check the IP header checksum.  */
12752 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12753 			/* Clear the IP header h/w cksum flag */
12754 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12755 		} else {
12756 #define	uph	((uint16_t *)ipha)
12757 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12758 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12759 #undef	uph
12760 			/* finish doing IP checksum */
12761 			sum = (sum & 0xFFFF) + (sum >> 16);
12762 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12763 			/*
12764 			 * Don't verify header checksum if this packet
12765 			 * is coming back from AH/ESP as we already did it.
12766 			 */
12767 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12768 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12769 				goto error;
12770 			}
12771 		}
12772 	}
12773 
12774 	if (!mctl_present) {
12775 		UPDATE_IB_PKT_COUNT(ire);
12776 		ire->ire_last_used_time = lbolt;
12777 	}
12778 
12779 	/* packet part of fragmented IP packet? */
12780 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12781 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12782 		goto fragmented;
12783 	}
12784 
12785 	/* u1 = IP header length (20 bytes) */
12786 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12787 
12788 	/* does packet contain IP+TCP headers? */
12789 	len = mp->b_wptr - rptr;
12790 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12791 		IP_STAT(ip_tcppullup);
12792 		goto tcppullup;
12793 	}
12794 
12795 	/* TCP options present? */
12796 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12797 
12798 	/*
12799 	 * If options need to be pulled up, then goto tcpoptions.
12800 	 * otherwise we are still in the fast path
12801 	 */
12802 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12803 		IP_STAT(ip_tcpoptions);
12804 		goto tcpoptions;
12805 	}
12806 
12807 	/* multiple mblks of tcp data? */
12808 	if ((mp1 = mp->b_cont) != NULL) {
12809 		/* more then two? */
12810 		if (mp1->b_cont != NULL) {
12811 			IP_STAT(ip_multipkttcp);
12812 			goto multipkttcp;
12813 		}
12814 		len += mp1->b_wptr - mp1->b_rptr;
12815 	}
12816 
12817 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12818 
12819 	/* part of pseudo checksum */
12820 
12821 	/* TCP datagram length */
12822 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12823 
12824 #define	iphs    ((uint16_t *)ipha)
12825 
12826 #ifdef	_BIG_ENDIAN
12827 	u1 += IPPROTO_TCP;
12828 #else
12829 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12830 #endif
12831 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12832 
12833 	/*
12834 	 * Revert to software checksum calculation if the interface
12835 	 * isn't capable of checksum offload or if IPsec is present.
12836 	 */
12837 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12838 		hck_flags = DB_CKSUMFLAGS(mp);
12839 
12840 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12841 		IP_STAT(ip_in_sw_cksum);
12842 
12843 	IP_CKSUM_RECV(hck_flags, u1,
12844 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12845 	    (int32_t)((uchar_t *)up - rptr),
12846 	    mp, mp1, cksum_err);
12847 
12848 	if (cksum_err) {
12849 		BUMP_MIB(&ip_mib, tcpInErrs);
12850 
12851 		if (hck_flags & HCK_FULLCKSUM)
12852 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12853 		else if (hck_flags & HCK_PARTIALCKSUM)
12854 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12855 		else
12856 			IP_STAT(ip_tcp_in_sw_cksum_err);
12857 
12858 		goto error;
12859 	}
12860 
12861 try_again:
12862 
12863 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12864 	    NULL) {
12865 		/* Send the TH_RST */
12866 		goto no_conn;
12867 	}
12868 
12869 	/*
12870 	 * TCP FAST PATH for AF_INET socket.
12871 	 *
12872 	 * TCP fast path to avoid extra work. An AF_INET socket type
12873 	 * does not have facility to receive extra information via
12874 	 * ip_process or ip_add_info. Also, when the connection was
12875 	 * established, we made a check if this connection is impacted
12876 	 * by any global IPSec policy or per connection policy (a
12877 	 * policy that comes in effect later will not apply to this
12878 	 * connection). Since all this can be determined at the
12879 	 * connection establishment time, a quick check of flags
12880 	 * can avoid extra work.
12881 	 */
12882 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12883 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12884 		ASSERT(first_mp == mp);
12885 		SET_SQUEUE(mp, tcp_rput_data, connp);
12886 		return (mp);
12887 	}
12888 
12889 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12890 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12891 		if (IPCL_IS_TCP(connp)) {
12892 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12893 			DB_CKSUMSTART(mp) =
12894 			    (intptr_t)ip_squeue_get(ill_ring);
12895 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12896 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12897 				SET_SQUEUE(mp, connp->conn_recv, connp);
12898 				return (mp);
12899 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12900 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12901 				ip_squeue_enter_unbound++;
12902 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12903 				    connp);
12904 				return (mp);
12905 			}
12906 			syn_present = B_TRUE;
12907 		}
12908 
12909 	}
12910 
12911 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12912 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12913 
12914 		/* No need to send this packet to TCP */
12915 		if ((flags & TH_RST) || (flags & TH_URG)) {
12916 			CONN_DEC_REF(connp);
12917 			freemsg(first_mp);
12918 			return (NULL);
12919 		}
12920 		if (flags & TH_ACK) {
12921 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
12922 			CONN_DEC_REF(connp);
12923 			return (NULL);
12924 		}
12925 
12926 		CONN_DEC_REF(connp);
12927 		freemsg(first_mp);
12928 		return (NULL);
12929 	}
12930 
12931 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12932 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12933 		    ipha, NULL, mctl_present);
12934 		if (first_mp == NULL) {
12935 			CONN_DEC_REF(connp);
12936 			return (NULL);
12937 		}
12938 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12939 			ASSERT(syn_present);
12940 			if (mctl_present) {
12941 				ASSERT(first_mp != mp);
12942 				first_mp->b_datap->db_struioflag |=
12943 				    STRUIO_POLICY;
12944 			} else {
12945 				ASSERT(first_mp == mp);
12946 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12947 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12948 			}
12949 		} else {
12950 			/*
12951 			 * Discard first_mp early since we're dealing with a
12952 			 * fully-connected conn_t and tcp doesn't do policy in
12953 			 * this case.
12954 			 */
12955 			if (mctl_present) {
12956 				freeb(first_mp);
12957 				mctl_present = B_FALSE;
12958 			}
12959 			first_mp = mp;
12960 		}
12961 	}
12962 
12963 	/* Initiate IPPF processing for fastpath */
12964 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12965 		uint32_t	ill_index;
12966 
12967 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12968 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12969 		if (mp == NULL) {
12970 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12971 			    "deferred/dropped during IPPF processing\n"));
12972 			CONN_DEC_REF(connp);
12973 			if (mctl_present)
12974 				freeb(first_mp);
12975 			return (NULL);
12976 		} else if (mctl_present) {
12977 			/*
12978 			 * ip_process might return a new mp.
12979 			 */
12980 			ASSERT(first_mp != mp);
12981 			first_mp->b_cont = mp;
12982 		} else {
12983 			first_mp = mp;
12984 		}
12985 
12986 	}
12987 
12988 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12989 		mp = ip_add_info(mp, recv_ill, flags);
12990 		if (mp == NULL) {
12991 			CONN_DEC_REF(connp);
12992 			if (mctl_present)
12993 				freeb(first_mp);
12994 			return (NULL);
12995 		} else if (mctl_present) {
12996 			/*
12997 			 * ip_add_info might return a new mp.
12998 			 */
12999 			ASSERT(first_mp != mp);
13000 			first_mp->b_cont = mp;
13001 		} else {
13002 			first_mp = mp;
13003 		}
13004 	}
13005 
13006 	if (IPCL_IS_TCP(connp)) {
13007 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13008 		return (first_mp);
13009 	} else {
13010 		putnext(connp->conn_rq, first_mp);
13011 		CONN_DEC_REF(connp);
13012 		return (NULL);
13013 	}
13014 
13015 no_conn:
13016 	/* Initiate IPPf processing, if needed. */
13017 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13018 		uint32_t ill_index;
13019 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13020 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13021 		if (first_mp == NULL) {
13022 			return (NULL);
13023 		}
13024 	}
13025 	BUMP_MIB(&ip_mib, ipInDelivers);
13026 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid);
13027 	return (NULL);
13028 ipoptions:
13029 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
13030 		goto slow_done;
13031 	}
13032 
13033 	UPDATE_IB_PKT_COUNT(ire);
13034 	ire->ire_last_used_time = lbolt;
13035 
13036 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13037 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13038 fragmented:
13039 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13040 			if (mctl_present)
13041 				freeb(first_mp);
13042 			goto slow_done;
13043 		}
13044 		/*
13045 		 * Make sure that first_mp points back to mp as
13046 		 * the mp we came in with could have changed in
13047 		 * ip_rput_fragment().
13048 		 */
13049 		ASSERT(!mctl_present);
13050 		ipha = (ipha_t *)mp->b_rptr;
13051 		first_mp = mp;
13052 	}
13053 
13054 	/* Now we have a complete datagram, destined for this machine. */
13055 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13056 
13057 	len = mp->b_wptr - mp->b_rptr;
13058 	/* Pull up a minimal TCP header, if necessary. */
13059 	if (len < (u1 + 20)) {
13060 tcppullup:
13061 		if (!pullupmsg(mp, u1 + 20)) {
13062 			BUMP_MIB(&ip_mib, ipInDiscards);
13063 			goto error;
13064 		}
13065 		ipha = (ipha_t *)mp->b_rptr;
13066 		len = mp->b_wptr - mp->b_rptr;
13067 	}
13068 
13069 	/*
13070 	 * Extract the offset field from the TCP header.  As usual, we
13071 	 * try to help the compiler more than the reader.
13072 	 */
13073 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13074 	if (offset != 5) {
13075 tcpoptions:
13076 		if (offset < 5) {
13077 			BUMP_MIB(&ip_mib, ipInDiscards);
13078 			goto error;
13079 		}
13080 		/*
13081 		 * There must be TCP options.
13082 		 * Make sure we can grab them.
13083 		 */
13084 		offset <<= 2;
13085 		offset += u1;
13086 		if (len < offset) {
13087 			if (!pullupmsg(mp, offset)) {
13088 				BUMP_MIB(&ip_mib, ipInDiscards);
13089 				goto error;
13090 			}
13091 			ipha = (ipha_t *)mp->b_rptr;
13092 			len = mp->b_wptr - rptr;
13093 		}
13094 	}
13095 
13096 	/* Get the total packet length in len, including headers. */
13097 	if (mp->b_cont) {
13098 multipkttcp:
13099 		len = msgdsize(mp);
13100 	}
13101 
13102 	/*
13103 	 * Check the TCP checksum by pulling together the pseudo-
13104 	 * header checksum, and passing it to ip_csum to be added in
13105 	 * with the TCP datagram.
13106 	 *
13107 	 * Since we are not using the hwcksum if available we must
13108 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13109 	 * If either of these fails along the way the mblk is freed.
13110 	 * If this logic ever changes and mblk is reused to say send
13111 	 * ICMP's back, then this flag may need to be cleared in
13112 	 * other places as well.
13113 	 */
13114 	DB_CKSUMFLAGS(mp) = 0;
13115 
13116 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13117 
13118 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13119 #ifdef	_BIG_ENDIAN
13120 	u1 += IPPROTO_TCP;
13121 #else
13122 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13123 #endif
13124 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13125 	/*
13126 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13127 	 */
13128 	IP_STAT(ip_in_sw_cksum);
13129 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13130 		BUMP_MIB(&ip_mib, tcpInErrs);
13131 		goto error;
13132 	}
13133 
13134 	IP_STAT(ip_tcp_slow_path);
13135 	goto try_again;
13136 #undef  iphs
13137 #undef  rptr
13138 
13139 error:
13140 	freemsg(first_mp);
13141 slow_done:
13142 	return (NULL);
13143 }
13144 
13145 /* ARGSUSED */
13146 static void
13147 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13148     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13149 {
13150 	conn_t		*connp;
13151 	uint32_t	sum;
13152 	uint32_t	u1;
13153 	ssize_t		len;
13154 	sctp_hdr_t	*sctph;
13155 	zoneid_t	zoneid = ire->ire_zoneid;
13156 	uint32_t	pktsum;
13157 	uint32_t	calcsum;
13158 	uint32_t	ports;
13159 	uint_t		ipif_seqid;
13160 	in6_addr_t	map_src, map_dst;
13161 	ill_t		*ill = (ill_t *)q->q_ptr;
13162 
13163 #define	rptr	((uchar_t *)ipha)
13164 
13165 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13166 
13167 	/* u1 is # words of IP options */
13168 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13169 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13170 
13171 	/* IP options present */
13172 	if (u1 > 0) {
13173 		goto ipoptions;
13174 	} else {
13175 		/* Check the IP header checksum.  */
13176 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13177 #define	uph	((uint16_t *)ipha)
13178 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13179 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13180 #undef	uph
13181 			/* finish doing IP checksum */
13182 			sum = (sum & 0xFFFF) + (sum >> 16);
13183 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13184 			/*
13185 			 * Don't verify header checksum if this packet
13186 			 * is coming back from AH/ESP as we already did it.
13187 			 */
13188 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13189 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13190 				goto error;
13191 			}
13192 		}
13193 		/*
13194 		 * Since there is no SCTP h/w cksum support yet, just
13195 		 * clear the flag.
13196 		 */
13197 		DB_CKSUMFLAGS(mp) = 0;
13198 	}
13199 
13200 	/*
13201 	 * Don't verify header checksum if this packet is coming
13202 	 * back from AH/ESP as we already did it.
13203 	 */
13204 	if (!mctl_present) {
13205 		UPDATE_IB_PKT_COUNT(ire);
13206 		ire->ire_last_used_time = lbolt;
13207 	}
13208 
13209 	/* packet part of fragmented IP packet? */
13210 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13211 	if (u1 & (IPH_MF | IPH_OFFSET))
13212 		goto fragmented;
13213 
13214 	/* u1 = IP header length (20 bytes) */
13215 	u1 = IP_SIMPLE_HDR_LENGTH;
13216 
13217 find_sctp_client:
13218 	/* Pullup if we don't have the sctp common header. */
13219 	len = MBLKL(mp);
13220 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13221 		if (mp->b_cont == NULL ||
13222 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13223 			BUMP_MIB(&ip_mib, ipInDiscards);
13224 			goto error;
13225 		}
13226 		ipha = (ipha_t *)mp->b_rptr;
13227 		len = MBLKL(mp);
13228 	}
13229 
13230 	sctph = (sctp_hdr_t *)(rptr + u1);
13231 #ifdef	DEBUG
13232 	if (!skip_sctp_cksum) {
13233 #endif
13234 		pktsum = sctph->sh_chksum;
13235 		sctph->sh_chksum = 0;
13236 		calcsum = sctp_cksum(mp, u1);
13237 		if (calcsum != pktsum) {
13238 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13239 			goto error;
13240 		}
13241 		sctph->sh_chksum = pktsum;
13242 #ifdef	DEBUG	/* skip_sctp_cksum */
13243 	}
13244 #endif
13245 	/* get the ports */
13246 	ports = *(uint32_t *)&sctph->sh_sport;
13247 
13248 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13249 	IRE_REFRELE(ire);
13250 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13251 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13252 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13253 	    mp)) == NULL) {
13254 		/* Check for raw socket or OOTB handling */
13255 		goto no_conn;
13256 	}
13257 
13258 	/* Found a client; up it goes */
13259 	BUMP_MIB(&ip_mib, ipInDelivers);
13260 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13261 	return;
13262 
13263 no_conn:
13264 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13265 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13266 	return;
13267 
13268 ipoptions:
13269 	DB_CKSUMFLAGS(mp) = 0;
13270 	if (!ip_options_cksum(q, first_mp, ipha, ire))
13271 		goto slow_done;
13272 
13273 	UPDATE_IB_PKT_COUNT(ire);
13274 	ire->ire_last_used_time = lbolt;
13275 
13276 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13277 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13278 fragmented:
13279 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13280 			goto slow_done;
13281 		/*
13282 		 * Make sure that first_mp points back to mp as
13283 		 * the mp we came in with could have changed in
13284 		 * ip_rput_fragment().
13285 		 */
13286 		ASSERT(!mctl_present);
13287 		ipha = (ipha_t *)mp->b_rptr;
13288 		first_mp = mp;
13289 	}
13290 
13291 	/* Now we have a complete datagram, destined for this machine. */
13292 	u1 = IPH_HDR_LENGTH(ipha);
13293 	goto find_sctp_client;
13294 #undef  iphs
13295 #undef  rptr
13296 
13297 error:
13298 	freemsg(first_mp);
13299 slow_done:
13300 	IRE_REFRELE(ire);
13301 }
13302 
13303 #define	VER_BITS	0xF0
13304 #define	VERSION_6	0x60
13305 
13306 static boolean_t
13307 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
13308     ipaddr_t *dstp)
13309 {
13310 	uint_t	opt_len;
13311 	ipha_t *ipha;
13312 	ssize_t len;
13313 	uint_t	pkt_len;
13314 
13315 	IP_STAT(ip_ipoptions);
13316 	ipha = *iphapp;
13317 
13318 #define	rptr    ((uchar_t *)ipha)
13319 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13320 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13321 		BUMP_MIB(&ip_mib, ipInIPv6);
13322 		freemsg(mp);
13323 		return (B_FALSE);
13324 	}
13325 
13326 	/* multiple mblk or too short */
13327 	pkt_len = ntohs(ipha->ipha_length);
13328 
13329 	/* Get the number of words of IP options in the IP header. */
13330 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13331 	if (opt_len) {
13332 		/* IP Options present!  Validate and process. */
13333 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13334 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13335 			goto done;
13336 		}
13337 		/*
13338 		 * Recompute complete header length and make sure we
13339 		 * have access to all of it.
13340 		 */
13341 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13342 		if (len > (mp->b_wptr - rptr)) {
13343 			if (len > pkt_len) {
13344 				BUMP_MIB(&ip_mib, ipInHdrErrors);
13345 				goto done;
13346 			}
13347 			if (!pullupmsg(mp, len)) {
13348 				BUMP_MIB(&ip_mib, ipInDiscards);
13349 				goto done;
13350 			}
13351 			ipha = (ipha_t *)mp->b_rptr;
13352 		}
13353 		/*
13354 		 * Go off to ip_rput_options which returns the next hop
13355 		 * destination address, which may have been affected
13356 		 * by source routing.
13357 		 */
13358 		IP_STAT(ip_opt);
13359 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13360 			return (B_FALSE);
13361 		}
13362 	}
13363 	*iphapp = ipha;
13364 	return (B_TRUE);
13365 done:
13366 	/* clear b_prev - used by ip_mroute_decap */
13367 	mp->b_prev = NULL;
13368 	freemsg(mp);
13369 	return (B_FALSE);
13370 #undef  rptr
13371 }
13372 
13373 /*
13374  * Deal with the fact that there is no ire for the destination.
13375  * The incoming ill (in_ill) is passed in to ip_newroute only
13376  * in the case of packets coming from mobile ip forward tunnel.
13377  * It must be null otherwise.
13378  */
13379 static ire_t *
13380 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13381     ipaddr_t dst)
13382 {
13383 	ipha_t	*ipha;
13384 	ill_t	*ill;
13385 	ire_t	*ire;
13386 	boolean_t	check_multirt = B_FALSE;
13387 
13388 	ipha = (ipha_t *)mp->b_rptr;
13389 	ill = (ill_t *)q->q_ptr;
13390 
13391 	ASSERT(ill != NULL);
13392 	/*
13393 	 * No IRE for this destination, so it can't be for us.
13394 	 * Unless we are forwarding, drop the packet.
13395 	 * We have to let source routed packets through
13396 	 * since we don't yet know if they are 'ping -l'
13397 	 * packets i.e. if they will go out over the
13398 	 * same interface as they came in on.
13399 	 */
13400 	if (ll_multicast) {
13401 		freemsg(mp);
13402 		return (NULL);
13403 	}
13404 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13405 		BUMP_MIB(&ip_mib, ipForwProhibits);
13406 		freemsg(mp);
13407 		return (NULL);
13408 	}
13409 
13410 	/*
13411 	 * Mark this packet as having originated externally.
13412 	 *
13413 	 * For non-forwarding code path, ire_send later double
13414 	 * checks this interface to see if it is still exists
13415 	 * post-ARP resolution.
13416 	 *
13417 	 * Also, IPQOS uses this to differentiate between
13418 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13419 	 * QOS packet processing in ip_wput_attach_llhdr().
13420 	 * The QoS module can mark the b_band for a fastpath message
13421 	 * or the dl_priority field in a unitdata_req header for
13422 	 * CoS marking. This info can only be found in
13423 	 * ip_wput_attach_llhdr().
13424 	 */
13425 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13426 	/*
13427 	 * Clear the indication that this may have a hardware checksum
13428 	 * as we are not using it
13429 	 */
13430 	DB_CKSUMFLAGS(mp) = 0;
13431 
13432 	if (in_ill != NULL) {
13433 		/*
13434 		 * Now hand the packet to ip_newroute.
13435 		 */
13436 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13437 		return (NULL);
13438 	}
13439 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13440 	    MBLK_GETLABEL(mp));
13441 
13442 	if (ire == NULL && check_multirt) {
13443 		/* Let ip_newroute handle CGTP  */
13444 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13445 		return (NULL);
13446 	}
13447 
13448 	if (ire != NULL)
13449 		return (ire);
13450 
13451 	mp->b_prev = mp->b_next = 0;
13452 	/* send icmp unreachable */
13453 	q = WR(q);
13454 	/* Sent by forwarding path, and router is global zone */
13455 	if (ip_source_routed(ipha)) {
13456 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13457 		    GLOBAL_ZONEID);
13458 	} else {
13459 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13460 	}
13461 
13462 	return (NULL);
13463 
13464 }
13465 
13466 /*
13467  * check ip header length and align it.
13468  */
13469 static boolean_t
13470 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13471 {
13472 	ssize_t len;
13473 	ill_t *ill;
13474 	ipha_t	*ipha;
13475 
13476 	len = MBLKL(mp);
13477 
13478 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13479 		if (!OK_32PTR(mp->b_rptr))
13480 			IP_STAT(ip_notaligned1);
13481 		else
13482 			IP_STAT(ip_notaligned2);
13483 		/* Guard against bogus device drivers */
13484 		if (len < 0) {
13485 			/* clear b_prev - used by ip_mroute_decap */
13486 			mp->b_prev = NULL;
13487 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13488 			freemsg(mp);
13489 			return (B_FALSE);
13490 		}
13491 
13492 		if (ip_rput_pullups++ == 0) {
13493 			ill = (ill_t *)q->q_ptr;
13494 			ipha = (ipha_t *)mp->b_rptr;
13495 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13496 			    "ip_check_and_align_header: %s forced us to "
13497 			    " pullup pkt, hdr len %ld, hdr addr %p",
13498 			    ill->ill_name, len, ipha);
13499 		}
13500 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13501 			/* clear b_prev - used by ip_mroute_decap */
13502 			mp->b_prev = NULL;
13503 			BUMP_MIB(&ip_mib, ipInDiscards);
13504 			freemsg(mp);
13505 			return (B_FALSE);
13506 		}
13507 	}
13508 	return (B_TRUE);
13509 }
13510 
13511 static boolean_t
13512 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13513 {
13514 	ill_group_t	*ill_group;
13515 	ill_group_t	*ire_group;
13516 	queue_t 	*q;
13517 	ill_t		*ire_ill;
13518 	uint_t		ill_ifindex;
13519 
13520 	q = *qp;
13521 	/*
13522 	 * We need to check to make sure the packet came in
13523 	 * on the queue associated with the destination IRE.
13524 	 * Note that for multicast packets and broadcast packets sent to
13525 	 * a broadcast address which is shared between multiple interfaces
13526 	 * we should not do this since we just got a random broadcast ire.
13527 	 */
13528 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13529 		boolean_t check_multi = B_TRUE;
13530 
13531 		/*
13532 		 * This packet came in on an interface other than the
13533 		 * one associated with the destination address.
13534 		 * "Gateway" it to the appropriate interface here.
13535 		 * As long as the ills belong to the same group,
13536 		 * we don't consider them to arriving on the wrong
13537 		 * interface. Thus, when the switch is doing inbound
13538 		 * load spreading, we won't drop packets when we
13539 		 * are doing strict multihoming checks. Note, the
13540 		 * same holds true for 'usesrc groups' where the
13541 		 * destination address may belong to another interface
13542 		 * to allow multipathing to happen
13543 		 */
13544 		ill_group = ill->ill_group;
13545 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13546 		ill_ifindex = ill->ill_usesrc_ifindex;
13547 		ire_group = ire_ill->ill_group;
13548 
13549 		/*
13550 		 * If it's part of the same IPMP group, or if it's a legal
13551 		 * address on the 'usesrc' interface, then bypass strict
13552 		 * checks.
13553 		 */
13554 		if (ill_group != NULL && ill_group == ire_group) {
13555 			check_multi = B_FALSE;
13556 		} else if (ill_ifindex != 0 &&
13557 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13558 			check_multi = B_FALSE;
13559 		}
13560 
13561 		if (check_multi &&
13562 		    ip_strict_dst_multihoming &&
13563 		    ((ill->ill_flags &
13564 		    ire->ire_ipif->ipif_ill->ill_flags &
13565 		    ILLF_ROUTER) == 0)) {
13566 			/* Drop packet */
13567 			BUMP_MIB(&ip_mib, ipForwProhibits);
13568 			freemsg(mp);
13569 			return (B_TRUE);
13570 		}
13571 
13572 		/*
13573 		 * Change the queue (for non-virtual destination network
13574 		 * interfaces) and ip_rput_local will be called with the right
13575 		 * queue
13576 		 */
13577 		q = ire->ire_rfq;
13578 	}
13579 	/* Must be broadcast.  We'll take it. */
13580 	*qp = q;
13581 	return (B_FALSE);
13582 }
13583 
13584 ire_t *
13585 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13586 {
13587 	ipha_t	*ipha;
13588 	ipaddr_t ip_dst, ip_src;
13589 	ire_t	*src_ire = NULL;
13590 	ill_t	*stq_ill;
13591 	uint_t	hlen;
13592 	uint32_t sum;
13593 	queue_t	*dev_q;
13594 	boolean_t check_multirt = B_FALSE;
13595 
13596 
13597 	ipha = (ipha_t *)mp->b_rptr;
13598 
13599 	/*
13600 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13601 	 * The loopback address check for both src and dst has already
13602 	 * been checked in ip_input
13603 	 */
13604 	ip_dst = ntohl(dst);
13605 	ip_src = ntohl(ipha->ipha_src);
13606 
13607 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13608 	    IN_CLASSD(ip_src)) {
13609 		BUMP_MIB(&ip_mib, ipForwProhibits);
13610 		goto drop;
13611 	}
13612 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13613 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13614 
13615 	if (src_ire != NULL) {
13616 		BUMP_MIB(&ip_mib, ipForwProhibits);
13617 		goto drop;
13618 	}
13619 
13620 	/* No ire cache of nexthop. So first create one  */
13621 	if (ire == NULL) {
13622 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13623 		/*
13624 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13625 		 * is not set. So upon return from ire_forward
13626 		 * check_multirt should remain as false.
13627 		 */
13628 		ASSERT(!check_multirt);
13629 		if (ire == NULL) {
13630 			BUMP_MIB(&ip_mib, ipInDiscards);
13631 			mp->b_prev = mp->b_next = 0;
13632 			/* send icmp unreachable */
13633 			/* Sent by forwarding path, and router is global zone */
13634 			if (ip_source_routed(ipha)) {
13635 				icmp_unreachable(ill->ill_wq, mp,
13636 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13637 			} else {
13638 				icmp_unreachable(ill->ill_wq, mp,
13639 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13640 			}
13641 			return (ire);
13642 		}
13643 	}
13644 
13645 	/*
13646 	 * Forwarding fastpath exception case:
13647 	 * If either of the follwoing case is true, we take
13648 	 * the slowpath
13649 	 *	o forwarding is not enabled
13650 	 *	o incoming and outgoing interface are the same, or the same
13651 	 *	  IPMP group
13652 	 *	o corresponding ire is in incomplete state
13653 	 *	o packet needs fragmentation
13654 	 *
13655 	 * The codeflow from here on is thus:
13656 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13657 	 */
13658 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13659 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13660 	    !(ill->ill_flags & ILLF_ROUTER) ||
13661 	    (ill == stq_ill) ||
13662 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13663 	    (ire->ire_nce == NULL) ||
13664 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13665 	    (ntohs(ipha->ipha_length) > ire->ire_max_frag) ||
13666 	    ipha->ipha_ttl <= 1) {
13667 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13668 		    ipha, ill, B_FALSE);
13669 		return (ire);
13670 	}
13671 
13672 	DTRACE_PROBE4(ip4__forwarding__start,
13673 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13674 
13675 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
13676 	    ill, stq_ill, ipha, mp, mp);
13677 
13678 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13679 
13680 	if (mp == NULL)
13681 		goto drop;
13682 
13683 	mp->b_datap->db_struioun.cksum.flags = 0;
13684 	/* Adjust the checksum to reflect the ttl decrement. */
13685 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13686 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13687 	ipha->ipha_ttl--;
13688 
13689 	dev_q = ire->ire_stq->q_next;
13690 	if ((dev_q->q_next != NULL ||
13691 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13692 		goto indiscard;
13693 	}
13694 
13695 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13696 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13697 
13698 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13699 		mblk_t *mpip = mp;
13700 
13701 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13702 		if (mp != NULL) {
13703 			DTRACE_PROBE4(ip4__physical__out__start,
13704 			    ill_t *, NULL, ill_t *, stq_ill,
13705 			    ipha_t *, ipha, mblk_t *, mp);
13706 			FW_HOOKS(ip4_physical_out_event,
13707 			    ipv4firewall_physical_out,
13708 			    NULL, stq_ill, ipha, mp, mpip);
13709 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13710 			    mp);
13711 			if (mp == NULL)
13712 				goto drop;
13713 
13714 			UPDATE_IB_PKT_COUNT(ire);
13715 			ire->ire_last_used_time = lbolt;
13716 			BUMP_MIB(&ip_mib, ipForwDatagrams);
13717 			putnext(ire->ire_stq, mp);
13718 			return (ire);
13719 		}
13720 	}
13721 
13722 indiscard:
13723 	BUMP_MIB(&ip_mib, ipInDiscards);
13724 drop:
13725 	if (mp != NULL)
13726 		freemsg(mp);
13727 	if (src_ire != NULL)
13728 		ire_refrele(src_ire);
13729 	return (ire);
13730 
13731 }
13732 
13733 /*
13734  * This function is called in the forwarding slowpath, when
13735  * either the ire lacks the link-layer address, or the packet needs
13736  * further processing(eg. fragmentation), before transmission.
13737  */
13738 
13739 static void
13740 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13741     ill_t *ill, boolean_t ll_multicast)
13742 {
13743 	ill_group_t	*ill_group;
13744 	ill_group_t	*ire_group;
13745 	queue_t		*dev_q;
13746 	ire_t		*src_ire;
13747 
13748 	ASSERT(ire->ire_stq != NULL);
13749 
13750 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13751 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13752 
13753 	if (ll_multicast != 0)
13754 		goto drop_pkt;
13755 
13756 	/*
13757 	 * check if ipha_src is a broadcast address. Note that this
13758 	 * check is redundant when we get here from ip_fast_forward()
13759 	 * which has already done this check. However, since we can
13760 	 * also get here from ip_rput_process_broadcast() or, for
13761 	 * for the slow path through ip_fast_forward(), we perform
13762 	 * the check again for code-reusability
13763 	 */
13764 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13765 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13766 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13767 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13768 		if (src_ire != NULL)
13769 			ire_refrele(src_ire);
13770 		BUMP_MIB(&ip_mib, ipForwProhibits);
13771 		ip2dbg(("ip_rput_process_forward: Received packet with"
13772 		    " bad src/dst address on %s\n", ill->ill_name));
13773 		goto drop_pkt;
13774 	}
13775 
13776 	ill_group = ill->ill_group;
13777 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13778 	/*
13779 	 * Check if we want to forward this one at this time.
13780 	 * We allow source routed packets on a host provided that
13781 	 * they go out the same interface or same interface group
13782 	 * as they came in on.
13783 	 *
13784 	 * XXX To be quicker, we may wish to not chase pointers to
13785 	 * get the ILLF_ROUTER flag and instead store the
13786 	 * forwarding policy in the ire.  An unfortunate
13787 	 * side-effect of that would be requiring an ire flush
13788 	 * whenever the ILLF_ROUTER flag changes.
13789 	 */
13790 	if (((ill->ill_flags &
13791 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13792 	    ILLF_ROUTER) == 0) &&
13793 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13794 	    (ill_group != NULL && ill_group == ire_group)))) {
13795 		BUMP_MIB(&ip_mib, ipForwProhibits);
13796 		if (ip_source_routed(ipha)) {
13797 			q = WR(q);
13798 			/*
13799 			 * Clear the indication that this may have
13800 			 * hardware checksum as we are not using it.
13801 			 */
13802 			DB_CKSUMFLAGS(mp) = 0;
13803 			/* Sent by forwarding path, and router is global zone */
13804 			icmp_unreachable(q, mp,
13805 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13806 			return;
13807 		}
13808 		goto drop_pkt;
13809 	}
13810 
13811 	/* Packet is being forwarded. Turning off hwcksum flag. */
13812 	DB_CKSUMFLAGS(mp) = 0;
13813 	if (ip_g_send_redirects) {
13814 		/*
13815 		 * Check whether the incoming interface and outgoing
13816 		 * interface is part of the same group. If so,
13817 		 * send redirects.
13818 		 *
13819 		 * Check the source address to see if it originated
13820 		 * on the same logical subnet it is going back out on.
13821 		 * If so, we should be able to send it a redirect.
13822 		 * Avoid sending a redirect if the destination
13823 		 * is directly connected (i.e., ipha_dst is the same
13824 		 * as ire_gateway_addr or the ire_addr of the
13825 		 * nexthop IRE_CACHE ), or if the packet was source
13826 		 * routed out this interface.
13827 		 */
13828 		ipaddr_t src, nhop;
13829 		mblk_t	*mp1;
13830 		ire_t	*nhop_ire = NULL;
13831 
13832 		/*
13833 		 * Check whether ire_rfq and q are from the same ill
13834 		 * or if they are not same, they at least belong
13835 		 * to the same group. If so, send redirects.
13836 		 */
13837 		if ((ire->ire_rfq == q ||
13838 		    (ill_group != NULL && ill_group == ire_group)) &&
13839 		    !ip_source_routed(ipha)) {
13840 
13841 			nhop = (ire->ire_gateway_addr != 0 ?
13842 			    ire->ire_gateway_addr : ire->ire_addr);
13843 
13844 			if (ipha->ipha_dst == nhop) {
13845 				/*
13846 				 * We avoid sending a redirect if the
13847 				 * destination is directly connected
13848 				 * because it is possible that multiple
13849 				 * IP subnets may have been configured on
13850 				 * the link, and the source may not
13851 				 * be on the same subnet as ip destination,
13852 				 * even though they are on the same
13853 				 * physical link.
13854 				 */
13855 				goto sendit;
13856 			}
13857 
13858 			src = ipha->ipha_src;
13859 
13860 			/*
13861 			 * We look up the interface ire for the nexthop,
13862 			 * to see if ipha_src is in the same subnet
13863 			 * as the nexthop.
13864 			 *
13865 			 * Note that, if, in the future, IRE_CACHE entries
13866 			 * are obsoleted,  this lookup will not be needed,
13867 			 * as the ire passed to this function will be the
13868 			 * same as the nhop_ire computed below.
13869 			 */
13870 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
13871 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
13872 			    0, NULL, MATCH_IRE_TYPE);
13873 
13874 			if (nhop_ire != NULL &&
13875 			    (src & nhop_ire->ire_mask) ==
13876 			    (nhop & nhop_ire->ire_mask)) {
13877 				/*
13878 				 * The source is directly connected.
13879 				 * Just copy the ip header (which is
13880 				 * in the first mblk)
13881 				 */
13882 				mp1 = copyb(mp);
13883 				if (mp1 != NULL) {
13884 					icmp_send_redirect(WR(q), mp1, nhop);
13885 				}
13886 				ire_refrele(nhop_ire);
13887 			}
13888 		}
13889 	}
13890 sendit:
13891 	dev_q = ire->ire_stq->q_next;
13892 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13893 		BUMP_MIB(&ip_mib, ipInDiscards);
13894 		freemsg(mp);
13895 		return;
13896 	}
13897 
13898 	ip_rput_forward(ire, ipha, mp, ill);
13899 	return;
13900 
13901 drop_pkt:
13902 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
13903 	freemsg(mp);
13904 }
13905 
13906 ire_t *
13907 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13908     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13909 {
13910 	queue_t		*q;
13911 	uint16_t	hcksumflags;
13912 
13913 	q = *qp;
13914 
13915 	/*
13916 	 * Clear the indication that this may have hardware
13917 	 * checksum as we are not using it for forwarding.
13918 	 */
13919 	hcksumflags = DB_CKSUMFLAGS(mp);
13920 	DB_CKSUMFLAGS(mp) = 0;
13921 
13922 	/*
13923 	 * Directed broadcast forwarding: if the packet came in over a
13924 	 * different interface then it is routed out over we can forward it.
13925 	 */
13926 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13927 		ire_refrele(ire);
13928 		freemsg(mp);
13929 		BUMP_MIB(&ip_mib, ipInDiscards);
13930 		return (NULL);
13931 	}
13932 	/*
13933 	 * For multicast we have set dst to be INADDR_BROADCAST
13934 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13935 	 * only for broadcast packets.
13936 	 */
13937 	if (!CLASSD(ipha->ipha_dst)) {
13938 		ire_t *new_ire;
13939 		ipif_t *ipif;
13940 		/*
13941 		 * For ill groups, as the switch duplicates broadcasts
13942 		 * across all the ports, we need to filter out and
13943 		 * send up only one copy. There is one copy for every
13944 		 * broadcast address on each ill. Thus, we look for a
13945 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13946 		 * later to see whether this ill is eligible to receive
13947 		 * them or not. ill_nominate_bcast_rcv() nominates only
13948 		 * one set of IREs for receiving.
13949 		 */
13950 
13951 		ipif = ipif_get_next_ipif(NULL, ill);
13952 		if (ipif == NULL) {
13953 			ire_refrele(ire);
13954 			freemsg(mp);
13955 			BUMP_MIB(&ip_mib, ipInDiscards);
13956 			return (NULL);
13957 		}
13958 		new_ire = ire_ctable_lookup(dst, 0, 0,
13959 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13960 		ipif_refrele(ipif);
13961 
13962 		if (new_ire != NULL) {
13963 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13964 				ire_refrele(ire);
13965 				ire_refrele(new_ire);
13966 				freemsg(mp);
13967 				BUMP_MIB(&ip_mib, ipInDiscards);
13968 				return (NULL);
13969 			}
13970 			/*
13971 			 * In the special case of multirouted broadcast
13972 			 * packets, we unconditionally need to "gateway"
13973 			 * them to the appropriate interface here.
13974 			 * In the normal case, this cannot happen, because
13975 			 * there is no broadcast IRE tagged with the
13976 			 * RTF_MULTIRT flag.
13977 			 */
13978 			if (new_ire->ire_flags & RTF_MULTIRT) {
13979 				ire_refrele(new_ire);
13980 				if (ire->ire_rfq != NULL) {
13981 					q = ire->ire_rfq;
13982 					*qp = q;
13983 				}
13984 			} else {
13985 				ire_refrele(ire);
13986 				ire = new_ire;
13987 			}
13988 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
13989 			if (!ip_g_forward_directed_bcast) {
13990 				/*
13991 				 * Free the message if
13992 				 * ip_g_forward_directed_bcast is turned
13993 				 * off for non-local broadcast.
13994 				 */
13995 				ire_refrele(ire);
13996 				freemsg(mp);
13997 				BUMP_MIB(&ip_mib, ipInDiscards);
13998 				return (NULL);
13999 			}
14000 		} else {
14001 			/*
14002 			 * This CGTP packet successfully passed the
14003 			 * CGTP filter, but the related CGTP
14004 			 * broadcast IRE has not been found,
14005 			 * meaning that the redundant ipif is
14006 			 * probably down. However, if we discarded
14007 			 * this packet, its duplicate would be
14008 			 * filtered out by the CGTP filter so none
14009 			 * of them would get through. So we keep
14010 			 * going with this one.
14011 			 */
14012 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14013 			if (ire->ire_rfq != NULL) {
14014 				q = ire->ire_rfq;
14015 				*qp = q;
14016 			}
14017 		}
14018 	}
14019 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
14020 		/*
14021 		 * Verify that there are not more then one
14022 		 * IRE_BROADCAST with this broadcast address which
14023 		 * has ire_stq set.
14024 		 * TODO: simplify, loop over all IRE's
14025 		 */
14026 		ire_t	*ire1;
14027 		int	num_stq = 0;
14028 		mblk_t	*mp1;
14029 
14030 		/* Find the first one with ire_stq set */
14031 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14032 		for (ire1 = ire; ire1 &&
14033 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14034 		    ire1 = ire1->ire_next)
14035 			;
14036 		if (ire1) {
14037 			ire_refrele(ire);
14038 			ire = ire1;
14039 			IRE_REFHOLD(ire);
14040 		}
14041 
14042 		/* Check if there are additional ones with stq set */
14043 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14044 			if (ire->ire_addr != ire1->ire_addr)
14045 				break;
14046 			if (ire1->ire_stq) {
14047 				num_stq++;
14048 				break;
14049 			}
14050 		}
14051 		rw_exit(&ire->ire_bucket->irb_lock);
14052 		if (num_stq == 1 && ire->ire_stq != NULL) {
14053 			ip1dbg(("ip_rput_process_broadcast: directed "
14054 			    "broadcast to 0x%x\n",
14055 			    ntohl(ire->ire_addr)));
14056 			mp1 = copymsg(mp);
14057 			if (mp1) {
14058 				switch (ipha->ipha_protocol) {
14059 				case IPPROTO_UDP:
14060 					ip_udp_input(q, mp1, ipha, ire, ill);
14061 					break;
14062 				default:
14063 					ip_proto_input(q, mp1, ipha, ire, ill);
14064 					break;
14065 				}
14066 			}
14067 			/*
14068 			 * Adjust ttl to 2 (1+1 - the forward engine
14069 			 * will decrement it by one.
14070 			 */
14071 			if (ip_csum_hdr(ipha)) {
14072 				BUMP_MIB(&ip_mib, ipInCksumErrs);
14073 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14074 				freemsg(mp);
14075 				ire_refrele(ire);
14076 				return (NULL);
14077 			}
14078 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
14079 			ipha->ipha_hdr_checksum = 0;
14080 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14081 			ip_rput_process_forward(q, mp, ire, ipha,
14082 			    ill, ll_multicast);
14083 			ire_refrele(ire);
14084 			return (NULL);
14085 		}
14086 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14087 		    ntohl(ire->ire_addr)));
14088 	}
14089 
14090 
14091 	/* Restore any hardware checksum flags */
14092 	DB_CKSUMFLAGS(mp) = hcksumflags;
14093 	return (ire);
14094 }
14095 
14096 /* ARGSUSED */
14097 static boolean_t
14098 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14099     int *ll_multicast, ipaddr_t *dstp)
14100 {
14101 	/*
14102 	 * Forward packets only if we have joined the allmulti
14103 	 * group on this interface.
14104 	 */
14105 	if (ip_g_mrouter && ill->ill_join_allmulti) {
14106 		int retval;
14107 
14108 		/*
14109 		 * Clear the indication that this may have hardware
14110 		 * checksum as we are not using it.
14111 		 */
14112 		DB_CKSUMFLAGS(mp) = 0;
14113 		retval = ip_mforward(ill, ipha, mp);
14114 		/* ip_mforward updates mib variables if needed */
14115 		/* clear b_prev - used by ip_mroute_decap */
14116 		mp->b_prev = NULL;
14117 
14118 		switch (retval) {
14119 		case 0:
14120 			/*
14121 			 * pkt is okay and arrived on phyint.
14122 			 *
14123 			 * If we are running as a multicast router
14124 			 * we need to see all IGMP and/or PIM packets.
14125 			 */
14126 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14127 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14128 				goto done;
14129 			}
14130 			break;
14131 		case -1:
14132 			/* pkt is mal-formed, toss it */
14133 			goto drop_pkt;
14134 		case 1:
14135 			/* pkt is okay and arrived on a tunnel */
14136 			/*
14137 			 * If we are running a multicast router
14138 			 *  we need to see all igmp packets.
14139 			 */
14140 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14141 				*dstp = INADDR_BROADCAST;
14142 				*ll_multicast = 1;
14143 				return (B_FALSE);
14144 			}
14145 
14146 			goto drop_pkt;
14147 		}
14148 	}
14149 
14150 	ILM_WALKER_HOLD(ill);
14151 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14152 		/*
14153 		 * This might just be caused by the fact that
14154 		 * multiple IP Multicast addresses map to the same
14155 		 * link layer multicast - no need to increment counter!
14156 		 */
14157 		ILM_WALKER_RELE(ill);
14158 		freemsg(mp);
14159 		return (B_TRUE);
14160 	}
14161 	ILM_WALKER_RELE(ill);
14162 done:
14163 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14164 	/*
14165 	 * This assumes the we deliver to all streams for multicast
14166 	 * and broadcast packets.
14167 	 */
14168 	*dstp = INADDR_BROADCAST;
14169 	*ll_multicast = 1;
14170 	return (B_FALSE);
14171 drop_pkt:
14172 	ip2dbg(("ip_rput: drop pkt\n"));
14173 	freemsg(mp);
14174 	return (B_TRUE);
14175 }
14176 
14177 static boolean_t
14178 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14179     int *ll_multicast, mblk_t **mpp)
14180 {
14181 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14182 	boolean_t must_copy = B_FALSE;
14183 	struct iocblk   *iocp;
14184 	ipha_t		*ipha;
14185 
14186 #define	rptr    ((uchar_t *)ipha)
14187 
14188 	first_mp = *first_mpp;
14189 	mp = *mpp;
14190 
14191 	ASSERT(first_mp == mp);
14192 
14193 	/*
14194 	 * if db_ref > 1 then copymsg and free original. Packet may be
14195 	 * changed and do not want other entity who has a reference to this
14196 	 * message to trip over the changes. This is a blind change because
14197 	 * trying to catch all places that might change packet is too
14198 	 * difficult (since it may be a module above this one)
14199 	 *
14200 	 * This corresponds to the non-fast path case. We walk down the full
14201 	 * chain in this case, and check the db_ref count of all the dblks,
14202 	 * and do a copymsg if required. It is possible that the db_ref counts
14203 	 * of the data blocks in the mblk chain can be different.
14204 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14205 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14206 	 * 'snoop' is running.
14207 	 */
14208 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14209 		if (mp1->b_datap->db_ref > 1) {
14210 			must_copy = B_TRUE;
14211 			break;
14212 		}
14213 	}
14214 
14215 	if (must_copy) {
14216 		mp1 = copymsg(mp);
14217 		if (mp1 == NULL) {
14218 			for (mp1 = mp; mp1 != NULL;
14219 			    mp1 = mp1->b_cont) {
14220 				mp1->b_next = NULL;
14221 				mp1->b_prev = NULL;
14222 			}
14223 			freemsg(mp);
14224 			BUMP_MIB(&ip_mib, ipInDiscards);
14225 			return (B_TRUE);
14226 		}
14227 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14228 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14229 			/* Copy b_prev - used by ip_mroute_decap */
14230 			to_mp->b_prev = from_mp->b_prev;
14231 			from_mp->b_prev = NULL;
14232 		}
14233 		*first_mpp = first_mp = mp1;
14234 		freemsg(mp);
14235 		mp = mp1;
14236 		*mpp = mp1;
14237 	}
14238 
14239 	ipha = (ipha_t *)mp->b_rptr;
14240 
14241 	/*
14242 	 * previous code has a case for M_DATA.
14243 	 * We want to check how that happens.
14244 	 */
14245 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14246 	switch (first_mp->b_datap->db_type) {
14247 	case M_PROTO:
14248 	case M_PCPROTO:
14249 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14250 		    DL_UNITDATA_IND) {
14251 			/* Go handle anything other than data elsewhere. */
14252 			ip_rput_dlpi(q, mp);
14253 			return (B_TRUE);
14254 		}
14255 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14256 		/* Ditch the DLPI header. */
14257 		mp1 = mp->b_cont;
14258 		ASSERT(first_mp == mp);
14259 		*first_mpp = mp1;
14260 		freeb(mp);
14261 		*mpp = mp1;
14262 		return (B_FALSE);
14263 	case M_IOCACK:
14264 		ip1dbg(("got iocack "));
14265 		iocp = (struct iocblk *)mp->b_rptr;
14266 		switch (iocp->ioc_cmd) {
14267 		case DL_IOC_HDR_INFO:
14268 			ill = (ill_t *)q->q_ptr;
14269 			ill_fastpath_ack(ill, mp);
14270 			return (B_TRUE);
14271 		case SIOCSTUNPARAM:
14272 		case OSIOCSTUNPARAM:
14273 			/* Go through qwriter_ip */
14274 			break;
14275 		case SIOCGTUNPARAM:
14276 		case OSIOCGTUNPARAM:
14277 			ip_rput_other(NULL, q, mp, NULL);
14278 			return (B_TRUE);
14279 		default:
14280 			putnext(q, mp);
14281 			return (B_TRUE);
14282 		}
14283 		/* FALLTHRU */
14284 	case M_ERROR:
14285 	case M_HANGUP:
14286 		/*
14287 		 * Since this is on the ill stream we unconditionally
14288 		 * bump up the refcount
14289 		 */
14290 		ill_refhold(ill);
14291 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14292 		    B_FALSE);
14293 		return (B_TRUE);
14294 	case M_CTL:
14295 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14296 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14297 			IPHADA_M_CTL)) {
14298 			/*
14299 			 * It's an IPsec accelerated packet.
14300 			 * Make sure that the ill from which we received the
14301 			 * packet has enabled IPsec hardware acceleration.
14302 			 */
14303 			if (!(ill->ill_capabilities &
14304 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14305 				/* IPsec kstats: bean counter */
14306 				freemsg(mp);
14307 				return (B_TRUE);
14308 			}
14309 
14310 			/*
14311 			 * Make mp point to the mblk following the M_CTL,
14312 			 * then process according to type of mp.
14313 			 * After this processing, first_mp will point to
14314 			 * the data-attributes and mp to the pkt following
14315 			 * the M_CTL.
14316 			 */
14317 			mp = first_mp->b_cont;
14318 			if (mp == NULL) {
14319 				freemsg(first_mp);
14320 				return (B_TRUE);
14321 			}
14322 			/*
14323 			 * A Hardware Accelerated packet can only be M_DATA
14324 			 * ESP or AH packet.
14325 			 */
14326 			if (mp->b_datap->db_type != M_DATA) {
14327 				/* non-M_DATA IPsec accelerated packet */
14328 				IPSECHW_DEBUG(IPSECHW_PKT,
14329 				    ("non-M_DATA IPsec accelerated pkt\n"));
14330 				freemsg(first_mp);
14331 				return (B_TRUE);
14332 			}
14333 			ipha = (ipha_t *)mp->b_rptr;
14334 			if (ipha->ipha_protocol != IPPROTO_AH &&
14335 			    ipha->ipha_protocol != IPPROTO_ESP) {
14336 				IPSECHW_DEBUG(IPSECHW_PKT,
14337 				    ("non-M_DATA IPsec accelerated pkt\n"));
14338 				freemsg(first_mp);
14339 				return (B_TRUE);
14340 			}
14341 			*mpp = mp;
14342 			return (B_FALSE);
14343 		}
14344 		putnext(q, mp);
14345 		return (B_TRUE);
14346 	case M_FLUSH:
14347 		if (*mp->b_rptr & FLUSHW) {
14348 			*mp->b_rptr &= ~FLUSHR;
14349 			qreply(q, mp);
14350 			return (B_TRUE);
14351 		}
14352 		freemsg(mp);
14353 		return (B_TRUE);
14354 	case M_IOCNAK:
14355 		ip1dbg(("got iocnak "));
14356 		iocp = (struct iocblk *)mp->b_rptr;
14357 		switch (iocp->ioc_cmd) {
14358 		case DL_IOC_HDR_INFO:
14359 		case SIOCSTUNPARAM:
14360 		case OSIOCSTUNPARAM:
14361 			/*
14362 			 * Since this is on the ill stream we unconditionally
14363 			 * bump up the refcount
14364 			 */
14365 			ill_refhold(ill);
14366 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14367 			    CUR_OP, B_FALSE);
14368 			return (B_TRUE);
14369 		case SIOCGTUNPARAM:
14370 		case OSIOCGTUNPARAM:
14371 			ip_rput_other(NULL, q, mp, NULL);
14372 			return (B_TRUE);
14373 		default:
14374 			break;
14375 		}
14376 		/* FALLTHRU */
14377 	default:
14378 		putnext(q, mp);
14379 		return (B_TRUE);
14380 	}
14381 }
14382 
14383 /* Read side put procedure.  Packets coming from the wire arrive here. */
14384 void
14385 ip_rput(queue_t *q, mblk_t *mp)
14386 {
14387 	ill_t	*ill;
14388 	mblk_t	 *dmp = NULL;
14389 
14390 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14391 
14392 	ill = (ill_t *)q->q_ptr;
14393 
14394 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14395 		union DL_primitives *dl;
14396 
14397 		/*
14398 		 * Things are opening or closing. Only accept DLPI control
14399 		 * messages. In the open case, the ill->ill_ipif has not yet
14400 		 * been created. In the close case, things hanging off the
14401 		 * ill could have been freed already. In either case it
14402 		 * may not be safe to proceed further.
14403 		 */
14404 
14405 		dl = (union DL_primitives *)mp->b_rptr;
14406 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14407 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14408 			/*
14409 			 * Also SIOC[GS]TUN* ioctls can come here.
14410 			 */
14411 			inet_freemsg(mp);
14412 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14413 			    "ip_input_end: q %p (%S)", q, "uninit");
14414 			return;
14415 		}
14416 	}
14417 
14418 	/*
14419 	 * if db_ref > 1 then copymsg and free original. Packet may be
14420 	 * changed and we do not want the other entity who has a reference to
14421 	 * this message to trip over the changes. This is a blind change because
14422 	 * trying to catch all places that might change the packet is too
14423 	 * difficult.
14424 	 *
14425 	 * This corresponds to the fast path case, where we have a chain of
14426 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14427 	 * in the mblk chain. There doesn't seem to be a reason why a device
14428 	 * driver would send up data with varying db_ref counts in the mblk
14429 	 * chain. In any case the Fast path is a private interface, and our
14430 	 * drivers don't do such a thing. Given the above assumption, there is
14431 	 * no need to walk down the entire mblk chain (which could have a
14432 	 * potential performance problem)
14433 	 */
14434 	if (mp->b_datap->db_ref > 1) {
14435 		mblk_t  *mp1;
14436 		boolean_t adjusted = B_FALSE;
14437 		IP_STAT(ip_db_ref);
14438 
14439 		/*
14440 		 * The IP_RECVSLLA option depends on having the link layer
14441 		 * header. First check that:
14442 		 * a> the underlying device is of type ether, since this
14443 		 * option is currently supported only over ethernet.
14444 		 * b> there is enough room to copy over the link layer header.
14445 		 *
14446 		 * Once the checks are done, adjust rptr so that the link layer
14447 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14448 		 * be returned by some non-ethernet drivers but in this case the
14449 		 * second check will fail.
14450 		 */
14451 		if (ill->ill_type == IFT_ETHER &&
14452 		    (mp->b_rptr - mp->b_datap->db_base) >=
14453 		    sizeof (struct ether_header)) {
14454 			mp->b_rptr -= sizeof (struct ether_header);
14455 			adjusted = B_TRUE;
14456 		}
14457 		mp1 = copymsg(mp);
14458 		if (mp1 == NULL) {
14459 			mp->b_next = NULL;
14460 			/* clear b_prev - used by ip_mroute_decap */
14461 			mp->b_prev = NULL;
14462 			freemsg(mp);
14463 			BUMP_MIB(&ip_mib, ipInDiscards);
14464 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14465 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14466 			return;
14467 		}
14468 		if (adjusted) {
14469 			/*
14470 			 * Copy is done. Restore the pointer in the _new_ mblk
14471 			 */
14472 			mp1->b_rptr += sizeof (struct ether_header);
14473 		}
14474 		/* Copy b_prev - used by ip_mroute_decap */
14475 		mp1->b_prev = mp->b_prev;
14476 		mp->b_prev = NULL;
14477 		freemsg(mp);
14478 		mp = mp1;
14479 	}
14480 	if (DB_TYPE(mp) == M_DATA) {
14481 		dmp = mp;
14482 	} else if (DB_TYPE(mp) == M_PROTO &&
14483 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14484 		dmp = mp->b_cont;
14485 	}
14486 	if (dmp != NULL) {
14487 		/*
14488 		 * IP header ptr not aligned?
14489 		 * OR IP header not complete in first mblk
14490 		 */
14491 		if (!OK_32PTR(dmp->b_rptr) ||
14492 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14493 			if (!ip_check_and_align_header(q, dmp))
14494 				return;
14495 		}
14496 	}
14497 
14498 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14499 	    "ip_rput_end: q %p (%S)", q, "end");
14500 
14501 	ip_input(ill, NULL, mp, NULL);
14502 }
14503 
14504 /*
14505  * Direct read side procedure capable of dealing with chains. GLDv3 based
14506  * drivers call this function directly with mblk chains while STREAMS
14507  * read side procedure ip_rput() calls this for single packet with ip_ring
14508  * set to NULL to process one packet at a time.
14509  *
14510  * The ill will always be valid if this function is called directly from
14511  * the driver.
14512  *
14513  * If ip_input() is called from GLDv3:
14514  *
14515  *   - This must be a non-VLAN IP stream.
14516  *   - 'mp' is either an untagged or a special priority-tagged packet.
14517  *   - Any VLAN tag that was in the MAC header has been stripped.
14518  *
14519  * Thus, there is no need to adjust b_rptr in this function.
14520  */
14521 /* ARGSUSED */
14522 void
14523 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14524     struct mac_header_info_s *mhip)
14525 {
14526 	ipaddr_t		dst = NULL;
14527 	ipaddr_t		prev_dst;
14528 	ire_t			*ire = NULL;
14529 	ipha_t			*ipha;
14530 	uint_t			pkt_len;
14531 	ssize_t			len;
14532 	uint_t			opt_len;
14533 	int			ll_multicast;
14534 	int			cgtp_flt_pkt;
14535 	queue_t			*q = ill->ill_rq;
14536 	squeue_t		*curr_sqp = NULL;
14537 	mblk_t 			*head = NULL;
14538 	mblk_t			*tail = NULL;
14539 	mblk_t			*first_mp;
14540 	mblk_t 			*mp;
14541 	int			cnt = 0;
14542 
14543 	ASSERT(mp_chain != NULL);
14544 	ASSERT(ill != NULL);
14545 
14546 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14547 
14548 #define	rptr	((uchar_t *)ipha)
14549 
14550 	while (mp_chain != NULL) {
14551 		first_mp = mp = mp_chain;
14552 		mp_chain = mp_chain->b_next;
14553 		mp->b_next = NULL;
14554 		ll_multicast = 0;
14555 
14556 		/*
14557 		 * We do ire caching from one iteration to
14558 		 * another. In the event the packet chain contains
14559 		 * all packets from the same dst, this caching saves
14560 		 * an ire_cache_lookup for each of the succeeding
14561 		 * packets in a packet chain.
14562 		 */
14563 		prev_dst = dst;
14564 
14565 		/*
14566 		 * ip_input fast path
14567 		 */
14568 
14569 		/* mblk type is not M_DATA */
14570 		if (mp->b_datap->db_type != M_DATA) {
14571 			if (ip_rput_process_notdata(q, &first_mp, ill,
14572 			    &ll_multicast, &mp))
14573 				continue;
14574 		}
14575 
14576 		/* Make sure its an M_DATA and that its aligned */
14577 		ASSERT(mp->b_datap->db_type == M_DATA);
14578 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14579 
14580 		ipha = (ipha_t *)mp->b_rptr;
14581 		len = mp->b_wptr - rptr;
14582 
14583 		BUMP_MIB(&ip_mib, ipInReceives);
14584 
14585 
14586 		/* multiple mblk or too short */
14587 		pkt_len = ntohs(ipha->ipha_length);
14588 		len -= pkt_len;
14589 		if (len != 0) {
14590 			/*
14591 			 * Make sure we have data length consistent
14592 			 * with the IP header.
14593 			 */
14594 			if (mp->b_cont == NULL) {
14595 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14596 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14597 					ip2dbg(("ip_input: drop pkt\n"));
14598 					freemsg(mp);
14599 					continue;
14600 				}
14601 				mp->b_wptr = rptr + pkt_len;
14602 			} else if (len += msgdsize(mp->b_cont)) {
14603 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14604 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14605 					ip2dbg(("ip_input: drop pkt\n"));
14606 					freemsg(mp);
14607 					continue;
14608 				}
14609 				(void) adjmsg(mp, -len);
14610 				IP_STAT(ip_multimblk3);
14611 			}
14612 		}
14613 
14614 		/* Obtain the dst of the current packet */
14615 		dst = ipha->ipha_dst;
14616 
14617 		if (IP_LOOPBACK_ADDR(dst) ||
14618 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14619 			BUMP_MIB(&ip_mib, ipInAddrErrors);
14620 			cmn_err(CE_CONT, "dst %X src %X\n",
14621 			    dst, ipha->ipha_src);
14622 			freemsg(mp);
14623 			continue;
14624 		}
14625 
14626 		/*
14627 		 * The event for packets being received from a 'physical'
14628 		 * interface is placed after validation of the source and/or
14629 		 * destination address as being local so that packets can be
14630 		 * redirected to loopback addresses using ipnat.
14631 		 */
14632 		DTRACE_PROBE4(ip4__physical__in__start,
14633 		    ill_t *, ill, ill_t *, NULL,
14634 		    ipha_t *, ipha, mblk_t *, first_mp);
14635 
14636 		FW_HOOKS(ip4_physical_in_event, ipv4firewall_physical_in,
14637 		    ill, NULL, ipha, first_mp, mp);
14638 
14639 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14640 
14641 		if (first_mp == NULL) {
14642 			continue;
14643 		}
14644 		dst = ipha->ipha_dst;
14645 
14646 		/*
14647 		 * Attach any necessary label information to
14648 		 * this packet
14649 		 */
14650 		if (is_system_labeled() &&
14651 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14652 			BUMP_MIB(&ip_mib, ipInDiscards);
14653 			freemsg(mp);
14654 			continue;
14655 		}
14656 
14657 		/*
14658 		 * Reuse the cached ire only if the ipha_dst of the previous
14659 		 * packet is the same as the current packet AND it is not
14660 		 * INADDR_ANY.
14661 		 */
14662 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14663 		    (ire != NULL)) {
14664 			ire_refrele(ire);
14665 			ire = NULL;
14666 		}
14667 		opt_len = ipha->ipha_version_and_hdr_length -
14668 		    IP_SIMPLE_HDR_VERSION;
14669 
14670 		/*
14671 		 * Check to see if we can take the fastpath.
14672 		 * That is possible if the following conditions are met
14673 		 *	o Tsol disabled
14674 		 *	o CGTP disabled
14675 		 *	o ipp_action_count is 0
14676 		 *	o Mobile IP not running
14677 		 *	o no options in the packet
14678 		 *	o not a RSVP packet
14679 		 * 	o not a multicast packet
14680 		 */
14681 		if (!is_system_labeled() &&
14682 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14683 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14684 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14685 		    !ll_multicast && !CLASSD(dst)) {
14686 			if (ire == NULL)
14687 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14688 
14689 			/* incoming packet is for forwarding */
14690 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14691 				ire = ip_fast_forward(ire, dst, ill, mp);
14692 				continue;
14693 			}
14694 			/* incoming packet is for local consumption */
14695 			if (ire->ire_type & IRE_LOCAL)
14696 				goto local;
14697 		}
14698 
14699 		/*
14700 		 * Disable ire caching for anything more complex
14701 		 * than the simple fast path case we checked for above.
14702 		 */
14703 		if (ire != NULL) {
14704 			ire_refrele(ire);
14705 			ire = NULL;
14706 		}
14707 
14708 		/* Full-blown slow path */
14709 		if (opt_len != 0) {
14710 			if (len != 0)
14711 				IP_STAT(ip_multimblk4);
14712 			else
14713 				IP_STAT(ip_ipoptions);
14714 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
14715 				continue;
14716 		}
14717 
14718 		/*
14719 		 * Invoke the CGTP (multirouting) filtering module to process
14720 		 * the incoming packet. Packets identified as duplicates
14721 		 * must be discarded. Filtering is active only if the
14722 		 * the ip_cgtp_filter ndd variable is non-zero.
14723 		 */
14724 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14725 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
14726 			cgtp_flt_pkt =
14727 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14728 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14729 				freemsg(first_mp);
14730 				continue;
14731 			}
14732 		}
14733 
14734 		/*
14735 		 * If rsvpd is running, let RSVP daemon handle its processing
14736 		 * and forwarding of RSVP multicast/unicast packets.
14737 		 * If rsvpd is not running but mrouted is running, RSVP
14738 		 * multicast packets are forwarded as multicast traffic
14739 		 * and RSVP unicast packets are forwarded by unicast router.
14740 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14741 		 * packets are not forwarded, but the unicast packets are
14742 		 * forwarded like unicast traffic.
14743 		 */
14744 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14745 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
14746 			/* RSVP packet and rsvpd running. Treat as ours */
14747 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14748 			/*
14749 			 * This assumes that we deliver to all streams for
14750 			 * multicast and broadcast packets.
14751 			 * We have to force ll_multicast to 1 to handle the
14752 			 * M_DATA messages passed in from ip_mroute_decap.
14753 			 */
14754 			dst = INADDR_BROADCAST;
14755 			ll_multicast = 1;
14756 		} else if (CLASSD(dst)) {
14757 			/* packet is multicast */
14758 			mp->b_next = NULL;
14759 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14760 			    &ll_multicast, &dst))
14761 				continue;
14762 		}
14763 
14764 
14765 		/*
14766 		 * Check if the packet is coming from the Mobile IP
14767 		 * forward tunnel interface
14768 		 */
14769 		if (ill->ill_srcif_refcnt > 0) {
14770 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
14771 			    NULL, ill, MATCH_IRE_TYPE);
14772 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
14773 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
14774 
14775 				/* We need to resolve the link layer info */
14776 				ire_refrele(ire);
14777 				ire = NULL;
14778 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
14779 				    ll_multicast, dst);
14780 				continue;
14781 			}
14782 		}
14783 
14784 		if (ire == NULL) {
14785 			ire = ire_cache_lookup(dst, ALL_ZONES,
14786 			    MBLK_GETLABEL(mp));
14787 		}
14788 
14789 		/*
14790 		 * If mipagent is running and reverse tunnel is created as per
14791 		 * mobile node request, then any packet coming through the
14792 		 * incoming interface from the mobile-node, should be reverse
14793 		 * tunneled to it's home agent except those that are destined
14794 		 * to foreign agent only.
14795 		 * This needs source address based ire lookup. The routing
14796 		 * entries for source address based lookup are only created by
14797 		 * mipagent program only when a reverse tunnel is created.
14798 		 * Reference : RFC2002, RFC2344
14799 		 */
14800 		if (ill->ill_mrtun_refcnt > 0) {
14801 			ipaddr_t	srcaddr;
14802 			ire_t		*tmp_ire;
14803 
14804 			tmp_ire = ire;	/* Save, we might need it later */
14805 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14806 			    ire->ire_type != IRE_BROADCAST)) {
14807 				srcaddr = ipha->ipha_src;
14808 				ire = ire_mrtun_lookup(srcaddr, ill);
14809 				if (ire != NULL) {
14810 					/*
14811 					 * Should not be getting iphada packet
14812 					 * here. we should only get those for
14813 					 * IRE_LOCAL traffic, excluded above.
14814 					 * Fail-safe (drop packet) in the event
14815 					 * hardware is misbehaving.
14816 					 */
14817 					if (first_mp != mp) {
14818 						/* IPsec KSTATS: beancount me */
14819 						freemsg(first_mp);
14820 					} else {
14821 						/*
14822 						 * This packet must be forwarded
14823 						 * to Reverse Tunnel
14824 						 */
14825 						ip_mrtun_forward(ire, ill, mp);
14826 					}
14827 					ire_refrele(ire);
14828 					ire = NULL;
14829 					if (tmp_ire != NULL) {
14830 						ire_refrele(tmp_ire);
14831 						tmp_ire = NULL;
14832 					}
14833 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14834 					    "ip_input_end: q %p (%S)",
14835 					    q, "uninit");
14836 					continue;
14837 				}
14838 			}
14839 			/*
14840 			 * If this packet is from a non-mobilenode  or a
14841 			 * mobile-node which does not request reverse
14842 			 * tunnel service
14843 			 */
14844 			ire = tmp_ire;
14845 		}
14846 
14847 
14848 		/*
14849 		 * If we reach here that means the incoming packet satisfies
14850 		 * one of the following conditions:
14851 		 *   - packet is from a mobile node which does not request
14852 		 *	reverse tunnel
14853 		 *   - packet is from a non-mobile node, which is the most
14854 		 *	common case
14855 		 *   - packet is from a reverse tunnel enabled mobile node
14856 		 *	and destined to foreign agent only
14857 		 */
14858 
14859 		if (ire == NULL) {
14860 			/*
14861 			 * No IRE for this destination, so it can't be for us.
14862 			 * Unless we are forwarding, drop the packet.
14863 			 * We have to let source routed packets through
14864 			 * since we don't yet know if they are 'ping -l'
14865 			 * packets i.e. if they will go out over the
14866 			 * same interface as they came in on.
14867 			 */
14868 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14869 			if (ire == NULL)
14870 				continue;
14871 		}
14872 
14873 		/*
14874 		 * Broadcast IRE may indicate either broadcast or
14875 		 * multicast packet
14876 		 */
14877 		if (ire->ire_type == IRE_BROADCAST) {
14878 			/*
14879 			 * Skip broadcast checks if packet is UDP multicast;
14880 			 * we'd rather not enter ip_rput_process_broadcast()
14881 			 * unless the packet is broadcast for real, since
14882 			 * that routine is a no-op for multicast.
14883 			 */
14884 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14885 			    !CLASSD(ipha->ipha_dst)) {
14886 				ire = ip_rput_process_broadcast(&q, mp,
14887 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14888 				    ll_multicast);
14889 				if (ire == NULL)
14890 					continue;
14891 			}
14892 		} else if (ire->ire_stq != NULL) {
14893 			/* fowarding? */
14894 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14895 			    ll_multicast);
14896 			/* ip_rput_process_forward consumed the packet */
14897 			continue;
14898 		}
14899 
14900 local:
14901 		/* packet not for us */
14902 		if (ire->ire_rfq != q) {
14903 			if (ip_rput_notforus(&q, mp, ire, ill))
14904 				continue;
14905 		}
14906 
14907 		switch (ipha->ipha_protocol) {
14908 		case IPPROTO_TCP:
14909 			ASSERT(first_mp == mp);
14910 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14911 				mp, 0, q, ip_ring)) != NULL) {
14912 				if (curr_sqp == NULL) {
14913 					curr_sqp = GET_SQUEUE(mp);
14914 					ASSERT(cnt == 0);
14915 					cnt++;
14916 					head = tail = mp;
14917 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14918 					ASSERT(tail != NULL);
14919 					cnt++;
14920 					tail->b_next = mp;
14921 					tail = mp;
14922 				} else {
14923 					/*
14924 					 * A different squeue. Send the
14925 					 * chain for the previous squeue on
14926 					 * its way. This shouldn't happen
14927 					 * often unless interrupt binding
14928 					 * changes.
14929 					 */
14930 					IP_STAT(ip_input_multi_squeue);
14931 					squeue_enter_chain(curr_sqp, head,
14932 					    tail, cnt, SQTAG_IP_INPUT);
14933 					curr_sqp = GET_SQUEUE(mp);
14934 					head = mp;
14935 					tail = mp;
14936 					cnt = 1;
14937 				}
14938 			}
14939 			continue;
14940 		case IPPROTO_UDP:
14941 			ASSERT(first_mp == mp);
14942 			ip_udp_input(q, mp, ipha, ire, ill);
14943 			continue;
14944 		case IPPROTO_SCTP:
14945 			ASSERT(first_mp == mp);
14946 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14947 			    q, dst);
14948 			/* ire has been released by ip_sctp_input */
14949 			ire = NULL;
14950 			continue;
14951 		default:
14952 			ip_proto_input(q, first_mp, ipha, ire, ill);
14953 			continue;
14954 		}
14955 	}
14956 
14957 	if (ire != NULL)
14958 		ire_refrele(ire);
14959 
14960 	if (head != NULL)
14961 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14962 
14963 	/*
14964 	 * This code is there just to make netperf/ttcp look good.
14965 	 *
14966 	 * Its possible that after being in polling mode (and having cleared
14967 	 * the backlog), squeues have turned the interrupt frequency higher
14968 	 * to improve latency at the expense of more CPU utilization (less
14969 	 * packets per interrupts or more number of interrupts). Workloads
14970 	 * like ttcp/netperf do manage to tickle polling once in a while
14971 	 * but for the remaining time, stay in higher interrupt mode since
14972 	 * their packet arrival rate is pretty uniform and this shows up
14973 	 * as higher CPU utilization. Since people care about CPU utilization
14974 	 * while running netperf/ttcp, turn the interrupt frequency back to
14975 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14976 	 */
14977 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14978 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14979 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14980 			ip_ring->rr_blank(ip_ring->rr_handle,
14981 			    ip_ring->rr_normal_blank_time,
14982 			    ip_ring->rr_normal_pkt_cnt);
14983 		}
14984 	}
14985 
14986 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14987 	    "ip_input_end: q %p (%S)", q, "end");
14988 #undef	rptr
14989 }
14990 
14991 static void
14992 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
14993     t_uscalar_t err)
14994 {
14995 	if (dl_err == DL_SYSERR) {
14996 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14997 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
14998 		    ill->ill_name, dlpi_prim_str(prim), err);
14999 		return;
15000 	}
15001 
15002 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15003 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15004 	    dlpi_err_str(dl_err));
15005 }
15006 
15007 /*
15008  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15009  * than DL_UNITDATA_IND messages. If we need to process this message
15010  * exclusively, we call qwriter_ip, in which case we also need to call
15011  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15012  */
15013 void
15014 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15015 {
15016 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15017 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15018 	ill_t		*ill;
15019 
15020 	ip1dbg(("ip_rput_dlpi"));
15021 	ill = (ill_t *)q->q_ptr;
15022 	switch (dloa->dl_primitive) {
15023 	case DL_ERROR_ACK:
15024 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15025 		    "%s (0x%x), unix %u\n", ill->ill_name,
15026 		    dlpi_prim_str(dlea->dl_error_primitive),
15027 		    dlea->dl_error_primitive,
15028 		    dlpi_err_str(dlea->dl_errno),
15029 		    dlea->dl_errno,
15030 		    dlea->dl_unix_errno));
15031 		switch (dlea->dl_error_primitive) {
15032 		case DL_UNBIND_REQ:
15033 			mutex_enter(&ill->ill_lock);
15034 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15035 			cv_signal(&ill->ill_cv);
15036 			mutex_exit(&ill->ill_lock);
15037 			/* FALLTHRU */
15038 		case DL_NOTIFY_REQ:
15039 		case DL_ATTACH_REQ:
15040 		case DL_DETACH_REQ:
15041 		case DL_INFO_REQ:
15042 		case DL_BIND_REQ:
15043 		case DL_ENABMULTI_REQ:
15044 		case DL_PHYS_ADDR_REQ:
15045 		case DL_CAPABILITY_REQ:
15046 		case DL_CONTROL_REQ:
15047 			/*
15048 			 * Refhold the ill to match qwriter_ip which does a
15049 			 * refrele. Since this is on the ill stream we
15050 			 * unconditionally bump up the refcount without
15051 			 * checking for ILL_CAN_LOOKUP
15052 			 */
15053 			ill_refhold(ill);
15054 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15055 			    CUR_OP, B_FALSE);
15056 			return;
15057 		case DL_DISABMULTI_REQ:
15058 			freemsg(mp);	/* Don't want to pass this up */
15059 			return;
15060 		default:
15061 			break;
15062 		}
15063 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15064 		    dlea->dl_errno, dlea->dl_unix_errno);
15065 		freemsg(mp);
15066 		return;
15067 	case DL_INFO_ACK:
15068 	case DL_BIND_ACK:
15069 	case DL_PHYS_ADDR_ACK:
15070 	case DL_NOTIFY_ACK:
15071 	case DL_CAPABILITY_ACK:
15072 	case DL_CONTROL_ACK:
15073 		/*
15074 		 * Refhold the ill to match qwriter_ip which does a refrele
15075 		 * Since this is on the ill stream we unconditionally
15076 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15077 		 */
15078 		ill_refhold(ill);
15079 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15080 		    CUR_OP, B_FALSE);
15081 		return;
15082 	case DL_NOTIFY_IND:
15083 		ill_refhold(ill);
15084 		/*
15085 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15086 		 * relation to the current ioctl in progress (if any). Hence we
15087 		 * pass in NEW_OP in this case.
15088 		 */
15089 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15090 		    NEW_OP, B_FALSE);
15091 		return;
15092 	case DL_OK_ACK:
15093 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15094 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15095 		switch (dloa->dl_correct_primitive) {
15096 		case DL_UNBIND_REQ:
15097 			mutex_enter(&ill->ill_lock);
15098 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15099 			cv_signal(&ill->ill_cv);
15100 			mutex_exit(&ill->ill_lock);
15101 			/* FALLTHRU */
15102 		case DL_ATTACH_REQ:
15103 		case DL_DETACH_REQ:
15104 			/*
15105 			 * Refhold the ill to match qwriter_ip which does a
15106 			 * refrele. Since this is on the ill stream we
15107 			 * unconditionally bump up the refcount
15108 			 */
15109 			ill_refhold(ill);
15110 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15111 			    CUR_OP, B_FALSE);
15112 			return;
15113 		case DL_ENABMULTI_REQ:
15114 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15115 				ill->ill_dlpi_multicast_state = IDS_OK;
15116 			break;
15117 
15118 		}
15119 		break;
15120 	default:
15121 		break;
15122 	}
15123 	freemsg(mp);
15124 }
15125 
15126 /*
15127  * Handling of DLPI messages that require exclusive access to the ipsq.
15128  *
15129  * Need to do ill_pending_mp_release on ioctl completion, which could
15130  * happen here. (along with mi_copy_done)
15131  */
15132 /* ARGSUSED */
15133 static void
15134 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15135 {
15136 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15137 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15138 	int		err = 0;
15139 	ill_t		*ill;
15140 	ipif_t		*ipif = NULL;
15141 	mblk_t		*mp1 = NULL;
15142 	conn_t		*connp = NULL;
15143 	t_uscalar_t	physaddr_req;
15144 	mblk_t		*mp_hw;
15145 	union DL_primitives *dlp;
15146 	boolean_t	success;
15147 	boolean_t	ioctl_aborted = B_FALSE;
15148 	boolean_t	log = B_TRUE;
15149 	hook_nic_event_t	*info;
15150 
15151 	ip1dbg(("ip_rput_dlpi_writer .."));
15152 	ill = (ill_t *)q->q_ptr;
15153 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15154 
15155 	ASSERT(IAM_WRITER_ILL(ill));
15156 
15157 	/*
15158 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15159 	 * both are null or non-null. However we can assert that only
15160 	 * after grabbing the ipsq_lock. So we don't make any assertion
15161 	 * here and in other places in the code.
15162 	 */
15163 	ipif = ipsq->ipsq_pending_ipif;
15164 	/*
15165 	 * The current ioctl could have been aborted by the user and a new
15166 	 * ioctl to bring up another ill could have started. We could still
15167 	 * get a response from the driver later.
15168 	 */
15169 	if (ipif != NULL && ipif->ipif_ill != ill)
15170 		ioctl_aborted = B_TRUE;
15171 
15172 	switch (dloa->dl_primitive) {
15173 	case DL_ERROR_ACK:
15174 		switch (dlea->dl_error_primitive) {
15175 		case DL_UNBIND_REQ:
15176 		case DL_ATTACH_REQ:
15177 		case DL_DETACH_REQ:
15178 		case DL_INFO_REQ:
15179 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15180 			break;
15181 		case DL_NOTIFY_REQ:
15182 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15183 			log = B_FALSE;
15184 			break;
15185 		case DL_PHYS_ADDR_REQ:
15186 			/*
15187 			 * For IPv6 only, there are two additional
15188 			 * phys_addr_req's sent to the driver to get the
15189 			 * IPv6 token and lla. This allows IP to acquire
15190 			 * the hardware address format for a given interface
15191 			 * without having built in knowledge of the hardware
15192 			 * address. ill_phys_addr_pend keeps track of the last
15193 			 * DL_PAR sent so we know which response we are
15194 			 * dealing with. ill_dlpi_done will update
15195 			 * ill_phys_addr_pend when it sends the next req.
15196 			 * We don't complete the IOCTL until all three DL_PARs
15197 			 * have been attempted, so set *_len to 0 and break.
15198 			 */
15199 			physaddr_req = ill->ill_phys_addr_pend;
15200 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15201 			if (physaddr_req == DL_IPV6_TOKEN) {
15202 				ill->ill_token_length = 0;
15203 				log = B_FALSE;
15204 				break;
15205 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15206 				ill->ill_nd_lla_len = 0;
15207 				log = B_FALSE;
15208 				break;
15209 			}
15210 			/*
15211 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15212 			 * We presumably have an IOCTL hanging out waiting
15213 			 * for completion. Find it and complete the IOCTL
15214 			 * with the error noted.
15215 			 * However, ill_dl_phys was called on an ill queue
15216 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15217 			 * set. But the ioctl is known to be pending on ill_wq.
15218 			 */
15219 			if (!ill->ill_ifname_pending)
15220 				break;
15221 			ill->ill_ifname_pending = 0;
15222 			if (!ioctl_aborted)
15223 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15224 			if (mp1 != NULL) {
15225 				/*
15226 				 * This operation (SIOCSLIFNAME) must have
15227 				 * happened on the ill. Assert there is no conn
15228 				 */
15229 				ASSERT(connp == NULL);
15230 				q = ill->ill_wq;
15231 			}
15232 			break;
15233 		case DL_BIND_REQ:
15234 			ill_dlpi_done(ill, DL_BIND_REQ);
15235 			if (ill->ill_ifname_pending)
15236 				break;
15237 			/*
15238 			 * Something went wrong with the bind.  We presumably
15239 			 * have an IOCTL hanging out waiting for completion.
15240 			 * Find it, take down the interface that was coming
15241 			 * up, and complete the IOCTL with the error noted.
15242 			 */
15243 			if (!ioctl_aborted)
15244 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15245 			if (mp1 != NULL) {
15246 				/*
15247 				 * This operation (SIOCSLIFFLAGS) must have
15248 				 * happened from a conn.
15249 				 */
15250 				ASSERT(connp != NULL);
15251 				q = CONNP_TO_WQ(connp);
15252 				if (ill->ill_move_in_progress) {
15253 					ILL_CLEAR_MOVE(ill);
15254 				}
15255 				(void) ipif_down(ipif, NULL, NULL);
15256 				/* error is set below the switch */
15257 			}
15258 			break;
15259 		case DL_ENABMULTI_REQ:
15260 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15261 
15262 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15263 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15264 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15265 				ipif_t *ipif;
15266 
15267 				log = B_FALSE;
15268 				printf("ip: joining multicasts failed (%d)"
15269 				    " on %s - will use link layer "
15270 				    "broadcasts for multicast\n",
15271 				    dlea->dl_errno, ill->ill_name);
15272 
15273 				/*
15274 				 * Set up the multicast mapping alone.
15275 				 * writer, so ok to access ill->ill_ipif
15276 				 * without any lock.
15277 				 */
15278 				ipif = ill->ill_ipif;
15279 				mutex_enter(&ill->ill_phyint->phyint_lock);
15280 				ill->ill_phyint->phyint_flags |=
15281 				    PHYI_MULTI_BCAST;
15282 				mutex_exit(&ill->ill_phyint->phyint_lock);
15283 
15284 				if (!ill->ill_isv6) {
15285 					(void) ipif_arp_setup_multicast(ipif,
15286 					    NULL);
15287 				} else {
15288 					(void) ipif_ndp_setup_multicast(ipif,
15289 					    NULL);
15290 				}
15291 			}
15292 			freemsg(mp);	/* Don't want to pass this up */
15293 			return;
15294 		case DL_CAPABILITY_REQ:
15295 		case DL_CONTROL_REQ:
15296 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15297 			    "DL_CAPABILITY/CONTROL REQ\n"));
15298 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15299 			ill->ill_dlpi_capab_state = IDS_FAILED;
15300 			freemsg(mp);
15301 			return;
15302 		}
15303 		/*
15304 		 * Note the error for IOCTL completion (mp1 is set when
15305 		 * ready to complete ioctl). If ill_ifname_pending_err is
15306 		 * set, an error occured during plumbing (ill_ifname_pending),
15307 		 * so we want to report that error.
15308 		 *
15309 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15310 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15311 		 * expected to get errack'd if the driver doesn't support
15312 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15313 		 * if these error conditions are encountered.
15314 		 */
15315 		if (mp1 != NULL) {
15316 			if (ill->ill_ifname_pending_err != 0)  {
15317 				err = ill->ill_ifname_pending_err;
15318 				ill->ill_ifname_pending_err = 0;
15319 			} else {
15320 				err = dlea->dl_unix_errno ?
15321 				    dlea->dl_unix_errno : ENXIO;
15322 			}
15323 		/*
15324 		 * If we're plumbing an interface and an error hasn't already
15325 		 * been saved, set ill_ifname_pending_err to the error passed
15326 		 * up. Ignore the error if log is B_FALSE (see comment above).
15327 		 */
15328 		} else if (log && ill->ill_ifname_pending &&
15329 		    ill->ill_ifname_pending_err == 0) {
15330 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15331 			dlea->dl_unix_errno : ENXIO;
15332 		}
15333 
15334 		if (log)
15335 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15336 			    dlea->dl_errno, dlea->dl_unix_errno);
15337 		break;
15338 	case DL_CAPABILITY_ACK: {
15339 		boolean_t reneg_flag = B_FALSE;
15340 		/* Call a routine to handle this one. */
15341 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15342 		/*
15343 		 * Check if the ACK is due to renegotiation case since we
15344 		 * will need to send a new CAPABILITY_REQ later.
15345 		 */
15346 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15347 			/* This is the ack for a renogiation case */
15348 			reneg_flag = B_TRUE;
15349 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15350 		}
15351 		ill_capability_ack(ill, mp);
15352 		if (reneg_flag)
15353 			ill_capability_probe(ill);
15354 		break;
15355 	}
15356 	case DL_CONTROL_ACK:
15357 		/* We treat all of these as "fire and forget" */
15358 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15359 		break;
15360 	case DL_INFO_ACK:
15361 		/* Call a routine to handle this one. */
15362 		ill_dlpi_done(ill, DL_INFO_REQ);
15363 		ip_ll_subnet_defaults(ill, mp);
15364 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15365 		return;
15366 	case DL_BIND_ACK:
15367 		/*
15368 		 * We should have an IOCTL waiting on this unless
15369 		 * sent by ill_dl_phys, in which case just return
15370 		 */
15371 		ill_dlpi_done(ill, DL_BIND_REQ);
15372 		if (ill->ill_ifname_pending)
15373 			break;
15374 
15375 		if (!ioctl_aborted)
15376 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15377 		if (mp1 == NULL)
15378 			break;
15379 		ASSERT(connp != NULL);
15380 		q = CONNP_TO_WQ(connp);
15381 
15382 		/*
15383 		 * We are exclusive. So nothing can change even after
15384 		 * we get the pending mp. If need be we can put it back
15385 		 * and restart, as in calling ipif_arp_up()  below.
15386 		 */
15387 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15388 
15389 		mutex_enter(&ill->ill_lock);
15390 
15391 		ill->ill_dl_up = 1;
15392 
15393 		if ((info = ill->ill_nic_event_info) != NULL) {
15394 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15395 			    "attached for %s\n", info->hne_event,
15396 			    ill->ill_name));
15397 			if (info->hne_data != NULL)
15398 				kmem_free(info->hne_data, info->hne_datalen);
15399 			kmem_free(info, sizeof (hook_nic_event_t));
15400 		}
15401 
15402 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15403 		if (info != NULL) {
15404 			info->hne_nic = ill->ill_phyint->phyint_ifindex;
15405 			info->hne_lif = 0;
15406 			info->hne_event = NE_UP;
15407 			info->hne_data = NULL;
15408 			info->hne_datalen = 0;
15409 			info->hne_family = ill->ill_isv6 ? ipv6 : ipv4;
15410 		} else
15411 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15412 			    "event information for %s (ENOMEM)\n",
15413 			    ill->ill_name));
15414 
15415 		ill->ill_nic_event_info = info;
15416 
15417 		mutex_exit(&ill->ill_lock);
15418 
15419 		/*
15420 		 * Now bring up the resolver; when that is complete, we'll
15421 		 * create IREs.  Note that we intentionally mirror what
15422 		 * ipif_up() would have done, because we got here by way of
15423 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15424 		 */
15425 		if (ill->ill_isv6) {
15426 			/*
15427 			 * v6 interfaces.
15428 			 * Unlike ARP which has to do another bind
15429 			 * and attach, once we get here we are
15430 			 * done with NDP. Except in the case of
15431 			 * ILLF_XRESOLV, in which case we send an
15432 			 * AR_INTERFACE_UP to the external resolver.
15433 			 * If all goes well, the ioctl will complete
15434 			 * in ip_rput(). If there's an error, we
15435 			 * complete it here.
15436 			 */
15437 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15438 			    B_FALSE);
15439 			if (err == 0) {
15440 				if (ill->ill_flags & ILLF_XRESOLV) {
15441 					mutex_enter(&connp->conn_lock);
15442 					mutex_enter(&ill->ill_lock);
15443 					success = ipsq_pending_mp_add(
15444 					    connp, ipif, q, mp1, 0);
15445 					mutex_exit(&ill->ill_lock);
15446 					mutex_exit(&connp->conn_lock);
15447 					if (success) {
15448 						err = ipif_resolver_up(ipif,
15449 						    Res_act_initial);
15450 						if (err == EINPROGRESS) {
15451 							freemsg(mp);
15452 							return;
15453 						}
15454 						ASSERT(err != 0);
15455 						mp1 = ipsq_pending_mp_get(ipsq,
15456 						    &connp);
15457 						ASSERT(mp1 != NULL);
15458 					} else {
15459 						/* conn has started closing */
15460 						err = EINTR;
15461 					}
15462 				} else { /* Non XRESOLV interface */
15463 					(void) ipif_resolver_up(ipif,
15464 					    Res_act_initial);
15465 					err = ipif_up_done_v6(ipif);
15466 				}
15467 			}
15468 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15469 			/*
15470 			 * ARP and other v4 external resolvers.
15471 			 * Leave the pending mblk intact so that
15472 			 * the ioctl completes in ip_rput().
15473 			 */
15474 			mutex_enter(&connp->conn_lock);
15475 			mutex_enter(&ill->ill_lock);
15476 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15477 			mutex_exit(&ill->ill_lock);
15478 			mutex_exit(&connp->conn_lock);
15479 			if (success) {
15480 				err = ipif_resolver_up(ipif, Res_act_initial);
15481 				if (err == EINPROGRESS) {
15482 					freemsg(mp);
15483 					return;
15484 				}
15485 				ASSERT(err != 0);
15486 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15487 			} else {
15488 				/* The conn has started closing */
15489 				err = EINTR;
15490 			}
15491 		} else {
15492 			/*
15493 			 * This one is complete. Reply to pending ioctl.
15494 			 */
15495 			(void) ipif_resolver_up(ipif, Res_act_initial);
15496 			err = ipif_up_done(ipif);
15497 		}
15498 
15499 		if ((err == 0) && (ill->ill_up_ipifs)) {
15500 			err = ill_up_ipifs(ill, q, mp1);
15501 			if (err == EINPROGRESS) {
15502 				freemsg(mp);
15503 				return;
15504 			}
15505 		}
15506 
15507 		if (ill->ill_up_ipifs) {
15508 			ill_group_cleanup(ill);
15509 		}
15510 
15511 		break;
15512 	case DL_NOTIFY_IND: {
15513 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15514 		ire_t *ire;
15515 		boolean_t need_ire_walk_v4 = B_FALSE;
15516 		boolean_t need_ire_walk_v6 = B_FALSE;
15517 
15518 		/*
15519 		 * Change the address everywhere we need to.
15520 		 * What we're getting here is a link-level addr or phys addr.
15521 		 * The new addr is at notify + notify->dl_addr_offset
15522 		 * The address length is notify->dl_addr_length;
15523 		 */
15524 		switch (notify->dl_notification) {
15525 		case DL_NOTE_PHYS_ADDR:
15526 			mp_hw = copyb(mp);
15527 			if (mp_hw == NULL) {
15528 				err = ENOMEM;
15529 				break;
15530 			}
15531 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15532 			/*
15533 			 * We currently don't support changing
15534 			 * the token via DL_NOTIFY_IND.
15535 			 * When we do support it, we have to consider
15536 			 * what the implications are with respect to
15537 			 * the token and the link local address.
15538 			 */
15539 			mutex_enter(&ill->ill_lock);
15540 			if (dlp->notify_ind.dl_data ==
15541 			    DL_IPV6_LINK_LAYER_ADDR) {
15542 				if (ill->ill_nd_lla_mp != NULL)
15543 					freemsg(ill->ill_nd_lla_mp);
15544 				ill->ill_nd_lla_mp = mp_hw;
15545 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15546 				    dlp->notify_ind.dl_addr_offset;
15547 				ill->ill_nd_lla_len =
15548 				    dlp->notify_ind.dl_addr_length -
15549 				    ABS(ill->ill_sap_length);
15550 				mutex_exit(&ill->ill_lock);
15551 				break;
15552 			} else if (dlp->notify_ind.dl_data ==
15553 			    DL_CURR_PHYS_ADDR) {
15554 				if (ill->ill_phys_addr_mp != NULL)
15555 					freemsg(ill->ill_phys_addr_mp);
15556 				ill->ill_phys_addr_mp = mp_hw;
15557 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15558 				    dlp->notify_ind.dl_addr_offset;
15559 				ill->ill_phys_addr_length =
15560 				    dlp->notify_ind.dl_addr_length -
15561 				    ABS(ill->ill_sap_length);
15562 				if (ill->ill_isv6 &&
15563 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15564 					if (ill->ill_nd_lla_mp != NULL)
15565 						freemsg(ill->ill_nd_lla_mp);
15566 					ill->ill_nd_lla_mp = copyb(mp_hw);
15567 					ill->ill_nd_lla = (uchar_t *)
15568 					    ill->ill_nd_lla_mp->b_rptr +
15569 					    dlp->notify_ind.dl_addr_offset;
15570 					ill->ill_nd_lla_len =
15571 					    ill->ill_phys_addr_length;
15572 				}
15573 			}
15574 			mutex_exit(&ill->ill_lock);
15575 			/*
15576 			 * Send out gratuitous arp request for our new
15577 			 * hardware address.
15578 			 */
15579 			for (ipif = ill->ill_ipif; ipif != NULL;
15580 			    ipif = ipif->ipif_next) {
15581 				if (!(ipif->ipif_flags & IPIF_UP))
15582 					continue;
15583 				if (ill->ill_isv6) {
15584 					ipif_ndp_down(ipif);
15585 					/*
15586 					 * Set B_TRUE to enable
15587 					 * ipif_ndp_up() to send out
15588 					 * unsolicited advertisements.
15589 					 */
15590 					err = ipif_ndp_up(ipif,
15591 					    &ipif->ipif_v6lcl_addr,
15592 					    B_TRUE);
15593 					if (err) {
15594 						ip1dbg((
15595 						    "ip_rput_dlpi_writer: "
15596 						    "Failed to update ndp "
15597 						    "err %d\n", err));
15598 					}
15599 				} else {
15600 					/*
15601 					 * IPv4 ARP case
15602 					 *
15603 					 * Set Res_act_move, as we only want
15604 					 * ipif_resolver_up to send an
15605 					 * AR_ENTRY_ADD request up to
15606 					 * ARP.
15607 					 */
15608 					err = ipif_resolver_up(ipif,
15609 					    Res_act_move);
15610 					if (err) {
15611 						ip1dbg((
15612 						    "ip_rput_dlpi_writer: "
15613 						    "Failed to update arp "
15614 						    "err %d\n", err));
15615 					}
15616 				}
15617 			}
15618 			/*
15619 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15620 			 * case so that all old fastpath information can be
15621 			 * purged from IRE caches.
15622 			 */
15623 		/* FALLTHRU */
15624 		case DL_NOTE_FASTPATH_FLUSH:
15625 			/*
15626 			 * Any fastpath probe sent henceforth will get the
15627 			 * new fp mp. So we first delete any ires that are
15628 			 * waiting for the fastpath. Then walk all ires and
15629 			 * delete the ire or delete the fp mp. In the case of
15630 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15631 			 * recreate the ire's without going through a complex
15632 			 * ipif up/down dance. So we don't delete the ire
15633 			 * itself, but just the nce_fp_mp for these 2 ire's
15634 			 * In the case of the other ire's we delete the ire's
15635 			 * themselves. Access to nce_fp_mp is completely
15636 			 * protected by ire_lock for IRE_MIPRTUN and
15637 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15638 			 * other cases for performance.
15639 			 */
15640 			if (ill->ill_isv6) {
15641 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15642 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15643 				    NULL);
15644 			} else {
15645 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15646 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15647 				    IRE_CACHE | IRE_BROADCAST,
15648 				    ire_fastpath_flush, NULL, ill);
15649 				mutex_enter(&ire_mrtun_lock);
15650 				if (ire_mrtun_count != 0) {
15651 					mutex_exit(&ire_mrtun_lock);
15652 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15653 					    IRE_MIPRTUN, ire_fastpath_flush,
15654 					    NULL, ill);
15655 				} else {
15656 					mutex_exit(&ire_mrtun_lock);
15657 				}
15658 			}
15659 			break;
15660 		case DL_NOTE_SDU_SIZE:
15661 			/*
15662 			 * Change the MTU size of the interface, of all
15663 			 * attached ipif's, and of all relevant ire's.  The
15664 			 * new value's a uint32_t at notify->dl_data.
15665 			 * Mtu change Vs. new ire creation - protocol below.
15666 			 *
15667 			 * a Mark the ipif as IPIF_CHANGING.
15668 			 * b Set the new mtu in the ipif.
15669 			 * c Change the ire_max_frag on all affected ires
15670 			 * d Unmark the IPIF_CHANGING
15671 			 *
15672 			 * To see how the protocol works, assume an interface
15673 			 * route is also being added simultaneously by
15674 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15675 			 * the ire. If the ire is created before step a,
15676 			 * it will be cleaned up by step c. If the ire is
15677 			 * created after step d, it will see the new value of
15678 			 * ipif_mtu. Any attempt to create the ire between
15679 			 * steps a to d will fail because of the IPIF_CHANGING
15680 			 * flag. Note that ire_create() is passed a pointer to
15681 			 * the ipif_mtu, and not the value. During ire_add
15682 			 * under the bucket lock, the ire_max_frag of the
15683 			 * new ire being created is set from the ipif/ire from
15684 			 * which it is being derived.
15685 			 */
15686 			mutex_enter(&ill->ill_lock);
15687 			ill->ill_max_frag = (uint_t)notify->dl_data;
15688 
15689 			/*
15690 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15691 			 * leave it alone
15692 			 */
15693 			if (ill->ill_mtu_userspecified) {
15694 				mutex_exit(&ill->ill_lock);
15695 				break;
15696 			}
15697 			ill->ill_max_mtu = ill->ill_max_frag;
15698 			if (ill->ill_isv6) {
15699 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15700 					ill->ill_max_mtu = IPV6_MIN_MTU;
15701 			} else {
15702 				if (ill->ill_max_mtu < IP_MIN_MTU)
15703 					ill->ill_max_mtu = IP_MIN_MTU;
15704 			}
15705 			for (ipif = ill->ill_ipif; ipif != NULL;
15706 			    ipif = ipif->ipif_next) {
15707 				/*
15708 				 * Don't override the mtu if the user
15709 				 * has explicitly set it.
15710 				 */
15711 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15712 					continue;
15713 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15714 				if (ipif->ipif_isv6)
15715 					ire = ipif_to_ire_v6(ipif);
15716 				else
15717 					ire = ipif_to_ire(ipif);
15718 				if (ire != NULL) {
15719 					ire->ire_max_frag = ipif->ipif_mtu;
15720 					ire_refrele(ire);
15721 				}
15722 				if (ipif->ipif_flags & IPIF_UP) {
15723 					if (ill->ill_isv6)
15724 						need_ire_walk_v6 = B_TRUE;
15725 					else
15726 						need_ire_walk_v4 = B_TRUE;
15727 				}
15728 			}
15729 			mutex_exit(&ill->ill_lock);
15730 			if (need_ire_walk_v4)
15731 				ire_walk_v4(ill_mtu_change, (char *)ill,
15732 				    ALL_ZONES);
15733 			if (need_ire_walk_v6)
15734 				ire_walk_v6(ill_mtu_change, (char *)ill,
15735 				    ALL_ZONES);
15736 			break;
15737 		case DL_NOTE_LINK_UP:
15738 		case DL_NOTE_LINK_DOWN: {
15739 			/*
15740 			 * We are writer. ill / phyint / ipsq assocs stable.
15741 			 * The RUNNING flag reflects the state of the link.
15742 			 */
15743 			phyint_t *phyint = ill->ill_phyint;
15744 			uint64_t new_phyint_flags;
15745 			boolean_t changed = B_FALSE;
15746 			boolean_t went_up;
15747 
15748 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15749 			mutex_enter(&phyint->phyint_lock);
15750 			new_phyint_flags = went_up ?
15751 			    phyint->phyint_flags | PHYI_RUNNING :
15752 			    phyint->phyint_flags & ~PHYI_RUNNING;
15753 			if (new_phyint_flags != phyint->phyint_flags) {
15754 				phyint->phyint_flags = new_phyint_flags;
15755 				changed = B_TRUE;
15756 			}
15757 			mutex_exit(&phyint->phyint_lock);
15758 			/*
15759 			 * ill_restart_dad handles the DAD restart and routing
15760 			 * socket notification logic.
15761 			 */
15762 			if (changed) {
15763 				ill_restart_dad(phyint->phyint_illv4, went_up);
15764 				ill_restart_dad(phyint->phyint_illv6, went_up);
15765 			}
15766 			break;
15767 		}
15768 		case DL_NOTE_PROMISC_ON_PHYS:
15769 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15770 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15771 			mutex_enter(&ill->ill_lock);
15772 			ill->ill_promisc_on_phys = B_TRUE;
15773 			mutex_exit(&ill->ill_lock);
15774 			break;
15775 		case DL_NOTE_PROMISC_OFF_PHYS:
15776 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15777 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15778 			mutex_enter(&ill->ill_lock);
15779 			ill->ill_promisc_on_phys = B_FALSE;
15780 			mutex_exit(&ill->ill_lock);
15781 			break;
15782 		case DL_NOTE_CAPAB_RENEG:
15783 			/*
15784 			 * Something changed on the driver side.
15785 			 * It wants us to renegotiate the capabilities
15786 			 * on this ill. The most likely cause is the
15787 			 * aggregation interface under us where a
15788 			 * port got added or went away.
15789 			 *
15790 			 * We reset the capabilities and set the
15791 			 * state to IDS_RENG so that when the ack
15792 			 * comes back, we can start the
15793 			 * renegotiation process.
15794 			 */
15795 			ill_capability_reset(ill);
15796 			ill->ill_dlpi_capab_state = IDS_RENEG;
15797 			break;
15798 		default:
15799 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15800 			    "type 0x%x for DL_NOTIFY_IND\n",
15801 			    notify->dl_notification));
15802 			break;
15803 		}
15804 
15805 		/*
15806 		 * As this is an asynchronous operation, we
15807 		 * should not call ill_dlpi_done
15808 		 */
15809 		break;
15810 	}
15811 	case DL_NOTIFY_ACK: {
15812 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15813 
15814 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15815 			ill->ill_note_link = 1;
15816 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15817 		break;
15818 	}
15819 	case DL_PHYS_ADDR_ACK: {
15820 		/*
15821 		 * We should have an IOCTL waiting on this when request
15822 		 * sent by ill_dl_phys.
15823 		 * However, ill_dl_phys was called on an ill queue (from
15824 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15825 		 * ioctl is known to be pending on ill_wq.
15826 		 * There are two additional phys_addr_req's sent to the
15827 		 * driver to get the token and lla. ill_phys_addr_pend
15828 		 * keeps track of the last one sent so we know which
15829 		 * response we are dealing with. ill_dlpi_done will
15830 		 * update ill_phys_addr_pend when it sends the next req.
15831 		 * We don't complete the IOCTL until all three DL_PARs
15832 		 * have been attempted.
15833 		 *
15834 		 * We don't need any lock to update ill_nd_lla* fields,
15835 		 * since the ill is not yet up, We grab the lock just
15836 		 * for uniformity with other code that accesses ill_nd_lla.
15837 		 */
15838 		physaddr_req = ill->ill_phys_addr_pend;
15839 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15840 		if (physaddr_req == DL_IPV6_TOKEN ||
15841 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15842 			if (physaddr_req == DL_IPV6_TOKEN) {
15843 				/*
15844 				 * bcopy to low-order bits of ill_token
15845 				 *
15846 				 * XXX Temporary hack - currently,
15847 				 * all known tokens are 64 bits,
15848 				 * so I'll cheat for the moment.
15849 				 */
15850 				dlp = (union DL_primitives *)mp->b_rptr;
15851 
15852 				mutex_enter(&ill->ill_lock);
15853 				bcopy((uchar_t *)(mp->b_rptr +
15854 				dlp->physaddr_ack.dl_addr_offset),
15855 				(void *)&ill->ill_token.s6_addr32[2],
15856 				dlp->physaddr_ack.dl_addr_length);
15857 				ill->ill_token_length =
15858 					dlp->physaddr_ack.dl_addr_length;
15859 				mutex_exit(&ill->ill_lock);
15860 			} else {
15861 				ASSERT(ill->ill_nd_lla_mp == NULL);
15862 				mp_hw = copyb(mp);
15863 				if (mp_hw == NULL) {
15864 					err = ENOMEM;
15865 					break;
15866 				}
15867 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15868 				mutex_enter(&ill->ill_lock);
15869 				ill->ill_nd_lla_mp = mp_hw;
15870 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15871 				dlp->physaddr_ack.dl_addr_offset;
15872 				ill->ill_nd_lla_len =
15873 					dlp->physaddr_ack.dl_addr_length;
15874 				mutex_exit(&ill->ill_lock);
15875 			}
15876 			break;
15877 		}
15878 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15879 		ASSERT(ill->ill_phys_addr_mp == NULL);
15880 		if (!ill->ill_ifname_pending)
15881 			break;
15882 		ill->ill_ifname_pending = 0;
15883 		if (!ioctl_aborted)
15884 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15885 		if (mp1 != NULL) {
15886 			ASSERT(connp == NULL);
15887 			q = ill->ill_wq;
15888 		}
15889 		/*
15890 		 * If any error acks received during the plumbing sequence,
15891 		 * ill_ifname_pending_err will be set. Break out and send up
15892 		 * the error to the pending ioctl.
15893 		 */
15894 		if (ill->ill_ifname_pending_err != 0) {
15895 			err = ill->ill_ifname_pending_err;
15896 			ill->ill_ifname_pending_err = 0;
15897 			break;
15898 		}
15899 		/*
15900 		 * Get the interface token.  If the zeroth interface
15901 		 * address is zero then set the address to the link local
15902 		 * address
15903 		 */
15904 		mp_hw = copyb(mp);
15905 		if (mp_hw == NULL) {
15906 			err = ENOMEM;
15907 			break;
15908 		}
15909 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15910 		ill->ill_phys_addr_mp = mp_hw;
15911 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15912 				dlp->physaddr_ack.dl_addr_offset;
15913 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15914 		    ill->ill_phys_addr_length == 0 ||
15915 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15916 			/*
15917 			 * Compatibility: atun driver returns a length of 0.
15918 			 * ipdptp has an ill_phys_addr_length of zero(from
15919 			 * DL_BIND_ACK) but a non-zero length here.
15920 			 * ipd has an ill_phys_addr_length of 4(from
15921 			 * DL_BIND_ACK) but a non-zero length here.
15922 			 */
15923 			ill->ill_phys_addr = NULL;
15924 		} else if (dlp->physaddr_ack.dl_addr_length !=
15925 		    ill->ill_phys_addr_length) {
15926 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15927 			    "Address length mismatch %d %d\n",
15928 			    dlp->physaddr_ack.dl_addr_length,
15929 			    ill->ill_phys_addr_length));
15930 			err = EINVAL;
15931 			break;
15932 		}
15933 		mutex_enter(&ill->ill_lock);
15934 		if (ill->ill_nd_lla_mp == NULL) {
15935 			ill->ill_nd_lla_mp = copyb(mp_hw);
15936 			if (ill->ill_nd_lla_mp == NULL) {
15937 				err = ENOMEM;
15938 				mutex_exit(&ill->ill_lock);
15939 				break;
15940 			}
15941 			ill->ill_nd_lla =
15942 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15943 			    dlp->physaddr_ack.dl_addr_offset;
15944 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15945 		}
15946 		mutex_exit(&ill->ill_lock);
15947 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15948 			(void) ill_setdefaulttoken(ill);
15949 
15950 		/*
15951 		 * If the ill zero interface has a zero address assign
15952 		 * it the proper link local address.
15953 		 */
15954 		ASSERT(ill->ill_ipif->ipif_id == 0);
15955 		if (ipif != NULL &&
15956 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15957 			(void) ipif_setlinklocal(ipif);
15958 		break;
15959 	}
15960 	case DL_OK_ACK:
15961 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15962 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15963 		    dloa->dl_correct_primitive));
15964 		switch (dloa->dl_correct_primitive) {
15965 		case DL_UNBIND_REQ:
15966 		case DL_ATTACH_REQ:
15967 		case DL_DETACH_REQ:
15968 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15969 			break;
15970 		}
15971 		break;
15972 	default:
15973 		break;
15974 	}
15975 
15976 	freemsg(mp);
15977 	if (mp1) {
15978 		struct iocblk *iocp;
15979 		int mode;
15980 
15981 		/*
15982 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15983 		 * SIOCSLIFNAME do a copyout.
15984 		 */
15985 		iocp = (struct iocblk *)mp1->b_rptr;
15986 
15987 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
15988 		    iocp->ioc_cmd == SIOCSLIFNAME)
15989 			mode = COPYOUT;
15990 		else
15991 			mode = NO_COPYOUT;
15992 		/*
15993 		 * The ioctl must complete now without EINPROGRESS
15994 		 * since ipsq_pending_mp_get has removed the ioctl mblk
15995 		 * from ipsq_pending_mp. Otherwise the ioctl will be
15996 		 * stuck for ever in the ipsq.
15997 		 */
15998 		ASSERT(err != EINPROGRESS);
15999 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
16000 
16001 	}
16002 }
16003 
16004 /*
16005  * ip_rput_other is called by ip_rput to handle messages modifying the global
16006  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16007  */
16008 /* ARGSUSED */
16009 void
16010 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16011 {
16012 	ill_t		*ill;
16013 	struct iocblk	*iocp;
16014 	mblk_t		*mp1;
16015 	conn_t		*connp = NULL;
16016 
16017 	ip1dbg(("ip_rput_other "));
16018 	ill = (ill_t *)q->q_ptr;
16019 	/*
16020 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16021 	 * in which case ipsq is NULL.
16022 	 */
16023 	if (ipsq != NULL) {
16024 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16025 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16026 	}
16027 
16028 	switch (mp->b_datap->db_type) {
16029 	case M_ERROR:
16030 	case M_HANGUP:
16031 		/*
16032 		 * The device has a problem.  We force the ILL down.  It can
16033 		 * be brought up again manually using SIOCSIFFLAGS (via
16034 		 * ifconfig or equivalent).
16035 		 */
16036 		ASSERT(ipsq != NULL);
16037 		if (mp->b_rptr < mp->b_wptr)
16038 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16039 		if (ill->ill_error == 0)
16040 			ill->ill_error = ENXIO;
16041 		if (!ill_down_start(q, mp))
16042 			return;
16043 		ipif_all_down_tail(ipsq, q, mp, NULL);
16044 		break;
16045 	case M_IOCACK:
16046 		iocp = (struct iocblk *)mp->b_rptr;
16047 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16048 		switch (iocp->ioc_cmd) {
16049 		case SIOCSTUNPARAM:
16050 		case OSIOCSTUNPARAM:
16051 			ASSERT(ipsq != NULL);
16052 			/*
16053 			 * Finish socket ioctl passed through to tun.
16054 			 * We should have an IOCTL waiting on this.
16055 			 */
16056 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16057 			if (ill->ill_isv6) {
16058 				struct iftun_req *ta;
16059 
16060 				/*
16061 				 * if a source or destination is
16062 				 * being set, try and set the link
16063 				 * local address for the tunnel
16064 				 */
16065 				ta = (struct iftun_req *)mp->b_cont->
16066 				    b_cont->b_rptr;
16067 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16068 					ipif_set_tun_llink(ill, ta);
16069 				}
16070 
16071 			}
16072 			if (mp1 != NULL) {
16073 				/*
16074 				 * Now copy back the b_next/b_prev used by
16075 				 * mi code for the mi_copy* functions.
16076 				 * See ip_sioctl_tunparam() for the reason.
16077 				 * Also protect against missing b_cont.
16078 				 */
16079 				if (mp->b_cont != NULL) {
16080 					mp->b_cont->b_next =
16081 					    mp1->b_cont->b_next;
16082 					mp->b_cont->b_prev =
16083 					    mp1->b_cont->b_prev;
16084 				}
16085 				inet_freemsg(mp1);
16086 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16087 				ASSERT(connp != NULL);
16088 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16089 				    iocp->ioc_error, NO_COPYOUT,
16090 				    ipsq->ipsq_current_ipif, ipsq);
16091 			} else {
16092 				ASSERT(connp == NULL);
16093 				putnext(q, mp);
16094 			}
16095 			break;
16096 		case SIOCGTUNPARAM:
16097 		case OSIOCGTUNPARAM:
16098 			/*
16099 			 * This is really M_IOCDATA from the tunnel driver.
16100 			 * convert back and complete the ioctl.
16101 			 * We should have an IOCTL waiting on this.
16102 			 */
16103 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16104 			if (mp1) {
16105 				/*
16106 				 * Now copy back the b_next/b_prev used by
16107 				 * mi code for the mi_copy* functions.
16108 				 * See ip_sioctl_tunparam() for the reason.
16109 				 * Also protect against missing b_cont.
16110 				 */
16111 				if (mp->b_cont != NULL) {
16112 					mp->b_cont->b_next =
16113 					    mp1->b_cont->b_next;
16114 					mp->b_cont->b_prev =
16115 					    mp1->b_cont->b_prev;
16116 				}
16117 				inet_freemsg(mp1);
16118 				if (iocp->ioc_error == 0)
16119 					mp->b_datap->db_type = M_IOCDATA;
16120 				ASSERT(connp != NULL);
16121 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16122 				    iocp->ioc_error, COPYOUT, NULL, NULL);
16123 			} else {
16124 				ASSERT(connp == NULL);
16125 				putnext(q, mp);
16126 			}
16127 			break;
16128 		default:
16129 			break;
16130 		}
16131 		break;
16132 	case M_IOCNAK:
16133 		iocp = (struct iocblk *)mp->b_rptr;
16134 
16135 		switch (iocp->ioc_cmd) {
16136 		int mode;
16137 		ipif_t	*ipif;
16138 
16139 		case DL_IOC_HDR_INFO:
16140 			/*
16141 			 * If this was the first attempt turn of the
16142 			 * fastpath probing.
16143 			 */
16144 			mutex_enter(&ill->ill_lock);
16145 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16146 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16147 				mutex_exit(&ill->ill_lock);
16148 				ill_fastpath_nack(ill);
16149 				ip1dbg(("ip_rput: DLPI fastpath off on "
16150 				    "interface %s\n",
16151 				    ill->ill_name));
16152 			} else {
16153 				mutex_exit(&ill->ill_lock);
16154 			}
16155 			freemsg(mp);
16156 			break;
16157 		case SIOCSTUNPARAM:
16158 		case OSIOCSTUNPARAM:
16159 			ASSERT(ipsq != NULL);
16160 			/*
16161 			 * Finish socket ioctl passed through to tun
16162 			 * We should have an IOCTL waiting on this.
16163 			 */
16164 			/* FALLTHRU */
16165 		case SIOCGTUNPARAM:
16166 		case OSIOCGTUNPARAM:
16167 			/*
16168 			 * This is really M_IOCDATA from the tunnel driver.
16169 			 * convert back and complete the ioctl.
16170 			 * We should have an IOCTL waiting on this.
16171 			 */
16172 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16173 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16174 				mp1 = ill_pending_mp_get(ill, &connp,
16175 				    iocp->ioc_id);
16176 				mode = COPYOUT;
16177 				ipsq = NULL;
16178 				ipif = NULL;
16179 			} else {
16180 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16181 				mode = NO_COPYOUT;
16182 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16183 				ipif = ipsq->ipsq_current_ipif;
16184 			}
16185 			if (mp1 != NULL) {
16186 				/*
16187 				 * Now copy back the b_next/b_prev used by
16188 				 * mi code for the mi_copy* functions.
16189 				 * See ip_sioctl_tunparam() for the reason.
16190 				 * Also protect against missing b_cont.
16191 				 */
16192 				if (mp->b_cont != NULL) {
16193 					mp->b_cont->b_next =
16194 					    mp1->b_cont->b_next;
16195 					mp->b_cont->b_prev =
16196 					    mp1->b_cont->b_prev;
16197 				}
16198 				inet_freemsg(mp1);
16199 				if (iocp->ioc_error == 0)
16200 					iocp->ioc_error = EINVAL;
16201 				ASSERT(connp != NULL);
16202 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16203 				    iocp->ioc_error, mode, ipif, ipsq);
16204 			} else {
16205 				ASSERT(connp == NULL);
16206 				putnext(q, mp);
16207 			}
16208 			break;
16209 		default:
16210 			break;
16211 		}
16212 	default:
16213 		break;
16214 	}
16215 }
16216 
16217 /*
16218  * NOTE : This function does not ire_refrele the ire argument passed in.
16219  *
16220  * IPQoS notes
16221  * IP policy is invoked twice for a forwarded packet, once on the read side
16222  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16223  * enabled. An additional parameter, in_ill, has been added for this purpose.
16224  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16225  * because ip_mroute drops this information.
16226  *
16227  */
16228 void
16229 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16230 {
16231 	uint32_t	pkt_len;
16232 	queue_t	*q;
16233 	uint32_t	sum;
16234 #define	rptr	((uchar_t *)ipha)
16235 	uint32_t	max_frag;
16236 	uint32_t	ill_index;
16237 	ill_t		*out_ill;
16238 
16239 	/* Get the ill_index of the incoming ILL */
16240 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16241 
16242 	/* Initiate Read side IPPF processing */
16243 	if (IPP_ENABLED(IPP_FWD_IN)) {
16244 		ip_process(IPP_FWD_IN, &mp, ill_index);
16245 		if (mp == NULL) {
16246 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16247 			    "during IPPF processing\n"));
16248 			return;
16249 		}
16250 	}
16251 
16252 	pkt_len = ntohs(ipha->ipha_length);
16253 
16254 	/* Adjust the checksum to reflect the ttl decrement. */
16255 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16256 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16257 
16258 	if (ipha->ipha_ttl-- <= 1) {
16259 		if (ip_csum_hdr(ipha)) {
16260 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16261 			goto drop_pkt;
16262 		}
16263 		/*
16264 		 * Note: ire_stq this will be NULL for multicast
16265 		 * datagrams using the long path through arp (the IRE
16266 		 * is not an IRE_CACHE). This should not cause
16267 		 * problems since we don't generate ICMP errors for
16268 		 * multicast packets.
16269 		 */
16270 		q = ire->ire_stq;
16271 		if (q != NULL) {
16272 			/* Sent by forwarding path, and router is global zone */
16273 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16274 			    GLOBAL_ZONEID);
16275 		} else
16276 			freemsg(mp);
16277 		return;
16278 	}
16279 
16280 	/*
16281 	 * Don't forward if the interface is down
16282 	 */
16283 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16284 		BUMP_MIB(&ip_mib, ipInDiscards);
16285 		ip2dbg(("ip_rput_forward:interface is down\n"));
16286 		goto drop_pkt;
16287 	}
16288 
16289 	/* Get the ill_index of the outgoing ILL */
16290 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16291 
16292 	out_ill = ire->ire_ipif->ipif_ill;
16293 
16294 	DTRACE_PROBE4(ip4__forwarding__start,
16295 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16296 
16297 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
16298 	    in_ill, out_ill, ipha, mp, mp);
16299 
16300 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16301 
16302 	if (mp == NULL)
16303 		return;
16304 	pkt_len = ntohs(ipha->ipha_length);
16305 
16306 	if (is_system_labeled()) {
16307 		mblk_t *mp1;
16308 
16309 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16310 			BUMP_MIB(&ip_mib, ipForwProhibits);
16311 			goto drop_pkt;
16312 		}
16313 		/* Size may have changed */
16314 		mp = mp1;
16315 		ipha = (ipha_t *)mp->b_rptr;
16316 		pkt_len = ntohs(ipha->ipha_length);
16317 	}
16318 
16319 	/* Check if there are options to update */
16320 	if (!IS_SIMPLE_IPH(ipha)) {
16321 		if (ip_csum_hdr(ipha)) {
16322 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16323 			goto drop_pkt;
16324 		}
16325 		if (ip_rput_forward_options(mp, ipha, ire)) {
16326 			return;
16327 		}
16328 
16329 		ipha->ipha_hdr_checksum = 0;
16330 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16331 	}
16332 	max_frag = ire->ire_max_frag;
16333 	if (pkt_len > max_frag) {
16334 		/*
16335 		 * It needs fragging on its way out.  We haven't
16336 		 * verified the header checksum yet.  Since we
16337 		 * are going to put a surely good checksum in the
16338 		 * outgoing header, we have to make sure that it
16339 		 * was good coming in.
16340 		 */
16341 		if (ip_csum_hdr(ipha)) {
16342 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16343 			goto drop_pkt;
16344 		}
16345 		/* Initiate Write side IPPF processing */
16346 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16347 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16348 			if (mp == NULL) {
16349 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16350 				    " during IPPF processing\n"));
16351 				return;
16352 			}
16353 		}
16354 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
16355 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16356 		return;
16357 	}
16358 
16359 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16360 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16361 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
16362 	    NULL, out_ill, ipha, mp, mp);
16363 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16364 	if (mp == NULL)
16365 		return;
16366 
16367 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16368 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16369 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16370 	/* ip_xmit_v4 always consumes the packet */
16371 	return;
16372 
16373 drop_pkt:;
16374 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16375 	freemsg(mp);
16376 #undef	rptr
16377 }
16378 
16379 void
16380 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16381 {
16382 	ire_t	*ire;
16383 
16384 	ASSERT(!ipif->ipif_isv6);
16385 	/*
16386 	 * Find an IRE which matches the destination and the outgoing
16387 	 * queue in the cache table. All we need is an IRE_CACHE which
16388 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16389 	 * then it is enough to have some IRE_CACHE in the group.
16390 	 */
16391 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16392 		dst = ipif->ipif_pp_dst_addr;
16393 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16394 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16395 	if (ire == NULL) {
16396 		/*
16397 		 * Mark this packet to make it be delivered to
16398 		 * ip_rput_forward after the new ire has been
16399 		 * created.
16400 		 */
16401 		mp->b_prev = NULL;
16402 		mp->b_next = mp;
16403 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16404 		    NULL, 0, GLOBAL_ZONEID);
16405 	} else {
16406 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16407 		IRE_REFRELE(ire);
16408 	}
16409 }
16410 
16411 /* Update any source route, record route or timestamp options */
16412 static int
16413 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16414 {
16415 	ipoptp_t	opts;
16416 	uchar_t		*opt;
16417 	uint8_t		optval;
16418 	uint8_t		optlen;
16419 	ipaddr_t	dst;
16420 	uint32_t	ts;
16421 	ire_t		*dst_ire = NULL;
16422 	ire_t		*tmp_ire = NULL;
16423 	timestruc_t	now;
16424 
16425 	ip2dbg(("ip_rput_forward_options\n"));
16426 	dst = ipha->ipha_dst;
16427 	for (optval = ipoptp_first(&opts, ipha);
16428 	    optval != IPOPT_EOL;
16429 	    optval = ipoptp_next(&opts)) {
16430 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16431 		opt = opts.ipoptp_cur;
16432 		optlen = opts.ipoptp_len;
16433 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16434 		    optval, opts.ipoptp_len));
16435 		switch (optval) {
16436 			uint32_t off;
16437 		case IPOPT_SSRR:
16438 		case IPOPT_LSRR:
16439 			/* Check if adminstratively disabled */
16440 			if (!ip_forward_src_routed) {
16441 				BUMP_MIB(&ip_mib, ipForwProhibits);
16442 				if (ire->ire_stq != NULL) {
16443 					/*
16444 					 * Sent by forwarding path, and router
16445 					 * is global zone
16446 					 */
16447 					icmp_unreachable(ire->ire_stq, mp,
16448 					    ICMP_SOURCE_ROUTE_FAILED,
16449 					    GLOBAL_ZONEID);
16450 				} else {
16451 					ip0dbg(("ip_rput_forward_options: "
16452 					    "unable to send unreach\n"));
16453 					freemsg(mp);
16454 				}
16455 				return (-1);
16456 			}
16457 
16458 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16459 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16460 			if (dst_ire == NULL) {
16461 				/*
16462 				 * Must be partial since ip_rput_options
16463 				 * checked for strict.
16464 				 */
16465 				break;
16466 			}
16467 			off = opt[IPOPT_OFFSET];
16468 			off--;
16469 		redo_srr:
16470 			if (optlen < IP_ADDR_LEN ||
16471 			    off > optlen - IP_ADDR_LEN) {
16472 				/* End of source route */
16473 				ip1dbg((
16474 				    "ip_rput_forward_options: end of SR\n"));
16475 				ire_refrele(dst_ire);
16476 				break;
16477 			}
16478 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16479 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16480 			    IP_ADDR_LEN);
16481 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16482 			    ntohl(dst)));
16483 
16484 			/*
16485 			 * Check if our address is present more than
16486 			 * once as consecutive hops in source route.
16487 			 */
16488 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16489 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16490 			if (tmp_ire != NULL) {
16491 				ire_refrele(tmp_ire);
16492 				off += IP_ADDR_LEN;
16493 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16494 				goto redo_srr;
16495 			}
16496 			ipha->ipha_dst = dst;
16497 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16498 			ire_refrele(dst_ire);
16499 			break;
16500 		case IPOPT_RR:
16501 			off = opt[IPOPT_OFFSET];
16502 			off--;
16503 			if (optlen < IP_ADDR_LEN ||
16504 			    off > optlen - IP_ADDR_LEN) {
16505 				/* No more room - ignore */
16506 				ip1dbg((
16507 				    "ip_rput_forward_options: end of RR\n"));
16508 				break;
16509 			}
16510 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16511 			    IP_ADDR_LEN);
16512 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16513 			break;
16514 		case IPOPT_TS:
16515 			/* Insert timestamp if there is room */
16516 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16517 			case IPOPT_TS_TSONLY:
16518 				off = IPOPT_TS_TIMELEN;
16519 				break;
16520 			case IPOPT_TS_PRESPEC:
16521 			case IPOPT_TS_PRESPEC_RFC791:
16522 				/* Verify that the address matched */
16523 				off = opt[IPOPT_OFFSET] - 1;
16524 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16525 				dst_ire = ire_ctable_lookup(dst, 0,
16526 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16527 				    MATCH_IRE_TYPE);
16528 
16529 				if (dst_ire == NULL) {
16530 					/* Not for us */
16531 					break;
16532 				}
16533 				ire_refrele(dst_ire);
16534 				/* FALLTHRU */
16535 			case IPOPT_TS_TSANDADDR:
16536 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16537 				break;
16538 			default:
16539 				/*
16540 				 * ip_*put_options should have already
16541 				 * dropped this packet.
16542 				 */
16543 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16544 				    "unknown IT - bug in ip_rput_options?\n");
16545 				return (0);	/* Keep "lint" happy */
16546 			}
16547 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16548 				/* Increase overflow counter */
16549 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16550 				opt[IPOPT_POS_OV_FLG] =
16551 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16552 				    (off << 4));
16553 				break;
16554 			}
16555 			off = opt[IPOPT_OFFSET] - 1;
16556 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16557 			case IPOPT_TS_PRESPEC:
16558 			case IPOPT_TS_PRESPEC_RFC791:
16559 			case IPOPT_TS_TSANDADDR:
16560 				bcopy(&ire->ire_src_addr,
16561 				    (char *)opt + off, IP_ADDR_LEN);
16562 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16563 				/* FALLTHRU */
16564 			case IPOPT_TS_TSONLY:
16565 				off = opt[IPOPT_OFFSET] - 1;
16566 				/* Compute # of milliseconds since midnight */
16567 				gethrestime(&now);
16568 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16569 				    now.tv_nsec / (NANOSEC / MILLISEC);
16570 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16571 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16572 				break;
16573 			}
16574 			break;
16575 		}
16576 	}
16577 	return (0);
16578 }
16579 
16580 /*
16581  * This is called after processing at least one of AH/ESP headers.
16582  *
16583  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16584  * the actual, physical interface on which the packet was received,
16585  * but, when ip_strict_dst_multihoming is set to 1, could be the
16586  * interface which had the ipha_dst configured when the packet went
16587  * through ip_rput. The ill_index corresponding to the recv_ill
16588  * is saved in ipsec_in_rill_index
16589  */
16590 void
16591 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16592 {
16593 	mblk_t *mp;
16594 	ipaddr_t dst;
16595 	in6_addr_t *v6dstp;
16596 	ipha_t *ipha;
16597 	ip6_t *ip6h;
16598 	ipsec_in_t *ii;
16599 	boolean_t ill_need_rele = B_FALSE;
16600 	boolean_t rill_need_rele = B_FALSE;
16601 	boolean_t ire_need_rele = B_FALSE;
16602 
16603 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16604 	ASSERT(ii->ipsec_in_ill_index != 0);
16605 
16606 	mp = ipsec_mp->b_cont;
16607 	ASSERT(mp != NULL);
16608 
16609 
16610 	if (ill == NULL) {
16611 		ASSERT(recv_ill == NULL);
16612 		/*
16613 		 * We need to get the original queue on which ip_rput_local
16614 		 * or ip_rput_data_v6 was called.
16615 		 */
16616 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16617 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16618 		ill_need_rele = B_TRUE;
16619 
16620 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16621 			recv_ill = ill_lookup_on_ifindex(
16622 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16623 			    NULL, NULL, NULL, NULL);
16624 			rill_need_rele = B_TRUE;
16625 		} else {
16626 			recv_ill = ill;
16627 		}
16628 
16629 		if ((ill == NULL) || (recv_ill == NULL)) {
16630 			ip0dbg(("ip_fanout_proto_again: interface "
16631 			    "disappeared\n"));
16632 			if (ill != NULL)
16633 				ill_refrele(ill);
16634 			if (recv_ill != NULL)
16635 				ill_refrele(recv_ill);
16636 			freemsg(ipsec_mp);
16637 			return;
16638 		}
16639 	}
16640 
16641 	ASSERT(ill != NULL && recv_ill != NULL);
16642 
16643 	if (mp->b_datap->db_type == M_CTL) {
16644 		/*
16645 		 * AH/ESP is returning the ICMP message after
16646 		 * removing their headers. Fanout again till
16647 		 * it gets to the right protocol.
16648 		 */
16649 		if (ii->ipsec_in_v4) {
16650 			icmph_t *icmph;
16651 			int iph_hdr_length;
16652 			int hdr_length;
16653 
16654 			ipha = (ipha_t *)mp->b_rptr;
16655 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16656 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16657 			ipha = (ipha_t *)&icmph[1];
16658 			hdr_length = IPH_HDR_LENGTH(ipha);
16659 			/*
16660 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16661 			 * Reset the type to M_DATA.
16662 			 */
16663 			mp->b_datap->db_type = M_DATA;
16664 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16665 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16666 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16667 		} else {
16668 			icmp6_t *icmp6;
16669 			int hdr_length;
16670 
16671 			ip6h = (ip6_t *)mp->b_rptr;
16672 			/* Don't call hdr_length_v6() unless you have to. */
16673 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16674 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16675 			else
16676 				hdr_length = IPV6_HDR_LEN;
16677 
16678 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16679 			/*
16680 			 * icmp_inbound_error_fanout_v6 may need to do
16681 			 * pullupmsg.  Reset the type to M_DATA.
16682 			 */
16683 			mp->b_datap->db_type = M_DATA;
16684 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16685 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16686 		}
16687 		if (ill_need_rele)
16688 			ill_refrele(ill);
16689 		if (rill_need_rele)
16690 			ill_refrele(recv_ill);
16691 		return;
16692 	}
16693 
16694 	if (ii->ipsec_in_v4) {
16695 		ipha = (ipha_t *)mp->b_rptr;
16696 		dst = ipha->ipha_dst;
16697 		if (CLASSD(dst)) {
16698 			/*
16699 			 * Multicast has to be delivered to all streams.
16700 			 */
16701 			dst = INADDR_BROADCAST;
16702 		}
16703 
16704 		if (ire == NULL) {
16705 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16706 			    MBLK_GETLABEL(mp));
16707 			if (ire == NULL) {
16708 				if (ill_need_rele)
16709 					ill_refrele(ill);
16710 				if (rill_need_rele)
16711 					ill_refrele(recv_ill);
16712 				ip1dbg(("ip_fanout_proto_again: "
16713 				    "IRE not found"));
16714 				freemsg(ipsec_mp);
16715 				return;
16716 			}
16717 			ire_need_rele = B_TRUE;
16718 		}
16719 
16720 		switch (ipha->ipha_protocol) {
16721 			case IPPROTO_UDP:
16722 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16723 				    recv_ill);
16724 				if (ire_need_rele)
16725 					ire_refrele(ire);
16726 				break;
16727 			case IPPROTO_TCP:
16728 				if (!ire_need_rele)
16729 					IRE_REFHOLD(ire);
16730 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16731 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16732 				IRE_REFRELE(ire);
16733 				if (mp != NULL)
16734 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16735 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16736 				break;
16737 			case IPPROTO_SCTP:
16738 				if (!ire_need_rele)
16739 					IRE_REFHOLD(ire);
16740 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16741 				    ipsec_mp, 0, ill->ill_rq, dst);
16742 				break;
16743 			default:
16744 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16745 				    recv_ill);
16746 				if (ire_need_rele)
16747 					ire_refrele(ire);
16748 				break;
16749 		}
16750 	} else {
16751 		uint32_t rput_flags = 0;
16752 
16753 		ip6h = (ip6_t *)mp->b_rptr;
16754 		v6dstp = &ip6h->ip6_dst;
16755 		/*
16756 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16757 		 * address.
16758 		 *
16759 		 * Currently, we don't store that state in the IPSEC_IN
16760 		 * message, and we may need to.
16761 		 */
16762 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16763 		    IP6_IN_LLMCAST : 0);
16764 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16765 		    NULL, NULL);
16766 	}
16767 	if (ill_need_rele)
16768 		ill_refrele(ill);
16769 	if (rill_need_rele)
16770 		ill_refrele(recv_ill);
16771 }
16772 
16773 /*
16774  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16775  * returns 'true' if there are still fragments left on the queue, in
16776  * which case we restart the timer.
16777  */
16778 void
16779 ill_frag_timer(void *arg)
16780 {
16781 	ill_t	*ill = (ill_t *)arg;
16782 	boolean_t frag_pending;
16783 
16784 	mutex_enter(&ill->ill_lock);
16785 	ASSERT(!ill->ill_fragtimer_executing);
16786 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16787 		ill->ill_frag_timer_id = 0;
16788 		mutex_exit(&ill->ill_lock);
16789 		return;
16790 	}
16791 	ill->ill_fragtimer_executing = 1;
16792 	mutex_exit(&ill->ill_lock);
16793 
16794 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16795 
16796 	/*
16797 	 * Restart the timer, if we have fragments pending or if someone
16798 	 * wanted us to be scheduled again.
16799 	 */
16800 	mutex_enter(&ill->ill_lock);
16801 	ill->ill_fragtimer_executing = 0;
16802 	ill->ill_frag_timer_id = 0;
16803 	if (frag_pending || ill->ill_fragtimer_needrestart)
16804 		ill_frag_timer_start(ill);
16805 	mutex_exit(&ill->ill_lock);
16806 }
16807 
16808 void
16809 ill_frag_timer_start(ill_t *ill)
16810 {
16811 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16812 
16813 	/* If the ill is closing or opening don't proceed */
16814 	if (ill->ill_state_flags & ILL_CONDEMNED)
16815 		return;
16816 
16817 	if (ill->ill_fragtimer_executing) {
16818 		/*
16819 		 * ill_frag_timer is currently executing. Just record the
16820 		 * the fact that we want the timer to be restarted.
16821 		 * ill_frag_timer will post a timeout before it returns,
16822 		 * ensuring it will be called again.
16823 		 */
16824 		ill->ill_fragtimer_needrestart = 1;
16825 		return;
16826 	}
16827 
16828 	if (ill->ill_frag_timer_id == 0) {
16829 		/*
16830 		 * The timer is neither running nor is the timeout handler
16831 		 * executing. Post a timeout so that ill_frag_timer will be
16832 		 * called
16833 		 */
16834 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16835 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16836 		ill->ill_fragtimer_needrestart = 0;
16837 	}
16838 }
16839 
16840 /*
16841  * This routine is needed for loopback when forwarding multicasts.
16842  *
16843  * IPQoS Notes:
16844  * IPPF processing is done in fanout routines.
16845  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16846  * processing for IPSec packets is done when it comes back in clear.
16847  * NOTE : The callers of this function need to do the ire_refrele for the
16848  *	  ire that is being passed in.
16849  */
16850 void
16851 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16852     ill_t *recv_ill)
16853 {
16854 	ill_t	*ill = (ill_t *)q->q_ptr;
16855 	uint32_t	sum;
16856 	uint32_t	u1;
16857 	uint32_t	u2;
16858 	int		hdr_length;
16859 	boolean_t	mctl_present;
16860 	mblk_t		*first_mp = mp;
16861 	mblk_t		*hada_mp = NULL;
16862 	ipha_t		*inner_ipha;
16863 
16864 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16865 	    "ip_rput_locl_start: q %p", q);
16866 
16867 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16868 
16869 
16870 #define	rptr	((uchar_t *)ipha)
16871 #define	iphs	((uint16_t *)ipha)
16872 
16873 	/*
16874 	 * no UDP or TCP packet should come here anymore.
16875 	 */
16876 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16877 	    (ipha->ipha_protocol != IPPROTO_UDP));
16878 
16879 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16880 	if (mctl_present &&
16881 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16882 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16883 
16884 		/*
16885 		 * It's an IPsec accelerated packet.
16886 		 * Keep a pointer to the data attributes around until
16887 		 * we allocate the ipsec_info_t.
16888 		 */
16889 		IPSECHW_DEBUG(IPSECHW_PKT,
16890 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16891 		hada_mp = first_mp;
16892 		hada_mp->b_cont = NULL;
16893 		/*
16894 		 * Since it is accelerated, it comes directly from
16895 		 * the ill and the data attributes is followed by
16896 		 * the packet data.
16897 		 */
16898 		ASSERT(mp->b_datap->db_type != M_CTL);
16899 		first_mp = mp;
16900 		mctl_present = B_FALSE;
16901 	}
16902 
16903 	/*
16904 	 * IF M_CTL is not present, then ipsec_in_is_secure
16905 	 * should return B_TRUE. There is a case where loopback
16906 	 * packets has an M_CTL in the front with all the
16907 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16908 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16909 	 * packets never comes here, it is safe to ASSERT the
16910 	 * following.
16911 	 */
16912 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16913 
16914 
16915 	/* u1 is # words of IP options */
16916 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16917 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16918 
16919 	if (u1) {
16920 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16921 			if (hada_mp != NULL)
16922 				freemsg(hada_mp);
16923 			return;
16924 		}
16925 	} else {
16926 		/* Check the IP header checksum.  */
16927 #define	uph	((uint16_t *)ipha)
16928 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16929 		    uph[6] + uph[7] + uph[8] + uph[9];
16930 #undef  uph
16931 		/* finish doing IP checksum */
16932 		sum = (sum & 0xFFFF) + (sum >> 16);
16933 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16934 		/*
16935 		 * Don't verify header checksum if this packet is coming
16936 		 * back from AH/ESP as we already did it.
16937 		 */
16938 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16939 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16940 			goto drop_pkt;
16941 		}
16942 	}
16943 
16944 	/*
16945 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16946 	 * might be called more than once for secure packets, count only
16947 	 * the first time.
16948 	 */
16949 	if (!mctl_present) {
16950 		UPDATE_IB_PKT_COUNT(ire);
16951 		ire->ire_last_used_time = lbolt;
16952 	}
16953 
16954 	/* Check for fragmentation offset. */
16955 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16956 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16957 	if (u1) {
16958 		/*
16959 		 * We re-assemble fragments before we do the AH/ESP
16960 		 * processing. Thus, M_CTL should not be present
16961 		 * while we are re-assembling.
16962 		 */
16963 		ASSERT(!mctl_present);
16964 		ASSERT(first_mp == mp);
16965 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16966 			return;
16967 		}
16968 		/*
16969 		 * Make sure that first_mp points back to mp as
16970 		 * the mp we came in with could have changed in
16971 		 * ip_rput_fragment().
16972 		 */
16973 		ipha = (ipha_t *)mp->b_rptr;
16974 		first_mp = mp;
16975 	}
16976 
16977 	/*
16978 	 * Clear hardware checksumming flag as it is currently only
16979 	 * used by TCP and UDP.
16980 	 */
16981 	DB_CKSUMFLAGS(mp) = 0;
16982 
16983 	/* Now we have a complete datagram, destined for this machine. */
16984 	u1 = IPH_HDR_LENGTH(ipha);
16985 	switch (ipha->ipha_protocol) {
16986 	case IPPROTO_ICMP: {
16987 		ire_t		*ire_zone;
16988 		ilm_t		*ilm;
16989 		mblk_t		*mp1;
16990 		zoneid_t	last_zoneid;
16991 
16992 		if (CLASSD(ipha->ipha_dst) &&
16993 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
16994 			ASSERT(ire->ire_type == IRE_BROADCAST);
16995 			/*
16996 			 * In the multicast case, applications may have joined
16997 			 * the group from different zones, so we need to deliver
16998 			 * the packet to each of them. Loop through the
16999 			 * multicast memberships structures (ilm) on the receive
17000 			 * ill and send a copy of the packet up each matching
17001 			 * one. However, we don't do this for multicasts sent on
17002 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17003 			 * they must stay in the sender's zone.
17004 			 *
17005 			 * ilm_add_v6() ensures that ilms in the same zone are
17006 			 * contiguous in the ill_ilm list. We use this property
17007 			 * to avoid sending duplicates needed when two
17008 			 * applications in the same zone join the same group on
17009 			 * different logical interfaces: we ignore the ilm if
17010 			 * its zoneid is the same as the last matching one.
17011 			 * In addition, the sending of the packet for
17012 			 * ire_zoneid is delayed until all of the other ilms
17013 			 * have been exhausted.
17014 			 */
17015 			last_zoneid = -1;
17016 			ILM_WALKER_HOLD(recv_ill);
17017 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17018 			    ilm = ilm->ilm_next) {
17019 				if ((ilm->ilm_flags & ILM_DELETED) ||
17020 				    ipha->ipha_dst != ilm->ilm_addr ||
17021 				    ilm->ilm_zoneid == last_zoneid ||
17022 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17023 				    ilm->ilm_zoneid == ALL_ZONES ||
17024 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17025 					continue;
17026 				mp1 = ip_copymsg(first_mp);
17027 				if (mp1 == NULL)
17028 					continue;
17029 				icmp_inbound(q, mp1, B_TRUE, ill,
17030 				    0, sum, mctl_present, B_TRUE,
17031 				    recv_ill, ilm->ilm_zoneid);
17032 				last_zoneid = ilm->ilm_zoneid;
17033 			}
17034 			ILM_WALKER_RELE(recv_ill);
17035 		} else if (ire->ire_type == IRE_BROADCAST) {
17036 			/*
17037 			 * In the broadcast case, there may be many zones
17038 			 * which need a copy of the packet delivered to them.
17039 			 * There is one IRE_BROADCAST per broadcast address
17040 			 * and per zone; we walk those using a helper function.
17041 			 * In addition, the sending of the packet for ire is
17042 			 * delayed until all of the other ires have been
17043 			 * processed.
17044 			 */
17045 			IRB_REFHOLD(ire->ire_bucket);
17046 			ire_zone = NULL;
17047 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17048 			    ire)) != NULL) {
17049 				mp1 = ip_copymsg(first_mp);
17050 				if (mp1 == NULL)
17051 					continue;
17052 
17053 				UPDATE_IB_PKT_COUNT(ire_zone);
17054 				ire_zone->ire_last_used_time = lbolt;
17055 				icmp_inbound(q, mp1, B_TRUE, ill,
17056 				    0, sum, mctl_present, B_TRUE,
17057 				    recv_ill, ire_zone->ire_zoneid);
17058 			}
17059 			IRB_REFRELE(ire->ire_bucket);
17060 		}
17061 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17062 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17063 		    ire->ire_zoneid);
17064 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17065 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17066 		return;
17067 	}
17068 	case IPPROTO_IGMP:
17069 		/*
17070 		 * If we are not willing to accept IGMP packets in clear,
17071 		 * then check with global policy.
17072 		 */
17073 		if (igmp_accept_clear_messages == 0) {
17074 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17075 			    ipha, NULL, mctl_present);
17076 			if (first_mp == NULL)
17077 				return;
17078 		}
17079 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17080 			freemsg(first_mp);
17081 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17082 			BUMP_MIB(&ip_mib, ipInDiscards);
17083 			return;
17084 		}
17085 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17086 			/* Bad packet - discarded by igmp_input */
17087 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17088 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17089 			if (mctl_present)
17090 				freeb(first_mp);
17091 			return;
17092 		}
17093 		/*
17094 		 * igmp_input() may have returned the pulled up message.
17095 		 * So first_mp and ipha need to be reinitialized.
17096 		 */
17097 		ipha = (ipha_t *)mp->b_rptr;
17098 		if (mctl_present)
17099 			first_mp->b_cont = mp;
17100 		else
17101 			first_mp = mp;
17102 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17103 			/* No user-level listener for IGMP packets */
17104 			goto drop_pkt;
17105 		}
17106 		/* deliver to local raw users */
17107 		break;
17108 	case IPPROTO_PIM:
17109 		/*
17110 		 * If we are not willing to accept PIM packets in clear,
17111 		 * then check with global policy.
17112 		 */
17113 		if (pim_accept_clear_messages == 0) {
17114 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17115 			    ipha, NULL, mctl_present);
17116 			if (first_mp == NULL)
17117 				return;
17118 		}
17119 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17120 			freemsg(first_mp);
17121 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17122 			BUMP_MIB(&ip_mib, ipInDiscards);
17123 			return;
17124 		}
17125 		if (pim_input(q, mp) != 0) {
17126 			/* Bad packet - discarded by pim_input */
17127 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17128 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17129 			if (mctl_present)
17130 				freeb(first_mp);
17131 			return;
17132 		}
17133 
17134 		/*
17135 		 * pim_input() may have pulled up the message so ipha needs to
17136 		 * be reinitialized.
17137 		 */
17138 		ipha = (ipha_t *)mp->b_rptr;
17139 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17140 			/* No user-level listener for PIM packets */
17141 			goto drop_pkt;
17142 		}
17143 		/* deliver to local raw users */
17144 		break;
17145 	case IPPROTO_ENCAP:
17146 		/*
17147 		 * Handle self-encapsulated packets (IP-in-IP where
17148 		 * the inner addresses == the outer addresses).
17149 		 */
17150 		hdr_length = IPH_HDR_LENGTH(ipha);
17151 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17152 		    mp->b_wptr) {
17153 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17154 			    sizeof (ipha_t) - mp->b_rptr)) {
17155 				BUMP_MIB(&ip_mib, ipInDiscards);
17156 				freemsg(first_mp);
17157 				return;
17158 			}
17159 			ipha = (ipha_t *)mp->b_rptr;
17160 		}
17161 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17162 		/*
17163 		 * Check the sanity of the inner IP header.
17164 		 */
17165 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17166 			BUMP_MIB(&ip_mib, ipInDiscards);
17167 			freemsg(first_mp);
17168 			return;
17169 		}
17170 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17171 			BUMP_MIB(&ip_mib, ipInDiscards);
17172 			freemsg(first_mp);
17173 			return;
17174 		}
17175 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17176 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17177 			ipsec_in_t *ii;
17178 
17179 			/*
17180 			 * Self-encapsulated tunnel packet. Remove
17181 			 * the outer IP header and fanout again.
17182 			 * We also need to make sure that the inner
17183 			 * header is pulled up until options.
17184 			 */
17185 			mp->b_rptr = (uchar_t *)inner_ipha;
17186 			ipha = inner_ipha;
17187 			hdr_length = IPH_HDR_LENGTH(ipha);
17188 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17189 				if (!pullupmsg(mp, (uchar_t *)ipha +
17190 				    + hdr_length - mp->b_rptr)) {
17191 					freemsg(first_mp);
17192 					return;
17193 				}
17194 				ipha = (ipha_t *)mp->b_rptr;
17195 			}
17196 			if (!mctl_present) {
17197 				ASSERT(first_mp == mp);
17198 				/*
17199 				 * This means that somebody is sending
17200 				 * Self-encapsualted packets without AH/ESP.
17201 				 * If AH/ESP was present, we would have already
17202 				 * allocated the first_mp.
17203 				 */
17204 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
17205 				    NULL) {
17206 					ip1dbg(("ip_proto_input: IPSEC_IN "
17207 					    "allocation failure.\n"));
17208 					BUMP_MIB(&ip_mib, ipInDiscards);
17209 					freemsg(mp);
17210 					return;
17211 				}
17212 				first_mp->b_cont = mp;
17213 			}
17214 			/*
17215 			 * We generally store the ill_index if we need to
17216 			 * do IPSEC processing as we lose the ill queue when
17217 			 * we come back. But in this case, we never should
17218 			 * have to store the ill_index here as it should have
17219 			 * been stored previously when we processed the
17220 			 * AH/ESP header in this routine or for non-ipsec
17221 			 * cases, we still have the queue. But for some bad
17222 			 * packets from the wire, we can get to IPSEC after
17223 			 * this and we better store the index for that case.
17224 			 */
17225 			ill = (ill_t *)q->q_ptr;
17226 			ii = (ipsec_in_t *)first_mp->b_rptr;
17227 			ii->ipsec_in_ill_index =
17228 			    ill->ill_phyint->phyint_ifindex;
17229 			ii->ipsec_in_rill_index =
17230 			    recv_ill->ill_phyint->phyint_ifindex;
17231 			if (ii->ipsec_in_decaps) {
17232 				/*
17233 				 * This packet is self-encapsulated multiple
17234 				 * times. We don't want to recurse infinitely.
17235 				 * To keep it simple, drop the packet.
17236 				 */
17237 				BUMP_MIB(&ip_mib, ipInDiscards);
17238 				freemsg(first_mp);
17239 				return;
17240 			}
17241 			ii->ipsec_in_decaps = B_TRUE;
17242 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
17243 			return;
17244 		}
17245 		break;
17246 	case IPPROTO_AH:
17247 	case IPPROTO_ESP: {
17248 		/*
17249 		 * Fast path for AH/ESP. If this is the first time
17250 		 * we are sending a datagram to AH/ESP, allocate
17251 		 * a IPSEC_IN message and prepend it. Otherwise,
17252 		 * just fanout.
17253 		 */
17254 
17255 		int ipsec_rc;
17256 		ipsec_in_t *ii;
17257 
17258 		IP_STAT(ipsec_proto_ahesp);
17259 		if (!mctl_present) {
17260 			ASSERT(first_mp == mp);
17261 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
17262 				ip1dbg(("ip_proto_input: IPSEC_IN "
17263 				    "allocation failure.\n"));
17264 				freemsg(hada_mp); /* okay ifnull */
17265 				BUMP_MIB(&ip_mib, ipInDiscards);
17266 				freemsg(mp);
17267 				return;
17268 			}
17269 			/*
17270 			 * Store the ill_index so that when we come back
17271 			 * from IPSEC we ride on the same queue.
17272 			 */
17273 			ill = (ill_t *)q->q_ptr;
17274 			ii = (ipsec_in_t *)first_mp->b_rptr;
17275 			ii->ipsec_in_ill_index =
17276 			    ill->ill_phyint->phyint_ifindex;
17277 			ii->ipsec_in_rill_index =
17278 			    recv_ill->ill_phyint->phyint_ifindex;
17279 			first_mp->b_cont = mp;
17280 			/*
17281 			 * Cache hardware acceleration info.
17282 			 */
17283 			if (hada_mp != NULL) {
17284 				IPSECHW_DEBUG(IPSECHW_PKT,
17285 				    ("ip_rput_local: caching data attr.\n"));
17286 				ii->ipsec_in_accelerated = B_TRUE;
17287 				ii->ipsec_in_da = hada_mp;
17288 				hada_mp = NULL;
17289 			}
17290 		} else {
17291 			ii = (ipsec_in_t *)first_mp->b_rptr;
17292 		}
17293 
17294 		if (!ipsec_loaded()) {
17295 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17296 			    ire->ire_zoneid);
17297 			return;
17298 		}
17299 
17300 		/* select inbound SA and have IPsec process the pkt */
17301 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17302 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17303 			if (esph == NULL)
17304 				return;
17305 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17306 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17307 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17308 			    first_mp, esph);
17309 		} else {
17310 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17311 			if (ah == NULL)
17312 				return;
17313 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17314 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17315 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17316 			    first_mp, ah);
17317 		}
17318 
17319 		switch (ipsec_rc) {
17320 		case IPSEC_STATUS_SUCCESS:
17321 			break;
17322 		case IPSEC_STATUS_FAILED:
17323 			BUMP_MIB(&ip_mib, ipInDiscards);
17324 			/* FALLTHRU */
17325 		case IPSEC_STATUS_PENDING:
17326 			return;
17327 		}
17328 		/* we're done with IPsec processing, send it up */
17329 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17330 		return;
17331 	}
17332 	default:
17333 		break;
17334 	}
17335 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17336 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17337 		    ire->ire_zoneid));
17338 		goto drop_pkt;
17339 	}
17340 	/*
17341 	 * Handle protocols with which IP is less intimate.  There
17342 	 * can be more than one stream bound to a particular
17343 	 * protocol.  When this is the case, each one gets a copy
17344 	 * of any incoming packets.
17345 	 */
17346 	ip_fanout_proto(q, first_mp, ill, ipha,
17347 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17348 	    B_TRUE, recv_ill, ire->ire_zoneid);
17349 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17350 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17351 	return;
17352 
17353 drop_pkt:
17354 	freemsg(first_mp);
17355 	if (hada_mp != NULL)
17356 		freeb(hada_mp);
17357 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17358 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17359 #undef	rptr
17360 #undef  iphs
17361 
17362 }
17363 
17364 /*
17365  * Update any source route, record route or timestamp options.
17366  * Check that we are at end of strict source route.
17367  * The options have already been checked for sanity in ip_rput_options().
17368  */
17369 static boolean_t
17370 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17371 {
17372 	ipoptp_t	opts;
17373 	uchar_t		*opt;
17374 	uint8_t		optval;
17375 	uint8_t		optlen;
17376 	ipaddr_t	dst;
17377 	uint32_t	ts;
17378 	ire_t		*dst_ire;
17379 	timestruc_t	now;
17380 	zoneid_t	zoneid;
17381 	ill_t		*ill;
17382 
17383 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17384 
17385 	ip2dbg(("ip_rput_local_options\n"));
17386 
17387 	for (optval = ipoptp_first(&opts, ipha);
17388 	    optval != IPOPT_EOL;
17389 	    optval = ipoptp_next(&opts)) {
17390 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17391 		opt = opts.ipoptp_cur;
17392 		optlen = opts.ipoptp_len;
17393 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17394 		    optval, optlen));
17395 		switch (optval) {
17396 			uint32_t off;
17397 		case IPOPT_SSRR:
17398 		case IPOPT_LSRR:
17399 			off = opt[IPOPT_OFFSET];
17400 			off--;
17401 			if (optlen < IP_ADDR_LEN ||
17402 			    off > optlen - IP_ADDR_LEN) {
17403 				/* End of source route */
17404 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17405 				break;
17406 			}
17407 			/*
17408 			 * This will only happen if two consecutive entries
17409 			 * in the source route contains our address or if
17410 			 * it is a packet with a loose source route which
17411 			 * reaches us before consuming the whole source route
17412 			 */
17413 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17414 			if (optval == IPOPT_SSRR) {
17415 				goto bad_src_route;
17416 			}
17417 			/*
17418 			 * Hack: instead of dropping the packet truncate the
17419 			 * source route to what has been used by filling the
17420 			 * rest with IPOPT_NOP.
17421 			 */
17422 			opt[IPOPT_OLEN] = (uint8_t)off;
17423 			while (off < optlen) {
17424 				opt[off++] = IPOPT_NOP;
17425 			}
17426 			break;
17427 		case IPOPT_RR:
17428 			off = opt[IPOPT_OFFSET];
17429 			off--;
17430 			if (optlen < IP_ADDR_LEN ||
17431 			    off > optlen - IP_ADDR_LEN) {
17432 				/* No more room - ignore */
17433 				ip1dbg((
17434 				    "ip_rput_local_options: end of RR\n"));
17435 				break;
17436 			}
17437 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17438 			    IP_ADDR_LEN);
17439 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17440 			break;
17441 		case IPOPT_TS:
17442 			/* Insert timestamp if there is romm */
17443 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17444 			case IPOPT_TS_TSONLY:
17445 				off = IPOPT_TS_TIMELEN;
17446 				break;
17447 			case IPOPT_TS_PRESPEC:
17448 			case IPOPT_TS_PRESPEC_RFC791:
17449 				/* Verify that the address matched */
17450 				off = opt[IPOPT_OFFSET] - 1;
17451 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17452 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17453 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17454 				if (dst_ire == NULL) {
17455 					/* Not for us */
17456 					break;
17457 				}
17458 				ire_refrele(dst_ire);
17459 				/* FALLTHRU */
17460 			case IPOPT_TS_TSANDADDR:
17461 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17462 				break;
17463 			default:
17464 				/*
17465 				 * ip_*put_options should have already
17466 				 * dropped this packet.
17467 				 */
17468 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17469 				    "unknown IT - bug in ip_rput_options?\n");
17470 				return (B_TRUE);	/* Keep "lint" happy */
17471 			}
17472 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17473 				/* Increase overflow counter */
17474 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17475 				opt[IPOPT_POS_OV_FLG] =
17476 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17477 				    (off << 4));
17478 				break;
17479 			}
17480 			off = opt[IPOPT_OFFSET] - 1;
17481 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17482 			case IPOPT_TS_PRESPEC:
17483 			case IPOPT_TS_PRESPEC_RFC791:
17484 			case IPOPT_TS_TSANDADDR:
17485 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17486 				    IP_ADDR_LEN);
17487 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17488 				/* FALLTHRU */
17489 			case IPOPT_TS_TSONLY:
17490 				off = opt[IPOPT_OFFSET] - 1;
17491 				/* Compute # of milliseconds since midnight */
17492 				gethrestime(&now);
17493 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17494 				    now.tv_nsec / (NANOSEC / MILLISEC);
17495 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17496 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17497 				break;
17498 			}
17499 			break;
17500 		}
17501 	}
17502 	return (B_TRUE);
17503 
17504 bad_src_route:
17505 	q = WR(q);
17506 	if (q->q_next != NULL)
17507 		ill = q->q_ptr;
17508 	else
17509 		ill = NULL;
17510 
17511 	/* make sure we clear any indication of a hardware checksum */
17512 	DB_CKSUMFLAGS(mp) = 0;
17513 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill);
17514 	if (zoneid == ALL_ZONES)
17515 		freemsg(mp);
17516 	else
17517 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17518 	return (B_FALSE);
17519 
17520 }
17521 
17522 /*
17523  * Process IP options in an inbound packet.  If an option affects the
17524  * effective destination address, return the next hop address via dstp.
17525  * Returns -1 if something fails in which case an ICMP error has been sent
17526  * and mp freed.
17527  */
17528 static int
17529 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17530 {
17531 	ipoptp_t	opts;
17532 	uchar_t		*opt;
17533 	uint8_t		optval;
17534 	uint8_t		optlen;
17535 	ipaddr_t	dst;
17536 	intptr_t	code = 0;
17537 	ire_t		*ire = NULL;
17538 	zoneid_t	zoneid;
17539 	ill_t		*ill;
17540 
17541 	ip2dbg(("ip_rput_options\n"));
17542 	dst = ipha->ipha_dst;
17543 	for (optval = ipoptp_first(&opts, ipha);
17544 	    optval != IPOPT_EOL;
17545 	    optval = ipoptp_next(&opts)) {
17546 		opt = opts.ipoptp_cur;
17547 		optlen = opts.ipoptp_len;
17548 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17549 		    optval, optlen));
17550 		/*
17551 		 * Note: we need to verify the checksum before we
17552 		 * modify anything thus this routine only extracts the next
17553 		 * hop dst from any source route.
17554 		 */
17555 		switch (optval) {
17556 			uint32_t off;
17557 		case IPOPT_SSRR:
17558 		case IPOPT_LSRR:
17559 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17560 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17561 			if (ire == NULL) {
17562 				if (optval == IPOPT_SSRR) {
17563 					ip1dbg(("ip_rput_options: not next"
17564 					    " strict source route 0x%x\n",
17565 					    ntohl(dst)));
17566 					code = (char *)&ipha->ipha_dst -
17567 					    (char *)ipha;
17568 					goto param_prob; /* RouterReq's */
17569 				}
17570 				ip2dbg(("ip_rput_options: "
17571 				    "not next source route 0x%x\n",
17572 				    ntohl(dst)));
17573 				break;
17574 			}
17575 			ire_refrele(ire);
17576 
17577 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17578 				ip1dbg((
17579 				    "ip_rput_options: bad option offset\n"));
17580 				code = (char *)&opt[IPOPT_OLEN] -
17581 				    (char *)ipha;
17582 				goto param_prob;
17583 			}
17584 			off = opt[IPOPT_OFFSET];
17585 			off--;
17586 		redo_srr:
17587 			if (optlen < IP_ADDR_LEN ||
17588 			    off > optlen - IP_ADDR_LEN) {
17589 				/* End of source route */
17590 				ip1dbg(("ip_rput_options: end of SR\n"));
17591 				break;
17592 			}
17593 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17594 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17595 			    ntohl(dst)));
17596 
17597 			/*
17598 			 * Check if our address is present more than
17599 			 * once as consecutive hops in source route.
17600 			 * XXX verify per-interface ip_forwarding
17601 			 * for source route?
17602 			 */
17603 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17604 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17605 
17606 			if (ire != NULL) {
17607 				ire_refrele(ire);
17608 				off += IP_ADDR_LEN;
17609 				goto redo_srr;
17610 			}
17611 
17612 			if (dst == htonl(INADDR_LOOPBACK)) {
17613 				ip1dbg(("ip_rput_options: loopback addr in "
17614 				    "source route!\n"));
17615 				goto bad_src_route;
17616 			}
17617 			/*
17618 			 * For strict: verify that dst is directly
17619 			 * reachable.
17620 			 */
17621 			if (optval == IPOPT_SSRR) {
17622 				ire = ire_ftable_lookup(dst, 0, 0,
17623 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17624 				    MBLK_GETLABEL(mp),
17625 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17626 				if (ire == NULL) {
17627 					ip1dbg(("ip_rput_options: SSRR not "
17628 					    "directly reachable: 0x%x\n",
17629 					    ntohl(dst)));
17630 					goto bad_src_route;
17631 				}
17632 				ire_refrele(ire);
17633 			}
17634 			/*
17635 			 * Defer update of the offset and the record route
17636 			 * until the packet is forwarded.
17637 			 */
17638 			break;
17639 		case IPOPT_RR:
17640 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17641 				ip1dbg((
17642 				    "ip_rput_options: bad option offset\n"));
17643 				code = (char *)&opt[IPOPT_OLEN] -
17644 				    (char *)ipha;
17645 				goto param_prob;
17646 			}
17647 			break;
17648 		case IPOPT_TS:
17649 			/*
17650 			 * Verify that length >= 5 and that there is either
17651 			 * room for another timestamp or that the overflow
17652 			 * counter is not maxed out.
17653 			 */
17654 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17655 			if (optlen < IPOPT_MINLEN_IT) {
17656 				goto param_prob;
17657 			}
17658 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17659 				ip1dbg((
17660 				    "ip_rput_options: bad option offset\n"));
17661 				code = (char *)&opt[IPOPT_OFFSET] -
17662 				    (char *)ipha;
17663 				goto param_prob;
17664 			}
17665 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17666 			case IPOPT_TS_TSONLY:
17667 				off = IPOPT_TS_TIMELEN;
17668 				break;
17669 			case IPOPT_TS_TSANDADDR:
17670 			case IPOPT_TS_PRESPEC:
17671 			case IPOPT_TS_PRESPEC_RFC791:
17672 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17673 				break;
17674 			default:
17675 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17676 				    (char *)ipha;
17677 				goto param_prob;
17678 			}
17679 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17680 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17681 				/*
17682 				 * No room and the overflow counter is 15
17683 				 * already.
17684 				 */
17685 				goto param_prob;
17686 			}
17687 			break;
17688 		}
17689 	}
17690 
17691 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17692 		*dstp = dst;
17693 		return (0);
17694 	}
17695 
17696 	ip1dbg(("ip_rput_options: error processing IP options."));
17697 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17698 
17699 param_prob:
17700 	q = WR(q);
17701 	if (q->q_next != NULL)
17702 		ill = q->q_ptr;
17703 	else
17704 		ill = NULL;
17705 
17706 	/* make sure we clear any indication of a hardware checksum */
17707 	DB_CKSUMFLAGS(mp) = 0;
17708 	/* Don't know whether this is for non-global or global/forwarding */
17709 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17710 	if (zoneid == ALL_ZONES)
17711 		freemsg(mp);
17712 	else
17713 		icmp_param_problem(q, mp, (uint8_t)code, zoneid);
17714 	return (-1);
17715 
17716 bad_src_route:
17717 	q = WR(q);
17718 	if (q->q_next != NULL)
17719 		ill = q->q_ptr;
17720 	else
17721 		ill = NULL;
17722 
17723 	/* make sure we clear any indication of a hardware checksum */
17724 	DB_CKSUMFLAGS(mp) = 0;
17725 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17726 	if (zoneid == ALL_ZONES)
17727 		freemsg(mp);
17728 	else
17729 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17730 	return (-1);
17731 }
17732 
17733 /*
17734  * IP & ICMP info in >=14 msg's ...
17735  *  - ip fixed part (mib2_ip_t)
17736  *  - icmp fixed part (mib2_icmp_t)
17737  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17738  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17739  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
17740  *  - ipRouteAttributeTable (ip 102)	labeled routes
17741  *  - ip multicast membership (ip_member_t)
17742  *  - ip multicast source filtering (ip_grpsrc_t)
17743  *  - igmp fixed part (struct igmpstat)
17744  *  - multicast routing stats (struct mrtstat)
17745  *  - multicast routing vifs (array of struct vifctl)
17746  *  - multicast routing routes (array of struct mfcctl)
17747  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17748  *					One per ill plus one generic
17749  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17750  *					One per ill plus one generic
17751  *  - ipv6RouteEntry			all IPv6 IREs
17752  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17753  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17754  *  - ipv6AddrEntry			all IPv6 ipifs
17755  *  - ipv6 multicast membership (ipv6_member_t)
17756  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17757  *
17758  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
17759  * already present.
17760  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17761  * already filled in by the caller.
17762  * Return value of 0 indicates that no messages were sent and caller
17763  * should free mpctl.
17764  */
17765 int
17766 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17767 {
17768 
17769 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17770 		return (0);
17771 	}
17772 
17773 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
17774 		return (1);
17775 	}
17776 
17777 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17778 		return (1);
17779 	}
17780 
17781 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17782 		return (1);
17783 	}
17784 
17785 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17786 		return (1);
17787 	}
17788 
17789 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17790 		return (1);
17791 	}
17792 
17793 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17794 		return (1);
17795 	}
17796 
17797 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17798 		return (1);
17799 	}
17800 
17801 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17802 		return (1);
17803 	}
17804 
17805 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17806 		return (1);
17807 	}
17808 
17809 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17810 		return (1);
17811 	}
17812 
17813 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17814 		return (1);
17815 	}
17816 
17817 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17818 		return (1);
17819 	}
17820 
17821 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17822 		return (1);
17823 	}
17824 
17825 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17826 		return (1);
17827 	}
17828 
17829 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17830 		return (1);
17831 	}
17832 
17833 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17834 		return (1);
17835 	}
17836 
17837 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17838 		return (1);
17839 	}
17840 	freemsg(mpctl);
17841 	return (1);
17842 }
17843 
17844 
17845 /* Get global IPv4 statistics */
17846 static mblk_t *
17847 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
17848 {
17849 	struct opthdr		*optp;
17850 	mblk_t			*mp2ctl;
17851 
17852 	/*
17853 	 * make a copy of the original message
17854 	 */
17855 	mp2ctl = copymsg(mpctl);
17856 
17857 	/* fixed length IP structure... */
17858 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17859 	optp->level = MIB2_IP;
17860 	optp->name = 0;
17861 	SET_MIB(ip_mib.ipForwarding,
17862 	    (WE_ARE_FORWARDING ? 1 : 2));
17863 	SET_MIB(ip_mib.ipDefaultTTL,
17864 	    (uint32_t)ip_def_ttl);
17865 	SET_MIB(ip_mib.ipReasmTimeout,
17866 	    ip_g_frag_timeout);
17867 	SET_MIB(ip_mib.ipAddrEntrySize,
17868 	    sizeof (mib2_ipAddrEntry_t));
17869 	SET_MIB(ip_mib.ipRouteEntrySize,
17870 	    sizeof (mib2_ipRouteEntry_t));
17871 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
17872 	    sizeof (mib2_ipNetToMediaEntry_t));
17873 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17874 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17875 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
17876 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17877 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
17878 	    (int)sizeof (ip_mib))) {
17879 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17880 		    (uint_t)sizeof (ip_mib)));
17881 	}
17882 
17883 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17884 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17885 	    (int)optp->level, (int)optp->name, (int)optp->len));
17886 	qreply(q, mpctl);
17887 	return (mp2ctl);
17888 }
17889 
17890 /* Global IPv4 ICMP statistics */
17891 static mblk_t *
17892 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
17893 {
17894 	struct opthdr		*optp;
17895 	mblk_t			*mp2ctl;
17896 
17897 	/*
17898 	 * Make a copy of the original message
17899 	 */
17900 	mp2ctl = copymsg(mpctl);
17901 
17902 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17903 	optp->level = MIB2_ICMP;
17904 	optp->name = 0;
17905 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17906 	    (int)sizeof (icmp_mib))) {
17907 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17908 		    (uint_t)sizeof (icmp_mib)));
17909 	}
17910 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17911 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17912 	    (int)optp->level, (int)optp->name, (int)optp->len));
17913 	qreply(q, mpctl);
17914 	return (mp2ctl);
17915 }
17916 
17917 /* Global IPv4 IGMP statistics */
17918 static mblk_t *
17919 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17920 {
17921 	struct opthdr		*optp;
17922 	mblk_t			*mp2ctl;
17923 
17924 	/*
17925 	 * make a copy of the original message
17926 	 */
17927 	mp2ctl = copymsg(mpctl);
17928 
17929 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17930 	optp->level = EXPER_IGMP;
17931 	optp->name = 0;
17932 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17933 	    (int)sizeof (igmpstat))) {
17934 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17935 		    (uint_t)sizeof (igmpstat)));
17936 	}
17937 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17938 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17939 	    (int)optp->level, (int)optp->name, (int)optp->len));
17940 	qreply(q, mpctl);
17941 	return (mp2ctl);
17942 }
17943 
17944 /* Global IPv4 Multicast Routing statistics */
17945 static mblk_t *
17946 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17947 {
17948 	struct opthdr		*optp;
17949 	mblk_t			*mp2ctl;
17950 
17951 	/*
17952 	 * make a copy of the original message
17953 	 */
17954 	mp2ctl = copymsg(mpctl);
17955 
17956 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17957 	optp->level = EXPER_DVMRP;
17958 	optp->name = 0;
17959 	if (!ip_mroute_stats(mpctl->b_cont)) {
17960 		ip0dbg(("ip_mroute_stats: failed\n"));
17961 	}
17962 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17963 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17964 	    (int)optp->level, (int)optp->name, (int)optp->len));
17965 	qreply(q, mpctl);
17966 	return (mp2ctl);
17967 }
17968 
17969 /* IPv4 address information */
17970 static mblk_t *
17971 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17972 {
17973 	struct opthdr		*optp;
17974 	mblk_t			*mp2ctl;
17975 	mblk_t			*mp_tail = NULL;
17976 	ill_t			*ill;
17977 	ipif_t			*ipif;
17978 	uint_t			bitval;
17979 	mib2_ipAddrEntry_t	mae;
17980 	zoneid_t		zoneid;
17981 	ill_walk_context_t ctx;
17982 
17983 	/*
17984 	 * make a copy of the original message
17985 	 */
17986 	mp2ctl = copymsg(mpctl);
17987 
17988 	/* ipAddrEntryTable */
17989 
17990 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17991 	optp->level = MIB2_IP;
17992 	optp->name = MIB2_IP_ADDR;
17993 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17994 
17995 	rw_enter(&ill_g_lock, RW_READER);
17996 	ill = ILL_START_WALK_V4(&ctx);
17997 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17998 		for (ipif = ill->ill_ipif; ipif != NULL;
17999 		    ipif = ipif->ipif_next) {
18000 			if (ipif->ipif_zoneid != zoneid &&
18001 			    ipif->ipif_zoneid != ALL_ZONES)
18002 				continue;
18003 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18004 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18005 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18006 
18007 			(void) ipif_get_name(ipif,
18008 			    mae.ipAdEntIfIndex.o_bytes,
18009 			    OCTET_LENGTH);
18010 			mae.ipAdEntIfIndex.o_length =
18011 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18012 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18013 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18014 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18015 			mae.ipAdEntInfo.ae_subnet_len =
18016 			    ip_mask_to_plen(ipif->ipif_net_mask);
18017 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18018 			for (bitval = 1;
18019 			    bitval &&
18020 			    !(bitval & ipif->ipif_brd_addr);
18021 			    bitval <<= 1)
18022 				noop;
18023 			mae.ipAdEntBcastAddr = bitval;
18024 			mae.ipAdEntReasmMaxSize = 65535;
18025 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18026 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18027 			mae.ipAdEntInfo.ae_broadcast_addr =
18028 			    ipif->ipif_brd_addr;
18029 			mae.ipAdEntInfo.ae_pp_dst_addr =
18030 			    ipif->ipif_pp_dst_addr;
18031 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18032 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18033 
18034 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18035 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18036 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18037 				    "allocate %u bytes\n",
18038 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18039 			}
18040 		}
18041 	}
18042 	rw_exit(&ill_g_lock);
18043 
18044 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18045 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18046 	    (int)optp->level, (int)optp->name, (int)optp->len));
18047 	qreply(q, mpctl);
18048 	return (mp2ctl);
18049 }
18050 
18051 /* IPv6 address information */
18052 static mblk_t *
18053 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
18054 {
18055 	struct opthdr		*optp;
18056 	mblk_t			*mp2ctl;
18057 	mblk_t			*mp_tail = NULL;
18058 	ill_t			*ill;
18059 	ipif_t			*ipif;
18060 	mib2_ipv6AddrEntry_t	mae6;
18061 	zoneid_t		zoneid;
18062 	ill_walk_context_t	ctx;
18063 
18064 	/*
18065 	 * make a copy of the original message
18066 	 */
18067 	mp2ctl = copymsg(mpctl);
18068 
18069 	/* ipv6AddrEntryTable */
18070 
18071 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18072 	optp->level = MIB2_IP6;
18073 	optp->name = MIB2_IP6_ADDR;
18074 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18075 
18076 	rw_enter(&ill_g_lock, RW_READER);
18077 	ill = ILL_START_WALK_V6(&ctx);
18078 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18079 		for (ipif = ill->ill_ipif; ipif != NULL;
18080 		    ipif = ipif->ipif_next) {
18081 			if (ipif->ipif_zoneid != zoneid &&
18082 			    ipif->ipif_zoneid != ALL_ZONES)
18083 				continue;
18084 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18085 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18086 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18087 
18088 			(void) ipif_get_name(ipif,
18089 			    mae6.ipv6AddrIfIndex.o_bytes,
18090 			    OCTET_LENGTH);
18091 			mae6.ipv6AddrIfIndex.o_length =
18092 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18093 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18094 			mae6.ipv6AddrPfxLength =
18095 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18096 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18097 			mae6.ipv6AddrInfo.ae_subnet_len =
18098 			    mae6.ipv6AddrPfxLength;
18099 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18100 
18101 			/* Type: stateless(1), stateful(2), unknown(3) */
18102 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18103 				mae6.ipv6AddrType = 1;
18104 			else
18105 				mae6.ipv6AddrType = 2;
18106 			/* Anycast: true(1), false(2) */
18107 			if (ipif->ipif_flags & IPIF_ANYCAST)
18108 				mae6.ipv6AddrAnycastFlag = 1;
18109 			else
18110 				mae6.ipv6AddrAnycastFlag = 2;
18111 
18112 			/*
18113 			 * Address status: preferred(1), deprecated(2),
18114 			 * invalid(3), inaccessible(4), unknown(5)
18115 			 */
18116 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18117 				mae6.ipv6AddrStatus = 3;
18118 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18119 				mae6.ipv6AddrStatus = 2;
18120 			else
18121 				mae6.ipv6AddrStatus = 1;
18122 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18123 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18124 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18125 						ipif->ipif_v6pp_dst_addr;
18126 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18127 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18128 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18129 				(char *)&mae6,
18130 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18131 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18132 				    "allocate %u bytes\n",
18133 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18134 			}
18135 		}
18136 	}
18137 	rw_exit(&ill_g_lock);
18138 
18139 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18140 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18141 	    (int)optp->level, (int)optp->name, (int)optp->len));
18142 	qreply(q, mpctl);
18143 	return (mp2ctl);
18144 }
18145 
18146 /* IPv4 multicast group membership. */
18147 static mblk_t *
18148 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
18149 {
18150 	struct opthdr		*optp;
18151 	mblk_t			*mp2ctl;
18152 	ill_t			*ill;
18153 	ipif_t			*ipif;
18154 	ilm_t			*ilm;
18155 	ip_member_t		ipm;
18156 	mblk_t			*mp_tail = NULL;
18157 	ill_walk_context_t	ctx;
18158 	zoneid_t		zoneid;
18159 
18160 	/*
18161 	 * make a copy of the original message
18162 	 */
18163 	mp2ctl = copymsg(mpctl);
18164 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18165 
18166 	/* ipGroupMember table */
18167 	optp = (struct opthdr *)&mpctl->b_rptr[
18168 	    sizeof (struct T_optmgmt_ack)];
18169 	optp->level = MIB2_IP;
18170 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18171 
18172 	rw_enter(&ill_g_lock, RW_READER);
18173 	ill = ILL_START_WALK_V4(&ctx);
18174 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18175 		ILM_WALKER_HOLD(ill);
18176 		for (ipif = ill->ill_ipif; ipif != NULL;
18177 		    ipif = ipif->ipif_next) {
18178 			if (ipif->ipif_zoneid != zoneid &&
18179 			    ipif->ipif_zoneid != ALL_ZONES)
18180 				continue;	/* not this zone */
18181 			(void) ipif_get_name(ipif,
18182 			    ipm.ipGroupMemberIfIndex.o_bytes,
18183 			    OCTET_LENGTH);
18184 			ipm.ipGroupMemberIfIndex.o_length =
18185 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18186 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18187 				ASSERT(ilm->ilm_ipif != NULL);
18188 				ASSERT(ilm->ilm_ill == NULL);
18189 				if (ilm->ilm_ipif != ipif)
18190 					continue;
18191 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18192 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18193 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18194 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18195 				    (char *)&ipm, (int)sizeof (ipm))) {
18196 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18197 					    "failed to allocate %u bytes\n",
18198 						(uint_t)sizeof (ipm)));
18199 				}
18200 			}
18201 		}
18202 		ILM_WALKER_RELE(ill);
18203 	}
18204 	rw_exit(&ill_g_lock);
18205 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18206 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18207 	    (int)optp->level, (int)optp->name, (int)optp->len));
18208 	qreply(q, mpctl);
18209 	return (mp2ctl);
18210 }
18211 
18212 /* IPv6 multicast group membership. */
18213 static mblk_t *
18214 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
18215 {
18216 	struct opthdr		*optp;
18217 	mblk_t			*mp2ctl;
18218 	ill_t			*ill;
18219 	ilm_t			*ilm;
18220 	ipv6_member_t		ipm6;
18221 	mblk_t			*mp_tail = NULL;
18222 	ill_walk_context_t	ctx;
18223 	zoneid_t		zoneid;
18224 
18225 	/*
18226 	 * make a copy of the original message
18227 	 */
18228 	mp2ctl = copymsg(mpctl);
18229 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18230 
18231 	/* ip6GroupMember table */
18232 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18233 	optp->level = MIB2_IP6;
18234 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18235 
18236 	rw_enter(&ill_g_lock, RW_READER);
18237 	ill = ILL_START_WALK_V6(&ctx);
18238 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18239 		ILM_WALKER_HOLD(ill);
18240 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18241 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18242 			ASSERT(ilm->ilm_ipif == NULL);
18243 			ASSERT(ilm->ilm_ill != NULL);
18244 			if (ilm->ilm_zoneid != zoneid)
18245 				continue;	/* not this zone */
18246 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18247 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18248 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18249 			if (!snmp_append_data2(mpctl->b_cont,
18250 			    &mp_tail,
18251 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18252 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18253 				    "failed to allocate %u bytes\n",
18254 				    (uint_t)sizeof (ipm6)));
18255 			}
18256 		}
18257 		ILM_WALKER_RELE(ill);
18258 	}
18259 	rw_exit(&ill_g_lock);
18260 
18261 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18262 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18263 	    (int)optp->level, (int)optp->name, (int)optp->len));
18264 	qreply(q, mpctl);
18265 	return (mp2ctl);
18266 }
18267 
18268 /* IP multicast filtered sources */
18269 static mblk_t *
18270 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
18271 {
18272 	struct opthdr		*optp;
18273 	mblk_t			*mp2ctl;
18274 	ill_t			*ill;
18275 	ipif_t			*ipif;
18276 	ilm_t			*ilm;
18277 	ip_grpsrc_t		ips;
18278 	mblk_t			*mp_tail = NULL;
18279 	ill_walk_context_t	ctx;
18280 	zoneid_t		zoneid;
18281 	int			i;
18282 	slist_t			*sl;
18283 
18284 	/*
18285 	 * make a copy of the original message
18286 	 */
18287 	mp2ctl = copymsg(mpctl);
18288 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18289 
18290 	/* ipGroupSource table */
18291 	optp = (struct opthdr *)&mpctl->b_rptr[
18292 	    sizeof (struct T_optmgmt_ack)];
18293 	optp->level = MIB2_IP;
18294 	optp->name = EXPER_IP_GROUP_SOURCES;
18295 
18296 	rw_enter(&ill_g_lock, RW_READER);
18297 	ill = ILL_START_WALK_V4(&ctx);
18298 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18299 		ILM_WALKER_HOLD(ill);
18300 		for (ipif = ill->ill_ipif; ipif != NULL;
18301 		    ipif = ipif->ipif_next) {
18302 			if (ipif->ipif_zoneid != zoneid)
18303 				continue;	/* not this zone */
18304 			(void) ipif_get_name(ipif,
18305 			    ips.ipGroupSourceIfIndex.o_bytes,
18306 			    OCTET_LENGTH);
18307 			ips.ipGroupSourceIfIndex.o_length =
18308 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18309 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18310 				ASSERT(ilm->ilm_ipif != NULL);
18311 				ASSERT(ilm->ilm_ill == NULL);
18312 				sl = ilm->ilm_filter;
18313 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18314 					continue;
18315 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18316 				for (i = 0; i < sl->sl_numsrc; i++) {
18317 					if (!IN6_IS_ADDR_V4MAPPED(
18318 					    &sl->sl_addr[i]))
18319 						continue;
18320 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18321 					    ips.ipGroupSourceAddress);
18322 					if (snmp_append_data2(mpctl->b_cont,
18323 					    &mp_tail, (char *)&ips,
18324 					    (int)sizeof (ips)) == 0) {
18325 						ip1dbg(("ip_snmp_get_mib2_"
18326 						    "ip_group_src: failed to "
18327 						    "allocate %u bytes\n",
18328 						    (uint_t)sizeof (ips)));
18329 					}
18330 				}
18331 			}
18332 		}
18333 		ILM_WALKER_RELE(ill);
18334 	}
18335 	rw_exit(&ill_g_lock);
18336 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18337 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18338 	    (int)optp->level, (int)optp->name, (int)optp->len));
18339 	qreply(q, mpctl);
18340 	return (mp2ctl);
18341 }
18342 
18343 /* IPv6 multicast filtered sources. */
18344 static mblk_t *
18345 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18346 {
18347 	struct opthdr		*optp;
18348 	mblk_t			*mp2ctl;
18349 	ill_t			*ill;
18350 	ilm_t			*ilm;
18351 	ipv6_grpsrc_t		ips6;
18352 	mblk_t			*mp_tail = NULL;
18353 	ill_walk_context_t	ctx;
18354 	zoneid_t		zoneid;
18355 	int			i;
18356 	slist_t			*sl;
18357 
18358 	/*
18359 	 * make a copy of the original message
18360 	 */
18361 	mp2ctl = copymsg(mpctl);
18362 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18363 
18364 	/* ip6GroupMember table */
18365 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18366 	optp->level = MIB2_IP6;
18367 	optp->name = EXPER_IP6_GROUP_SOURCES;
18368 
18369 	rw_enter(&ill_g_lock, RW_READER);
18370 	ill = ILL_START_WALK_V6(&ctx);
18371 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18372 		ILM_WALKER_HOLD(ill);
18373 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18374 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18375 			ASSERT(ilm->ilm_ipif == NULL);
18376 			ASSERT(ilm->ilm_ill != NULL);
18377 			sl = ilm->ilm_filter;
18378 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18379 				continue;
18380 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18381 			for (i = 0; i < sl->sl_numsrc; i++) {
18382 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18383 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18384 				    (char *)&ips6, (int)sizeof (ips6))) {
18385 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18386 					    "group_src: failed to allocate "
18387 					    "%u bytes\n",
18388 					    (uint_t)sizeof (ips6)));
18389 				}
18390 			}
18391 		}
18392 		ILM_WALKER_RELE(ill);
18393 	}
18394 	rw_exit(&ill_g_lock);
18395 
18396 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18397 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18398 	    (int)optp->level, (int)optp->name, (int)optp->len));
18399 	qreply(q, mpctl);
18400 	return (mp2ctl);
18401 }
18402 
18403 /* Multicast routing virtual interface table. */
18404 static mblk_t *
18405 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18406 {
18407 	struct opthdr		*optp;
18408 	mblk_t			*mp2ctl;
18409 
18410 	/*
18411 	 * make a copy of the original message
18412 	 */
18413 	mp2ctl = copymsg(mpctl);
18414 
18415 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18416 	optp->level = EXPER_DVMRP;
18417 	optp->name = EXPER_DVMRP_VIF;
18418 	if (!ip_mroute_vif(mpctl->b_cont)) {
18419 		ip0dbg(("ip_mroute_vif: failed\n"));
18420 	}
18421 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18422 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18423 	    (int)optp->level, (int)optp->name, (int)optp->len));
18424 	qreply(q, mpctl);
18425 	return (mp2ctl);
18426 }
18427 
18428 /* Multicast routing table. */
18429 static mblk_t *
18430 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18431 {
18432 	struct opthdr		*optp;
18433 	mblk_t			*mp2ctl;
18434 
18435 	/*
18436 	 * make a copy of the original message
18437 	 */
18438 	mp2ctl = copymsg(mpctl);
18439 
18440 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18441 	optp->level = EXPER_DVMRP;
18442 	optp->name = EXPER_DVMRP_MRT;
18443 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18444 		ip0dbg(("ip_mroute_mrt: failed\n"));
18445 	}
18446 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18447 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18448 	    (int)optp->level, (int)optp->name, (int)optp->len));
18449 	qreply(q, mpctl);
18450 	return (mp2ctl);
18451 }
18452 
18453 /*
18454  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18455  * in one IRE walk.
18456  */
18457 static mblk_t *
18458 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18459 {
18460 	struct opthdr	*optp;
18461 	mblk_t		*mp2ctl;	/* Returned */
18462 	mblk_t		*mp3ctl;	/* nettomedia */
18463 	mblk_t		*mp4ctl;	/* routeattrs */
18464 	iproutedata_t	ird;
18465 	zoneid_t	zoneid;
18466 
18467 	/*
18468 	 * make copies of the original message
18469 	 *	- mp2ctl is returned unchanged to the caller for his use
18470 	 *	- mpctl is sent upstream as ipRouteEntryTable
18471 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18472 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18473 	 */
18474 	mp2ctl = copymsg(mpctl);
18475 	mp3ctl = copymsg(mpctl);
18476 	mp4ctl = copymsg(mpctl);
18477 	if (mp3ctl == NULL || mp4ctl == NULL) {
18478 		freemsg(mp4ctl);
18479 		freemsg(mp3ctl);
18480 		freemsg(mp2ctl);
18481 		freemsg(mpctl);
18482 		return (NULL);
18483 	}
18484 
18485 	bzero(&ird, sizeof (ird));
18486 
18487 	ird.ird_route.lp_head = mpctl->b_cont;
18488 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18489 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18490 
18491 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18492 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18493 	if (zoneid == GLOBAL_ZONEID) {
18494 		/*
18495 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18496 		 * the sys_net_config privilege, it can only run in the global
18497 		 * zone, so we don't display these IREs in the other zones.
18498 		 */
18499 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18500 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18501 	}
18502 
18503 	/* ipRouteEntryTable in mpctl */
18504 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18505 	optp->level = MIB2_IP;
18506 	optp->name = MIB2_IP_ROUTE;
18507 	optp->len = msgdsize(ird.ird_route.lp_head);
18508 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18509 	    (int)optp->level, (int)optp->name, (int)optp->len));
18510 	qreply(q, mpctl);
18511 
18512 	/* ipNetToMediaEntryTable in mp3ctl */
18513 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18514 	optp->level = MIB2_IP;
18515 	optp->name = MIB2_IP_MEDIA;
18516 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18517 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18518 	    (int)optp->level, (int)optp->name, (int)optp->len));
18519 	qreply(q, mp3ctl);
18520 
18521 	/* ipRouteAttributeTable in mp4ctl */
18522 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18523 	optp->level = MIB2_IP;
18524 	optp->name = EXPER_IP_RTATTR;
18525 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18526 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18527 	    (int)optp->level, (int)optp->name, (int)optp->len));
18528 	if (optp->len == 0)
18529 		freemsg(mp4ctl);
18530 	else
18531 		qreply(q, mp4ctl);
18532 
18533 	return (mp2ctl);
18534 }
18535 
18536 /*
18537  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18538  * ipv6NetToMediaEntryTable in an NDP walk.
18539  */
18540 static mblk_t *
18541 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18542 {
18543 	struct opthdr	*optp;
18544 	mblk_t		*mp2ctl;	/* Returned */
18545 	mblk_t		*mp3ctl;	/* nettomedia */
18546 	mblk_t		*mp4ctl;	/* routeattrs */
18547 	iproutedata_t	ird;
18548 	zoneid_t	zoneid;
18549 
18550 	/*
18551 	 * make copies of the original message
18552 	 *	- mp2ctl is returned unchanged to the caller for his use
18553 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18554 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18555 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18556 	 */
18557 	mp2ctl = copymsg(mpctl);
18558 	mp3ctl = copymsg(mpctl);
18559 	mp4ctl = copymsg(mpctl);
18560 	if (mp3ctl == NULL || mp4ctl == NULL) {
18561 		freemsg(mp4ctl);
18562 		freemsg(mp3ctl);
18563 		freemsg(mp2ctl);
18564 		freemsg(mpctl);
18565 		return (NULL);
18566 	}
18567 
18568 	bzero(&ird, sizeof (ird));
18569 
18570 	ird.ird_route.lp_head = mpctl->b_cont;
18571 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18572 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18573 
18574 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18575 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18576 
18577 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18578 	optp->level = MIB2_IP6;
18579 	optp->name = MIB2_IP6_ROUTE;
18580 	optp->len = msgdsize(ird.ird_route.lp_head);
18581 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18582 	    (int)optp->level, (int)optp->name, (int)optp->len));
18583 	qreply(q, mpctl);
18584 
18585 	/* ipv6NetToMediaEntryTable in mp3ctl */
18586 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18587 
18588 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18589 	optp->level = MIB2_IP6;
18590 	optp->name = MIB2_IP6_MEDIA;
18591 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18592 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18593 	    (int)optp->level, (int)optp->name, (int)optp->len));
18594 	qreply(q, mp3ctl);
18595 
18596 	/* ipv6RouteAttributeTable in mp4ctl */
18597 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18598 	optp->level = MIB2_IP6;
18599 	optp->name = EXPER_IP_RTATTR;
18600 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18601 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18602 	    (int)optp->level, (int)optp->name, (int)optp->len));
18603 	if (optp->len == 0)
18604 		freemsg(mp4ctl);
18605 	else
18606 		qreply(q, mp4ctl);
18607 
18608 	return (mp2ctl);
18609 }
18610 
18611 /*
18612  * ICMPv6 mib: One per ill
18613  */
18614 static mblk_t *
18615 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18616 {
18617 	struct opthdr		*optp;
18618 	mblk_t			*mp2ctl;
18619 	ill_t			*ill;
18620 	ill_walk_context_t	ctx;
18621 	mblk_t			*mp_tail = NULL;
18622 
18623 	/*
18624 	 * Make a copy of the original message
18625 	 */
18626 	mp2ctl = copymsg(mpctl);
18627 
18628 	/* fixed length IPv6 structure ... */
18629 
18630 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18631 	optp->level = MIB2_IP6;
18632 	optp->name = 0;
18633 	/* Include "unknown interface" ip6_mib */
18634 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
18635 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
18636 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
18637 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
18638 	    sizeof (mib2_ipv6IfStatsEntry_t));
18639 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18640 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
18641 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
18642 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18643 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
18644 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18645 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18646 	    (int)sizeof (ip6_mib))) {
18647 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18648 		    (uint_t)sizeof (ip6_mib)));
18649 	}
18650 
18651 	rw_enter(&ill_g_lock, RW_READER);
18652 	ill = ILL_START_WALK_V6(&ctx);
18653 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18654 		ill->ill_ip6_mib->ipv6IfIndex =
18655 		    ill->ill_phyint->phyint_ifindex;
18656 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
18657 		    ipv6_forward ? 1 : 2);
18658 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
18659 		    ill->ill_max_hops);
18660 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
18661 		    sizeof (mib2_ipv6IfStatsEntry_t));
18662 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
18663 		    sizeof (mib2_ipv6AddrEntry_t));
18664 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
18665 		    sizeof (mib2_ipv6RouteEntry_t));
18666 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
18667 		    sizeof (mib2_ipv6NetToMediaEntry_t));
18668 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
18669 		    sizeof (ipv6_member_t));
18670 
18671 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18672 		    (char *)ill->ill_ip6_mib,
18673 		    (int)sizeof (*ill->ill_ip6_mib))) {
18674 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18675 				"%u bytes\n",
18676 				(uint_t)sizeof (*ill->ill_ip6_mib)));
18677 		}
18678 	}
18679 	rw_exit(&ill_g_lock);
18680 
18681 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18682 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18683 	    (int)optp->level, (int)optp->name, (int)optp->len));
18684 	qreply(q, mpctl);
18685 	return (mp2ctl);
18686 }
18687 
18688 /*
18689  * ICMPv6 mib: One per ill
18690  */
18691 static mblk_t *
18692 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18693 {
18694 	struct opthdr		*optp;
18695 	mblk_t			*mp2ctl;
18696 	ill_t			*ill;
18697 	ill_walk_context_t	ctx;
18698 	mblk_t			*mp_tail = NULL;
18699 	/*
18700 	 * Make a copy of the original message
18701 	 */
18702 	mp2ctl = copymsg(mpctl);
18703 
18704 	/* fixed length ICMPv6 structure ... */
18705 
18706 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18707 	optp->level = MIB2_ICMP6;
18708 	optp->name = 0;
18709 	/* Include "unknown interface" icmp6_mib */
18710 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
18711 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18712 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18713 	    (int)sizeof (icmp6_mib))) {
18714 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18715 		    (uint_t)sizeof (icmp6_mib)));
18716 	}
18717 
18718 	rw_enter(&ill_g_lock, RW_READER);
18719 	ill = ILL_START_WALK_V6(&ctx);
18720 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18721 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18722 		    ill->ill_phyint->phyint_ifindex;
18723 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
18724 		    sizeof (mib2_ipv6IfIcmpEntry_t);
18725 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18726 		    (char *)ill->ill_icmp6_mib,
18727 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18728 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18729 			    "%u bytes\n",
18730 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18731 		}
18732 	}
18733 	rw_exit(&ill_g_lock);
18734 
18735 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18736 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18737 	    (int)optp->level, (int)optp->name, (int)optp->len));
18738 	qreply(q, mpctl);
18739 	return (mp2ctl);
18740 }
18741 
18742 /*
18743  * ire_walk routine to create both ipRouteEntryTable and
18744  * ipNetToMediaEntryTable in one IRE walk
18745  */
18746 static void
18747 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18748 {
18749 	ill_t				*ill;
18750 	ipif_t				*ipif;
18751 	mblk_t				*llmp;
18752 	dl_unitdata_req_t		*dlup;
18753 	mib2_ipRouteEntry_t		*re;
18754 	mib2_ipNetToMediaEntry_t	ntme;
18755 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18756 	ipaddr_t			gw_addr;
18757 	tsol_ire_gw_secattr_t		*attrp;
18758 	tsol_gc_t			*gc = NULL;
18759 	tsol_gcgrp_t			*gcgrp = NULL;
18760 	uint_t				sacnt = 0;
18761 	int				i;
18762 
18763 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18764 
18765 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18766 		return;
18767 
18768 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18769 		mutex_enter(&attrp->igsa_lock);
18770 		if ((gc = attrp->igsa_gc) != NULL) {
18771 			gcgrp = gc->gc_grp;
18772 			ASSERT(gcgrp != NULL);
18773 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18774 			sacnt = 1;
18775 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18776 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18777 			gc = gcgrp->gcgrp_head;
18778 			sacnt = gcgrp->gcgrp_count;
18779 		}
18780 		mutex_exit(&attrp->igsa_lock);
18781 
18782 		/* do nothing if there's no gc to report */
18783 		if (gc == NULL) {
18784 			ASSERT(sacnt == 0);
18785 			if (gcgrp != NULL) {
18786 				/* we might as well drop the lock now */
18787 				rw_exit(&gcgrp->gcgrp_rwlock);
18788 				gcgrp = NULL;
18789 			}
18790 			attrp = NULL;
18791 		}
18792 
18793 		ASSERT(gc == NULL || (gcgrp != NULL &&
18794 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18795 	}
18796 	ASSERT(sacnt == 0 || gc != NULL);
18797 
18798 	if (sacnt != 0 &&
18799 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18800 		kmem_free(re, sizeof (*re));
18801 		rw_exit(&gcgrp->gcgrp_rwlock);
18802 		return;
18803 	}
18804 
18805 	/*
18806 	 * Return all IRE types for route table... let caller pick and choose
18807 	 */
18808 	re->ipRouteDest = ire->ire_addr;
18809 	ipif = ire->ire_ipif;
18810 	re->ipRouteIfIndex.o_length = 0;
18811 	if (ire->ire_type == IRE_CACHE) {
18812 		ill = (ill_t *)ire->ire_stq->q_ptr;
18813 		re->ipRouteIfIndex.o_length =
18814 		    ill->ill_name_length == 0 ? 0 :
18815 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18816 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18817 		    re->ipRouteIfIndex.o_length);
18818 	} else if (ipif != NULL) {
18819 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18820 		    OCTET_LENGTH);
18821 		re->ipRouteIfIndex.o_length =
18822 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18823 	}
18824 	re->ipRouteMetric1 = -1;
18825 	re->ipRouteMetric2 = -1;
18826 	re->ipRouteMetric3 = -1;
18827 	re->ipRouteMetric4 = -1;
18828 
18829 	gw_addr = ire->ire_gateway_addr;
18830 
18831 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18832 		re->ipRouteNextHop = ire->ire_src_addr;
18833 	else
18834 		re->ipRouteNextHop = gw_addr;
18835 	/* indirect(4), direct(3), or invalid(2) */
18836 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18837 		re->ipRouteType = 2;
18838 	else
18839 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18840 	re->ipRouteProto = -1;
18841 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18842 	re->ipRouteMask = ire->ire_mask;
18843 	re->ipRouteMetric5 = -1;
18844 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
18845 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
18846 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
18847 	if (ire->ire_nce &&
18848 	    ire->ire_nce->nce_state == ND_REACHABLE)
18849 		llmp = ire->ire_nce->nce_res_mp;
18850 	else
18851 		llmp = NULL;
18852 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
18853 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
18854 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18855 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18856 	re->ipRouteInfo.re_flags	= ire->ire_flags;
18857 	re->ipRouteInfo.re_in_ill.o_length = 0;
18858 
18859 	if (ire->ire_flags & RTF_DYNAMIC) {
18860 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
18861 	} else {
18862 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
18863 	}
18864 
18865 	if (ire->ire_in_ill != NULL) {
18866 		re->ipRouteInfo.re_in_ill.o_length =
18867 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
18868 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
18869 		bcopy(ire->ire_in_ill->ill_name,
18870 		    re->ipRouteInfo.re_in_ill.o_bytes,
18871 		    re->ipRouteInfo.re_in_ill.o_length);
18872 	}
18873 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
18874 
18875 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18876 	    (char *)re, (int)sizeof (*re))) {
18877 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18878 		    (uint_t)sizeof (*re)));
18879 	}
18880 
18881 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18882 		iaeptr->iae_routeidx = ird->ird_idx;
18883 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18884 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18885 	}
18886 
18887 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18888 	    (char *)iae, sacnt * sizeof (*iae))) {
18889 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18890 		    (unsigned)(sacnt * sizeof (*iae))));
18891 	}
18892 
18893 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
18894 		goto done;
18895 	/*
18896 	 * only IRE_CACHE entries that are for a directly connected subnet
18897 	 * get appended to net -> phys addr table
18898 	 * (others in arp)
18899 	 */
18900 	ntme.ipNetToMediaIfIndex.o_length = 0;
18901 	ill = ire_to_ill(ire);
18902 	ASSERT(ill != NULL);
18903 	ntme.ipNetToMediaIfIndex.o_length =
18904 	    ill->ill_name_length == 0 ? 0 :
18905 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18906 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
18907 		    ntme.ipNetToMediaIfIndex.o_length);
18908 
18909 	ntme.ipNetToMediaPhysAddress.o_length = 0;
18910 	if (llmp) {
18911 		uchar_t *addr;
18912 
18913 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
18914 		/* Remove sap from  address */
18915 		if (ill->ill_sap_length < 0)
18916 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
18917 		else
18918 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
18919 			    ill->ill_sap_length;
18920 
18921 		ntme.ipNetToMediaPhysAddress.o_length =
18922 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18923 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18924 		    ntme.ipNetToMediaPhysAddress.o_length);
18925 	}
18926 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18927 	/* assume dynamic (may be changed in arp) */
18928 	ntme.ipNetToMediaType = 3;
18929 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18930 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18931 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18932 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18933 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18934 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18935 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18936 		    (uint_t)sizeof (ntme)));
18937 	}
18938 done:
18939 	/* bump route index for next pass */
18940 	ird->ird_idx++;
18941 
18942 	kmem_free(re, sizeof (*re));
18943 	if (sacnt != 0)
18944 		kmem_free(iae, sacnt * sizeof (*iae));
18945 
18946 	if (gcgrp != NULL)
18947 		rw_exit(&gcgrp->gcgrp_rwlock);
18948 }
18949 
18950 /*
18951  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18952  */
18953 static void
18954 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18955 {
18956 	ill_t				*ill;
18957 	ipif_t				*ipif;
18958 	mib2_ipv6RouteEntry_t		*re;
18959 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18960 	in6_addr_t			gw_addr_v6;
18961 	tsol_ire_gw_secattr_t		*attrp;
18962 	tsol_gc_t			*gc = NULL;
18963 	tsol_gcgrp_t			*gcgrp = NULL;
18964 	uint_t				sacnt = 0;
18965 	int				i;
18966 
18967 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18968 
18969 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18970 		return;
18971 
18972 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18973 		mutex_enter(&attrp->igsa_lock);
18974 		if ((gc = attrp->igsa_gc) != NULL) {
18975 			gcgrp = gc->gc_grp;
18976 			ASSERT(gcgrp != NULL);
18977 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18978 			sacnt = 1;
18979 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18980 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18981 			gc = gcgrp->gcgrp_head;
18982 			sacnt = gcgrp->gcgrp_count;
18983 		}
18984 		mutex_exit(&attrp->igsa_lock);
18985 
18986 		/* do nothing if there's no gc to report */
18987 		if (gc == NULL) {
18988 			ASSERT(sacnt == 0);
18989 			if (gcgrp != NULL) {
18990 				/* we might as well drop the lock now */
18991 				rw_exit(&gcgrp->gcgrp_rwlock);
18992 				gcgrp = NULL;
18993 			}
18994 			attrp = NULL;
18995 		}
18996 
18997 		ASSERT(gc == NULL || (gcgrp != NULL &&
18998 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18999 	}
19000 	ASSERT(sacnt == 0 || gc != NULL);
19001 
19002 	if (sacnt != 0 &&
19003 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19004 		kmem_free(re, sizeof (*re));
19005 		rw_exit(&gcgrp->gcgrp_rwlock);
19006 		return;
19007 	}
19008 
19009 	/*
19010 	 * Return all IRE types for route table... let caller pick and choose
19011 	 */
19012 	re->ipv6RouteDest = ire->ire_addr_v6;
19013 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19014 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19015 	re->ipv6RouteIfIndex.o_length = 0;
19016 	ipif = ire->ire_ipif;
19017 	if (ire->ire_type == IRE_CACHE) {
19018 		ill = (ill_t *)ire->ire_stq->q_ptr;
19019 		re->ipv6RouteIfIndex.o_length =
19020 		    ill->ill_name_length == 0 ? 0 :
19021 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19022 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19023 		    re->ipv6RouteIfIndex.o_length);
19024 	} else if (ipif != NULL) {
19025 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19026 		    OCTET_LENGTH);
19027 		re->ipv6RouteIfIndex.o_length =
19028 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19029 	}
19030 
19031 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19032 
19033 	mutex_enter(&ire->ire_lock);
19034 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19035 	mutex_exit(&ire->ire_lock);
19036 
19037 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19038 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19039 	else
19040 		re->ipv6RouteNextHop = gw_addr_v6;
19041 
19042 	/* remote(4), local(3), or discard(2) */
19043 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19044 		re->ipv6RouteType = 2;
19045 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19046 		re->ipv6RouteType = 3;
19047 	else
19048 		re->ipv6RouteType = 4;
19049 
19050 	re->ipv6RouteProtocol	= -1;
19051 	re->ipv6RoutePolicy	= 0;
19052 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19053 	re->ipv6RouteNextHopRDI	= 0;
19054 	re->ipv6RouteWeight	= 0;
19055 	re->ipv6RouteMetric	= 0;
19056 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19057 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19058 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19059 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19060 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19061 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19062 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19063 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19064 
19065 	if (ire->ire_flags & RTF_DYNAMIC) {
19066 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19067 	} else {
19068 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19069 	}
19070 
19071 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19072 	    (char *)re, (int)sizeof (*re))) {
19073 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19074 		    (uint_t)sizeof (*re)));
19075 	}
19076 
19077 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19078 		iaeptr->iae_routeidx = ird->ird_idx;
19079 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19080 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19081 	}
19082 
19083 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19084 	    (char *)iae, sacnt * sizeof (*iae))) {
19085 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19086 		    (unsigned)(sacnt * sizeof (*iae))));
19087 	}
19088 
19089 	/* bump route index for next pass */
19090 	ird->ird_idx++;
19091 
19092 	kmem_free(re, sizeof (*re));
19093 	if (sacnt != 0)
19094 		kmem_free(iae, sacnt * sizeof (*iae));
19095 
19096 	if (gcgrp != NULL)
19097 		rw_exit(&gcgrp->gcgrp_rwlock);
19098 }
19099 
19100 /*
19101  * ndp_walk routine to create ipv6NetToMediaEntryTable
19102  */
19103 static int
19104 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19105 {
19106 	ill_t				*ill;
19107 	mib2_ipv6NetToMediaEntry_t	ntme;
19108 	dl_unitdata_req_t		*dl;
19109 
19110 	ill = nce->nce_ill;
19111 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19112 		return (0);
19113 
19114 	/*
19115 	 * Neighbor cache entry attached to IRE with on-link
19116 	 * destination.
19117 	 */
19118 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19119 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19120 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19121 	    (nce->nce_res_mp != NULL)) {
19122 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19123 		ntme.ipv6NetToMediaPhysAddress.o_length =
19124 		    dl->dl_dest_addr_length;
19125 	} else {
19126 		ntme.ipv6NetToMediaPhysAddress.o_length =
19127 		    ill->ill_phys_addr_length;
19128 	}
19129 	if (nce->nce_res_mp != NULL) {
19130 		bcopy((char *)nce->nce_res_mp->b_rptr +
19131 		    NCE_LL_ADDR_OFFSET(ill),
19132 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19133 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19134 	} else {
19135 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19136 		    ill->ill_phys_addr_length);
19137 	}
19138 	/*
19139 	 * Note: Returns ND_* states. Should be:
19140 	 * reachable(1), stale(2), delay(3), probe(4),
19141 	 * invalid(5), unknown(6)
19142 	 */
19143 	ntme.ipv6NetToMediaState = nce->nce_state;
19144 	ntme.ipv6NetToMediaLastUpdated = 0;
19145 
19146 	/* other(1), dynamic(2), static(3), local(4) */
19147 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19148 		ntme.ipv6NetToMediaType = 4;
19149 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19150 		ntme.ipv6NetToMediaType = 1;
19151 	} else {
19152 		ntme.ipv6NetToMediaType = 2;
19153 	}
19154 
19155 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19156 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19157 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19158 		    (uint_t)sizeof (ntme)));
19159 	}
19160 	return (0);
19161 }
19162 
19163 /*
19164  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19165  */
19166 /* ARGSUSED */
19167 int
19168 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19169 {
19170 	switch (level) {
19171 	case MIB2_IP:
19172 	case MIB2_ICMP:
19173 		switch (name) {
19174 		default:
19175 			break;
19176 		}
19177 		return (1);
19178 	default:
19179 		return (1);
19180 	}
19181 }
19182 
19183 /*
19184  * Called before the options are updated to check if this packet will
19185  * be source routed from here.
19186  * This routine assumes that the options are well formed i.e. that they
19187  * have already been checked.
19188  */
19189 static boolean_t
19190 ip_source_routed(ipha_t *ipha)
19191 {
19192 	ipoptp_t	opts;
19193 	uchar_t		*opt;
19194 	uint8_t		optval;
19195 	uint8_t		optlen;
19196 	ipaddr_t	dst;
19197 	ire_t		*ire;
19198 
19199 	if (IS_SIMPLE_IPH(ipha)) {
19200 		ip2dbg(("not source routed\n"));
19201 		return (B_FALSE);
19202 	}
19203 	dst = ipha->ipha_dst;
19204 	for (optval = ipoptp_first(&opts, ipha);
19205 	    optval != IPOPT_EOL;
19206 	    optval = ipoptp_next(&opts)) {
19207 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19208 		opt = opts.ipoptp_cur;
19209 		optlen = opts.ipoptp_len;
19210 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19211 		    optval, optlen));
19212 		switch (optval) {
19213 			uint32_t off;
19214 		case IPOPT_SSRR:
19215 		case IPOPT_LSRR:
19216 			/*
19217 			 * If dst is one of our addresses and there are some
19218 			 * entries left in the source route return (true).
19219 			 */
19220 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19221 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
19222 			if (ire == NULL) {
19223 				ip2dbg(("ip_source_routed: not next"
19224 				    " source route 0x%x\n",
19225 				    ntohl(dst)));
19226 				return (B_FALSE);
19227 			}
19228 			ire_refrele(ire);
19229 			off = opt[IPOPT_OFFSET];
19230 			off--;
19231 			if (optlen < IP_ADDR_LEN ||
19232 			    off > optlen - IP_ADDR_LEN) {
19233 				/* End of source route */
19234 				ip1dbg(("ip_source_routed: end of SR\n"));
19235 				return (B_FALSE);
19236 			}
19237 			return (B_TRUE);
19238 		}
19239 	}
19240 	ip2dbg(("not source routed\n"));
19241 	return (B_FALSE);
19242 }
19243 
19244 /*
19245  * Check if the packet contains any source route.
19246  */
19247 static boolean_t
19248 ip_source_route_included(ipha_t *ipha)
19249 {
19250 	ipoptp_t	opts;
19251 	uint8_t		optval;
19252 
19253 	if (IS_SIMPLE_IPH(ipha))
19254 		return (B_FALSE);
19255 	for (optval = ipoptp_first(&opts, ipha);
19256 	    optval != IPOPT_EOL;
19257 	    optval = ipoptp_next(&opts)) {
19258 		switch (optval) {
19259 		case IPOPT_SSRR:
19260 		case IPOPT_LSRR:
19261 			return (B_TRUE);
19262 		}
19263 	}
19264 	return (B_FALSE);
19265 }
19266 
19267 /*
19268  * Called when the IRE expiration timer fires.
19269  */
19270 /* ARGSUSED */
19271 void
19272 ip_trash_timer_expire(void *args)
19273 {
19274 	int	flush_flag = 0;
19275 
19276 	/*
19277 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19278 	 * This lock makes sure that a new invocation of this function
19279 	 * that occurs due to an almost immediate timer firing will not
19280 	 * progress beyond this point until the current invocation is done
19281 	 */
19282 	mutex_enter(&ip_trash_timer_lock);
19283 	ip_ire_expire_id = 0;
19284 	mutex_exit(&ip_trash_timer_lock);
19285 
19286 	/* Periodic timer */
19287 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
19288 		/*
19289 		 * Remove all IRE_CACHE entries since they might
19290 		 * contain arp information.
19291 		 */
19292 		flush_flag |= FLUSH_ARP_TIME;
19293 		ip_ire_arp_time_elapsed = 0;
19294 		IP_STAT(ip_ire_arp_timer_expired);
19295 	}
19296 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
19297 		/* Remove all redirects */
19298 		flush_flag |= FLUSH_REDIRECT_TIME;
19299 		ip_ire_rd_time_elapsed = 0;
19300 		IP_STAT(ip_ire_redirect_timer_expired);
19301 	}
19302 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
19303 		/* Increase path mtu */
19304 		flush_flag |= FLUSH_MTU_TIME;
19305 		ip_ire_pmtu_time_elapsed = 0;
19306 		IP_STAT(ip_ire_pmtu_timer_expired);
19307 	}
19308 
19309 	/*
19310 	 * Optimize for the case when there are no redirects in the
19311 	 * ftable, that is, no need to walk the ftable in that case.
19312 	 */
19313 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19314 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19315 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
19316 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
19317 	}
19318 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
19319 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19320 		    ire_expire, (char *)(uintptr_t)flush_flag,
19321 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
19322 	}
19323 	if (flush_flag & FLUSH_MTU_TIME) {
19324 		/*
19325 		 * Walk all IPv6 IRE's and update them
19326 		 * Note that ARP and redirect timers are not
19327 		 * needed since NUD handles stale entries.
19328 		 */
19329 		flush_flag = FLUSH_MTU_TIME;
19330 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
19331 		    ALL_ZONES);
19332 	}
19333 
19334 	ip_ire_arp_time_elapsed += ip_timer_interval;
19335 	ip_ire_rd_time_elapsed += ip_timer_interval;
19336 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19337 
19338 	/*
19339 	 * Hold the lock to serialize timeout calls and prevent
19340 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19341 	 * for the timer to fire and a new invocation of this function
19342 	 * to start before the return value of timeout has been stored
19343 	 * in ip_ire_expire_id by the current invocation.
19344 	 */
19345 	mutex_enter(&ip_trash_timer_lock);
19346 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19347 	    MSEC_TO_TICK(ip_timer_interval));
19348 	mutex_exit(&ip_trash_timer_lock);
19349 }
19350 
19351 /*
19352  * Called by the memory allocator subsystem directly, when the system
19353  * is running low on memory.
19354  */
19355 /* ARGSUSED */
19356 void
19357 ip_trash_ire_reclaim(void *args)
19358 {
19359 	ire_cache_count_t icc;
19360 	ire_cache_reclaim_t icr;
19361 	ncc_cache_count_t ncc;
19362 	nce_cache_reclaim_t ncr;
19363 	uint_t delete_cnt;
19364 	/*
19365 	 * Memory reclaim call back.
19366 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19367 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19368 	 * entries, determine what fraction to free for
19369 	 * each category of IRE_CACHE entries giving absolute priority
19370 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19371 	 * entry will be freed unless all offlink entries are freed).
19372 	 */
19373 	icc.icc_total = 0;
19374 	icc.icc_unused = 0;
19375 	icc.icc_offlink = 0;
19376 	icc.icc_pmtu = 0;
19377 	icc.icc_onlink = 0;
19378 	ire_walk(ire_cache_count, (char *)&icc);
19379 
19380 	/*
19381 	 * Free NCEs for IPv6 like the onlink ires.
19382 	 */
19383 	ncc.ncc_total = 0;
19384 	ncc.ncc_host = 0;
19385 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19386 
19387 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19388 	    icc.icc_pmtu + icc.icc_onlink);
19389 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19390 	IP_STAT(ip_trash_ire_reclaim_calls);
19391 	if (delete_cnt == 0)
19392 		return;
19393 	IP_STAT(ip_trash_ire_reclaim_success);
19394 	/* Always delete all unused offlink entries */
19395 	icr.icr_unused = 1;
19396 	if (delete_cnt <= icc.icc_unused) {
19397 		/*
19398 		 * Only need to free unused entries.  In other words,
19399 		 * there are enough unused entries to free to meet our
19400 		 * target number of freed ire cache entries.
19401 		 */
19402 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19403 		ncr.ncr_host = 0;
19404 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19405 		/*
19406 		 * Only need to free unused entries, plus a fraction of offlink
19407 		 * entries.  It follows from the first if statement that
19408 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19409 		 */
19410 		delete_cnt -= icc.icc_unused;
19411 		/* Round up # deleted by truncating fraction */
19412 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19413 		icr.icr_pmtu = icr.icr_onlink = 0;
19414 		ncr.ncr_host = 0;
19415 	} else if (delete_cnt <=
19416 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19417 		/*
19418 		 * Free all unused and offlink entries, plus a fraction of
19419 		 * pmtu entries.  It follows from the previous if statement
19420 		 * that icc_pmtu is non-zero, and that
19421 		 * delete_cnt != icc_unused + icc_offlink.
19422 		 */
19423 		icr.icr_offlink = 1;
19424 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19425 		/* Round up # deleted by truncating fraction */
19426 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19427 		icr.icr_onlink = 0;
19428 		ncr.ncr_host = 0;
19429 	} else {
19430 		/*
19431 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19432 		 * of onlink entries.  If we're here, then we know that
19433 		 * icc_onlink is non-zero, and that
19434 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19435 		 */
19436 		icr.icr_offlink = icr.icr_pmtu = 1;
19437 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19438 		    icc.icc_pmtu;
19439 		/* Round up # deleted by truncating fraction */
19440 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19441 		/* Using the same delete fraction as for onlink IREs */
19442 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19443 	}
19444 #ifdef DEBUG
19445 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19446 	    "fractions %d/%d/%d/%d\n",
19447 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19448 	    icc.icc_unused, icc.icc_offlink,
19449 	    icc.icc_pmtu, icc.icc_onlink,
19450 	    icr.icr_unused, icr.icr_offlink,
19451 	    icr.icr_pmtu, icr.icr_onlink));
19452 #endif
19453 	ire_walk(ire_cache_reclaim, (char *)&icr);
19454 	if (ncr.ncr_host != 0)
19455 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19456 		    (uchar_t *)&ncr);
19457 #ifdef DEBUG
19458 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19459 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19460 	ire_walk(ire_cache_count, (char *)&icc);
19461 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19462 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19463 	    icc.icc_pmtu, icc.icc_onlink));
19464 #endif
19465 }
19466 
19467 /*
19468  * ip_unbind is called when a copy of an unbind request is received from the
19469  * upper level protocol.  We remove this conn from any fanout hash list it is
19470  * on, and zero out the bind information.  No reply is expected up above.
19471  */
19472 mblk_t *
19473 ip_unbind(queue_t *q, mblk_t *mp)
19474 {
19475 	conn_t	*connp = Q_TO_CONN(q);
19476 
19477 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19478 
19479 	if (is_system_labeled() && connp->conn_anon_port) {
19480 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19481 		    connp->conn_mlp_type, connp->conn_ulp,
19482 		    ntohs(connp->conn_lport), B_FALSE);
19483 		connp->conn_anon_port = 0;
19484 	}
19485 	connp->conn_mlp_type = mlptSingle;
19486 
19487 	ipcl_hash_remove(connp);
19488 
19489 	ASSERT(mp->b_cont == NULL);
19490 	/*
19491 	 * Convert mp into a T_OK_ACK
19492 	 */
19493 	mp = mi_tpi_ok_ack_alloc(mp);
19494 
19495 	/*
19496 	 * should not happen in practice... T_OK_ACK is smaller than the
19497 	 * original message.
19498 	 */
19499 	if (mp == NULL)
19500 		return (NULL);
19501 
19502 	/*
19503 	 * Don't bzero the ports if its TCP since TCP still needs the
19504 	 * lport to remove it from its own bind hash. TCP will do the
19505 	 * cleanup.
19506 	 */
19507 	if (!IPCL_IS_TCP(connp))
19508 		bzero(&connp->u_port, sizeof (connp->u_port));
19509 
19510 	return (mp);
19511 }
19512 
19513 /*
19514  * Write side put procedure.  Outbound data, IOCTLs, responses from
19515  * resolvers, etc, come down through here.
19516  *
19517  * arg2 is always a queue_t *.
19518  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19519  * the zoneid.
19520  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19521  */
19522 void
19523 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19524 {
19525 	conn_t		*connp = NULL;
19526 	queue_t		*q = (queue_t *)arg2;
19527 	ipha_t		*ipha;
19528 #define	rptr	((uchar_t *)ipha)
19529 	ire_t		*ire = NULL;
19530 	ire_t		*sctp_ire = NULL;
19531 	uint32_t	v_hlen_tos_len;
19532 	ipaddr_t	dst;
19533 	mblk_t		*first_mp = NULL;
19534 	boolean_t	mctl_present;
19535 	ipsec_out_t	*io;
19536 	int		match_flags;
19537 	ill_t		*attach_ill = NULL;
19538 					/* Bind to IPIF_NOFAILOVER ill etc. */
19539 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19540 	ipif_t		*dst_ipif;
19541 	boolean_t	multirt_need_resolve = B_FALSE;
19542 	mblk_t		*copy_mp = NULL;
19543 	int		err;
19544 	zoneid_t	zoneid;
19545 	int	adjust;
19546 	uint16_t iplen;
19547 	boolean_t	need_decref = B_FALSE;
19548 	boolean_t	ignore_dontroute = B_FALSE;
19549 	boolean_t	ignore_nexthop = B_FALSE;
19550 	boolean_t	ip_nexthop = B_FALSE;
19551 	ipaddr_t	nexthop_addr;
19552 
19553 #ifdef	_BIG_ENDIAN
19554 #define	V_HLEN	(v_hlen_tos_len >> 24)
19555 #else
19556 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19557 #endif
19558 
19559 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19560 	    "ip_wput_start: q %p", q);
19561 
19562 	/*
19563 	 * ip_wput fast path
19564 	 */
19565 
19566 	/* is packet from ARP ? */
19567 	if (q->q_next != NULL) {
19568 		zoneid = (zoneid_t)(uintptr_t)arg;
19569 		goto qnext;
19570 	}
19571 
19572 	connp = (conn_t *)arg;
19573 	ASSERT(connp != NULL);
19574 	zoneid = connp->conn_zoneid;
19575 
19576 	/* is queue flow controlled? */
19577 	if ((q->q_first != NULL || connp->conn_draining) &&
19578 	    (caller == IP_WPUT)) {
19579 		ASSERT(!need_decref);
19580 		(void) putq(q, mp);
19581 		return;
19582 	}
19583 
19584 	/* Multidata transmit? */
19585 	if (DB_TYPE(mp) == M_MULTIDATA) {
19586 		/*
19587 		 * We should never get here, since all Multidata messages
19588 		 * originating from tcp should have been directed over to
19589 		 * tcp_multisend() in the first place.
19590 		 */
19591 		BUMP_MIB(&ip_mib, ipOutDiscards);
19592 		freemsg(mp);
19593 		return;
19594 	} else if (DB_TYPE(mp) != M_DATA)
19595 		goto notdata;
19596 
19597 	if (mp->b_flag & MSGHASREF) {
19598 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19599 		mp->b_flag &= ~MSGHASREF;
19600 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19601 		need_decref = B_TRUE;
19602 	}
19603 	ipha = (ipha_t *)mp->b_rptr;
19604 
19605 	/* is IP header non-aligned or mblk smaller than basic IP header */
19606 #ifndef SAFETY_BEFORE_SPEED
19607 	if (!OK_32PTR(rptr) ||
19608 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19609 		goto hdrtoosmall;
19610 #endif
19611 
19612 	ASSERT(OK_32PTR(ipha));
19613 
19614 	/*
19615 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19616 	 * wrong version, we'll catch it again in ip_output_v6.
19617 	 *
19618 	 * Note that this is *only* locally-generated output here, and never
19619 	 * forwarded data, and that we need to deal only with transports that
19620 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19621 	 * label.)
19622 	 */
19623 	if (is_system_labeled() &&
19624 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19625 	    !connp->conn_ulp_labeled) {
19626 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19627 		    connp->conn_mac_exempt);
19628 		ipha = (ipha_t *)mp->b_rptr;
19629 		if (err != 0) {
19630 			first_mp = mp;
19631 			if (err == EINVAL)
19632 				goto icmp_parameter_problem;
19633 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19634 			goto drop_pkt;
19635 		}
19636 		iplen = ntohs(ipha->ipha_length) + adjust;
19637 		ipha->ipha_length = htons(iplen);
19638 	}
19639 
19640 	/*
19641 	 * If there is a policy, try to attach an ipsec_out in
19642 	 * the front. At the end, first_mp either points to a
19643 	 * M_DATA message or IPSEC_OUT message linked to a
19644 	 * M_DATA message. We have to do it now as we might
19645 	 * lose the "conn" if we go through ip_newroute.
19646 	 */
19647 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19648 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
19649 		    ipha->ipha_protocol)) == NULL)) {
19650 			if (need_decref)
19651 				CONN_DEC_REF(connp);
19652 			return;
19653 		} else {
19654 			ASSERT(mp->b_datap->db_type == M_CTL);
19655 			first_mp = mp;
19656 			mp = mp->b_cont;
19657 			mctl_present = B_TRUE;
19658 		}
19659 	} else {
19660 		first_mp = mp;
19661 		mctl_present = B_FALSE;
19662 	}
19663 
19664 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19665 
19666 	/* is wrong version or IP options present */
19667 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19668 		goto version_hdrlen_check;
19669 	dst = ipha->ipha_dst;
19670 
19671 	if (connp->conn_nofailover_ill != NULL) {
19672 		attach_ill = conn_get_held_ill(connp,
19673 		    &connp->conn_nofailover_ill, &err);
19674 		if (err == ILL_LOOKUP_FAILED) {
19675 			if (need_decref)
19676 				CONN_DEC_REF(connp);
19677 			freemsg(first_mp);
19678 			return;
19679 		}
19680 	}
19681 
19682 	/* is packet multicast? */
19683 	if (CLASSD(dst))
19684 		goto multicast;
19685 
19686 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19687 	    (connp->conn_nexthop_set)) {
19688 		/*
19689 		 * If the destination is a broadcast or a loopback
19690 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
19691 		 * through the standard path. But in the case of local
19692 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
19693 		 * the standard path not IP_XMIT_IF.
19694 		 */
19695 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19696 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
19697 		    (ire->ire_type != IRE_LOOPBACK))) {
19698 			if ((connp->conn_dontroute ||
19699 			    connp->conn_nexthop_set) && (ire != NULL) &&
19700 			    (ire->ire_type == IRE_LOCAL))
19701 				goto standard_path;
19702 
19703 			if (ire != NULL) {
19704 				ire_refrele(ire);
19705 				/* No more access to ire */
19706 				ire = NULL;
19707 			}
19708 			/*
19709 			 * bypass routing checks and go directly to
19710 			 * interface.
19711 			 */
19712 			if (connp->conn_dontroute) {
19713 				goto dontroute;
19714 			} else if (connp->conn_nexthop_set) {
19715 				ip_nexthop = B_TRUE;
19716 				nexthop_addr = connp->conn_nexthop_v4;
19717 				goto send_from_ill;
19718 			}
19719 
19720 			/*
19721 			 * If IP_XMIT_IF socket option is set,
19722 			 * then we allow unicast and multicast
19723 			 * packets to go through the ill. It is
19724 			 * quite possible that the destination
19725 			 * is not in the ire cache table and we
19726 			 * do not want to go to ip_newroute()
19727 			 * instead we call ip_newroute_ipif.
19728 			 */
19729 			xmit_ill = conn_get_held_ill(connp,
19730 			    &connp->conn_xmit_if_ill, &err);
19731 			if (err == ILL_LOOKUP_FAILED) {
19732 				if (attach_ill != NULL)
19733 					ill_refrele(attach_ill);
19734 				if (need_decref)
19735 					CONN_DEC_REF(connp);
19736 				freemsg(first_mp);
19737 				return;
19738 			}
19739 			goto send_from_ill;
19740 		}
19741 standard_path:
19742 		/* Must be a broadcast, a loopback or a local ire */
19743 		if (ire != NULL) {
19744 			ire_refrele(ire);
19745 			/* No more access to ire */
19746 			ire = NULL;
19747 		}
19748 	}
19749 
19750 	if (attach_ill != NULL)
19751 		goto send_from_ill;
19752 
19753 	/*
19754 	 * We cache IRE_CACHEs to avoid lookups. We don't do
19755 	 * this for the tcp global queue and listen end point
19756 	 * as it does not really have a real destination to
19757 	 * talk to.  This is also true for SCTP.
19758 	 */
19759 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
19760 	    !connp->conn_fully_bound) {
19761 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19762 		if (ire == NULL)
19763 			goto noirefound;
19764 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19765 		    "ip_wput_end: q %p (%S)", q, "end");
19766 
19767 		/*
19768 		 * Check if the ire has the RTF_MULTIRT flag, inherited
19769 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19770 		 */
19771 		if (ire->ire_flags & RTF_MULTIRT) {
19772 
19773 			/*
19774 			 * Force the TTL of multirouted packets if required.
19775 			 * The TTL of such packets is bounded by the
19776 			 * ip_multirt_ttl ndd variable.
19777 			 */
19778 			if ((ip_multirt_ttl > 0) &&
19779 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
19780 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
19781 				    "(was %d), dst 0x%08x\n",
19782 				    ip_multirt_ttl, ipha->ipha_ttl,
19783 				    ntohl(ire->ire_addr)));
19784 				ipha->ipha_ttl = ip_multirt_ttl;
19785 			}
19786 			/*
19787 			 * We look at this point if there are pending
19788 			 * unresolved routes. ire_multirt_resolvable()
19789 			 * checks in O(n) that all IRE_OFFSUBNET ire
19790 			 * entries for the packet's destination and
19791 			 * flagged RTF_MULTIRT are currently resolved.
19792 			 * If some remain unresolved, we make a copy
19793 			 * of the current message. It will be used
19794 			 * to initiate additional route resolutions.
19795 			 */
19796 			multirt_need_resolve =
19797 			    ire_multirt_need_resolve(ire->ire_addr,
19798 			    MBLK_GETLABEL(first_mp));
19799 			ip2dbg(("ip_wput[TCP]: ire %p, "
19800 			    "multirt_need_resolve %d, first_mp %p\n",
19801 			    (void *)ire, multirt_need_resolve,
19802 			    (void *)first_mp));
19803 			if (multirt_need_resolve) {
19804 				copy_mp = copymsg(first_mp);
19805 				if (copy_mp != NULL) {
19806 					MULTIRT_DEBUG_TAG(copy_mp);
19807 				}
19808 			}
19809 		}
19810 
19811 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19812 
19813 		/*
19814 		 * Try to resolve another multiroute if
19815 		 * ire_multirt_need_resolve() deemed it necessary.
19816 		 */
19817 		if (copy_mp != NULL) {
19818 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19819 		}
19820 		if (need_decref)
19821 			CONN_DEC_REF(connp);
19822 		return;
19823 	}
19824 
19825 	/*
19826 	 * Access to conn_ire_cache. (protected by conn_lock)
19827 	 *
19828 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
19829 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
19830 	 * send a packet or two with the IRE_CACHE that is going away.
19831 	 * Access to the ire requires an ire refhold on the ire prior to
19832 	 * its use since an interface unplumb thread may delete the cached
19833 	 * ire and release the refhold at any time.
19834 	 *
19835 	 * Caching an ire in the conn_ire_cache
19836 	 *
19837 	 * o Caching an ire pointer in the conn requires a strict check for
19838 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
19839 	 * ires  before cleaning up the conns. So the caching of an ire pointer
19840 	 * in the conn is done after making sure under the bucket lock that the
19841 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
19842 	 * caching an ire after the unplumb thread has cleaned up the conn.
19843 	 * If the conn does not send a packet subsequently the unplumb thread
19844 	 * will be hanging waiting for the ire count to drop to zero.
19845 	 *
19846 	 * o We also need to atomically test for a null conn_ire_cache and
19847 	 * set the conn_ire_cache under the the protection of the conn_lock
19848 	 * to avoid races among concurrent threads trying to simultaneously
19849 	 * cache an ire in the conn_ire_cache.
19850 	 */
19851 	mutex_enter(&connp->conn_lock);
19852 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
19853 
19854 	if (ire != NULL && ire->ire_addr == dst &&
19855 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19856 
19857 		IRE_REFHOLD(ire);
19858 		mutex_exit(&connp->conn_lock);
19859 
19860 	} else {
19861 		boolean_t cached = B_FALSE;
19862 		connp->conn_ire_cache = NULL;
19863 		mutex_exit(&connp->conn_lock);
19864 		/* Release the old ire */
19865 		if (ire != NULL && sctp_ire == NULL)
19866 			IRE_REFRELE_NOTR(ire);
19867 
19868 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19869 		if (ire == NULL)
19870 			goto noirefound;
19871 		IRE_REFHOLD_NOTR(ire);
19872 
19873 		mutex_enter(&connp->conn_lock);
19874 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
19875 		    connp->conn_ire_cache == NULL) {
19876 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19877 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19878 				connp->conn_ire_cache = ire;
19879 				cached = B_TRUE;
19880 			}
19881 			rw_exit(&ire->ire_bucket->irb_lock);
19882 		}
19883 		mutex_exit(&connp->conn_lock);
19884 
19885 		/*
19886 		 * We can continue to use the ire but since it was
19887 		 * not cached, we should drop the extra reference.
19888 		 */
19889 		if (!cached)
19890 			IRE_REFRELE_NOTR(ire);
19891 	}
19892 
19893 
19894 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19895 	    "ip_wput_end: q %p (%S)", q, "end");
19896 
19897 	/*
19898 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19899 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19900 	 */
19901 	if (ire->ire_flags & RTF_MULTIRT) {
19902 
19903 		/*
19904 		 * Force the TTL of multirouted packets if required.
19905 		 * The TTL of such packets is bounded by the
19906 		 * ip_multirt_ttl ndd variable.
19907 		 */
19908 		if ((ip_multirt_ttl > 0) &&
19909 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19910 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19911 			    "(was %d), dst 0x%08x\n",
19912 			    ip_multirt_ttl, ipha->ipha_ttl,
19913 			    ntohl(ire->ire_addr)));
19914 			ipha->ipha_ttl = ip_multirt_ttl;
19915 		}
19916 
19917 		/*
19918 		 * At this point, we check to see if there are any pending
19919 		 * unresolved routes. ire_multirt_resolvable()
19920 		 * checks in O(n) that all IRE_OFFSUBNET ire
19921 		 * entries for the packet's destination and
19922 		 * flagged RTF_MULTIRT are currently resolved.
19923 		 * If some remain unresolved, we make a copy
19924 		 * of the current message. It will be used
19925 		 * to initiate additional route resolutions.
19926 		 */
19927 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19928 		    MBLK_GETLABEL(first_mp));
19929 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19930 		    "multirt_need_resolve %d, first_mp %p\n",
19931 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19932 		if (multirt_need_resolve) {
19933 			copy_mp = copymsg(first_mp);
19934 			if (copy_mp != NULL) {
19935 				MULTIRT_DEBUG_TAG(copy_mp);
19936 			}
19937 		}
19938 	}
19939 
19940 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19941 
19942 	/*
19943 	 * Try to resolve another multiroute if
19944 	 * ire_multirt_resolvable() deemed it necessary
19945 	 */
19946 	if (copy_mp != NULL) {
19947 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19948 	}
19949 	if (need_decref)
19950 		CONN_DEC_REF(connp);
19951 	return;
19952 
19953 qnext:
19954 	/*
19955 	 * Upper Level Protocols pass down complete IP datagrams
19956 	 * as M_DATA messages.	Everything else is a sideshow.
19957 	 *
19958 	 * 1) We could be re-entering ip_wput because of ip_neworute
19959 	 *    in which case we could have a IPSEC_OUT message. We
19960 	 *    need to pass through ip_wput like other datagrams and
19961 	 *    hence cannot branch to ip_wput_nondata.
19962 	 *
19963 	 * 2) ARP, AH, ESP, and other clients who are on the module
19964 	 *    instance of IP stream, give us something to deal with.
19965 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19966 	 *
19967 	 * 3) ICMP replies also could come here.
19968 	 */
19969 	if (DB_TYPE(mp) != M_DATA) {
19970 	    notdata:
19971 		if (DB_TYPE(mp) == M_CTL) {
19972 			/*
19973 			 * M_CTL messages are used by ARP, AH and ESP to
19974 			 * communicate with IP. We deal with IPSEC_IN and
19975 			 * IPSEC_OUT here. ip_wput_nondata handles other
19976 			 * cases.
19977 			 */
19978 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19979 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19980 				first_mp = mp->b_cont;
19981 				first_mp->b_flag &= ~MSGHASREF;
19982 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19983 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19984 				CONN_DEC_REF(connp);
19985 				connp = NULL;
19986 			}
19987 			if (ii->ipsec_info_type == IPSEC_IN) {
19988 				/*
19989 				 * Either this message goes back to
19990 				 * IPSEC for further processing or to
19991 				 * ULP after policy checks.
19992 				 */
19993 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19994 				return;
19995 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19996 				io = (ipsec_out_t *)ii;
19997 				if (io->ipsec_out_proc_begin) {
19998 					/*
19999 					 * IPSEC processing has already started.
20000 					 * Complete it.
20001 					 * IPQoS notes: We don't care what is
20002 					 * in ipsec_out_ill_index since this
20003 					 * won't be processed for IPQoS policies
20004 					 * in ipsec_out_process.
20005 					 */
20006 					ipsec_out_process(q, mp, NULL,
20007 					    io->ipsec_out_ill_index);
20008 					return;
20009 				} else {
20010 					connp = (q->q_next != NULL) ?
20011 					    NULL : Q_TO_CONN(q);
20012 					first_mp = mp;
20013 					mp = mp->b_cont;
20014 					mctl_present = B_TRUE;
20015 				}
20016 				zoneid = io->ipsec_out_zoneid;
20017 				ASSERT(zoneid != ALL_ZONES);
20018 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20019 				/*
20020 				 * It's an IPsec control message requesting
20021 				 * an SADB update to be sent to the IPsec
20022 				 * hardware acceleration capable ills.
20023 				 */
20024 				ipsec_ctl_t *ipsec_ctl =
20025 				    (ipsec_ctl_t *)mp->b_rptr;
20026 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20027 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20028 				mblk_t *cmp = mp->b_cont;
20029 
20030 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20031 				ASSERT(cmp != NULL);
20032 
20033 				freeb(mp);
20034 				ill_ipsec_capab_send_all(satype, cmp, sa);
20035 				return;
20036 			} else {
20037 				/*
20038 				 * This must be ARP or special TSOL signaling.
20039 				 */
20040 				ip_wput_nondata(NULL, q, mp, NULL);
20041 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20042 				    "ip_wput_end: q %p (%S)", q, "nondata");
20043 				return;
20044 			}
20045 		} else {
20046 			/*
20047 			 * This must be non-(ARP/AH/ESP) messages.
20048 			 */
20049 			ASSERT(!need_decref);
20050 			ip_wput_nondata(NULL, q, mp, NULL);
20051 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20052 			    "ip_wput_end: q %p (%S)", q, "nondata");
20053 			return;
20054 		}
20055 	} else {
20056 		first_mp = mp;
20057 		mctl_present = B_FALSE;
20058 	}
20059 
20060 	ASSERT(first_mp != NULL);
20061 	/*
20062 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20063 	 * to make sure that this packet goes out on the same interface it
20064 	 * came in. We handle that here.
20065 	 */
20066 	if (mctl_present) {
20067 		uint_t ifindex;
20068 
20069 		io = (ipsec_out_t *)first_mp->b_rptr;
20070 		if (io->ipsec_out_attach_if ||
20071 		    io->ipsec_out_xmit_if ||
20072 		    io->ipsec_out_ip_nexthop) {
20073 			ill_t	*ill;
20074 
20075 			/*
20076 			 * We may have lost the conn context if we are
20077 			 * coming here from ip_newroute(). Copy the
20078 			 * nexthop information.
20079 			 */
20080 			if (io->ipsec_out_ip_nexthop) {
20081 				ip_nexthop = B_TRUE;
20082 				nexthop_addr = io->ipsec_out_nexthop_addr;
20083 
20084 				ipha = (ipha_t *)mp->b_rptr;
20085 				dst = ipha->ipha_dst;
20086 				goto send_from_ill;
20087 			} else {
20088 				ASSERT(io->ipsec_out_ill_index != 0);
20089 				ifindex = io->ipsec_out_ill_index;
20090 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20091 				    NULL, NULL, NULL, NULL);
20092 				/*
20093 				 * ipsec_out_xmit_if bit is used to tell
20094 				 * ip_wput to use the ill to send outgoing data
20095 				 * as we have no conn when data comes from ICMP
20096 				 * error msg routines. Currently this feature is
20097 				 * only used by ip_mrtun_forward routine.
20098 				 */
20099 				if (io->ipsec_out_xmit_if) {
20100 					xmit_ill = ill;
20101 					if (xmit_ill == NULL) {
20102 						ip1dbg(("ip_output:bad ifindex "
20103 						    "for xmit_ill %d\n",
20104 						    ifindex));
20105 						freemsg(first_mp);
20106 						BUMP_MIB(&ip_mib,
20107 						    ipOutDiscards);
20108 						ASSERT(!need_decref);
20109 						return;
20110 					}
20111 					/* Free up the ipsec_out_t mblk */
20112 					ASSERT(first_mp->b_cont == mp);
20113 					first_mp->b_cont = NULL;
20114 					freeb(first_mp);
20115 					/* Just send the IP header+ICMP+data */
20116 					first_mp = mp;
20117 					ipha = (ipha_t *)mp->b_rptr;
20118 					dst = ipha->ipha_dst;
20119 					goto send_from_ill;
20120 				} else {
20121 					attach_ill = ill;
20122 				}
20123 
20124 				if (attach_ill == NULL) {
20125 					ASSERT(xmit_ill == NULL);
20126 					ip1dbg(("ip_output: bad ifindex for "
20127 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20128 					    ifindex));
20129 					freemsg(first_mp);
20130 					BUMP_MIB(&ip_mib, ipOutDiscards);
20131 					ASSERT(!need_decref);
20132 					return;
20133 				}
20134 			}
20135 		}
20136 	}
20137 
20138 	ASSERT(xmit_ill == NULL);
20139 
20140 	/* We have a complete IP datagram heading outbound. */
20141 	ipha = (ipha_t *)mp->b_rptr;
20142 
20143 #ifndef SPEED_BEFORE_SAFETY
20144 	/*
20145 	 * Make sure we have a full-word aligned message and that at least
20146 	 * a simple IP header is accessible in the first message.  If not,
20147 	 * try a pullup.
20148 	 */
20149 	if (!OK_32PTR(rptr) ||
20150 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20151 	    hdrtoosmall:
20152 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20153 			BUMP_MIB(&ip_mib, ipOutDiscards);
20154 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20155 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20156 			if (first_mp == NULL)
20157 				first_mp = mp;
20158 			goto drop_pkt;
20159 		}
20160 
20161 		/* This function assumes that mp points to an IPv4 packet. */
20162 		if (is_system_labeled() && q->q_next == NULL &&
20163 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20164 		    !connp->conn_ulp_labeled) {
20165 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20166 			    &adjust, connp->conn_mac_exempt);
20167 			ipha = (ipha_t *)mp->b_rptr;
20168 			if (first_mp != NULL)
20169 				first_mp->b_cont = mp;
20170 			if (err != 0) {
20171 				if (first_mp == NULL)
20172 					first_mp = mp;
20173 				if (err == EINVAL)
20174 					goto icmp_parameter_problem;
20175 				ip2dbg(("ip_wput: label check failed (%d)\n",
20176 				    err));
20177 				goto drop_pkt;
20178 			}
20179 			iplen = ntohs(ipha->ipha_length) + adjust;
20180 			ipha->ipha_length = htons(iplen);
20181 		}
20182 
20183 		ipha = (ipha_t *)mp->b_rptr;
20184 		if (first_mp == NULL) {
20185 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20186 			/*
20187 			 * If we got here because of "goto hdrtoosmall"
20188 			 * We need to attach a IPSEC_OUT.
20189 			 */
20190 			if (connp->conn_out_enforce_policy) {
20191 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20192 				    NULL, ipha->ipha_protocol)) == NULL)) {
20193 					if (need_decref)
20194 						CONN_DEC_REF(connp);
20195 					return;
20196 				} else {
20197 					ASSERT(mp->b_datap->db_type == M_CTL);
20198 					first_mp = mp;
20199 					mp = mp->b_cont;
20200 					mctl_present = B_TRUE;
20201 				}
20202 			} else {
20203 				first_mp = mp;
20204 				mctl_present = B_FALSE;
20205 			}
20206 		}
20207 	}
20208 #endif
20209 
20210 	/* Most of the code below is written for speed, not readability */
20211 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20212 
20213 	/*
20214 	 * If ip_newroute() fails, we're going to need a full
20215 	 * header for the icmp wraparound.
20216 	 */
20217 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20218 		uint_t	v_hlen;
20219 	    version_hdrlen_check:
20220 		ASSERT(first_mp != NULL);
20221 		v_hlen = V_HLEN;
20222 		/*
20223 		 * siphon off IPv6 packets coming down from transport
20224 		 * layer modules here.
20225 		 * Note: high-order bit carries NUD reachability confirmation
20226 		 */
20227 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20228 			/*
20229 			 * XXX implement a IPv4 and IPv6 packet counter per
20230 			 * conn and switch when ratio exceeds e.g. 10:1
20231 			 */
20232 #ifdef notyet
20233 			if (q->q_next == NULL) /* Avoid ill queue */
20234 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
20235 #endif
20236 			BUMP_MIB(&ip_mib, ipOutIPv6);
20237 			ASSERT(xmit_ill == NULL);
20238 			if (attach_ill != NULL)
20239 				ill_refrele(attach_ill);
20240 			if (need_decref)
20241 				mp->b_flag |= MSGHASREF;
20242 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20243 			return;
20244 		}
20245 
20246 		if ((v_hlen >> 4) != IP_VERSION) {
20247 			BUMP_MIB(&ip_mib, ipOutDiscards);
20248 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20249 			    "ip_wput_end: q %p (%S)", q, "badvers");
20250 			goto drop_pkt;
20251 		}
20252 		/*
20253 		 * Is the header length at least 20 bytes?
20254 		 *
20255 		 * Are there enough bytes accessible in the header?  If
20256 		 * not, try a pullup.
20257 		 */
20258 		v_hlen &= 0xF;
20259 		v_hlen <<= 2;
20260 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20261 			BUMP_MIB(&ip_mib, ipOutDiscards);
20262 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20263 			    "ip_wput_end: q %p (%S)", q, "badlen");
20264 			goto drop_pkt;
20265 		}
20266 		if (v_hlen > (mp->b_wptr - rptr)) {
20267 			if (!pullupmsg(mp, v_hlen)) {
20268 				BUMP_MIB(&ip_mib, ipOutDiscards);
20269 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20270 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20271 				goto drop_pkt;
20272 			}
20273 			ipha = (ipha_t *)mp->b_rptr;
20274 		}
20275 		/*
20276 		 * Move first entry from any source route into ipha_dst and
20277 		 * verify the options
20278 		 */
20279 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
20280 			ASSERT(xmit_ill == NULL);
20281 			if (attach_ill != NULL)
20282 				ill_refrele(attach_ill);
20283 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20284 			    "ip_wput_end: q %p (%S)", q, "badopts");
20285 			if (need_decref)
20286 				CONN_DEC_REF(connp);
20287 			return;
20288 		}
20289 	}
20290 	dst = ipha->ipha_dst;
20291 
20292 	/*
20293 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20294 	 * we have to run the packet through ip_newroute which will take
20295 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20296 	 * a resolver, or assigning a default gateway, etc.
20297 	 */
20298 	if (CLASSD(dst)) {
20299 		ipif_t	*ipif;
20300 		uint32_t setsrc = 0;
20301 
20302 	    multicast:
20303 		ASSERT(first_mp != NULL);
20304 		ASSERT(xmit_ill == NULL);
20305 		ip2dbg(("ip_wput: CLASSD\n"));
20306 		if (connp == NULL) {
20307 			/*
20308 			 * Use the first good ipif on the ill.
20309 			 * XXX Should this ever happen? (Appears
20310 			 * to show up with just ppp and no ethernet due
20311 			 * to in.rdisc.)
20312 			 * However, ire_send should be able to
20313 			 * call ip_wput_ire directly.
20314 			 *
20315 			 * XXX Also, this can happen for ICMP and other packets
20316 			 * with multicast source addresses.  Perhaps we should
20317 			 * fix things so that we drop the packet in question,
20318 			 * but for now, just run with it.
20319 			 */
20320 			ill_t *ill = (ill_t *)q->q_ptr;
20321 
20322 			/*
20323 			 * Don't honor attach_if for this case. If ill
20324 			 * is part of the group, ipif could belong to
20325 			 * any ill and we cannot maintain attach_ill
20326 			 * and ipif_ill same anymore and the assert
20327 			 * below would fail.
20328 			 */
20329 			if (mctl_present && io->ipsec_out_attach_if) {
20330 				io->ipsec_out_ill_index = 0;
20331 				io->ipsec_out_attach_if = B_FALSE;
20332 				ASSERT(attach_ill != NULL);
20333 				ill_refrele(attach_ill);
20334 				attach_ill = NULL;
20335 			}
20336 
20337 			ASSERT(attach_ill == NULL);
20338 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20339 			if (ipif == NULL) {
20340 				if (need_decref)
20341 					CONN_DEC_REF(connp);
20342 				freemsg(first_mp);
20343 				return;
20344 			}
20345 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20346 			    ntohl(dst), ill->ill_name));
20347 		} else {
20348 			/*
20349 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
20350 			 * IP_XMIT_IF is honoured.
20351 			 * Block comment above this function explains the
20352 			 * locking mechanism used here
20353 			 */
20354 			xmit_ill = conn_get_held_ill(connp,
20355 			    &connp->conn_xmit_if_ill, &err);
20356 			if (err == ILL_LOOKUP_FAILED) {
20357 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
20358 				goto drop_pkt;
20359 			}
20360 			if (xmit_ill == NULL) {
20361 				ipif = conn_get_held_ipif(connp,
20362 				    &connp->conn_multicast_ipif, &err);
20363 				if (err == IPIF_LOOKUP_FAILED) {
20364 					ip1dbg(("ip_wput: No ipif for "
20365 					    "multicast\n"));
20366 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20367 					goto drop_pkt;
20368 				}
20369 			}
20370 			if (xmit_ill != NULL) {
20371 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20372 				if (ipif == NULL) {
20373 					ip1dbg(("ip_wput: No ipif for "
20374 					    "IP_XMIT_IF\n"));
20375 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20376 					goto drop_pkt;
20377 				}
20378 			} else if (ipif == NULL || ipif->ipif_isv6) {
20379 				/*
20380 				 * We must do this ipif determination here
20381 				 * else we could pass through ip_newroute
20382 				 * and come back here without the conn context.
20383 				 *
20384 				 * Note: we do late binding i.e. we bind to
20385 				 * the interface when the first packet is sent.
20386 				 * For performance reasons we do not rebind on
20387 				 * each packet but keep the binding until the
20388 				 * next IP_MULTICAST_IF option.
20389 				 *
20390 				 * conn_multicast_{ipif,ill} are shared between
20391 				 * IPv4 and IPv6 and AF_INET6 sockets can
20392 				 * send both IPv4 and IPv6 packets. Hence
20393 				 * we have to check that "isv6" matches above.
20394 				 */
20395 				if (ipif != NULL)
20396 					ipif_refrele(ipif);
20397 				ipif = ipif_lookup_group(dst, zoneid);
20398 				if (ipif == NULL) {
20399 					ip1dbg(("ip_wput: No ipif for "
20400 					    "multicast\n"));
20401 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20402 					goto drop_pkt;
20403 				}
20404 				err = conn_set_held_ipif(connp,
20405 				    &connp->conn_multicast_ipif, ipif);
20406 				if (err == IPIF_LOOKUP_FAILED) {
20407 					ipif_refrele(ipif);
20408 					ip1dbg(("ip_wput: No ipif for "
20409 					    "multicast\n"));
20410 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20411 					goto drop_pkt;
20412 				}
20413 			}
20414 		}
20415 		ASSERT(!ipif->ipif_isv6);
20416 		/*
20417 		 * As we may lose the conn by the time we reach ip_wput_ire,
20418 		 * we copy conn_multicast_loop and conn_dontroute on to an
20419 		 * ipsec_out. In case if this datagram goes out secure,
20420 		 * we need the ill_index also. Copy that also into the
20421 		 * ipsec_out.
20422 		 */
20423 		if (mctl_present) {
20424 			io = (ipsec_out_t *)first_mp->b_rptr;
20425 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20426 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20427 		} else {
20428 			ASSERT(mp == first_mp);
20429 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20430 			    BPRI_HI)) == NULL) {
20431 				ipif_refrele(ipif);
20432 				first_mp = mp;
20433 				goto drop_pkt;
20434 			}
20435 			first_mp->b_datap->db_type = M_CTL;
20436 			first_mp->b_wptr += sizeof (ipsec_info_t);
20437 			/* ipsec_out_secure is B_FALSE now */
20438 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20439 			io = (ipsec_out_t *)first_mp->b_rptr;
20440 			io->ipsec_out_type = IPSEC_OUT;
20441 			io->ipsec_out_len = sizeof (ipsec_out_t);
20442 			io->ipsec_out_use_global_policy = B_TRUE;
20443 			first_mp->b_cont = mp;
20444 			mctl_present = B_TRUE;
20445 		}
20446 		if (attach_ill != NULL) {
20447 			ASSERT(attach_ill == ipif->ipif_ill);
20448 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20449 
20450 			/*
20451 			 * Check if we need an ire that will not be
20452 			 * looked up by anybody else i.e. HIDDEN.
20453 			 */
20454 			if (ill_is_probeonly(attach_ill)) {
20455 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20456 			}
20457 			io->ipsec_out_ill_index =
20458 			    attach_ill->ill_phyint->phyint_ifindex;
20459 			io->ipsec_out_attach_if = B_TRUE;
20460 		} else {
20461 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20462 			io->ipsec_out_ill_index =
20463 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20464 		}
20465 		if (connp != NULL) {
20466 			io->ipsec_out_multicast_loop =
20467 			    connp->conn_multicast_loop;
20468 			io->ipsec_out_dontroute = connp->conn_dontroute;
20469 			io->ipsec_out_zoneid = connp->conn_zoneid;
20470 		}
20471 		/*
20472 		 * If the application uses IP_MULTICAST_IF with
20473 		 * different logical addresses of the same ILL, we
20474 		 * need to make sure that the soruce address of
20475 		 * the packet matches the logical IP address used
20476 		 * in the option. We do it by initializing ipha_src
20477 		 * here. This should keep IPSEC also happy as
20478 		 * when we return from IPSEC processing, we don't
20479 		 * have to worry about getting the right address on
20480 		 * the packet. Thus it is sufficient to look for
20481 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20482 		 * MATCH_IRE_IPIF.
20483 		 *
20484 		 * NOTE : We need to do it for non-secure case also as
20485 		 * this might go out secure if there is a global policy
20486 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20487 		 * address, the source should be initialized already and
20488 		 * hence we won't be initializing here.
20489 		 *
20490 		 * As we do not have the ire yet, it is possible that
20491 		 * we set the source address here and then later discover
20492 		 * that the ire implies the source address to be assigned
20493 		 * through the RTF_SETSRC flag.
20494 		 * In that case, the setsrc variable will remind us
20495 		 * that overwritting the source address by the one
20496 		 * of the RTF_SETSRC-flagged ire is allowed.
20497 		 */
20498 		if (ipha->ipha_src == INADDR_ANY &&
20499 		    (connp == NULL || !connp->conn_unspec_src)) {
20500 			ipha->ipha_src = ipif->ipif_src_addr;
20501 			setsrc = RTF_SETSRC;
20502 		}
20503 		/*
20504 		 * Find an IRE which matches the destination and the outgoing
20505 		 * queue (i.e. the outgoing interface.)
20506 		 * For loopback use a unicast IP address for
20507 		 * the ire lookup.
20508 		 */
20509 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20510 		    PHYI_LOOPBACK) {
20511 			dst = ipif->ipif_lcl_addr;
20512 		}
20513 		/*
20514 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20515 		 * We don't need to lookup ire in ctable as the packet
20516 		 * needs to be sent to the destination through the specified
20517 		 * ill irrespective of ires in the cache table.
20518 		 */
20519 		ire = NULL;
20520 		if (xmit_ill == NULL) {
20521 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20522 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20523 		}
20524 
20525 		/*
20526 		 * refrele attach_ill as its not needed anymore.
20527 		 */
20528 		if (attach_ill != NULL) {
20529 			ill_refrele(attach_ill);
20530 			attach_ill = NULL;
20531 		}
20532 
20533 		if (ire == NULL) {
20534 			/*
20535 			 * Multicast loopback and multicast forwarding is
20536 			 * done in ip_wput_ire.
20537 			 *
20538 			 * Mark this packet to make it be delivered to
20539 			 * ip_wput_ire after the new ire has been
20540 			 * created.
20541 			 *
20542 			 * The call to ip_newroute_ipif takes into account
20543 			 * the setsrc reminder. In any case, we take care
20544 			 * of the RTF_MULTIRT flag.
20545 			 */
20546 			mp->b_prev = mp->b_next = NULL;
20547 			if (xmit_ill == NULL ||
20548 			    xmit_ill->ill_ipif_up_count > 0) {
20549 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20550 				    setsrc | RTF_MULTIRT, zoneid);
20551 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20552 				    "ip_wput_end: q %p (%S)", q, "noire");
20553 			} else {
20554 				freemsg(first_mp);
20555 			}
20556 			ipif_refrele(ipif);
20557 			if (xmit_ill != NULL)
20558 				ill_refrele(xmit_ill);
20559 			if (need_decref)
20560 				CONN_DEC_REF(connp);
20561 			return;
20562 		}
20563 
20564 		ipif_refrele(ipif);
20565 		ipif = NULL;
20566 		ASSERT(xmit_ill == NULL);
20567 
20568 		/*
20569 		 * Honor the RTF_SETSRC flag for multicast packets,
20570 		 * if allowed by the setsrc reminder.
20571 		 */
20572 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20573 			ipha->ipha_src = ire->ire_src_addr;
20574 		}
20575 
20576 		/*
20577 		 * Unconditionally force the TTL to 1 for
20578 		 * multirouted multicast packets:
20579 		 * multirouted multicast should not cross
20580 		 * multicast routers.
20581 		 */
20582 		if (ire->ire_flags & RTF_MULTIRT) {
20583 			if (ipha->ipha_ttl > 1) {
20584 				ip2dbg(("ip_wput: forcing multicast "
20585 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20586 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20587 				ipha->ipha_ttl = 1;
20588 			}
20589 		}
20590 	} else {
20591 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20592 		if ((ire != NULL) && (ire->ire_type &
20593 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20594 			ignore_dontroute = B_TRUE;
20595 			ignore_nexthop = B_TRUE;
20596 		}
20597 		if (ire != NULL) {
20598 			ire_refrele(ire);
20599 			ire = NULL;
20600 		}
20601 		/*
20602 		 * Guard against coming in from arp in which case conn is NULL.
20603 		 * Also guard against non M_DATA with dontroute set but
20604 		 * destined to local, loopback or broadcast addresses.
20605 		 */
20606 		if (connp != NULL && connp->conn_dontroute &&
20607 		    !ignore_dontroute) {
20608 dontroute:
20609 			/*
20610 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20611 			 * routing protocols from seeing false direct
20612 			 * connectivity.
20613 			 */
20614 			ipha->ipha_ttl = 1;
20615 			/*
20616 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20617 			 * along with SO_DONTROUTE, higher precedence is
20618 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20619 			 */
20620 			if (connp->conn_xmit_if_ill == NULL) {
20621 				/* If suitable ipif not found, drop packet */
20622 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20623 				if (dst_ipif == NULL) {
20624 					ip1dbg(("ip_wput: no route for "
20625 					    "dst using SO_DONTROUTE\n"));
20626 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20627 					mp->b_prev = mp->b_next = NULL;
20628 					if (first_mp == NULL)
20629 						first_mp = mp;
20630 					goto drop_pkt;
20631 				} else {
20632 					/*
20633 					 * If suitable ipif has been found, set
20634 					 * xmit_ill to the corresponding
20635 					 * ipif_ill because we'll be following
20636 					 * the IP_XMIT_IF logic.
20637 					 */
20638 					ASSERT(xmit_ill == NULL);
20639 					xmit_ill = dst_ipif->ipif_ill;
20640 					mutex_enter(&xmit_ill->ill_lock);
20641 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20642 						mutex_exit(&xmit_ill->ill_lock);
20643 						xmit_ill = NULL;
20644 						ipif_refrele(dst_ipif);
20645 						ip1dbg(("ip_wput: no route for"
20646 						    " dst using"
20647 						    " SO_DONTROUTE\n"));
20648 						BUMP_MIB(&ip_mib,
20649 						    ipOutNoRoutes);
20650 						mp->b_prev = mp->b_next = NULL;
20651 						if (first_mp == NULL)
20652 							first_mp = mp;
20653 						goto drop_pkt;
20654 					}
20655 					ill_refhold_locked(xmit_ill);
20656 					mutex_exit(&xmit_ill->ill_lock);
20657 					ipif_refrele(dst_ipif);
20658 				}
20659 			}
20660 
20661 		}
20662 		/*
20663 		 * If we are bound to IPIF_NOFAILOVER address, look for
20664 		 * an IRE_CACHE matching the ill.
20665 		 */
20666 send_from_ill:
20667 		if (attach_ill != NULL) {
20668 			ipif_t	*attach_ipif;
20669 
20670 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20671 
20672 			/*
20673 			 * Check if we need an ire that will not be
20674 			 * looked up by anybody else i.e. HIDDEN.
20675 			 */
20676 			if (ill_is_probeonly(attach_ill)) {
20677 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20678 			}
20679 
20680 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20681 			if (attach_ipif == NULL) {
20682 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20683 				goto drop_pkt;
20684 			}
20685 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20686 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20687 			ipif_refrele(attach_ipif);
20688 		} else if (xmit_ill != NULL || (connp != NULL &&
20689 			    connp->conn_xmit_if_ill != NULL)) {
20690 			/*
20691 			 * Mark this packet as originated locally
20692 			 */
20693 			mp->b_prev = mp->b_next = NULL;
20694 			/*
20695 			 * xmit_ill could be NULL if SO_DONTROUTE
20696 			 * is also set.
20697 			 */
20698 			if (xmit_ill == NULL) {
20699 				xmit_ill = conn_get_held_ill(connp,
20700 				    &connp->conn_xmit_if_ill, &err);
20701 				if (err == ILL_LOOKUP_FAILED) {
20702 					if (need_decref)
20703 						CONN_DEC_REF(connp);
20704 					freemsg(first_mp);
20705 					return;
20706 				}
20707 				if (xmit_ill == NULL) {
20708 					if (connp->conn_dontroute)
20709 						goto dontroute;
20710 					goto send_from_ill;
20711 				}
20712 			}
20713 			/*
20714 			 * could be SO_DONTROUTE case also.
20715 			 * check at least one interface is UP as
20716 			 * spcified by this ILL, and then call
20717 			 * ip_newroute_ipif()
20718 			 */
20719 			if (xmit_ill->ill_ipif_up_count > 0) {
20720 				ipif_t *ipif;
20721 
20722 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20723 				if (ipif != NULL) {
20724 					ip_newroute_ipif(q, first_mp, ipif,
20725 					    dst, connp, 0, zoneid);
20726 					ipif_refrele(ipif);
20727 					ip1dbg(("ip_wput: ip_unicast_if\n"));
20728 				}
20729 			} else {
20730 				freemsg(first_mp);
20731 			}
20732 			ill_refrele(xmit_ill);
20733 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20734 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
20735 			if (need_decref)
20736 				CONN_DEC_REF(connp);
20737 			return;
20738 		} else if (ip_nexthop || (connp != NULL &&
20739 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
20740 			if (!ip_nexthop) {
20741 				ip_nexthop = B_TRUE;
20742 				nexthop_addr = connp->conn_nexthop_v4;
20743 			}
20744 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
20745 			    MATCH_IRE_GW;
20746 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
20747 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
20748 		} else {
20749 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20750 		}
20751 		if (!ire) {
20752 			/*
20753 			 * Make sure we don't load spread if this
20754 			 * is IPIF_NOFAILOVER case.
20755 			 */
20756 			if ((attach_ill != NULL) ||
20757 			    (ip_nexthop && !ignore_nexthop)) {
20758 				if (mctl_present) {
20759 					io = (ipsec_out_t *)first_mp->b_rptr;
20760 					ASSERT(first_mp->b_datap->db_type ==
20761 					    M_CTL);
20762 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
20763 				} else {
20764 					ASSERT(mp == first_mp);
20765 					first_mp = allocb(
20766 					    sizeof (ipsec_info_t), BPRI_HI);
20767 					if (first_mp == NULL) {
20768 						first_mp = mp;
20769 						goto drop_pkt;
20770 					}
20771 					first_mp->b_datap->db_type = M_CTL;
20772 					first_mp->b_wptr +=
20773 					    sizeof (ipsec_info_t);
20774 					/* ipsec_out_secure is B_FALSE now */
20775 					bzero(first_mp->b_rptr,
20776 					    sizeof (ipsec_info_t));
20777 					io = (ipsec_out_t *)first_mp->b_rptr;
20778 					io->ipsec_out_type = IPSEC_OUT;
20779 					io->ipsec_out_len =
20780 					    sizeof (ipsec_out_t);
20781 					io->ipsec_out_use_global_policy =
20782 					    B_TRUE;
20783 					first_mp->b_cont = mp;
20784 					mctl_present = B_TRUE;
20785 				}
20786 				if (attach_ill != NULL) {
20787 					io->ipsec_out_ill_index = attach_ill->
20788 					    ill_phyint->phyint_ifindex;
20789 					io->ipsec_out_attach_if = B_TRUE;
20790 				} else {
20791 					io->ipsec_out_ip_nexthop = ip_nexthop;
20792 					io->ipsec_out_nexthop_addr =
20793 					    nexthop_addr;
20794 				}
20795 			}
20796 noirefound:
20797 			/*
20798 			 * Mark this packet as having originated on
20799 			 * this machine.  This will be noted in
20800 			 * ire_add_then_send, which needs to know
20801 			 * whether to run it back through ip_wput or
20802 			 * ip_rput following successful resolution.
20803 			 */
20804 			mp->b_prev = NULL;
20805 			mp->b_next = NULL;
20806 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid);
20807 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20808 			    "ip_wput_end: q %p (%S)", q, "newroute");
20809 			if (attach_ill != NULL)
20810 				ill_refrele(attach_ill);
20811 			if (xmit_ill != NULL)
20812 				ill_refrele(xmit_ill);
20813 			if (need_decref)
20814 				CONN_DEC_REF(connp);
20815 			return;
20816 		}
20817 	}
20818 
20819 	/* We now know where we are going with it. */
20820 
20821 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20822 	    "ip_wput_end: q %p (%S)", q, "end");
20823 
20824 	/*
20825 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20826 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
20827 	 */
20828 	if (ire->ire_flags & RTF_MULTIRT) {
20829 		/*
20830 		 * Force the TTL of multirouted packets if required.
20831 		 * The TTL of such packets is bounded by the
20832 		 * ip_multirt_ttl ndd variable.
20833 		 */
20834 		if ((ip_multirt_ttl > 0) &&
20835 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20836 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20837 			    "(was %d), dst 0x%08x\n",
20838 			    ip_multirt_ttl, ipha->ipha_ttl,
20839 			    ntohl(ire->ire_addr)));
20840 			ipha->ipha_ttl = ip_multirt_ttl;
20841 		}
20842 		/*
20843 		 * At this point, we check to see if there are any pending
20844 		 * unresolved routes. ire_multirt_resolvable()
20845 		 * checks in O(n) that all IRE_OFFSUBNET ire
20846 		 * entries for the packet's destination and
20847 		 * flagged RTF_MULTIRT are currently resolved.
20848 		 * If some remain unresolved, we make a copy
20849 		 * of the current message. It will be used
20850 		 * to initiate additional route resolutions.
20851 		 */
20852 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20853 		    MBLK_GETLABEL(first_mp));
20854 		ip2dbg(("ip_wput[noirefound]: ire %p, "
20855 		    "multirt_need_resolve %d, first_mp %p\n",
20856 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20857 		if (multirt_need_resolve) {
20858 			copy_mp = copymsg(first_mp);
20859 			if (copy_mp != NULL) {
20860 				MULTIRT_DEBUG_TAG(copy_mp);
20861 			}
20862 		}
20863 	}
20864 
20865 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20866 	/*
20867 	 * Try to resolve another multiroute if
20868 	 * ire_multirt_resolvable() deemed it necessary.
20869 	 * At this point, we need to distinguish
20870 	 * multicasts from other packets. For multicasts,
20871 	 * we call ip_newroute_ipif() and request that both
20872 	 * multirouting and setsrc flags are checked.
20873 	 */
20874 	if (copy_mp != NULL) {
20875 		if (CLASSD(dst)) {
20876 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
20877 			if (ipif) {
20878 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
20879 				    RTF_SETSRC | RTF_MULTIRT, zoneid);
20880 				ipif_refrele(ipif);
20881 			} else {
20882 				MULTIRT_DEBUG_UNTAG(copy_mp);
20883 				freemsg(copy_mp);
20884 				copy_mp = NULL;
20885 			}
20886 		} else {
20887 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20888 		}
20889 	}
20890 	if (attach_ill != NULL)
20891 		ill_refrele(attach_ill);
20892 	if (xmit_ill != NULL)
20893 		ill_refrele(xmit_ill);
20894 	if (need_decref)
20895 		CONN_DEC_REF(connp);
20896 	return;
20897 
20898 icmp_parameter_problem:
20899 	/* could not have originated externally */
20900 	ASSERT(mp->b_prev == NULL);
20901 	if (ip_hdr_complete(ipha, zoneid) == 0) {
20902 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
20903 		/* it's the IP header length that's in trouble */
20904 		icmp_param_problem(q, first_mp, 0, zoneid);
20905 		first_mp = NULL;
20906 	}
20907 
20908 drop_pkt:
20909 	ip1dbg(("ip_wput: dropped packet\n"));
20910 	if (ire != NULL)
20911 		ire_refrele(ire);
20912 	if (need_decref)
20913 		CONN_DEC_REF(connp);
20914 	freemsg(first_mp);
20915 	if (attach_ill != NULL)
20916 		ill_refrele(attach_ill);
20917 	if (xmit_ill != NULL)
20918 		ill_refrele(xmit_ill);
20919 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20920 	    "ip_wput_end: q %p (%S)", q, "droppkt");
20921 }
20922 
20923 /*
20924  * If this is a conn_t queue, then we pass in the conn. This includes the
20925  * zoneid.
20926  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
20927  * in which case we use the global zoneid since those are all part of
20928  * the global zone.
20929  */
20930 void
20931 ip_wput(queue_t *q, mblk_t *mp)
20932 {
20933 	if (CONN_Q(q))
20934 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20935 	else
20936 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
20937 }
20938 
20939 /*
20940  *
20941  * The following rules must be observed when accessing any ipif or ill
20942  * that has been cached in the conn. Typically conn_nofailover_ill,
20943  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20944  *
20945  * Access: The ipif or ill pointed to from the conn can be accessed under
20946  * the protection of the conn_lock or after it has been refheld under the
20947  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20948  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20949  * The reason for this is that a concurrent unplumb could actually be
20950  * cleaning up these cached pointers by walking the conns and might have
20951  * finished cleaning up the conn in question. The macros check that an
20952  * unplumb has not yet started on the ipif or ill.
20953  *
20954  * Caching: An ipif or ill pointer may be cached in the conn only after
20955  * making sure that an unplumb has not started. So the caching is done
20956  * while holding both the conn_lock and the ill_lock and after using the
20957  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20958  * flag before starting the cleanup of conns.
20959  *
20960  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20961  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20962  * or a reference to the ipif or a reference to an ire that references the
20963  * ipif. An ipif does not change its ill except for failover/failback. Since
20964  * failover/failback happens only after bringing down the ipif and making sure
20965  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20966  * the above holds.
20967  */
20968 ipif_t *
20969 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20970 {
20971 	ipif_t	*ipif;
20972 	ill_t	*ill;
20973 
20974 	*err = 0;
20975 	rw_enter(&ill_g_lock, RW_READER);
20976 	mutex_enter(&connp->conn_lock);
20977 	ipif = *ipifp;
20978 	if (ipif != NULL) {
20979 		ill = ipif->ipif_ill;
20980 		mutex_enter(&ill->ill_lock);
20981 		if (IPIF_CAN_LOOKUP(ipif)) {
20982 			ipif_refhold_locked(ipif);
20983 			mutex_exit(&ill->ill_lock);
20984 			mutex_exit(&connp->conn_lock);
20985 			rw_exit(&ill_g_lock);
20986 			return (ipif);
20987 		} else {
20988 			*err = IPIF_LOOKUP_FAILED;
20989 		}
20990 		mutex_exit(&ill->ill_lock);
20991 	}
20992 	mutex_exit(&connp->conn_lock);
20993 	rw_exit(&ill_g_lock);
20994 	return (NULL);
20995 }
20996 
20997 ill_t *
20998 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20999 {
21000 	ill_t	*ill;
21001 
21002 	*err = 0;
21003 	mutex_enter(&connp->conn_lock);
21004 	ill = *illp;
21005 	if (ill != NULL) {
21006 		mutex_enter(&ill->ill_lock);
21007 		if (ILL_CAN_LOOKUP(ill)) {
21008 			ill_refhold_locked(ill);
21009 			mutex_exit(&ill->ill_lock);
21010 			mutex_exit(&connp->conn_lock);
21011 			return (ill);
21012 		} else {
21013 			*err = ILL_LOOKUP_FAILED;
21014 		}
21015 		mutex_exit(&ill->ill_lock);
21016 	}
21017 	mutex_exit(&connp->conn_lock);
21018 	return (NULL);
21019 }
21020 
21021 static int
21022 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21023 {
21024 	ill_t	*ill;
21025 
21026 	ill = ipif->ipif_ill;
21027 	mutex_enter(&connp->conn_lock);
21028 	mutex_enter(&ill->ill_lock);
21029 	if (IPIF_CAN_LOOKUP(ipif)) {
21030 		*ipifp = ipif;
21031 		mutex_exit(&ill->ill_lock);
21032 		mutex_exit(&connp->conn_lock);
21033 		return (0);
21034 	}
21035 	mutex_exit(&ill->ill_lock);
21036 	mutex_exit(&connp->conn_lock);
21037 	return (IPIF_LOOKUP_FAILED);
21038 }
21039 
21040 /*
21041  * This is called if the outbound datagram needs fragmentation.
21042  *
21043  * NOTE : This function does not ire_refrele the ire argument passed in.
21044  */
21045 static void
21046 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid)
21047 {
21048 	ipha_t		*ipha;
21049 	mblk_t		*mp;
21050 	uint32_t	v_hlen_tos_len;
21051 	uint32_t	max_frag;
21052 	uint32_t	frag_flag;
21053 	boolean_t	dont_use;
21054 
21055 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21056 		mp = ipsec_mp->b_cont;
21057 	} else {
21058 		mp = ipsec_mp;
21059 	}
21060 
21061 	ipha = (ipha_t *)mp->b_rptr;
21062 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21063 
21064 #ifdef	_BIG_ENDIAN
21065 #define	V_HLEN	(v_hlen_tos_len >> 24)
21066 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21067 #else
21068 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21069 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21070 #endif
21071 
21072 #ifndef SPEED_BEFORE_SAFETY
21073 	/*
21074 	 * Check that ipha_length is consistent with
21075 	 * the mblk length
21076 	 */
21077 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21078 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21079 		    LENGTH, msgdsize(mp)));
21080 		freemsg(ipsec_mp);
21081 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21082 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21083 		    "packet length mismatch");
21084 		return;
21085 	}
21086 #endif
21087 	/*
21088 	 * Don't use frag_flag if pre-built packet or source
21089 	 * routed or if multicast (since multicast packets do not solicit
21090 	 * ICMP "packet too big" messages). Get the values of
21091 	 * max_frag and frag_flag atomically by acquiring the
21092 	 * ire_lock.
21093 	 */
21094 	mutex_enter(&ire->ire_lock);
21095 	max_frag = ire->ire_max_frag;
21096 	frag_flag = ire->ire_frag_flag;
21097 	mutex_exit(&ire->ire_lock);
21098 
21099 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21100 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21101 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21102 
21103 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21104 	    (dont_use ? 0 : frag_flag), zoneid);
21105 }
21106 
21107 /*
21108  * Used for deciding the MSS size for the upper layer. Thus
21109  * we need to check the outbound policy values in the conn.
21110  */
21111 int
21112 conn_ipsec_length(conn_t *connp)
21113 {
21114 	ipsec_latch_t *ipl;
21115 
21116 	ipl = connp->conn_latch;
21117 	if (ipl == NULL)
21118 		return (0);
21119 
21120 	if (ipl->ipl_out_policy == NULL)
21121 		return (0);
21122 
21123 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21124 }
21125 
21126 /*
21127  * Returns an estimate of the IPSEC headers size. This is used if
21128  * we don't want to call into IPSEC to get the exact size.
21129  */
21130 int
21131 ipsec_out_extra_length(mblk_t *ipsec_mp)
21132 {
21133 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21134 	ipsec_action_t *a;
21135 
21136 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21137 	if (!io->ipsec_out_secure)
21138 		return (0);
21139 
21140 	a = io->ipsec_out_act;
21141 
21142 	if (a == NULL) {
21143 		ASSERT(io->ipsec_out_policy != NULL);
21144 		a = io->ipsec_out_policy->ipsp_act;
21145 	}
21146 	ASSERT(a != NULL);
21147 
21148 	return (a->ipa_ovhd);
21149 }
21150 
21151 /*
21152  * Returns an estimate of the IPSEC headers size. This is used if
21153  * we don't want to call into IPSEC to get the exact size.
21154  */
21155 int
21156 ipsec_in_extra_length(mblk_t *ipsec_mp)
21157 {
21158 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21159 	ipsec_action_t *a;
21160 
21161 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21162 
21163 	a = ii->ipsec_in_action;
21164 	return (a == NULL ? 0 : a->ipa_ovhd);
21165 }
21166 
21167 /*
21168  * If there are any source route options, return the true final
21169  * destination. Otherwise, return the destination.
21170  */
21171 ipaddr_t
21172 ip_get_dst(ipha_t *ipha)
21173 {
21174 	ipoptp_t	opts;
21175 	uchar_t		*opt;
21176 	uint8_t		optval;
21177 	uint8_t		optlen;
21178 	ipaddr_t	dst;
21179 	uint32_t off;
21180 
21181 	dst = ipha->ipha_dst;
21182 
21183 	if (IS_SIMPLE_IPH(ipha))
21184 		return (dst);
21185 
21186 	for (optval = ipoptp_first(&opts, ipha);
21187 	    optval != IPOPT_EOL;
21188 	    optval = ipoptp_next(&opts)) {
21189 		opt = opts.ipoptp_cur;
21190 		optlen = opts.ipoptp_len;
21191 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21192 		switch (optval) {
21193 		case IPOPT_SSRR:
21194 		case IPOPT_LSRR:
21195 			off = opt[IPOPT_OFFSET];
21196 			/*
21197 			 * If one of the conditions is true, it means
21198 			 * end of options and dst already has the right
21199 			 * value.
21200 			 */
21201 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21202 				off = optlen - IP_ADDR_LEN;
21203 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21204 			}
21205 			return (dst);
21206 		default:
21207 			break;
21208 		}
21209 	}
21210 
21211 	return (dst);
21212 }
21213 
21214 mblk_t *
21215 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21216     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21217 {
21218 	ipsec_out_t	*io;
21219 	mblk_t		*first_mp;
21220 	boolean_t policy_present;
21221 
21222 	first_mp = mp;
21223 	if (mp->b_datap->db_type == M_CTL) {
21224 		io = (ipsec_out_t *)first_mp->b_rptr;
21225 		/*
21226 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21227 		 *
21228 		 * 1) There is per-socket policy (including cached global
21229 		 *    policy).
21230 		 * 2) There is no per-socket policy, but it is
21231 		 *    a multicast packet that needs to go out
21232 		 *    on a specific interface. This is the case
21233 		 *    where (ip_wput and ip_wput_multicast) attaches
21234 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21235 		 *
21236 		 * In case (2) we check with global policy to
21237 		 * see if there is a match and set the ill_index
21238 		 * appropriately so that we can lookup the ire
21239 		 * properly in ip_wput_ipsec_out.
21240 		 */
21241 
21242 		/*
21243 		 * ipsec_out_use_global_policy is set to B_FALSE
21244 		 * in ipsec_in_to_out(). Refer to that function for
21245 		 * details.
21246 		 */
21247 		if ((io->ipsec_out_latch == NULL) &&
21248 		    (io->ipsec_out_use_global_policy)) {
21249 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21250 				    ire, connp, unspec_src, zoneid));
21251 		}
21252 		if (!io->ipsec_out_secure) {
21253 			/*
21254 			 * If this is not a secure packet, drop
21255 			 * the IPSEC_OUT mp and treat it as a clear
21256 			 * packet. This happens when we are sending
21257 			 * a ICMP reply back to a clear packet. See
21258 			 * ipsec_in_to_out() for details.
21259 			 */
21260 			mp = first_mp->b_cont;
21261 			freeb(first_mp);
21262 		}
21263 		return (mp);
21264 	}
21265 	/*
21266 	 * See whether we need to attach a global policy here. We
21267 	 * don't depend on the conn (as it could be null) for deciding
21268 	 * what policy this datagram should go through because it
21269 	 * should have happened in ip_wput if there was some
21270 	 * policy. This normally happens for connections which are not
21271 	 * fully bound preventing us from caching policies in
21272 	 * ip_bind. Packets coming from the TCP listener/global queue
21273 	 * - which are non-hard_bound - could also be affected by
21274 	 * applying policy here.
21275 	 *
21276 	 * If this packet is coming from tcp global queue or listener,
21277 	 * we will be applying policy here.  This may not be *right*
21278 	 * if these packets are coming from the detached connection as
21279 	 * it could have gone in clear before. This happens only if a
21280 	 * TCP connection started when there is no policy and somebody
21281 	 * added policy before it became detached. Thus packets of the
21282 	 * detached connection could go out secure and the other end
21283 	 * would drop it because it will be expecting in clear. The
21284 	 * converse is not true i.e if somebody starts a TCP
21285 	 * connection and deletes the policy, all the packets will
21286 	 * still go out with the policy that existed before deleting
21287 	 * because ip_unbind sends up policy information which is used
21288 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21289 	 * TCP to attach a dummy IPSEC_OUT and set
21290 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21291 	 * affect performance for normal cases, we are not doing it.
21292 	 * Thus, set policy before starting any TCP connections.
21293 	 *
21294 	 * NOTE - We might apply policy even for a hard bound connection
21295 	 * - for which we cached policy in ip_bind - if somebody added
21296 	 * global policy after we inherited the policy in ip_bind.
21297 	 * This means that the packets that were going out in clear
21298 	 * previously would start going secure and hence get dropped
21299 	 * on the other side. To fix this, TCP attaches a dummy
21300 	 * ipsec_out and make sure that we don't apply global policy.
21301 	 */
21302 	if (ipha != NULL)
21303 		policy_present = ipsec_outbound_v4_policy_present;
21304 	else
21305 		policy_present = ipsec_outbound_v6_policy_present;
21306 	if (!policy_present)
21307 		return (mp);
21308 
21309 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21310 		    zoneid));
21311 }
21312 
21313 ire_t *
21314 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21315 {
21316 	ipaddr_t addr;
21317 	ire_t *save_ire;
21318 	irb_t *irb;
21319 	ill_group_t *illgrp;
21320 	int	err;
21321 
21322 	save_ire = ire;
21323 	addr = ire->ire_addr;
21324 
21325 	ASSERT(ire->ire_type == IRE_BROADCAST);
21326 
21327 	illgrp = connp->conn_outgoing_ill->ill_group;
21328 	if (illgrp == NULL) {
21329 		*conn_outgoing_ill = conn_get_held_ill(connp,
21330 		    &connp->conn_outgoing_ill, &err);
21331 		if (err == ILL_LOOKUP_FAILED) {
21332 			ire_refrele(save_ire);
21333 			return (NULL);
21334 		}
21335 		return (save_ire);
21336 	}
21337 	/*
21338 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21339 	 * If it is part of the group, we need to send on the ire
21340 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21341 	 * to this group. This is okay as IP_BOUND_IF really means
21342 	 * any ill in the group. We depend on the fact that the
21343 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21344 	 * if such an ire exists. This is possible only if you have
21345 	 * at least one ill in the group that has not failed.
21346 	 *
21347 	 * First get to the ire that matches the address and group.
21348 	 *
21349 	 * We don't look for an ire with a matching zoneid because a given zone
21350 	 * won't always have broadcast ires on all ills in the group.
21351 	 */
21352 	irb = ire->ire_bucket;
21353 	rw_enter(&irb->irb_lock, RW_READER);
21354 	if (ire->ire_marks & IRE_MARK_NORECV) {
21355 		/*
21356 		 * If the current zone only has an ire broadcast for this
21357 		 * address marked NORECV, the ire we want is ahead in the
21358 		 * bucket, so we look it up deliberately ignoring the zoneid.
21359 		 */
21360 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21361 			if (ire->ire_addr != addr)
21362 				continue;
21363 			/* skip over deleted ires */
21364 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21365 				continue;
21366 		}
21367 	}
21368 	while (ire != NULL) {
21369 		/*
21370 		 * If a new interface is coming up, we could end up
21371 		 * seeing the loopback ire and the non-loopback ire
21372 		 * may not have been added yet. So check for ire_stq
21373 		 */
21374 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21375 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21376 			break;
21377 		}
21378 		ire = ire->ire_next;
21379 	}
21380 	if (ire != NULL && ire->ire_addr == addr &&
21381 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21382 		IRE_REFHOLD(ire);
21383 		rw_exit(&irb->irb_lock);
21384 		ire_refrele(save_ire);
21385 		*conn_outgoing_ill = ire_to_ill(ire);
21386 		/*
21387 		 * Refhold the ill to make the conn_outgoing_ill
21388 		 * independent of the ire. ip_wput_ire goes in a loop
21389 		 * and may refrele the ire. Since we have an ire at this
21390 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21391 		 */
21392 		ill_refhold(*conn_outgoing_ill);
21393 		return (ire);
21394 	}
21395 	rw_exit(&irb->irb_lock);
21396 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21397 	/*
21398 	 * If we can't find a suitable ire, return the original ire.
21399 	 */
21400 	return (save_ire);
21401 }
21402 
21403 /*
21404  * This function does the ire_refrele of the ire passed in as the
21405  * argument. As this function looks up more ires i.e broadcast ires,
21406  * it needs to REFRELE them. Currently, for simplicity we don't
21407  * differentiate the one passed in and looked up here. We always
21408  * REFRELE.
21409  * IPQoS Notes:
21410  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21411  * IPSec packets are done in ipsec_out_process.
21412  *
21413  */
21414 void
21415 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21416     zoneid_t zoneid)
21417 {
21418 	ipha_t		*ipha;
21419 #define	rptr	((uchar_t *)ipha)
21420 	queue_t		*stq;
21421 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21422 	uint32_t	v_hlen_tos_len;
21423 	uint32_t	ttl_protocol;
21424 	ipaddr_t	src;
21425 	ipaddr_t	dst;
21426 	uint32_t	cksum;
21427 	ipaddr_t	orig_src;
21428 	ire_t		*ire1;
21429 	mblk_t		*next_mp;
21430 	uint_t		hlen;
21431 	uint16_t	*up;
21432 	uint32_t	max_frag = ire->ire_max_frag;
21433 	ill_t		*ill = ire_to_ill(ire);
21434 	int		clusterwide;
21435 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21436 	int		ipsec_len;
21437 	mblk_t		*first_mp;
21438 	ipsec_out_t	*io;
21439 	boolean_t	conn_dontroute;		/* conn value for multicast */
21440 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21441 	boolean_t	multicast_forward;	/* Should we forward ? */
21442 	boolean_t	unspec_src;
21443 	ill_t		*conn_outgoing_ill = NULL;
21444 	ill_t		*ire_ill;
21445 	ill_t		*ire1_ill;
21446 	ill_t		*out_ill;
21447 	uint32_t 	ill_index = 0;
21448 	boolean_t	multirt_send = B_FALSE;
21449 	int		err;
21450 	ipxmit_state_t	pktxmit_state;
21451 
21452 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21453 	    "ip_wput_ire_start: q %p", q);
21454 
21455 	multicast_forward = B_FALSE;
21456 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21457 
21458 	if (ire->ire_flags & RTF_MULTIRT) {
21459 		/*
21460 		 * Multirouting case. The bucket where ire is stored
21461 		 * probably holds other RTF_MULTIRT flagged ire
21462 		 * to the destination. In this call to ip_wput_ire,
21463 		 * we attempt to send the packet through all
21464 		 * those ires. Thus, we first ensure that ire is the
21465 		 * first RTF_MULTIRT ire in the bucket,
21466 		 * before walking the ire list.
21467 		 */
21468 		ire_t *first_ire;
21469 		irb_t *irb = ire->ire_bucket;
21470 		ASSERT(irb != NULL);
21471 
21472 		/* Make sure we do not omit any multiroute ire. */
21473 		IRB_REFHOLD(irb);
21474 		for (first_ire = irb->irb_ire;
21475 		    first_ire != NULL;
21476 		    first_ire = first_ire->ire_next) {
21477 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21478 			    (first_ire->ire_addr == ire->ire_addr) &&
21479 			    !(first_ire->ire_marks &
21480 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21481 				break;
21482 		}
21483 
21484 		if ((first_ire != NULL) && (first_ire != ire)) {
21485 			IRE_REFHOLD(first_ire);
21486 			ire_refrele(ire);
21487 			ire = first_ire;
21488 			ill = ire_to_ill(ire);
21489 		}
21490 		IRB_REFRELE(irb);
21491 	}
21492 
21493 	/*
21494 	 * conn_outgoing_ill is used only in the broadcast loop.
21495 	 * for performance we don't grab the mutexs in the fastpath
21496 	 */
21497 	if ((connp != NULL) &&
21498 	    (connp->conn_xmit_if_ill == NULL) &&
21499 	    (ire->ire_type == IRE_BROADCAST) &&
21500 	    ((connp->conn_nofailover_ill != NULL) ||
21501 	    (connp->conn_outgoing_ill != NULL))) {
21502 		/*
21503 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21504 		 * option. So, see if this endpoint is bound to a
21505 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21506 		 * that if the interface is failed, we will still send
21507 		 * the packet on the same ill which is what we want.
21508 		 */
21509 		conn_outgoing_ill = conn_get_held_ill(connp,
21510 		    &connp->conn_nofailover_ill, &err);
21511 		if (err == ILL_LOOKUP_FAILED) {
21512 			ire_refrele(ire);
21513 			freemsg(mp);
21514 			return;
21515 		}
21516 		if (conn_outgoing_ill == NULL) {
21517 			/*
21518 			 * Choose a good ill in the group to send the
21519 			 * packets on.
21520 			 */
21521 			ire = conn_set_outgoing_ill(connp, ire,
21522 			    &conn_outgoing_ill);
21523 			if (ire == NULL) {
21524 				freemsg(mp);
21525 				return;
21526 			}
21527 		}
21528 	}
21529 
21530 	if (mp->b_datap->db_type != M_CTL) {
21531 		ipha = (ipha_t *)mp->b_rptr;
21532 	} else {
21533 		io = (ipsec_out_t *)mp->b_rptr;
21534 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21535 		ASSERT(zoneid == io->ipsec_out_zoneid);
21536 		ASSERT(zoneid != ALL_ZONES);
21537 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21538 		dst = ipha->ipha_dst;
21539 		/*
21540 		 * For the multicast case, ipsec_out carries conn_dontroute and
21541 		 * conn_multicast_loop as conn may not be available here. We
21542 		 * need this for multicast loopback and forwarding which is done
21543 		 * later in the code.
21544 		 */
21545 		if (CLASSD(dst)) {
21546 			conn_dontroute = io->ipsec_out_dontroute;
21547 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21548 			/*
21549 			 * If conn_dontroute is not set or conn_multicast_loop
21550 			 * is set, we need to do forwarding/loopback. For
21551 			 * datagrams from ip_wput_multicast, conn_dontroute is
21552 			 * set to B_TRUE and conn_multicast_loop is set to
21553 			 * B_FALSE so that we neither do forwarding nor
21554 			 * loopback.
21555 			 */
21556 			if (!conn_dontroute || conn_multicast_loop)
21557 				multicast_forward = B_TRUE;
21558 		}
21559 	}
21560 
21561 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21562 	    ire->ire_zoneid != ALL_ZONES) {
21563 		/*
21564 		 * When a zone sends a packet to another zone, we try to deliver
21565 		 * the packet under the same conditions as if the destination
21566 		 * was a real node on the network. To do so, we look for a
21567 		 * matching route in the forwarding table.
21568 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21569 		 * ip_newroute() does.
21570 		 * Note that IRE_LOCAL are special, since they are used
21571 		 * when the zoneid doesn't match in some cases. This means that
21572 		 * we need to handle ipha_src differently since ire_src_addr
21573 		 * belongs to the receiving zone instead of the sending zone.
21574 		 * When ip_restrict_interzone_loopback is set, then
21575 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
21576 		 * for loopback between zones when the logical "Ethernet" would
21577 		 * have looped them back.
21578 		 */
21579 		ire_t *src_ire;
21580 
21581 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21582 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21583 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
21584 		if (src_ire != NULL &&
21585 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
21586 		    (!ip_restrict_interzone_loopback ||
21587 		    ire_local_same_ill_group(ire, src_ire))) {
21588 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21589 				ipha->ipha_src = src_ire->ire_src_addr;
21590 			ire_refrele(src_ire);
21591 		} else {
21592 			ire_refrele(ire);
21593 			if (conn_outgoing_ill != NULL)
21594 				ill_refrele(conn_outgoing_ill);
21595 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
21596 			if (src_ire != NULL) {
21597 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21598 					ire_refrele(src_ire);
21599 					freemsg(mp);
21600 					return;
21601 				}
21602 				ire_refrele(src_ire);
21603 			}
21604 			if (ip_hdr_complete(ipha, zoneid)) {
21605 				/* Failed */
21606 				freemsg(mp);
21607 				return;
21608 			}
21609 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid);
21610 			return;
21611 		}
21612 	}
21613 
21614 	if (mp->b_datap->db_type == M_CTL ||
21615 	    ipsec_outbound_v4_policy_present) {
21616 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21617 		    unspec_src, zoneid);
21618 		if (mp == NULL) {
21619 			ire_refrele(ire);
21620 			if (conn_outgoing_ill != NULL)
21621 				ill_refrele(conn_outgoing_ill);
21622 			return;
21623 		}
21624 	}
21625 
21626 	first_mp = mp;
21627 	ipsec_len = 0;
21628 
21629 	if (first_mp->b_datap->db_type == M_CTL) {
21630 		io = (ipsec_out_t *)first_mp->b_rptr;
21631 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21632 		mp = first_mp->b_cont;
21633 		ipsec_len = ipsec_out_extra_length(first_mp);
21634 		ASSERT(ipsec_len >= 0);
21635 		/* We already picked up the zoneid from the M_CTL above */
21636 		ASSERT(zoneid == io->ipsec_out_zoneid);
21637 		ASSERT(zoneid != ALL_ZONES);
21638 
21639 		/*
21640 		 * Drop M_CTL here if IPsec processing is not needed.
21641 		 * (Non-IPsec use of M_CTL extracted any information it
21642 		 * needed above).
21643 		 */
21644 		if (ipsec_len == 0) {
21645 			freeb(first_mp);
21646 			first_mp = mp;
21647 		}
21648 	}
21649 
21650 	/*
21651 	 * Fast path for ip_wput_ire
21652 	 */
21653 
21654 	ipha = (ipha_t *)mp->b_rptr;
21655 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21656 	dst = ipha->ipha_dst;
21657 
21658 	/*
21659 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21660 	 * if the socket is a SOCK_RAW type. The transport checksum should
21661 	 * be provided in the pre-built packet, so we don't need to compute it.
21662 	 * Also, other application set flags, like DF, should not be altered.
21663 	 * Other transport MUST pass down zero.
21664 	 */
21665 	ip_hdr_included = ipha->ipha_ident;
21666 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21667 
21668 	if (CLASSD(dst)) {
21669 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
21670 		    ntohl(dst),
21671 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
21672 		    ntohl(ire->ire_addr)));
21673 	}
21674 
21675 /* Macros to extract header fields from data already in registers */
21676 #ifdef	_BIG_ENDIAN
21677 #define	V_HLEN	(v_hlen_tos_len >> 24)
21678 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21679 #define	PROTO	(ttl_protocol & 0xFF)
21680 #else
21681 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21682 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21683 #define	PROTO	(ttl_protocol >> 8)
21684 #endif
21685 
21686 
21687 	orig_src = src = ipha->ipha_src;
21688 	/* (The loop back to "another" is explained down below.) */
21689 another:;
21690 	/*
21691 	 * Assign an ident value for this packet.  We assign idents on
21692 	 * a per destination basis out of the IRE.  There could be
21693 	 * other threads targeting the same destination, so we have to
21694 	 * arrange for a atomic increment.  Note that we use a 32-bit
21695 	 * atomic add because it has better performance than its
21696 	 * 16-bit sibling.
21697 	 *
21698 	 * If running in cluster mode and if the source address
21699 	 * belongs to a replicated service then vector through
21700 	 * cl_inet_ipident vector to allocate ip identifier
21701 	 * NOTE: This is a contract private interface with the
21702 	 * clustering group.
21703 	 */
21704 	clusterwide = 0;
21705 	if (cl_inet_ipident) {
21706 		ASSERT(cl_inet_isclusterwide);
21707 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21708 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
21709 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
21710 			    AF_INET, (uint8_t *)(uintptr_t)src,
21711 			    (uint8_t *)(uintptr_t)dst);
21712 			clusterwide = 1;
21713 		}
21714 	}
21715 	if (!clusterwide) {
21716 		ipha->ipha_ident =
21717 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
21718 	}
21719 
21720 #ifndef _BIG_ENDIAN
21721 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21722 #endif
21723 
21724 	/*
21725 	 * Set source address unless sent on an ill or conn_unspec_src is set.
21726 	 * This is needed to obey conn_unspec_src when packets go through
21727 	 * ip_newroute + arp.
21728 	 * Assumes ip_newroute{,_multi} sets the source address as well.
21729 	 */
21730 	if (src == INADDR_ANY && !unspec_src) {
21731 		/*
21732 		 * Assign the appropriate source address from the IRE if none
21733 		 * was specified.
21734 		 */
21735 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
21736 
21737 		/*
21738 		 * With IP multipathing, broadcast packets are sent on the ire
21739 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
21740 		 * the group. However, this ire might not be in the same zone so
21741 		 * we can't always use its source address. We look for a
21742 		 * broadcast ire in the same group and in the right zone.
21743 		 */
21744 		if (ire->ire_type == IRE_BROADCAST &&
21745 		    ire->ire_zoneid != zoneid) {
21746 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
21747 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
21748 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
21749 			if (src_ire != NULL) {
21750 				src = src_ire->ire_src_addr;
21751 				ire_refrele(src_ire);
21752 			} else {
21753 				ire_refrele(ire);
21754 				if (conn_outgoing_ill != NULL)
21755 					ill_refrele(conn_outgoing_ill);
21756 				freemsg(first_mp);
21757 				BUMP_MIB(&ip_mib, ipOutDiscards);
21758 				return;
21759 			}
21760 		} else {
21761 			src = ire->ire_src_addr;
21762 		}
21763 
21764 		if (connp == NULL) {
21765 			ip1dbg(("ip_wput_ire: no connp and no src "
21766 			    "address for dst 0x%x, using src 0x%x\n",
21767 			    ntohl(dst),
21768 			    ntohl(src)));
21769 		}
21770 		ipha->ipha_src = src;
21771 	}
21772 	stq = ire->ire_stq;
21773 
21774 	/*
21775 	 * We only allow ire chains for broadcasts since there will
21776 	 * be multiple IRE_CACHE entries for the same multicast
21777 	 * address (one per ipif).
21778 	 */
21779 	next_mp = NULL;
21780 
21781 	/* broadcast packet */
21782 	if (ire->ire_type == IRE_BROADCAST)
21783 		goto broadcast;
21784 
21785 	/* loopback ? */
21786 	if (stq == NULL)
21787 		goto nullstq;
21788 
21789 	/* The ill_index for outbound ILL */
21790 	ill_index = Q_TO_INDEX(stq);
21791 
21792 	BUMP_MIB(&ip_mib, ipOutRequests);
21793 	ttl_protocol = ((uint16_t *)ipha)[4];
21794 
21795 	/* pseudo checksum (do it in parts for IP header checksum) */
21796 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21797 
21798 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
21799 		queue_t *dev_q = stq->q_next;
21800 
21801 		/* flow controlled */
21802 		if ((dev_q->q_next || dev_q->q_first) &&
21803 		    !canput(dev_q))
21804 			goto blocked;
21805 		if ((PROTO == IPPROTO_UDP) &&
21806 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21807 			hlen = (V_HLEN & 0xF) << 2;
21808 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21809 			if (*up != 0) {
21810 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
21811 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
21812 				/* Software checksum? */
21813 				if (DB_CKSUMFLAGS(mp) == 0) {
21814 					IP_STAT(ip_out_sw_cksum);
21815 					IP_STAT_UPDATE(
21816 					    ip_udp_out_sw_cksum_bytes,
21817 					    LENGTH - hlen);
21818 				}
21819 			}
21820 		}
21821 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
21822 		hlen = (V_HLEN & 0xF) << 2;
21823 		if (PROTO == IPPROTO_TCP) {
21824 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21825 			/*
21826 			 * The packet header is processed once and for all, even
21827 			 * in the multirouting case. We disable hardware
21828 			 * checksum if the packet is multirouted, as it will be
21829 			 * replicated via several interfaces, and not all of
21830 			 * them may have this capability.
21831 			 */
21832 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
21833 			    LENGTH, max_frag, ipsec_len, cksum);
21834 			/* Software checksum? */
21835 			if (DB_CKSUMFLAGS(mp) == 0) {
21836 				IP_STAT(ip_out_sw_cksum);
21837 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21838 				    LENGTH - hlen);
21839 			}
21840 		} else {
21841 			sctp_hdr_t	*sctph;
21842 
21843 			ASSERT(PROTO == IPPROTO_SCTP);
21844 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21845 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21846 			/*
21847 			 * Zero out the checksum field to ensure proper
21848 			 * checksum calculation.
21849 			 */
21850 			sctph->sh_chksum = 0;
21851 #ifdef	DEBUG
21852 			if (!skip_sctp_cksum)
21853 #endif
21854 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21855 		}
21856 	}
21857 
21858 	/*
21859 	 * If this is a multicast packet and originated from ip_wput
21860 	 * we need to do loopback and forwarding checks. If it comes
21861 	 * from ip_wput_multicast, we SHOULD not do this.
21862 	 */
21863 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
21864 
21865 	/* checksum */
21866 	cksum += ttl_protocol;
21867 
21868 	/* fragment the packet */
21869 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
21870 		goto fragmentit;
21871 	/*
21872 	 * Don't use frag_flag if packet is pre-built or source
21873 	 * routed or if multicast (since multicast packets do
21874 	 * not solicit ICMP "packet too big" messages).
21875 	 */
21876 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21877 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21878 	    !ip_source_route_included(ipha)) &&
21879 	    !CLASSD(ipha->ipha_dst))
21880 		ipha->ipha_fragment_offset_and_flags |=
21881 		    htons(ire->ire_frag_flag);
21882 
21883 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21884 		/* calculate IP header checksum */
21885 		cksum += ipha->ipha_ident;
21886 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
21887 		cksum += ipha->ipha_fragment_offset_and_flags;
21888 
21889 		/* IP options present */
21890 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21891 		if (hlen)
21892 			goto checksumoptions;
21893 
21894 		/* calculate hdr checksum */
21895 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21896 		cksum = ~(cksum + (cksum >> 16));
21897 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
21898 	}
21899 	if (ipsec_len != 0) {
21900 		/*
21901 		 * We will do the rest of the processing after
21902 		 * we come back from IPSEC in ip_wput_ipsec_out().
21903 		 */
21904 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
21905 
21906 		io = (ipsec_out_t *)first_mp->b_rptr;
21907 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
21908 				ill_phyint->phyint_ifindex;
21909 
21910 		ipsec_out_process(q, first_mp, ire, ill_index);
21911 		ire_refrele(ire);
21912 		if (conn_outgoing_ill != NULL)
21913 			ill_refrele(conn_outgoing_ill);
21914 		return;
21915 	}
21916 
21917 	/*
21918 	 * In most cases, the emission loop below is entered only
21919 	 * once. Only in the case where the ire holds the
21920 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
21921 	 * flagged ires in the bucket, and send the packet
21922 	 * through all crossed RTF_MULTIRT routes.
21923 	 */
21924 	if (ire->ire_flags & RTF_MULTIRT) {
21925 		multirt_send = B_TRUE;
21926 	}
21927 	do {
21928 		if (multirt_send) {
21929 			irb_t *irb;
21930 			/*
21931 			 * We are in a multiple send case, need to get
21932 			 * the next ire and make a duplicate of the packet.
21933 			 * ire1 holds here the next ire to process in the
21934 			 * bucket. If multirouting is expected,
21935 			 * any non-RTF_MULTIRT ire that has the
21936 			 * right destination address is ignored.
21937 			 */
21938 			irb = ire->ire_bucket;
21939 			ASSERT(irb != NULL);
21940 
21941 			IRB_REFHOLD(irb);
21942 			for (ire1 = ire->ire_next;
21943 			    ire1 != NULL;
21944 			    ire1 = ire1->ire_next) {
21945 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21946 					continue;
21947 				if (ire1->ire_addr != ire->ire_addr)
21948 					continue;
21949 				if (ire1->ire_marks &
21950 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21951 					continue;
21952 
21953 				/* Got one */
21954 				IRE_REFHOLD(ire1);
21955 				break;
21956 			}
21957 			IRB_REFRELE(irb);
21958 
21959 			if (ire1 != NULL) {
21960 				next_mp = copyb(mp);
21961 				if ((next_mp == NULL) ||
21962 				    ((mp->b_cont != NULL) &&
21963 				    ((next_mp->b_cont =
21964 				    dupmsg(mp->b_cont)) == NULL))) {
21965 					freemsg(next_mp);
21966 					next_mp = NULL;
21967 					ire_refrele(ire1);
21968 					ire1 = NULL;
21969 				}
21970 			}
21971 
21972 			/* Last multiroute ire; don't loop anymore. */
21973 			if (ire1 == NULL) {
21974 				multirt_send = B_FALSE;
21975 			}
21976 		}
21977 
21978 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
21979 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
21980 		    mblk_t *, mp);
21981 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
21982 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp);
21983 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21984 		if (mp == NULL)
21985 			goto release_ire_and_ill;
21986 
21987 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
21988 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
21989 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
21990 		if ((pktxmit_state == SEND_FAILED) ||
21991 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
21992 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
21993 			    "- packet dropped\n"));
21994 release_ire_and_ill:
21995 			ire_refrele(ire);
21996 			if (next_mp != NULL) {
21997 				freemsg(next_mp);
21998 				ire_refrele(ire1);
21999 			}
22000 			if (conn_outgoing_ill != NULL)
22001 				ill_refrele(conn_outgoing_ill);
22002 			return;
22003 		}
22004 
22005 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22006 		    "ip_wput_ire_end: q %p (%S)",
22007 		    q, "last copy out");
22008 		IRE_REFRELE(ire);
22009 
22010 		if (multirt_send) {
22011 			ASSERT(ire1);
22012 			/*
22013 			 * Proceed with the next RTF_MULTIRT ire,
22014 			 * Also set up the send-to queue accordingly.
22015 			 */
22016 			ire = ire1;
22017 			ire1 = NULL;
22018 			stq = ire->ire_stq;
22019 			mp = next_mp;
22020 			next_mp = NULL;
22021 			ipha = (ipha_t *)mp->b_rptr;
22022 			ill_index = Q_TO_INDEX(stq);
22023 		}
22024 	} while (multirt_send);
22025 	if (conn_outgoing_ill != NULL)
22026 		ill_refrele(conn_outgoing_ill);
22027 	return;
22028 
22029 	/*
22030 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22031 	 */
22032 broadcast:
22033 	{
22034 		/*
22035 		 * Avoid broadcast storms by setting the ttl to 1
22036 		 * for broadcasts. This parameter can be set
22037 		 * via ndd, so make sure that for the SO_DONTROUTE
22038 		 * case that ipha_ttl is always set to 1.
22039 		 * In the event that we are replying to incoming
22040 		 * ICMP packets, conn could be NULL.
22041 		 */
22042 		if ((connp != NULL) && connp->conn_dontroute)
22043 			ipha->ipha_ttl = 1;
22044 		else
22045 			ipha->ipha_ttl = ip_broadcast_ttl;
22046 
22047 		/*
22048 		 * Note that we are not doing a IRB_REFHOLD here.
22049 		 * Actually we don't care if the list changes i.e
22050 		 * if somebody deletes an IRE from the list while
22051 		 * we drop the lock, the next time we come around
22052 		 * ire_next will be NULL and hence we won't send
22053 		 * out multiple copies which is fine.
22054 		 */
22055 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22056 		ire1 = ire->ire_next;
22057 		if (conn_outgoing_ill != NULL) {
22058 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22059 				ASSERT(ire1 == ire->ire_next);
22060 				if (ire1 != NULL && ire1->ire_addr == dst) {
22061 					ire_refrele(ire);
22062 					ire = ire1;
22063 					IRE_REFHOLD(ire);
22064 					ire1 = ire->ire_next;
22065 					continue;
22066 				}
22067 				rw_exit(&ire->ire_bucket->irb_lock);
22068 				/* Did not find a matching ill */
22069 				ip1dbg(("ip_wput_ire: broadcast with no "
22070 				    "matching IP_BOUND_IF ill %s\n",
22071 				    conn_outgoing_ill->ill_name));
22072 				freemsg(first_mp);
22073 				if (ire != NULL)
22074 					ire_refrele(ire);
22075 				ill_refrele(conn_outgoing_ill);
22076 				return;
22077 			}
22078 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22079 			/*
22080 			 * If the next IRE has the same address and is not one
22081 			 * of the two copies that we need to send, try to see
22082 			 * whether this copy should be sent at all. This
22083 			 * assumes that we insert loopbacks first and then
22084 			 * non-loopbacks. This is acheived by inserting the
22085 			 * loopback always before non-loopback.
22086 			 * This is used to send a single copy of a broadcast
22087 			 * packet out all physical interfaces that have an
22088 			 * matching IRE_BROADCAST while also looping
22089 			 * back one copy (to ip_wput_local) for each
22090 			 * matching physical interface. However, we avoid
22091 			 * sending packets out different logical that match by
22092 			 * having ipif_up/ipif_down supress duplicate
22093 			 * IRE_BROADCASTS.
22094 			 *
22095 			 * This feature is currently used to get broadcasts
22096 			 * sent to multiple interfaces, when the broadcast
22097 			 * address being used applies to multiple interfaces.
22098 			 * For example, a whole net broadcast will be
22099 			 * replicated on every connected subnet of
22100 			 * the target net.
22101 			 *
22102 			 * Each zone has its own set of IRE_BROADCASTs, so that
22103 			 * we're able to distribute inbound packets to multiple
22104 			 * zones who share a broadcast address. We avoid looping
22105 			 * back outbound packets in different zones but on the
22106 			 * same ill, as the application would see duplicates.
22107 			 *
22108 			 * If the interfaces are part of the same group,
22109 			 * we would want to send only one copy out for
22110 			 * whole group.
22111 			 *
22112 			 * This logic assumes that ire_add_v4() groups the
22113 			 * IRE_BROADCAST entries so that those with the same
22114 			 * ire_addr and ill_group are kept together.
22115 			 */
22116 			ire_ill = ire->ire_ipif->ipif_ill;
22117 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22118 				if (ire_ill->ill_group != NULL &&
22119 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22120 					/*
22121 					 * If the current zone only has an ire
22122 					 * broadcast for this address marked
22123 					 * NORECV, the ire we want is ahead in
22124 					 * the bucket, so we look it up
22125 					 * deliberately ignoring the zoneid.
22126 					 */
22127 					for (ire1 = ire->ire_bucket->irb_ire;
22128 					    ire1 != NULL;
22129 					    ire1 = ire1->ire_next) {
22130 						ire1_ill =
22131 						    ire1->ire_ipif->ipif_ill;
22132 						if (ire1->ire_addr != dst)
22133 							continue;
22134 						/* skip over the current ire */
22135 						if (ire1 == ire)
22136 							continue;
22137 						/* skip over deleted ires */
22138 						if (ire1->ire_marks &
22139 						    IRE_MARK_CONDEMNED)
22140 							continue;
22141 						/*
22142 						 * non-loopback ire in our
22143 						 * group: use it for the next
22144 						 * pass in the loop
22145 						 */
22146 						if (ire1->ire_stq != NULL &&
22147 						    ire1_ill->ill_group ==
22148 						    ire_ill->ill_group)
22149 							break;
22150 					}
22151 				}
22152 			} else {
22153 				while (ire1 != NULL && ire1->ire_addr == dst) {
22154 					ire1_ill = ire1->ire_ipif->ipif_ill;
22155 					/*
22156 					 * We can have two broadcast ires on the
22157 					 * same ill in different zones; here
22158 					 * we'll send a copy of the packet on
22159 					 * each ill and the fanout code will
22160 					 * call conn_wantpacket() to check that
22161 					 * the zone has the broadcast address
22162 					 * configured on the ill. If the two
22163 					 * ires are in the same group we only
22164 					 * send one copy up.
22165 					 */
22166 					if (ire1_ill != ire_ill &&
22167 					    (ire1_ill->ill_group == NULL ||
22168 					    ire_ill->ill_group == NULL ||
22169 					    ire1_ill->ill_group !=
22170 					    ire_ill->ill_group)) {
22171 						break;
22172 					}
22173 					ire1 = ire1->ire_next;
22174 				}
22175 			}
22176 		}
22177 		ASSERT(multirt_send == B_FALSE);
22178 		if (ire1 != NULL && ire1->ire_addr == dst) {
22179 			if ((ire->ire_flags & RTF_MULTIRT) &&
22180 			    (ire1->ire_flags & RTF_MULTIRT)) {
22181 				/*
22182 				 * We are in the multirouting case.
22183 				 * The message must be sent at least
22184 				 * on both ires. These ires have been
22185 				 * inserted AFTER the standard ones
22186 				 * in ip_rt_add(). There are thus no
22187 				 * other ire entries for the destination
22188 				 * address in the rest of the bucket
22189 				 * that do not have the RTF_MULTIRT
22190 				 * flag. We don't process a copy
22191 				 * of the message here. This will be
22192 				 * done in the final sending loop.
22193 				 */
22194 				multirt_send = B_TRUE;
22195 			} else {
22196 				next_mp = ip_copymsg(first_mp);
22197 				if (next_mp != NULL)
22198 					IRE_REFHOLD(ire1);
22199 			}
22200 		}
22201 		rw_exit(&ire->ire_bucket->irb_lock);
22202 	}
22203 
22204 	if (stq) {
22205 		/*
22206 		 * A non-NULL send-to queue means this packet is going
22207 		 * out of this machine.
22208 		 */
22209 
22210 		BUMP_MIB(&ip_mib, ipOutRequests);
22211 		ttl_protocol = ((uint16_t *)ipha)[4];
22212 		/*
22213 		 * We accumulate the pseudo header checksum in cksum.
22214 		 * This is pretty hairy code, so watch close.  One
22215 		 * thing to keep in mind is that UDP and TCP have
22216 		 * stored their respective datagram lengths in their
22217 		 * checksum fields.  This lines things up real nice.
22218 		 */
22219 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22220 		    (src >> 16) + (src & 0xFFFF);
22221 		/*
22222 		 * We assume the udp checksum field contains the
22223 		 * length, so to compute the pseudo header checksum,
22224 		 * all we need is the protocol number and src/dst.
22225 		 */
22226 		/* Provide the checksums for UDP and TCP. */
22227 		if ((PROTO == IPPROTO_TCP) &&
22228 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22229 			/* hlen gets the number of uchar_ts in the IP header */
22230 			hlen = (V_HLEN & 0xF) << 2;
22231 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22232 			IP_STAT(ip_out_sw_cksum);
22233 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22234 			    LENGTH - hlen);
22235 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22236 			if (*up == 0)
22237 				*up = 0xFFFF;
22238 		} else if (PROTO == IPPROTO_SCTP &&
22239 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22240 			sctp_hdr_t	*sctph;
22241 
22242 			hlen = (V_HLEN & 0xF) << 2;
22243 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22244 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22245 			sctph->sh_chksum = 0;
22246 #ifdef	DEBUG
22247 			if (!skip_sctp_cksum)
22248 #endif
22249 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22250 		} else {
22251 			queue_t *dev_q = stq->q_next;
22252 
22253 			if ((dev_q->q_next || dev_q->q_first) &&
22254 			    !canput(dev_q)) {
22255 			    blocked:
22256 				ipha->ipha_ident = ip_hdr_included;
22257 				/*
22258 				 * If we don't have a conn to apply
22259 				 * backpressure, free the message.
22260 				 * In the ire_send path, we don't know
22261 				 * the position to requeue the packet. Rather
22262 				 * than reorder packets, we just drop this
22263 				 * packet.
22264 				 */
22265 				if (ip_output_queue && connp != NULL &&
22266 				    caller != IRE_SEND) {
22267 					if (caller == IP_WSRV) {
22268 						connp->conn_did_putbq = 1;
22269 						(void) putbq(connp->conn_wq,
22270 						    first_mp);
22271 						conn_drain_insert(connp);
22272 						/*
22273 						 * This is the service thread,
22274 						 * and the queue is already
22275 						 * noenabled. The check for
22276 						 * canput and the putbq is not
22277 						 * atomic. So we need to check
22278 						 * again.
22279 						 */
22280 						if (canput(stq->q_next))
22281 							connp->conn_did_putbq
22282 							    = 0;
22283 						IP_STAT(ip_conn_flputbq);
22284 					} else {
22285 						/*
22286 						 * We are not the service proc.
22287 						 * ip_wsrv will be scheduled or
22288 						 * is already running.
22289 						 */
22290 						(void) putq(connp->conn_wq,
22291 						    first_mp);
22292 					}
22293 				} else {
22294 					BUMP_MIB(&ip_mib, ipOutDiscards);
22295 					freemsg(first_mp);
22296 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22297 					    "ip_wput_ire_end: q %p (%S)",
22298 					    q, "discard");
22299 				}
22300 				ire_refrele(ire);
22301 				if (next_mp) {
22302 					ire_refrele(ire1);
22303 					freemsg(next_mp);
22304 				}
22305 				if (conn_outgoing_ill != NULL)
22306 					ill_refrele(conn_outgoing_ill);
22307 				return;
22308 			}
22309 			if ((PROTO == IPPROTO_UDP) &&
22310 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22311 				/*
22312 				 * hlen gets the number of uchar_ts in the
22313 				 * IP header
22314 				 */
22315 				hlen = (V_HLEN & 0xF) << 2;
22316 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22317 				max_frag = ire->ire_max_frag;
22318 				if (*up != 0) {
22319 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22320 					    up, PROTO, hlen, LENGTH, max_frag,
22321 					    ipsec_len, cksum);
22322 					/* Software checksum? */
22323 					if (DB_CKSUMFLAGS(mp) == 0) {
22324 						IP_STAT(ip_out_sw_cksum);
22325 						IP_STAT_UPDATE(
22326 						    ip_udp_out_sw_cksum_bytes,
22327 						    LENGTH - hlen);
22328 					}
22329 				}
22330 			}
22331 		}
22332 		/*
22333 		 * Need to do this even when fragmenting. The local
22334 		 * loopback can be done without computing checksums
22335 		 * but forwarding out other interface must be done
22336 		 * after the IP checksum (and ULP checksums) have been
22337 		 * computed.
22338 		 *
22339 		 * NOTE : multicast_forward is set only if this packet
22340 		 * originated from ip_wput. For packets originating from
22341 		 * ip_wput_multicast, it is not set.
22342 		 */
22343 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22344 		    multi_loopback:
22345 			ip2dbg(("ip_wput: multicast, loop %d\n",
22346 			    conn_multicast_loop));
22347 
22348 			/*  Forget header checksum offload */
22349 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22350 
22351 			/*
22352 			 * Local loopback of multicasts?  Check the
22353 			 * ill.
22354 			 *
22355 			 * Note that the loopback function will not come
22356 			 * in through ip_rput - it will only do the
22357 			 * client fanout thus we need to do an mforward
22358 			 * as well.  The is different from the BSD
22359 			 * logic.
22360 			 */
22361 			if (ill != NULL) {
22362 				ilm_t	*ilm;
22363 
22364 				ILM_WALKER_HOLD(ill);
22365 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22366 				    ALL_ZONES);
22367 				ILM_WALKER_RELE(ill);
22368 				if (ilm != NULL) {
22369 					/*
22370 					 * Pass along the virtual output q.
22371 					 * ip_wput_local() will distribute the
22372 					 * packet to all the matching zones,
22373 					 * except the sending zone when
22374 					 * IP_MULTICAST_LOOP is false.
22375 					 */
22376 					ip_multicast_loopback(q, ill, first_mp,
22377 					    conn_multicast_loop ? 0 :
22378 					    IP_FF_NO_MCAST_LOOP, zoneid);
22379 				}
22380 			}
22381 			if (ipha->ipha_ttl == 0) {
22382 				/*
22383 				 * 0 => only to this host i.e. we are
22384 				 * done. We are also done if this was the
22385 				 * loopback interface since it is sufficient
22386 				 * to loopback one copy of a multicast packet.
22387 				 */
22388 				freemsg(first_mp);
22389 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22390 				    "ip_wput_ire_end: q %p (%S)",
22391 				    q, "loopback");
22392 				ire_refrele(ire);
22393 				if (conn_outgoing_ill != NULL)
22394 					ill_refrele(conn_outgoing_ill);
22395 				return;
22396 			}
22397 			/*
22398 			 * ILLF_MULTICAST is checked in ip_newroute
22399 			 * i.e. we don't need to check it here since
22400 			 * all IRE_CACHEs come from ip_newroute.
22401 			 * For multicast traffic, SO_DONTROUTE is interpreted
22402 			 * to mean only send the packet out the interface
22403 			 * (optionally specified with IP_MULTICAST_IF)
22404 			 * and do not forward it out additional interfaces.
22405 			 * RSVP and the rsvp daemon is an example of a
22406 			 * protocol and user level process that
22407 			 * handles it's own routing. Hence, it uses the
22408 			 * SO_DONTROUTE option to accomplish this.
22409 			 */
22410 
22411 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22412 				/* Unconditionally redo the checksum */
22413 				ipha->ipha_hdr_checksum = 0;
22414 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22415 
22416 				/*
22417 				 * If this needs to go out secure, we need
22418 				 * to wait till we finish the IPSEC
22419 				 * processing.
22420 				 */
22421 				if (ipsec_len == 0 &&
22422 				    ip_mforward(ill, ipha, mp)) {
22423 					freemsg(first_mp);
22424 					ip1dbg(("ip_wput: mforward failed\n"));
22425 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22426 					    "ip_wput_ire_end: q %p (%S)",
22427 					    q, "mforward failed");
22428 					ire_refrele(ire);
22429 					if (conn_outgoing_ill != NULL)
22430 						ill_refrele(conn_outgoing_ill);
22431 					return;
22432 				}
22433 			}
22434 		}
22435 		max_frag = ire->ire_max_frag;
22436 		cksum += ttl_protocol;
22437 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22438 			/* No fragmentation required for this one. */
22439 			/*
22440 			 * Don't use frag_flag if packet is pre-built or source
22441 			 * routed or if multicast (since multicast packets do
22442 			 * not solicit ICMP "packet too big" messages).
22443 			 */
22444 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22445 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22446 			    !ip_source_route_included(ipha)) &&
22447 			    !CLASSD(ipha->ipha_dst))
22448 				ipha->ipha_fragment_offset_and_flags |=
22449 				    htons(ire->ire_frag_flag);
22450 
22451 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22452 				/* Complete the IP header checksum. */
22453 				cksum += ipha->ipha_ident;
22454 				cksum += (v_hlen_tos_len >> 16)+
22455 				    (v_hlen_tos_len & 0xFFFF);
22456 				cksum += ipha->ipha_fragment_offset_and_flags;
22457 				hlen = (V_HLEN & 0xF) -
22458 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22459 				if (hlen) {
22460 				    checksumoptions:
22461 					/*
22462 					 * Account for the IP Options in the IP
22463 					 * header checksum.
22464 					 */
22465 					up = (uint16_t *)(rptr+
22466 					    IP_SIMPLE_HDR_LENGTH);
22467 					do {
22468 						cksum += up[0];
22469 						cksum += up[1];
22470 						up += 2;
22471 					} while (--hlen);
22472 				}
22473 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22474 				cksum = ~(cksum + (cksum >> 16));
22475 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22476 			}
22477 			if (ipsec_len != 0) {
22478 				ipsec_out_process(q, first_mp, ire, ill_index);
22479 				if (!next_mp) {
22480 					ire_refrele(ire);
22481 					if (conn_outgoing_ill != NULL)
22482 						ill_refrele(conn_outgoing_ill);
22483 					return;
22484 				}
22485 				goto next;
22486 			}
22487 
22488 			/*
22489 			 * multirt_send has already been handled
22490 			 * for broadcast, but not yet for multicast
22491 			 * or IP options.
22492 			 */
22493 			if (next_mp == NULL) {
22494 				if (ire->ire_flags & RTF_MULTIRT) {
22495 					multirt_send = B_TRUE;
22496 				}
22497 			}
22498 
22499 			/*
22500 			 * In most cases, the emission loop below is
22501 			 * entered only once. Only in the case where
22502 			 * the ire holds the RTF_MULTIRT flag, do we loop
22503 			 * to process all RTF_MULTIRT ires in the bucket,
22504 			 * and send the packet through all crossed
22505 			 * RTF_MULTIRT routes.
22506 			 */
22507 			do {
22508 				if (multirt_send) {
22509 					irb_t *irb;
22510 
22511 					irb = ire->ire_bucket;
22512 					ASSERT(irb != NULL);
22513 					/*
22514 					 * We are in a multiple send case,
22515 					 * need to get the next IRE and make
22516 					 * a duplicate of the packet.
22517 					 */
22518 					IRB_REFHOLD(irb);
22519 					for (ire1 = ire->ire_next;
22520 					    ire1 != NULL;
22521 					    ire1 = ire1->ire_next) {
22522 						if (!(ire1->ire_flags &
22523 						    RTF_MULTIRT))
22524 							continue;
22525 						if (ire1->ire_addr !=
22526 						    ire->ire_addr)
22527 							continue;
22528 						if (ire1->ire_marks &
22529 						    (IRE_MARK_CONDEMNED|
22530 							IRE_MARK_HIDDEN))
22531 							continue;
22532 
22533 						/* Got one */
22534 						IRE_REFHOLD(ire1);
22535 						break;
22536 					}
22537 					IRB_REFRELE(irb);
22538 
22539 					if (ire1 != NULL) {
22540 						next_mp = copyb(mp);
22541 						if ((next_mp == NULL) ||
22542 						    ((mp->b_cont != NULL) &&
22543 						    ((next_mp->b_cont =
22544 						    dupmsg(mp->b_cont))
22545 						    == NULL))) {
22546 							freemsg(next_mp);
22547 							next_mp = NULL;
22548 							ire_refrele(ire1);
22549 							ire1 = NULL;
22550 						}
22551 					}
22552 
22553 					/*
22554 					 * Last multiroute ire; don't loop
22555 					 * anymore. The emission is over
22556 					 * and next_mp is NULL.
22557 					 */
22558 					if (ire1 == NULL) {
22559 						multirt_send = B_FALSE;
22560 					}
22561 				}
22562 
22563 				out_ill = ire->ire_ipif->ipif_ill;
22564 				DTRACE_PROBE4(ip4__physical__out__start,
22565 				    ill_t *, NULL,
22566 				    ill_t *, out_ill,
22567 				    ipha_t *, ipha, mblk_t *, mp);
22568 				FW_HOOKS(ip4_physical_out_event,
22569 				    ipv4firewall_physical_out,
22570 				    NULL, out_ill, ipha, mp, mp);
22571 				DTRACE_PROBE1(ip4__physical__out__end,
22572 				    mblk_t *, mp);
22573 				if (mp == NULL)
22574 					goto release_ire_and_ill_2;
22575 
22576 				ASSERT(ipsec_len == 0);
22577 				mp->b_prev =
22578 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22579 				DTRACE_PROBE2(ip__xmit__2,
22580 				    mblk_t *, mp, ire_t *, ire);
22581 				pktxmit_state = ip_xmit_v4(mp, ire,
22582 				    NULL, B_TRUE);
22583 				if ((pktxmit_state == SEND_FAILED) ||
22584 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22585 release_ire_and_ill_2:
22586 					if (next_mp) {
22587 						freemsg(next_mp);
22588 						ire_refrele(ire1);
22589 					}
22590 					ire_refrele(ire);
22591 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22592 					    "ip_wput_ire_end: q %p (%S)",
22593 					    q, "discard MDATA");
22594 					if (conn_outgoing_ill != NULL)
22595 						ill_refrele(conn_outgoing_ill);
22596 					return;
22597 				}
22598 
22599 				if (multirt_send) {
22600 					/*
22601 					 * We are in a multiple send case,
22602 					 * need to re-enter the sending loop
22603 					 * using the next ire.
22604 					 */
22605 					ire_refrele(ire);
22606 					ire = ire1;
22607 					stq = ire->ire_stq;
22608 					mp = next_mp;
22609 					next_mp = NULL;
22610 					ipha = (ipha_t *)mp->b_rptr;
22611 					ill_index = Q_TO_INDEX(stq);
22612 				}
22613 			} while (multirt_send);
22614 
22615 			if (!next_mp) {
22616 				/*
22617 				 * Last copy going out (the ultra-common
22618 				 * case).  Note that we intentionally replicate
22619 				 * the putnext rather than calling it before
22620 				 * the next_mp check in hopes of a little
22621 				 * tail-call action out of the compiler.
22622 				 */
22623 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22624 				    "ip_wput_ire_end: q %p (%S)",
22625 				    q, "last copy out(1)");
22626 				ire_refrele(ire);
22627 				if (conn_outgoing_ill != NULL)
22628 					ill_refrele(conn_outgoing_ill);
22629 				return;
22630 			}
22631 			/* More copies going out below. */
22632 		} else {
22633 			int offset;
22634 		    fragmentit:
22635 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22636 			/*
22637 			 * If this would generate a icmp_frag_needed message,
22638 			 * we need to handle it before we do the IPSEC
22639 			 * processing. Otherwise, we need to strip the IPSEC
22640 			 * headers before we send up the message to the ULPs
22641 			 * which becomes messy and difficult.
22642 			 */
22643 			if (ipsec_len != 0) {
22644 				if ((max_frag < (unsigned int)(LENGTH +
22645 				    ipsec_len)) && (offset & IPH_DF)) {
22646 
22647 					BUMP_MIB(&ip_mib, ipFragFails);
22648 					ipha->ipha_hdr_checksum = 0;
22649 					ipha->ipha_hdr_checksum =
22650 					    (uint16_t)ip_csum_hdr(ipha);
22651 					icmp_frag_needed(ire->ire_stq, first_mp,
22652 					    max_frag, zoneid);
22653 					if (!next_mp) {
22654 						ire_refrele(ire);
22655 						if (conn_outgoing_ill != NULL) {
22656 							ill_refrele(
22657 							    conn_outgoing_ill);
22658 						}
22659 						return;
22660 					}
22661 				} else {
22662 					/*
22663 					 * This won't cause a icmp_frag_needed
22664 					 * message. to be gnerated. Send it on
22665 					 * the wire. Note that this could still
22666 					 * cause fragmentation and all we
22667 					 * do is the generation of the message
22668 					 * to the ULP if needed before IPSEC.
22669 					 */
22670 					if (!next_mp) {
22671 						ipsec_out_process(q, first_mp,
22672 						    ire, ill_index);
22673 						TRACE_2(TR_FAC_IP,
22674 						    TR_IP_WPUT_IRE_END,
22675 						    "ip_wput_ire_end: q %p "
22676 						    "(%S)", q,
22677 						    "last ipsec_out_process");
22678 						ire_refrele(ire);
22679 						if (conn_outgoing_ill != NULL) {
22680 							ill_refrele(
22681 							    conn_outgoing_ill);
22682 						}
22683 						return;
22684 					}
22685 					ipsec_out_process(q, first_mp,
22686 					    ire, ill_index);
22687 				}
22688 			} else {
22689 				/*
22690 				 * Initiate IPPF processing. For
22691 				 * fragmentable packets we finish
22692 				 * all QOS packet processing before
22693 				 * calling:
22694 				 * ip_wput_ire_fragmentit->ip_wput_frag
22695 				 */
22696 
22697 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22698 					ip_process(IPP_LOCAL_OUT, &mp,
22699 					    ill_index);
22700 					if (mp == NULL) {
22701 						BUMP_MIB(&ip_mib,
22702 						    ipOutDiscards);
22703 						if (next_mp != NULL) {
22704 							freemsg(next_mp);
22705 							ire_refrele(ire1);
22706 						}
22707 						ire_refrele(ire);
22708 						TRACE_2(TR_FAC_IP,
22709 						    TR_IP_WPUT_IRE_END,
22710 						    "ip_wput_ire: q %p (%S)",
22711 						    q, "discard MDATA");
22712 						if (conn_outgoing_ill != NULL) {
22713 							ill_refrele(
22714 							    conn_outgoing_ill);
22715 						}
22716 						return;
22717 					}
22718 				}
22719 				if (!next_mp) {
22720 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22721 					    "ip_wput_ire_end: q %p (%S)",
22722 					    q, "last fragmentation");
22723 					ip_wput_ire_fragmentit(mp, ire,
22724 					    zoneid);
22725 					ire_refrele(ire);
22726 					if (conn_outgoing_ill != NULL)
22727 						ill_refrele(conn_outgoing_ill);
22728 					return;
22729 				}
22730 				ip_wput_ire_fragmentit(mp, ire, zoneid);
22731 			}
22732 		}
22733 	} else {
22734 	    nullstq:
22735 		/* A NULL stq means the destination address is local. */
22736 		UPDATE_OB_PKT_COUNT(ire);
22737 		ire->ire_last_used_time = lbolt;
22738 		ASSERT(ire->ire_ipif != NULL);
22739 		if (!next_mp) {
22740 			/*
22741 			 * Is there an "in" and "out" for traffic local
22742 			 * to a host (loopback)?  The code in Solaris doesn't
22743 			 * explicitly draw a line in its code for in vs out,
22744 			 * so we've had to draw a line in the sand: ip_wput_ire
22745 			 * is considered to be the "output" side and
22746 			 * ip_wput_local to be the "input" side.
22747 			 */
22748 			out_ill = ire->ire_ipif->ipif_ill;
22749 
22750 			DTRACE_PROBE4(ip4__loopback__out__start,
22751 			    ill_t *, NULL, ill_t *, out_ill,
22752 			    ipha_t *, ipha, mblk_t *, first_mp);
22753 
22754 			FW_HOOKS(ip4_loopback_out_event,
22755 			    ipv4firewall_loopback_out,
22756 			    NULL, out_ill, ipha, first_mp, mp);
22757 
22758 			DTRACE_PROBE1(ip4__loopback__out_end,
22759 			    mblk_t *, first_mp);
22760 
22761 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22762 			    "ip_wput_ire_end: q %p (%S)",
22763 			    q, "local address");
22764 
22765 			if (first_mp != NULL)
22766 				ip_wput_local(q, out_ill, ipha,
22767 				    first_mp, ire, 0, ire->ire_zoneid);
22768 			ire_refrele(ire);
22769 			if (conn_outgoing_ill != NULL)
22770 				ill_refrele(conn_outgoing_ill);
22771 			return;
22772 		}
22773 
22774 		out_ill = ire->ire_ipif->ipif_ill;
22775 
22776 		DTRACE_PROBE4(ip4__loopback__out__start,
22777 		    ill_t *, NULL, ill_t *, out_ill,
22778 		    ipha_t *, ipha, mblk_t *, first_mp);
22779 
22780 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
22781 		    NULL, out_ill, ipha, first_mp, mp);
22782 
22783 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
22784 
22785 		if (first_mp != NULL)
22786 			ip_wput_local(q, out_ill, ipha,
22787 			    first_mp, ire, 0, ire->ire_zoneid);
22788 	}
22789 next:
22790 	/*
22791 	 * More copies going out to additional interfaces.
22792 	 * ire1 has already been held. We don't need the
22793 	 * "ire" anymore.
22794 	 */
22795 	ire_refrele(ire);
22796 	ire = ire1;
22797 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
22798 	mp = next_mp;
22799 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
22800 	ill = ire_to_ill(ire);
22801 	first_mp = mp;
22802 	if (ipsec_len != 0) {
22803 		ASSERT(first_mp->b_datap->db_type == M_CTL);
22804 		mp = mp->b_cont;
22805 	}
22806 	dst = ire->ire_addr;
22807 	ipha = (ipha_t *)mp->b_rptr;
22808 	/*
22809 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
22810 	 * Restore ipha_ident "no checksum" flag.
22811 	 */
22812 	src = orig_src;
22813 	ipha->ipha_ident = ip_hdr_included;
22814 	goto another;
22815 
22816 #undef	rptr
22817 #undef	Q_TO_INDEX
22818 }
22819 
22820 /*
22821  * Routine to allocate a message that is used to notify the ULP about MDT.
22822  * The caller may provide a pointer to the link-layer MDT capabilities,
22823  * or NULL if MDT is to be disabled on the stream.
22824  */
22825 mblk_t *
22826 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
22827 {
22828 	mblk_t *mp;
22829 	ip_mdt_info_t *mdti;
22830 	ill_mdt_capab_t *idst;
22831 
22832 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
22833 		DB_TYPE(mp) = M_CTL;
22834 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
22835 		mdti = (ip_mdt_info_t *)mp->b_rptr;
22836 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
22837 		idst = &(mdti->mdt_capab);
22838 
22839 		/*
22840 		 * If the caller provides us with the capability, copy
22841 		 * it over into our notification message; otherwise
22842 		 * we zero out the capability portion.
22843 		 */
22844 		if (isrc != NULL)
22845 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22846 		else
22847 			bzero((caddr_t)idst, sizeof (*idst));
22848 	}
22849 	return (mp);
22850 }
22851 
22852 /*
22853  * Routine which determines whether MDT can be enabled on the destination
22854  * IRE and IPC combination, and if so, allocates and returns the MDT
22855  * notification mblk that may be used by ULP.  We also check if we need to
22856  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
22857  * MDT usage in the past have been lifted.  This gets called during IP
22858  * and ULP binding.
22859  */
22860 mblk_t *
22861 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22862     ill_mdt_capab_t *mdt_cap)
22863 {
22864 	mblk_t *mp;
22865 	boolean_t rc = B_FALSE;
22866 
22867 	ASSERT(dst_ire != NULL);
22868 	ASSERT(connp != NULL);
22869 	ASSERT(mdt_cap != NULL);
22870 
22871 	/*
22872 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
22873 	 * Multidata, which is handled in tcp_multisend().  This
22874 	 * is the reason why we do all these checks here, to ensure
22875 	 * that we don't enable Multidata for the cases which we
22876 	 * can't handle at the moment.
22877 	 */
22878 	do {
22879 		/* Only do TCP at the moment */
22880 		if (connp->conn_ulp != IPPROTO_TCP)
22881 			break;
22882 
22883 		/*
22884 		 * IPSEC outbound policy present?  Note that we get here
22885 		 * after calling ipsec_conn_cache_policy() where the global
22886 		 * policy checking is performed.  conn_latch will be
22887 		 * non-NULL as long as there's a policy defined,
22888 		 * i.e. conn_out_enforce_policy may be NULL in such case
22889 		 * when the connection is non-secure, and hence we check
22890 		 * further if the latch refers to an outbound policy.
22891 		 */
22892 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
22893 			break;
22894 
22895 		/* CGTP (multiroute) is enabled? */
22896 		if (dst_ire->ire_flags & RTF_MULTIRT)
22897 			break;
22898 
22899 		/* Outbound IPQoS enabled? */
22900 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22901 			/*
22902 			 * In this case, we disable MDT for this and all
22903 			 * future connections going over the interface.
22904 			 */
22905 			mdt_cap->ill_mdt_on = 0;
22906 			break;
22907 		}
22908 
22909 		/* socket option(s) present? */
22910 		if (!CONN_IS_MD_FASTPATH(connp))
22911 			break;
22912 
22913 		rc = B_TRUE;
22914 	/* CONSTCOND */
22915 	} while (0);
22916 
22917 	/* Remember the result */
22918 	connp->conn_mdt_ok = rc;
22919 
22920 	if (!rc)
22921 		return (NULL);
22922 	else if (!mdt_cap->ill_mdt_on) {
22923 		/*
22924 		 * If MDT has been previously turned off in the past, and we
22925 		 * currently can do MDT (due to IPQoS policy removal, etc.)
22926 		 * then enable it for this interface.
22927 		 */
22928 		mdt_cap->ill_mdt_on = 1;
22929 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
22930 		    "interface %s\n", ill_name));
22931 	}
22932 
22933 	/* Allocate the MDT info mblk */
22934 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
22935 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
22936 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
22937 		return (NULL);
22938 	}
22939 	return (mp);
22940 }
22941 
22942 /*
22943  * Create destination address attribute, and fill it with the physical
22944  * destination address and SAP taken from the template DL_UNITDATA_REQ
22945  * message block.
22946  */
22947 boolean_t
22948 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
22949 {
22950 	dl_unitdata_req_t *dlurp;
22951 	pattr_t *pa;
22952 	pattrinfo_t pa_info;
22953 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
22954 	uint_t das_len, das_off;
22955 
22956 	ASSERT(dlmp != NULL);
22957 
22958 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
22959 	das_len = dlurp->dl_dest_addr_length;
22960 	das_off = dlurp->dl_dest_addr_offset;
22961 
22962 	pa_info.type = PATTR_DSTADDRSAP;
22963 	pa_info.len = sizeof (**das) + das_len - 1;
22964 
22965 	/* create and associate the attribute */
22966 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22967 	if (pa != NULL) {
22968 		ASSERT(*das != NULL);
22969 		(*das)->addr_is_group = 0;
22970 		(*das)->addr_len = (uint8_t)das_len;
22971 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
22972 	}
22973 
22974 	return (pa != NULL);
22975 }
22976 
22977 /*
22978  * Create hardware checksum attribute and fill it with the values passed.
22979  */
22980 boolean_t
22981 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
22982     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
22983 {
22984 	pattr_t *pa;
22985 	pattrinfo_t pa_info;
22986 
22987 	ASSERT(mmd != NULL);
22988 
22989 	pa_info.type = PATTR_HCKSUM;
22990 	pa_info.len = sizeof (pattr_hcksum_t);
22991 
22992 	/* create and associate the attribute */
22993 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22994 	if (pa != NULL) {
22995 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
22996 
22997 		hck->hcksum_start_offset = start_offset;
22998 		hck->hcksum_stuff_offset = stuff_offset;
22999 		hck->hcksum_end_offset = end_offset;
23000 		hck->hcksum_flags = flags;
23001 	}
23002 	return (pa != NULL);
23003 }
23004 
23005 /*
23006  * Create zerocopy attribute and fill it with the specified flags
23007  */
23008 boolean_t
23009 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23010 {
23011 	pattr_t *pa;
23012 	pattrinfo_t pa_info;
23013 
23014 	ASSERT(mmd != NULL);
23015 	pa_info.type = PATTR_ZCOPY;
23016 	pa_info.len = sizeof (pattr_zcopy_t);
23017 
23018 	/* create and associate the attribute */
23019 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23020 	if (pa != NULL) {
23021 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23022 
23023 		zcopy->zcopy_flags = flags;
23024 	}
23025 	return (pa != NULL);
23026 }
23027 
23028 /*
23029  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23030  * block chain. We could rewrite to handle arbitrary message block chains but
23031  * that would make the code complicated and slow. Right now there three
23032  * restrictions:
23033  *
23034  *   1. The first message block must contain the complete IP header and
23035  *	at least 1 byte of payload data.
23036  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23037  *	so that we can use a single Multidata message.
23038  *   3. No frag must be distributed over two or more message blocks so
23039  *	that we don't need more than two packet descriptors per frag.
23040  *
23041  * The above restrictions allow us to support userland applications (which
23042  * will send down a single message block) and NFS over UDP (which will
23043  * send down a chain of at most three message blocks).
23044  *
23045  * We also don't use MDT for payloads with less than or equal to
23046  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23047  */
23048 boolean_t
23049 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23050 {
23051 	int	blocks;
23052 	ssize_t	total, missing, size;
23053 
23054 	ASSERT(mp != NULL);
23055 	ASSERT(hdr_len > 0);
23056 
23057 	size = MBLKL(mp) - hdr_len;
23058 	if (size <= 0)
23059 		return (B_FALSE);
23060 
23061 	/* The first mblk contains the header and some payload. */
23062 	blocks = 1;
23063 	total = size;
23064 	size %= len;
23065 	missing = (size == 0) ? 0 : (len - size);
23066 	mp = mp->b_cont;
23067 
23068 	while (mp != NULL) {
23069 		/*
23070 		 * Give up if we encounter a zero length message block.
23071 		 * In practice, this should rarely happen and therefore
23072 		 * not worth the trouble of freeing and re-linking the
23073 		 * mblk from the chain to handle such case.
23074 		 */
23075 		if ((size = MBLKL(mp)) == 0)
23076 			return (B_FALSE);
23077 
23078 		/* Too many payload buffers for a single Multidata message? */
23079 		if (++blocks > MULTIDATA_MAX_PBUFS)
23080 			return (B_FALSE);
23081 
23082 		total += size;
23083 		/* Is a frag distributed over two or more message blocks? */
23084 		if (missing > size)
23085 			return (B_FALSE);
23086 		size -= missing;
23087 
23088 		size %= len;
23089 		missing = (size == 0) ? 0 : (len - size);
23090 
23091 		mp = mp->b_cont;
23092 	}
23093 
23094 	return (total > ip_wput_frag_mdt_min);
23095 }
23096 
23097 /*
23098  * Outbound IPv4 fragmentation routine using MDT.
23099  */
23100 static void
23101 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23102     uint32_t frag_flag, int offset)
23103 {
23104 	ipha_t		*ipha_orig;
23105 	int		i1, ip_data_end;
23106 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23107 	mblk_t		*hdr_mp, *md_mp = NULL;
23108 	unsigned char	*hdr_ptr, *pld_ptr;
23109 	multidata_t	*mmd;
23110 	ip_pdescinfo_t	pdi;
23111 
23112 	ASSERT(DB_TYPE(mp) == M_DATA);
23113 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23114 
23115 	ipha_orig = (ipha_t *)mp->b_rptr;
23116 	mp->b_rptr += sizeof (ipha_t);
23117 
23118 	/* Calculate how many packets we will send out */
23119 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23120 	pkts = (i1 + len - 1) / len;
23121 	ASSERT(pkts > 1);
23122 
23123 	/* Allocate a message block which will hold all the IP Headers. */
23124 	wroff = ip_wroff_extra;
23125 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23126 
23127 	i1 = pkts * hdr_chunk_len;
23128 	/*
23129 	 * Create the header buffer, Multidata and destination address
23130 	 * and SAP attribute that should be associated with it.
23131 	 */
23132 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23133 	    ((hdr_mp->b_wptr += i1),
23134 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23135 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23136 		freemsg(mp);
23137 		if (md_mp == NULL) {
23138 			freemsg(hdr_mp);
23139 		} else {
23140 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
23141 			freemsg(md_mp);
23142 		}
23143 		IP_STAT(ip_frag_mdt_allocfail);
23144 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
23145 		return;
23146 	}
23147 	IP_STAT(ip_frag_mdt_allocd);
23148 
23149 	/*
23150 	 * Add a payload buffer to the Multidata; this operation must not
23151 	 * fail, or otherwise our logic in this routine is broken.  There
23152 	 * is no memory allocation done by the routine, so any returned
23153 	 * failure simply tells us that we've done something wrong.
23154 	 *
23155 	 * A failure tells us that either we're adding the same payload
23156 	 * buffer more than once, or we're trying to add more buffers than
23157 	 * allowed.  None of the above cases should happen, and we panic
23158 	 * because either there's horrible heap corruption, and/or
23159 	 * programming mistake.
23160 	 */
23161 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23162 		goto pbuf_panic;
23163 
23164 	hdr_ptr = hdr_mp->b_rptr;
23165 	pld_ptr = mp->b_rptr;
23166 
23167 	/* Establish the ending byte offset, based on the starting offset. */
23168 	offset <<= 3;
23169 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23170 	    IP_SIMPLE_HDR_LENGTH;
23171 
23172 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23173 
23174 	while (pld_ptr < mp->b_wptr) {
23175 		ipha_t		*ipha;
23176 		uint16_t	offset_and_flags;
23177 		uint16_t	ip_len;
23178 		int		error;
23179 
23180 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23181 		ipha = (ipha_t *)(hdr_ptr + wroff);
23182 		ASSERT(OK_32PTR(ipha));
23183 		*ipha = *ipha_orig;
23184 
23185 		if (ip_data_end - offset > len) {
23186 			offset_and_flags = IPH_MF;
23187 		} else {
23188 			/*
23189 			 * Last frag. Set len to the length of this last piece.
23190 			 */
23191 			len = ip_data_end - offset;
23192 			/* A frag of a frag might have IPH_MF non-zero */
23193 			offset_and_flags =
23194 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23195 			    IPH_MF;
23196 		}
23197 		offset_and_flags |= (uint16_t)(offset >> 3);
23198 		offset_and_flags |= (uint16_t)frag_flag;
23199 		/* Store the offset and flags in the IP header. */
23200 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23201 
23202 		/* Store the length in the IP header. */
23203 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23204 		ipha->ipha_length = htons(ip_len);
23205 
23206 		/*
23207 		 * Set the IP header checksum.  Note that mp is just
23208 		 * the header, so this is easy to pass to ip_csum.
23209 		 */
23210 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23211 
23212 		/*
23213 		 * Record offset and size of header and data of the next packet
23214 		 * in the multidata message.
23215 		 */
23216 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23217 		PDESC_PLD_INIT(&pdi);
23218 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23219 		ASSERT(i1 > 0);
23220 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23221 		if (i1 == len) {
23222 			pld_ptr += len;
23223 		} else {
23224 			i1 = len - i1;
23225 			mp = mp->b_cont;
23226 			ASSERT(mp != NULL);
23227 			ASSERT(MBLKL(mp) >= i1);
23228 			/*
23229 			 * Attach the next payload message block to the
23230 			 * multidata message.
23231 			 */
23232 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23233 				goto pbuf_panic;
23234 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23235 			pld_ptr = mp->b_rptr + i1;
23236 		}
23237 
23238 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23239 		    KM_NOSLEEP)) == NULL) {
23240 			/*
23241 			 * Any failure other than ENOMEM indicates that we
23242 			 * have passed in invalid pdesc info or parameters
23243 			 * to mmd_addpdesc, which must not happen.
23244 			 *
23245 			 * EINVAL is a result of failure on boundary checks
23246 			 * against the pdesc info contents.  It should not
23247 			 * happen, and we panic because either there's
23248 			 * horrible heap corruption, and/or programming
23249 			 * mistake.
23250 			 */
23251 			if (error != ENOMEM) {
23252 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23253 				    "pdesc logic error detected for "
23254 				    "mmd %p pinfo %p (%d)\n",
23255 				    (void *)mmd, (void *)&pdi, error);
23256 				/* NOTREACHED */
23257 			}
23258 			IP_STAT(ip_frag_mdt_addpdescfail);
23259 			/* Free unattached payload message blocks as well */
23260 			md_mp->b_cont = mp->b_cont;
23261 			goto free_mmd;
23262 		}
23263 
23264 		/* Advance fragment offset. */
23265 		offset += len;
23266 
23267 		/* Advance to location for next header in the buffer. */
23268 		hdr_ptr += hdr_chunk_len;
23269 
23270 		/* Did we reach the next payload message block? */
23271 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23272 			mp = mp->b_cont;
23273 			/*
23274 			 * Attach the next message block with payload
23275 			 * data to the multidata message.
23276 			 */
23277 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23278 				goto pbuf_panic;
23279 			pld_ptr = mp->b_rptr;
23280 		}
23281 	}
23282 
23283 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23284 	ASSERT(mp->b_wptr == pld_ptr);
23285 
23286 	/* Update IP statistics */
23287 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
23288 	BUMP_MIB(&ip_mib, ipFragOKs);
23289 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
23290 
23291 	if (pkt_type == OB_PKT) {
23292 		ire->ire_ob_pkt_count += pkts;
23293 		if (ire->ire_ipif != NULL)
23294 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23295 	} else {
23296 		/*
23297 		 * The type is IB_PKT in the forwarding path and in
23298 		 * the mobile IP case when the packet is being reverse-
23299 		 * tunneled to the home agent.
23300 		 */
23301 		ire->ire_ib_pkt_count += pkts;
23302 		ASSERT(!IRE_IS_LOCAL(ire));
23303 		if (ire->ire_type & IRE_BROADCAST)
23304 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23305 		else
23306 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23307 	}
23308 	ire->ire_last_used_time = lbolt;
23309 	/* Send it down */
23310 	putnext(ire->ire_stq, md_mp);
23311 	return;
23312 
23313 pbuf_panic:
23314 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23315 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23316 	    pbuf_idx);
23317 	/* NOTREACHED */
23318 }
23319 
23320 /*
23321  * Outbound IP fragmentation routine.
23322  *
23323  * NOTE : This routine does not ire_refrele the ire that is passed in
23324  * as the argument.
23325  */
23326 static void
23327 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23328     uint32_t frag_flag, zoneid_t zoneid)
23329 {
23330 	int		i1;
23331 	mblk_t		*ll_hdr_mp;
23332 	int 		ll_hdr_len;
23333 	int		hdr_len;
23334 	mblk_t		*hdr_mp;
23335 	ipha_t		*ipha;
23336 	int		ip_data_end;
23337 	int		len;
23338 	mblk_t		*mp = mp_orig, *mp1;
23339 	int		offset;
23340 	queue_t		*q;
23341 	uint32_t	v_hlen_tos_len;
23342 	mblk_t		*first_mp;
23343 	boolean_t	mctl_present;
23344 	ill_t		*ill;
23345 	ill_t		*out_ill;
23346 	mblk_t		*xmit_mp;
23347 	mblk_t		*carve_mp;
23348 	ire_t		*ire1 = NULL;
23349 	ire_t		*save_ire = NULL;
23350 	mblk_t  	*next_mp = NULL;
23351 	boolean_t	last_frag = B_FALSE;
23352 	boolean_t	multirt_send = B_FALSE;
23353 	ire_t		*first_ire = NULL;
23354 	irb_t		*irb = NULL;
23355 
23356 	/*
23357 	 * IPSEC does not allow hw accelerated packets to be fragmented
23358 	 * This check is made in ip_wput_ipsec_out prior to coming here
23359 	 * via ip_wput_ire_fragmentit.
23360 	 *
23361 	 * If at this point we have an ire whose ARP request has not
23362 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23363 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23364 	 * This packet and all fragmentable packets for this ire will
23365 	 * continue to get dropped while ire_nce->nce_state remains in
23366 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23367 	 * ND_REACHABLE, all subsquent large packets for this ire will
23368 	 * get fragemented and sent out by this function.
23369 	 */
23370 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23371 		/* If nce_state is ND_INITIAL, trigger ARP query */
23372 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23373 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23374 		    " -  dropping packet\n"));
23375 		BUMP_MIB(&ip_mib, ipFragFails);
23376 		freemsg(mp);
23377 		return;
23378 	}
23379 
23380 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23381 	    "ip_wput_frag_start:");
23382 
23383 	if (mp->b_datap->db_type == M_CTL) {
23384 		first_mp = mp;
23385 		mp_orig = mp = mp->b_cont;
23386 		mctl_present = B_TRUE;
23387 	} else {
23388 		first_mp = mp;
23389 		mctl_present = B_FALSE;
23390 	}
23391 
23392 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23393 	ipha = (ipha_t *)mp->b_rptr;
23394 
23395 	/*
23396 	 * If the Don't Fragment flag is on, generate an ICMP destination
23397 	 * unreachable, fragmentation needed.
23398 	 */
23399 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23400 	if (offset & IPH_DF) {
23401 		BUMP_MIB(&ip_mib, ipFragFails);
23402 		/*
23403 		 * Need to compute hdr checksum if called from ip_wput_ire.
23404 		 * Note that ip_rput_forward verifies the checksum before
23405 		 * calling this routine so in that case this is a noop.
23406 		 */
23407 		ipha->ipha_hdr_checksum = 0;
23408 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23409 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid);
23410 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23411 		    "ip_wput_frag_end:(%S)",
23412 		    "don't fragment");
23413 		return;
23414 	}
23415 	if (mctl_present)
23416 		freeb(first_mp);
23417 	/*
23418 	 * Establish the starting offset.  May not be zero if we are fragging
23419 	 * a fragment that is being forwarded.
23420 	 */
23421 	offset = offset & IPH_OFFSET;
23422 
23423 	/* TODO why is this test needed? */
23424 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23425 	if (((max_frag - LENGTH) & ~7) < 8) {
23426 		/* TODO: notify ulp somehow */
23427 		BUMP_MIB(&ip_mib, ipFragFails);
23428 		freemsg(mp);
23429 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23430 		    "ip_wput_frag_end:(%S)",
23431 		    "len < 8");
23432 		return;
23433 	}
23434 
23435 	hdr_len = (V_HLEN & 0xF) << 2;
23436 
23437 	ipha->ipha_hdr_checksum = 0;
23438 
23439 	/*
23440 	 * Establish the number of bytes maximum per frag, after putting
23441 	 * in the header.
23442 	 */
23443 	len = (max_frag - hdr_len) & ~7;
23444 
23445 	/* Check if we can use MDT to send out the frags. */
23446 	ASSERT(!IRE_IS_LOCAL(ire));
23447 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
23448 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
23449 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
23450 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23451 		ASSERT(ill->ill_mdt_capab != NULL);
23452 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23453 			/*
23454 			 * If MDT has been previously turned off in the past,
23455 			 * and we currently can do MDT (due to IPQoS policy
23456 			 * removal, etc.) then enable it for this interface.
23457 			 */
23458 			ill->ill_mdt_capab->ill_mdt_on = 1;
23459 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23460 			    ill->ill_name));
23461 		}
23462 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23463 		    offset);
23464 		return;
23465 	}
23466 
23467 	/* Get a copy of the header for the trailing frags */
23468 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
23469 	if (!hdr_mp) {
23470 		BUMP_MIB(&ip_mib, ipOutDiscards);
23471 		freemsg(mp);
23472 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23473 		    "ip_wput_frag_end:(%S)",
23474 		    "couldn't copy hdr");
23475 		return;
23476 	}
23477 	if (DB_CRED(mp) != NULL)
23478 		mblk_setcred(hdr_mp, DB_CRED(mp));
23479 
23480 	/* Store the starting offset, with the MoreFrags flag. */
23481 	i1 = offset | IPH_MF | frag_flag;
23482 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23483 
23484 	/* Establish the ending byte offset, based on the starting offset. */
23485 	offset <<= 3;
23486 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23487 
23488 	/* Store the length of the first fragment in the IP header. */
23489 	i1 = len + hdr_len;
23490 	ASSERT(i1 <= IP_MAXPACKET);
23491 	ipha->ipha_length = htons((uint16_t)i1);
23492 
23493 	/*
23494 	 * Compute the IP header checksum for the first frag.  We have to
23495 	 * watch out that we stop at the end of the header.
23496 	 */
23497 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23498 
23499 	/*
23500 	 * Now carve off the first frag.  Note that this will include the
23501 	 * original IP header.
23502 	 */
23503 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
23504 		BUMP_MIB(&ip_mib, ipOutDiscards);
23505 		freeb(hdr_mp);
23506 		freemsg(mp_orig);
23507 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23508 		    "ip_wput_frag_end:(%S)",
23509 		    "couldn't carve first");
23510 		return;
23511 	}
23512 
23513 	/*
23514 	 * Multirouting case. Each fragment is replicated
23515 	 * via all non-condemned RTF_MULTIRT routes
23516 	 * currently resolved.
23517 	 * We ensure that first_ire is the first RTF_MULTIRT
23518 	 * ire in the bucket.
23519 	 */
23520 	if (ire->ire_flags & RTF_MULTIRT) {
23521 		irb = ire->ire_bucket;
23522 		ASSERT(irb != NULL);
23523 
23524 		multirt_send = B_TRUE;
23525 
23526 		/* Make sure we do not omit any multiroute ire. */
23527 		IRB_REFHOLD(irb);
23528 		for (first_ire = irb->irb_ire;
23529 		    first_ire != NULL;
23530 		    first_ire = first_ire->ire_next) {
23531 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23532 			    (first_ire->ire_addr == ire->ire_addr) &&
23533 			    !(first_ire->ire_marks &
23534 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23535 				break;
23536 		}
23537 
23538 		if (first_ire != NULL) {
23539 			if (first_ire != ire) {
23540 				IRE_REFHOLD(first_ire);
23541 				/*
23542 				 * Do not release the ire passed in
23543 				 * as the argument.
23544 				 */
23545 				ire = first_ire;
23546 			} else {
23547 				first_ire = NULL;
23548 			}
23549 		}
23550 		IRB_REFRELE(irb);
23551 
23552 		/*
23553 		 * Save the first ire; we will need to restore it
23554 		 * for the trailing frags.
23555 		 * We REFHOLD save_ire, as each iterated ire will be
23556 		 * REFRELEd.
23557 		 */
23558 		save_ire = ire;
23559 		IRE_REFHOLD(save_ire);
23560 	}
23561 
23562 	/*
23563 	 * First fragment emission loop.
23564 	 * In most cases, the emission loop below is entered only
23565 	 * once. Only in the case where the ire holds the RTF_MULTIRT
23566 	 * flag, do we loop to process all RTF_MULTIRT ires in the
23567 	 * bucket, and send the fragment through all crossed
23568 	 * RTF_MULTIRT routes.
23569 	 */
23570 	do {
23571 		if (ire->ire_flags & RTF_MULTIRT) {
23572 			/*
23573 			 * We are in a multiple send case, need to get
23574 			 * the next ire and make a copy of the packet.
23575 			 * ire1 holds here the next ire to process in the
23576 			 * bucket. If multirouting is expected,
23577 			 * any non-RTF_MULTIRT ire that has the
23578 			 * right destination address is ignored.
23579 			 *
23580 			 * We have to take into account the MTU of
23581 			 * each walked ire. max_frag is set by the
23582 			 * the caller and generally refers to
23583 			 * the primary ire entry. Here we ensure that
23584 			 * no route with a lower MTU will be used, as
23585 			 * fragments are carved once for all ires,
23586 			 * then replicated.
23587 			 */
23588 			ASSERT(irb != NULL);
23589 			IRB_REFHOLD(irb);
23590 			for (ire1 = ire->ire_next;
23591 			    ire1 != NULL;
23592 			    ire1 = ire1->ire_next) {
23593 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23594 					continue;
23595 				if (ire1->ire_addr != ire->ire_addr)
23596 					continue;
23597 				if (ire1->ire_marks &
23598 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23599 					continue;
23600 				/*
23601 				 * Ensure we do not exceed the MTU
23602 				 * of the next route.
23603 				 */
23604 				if (ire1->ire_max_frag < max_frag) {
23605 					ip_multirt_bad_mtu(ire1, max_frag);
23606 					continue;
23607 				}
23608 
23609 				/* Got one. */
23610 				IRE_REFHOLD(ire1);
23611 				break;
23612 			}
23613 			IRB_REFRELE(irb);
23614 
23615 			if (ire1 != NULL) {
23616 				next_mp = copyb(mp);
23617 				if ((next_mp == NULL) ||
23618 				    ((mp->b_cont != NULL) &&
23619 				    ((next_mp->b_cont =
23620 				    dupmsg(mp->b_cont)) == NULL))) {
23621 					freemsg(next_mp);
23622 					next_mp = NULL;
23623 					ire_refrele(ire1);
23624 					ire1 = NULL;
23625 				}
23626 			}
23627 
23628 			/* Last multiroute ire; don't loop anymore. */
23629 			if (ire1 == NULL) {
23630 				multirt_send = B_FALSE;
23631 			}
23632 		}
23633 
23634 		ll_hdr_len = 0;
23635 		LOCK_IRE_FP_MP(ire);
23636 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23637 		if (ll_hdr_mp != NULL) {
23638 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23639 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
23640 		} else {
23641 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
23642 		}
23643 
23644 		/* If there is a transmit header, get a copy for this frag. */
23645 		/*
23646 		 * TODO: should check db_ref before calling ip_carve_mp since
23647 		 * it might give us a dup.
23648 		 */
23649 		if (!ll_hdr_mp) {
23650 			/* No xmit header. */
23651 			xmit_mp = mp;
23652 
23653 		/* We have a link-layer header that can fit in our mblk. */
23654 		} else if (mp->b_datap->db_ref == 1 &&
23655 		    ll_hdr_len != 0 &&
23656 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23657 			/* M_DATA fastpath */
23658 			mp->b_rptr -= ll_hdr_len;
23659 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
23660 			xmit_mp = mp;
23661 
23662 		/* Corner case if copyb has failed */
23663 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
23664 			UNLOCK_IRE_FP_MP(ire);
23665 			BUMP_MIB(&ip_mib, ipOutDiscards);
23666 			freeb(hdr_mp);
23667 			freemsg(mp);
23668 			freemsg(mp_orig);
23669 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23670 			    "ip_wput_frag_end:(%S)",
23671 			    "discard");
23672 
23673 			if (multirt_send) {
23674 				ASSERT(ire1);
23675 				ASSERT(next_mp);
23676 
23677 				freemsg(next_mp);
23678 				ire_refrele(ire1);
23679 			}
23680 			if (save_ire != NULL)
23681 				IRE_REFRELE(save_ire);
23682 
23683 			if (first_ire != NULL)
23684 				ire_refrele(first_ire);
23685 			return;
23686 
23687 		/*
23688 		 * Case of res_mp OR the fastpath mp can't fit
23689 		 * in the mblk
23690 		 */
23691 		} else {
23692 			xmit_mp->b_cont = mp;
23693 			if (DB_CRED(mp) != NULL)
23694 				mblk_setcred(xmit_mp, DB_CRED(mp));
23695 			/*
23696 			 * Get priority marking, if any.
23697 			 * We propagate the CoS marking from the
23698 			 * original packet that went to QoS processing
23699 			 * in ip_wput_ire to the newly carved mp.
23700 			 */
23701 			if (DB_TYPE(xmit_mp) == M_DATA)
23702 				xmit_mp->b_band = mp->b_band;
23703 		}
23704 		UNLOCK_IRE_FP_MP(ire);
23705 		q = ire->ire_stq;
23706 		BUMP_MIB(&ip_mib, ipFragCreates);
23707 
23708 		out_ill = (ill_t *)q->q_ptr;
23709 
23710 		DTRACE_PROBE4(ip4__physical__out__start,
23711 		    ill_t *, NULL, ill_t *, out_ill,
23712 		    ipha_t *, ipha, mblk_t *, xmit_mp);
23713 
23714 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
23715 		    NULL, out_ill, ipha, xmit_mp, mp);
23716 
23717 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
23718 
23719 		if (xmit_mp != NULL) {
23720 			putnext(q, xmit_mp);
23721 			if (pkt_type != OB_PKT) {
23722 				/*
23723 				 * Update the packet count of trailing
23724 				 * RTF_MULTIRT ires.
23725 				 */
23726 				UPDATE_OB_PKT_COUNT(ire);
23727 			}
23728 		}
23729 
23730 		if (multirt_send) {
23731 			/*
23732 			 * We are in a multiple send case; look for
23733 			 * the next ire and re-enter the loop.
23734 			 */
23735 			ASSERT(ire1);
23736 			ASSERT(next_mp);
23737 			/* REFRELE the current ire before looping */
23738 			ire_refrele(ire);
23739 			ire = ire1;
23740 			ire1 = NULL;
23741 			mp = next_mp;
23742 			next_mp = NULL;
23743 		}
23744 	} while (multirt_send);
23745 
23746 	ASSERT(ire1 == NULL);
23747 
23748 	/* Restore the original ire; we need it for the trailing frags */
23749 	if (save_ire != NULL) {
23750 		/* REFRELE the last iterated ire */
23751 		ire_refrele(ire);
23752 		/* save_ire has been REFHOLDed */
23753 		ire = save_ire;
23754 		save_ire = NULL;
23755 		q = ire->ire_stq;
23756 	}
23757 
23758 	if (pkt_type == OB_PKT) {
23759 		UPDATE_OB_PKT_COUNT(ire);
23760 	} else {
23761 		UPDATE_IB_PKT_COUNT(ire);
23762 	}
23763 
23764 	/* Advance the offset to the second frag starting point. */
23765 	offset += len;
23766 	/*
23767 	 * Update hdr_len from the copied header - there might be less options
23768 	 * in the later fragments.
23769 	 */
23770 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
23771 	/* Loop until done. */
23772 	for (;;) {
23773 		uint16_t	offset_and_flags;
23774 		uint16_t	ip_len;
23775 
23776 		if (ip_data_end - offset > len) {
23777 			/*
23778 			 * Carve off the appropriate amount from the original
23779 			 * datagram.
23780 			 */
23781 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23782 				mp = NULL;
23783 				break;
23784 			}
23785 			/*
23786 			 * More frags after this one.  Get another copy
23787 			 * of the header.
23788 			 */
23789 			if (carve_mp->b_datap->db_ref == 1 &&
23790 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23791 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23792 				/* Inline IP header */
23793 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23794 				    hdr_mp->b_rptr;
23795 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23796 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23797 				mp = carve_mp;
23798 			} else {
23799 				if (!(mp = copyb(hdr_mp))) {
23800 					freemsg(carve_mp);
23801 					break;
23802 				}
23803 				/* Get priority marking, if any. */
23804 				mp->b_band = carve_mp->b_band;
23805 				mp->b_cont = carve_mp;
23806 			}
23807 			ipha = (ipha_t *)mp->b_rptr;
23808 			offset_and_flags = IPH_MF;
23809 		} else {
23810 			/*
23811 			 * Last frag.  Consume the header. Set len to
23812 			 * the length of this last piece.
23813 			 */
23814 			len = ip_data_end - offset;
23815 
23816 			/*
23817 			 * Carve off the appropriate amount from the original
23818 			 * datagram.
23819 			 */
23820 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23821 				mp = NULL;
23822 				break;
23823 			}
23824 			if (carve_mp->b_datap->db_ref == 1 &&
23825 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23826 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23827 				/* Inline IP header */
23828 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23829 				    hdr_mp->b_rptr;
23830 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23831 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23832 				mp = carve_mp;
23833 				freeb(hdr_mp);
23834 				hdr_mp = mp;
23835 			} else {
23836 				mp = hdr_mp;
23837 				/* Get priority marking, if any. */
23838 				mp->b_band = carve_mp->b_band;
23839 				mp->b_cont = carve_mp;
23840 			}
23841 			ipha = (ipha_t *)mp->b_rptr;
23842 			/* A frag of a frag might have IPH_MF non-zero */
23843 			offset_and_flags =
23844 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23845 			    IPH_MF;
23846 		}
23847 		offset_and_flags |= (uint16_t)(offset >> 3);
23848 		offset_and_flags |= (uint16_t)frag_flag;
23849 		/* Store the offset and flags in the IP header. */
23850 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23851 
23852 		/* Store the length in the IP header. */
23853 		ip_len = (uint16_t)(len + hdr_len);
23854 		ipha->ipha_length = htons(ip_len);
23855 
23856 		/*
23857 		 * Set the IP header checksum.	Note that mp is just
23858 		 * the header, so this is easy to pass to ip_csum.
23859 		 */
23860 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23861 
23862 		/* Attach a transmit header, if any, and ship it. */
23863 		if (pkt_type == OB_PKT) {
23864 			UPDATE_OB_PKT_COUNT(ire);
23865 		} else {
23866 			UPDATE_IB_PKT_COUNT(ire);
23867 		}
23868 
23869 		if (ire->ire_flags & RTF_MULTIRT) {
23870 			irb = ire->ire_bucket;
23871 			ASSERT(irb != NULL);
23872 
23873 			multirt_send = B_TRUE;
23874 
23875 			/*
23876 			 * Save the original ire; we will need to restore it
23877 			 * for the tailing frags.
23878 			 */
23879 			save_ire = ire;
23880 			IRE_REFHOLD(save_ire);
23881 		}
23882 		/*
23883 		 * Emission loop for this fragment, similar
23884 		 * to what is done for the first fragment.
23885 		 */
23886 		do {
23887 			if (multirt_send) {
23888 				/*
23889 				 * We are in a multiple send case, need to get
23890 				 * the next ire and make a copy of the packet.
23891 				 */
23892 				ASSERT(irb != NULL);
23893 				IRB_REFHOLD(irb);
23894 				for (ire1 = ire->ire_next;
23895 				    ire1 != NULL;
23896 				    ire1 = ire1->ire_next) {
23897 					if (!(ire1->ire_flags & RTF_MULTIRT))
23898 						continue;
23899 					if (ire1->ire_addr != ire->ire_addr)
23900 						continue;
23901 					if (ire1->ire_marks &
23902 					    (IRE_MARK_CONDEMNED|
23903 						IRE_MARK_HIDDEN))
23904 						continue;
23905 					/*
23906 					 * Ensure we do not exceed the MTU
23907 					 * of the next route.
23908 					 */
23909 					if (ire1->ire_max_frag < max_frag) {
23910 						ip_multirt_bad_mtu(ire1,
23911 						    max_frag);
23912 						continue;
23913 					}
23914 
23915 					/* Got one. */
23916 					IRE_REFHOLD(ire1);
23917 					break;
23918 				}
23919 				IRB_REFRELE(irb);
23920 
23921 				if (ire1 != NULL) {
23922 					next_mp = copyb(mp);
23923 					if ((next_mp == NULL) ||
23924 					    ((mp->b_cont != NULL) &&
23925 					    ((next_mp->b_cont =
23926 					    dupmsg(mp->b_cont)) == NULL))) {
23927 						freemsg(next_mp);
23928 						next_mp = NULL;
23929 						ire_refrele(ire1);
23930 						ire1 = NULL;
23931 					}
23932 				}
23933 
23934 				/* Last multiroute ire; don't loop anymore. */
23935 				if (ire1 == NULL) {
23936 					multirt_send = B_FALSE;
23937 				}
23938 			}
23939 
23940 			/* Update transmit header */
23941 			ll_hdr_len = 0;
23942 			LOCK_IRE_FP_MP(ire);
23943 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23944 			if (ll_hdr_mp != NULL) {
23945 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23946 				ll_hdr_len = MBLKL(ll_hdr_mp);
23947 			} else {
23948 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
23949 			}
23950 
23951 			if (!ll_hdr_mp) {
23952 				xmit_mp = mp;
23953 
23954 			/*
23955 			 * We have link-layer header that can fit in
23956 			 * our mblk.
23957 			 */
23958 			} else if (mp->b_datap->db_ref == 1 &&
23959 			    ll_hdr_len != 0 &&
23960 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23961 				/* M_DATA fastpath */
23962 				mp->b_rptr -= ll_hdr_len;
23963 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
23964 				    ll_hdr_len);
23965 				xmit_mp = mp;
23966 
23967 			/*
23968 			 * Case of res_mp OR the fastpath mp can't fit
23969 			 * in the mblk
23970 			 */
23971 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
23972 				xmit_mp->b_cont = mp;
23973 				if (DB_CRED(mp) != NULL)
23974 					mblk_setcred(xmit_mp, DB_CRED(mp));
23975 				/* Get priority marking, if any. */
23976 				if (DB_TYPE(xmit_mp) == M_DATA)
23977 					xmit_mp->b_band = mp->b_band;
23978 
23979 			/* Corner case if copyb failed */
23980 			} else {
23981 				/*
23982 				 * Exit both the replication and
23983 				 * fragmentation loops.
23984 				 */
23985 				UNLOCK_IRE_FP_MP(ire);
23986 				goto drop_pkt;
23987 			}
23988 			UNLOCK_IRE_FP_MP(ire);
23989 			BUMP_MIB(&ip_mib, ipFragCreates);
23990 
23991 			mp1 = mp;
23992 			out_ill = (ill_t *)q->q_ptr;
23993 
23994 			DTRACE_PROBE4(ip4__physical__out__start,
23995 			    ill_t *, NULL, ill_t *, out_ill,
23996 			    ipha_t *, ipha, mblk_t *, xmit_mp);
23997 
23998 			FW_HOOKS(ip4_physical_out_event,
23999 			    ipv4firewall_physical_out,
24000 			    NULL, out_ill, ipha, xmit_mp, mp);
24001 
24002 			DTRACE_PROBE1(ip4__physical__out__end,
24003 			    mblk_t *, xmit_mp);
24004 
24005 			if (mp != mp1 && hdr_mp == mp1)
24006 				hdr_mp = mp;
24007 			if (mp != mp1 && mp_orig == mp1)
24008 				mp_orig = mp;
24009 
24010 			if (xmit_mp != NULL) {
24011 				putnext(q, xmit_mp);
24012 
24013 				if (pkt_type != OB_PKT) {
24014 					/*
24015 					 * Update the packet count of trailing
24016 					 * RTF_MULTIRT ires.
24017 					 */
24018 					UPDATE_OB_PKT_COUNT(ire);
24019 				}
24020 			}
24021 
24022 			/* All done if we just consumed the hdr_mp. */
24023 			if (mp == hdr_mp) {
24024 				last_frag = B_TRUE;
24025 			}
24026 
24027 			if (multirt_send) {
24028 				/*
24029 				 * We are in a multiple send case; look for
24030 				 * the next ire and re-enter the loop.
24031 				 */
24032 				ASSERT(ire1);
24033 				ASSERT(next_mp);
24034 				/* REFRELE the current ire before looping */
24035 				ire_refrele(ire);
24036 				ire = ire1;
24037 				ire1 = NULL;
24038 				q = ire->ire_stq;
24039 				mp = next_mp;
24040 				next_mp = NULL;
24041 			}
24042 		} while (multirt_send);
24043 		/*
24044 		 * Restore the original ire; we need it for the
24045 		 * trailing frags
24046 		 */
24047 		if (save_ire != NULL) {
24048 			ASSERT(ire1 == NULL);
24049 			/* REFRELE the last iterated ire */
24050 			ire_refrele(ire);
24051 			/* save_ire has been REFHOLDed */
24052 			ire = save_ire;
24053 			q = ire->ire_stq;
24054 			save_ire = NULL;
24055 		}
24056 
24057 		if (last_frag) {
24058 			BUMP_MIB(&ip_mib, ipFragOKs);
24059 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24060 			    "ip_wput_frag_end:(%S)",
24061 			    "consumed hdr_mp");
24062 
24063 			if (first_ire != NULL)
24064 				ire_refrele(first_ire);
24065 			return;
24066 		}
24067 		/* Otherwise, advance and loop. */
24068 		offset += len;
24069 	}
24070 
24071 drop_pkt:
24072 	/* Clean up following allocation failure. */
24073 	BUMP_MIB(&ip_mib, ipOutDiscards);
24074 	freemsg(mp);
24075 	if (mp != hdr_mp)
24076 		freeb(hdr_mp);
24077 	if (mp != mp_orig)
24078 		freemsg(mp_orig);
24079 
24080 	if (save_ire != NULL)
24081 		IRE_REFRELE(save_ire);
24082 	if (first_ire != NULL)
24083 		ire_refrele(first_ire);
24084 
24085 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24086 	    "ip_wput_frag_end:(%S)",
24087 	    "end--alloc failure");
24088 }
24089 
24090 /*
24091  * Copy the header plus those options which have the copy bit set
24092  */
24093 static mblk_t *
24094 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
24095 {
24096 	mblk_t	*mp;
24097 	uchar_t	*up;
24098 
24099 	/*
24100 	 * Quick check if we need to look for options without the copy bit
24101 	 * set
24102 	 */
24103 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
24104 	if (!mp)
24105 		return (mp);
24106 	mp->b_rptr += ip_wroff_extra;
24107 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24108 		bcopy(rptr, mp->b_rptr, hdr_len);
24109 		mp->b_wptr += hdr_len + ip_wroff_extra;
24110 		return (mp);
24111 	}
24112 	up  = mp->b_rptr;
24113 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24114 	up += IP_SIMPLE_HDR_LENGTH;
24115 	rptr += IP_SIMPLE_HDR_LENGTH;
24116 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24117 	while (hdr_len > 0) {
24118 		uint32_t optval;
24119 		uint32_t optlen;
24120 
24121 		optval = *rptr;
24122 		if (optval == IPOPT_EOL)
24123 			break;
24124 		if (optval == IPOPT_NOP)
24125 			optlen = 1;
24126 		else
24127 			optlen = rptr[1];
24128 		if (optval & IPOPT_COPY) {
24129 			bcopy(rptr, up, optlen);
24130 			up += optlen;
24131 		}
24132 		rptr += optlen;
24133 		hdr_len -= optlen;
24134 	}
24135 	/*
24136 	 * Make sure that we drop an even number of words by filling
24137 	 * with EOL to the next word boundary.
24138 	 */
24139 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24140 	    hdr_len & 0x3; hdr_len++)
24141 		*up++ = IPOPT_EOL;
24142 	mp->b_wptr = up;
24143 	/* Update header length */
24144 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24145 	return (mp);
24146 }
24147 
24148 /*
24149  * Delivery to local recipients including fanout to multiple recipients.
24150  * Does not do checksumming of UDP/TCP.
24151  * Note: q should be the read side queue for either the ill or conn.
24152  * Note: rq should be the read side q for the lower (ill) stream.
24153  * We don't send packets to IPPF processing, thus the last argument
24154  * to all the fanout calls are B_FALSE.
24155  */
24156 void
24157 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24158     int fanout_flags, zoneid_t zoneid)
24159 {
24160 	uint32_t	protocol;
24161 	mblk_t		*first_mp;
24162 	boolean_t	mctl_present;
24163 	int		ire_type;
24164 #define	rptr	((uchar_t *)ipha)
24165 
24166 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24167 	    "ip_wput_local_start: q %p", q);
24168 
24169 	if (ire != NULL) {
24170 		ire_type = ire->ire_type;
24171 	} else {
24172 		/*
24173 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24174 		 * packet is not multicast, we can't tell the ire type.
24175 		 */
24176 		ASSERT(CLASSD(ipha->ipha_dst));
24177 		ire_type = IRE_BROADCAST;
24178 	}
24179 
24180 	first_mp = mp;
24181 	if (first_mp->b_datap->db_type == M_CTL) {
24182 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24183 		if (!io->ipsec_out_secure) {
24184 			/*
24185 			 * This ipsec_out_t was allocated in ip_wput
24186 			 * for multicast packets to store the ill_index.
24187 			 * As this is being delivered locally, we don't
24188 			 * need this anymore.
24189 			 */
24190 			mp = first_mp->b_cont;
24191 			freeb(first_mp);
24192 			first_mp = mp;
24193 			mctl_present = B_FALSE;
24194 		} else {
24195 			mctl_present = B_TRUE;
24196 			mp = first_mp->b_cont;
24197 			ASSERT(mp != NULL);
24198 			ipsec_out_to_in(first_mp);
24199 		}
24200 	} else {
24201 		mctl_present = B_FALSE;
24202 	}
24203 
24204 	DTRACE_PROBE4(ip4__loopback__in__start,
24205 	    ill_t *, ill, ill_t *, NULL,
24206 	    ipha_t *, ipha, mblk_t *, first_mp);
24207 
24208 	FW_HOOKS(ip4_loopback_in_event, ipv4firewall_loopback_in,
24209 	    ill, NULL, ipha, first_mp, mp);
24210 
24211 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24212 
24213 	if (first_mp == NULL)
24214 		return;
24215 
24216 	loopback_packets++;
24217 
24218 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24219 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24220 	if (!IS_SIMPLE_IPH(ipha)) {
24221 		ip_wput_local_options(ipha);
24222 	}
24223 
24224 	protocol = ipha->ipha_protocol;
24225 	switch (protocol) {
24226 	case IPPROTO_ICMP: {
24227 		ire_t		*ire_zone;
24228 		ilm_t		*ilm;
24229 		mblk_t		*mp1;
24230 		zoneid_t	last_zoneid;
24231 
24232 		if (CLASSD(ipha->ipha_dst) &&
24233 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
24234 			ASSERT(ire_type == IRE_BROADCAST);
24235 			/*
24236 			 * In the multicast case, applications may have joined
24237 			 * the group from different zones, so we need to deliver
24238 			 * the packet to each of them. Loop through the
24239 			 * multicast memberships structures (ilm) on the receive
24240 			 * ill and send a copy of the packet up each matching
24241 			 * one. However, we don't do this for multicasts sent on
24242 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24243 			 * they must stay in the sender's zone.
24244 			 *
24245 			 * ilm_add_v6() ensures that ilms in the same zone are
24246 			 * contiguous in the ill_ilm list. We use this property
24247 			 * to avoid sending duplicates needed when two
24248 			 * applications in the same zone join the same group on
24249 			 * different logical interfaces: we ignore the ilm if
24250 			 * it's zoneid is the same as the last matching one.
24251 			 * In addition, the sending of the packet for
24252 			 * ire_zoneid is delayed until all of the other ilms
24253 			 * have been exhausted.
24254 			 */
24255 			last_zoneid = -1;
24256 			ILM_WALKER_HOLD(ill);
24257 			for (ilm = ill->ill_ilm; ilm != NULL;
24258 			    ilm = ilm->ilm_next) {
24259 				if ((ilm->ilm_flags & ILM_DELETED) ||
24260 				    ipha->ipha_dst != ilm->ilm_addr ||
24261 				    ilm->ilm_zoneid == last_zoneid ||
24262 				    ilm->ilm_zoneid == zoneid ||
24263 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24264 					continue;
24265 				mp1 = ip_copymsg(first_mp);
24266 				if (mp1 == NULL)
24267 					continue;
24268 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24269 				    mctl_present, B_FALSE, ill,
24270 				    ilm->ilm_zoneid);
24271 				last_zoneid = ilm->ilm_zoneid;
24272 			}
24273 			ILM_WALKER_RELE(ill);
24274 			/*
24275 			 * Loopback case: the sending endpoint has
24276 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24277 			 * dispatch the multicast packet to the sending zone.
24278 			 */
24279 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24280 				freemsg(first_mp);
24281 				return;
24282 			}
24283 		} else if (ire_type == IRE_BROADCAST) {
24284 			/*
24285 			 * In the broadcast case, there may be many zones
24286 			 * which need a copy of the packet delivered to them.
24287 			 * There is one IRE_BROADCAST per broadcast address
24288 			 * and per zone; we walk those using a helper function.
24289 			 * In addition, the sending of the packet for zoneid is
24290 			 * delayed until all of the other ires have been
24291 			 * processed.
24292 			 */
24293 			IRB_REFHOLD(ire->ire_bucket);
24294 			ire_zone = NULL;
24295 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24296 			    ire)) != NULL) {
24297 				mp1 = ip_copymsg(first_mp);
24298 				if (mp1 == NULL)
24299 					continue;
24300 
24301 				UPDATE_IB_PKT_COUNT(ire_zone);
24302 				ire_zone->ire_last_used_time = lbolt;
24303 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24304 				    mctl_present, B_FALSE, ill,
24305 				    ire_zone->ire_zoneid);
24306 			}
24307 			IRB_REFRELE(ire->ire_bucket);
24308 		}
24309 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
24310 		    0, mctl_present, B_FALSE, ill, zoneid);
24311 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24312 		    "ip_wput_local_end: q %p (%S)",
24313 		    q, "icmp");
24314 		return;
24315 	}
24316 	case IPPROTO_IGMP:
24317 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
24318 			/* Bad packet - discarded by igmp_input */
24319 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24320 			    "ip_wput_local_end: q %p (%S)",
24321 			    q, "igmp_input--bad packet");
24322 			if (mctl_present)
24323 				freeb(first_mp);
24324 			return;
24325 		}
24326 		/*
24327 		 * igmp_input() may have returned the pulled up message.
24328 		 * So first_mp and ipha need to be reinitialized.
24329 		 */
24330 		ipha = (ipha_t *)mp->b_rptr;
24331 		if (mctl_present)
24332 			first_mp->b_cont = mp;
24333 		else
24334 			first_mp = mp;
24335 		/* deliver to local raw users */
24336 		break;
24337 	case IPPROTO_ENCAP:
24338 		/*
24339 		 * This case is covered by either ip_fanout_proto, or by
24340 		 * the above security processing for self-tunneled packets.
24341 		 */
24342 		break;
24343 	case IPPROTO_UDP: {
24344 		uint16_t	*up;
24345 		uint32_t	ports;
24346 
24347 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
24348 		    UDP_PORTS_OFFSET);
24349 		/* Force a 'valid' checksum. */
24350 		up[3] = 0;
24351 
24352 		ports = *(uint32_t *)up;
24353 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24354 		    (ire_type == IRE_BROADCAST),
24355 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24356 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
24357 		    ill, zoneid);
24358 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24359 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24360 		return;
24361 	}
24362 	case IPPROTO_TCP: {
24363 
24364 		/*
24365 		 * For TCP, discard broadcast packets.
24366 		 */
24367 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24368 			freemsg(first_mp);
24369 			BUMP_MIB(&ip_mib, ipInDiscards);
24370 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24371 			return;
24372 		}
24373 
24374 		if (mp->b_datap->db_type == M_DATA) {
24375 			/*
24376 			 * M_DATA mblk, so init mblk (chain) for no struio().
24377 			 */
24378 			mblk_t	*mp1 = mp;
24379 
24380 			do
24381 				mp1->b_datap->db_struioflag = 0;
24382 			while ((mp1 = mp1->b_cont) != NULL);
24383 		}
24384 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24385 		    <= mp->b_wptr);
24386 		ip_fanout_tcp(q, first_mp, ill, ipha,
24387 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24388 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
24389 		    mctl_present, B_FALSE, zoneid);
24390 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24391 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24392 		return;
24393 	}
24394 	case IPPROTO_SCTP:
24395 	{
24396 		uint32_t	ports;
24397 
24398 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24399 		ip_fanout_sctp(first_mp, ill, ipha, ports,
24400 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24401 		    IP_FF_IP6INFO,
24402 		    mctl_present, B_FALSE, 0, zoneid);
24403 		return;
24404 	}
24405 
24406 	default:
24407 		break;
24408 	}
24409 	/*
24410 	 * Find a client for some other protocol.  We give
24411 	 * copies to multiple clients, if more than one is
24412 	 * bound.
24413 	 */
24414 	ip_fanout_proto(q, first_mp, ill, ipha,
24415 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
24416 	    mctl_present, B_FALSE, ill, zoneid);
24417 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24418 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
24419 #undef	rptr
24420 }
24421 
24422 /*
24423  * Update any source route, record route, or timestamp options.
24424  * Check that we are at end of strict source route.
24425  * The options have been sanity checked by ip_wput_options().
24426  */
24427 static void
24428 ip_wput_local_options(ipha_t *ipha)
24429 {
24430 	ipoptp_t	opts;
24431 	uchar_t		*opt;
24432 	uint8_t		optval;
24433 	uint8_t		optlen;
24434 	ipaddr_t	dst;
24435 	uint32_t	ts;
24436 	ire_t		*ire;
24437 	timestruc_t	now;
24438 
24439 	ip2dbg(("ip_wput_local_options\n"));
24440 	for (optval = ipoptp_first(&opts, ipha);
24441 	    optval != IPOPT_EOL;
24442 	    optval = ipoptp_next(&opts)) {
24443 		opt = opts.ipoptp_cur;
24444 		optlen = opts.ipoptp_len;
24445 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
24446 		switch (optval) {
24447 			uint32_t off;
24448 		case IPOPT_SSRR:
24449 		case IPOPT_LSRR:
24450 			off = opt[IPOPT_OFFSET];
24451 			off--;
24452 			if (optlen < IP_ADDR_LEN ||
24453 			    off > optlen - IP_ADDR_LEN) {
24454 				/* End of source route */
24455 				break;
24456 			}
24457 			/*
24458 			 * This will only happen if two consecutive entries
24459 			 * in the source route contains our address or if
24460 			 * it is a packet with a loose source route which
24461 			 * reaches us before consuming the whole source route
24462 			 */
24463 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
24464 			if (optval == IPOPT_SSRR) {
24465 				return;
24466 			}
24467 			/*
24468 			 * Hack: instead of dropping the packet truncate the
24469 			 * source route to what has been used by filling the
24470 			 * rest with IPOPT_NOP.
24471 			 */
24472 			opt[IPOPT_OLEN] = (uint8_t)off;
24473 			while (off < optlen) {
24474 				opt[off++] = IPOPT_NOP;
24475 			}
24476 			break;
24477 		case IPOPT_RR:
24478 			off = opt[IPOPT_OFFSET];
24479 			off--;
24480 			if (optlen < IP_ADDR_LEN ||
24481 			    off > optlen - IP_ADDR_LEN) {
24482 				/* No more room - ignore */
24483 				ip1dbg((
24484 				    "ip_wput_forward_options: end of RR\n"));
24485 				break;
24486 			}
24487 			dst = htonl(INADDR_LOOPBACK);
24488 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24489 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24490 			break;
24491 		case IPOPT_TS:
24492 			/* Insert timestamp if there is romm */
24493 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24494 			case IPOPT_TS_TSONLY:
24495 				off = IPOPT_TS_TIMELEN;
24496 				break;
24497 			case IPOPT_TS_PRESPEC:
24498 			case IPOPT_TS_PRESPEC_RFC791:
24499 				/* Verify that the address matched */
24500 				off = opt[IPOPT_OFFSET] - 1;
24501 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
24502 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
24503 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
24504 				if (ire == NULL) {
24505 					/* Not for us */
24506 					break;
24507 				}
24508 				ire_refrele(ire);
24509 				/* FALLTHRU */
24510 			case IPOPT_TS_TSANDADDR:
24511 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24512 				break;
24513 			default:
24514 				/*
24515 				 * ip_*put_options should have already
24516 				 * dropped this packet.
24517 				 */
24518 				cmn_err(CE_PANIC, "ip_wput_local_options: "
24519 				    "unknown IT - bug in ip_wput_options?\n");
24520 				return;	/* Keep "lint" happy */
24521 			}
24522 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
24523 				/* Increase overflow counter */
24524 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
24525 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
24526 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
24527 				    (off << 4);
24528 				break;
24529 			}
24530 			off = opt[IPOPT_OFFSET] - 1;
24531 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24532 			case IPOPT_TS_PRESPEC:
24533 			case IPOPT_TS_PRESPEC_RFC791:
24534 			case IPOPT_TS_TSANDADDR:
24535 				dst = htonl(INADDR_LOOPBACK);
24536 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24537 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24538 				/* FALLTHRU */
24539 			case IPOPT_TS_TSONLY:
24540 				off = opt[IPOPT_OFFSET] - 1;
24541 				/* Compute # of milliseconds since midnight */
24542 				gethrestime(&now);
24543 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
24544 				    now.tv_nsec / (NANOSEC / MILLISEC);
24545 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
24546 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
24547 				break;
24548 			}
24549 			break;
24550 		}
24551 	}
24552 }
24553 
24554 /*
24555  * Send out a multicast packet on interface ipif.
24556  * The sender does not have an conn.
24557  * Caller verifies that this isn't a PHYI_LOOPBACK.
24558  */
24559 void
24560 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
24561 {
24562 	ipha_t	*ipha;
24563 	ire_t	*ire;
24564 	ipaddr_t	dst;
24565 	mblk_t		*first_mp;
24566 
24567 	/* igmp_sendpkt always allocates a ipsec_out_t */
24568 	ASSERT(mp->b_datap->db_type == M_CTL);
24569 	ASSERT(!ipif->ipif_isv6);
24570 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
24571 
24572 	first_mp = mp;
24573 	mp = first_mp->b_cont;
24574 	ASSERT(mp->b_datap->db_type == M_DATA);
24575 	ipha = (ipha_t *)mp->b_rptr;
24576 
24577 	/*
24578 	 * Find an IRE which matches the destination and the outgoing
24579 	 * queue (i.e. the outgoing interface.)
24580 	 */
24581 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
24582 		dst = ipif->ipif_pp_dst_addr;
24583 	else
24584 		dst = ipha->ipha_dst;
24585 	/*
24586 	 * The source address has already been initialized by the
24587 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
24588 	 * be sufficient rather than MATCH_IRE_IPIF.
24589 	 *
24590 	 * This function is used for sending IGMP packets. We need
24591 	 * to make sure that we send the packet out of the interface
24592 	 * (ipif->ipif_ill) where we joined the group. This is to
24593 	 * prevent from switches doing IGMP snooping to send us multicast
24594 	 * packets for a given group on the interface we have joined.
24595 	 * If we can't find an ire, igmp_sendpkt has already initialized
24596 	 * ipsec_out_attach_if so that this will not be load spread in
24597 	 * ip_newroute_ipif.
24598 	 */
24599 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
24600 	    MATCH_IRE_ILL);
24601 	if (!ire) {
24602 		/*
24603 		 * Mark this packet to make it be delivered to
24604 		 * ip_wput_ire after the new ire has been
24605 		 * created.
24606 		 */
24607 		mp->b_prev = NULL;
24608 		mp->b_next = NULL;
24609 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
24610 		    zoneid);
24611 		return;
24612 	}
24613 
24614 	/*
24615 	 * Honor the RTF_SETSRC flag; this is the only case
24616 	 * where we force this addr whatever the current src addr is,
24617 	 * because this address is set by igmp_sendpkt(), and
24618 	 * cannot be specified by any user.
24619 	 */
24620 	if (ire->ire_flags & RTF_SETSRC) {
24621 		ipha->ipha_src = ire->ire_src_addr;
24622 	}
24623 
24624 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
24625 }
24626 
24627 /*
24628  * NOTE : This function does not ire_refrele the ire argument passed in.
24629  *
24630  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
24631  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
24632  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
24633  * the ire_lock to access the nce_fp_mp in this case.
24634  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
24635  * prepending a fastpath message IPQoS processing must precede it, we also set
24636  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
24637  * (IPQoS might have set the b_band for CoS marking).
24638  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
24639  * must follow it so that IPQoS can mark the dl_priority field for CoS
24640  * marking, if needed.
24641  */
24642 static mblk_t *
24643 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
24644 {
24645 	uint_t	hlen;
24646 	ipha_t *ipha;
24647 	mblk_t *mp1;
24648 	boolean_t qos_done = B_FALSE;
24649 	uchar_t	*ll_hdr;
24650 
24651 #define	rptr	((uchar_t *)ipha)
24652 
24653 	ipha = (ipha_t *)mp->b_rptr;
24654 	hlen = 0;
24655 	LOCK_IRE_FP_MP(ire);
24656 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
24657 		ASSERT(DB_TYPE(mp1) == M_DATA);
24658 		/* Initiate IPPF processing */
24659 		if ((proc != 0) && IPP_ENABLED(proc)) {
24660 			UNLOCK_IRE_FP_MP(ire);
24661 			ip_process(proc, &mp, ill_index);
24662 			if (mp == NULL)
24663 				return (NULL);
24664 
24665 			ipha = (ipha_t *)mp->b_rptr;
24666 			LOCK_IRE_FP_MP(ire);
24667 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
24668 				qos_done = B_TRUE;
24669 				goto no_fp_mp;
24670 			}
24671 			ASSERT(DB_TYPE(mp1) == M_DATA);
24672 		}
24673 		hlen = MBLKL(mp1);
24674 		/*
24675 		 * Check if we have enough room to prepend fastpath
24676 		 * header
24677 		 */
24678 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
24679 			ll_hdr = rptr - hlen;
24680 			bcopy(mp1->b_rptr, ll_hdr, hlen);
24681 			/*
24682 			 * Set the b_rptr to the start of the link layer
24683 			 * header
24684 			 */
24685 			mp->b_rptr = ll_hdr;
24686 			mp1 = mp;
24687 		} else {
24688 			mp1 = copyb(mp1);
24689 			if (mp1 == NULL)
24690 				goto unlock_err;
24691 			mp1->b_band = mp->b_band;
24692 			mp1->b_cont = mp;
24693 			/*
24694 			 * certain system generated traffic may not
24695 			 * have cred/label in ip header block. This
24696 			 * is true even for a labeled system. But for
24697 			 * labeled traffic, inherit the label in the
24698 			 * new header.
24699 			 */
24700 			if (DB_CRED(mp) != NULL)
24701 				mblk_setcred(mp1, DB_CRED(mp));
24702 			/*
24703 			 * XXX disable ICK_VALID and compute checksum
24704 			 * here; can happen if nce_fp_mp changes and
24705 			 * it can't be copied now due to insufficient
24706 			 * space. (unlikely, fp mp can change, but it
24707 			 * does not increase in length)
24708 			 */
24709 		}
24710 		UNLOCK_IRE_FP_MP(ire);
24711 	} else {
24712 no_fp_mp:
24713 		mp1 = copyb(ire->ire_nce->nce_res_mp);
24714 		if (mp1 == NULL) {
24715 unlock_err:
24716 			UNLOCK_IRE_FP_MP(ire);
24717 			freemsg(mp);
24718 			return (NULL);
24719 		}
24720 		UNLOCK_IRE_FP_MP(ire);
24721 		mp1->b_cont = mp;
24722 		/*
24723 		 * certain system generated traffic may not
24724 		 * have cred/label in ip header block. This
24725 		 * is true even for a labeled system. But for
24726 		 * labeled traffic, inherit the label in the
24727 		 * new header.
24728 		 */
24729 		if (DB_CRED(mp) != NULL)
24730 			mblk_setcred(mp1, DB_CRED(mp));
24731 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
24732 			ip_process(proc, &mp1, ill_index);
24733 			if (mp1 == NULL)
24734 				return (NULL);
24735 		}
24736 	}
24737 	return (mp1);
24738 #undef rptr
24739 }
24740 
24741 /*
24742  * Finish the outbound IPsec processing for an IPv6 packet. This function
24743  * is called from ipsec_out_process() if the IPsec packet was processed
24744  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24745  * asynchronously.
24746  */
24747 void
24748 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
24749     ire_t *ire_arg)
24750 {
24751 	in6_addr_t *v6dstp;
24752 	ire_t *ire;
24753 	mblk_t *mp;
24754 	ip6_t *ip6h1;
24755 	uint_t	ill_index;
24756 	ipsec_out_t *io;
24757 	boolean_t attach_if, hwaccel;
24758 	uint32_t flags = IP6_NO_IPPOLICY;
24759 	int match_flags;
24760 	zoneid_t zoneid;
24761 	boolean_t ill_need_rele = B_FALSE;
24762 	boolean_t ire_need_rele = B_FALSE;
24763 
24764 	mp = ipsec_mp->b_cont;
24765 	ip6h1 = (ip6_t *)mp->b_rptr;
24766 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24767 	ill_index = io->ipsec_out_ill_index;
24768 	if (io->ipsec_out_reachable) {
24769 		flags |= IPV6_REACHABILITY_CONFIRMATION;
24770 	}
24771 	attach_if = io->ipsec_out_attach_if;
24772 	hwaccel = io->ipsec_out_accelerated;
24773 	zoneid = io->ipsec_out_zoneid;
24774 	ASSERT(zoneid != ALL_ZONES);
24775 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24776 	/* Multicast addresses should have non-zero ill_index. */
24777 	v6dstp = &ip6h->ip6_dst;
24778 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
24779 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
24780 	ASSERT(!attach_if || ill_index != 0);
24781 	if (ill_index != 0) {
24782 		if (ill == NULL) {
24783 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
24784 			    B_TRUE);
24785 
24786 			/* Failure case frees things for us. */
24787 			if (ill == NULL)
24788 				return;
24789 
24790 			ill_need_rele = B_TRUE;
24791 		}
24792 		/*
24793 		 * If this packet needs to go out on a particular interface
24794 		 * honor it.
24795 		 */
24796 		if (attach_if) {
24797 			match_flags = MATCH_IRE_ILL;
24798 
24799 			/*
24800 			 * Check if we need an ire that will not be
24801 			 * looked up by anybody else i.e. HIDDEN.
24802 			 */
24803 			if (ill_is_probeonly(ill)) {
24804 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24805 			}
24806 		}
24807 	}
24808 	ASSERT(mp != NULL);
24809 
24810 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
24811 		boolean_t unspec_src;
24812 		ipif_t	*ipif;
24813 
24814 		/*
24815 		 * Use the ill_index to get the right ill.
24816 		 */
24817 		unspec_src = io->ipsec_out_unspec_src;
24818 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24819 		if (ipif == NULL) {
24820 			if (ill_need_rele)
24821 				ill_refrele(ill);
24822 			freemsg(ipsec_mp);
24823 			return;
24824 		}
24825 
24826 		if (ire_arg != NULL) {
24827 			ire = ire_arg;
24828 		} else {
24829 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24830 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24831 			ire_need_rele = B_TRUE;
24832 		}
24833 		if (ire != NULL) {
24834 			ipif_refrele(ipif);
24835 			/*
24836 			 * XXX Do the multicast forwarding now, as the IPSEC
24837 			 * processing has been done.
24838 			 */
24839 			goto send;
24840 		}
24841 
24842 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
24843 		mp->b_prev = NULL;
24844 		mp->b_next = NULL;
24845 
24846 		/*
24847 		 * If the IPsec packet was processed asynchronously,
24848 		 * drop it now.
24849 		 */
24850 		if (q == NULL) {
24851 			if (ill_need_rele)
24852 				ill_refrele(ill);
24853 			freemsg(ipsec_mp);
24854 			return;
24855 		}
24856 
24857 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
24858 		    unspec_src, zoneid);
24859 		ipif_refrele(ipif);
24860 	} else {
24861 		if (attach_if) {
24862 			ipif_t	*ipif;
24863 
24864 			ipif = ipif_get_next_ipif(NULL, ill);
24865 			if (ipif == NULL) {
24866 				if (ill_need_rele)
24867 					ill_refrele(ill);
24868 				freemsg(ipsec_mp);
24869 				return;
24870 			}
24871 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24872 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24873 			ire_need_rele = B_TRUE;
24874 			ipif_refrele(ipif);
24875 		} else {
24876 			if (ire_arg != NULL) {
24877 				ire = ire_arg;
24878 			} else {
24879 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
24880 				ire_need_rele = B_TRUE;
24881 			}
24882 		}
24883 		if (ire != NULL)
24884 			goto send;
24885 		/*
24886 		 * ire disappeared underneath.
24887 		 *
24888 		 * What we need to do here is the ip_newroute
24889 		 * logic to get the ire without doing the IPSEC
24890 		 * processing. Follow the same old path. But this
24891 		 * time, ip_wput or ire_add_then_send will call us
24892 		 * directly as all the IPSEC operations are done.
24893 		 */
24894 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
24895 		mp->b_prev = NULL;
24896 		mp->b_next = NULL;
24897 
24898 		/*
24899 		 * If the IPsec packet was processed asynchronously,
24900 		 * drop it now.
24901 		 */
24902 		if (q == NULL) {
24903 			if (ill_need_rele)
24904 				ill_refrele(ill);
24905 			freemsg(ipsec_mp);
24906 			return;
24907 		}
24908 
24909 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
24910 		    zoneid);
24911 	}
24912 	if (ill != NULL && ill_need_rele)
24913 		ill_refrele(ill);
24914 	return;
24915 send:
24916 	if (ill != NULL && ill_need_rele)
24917 		ill_refrele(ill);
24918 
24919 	/* Local delivery */
24920 	if (ire->ire_stq == NULL) {
24921 		ill_t	*out_ill;
24922 		ASSERT(q != NULL);
24923 
24924 		/* PFHooks: LOOPBACK_OUT */
24925 		out_ill = ire->ire_ipif->ipif_ill;
24926 
24927 		DTRACE_PROBE4(ip6__loopback__out__start,
24928 		    ill_t *, NULL, ill_t *, out_ill,
24929 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
24930 
24931 		FW_HOOKS6(ip6_loopback_out_event, ipv6firewall_loopback_out,
24932 		    NULL, out_ill, ip6h1, ipsec_mp, mp);
24933 
24934 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
24935 
24936 		if (ipsec_mp != NULL)
24937 			ip_wput_local_v6(RD(q), out_ill,
24938 			    ip6h, ipsec_mp, ire, 0);
24939 		if (ire_need_rele)
24940 			ire_refrele(ire);
24941 		return;
24942 	}
24943 	/*
24944 	 * Everything is done. Send it out on the wire.
24945 	 * We force the insertion of a fragment header using the
24946 	 * IPH_FRAG_HDR flag in two cases:
24947 	 * - after reception of an ICMPv6 "packet too big" message
24948 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
24949 	 * - for multirouted IPv6 packets, so that the receiver can
24950 	 *   discard duplicates according to their fragment identifier
24951 	 */
24952 	/* XXX fix flow control problems. */
24953 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
24954 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
24955 		if (hwaccel) {
24956 			/*
24957 			 * hardware acceleration does not handle these
24958 			 * "slow path" cases.
24959 			 */
24960 			/* IPsec KSTATS: should bump bean counter here. */
24961 			if (ire_need_rele)
24962 				ire_refrele(ire);
24963 			freemsg(ipsec_mp);
24964 			return;
24965 		}
24966 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
24967 		    (mp->b_cont ? msgdsize(mp) :
24968 		    mp->b_wptr - (uchar_t *)ip6h)) {
24969 			/* IPsec KSTATS: should bump bean counter here. */
24970 			ip0dbg(("Packet length mismatch: %d, %ld\n",
24971 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
24972 			    msgdsize(mp)));
24973 			if (ire_need_rele)
24974 				ire_refrele(ire);
24975 			freemsg(ipsec_mp);
24976 			return;
24977 		}
24978 		ASSERT(mp->b_prev == NULL);
24979 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
24980 		    ntohs(ip6h->ip6_plen) +
24981 		    IPV6_HDR_LEN, ire->ire_max_frag));
24982 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
24983 		    ire->ire_max_frag);
24984 	} else {
24985 		UPDATE_OB_PKT_COUNT(ire);
24986 		ire->ire_last_used_time = lbolt;
24987 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
24988 	}
24989 	if (ire_need_rele)
24990 		ire_refrele(ire);
24991 	freeb(ipsec_mp);
24992 }
24993 
24994 void
24995 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
24996 {
24997 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
24998 	da_ipsec_t *hada;	/* data attributes */
24999 	ill_t *ill = (ill_t *)q->q_ptr;
25000 
25001 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25002 
25003 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25004 		/* IPsec KSTATS: Bump lose counter here! */
25005 		freemsg(mp);
25006 		return;
25007 	}
25008 
25009 	/*
25010 	 * It's an IPsec packet that must be
25011 	 * accelerated by the Provider, and the
25012 	 * outbound ill is IPsec acceleration capable.
25013 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25014 	 * to the ill.
25015 	 * IPsec KSTATS: should bump packet counter here.
25016 	 */
25017 
25018 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25019 	if (hada_mp == NULL) {
25020 		/* IPsec KSTATS: should bump packet counter here. */
25021 		freemsg(mp);
25022 		return;
25023 	}
25024 
25025 	hada_mp->b_datap->db_type = M_CTL;
25026 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25027 	hada_mp->b_cont = mp;
25028 
25029 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25030 	bzero(hada, sizeof (da_ipsec_t));
25031 	hada->da_type = IPHADA_M_CTL;
25032 
25033 	putnext(q, hada_mp);
25034 }
25035 
25036 /*
25037  * Finish the outbound IPsec processing. This function is called from
25038  * ipsec_out_process() if the IPsec packet was processed
25039  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25040  * asynchronously.
25041  */
25042 void
25043 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25044     ire_t *ire_arg)
25045 {
25046 	uint32_t v_hlen_tos_len;
25047 	ipaddr_t	dst;
25048 	ipif_t	*ipif = NULL;
25049 	ire_t *ire;
25050 	ire_t *ire1 = NULL;
25051 	mblk_t *next_mp = NULL;
25052 	uint32_t max_frag;
25053 	boolean_t multirt_send = B_FALSE;
25054 	mblk_t *mp;
25055 	mblk_t *mp1;
25056 	ipha_t *ipha1;
25057 	uint_t	ill_index;
25058 	ipsec_out_t *io;
25059 	boolean_t attach_if;
25060 	int match_flags, offset;
25061 	irb_t *irb = NULL;
25062 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25063 	zoneid_t zoneid;
25064 	uint32_t cksum;
25065 	uint16_t *up;
25066 	ipxmit_state_t	pktxmit_state;
25067 #ifdef	_BIG_ENDIAN
25068 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25069 #else
25070 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25071 #endif
25072 
25073 	mp = ipsec_mp->b_cont;
25074 	ipha1 = (ipha_t *)mp->b_rptr;
25075 	ASSERT(mp != NULL);
25076 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25077 	dst = ipha->ipha_dst;
25078 
25079 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25080 	ill_index = io->ipsec_out_ill_index;
25081 	attach_if = io->ipsec_out_attach_if;
25082 	zoneid = io->ipsec_out_zoneid;
25083 	ASSERT(zoneid != ALL_ZONES);
25084 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25085 	if (ill_index != 0) {
25086 		if (ill == NULL) {
25087 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25088 			    ill_index, B_FALSE);
25089 
25090 			/* Failure case frees things for us. */
25091 			if (ill == NULL)
25092 				return;
25093 
25094 			ill_need_rele = B_TRUE;
25095 		}
25096 		/*
25097 		 * If this packet needs to go out on a particular interface
25098 		 * honor it.
25099 		 */
25100 		if (attach_if) {
25101 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25102 
25103 			/*
25104 			 * Check if we need an ire that will not be
25105 			 * looked up by anybody else i.e. HIDDEN.
25106 			 */
25107 			if (ill_is_probeonly(ill)) {
25108 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25109 			}
25110 		}
25111 	}
25112 
25113 	if (CLASSD(dst)) {
25114 		boolean_t conn_dontroute;
25115 		/*
25116 		 * Use the ill_index to get the right ipif.
25117 		 */
25118 		conn_dontroute = io->ipsec_out_dontroute;
25119 		if (ill_index == 0)
25120 			ipif = ipif_lookup_group(dst, zoneid);
25121 		else
25122 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25123 		if (ipif == NULL) {
25124 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25125 			    " multicast\n"));
25126 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
25127 			freemsg(ipsec_mp);
25128 			goto done;
25129 		}
25130 		/*
25131 		 * ipha_src has already been intialized with the
25132 		 * value of the ipif in ip_wput. All we need now is
25133 		 * an ire to send this downstream.
25134 		 */
25135 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25136 		    MBLK_GETLABEL(mp), match_flags);
25137 		if (ire != NULL) {
25138 			ill_t *ill1;
25139 			/*
25140 			 * Do the multicast forwarding now, as the IPSEC
25141 			 * processing has been done.
25142 			 */
25143 			if (ip_g_mrouter && !conn_dontroute &&
25144 			    (ill1 = ire_to_ill(ire))) {
25145 				if (ip_mforward(ill1, ipha, mp)) {
25146 					freemsg(ipsec_mp);
25147 					ip1dbg(("ip_wput_ipsec_out: mforward "
25148 					    "failed\n"));
25149 					ire_refrele(ire);
25150 					goto done;
25151 				}
25152 			}
25153 			goto send;
25154 		}
25155 
25156 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25157 		mp->b_prev = NULL;
25158 		mp->b_next = NULL;
25159 
25160 		/*
25161 		 * If the IPsec packet was processed asynchronously,
25162 		 * drop it now.
25163 		 */
25164 		if (q == NULL) {
25165 			freemsg(ipsec_mp);
25166 			goto done;
25167 		}
25168 
25169 		/*
25170 		 * We may be using a wrong ipif to create the ire.
25171 		 * But it is okay as the source address is assigned
25172 		 * for the packet already. Next outbound packet would
25173 		 * create the IRE with the right IPIF in ip_wput.
25174 		 *
25175 		 * Also handle RTF_MULTIRT routes.
25176 		 */
25177 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25178 		    zoneid);
25179 	} else {
25180 		if (attach_if) {
25181 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25182 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25183 		} else {
25184 			if (ire_arg != NULL) {
25185 				ire = ire_arg;
25186 				ire_need_rele = B_FALSE;
25187 			} else {
25188 				ire = ire_cache_lookup(dst, zoneid,
25189 				    MBLK_GETLABEL(mp));
25190 			}
25191 		}
25192 		if (ire != NULL) {
25193 			goto send;
25194 		}
25195 
25196 		/*
25197 		 * ire disappeared underneath.
25198 		 *
25199 		 * What we need to do here is the ip_newroute
25200 		 * logic to get the ire without doing the IPSEC
25201 		 * processing. Follow the same old path. But this
25202 		 * time, ip_wput or ire_add_then_put will call us
25203 		 * directly as all the IPSEC operations are done.
25204 		 */
25205 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25206 		mp->b_prev = NULL;
25207 		mp->b_next = NULL;
25208 
25209 		/*
25210 		 * If the IPsec packet was processed asynchronously,
25211 		 * drop it now.
25212 		 */
25213 		if (q == NULL) {
25214 			freemsg(ipsec_mp);
25215 			goto done;
25216 		}
25217 
25218 		/*
25219 		 * Since we're going through ip_newroute() again, we
25220 		 * need to make sure we don't:
25221 		 *
25222 		 *	1.) Trigger the ASSERT() with the ipha_ident
25223 		 *	    overloading.
25224 		 *	2.) Redo transport-layer checksumming, since we've
25225 		 *	    already done all that to get this far.
25226 		 *
25227 		 * The easiest way not do either of the above is to set
25228 		 * the ipha_ident field to IP_HDR_INCLUDED.
25229 		 */
25230 		ipha->ipha_ident = IP_HDR_INCLUDED;
25231 		ip_newroute(q, ipsec_mp, dst, NULL,
25232 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid);
25233 	}
25234 	goto done;
25235 send:
25236 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
25237 		/*
25238 		 * ESP NAT-Traversal packet.
25239 		 *
25240 		 * Just do software checksum for now.
25241 		 */
25242 
25243 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
25244 		IP_STAT(ip_out_sw_cksum);
25245 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
25246 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
25247 #define	iphs	((uint16_t *)ipha)
25248 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
25249 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
25250 		    IP_SIMPLE_HDR_LENGTH);
25251 #undef iphs
25252 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
25253 			cksum = 0xFFFF;
25254 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
25255 			if (mp1->b_wptr - mp1->b_rptr >=
25256 			    offset + sizeof (uint16_t)) {
25257 				up = (uint16_t *)(mp1->b_rptr + offset);
25258 				*up = cksum;
25259 				break;	/* out of for loop */
25260 			} else {
25261 				offset -= (mp->b_wptr - mp->b_rptr);
25262 			}
25263 	} /* Otherwise, just keep the all-zero checksum. */
25264 
25265 	if (ire->ire_stq == NULL) {
25266 		ill_t	*out_ill;
25267 		/*
25268 		 * Loopbacks go through ip_wput_local except for one case.
25269 		 * We come here if we generate a icmp_frag_needed message
25270 		 * after IPSEC processing is over. When this function calls
25271 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25272 		 * icmp_frag_needed. The message generated comes back here
25273 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25274 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25275 		 * source address as it is usually set in ip_wput_ire. As
25276 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25277 		 * and we end up here. We can't enter ip_wput_ire once the
25278 		 * IPSEC processing is over and hence we need to do it here.
25279 		 */
25280 		ASSERT(q != NULL);
25281 		UPDATE_OB_PKT_COUNT(ire);
25282 		ire->ire_last_used_time = lbolt;
25283 		if (ipha->ipha_src == 0)
25284 			ipha->ipha_src = ire->ire_src_addr;
25285 
25286 		/* PFHooks: LOOPBACK_OUT */
25287 		out_ill = ire->ire_ipif->ipif_ill;
25288 
25289 		DTRACE_PROBE4(ip4__loopback__out__start,
25290 		    ill_t *, NULL, ill_t *, out_ill,
25291 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25292 
25293 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
25294 		    NULL, out_ill, ipha1, ipsec_mp, mp);
25295 
25296 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25297 
25298 		if (ipsec_mp != NULL)
25299 			ip_wput_local(RD(q), out_ill,
25300 			    ipha, ipsec_mp, ire, 0, zoneid);
25301 		if (ire_need_rele)
25302 			ire_refrele(ire);
25303 		goto done;
25304 	}
25305 
25306 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25307 		/*
25308 		 * We are through with IPSEC processing.
25309 		 * Fragment this and send it on the wire.
25310 		 */
25311 		if (io->ipsec_out_accelerated) {
25312 			/*
25313 			 * The packet has been accelerated but must
25314 			 * be fragmented. This should not happen
25315 			 * since AH and ESP must not accelerate
25316 			 * packets that need fragmentation, however
25317 			 * the configuration could have changed
25318 			 * since the AH or ESP processing.
25319 			 * Drop packet.
25320 			 * IPsec KSTATS: bump bean counter here.
25321 			 */
25322 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25323 			    "fragmented accelerated packet!\n"));
25324 			freemsg(ipsec_mp);
25325 		} else {
25326 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid);
25327 		}
25328 		if (ire_need_rele)
25329 			ire_refrele(ire);
25330 		goto done;
25331 	}
25332 
25333 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25334 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25335 	    (void *)ire->ire_ipif, (void *)ipif));
25336 
25337 	/*
25338 	 * Multiroute the secured packet, unless IPsec really
25339 	 * requires the packet to go out only through a particular
25340 	 * interface.
25341 	 */
25342 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
25343 		ire_t *first_ire;
25344 		irb = ire->ire_bucket;
25345 		ASSERT(irb != NULL);
25346 		/*
25347 		 * This ire has been looked up as the one that
25348 		 * goes through the given ipif;
25349 		 * make sure we do not omit any other multiroute ire
25350 		 * that may be present in the bucket before this one.
25351 		 */
25352 		IRB_REFHOLD(irb);
25353 		for (first_ire = irb->irb_ire;
25354 		    first_ire != NULL;
25355 		    first_ire = first_ire->ire_next) {
25356 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25357 			    (first_ire->ire_addr == ire->ire_addr) &&
25358 			    !(first_ire->ire_marks &
25359 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
25360 				break;
25361 		}
25362 
25363 		if ((first_ire != NULL) && (first_ire != ire)) {
25364 			/*
25365 			 * Don't change the ire if the packet must
25366 			 * be fragmented if sent via this new one.
25367 			 */
25368 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25369 				IRE_REFHOLD(first_ire);
25370 				if (ire_need_rele)
25371 					ire_refrele(ire);
25372 				else
25373 					ire_need_rele = B_TRUE;
25374 				ire = first_ire;
25375 			}
25376 		}
25377 		IRB_REFRELE(irb);
25378 
25379 		multirt_send = B_TRUE;
25380 		max_frag = ire->ire_max_frag;
25381 	} else {
25382 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
25383 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25384 			    "flag, attach_if %d\n", attach_if));
25385 		}
25386 	}
25387 
25388 	/*
25389 	 * In most cases, the emission loop below is entered only once.
25390 	 * Only in the case where the ire holds the RTF_MULTIRT
25391 	 * flag, we loop to process all RTF_MULTIRT ires in the
25392 	 * bucket, and send the packet through all crossed
25393 	 * RTF_MULTIRT routes.
25394 	 */
25395 	do {
25396 		if (multirt_send) {
25397 			/*
25398 			 * ire1 holds here the next ire to process in the
25399 			 * bucket. If multirouting is expected,
25400 			 * any non-RTF_MULTIRT ire that has the
25401 			 * right destination address is ignored.
25402 			 */
25403 			ASSERT(irb != NULL);
25404 			IRB_REFHOLD(irb);
25405 			for (ire1 = ire->ire_next;
25406 			    ire1 != NULL;
25407 			    ire1 = ire1->ire_next) {
25408 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
25409 					continue;
25410 				if (ire1->ire_addr != ire->ire_addr)
25411 					continue;
25412 				if (ire1->ire_marks &
25413 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
25414 					continue;
25415 				/* No loopback here */
25416 				if (ire1->ire_stq == NULL)
25417 					continue;
25418 				/*
25419 				 * Ensure we do not exceed the MTU
25420 				 * of the next route.
25421 				 */
25422 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
25423 					ip_multirt_bad_mtu(ire1, max_frag);
25424 					continue;
25425 				}
25426 
25427 				IRE_REFHOLD(ire1);
25428 				break;
25429 			}
25430 			IRB_REFRELE(irb);
25431 			if (ire1 != NULL) {
25432 				/*
25433 				 * We are in a multiple send case, need to
25434 				 * make a copy of the packet.
25435 				 */
25436 				next_mp = copymsg(ipsec_mp);
25437 				if (next_mp == NULL) {
25438 					ire_refrele(ire1);
25439 					ire1 = NULL;
25440 				}
25441 			}
25442 		}
25443 		/*
25444 		 * Everything is done. Send it out on the wire
25445 		 *
25446 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
25447 		 * either send it on the wire or, in the case of
25448 		 * HW acceleration, call ipsec_hw_putnext.
25449 		 */
25450 		if (ire->ire_nce &&
25451 		    ire->ire_nce->nce_state != ND_REACHABLE) {
25452 			DTRACE_PROBE2(ip__wput__ipsec__bail,
25453 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
25454 			/*
25455 			 * If ire's link-layer is unresolved (this
25456 			 * would only happen if the incomplete ire
25457 			 * was added to cachetable via forwarding path)
25458 			 * don't bother going to ip_xmit_v4. Just drop the
25459 			 * packet.
25460 			 * There is a slight risk here, in that, if we
25461 			 * have the forwarding path create an incomplete
25462 			 * IRE, then until the IRE is completed, any
25463 			 * transmitted IPSEC packets will be dropped
25464 			 * instead of being queued waiting for resolution.
25465 			 *
25466 			 * But the likelihood of a forwarding packet and a wput
25467 			 * packet sending to the same dst at the same time
25468 			 * and there not yet be an ARP entry for it is small.
25469 			 * Furthermore, if this actually happens, it might
25470 			 * be likely that wput would generate multiple
25471 			 * packets (and forwarding would also have a train
25472 			 * of packets) for that destination. If this is
25473 			 * the case, some of them would have been dropped
25474 			 * anyway, since ARP only queues a few packets while
25475 			 * waiting for resolution
25476 			 *
25477 			 * NOTE: We should really call ip_xmit_v4,
25478 			 * and let it queue the packet and send the
25479 			 * ARP query and have ARP come back thus:
25480 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
25481 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
25482 			 * hw accel work. But it's too complex to get
25483 			 * the IPsec hw  acceleration approach to fit
25484 			 * well with ip_xmit_v4 doing ARP without
25485 			 * doing IPSEC simplification. For now, we just
25486 			 * poke ip_xmit_v4 to trigger the arp resolve, so
25487 			 * that we can continue with the send on the next
25488 			 * attempt.
25489 			 *
25490 			 * XXX THis should be revisited, when
25491 			 * the IPsec/IP interaction is cleaned up
25492 			 */
25493 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
25494 			    " - dropping packet\n"));
25495 			freemsg(ipsec_mp);
25496 			/*
25497 			 * Call ip_xmit_v4() to trigger ARP query
25498 			 * in case the nce_state is ND_INITIAL
25499 			 */
25500 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
25501 			goto drop_pkt;
25502 		}
25503 
25504 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
25505 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
25506 		    mblk_t *, mp);
25507 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
25508 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp);
25509 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
25510 		if (mp == NULL)
25511 			goto drop_pkt;
25512 
25513 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
25514 		pktxmit_state = ip_xmit_v4(mp, ire,
25515 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
25516 
25517 		if ((pktxmit_state ==  SEND_FAILED) ||
25518 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
25519 
25520 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
25521 drop_pkt:
25522 			BUMP_MIB(&ip_mib, ipOutDiscards);
25523 			if (ire_need_rele)
25524 				ire_refrele(ire);
25525 			if (ire1 != NULL) {
25526 				ire_refrele(ire1);
25527 				freemsg(next_mp);
25528 			}
25529 			goto done;
25530 		}
25531 
25532 		freeb(ipsec_mp);
25533 		if (ire_need_rele)
25534 			ire_refrele(ire);
25535 
25536 		if (ire1 != NULL) {
25537 			ire = ire1;
25538 			ire_need_rele = B_TRUE;
25539 			ASSERT(next_mp);
25540 			ipsec_mp = next_mp;
25541 			mp = ipsec_mp->b_cont;
25542 			ire1 = NULL;
25543 			next_mp = NULL;
25544 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
25545 		} else {
25546 			multirt_send = B_FALSE;
25547 		}
25548 	} while (multirt_send);
25549 done:
25550 	if (ill != NULL && ill_need_rele)
25551 		ill_refrele(ill);
25552 	if (ipif != NULL)
25553 		ipif_refrele(ipif);
25554 }
25555 
25556 /*
25557  * Get the ill corresponding to the specified ire, and compare its
25558  * capabilities with the protocol and algorithms specified by the
25559  * the SA obtained from ipsec_out. If they match, annotate the
25560  * ipsec_out structure to indicate that the packet needs acceleration.
25561  *
25562  *
25563  * A packet is eligible for outbound hardware acceleration if the
25564  * following conditions are satisfied:
25565  *
25566  * 1. the packet will not be fragmented
25567  * 2. the provider supports the algorithm
25568  * 3. there is no pending control message being exchanged
25569  * 4. snoop is not attached
25570  * 5. the destination address is not a broadcast or multicast address.
25571  *
25572  * Rationale:
25573  *	- Hardware drivers do not support fragmentation with
25574  *	  the current interface.
25575  *	- snoop, multicast, and broadcast may result in exposure of
25576  *	  a cleartext datagram.
25577  * We check all five of these conditions here.
25578  *
25579  * XXX would like to nuke "ire_t *" parameter here; problem is that
25580  * IRE is only way to figure out if a v4 address is a broadcast and
25581  * thus ineligible for acceleration...
25582  */
25583 static void
25584 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
25585 {
25586 	ipsec_out_t *io;
25587 	mblk_t *data_mp;
25588 	uint_t plen, overhead;
25589 
25590 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
25591 		return;
25592 
25593 	if (ill == NULL)
25594 		return;
25595 
25596 	/*
25597 	 * Destination address is a broadcast or multicast.  Punt.
25598 	 */
25599 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
25600 	    IRE_LOCAL)))
25601 		return;
25602 
25603 	data_mp = ipsec_mp->b_cont;
25604 
25605 	if (ill->ill_isv6) {
25606 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
25607 
25608 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
25609 			return;
25610 
25611 		plen = ip6h->ip6_plen;
25612 	} else {
25613 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
25614 
25615 		if (CLASSD(ipha->ipha_dst))
25616 			return;
25617 
25618 		plen = ipha->ipha_length;
25619 	}
25620 	/*
25621 	 * Is there a pending DLPI control message being exchanged
25622 	 * between IP/IPsec and the DLS Provider? If there is, it
25623 	 * could be a SADB update, and the state of the DLS Provider
25624 	 * SADB might not be in sync with the SADB maintained by
25625 	 * IPsec. To avoid dropping packets or using the wrong keying
25626 	 * material, we do not accelerate this packet.
25627 	 */
25628 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
25629 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25630 		    "ill_dlpi_pending! don't accelerate packet\n"));
25631 		return;
25632 	}
25633 
25634 	/*
25635 	 * Is the Provider in promiscous mode? If it does, we don't
25636 	 * accelerate the packet since it will bounce back up to the
25637 	 * listeners in the clear.
25638 	 */
25639 	if (ill->ill_promisc_on_phys) {
25640 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25641 		    "ill in promiscous mode, don't accelerate packet\n"));
25642 		return;
25643 	}
25644 
25645 	/*
25646 	 * Will the packet require fragmentation?
25647 	 */
25648 
25649 	/*
25650 	 * IPsec ESP note: this is a pessimistic estimate, but the same
25651 	 * as is used elsewhere.
25652 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
25653 	 *	+ 2-byte trailer
25654 	 */
25655 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
25656 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
25657 
25658 	if ((plen + overhead) > ill->ill_max_mtu)
25659 		return;
25660 
25661 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25662 
25663 	/*
25664 	 * Can the ill accelerate this IPsec protocol and algorithm
25665 	 * specified by the SA?
25666 	 */
25667 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
25668 	    ill->ill_isv6, sa)) {
25669 		return;
25670 	}
25671 
25672 	/*
25673 	 * Tell AH or ESP that the outbound ill is capable of
25674 	 * accelerating this packet.
25675 	 */
25676 	io->ipsec_out_is_capab_ill = B_TRUE;
25677 }
25678 
25679 /*
25680  * Select which AH & ESP SA's to use (if any) for the outbound packet.
25681  *
25682  * If this function returns B_TRUE, the requested SA's have been filled
25683  * into the ipsec_out_*_sa pointers.
25684  *
25685  * If the function returns B_FALSE, the packet has been "consumed", most
25686  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
25687  *
25688  * The SA references created by the protocol-specific "select"
25689  * function will be released when the ipsec_mp is freed, thanks to the
25690  * ipsec_out_free destructor -- see spd.c.
25691  */
25692 static boolean_t
25693 ipsec_out_select_sa(mblk_t *ipsec_mp)
25694 {
25695 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
25696 	ipsec_out_t *io;
25697 	ipsec_policy_t *pp;
25698 	ipsec_action_t *ap;
25699 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25700 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25701 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25702 
25703 	if (!io->ipsec_out_secure) {
25704 		/*
25705 		 * We came here by mistake.
25706 		 * Don't bother with ipsec processing
25707 		 * We should "discourage" this path in the future.
25708 		 */
25709 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25710 		return (B_FALSE);
25711 	}
25712 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25713 	ASSERT((io->ipsec_out_policy != NULL) ||
25714 	    (io->ipsec_out_act != NULL));
25715 
25716 	ASSERT(io->ipsec_out_failed == B_FALSE);
25717 
25718 	/*
25719 	 * IPSEC processing has started.
25720 	 */
25721 	io->ipsec_out_proc_begin = B_TRUE;
25722 	ap = io->ipsec_out_act;
25723 	if (ap == NULL) {
25724 		pp = io->ipsec_out_policy;
25725 		ASSERT(pp != NULL);
25726 		ap = pp->ipsp_act;
25727 		ASSERT(ap != NULL);
25728 	}
25729 
25730 	/*
25731 	 * We have an action.  now, let's select SA's.
25732 	 * (In the future, we can cache this in the conn_t..)
25733 	 */
25734 	if (ap->ipa_want_esp) {
25735 		if (io->ipsec_out_esp_sa == NULL) {
25736 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
25737 			    IPPROTO_ESP);
25738 		}
25739 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
25740 	}
25741 
25742 	if (ap->ipa_want_ah) {
25743 		if (io->ipsec_out_ah_sa == NULL) {
25744 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
25745 			    IPPROTO_AH);
25746 		}
25747 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
25748 		/*
25749 		 * The ESP and AH processing order needs to be preserved
25750 		 * when both protocols are required (ESP should be applied
25751 		 * before AH for an outbound packet). Force an ESP ACQUIRE
25752 		 * when both ESP and AH are required, and an AH ACQUIRE
25753 		 * is needed.
25754 		 */
25755 		if (ap->ipa_want_esp && need_ah_acquire)
25756 			need_esp_acquire = B_TRUE;
25757 	}
25758 
25759 	/*
25760 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
25761 	 * Release SAs that got referenced, but will not be used until we
25762 	 * acquire _all_ of the SAs we need.
25763 	 */
25764 	if (need_ah_acquire || need_esp_acquire) {
25765 		if (io->ipsec_out_ah_sa != NULL) {
25766 			IPSA_REFRELE(io->ipsec_out_ah_sa);
25767 			io->ipsec_out_ah_sa = NULL;
25768 		}
25769 		if (io->ipsec_out_esp_sa != NULL) {
25770 			IPSA_REFRELE(io->ipsec_out_esp_sa);
25771 			io->ipsec_out_esp_sa = NULL;
25772 		}
25773 
25774 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
25775 		return (B_FALSE);
25776 	}
25777 
25778 	return (B_TRUE);
25779 }
25780 
25781 /*
25782  * Process an IPSEC_OUT message and see what you can
25783  * do with it.
25784  * IPQoS Notes:
25785  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
25786  * IPSec.
25787  * XXX would like to nuke ire_t.
25788  * XXX ill_index better be "real"
25789  */
25790 void
25791 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
25792 {
25793 	ipsec_out_t *io;
25794 	ipsec_policy_t *pp;
25795 	ipsec_action_t *ap;
25796 	ipha_t *ipha;
25797 	ip6_t *ip6h;
25798 	mblk_t *mp;
25799 	ill_t *ill;
25800 	zoneid_t zoneid;
25801 	ipsec_status_t ipsec_rc;
25802 	boolean_t ill_need_rele = B_FALSE;
25803 
25804 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25805 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25806 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25807 	mp = ipsec_mp->b_cont;
25808 
25809 	/*
25810 	 * Initiate IPPF processing. We do it here to account for packets
25811 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
25812 	 * We can check for ipsec_out_proc_begin even for such packets, as
25813 	 * they will always be false (asserted below).
25814 	 */
25815 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
25816 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
25817 		    io->ipsec_out_ill_index : ill_index);
25818 		if (mp == NULL) {
25819 			ip2dbg(("ipsec_out_process: packet dropped "\
25820 			    "during IPPF processing\n"));
25821 			freeb(ipsec_mp);
25822 			BUMP_MIB(&ip_mib, ipOutDiscards);
25823 			return;
25824 		}
25825 	}
25826 
25827 	if (!io->ipsec_out_secure) {
25828 		/*
25829 		 * We came here by mistake.
25830 		 * Don't bother with ipsec processing
25831 		 * Should "discourage" this path in the future.
25832 		 */
25833 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25834 		goto done;
25835 	}
25836 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25837 	ASSERT((io->ipsec_out_policy != NULL) ||
25838 	    (io->ipsec_out_act != NULL));
25839 	ASSERT(io->ipsec_out_failed == B_FALSE);
25840 
25841 	if (!ipsec_loaded()) {
25842 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
25843 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25844 			BUMP_MIB(&ip_mib, ipOutDiscards);
25845 		} else {
25846 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
25847 		}
25848 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
25849 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
25850 		return;
25851 	}
25852 
25853 	/*
25854 	 * IPSEC processing has started.
25855 	 */
25856 	io->ipsec_out_proc_begin = B_TRUE;
25857 	ap = io->ipsec_out_act;
25858 	if (ap == NULL) {
25859 		pp = io->ipsec_out_policy;
25860 		ASSERT(pp != NULL);
25861 		ap = pp->ipsp_act;
25862 		ASSERT(ap != NULL);
25863 	}
25864 
25865 	/*
25866 	 * Save the outbound ill index. When the packet comes back
25867 	 * from IPsec, we make sure the ill hasn't changed or disappeared
25868 	 * before sending it the accelerated packet.
25869 	 */
25870 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
25871 		int ifindex;
25872 		ill = ire_to_ill(ire);
25873 		ifindex = ill->ill_phyint->phyint_ifindex;
25874 		io->ipsec_out_capab_ill_index = ifindex;
25875 	}
25876 
25877 	/*
25878 	 * The order of processing is first insert a IP header if needed.
25879 	 * Then insert the ESP header and then the AH header.
25880 	 */
25881 	if ((io->ipsec_out_se_done == B_FALSE) &&
25882 	    (ap->ipa_want_se)) {
25883 		/*
25884 		 * First get the outer IP header before sending
25885 		 * it to ESP.
25886 		 */
25887 		ipha_t *oipha, *iipha;
25888 		mblk_t *outer_mp, *inner_mp;
25889 
25890 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
25891 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
25892 			    "ipsec_out_process: "
25893 			    "Self-Encapsulation failed: Out of memory\n");
25894 			freemsg(ipsec_mp);
25895 			BUMP_MIB(&ip_mib, ipOutDiscards);
25896 			return;
25897 		}
25898 		inner_mp = ipsec_mp->b_cont;
25899 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
25900 		oipha = (ipha_t *)outer_mp->b_rptr;
25901 		iipha = (ipha_t *)inner_mp->b_rptr;
25902 		*oipha = *iipha;
25903 		outer_mp->b_wptr += sizeof (ipha_t);
25904 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
25905 		    sizeof (ipha_t));
25906 		oipha->ipha_protocol = IPPROTO_ENCAP;
25907 		oipha->ipha_version_and_hdr_length =
25908 		    IP_SIMPLE_HDR_VERSION;
25909 		oipha->ipha_hdr_checksum = 0;
25910 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
25911 		outer_mp->b_cont = inner_mp;
25912 		ipsec_mp->b_cont = outer_mp;
25913 
25914 		io->ipsec_out_se_done = B_TRUE;
25915 		io->ipsec_out_encaps = B_TRUE;
25916 	}
25917 
25918 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
25919 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
25920 	    !ipsec_out_select_sa(ipsec_mp))
25921 		return;
25922 
25923 	/*
25924 	 * By now, we know what SA's to use.  Toss over to ESP & AH
25925 	 * to do the heavy lifting.
25926 	 */
25927 	zoneid = io->ipsec_out_zoneid;
25928 	ASSERT(zoneid != ALL_ZONES);
25929 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
25930 		ASSERT(io->ipsec_out_esp_sa != NULL);
25931 		io->ipsec_out_esp_done = B_TRUE;
25932 		/*
25933 		 * Note that since hw accel can only apply one transform,
25934 		 * not two, we skip hw accel for ESP if we also have AH
25935 		 * This is an design limitation of the interface
25936 		 * which should be revisited.
25937 		 */
25938 		ASSERT(ire != NULL);
25939 		if (io->ipsec_out_ah_sa == NULL) {
25940 			ill = (ill_t *)ire->ire_stq->q_ptr;
25941 			ipsec_out_is_accelerated(ipsec_mp,
25942 			    io->ipsec_out_esp_sa, ill, ire);
25943 		}
25944 
25945 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
25946 		switch (ipsec_rc) {
25947 		case IPSEC_STATUS_SUCCESS:
25948 			break;
25949 		case IPSEC_STATUS_FAILED:
25950 			BUMP_MIB(&ip_mib, ipOutDiscards);
25951 			/* FALLTHRU */
25952 		case IPSEC_STATUS_PENDING:
25953 			return;
25954 		}
25955 	}
25956 
25957 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
25958 		ASSERT(io->ipsec_out_ah_sa != NULL);
25959 		io->ipsec_out_ah_done = B_TRUE;
25960 		if (ire == NULL) {
25961 			int idx = io->ipsec_out_capab_ill_index;
25962 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
25963 			    NULL, NULL, NULL, NULL);
25964 			ill_need_rele = B_TRUE;
25965 		} else {
25966 			ill = (ill_t *)ire->ire_stq->q_ptr;
25967 		}
25968 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
25969 		    ire);
25970 
25971 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
25972 		switch (ipsec_rc) {
25973 		case IPSEC_STATUS_SUCCESS:
25974 			break;
25975 		case IPSEC_STATUS_FAILED:
25976 			BUMP_MIB(&ip_mib, ipOutDiscards);
25977 			/* FALLTHRU */
25978 		case IPSEC_STATUS_PENDING:
25979 			if (ill != NULL && ill_need_rele)
25980 				ill_refrele(ill);
25981 			return;
25982 		}
25983 	}
25984 	/*
25985 	 * We are done with IPSEC processing. Send it over
25986 	 * the wire.
25987 	 */
25988 done:
25989 	mp = ipsec_mp->b_cont;
25990 	ipha = (ipha_t *)mp->b_rptr;
25991 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25992 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
25993 	} else {
25994 		ip6h = (ip6_t *)ipha;
25995 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
25996 	}
25997 	if (ill != NULL && ill_need_rele)
25998 		ill_refrele(ill);
25999 }
26000 
26001 /* ARGSUSED */
26002 void
26003 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26004 {
26005 	opt_restart_t	*or;
26006 	int	err;
26007 	conn_t	*connp;
26008 
26009 	ASSERT(CONN_Q(q));
26010 	connp = Q_TO_CONN(q);
26011 
26012 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26013 	or = (opt_restart_t *)first_mp->b_rptr;
26014 	/*
26015 	 * We don't need to pass any credentials here since this is just
26016 	 * a restart. The credentials are passed in when svr4_optcom_req
26017 	 * is called the first time (from ip_wput_nondata).
26018 	 */
26019 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26020 		err = svr4_optcom_req(q, first_mp, NULL,
26021 		    &ip_opt_obj);
26022 	} else {
26023 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26024 		err = tpi_optcom_req(q, first_mp, NULL,
26025 		    &ip_opt_obj);
26026 	}
26027 	if (err != EINPROGRESS) {
26028 		/* operation is done */
26029 		CONN_OPER_PENDING_DONE(connp);
26030 	}
26031 }
26032 
26033 /*
26034  * ioctls that go through a down/up sequence may need to wait for the down
26035  * to complete. This involves waiting for the ire and ipif refcnts to go down
26036  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26037  */
26038 /* ARGSUSED */
26039 void
26040 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26041 {
26042 	struct iocblk *iocp;
26043 	mblk_t *mp1;
26044 	ipif_t	*ipif;
26045 	ip_ioctl_cmd_t *ipip;
26046 	int err;
26047 	sin_t	*sin;
26048 	struct lifreq *lifr;
26049 	struct ifreq *ifr;
26050 
26051 	iocp = (struct iocblk *)mp->b_rptr;
26052 	ASSERT(ipsq != NULL);
26053 	/* Existence of mp1 verified in ip_wput_nondata */
26054 	mp1 = mp->b_cont->b_cont;
26055 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26056 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26057 		ill_t *ill;
26058 		/*
26059 		 * Special case where ipsq_current_ipif may not be set.
26060 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26061 		 * ill could also have become part of a ipmp group in the
26062 		 * process, we are here as were not able to complete the
26063 		 * operation in ipif_set_values because we could not become
26064 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26065 		 * will not be set so we need to set it.
26066 		 */
26067 		ill = (ill_t *)q->q_ptr;
26068 		ipsq->ipsq_current_ipif = ill->ill_ipif;
26069 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26070 	}
26071 
26072 	ipif = ipsq->ipsq_current_ipif;
26073 	ASSERT(ipif != NULL);
26074 	if (ipip->ipi_cmd_type == IF_CMD) {
26075 		/* This a old style SIOC[GS]IF* command */
26076 		ifr = (struct ifreq *)mp1->b_rptr;
26077 		sin = (sin_t *)&ifr->ifr_addr;
26078 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26079 		/* This a new style SIOC[GS]LIF* command */
26080 		lifr = (struct lifreq *)mp1->b_rptr;
26081 		sin = (sin_t *)&lifr->lifr_addr;
26082 	} else {
26083 		sin = NULL;
26084 	}
26085 
26086 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
26087 	    (void *)mp1->b_rptr);
26088 
26089 	/* SIOCLIFREMOVEIF could have removed the ipif */
26090 	ip_ioctl_finish(q, mp, err,
26091 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26092 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
26093 }
26094 
26095 /*
26096  * ioctl processing
26097  *
26098  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
26099  * the ioctl command in the ioctl tables and determines the copyin data size
26100  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
26101  * size.
26102  *
26103  * ioctl processing then continues when the M_IOCDATA makes its way down.
26104  * Now the ioctl is looked up again in the ioctl table, and its properties are
26105  * extracted. The associated 'conn' is then refheld till the end of the ioctl
26106  * and the general ioctl processing function ip_process_ioctl is called.
26107  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26108  * so goes thru the serialization primitive ipsq_try_enter. Then the
26109  * appropriate function to handle the ioctl is called based on the entry in
26110  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26111  * which also refreleases the 'conn' that was refheld at the start of the
26112  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26113  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
26114  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
26115  *
26116  * Many exclusive ioctls go thru an internal down up sequence as part of
26117  * the operation. For example an attempt to change the IP address of an
26118  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26119  * does all the cleanup such as deleting all ires that use this address.
26120  * Then we need to wait till all references to the interface go away.
26121  */
26122 void
26123 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26124 {
26125 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26126 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
26127 	cmd_info_t ci;
26128 	int err;
26129 	boolean_t entered_ipsq = B_FALSE;
26130 
26131 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26132 
26133 	if (ipip == NULL)
26134 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26135 
26136 	/*
26137 	 * SIOCLIFADDIF needs to go thru a special path since the
26138 	 * ill may not exist yet. This happens in the case of lo0
26139 	 * which is created using this ioctl.
26140 	 */
26141 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26142 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26143 		ip_ioctl_finish(q, mp, err,
26144 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26145 		    NULL, NULL);
26146 		return;
26147 	}
26148 
26149 	ci.ci_ipif = NULL;
26150 	switch (ipip->ipi_cmd_type) {
26151 	case IF_CMD:
26152 	case LIF_CMD:
26153 		/*
26154 		 * ioctls that pass in a [l]ifreq appear here.
26155 		 * ip_extract_lifreq_cmn returns a refheld ipif in
26156 		 * ci.ci_ipif
26157 		 */
26158 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
26159 		    ipip->ipi_flags, &ci, ip_process_ioctl);
26160 		if (err != 0) {
26161 			ip_ioctl_finish(q, mp, err,
26162 			    ipip->ipi_flags & IPI_GET_CMD ?
26163 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26164 			return;
26165 		}
26166 		ASSERT(ci.ci_ipif != NULL);
26167 		break;
26168 
26169 	case TUN_CMD:
26170 		/*
26171 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
26172 		 * a refheld ipif in ci.ci_ipif
26173 		 */
26174 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
26175 		if (err != 0) {
26176 			ip_ioctl_finish(q, mp, err,
26177 			    ipip->ipi_flags & IPI_GET_CMD ?
26178 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26179 			return;
26180 		}
26181 		ASSERT(ci.ci_ipif != NULL);
26182 		break;
26183 
26184 	case MISC_CMD:
26185 		/*
26186 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
26187 		 * For eg. SIOCGLIFCONF will appear here.
26188 		 */
26189 		switch (ipip->ipi_cmd) {
26190 		case IF_UNITSEL:
26191 			/* ioctl comes down the ill */
26192 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26193 			ipif_refhold(ci.ci_ipif);
26194 			break;
26195 		case SIOCGMSFILTER:
26196 		case SIOCSMSFILTER:
26197 		case SIOCGIPMSFILTER:
26198 		case SIOCSIPMSFILTER:
26199 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
26200 			    ip_process_ioctl);
26201 			if (err != 0) {
26202 				ip_ioctl_finish(q, mp, err,
26203 				    ipip->ipi_flags & IPI_GET_CMD ?
26204 				    COPYOUT : NO_COPYOUT, NULL, NULL);
26205 				return;
26206 			}
26207 			break;
26208 		}
26209 		err = 0;
26210 		ci.ci_sin = NULL;
26211 		ci.ci_sin6 = NULL;
26212 		ci.ci_lifr = NULL;
26213 		break;
26214 	}
26215 
26216 	/*
26217 	 * If ipsq is non-null, we are already being called exclusively
26218 	 */
26219 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26220 	if (!(ipip->ipi_flags & IPI_WR)) {
26221 		/*
26222 		 * A return value of EINPROGRESS means the ioctl is
26223 		 * either queued and waiting for some reason or has
26224 		 * already completed.
26225 		 */
26226 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26227 		    ci.ci_lifr);
26228 		if (ci.ci_ipif != NULL)
26229 			ipif_refrele(ci.ci_ipif);
26230 		ip_ioctl_finish(q, mp, err,
26231 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26232 		    NULL, NULL);
26233 		return;
26234 	}
26235 
26236 	ASSERT(ci.ci_ipif != NULL);
26237 
26238 	if (ipsq == NULL) {
26239 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26240 		    ip_process_ioctl, NEW_OP, B_TRUE);
26241 		entered_ipsq = B_TRUE;
26242 	}
26243 	/*
26244 	 * Release the ipif so that ipif_down and friends that wait for
26245 	 * references to go away are not misled about the current ipif_refcnt
26246 	 * values. We are writer so we can access the ipif even after releasing
26247 	 * the ipif.
26248 	 */
26249 	ipif_refrele(ci.ci_ipif);
26250 	if (ipsq == NULL)
26251 		return;
26252 
26253 	mutex_enter(&ipsq->ipsq_lock);
26254 	ASSERT(ipsq->ipsq_current_ipif == NULL);
26255 	ipsq->ipsq_current_ipif = ci.ci_ipif;
26256 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26257 	mutex_exit(&ipsq->ipsq_lock);
26258 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26259 	/*
26260 	 * For most set ioctls that come here, this serves as a single point
26261 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26262 	 * be any new references to the ipif. This helps functions that go
26263 	 * through this path and end up trying to wait for the refcnts
26264 	 * associated with the ipif to go down to zero. Some exceptions are
26265 	 * Failover, Failback, and Groupname commands that operate on more than
26266 	 * just the ci.ci_ipif. These commands internally determine the
26267 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26268 	 * flags on that set. Another exception is the Removeif command that
26269 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26270 	 * ipif to operate on.
26271 	 */
26272 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26273 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26274 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26275 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26276 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26277 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26278 
26279 	/*
26280 	 * A return value of EINPROGRESS means the ioctl is
26281 	 * either queued and waiting for some reason or has
26282 	 * already completed.
26283 	 */
26284 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26285 	    ci.ci_lifr);
26286 
26287 	/* SIOCLIFREMOVEIF could have removed the ipif */
26288 	ip_ioctl_finish(q, mp, err,
26289 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26290 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
26291 
26292 	if (entered_ipsq)
26293 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26294 }
26295 
26296 /*
26297  * Complete the ioctl. Typically ioctls use the mi package and need to
26298  * do mi_copyout/mi_copy_done.
26299  */
26300 void
26301 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
26302     ipif_t *ipif, ipsq_t *ipsq)
26303 {
26304 	conn_t	*connp = NULL;
26305 	hook_nic_event_t *info;
26306 
26307 	if (err == EINPROGRESS)
26308 		return;
26309 
26310 	if (CONN_Q(q)) {
26311 		connp = Q_TO_CONN(q);
26312 		ASSERT(connp->conn_ref >= 2);
26313 	}
26314 
26315 	switch (mode) {
26316 	case COPYOUT:
26317 		if (err == 0)
26318 			mi_copyout(q, mp);
26319 		else
26320 			mi_copy_done(q, mp, err);
26321 		break;
26322 
26323 	case NO_COPYOUT:
26324 		mi_copy_done(q, mp, err);
26325 		break;
26326 
26327 	default:
26328 		/* An ioctl aborted through a conn close would take this path */
26329 		break;
26330 	}
26331 
26332 	/*
26333 	 * The refhold placed at the start of the ioctl is released here.
26334 	 */
26335 	if (connp != NULL)
26336 		CONN_OPER_PENDING_DONE(connp);
26337 
26338 	/*
26339 	 * If the ioctl were an exclusive ioctl it would have set
26340 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
26341 	 */
26342 	if (ipif != NULL) {
26343 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
26344 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
26345 
26346 		/*
26347 		 * Unhook the nic event message from the ill and enqueue it into
26348 		 * the nic event taskq.
26349 		 */
26350 		if ((info = ipif->ipif_ill->ill_nic_event_info) != NULL) {
26351 			if (ddi_taskq_dispatch(eventq_queue_nic,
26352 			    ip_ne_queue_func, (void *)info, DDI_SLEEP)
26353 			    == DDI_FAILURE) {
26354 				ip2dbg(("ip_ioctl_finish: ddi_taskq_dispatch"
26355 				    "failed\n"));
26356 				if (info->hne_data != NULL)
26357 					kmem_free(info->hne_data,
26358 					    info->hne_datalen);
26359 				kmem_free(info, sizeof (hook_nic_event_t));
26360 			}
26361 
26362 			ipif->ipif_ill->ill_nic_event_info = NULL;
26363 		}
26364 
26365 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
26366 	}
26367 
26368 	/*
26369 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
26370 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
26371 	 * entering the ipsq
26372 	 */
26373 	if (ipsq != NULL) {
26374 		mutex_enter(&ipsq->ipsq_lock);
26375 		ipsq->ipsq_current_ipif = NULL;
26376 		mutex_exit(&ipsq->ipsq_lock);
26377 	}
26378 }
26379 
26380 /*
26381  * This is called from ip_wput_nondata to resume a deferred TCP bind.
26382  */
26383 /* ARGSUSED */
26384 void
26385 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
26386 {
26387 	conn_t *connp = arg;
26388 	tcp_t	*tcp;
26389 
26390 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
26391 	tcp = connp->conn_tcp;
26392 
26393 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
26394 		freemsg(mp);
26395 	else
26396 		tcp_rput_other(tcp, mp);
26397 	CONN_OPER_PENDING_DONE(connp);
26398 }
26399 
26400 /* Called from ip_wput for all non data messages */
26401 /* ARGSUSED */
26402 void
26403 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26404 {
26405 	mblk_t		*mp1;
26406 	ire_t		*ire, *fake_ire;
26407 	ill_t		*ill;
26408 	struct iocblk	*iocp;
26409 	ip_ioctl_cmd_t	*ipip;
26410 	cred_t		*cr;
26411 	conn_t		*connp = NULL;
26412 	int		cmd, err;
26413 	nce_t		*nce;
26414 	ipif_t		*ipif;
26415 
26416 	if (CONN_Q(q))
26417 		connp = Q_TO_CONN(q);
26418 
26419 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26420 
26421 	/* Check if it is a queue to /dev/sctp. */
26422 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26423 	    connp->conn_rq == NULL) {
26424 		sctp_wput(q, mp);
26425 		return;
26426 	}
26427 
26428 	switch (DB_TYPE(mp)) {
26429 	case M_IOCTL:
26430 		/*
26431 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26432 		 * will arrange to copy in associated control structures.
26433 		 */
26434 		ip_sioctl_copyin_setup(q, mp);
26435 		return;
26436 	case M_IOCDATA:
26437 		/*
26438 		 * Ensure that this is associated with one of our trans-
26439 		 * parent ioctls.  If it's not ours, discard it if we're
26440 		 * running as a driver, or pass it on if we're a module.
26441 		 */
26442 		iocp = (struct iocblk *)mp->b_rptr;
26443 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26444 		if (ipip == NULL) {
26445 			if (q->q_next == NULL) {
26446 				goto nak;
26447 			} else {
26448 				putnext(q, mp);
26449 			}
26450 			return;
26451 		} else if ((q->q_next != NULL) &&
26452 		    !(ipip->ipi_flags & IPI_MODOK)) {
26453 			/*
26454 			 * the ioctl is one we recognise, but is not
26455 			 * consumed by IP as a module, pass M_IOCDATA
26456 			 * for processing downstream, but only for
26457 			 * common Streams ioctls.
26458 			 */
26459 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26460 				putnext(q, mp);
26461 				return;
26462 			} else {
26463 				goto nak;
26464 			}
26465 		}
26466 
26467 		/* IOCTL continuation following copyin or copyout. */
26468 		if (mi_copy_state(q, mp, NULL) == -1) {
26469 			/*
26470 			 * The copy operation failed.  mi_copy_state already
26471 			 * cleaned up, so we're out of here.
26472 			 */
26473 			return;
26474 		}
26475 		/*
26476 		 * If we just completed a copy in, we become writer and
26477 		 * continue processing in ip_sioctl_copyin_done.  If it
26478 		 * was a copy out, we call mi_copyout again.  If there is
26479 		 * nothing more to copy out, it will complete the IOCTL.
26480 		 */
26481 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
26482 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
26483 				mi_copy_done(q, mp, EPROTO);
26484 				return;
26485 			}
26486 			/*
26487 			 * Check for cases that need more copying.  A return
26488 			 * value of 0 means a second copyin has been started,
26489 			 * so we return; a return value of 1 means no more
26490 			 * copying is needed, so we continue.
26491 			 */
26492 			cmd = iocp->ioc_cmd;
26493 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
26494 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
26495 			    MI_COPY_COUNT(mp) == 1) {
26496 				if (ip_copyin_msfilter(q, mp) == 0)
26497 					return;
26498 			}
26499 			/*
26500 			 * Refhold the conn, till the ioctl completes. This is
26501 			 * needed in case the ioctl ends up in the pending mp
26502 			 * list. Every mp in the ill_pending_mp list and
26503 			 * the ipsq_pending_mp must have a refhold on the conn
26504 			 * to resume processing. The refhold is released when
26505 			 * the ioctl completes. (normally or abnormally)
26506 			 * In all cases ip_ioctl_finish is called to finish
26507 			 * the ioctl.
26508 			 */
26509 			if (connp != NULL) {
26510 				/* This is not a reentry */
26511 				ASSERT(ipsq == NULL);
26512 				CONN_INC_REF(connp);
26513 			} else {
26514 				if (!(ipip->ipi_flags & IPI_MODOK)) {
26515 					mi_copy_done(q, mp, EINVAL);
26516 					return;
26517 				}
26518 			}
26519 
26520 			ip_process_ioctl(ipsq, q, mp, ipip);
26521 
26522 		} else {
26523 			mi_copyout(q, mp);
26524 		}
26525 		return;
26526 nak:
26527 		iocp->ioc_error = EINVAL;
26528 		mp->b_datap->db_type = M_IOCNAK;
26529 		iocp->ioc_count = 0;
26530 		qreply(q, mp);
26531 		return;
26532 
26533 	case M_IOCNAK:
26534 		/*
26535 		 * The only way we could get here is if a resolver didn't like
26536 		 * an IOCTL we sent it.	 This shouldn't happen.
26537 		 */
26538 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
26539 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
26540 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
26541 		freemsg(mp);
26542 		return;
26543 	case M_IOCACK:
26544 		/* Finish socket ioctls passed through to ARP. */
26545 		ip_sioctl_iocack(q, mp);
26546 		return;
26547 	case M_FLUSH:
26548 		if (*mp->b_rptr & FLUSHW)
26549 			flushq(q, FLUSHALL);
26550 		if (q->q_next) {
26551 			/*
26552 			 * M_FLUSH is sent up to IP by some drivers during
26553 			 * unbind. ip_rput has already replied to it. We are
26554 			 * here for the M_FLUSH that we originated in IP
26555 			 * before sending the unbind request to the driver.
26556 			 * Just free it as we don't queue packets in IP
26557 			 * on the write side of the device instance.
26558 			 */
26559 			freemsg(mp);
26560 			return;
26561 		}
26562 		if (*mp->b_rptr & FLUSHR) {
26563 			*mp->b_rptr &= ~FLUSHW;
26564 			qreply(q, mp);
26565 			return;
26566 		}
26567 		freemsg(mp);
26568 		return;
26569 	case IRE_DB_REQ_TYPE:
26570 		/* An Upper Level Protocol wants a copy of an IRE. */
26571 		ip_ire_req(q, mp);
26572 		return;
26573 	case M_CTL:
26574 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
26575 			break;
26576 
26577 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
26578 		    IP_ULP_OUT_LABELED) {
26579 			out_labeled_t *olp;
26580 
26581 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
26582 				break;
26583 			olp = (out_labeled_t *)mp->b_rptr;
26584 			connp->conn_ulp_labeled = olp->out_qnext == q;
26585 			freemsg(mp);
26586 			return;
26587 		}
26588 
26589 		/* M_CTL messages are used by ARP to tell us things. */
26590 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
26591 			break;
26592 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
26593 		case AR_ENTRY_SQUERY:
26594 			ip_wput_ctl(q, mp);
26595 			return;
26596 		case AR_CLIENT_NOTIFY:
26597 			ip_arp_news(q, mp);
26598 			return;
26599 		case AR_DLPIOP_DONE:
26600 			ASSERT(q->q_next != NULL);
26601 			ill = (ill_t *)q->q_ptr;
26602 			/* qwriter_ip releases the refhold */
26603 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
26604 			ill_refhold(ill);
26605 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
26606 			    CUR_OP, B_FALSE);
26607 			return;
26608 		case AR_ARP_CLOSING:
26609 			/*
26610 			 * ARP (above us) is closing. If no ARP bringup is
26611 			 * currently pending, ack the message so that ARP
26612 			 * can complete its close. Also mark ill_arp_closing
26613 			 * so that new ARP bringups will fail. If any
26614 			 * ARP bringup is currently in progress, we will
26615 			 * ack this when the current ARP bringup completes.
26616 			 */
26617 			ASSERT(q->q_next != NULL);
26618 			ill = (ill_t *)q->q_ptr;
26619 			mutex_enter(&ill->ill_lock);
26620 			ill->ill_arp_closing = 1;
26621 			if (!ill->ill_arp_bringup_pending) {
26622 				mutex_exit(&ill->ill_lock);
26623 				qreply(q, mp);
26624 			} else {
26625 				mutex_exit(&ill->ill_lock);
26626 				freemsg(mp);
26627 			}
26628 			return;
26629 		case AR_ARP_EXTEND:
26630 			/*
26631 			 * The ARP module above us is capable of duplicate
26632 			 * address detection.  Old ATM drivers will not send
26633 			 * this message.
26634 			 */
26635 			ASSERT(q->q_next != NULL);
26636 			ill = (ill_t *)q->q_ptr;
26637 			ill->ill_arp_extend = B_TRUE;
26638 			freemsg(mp);
26639 			return;
26640 		default:
26641 			break;
26642 		}
26643 		break;
26644 	case M_PROTO:
26645 	case M_PCPROTO:
26646 		/*
26647 		 * The only PROTO messages we expect are ULP binds and
26648 		 * copies of option negotiation acknowledgements.
26649 		 */
26650 		switch (((union T_primitives *)mp->b_rptr)->type) {
26651 		case O_T_BIND_REQ:
26652 		case T_BIND_REQ: {
26653 			/* Request can get queued in bind */
26654 			ASSERT(connp != NULL);
26655 			/*
26656 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
26657 			 * instead of going through this path.  We only get
26658 			 * here in the following cases:
26659 			 *
26660 			 * a. Bind retries, where ipsq is non-NULL.
26661 			 * b. T_BIND_REQ is issued from non TCP/UDP
26662 			 *    transport, e.g. icmp for raw socket,
26663 			 *    in which case ipsq will be NULL.
26664 			 */
26665 			ASSERT(ipsq != NULL ||
26666 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
26667 
26668 			/* Don't increment refcnt if this is a re-entry */
26669 			if (ipsq == NULL)
26670 				CONN_INC_REF(connp);
26671 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
26672 			    connp, NULL) : ip_bind_v4(q, mp, connp);
26673 			if (mp == NULL)
26674 				return;
26675 			if (IPCL_IS_TCP(connp)) {
26676 				/*
26677 				 * In the case of TCP endpoint we
26678 				 * come here only for bind retries
26679 				 */
26680 				ASSERT(ipsq != NULL);
26681 				CONN_INC_REF(connp);
26682 				squeue_fill(connp->conn_sqp, mp,
26683 				    ip_resume_tcp_bind, connp,
26684 				    SQTAG_BIND_RETRY);
26685 				return;
26686 			} else if (IPCL_IS_UDP(connp)) {
26687 				/*
26688 				 * In the case of UDP endpoint we
26689 				 * come here only for bind retries
26690 				 */
26691 				ASSERT(ipsq != NULL);
26692 				udp_resume_bind(connp, mp);
26693 				return;
26694 			}
26695 			qreply(q, mp);
26696 			CONN_OPER_PENDING_DONE(connp);
26697 			return;
26698 		}
26699 		case T_SVR4_OPTMGMT_REQ:
26700 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
26701 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
26702 
26703 			ASSERT(connp != NULL);
26704 			if (!snmpcom_req(q, mp, ip_snmp_set,
26705 			    ip_snmp_get, cr)) {
26706 				/*
26707 				 * Call svr4_optcom_req so that it can
26708 				 * generate the ack. We don't come here
26709 				 * if this operation is being restarted.
26710 				 * ip_restart_optmgmt will drop the conn ref.
26711 				 * In the case of ipsec option after the ipsec
26712 				 * load is complete conn_restart_ipsec_waiter
26713 				 * drops the conn ref.
26714 				 */
26715 				ASSERT(ipsq == NULL);
26716 				CONN_INC_REF(connp);
26717 				if (ip_check_for_ipsec_opt(q, mp))
26718 					return;
26719 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
26720 				if (err != EINPROGRESS) {
26721 					/* Operation is done */
26722 					CONN_OPER_PENDING_DONE(connp);
26723 				}
26724 			}
26725 			return;
26726 		case T_OPTMGMT_REQ:
26727 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
26728 			/*
26729 			 * Note: No snmpcom_req support through new
26730 			 * T_OPTMGMT_REQ.
26731 			 * Call tpi_optcom_req so that it can
26732 			 * generate the ack.
26733 			 */
26734 			ASSERT(connp != NULL);
26735 			ASSERT(ipsq == NULL);
26736 			/*
26737 			 * We don't come here for restart. ip_restart_optmgmt
26738 			 * will drop the conn ref. In the case of ipsec option
26739 			 * after the ipsec load is complete
26740 			 * conn_restart_ipsec_waiter drops the conn ref.
26741 			 */
26742 			CONN_INC_REF(connp);
26743 			if (ip_check_for_ipsec_opt(q, mp))
26744 				return;
26745 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
26746 			if (err != EINPROGRESS) {
26747 				/* Operation is done */
26748 				CONN_OPER_PENDING_DONE(connp);
26749 			}
26750 			return;
26751 		case T_UNBIND_REQ:
26752 			mp = ip_unbind(q, mp);
26753 			qreply(q, mp);
26754 			return;
26755 		default:
26756 			/*
26757 			 * Have to drop any DLPI messages coming down from
26758 			 * arp (such as an info_req which would cause ip
26759 			 * to receive an extra info_ack if it was passed
26760 			 * through.
26761 			 */
26762 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
26763 			    (int)*(uint_t *)mp->b_rptr));
26764 			freemsg(mp);
26765 			return;
26766 		}
26767 		/* NOTREACHED */
26768 	case IRE_DB_TYPE: {
26769 		nce_t		*nce;
26770 		ill_t		*ill;
26771 		in6_addr_t	gw_addr_v6;
26772 
26773 
26774 		/*
26775 		 * This is a response back from a resolver.  It
26776 		 * consists of a message chain containing:
26777 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
26778 		 * The IRE_MBLK is the one we allocated in ip_newroute.
26779 		 * The LL_HDR_MBLK is the DLPI header to use to get
26780 		 * the attached packet, and subsequent ones for the
26781 		 * same destination, transmitted.
26782 		 */
26783 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
26784 			break;
26785 		/*
26786 		 * First, check to make sure the resolution succeeded.
26787 		 * If it failed, the second mblk will be empty.
26788 		 * If it is, free the chain, dropping the packet.
26789 		 * (We must ire_delete the ire; that frees the ire mblk)
26790 		 * We're doing this now to support PVCs for ATM; it's
26791 		 * a partial xresolv implementation. When we fully implement
26792 		 * xresolv interfaces, instead of freeing everything here
26793 		 * we'll initiate neighbor discovery.
26794 		 *
26795 		 * For v4 (ARP and other external resolvers) the resolver
26796 		 * frees the message, so no check is needed. This check
26797 		 * is required, though, for a full xresolve implementation.
26798 		 * Including this code here now both shows how external
26799 		 * resolvers can NACK a resolution request using an
26800 		 * existing design that has no specific provisions for NACKs,
26801 		 * and also takes into account that the current non-ARP
26802 		 * external resolver has been coded to use this method of
26803 		 * NACKing for all IPv6 (xresolv) cases,
26804 		 * whether our xresolv implementation is complete or not.
26805 		 *
26806 		 */
26807 		ire = (ire_t *)mp->b_rptr;
26808 		ill = ire_to_ill(ire);
26809 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26810 		if (mp1->b_rptr == mp1->b_wptr) {
26811 			if (ire->ire_ipversion == IPV6_VERSION) {
26812 				/*
26813 				 * XRESOLV interface.
26814 				 */
26815 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
26816 				mutex_enter(&ire->ire_lock);
26817 				gw_addr_v6 = ire->ire_gateway_addr_v6;
26818 				mutex_exit(&ire->ire_lock);
26819 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26820 					nce = ndp_lookup_v6(ill,
26821 					    &ire->ire_addr_v6, B_FALSE);
26822 				} else {
26823 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
26824 					    B_FALSE);
26825 				}
26826 				if (nce != NULL) {
26827 					nce_resolv_failed(nce);
26828 					ndp_delete(nce);
26829 					NCE_REFRELE(nce);
26830 				}
26831 			}
26832 			mp->b_cont = NULL;
26833 			freemsg(mp1);		/* frees the pkt as well */
26834 			ASSERT(ire->ire_nce == NULL);
26835 			ire_delete((ire_t *)mp->b_rptr);
26836 			return;
26837 		}
26838 
26839 		/*
26840 		 * Split them into IRE_MBLK and pkt and feed it into
26841 		 * ire_add_then_send. Then in ire_add_then_send
26842 		 * the IRE will be added, and then the packet will be
26843 		 * run back through ip_wput. This time it will make
26844 		 * it to the wire.
26845 		 */
26846 		mp->b_cont = NULL;
26847 		mp = mp1->b_cont;		/* now, mp points to pkt */
26848 		mp1->b_cont = NULL;
26849 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
26850 		if (ire->ire_ipversion == IPV6_VERSION) {
26851 			/*
26852 			 * XRESOLV interface. Find the nce and put a copy
26853 			 * of the dl_unitdata_req in nce_res_mp
26854 			 */
26855 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
26856 			mutex_enter(&ire->ire_lock);
26857 			gw_addr_v6 = ire->ire_gateway_addr_v6;
26858 			mutex_exit(&ire->ire_lock);
26859 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26860 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
26861 				    B_FALSE);
26862 			} else {
26863 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
26864 			}
26865 			if (nce != NULL) {
26866 				/*
26867 				 * We have to protect nce_res_mp here
26868 				 * from being accessed by other threads
26869 				 * while we change the mblk pointer.
26870 				 * Other functions will also lock the nce when
26871 				 * accessing nce_res_mp.
26872 				 *
26873 				 * The reason we change the mblk pointer
26874 				 * here rather than copying the resolved address
26875 				 * into the template is that, unlike with
26876 				 * ethernet, we have no guarantee that the
26877 				 * resolved address length will be
26878 				 * smaller than or equal to the lla length
26879 				 * with which the template was allocated,
26880 				 * (for ethernet, they're equal)
26881 				 * so we have to use the actual resolved
26882 				 * address mblk - which holds the real
26883 				 * dl_unitdata_req with the resolved address.
26884 				 *
26885 				 * Doing this is the same behavior as was
26886 				 * previously used in the v4 ARP case.
26887 				 */
26888 				mutex_enter(&nce->nce_lock);
26889 				if (nce->nce_res_mp != NULL)
26890 					freemsg(nce->nce_res_mp);
26891 				nce->nce_res_mp = mp1;
26892 				mutex_exit(&nce->nce_lock);
26893 				/*
26894 				 * We do a fastpath probe here because
26895 				 * we have resolved the address without
26896 				 * using Neighbor Discovery.
26897 				 * In the non-XRESOLV v6 case, the fastpath
26898 				 * probe is done right after neighbor
26899 				 * discovery completes.
26900 				 */
26901 				if (nce->nce_res_mp != NULL) {
26902 					int res;
26903 					nce_fastpath_list_add(nce);
26904 					res = ill_fastpath_probe(ill,
26905 					    nce->nce_res_mp);
26906 					if (res != 0 && res != EAGAIN)
26907 						nce_fastpath_list_delete(nce);
26908 				}
26909 
26910 				ire_add_then_send(q, ire, mp);
26911 				/*
26912 				 * Now we have to clean out any packets
26913 				 * that may have been queued on the nce
26914 				 * while it was waiting for address resolution
26915 				 * to complete.
26916 				 */
26917 				mutex_enter(&nce->nce_lock);
26918 				mp1 = nce->nce_qd_mp;
26919 				nce->nce_qd_mp = NULL;
26920 				mutex_exit(&nce->nce_lock);
26921 				while (mp1 != NULL) {
26922 					mblk_t *nxt_mp;
26923 					queue_t *fwdq = NULL;
26924 					ill_t   *inbound_ill;
26925 					uint_t ifindex;
26926 
26927 					nxt_mp = mp1->b_next;
26928 					mp1->b_next = NULL;
26929 					/*
26930 					 * Retrieve ifindex stored in
26931 					 * ip_rput_data_v6()
26932 					 */
26933 					ifindex =
26934 					    (uint_t)(uintptr_t)mp1->b_prev;
26935 					inbound_ill =
26936 						ill_lookup_on_ifindex(ifindex,
26937 						    B_TRUE, NULL, NULL, NULL,
26938 						    NULL);
26939 					mp1->b_prev = NULL;
26940 					if (inbound_ill != NULL)
26941 						fwdq = inbound_ill->ill_rq;
26942 
26943 					if (fwdq != NULL) {
26944 						put(fwdq, mp1);
26945 						ill_refrele(inbound_ill);
26946 					} else
26947 						put(WR(ill->ill_rq), mp1);
26948 					mp1 = nxt_mp;
26949 				}
26950 				NCE_REFRELE(nce);
26951 			} else {	/* nce is NULL; clean up */
26952 				ire_delete(ire);
26953 				freemsg(mp);
26954 				freemsg(mp1);
26955 				return;
26956 			}
26957 		} else {
26958 			nce_t *arpce;
26959 			/*
26960 			 * Link layer resolution succeeded. Recompute the
26961 			 * ire_nce.
26962 			 */
26963 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
26964 			if ((arpce = ndp_lookup_v4(ill,
26965 			    (ire->ire_gateway_addr != INADDR_ANY ?
26966 			    &ire->ire_gateway_addr : &ire->ire_addr),
26967 			    B_FALSE)) == NULL) {
26968 				freeb(ire->ire_mp);
26969 				freeb(mp1);
26970 				freemsg(mp);
26971 				return;
26972 			}
26973 			mutex_enter(&arpce->nce_lock);
26974 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
26975 			if (arpce->nce_state == ND_REACHABLE) {
26976 				/*
26977 				 * Someone resolved this before us;
26978 				 * cleanup the res_mp. Since ire has
26979 				 * not been added yet, the call to ire_add_v4
26980 				 * from ire_add_then_send (when a dup is
26981 				 * detected) will clean up the ire.
26982 				 */
26983 				freeb(mp1);
26984 			} else {
26985 				if (arpce->nce_res_mp != NULL)
26986 					freemsg(arpce->nce_res_mp);
26987 				arpce->nce_res_mp = mp1;
26988 				arpce->nce_state = ND_REACHABLE;
26989 			}
26990 			mutex_exit(&arpce->nce_lock);
26991 			if (ire->ire_marks & IRE_MARK_NOADD) {
26992 				/*
26993 				 * this ire will not be added to the ire
26994 				 * cache table, so we can set the ire_nce
26995 				 * here, as there are no atomicity constraints.
26996 				 */
26997 				ire->ire_nce = arpce;
26998 				/*
26999 				 * We are associating this nce with the ire
27000 				 * so change the nce ref taken in
27001 				 * ndp_lookup_v4() from
27002 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27003 				 */
27004 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27005 			} else {
27006 				NCE_REFRELE(arpce);
27007 			}
27008 			ire_add_then_send(q, ire, mp);
27009 		}
27010 		return;	/* All is well, the packet has been sent. */
27011 	}
27012 	case IRE_ARPRESOLVE_TYPE: {
27013 
27014 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27015 			break;
27016 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27017 		mp->b_cont = NULL;
27018 		/*
27019 		 * First, check to make sure the resolution succeeded.
27020 		 * If it failed, the second mblk will be empty.
27021 		 */
27022 		if (mp1->b_rptr == mp1->b_wptr) {
27023 			/* cleanup  the incomplete ire, free queued packets */
27024 			freemsg(mp); /* fake ire */
27025 			freeb(mp1);  /* dl_unitdata response */
27026 			return;
27027 		}
27028 
27029 		/*
27030 		 * update any incomplete nce_t found. we lookup the ctable
27031 		 * and find the nce from the ire->ire_nce because we need
27032 		 * to pass the ire to ip_xmit_v4 later, and can find both
27033 		 * ire and nce in one lookup from the ctable.
27034 		 */
27035 		fake_ire = (ire_t *)mp->b_rptr;
27036 		/*
27037 		 * By the time we come back here from ARP
27038 		 * the logical outgoing interface  of the incomplete ire
27039 		 * we added in ire_forward could have disappeared,
27040 		 * causing the incomplete ire to also have
27041 		 * dissapeared. So we need to retreive the
27042 		 * proper ipif for the ire  before looking
27043 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27044 		 */
27045 		ill = q->q_ptr;
27046 
27047 		/* Get the outgoing ipif */
27048 		mutex_enter(&ill->ill_lock);
27049 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27050 			mutex_exit(&ill->ill_lock);
27051 			freemsg(mp); /* fake ire */
27052 			freeb(mp1);  /* dl_unitdata response */
27053 			return;
27054 		}
27055 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27056 
27057 		if (ipif == NULL) {
27058 			mutex_exit(&ill->ill_lock);
27059 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27060 			freemsg(mp);
27061 			freeb(mp1);
27062 			return;
27063 		}
27064 		ipif_refhold_locked(ipif);
27065 		mutex_exit(&ill->ill_lock);
27066 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27067 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27068 		    ipif, fake_ire->ire_zoneid, NULL,
27069 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
27070 		ipif_refrele(ipif);
27071 		if (ire == NULL) {
27072 			/*
27073 			 * no ire was found; check if there is an nce
27074 			 * for this lookup; if it has no ire's pointing at it
27075 			 * cleanup.
27076 			 */
27077 			if ((nce = ndp_lookup_v4(ill,
27078 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27079 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27080 			    B_FALSE)) != NULL) {
27081 				/*
27082 				 * cleanup: just reset nce.
27083 				 * We check for refcnt 2 (one for the nce
27084 				 * hash list + 1 for the ref taken by
27085 				 * ndp_lookup_v4) to ensure that there are
27086 				 * no ire's pointing at the nce.
27087 				 */
27088 				if (nce->nce_refcnt == 2) {
27089 					nce = nce_reinit(nce);
27090 				}
27091 				if (nce != NULL)
27092 					NCE_REFRELE(nce);
27093 			}
27094 			freeb(mp1);  /* dl_unitdata response */
27095 			freemsg(mp); /* fake ire */
27096 			return;
27097 		}
27098 		nce = ire->ire_nce;
27099 		DTRACE_PROBE2(ire__arpresolve__type,
27100 		    ire_t *, ire, nce_t *, nce);
27101 		ASSERT(nce->nce_state != ND_INITIAL);
27102 		mutex_enter(&nce->nce_lock);
27103 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27104 		if (nce->nce_state == ND_REACHABLE) {
27105 			/*
27106 			 * Someone resolved this before us;
27107 			 * our response is not needed any more.
27108 			 */
27109 			mutex_exit(&nce->nce_lock);
27110 			freeb(mp1);  /* dl_unitdata response */
27111 		} else {
27112 			if (nce->nce_res_mp != NULL) {
27113 				freemsg(nce->nce_res_mp);
27114 				/* existing dl_unitdata template */
27115 			}
27116 			nce->nce_res_mp = mp1;
27117 			nce->nce_state = ND_REACHABLE;
27118 			mutex_exit(&nce->nce_lock);
27119 			ire_fastpath(ire);
27120 		}
27121 		/*
27122 		 * The cached nce_t has been updated to be reachable;
27123 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
27124 		 */
27125 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27126 		freemsg(mp);
27127 		/*
27128 		 * send out queued packets.
27129 		 */
27130 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27131 
27132 		IRE_REFRELE(ire);
27133 		return;
27134 	}
27135 	default:
27136 		break;
27137 	}
27138 	if (q->q_next) {
27139 		putnext(q, mp);
27140 	} else
27141 		freemsg(mp);
27142 }
27143 
27144 /*
27145  * Process IP options in an outbound packet.  Modify the destination if there
27146  * is a source route option.
27147  * Returns non-zero if something fails in which case an ICMP error has been
27148  * sent and mp freed.
27149  */
27150 static int
27151 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27152     boolean_t mctl_present, zoneid_t zoneid)
27153 {
27154 	ipoptp_t	opts;
27155 	uchar_t		*opt;
27156 	uint8_t		optval;
27157 	uint8_t		optlen;
27158 	ipaddr_t	dst;
27159 	intptr_t	code = 0;
27160 	mblk_t		*mp;
27161 	ire_t		*ire = NULL;
27162 
27163 	ip2dbg(("ip_wput_options\n"));
27164 	mp = ipsec_mp;
27165 	if (mctl_present) {
27166 		mp = ipsec_mp->b_cont;
27167 	}
27168 
27169 	dst = ipha->ipha_dst;
27170 	for (optval = ipoptp_first(&opts, ipha);
27171 	    optval != IPOPT_EOL;
27172 	    optval = ipoptp_next(&opts)) {
27173 		opt = opts.ipoptp_cur;
27174 		optlen = opts.ipoptp_len;
27175 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27176 		    optval, optlen));
27177 		switch (optval) {
27178 			uint32_t off;
27179 		case IPOPT_SSRR:
27180 		case IPOPT_LSRR:
27181 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27182 				ip1dbg((
27183 				    "ip_wput_options: bad option offset\n"));
27184 				code = (char *)&opt[IPOPT_OLEN] -
27185 				    (char *)ipha;
27186 				goto param_prob;
27187 			}
27188 			off = opt[IPOPT_OFFSET];
27189 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27190 			    ntohl(dst)));
27191 			/*
27192 			 * For strict: verify that dst is directly
27193 			 * reachable.
27194 			 */
27195 			if (optval == IPOPT_SSRR) {
27196 				ire = ire_ftable_lookup(dst, 0, 0,
27197 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27198 				    MBLK_GETLABEL(mp),
27199 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
27200 				if (ire == NULL) {
27201 					ip1dbg(("ip_wput_options: SSRR not"
27202 					    " directly reachable: 0x%x\n",
27203 					    ntohl(dst)));
27204 					goto bad_src_route;
27205 				}
27206 				ire_refrele(ire);
27207 			}
27208 			break;
27209 		case IPOPT_RR:
27210 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27211 				ip1dbg((
27212 				    "ip_wput_options: bad option offset\n"));
27213 				code = (char *)&opt[IPOPT_OLEN] -
27214 				    (char *)ipha;
27215 				goto param_prob;
27216 			}
27217 			break;
27218 		case IPOPT_TS:
27219 			/*
27220 			 * Verify that length >=5 and that there is either
27221 			 * room for another timestamp or that the overflow
27222 			 * counter is not maxed out.
27223 			 */
27224 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27225 			if (optlen < IPOPT_MINLEN_IT) {
27226 				goto param_prob;
27227 			}
27228 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27229 				ip1dbg((
27230 				    "ip_wput_options: bad option offset\n"));
27231 				code = (char *)&opt[IPOPT_OFFSET] -
27232 				    (char *)ipha;
27233 				goto param_prob;
27234 			}
27235 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27236 			case IPOPT_TS_TSONLY:
27237 				off = IPOPT_TS_TIMELEN;
27238 				break;
27239 			case IPOPT_TS_TSANDADDR:
27240 			case IPOPT_TS_PRESPEC:
27241 			case IPOPT_TS_PRESPEC_RFC791:
27242 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27243 				break;
27244 			default:
27245 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27246 				    (char *)ipha;
27247 				goto param_prob;
27248 			}
27249 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27250 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27251 				/*
27252 				 * No room and the overflow counter is 15
27253 				 * already.
27254 				 */
27255 				goto param_prob;
27256 			}
27257 			break;
27258 		}
27259 	}
27260 
27261 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27262 		return (0);
27263 
27264 	ip1dbg(("ip_wput_options: error processing IP options."));
27265 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27266 
27267 param_prob:
27268 	/*
27269 	 * Since ip_wput() isn't close to finished, we fill
27270 	 * in enough of the header for credible error reporting.
27271 	 */
27272 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27273 		/* Failed */
27274 		freemsg(ipsec_mp);
27275 		return (-1);
27276 	}
27277 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid);
27278 	return (-1);
27279 
27280 bad_src_route:
27281 	/*
27282 	 * Since ip_wput() isn't close to finished, we fill
27283 	 * in enough of the header for credible error reporting.
27284 	 */
27285 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27286 		/* Failed */
27287 		freemsg(ipsec_mp);
27288 		return (-1);
27289 	}
27290 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
27291 	return (-1);
27292 }
27293 
27294 /*
27295  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27296  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27297  * thru /etc/system.
27298  */
27299 #define	CONN_MAXDRAINCNT	64
27300 
27301 static void
27302 conn_drain_init(void)
27303 {
27304 	int i;
27305 
27306 	conn_drain_list_cnt = conn_drain_nthreads;
27307 
27308 	if ((conn_drain_list_cnt == 0) ||
27309 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27310 		/*
27311 		 * Default value of the number of drainers is the
27312 		 * number of cpus, subject to maximum of 8 drainers.
27313 		 */
27314 		if (boot_max_ncpus != -1)
27315 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27316 		else
27317 			conn_drain_list_cnt = MIN(max_ncpus, 8);
27318 	}
27319 
27320 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
27321 	    KM_SLEEP);
27322 
27323 	for (i = 0; i < conn_drain_list_cnt; i++) {
27324 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
27325 		    MUTEX_DEFAULT, NULL);
27326 	}
27327 }
27328 
27329 static void
27330 conn_drain_fini(void)
27331 {
27332 	int i;
27333 
27334 	for (i = 0; i < conn_drain_list_cnt; i++)
27335 		mutex_destroy(&conn_drain_list[i].idl_lock);
27336 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
27337 	conn_drain_list = NULL;
27338 }
27339 
27340 /*
27341  * Note: For an overview of how flowcontrol is handled in IP please see the
27342  * IP Flowcontrol notes at the top of this file.
27343  *
27344  * Flow control has blocked us from proceeding. Insert the given conn in one
27345  * of the conn drain lists. These conn wq's will be qenabled later on when
27346  * STREAMS flow control does a backenable. conn_walk_drain will enable
27347  * the first conn in each of these drain lists. Each of these qenabled conns
27348  * in turn enables the next in the list, after it runs, or when it closes,
27349  * thus sustaining the drain process.
27350  *
27351  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27352  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27353  * running at any time, on a given conn, since there can be only 1 service proc
27354  * running on a queue at any time.
27355  */
27356 void
27357 conn_drain_insert(conn_t *connp)
27358 {
27359 	idl_t	*idl;
27360 	uint_t	index;
27361 
27362 	mutex_enter(&connp->conn_lock);
27363 	if (connp->conn_state_flags & CONN_CLOSING) {
27364 		/*
27365 		 * The conn is closing as a result of which CONN_CLOSING
27366 		 * is set. Return.
27367 		 */
27368 		mutex_exit(&connp->conn_lock);
27369 		return;
27370 	} else if (connp->conn_idl == NULL) {
27371 		/*
27372 		 * Assign the next drain list round robin. We dont' use
27373 		 * a lock, and thus it may not be strictly round robin.
27374 		 * Atomicity of load/stores is enough to make sure that
27375 		 * conn_drain_list_index is always within bounds.
27376 		 */
27377 		index = conn_drain_list_index;
27378 		ASSERT(index < conn_drain_list_cnt);
27379 		connp->conn_idl = &conn_drain_list[index];
27380 		index++;
27381 		if (index == conn_drain_list_cnt)
27382 			index = 0;
27383 		conn_drain_list_index = index;
27384 	}
27385 	mutex_exit(&connp->conn_lock);
27386 
27387 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27388 	if ((connp->conn_drain_prev != NULL) ||
27389 	    (connp->conn_state_flags & CONN_CLOSING)) {
27390 		/*
27391 		 * The conn is already in the drain list, OR
27392 		 * the conn is closing. We need to check again for
27393 		 * the closing case again since close can happen
27394 		 * after we drop the conn_lock, and before we
27395 		 * acquire the CONN_DRAIN_LIST_LOCK.
27396 		 */
27397 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27398 		return;
27399 	} else {
27400 		idl = connp->conn_idl;
27401 	}
27402 
27403 	/*
27404 	 * The conn is not in the drain list. Insert it at the
27405 	 * tail of the drain list. The drain list is circular
27406 	 * and doubly linked. idl_conn points to the 1st element
27407 	 * in the list.
27408 	 */
27409 	if (idl->idl_conn == NULL) {
27410 		idl->idl_conn = connp;
27411 		connp->conn_drain_next = connp;
27412 		connp->conn_drain_prev = connp;
27413 	} else {
27414 		conn_t *head = idl->idl_conn;
27415 
27416 		connp->conn_drain_next = head;
27417 		connp->conn_drain_prev = head->conn_drain_prev;
27418 		head->conn_drain_prev->conn_drain_next = connp;
27419 		head->conn_drain_prev = connp;
27420 	}
27421 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27422 }
27423 
27424 /*
27425  * This conn is closing, and we are called from ip_close. OR
27426  * This conn has been serviced by ip_wsrv, and we need to do the tail
27427  * processing.
27428  * If this conn is part of the drain list, we may need to sustain the drain
27429  * process by qenabling the next conn in the drain list. We may also need to
27430  * remove this conn from the list, if it is done.
27431  */
27432 static void
27433 conn_drain_tail(conn_t *connp, boolean_t closing)
27434 {
27435 	idl_t *idl;
27436 
27437 	/*
27438 	 * connp->conn_idl is stable at this point, and no lock is needed
27439 	 * to check it. If we are called from ip_close, close has already
27440 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27441 	 * called us only because conn_idl is non-null. If we are called thru
27442 	 * service, conn_idl could be null, but it cannot change because
27443 	 * service is single-threaded per queue, and there cannot be another
27444 	 * instance of service trying to call conn_drain_insert on this conn
27445 	 * now.
27446 	 */
27447 	ASSERT(!closing || (connp->conn_idl != NULL));
27448 
27449 	/*
27450 	 * If connp->conn_idl is null, the conn has not been inserted into any
27451 	 * drain list even once since creation of the conn. Just return.
27452 	 */
27453 	if (connp->conn_idl == NULL)
27454 		return;
27455 
27456 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27457 
27458 	if (connp->conn_drain_prev == NULL) {
27459 		/* This conn is currently not in the drain list.  */
27460 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27461 		return;
27462 	}
27463 	idl = connp->conn_idl;
27464 	if (idl->idl_conn_draining == connp) {
27465 		/*
27466 		 * This conn is the current drainer. If this is the last conn
27467 		 * in the drain list, we need to do more checks, in the 'if'
27468 		 * below. Otherwwise we need to just qenable the next conn,
27469 		 * to sustain the draining, and is handled in the 'else'
27470 		 * below.
27471 		 */
27472 		if (connp->conn_drain_next == idl->idl_conn) {
27473 			/*
27474 			 * This conn is the last in this list. This round
27475 			 * of draining is complete. If idl_repeat is set,
27476 			 * it means another flow enabling has happened from
27477 			 * the driver/streams and we need to another round
27478 			 * of draining.
27479 			 * If there are more than 2 conns in the drain list,
27480 			 * do a left rotate by 1, so that all conns except the
27481 			 * conn at the head move towards the head by 1, and the
27482 			 * the conn at the head goes to the tail. This attempts
27483 			 * a more even share for all queues that are being
27484 			 * drained.
27485 			 */
27486 			if ((connp->conn_drain_next != connp) &&
27487 			    (idl->idl_conn->conn_drain_next != connp)) {
27488 				idl->idl_conn = idl->idl_conn->conn_drain_next;
27489 			}
27490 			if (idl->idl_repeat) {
27491 				qenable(idl->idl_conn->conn_wq);
27492 				idl->idl_conn_draining = idl->idl_conn;
27493 				idl->idl_repeat = 0;
27494 			} else {
27495 				idl->idl_conn_draining = NULL;
27496 			}
27497 		} else {
27498 			/*
27499 			 * If the next queue that we are now qenable'ing,
27500 			 * is closing, it will remove itself from this list
27501 			 * and qenable the subsequent queue in ip_close().
27502 			 * Serialization is acheived thru idl_lock.
27503 			 */
27504 			qenable(connp->conn_drain_next->conn_wq);
27505 			idl->idl_conn_draining = connp->conn_drain_next;
27506 		}
27507 	}
27508 	if (!connp->conn_did_putbq || closing) {
27509 		/*
27510 		 * Remove ourself from the drain list, if we did not do
27511 		 * a putbq, or if the conn is closing.
27512 		 * Note: It is possible that q->q_first is non-null. It means
27513 		 * that these messages landed after we did a enableok() in
27514 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
27515 		 * service them.
27516 		 */
27517 		if (connp->conn_drain_next == connp) {
27518 			/* Singleton in the list */
27519 			ASSERT(connp->conn_drain_prev == connp);
27520 			idl->idl_conn = NULL;
27521 			idl->idl_conn_draining = NULL;
27522 		} else {
27523 			connp->conn_drain_prev->conn_drain_next =
27524 			    connp->conn_drain_next;
27525 			connp->conn_drain_next->conn_drain_prev =
27526 			    connp->conn_drain_prev;
27527 			if (idl->idl_conn == connp)
27528 				idl->idl_conn = connp->conn_drain_next;
27529 			ASSERT(idl->idl_conn_draining != connp);
27530 
27531 		}
27532 		connp->conn_drain_next = NULL;
27533 		connp->conn_drain_prev = NULL;
27534 	}
27535 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27536 }
27537 
27538 /*
27539  * Write service routine. Shared perimeter entry point.
27540  * ip_wsrv can be called in any of the following ways.
27541  * 1. The device queue's messages has fallen below the low water mark
27542  *    and STREAMS has backenabled the ill_wq. We walk thru all the
27543  *    the drain lists and backenable the first conn in each list.
27544  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
27545  *    qenabled non-tcp upper layers. We start dequeing messages and call
27546  *    ip_wput for each message.
27547  */
27548 
27549 void
27550 ip_wsrv(queue_t *q)
27551 {
27552 	conn_t	*connp;
27553 	ill_t	*ill;
27554 	mblk_t	*mp;
27555 
27556 	if (q->q_next) {
27557 		ill = (ill_t *)q->q_ptr;
27558 		if (ill->ill_state_flags == 0) {
27559 			/*
27560 			 * The device flow control has opened up.
27561 			 * Walk through conn drain lists and qenable the
27562 			 * first conn in each list. This makes sense only
27563 			 * if the stream is fully plumbed and setup.
27564 			 * Hence the if check above.
27565 			 */
27566 			ip1dbg(("ip_wsrv: walking\n"));
27567 			conn_walk_drain();
27568 		}
27569 		return;
27570 	}
27571 
27572 	connp = Q_TO_CONN(q);
27573 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
27574 
27575 	/*
27576 	 * 1. Set conn_draining flag to signal that service is active.
27577 	 *
27578 	 * 2. ip_output determines whether it has been called from service,
27579 	 *    based on the last parameter. If it is IP_WSRV it concludes it
27580 	 *    has been called from service.
27581 	 *
27582 	 * 3. Message ordering is preserved by the following logic.
27583 	 *    i. A directly called ip_output (i.e. not thru service) will queue
27584 	 *    the message at the tail, if conn_draining is set (i.e. service
27585 	 *    is running) or if q->q_first is non-null.
27586 	 *
27587 	 *    ii. If ip_output is called from service, and if ip_output cannot
27588 	 *    putnext due to flow control, it does a putbq.
27589 	 *
27590 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
27591 	 *    (causing an infinite loop).
27592 	 */
27593 	ASSERT(!connp->conn_did_putbq);
27594 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
27595 		connp->conn_draining = 1;
27596 		noenable(q);
27597 		while ((mp = getq(q)) != NULL) {
27598 			ASSERT(CONN_Q(q));
27599 
27600 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
27601 			if (connp->conn_did_putbq) {
27602 				/* ip_wput did a putbq */
27603 				break;
27604 			}
27605 		}
27606 		/*
27607 		 * At this point, a thread coming down from top, calling
27608 		 * ip_wput, may end up queueing the message. We have not yet
27609 		 * enabled the queue, so ip_wsrv won't be called again.
27610 		 * To avoid this race, check q->q_first again (in the loop)
27611 		 * If the other thread queued the message before we call
27612 		 * enableok(), we will catch it in the q->q_first check.
27613 		 * If the other thread queues the message after we call
27614 		 * enableok(), ip_wsrv will be called again by STREAMS.
27615 		 */
27616 		connp->conn_draining = 0;
27617 		enableok(q);
27618 	}
27619 
27620 	/* Enable the next conn for draining */
27621 	conn_drain_tail(connp, B_FALSE);
27622 
27623 	connp->conn_did_putbq = 0;
27624 }
27625 
27626 /*
27627  * Walk the list of all conn's calling the function provided with the
27628  * specified argument for each.	 Note that this only walks conn's that
27629  * have been bound.
27630  * Applies to both IPv4 and IPv6.
27631  */
27632 static void
27633 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
27634 {
27635 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
27636 	    func, arg, zoneid);
27637 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
27638 	    func, arg, zoneid);
27639 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
27640 	    func, arg, zoneid);
27641 	conn_walk_fanout_table(ipcl_proto_fanout,
27642 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
27643 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
27644 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
27645 }
27646 
27647 /*
27648  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
27649  * of conns that need to be drained, check if drain is already in progress.
27650  * If so set the idl_repeat bit, indicating that the last conn in the list
27651  * needs to reinitiate the drain once again, for the list. If drain is not
27652  * in progress for the list, initiate the draining, by qenabling the 1st
27653  * conn in the list. The drain is self-sustaining, each qenabled conn will
27654  * in turn qenable the next conn, when it is done/blocked/closing.
27655  */
27656 static void
27657 conn_walk_drain(void)
27658 {
27659 	int i;
27660 	idl_t *idl;
27661 
27662 	IP_STAT(ip_conn_walk_drain);
27663 
27664 	for (i = 0; i < conn_drain_list_cnt; i++) {
27665 		idl = &conn_drain_list[i];
27666 		mutex_enter(&idl->idl_lock);
27667 		if (idl->idl_conn == NULL) {
27668 			mutex_exit(&idl->idl_lock);
27669 			continue;
27670 		}
27671 		/*
27672 		 * If this list is not being drained currently by
27673 		 * an ip_wsrv thread, start the process.
27674 		 */
27675 		if (idl->idl_conn_draining == NULL) {
27676 			ASSERT(idl->idl_repeat == 0);
27677 			qenable(idl->idl_conn->conn_wq);
27678 			idl->idl_conn_draining = idl->idl_conn;
27679 		} else {
27680 			idl->idl_repeat = 1;
27681 		}
27682 		mutex_exit(&idl->idl_lock);
27683 	}
27684 }
27685 
27686 /*
27687  * Walk an conn hash table of `count' buckets, calling func for each entry.
27688  */
27689 static void
27690 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
27691     zoneid_t zoneid)
27692 {
27693 	conn_t	*connp;
27694 
27695 	while (count-- > 0) {
27696 		mutex_enter(&connfp->connf_lock);
27697 		for (connp = connfp->connf_head; connp != NULL;
27698 		    connp = connp->conn_next) {
27699 			if (zoneid == GLOBAL_ZONEID ||
27700 			    zoneid == connp->conn_zoneid) {
27701 				CONN_INC_REF(connp);
27702 				mutex_exit(&connfp->connf_lock);
27703 				(*func)(connp, arg);
27704 				mutex_enter(&connfp->connf_lock);
27705 				CONN_DEC_REF(connp);
27706 			}
27707 		}
27708 		mutex_exit(&connfp->connf_lock);
27709 		connfp++;
27710 	}
27711 }
27712 
27713 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
27714 static void
27715 conn_report1(conn_t *connp, void *mp)
27716 {
27717 	char	buf1[INET6_ADDRSTRLEN];
27718 	char	buf2[INET6_ADDRSTRLEN];
27719 	uint_t	print_len, buf_len;
27720 
27721 	ASSERT(connp != NULL);
27722 
27723 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
27724 	if (buf_len <= 0)
27725 		return;
27726 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
27727 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
27728 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
27729 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
27730 	    "%5d %s/%05d %s/%05d\n",
27731 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
27732 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
27733 	    buf1, connp->conn_lport,
27734 	    buf2, connp->conn_fport);
27735 	if (print_len < buf_len) {
27736 		((mblk_t *)mp)->b_wptr += print_len;
27737 	} else {
27738 		((mblk_t *)mp)->b_wptr += buf_len;
27739 	}
27740 }
27741 
27742 /*
27743  * Named Dispatch routine to produce a formatted report on all conns
27744  * that are listed in one of the fanout tables.
27745  * This report is accessed by using the ndd utility to "get" ND variable
27746  * "ip_conn_status".
27747  */
27748 /* ARGSUSED */
27749 static int
27750 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
27751 {
27752 	(void) mi_mpprintf(mp,
27753 	    "CONN      " MI_COL_HDRPAD_STR
27754 	    "rfq      " MI_COL_HDRPAD_STR
27755 	    "stq      " MI_COL_HDRPAD_STR
27756 	    " zone local                 remote");
27757 
27758 	/*
27759 	 * Because of the ndd constraint, at most we can have 64K buffer
27760 	 * to put in all conn info.  So to be more efficient, just
27761 	 * allocate a 64K buffer here, assuming we need that large buffer.
27762 	 * This should be OK as only privileged processes can do ndd /dev/ip.
27763 	 */
27764 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
27765 		/* The following may work even if we cannot get a large buf. */
27766 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
27767 		return (0);
27768 	}
27769 
27770 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
27771 	return (0);
27772 }
27773 
27774 /*
27775  * Determine if the ill and multicast aspects of that packets
27776  * "matches" the conn.
27777  */
27778 boolean_t
27779 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
27780     zoneid_t zoneid)
27781 {
27782 	ill_t *in_ill;
27783 	boolean_t found;
27784 	ipif_t *ipif;
27785 	ire_t *ire;
27786 	ipaddr_t dst, src;
27787 
27788 	dst = ipha->ipha_dst;
27789 	src = ipha->ipha_src;
27790 
27791 	/*
27792 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
27793 	 * unicast, broadcast and multicast reception to
27794 	 * conn_incoming_ill. conn_wantpacket itself is called
27795 	 * only for BROADCAST and multicast.
27796 	 *
27797 	 * 1) ip_rput supresses duplicate broadcasts if the ill
27798 	 *    is part of a group. Hence, we should be receiving
27799 	 *    just one copy of broadcast for the whole group.
27800 	 *    Thus, if it is part of the group the packet could
27801 	 *    come on any ill of the group and hence we need a
27802 	 *    match on the group. Otherwise, match on ill should
27803 	 *    be sufficient.
27804 	 *
27805 	 * 2) ip_rput does not suppress duplicate multicast packets.
27806 	 *    If there are two interfaces in a ill group and we have
27807 	 *    2 applications (conns) joined a multicast group G on
27808 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
27809 	 *    will give us two packets because we join G on both the
27810 	 *    interfaces rather than nominating just one interface
27811 	 *    for receiving multicast like broadcast above. So,
27812 	 *    we have to call ilg_lookup_ill to filter out duplicate
27813 	 *    copies, if ill is part of a group.
27814 	 */
27815 	in_ill = connp->conn_incoming_ill;
27816 	if (in_ill != NULL) {
27817 		if (in_ill->ill_group == NULL) {
27818 			if (in_ill != ill)
27819 				return (B_FALSE);
27820 		} else if (in_ill->ill_group != ill->ill_group) {
27821 			return (B_FALSE);
27822 		}
27823 	}
27824 
27825 	if (!CLASSD(dst)) {
27826 		if (IPCL_ZONE_MATCH(connp, zoneid))
27827 			return (B_TRUE);
27828 		/*
27829 		 * The conn is in a different zone; we need to check that this
27830 		 * broadcast address is configured in the application's zone and
27831 		 * on one ill in the group.
27832 		 */
27833 		ipif = ipif_get_next_ipif(NULL, ill);
27834 		if (ipif == NULL)
27835 			return (B_FALSE);
27836 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
27837 		    connp->conn_zoneid, NULL,
27838 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
27839 		ipif_refrele(ipif);
27840 		if (ire != NULL) {
27841 			ire_refrele(ire);
27842 			return (B_TRUE);
27843 		} else {
27844 			return (B_FALSE);
27845 		}
27846 	}
27847 
27848 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
27849 	    connp->conn_zoneid == zoneid) {
27850 		/*
27851 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
27852 		 * disabled, therefore we don't dispatch the multicast packet to
27853 		 * the sending zone.
27854 		 */
27855 		return (B_FALSE);
27856 	}
27857 
27858 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
27859 	    connp->conn_zoneid != zoneid) {
27860 		/*
27861 		 * Multicast packet on the loopback interface: we only match
27862 		 * conns who joined the group in the specified zone.
27863 		 */
27864 		return (B_FALSE);
27865 	}
27866 
27867 	if (connp->conn_multi_router) {
27868 		/* multicast packet and multicast router socket: send up */
27869 		return (B_TRUE);
27870 	}
27871 
27872 	mutex_enter(&connp->conn_lock);
27873 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
27874 	mutex_exit(&connp->conn_lock);
27875 	return (found);
27876 }
27877 
27878 /*
27879  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
27880  */
27881 /* ARGSUSED */
27882 static void
27883 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
27884 {
27885 	ill_t *ill = (ill_t *)q->q_ptr;
27886 	mblk_t	*mp1, *mp2;
27887 	ipif_t  *ipif;
27888 	int err = 0;
27889 	conn_t *connp = NULL;
27890 	ipsq_t	*ipsq;
27891 	arc_t	*arc;
27892 
27893 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
27894 
27895 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
27896 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
27897 
27898 	ASSERT(IAM_WRITER_ILL(ill));
27899 	mp2 = mp->b_cont;
27900 	mp->b_cont = NULL;
27901 
27902 	/*
27903 	 * We have now received the arp bringup completion message
27904 	 * from ARP. Mark the arp bringup as done. Also if the arp
27905 	 * stream has already started closing, send up the AR_ARP_CLOSING
27906 	 * ack now since ARP is waiting in close for this ack.
27907 	 */
27908 	mutex_enter(&ill->ill_lock);
27909 	ill->ill_arp_bringup_pending = 0;
27910 	if (ill->ill_arp_closing) {
27911 		mutex_exit(&ill->ill_lock);
27912 		/* Let's reuse the mp for sending the ack */
27913 		arc = (arc_t *)mp->b_rptr;
27914 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
27915 		arc->arc_cmd = AR_ARP_CLOSING;
27916 		qreply(q, mp);
27917 	} else {
27918 		mutex_exit(&ill->ill_lock);
27919 		freeb(mp);
27920 	}
27921 
27922 	/* We should have an IOCTL waiting on this. */
27923 	ipsq = ill->ill_phyint->phyint_ipsq;
27924 	ipif = ipsq->ipsq_pending_ipif;
27925 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
27926 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
27927 	if (mp1 == NULL) {
27928 		/* bringup was aborted by the user */
27929 		freemsg(mp2);
27930 		return;
27931 	}
27932 	ASSERT(connp != NULL);
27933 	q = CONNP_TO_WQ(connp);
27934 	/*
27935 	 * If the DL_BIND_REQ fails, it is noted
27936 	 * in arc_name_offset.
27937 	 */
27938 	err = *((int *)mp2->b_rptr);
27939 	if (err == 0) {
27940 		if (ipif->ipif_isv6) {
27941 			if ((err = ipif_up_done_v6(ipif)) != 0)
27942 				ip0dbg(("ip_arp_done: init failed\n"));
27943 		} else {
27944 			if ((err = ipif_up_done(ipif)) != 0)
27945 				ip0dbg(("ip_arp_done: init failed\n"));
27946 		}
27947 	} else {
27948 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
27949 	}
27950 
27951 	freemsg(mp2);
27952 
27953 	if ((err == 0) && (ill->ill_up_ipifs)) {
27954 		err = ill_up_ipifs(ill, q, mp1);
27955 		if (err == EINPROGRESS)
27956 			return;
27957 	}
27958 
27959 	if (ill->ill_up_ipifs) {
27960 		ill_group_cleanup(ill);
27961 	}
27962 
27963 	/*
27964 	 * The ioctl must complete now without EINPROGRESS
27965 	 * since ipsq_pending_mp_get has removed the ioctl mblk
27966 	 * from ipsq_pending_mp. Otherwise the ioctl will be
27967 	 * stuck for ever in the ipsq.
27968 	 */
27969 	ASSERT(err != EINPROGRESS);
27970 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
27971 }
27972 
27973 /* Allocate the private structure */
27974 static int
27975 ip_priv_alloc(void **bufp)
27976 {
27977 	void	*buf;
27978 
27979 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
27980 		return (ENOMEM);
27981 
27982 	*bufp = buf;
27983 	return (0);
27984 }
27985 
27986 /* Function to delete the private structure */
27987 void
27988 ip_priv_free(void *buf)
27989 {
27990 	ASSERT(buf != NULL);
27991 	kmem_free(buf, sizeof (ip_priv_t));
27992 }
27993 
27994 /*
27995  * The entry point for IPPF processing.
27996  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
27997  * routine just returns.
27998  *
27999  * When called, ip_process generates an ipp_packet_t structure
28000  * which holds the state information for this packet and invokes the
28001  * the classifier (via ipp_packet_process). The classification, depending on
28002  * configured filters, results in a list of actions for this packet. Invoking
28003  * an action may cause the packet to be dropped, in which case the resulting
28004  * mblk (*mpp) is NULL. proc indicates the callout position for
28005  * this packet and ill_index is the interface this packet on or will leave
28006  * on (inbound and outbound resp.).
28007  */
28008 void
28009 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28010 {
28011 	mblk_t		*mp;
28012 	ip_priv_t	*priv;
28013 	ipp_action_id_t	aid;
28014 	int		rc = 0;
28015 	ipp_packet_t	*pp;
28016 #define	IP_CLASS	"ip"
28017 
28018 	/* If the classifier is not loaded, return  */
28019 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28020 		return;
28021 	}
28022 
28023 	mp = *mpp;
28024 	ASSERT(mp != NULL);
28025 
28026 	/* Allocate the packet structure */
28027 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28028 	if (rc != 0) {
28029 		*mpp = NULL;
28030 		freemsg(mp);
28031 		return;
28032 	}
28033 
28034 	/* Allocate the private structure */
28035 	rc = ip_priv_alloc((void **)&priv);
28036 	if (rc != 0) {
28037 		*mpp = NULL;
28038 		freemsg(mp);
28039 		ipp_packet_free(pp);
28040 		return;
28041 	}
28042 	priv->proc = proc;
28043 	priv->ill_index = ill_index;
28044 	ipp_packet_set_private(pp, priv, ip_priv_free);
28045 	ipp_packet_set_data(pp, mp);
28046 
28047 	/* Invoke the classifier */
28048 	rc = ipp_packet_process(&pp);
28049 	if (pp != NULL) {
28050 		mp = ipp_packet_get_data(pp);
28051 		ipp_packet_free(pp);
28052 		if (rc != 0) {
28053 			freemsg(mp);
28054 			*mpp = NULL;
28055 		}
28056 	} else {
28057 		*mpp = NULL;
28058 	}
28059 #undef	IP_CLASS
28060 }
28061 
28062 /*
28063  * Propagate a multicast group membership operation (add/drop) on
28064  * all the interfaces crossed by the related multirt routes.
28065  * The call is considered successful if the operation succeeds
28066  * on at least one interface.
28067  */
28068 static int
28069 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28070     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28071     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28072     mblk_t *first_mp)
28073 {
28074 	ire_t		*ire_gw;
28075 	irb_t		*irb;
28076 	int		error = 0;
28077 	opt_restart_t	*or;
28078 
28079 	irb = ire->ire_bucket;
28080 	ASSERT(irb != NULL);
28081 
28082 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28083 
28084 	or = (opt_restart_t *)first_mp->b_rptr;
28085 	IRB_REFHOLD(irb);
28086 	for (; ire != NULL; ire = ire->ire_next) {
28087 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28088 			continue;
28089 		if (ire->ire_addr != group)
28090 			continue;
28091 
28092 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28093 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28094 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
28095 		/* No resolver exists for the gateway; skip this ire. */
28096 		if (ire_gw == NULL)
28097 			continue;
28098 
28099 		/*
28100 		 * This function can return EINPROGRESS. If so the operation
28101 		 * will be restarted from ip_restart_optmgmt which will
28102 		 * call ip_opt_set and option processing will restart for
28103 		 * this option. So we may end up calling 'fn' more than once.
28104 		 * This requires that 'fn' is idempotent except for the
28105 		 * return value. The operation is considered a success if
28106 		 * it succeeds at least once on any one interface.
28107 		 */
28108 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28109 		    NULL, fmode, src, first_mp);
28110 		if (error == 0)
28111 			or->or_private = CGTP_MCAST_SUCCESS;
28112 
28113 		if (ip_debug > 0) {
28114 			ulong_t	off;
28115 			char	*ksym;
28116 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28117 			ip2dbg(("ip_multirt_apply_membership: "
28118 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28119 			    "error %d [success %u]\n",
28120 			    ksym ? ksym : "?",
28121 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28122 			    error, or->or_private));
28123 		}
28124 
28125 		ire_refrele(ire_gw);
28126 		if (error == EINPROGRESS) {
28127 			IRB_REFRELE(irb);
28128 			return (error);
28129 		}
28130 	}
28131 	IRB_REFRELE(irb);
28132 	/*
28133 	 * Consider the call as successful if we succeeded on at least
28134 	 * one interface. Otherwise, return the last encountered error.
28135 	 */
28136 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28137 }
28138 
28139 
28140 /*
28141  * Issue a warning regarding a route crossing an interface with an
28142  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28143  * amount of time is logged.
28144  */
28145 static void
28146 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28147 {
28148 	hrtime_t	current = gethrtime();
28149 	char		buf[INET_ADDRSTRLEN];
28150 
28151 	/* Convert interval in ms to hrtime in ns */
28152 	if (multirt_bad_mtu_last_time +
28153 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
28154 	    current) {
28155 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28156 		    "to %s, incorrect MTU %u (expected %u)\n",
28157 		    ip_dot_addr(ire->ire_addr, buf),
28158 		    ire->ire_max_frag, max_frag);
28159 
28160 		multirt_bad_mtu_last_time = current;
28161 	}
28162 }
28163 
28164 
28165 /*
28166  * Get the CGTP (multirouting) filtering status.
28167  * If 0, the CGTP hooks are transparent.
28168  */
28169 /* ARGSUSED */
28170 static int
28171 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28172 {
28173 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28174 
28175 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28176 	return (0);
28177 }
28178 
28179 
28180 /*
28181  * Set the CGTP (multirouting) filtering status.
28182  * If the status is changed from active to transparent
28183  * or from transparent to active, forward the new status
28184  * to the filtering module (if loaded).
28185  */
28186 /* ARGSUSED */
28187 static int
28188 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28189     cred_t *ioc_cr)
28190 {
28191 	long		new_value;
28192 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28193 
28194 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28195 	    new_value < 0 || new_value > 1) {
28196 		return (EINVAL);
28197 	}
28198 
28199 	/*
28200 	 * Do not enable CGTP filtering - thus preventing the hooks
28201 	 * from being invoked - if the version number of the
28202 	 * filtering module hooks does not match.
28203 	 */
28204 	if ((ip_cgtp_filter_ops != NULL) &&
28205 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
28206 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
28207 		    "(module hooks version %d, expecting %d)\n",
28208 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
28209 		return (ENOTSUP);
28210 	}
28211 
28212 	if ((!*ip_cgtp_filter_value) && new_value) {
28213 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28214 		    ip_cgtp_filter_ops == NULL ?
28215 		    " (module not loaded)" : "");
28216 	}
28217 	if (*ip_cgtp_filter_value && (!new_value)) {
28218 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28219 		    ip_cgtp_filter_ops == NULL ?
28220 		    " (module not loaded)" : "");
28221 	}
28222 
28223 	if (ip_cgtp_filter_ops != NULL) {
28224 		int	res;
28225 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
28226 			return (res);
28227 		}
28228 	}
28229 
28230 	*ip_cgtp_filter_value = (boolean_t)new_value;
28231 
28232 	return (0);
28233 }
28234 
28235 
28236 /*
28237  * Return the expected CGTP hooks version number.
28238  */
28239 int
28240 ip_cgtp_filter_supported(void)
28241 {
28242 	return (ip_cgtp_filter_rev);
28243 }
28244 
28245 
28246 /*
28247  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
28248  * or by invoking this function. In the first case, the version number
28249  * of the registered structure is checked at hooks activation time
28250  * in ip_cgtp_filter_set().
28251  */
28252 int
28253 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
28254 {
28255 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28256 		return (ENOTSUP);
28257 
28258 	ip_cgtp_filter_ops = ops;
28259 	return (0);
28260 }
28261 
28262 static squeue_func_t
28263 ip_squeue_switch(int val)
28264 {
28265 	squeue_func_t rval = squeue_fill;
28266 
28267 	switch (val) {
28268 	case IP_SQUEUE_ENTER_NODRAIN:
28269 		rval = squeue_enter_nodrain;
28270 		break;
28271 	case IP_SQUEUE_ENTER:
28272 		rval = squeue_enter;
28273 		break;
28274 	default:
28275 		break;
28276 	}
28277 	return (rval);
28278 }
28279 
28280 /* ARGSUSED */
28281 static int
28282 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28283     caddr_t addr, cred_t *cr)
28284 {
28285 	int *v = (int *)addr;
28286 	long new_value;
28287 
28288 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28289 		return (EINVAL);
28290 
28291 	ip_input_proc = ip_squeue_switch(new_value);
28292 	*v = new_value;
28293 	return (0);
28294 }
28295 
28296 /* ARGSUSED */
28297 static int
28298 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28299     caddr_t addr, cred_t *cr)
28300 {
28301 	int *v = (int *)addr;
28302 	long new_value;
28303 
28304 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28305 		return (EINVAL);
28306 
28307 	*v = new_value;
28308 	return (0);
28309 }
28310 
28311 static void
28312 ip_kstat_init(void)
28313 {
28314 	ip_named_kstat_t template = {
28315 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
28316 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
28317 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
28318 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
28319 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
28320 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
28321 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
28322 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
28323 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
28324 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
28325 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
28326 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
28327 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
28328 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
28329 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
28330 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
28331 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
28332 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
28333 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
28334 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
28335 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
28336 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
28337 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
28338 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
28339 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
28340 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
28341 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
28342 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
28343 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
28344 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
28345 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
28346 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
28347 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
28348 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
28349 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
28350 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
28351 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
28352 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
28353 	};
28354 
28355 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
28356 					NUM_OF_FIELDS(ip_named_kstat_t),
28357 					0);
28358 	if (!ip_mibkp)
28359 		return;
28360 
28361 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
28362 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
28363 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
28364 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
28365 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
28366 
28367 	template.netToMediaEntrySize.value.i32 =
28368 		sizeof (mib2_ipNetToMediaEntry_t);
28369 
28370 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
28371 
28372 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
28373 
28374 	ip_mibkp->ks_update = ip_kstat_update;
28375 
28376 	kstat_install(ip_mibkp);
28377 }
28378 
28379 static void
28380 ip_kstat_fini(void)
28381 {
28382 
28383 	if (ip_mibkp != NULL) {
28384 		kstat_delete(ip_mibkp);
28385 		ip_mibkp = NULL;
28386 	}
28387 }
28388 
28389 static int
28390 ip_kstat_update(kstat_t *kp, int rw)
28391 {
28392 	ip_named_kstat_t *ipkp;
28393 
28394 	if (!kp || !kp->ks_data)
28395 		return (EIO);
28396 
28397 	if (rw == KSTAT_WRITE)
28398 		return (EACCES);
28399 
28400 	ipkp = (ip_named_kstat_t *)kp->ks_data;
28401 
28402 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
28403 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
28404 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
28405 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
28406 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
28407 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
28408 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
28409 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
28410 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
28411 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
28412 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
28413 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
28414 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
28415 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
28416 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
28417 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
28418 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
28419 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
28420 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
28421 
28422 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
28423 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
28424 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
28425 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
28426 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
28427 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
28428 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
28429 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
28430 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
28431 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
28432 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
28433 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
28434 
28435 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
28436 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
28437 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
28438 
28439 	return (0);
28440 }
28441 
28442 static void
28443 icmp_kstat_init(void)
28444 {
28445 	icmp_named_kstat_t template = {
28446 		{ "inMsgs",		KSTAT_DATA_UINT32 },
28447 		{ "inErrors",		KSTAT_DATA_UINT32 },
28448 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
28449 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
28450 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
28451 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
28452 		{ "inRedirects",	KSTAT_DATA_UINT32 },
28453 		{ "inEchos",		KSTAT_DATA_UINT32 },
28454 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
28455 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
28456 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
28457 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
28458 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
28459 		{ "outMsgs",		KSTAT_DATA_UINT32 },
28460 		{ "outErrors",		KSTAT_DATA_UINT32 },
28461 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
28462 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
28463 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
28464 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
28465 		{ "outRedirects",	KSTAT_DATA_UINT32 },
28466 		{ "outEchos",		KSTAT_DATA_UINT32 },
28467 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
28468 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
28469 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
28470 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
28471 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
28472 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
28473 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
28474 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
28475 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
28476 		{ "outDrops",		KSTAT_DATA_UINT32 },
28477 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
28478 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
28479 	};
28480 
28481 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
28482 					NUM_OF_FIELDS(icmp_named_kstat_t),
28483 					0);
28484 	if (icmp_mibkp == NULL)
28485 		return;
28486 
28487 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
28488 
28489 	icmp_mibkp->ks_update = icmp_kstat_update;
28490 
28491 	kstat_install(icmp_mibkp);
28492 }
28493 
28494 static void
28495 icmp_kstat_fini(void)
28496 {
28497 
28498 	if (icmp_mibkp != NULL) {
28499 		kstat_delete(icmp_mibkp);
28500 		icmp_mibkp = NULL;
28501 	}
28502 }
28503 
28504 static int
28505 icmp_kstat_update(kstat_t *kp, int rw)
28506 {
28507 	icmp_named_kstat_t *icmpkp;
28508 
28509 	if ((kp == NULL) || (kp->ks_data == NULL))
28510 		return (EIO);
28511 
28512 	if (rw == KSTAT_WRITE)
28513 		return (EACCES);
28514 
28515 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
28516 
28517 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
28518 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
28519 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
28520 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
28521 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
28522 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
28523 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
28524 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
28525 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
28526 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
28527 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
28528 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
28529 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
28530 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
28531 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
28532 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
28533 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
28534 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
28535 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
28536 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
28537 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
28538 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
28539 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
28540 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
28541 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
28542 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
28543 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
28544 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
28545 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
28546 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
28547 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
28548 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
28549 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
28550 
28551 	return (0);
28552 }
28553 
28554 /*
28555  * This is the fanout function for raw socket opened for SCTP.  Note
28556  * that it is called after SCTP checks that there is no socket which
28557  * wants a packet.  Then before SCTP handles this out of the blue packet,
28558  * this function is called to see if there is any raw socket for SCTP.
28559  * If there is and it is bound to the correct address, the packet will
28560  * be sent to that socket.  Note that only one raw socket can be bound to
28561  * a port.  This is assured in ipcl_sctp_hash_insert();
28562  */
28563 void
28564 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
28565     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
28566     uint_t ipif_seqid, zoneid_t zoneid)
28567 {
28568 	conn_t		*connp;
28569 	queue_t		*rq;
28570 	mblk_t		*first_mp;
28571 	boolean_t	secure;
28572 	ip6_t		*ip6h;
28573 
28574 	first_mp = mp;
28575 	if (mctl_present) {
28576 		mp = first_mp->b_cont;
28577 		secure = ipsec_in_is_secure(first_mp);
28578 		ASSERT(mp != NULL);
28579 	} else {
28580 		secure = B_FALSE;
28581 	}
28582 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
28583 
28584 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
28585 	if (connp == NULL) {
28586 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
28587 		    mctl_present);
28588 		return;
28589 	}
28590 	rq = connp->conn_rq;
28591 	if (!canputnext(rq)) {
28592 		CONN_DEC_REF(connp);
28593 		BUMP_MIB(&ip_mib, rawipInOverflows);
28594 		freemsg(first_mp);
28595 		return;
28596 	}
28597 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
28598 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
28599 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
28600 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
28601 		if (first_mp == NULL) {
28602 			CONN_DEC_REF(connp);
28603 			return;
28604 		}
28605 	}
28606 	/*
28607 	 * We probably should not send M_CTL message up to
28608 	 * raw socket.
28609 	 */
28610 	if (mctl_present)
28611 		freeb(first_mp);
28612 
28613 	/* Initiate IPPF processing here if needed. */
28614 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
28615 	    (!isv4 && IP6_IN_IPP(flags))) {
28616 		ip_process(IPP_LOCAL_IN, &mp,
28617 		    recv_ill->ill_phyint->phyint_ifindex);
28618 		if (mp == NULL) {
28619 			CONN_DEC_REF(connp);
28620 			return;
28621 		}
28622 	}
28623 
28624 	if (connp->conn_recvif || connp->conn_recvslla ||
28625 	    ((connp->conn_ipv6_recvpktinfo ||
28626 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
28627 	    (flags & IP_FF_IP6INFO))) {
28628 		int in_flags = 0;
28629 
28630 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
28631 			in_flags = IPF_RECVIF;
28632 		}
28633 		if (connp->conn_recvslla) {
28634 			in_flags |= IPF_RECVSLLA;
28635 		}
28636 		if (isv4) {
28637 			mp = ip_add_info(mp, recv_ill, in_flags);
28638 		} else {
28639 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
28640 			if (mp == NULL) {
28641 				CONN_DEC_REF(connp);
28642 				return;
28643 			}
28644 		}
28645 	}
28646 
28647 	BUMP_MIB(&ip_mib, ipInDelivers);
28648 	/*
28649 	 * We are sending the IPSEC_IN message also up. Refer
28650 	 * to comments above this function.
28651 	 */
28652 	putnext(rq, mp);
28653 	CONN_DEC_REF(connp);
28654 }
28655 
28656 /*
28657  * This function should be called only if all packet processing
28658  * including fragmentation is complete. Callers of this function
28659  * must set mp->b_prev to one of these values:
28660  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
28661  * prior to handing over the mp as first argument to this function.
28662  *
28663  * If the ire passed by caller is incomplete, this function
28664  * queues the packet and if necessary, sends ARP request and bails.
28665  * If the ire passed is fully resolved, we simply prepend
28666  * the link-layer header to the packet, do ipsec hw acceleration
28667  * work if necessary, and send the packet out on the wire.
28668  *
28669  * NOTE: IPSEC will only call this function with fully resolved
28670  * ires if hw acceleration is involved.
28671  * TODO list :
28672  * 	a Handle M_MULTIDATA so that
28673  *	  tcp_multisend->tcp_multisend_data can
28674  *	  call ip_xmit_v4 directly
28675  *	b Handle post-ARP work for fragments so that
28676  *	  ip_wput_frag can call this function.
28677  */
28678 ipxmit_state_t
28679 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
28680 {
28681 	nce_t		*arpce;
28682 	queue_t		*q;
28683 	int		ill_index;
28684 	mblk_t		*nxt_mp, *first_mp;
28685 	boolean_t	xmit_drop = B_FALSE;
28686 	ip_proc_t	proc;
28687 	ill_t		*out_ill;
28688 
28689 	arpce = ire->ire_nce;
28690 	ASSERT(arpce != NULL);
28691 
28692 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
28693 
28694 	mutex_enter(&arpce->nce_lock);
28695 	switch (arpce->nce_state) {
28696 	case ND_REACHABLE:
28697 		/* If there are other queued packets, queue this packet */
28698 		if (arpce->nce_qd_mp != NULL) {
28699 			if (mp != NULL)
28700 				nce_queue_mp_common(arpce, mp, B_FALSE);
28701 			mp = arpce->nce_qd_mp;
28702 		}
28703 		arpce->nce_qd_mp = NULL;
28704 		mutex_exit(&arpce->nce_lock);
28705 
28706 		/*
28707 		 * Flush the queue.  In the common case, where the
28708 		 * ARP is already resolved,  it will go through the
28709 		 * while loop only once.
28710 		 */
28711 		while (mp != NULL) {
28712 
28713 			nxt_mp = mp->b_next;
28714 			mp->b_next = NULL;
28715 			/*
28716 			 * This info is needed for IPQOS to do COS marking
28717 			 * in ip_wput_attach_llhdr->ip_process.
28718 			 */
28719 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
28720 			mp->b_prev = NULL;
28721 
28722 			/* set up ill index for outbound qos processing */
28723 			out_ill = ire->ire_ipif->ipif_ill;
28724 			ill_index = out_ill->ill_phyint->phyint_ifindex;
28725 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
28726 			    ill_index);
28727 			if (first_mp == NULL) {
28728 				xmit_drop = B_TRUE;
28729 				if (proc == IPP_FWD_OUT) {
28730 					BUMP_MIB(&ip_mib, ipInDiscards);
28731 				} else {
28732 					BUMP_MIB(&ip_mib, ipOutDiscards);
28733 				}
28734 				goto next_mp;
28735 			}
28736 			/* non-ipsec hw accel case */
28737 			if (io == NULL || !io->ipsec_out_accelerated) {
28738 				/* send it */
28739 				q = ire->ire_stq;
28740 				if (proc == IPP_FWD_OUT) {
28741 					UPDATE_IB_PKT_COUNT(ire);
28742 				} else {
28743 					UPDATE_OB_PKT_COUNT(ire);
28744 				}
28745 				ire->ire_last_used_time = lbolt;
28746 
28747 				if (flow_ctl_enabled || canputnext(q))  {
28748 					if (proc == IPP_FWD_OUT) {
28749 						BUMP_MIB(&ip_mib,
28750 						    ipForwDatagrams);
28751 					}
28752 
28753 					if (mp == NULL)
28754 						goto next_mp;
28755 					putnext(q, first_mp);
28756 				} else {
28757 					BUMP_MIB(&ip_mib,
28758 					    ipOutDiscards);
28759 					xmit_drop = B_TRUE;
28760 					freemsg(first_mp);
28761 				}
28762 			} else {
28763 				/*
28764 				 * Safety Pup says: make sure this
28765 				 *  is going to the right interface!
28766 				 */
28767 				ill_t *ill1 =
28768 				    (ill_t *)ire->ire_stq->q_ptr;
28769 				int ifindex =
28770 				    ill1->ill_phyint->phyint_ifindex;
28771 				if (ifindex !=
28772 				    io->ipsec_out_capab_ill_index) {
28773 					xmit_drop = B_TRUE;
28774 					freemsg(mp);
28775 				} else {
28776 					ipsec_hw_putnext(ire->ire_stq,
28777 					    mp);
28778 				}
28779 			}
28780 next_mp:
28781 			mp = nxt_mp;
28782 		} /* while (mp != NULL) */
28783 		if (xmit_drop)
28784 			return (SEND_FAILED);
28785 		else
28786 			return (SEND_PASSED);
28787 
28788 	case ND_INITIAL:
28789 	case ND_INCOMPLETE:
28790 
28791 		/*
28792 		 * While we do send off packets to dests that
28793 		 * use fully-resolved CGTP routes, we do not
28794 		 * handle unresolved CGTP routes.
28795 		 */
28796 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
28797 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
28798 
28799 		if (mp != NULL) {
28800 			/* queue the packet */
28801 			nce_queue_mp_common(arpce, mp, B_FALSE);
28802 		}
28803 
28804 		if (arpce->nce_state == ND_INCOMPLETE) {
28805 			mutex_exit(&arpce->nce_lock);
28806 			DTRACE_PROBE3(ip__xmit__incomplete,
28807 			    (ire_t *), ire, (mblk_t *), mp,
28808 			    (ipsec_out_t *), io);
28809 			return (LOOKUP_IN_PROGRESS);
28810 		}
28811 
28812 		arpce->nce_state = ND_INCOMPLETE;
28813 		mutex_exit(&arpce->nce_lock);
28814 		/*
28815 		 * Note that ire_add() (called from ire_forward())
28816 		 * holds a ref on the ire until ARP is completed.
28817 		 */
28818 
28819 		ire_arpresolve(ire, ire_to_ill(ire));
28820 		return (LOOKUP_IN_PROGRESS);
28821 	default:
28822 		ASSERT(0);
28823 		mutex_exit(&arpce->nce_lock);
28824 		return (LLHDR_RESLV_FAILED);
28825 	}
28826 }
28827 
28828 /*
28829  * Return B_TRUE if the buffers differ in length or content.
28830  * This is used for comparing extension header buffers.
28831  * Note that an extension header would be declared different
28832  * even if all that changed was the next header value in that header i.e.
28833  * what really changed is the next extension header.
28834  */
28835 boolean_t
28836 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
28837     uint_t blen)
28838 {
28839 	if (!b_valid)
28840 		blen = 0;
28841 
28842 	if (alen != blen)
28843 		return (B_TRUE);
28844 	if (alen == 0)
28845 		return (B_FALSE);	/* Both zero length */
28846 	return (bcmp(abuf, bbuf, alen));
28847 }
28848 
28849 /*
28850  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
28851  * Return B_FALSE if memory allocation fails - don't change any state!
28852  */
28853 boolean_t
28854 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28855     const void *src, uint_t srclen)
28856 {
28857 	void *dst;
28858 
28859 	if (!src_valid)
28860 		srclen = 0;
28861 
28862 	ASSERT(*dstlenp == 0);
28863 	if (src != NULL && srclen != 0) {
28864 		dst = mi_alloc(srclen, BPRI_MED);
28865 		if (dst == NULL)
28866 			return (B_FALSE);
28867 	} else {
28868 		dst = NULL;
28869 	}
28870 	if (*dstp != NULL)
28871 		mi_free(*dstp);
28872 	*dstp = dst;
28873 	*dstlenp = dst == NULL ? 0 : srclen;
28874 	return (B_TRUE);
28875 }
28876 
28877 /*
28878  * Replace what is in *dst, *dstlen with the source.
28879  * Assumes ip_allocbuf has already been called.
28880  */
28881 void
28882 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28883     const void *src, uint_t srclen)
28884 {
28885 	if (!src_valid)
28886 		srclen = 0;
28887 
28888 	ASSERT(*dstlenp == srclen);
28889 	if (src != NULL && srclen != 0)
28890 		bcopy(src, *dstp, srclen);
28891 }
28892 
28893 /*
28894  * Free the storage pointed to by the members of an ip6_pkt_t.
28895  */
28896 void
28897 ip6_pkt_free(ip6_pkt_t *ipp)
28898 {
28899 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
28900 
28901 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
28902 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
28903 		ipp->ipp_hopopts = NULL;
28904 		ipp->ipp_hopoptslen = 0;
28905 	}
28906 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
28907 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
28908 		ipp->ipp_rtdstopts = NULL;
28909 		ipp->ipp_rtdstoptslen = 0;
28910 	}
28911 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
28912 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
28913 		ipp->ipp_dstopts = NULL;
28914 		ipp->ipp_dstoptslen = 0;
28915 	}
28916 	if (ipp->ipp_fields & IPPF_RTHDR) {
28917 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
28918 		ipp->ipp_rthdr = NULL;
28919 		ipp->ipp_rthdrlen = 0;
28920 	}
28921 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
28922 	    IPPF_RTHDR);
28923 }
28924