xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 60a3f738d56f92ae8b80e4b62a2331c6e1f2311f)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /* Copyright (c) 1990 Mentat Inc. */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/stream.h>
31 #include <sys/dlpi.h>
32 #include <sys/stropts.h>
33 #include <sys/sysmacros.h>
34 #include <sys/strsubr.h>
35 #include <sys/strlog.h>
36 #include <sys/strsun.h>
37 #include <sys/zone.h>
38 #define	_SUN_TPI_VERSION 2
39 #include <sys/tihdr.h>
40 #include <sys/xti_inet.h>
41 #include <sys/ddi.h>
42 #include <sys/sunddi.h>
43 #include <sys/cmn_err.h>
44 #include <sys/debug.h>
45 #include <sys/kobj.h>
46 #include <sys/modctl.h>
47 #include <sys/atomic.h>
48 #include <sys/policy.h>
49 #include <sys/priv.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/sdt.h>
55 #include <sys/socket.h>
56 #include <sys/vtrace.h>
57 #include <sys/isa_defs.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/kstatcom.h>
72 
73 #include <netinet/igmp_var.h>
74 #include <netinet/ip6.h>
75 #include <netinet/icmp6.h>
76 #include <netinet/sctp.h>
77 
78 #include <inet/ip.h>
79 #include <inet/ip_impl.h>
80 #include <inet/ip6.h>
81 #include <inet/ip6_asp.h>
82 #include <inet/tcp.h>
83 #include <inet/tcp_impl.h>
84 #include <inet/ip_multi.h>
85 #include <inet/ip_if.h>
86 #include <inet/ip_ire.h>
87 #include <inet/ip_ftable.h>
88 #include <inet/ip_rts.h>
89 #include <inet/optcom.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <sys/sunddi.h>
121 
122 #include <sys/tsol/label.h>
123 #include <sys/tsol/tnet.h>
124 
125 #include <rpc/pmap_prot.h>
126 
127 /*
128  * Values for squeue switch:
129  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
130  * IP_SQUEUE_ENTER: squeue_enter
131  * IP_SQUEUE_FILL: squeue_fill
132  */
133 int ip_squeue_enter = 2;
134 squeue_func_t ip_input_proc;
135 /*
136  * IP statistics.
137  */
138 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
139 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
140 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
141 
142 typedef struct ip_stat {
143 	kstat_named_t	ipsec_fanout_proto;
144 	kstat_named_t	ip_udp_fannorm;
145 	kstat_named_t	ip_udp_fanmb;
146 	kstat_named_t	ip_udp_fanothers;
147 	kstat_named_t	ip_udp_fast_path;
148 	kstat_named_t	ip_udp_slow_path;
149 	kstat_named_t	ip_udp_input_err;
150 	kstat_named_t	ip_tcppullup;
151 	kstat_named_t	ip_tcpoptions;
152 	kstat_named_t	ip_multipkttcp;
153 	kstat_named_t	ip_tcp_fast_path;
154 	kstat_named_t	ip_tcp_slow_path;
155 	kstat_named_t	ip_tcp_input_error;
156 	kstat_named_t	ip_db_ref;
157 	kstat_named_t	ip_notaligned1;
158 	kstat_named_t	ip_notaligned2;
159 	kstat_named_t	ip_multimblk3;
160 	kstat_named_t	ip_multimblk4;
161 	kstat_named_t	ip_ipoptions;
162 	kstat_named_t	ip_classify_fail;
163 	kstat_named_t	ip_opt;
164 	kstat_named_t	ip_udp_rput_local;
165 	kstat_named_t	ipsec_proto_ahesp;
166 	kstat_named_t	ip_conn_flputbq;
167 	kstat_named_t	ip_conn_walk_drain;
168 	kstat_named_t   ip_out_sw_cksum;
169 	kstat_named_t   ip_in_sw_cksum;
170 	kstat_named_t   ip_trash_ire_reclaim_calls;
171 	kstat_named_t   ip_trash_ire_reclaim_success;
172 	kstat_named_t   ip_ire_arp_timer_expired;
173 	kstat_named_t   ip_ire_redirect_timer_expired;
174 	kstat_named_t	ip_ire_pmtu_timer_expired;
175 	kstat_named_t	ip_input_multi_squeue;
176 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
177 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
178 	kstat_named_t	ip_tcp_in_sw_cksum_err;
179 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
180 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
181 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
182 	kstat_named_t	ip_udp_in_sw_cksum_err;
183 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
184 	kstat_named_t	ip_frag_mdt_pkt_out;
185 	kstat_named_t	ip_frag_mdt_discarded;
186 	kstat_named_t	ip_frag_mdt_allocfail;
187 	kstat_named_t	ip_frag_mdt_addpdescfail;
188 	kstat_named_t	ip_frag_mdt_allocd;
189 } ip_stat_t;
190 
191 static ip_stat_t ip_statistics = {
192 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
193 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
194 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
195 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
196 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
197 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
198 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
199 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
200 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
201 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
202 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
203 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
204 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
205 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
206 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
207 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
208 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
209 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
210 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
211 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
212 	{ "ip_opt",				KSTAT_DATA_UINT64 },
213 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
214 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
215 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
216 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
217 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
218 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
219 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
220 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
221 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
222 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
223 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
224 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
225 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
226 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
227 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
228 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
229 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
230 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
231 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
232 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
233 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
234 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
235 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
236 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
237 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
238 };
239 
240 static kstat_t *ip_kstat;
241 
242 #define	TCP6 "tcp6"
243 #define	TCP "tcp"
244 #define	SCTP "sctp"
245 #define	SCTP6 "sctp6"
246 
247 major_t TCP6_MAJ;
248 major_t TCP_MAJ;
249 major_t SCTP_MAJ;
250 major_t SCTP6_MAJ;
251 
252 int ip_poll_normal_ms = 100;
253 int ip_poll_normal_ticks = 0;
254 
255 /*
256  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
257  */
258 
259 struct listptr_s {
260 	mblk_t	*lp_head;	/* pointer to the head of the list */
261 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
262 };
263 
264 typedef struct listptr_s listptr_t;
265 
266 /*
267  * This is used by ip_snmp_get_mib2_ip_route_media and
268  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
269  */
270 typedef struct iproutedata_s {
271 	uint_t		ird_idx;
272 	listptr_t	ird_route;	/* ipRouteEntryTable */
273 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
274 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
275 } iproutedata_t;
276 
277 /*
278  * Cluster specific hooks. These should be NULL when booted as a non-cluster
279  */
280 
281 /*
282  * Hook functions to enable cluster networking
283  * On non-clustered systems these vectors must always be NULL.
284  *
285  * Hook function to Check ip specified ip address is a shared ip address
286  * in the cluster
287  *
288  */
289 int (*cl_inet_isclusterwide)(uint8_t protocol,
290     sa_family_t addr_family, uint8_t *laddrp) = NULL;
291 
292 /*
293  * Hook function to generate cluster wide ip fragment identifier
294  */
295 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
296     uint8_t *laddrp, uint8_t *faddrp) = NULL;
297 
298 /*
299  * Synchronization notes:
300  *
301  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
302  * MT level protection given by STREAMS. IP uses a combination of its own
303  * internal serialization mechanism and standard Solaris locking techniques.
304  * The internal serialization is per phyint (no IPMP) or per IPMP group.
305  * This is used to serialize plumbing operations, IPMP operations, certain
306  * multicast operations, most set ioctls, igmp/mld timers etc.
307  *
308  * Plumbing is a long sequence of operations involving message
309  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
310  * involved in plumbing operations. A natural model is to serialize these
311  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
312  * parallel without any interference. But various set ioctls on hme0 are best
313  * serialized. However if the system uses IPMP, the operations are easier if
314  * they are serialized on a per IPMP group basis since IPMP operations
315  * happen across ill's of a group. Thus the lowest common denominator is to
316  * serialize most set ioctls, multicast join/leave operations, IPMP operations
317  * igmp/mld timer operations, and processing of DLPI control messages received
318  * from drivers on a per IPMP group basis. If the system does not employ
319  * IPMP the serialization is on a per phyint basis. This serialization is
320  * provided by the ipsq_t and primitives operating on this. Details can
321  * be found in ip_if.c above the core primitives operating on ipsq_t.
322  *
323  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
324  * Simiarly lookup of an ire by a thread also returns a refheld ire.
325  * In addition ipif's and ill's referenced by the ire are also indirectly
326  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
327  * the ipif's address or netmask change as long as an ipif is refheld
328  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
329  * address of an ipif has to go through the ipsq_t. This ensures that only
330  * 1 such exclusive operation proceeds at any time on the ipif. It then
331  * deletes all ires associated with this ipif, and waits for all refcnts
332  * associated with this ipif to come down to zero. The address is changed
333  * only after the ipif has been quiesced. Then the ipif is brought up again.
334  * More details are described above the comment in ip_sioctl_flags.
335  *
336  * Packet processing is based mostly on IREs and are fully multi-threaded
337  * using standard Solaris MT techniques.
338  *
339  * There are explicit locks in IP to handle:
340  * - The ip_g_head list maintained by mi_open_link() and friends.
341  *
342  * - The reassembly data structures (one lock per hash bucket)
343  *
344  * - conn_lock is meant to protect conn_t fields. The fields actually
345  *   protected by conn_lock are documented in the conn_t definition.
346  *
347  * - ire_lock to protect some of the fields of the ire, IRE tables
348  *   (one lock per hash bucket). Refer to ip_ire.c for details.
349  *
350  * - ndp_g_lock and nce_lock for protecting NCEs.
351  *
352  * - ill_lock protects fields of the ill and ipif. Details in ip.h
353  *
354  * - ill_g_lock: This is a global reader/writer lock. Protects the following
355  *	* The AVL tree based global multi list of all ills.
356  *	* The linked list of all ipifs of an ill
357  *	* The <ill-ipsq> mapping
358  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
359  *	* The illgroup list threaded by ill_group_next.
360  *	* <ill-phyint> association
361  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
362  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
363  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
364  *   will all have to hold the ill_g_lock as writer for the actual duration
365  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
366  *   may be found in the IPMP section.
367  *
368  * - ill_lock:  This is a per ill mutex.
369  *   It protects some members of the ill and is documented below.
370  *   It also protects the <ill-ipsq> mapping
371  *   It also protects the illgroup list threaded by ill_group_next.
372  *   It also protects the <ill-phyint> assoc.
373  *   It also protects the list of ipifs hanging off the ill.
374  *
375  * - ipsq_lock: This is a per ipsq_t mutex lock.
376  *   This protects all the other members of the ipsq struct except
377  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
378  *
379  * - illgrp_lock: This is a per ill_group mutex lock.
380  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
381  *   which dictates which is the next ill in an ill_group that is to be chosen
382  *   for sending outgoing packets, through creation of an IRE_CACHE that
383  *   references this ill.
384  *
385  * - phyint_lock: This is a per phyint mutex lock. Protects just the
386  *   phyint_flags
387  *
388  * - ip_g_nd_lock: This is a global reader/writer lock.
389  *   Any call to nd_load to load a new parameter to the ND table must hold the
390  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
391  *   as reader.
392  *
393  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
394  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
395  *   uniqueness check also done atomically.
396  *
397  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
398  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
399  *   as a writer when adding or deleting elements from these lists, and
400  *   as a reader when walking these lists to send a SADB update to the
401  *   IPsec capable ills.
402  *
403  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
404  *   group list linked by ill_usesrc_grp_next. It also protects the
405  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
406  *   group is being added or deleted.  This lock is taken as a reader when
407  *   walking the list/group(eg: to get the number of members in a usesrc group).
408  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
409  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
410  *   example, it is not necessary to take this lock in the initial portion
411  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
412  *   ip_sioctl_flags since the these operations are executed exclusively and
413  *   that ensures that the "usesrc group state" cannot change. The "usesrc
414  *   group state" change can happen only in the latter part of
415  *   ip_sioctl_slifusesrc and in ill_delete.
416  *
417  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
418  *
419  * To change the <ill-phyint> association, the ill_g_lock must be held
420  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
421  * must be held.
422  *
423  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
424  * and the ill_lock of the ill in question must be held.
425  *
426  * To change the <ill-illgroup> association the ill_g_lock must be held as
427  * writer and the ill_lock of the ill in question must be held.
428  *
429  * To add or delete an ipif from the list of ipifs hanging off the ill,
430  * ill_g_lock (writer) and ill_lock must be held and the thread must be
431  * a writer on the associated ipsq,.
432  *
433  * To add or delete an ill to the system, the ill_g_lock must be held as
434  * writer and the thread must be a writer on the associated ipsq.
435  *
436  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
437  * must be a writer on the associated ipsq.
438  *
439  * Lock hierarchy
440  *
441  * Some lock hierarchy scenarios are listed below.
442  *
443  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
444  * ill_g_lock -> illgrp_lock -> ill_lock
445  * ill_g_lock -> ill_lock(s) -> phyint_lock
446  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
447  * ill_g_lock -> ip_addr_avail_lock
448  * conn_lock -> irb_lock -> ill_lock -> ire_lock
449  * ill_g_lock -> ip_g_nd_lock
450  *
451  * When more than 1 ill lock is needed to be held, all ill lock addresses
452  * are sorted on address and locked starting from highest addressed lock
453  * downward.
454  *
455  * Mobile-IP scenarios
456  *
457  * irb_lock -> ill_lock -> ire_mrtun_lock
458  * irb_lock -> ill_lock -> ire_srcif_table_lock
459  *
460  * IPsec scenarios
461  *
462  * ipsa_lock -> ill_g_lock -> ill_lock
463  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
464  * ipsec_capab_ills_lock -> ipsa_lock
465  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
466  *
467  * Trusted Solaris scenarios
468  *
469  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
470  * igsa_lock -> gcdb_lock
471  * gcgrp_rwlock -> ire_lock
472  * gcgrp_rwlock -> gcdb_lock
473  *
474  *
475  * Routing/forwarding table locking notes:
476  *
477  * Lock acquisition order: Radix tree lock, irb_lock.
478  * Requirements:
479  * i.  Walker must not hold any locks during the walker callback.
480  * ii  Walker must not see a truncated tree during the walk because of any node
481  *     deletion.
482  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
483  *     in many places in the code to walk the irb list. Thus even if all the
484  *     ires in a bucket have been deleted, we still can't free the radix node
485  *     until the ires have actually been inactive'd (freed).
486  *
487  * Tree traversal - Need to hold the global tree lock in read mode.
488  * Before dropping the global tree lock, need to either increment the ire_refcnt
489  * to ensure that the radix node can't be deleted.
490  *
491  * Tree add - Need to hold the global tree lock in write mode to add a
492  * radix node. To prevent the node from being deleted, increment the
493  * irb_refcnt, after the node is added to the tree. The ire itself is
494  * added later while holding the irb_lock, but not the tree lock.
495  *
496  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
497  * All associated ires must be inactive (i.e. freed), and irb_refcnt
498  * must be zero.
499  *
500  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
501  * global tree lock (read mode) for traversal.
502  *
503  * IPSEC notes :
504  *
505  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
506  * in front of the actual packet. For outbound datagrams, the M_CTL
507  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
508  * information used by the IPSEC code for applying the right level of
509  * protection. The information initialized by IP in the ipsec_out_t
510  * is determined by the per-socket policy or global policy in the system.
511  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
512  * ipsec_info.h) which starts out with nothing in it. It gets filled
513  * with the right information if it goes through the AH/ESP code, which
514  * happens if the incoming packet is secure. The information initialized
515  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
516  * the policy requirements needed by per-socket policy or global policy
517  * is met or not.
518  *
519  * If there is both per-socket policy (set using setsockopt) and there
520  * is also global policy match for the 5 tuples of the socket,
521  * ipsec_override_policy() makes the decision of which one to use.
522  *
523  * For fully connected sockets i.e dst, src [addr, port] is known,
524  * conn_policy_cached is set indicating that policy has been cached.
525  * conn_in_enforce_policy may or may not be set depending on whether
526  * there is a global policy match or per-socket policy match.
527  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
528  * Once the right policy is set on the conn_t, policy cannot change for
529  * this socket. This makes life simpler for TCP (UDP ?) where
530  * re-transmissions go out with the same policy. For symmetry, policy
531  * is cached for fully connected UDP sockets also. Thus if policy is cached,
532  * it also implies that policy is latched i.e policy cannot change
533  * on these sockets. As we have the right policy on the conn, we don't
534  * have to lookup global policy for every outbound and inbound datagram
535  * and thus serving as an optimization. Note that a global policy change
536  * does not affect fully connected sockets if they have policy. If fully
537  * connected sockets did not have any policy associated with it, global
538  * policy change may affect them.
539  *
540  * IP Flow control notes:
541  *
542  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
543  * cannot be sent down to the driver by IP, because of a canput failure, IP
544  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
545  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
546  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
547  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
548  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
549  * the queued messages, and removes the conn from the drain list, if all
550  * messages were drained. It also qenables the next conn in the drain list to
551  * continue the drain process.
552  *
553  * In reality the drain list is not a single list, but a configurable number
554  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
555  * list. If the ip_wsrv of the next qenabled conn does not run, because the
556  * stream closes, ip_close takes responsibility to qenable the next conn in
557  * the drain list. The directly called ip_wput path always does a putq, if
558  * it cannot putnext. Thus synchronization problems are handled between
559  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
560  * functions that manipulate this drain list. Furthermore conn_drain_insert
561  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
562  * running on a queue at any time. conn_drain_tail can be simultaneously called
563  * from both ip_wsrv and ip_close.
564  *
565  * IPQOS notes:
566  *
567  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
568  * and IPQoS modules. IPPF includes hooks in IP at different control points
569  * (callout positions) which direct packets to IPQoS modules for policy
570  * processing. Policies, if present, are global.
571  *
572  * The callout positions are located in the following paths:
573  *		o local_in (packets destined for this host)
574  *		o local_out (packets orginating from this host )
575  *		o fwd_in  (packets forwarded by this m/c - inbound)
576  *		o fwd_out (packets forwarded by this m/c - outbound)
577  * Hooks at these callout points can be enabled/disabled using the ndd variable
578  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
579  * By default all the callout positions are enabled.
580  *
581  * Outbound (local_out)
582  * Hooks are placed in ip_wput_ire and ipsec_out_process.
583  *
584  * Inbound (local_in)
585  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
586  * TCP and UDP fanout routines.
587  *
588  * Forwarding (in and out)
589  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
590  *
591  * IP Policy Framework processing (IPPF processing)
592  * Policy processing for a packet is initiated by ip_process, which ascertains
593  * that the classifier (ipgpc) is loaded and configured, failing which the
594  * packet resumes normal processing in IP. If the clasifier is present, the
595  * packet is acted upon by one or more IPQoS modules (action instances), per
596  * filters configured in ipgpc and resumes normal IP processing thereafter.
597  * An action instance can drop a packet in course of its processing.
598  *
599  * A boolean variable, ip_policy, is used in all the fanout routines that can
600  * invoke ip_process for a packet. This variable indicates if the packet should
601  * to be sent for policy processing. The variable is set to B_TRUE by default,
602  * i.e. when the routines are invoked in the normal ip procesing path for a
603  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
604  * ip_policy is set to B_FALSE for all the routines called in these two
605  * functions because, in the former case,  we don't process loopback traffic
606  * currently while in the latter, the packets have already been processed in
607  * icmp_inbound.
608  *
609  * Zones notes:
610  *
611  * The partitioning rules for networking are as follows:
612  * 1) Packets coming from a zone must have a source address belonging to that
613  * zone.
614  * 2) Packets coming from a zone can only be sent on a physical interface on
615  * which the zone has an IP address.
616  * 3) Between two zones on the same machine, packet delivery is only allowed if
617  * there's a matching route for the destination and zone in the forwarding
618  * table.
619  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
620  * different zones can bind to the same port with the wildcard address
621  * (INADDR_ANY).
622  *
623  * The granularity of interface partitioning is at the logical interface level.
624  * Therefore, every zone has its own IP addresses, and incoming packets can be
625  * attributed to a zone unambiguously. A logical interface is placed into a zone
626  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
627  * structure. Rule (1) is implemented by modifying the source address selection
628  * algorithm so that the list of eligible addresses is filtered based on the
629  * sending process zone.
630  *
631  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
632  * across all zones, depending on their type. Here is the break-up:
633  *
634  * IRE type				Shared/exclusive
635  * --------				----------------
636  * IRE_BROADCAST			Exclusive
637  * IRE_DEFAULT (default routes)		Shared (*)
638  * IRE_LOCAL				Exclusive (x)
639  * IRE_LOOPBACK				Exclusive
640  * IRE_PREFIX (net routes)		Shared (*)
641  * IRE_CACHE				Exclusive
642  * IRE_IF_NORESOLVER (interface routes)	Exclusive
643  * IRE_IF_RESOLVER (interface routes)	Exclusive
644  * IRE_HOST (host routes)		Shared (*)
645  *
646  * (*) A zone can only use a default or off-subnet route if the gateway is
647  * directly reachable from the zone, that is, if the gateway's address matches
648  * one of the zone's logical interfaces.
649  *
650  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
651  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
652  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
653  * address of the zone itself (the destination). Since IRE_LOCAL is used
654  * for communication between zones, ip_wput_ire has special logic to set
655  * the right source address when sending using an IRE_LOCAL.
656  *
657  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
658  * ire_cache_lookup restricts loopback using an IRE_LOCAL
659  * between zone to the case when L2 would have conceptually looped the packet
660  * back, i.e. the loopback which is required since neither Ethernet drivers
661  * nor Ethernet hardware loops them back. This is the case when the normal
662  * routes (ignoring IREs with different zoneids) would send out the packet on
663  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
664  * associated.
665  *
666  * Multiple zones can share a common broadcast address; typically all zones
667  * share the 255.255.255.255 address. Incoming as well as locally originated
668  * broadcast packets must be dispatched to all the zones on the broadcast
669  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
670  * since some zones may not be on the 10.16.72/24 network. To handle this, each
671  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
672  * sent to every zone that has an IRE_BROADCAST entry for the destination
673  * address on the input ill, see conn_wantpacket().
674  *
675  * Applications in different zones can join the same multicast group address.
676  * For IPv4, group memberships are per-logical interface, so they're already
677  * inherently part of a zone. For IPv6, group memberships are per-physical
678  * interface, so we distinguish IPv6 group memberships based on group address,
679  * interface and zoneid. In both cases, received multicast packets are sent to
680  * every zone for which a group membership entry exists. On IPv6 we need to
681  * check that the target zone still has an address on the receiving physical
682  * interface; it could have been removed since the application issued the
683  * IPV6_JOIN_GROUP.
684  */
685 
686 /*
687  * Squeue Fanout flags:
688  *	0: No fanout.
689  *	1: Fanout across all squeues
690  */
691 boolean_t	ip_squeue_fanout = 0;
692 
693 /*
694  * Maximum dups allowed per packet.
695  */
696 uint_t ip_max_frag_dups = 10;
697 
698 #define	IS_SIMPLE_IPH(ipha)						\
699 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
700 
701 /* RFC1122 Conformance */
702 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
703 
704 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
705 
706 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
707 
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
709 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t);
712 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
713     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
714 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
715 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
716 		    mblk_t *, int);
717 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
718 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
719 		    ill_t *, zoneid_t);
720 static void	icmp_options_update(ipha_t *);
721 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t);
722 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
723 		    zoneid_t zoneid);
724 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
725 static void	icmp_redirect(mblk_t *);
726 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
727 
728 static void	ip_arp_news(queue_t *, mblk_t *);
729 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
730 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
731 char		*ip_dot_addr(ipaddr_t, char *);
732 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
733 int		ip_close(queue_t *, int);
734 static char	*ip_dot_saddr(uchar_t *, char *);
735 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
736 		    boolean_t, boolean_t, ill_t *, zoneid_t);
737 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
738 		    boolean_t, boolean_t, zoneid_t);
739 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
740 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
741 static void	ip_lrput(queue_t *, mblk_t *);
742 ipaddr_t	ip_massage_options(ipha_t *);
743 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
744 ipaddr_t	ip_net_mask(ipaddr_t);
745 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
746 		    zoneid_t);
747 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
748 		    conn_t *, uint32_t, zoneid_t);
749 char		*ip_nv_lookup(nv_t *, int);
750 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
751 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
752 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
754 			    size_t);
755 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
756 void	ip_rput(queue_t *, mblk_t *);
757 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
758 		    void *dummy_arg);
759 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
760 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
761 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
762 			    ire_t *);
763 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
764 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
765 		    uint16_t *);
766 int		ip_snmp_get(queue_t *, mblk_t *);
767 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
768 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
769 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
770 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
771 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
772 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
773 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
775 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
777 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
778 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
779 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
780 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
781 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
782 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
783 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
784 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
785 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
786 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
787 static boolean_t	ip_source_routed(ipha_t *);
788 static boolean_t	ip_source_route_included(ipha_t *);
789 
790 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
791 		    zoneid_t);
792 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
793 static void	ip_wput_local_options(ipha_t *);
794 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
795 		    zoneid_t);
796 
797 static void	conn_drain_init(void);
798 static void	conn_drain_fini(void);
799 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
800 
801 static void	conn_walk_drain(void);
802 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
803     zoneid_t);
804 
805 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
806     zoneid_t);
807 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
808     void *dummy_arg);
809 
810 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
811 
812 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
813     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
814     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
815 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
816 
817 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
818 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
819     caddr_t, cred_t *);
820 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
821     caddr_t cp, cred_t *cr);
822 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
823     cred_t *);
824 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
825     caddr_t cp, cred_t *cr);
826 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
827     cred_t *);
828 static squeue_func_t ip_squeue_switch(int);
829 
830 static void	ip_kstat_init(void);
831 static void	ip_kstat_fini(void);
832 static int	ip_kstat_update(kstat_t *kp, int rw);
833 static void	icmp_kstat_init(void);
834 static void	icmp_kstat_fini(void);
835 static int	icmp_kstat_update(kstat_t *kp, int rw);
836 
837 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
838 
839 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
840     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
841 
842 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
843     ipha_t *, ill_t *, boolean_t);
844 
845 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
846 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
847 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
848 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
849 
850 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
851 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
852 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
853 
854 /* How long, in seconds, we allow frags to hang around. */
855 #define	IP_FRAG_TIMEOUT	60
856 
857 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
858 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
859 
860 /*
861  * Threshold which determines whether MDT should be used when
862  * generating IP fragments; payload size must be greater than
863  * this threshold for MDT to take place.
864  */
865 #define	IP_WPUT_FRAG_MDT_MIN	32768
866 
867 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
868 
869 /* Protected by ip_mi_lock */
870 static void	*ip_g_head;		/* Instance Data List Head */
871 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
872 
873 /* Only modified during _init and _fini thus no locking is needed. */
874 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
875 
876 
877 static long ip_rput_pullups;
878 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
879 
880 vmem_t *ip_minor_arena;
881 
882 /*
883  * MIB-2 stuff for SNMP (both IP and ICMP)
884  */
885 mib2_ip_t	ip_mib;
886 mib2_icmp_t	icmp_mib;
887 
888 #ifdef DEBUG
889 uint32_t ipsechw_debug = 0;
890 #endif
891 
892 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
893 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
894 
895 uint_t	loopback_packets = 0;
896 
897 /*
898  * Multirouting/CGTP stuff
899  */
900 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
901 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
902 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
903 /* Interval (in ms) between consecutive 'bad MTU' warnings */
904 hrtime_t ip_multirt_log_interval = 1000;
905 /* Time since last warning issued. */
906 static hrtime_t	multirt_bad_mtu_last_time = 0;
907 
908 kmutex_t ip_trash_timer_lock;
909 krwlock_t ip_g_nd_lock;
910 
911 /*
912  * XXX following really should only be in a header. Would need more
913  * header and .c clean up first.
914  */
915 extern optdb_obj_t	ip_opt_obj;
916 
917 ulong_t ip_squeue_enter_unbound = 0;
918 
919 /*
920  * Named Dispatch Parameter Table.
921  * All of these are alterable, within the min/max values given, at run time.
922  */
923 static ipparam_t	lcl_param_arr[] = {
924 	/* min	max	value	name */
925 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
926 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
927 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
928 	{  0,	1,	0,	"ip_respond_to_timestamp"},
929 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
930 	{  0,	1,	1,	"ip_send_redirects"},
931 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
932 	{  0,	10,	0,	"ip_debug"},
933 	{  0,	10,	0,	"ip_mrtdebug"},
934 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
935 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
936 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
937 	{  1,	255,	255,	"ip_def_ttl" },
938 	{  0,	1,	0,	"ip_forward_src_routed"},
939 	{  0,	256,	32,	"ip_wroff_extra" },
940 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
941 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
942 	{  0,	1,	1,	"ip_path_mtu_discovery" },
943 	{  0,	240,	30,	"ip_ignore_delete_time" },
944 	{  0,	1,	0,	"ip_ignore_redirect" },
945 	{  0,	1,	1,	"ip_output_queue" },
946 	{  1,	254,	1,	"ip_broadcast_ttl" },
947 	{  0,	99999,	100,	"ip_icmp_err_interval" },
948 	{  1,	99999,	10,	"ip_icmp_err_burst" },
949 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
950 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
951 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
952 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
953 	{  0,	1,	1,	"icmp_accept_clear_messages" },
954 	{  0,	1,	1,	"igmp_accept_clear_messages" },
955 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
956 				"ip_ndp_delay_first_probe_time"},
957 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
958 				"ip_ndp_max_unicast_solicit"},
959 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
960 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
961 	{  0,	1,	0,	"ip6_forward_src_routed"},
962 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
963 	{  0,	1,	1,	"ip6_send_redirects"},
964 	{  0,	1,	0,	"ip6_ignore_redirect" },
965 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
966 
967 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
968 
969 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
970 
971 	{  0,	1,	1,	"pim_accept_clear_messages" },
972 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
973 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
974 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
975 	{  0,	15,	0,	"ip_policy_mask" },
976 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
977 	{  0,	255,	1,	"ip_multirt_ttl" },
978 	{  0,	1,	1,	"ip_multidata_outbound" },
979 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
980 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
981 	{  0,	1000,	1,	"ip_max_temp_defend" },
982 	{  0,	1000,	3,	"ip_max_defend" },
983 	{  0,	999999,	30,	"ip_defend_interval" },
984 	{  0,	3600000, 300000, "ip_dup_recovery" },
985 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
986 #ifdef DEBUG
987 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
988 #endif
989 };
990 
991 ipparam_t	*ip_param_arr = lcl_param_arr;
992 
993 /* Extended NDP table */
994 static ipndp_t	lcl_ndp_arr[] = {
995 	/* getf			setf		data			name */
996 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
997 	    "ip_forwarding" },
998 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
999 	    "ip6_forwarding" },
1000 	{  ip_ill_report,	NULL,		NULL,
1001 	    "ip_ill_status" },
1002 	{  ip_ipif_report,	NULL,		NULL,
1003 	    "ip_ipif_status" },
1004 	{  ip_ire_report,	NULL,		NULL,
1005 	    "ipv4_ire_status" },
1006 	{  ip_ire_report_mrtun,	NULL,		NULL,
1007 	    "ipv4_mrtun_ire_status" },
1008 	{  ip_ire_report_srcif,	NULL,		NULL,
1009 	    "ipv4_srcif_ire_status" },
1010 	{  ip_ire_report_v6,	NULL,		NULL,
1011 	    "ipv6_ire_status" },
1012 	{  ip_conn_report,	NULL,		NULL,
1013 	    "ip_conn_status" },
1014 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1015 	    "ip_rput_pullups" },
1016 	{  ndp_report,		NULL,		NULL,
1017 	    "ip_ndp_cache_report" },
1018 	{  ip_srcid_report,	NULL,		NULL,
1019 	    "ip_srcid_status" },
1020 	{ ip_param_generic_get, ip_squeue_profile_set,
1021 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
1022 	{ ip_param_generic_get, ip_squeue_bind_set,
1023 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
1024 	{ ip_param_generic_get, ip_input_proc_set,
1025 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1026 	{ ip_param_generic_get, ip_int_set,
1027 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1028 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
1029 	    "ip_cgtp_filter" },
1030 	{ ip_param_generic_get, ip_int_set,
1031 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
1032 };
1033 
1034 /*
1035  * ip_g_forward controls IP forwarding.  It takes two values:
1036  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
1037  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
1038  *
1039  * RFC1122 says there must be a configuration switch to control forwarding,
1040  * but that the default MUST be to not forward packets ever.  Implicit
1041  * control based on configuration of multiple interfaces MUST NOT be
1042  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
1043  * and, in fact, it was the default.  That capability is now provided in the
1044  * /etc/rc2.d/S69inet script.
1045  */
1046 int ip_g_forward = IP_FORWARD_DEFAULT;
1047 
1048 /* It also has an IPv6 counterpart. */
1049 
1050 int ipv6_forward = IP_FORWARD_DEFAULT;
1051 
1052 /*
1053  * Table of IP ioctls encoding the various properties of the ioctl and
1054  * indexed based on the last byte of the ioctl command. Occasionally there
1055  * is a clash, and there is more than 1 ioctl with the same last byte.
1056  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1057  * ioctls are encoded in the misc table. An entry in the ndx table is
1058  * retrieved by indexing on the last byte of the ioctl command and comparing
1059  * the ioctl command with the value in the ndx table. In the event of a
1060  * mismatch the misc table is then searched sequentially for the desired
1061  * ioctl command.
1062  *
1063  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1064  */
1065 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1066 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 
1077 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1078 			MISC_CMD, ip_siocaddrt, NULL },
1079 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1080 			MISC_CMD, ip_siocdelrt, NULL },
1081 
1082 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1083 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1084 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1085 			IF_CMD, ip_sioctl_get_addr, NULL },
1086 
1087 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1088 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1089 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1090 			IPI_GET_CMD | IPI_REPL,
1091 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1092 
1093 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1094 			IPI_PRIV | IPI_WR | IPI_REPL,
1095 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1096 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1097 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1098 			IF_CMD, ip_sioctl_get_flags, NULL },
1099 
1100 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 
1103 	/* copyin size cannot be coded for SIOCGIFCONF */
1104 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1105 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1106 
1107 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1108 			IF_CMD, ip_sioctl_mtu, NULL },
1109 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1110 			IF_CMD, ip_sioctl_get_mtu, NULL },
1111 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1112 			IPI_GET_CMD | IPI_REPL,
1113 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1114 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1115 			IF_CMD, ip_sioctl_brdaddr, NULL },
1116 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1117 			IPI_GET_CMD | IPI_REPL,
1118 			IF_CMD, ip_sioctl_get_netmask, NULL },
1119 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1120 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1121 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1122 			IPI_GET_CMD | IPI_REPL,
1123 			IF_CMD, ip_sioctl_get_metric, NULL },
1124 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1125 			IF_CMD, ip_sioctl_metric, NULL },
1126 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 
1128 	/* See 166-168 below for extended SIOC*XARP ioctls */
1129 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1130 			MISC_CMD, ip_sioctl_arp, NULL },
1131 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1132 			MISC_CMD, ip_sioctl_arp, NULL },
1133 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1134 			MISC_CMD, ip_sioctl_arp, NULL },
1135 
1136 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 
1158 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1159 			MISC_CMD, if_unitsel, if_unitsel_restart },
1160 
1161 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 
1180 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1181 			IPI_PRIV | IPI_WR | IPI_MODOK,
1182 			IF_CMD, ip_sioctl_sifname, NULL },
1183 
1184 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1190 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 
1198 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1199 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1200 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1201 			IF_CMD, ip_sioctl_get_muxid, NULL },
1202 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1203 			IPI_PRIV | IPI_WR | IPI_REPL,
1204 			IF_CMD, ip_sioctl_muxid, NULL },
1205 
1206 	/* Both if and lif variants share same func */
1207 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1208 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1209 	/* Both if and lif variants share same func */
1210 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1211 			IPI_PRIV | IPI_WR | IPI_REPL,
1212 			IF_CMD, ip_sioctl_slifindex, NULL },
1213 
1214 	/* copyin size cannot be coded for SIOCGIFCONF */
1215 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1216 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1217 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1218 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1219 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1220 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1221 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1222 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1223 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1226 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1227 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1228 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1229 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1230 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1231 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1232 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1233 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1234 
1235 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1236 			IPI_PRIV | IPI_WR | IPI_REPL,
1237 			LIF_CMD, ip_sioctl_removeif,
1238 			ip_sioctl_removeif_restart },
1239 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1240 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1241 			LIF_CMD, ip_sioctl_addif, NULL },
1242 #define	SIOCLIFADDR_NDX 112
1243 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1244 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1245 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1246 			IPI_GET_CMD | IPI_REPL,
1247 			LIF_CMD, ip_sioctl_get_addr, NULL },
1248 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1249 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1250 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1251 			IPI_GET_CMD | IPI_REPL,
1252 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1253 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1254 			IPI_PRIV | IPI_WR | IPI_REPL,
1255 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1256 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1257 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1258 			LIF_CMD, ip_sioctl_get_flags, NULL },
1259 
1260 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1261 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1262 
1263 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1264 			ip_sioctl_get_lifconf, NULL },
1265 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1266 			LIF_CMD, ip_sioctl_mtu, NULL },
1267 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1268 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1269 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1270 			IPI_GET_CMD | IPI_REPL,
1271 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1272 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1273 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1274 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1275 			IPI_GET_CMD | IPI_REPL,
1276 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1277 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1278 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1279 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1280 			IPI_GET_CMD | IPI_REPL,
1281 			LIF_CMD, ip_sioctl_get_metric, NULL },
1282 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1283 			LIF_CMD, ip_sioctl_metric, NULL },
1284 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1285 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1286 			LIF_CMD, ip_sioctl_slifname,
1287 			ip_sioctl_slifname_restart },
1288 
1289 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1290 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1291 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1292 			IPI_GET_CMD | IPI_REPL,
1293 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1294 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1295 			IPI_PRIV | IPI_WR | IPI_REPL,
1296 			LIF_CMD, ip_sioctl_muxid, NULL },
1297 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1298 			IPI_GET_CMD | IPI_REPL,
1299 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1300 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1301 			IPI_PRIV | IPI_WR | IPI_REPL,
1302 			LIF_CMD, ip_sioctl_slifindex, 0 },
1303 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1304 			LIF_CMD, ip_sioctl_token, NULL },
1305 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1306 			IPI_GET_CMD | IPI_REPL,
1307 			LIF_CMD, ip_sioctl_get_token, NULL },
1308 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1309 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1310 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1311 			IPI_GET_CMD | IPI_REPL,
1312 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1313 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1314 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1315 
1316 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1317 			IPI_GET_CMD | IPI_REPL,
1318 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1319 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1320 			LIF_CMD, ip_siocdelndp_v6, NULL },
1321 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1322 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1323 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1324 			LIF_CMD, ip_siocsetndp_v6, NULL },
1325 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1326 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1327 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1328 			MISC_CMD, ip_sioctl_tonlink, NULL },
1329 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1330 			MISC_CMD, ip_sioctl_tmysite, NULL },
1331 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1332 			TUN_CMD, ip_sioctl_tunparam, NULL },
1333 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1334 			IPI_PRIV | IPI_WR,
1335 			TUN_CMD, ip_sioctl_tunparam, NULL },
1336 
1337 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1338 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1339 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1340 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1341 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1342 
1343 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1344 			IPI_PRIV | IPI_WR | IPI_REPL,
1345 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1346 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1347 			IPI_PRIV | IPI_WR | IPI_REPL,
1348 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1349 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1350 			IPI_PRIV | IPI_WR,
1351 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1352 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1353 			IPI_GET_CMD | IPI_REPL,
1354 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1355 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1356 			IPI_GET_CMD | IPI_REPL,
1357 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1358 
1359 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1360 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1361 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1362 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1363 
1364 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1365 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1366 
1367 	/* These are handled in ip_sioctl_copyin_setup itself */
1368 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1369 			MISC_CMD, NULL, NULL },
1370 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1371 			MISC_CMD, NULL, NULL },
1372 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1373 
1374 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1375 			ip_sioctl_get_lifconf, NULL },
1376 
1377 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1378 			MISC_CMD, ip_sioctl_xarp, NULL },
1379 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1380 			MISC_CMD, ip_sioctl_xarp, NULL },
1381 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1382 			MISC_CMD, ip_sioctl_xarp, NULL },
1383 
1384 	/* SIOCPOPSOCKFS is not handled by IP */
1385 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1386 
1387 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1388 			IPI_GET_CMD | IPI_REPL,
1389 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1390 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1391 			IPI_PRIV | IPI_WR | IPI_REPL,
1392 			LIF_CMD, ip_sioctl_slifzone,
1393 			ip_sioctl_slifzone_restart },
1394 	/* 172-174 are SCTP ioctls and not handled by IP */
1395 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1396 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1397 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1398 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1399 			IPI_GET_CMD, LIF_CMD,
1400 			ip_sioctl_get_lifusesrc, 0 },
1401 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1402 			IPI_PRIV | IPI_WR,
1403 			LIF_CMD, ip_sioctl_slifusesrc,
1404 			NULL },
1405 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1406 			ip_sioctl_get_lifsrcof, NULL },
1407 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1408 			MISC_CMD, ip_sioctl_msfilter, NULL },
1409 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1410 			MISC_CMD, ip_sioctl_msfilter, NULL },
1411 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1412 			MISC_CMD, ip_sioctl_msfilter, NULL },
1413 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1414 			MISC_CMD, ip_sioctl_msfilter, NULL },
1415 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1416 			ip_sioctl_set_ipmpfailback, NULL }
1417 };
1418 
1419 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1420 
1421 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1422 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1423 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1424 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1425 		TUN_CMD, ip_sioctl_tunparam, NULL },
1426 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1427 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1428 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1429 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1430 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1431 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1432 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1433 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1434 		MISC_CMD, mrt_ioctl},
1435 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1436 		MISC_CMD, mrt_ioctl},
1437 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1438 		MISC_CMD, mrt_ioctl}
1439 };
1440 
1441 int ip_misc_ioctl_count =
1442     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1443 
1444 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1445 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1446 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1447 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1448 					/* Settable in /etc/system */
1449 uint_t	ip_redirect_cnt;		/* Num of redirect routes in ftable */
1450 
1451 /* Defined in ip_ire.c */
1452 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1453 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1454 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1455 
1456 static nv_t	ire_nv_arr[] = {
1457 	{ IRE_BROADCAST, "BROADCAST" },
1458 	{ IRE_LOCAL, "LOCAL" },
1459 	{ IRE_LOOPBACK, "LOOPBACK" },
1460 	{ IRE_CACHE, "CACHE" },
1461 	{ IRE_DEFAULT, "DEFAULT" },
1462 	{ IRE_PREFIX, "PREFIX" },
1463 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1464 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1465 	{ IRE_HOST, "HOST" },
1466 	{ 0 }
1467 };
1468 
1469 nv_t	*ire_nv_tbl = ire_nv_arr;
1470 
1471 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1472 extern krwlock_t ipsec_capab_ills_lock;
1473 
1474 /* Defined in ip_netinfo.c */
1475 extern ddi_taskq_t	*eventq_queue_nic;
1476 
1477 /* Packet dropper for IP IPsec processing failures */
1478 ipdropper_t ip_dropper;
1479 
1480 /* Simple ICMP IP Header Template */
1481 static ipha_t icmp_ipha = {
1482 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1483 };
1484 
1485 struct module_info ip_mod_info = {
1486 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1487 };
1488 
1489 /*
1490  * Duplicate static symbols within a module confuses mdb; so we avoid the
1491  * problem by making the symbols here distinct from those in udp.c.
1492  */
1493 
1494 static struct qinit iprinit = {
1495 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1496 	&ip_mod_info
1497 };
1498 
1499 static struct qinit ipwinit = {
1500 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1501 	&ip_mod_info
1502 };
1503 
1504 static struct qinit iplrinit = {
1505 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1506 	&ip_mod_info
1507 };
1508 
1509 static struct qinit iplwinit = {
1510 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1511 	&ip_mod_info
1512 };
1513 
1514 struct streamtab ipinfo = {
1515 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1516 };
1517 
1518 #ifdef	DEBUG
1519 static boolean_t skip_sctp_cksum = B_FALSE;
1520 #endif
1521 
1522 /*
1523  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1524  * ip_rput_v6(), ip_output(), etc.  If the message
1525  * block already has a M_CTL at the front of it, then simply set the zoneid
1526  * appropriately.
1527  */
1528 mblk_t *
1529 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid)
1530 {
1531 	mblk_t		*first_mp;
1532 	ipsec_out_t	*io;
1533 
1534 	ASSERT(zoneid != ALL_ZONES);
1535 	if (mp->b_datap->db_type == M_CTL) {
1536 		io = (ipsec_out_t *)mp->b_rptr;
1537 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1538 		io->ipsec_out_zoneid = zoneid;
1539 		return (mp);
1540 	}
1541 
1542 	first_mp = ipsec_alloc_ipsec_out();
1543 	if (first_mp == NULL)
1544 		return (NULL);
1545 	io = (ipsec_out_t *)first_mp->b_rptr;
1546 	/* This is not a secure packet */
1547 	io->ipsec_out_secure = B_FALSE;
1548 	io->ipsec_out_zoneid = zoneid;
1549 	first_mp->b_cont = mp;
1550 	return (first_mp);
1551 }
1552 
1553 /*
1554  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1555  */
1556 mblk_t *
1557 ip_copymsg(mblk_t *mp)
1558 {
1559 	mblk_t *nmp;
1560 	ipsec_info_t *in;
1561 
1562 	if (mp->b_datap->db_type != M_CTL)
1563 		return (copymsg(mp));
1564 
1565 	in = (ipsec_info_t *)mp->b_rptr;
1566 
1567 	/*
1568 	 * Note that M_CTL is also used for delivering ICMP error messages
1569 	 * upstream to transport layers.
1570 	 */
1571 	if (in->ipsec_info_type != IPSEC_OUT &&
1572 	    in->ipsec_info_type != IPSEC_IN)
1573 		return (copymsg(mp));
1574 
1575 	nmp = copymsg(mp->b_cont);
1576 
1577 	if (in->ipsec_info_type == IPSEC_OUT)
1578 		return (ipsec_out_tag(mp, nmp));
1579 	else
1580 		return (ipsec_in_tag(mp, nmp));
1581 }
1582 
1583 /* Generate an ICMP fragmentation needed message. */
1584 static void
1585 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid)
1586 {
1587 	icmph_t	icmph;
1588 	mblk_t *first_mp;
1589 	boolean_t mctl_present;
1590 
1591 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1592 
1593 	if (!(mp = icmp_pkt_err_ok(mp))) {
1594 		if (mctl_present)
1595 			freeb(first_mp);
1596 		return;
1597 	}
1598 
1599 	bzero(&icmph, sizeof (icmph_t));
1600 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1601 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1602 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1603 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1604 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1605 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
1606 }
1607 
1608 /*
1609  * icmp_inbound deals with ICMP messages in the following ways.
1610  *
1611  * 1) It needs to send a reply back and possibly delivering it
1612  *    to the "interested" upper clients.
1613  * 2) It needs to send it to the upper clients only.
1614  * 3) It needs to change some values in IP only.
1615  * 4) It needs to change some values in IP and upper layers e.g TCP.
1616  *
1617  * We need to accomodate icmp messages coming in clear until we get
1618  * everything secure from the wire. If icmp_accept_clear_messages
1619  * is zero we check with the global policy and act accordingly. If
1620  * it is non-zero, we accept the message without any checks. But
1621  * *this does not mean* that this will be delivered to the upper
1622  * clients. By accepting we might send replies back, change our MTU
1623  * value etc. but delivery to the ULP/clients depends on their policy
1624  * dispositions.
1625  *
1626  * We handle the above 4 cases in the context of IPSEC in the
1627  * following way :
1628  *
1629  * 1) Send the reply back in the same way as the request came in.
1630  *    If it came in encrypted, it goes out encrypted. If it came in
1631  *    clear, it goes out in clear. Thus, this will prevent chosen
1632  *    plain text attack.
1633  * 2) The client may or may not expect things to come in secure.
1634  *    If it comes in secure, the policy constraints are checked
1635  *    before delivering it to the upper layers. If it comes in
1636  *    clear, ipsec_inbound_accept_clear will decide whether to
1637  *    accept this in clear or not. In both the cases, if the returned
1638  *    message (IP header + 8 bytes) that caused the icmp message has
1639  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1640  *    sending up. If there are only 8 bytes of returned message, then
1641  *    upper client will not be notified.
1642  * 3) Check with global policy to see whether it matches the constaints.
1643  *    But this will be done only if icmp_accept_messages_in_clear is
1644  *    zero.
1645  * 4) If we need to change both in IP and ULP, then the decision taken
1646  *    while affecting the values in IP and while delivering up to TCP
1647  *    should be the same.
1648  *
1649  * 	There are two cases.
1650  *
1651  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1652  *	   failed), we will not deliver it to the ULP, even though they
1653  *	   are *willing* to accept in *clear*. This is fine as our global
1654  *	   disposition to icmp messages asks us reject the datagram.
1655  *
1656  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1657  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1658  *	   to deliver it to ULP (policy failed), it can lead to
1659  *	   consistency problems. The cases known at this time are
1660  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1661  *	   values :
1662  *
1663  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1664  *	     and Upper layer rejects. Then the communication will
1665  *	     come to a stop. This is solved by making similar decisions
1666  *	     at both levels. Currently, when we are unable to deliver
1667  *	     to the Upper Layer (due to policy failures) while IP has
1668  *	     adjusted ire_max_frag, the next outbound datagram would
1669  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1670  *	     will be with the right level of protection. Thus the right
1671  *	     value will be communicated even if we are not able to
1672  *	     communicate when we get from the wire initially. But this
1673  *	     assumes there would be at least one outbound datagram after
1674  *	     IP has adjusted its ire_max_frag value. To make things
1675  *	     simpler, we accept in clear after the validation of
1676  *	     AH/ESP headers.
1677  *
1678  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1679  *	     upper layer depending on the level of protection the upper
1680  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1681  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1682  *	     should be accepted in clear when the Upper layer expects secure.
1683  *	     Thus the communication may get aborted by some bad ICMP
1684  *	     packets.
1685  *
1686  * IPQoS Notes:
1687  * The only instance when a packet is sent for processing is when there
1688  * isn't an ICMP client and if we are interested in it.
1689  * If there is a client, IPPF processing will take place in the
1690  * ip_fanout_proto routine.
1691  *
1692  * Zones notes:
1693  * The packet is only processed in the context of the specified zone: typically
1694  * only this zone will reply to an echo request, and only interested clients in
1695  * this zone will receive a copy of the packet. This means that the caller must
1696  * call icmp_inbound() for each relevant zone.
1697  */
1698 static void
1699 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1700     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1701     ill_t *recv_ill, zoneid_t zoneid)
1702 {
1703 	icmph_t	*icmph;
1704 	ipha_t	*ipha;
1705 	int	iph_hdr_length;
1706 	int	hdr_length;
1707 	boolean_t	interested;
1708 	uint32_t	ts;
1709 	uchar_t	*wptr;
1710 	ipif_t	*ipif;
1711 	mblk_t *first_mp;
1712 	ipsec_in_t *ii;
1713 	ire_t *src_ire;
1714 	boolean_t onlink;
1715 	timestruc_t now;
1716 	uint32_t ill_index;
1717 
1718 	ASSERT(ill != NULL);
1719 
1720 	first_mp = mp;
1721 	if (mctl_present) {
1722 		mp = first_mp->b_cont;
1723 		ASSERT(mp != NULL);
1724 	}
1725 
1726 	ipha = (ipha_t *)mp->b_rptr;
1727 	if (icmp_accept_clear_messages == 0) {
1728 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1729 		    ipha, NULL, mctl_present);
1730 		if (first_mp == NULL)
1731 			return;
1732 	}
1733 
1734 	/*
1735 	 * On a labeled system, we have to check whether the zone itself is
1736 	 * permitted to receive raw traffic.
1737 	 */
1738 	if (is_system_labeled()) {
1739 		if (zoneid == ALL_ZONES)
1740 			zoneid = tsol_packet_to_zoneid(mp);
1741 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1742 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1743 			    zoneid));
1744 			BUMP_MIB(&icmp_mib, icmpInErrors);
1745 			freemsg(first_mp);
1746 			return;
1747 		}
1748 	}
1749 
1750 	/*
1751 	 * We have accepted the ICMP message. It means that we will
1752 	 * respond to the packet if needed. It may not be delivered
1753 	 * to the upper client depending on the policy constraints
1754 	 * and the disposition in ipsec_inbound_accept_clear.
1755 	 */
1756 
1757 	ASSERT(ill != NULL);
1758 
1759 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1760 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1761 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1762 		/* Last chance to get real. */
1763 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1764 			BUMP_MIB(&icmp_mib, icmpInErrors);
1765 			freemsg(first_mp);
1766 			return;
1767 		}
1768 		/* Refresh iph following the pullup. */
1769 		ipha = (ipha_t *)mp->b_rptr;
1770 	}
1771 	/* ICMP header checksum, including checksum field, should be zero. */
1772 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1773 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1774 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1775 		freemsg(first_mp);
1776 		return;
1777 	}
1778 	/* The IP header will always be a multiple of four bytes */
1779 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1780 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1781 	    icmph->icmph_code));
1782 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1783 	/* We will set "interested" to "true" if we want a copy */
1784 	interested = B_FALSE;
1785 	switch (icmph->icmph_type) {
1786 	case ICMP_ECHO_REPLY:
1787 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1788 		break;
1789 	case ICMP_DEST_UNREACHABLE:
1790 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1791 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1792 		interested = B_TRUE;	/* Pass up to transport */
1793 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1794 		break;
1795 	case ICMP_SOURCE_QUENCH:
1796 		interested = B_TRUE;	/* Pass up to transport */
1797 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1798 		break;
1799 	case ICMP_REDIRECT:
1800 		if (!ip_ignore_redirect)
1801 			interested = B_TRUE;
1802 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1803 		break;
1804 	case ICMP_ECHO_REQUEST:
1805 		/*
1806 		 * Whether to respond to echo requests that come in as IP
1807 		 * broadcasts or as IP multicast is subject to debate
1808 		 * (what isn't?).  We aim to please, you pick it.
1809 		 * Default is do it.
1810 		 */
1811 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1812 			/* unicast: always respond */
1813 			interested = B_TRUE;
1814 		} else if (CLASSD(ipha->ipha_dst)) {
1815 			/* multicast: respond based on tunable */
1816 			interested = ip_g_resp_to_echo_mcast;
1817 		} else if (broadcast) {
1818 			/* broadcast: respond based on tunable */
1819 			interested = ip_g_resp_to_echo_bcast;
1820 		}
1821 		BUMP_MIB(&icmp_mib, icmpInEchos);
1822 		break;
1823 	case ICMP_ROUTER_ADVERTISEMENT:
1824 	case ICMP_ROUTER_SOLICITATION:
1825 		break;
1826 	case ICMP_TIME_EXCEEDED:
1827 		interested = B_TRUE;	/* Pass up to transport */
1828 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1829 		break;
1830 	case ICMP_PARAM_PROBLEM:
1831 		interested = B_TRUE;	/* Pass up to transport */
1832 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1833 		break;
1834 	case ICMP_TIME_STAMP_REQUEST:
1835 		/* Response to Time Stamp Requests is local policy. */
1836 		if (ip_g_resp_to_timestamp &&
1837 		    /* So is whether to respond if it was an IP broadcast. */
1838 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1839 			int tstamp_len = 3 * sizeof (uint32_t);
1840 
1841 			if (wptr +  tstamp_len > mp->b_wptr) {
1842 				if (!pullupmsg(mp, wptr + tstamp_len -
1843 				    mp->b_rptr)) {
1844 					BUMP_MIB(&ip_mib, ipInDiscards);
1845 					freemsg(first_mp);
1846 					return;
1847 				}
1848 				/* Refresh ipha following the pullup. */
1849 				ipha = (ipha_t *)mp->b_rptr;
1850 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1851 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1852 			}
1853 			interested = B_TRUE;
1854 		}
1855 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1856 		break;
1857 	case ICMP_TIME_STAMP_REPLY:
1858 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1859 		break;
1860 	case ICMP_INFO_REQUEST:
1861 		/* Per RFC 1122 3.2.2.7, ignore this. */
1862 	case ICMP_INFO_REPLY:
1863 		break;
1864 	case ICMP_ADDRESS_MASK_REQUEST:
1865 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1866 		    /* TODO m_pullup of complete header? */
1867 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1868 			interested = B_TRUE;
1869 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1870 		break;
1871 	case ICMP_ADDRESS_MASK_REPLY:
1872 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1873 		break;
1874 	default:
1875 		interested = B_TRUE;	/* Pass up to transport */
1876 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1877 		break;
1878 	}
1879 	/* See if there is an ICMP client. */
1880 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1881 		/* If there is an ICMP client and we want one too, copy it. */
1882 		mblk_t *first_mp1;
1883 
1884 		if (!interested) {
1885 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1886 			    ip_policy, recv_ill, zoneid);
1887 			return;
1888 		}
1889 		first_mp1 = ip_copymsg(first_mp);
1890 		if (first_mp1 != NULL) {
1891 			ip_fanout_proto(q, first_mp1, ill, ipha,
1892 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1893 		}
1894 	} else if (!interested) {
1895 		freemsg(first_mp);
1896 		return;
1897 	} else {
1898 		/*
1899 		 * Initiate policy processing for this packet if ip_policy
1900 		 * is true.
1901 		 */
1902 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1903 			ill_index = ill->ill_phyint->phyint_ifindex;
1904 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1905 			if (mp == NULL) {
1906 				if (mctl_present) {
1907 					freeb(first_mp);
1908 				}
1909 				BUMP_MIB(&icmp_mib, icmpInErrors);
1910 				return;
1911 			}
1912 		}
1913 	}
1914 	/* We want to do something with it. */
1915 	/* Check db_ref to make sure we can modify the packet. */
1916 	if (mp->b_datap->db_ref > 1) {
1917 		mblk_t	*first_mp1;
1918 
1919 		first_mp1 = ip_copymsg(first_mp);
1920 		freemsg(first_mp);
1921 		if (!first_mp1) {
1922 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1923 			return;
1924 		}
1925 		first_mp = first_mp1;
1926 		if (mctl_present) {
1927 			mp = first_mp->b_cont;
1928 			ASSERT(mp != NULL);
1929 		} else {
1930 			mp = first_mp;
1931 		}
1932 		ipha = (ipha_t *)mp->b_rptr;
1933 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1934 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1935 	}
1936 	switch (icmph->icmph_type) {
1937 	case ICMP_ADDRESS_MASK_REQUEST:
1938 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1939 		if (ipif == NULL) {
1940 			freemsg(first_mp);
1941 			return;
1942 		}
1943 		/*
1944 		 * outging interface must be IPv4
1945 		 */
1946 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1947 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1948 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1949 		ipif_refrele(ipif);
1950 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1951 		break;
1952 	case ICMP_ECHO_REQUEST:
1953 		icmph->icmph_type = ICMP_ECHO_REPLY;
1954 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1955 		break;
1956 	case ICMP_TIME_STAMP_REQUEST: {
1957 		uint32_t *tsp;
1958 
1959 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1960 		tsp = (uint32_t *)wptr;
1961 		tsp++;		/* Skip past 'originate time' */
1962 		/* Compute # of milliseconds since midnight */
1963 		gethrestime(&now);
1964 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1965 		    now.tv_nsec / (NANOSEC / MILLISEC);
1966 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1967 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1968 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1969 		break;
1970 	}
1971 	default:
1972 		ipha = (ipha_t *)&icmph[1];
1973 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1974 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1975 				BUMP_MIB(&ip_mib, ipInDiscards);
1976 				freemsg(first_mp);
1977 				return;
1978 			}
1979 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1980 			ipha = (ipha_t *)&icmph[1];
1981 		}
1982 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1983 			BUMP_MIB(&ip_mib, ipInDiscards);
1984 			freemsg(first_mp);
1985 			return;
1986 		}
1987 		hdr_length = IPH_HDR_LENGTH(ipha);
1988 		if (hdr_length < sizeof (ipha_t)) {
1989 			BUMP_MIB(&ip_mib, ipInDiscards);
1990 			freemsg(first_mp);
1991 			return;
1992 		}
1993 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1994 			if (!pullupmsg(mp,
1995 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1996 				BUMP_MIB(&ip_mib, ipInDiscards);
1997 				freemsg(first_mp);
1998 				return;
1999 			}
2000 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2001 			ipha = (ipha_t *)&icmph[1];
2002 		}
2003 		switch (icmph->icmph_type) {
2004 		case ICMP_REDIRECT:
2005 			/*
2006 			 * As there is no upper client to deliver, we don't
2007 			 * need the first_mp any more.
2008 			 */
2009 			if (mctl_present) {
2010 				freeb(first_mp);
2011 			}
2012 			icmp_redirect(mp);
2013 			return;
2014 		case ICMP_DEST_UNREACHABLE:
2015 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
2016 				if (!icmp_inbound_too_big(icmph, ipha, ill,
2017 				    zoneid, mp, iph_hdr_length)) {
2018 					freemsg(first_mp);
2019 					return;
2020 				}
2021 				/*
2022 				 * icmp_inbound_too_big() may alter mp.
2023 				 * Resynch ipha and icmph accordingly.
2024 				 */
2025 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2026 				ipha = (ipha_t *)&icmph[1];
2027 			}
2028 			/* FALLTHRU */
2029 		default :
2030 			/*
2031 			 * IPQoS notes: Since we have already done IPQoS
2032 			 * processing we don't want to do it again in
2033 			 * the fanout routines called by
2034 			 * icmp_inbound_error_fanout, hence the last
2035 			 * argument, ip_policy, is B_FALSE.
2036 			 */
2037 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2038 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2039 			    B_FALSE, recv_ill, zoneid);
2040 		}
2041 		return;
2042 	}
2043 	/* Send out an ICMP packet */
2044 	icmph->icmph_checksum = 0;
2045 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2046 	if (icmph->icmph_checksum == 0)
2047 		icmph->icmph_checksum = 0xFFFF;
2048 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2049 		ipif_t	*ipif_chosen;
2050 		/*
2051 		 * Make it look like it was directed to us, so we don't look
2052 		 * like a fool with a broadcast or multicast source address.
2053 		 */
2054 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2055 		/*
2056 		 * Make sure that we haven't grabbed an interface that's DOWN.
2057 		 */
2058 		if (ipif != NULL) {
2059 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2060 			    ipha->ipha_src, zoneid);
2061 			if (ipif_chosen != NULL) {
2062 				ipif_refrele(ipif);
2063 				ipif = ipif_chosen;
2064 			}
2065 		}
2066 		if (ipif == NULL) {
2067 			ip0dbg(("icmp_inbound: "
2068 			    "No source for broadcast/multicast:\n"
2069 			    "\tsrc 0x%x dst 0x%x ill %p "
2070 			    "ipif_lcl_addr 0x%x\n",
2071 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2072 			    (void *)ill,
2073 			    ill->ill_ipif->ipif_lcl_addr));
2074 			freemsg(first_mp);
2075 			return;
2076 		}
2077 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2078 		ipha->ipha_dst = ipif->ipif_src_addr;
2079 		ipif_refrele(ipif);
2080 	}
2081 	/* Reset time to live. */
2082 	ipha->ipha_ttl = ip_def_ttl;
2083 	{
2084 		/* Swap source and destination addresses */
2085 		ipaddr_t tmp;
2086 
2087 		tmp = ipha->ipha_src;
2088 		ipha->ipha_src = ipha->ipha_dst;
2089 		ipha->ipha_dst = tmp;
2090 	}
2091 	ipha->ipha_ident = 0;
2092 	if (!IS_SIMPLE_IPH(ipha))
2093 		icmp_options_update(ipha);
2094 
2095 	/*
2096 	 * ICMP echo replies should go out on the same interface
2097 	 * the request came on as probes used by in.mpathd for detecting
2098 	 * NIC failures are ECHO packets. We turn-off load spreading
2099 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2100 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2101 	 * function. This is in turn handled by ip_wput and ip_newroute
2102 	 * to make sure that the packet goes out on the interface it came
2103 	 * in on. If we don't turnoff load spreading, the packets might get
2104 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2105 	 * to go out and in.mpathd would wrongly detect a failure or
2106 	 * mis-detect a NIC failure for link failure. As load spreading
2107 	 * can happen only if ill_group is not NULL, we do only for
2108 	 * that case and this does not affect the normal case.
2109 	 *
2110 	 * We turn off load spreading only on echo packets that came from
2111 	 * on-link hosts. If the interface route has been deleted, this will
2112 	 * not be enforced as we can't do much. For off-link hosts, as the
2113 	 * default routes in IPv4 does not typically have an ire_ipif
2114 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2115 	 * Moreover, expecting a default route through this interface may
2116 	 * not be correct. We use ipha_dst because of the swap above.
2117 	 */
2118 	onlink = B_FALSE;
2119 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2120 		/*
2121 		 * First, we need to make sure that it is not one of our
2122 		 * local addresses. If we set onlink when it is one of
2123 		 * our local addresses, we will end up creating IRE_CACHES
2124 		 * for one of our local addresses. Then, we will never
2125 		 * accept packets for them afterwards.
2126 		 */
2127 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2128 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2129 		if (src_ire == NULL) {
2130 			ipif = ipif_get_next_ipif(NULL, ill);
2131 			if (ipif == NULL) {
2132 				BUMP_MIB(&ip_mib, ipInDiscards);
2133 				freemsg(mp);
2134 				return;
2135 			}
2136 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2137 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2138 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2139 			ipif_refrele(ipif);
2140 			if (src_ire != NULL) {
2141 				onlink = B_TRUE;
2142 				ire_refrele(src_ire);
2143 			}
2144 		} else {
2145 			ire_refrele(src_ire);
2146 		}
2147 	}
2148 	if (!mctl_present) {
2149 		/*
2150 		 * This packet should go out the same way as it
2151 		 * came in i.e in clear. To make sure that global
2152 		 * policy will not be applied to this in ip_wput_ire,
2153 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2154 		 */
2155 		ASSERT(first_mp == mp);
2156 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2157 			BUMP_MIB(&ip_mib, ipInDiscards);
2158 			freemsg(mp);
2159 			return;
2160 		}
2161 		ii = (ipsec_in_t *)first_mp->b_rptr;
2162 
2163 		/* This is not a secure packet */
2164 		ii->ipsec_in_secure = B_FALSE;
2165 		if (onlink) {
2166 			ii->ipsec_in_attach_if = B_TRUE;
2167 			ii->ipsec_in_ill_index =
2168 			    ill->ill_phyint->phyint_ifindex;
2169 			ii->ipsec_in_rill_index =
2170 			    recv_ill->ill_phyint->phyint_ifindex;
2171 		}
2172 		first_mp->b_cont = mp;
2173 	} else if (onlink) {
2174 		ii = (ipsec_in_t *)first_mp->b_rptr;
2175 		ii->ipsec_in_attach_if = B_TRUE;
2176 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2177 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2178 	} else {
2179 		ii = (ipsec_in_t *)first_mp->b_rptr;
2180 	}
2181 	ii->ipsec_in_zoneid = zoneid;
2182 	ASSERT(zoneid != ALL_ZONES);
2183 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2184 		BUMP_MIB(&ip_mib, ipInDiscards);
2185 		return;
2186 	}
2187 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2188 	put(WR(q), first_mp);
2189 }
2190 
2191 static ipaddr_t
2192 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2193 {
2194 	conn_t *connp;
2195 	connf_t *connfp;
2196 	ipaddr_t nexthop_addr = INADDR_ANY;
2197 	int hdr_length = IPH_HDR_LENGTH(ipha);
2198 	uint16_t *up;
2199 	uint32_t ports;
2200 
2201 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2202 	switch (ipha->ipha_protocol) {
2203 		case IPPROTO_TCP:
2204 		{
2205 			tcph_t *tcph;
2206 
2207 			/* do a reverse lookup */
2208 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2209 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2210 			    TCPS_LISTEN);
2211 			break;
2212 		}
2213 		case IPPROTO_UDP:
2214 		{
2215 			uint32_t dstport, srcport;
2216 
2217 			((uint16_t *)&ports)[0] = up[1];
2218 			((uint16_t *)&ports)[1] = up[0];
2219 
2220 			/* Extract ports in net byte order */
2221 			dstport = htons(ntohl(ports) & 0xFFFF);
2222 			srcport = htons(ntohl(ports) >> 16);
2223 
2224 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2225 			mutex_enter(&connfp->connf_lock);
2226 			connp = connfp->connf_head;
2227 
2228 			/* do a reverse lookup */
2229 			while ((connp != NULL) &&
2230 			    (!IPCL_UDP_MATCH(connp, dstport,
2231 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2232 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2233 				connp = connp->conn_next;
2234 			}
2235 			if (connp != NULL)
2236 				CONN_INC_REF(connp);
2237 			mutex_exit(&connfp->connf_lock);
2238 			break;
2239 		}
2240 		case IPPROTO_SCTP:
2241 		{
2242 			in6_addr_t map_src, map_dst;
2243 
2244 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2245 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2246 			((uint16_t *)&ports)[0] = up[1];
2247 			((uint16_t *)&ports)[1] = up[0];
2248 
2249 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2250 			    0, zoneid)) == NULL) {
2251 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2252 				    zoneid, ports, ipha);
2253 			} else {
2254 				CONN_INC_REF(connp);
2255 				SCTP_REFRELE(CONN2SCTP(connp));
2256 			}
2257 			break;
2258 		}
2259 		default:
2260 		{
2261 			ipha_t ripha;
2262 
2263 			ripha.ipha_src = ipha->ipha_dst;
2264 			ripha.ipha_dst = ipha->ipha_src;
2265 			ripha.ipha_protocol = ipha->ipha_protocol;
2266 
2267 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2268 			mutex_enter(&connfp->connf_lock);
2269 			connp = connfp->connf_head;
2270 			for (connp = connfp->connf_head; connp != NULL;
2271 			    connp = connp->conn_next) {
2272 				if (IPCL_PROTO_MATCH(connp,
2273 				    ipha->ipha_protocol, &ripha, ill,
2274 				    0, zoneid)) {
2275 					CONN_INC_REF(connp);
2276 					break;
2277 				}
2278 			}
2279 			mutex_exit(&connfp->connf_lock);
2280 		}
2281 	}
2282 	if (connp != NULL) {
2283 		if (connp->conn_nexthop_set)
2284 			nexthop_addr = connp->conn_nexthop_v4;
2285 		CONN_DEC_REF(connp);
2286 	}
2287 	return (nexthop_addr);
2288 }
2289 
2290 /* Table from RFC 1191 */
2291 static int icmp_frag_size_table[] =
2292 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2293 
2294 /*
2295  * Process received ICMP Packet too big.
2296  * After updating any IRE it does the fanout to any matching transport streams.
2297  * Assumes the message has been pulled up till the IP header that caused
2298  * the error.
2299  *
2300  * Returns B_FALSE on failure and B_TRUE on success.
2301  */
2302 static boolean_t
2303 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2304     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2305 {
2306 	ire_t	*ire, *first_ire;
2307 	int	mtu;
2308 	int	hdr_length;
2309 	ipaddr_t nexthop_addr;
2310 
2311 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2312 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2313 
2314 	hdr_length = IPH_HDR_LENGTH(ipha);
2315 
2316 	/* Drop if the original packet contained a source route */
2317 	if (ip_source_route_included(ipha)) {
2318 		return (B_FALSE);
2319 	}
2320 	/*
2321 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2322 	 * header.
2323 	 */
2324 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2325 	    mp->b_wptr) {
2326 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2327 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2328 			BUMP_MIB(&ip_mib, ipInDiscards);
2329 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2330 			return (B_FALSE);
2331 		}
2332 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2333 		ipha = (ipha_t *)&icmph[1];
2334 	}
2335 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2336 	if (nexthop_addr != INADDR_ANY) {
2337 		/* nexthop set */
2338 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2339 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2340 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2341 	} else {
2342 		/* nexthop not set */
2343 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2344 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2345 	}
2346 
2347 	if (!first_ire) {
2348 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2349 		    ntohl(ipha->ipha_dst)));
2350 		return (B_FALSE);
2351 	}
2352 	/* Check for MTU discovery advice as described in RFC 1191 */
2353 	mtu = ntohs(icmph->icmph_du_mtu);
2354 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2355 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2356 	    ire = ire->ire_next) {
2357 		/*
2358 		 * Look for the connection to which this ICMP message is
2359 		 * directed. If it has the IP_NEXTHOP option set, then the
2360 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2361 		 * option. Else the search is limited to regular IREs.
2362 		 */
2363 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2364 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2365 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2366 		    (nexthop_addr != INADDR_ANY)))
2367 			continue;
2368 
2369 		mutex_enter(&ire->ire_lock);
2370 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2371 			/* Reduce the IRE max frag value as advised. */
2372 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2373 			    mtu, ire->ire_max_frag));
2374 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2375 		} else {
2376 			uint32_t length;
2377 			int	i;
2378 
2379 			/*
2380 			 * Use the table from RFC 1191 to figure out
2381 			 * the next "plateau" based on the length in
2382 			 * the original IP packet.
2383 			 */
2384 			length = ntohs(ipha->ipha_length);
2385 			if (ire->ire_max_frag <= length &&
2386 			    ire->ire_max_frag >= length - hdr_length) {
2387 				/*
2388 				 * Handle broken BSD 4.2 systems that
2389 				 * return the wrong iph_length in ICMP
2390 				 * errors.
2391 				 */
2392 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2393 				    length, ire->ire_max_frag));
2394 				length -= hdr_length;
2395 			}
2396 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2397 				if (length > icmp_frag_size_table[i])
2398 					break;
2399 			}
2400 			if (i == A_CNT(icmp_frag_size_table)) {
2401 				/* Smaller than 68! */
2402 				ip1dbg(("Too big for packet size %d\n",
2403 				    length));
2404 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2405 				ire->ire_frag_flag = 0;
2406 			} else {
2407 				mtu = icmp_frag_size_table[i];
2408 				ip1dbg(("Calculated mtu %d, packet size %d, "
2409 				    "before %d", mtu, length,
2410 				    ire->ire_max_frag));
2411 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2412 				ip1dbg((", after %d\n", ire->ire_max_frag));
2413 			}
2414 			/* Record the new max frag size for the ULP. */
2415 			icmph->icmph_du_zero = 0;
2416 			icmph->icmph_du_mtu =
2417 			    htons((uint16_t)ire->ire_max_frag);
2418 		}
2419 		mutex_exit(&ire->ire_lock);
2420 	}
2421 	rw_exit(&first_ire->ire_bucket->irb_lock);
2422 	ire_refrele(first_ire);
2423 	return (B_TRUE);
2424 }
2425 
2426 /*
2427  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2428  * calls this function.
2429  */
2430 static mblk_t *
2431 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2432 {
2433 	ipha_t *ipha;
2434 	icmph_t *icmph;
2435 	ipha_t *in_ipha;
2436 	int length;
2437 
2438 	ASSERT(mp->b_datap->db_type == M_DATA);
2439 
2440 	/*
2441 	 * For Self-encapsulated packets, we added an extra IP header
2442 	 * without the options. Inner IP header is the one from which
2443 	 * the outer IP header was formed. Thus, we need to remove the
2444 	 * outer IP header. To do this, we pullup the whole message
2445 	 * and overlay whatever follows the outer IP header over the
2446 	 * outer IP header.
2447 	 */
2448 
2449 	if (!pullupmsg(mp, -1)) {
2450 		BUMP_MIB(&ip_mib, ipInDiscards);
2451 		return (NULL);
2452 	}
2453 
2454 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2455 	ipha = (ipha_t *)&icmph[1];
2456 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2457 
2458 	/*
2459 	 * The length that we want to overlay is following the inner
2460 	 * IP header. Subtracting the IP header + icmp header + outer
2461 	 * IP header's length should give us the length that we want to
2462 	 * overlay.
2463 	 */
2464 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2465 	    hdr_length;
2466 	/*
2467 	 * Overlay whatever follows the inner header over the
2468 	 * outer header.
2469 	 */
2470 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2471 
2472 	/* Set the wptr to account for the outer header */
2473 	mp->b_wptr -= hdr_length;
2474 	return (mp);
2475 }
2476 
2477 /*
2478  * Try to pass the ICMP message upstream in case the ULP cares.
2479  *
2480  * If the packet that caused the ICMP error is secure, we send
2481  * it to AH/ESP to make sure that the attached packet has a
2482  * valid association. ipha in the code below points to the
2483  * IP header of the packet that caused the error.
2484  *
2485  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2486  * in the context of IPSEC. Normally we tell the upper layer
2487  * whenever we send the ire (including ip_bind), the IPSEC header
2488  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2489  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2490  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2491  * same thing. As TCP has the IPSEC options size that needs to be
2492  * adjusted, we just pass the MTU unchanged.
2493  *
2494  * IFN could have been generated locally or by some router.
2495  *
2496  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2497  *	    This happens because IP adjusted its value of MTU on an
2498  *	    earlier IFN message and could not tell the upper layer,
2499  *	    the new adjusted value of MTU e.g. Packet was encrypted
2500  *	    or there was not enough information to fanout to upper
2501  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2502  *	    generates the IFN, where IPSEC processing has *not* been
2503  *	    done.
2504  *
2505  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2506  *	    could have generated this. This happens because ire_max_frag
2507  *	    value in IP was set to a new value, while the IPSEC processing
2508  *	    was being done and after we made the fragmentation check in
2509  *	    ip_wput_ire. Thus on return from IPSEC processing,
2510  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2511  *	    and generates the IFN. As IPSEC processing is over, we fanout
2512  *	    to AH/ESP to remove the header.
2513  *
2514  *	    In both these cases, ipsec_in_loopback will be set indicating
2515  *	    that IFN was generated locally.
2516  *
2517  * ROUTER : IFN could be secure or non-secure.
2518  *
2519  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2520  *	      packet in error has AH/ESP headers to validate the AH/ESP
2521  *	      headers. AH/ESP will verify whether there is a valid SA or
2522  *	      not and send it back. We will fanout again if we have more
2523  *	      data in the packet.
2524  *
2525  *	      If the packet in error does not have AH/ESP, we handle it
2526  *	      like any other case.
2527  *
2528  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2529  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2530  *	      for validation. AH/ESP will verify whether there is a
2531  *	      valid SA or not and send it back. We will fanout again if
2532  *	      we have more data in the packet.
2533  *
2534  *	      If the packet in error does not have AH/ESP, we handle it
2535  *	      like any other case.
2536  */
2537 static void
2538 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2539     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2540     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2541     zoneid_t zoneid)
2542 {
2543 	uint16_t *up;	/* Pointer to ports in ULP header */
2544 	uint32_t ports;	/* reversed ports for fanout */
2545 	ipha_t ripha;	/* With reversed addresses */
2546 	mblk_t *first_mp;
2547 	ipsec_in_t *ii;
2548 	tcph_t	*tcph;
2549 	conn_t	*connp;
2550 
2551 	first_mp = mp;
2552 	if (mctl_present) {
2553 		mp = first_mp->b_cont;
2554 		ASSERT(mp != NULL);
2555 
2556 		ii = (ipsec_in_t *)first_mp->b_rptr;
2557 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2558 	} else {
2559 		ii = NULL;
2560 	}
2561 
2562 	switch (ipha->ipha_protocol) {
2563 	case IPPROTO_UDP:
2564 		/*
2565 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2566 		 * transport header.
2567 		 */
2568 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2569 		    mp->b_wptr) {
2570 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2571 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2572 				BUMP_MIB(&ip_mib, ipInDiscards);
2573 				goto drop_pkt;
2574 			}
2575 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2576 			ipha = (ipha_t *)&icmph[1];
2577 		}
2578 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2579 
2580 		/*
2581 		 * Attempt to find a client stream based on port.
2582 		 * Note that we do a reverse lookup since the header is
2583 		 * in the form we sent it out.
2584 		 * The ripha header is only used for the IP_UDP_MATCH and we
2585 		 * only set the src and dst addresses and protocol.
2586 		 */
2587 		ripha.ipha_src = ipha->ipha_dst;
2588 		ripha.ipha_dst = ipha->ipha_src;
2589 		ripha.ipha_protocol = ipha->ipha_protocol;
2590 		((uint16_t *)&ports)[0] = up[1];
2591 		((uint16_t *)&ports)[1] = up[0];
2592 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2593 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2594 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2595 		    icmph->icmph_type, icmph->icmph_code));
2596 
2597 		/* Have to change db_type after any pullupmsg */
2598 		DB_TYPE(mp) = M_CTL;
2599 
2600 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2601 		    mctl_present, ip_policy, recv_ill, zoneid);
2602 		return;
2603 
2604 	case IPPROTO_TCP:
2605 		/*
2606 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2607 		 * transport header.
2608 		 */
2609 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2610 		    mp->b_wptr) {
2611 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2612 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2613 				BUMP_MIB(&ip_mib, ipInDiscards);
2614 				goto drop_pkt;
2615 			}
2616 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2617 			ipha = (ipha_t *)&icmph[1];
2618 		}
2619 		/*
2620 		 * Find a TCP client stream for this packet.
2621 		 * Note that we do a reverse lookup since the header is
2622 		 * in the form we sent it out.
2623 		 */
2624 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2625 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2626 		if (connp == NULL) {
2627 			BUMP_MIB(&ip_mib, ipInDiscards);
2628 			goto drop_pkt;
2629 		}
2630 
2631 		/* Have to change db_type after any pullupmsg */
2632 		DB_TYPE(mp) = M_CTL;
2633 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2634 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2635 		return;
2636 
2637 	case IPPROTO_SCTP:
2638 		/*
2639 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2640 		 * transport header.
2641 		 */
2642 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2643 		    mp->b_wptr) {
2644 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2645 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2646 				BUMP_MIB(&ip_mib, ipInDiscards);
2647 				goto drop_pkt;
2648 			}
2649 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2650 			ipha = (ipha_t *)&icmph[1];
2651 		}
2652 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2653 		/*
2654 		 * Find a SCTP client stream for this packet.
2655 		 * Note that we do a reverse lookup since the header is
2656 		 * in the form we sent it out.
2657 		 * The ripha header is only used for the matching and we
2658 		 * only set the src and dst addresses, protocol, and version.
2659 		 */
2660 		ripha.ipha_src = ipha->ipha_dst;
2661 		ripha.ipha_dst = ipha->ipha_src;
2662 		ripha.ipha_protocol = ipha->ipha_protocol;
2663 		ripha.ipha_version_and_hdr_length =
2664 		    ipha->ipha_version_and_hdr_length;
2665 		((uint16_t *)&ports)[0] = up[1];
2666 		((uint16_t *)&ports)[1] = up[0];
2667 
2668 		/* Have to change db_type after any pullupmsg */
2669 		DB_TYPE(mp) = M_CTL;
2670 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2671 		    mctl_present, ip_policy, 0, zoneid);
2672 		return;
2673 
2674 	case IPPROTO_ESP:
2675 	case IPPROTO_AH: {
2676 		int ipsec_rc;
2677 
2678 		/*
2679 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2680 		 * We will re-use the IPSEC_IN if it is already present as
2681 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2682 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2683 		 * one and attach it in the front.
2684 		 */
2685 		if (ii != NULL) {
2686 			/*
2687 			 * ip_fanout_proto_again converts the ICMP errors
2688 			 * that come back from AH/ESP to M_DATA so that
2689 			 * if it is non-AH/ESP and we do a pullupmsg in
2690 			 * this function, it would work. Convert it back
2691 			 * to M_CTL before we send up as this is a ICMP
2692 			 * error. This could have been generated locally or
2693 			 * by some router. Validate the inner IPSEC
2694 			 * headers.
2695 			 *
2696 			 * NOTE : ill_index is used by ip_fanout_proto_again
2697 			 * to locate the ill.
2698 			 */
2699 			ASSERT(ill != NULL);
2700 			ii->ipsec_in_ill_index =
2701 			    ill->ill_phyint->phyint_ifindex;
2702 			ii->ipsec_in_rill_index =
2703 			    recv_ill->ill_phyint->phyint_ifindex;
2704 			DB_TYPE(first_mp->b_cont) = M_CTL;
2705 		} else {
2706 			/*
2707 			 * IPSEC_IN is not present. We attach a ipsec_in
2708 			 * message and send up to IPSEC for validating
2709 			 * and removing the IPSEC headers. Clear
2710 			 * ipsec_in_secure so that when we return
2711 			 * from IPSEC, we don't mistakenly think that this
2712 			 * is a secure packet came from the network.
2713 			 *
2714 			 * NOTE : ill_index is used by ip_fanout_proto_again
2715 			 * to locate the ill.
2716 			 */
2717 			ASSERT(first_mp == mp);
2718 			first_mp = ipsec_in_alloc(B_TRUE);
2719 			if (first_mp == NULL) {
2720 				freemsg(mp);
2721 				BUMP_MIB(&ip_mib, ipInDiscards);
2722 				return;
2723 			}
2724 			ii = (ipsec_in_t *)first_mp->b_rptr;
2725 
2726 			/* This is not a secure packet */
2727 			ii->ipsec_in_secure = B_FALSE;
2728 			first_mp->b_cont = mp;
2729 			DB_TYPE(mp) = M_CTL;
2730 			ASSERT(ill != NULL);
2731 			ii->ipsec_in_ill_index =
2732 			    ill->ill_phyint->phyint_ifindex;
2733 			ii->ipsec_in_rill_index =
2734 			    recv_ill->ill_phyint->phyint_ifindex;
2735 		}
2736 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2737 
2738 		if (!ipsec_loaded()) {
2739 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2740 			return;
2741 		}
2742 
2743 		if (ipha->ipha_protocol == IPPROTO_ESP)
2744 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2745 		else
2746 			ipsec_rc = ipsecah_icmp_error(first_mp);
2747 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2748 			return;
2749 
2750 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2751 		return;
2752 	}
2753 	default:
2754 		/*
2755 		 * The ripha header is only used for the lookup and we
2756 		 * only set the src and dst addresses and protocol.
2757 		 */
2758 		ripha.ipha_src = ipha->ipha_dst;
2759 		ripha.ipha_dst = ipha->ipha_src;
2760 		ripha.ipha_protocol = ipha->ipha_protocol;
2761 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2762 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2763 		    ntohl(ipha->ipha_dst),
2764 		    icmph->icmph_type, icmph->icmph_code));
2765 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2766 			ipha_t *in_ipha;
2767 
2768 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2769 			    mp->b_wptr) {
2770 				if (!pullupmsg(mp, (uchar_t *)ipha +
2771 				    hdr_length + sizeof (ipha_t) -
2772 				    mp->b_rptr)) {
2773 
2774 					BUMP_MIB(&ip_mib, ipInDiscards);
2775 					goto drop_pkt;
2776 				}
2777 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2778 				ipha = (ipha_t *)&icmph[1];
2779 			}
2780 			/*
2781 			 * Caller has verified that length has to be
2782 			 * at least the size of IP header.
2783 			 */
2784 			ASSERT(hdr_length >= sizeof (ipha_t));
2785 			/*
2786 			 * Check the sanity of the inner IP header like
2787 			 * we did for the outer header.
2788 			 */
2789 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2790 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2791 				BUMP_MIB(&ip_mib, ipInDiscards);
2792 				goto drop_pkt;
2793 			}
2794 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2795 				BUMP_MIB(&ip_mib, ipInDiscards);
2796 				goto drop_pkt;
2797 			}
2798 			/* Check for Self-encapsulated tunnels */
2799 			if (in_ipha->ipha_src == ipha->ipha_src &&
2800 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2801 
2802 				mp = icmp_inbound_self_encap_error(mp,
2803 				    iph_hdr_length, hdr_length);
2804 				if (mp == NULL)
2805 					goto drop_pkt;
2806 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2807 				ipha = (ipha_t *)&icmph[1];
2808 				hdr_length = IPH_HDR_LENGTH(ipha);
2809 				/*
2810 				 * The packet in error is self-encapsualted.
2811 				 * And we are finding it further encapsulated
2812 				 * which we could not have possibly generated.
2813 				 */
2814 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2815 					BUMP_MIB(&ip_mib, ipInDiscards);
2816 					goto drop_pkt;
2817 				}
2818 				icmp_inbound_error_fanout(q, ill, first_mp,
2819 				    icmph, ipha, iph_hdr_length, hdr_length,
2820 				    mctl_present, ip_policy, recv_ill, zoneid);
2821 				return;
2822 			}
2823 		}
2824 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2825 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2826 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2827 		    ii != NULL &&
2828 		    ii->ipsec_in_loopback &&
2829 		    ii->ipsec_in_secure) {
2830 			/*
2831 			 * For IP tunnels that get a looped-back
2832 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2833 			 * reported new MTU to take into account the IPsec
2834 			 * headers protecting this configured tunnel.
2835 			 *
2836 			 * This allows the tunnel module (tun.c) to blindly
2837 			 * accept the MTU reported in an ICMP "too big"
2838 			 * message.
2839 			 *
2840 			 * Non-looped back ICMP messages will just be
2841 			 * handled by the security protocols (if needed),
2842 			 * and the first subsequent packet will hit this
2843 			 * path.
2844 			 */
2845 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2846 			    ipsec_in_extra_length(first_mp));
2847 		}
2848 		/* Have to change db_type after any pullupmsg */
2849 		DB_TYPE(mp) = M_CTL;
2850 
2851 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2852 		    ip_policy, recv_ill, zoneid);
2853 		return;
2854 	}
2855 	/* NOTREACHED */
2856 drop_pkt:;
2857 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2858 	freemsg(first_mp);
2859 }
2860 
2861 /*
2862  * Common IP options parser.
2863  *
2864  * Setup routine: fill in *optp with options-parsing state, then
2865  * tail-call ipoptp_next to return the first option.
2866  */
2867 uint8_t
2868 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2869 {
2870 	uint32_t totallen; /* total length of all options */
2871 
2872 	totallen = ipha->ipha_version_and_hdr_length -
2873 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2874 	totallen <<= 2;
2875 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2876 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2877 	optp->ipoptp_flags = 0;
2878 	return (ipoptp_next(optp));
2879 }
2880 
2881 /*
2882  * Common IP options parser: extract next option.
2883  */
2884 uint8_t
2885 ipoptp_next(ipoptp_t *optp)
2886 {
2887 	uint8_t *end = optp->ipoptp_end;
2888 	uint8_t *cur = optp->ipoptp_next;
2889 	uint8_t opt, len, pointer;
2890 
2891 	/*
2892 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2893 	 * has been corrupted.
2894 	 */
2895 	ASSERT(cur <= end);
2896 
2897 	if (cur == end)
2898 		return (IPOPT_EOL);
2899 
2900 	opt = cur[IPOPT_OPTVAL];
2901 
2902 	/*
2903 	 * Skip any NOP options.
2904 	 */
2905 	while (opt == IPOPT_NOP) {
2906 		cur++;
2907 		if (cur == end)
2908 			return (IPOPT_EOL);
2909 		opt = cur[IPOPT_OPTVAL];
2910 	}
2911 
2912 	if (opt == IPOPT_EOL)
2913 		return (IPOPT_EOL);
2914 
2915 	/*
2916 	 * Option requiring a length.
2917 	 */
2918 	if ((cur + 1) >= end) {
2919 		optp->ipoptp_flags |= IPOPTP_ERROR;
2920 		return (IPOPT_EOL);
2921 	}
2922 	len = cur[IPOPT_OLEN];
2923 	if (len < 2) {
2924 		optp->ipoptp_flags |= IPOPTP_ERROR;
2925 		return (IPOPT_EOL);
2926 	}
2927 	optp->ipoptp_cur = cur;
2928 	optp->ipoptp_len = len;
2929 	optp->ipoptp_next = cur + len;
2930 	if (cur + len > end) {
2931 		optp->ipoptp_flags |= IPOPTP_ERROR;
2932 		return (IPOPT_EOL);
2933 	}
2934 
2935 	/*
2936 	 * For the options which require a pointer field, make sure
2937 	 * its there, and make sure it points to either something
2938 	 * inside this option, or the end of the option.
2939 	 */
2940 	switch (opt) {
2941 	case IPOPT_RR:
2942 	case IPOPT_TS:
2943 	case IPOPT_LSRR:
2944 	case IPOPT_SSRR:
2945 		if (len <= IPOPT_OFFSET) {
2946 			optp->ipoptp_flags |= IPOPTP_ERROR;
2947 			return (opt);
2948 		}
2949 		pointer = cur[IPOPT_OFFSET];
2950 		if (pointer - 1 > len) {
2951 			optp->ipoptp_flags |= IPOPTP_ERROR;
2952 			return (opt);
2953 		}
2954 		break;
2955 	}
2956 
2957 	/*
2958 	 * Sanity check the pointer field based on the type of the
2959 	 * option.
2960 	 */
2961 	switch (opt) {
2962 	case IPOPT_RR:
2963 	case IPOPT_SSRR:
2964 	case IPOPT_LSRR:
2965 		if (pointer < IPOPT_MINOFF_SR)
2966 			optp->ipoptp_flags |= IPOPTP_ERROR;
2967 		break;
2968 	case IPOPT_TS:
2969 		if (pointer < IPOPT_MINOFF_IT)
2970 			optp->ipoptp_flags |= IPOPTP_ERROR;
2971 		/*
2972 		 * Note that the Internet Timestamp option also
2973 		 * contains two four bit fields (the Overflow field,
2974 		 * and the Flag field), which follow the pointer
2975 		 * field.  We don't need to check that these fields
2976 		 * fall within the length of the option because this
2977 		 * was implicitely done above.  We've checked that the
2978 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2979 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2980 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2981 		 */
2982 		ASSERT(len > IPOPT_POS_OV_FLG);
2983 		break;
2984 	}
2985 
2986 	return (opt);
2987 }
2988 
2989 /*
2990  * Use the outgoing IP header to create an IP_OPTIONS option the way
2991  * it was passed down from the application.
2992  */
2993 int
2994 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2995 {
2996 	ipoptp_t	opts;
2997 	const uchar_t	*opt;
2998 	uint8_t		optval;
2999 	uint8_t		optlen;
3000 	uint32_t	len = 0;
3001 	uchar_t	*buf1 = buf;
3002 
3003 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
3004 	len += IP_ADDR_LEN;
3005 	bzero(buf1, IP_ADDR_LEN);
3006 
3007 	/*
3008 	 * OK to cast away const here, as we don't store through the returned
3009 	 * opts.ipoptp_cur pointer.
3010 	 */
3011 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
3012 	    optval != IPOPT_EOL;
3013 	    optval = ipoptp_next(&opts)) {
3014 		int	off;
3015 
3016 		opt = opts.ipoptp_cur;
3017 		optlen = opts.ipoptp_len;
3018 		switch (optval) {
3019 		case IPOPT_SSRR:
3020 		case IPOPT_LSRR:
3021 
3022 			/*
3023 			 * Insert ipha_dst as the first entry in the source
3024 			 * route and move down the entries on step.
3025 			 * The last entry gets placed at buf1.
3026 			 */
3027 			buf[IPOPT_OPTVAL] = optval;
3028 			buf[IPOPT_OLEN] = optlen;
3029 			buf[IPOPT_OFFSET] = optlen;
3030 
3031 			off = optlen - IP_ADDR_LEN;
3032 			if (off < 0) {
3033 				/* No entries in source route */
3034 				break;
3035 			}
3036 			/* Last entry in source route */
3037 			bcopy(opt + off, buf1, IP_ADDR_LEN);
3038 			off -= IP_ADDR_LEN;
3039 
3040 			while (off > 0) {
3041 				bcopy(opt + off,
3042 				    buf + off + IP_ADDR_LEN,
3043 				    IP_ADDR_LEN);
3044 				off -= IP_ADDR_LEN;
3045 			}
3046 			/* ipha_dst into first slot */
3047 			bcopy(&ipha->ipha_dst,
3048 			    buf + off + IP_ADDR_LEN,
3049 			    IP_ADDR_LEN);
3050 			buf += optlen;
3051 			len += optlen;
3052 			break;
3053 
3054 		case IPOPT_COMSEC:
3055 		case IPOPT_SECURITY:
3056 			/* if passing up a label is not ok, then remove */
3057 			if (is_system_labeled())
3058 				break;
3059 			/* FALLTHROUGH */
3060 		default:
3061 			bcopy(opt, buf, optlen);
3062 			buf += optlen;
3063 			len += optlen;
3064 			break;
3065 		}
3066 	}
3067 done:
3068 	/* Pad the resulting options */
3069 	while (len & 0x3) {
3070 		*buf++ = IPOPT_EOL;
3071 		len++;
3072 	}
3073 	return (len);
3074 }
3075 
3076 /*
3077  * Update any record route or timestamp options to include this host.
3078  * Reverse any source route option.
3079  * This routine assumes that the options are well formed i.e. that they
3080  * have already been checked.
3081  */
3082 static void
3083 icmp_options_update(ipha_t *ipha)
3084 {
3085 	ipoptp_t	opts;
3086 	uchar_t		*opt;
3087 	uint8_t		optval;
3088 	ipaddr_t	src;		/* Our local address */
3089 	ipaddr_t	dst;
3090 
3091 	ip2dbg(("icmp_options_update\n"));
3092 	src = ipha->ipha_src;
3093 	dst = ipha->ipha_dst;
3094 
3095 	for (optval = ipoptp_first(&opts, ipha);
3096 	    optval != IPOPT_EOL;
3097 	    optval = ipoptp_next(&opts)) {
3098 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3099 		opt = opts.ipoptp_cur;
3100 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3101 		    optval, opts.ipoptp_len));
3102 		switch (optval) {
3103 			int off1, off2;
3104 		case IPOPT_SSRR:
3105 		case IPOPT_LSRR:
3106 			/*
3107 			 * Reverse the source route.  The first entry
3108 			 * should be the next to last one in the current
3109 			 * source route (the last entry is our address).
3110 			 * The last entry should be the final destination.
3111 			 */
3112 			off1 = IPOPT_MINOFF_SR - 1;
3113 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3114 			if (off2 < 0) {
3115 				/* No entries in source route */
3116 				ip1dbg((
3117 				    "icmp_options_update: bad src route\n"));
3118 				break;
3119 			}
3120 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3121 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3122 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3123 			off2 -= IP_ADDR_LEN;
3124 
3125 			while (off1 < off2) {
3126 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3127 				bcopy((char *)opt + off2, (char *)opt + off1,
3128 				    IP_ADDR_LEN);
3129 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3130 				off1 += IP_ADDR_LEN;
3131 				off2 -= IP_ADDR_LEN;
3132 			}
3133 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3134 			break;
3135 		}
3136 	}
3137 }
3138 
3139 /*
3140  * Process received ICMP Redirect messages.
3141  */
3142 /* ARGSUSED */
3143 static void
3144 icmp_redirect(mblk_t *mp)
3145 {
3146 	ipha_t	*ipha;
3147 	int	iph_hdr_length;
3148 	icmph_t	*icmph;
3149 	ipha_t	*ipha_err;
3150 	ire_t	*ire;
3151 	ire_t	*prev_ire;
3152 	ire_t	*save_ire;
3153 	ipaddr_t  src, dst, gateway;
3154 	iulp_t	ulp_info = { 0 };
3155 	int	error;
3156 
3157 	ipha = (ipha_t *)mp->b_rptr;
3158 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3159 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3160 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3161 		BUMP_MIB(&icmp_mib, icmpInErrors);
3162 		freemsg(mp);
3163 		return;
3164 	}
3165 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3166 	ipha_err = (ipha_t *)&icmph[1];
3167 	src = ipha->ipha_src;
3168 	dst = ipha_err->ipha_dst;
3169 	gateway = icmph->icmph_rd_gateway;
3170 	/* Make sure the new gateway is reachable somehow. */
3171 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3172 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3173 	/*
3174 	 * Make sure we had a route for the dest in question and that
3175 	 * that route was pointing to the old gateway (the source of the
3176 	 * redirect packet.)
3177 	 */
3178 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3179 	    NULL, MATCH_IRE_GW);
3180 	/*
3181 	 * Check that
3182 	 *	the redirect was not from ourselves
3183 	 *	the new gateway and the old gateway are directly reachable
3184 	 */
3185 	if (!prev_ire ||
3186 	    !ire ||
3187 	    ire->ire_type == IRE_LOCAL) {
3188 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3189 		freemsg(mp);
3190 		if (ire != NULL)
3191 			ire_refrele(ire);
3192 		if (prev_ire != NULL)
3193 			ire_refrele(prev_ire);
3194 		return;
3195 	}
3196 
3197 	/*
3198 	 * Should we use the old ULP info to create the new gateway?  From
3199 	 * a user's perspective, we should inherit the info so that it
3200 	 * is a "smooth" transition.  If we do not do that, then new
3201 	 * connections going thru the new gateway will have no route metrics,
3202 	 * which is counter-intuitive to user.  From a network point of
3203 	 * view, this may or may not make sense even though the new gateway
3204 	 * is still directly connected to us so the route metrics should not
3205 	 * change much.
3206 	 *
3207 	 * But if the old ire_uinfo is not initialized, we do another
3208 	 * recursive lookup on the dest using the new gateway.  There may
3209 	 * be a route to that.  If so, use it to initialize the redirect
3210 	 * route.
3211 	 */
3212 	if (prev_ire->ire_uinfo.iulp_set) {
3213 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3214 	} else {
3215 		ire_t *tmp_ire;
3216 		ire_t *sire;
3217 
3218 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3219 		    ALL_ZONES, 0, NULL,
3220 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3221 		if (sire != NULL) {
3222 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3223 			/*
3224 			 * If sire != NULL, ire_ftable_lookup() should not
3225 			 * return a NULL value.
3226 			 */
3227 			ASSERT(tmp_ire != NULL);
3228 			ire_refrele(tmp_ire);
3229 			ire_refrele(sire);
3230 		} else if (tmp_ire != NULL) {
3231 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3232 			    sizeof (iulp_t));
3233 			ire_refrele(tmp_ire);
3234 		}
3235 	}
3236 	if (prev_ire->ire_type == IRE_CACHE)
3237 		ire_delete(prev_ire);
3238 	ire_refrele(prev_ire);
3239 	/*
3240 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3241 	 * require TOS routing
3242 	 */
3243 	switch (icmph->icmph_code) {
3244 	case 0:
3245 	case 1:
3246 		/* TODO: TOS specificity for cases 2 and 3 */
3247 	case 2:
3248 	case 3:
3249 		break;
3250 	default:
3251 		freemsg(mp);
3252 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3253 		ire_refrele(ire);
3254 		return;
3255 	}
3256 	/*
3257 	 * Create a Route Association.  This will allow us to remember that
3258 	 * someone we believe told us to use the particular gateway.
3259 	 */
3260 	save_ire = ire;
3261 	ire = ire_create(
3262 		(uchar_t *)&dst,			/* dest addr */
3263 		(uchar_t *)&ip_g_all_ones,		/* mask */
3264 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3265 		(uchar_t *)&gateway,			/* gateway addr */
3266 		NULL,					/* no in_srcaddr */
3267 		&save_ire->ire_max_frag,		/* max frag */
3268 		NULL,					/* Fast Path header */
3269 		NULL,					/* no rfq */
3270 		NULL,					/* no stq */
3271 		IRE_HOST,
3272 		NULL,
3273 		NULL,
3274 		NULL,
3275 		0,
3276 		0,
3277 		0,
3278 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3279 		&ulp_info,
3280 		NULL,
3281 		NULL);
3282 
3283 	if (ire == NULL) {
3284 		freemsg(mp);
3285 		ire_refrele(save_ire);
3286 		return;
3287 	}
3288 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3289 	ire_refrele(save_ire);
3290 	atomic_inc_32(&ip_redirect_cnt);
3291 
3292 	if (error == 0) {
3293 		ire_refrele(ire);		/* Held in ire_add_v4 */
3294 		/* tell routing sockets that we received a redirect */
3295 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3296 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3297 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3298 	}
3299 
3300 	/*
3301 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3302 	 * This together with the added IRE has the effect of
3303 	 * modifying an existing redirect.
3304 	 */
3305 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3306 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3307 	if (prev_ire != NULL) {
3308 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3309 			ire_delete(prev_ire);
3310 		ire_refrele(prev_ire);
3311 	}
3312 
3313 	freemsg(mp);
3314 }
3315 
3316 /*
3317  * Generate an ICMP parameter problem message.
3318  */
3319 static void
3320 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid)
3321 {
3322 	icmph_t	icmph;
3323 	boolean_t mctl_present;
3324 	mblk_t *first_mp;
3325 
3326 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3327 
3328 	if (!(mp = icmp_pkt_err_ok(mp))) {
3329 		if (mctl_present)
3330 			freeb(first_mp);
3331 		return;
3332 	}
3333 
3334 	bzero(&icmph, sizeof (icmph_t));
3335 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3336 	icmph.icmph_pp_ptr = ptr;
3337 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3338 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3339 }
3340 
3341 /*
3342  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3343  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3344  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3345  * an icmp error packet can be sent.
3346  * Assigns an appropriate source address to the packet. If ipha_dst is
3347  * one of our addresses use it for source. Otherwise pick a source based
3348  * on a route lookup back to ipha_src.
3349  * Note that ipha_src must be set here since the
3350  * packet is likely to arrive on an ill queue in ip_wput() which will
3351  * not set a source address.
3352  */
3353 static void
3354 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3355     boolean_t mctl_present, zoneid_t zoneid)
3356 {
3357 	ipaddr_t dst;
3358 	icmph_t	*icmph;
3359 	ipha_t	*ipha;
3360 	uint_t	len_needed;
3361 	size_t	msg_len;
3362 	mblk_t	*mp1;
3363 	ipaddr_t src;
3364 	ire_t	*ire;
3365 	mblk_t *ipsec_mp;
3366 	ipsec_out_t	*io = NULL;
3367 	boolean_t xmit_if_on = B_FALSE;
3368 
3369 	if (mctl_present) {
3370 		/*
3371 		 * If it is :
3372 		 *
3373 		 * 1) a IPSEC_OUT, then this is caused by outbound
3374 		 *    datagram originating on this host. IPSEC processing
3375 		 *    may or may not have been done. Refer to comments above
3376 		 *    icmp_inbound_error_fanout for details.
3377 		 *
3378 		 * 2) a IPSEC_IN if we are generating a icmp_message
3379 		 *    for an incoming datagram destined for us i.e called
3380 		 *    from ip_fanout_send_icmp.
3381 		 */
3382 		ipsec_info_t *in;
3383 		ipsec_mp = mp;
3384 		mp = ipsec_mp->b_cont;
3385 
3386 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3387 		ipha = (ipha_t *)mp->b_rptr;
3388 
3389 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3390 		    in->ipsec_info_type == IPSEC_IN);
3391 
3392 		if (in->ipsec_info_type == IPSEC_IN) {
3393 			/*
3394 			 * Convert the IPSEC_IN to IPSEC_OUT.
3395 			 */
3396 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3397 				BUMP_MIB(&ip_mib, ipOutDiscards);
3398 				return;
3399 			}
3400 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3401 		} else {
3402 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3403 			io = (ipsec_out_t *)in;
3404 			if (io->ipsec_out_xmit_if)
3405 				xmit_if_on = B_TRUE;
3406 			/*
3407 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3408 			 * ire lookup.
3409 			 */
3410 			io->ipsec_out_proc_begin = B_FALSE;
3411 		}
3412 		ASSERT(zoneid == io->ipsec_out_zoneid);
3413 		ASSERT(zoneid != ALL_ZONES);
3414 	} else {
3415 		/*
3416 		 * This is in clear. The icmp message we are building
3417 		 * here should go out in clear.
3418 		 *
3419 		 * Pardon the convolution of it all, but it's easier to
3420 		 * allocate a "use cleartext" IPSEC_IN message and convert
3421 		 * it than it is to allocate a new one.
3422 		 */
3423 		ipsec_in_t *ii;
3424 		ASSERT(DB_TYPE(mp) == M_DATA);
3425 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3426 			freemsg(mp);
3427 			BUMP_MIB(&ip_mib, ipOutDiscards);
3428 			return;
3429 		}
3430 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3431 
3432 		/* This is not a secure packet */
3433 		ii->ipsec_in_secure = B_FALSE;
3434 		/*
3435 		 * For trusted extensions using a shared IP address we can
3436 		 * send using any zoneid.
3437 		 */
3438 		if (zoneid == ALL_ZONES)
3439 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3440 		else
3441 			ii->ipsec_in_zoneid = zoneid;
3442 		ipsec_mp->b_cont = mp;
3443 		ipha = (ipha_t *)mp->b_rptr;
3444 		/*
3445 		 * Convert the IPSEC_IN to IPSEC_OUT.
3446 		 */
3447 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3448 			BUMP_MIB(&ip_mib, ipOutDiscards);
3449 			return;
3450 		}
3451 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3452 	}
3453 
3454 	/* Remember our eventual destination */
3455 	dst = ipha->ipha_src;
3456 
3457 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3458 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3459 	if (ire != NULL &&
3460 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3461 		src = ipha->ipha_dst;
3462 	} else if (!xmit_if_on) {
3463 		if (ire != NULL)
3464 			ire_refrele(ire);
3465 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3466 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3467 		if (ire == NULL) {
3468 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3469 			freemsg(ipsec_mp);
3470 			return;
3471 		}
3472 		src = ire->ire_src_addr;
3473 	} else {
3474 		ipif_t	*ipif = NULL;
3475 		ill_t	*ill;
3476 		/*
3477 		 * This must be an ICMP error coming from
3478 		 * ip_mrtun_forward(). The src addr should
3479 		 * be equal to the IP-addr of the outgoing
3480 		 * interface.
3481 		 */
3482 		if (io == NULL) {
3483 			/* This is not a IPSEC_OUT type control msg */
3484 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3485 			freemsg(ipsec_mp);
3486 			return;
3487 		}
3488 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3489 		    NULL, NULL, NULL, NULL);
3490 		if (ill != NULL) {
3491 			ipif = ipif_get_next_ipif(NULL, ill);
3492 			ill_refrele(ill);
3493 		}
3494 		if (ipif == NULL) {
3495 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3496 			freemsg(ipsec_mp);
3497 			return;
3498 		}
3499 		src = ipif->ipif_src_addr;
3500 		ipif_refrele(ipif);
3501 	}
3502 
3503 	if (ire != NULL)
3504 		ire_refrele(ire);
3505 
3506 	/*
3507 	 * Check if we can send back more then 8 bytes in addition
3508 	 * to the IP header. We will include as much as 64 bytes.
3509 	 */
3510 	len_needed = IPH_HDR_LENGTH(ipha);
3511 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3512 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3513 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3514 	}
3515 	len_needed += ip_icmp_return;
3516 	msg_len = msgdsize(mp);
3517 	if (msg_len > len_needed) {
3518 		(void) adjmsg(mp, len_needed - msg_len);
3519 		msg_len = len_needed;
3520 	}
3521 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3522 	if (mp1 == NULL) {
3523 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3524 		freemsg(ipsec_mp);
3525 		return;
3526 	}
3527 	/*
3528 	 * On an unlabeled system, dblks don't necessarily have creds.
3529 	 */
3530 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3531 	if (DB_CRED(mp) != NULL)
3532 		mblk_setcred(mp1, DB_CRED(mp));
3533 	mp1->b_cont = mp;
3534 	mp = mp1;
3535 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3536 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3537 	    io->ipsec_out_type == IPSEC_OUT);
3538 	ipsec_mp->b_cont = mp;
3539 
3540 	/*
3541 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3542 	 * node generates be accepted in peace by all on-host destinations.
3543 	 * If we do NOT assume that all on-host destinations trust
3544 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3545 	 * (Look for ipsec_out_icmp_loopback).
3546 	 */
3547 	io->ipsec_out_icmp_loopback = B_TRUE;
3548 
3549 	ipha = (ipha_t *)mp->b_rptr;
3550 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3551 	*ipha = icmp_ipha;
3552 	ipha->ipha_src = src;
3553 	ipha->ipha_dst = dst;
3554 	ipha->ipha_ttl = ip_def_ttl;
3555 	msg_len += sizeof (icmp_ipha) + len;
3556 	if (msg_len > IP_MAXPACKET) {
3557 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3558 		msg_len = IP_MAXPACKET;
3559 	}
3560 	ipha->ipha_length = htons((uint16_t)msg_len);
3561 	icmph = (icmph_t *)&ipha[1];
3562 	bcopy(stuff, icmph, len);
3563 	icmph->icmph_checksum = 0;
3564 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3565 	if (icmph->icmph_checksum == 0)
3566 		icmph->icmph_checksum = 0xFFFF;
3567 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3568 	put(q, ipsec_mp);
3569 }
3570 
3571 /*
3572  * Determine if an ICMP error packet can be sent given the rate limit.
3573  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3574  * in milliseconds) and a burst size. Burst size number of packets can
3575  * be sent arbitrarely closely spaced.
3576  * The state is tracked using two variables to implement an approximate
3577  * token bucket filter:
3578  *	icmp_pkt_err_last - lbolt value when the last burst started
3579  *	icmp_pkt_err_sent - number of packets sent in current burst
3580  */
3581 boolean_t
3582 icmp_err_rate_limit(void)
3583 {
3584 	clock_t now = TICK_TO_MSEC(lbolt);
3585 	uint_t refilled; /* Number of packets refilled in tbf since last */
3586 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3587 
3588 	if (err_interval == 0)
3589 		return (B_FALSE);
3590 
3591 	if (icmp_pkt_err_last > now) {
3592 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3593 		icmp_pkt_err_last = 0;
3594 		icmp_pkt_err_sent = 0;
3595 	}
3596 	/*
3597 	 * If we are in a burst update the token bucket filter.
3598 	 * Update the "last" time to be close to "now" but make sure
3599 	 * we don't loose precision.
3600 	 */
3601 	if (icmp_pkt_err_sent != 0) {
3602 		refilled = (now - icmp_pkt_err_last)/err_interval;
3603 		if (refilled > icmp_pkt_err_sent) {
3604 			icmp_pkt_err_sent = 0;
3605 		} else {
3606 			icmp_pkt_err_sent -= refilled;
3607 			icmp_pkt_err_last += refilled * err_interval;
3608 		}
3609 	}
3610 	if (icmp_pkt_err_sent == 0) {
3611 		/* Start of new burst */
3612 		icmp_pkt_err_last = now;
3613 	}
3614 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3615 		icmp_pkt_err_sent++;
3616 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3617 		    icmp_pkt_err_sent));
3618 		return (B_FALSE);
3619 	}
3620 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3621 	return (B_TRUE);
3622 }
3623 
3624 /*
3625  * Check if it is ok to send an IPv4 ICMP error packet in
3626  * response to the IPv4 packet in mp.
3627  * Free the message and return null if no
3628  * ICMP error packet should be sent.
3629  */
3630 static mblk_t *
3631 icmp_pkt_err_ok(mblk_t *mp)
3632 {
3633 	icmph_t	*icmph;
3634 	ipha_t	*ipha;
3635 	uint_t	len_needed;
3636 	ire_t	*src_ire;
3637 	ire_t	*dst_ire;
3638 
3639 	if (!mp)
3640 		return (NULL);
3641 	ipha = (ipha_t *)mp->b_rptr;
3642 	if (ip_csum_hdr(ipha)) {
3643 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3644 		freemsg(mp);
3645 		return (NULL);
3646 	}
3647 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3648 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3649 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3650 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3651 	if (src_ire != NULL || dst_ire != NULL ||
3652 	    CLASSD(ipha->ipha_dst) ||
3653 	    CLASSD(ipha->ipha_src) ||
3654 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3655 		/* Note: only errors to the fragment with offset 0 */
3656 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3657 		freemsg(mp);
3658 		if (src_ire != NULL)
3659 			ire_refrele(src_ire);
3660 		if (dst_ire != NULL)
3661 			ire_refrele(dst_ire);
3662 		return (NULL);
3663 	}
3664 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3665 		/*
3666 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3667 		 * errors in response to any ICMP errors.
3668 		 */
3669 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3670 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3671 			if (!pullupmsg(mp, len_needed)) {
3672 				BUMP_MIB(&icmp_mib, icmpInErrors);
3673 				freemsg(mp);
3674 				return (NULL);
3675 			}
3676 			ipha = (ipha_t *)mp->b_rptr;
3677 		}
3678 		icmph = (icmph_t *)
3679 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3680 		switch (icmph->icmph_type) {
3681 		case ICMP_DEST_UNREACHABLE:
3682 		case ICMP_SOURCE_QUENCH:
3683 		case ICMP_TIME_EXCEEDED:
3684 		case ICMP_PARAM_PROBLEM:
3685 		case ICMP_REDIRECT:
3686 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3687 			freemsg(mp);
3688 			return (NULL);
3689 		default:
3690 			break;
3691 		}
3692 	}
3693 	/*
3694 	 * If this is a labeled system, then check to see if we're allowed to
3695 	 * send a response to this particular sender.  If not, then just drop.
3696 	 */
3697 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3698 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3699 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3700 		freemsg(mp);
3701 		return (NULL);
3702 	}
3703 	if (icmp_err_rate_limit()) {
3704 		/*
3705 		 * Only send ICMP error packets every so often.
3706 		 * This should be done on a per port/source basis,
3707 		 * but for now this will suffice.
3708 		 */
3709 		freemsg(mp);
3710 		return (NULL);
3711 	}
3712 	return (mp);
3713 }
3714 
3715 /*
3716  * Generate an ICMP redirect message.
3717  */
3718 static void
3719 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3720 {
3721 	icmph_t	icmph;
3722 
3723 	/*
3724 	 * We are called from ip_rput where we could
3725 	 * not have attached an IPSEC_IN.
3726 	 */
3727 	ASSERT(mp->b_datap->db_type == M_DATA);
3728 
3729 	if (!(mp = icmp_pkt_err_ok(mp))) {
3730 		return;
3731 	}
3732 
3733 	bzero(&icmph, sizeof (icmph_t));
3734 	icmph.icmph_type = ICMP_REDIRECT;
3735 	icmph.icmph_code = 1;
3736 	icmph.icmph_rd_gateway = gateway;
3737 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3738 	/* Redirects sent by router, and router is global zone */
3739 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID);
3740 }
3741 
3742 /*
3743  * Generate an ICMP time exceeded message.
3744  */
3745 void
3746 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3747 {
3748 	icmph_t	icmph;
3749 	boolean_t mctl_present;
3750 	mblk_t *first_mp;
3751 
3752 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3753 
3754 	if (!(mp = icmp_pkt_err_ok(mp))) {
3755 		if (mctl_present)
3756 			freeb(first_mp);
3757 		return;
3758 	}
3759 
3760 	bzero(&icmph, sizeof (icmph_t));
3761 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3762 	icmph.icmph_code = code;
3763 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3764 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3765 }
3766 
3767 /*
3768  * Generate an ICMP unreachable message.
3769  */
3770 void
3771 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3772 {
3773 	icmph_t	icmph;
3774 	mblk_t *first_mp;
3775 	boolean_t mctl_present;
3776 
3777 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3778 
3779 	if (!(mp = icmp_pkt_err_ok(mp))) {
3780 		if (mctl_present)
3781 			freeb(first_mp);
3782 		return;
3783 	}
3784 
3785 	bzero(&icmph, sizeof (icmph_t));
3786 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3787 	icmph.icmph_code = code;
3788 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3789 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3790 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3791 	    zoneid);
3792 }
3793 
3794 /*
3795  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3796  * duplicate.  As long as someone else holds the address, the interface will
3797  * stay down.  When that conflict goes away, the interface is brought back up.
3798  * This is done so that accidental shutdowns of addresses aren't made
3799  * permanent.  Your server will recover from a failure.
3800  *
3801  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3802  * user space process (dhcpagent).
3803  *
3804  * Recovery completes if ARP reports that the address is now ours (via
3805  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3806  *
3807  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3808  */
3809 static void
3810 ipif_dup_recovery(void *arg)
3811 {
3812 	ipif_t *ipif = arg;
3813 	ill_t *ill = ipif->ipif_ill;
3814 	mblk_t *arp_add_mp;
3815 	mblk_t *arp_del_mp;
3816 	area_t *area;
3817 
3818 	ipif->ipif_recovery_id = 0;
3819 
3820 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3821 	    (ipif->ipif_flags & IPIF_POINTOPOINT)) {
3822 		/* No reason to try to bring this address back. */
3823 		return;
3824 	}
3825 
3826 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3827 		goto alloc_fail;
3828 
3829 	if (ipif->ipif_arp_del_mp == NULL) {
3830 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3831 			goto alloc_fail;
3832 		ipif->ipif_arp_del_mp = arp_del_mp;
3833 	}
3834 
3835 	/* Setting the 'unverified' flag restarts DAD */
3836 	area = (area_t *)arp_add_mp->b_rptr;
3837 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3838 	    ACE_F_UNVERIFIED;
3839 	putnext(ill->ill_rq, arp_add_mp);
3840 	return;
3841 
3842 alloc_fail:
3843 	/* On allocation failure, just restart the timer */
3844 	freemsg(arp_add_mp);
3845 	if (ip_dup_recovery > 0) {
3846 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3847 		    MSEC_TO_TICK(ip_dup_recovery));
3848 	}
3849 }
3850 
3851 /*
3852  * This is for exclusive changes due to ARP.  Either tear down an interface due
3853  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3854  */
3855 /* ARGSUSED */
3856 static void
3857 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3858 {
3859 	ill_t	*ill = rq->q_ptr;
3860 	arh_t *arh;
3861 	ipaddr_t src;
3862 	ipif_t	*ipif;
3863 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3864 	char hbuf[MAC_STR_LEN];
3865 	char sbuf[INET_ADDRSTRLEN];
3866 	const char *failtype;
3867 	boolean_t bring_up;
3868 
3869 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3870 	case AR_CN_READY:
3871 		failtype = NULL;
3872 		bring_up = B_TRUE;
3873 		break;
3874 	case AR_CN_FAILED:
3875 		failtype = "in use";
3876 		bring_up = B_FALSE;
3877 		break;
3878 	default:
3879 		failtype = "claimed";
3880 		bring_up = B_FALSE;
3881 		break;
3882 	}
3883 
3884 	arh = (arh_t *)mp->b_cont->b_rptr;
3885 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3886 
3887 	/* Handle failures due to probes */
3888 	if (src == 0) {
3889 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3890 		    IP_ADDR_LEN);
3891 	}
3892 
3893 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3894 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3895 	    sizeof (hbuf));
3896 	(void) ip_dot_addr(src, sbuf);
3897 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3898 
3899 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3900 		    ipif->ipif_lcl_addr != src) {
3901 			continue;
3902 		}
3903 
3904 		/*
3905 		 * If we failed on a recovery probe, then restart the timer to
3906 		 * try again later.
3907 		 */
3908 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3909 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3910 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3911 		    ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0) {
3912 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3913 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3914 			continue;
3915 		}
3916 
3917 		/*
3918 		 * If what we're trying to do has already been done, then do
3919 		 * nothing.
3920 		 */
3921 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3922 			continue;
3923 
3924 		if (ipif->ipif_id != 0) {
3925 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3926 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3927 			    ipif->ipif_id);
3928 		}
3929 		if (failtype == NULL) {
3930 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3931 			    ibuf);
3932 		} else {
3933 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3934 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3935 		}
3936 
3937 		if (bring_up) {
3938 			ASSERT(ill->ill_dl_up);
3939 			/*
3940 			 * Free up the ARP delete message so we can allocate
3941 			 * a fresh one through the normal path.
3942 			 */
3943 			freemsg(ipif->ipif_arp_del_mp);
3944 			ipif->ipif_arp_del_mp = NULL;
3945 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3946 			    EINPROGRESS) {
3947 				ipif->ipif_addr_ready = 1;
3948 				(void) ipif_up_done(ipif);
3949 			}
3950 			continue;
3951 		}
3952 
3953 		mutex_enter(&ill->ill_lock);
3954 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3955 		ipif->ipif_flags |= IPIF_DUPLICATE;
3956 		ill->ill_ipif_dup_count++;
3957 		mutex_exit(&ill->ill_lock);
3958 		/*
3959 		 * Already exclusive on the ill; no need to handle deferred
3960 		 * processing here.
3961 		 */
3962 		(void) ipif_down(ipif, NULL, NULL);
3963 		ipif_down_tail(ipif);
3964 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3965 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3966 		    ip_dup_recovery > 0) {
3967 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3968 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3969 		}
3970 	}
3971 	freemsg(mp);
3972 }
3973 
3974 /* ARGSUSED */
3975 static void
3976 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3977 {
3978 	ill_t	*ill = rq->q_ptr;
3979 	arh_t *arh;
3980 	ipaddr_t src;
3981 	ipif_t	*ipif;
3982 
3983 	arh = (arh_t *)mp->b_cont->b_rptr;
3984 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3985 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3986 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3987 			(void) ipif_resolver_up(ipif, Res_act_defend);
3988 	}
3989 	freemsg(mp);
3990 }
3991 
3992 /*
3993  * News from ARP.  ARP sends notification of interesting events down
3994  * to its clients using M_CTL messages with the interesting ARP packet
3995  * attached via b_cont.
3996  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3997  * queue as opposed to ARP sending the message to all the clients, i.e. all
3998  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3999  * table if a cache IRE is found to delete all the entries for the address in
4000  * the packet.
4001  */
4002 static void
4003 ip_arp_news(queue_t *q, mblk_t *mp)
4004 {
4005 	arcn_t		*arcn;
4006 	arh_t		*arh;
4007 	ire_t		*ire = NULL;
4008 	char		hbuf[MAC_STR_LEN];
4009 	char		sbuf[INET_ADDRSTRLEN];
4010 	ipaddr_t	src;
4011 	in6_addr_t	v6src;
4012 	boolean_t	isv6 = B_FALSE;
4013 	ipif_t		*ipif;
4014 	ill_t		*ill;
4015 
4016 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
4017 		if (q->q_next) {
4018 			putnext(q, mp);
4019 		} else
4020 			freemsg(mp);
4021 		return;
4022 	}
4023 	arh = (arh_t *)mp->b_cont->b_rptr;
4024 	/* Is it one we are interested in? */
4025 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
4026 		isv6 = B_TRUE;
4027 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
4028 		    IPV6_ADDR_LEN);
4029 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
4030 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
4031 		    IP_ADDR_LEN);
4032 	} else {
4033 		freemsg(mp);
4034 		return;
4035 	}
4036 
4037 	ill = q->q_ptr;
4038 
4039 	arcn = (arcn_t *)mp->b_rptr;
4040 	switch (arcn->arcn_code) {
4041 	case AR_CN_BOGON:
4042 		/*
4043 		 * Someone is sending ARP packets with a source protocol
4044 		 * address that we have published and for which we believe our
4045 		 * entry is authoritative and (when ill_arp_extend is set)
4046 		 * verified to be unique on the network.
4047 		 *
4048 		 * The ARP module internally handles the cases where the sender
4049 		 * is just probing (for DAD) and where the hardware address of
4050 		 * a non-authoritative entry has changed.  Thus, these are the
4051 		 * real conflicts, and we have to do resolution.
4052 		 *
4053 		 * We back away quickly from the address if it's from DHCP or
4054 		 * otherwise temporary and hasn't been used recently (or at
4055 		 * all).  We'd like to include "deprecated" addresses here as
4056 		 * well (as there's no real reason to defend something we're
4057 		 * discarding), but IPMP "reuses" this flag to mean something
4058 		 * other than the standard meaning.
4059 		 *
4060 		 * If the ARP module above is not extended (meaning that it
4061 		 * doesn't know how to defend the address), then we just log
4062 		 * the problem as we always did and continue on.  It's not
4063 		 * right, but there's little else we can do, and those old ATM
4064 		 * users are going away anyway.
4065 		 */
4066 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4067 		    hbuf, sizeof (hbuf));
4068 		(void) ip_dot_addr(src, sbuf);
4069 		if (isv6)
4070 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
4071 		else
4072 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
4073 
4074 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4075 			uint32_t now;
4076 			uint32_t maxage;
4077 			clock_t lused;
4078 			uint_t maxdefense;
4079 			uint_t defs;
4080 
4081 			/*
4082 			 * First, figure out if this address hasn't been used
4083 			 * in a while.  If it hasn't, then it's a better
4084 			 * candidate for abandoning.
4085 			 */
4086 			ipif = ire->ire_ipif;
4087 			ASSERT(ipif != NULL);
4088 			now = gethrestime_sec();
4089 			maxage = now - ire->ire_create_time;
4090 			if (maxage > ip_max_temp_idle)
4091 				maxage = ip_max_temp_idle;
4092 			lused = drv_hztousec(ddi_get_lbolt() -
4093 			    ire->ire_last_used_time) / MICROSEC + 1;
4094 			if (lused >= maxage && (ipif->ipif_flags &
4095 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4096 				maxdefense = ip_max_temp_defend;
4097 			else
4098 				maxdefense = ip_max_defend;
4099 
4100 			/*
4101 			 * Now figure out how many times we've defended
4102 			 * ourselves.  Ignore defenses that happened long in
4103 			 * the past.
4104 			 */
4105 			mutex_enter(&ire->ire_lock);
4106 			if ((defs = ire->ire_defense_count) > 0 &&
4107 			    now - ire->ire_defense_time > ip_defend_interval) {
4108 				ire->ire_defense_count = defs = 0;
4109 			}
4110 			ire->ire_defense_count++;
4111 			ire->ire_defense_time = now;
4112 			mutex_exit(&ire->ire_lock);
4113 			ill_refhold(ill);
4114 			ire_refrele(ire);
4115 
4116 			/*
4117 			 * If we've defended ourselves too many times already,
4118 			 * then give up and tear down the interface(s) using
4119 			 * this address.  Otherwise, defend by sending out a
4120 			 * gratuitous ARP.
4121 			 */
4122 			if (defs >= maxdefense && ill->ill_arp_extend) {
4123 				(void) qwriter_ip(NULL, ill, q, mp,
4124 				    ip_arp_excl, CUR_OP, B_FALSE);
4125 			} else {
4126 				cmn_err(CE_WARN,
4127 				    "node %s is using our IP address %s on %s",
4128 				    hbuf, sbuf, ill->ill_name);
4129 				/*
4130 				 * If this is an old (ATM) ARP module, then
4131 				 * don't try to defend the address.  Remain
4132 				 * compatible with the old behavior.  Defend
4133 				 * only with new ARP.
4134 				 */
4135 				if (ill->ill_arp_extend) {
4136 					(void) qwriter_ip(NULL, ill, q, mp,
4137 					    ip_arp_defend, CUR_OP, B_FALSE);
4138 				} else {
4139 					ill_refrele(ill);
4140 				}
4141 			}
4142 			return;
4143 		}
4144 		cmn_err(CE_WARN,
4145 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4146 		    hbuf, sbuf, ill->ill_name);
4147 		if (ire != NULL)
4148 			ire_refrele(ire);
4149 		break;
4150 	case AR_CN_ANNOUNCE:
4151 		if (isv6) {
4152 			/*
4153 			 * For XRESOLV interfaces.
4154 			 * Delete the IRE cache entry and NCE for this
4155 			 * v6 address
4156 			 */
4157 			ip_ire_clookup_and_delete_v6(&v6src);
4158 			/*
4159 			 * If v6src is a non-zero, it's a router address
4160 			 * as below. Do the same sort of thing to clean
4161 			 * out off-net IRE_CACHE entries that go through
4162 			 * the router.
4163 			 */
4164 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4165 				ire_walk_v6(ire_delete_cache_gw_v6,
4166 				    (char *)&v6src, ALL_ZONES);
4167 			}
4168 		} else {
4169 			nce_hw_map_t hwm;
4170 
4171 			/*
4172 			 * ARP gives us a copy of any packet where it thinks
4173 			 * the address has changed, so that we can update our
4174 			 * caches.  We're responsible for caching known answers
4175 			 * in the current design.  We check whether the
4176 			 * hardware address really has changed in all of our
4177 			 * entries that have cached this mapping, and if so, we
4178 			 * blow them away.  This way we will immediately pick
4179 			 * up the rare case of a host changing hardware
4180 			 * address.
4181 			 */
4182 			if (src == 0)
4183 				break;
4184 			hwm.hwm_addr = src;
4185 			hwm.hwm_hwlen = arh->arh_hlen;
4186 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4187 			ndp_walk_common(&ndp4, NULL,
4188 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4189 		}
4190 		break;
4191 	case AR_CN_READY:
4192 		/* No external v6 resolver has a contract to use this */
4193 		if (isv6)
4194 			break;
4195 		/* If the link is down, we'll retry this later */
4196 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4197 			break;
4198 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4199 		    NULL, NULL);
4200 		if (ipif != NULL) {
4201 			/*
4202 			 * If this is a duplicate recovery, then we now need to
4203 			 * go exclusive to bring this thing back up.
4204 			 */
4205 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4206 			    IPIF_DUPLICATE) {
4207 				ipif_refrele(ipif);
4208 				ill_refhold(ill);
4209 				(void) qwriter_ip(NULL, ill, q, mp,
4210 				    ip_arp_excl, CUR_OP, B_FALSE);
4211 				return;
4212 			}
4213 			/*
4214 			 * If this is the first notice that this address is
4215 			 * ready, then let the user know now.
4216 			 */
4217 			if ((ipif->ipif_flags & IPIF_UP) &&
4218 			    !ipif->ipif_addr_ready) {
4219 				ipif_mask_reply(ipif);
4220 				ip_rts_ifmsg(ipif);
4221 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4222 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4223 			}
4224 			ipif->ipif_addr_ready = 1;
4225 			ipif_refrele(ipif);
4226 		}
4227 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp));
4228 		if (ire != NULL) {
4229 			ire->ire_defense_count = 0;
4230 			ire_refrele(ire);
4231 		}
4232 		break;
4233 	case AR_CN_FAILED:
4234 		/* No external v6 resolver has a contract to use this */
4235 		if (isv6)
4236 			break;
4237 		ill_refhold(ill);
4238 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4239 		    B_FALSE);
4240 		return;
4241 	}
4242 	freemsg(mp);
4243 }
4244 
4245 /*
4246  * Create a mblk suitable for carrying the interface index and/or source link
4247  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4248  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4249  * application.
4250  */
4251 mblk_t *
4252 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
4253 {
4254 	mblk_t		*mp;
4255 	in_pktinfo_t	*pinfo;
4256 	ipha_t *ipha;
4257 	struct ether_header *pether;
4258 
4259 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
4260 	if (mp == NULL) {
4261 		ip1dbg(("ip_add_info: allocation failure.\n"));
4262 		return (data_mp);
4263 	}
4264 
4265 	ipha	= (ipha_t *)data_mp->b_rptr;
4266 	pinfo = (in_pktinfo_t *)mp->b_rptr;
4267 	bzero(pinfo, sizeof (in_pktinfo_t));
4268 	pinfo->in_pkt_flags = (uchar_t)flags;
4269 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4270 
4271 	if (flags & IPF_RECVIF)
4272 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4273 
4274 	pether = (struct ether_header *)((char *)ipha
4275 	    - sizeof (struct ether_header));
4276 	/*
4277 	 * Make sure the interface is an ethernet type, since this option
4278 	 * is currently supported only on this type of interface. Also make
4279 	 * sure we are pointing correctly above db_base.
4280 	 */
4281 
4282 	if ((flags & IPF_RECVSLLA) &&
4283 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4284 	    (ill->ill_type == IFT_ETHER) &&
4285 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4286 
4287 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
4288 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4289 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
4290 	} else {
4291 		/*
4292 		 * Clear the bit. Indicate to upper layer that IP is not
4293 		 * sending this ancillary info.
4294 		 */
4295 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
4296 	}
4297 
4298 	mp->b_datap->db_type = M_CTL;
4299 	mp->b_wptr += sizeof (in_pktinfo_t);
4300 	mp->b_cont = data_mp;
4301 
4302 	return (mp);
4303 }
4304 
4305 /*
4306  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4307  * part of the bind request.
4308  */
4309 
4310 boolean_t
4311 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4312 {
4313 	ipsec_in_t *ii;
4314 
4315 	ASSERT(policy_mp != NULL);
4316 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4317 
4318 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4319 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4320 
4321 	connp->conn_policy = ii->ipsec_in_policy;
4322 	ii->ipsec_in_policy = NULL;
4323 
4324 	if (ii->ipsec_in_action != NULL) {
4325 		if (connp->conn_latch == NULL) {
4326 			connp->conn_latch = iplatch_create();
4327 			if (connp->conn_latch == NULL)
4328 				return (B_FALSE);
4329 		}
4330 		ipsec_latch_inbound(connp->conn_latch, ii);
4331 	}
4332 	return (B_TRUE);
4333 }
4334 
4335 /*
4336  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4337  * and to arrange for power-fanout assist.  The ULP is identified by
4338  * adding a single byte at the end of the original bind message.
4339  * A ULP other than UDP or TCP that wishes to be recognized passes
4340  * down a bind with a zero length address.
4341  *
4342  * The binding works as follows:
4343  * - A zero byte address means just bind to the protocol.
4344  * - A four byte address is treated as a request to validate
4345  *   that the address is a valid local address, appropriate for
4346  *   an application to bind to. This does not affect any fanout
4347  *   information in IP.
4348  * - A sizeof sin_t byte address is used to bind to only the local address
4349  *   and port.
4350  * - A sizeof ipa_conn_t byte address contains complete fanout information
4351  *   consisting of local and remote addresses and ports.  In
4352  *   this case, the addresses are both validated as appropriate
4353  *   for this operation, and, if so, the information is retained
4354  *   for use in the inbound fanout.
4355  *
4356  * The ULP (except in the zero-length bind) can append an
4357  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4358  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4359  * a copy of the source or destination IRE (source for local bind;
4360  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4361  * policy information contained should be copied on to the conn.
4362  *
4363  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4364  */
4365 mblk_t *
4366 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4367 {
4368 	ssize_t		len;
4369 	struct T_bind_req	*tbr;
4370 	sin_t		*sin;
4371 	ipa_conn_t	*ac;
4372 	uchar_t		*ucp;
4373 	mblk_t		*mp1;
4374 	boolean_t	ire_requested;
4375 	boolean_t	ipsec_policy_set = B_FALSE;
4376 	int		error = 0;
4377 	int		protocol;
4378 	ipa_conn_x_t	*acx;
4379 
4380 	ASSERT(!connp->conn_af_isv6);
4381 	connp->conn_pkt_isv6 = B_FALSE;
4382 
4383 	len = MBLKL(mp);
4384 	if (len < (sizeof (*tbr) + 1)) {
4385 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4386 		    "ip_bind: bogus msg, len %ld", len);
4387 		/* XXX: Need to return something better */
4388 		goto bad_addr;
4389 	}
4390 	/* Back up and extract the protocol identifier. */
4391 	mp->b_wptr--;
4392 	protocol = *mp->b_wptr & 0xFF;
4393 	tbr = (struct T_bind_req *)mp->b_rptr;
4394 	/* Reset the message type in preparation for shipping it back. */
4395 	DB_TYPE(mp) = M_PCPROTO;
4396 
4397 	connp->conn_ulp = (uint8_t)protocol;
4398 
4399 	/*
4400 	 * Check for a zero length address.  This is from a protocol that
4401 	 * wants to register to receive all packets of its type.
4402 	 */
4403 	if (tbr->ADDR_length == 0) {
4404 		/*
4405 		 * These protocols are now intercepted in ip_bind_v6().
4406 		 * Reject protocol-level binds here for now.
4407 		 *
4408 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4409 		 * so that the protocol type cannot be SCTP.
4410 		 */
4411 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4412 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4413 			goto bad_addr;
4414 		}
4415 
4416 		/*
4417 		 *
4418 		 * The udp module never sends down a zero-length address,
4419 		 * and allowing this on a labeled system will break MLP
4420 		 * functionality.
4421 		 */
4422 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4423 			goto bad_addr;
4424 
4425 		if (connp->conn_mac_exempt)
4426 			goto bad_addr;
4427 
4428 		/* No hash here really.  The table is big enough. */
4429 		connp->conn_srcv6 = ipv6_all_zeros;
4430 
4431 		ipcl_proto_insert(connp, protocol);
4432 
4433 		tbr->PRIM_type = T_BIND_ACK;
4434 		return (mp);
4435 	}
4436 
4437 	/* Extract the address pointer from the message. */
4438 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4439 	    tbr->ADDR_length);
4440 	if (ucp == NULL) {
4441 		ip1dbg(("ip_bind: no address\n"));
4442 		goto bad_addr;
4443 	}
4444 	if (!OK_32PTR(ucp)) {
4445 		ip1dbg(("ip_bind: unaligned address\n"));
4446 		goto bad_addr;
4447 	}
4448 	/*
4449 	 * Check for trailing mps.
4450 	 */
4451 
4452 	mp1 = mp->b_cont;
4453 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4454 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4455 
4456 	switch (tbr->ADDR_length) {
4457 	default:
4458 		ip1dbg(("ip_bind: bad address length %d\n",
4459 		    (int)tbr->ADDR_length));
4460 		goto bad_addr;
4461 
4462 	case IP_ADDR_LEN:
4463 		/* Verification of local address only */
4464 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4465 		    ire_requested, ipsec_policy_set, B_FALSE);
4466 		break;
4467 
4468 	case sizeof (sin_t):
4469 		sin = (sin_t *)ucp;
4470 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4471 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4472 		if (protocol == IPPROTO_TCP)
4473 			connp->conn_recv = tcp_conn_request;
4474 		break;
4475 
4476 	case sizeof (ipa_conn_t):
4477 		ac = (ipa_conn_t *)ucp;
4478 		/* For raw socket, the local port is not set. */
4479 		if (ac->ac_lport == 0)
4480 			ac->ac_lport = connp->conn_lport;
4481 		/* Always verify destination reachability. */
4482 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4483 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4484 		    ipsec_policy_set, B_TRUE, B_TRUE);
4485 		if (protocol == IPPROTO_TCP)
4486 			connp->conn_recv = tcp_input;
4487 		break;
4488 
4489 	case sizeof (ipa_conn_x_t):
4490 		acx = (ipa_conn_x_t *)ucp;
4491 		/*
4492 		 * Whether or not to verify destination reachability depends
4493 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4494 		 */
4495 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4496 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4497 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4498 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4499 		if (protocol == IPPROTO_TCP)
4500 			connp->conn_recv = tcp_input;
4501 		break;
4502 	}
4503 	if (error == EINPROGRESS)
4504 		return (NULL);
4505 	else if (error != 0)
4506 		goto bad_addr;
4507 	/*
4508 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4509 	 * We can't do this in ip_bind_insert_ire because the policy
4510 	 * may not have been inherited at that point in time and hence
4511 	 * conn_out_enforce_policy may not be set.
4512 	 */
4513 	mp1 = mp->b_cont;
4514 	if (ire_requested && connp->conn_out_enforce_policy &&
4515 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4516 		ire_t *ire = (ire_t *)mp1->b_rptr;
4517 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4518 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4519 	}
4520 
4521 	/* Send it home. */
4522 	mp->b_datap->db_type = M_PCPROTO;
4523 	tbr->PRIM_type = T_BIND_ACK;
4524 	return (mp);
4525 
4526 bad_addr:
4527 	/*
4528 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4529 	 * a unix errno.
4530 	 */
4531 	if (error > 0)
4532 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4533 	else
4534 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4535 	return (mp);
4536 }
4537 
4538 /*
4539  * Here address is verified to be a valid local address.
4540  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4541  * address is also considered a valid local address.
4542  * In the case of a broadcast/multicast address, however, the
4543  * upper protocol is expected to reset the src address
4544  * to 0 if it sees a IRE_BROADCAST type returned so that
4545  * no packets are emitted with broadcast/multicast address as
4546  * source address (that violates hosts requirements RFC1122)
4547  * The addresses valid for bind are:
4548  *	(1) - INADDR_ANY (0)
4549  *	(2) - IP address of an UP interface
4550  *	(3) - IP address of a DOWN interface
4551  *	(4) - valid local IP broadcast addresses. In this case
4552  *	the conn will only receive packets destined to
4553  *	the specified broadcast address.
4554  *	(5) - a multicast address. In this case
4555  *	the conn will only receive packets destined to
4556  *	the specified multicast address. Note: the
4557  *	application still has to issue an
4558  *	IP_ADD_MEMBERSHIP socket option.
4559  *
4560  * On error, return -1 for TBADADDR otherwise pass the
4561  * errno with TSYSERR reply.
4562  *
4563  * In all the above cases, the bound address must be valid in the current zone.
4564  * When the address is loopback, multicast or broadcast, there might be many
4565  * matching IREs so bind has to look up based on the zone.
4566  *
4567  * Note: lport is in network byte order.
4568  */
4569 int
4570 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4571     boolean_t ire_requested, boolean_t ipsec_policy_set,
4572     boolean_t fanout_insert)
4573 {
4574 	int		error = 0;
4575 	ire_t		*src_ire;
4576 	mblk_t		*policy_mp;
4577 	ipif_t		*ipif;
4578 	zoneid_t	zoneid;
4579 
4580 	if (ipsec_policy_set) {
4581 		policy_mp = mp->b_cont;
4582 	}
4583 
4584 	/*
4585 	 * If it was previously connected, conn_fully_bound would have
4586 	 * been set.
4587 	 */
4588 	connp->conn_fully_bound = B_FALSE;
4589 
4590 	src_ire = NULL;
4591 	ipif = NULL;
4592 
4593 	zoneid = IPCL_ZONEID(connp);
4594 
4595 	if (src_addr) {
4596 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4597 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4598 		/*
4599 		 * If an address other than 0.0.0.0 is requested,
4600 		 * we verify that it is a valid address for bind
4601 		 * Note: Following code is in if-else-if form for
4602 		 * readability compared to a condition check.
4603 		 */
4604 		/* LINTED - statement has no consequent */
4605 		if (IRE_IS_LOCAL(src_ire)) {
4606 			/*
4607 			 * (2) Bind to address of local UP interface
4608 			 */
4609 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4610 			/*
4611 			 * (4) Bind to broadcast address
4612 			 * Note: permitted only from transports that
4613 			 * request IRE
4614 			 */
4615 			if (!ire_requested)
4616 				error = EADDRNOTAVAIL;
4617 		} else {
4618 			/*
4619 			 * (3) Bind to address of local DOWN interface
4620 			 * (ipif_lookup_addr() looks up all interfaces
4621 			 * but we do not get here for UP interfaces
4622 			 * - case (2) above)
4623 			 * We put the protocol byte back into the mblk
4624 			 * since we may come back via ip_wput_nondata()
4625 			 * later with this mblk if ipif_lookup_addr chooses
4626 			 * to defer processing.
4627 			 */
4628 			*mp->b_wptr++ = (char)connp->conn_ulp;
4629 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4630 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4631 			    &error)) != NULL) {
4632 				ipif_refrele(ipif);
4633 			} else if (error == EINPROGRESS) {
4634 				if (src_ire != NULL)
4635 					ire_refrele(src_ire);
4636 				return (EINPROGRESS);
4637 			} else if (CLASSD(src_addr)) {
4638 				error = 0;
4639 				if (src_ire != NULL)
4640 					ire_refrele(src_ire);
4641 				/*
4642 				 * (5) bind to multicast address.
4643 				 * Fake out the IRE returned to upper
4644 				 * layer to be a broadcast IRE.
4645 				 */
4646 				src_ire = ire_ctable_lookup(
4647 				    INADDR_BROADCAST, INADDR_ANY,
4648 				    IRE_BROADCAST, NULL, zoneid, NULL,
4649 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4650 				if (src_ire == NULL || !ire_requested)
4651 					error = EADDRNOTAVAIL;
4652 			} else {
4653 				/*
4654 				 * Not a valid address for bind
4655 				 */
4656 				error = EADDRNOTAVAIL;
4657 			}
4658 			/*
4659 			 * Just to keep it consistent with the processing in
4660 			 * ip_bind_v4()
4661 			 */
4662 			mp->b_wptr--;
4663 		}
4664 		if (error) {
4665 			/* Red Alert!  Attempting to be a bogon! */
4666 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4667 			    ntohl(src_addr)));
4668 			goto bad_addr;
4669 		}
4670 	}
4671 
4672 	/*
4673 	 * Allow setting new policies. For example, disconnects come
4674 	 * down as ipa_t bind. As we would have set conn_policy_cached
4675 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4676 	 * can change after the disconnect.
4677 	 */
4678 	connp->conn_policy_cached = B_FALSE;
4679 
4680 	/*
4681 	 * If not fanout_insert this was just an address verification
4682 	 */
4683 	if (fanout_insert) {
4684 		/*
4685 		 * The addresses have been verified. Time to insert in
4686 		 * the correct fanout list.
4687 		 */
4688 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4689 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4690 		connp->conn_lport = lport;
4691 		connp->conn_fport = 0;
4692 		/*
4693 		 * Do we need to add a check to reject Multicast packets
4694 		 */
4695 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4696 	}
4697 
4698 	if (error == 0) {
4699 		if (ire_requested) {
4700 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4701 				error = -1;
4702 				/* Falls through to bad_addr */
4703 			}
4704 		} else if (ipsec_policy_set) {
4705 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4706 				error = -1;
4707 				/* Falls through to bad_addr */
4708 			}
4709 		}
4710 	}
4711 bad_addr:
4712 	if (error != 0) {
4713 		if (connp->conn_anon_port) {
4714 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4715 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4716 			    B_FALSE);
4717 		}
4718 		connp->conn_mlp_type = mlptSingle;
4719 	}
4720 	if (src_ire != NULL)
4721 		IRE_REFRELE(src_ire);
4722 	if (ipsec_policy_set) {
4723 		ASSERT(policy_mp == mp->b_cont);
4724 		ASSERT(policy_mp != NULL);
4725 		freeb(policy_mp);
4726 		/*
4727 		 * As of now assume that nothing else accompanies
4728 		 * IPSEC_POLICY_SET.
4729 		 */
4730 		mp->b_cont = NULL;
4731 	}
4732 	return (error);
4733 }
4734 
4735 /*
4736  * Verify that both the source and destination addresses
4737  * are valid.  If verify_dst is false, then the destination address may be
4738  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4739  * destination reachability, while tunnels do not.
4740  * Note that we allow connect to broadcast and multicast
4741  * addresses when ire_requested is set. Thus the ULP
4742  * has to check for IRE_BROADCAST and multicast.
4743  *
4744  * Returns zero if ok.
4745  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4746  * (for use with TSYSERR reply).
4747  *
4748  * Note: lport and fport are in network byte order.
4749  */
4750 int
4751 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4752     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4753     boolean_t ire_requested, boolean_t ipsec_policy_set,
4754     boolean_t fanout_insert, boolean_t verify_dst)
4755 {
4756 	ire_t		*src_ire;
4757 	ire_t		*dst_ire;
4758 	int		error = 0;
4759 	int 		protocol;
4760 	mblk_t		*policy_mp;
4761 	ire_t		*sire = NULL;
4762 	ire_t		*md_dst_ire = NULL;
4763 	ill_t		*md_ill = NULL;
4764 	zoneid_t	zoneid;
4765 	ipaddr_t	src_addr = *src_addrp;
4766 
4767 	src_ire = dst_ire = NULL;
4768 	protocol = *mp->b_wptr & 0xFF;
4769 
4770 	/*
4771 	 * If we never got a disconnect before, clear it now.
4772 	 */
4773 	connp->conn_fully_bound = B_FALSE;
4774 
4775 	if (ipsec_policy_set) {
4776 		policy_mp = mp->b_cont;
4777 	}
4778 
4779 	zoneid = IPCL_ZONEID(connp);
4780 
4781 	if (CLASSD(dst_addr)) {
4782 		/* Pick up an IRE_BROADCAST */
4783 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4784 		    NULL, zoneid, MBLK_GETLABEL(mp),
4785 		    (MATCH_IRE_RECURSIVE |
4786 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4787 		    MATCH_IRE_SECATTR));
4788 	} else {
4789 		/*
4790 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4791 		 * and onlink ipif is not found set ENETUNREACH error.
4792 		 */
4793 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4794 			ipif_t *ipif;
4795 
4796 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4797 			    dst_addr : connp->conn_nexthop_v4,
4798 			    connp->conn_zoneid);
4799 			if (ipif == NULL) {
4800 				error = ENETUNREACH;
4801 				goto bad_addr;
4802 			}
4803 			ipif_refrele(ipif);
4804 		}
4805 
4806 		if (connp->conn_nexthop_set) {
4807 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4808 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4809 			    MATCH_IRE_SECATTR);
4810 		} else {
4811 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4812 			    &sire, zoneid, MBLK_GETLABEL(mp),
4813 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4814 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4815 			    MATCH_IRE_SECATTR));
4816 		}
4817 	}
4818 	/*
4819 	 * dst_ire can't be a broadcast when not ire_requested.
4820 	 * We also prevent ire's with src address INADDR_ANY to
4821 	 * be used, which are created temporarily for
4822 	 * sending out packets from endpoints that have
4823 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4824 	 * reachable.  If verify_dst is false, the destination needn't be
4825 	 * reachable.
4826 	 *
4827 	 * If we match on a reject or black hole, then we've got a
4828 	 * local failure.  May as well fail out the connect() attempt,
4829 	 * since it's never going to succeed.
4830 	 */
4831 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4832 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4833 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4834 		/*
4835 		 * If we're verifying destination reachability, we always want
4836 		 * to complain here.
4837 		 *
4838 		 * If we're not verifying destination reachability but the
4839 		 * destination has a route, we still want to fail on the
4840 		 * temporary address and broadcast address tests.
4841 		 */
4842 		if (verify_dst || (dst_ire != NULL)) {
4843 			if (ip_debug > 2) {
4844 				pr_addr_dbg("ip_bind_connected: bad connected "
4845 				    "dst %s\n", AF_INET, &dst_addr);
4846 			}
4847 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4848 				error = ENETUNREACH;
4849 			else
4850 				error = EHOSTUNREACH;
4851 			goto bad_addr;
4852 		}
4853 	}
4854 
4855 	/*
4856 	 * We now know that routing will allow us to reach the destination.
4857 	 * Check whether Trusted Solaris policy allows communication with this
4858 	 * host, and pretend that the destination is unreachable if not.
4859 	 *
4860 	 * This is never a problem for TCP, since that transport is known to
4861 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4862 	 * handling.  If the remote is unreachable, it will be detected at that
4863 	 * point, so there's no reason to check it here.
4864 	 *
4865 	 * Note that for sendto (and other datagram-oriented friends), this
4866 	 * check is done as part of the data path label computation instead.
4867 	 * The check here is just to make non-TCP connect() report the right
4868 	 * error.
4869 	 */
4870 	if (dst_ire != NULL && is_system_labeled() &&
4871 	    !IPCL_IS_TCP(connp) &&
4872 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4873 	    connp->conn_mac_exempt) != 0) {
4874 		error = EHOSTUNREACH;
4875 		if (ip_debug > 2) {
4876 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4877 			    AF_INET, &dst_addr);
4878 		}
4879 		goto bad_addr;
4880 	}
4881 
4882 	/*
4883 	 * If the app does a connect(), it means that it will most likely
4884 	 * send more than 1 packet to the destination.  It makes sense
4885 	 * to clear the temporary flag.
4886 	 */
4887 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4888 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4889 		irb_t *irb = dst_ire->ire_bucket;
4890 
4891 		rw_enter(&irb->irb_lock, RW_WRITER);
4892 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4893 		irb->irb_tmp_ire_cnt--;
4894 		rw_exit(&irb->irb_lock);
4895 	}
4896 
4897 	/*
4898 	 * See if we should notify ULP about MDT; we do this whether or not
4899 	 * ire_requested is TRUE, in order to handle active connects; MDT
4900 	 * eligibility tests for passive connects are handled separately
4901 	 * through tcp_adapt_ire().  We do this before the source address
4902 	 * selection, because dst_ire may change after a call to
4903 	 * ipif_select_source().  This is a best-effort check, as the
4904 	 * packet for this connection may not actually go through
4905 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4906 	 * calling ip_newroute().  This is why we further check on the
4907 	 * IRE during Multidata packet transmission in tcp_multisend().
4908 	 */
4909 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4910 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4911 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4912 	    ILL_MDT_CAPABLE(md_ill)) {
4913 		md_dst_ire = dst_ire;
4914 		IRE_REFHOLD(md_dst_ire);
4915 	}
4916 
4917 	if (dst_ire != NULL &&
4918 	    dst_ire->ire_type == IRE_LOCAL &&
4919 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4920 		/*
4921 		 * If the IRE belongs to a different zone, look for a matching
4922 		 * route in the forwarding table and use the source address from
4923 		 * that route.
4924 		 */
4925 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4926 		    zoneid, 0, NULL,
4927 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4928 		    MATCH_IRE_RJ_BHOLE);
4929 		if (src_ire == NULL) {
4930 			error = EHOSTUNREACH;
4931 			goto bad_addr;
4932 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4933 			if (!(src_ire->ire_type & IRE_HOST))
4934 				error = ENETUNREACH;
4935 			else
4936 				error = EHOSTUNREACH;
4937 			goto bad_addr;
4938 		}
4939 		if (src_addr == INADDR_ANY)
4940 			src_addr = src_ire->ire_src_addr;
4941 		ire_refrele(src_ire);
4942 		src_ire = NULL;
4943 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4944 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4945 			src_addr = sire->ire_src_addr;
4946 			ire_refrele(dst_ire);
4947 			dst_ire = sire;
4948 			sire = NULL;
4949 		} else {
4950 			/*
4951 			 * Pick a source address so that a proper inbound
4952 			 * load spreading would happen.
4953 			 */
4954 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4955 			ipif_t *src_ipif = NULL;
4956 			ire_t *ipif_ire;
4957 
4958 			/*
4959 			 * Supply a local source address such that inbound
4960 			 * load spreading happens.
4961 			 *
4962 			 * Determine the best source address on this ill for
4963 			 * the destination.
4964 			 *
4965 			 * 1) For broadcast, we should return a broadcast ire
4966 			 *    found above so that upper layers know that the
4967 			 *    destination address is a broadcast address.
4968 			 *
4969 			 * 2) If this is part of a group, select a better
4970 			 *    source address so that better inbound load
4971 			 *    balancing happens. Do the same if the ipif
4972 			 *    is DEPRECATED.
4973 			 *
4974 			 * 3) If the outgoing interface is part of a usesrc
4975 			 *    group, then try selecting a source address from
4976 			 *    the usesrc ILL.
4977 			 */
4978 			if ((dst_ire->ire_zoneid != zoneid &&
4979 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4980 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4981 			    ((dst_ill->ill_group != NULL) ||
4982 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4983 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4984 				/*
4985 				 * If the destination is reachable via a
4986 				 * given gateway, the selected source address
4987 				 * should be in the same subnet as the gateway.
4988 				 * Otherwise, the destination is not reachable.
4989 				 *
4990 				 * If there are no interfaces on the same subnet
4991 				 * as the destination, ipif_select_source gives
4992 				 * first non-deprecated interface which might be
4993 				 * on a different subnet than the gateway.
4994 				 * This is not desirable. Hence pass the dst_ire
4995 				 * source address to ipif_select_source.
4996 				 * It is sure that the destination is reachable
4997 				 * with the dst_ire source address subnet.
4998 				 * So passing dst_ire source address to
4999 				 * ipif_select_source will make sure that the
5000 				 * selected source will be on the same subnet
5001 				 * as dst_ire source address.
5002 				 */
5003 				ipaddr_t saddr =
5004 				    dst_ire->ire_ipif->ipif_src_addr;
5005 				src_ipif = ipif_select_source(dst_ill,
5006 				    saddr, zoneid);
5007 				if (src_ipif != NULL) {
5008 					if (IS_VNI(src_ipif->ipif_ill)) {
5009 						/*
5010 						 * For VNI there is no
5011 						 * interface route
5012 						 */
5013 						src_addr =
5014 						    src_ipif->ipif_src_addr;
5015 					} else {
5016 						ipif_ire =
5017 						    ipif_to_ire(src_ipif);
5018 						if (ipif_ire != NULL) {
5019 							IRE_REFRELE(dst_ire);
5020 							dst_ire = ipif_ire;
5021 						}
5022 						src_addr =
5023 						    dst_ire->ire_src_addr;
5024 					}
5025 					ipif_refrele(src_ipif);
5026 				} else {
5027 					src_addr = dst_ire->ire_src_addr;
5028 				}
5029 			} else {
5030 				src_addr = dst_ire->ire_src_addr;
5031 			}
5032 		}
5033 	}
5034 
5035 	/*
5036 	 * We do ire_route_lookup() here (and not
5037 	 * interface lookup as we assert that
5038 	 * src_addr should only come from an
5039 	 * UP interface for hard binding.
5040 	 */
5041 	ASSERT(src_ire == NULL);
5042 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5043 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
5044 	/* src_ire must be a local|loopback */
5045 	if (!IRE_IS_LOCAL(src_ire)) {
5046 		if (ip_debug > 2) {
5047 			pr_addr_dbg("ip_bind_connected: bad connected "
5048 			    "src %s\n", AF_INET, &src_addr);
5049 		}
5050 		error = EADDRNOTAVAIL;
5051 		goto bad_addr;
5052 	}
5053 
5054 	/*
5055 	 * If the source address is a loopback address, the
5056 	 * destination had best be local or multicast.
5057 	 * The transports that can't handle multicast will reject
5058 	 * those addresses.
5059 	 */
5060 	if (src_ire->ire_type == IRE_LOOPBACK &&
5061 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5062 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5063 		error = -1;
5064 		goto bad_addr;
5065 	}
5066 
5067 	/*
5068 	 * Allow setting new policies. For example, disconnects come
5069 	 * down as ipa_t bind. As we would have set conn_policy_cached
5070 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5071 	 * can change after the disconnect.
5072 	 */
5073 	connp->conn_policy_cached = B_FALSE;
5074 
5075 	/*
5076 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5077 	 * can handle their passed-in conn's.
5078 	 */
5079 
5080 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5081 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5082 	connp->conn_lport = lport;
5083 	connp->conn_fport = fport;
5084 	*src_addrp = src_addr;
5085 
5086 	ASSERT(!(ipsec_policy_set && ire_requested));
5087 	if (ire_requested) {
5088 		iulp_t *ulp_info = NULL;
5089 
5090 		/*
5091 		 * Note that sire will not be NULL if this is an off-link
5092 		 * connection and there is not cache for that dest yet.
5093 		 *
5094 		 * XXX Because of an existing bug, if there are multiple
5095 		 * default routes, the IRE returned now may not be the actual
5096 		 * default route used (default routes are chosen in a
5097 		 * round robin fashion).  So if the metrics for different
5098 		 * default routes are different, we may return the wrong
5099 		 * metrics.  This will not be a problem if the existing
5100 		 * bug is fixed.
5101 		 */
5102 		if (sire != NULL) {
5103 			ulp_info = &(sire->ire_uinfo);
5104 		}
5105 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5106 			error = -1;
5107 			goto bad_addr;
5108 		}
5109 	} else if (ipsec_policy_set) {
5110 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5111 			error = -1;
5112 			goto bad_addr;
5113 		}
5114 	}
5115 
5116 	/*
5117 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5118 	 * we'll cache that.  If we don't, we'll inherit global policy.
5119 	 *
5120 	 * We can't insert until the conn reflects the policy. Note that
5121 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5122 	 * connections where we don't have a policy. This is to prevent
5123 	 * global policy lookups in the inbound path.
5124 	 *
5125 	 * If we insert before we set conn_policy_cached,
5126 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5127 	 * because global policy cound be non-empty. We normally call
5128 	 * ipsec_check_policy() for conn_policy_cached connections only if
5129 	 * ipc_in_enforce_policy is set. But in this case,
5130 	 * conn_policy_cached can get set anytime since we made the
5131 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5132 	 * called, which will make the above assumption false.  Thus, we
5133 	 * need to insert after we set conn_policy_cached.
5134 	 */
5135 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5136 		goto bad_addr;
5137 
5138 	if (fanout_insert) {
5139 		/*
5140 		 * The addresses have been verified. Time to insert in
5141 		 * the correct fanout list.
5142 		 */
5143 		error = ipcl_conn_insert(connp, protocol, src_addr,
5144 		    dst_addr, connp->conn_ports);
5145 	}
5146 
5147 	if (error == 0) {
5148 		connp->conn_fully_bound = B_TRUE;
5149 		/*
5150 		 * Our initial checks for MDT have passed; the IRE is not
5151 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5152 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
5153 		 * ip_mdinfo_return(), which performs further checks
5154 		 * against them and upon success, returns the MDT info
5155 		 * mblk which we will attach to the bind acknowledgment.
5156 		 */
5157 		if (md_dst_ire != NULL) {
5158 			mblk_t *mdinfo_mp;
5159 
5160 			ASSERT(md_ill != NULL);
5161 			ASSERT(md_ill->ill_mdt_capab != NULL);
5162 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5163 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
5164 				linkb(mp, mdinfo_mp);
5165 		}
5166 	}
5167 bad_addr:
5168 	if (ipsec_policy_set) {
5169 		ASSERT(policy_mp == mp->b_cont);
5170 		ASSERT(policy_mp != NULL);
5171 		freeb(policy_mp);
5172 		/*
5173 		 * As of now assume that nothing else accompanies
5174 		 * IPSEC_POLICY_SET.
5175 		 */
5176 		mp->b_cont = NULL;
5177 	}
5178 	if (src_ire != NULL)
5179 		IRE_REFRELE(src_ire);
5180 	if (dst_ire != NULL)
5181 		IRE_REFRELE(dst_ire);
5182 	if (sire != NULL)
5183 		IRE_REFRELE(sire);
5184 	if (md_dst_ire != NULL)
5185 		IRE_REFRELE(md_dst_ire);
5186 	return (error);
5187 }
5188 
5189 /*
5190  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5191  * Prefers dst_ire over src_ire.
5192  */
5193 static boolean_t
5194 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5195 {
5196 	mblk_t	*mp1;
5197 	ire_t *ret_ire = NULL;
5198 
5199 	mp1 = mp->b_cont;
5200 	ASSERT(mp1 != NULL);
5201 
5202 	if (ire != NULL) {
5203 		/*
5204 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5205 		 * appended mblk. Its <upper protocol>'s
5206 		 * job to make sure there is room.
5207 		 */
5208 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5209 			return (0);
5210 
5211 		mp1->b_datap->db_type = IRE_DB_TYPE;
5212 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5213 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5214 		ret_ire = (ire_t *)mp1->b_rptr;
5215 		/*
5216 		 * Pass the latest setting of the ip_path_mtu_discovery and
5217 		 * copy the ulp info if any.
5218 		 */
5219 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5220 		    IPH_DF : 0;
5221 		if (ulp_info != NULL) {
5222 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5223 			    sizeof (iulp_t));
5224 		}
5225 		ret_ire->ire_mp = mp1;
5226 	} else {
5227 		/*
5228 		 * No IRE was found. Remove IRE mblk.
5229 		 */
5230 		mp->b_cont = mp1->b_cont;
5231 		freeb(mp1);
5232 	}
5233 
5234 	return (1);
5235 }
5236 
5237 /*
5238  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5239  * the final piece where we don't.  Return a pointer to the first mblk in the
5240  * result, and update the pointer to the next mblk to chew on.  If anything
5241  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5242  * NULL pointer.
5243  */
5244 mblk_t *
5245 ip_carve_mp(mblk_t **mpp, ssize_t len)
5246 {
5247 	mblk_t	*mp0;
5248 	mblk_t	*mp1;
5249 	mblk_t	*mp2;
5250 
5251 	if (!len || !mpp || !(mp0 = *mpp))
5252 		return (NULL);
5253 	/* If we aren't going to consume the first mblk, we need a dup. */
5254 	if (mp0->b_wptr - mp0->b_rptr > len) {
5255 		mp1 = dupb(mp0);
5256 		if (mp1) {
5257 			/* Partition the data between the two mblks. */
5258 			mp1->b_wptr = mp1->b_rptr + len;
5259 			mp0->b_rptr = mp1->b_wptr;
5260 			/*
5261 			 * after adjustments if mblk not consumed is now
5262 			 * unaligned, try to align it. If this fails free
5263 			 * all messages and let upper layer recover.
5264 			 */
5265 			if (!OK_32PTR(mp0->b_rptr)) {
5266 				if (!pullupmsg(mp0, -1)) {
5267 					freemsg(mp0);
5268 					freemsg(mp1);
5269 					*mpp = NULL;
5270 					return (NULL);
5271 				}
5272 			}
5273 		}
5274 		return (mp1);
5275 	}
5276 	/* Eat through as many mblks as we need to get len bytes. */
5277 	len -= mp0->b_wptr - mp0->b_rptr;
5278 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5279 		if (mp2->b_wptr - mp2->b_rptr > len) {
5280 			/*
5281 			 * We won't consume the entire last mblk.  Like
5282 			 * above, dup and partition it.
5283 			 */
5284 			mp1->b_cont = dupb(mp2);
5285 			mp1 = mp1->b_cont;
5286 			if (!mp1) {
5287 				/*
5288 				 * Trouble.  Rather than go to a lot of
5289 				 * trouble to clean up, we free the messages.
5290 				 * This won't be any worse than losing it on
5291 				 * the wire.
5292 				 */
5293 				freemsg(mp0);
5294 				freemsg(mp2);
5295 				*mpp = NULL;
5296 				return (NULL);
5297 			}
5298 			mp1->b_wptr = mp1->b_rptr + len;
5299 			mp2->b_rptr = mp1->b_wptr;
5300 			/*
5301 			 * after adjustments if mblk not consumed is now
5302 			 * unaligned, try to align it. If this fails free
5303 			 * all messages and let upper layer recover.
5304 			 */
5305 			if (!OK_32PTR(mp2->b_rptr)) {
5306 				if (!pullupmsg(mp2, -1)) {
5307 					freemsg(mp0);
5308 					freemsg(mp2);
5309 					*mpp = NULL;
5310 					return (NULL);
5311 				}
5312 			}
5313 			*mpp = mp2;
5314 			return (mp0);
5315 		}
5316 		/* Decrement len by the amount we just got. */
5317 		len -= mp2->b_wptr - mp2->b_rptr;
5318 	}
5319 	/*
5320 	 * len should be reduced to zero now.  If not our caller has
5321 	 * screwed up.
5322 	 */
5323 	if (len) {
5324 		/* Shouldn't happen! */
5325 		freemsg(mp0);
5326 		*mpp = NULL;
5327 		return (NULL);
5328 	}
5329 	/*
5330 	 * We consumed up to exactly the end of an mblk.  Detach the part
5331 	 * we are returning from the rest of the chain.
5332 	 */
5333 	mp1->b_cont = NULL;
5334 	*mpp = mp2;
5335 	return (mp0);
5336 }
5337 
5338 /* The ill stream is being unplumbed. Called from ip_close */
5339 int
5340 ip_modclose(ill_t *ill)
5341 {
5342 
5343 	boolean_t success;
5344 	ipsq_t	*ipsq;
5345 	ipif_t	*ipif;
5346 	queue_t	*q = ill->ill_rq;
5347 	hook_nic_event_t *info;
5348 
5349 	/*
5350 	 * Forcibly enter the ipsq after some delay. This is to take
5351 	 * care of the case when some ioctl does not complete because
5352 	 * we sent a control message to the driver and it did not
5353 	 * send us a reply. We want to be able to at least unplumb
5354 	 * and replumb rather than force the user to reboot the system.
5355 	 */
5356 	success = ipsq_enter(ill, B_FALSE);
5357 
5358 	/*
5359 	 * Open/close/push/pop is guaranteed to be single threaded
5360 	 * per stream by STREAMS. FS guarantees that all references
5361 	 * from top are gone before close is called. So there can't
5362 	 * be another close thread that has set CONDEMNED on this ill.
5363 	 * and cause ipsq_enter to return failure.
5364 	 */
5365 	ASSERT(success);
5366 	ipsq = ill->ill_phyint->phyint_ipsq;
5367 
5368 	/*
5369 	 * Mark it condemned. No new reference will be made to this ill.
5370 	 * Lookup functions will return an error. Threads that try to
5371 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5372 	 * that the refcnt will drop down to zero.
5373 	 */
5374 	mutex_enter(&ill->ill_lock);
5375 	ill->ill_state_flags |= ILL_CONDEMNED;
5376 	for (ipif = ill->ill_ipif; ipif != NULL;
5377 	    ipif = ipif->ipif_next) {
5378 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5379 	}
5380 	/*
5381 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5382 	 * returns  error if ILL_CONDEMNED is set
5383 	 */
5384 	cv_broadcast(&ill->ill_cv);
5385 	mutex_exit(&ill->ill_lock);
5386 
5387 	/*
5388 	 * Shut down fragmentation reassembly.
5389 	 * ill_frag_timer won't start a timer again.
5390 	 * Now cancel any existing timer
5391 	 */
5392 	(void) untimeout(ill->ill_frag_timer_id);
5393 	(void) ill_frag_timeout(ill, 0);
5394 
5395 	/*
5396 	 * If MOVE was in progress, clear the
5397 	 * move_in_progress fields also.
5398 	 */
5399 	if (ill->ill_move_in_progress) {
5400 		ILL_CLEAR_MOVE(ill);
5401 	}
5402 
5403 	/*
5404 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5405 	 * this ill. Then wait for the refcnts to drop to zero.
5406 	 * ill_is_quiescent checks whether the ill is really quiescent.
5407 	 * Then make sure that threads that are waiting to enter the
5408 	 * ipsq have seen the error returned by ipsq_enter and have
5409 	 * gone away. Then we call ill_delete_tail which does the
5410 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5411 	 */
5412 	ill_delete(ill);
5413 	mutex_enter(&ill->ill_lock);
5414 	while (!ill_is_quiescent(ill))
5415 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5416 	while (ill->ill_waiters)
5417 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5418 
5419 	mutex_exit(&ill->ill_lock);
5420 
5421 	/* qprocsoff is called in ill_delete_tail */
5422 	ill_delete_tail(ill);
5423 
5424 	/*
5425 	 * Walk through all upper (conn) streams and qenable
5426 	 * those that have queued data.
5427 	 * close synchronization needs this to
5428 	 * be done to ensure that all upper layers blocked
5429 	 * due to flow control to the closing device
5430 	 * get unblocked.
5431 	 */
5432 	ip1dbg(("ip_wsrv: walking\n"));
5433 	conn_walk_drain();
5434 
5435 	mutex_enter(&ip_mi_lock);
5436 	mi_close_unlink(&ip_g_head, (IDP)ill);
5437 	mutex_exit(&ip_mi_lock);
5438 
5439 	/*
5440 	 * credp could be null if the open didn't succeed and ip_modopen
5441 	 * itself calls ip_close.
5442 	 */
5443 	if (ill->ill_credp != NULL)
5444 		crfree(ill->ill_credp);
5445 
5446 	/*
5447 	 * Unhook the nic event message from the ill and enqueue it into the nic
5448 	 * event taskq.
5449 	 */
5450 	if ((info = ill->ill_nic_event_info) != NULL) {
5451 		if (ddi_taskq_dispatch(eventq_queue_nic, ip_ne_queue_func,
5452 		    (void *)info, DDI_SLEEP) == DDI_FAILURE) {
5453 			ip2dbg(("ip_ioctl_finish:ddi_taskq_dispatch failed\n"));
5454 			if (info->hne_data != NULL)
5455 				kmem_free(info->hne_data, info->hne_datalen);
5456 			kmem_free(info, sizeof (hook_nic_event_t));
5457 		}
5458 		ill->ill_nic_event_info = NULL;
5459 	}
5460 
5461 	mi_close_free((IDP)ill);
5462 	q->q_ptr = WR(q)->q_ptr = NULL;
5463 
5464 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5465 
5466 	return (0);
5467 }
5468 
5469 /*
5470  * This is called as part of close() for both IP and UDP
5471  * in order to quiesce the conn.
5472  */
5473 void
5474 ip_quiesce_conn(conn_t *connp)
5475 {
5476 	boolean_t	drain_cleanup_reqd = B_FALSE;
5477 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5478 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5479 
5480 	ASSERT(!IPCL_IS_TCP(connp));
5481 
5482 	/*
5483 	 * Mark the conn as closing, and this conn must not be
5484 	 * inserted in future into any list. Eg. conn_drain_insert(),
5485 	 * won't insert this conn into the conn_drain_list.
5486 	 * Similarly ill_pending_mp_add() will not add any mp to
5487 	 * the pending mp list, after this conn has started closing.
5488 	 *
5489 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5490 	 * cannot get set henceforth.
5491 	 */
5492 	mutex_enter(&connp->conn_lock);
5493 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5494 	connp->conn_state_flags |= CONN_CLOSING;
5495 	if (connp->conn_idl != NULL)
5496 		drain_cleanup_reqd = B_TRUE;
5497 	if (connp->conn_oper_pending_ill != NULL)
5498 		conn_ioctl_cleanup_reqd = B_TRUE;
5499 	if (connp->conn_ilg_inuse != 0)
5500 		ilg_cleanup_reqd = B_TRUE;
5501 	mutex_exit(&connp->conn_lock);
5502 
5503 	if (IPCL_IS_UDP(connp))
5504 		udp_quiesce_conn(connp);
5505 
5506 	if (conn_ioctl_cleanup_reqd)
5507 		conn_ioctl_cleanup(connp);
5508 
5509 	if (is_system_labeled() && connp->conn_anon_port) {
5510 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5511 		    connp->conn_mlp_type, connp->conn_ulp,
5512 		    ntohs(connp->conn_lport), B_FALSE);
5513 		connp->conn_anon_port = 0;
5514 	}
5515 	connp->conn_mlp_type = mlptSingle;
5516 
5517 	/*
5518 	 * Remove this conn from any fanout list it is on.
5519 	 * and then wait for any threads currently operating
5520 	 * on this endpoint to finish
5521 	 */
5522 	ipcl_hash_remove(connp);
5523 
5524 	/*
5525 	 * Remove this conn from the drain list, and do
5526 	 * any other cleanup that may be required.
5527 	 * (Only non-tcp streams may have a non-null conn_idl.
5528 	 * TCP streams are never flow controlled, and
5529 	 * conn_idl will be null)
5530 	 */
5531 	if (drain_cleanup_reqd)
5532 		conn_drain_tail(connp, B_TRUE);
5533 
5534 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5535 		(void) ip_mrouter_done(NULL);
5536 
5537 	if (ilg_cleanup_reqd)
5538 		ilg_delete_all(connp);
5539 
5540 	conn_delete_ire(connp, NULL);
5541 
5542 	/*
5543 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5544 	 * callers from write side can't be there now because close
5545 	 * is in progress. The only other caller is ipcl_walk
5546 	 * which checks for the condemned flag.
5547 	 */
5548 	mutex_enter(&connp->conn_lock);
5549 	connp->conn_state_flags |= CONN_CONDEMNED;
5550 	while (connp->conn_ref != 1)
5551 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5552 	connp->conn_state_flags |= CONN_QUIESCED;
5553 	mutex_exit(&connp->conn_lock);
5554 }
5555 
5556 /* ARGSUSED */
5557 int
5558 ip_close(queue_t *q, int flags)
5559 {
5560 	conn_t		*connp;
5561 
5562 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5563 
5564 	/*
5565 	 * Call the appropriate delete routine depending on whether this is
5566 	 * a module or device.
5567 	 */
5568 	if (WR(q)->q_next != NULL) {
5569 		/* This is a module close */
5570 		return (ip_modclose((ill_t *)q->q_ptr));
5571 	}
5572 
5573 	connp = q->q_ptr;
5574 	ip_quiesce_conn(connp);
5575 
5576 	qprocsoff(q);
5577 
5578 	/*
5579 	 * Now we are truly single threaded on this stream, and can
5580 	 * delete the things hanging off the connp, and finally the connp.
5581 	 * We removed this connp from the fanout list, it cannot be
5582 	 * accessed thru the fanouts, and we already waited for the
5583 	 * conn_ref to drop to 0. We are already in close, so
5584 	 * there cannot be any other thread from the top. qprocsoff
5585 	 * has completed, and service has completed or won't run in
5586 	 * future.
5587 	 */
5588 	ASSERT(connp->conn_ref == 1);
5589 
5590 	/*
5591 	 * A conn which was previously marked as IPCL_UDP cannot
5592 	 * retain the flag because it would have been cleared by
5593 	 * udp_close().
5594 	 */
5595 	ASSERT(!IPCL_IS_UDP(connp));
5596 
5597 	if (connp->conn_latch != NULL) {
5598 		IPLATCH_REFRELE(connp->conn_latch);
5599 		connp->conn_latch = NULL;
5600 	}
5601 	if (connp->conn_policy != NULL) {
5602 		IPPH_REFRELE(connp->conn_policy);
5603 		connp->conn_policy = NULL;
5604 	}
5605 	if (connp->conn_ipsec_opt_mp != NULL) {
5606 		freemsg(connp->conn_ipsec_opt_mp);
5607 		connp->conn_ipsec_opt_mp = NULL;
5608 	}
5609 
5610 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5611 
5612 	connp->conn_ref--;
5613 	ipcl_conn_destroy(connp);
5614 
5615 	q->q_ptr = WR(q)->q_ptr = NULL;
5616 	return (0);
5617 }
5618 
5619 int
5620 ip_snmpmod_close(queue_t *q)
5621 {
5622 	conn_t *connp = Q_TO_CONN(q);
5623 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5624 
5625 	qprocsoff(q);
5626 
5627 	if (connp->conn_flags & IPCL_UDPMOD)
5628 		udp_close_free(connp);
5629 
5630 	if (connp->conn_cred != NULL) {
5631 		crfree(connp->conn_cred);
5632 		connp->conn_cred = NULL;
5633 	}
5634 	CONN_DEC_REF(connp);
5635 	q->q_ptr = WR(q)->q_ptr = NULL;
5636 	return (0);
5637 }
5638 
5639 /*
5640  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5641  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5642  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5643  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5644  * queues as we never enqueue messages there and we don't handle any ioctls.
5645  * Everything else is freed.
5646  */
5647 void
5648 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5649 {
5650 	conn_t	*connp = q->q_ptr;
5651 	pfi_t	setfn;
5652 	pfi_t	getfn;
5653 
5654 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5655 
5656 	switch (DB_TYPE(mp)) {
5657 	case M_PROTO:
5658 	case M_PCPROTO:
5659 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5660 		    ((((union T_primitives *)mp->b_rptr)->type ==
5661 			T_SVR4_OPTMGMT_REQ) ||
5662 		    (((union T_primitives *)mp->b_rptr)->type ==
5663 			T_OPTMGMT_REQ))) {
5664 			/*
5665 			 * This is the only TPI primitive supported. Its
5666 			 * handling does not require tcp_t, but it does require
5667 			 * conn_t to check permissions.
5668 			 */
5669 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5670 
5671 			if (connp->conn_flags & IPCL_TCPMOD) {
5672 				setfn = tcp_snmp_set;
5673 				getfn = tcp_snmp_get;
5674 			} else {
5675 				setfn = udp_snmp_set;
5676 				getfn = udp_snmp_get;
5677 			}
5678 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5679 				freemsg(mp);
5680 				return;
5681 			}
5682 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5683 		    != NULL)
5684 			qreply(q, mp);
5685 		break;
5686 	case M_FLUSH:
5687 	case M_IOCTL:
5688 		putnext(q, mp);
5689 		break;
5690 	default:
5691 		freemsg(mp);
5692 		break;
5693 	}
5694 }
5695 
5696 /* Return the IP checksum for the IP header at "iph". */
5697 uint16_t
5698 ip_csum_hdr(ipha_t *ipha)
5699 {
5700 	uint16_t	*uph;
5701 	uint32_t	sum;
5702 	int		opt_len;
5703 
5704 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5705 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5706 	uph = (uint16_t *)ipha;
5707 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5708 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5709 	if (opt_len > 0) {
5710 		do {
5711 			sum += uph[10];
5712 			sum += uph[11];
5713 			uph += 2;
5714 		} while (--opt_len);
5715 	}
5716 	sum = (sum & 0xFFFF) + (sum >> 16);
5717 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5718 	if (sum == 0xffff)
5719 		sum = 0;
5720 	return ((uint16_t)sum);
5721 }
5722 
5723 void
5724 ip_ddi_destroy(void)
5725 {
5726 	ipv4_hook_destroy();
5727 	ipv6_hook_destroy();
5728 	ip_net_destroy();
5729 
5730 	tnet_fini();
5731 	tcp_ddi_destroy();
5732 	sctp_ddi_destroy();
5733 	ipsec_loader_destroy();
5734 	ipsec_policy_destroy();
5735 	ipsec_kstat_destroy();
5736 	nd_free(&ip_g_nd);
5737 	mutex_destroy(&igmp_timer_lock);
5738 	mutex_destroy(&mld_timer_lock);
5739 	mutex_destroy(&igmp_slowtimeout_lock);
5740 	mutex_destroy(&mld_slowtimeout_lock);
5741 	mutex_destroy(&ip_mi_lock);
5742 	mutex_destroy(&rts_clients.connf_lock);
5743 	ip_ire_fini();
5744 	ip6_asp_free();
5745 	conn_drain_fini();
5746 	ipcl_destroy();
5747 	inet_minor_destroy(ip_minor_arena);
5748 	icmp_kstat_fini();
5749 	ip_kstat_fini();
5750 	rw_destroy(&ipsec_capab_ills_lock);
5751 	rw_destroy(&ill_g_usesrc_lock);
5752 	ip_drop_unregister(&ip_dropper);
5753 }
5754 
5755 
5756 void
5757 ip_ddi_init(void)
5758 {
5759 	TCP6_MAJ = ddi_name_to_major(TCP6);
5760 	TCP_MAJ	= ddi_name_to_major(TCP);
5761 	SCTP_MAJ = ddi_name_to_major(SCTP);
5762 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5763 
5764 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5765 
5766 	/* IP's IPsec code calls the packet dropper */
5767 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5768 
5769 	if (!ip_g_nd) {
5770 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5771 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5772 			nd_free(&ip_g_nd);
5773 		}
5774 	}
5775 
5776 	ipsec_loader_init();
5777 	ipsec_policy_init();
5778 	ipsec_kstat_init();
5779 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5780 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5781 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5782 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5783 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5784 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5785 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5786 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5787 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5788 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5789 
5790 	/*
5791 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5792 	 * initial devices: ip, ip6, tcp, tcp6.
5793 	 */
5794 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5795 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5796 		cmn_err(CE_PANIC,
5797 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5798 	}
5799 
5800 	ipcl_init();
5801 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5802 	ip_ire_init();
5803 	ip6_asp_init();
5804 	ipif_init();
5805 	conn_drain_init();
5806 	tcp_ddi_init();
5807 	sctp_ddi_init();
5808 
5809 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5810 
5811 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5812 		"net", KSTAT_TYPE_NAMED,
5813 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5814 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5815 		ip_kstat->ks_data = &ip_statistics;
5816 		kstat_install(ip_kstat);
5817 	}
5818 	ip_kstat_init();
5819 	ip6_kstat_init();
5820 	icmp_kstat_init();
5821 	ipsec_loader_start();
5822 	tnet_init();
5823 
5824 	ip_net_init();
5825 	ipv4_hook_init();
5826 	ipv6_hook_init();
5827 }
5828 
5829 /*
5830  * Allocate and initialize a DLPI template of the specified length.  (May be
5831  * called as writer.)
5832  */
5833 mblk_t *
5834 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5835 {
5836 	mblk_t	*mp;
5837 
5838 	mp = allocb(len, BPRI_MED);
5839 	if (!mp)
5840 		return (NULL);
5841 
5842 	/*
5843 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5844 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5845 	 * that other DLPI are M_PROTO.
5846 	 */
5847 	if (prim == DL_INFO_REQ) {
5848 		mp->b_datap->db_type = M_PCPROTO;
5849 	} else {
5850 		mp->b_datap->db_type = M_PROTO;
5851 	}
5852 
5853 	mp->b_wptr = mp->b_rptr + len;
5854 	bzero(mp->b_rptr, len);
5855 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5856 	return (mp);
5857 }
5858 
5859 const char *
5860 dlpi_prim_str(int prim)
5861 {
5862 	switch (prim) {
5863 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5864 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5865 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5866 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5867 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5868 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5869 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5870 	case DL_OK_ACK:		return ("DL_OK_ACK");
5871 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5872 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5873 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5874 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5875 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5876 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5877 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5878 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5879 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5880 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5881 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5882 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5883 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5884 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5885 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5886 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5887 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5888 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5889 	default:		return ("<unknown primitive>");
5890 	}
5891 }
5892 
5893 const char *
5894 dlpi_err_str(int err)
5895 {
5896 	switch (err) {
5897 	case DL_ACCESS:		return ("DL_ACCESS");
5898 	case DL_BADADDR:	return ("DL_BADADDR");
5899 	case DL_BADCORR:	return ("DL_BADCORR");
5900 	case DL_BADDATA:	return ("DL_BADDATA");
5901 	case DL_BADPPA:		return ("DL_BADPPA");
5902 	case DL_BADPRIM:	return ("DL_BADPRIM");
5903 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5904 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5905 	case DL_BADSAP:		return ("DL_BADSAP");
5906 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5907 	case DL_BOUND:		return ("DL_BOUND");
5908 	case DL_INITFAILED:	return ("DL_INITFAILED");
5909 	case DL_NOADDR:		return ("DL_NOADDR");
5910 	case DL_NOTINIT:	return ("DL_NOTINIT");
5911 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5912 	case DL_SYSERR:		return ("DL_SYSERR");
5913 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5914 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5915 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5916 	case DL_TOOMANY:	return ("DL_TOOMANY");
5917 	case DL_NOTENAB:	return ("DL_NOTENAB");
5918 	case DL_BUSY:		return ("DL_BUSY");
5919 	case DL_NOAUTO:		return ("DL_NOAUTO");
5920 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5921 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5922 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5923 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5924 	case DL_PENDING:	return ("DL_PENDING");
5925 	default:		return ("<unknown error>");
5926 	}
5927 }
5928 
5929 /*
5930  * Debug formatting routine.  Returns a character string representation of the
5931  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5932  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5933  *
5934  * Once the ndd table-printing interfaces are removed, this can be changed to
5935  * standard dotted-decimal form.
5936  */
5937 char *
5938 ip_dot_addr(ipaddr_t addr, char *buf)
5939 {
5940 	uint8_t *ap = (uint8_t *)&addr;
5941 
5942 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5943 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
5944 	return (buf);
5945 }
5946 
5947 /*
5948  * Write the given MAC address as a printable string in the usual colon-
5949  * separated format.
5950  */
5951 const char *
5952 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
5953 {
5954 	char *bp;
5955 
5956 	if (alen == 0 || buflen < 4)
5957 		return ("?");
5958 	bp = buf;
5959 	for (;;) {
5960 		/*
5961 		 * If there are more MAC address bytes available, but we won't
5962 		 * have any room to print them, then add "..." to the string
5963 		 * instead.  See below for the 'magic number' explanation.
5964 		 */
5965 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
5966 			(void) strcpy(bp, "...");
5967 			break;
5968 		}
5969 		(void) sprintf(bp, "%02x", *addr++);
5970 		bp += 2;
5971 		if (--alen == 0)
5972 			break;
5973 		*bp++ = ':';
5974 		buflen -= 3;
5975 		/*
5976 		 * At this point, based on the first 'if' statement above,
5977 		 * either alen == 1 and buflen >= 3, or alen > 1 and
5978 		 * buflen >= 4.  The first case leaves room for the final "xx"
5979 		 * number and trailing NUL byte.  The second leaves room for at
5980 		 * least "...".  Thus the apparently 'magic' numbers chosen for
5981 		 * that statement.
5982 		 */
5983 	}
5984 	return (buf);
5985 }
5986 
5987 /*
5988  * Send an ICMP error after patching up the packet appropriately.  Returns
5989  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5990  */
5991 static boolean_t
5992 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5993     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5994 {
5995 	ipha_t *ipha;
5996 	mblk_t *first_mp;
5997 	boolean_t secure;
5998 	unsigned char db_type;
5999 
6000 	first_mp = mp;
6001 	if (mctl_present) {
6002 		mp = mp->b_cont;
6003 		secure = ipsec_in_is_secure(first_mp);
6004 		ASSERT(mp != NULL);
6005 	} else {
6006 		/*
6007 		 * If this is an ICMP error being reported - which goes
6008 		 * up as M_CTLs, we need to convert them to M_DATA till
6009 		 * we finish checking with global policy because
6010 		 * ipsec_check_global_policy() assumes M_DATA as clear
6011 		 * and M_CTL as secure.
6012 		 */
6013 		db_type = DB_TYPE(mp);
6014 		DB_TYPE(mp) = M_DATA;
6015 		secure = B_FALSE;
6016 	}
6017 	/*
6018 	 * We are generating an icmp error for some inbound packet.
6019 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6020 	 * Before we generate an error, check with global policy
6021 	 * to see whether this is allowed to enter the system. As
6022 	 * there is no "conn", we are checking with global policy.
6023 	 */
6024 	ipha = (ipha_t *)mp->b_rptr;
6025 	if (secure || ipsec_inbound_v4_policy_present) {
6026 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6027 		    ipha, NULL, mctl_present);
6028 		if (first_mp == NULL)
6029 			return (B_FALSE);
6030 	}
6031 
6032 	if (!mctl_present)
6033 		DB_TYPE(mp) = db_type;
6034 
6035 	if (flags & IP_FF_SEND_ICMP) {
6036 		if (flags & IP_FF_HDR_COMPLETE) {
6037 			if (ip_hdr_complete(ipha, zoneid)) {
6038 				freemsg(first_mp);
6039 				return (B_TRUE);
6040 			}
6041 		}
6042 		if (flags & IP_FF_CKSUM) {
6043 			/*
6044 			 * Have to correct checksum since
6045 			 * the packet might have been
6046 			 * fragmented and the reassembly code in ip_rput
6047 			 * does not restore the IP checksum.
6048 			 */
6049 			ipha->ipha_hdr_checksum = 0;
6050 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6051 		}
6052 		switch (icmp_type) {
6053 		case ICMP_DEST_UNREACHABLE:
6054 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid);
6055 			break;
6056 		default:
6057 			freemsg(first_mp);
6058 			break;
6059 		}
6060 	} else {
6061 		freemsg(first_mp);
6062 		return (B_FALSE);
6063 	}
6064 
6065 	return (B_TRUE);
6066 }
6067 
6068 /*
6069  * Used to send an ICMP error message when a packet is received for
6070  * a protocol that is not supported. The mblk passed as argument
6071  * is consumed by this function.
6072  */
6073 void
6074 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
6075 {
6076 	mblk_t *mp;
6077 	ipha_t *ipha;
6078 	ill_t *ill;
6079 	ipsec_in_t *ii;
6080 
6081 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6082 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6083 
6084 	mp = ipsec_mp->b_cont;
6085 	ipsec_mp->b_cont = NULL;
6086 	ipha = (ipha_t *)mp->b_rptr;
6087 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6088 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
6089 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6090 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
6091 		}
6092 	} else {
6093 		/* Get ill from index in ipsec_in_t. */
6094 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6095 		    B_TRUE, NULL, NULL, NULL, NULL);
6096 		if (ill != NULL) {
6097 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6098 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6099 			    0, B_FALSE, zoneid)) {
6100 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
6101 			}
6102 
6103 			ill_refrele(ill);
6104 		} else { /* re-link for the freemsg() below. */
6105 			ipsec_mp->b_cont = mp;
6106 		}
6107 	}
6108 
6109 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6110 	freemsg(ipsec_mp);
6111 }
6112 
6113 /*
6114  * See if the inbound datagram has had IPsec processing applied to it.
6115  */
6116 boolean_t
6117 ipsec_in_is_secure(mblk_t *ipsec_mp)
6118 {
6119 	ipsec_in_t *ii;
6120 
6121 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6122 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6123 
6124 	if (ii->ipsec_in_loopback) {
6125 		return (ii->ipsec_in_secure);
6126 	} else {
6127 		return (ii->ipsec_in_ah_sa != NULL ||
6128 		    ii->ipsec_in_esp_sa != NULL ||
6129 		    ii->ipsec_in_decaps);
6130 	}
6131 }
6132 
6133 /*
6134  * Handle protocols with which IP is less intimate.  There
6135  * can be more than one stream bound to a particular
6136  * protocol.  When this is the case, normally each one gets a copy
6137  * of any incoming packets.
6138  *
6139  * IPSEC NOTE :
6140  *
6141  * Don't allow a secure packet going up a non-secure connection.
6142  * We don't allow this because
6143  *
6144  * 1) Reply might go out in clear which will be dropped at
6145  *    the sending side.
6146  * 2) If the reply goes out in clear it will give the
6147  *    adversary enough information for getting the key in
6148  *    most of the cases.
6149  *
6150  * Moreover getting a secure packet when we expect clear
6151  * implies that SA's were added without checking for
6152  * policy on both ends. This should not happen once ISAKMP
6153  * is used to negotiate SAs as SAs will be added only after
6154  * verifying the policy.
6155  *
6156  * NOTE : If the packet was tunneled and not multicast we only send
6157  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6158  * back to delivering packets to AF_INET6 raw sockets.
6159  *
6160  * IPQoS Notes:
6161  * Once we have determined the client, invoke IPPF processing.
6162  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6163  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6164  * ip_policy will be false.
6165  *
6166  * Zones notes:
6167  * Currently only applications in the global zone can create raw sockets for
6168  * protocols other than ICMP. So unlike the broadcast / multicast case of
6169  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6170  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6171  */
6172 static void
6173 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6174     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6175     zoneid_t zoneid)
6176 {
6177 	queue_t	*rq;
6178 	mblk_t	*mp1, *first_mp1;
6179 	uint_t	protocol = ipha->ipha_protocol;
6180 	ipaddr_t dst;
6181 	boolean_t one_only;
6182 	mblk_t *first_mp = mp;
6183 	boolean_t secure;
6184 	uint32_t ill_index;
6185 	conn_t	*connp, *first_connp, *next_connp;
6186 	connf_t	*connfp;
6187 	boolean_t shared_addr;
6188 
6189 	if (mctl_present) {
6190 		mp = first_mp->b_cont;
6191 		secure = ipsec_in_is_secure(first_mp);
6192 		ASSERT(mp != NULL);
6193 	} else {
6194 		secure = B_FALSE;
6195 	}
6196 	dst = ipha->ipha_dst;
6197 	/*
6198 	 * If the packet was tunneled and not multicast we only send to it
6199 	 * the first match.
6200 	 */
6201 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6202 	    !CLASSD(dst));
6203 
6204 	shared_addr = (zoneid == ALL_ZONES);
6205 	if (shared_addr) {
6206 		/*
6207 		 * We don't allow multilevel ports for raw IP, so no need to
6208 		 * check for that here.
6209 		 */
6210 		zoneid = tsol_packet_to_zoneid(mp);
6211 	}
6212 
6213 	connfp = &ipcl_proto_fanout[protocol];
6214 	mutex_enter(&connfp->connf_lock);
6215 	connp = connfp->connf_head;
6216 	for (connp = connfp->connf_head; connp != NULL;
6217 		connp = connp->conn_next) {
6218 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6219 		    zoneid) &&
6220 		    (!is_system_labeled() ||
6221 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6222 		    connp)))
6223 			break;
6224 	}
6225 
6226 	if (connp == NULL || connp->conn_upq == NULL) {
6227 		/*
6228 		 * No one bound to these addresses.  Is
6229 		 * there a client that wants all
6230 		 * unclaimed datagrams?
6231 		 */
6232 		mutex_exit(&connfp->connf_lock);
6233 		/*
6234 		 * Check for IPPROTO_ENCAP...
6235 		 */
6236 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6237 			/*
6238 			 * If an IPsec mblk is here on a multicast
6239 			 * tunnel (using ip_mroute stuff), check policy here,
6240 			 * THEN ship off to ip_mroute_decap().
6241 			 *
6242 			 * BTW,  If I match a configured IP-in-IP
6243 			 * tunnel, this path will not be reached, and
6244 			 * ip_mroute_decap will never be called.
6245 			 */
6246 			first_mp = ipsec_check_global_policy(first_mp, connp,
6247 			    ipha, NULL, mctl_present);
6248 			if (first_mp != NULL) {
6249 				if (mctl_present)
6250 					freeb(first_mp);
6251 				ip_mroute_decap(q, mp);
6252 			} /* Else we already freed everything! */
6253 		} else {
6254 			/*
6255 			 * Otherwise send an ICMP protocol unreachable.
6256 			 */
6257 			if (ip_fanout_send_icmp(q, first_mp, flags,
6258 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6259 			    mctl_present, zoneid)) {
6260 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
6261 			}
6262 		}
6263 		return;
6264 	}
6265 	CONN_INC_REF(connp);
6266 	first_connp = connp;
6267 
6268 	/*
6269 	 * Only send message to one tunnel driver by immediately
6270 	 * terminating the loop.
6271 	 */
6272 	connp = one_only ? NULL : connp->conn_next;
6273 
6274 	for (;;) {
6275 		while (connp != NULL) {
6276 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6277 			    flags, zoneid) &&
6278 			    (!is_system_labeled() ||
6279 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6280 			    shared_addr, connp)))
6281 				break;
6282 			connp = connp->conn_next;
6283 		}
6284 
6285 		/*
6286 		 * Copy the packet.
6287 		 */
6288 		if (connp == NULL || connp->conn_upq == NULL ||
6289 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6290 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6291 			/*
6292 			 * No more interested clients or memory
6293 			 * allocation failed
6294 			 */
6295 			connp = first_connp;
6296 			break;
6297 		}
6298 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6299 		CONN_INC_REF(connp);
6300 		mutex_exit(&connfp->connf_lock);
6301 		rq = connp->conn_rq;
6302 		if (!canputnext(rq)) {
6303 			if (flags & IP_FF_RAWIP) {
6304 				BUMP_MIB(&ip_mib, rawipInOverflows);
6305 			} else {
6306 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6307 			}
6308 
6309 			freemsg(first_mp1);
6310 		} else {
6311 			/*
6312 			 * Don't enforce here if we're an actual tunnel -
6313 			 * let "tun" do it instead.
6314 			 */
6315 			if (!IPCL_IS_IPTUN(connp) &&
6316 			    (CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6317 				first_mp1 = ipsec_check_inbound_policy
6318 				    (first_mp1, connp, ipha, NULL,
6319 				    mctl_present);
6320 			}
6321 			if (first_mp1 != NULL) {
6322 				/*
6323 				 * ip_fanout_proto also gets called from
6324 				 * icmp_inbound_error_fanout, in which case
6325 				 * the msg type is M_CTL.  Don't add info
6326 				 * in this case for the time being. In future
6327 				 * when there is a need for knowing the
6328 				 * inbound iface index for ICMP error msgs,
6329 				 * then this can be changed.
6330 				 */
6331 				if ((connp->conn_recvif != 0) &&
6332 				    (mp->b_datap->db_type != M_CTL)) {
6333 					/*
6334 					 * the actual data will be
6335 					 * contained in b_cont upon
6336 					 * successful return of the
6337 					 * following call else
6338 					 * original mblk is returned
6339 					 */
6340 					ASSERT(recv_ill != NULL);
6341 					mp1 = ip_add_info(mp1, recv_ill,
6342 						IPF_RECVIF);
6343 				}
6344 				BUMP_MIB(&ip_mib, ipInDelivers);
6345 				if (mctl_present)
6346 					freeb(first_mp1);
6347 				putnext(rq, mp1);
6348 			}
6349 		}
6350 		mutex_enter(&connfp->connf_lock);
6351 		/* Follow the next pointer before releasing the conn. */
6352 		next_connp = connp->conn_next;
6353 		CONN_DEC_REF(connp);
6354 		connp = next_connp;
6355 	}
6356 
6357 	/* Last one.  Send it upstream. */
6358 	mutex_exit(&connfp->connf_lock);
6359 
6360 	/*
6361 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6362 	 * will be set to false.
6363 	 */
6364 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6365 		ill_index = ill->ill_phyint->phyint_ifindex;
6366 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6367 		if (mp == NULL) {
6368 			CONN_DEC_REF(connp);
6369 			if (mctl_present) {
6370 				freeb(first_mp);
6371 			}
6372 			return;
6373 		}
6374 	}
6375 
6376 	rq = connp->conn_rq;
6377 	if (!canputnext(rq)) {
6378 		if (flags & IP_FF_RAWIP) {
6379 			BUMP_MIB(&ip_mib, rawipInOverflows);
6380 		} else {
6381 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6382 		}
6383 
6384 		freemsg(first_mp);
6385 	} else {
6386 		if (IPCL_IS_IPTUN(connp)) {
6387 			/*
6388 			 * Tunneled packet.  We enforce policy in the tunnel
6389 			 * module itself.
6390 			 *
6391 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6392 			 * a policy check.
6393 			 */
6394 			putnext(rq, first_mp);
6395 			CONN_DEC_REF(connp);
6396 			return;
6397 		}
6398 
6399 		if ((CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6400 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6401 			    ipha, NULL, mctl_present);
6402 		}
6403 
6404 		if (first_mp != NULL) {
6405 			/*
6406 			 * ip_fanout_proto also gets called
6407 			 * from icmp_inbound_error_fanout, in
6408 			 * which case the msg type is M_CTL.
6409 			 * Don't add info in this case for time
6410 			 * being. In future when there is a
6411 			 * need for knowing the inbound iface
6412 			 * index for ICMP error msgs, then this
6413 			 * can be changed
6414 			 */
6415 			if ((connp->conn_recvif != 0) &&
6416 			    (mp->b_datap->db_type != M_CTL)) {
6417 				/*
6418 				 * the actual data will be contained in
6419 				 * b_cont upon successful return
6420 				 * of the following call else original
6421 				 * mblk is returned
6422 				 */
6423 				ASSERT(recv_ill != NULL);
6424 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6425 			}
6426 			BUMP_MIB(&ip_mib, ipInDelivers);
6427 			putnext(rq, mp);
6428 			if (mctl_present)
6429 				freeb(first_mp);
6430 		}
6431 	}
6432 	CONN_DEC_REF(connp);
6433 }
6434 
6435 /*
6436  * Fanout for TCP packets
6437  * The caller puts <fport, lport> in the ports parameter.
6438  *
6439  * IPQoS Notes
6440  * Before sending it to the client, invoke IPPF processing.
6441  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6442  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6443  * ip_policy is false.
6444  */
6445 static void
6446 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6447     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6448 {
6449 	mblk_t  *first_mp;
6450 	boolean_t secure;
6451 	uint32_t ill_index;
6452 	int	ip_hdr_len;
6453 	tcph_t	*tcph;
6454 	boolean_t syn_present = B_FALSE;
6455 	conn_t	*connp;
6456 
6457 	first_mp = mp;
6458 	if (mctl_present) {
6459 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6460 		mp = first_mp->b_cont;
6461 		secure = ipsec_in_is_secure(first_mp);
6462 		ASSERT(mp != NULL);
6463 	} else {
6464 		secure = B_FALSE;
6465 	}
6466 
6467 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6468 
6469 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6470 	    NULL) {
6471 		/*
6472 		 * No connected connection or listener. Send a
6473 		 * TH_RST via tcp_xmit_listeners_reset.
6474 		 */
6475 
6476 		/* Initiate IPPf processing, if needed. */
6477 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6478 			uint32_t ill_index;
6479 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6480 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6481 			if (first_mp == NULL)
6482 				return;
6483 		}
6484 		BUMP_MIB(&ip_mib, ipInDelivers);
6485 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6486 		    zoneid));
6487 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6488 		return;
6489 	}
6490 
6491 	/*
6492 	 * Allocate the SYN for the TCP connection here itself
6493 	 */
6494 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6495 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6496 		if (IPCL_IS_TCP(connp)) {
6497 			squeue_t *sqp;
6498 
6499 			/*
6500 			 * For fused tcp loopback, assign the eager's
6501 			 * squeue to be that of the active connect's.
6502 			 * Note that we don't check for IP_FF_LOOPBACK
6503 			 * here since this routine gets called only
6504 			 * for loopback (unlike the IPv6 counterpart).
6505 			 */
6506 			ASSERT(Q_TO_CONN(q) != NULL);
6507 			if (do_tcp_fusion &&
6508 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6509 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6510 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6511 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6512 				sqp = Q_TO_CONN(q)->conn_sqp;
6513 			} else {
6514 				sqp = IP_SQUEUE_GET(lbolt);
6515 			}
6516 
6517 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6518 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6519 			syn_present = B_TRUE;
6520 		}
6521 	}
6522 
6523 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6524 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6525 		if ((flags & TH_RST) || (flags & TH_URG)) {
6526 			CONN_DEC_REF(connp);
6527 			freemsg(first_mp);
6528 			return;
6529 		}
6530 		if (flags & TH_ACK) {
6531 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6532 			CONN_DEC_REF(connp);
6533 			return;
6534 		}
6535 
6536 		CONN_DEC_REF(connp);
6537 		freemsg(first_mp);
6538 		return;
6539 	}
6540 
6541 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6542 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6543 		    NULL, mctl_present);
6544 		if (first_mp == NULL) {
6545 			CONN_DEC_REF(connp);
6546 			return;
6547 		}
6548 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6549 			ASSERT(syn_present);
6550 			if (mctl_present) {
6551 				ASSERT(first_mp != mp);
6552 				first_mp->b_datap->db_struioflag |=
6553 				    STRUIO_POLICY;
6554 			} else {
6555 				ASSERT(first_mp == mp);
6556 				mp->b_datap->db_struioflag &=
6557 				    ~STRUIO_EAGER;
6558 				mp->b_datap->db_struioflag |=
6559 				    STRUIO_POLICY;
6560 			}
6561 		} else {
6562 			/*
6563 			 * Discard first_mp early since we're dealing with a
6564 			 * fully-connected conn_t and tcp doesn't do policy in
6565 			 * this case.
6566 			 */
6567 			if (mctl_present) {
6568 				freeb(first_mp);
6569 				mctl_present = B_FALSE;
6570 			}
6571 			first_mp = mp;
6572 		}
6573 	}
6574 
6575 	/*
6576 	 * Initiate policy processing here if needed. If we get here from
6577 	 * icmp_inbound_error_fanout, ip_policy is false.
6578 	 */
6579 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6580 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6581 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6582 		if (mp == NULL) {
6583 			CONN_DEC_REF(connp);
6584 			if (mctl_present)
6585 				freeb(first_mp);
6586 			return;
6587 		} else if (mctl_present) {
6588 			ASSERT(first_mp != mp);
6589 			first_mp->b_cont = mp;
6590 		} else {
6591 			first_mp = mp;
6592 		}
6593 	}
6594 
6595 
6596 
6597 	/* Handle IPv6 socket options. */
6598 	if (!syn_present &&
6599 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6600 		/* Add header */
6601 		ASSERT(recv_ill != NULL);
6602 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6603 		if (mp == NULL) {
6604 			CONN_DEC_REF(connp);
6605 			if (mctl_present)
6606 				freeb(first_mp);
6607 			return;
6608 		} else if (mctl_present) {
6609 			/*
6610 			 * ip_add_info might return a new mp.
6611 			 */
6612 			ASSERT(first_mp != mp);
6613 			first_mp->b_cont = mp;
6614 		} else {
6615 			first_mp = mp;
6616 		}
6617 	}
6618 
6619 	BUMP_MIB(&ip_mib, ipInDelivers);
6620 	if (IPCL_IS_TCP(connp)) {
6621 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6622 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6623 	} else {
6624 		putnext(connp->conn_rq, first_mp);
6625 		CONN_DEC_REF(connp);
6626 	}
6627 }
6628 
6629 /*
6630  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6631  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6632  * Caller is responsible for dropping references to the conn, and freeing
6633  * first_mp.
6634  *
6635  * IPQoS Notes
6636  * Before sending it to the client, invoke IPPF processing. Policy processing
6637  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6638  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6639  * ip_wput_local, ip_policy is false.
6640  */
6641 static void
6642 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6643     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6644     boolean_t ip_policy)
6645 {
6646 	boolean_t	mctl_present = (first_mp != NULL);
6647 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6648 	uint32_t	ill_index;
6649 
6650 	if (mctl_present)
6651 		first_mp->b_cont = mp;
6652 	else
6653 		first_mp = mp;
6654 
6655 	if (CONN_UDP_FLOWCTLD(connp)) {
6656 		BUMP_MIB(&ip_mib, udpInOverflows);
6657 		freemsg(first_mp);
6658 		return;
6659 	}
6660 
6661 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6662 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6663 		    NULL, mctl_present);
6664 		if (first_mp == NULL)
6665 			return;	/* Freed by ipsec_check_inbound_policy(). */
6666 	}
6667 	if (mctl_present)
6668 		freeb(first_mp);
6669 
6670 	if (connp->conn_recvif)
6671 		in_flags = IPF_RECVIF;
6672 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6673 		in_flags |= IPF_RECVSLLA;
6674 
6675 	/* Handle IPv6 options. */
6676 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6677 		in_flags |= IPF_RECVIF;
6678 
6679 	/*
6680 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6681 	 * freed if the packet is dropped. The caller will do so.
6682 	 */
6683 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6684 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6685 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6686 		if (mp == NULL) {
6687 			return;
6688 		}
6689 	}
6690 	if ((in_flags != 0) &&
6691 	    (mp->b_datap->db_type != M_CTL)) {
6692 		/*
6693 		 * The actual data will be contained in b_cont
6694 		 * upon successful return of the following call
6695 		 * else original mblk is returned
6696 		 */
6697 		ASSERT(recv_ill != NULL);
6698 		mp = ip_add_info(mp, recv_ill, in_flags);
6699 	}
6700 	BUMP_MIB(&ip_mib, ipInDelivers);
6701 
6702 	/* Send it upstream */
6703 	CONN_UDP_RECV(connp, mp);
6704 }
6705 
6706 /*
6707  * Fanout for UDP packets.
6708  * The caller puts <fport, lport> in the ports parameter.
6709  *
6710  * If SO_REUSEADDR is set all multicast and broadcast packets
6711  * will be delivered to all streams bound to the same port.
6712  *
6713  * Zones notes:
6714  * Multicast and broadcast packets will be distributed to streams in all zones.
6715  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6716  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6717  * packets. To maintain this behavior with multiple zones, the conns are grouped
6718  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6719  * each zone. If unset, all the following conns in the same zone are skipped.
6720  */
6721 static void
6722 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6723     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6724     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6725 {
6726 	uint32_t	dstport, srcport;
6727 	ipaddr_t	dst;
6728 	mblk_t		*first_mp;
6729 	boolean_t	secure;
6730 	in6_addr_t	v6src;
6731 	conn_t		*connp;
6732 	connf_t		*connfp;
6733 	conn_t		*first_connp;
6734 	conn_t		*next_connp;
6735 	mblk_t		*mp1, *first_mp1;
6736 	ipaddr_t	src;
6737 	zoneid_t	last_zoneid;
6738 	boolean_t	reuseaddr;
6739 	boolean_t	shared_addr;
6740 
6741 	first_mp = mp;
6742 	if (mctl_present) {
6743 		mp = first_mp->b_cont;
6744 		first_mp->b_cont = NULL;
6745 		secure = ipsec_in_is_secure(first_mp);
6746 		ASSERT(mp != NULL);
6747 	} else {
6748 		first_mp = NULL;
6749 		secure = B_FALSE;
6750 	}
6751 
6752 	/* Extract ports in net byte order */
6753 	dstport = htons(ntohl(ports) & 0xFFFF);
6754 	srcport = htons(ntohl(ports) >> 16);
6755 	dst = ipha->ipha_dst;
6756 	src = ipha->ipha_src;
6757 
6758 	shared_addr = (zoneid == ALL_ZONES);
6759 	if (shared_addr) {
6760 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6761 		if (zoneid == ALL_ZONES)
6762 			zoneid = tsol_packet_to_zoneid(mp);
6763 	}
6764 
6765 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6766 	mutex_enter(&connfp->connf_lock);
6767 	connp = connfp->connf_head;
6768 	if (!broadcast && !CLASSD(dst)) {
6769 		/*
6770 		 * Not broadcast or multicast. Send to the one (first)
6771 		 * client we find. No need to check conn_wantpacket()
6772 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6773 		 * IPv4 unicast packets.
6774 		 */
6775 		while ((connp != NULL) &&
6776 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
6777 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
6778 			connp = connp->conn_next;
6779 		}
6780 
6781 		if (connp == NULL || connp->conn_upq == NULL)
6782 			goto notfound;
6783 
6784 		if (is_system_labeled() &&
6785 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6786 		    connp))
6787 			goto notfound;
6788 
6789 		CONN_INC_REF(connp);
6790 		mutex_exit(&connfp->connf_lock);
6791 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6792 		    recv_ill, ip_policy);
6793 		IP_STAT(ip_udp_fannorm);
6794 		CONN_DEC_REF(connp);
6795 		return;
6796 	}
6797 
6798 	/*
6799 	 * Broadcast and multicast case
6800 	 *
6801 	 * Need to check conn_wantpacket().
6802 	 * If SO_REUSEADDR has been set on the first we send the
6803 	 * packet to all clients that have joined the group and
6804 	 * match the port.
6805 	 */
6806 
6807 	while (connp != NULL) {
6808 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6809 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6810 		    (!is_system_labeled() ||
6811 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6812 		    connp)))
6813 			break;
6814 		connp = connp->conn_next;
6815 	}
6816 
6817 	if (connp == NULL || connp->conn_upq == NULL)
6818 		goto notfound;
6819 
6820 	first_connp = connp;
6821 	/*
6822 	 * When SO_REUSEADDR is not set, send the packet only to the first
6823 	 * matching connection in its zone by keeping track of the zoneid.
6824 	 */
6825 	reuseaddr = first_connp->conn_reuseaddr;
6826 	last_zoneid = first_connp->conn_zoneid;
6827 
6828 	CONN_INC_REF(connp);
6829 	connp = connp->conn_next;
6830 	for (;;) {
6831 		while (connp != NULL) {
6832 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6833 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6834 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6835 			    (!is_system_labeled() ||
6836 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6837 			    shared_addr, connp)))
6838 				break;
6839 			connp = connp->conn_next;
6840 		}
6841 		/*
6842 		 * Just copy the data part alone. The mctl part is
6843 		 * needed just for verifying policy and it is never
6844 		 * sent up.
6845 		 */
6846 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6847 		    ((mp1 = copymsg(mp)) == NULL))) {
6848 			/*
6849 			 * No more interested clients or memory
6850 			 * allocation failed
6851 			 */
6852 			connp = first_connp;
6853 			break;
6854 		}
6855 		if (connp->conn_zoneid != last_zoneid) {
6856 			/*
6857 			 * Update the zoneid so that the packet isn't sent to
6858 			 * any more conns in the same zone unless SO_REUSEADDR
6859 			 * is set.
6860 			 */
6861 			reuseaddr = connp->conn_reuseaddr;
6862 			last_zoneid = connp->conn_zoneid;
6863 		}
6864 		if (first_mp != NULL) {
6865 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6866 			    ipsec_info_type == IPSEC_IN);
6867 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6868 			if (first_mp1 == NULL) {
6869 				freemsg(mp1);
6870 				connp = first_connp;
6871 				break;
6872 			}
6873 		} else {
6874 			first_mp1 = NULL;
6875 		}
6876 		CONN_INC_REF(connp);
6877 		mutex_exit(&connfp->connf_lock);
6878 		/*
6879 		 * IPQoS notes: We don't send the packet for policy
6880 		 * processing here, will do it for the last one (below).
6881 		 * i.e. we do it per-packet now, but if we do policy
6882 		 * processing per-conn, then we would need to do it
6883 		 * here too.
6884 		 */
6885 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6886 		    ipha, flags, recv_ill, B_FALSE);
6887 		mutex_enter(&connfp->connf_lock);
6888 		/* Follow the next pointer before releasing the conn. */
6889 		next_connp = connp->conn_next;
6890 		IP_STAT(ip_udp_fanmb);
6891 		CONN_DEC_REF(connp);
6892 		connp = next_connp;
6893 	}
6894 
6895 	/* Last one.  Send it upstream. */
6896 	mutex_exit(&connfp->connf_lock);
6897 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6898 	    ip_policy);
6899 	IP_STAT(ip_udp_fanmb);
6900 	CONN_DEC_REF(connp);
6901 	return;
6902 
6903 notfound:
6904 
6905 	mutex_exit(&connfp->connf_lock);
6906 	IP_STAT(ip_udp_fanothers);
6907 	/*
6908 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6909 	 * have already been matched above, since they live in the IPv4
6910 	 * fanout tables. This implies we only need to
6911 	 * check for IPv6 in6addr_any endpoints here.
6912 	 * Thus we compare using ipv6_all_zeros instead of the destination
6913 	 * address, except for the multicast group membership lookup which
6914 	 * uses the IPv4 destination.
6915 	 */
6916 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6917 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6918 	mutex_enter(&connfp->connf_lock);
6919 	connp = connfp->connf_head;
6920 	if (!broadcast && !CLASSD(dst)) {
6921 		while (connp != NULL) {
6922 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6923 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6924 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6925 			    !connp->conn_ipv6_v6only)
6926 				break;
6927 			connp = connp->conn_next;
6928 		}
6929 
6930 		if (connp != NULL && is_system_labeled() &&
6931 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6932 		    connp))
6933 			connp = NULL;
6934 
6935 		if (connp == NULL || connp->conn_upq == NULL) {
6936 			/*
6937 			 * No one bound to this port.  Is
6938 			 * there a client that wants all
6939 			 * unclaimed datagrams?
6940 			 */
6941 			mutex_exit(&connfp->connf_lock);
6942 
6943 			if (mctl_present)
6944 				first_mp->b_cont = mp;
6945 			else
6946 				first_mp = mp;
6947 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6948 				ip_fanout_proto(q, first_mp, ill, ipha,
6949 				    flags | IP_FF_RAWIP, mctl_present,
6950 				    ip_policy, recv_ill, zoneid);
6951 			} else {
6952 				if (ip_fanout_send_icmp(q, first_mp, flags,
6953 				    ICMP_DEST_UNREACHABLE,
6954 				    ICMP_PORT_UNREACHABLE,
6955 				    mctl_present, zoneid)) {
6956 					BUMP_MIB(&ip_mib, udpNoPorts);
6957 				}
6958 			}
6959 			return;
6960 		}
6961 
6962 		CONN_INC_REF(connp);
6963 		mutex_exit(&connfp->connf_lock);
6964 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6965 		    recv_ill, ip_policy);
6966 		CONN_DEC_REF(connp);
6967 		return;
6968 	}
6969 	/*
6970 	 * IPv4 multicast packet being delivered to an AF_INET6
6971 	 * in6addr_any endpoint.
6972 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6973 	 * and not conn_wantpacket_v6() since any multicast membership is
6974 	 * for an IPv4-mapped multicast address.
6975 	 * The packet is sent to all clients in all zones that have joined the
6976 	 * group and match the port.
6977 	 */
6978 	while (connp != NULL) {
6979 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6980 		    srcport, v6src) &&
6981 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6982 		    (!is_system_labeled() ||
6983 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6984 		    connp)))
6985 			break;
6986 		connp = connp->conn_next;
6987 	}
6988 
6989 	if (connp == NULL || connp->conn_upq == NULL) {
6990 		/*
6991 		 * No one bound to this port.  Is
6992 		 * there a client that wants all
6993 		 * unclaimed datagrams?
6994 		 */
6995 		mutex_exit(&connfp->connf_lock);
6996 
6997 		if (mctl_present)
6998 			first_mp->b_cont = mp;
6999 		else
7000 			first_mp = mp;
7001 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
7002 			ip_fanout_proto(q, first_mp, ill, ipha,
7003 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7004 			    recv_ill, zoneid);
7005 		} else {
7006 			/*
7007 			 * We used to attempt to send an icmp error here, but
7008 			 * since this is known to be a multicast packet
7009 			 * and we don't send icmp errors in response to
7010 			 * multicast, just drop the packet and give up sooner.
7011 			 */
7012 			BUMP_MIB(&ip_mib, udpNoPorts);
7013 			freemsg(first_mp);
7014 		}
7015 		return;
7016 	}
7017 
7018 	first_connp = connp;
7019 
7020 	CONN_INC_REF(connp);
7021 	connp = connp->conn_next;
7022 	for (;;) {
7023 		while (connp != NULL) {
7024 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7025 			    ipv6_all_zeros, srcport, v6src) &&
7026 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7027 			    (!is_system_labeled() ||
7028 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7029 			    shared_addr, connp)))
7030 				break;
7031 			connp = connp->conn_next;
7032 		}
7033 		/*
7034 		 * Just copy the data part alone. The mctl part is
7035 		 * needed just for verifying policy and it is never
7036 		 * sent up.
7037 		 */
7038 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7039 		    ((mp1 = copymsg(mp)) == NULL))) {
7040 			/*
7041 			 * No more intested clients or memory
7042 			 * allocation failed
7043 			 */
7044 			connp = first_connp;
7045 			break;
7046 		}
7047 		if (first_mp != NULL) {
7048 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7049 			    ipsec_info_type == IPSEC_IN);
7050 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7051 			if (first_mp1 == NULL) {
7052 				freemsg(mp1);
7053 				connp = first_connp;
7054 				break;
7055 			}
7056 		} else {
7057 			first_mp1 = NULL;
7058 		}
7059 		CONN_INC_REF(connp);
7060 		mutex_exit(&connfp->connf_lock);
7061 		/*
7062 		 * IPQoS notes: We don't send the packet for policy
7063 		 * processing here, will do it for the last one (below).
7064 		 * i.e. we do it per-packet now, but if we do policy
7065 		 * processing per-conn, then we would need to do it
7066 		 * here too.
7067 		 */
7068 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
7069 		    ipha, flags, recv_ill, B_FALSE);
7070 		mutex_enter(&connfp->connf_lock);
7071 		/* Follow the next pointer before releasing the conn. */
7072 		next_connp = connp->conn_next;
7073 		CONN_DEC_REF(connp);
7074 		connp = next_connp;
7075 	}
7076 
7077 	/* Last one.  Send it upstream. */
7078 	mutex_exit(&connfp->connf_lock);
7079 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
7080 	    ip_policy);
7081 	CONN_DEC_REF(connp);
7082 }
7083 
7084 /*
7085  * Complete the ip_wput header so that it
7086  * is possible to generate ICMP
7087  * errors.
7088  */
7089 int
7090 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
7091 {
7092 	ire_t *ire;
7093 
7094 	if (ipha->ipha_src == INADDR_ANY) {
7095 		ire = ire_lookup_local(zoneid);
7096 		if (ire == NULL) {
7097 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7098 			return (1);
7099 		}
7100 		ipha->ipha_src = ire->ire_addr;
7101 		ire_refrele(ire);
7102 	}
7103 	ipha->ipha_ttl = ip_def_ttl;
7104 	ipha->ipha_hdr_checksum = 0;
7105 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7106 	return (0);
7107 }
7108 
7109 /*
7110  * Nobody should be sending
7111  * packets up this stream
7112  */
7113 static void
7114 ip_lrput(queue_t *q, mblk_t *mp)
7115 {
7116 	mblk_t *mp1;
7117 
7118 	switch (mp->b_datap->db_type) {
7119 	case M_FLUSH:
7120 		/* Turn around */
7121 		if (*mp->b_rptr & FLUSHW) {
7122 			*mp->b_rptr &= ~FLUSHR;
7123 			qreply(q, mp);
7124 			return;
7125 		}
7126 		break;
7127 	}
7128 	/* Could receive messages that passed through ar_rput */
7129 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7130 		mp1->b_prev = mp1->b_next = NULL;
7131 	freemsg(mp);
7132 }
7133 
7134 /* Nobody should be sending packets down this stream */
7135 /* ARGSUSED */
7136 void
7137 ip_lwput(queue_t *q, mblk_t *mp)
7138 {
7139 	freemsg(mp);
7140 }
7141 
7142 /*
7143  * Move the first hop in any source route to ipha_dst and remove that part of
7144  * the source route.  Called by other protocols.  Errors in option formatting
7145  * are ignored - will be handled by ip_wput_options Return the final
7146  * destination (either ipha_dst or the last entry in a source route.)
7147  */
7148 ipaddr_t
7149 ip_massage_options(ipha_t *ipha)
7150 {
7151 	ipoptp_t	opts;
7152 	uchar_t		*opt;
7153 	uint8_t		optval;
7154 	uint8_t		optlen;
7155 	ipaddr_t	dst;
7156 	int		i;
7157 	ire_t		*ire;
7158 
7159 	ip2dbg(("ip_massage_options\n"));
7160 	dst = ipha->ipha_dst;
7161 	for (optval = ipoptp_first(&opts, ipha);
7162 	    optval != IPOPT_EOL;
7163 	    optval = ipoptp_next(&opts)) {
7164 		opt = opts.ipoptp_cur;
7165 		switch (optval) {
7166 			uint8_t off;
7167 		case IPOPT_SSRR:
7168 		case IPOPT_LSRR:
7169 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7170 				ip1dbg(("ip_massage_options: bad src route\n"));
7171 				break;
7172 			}
7173 			optlen = opts.ipoptp_len;
7174 			off = opt[IPOPT_OFFSET];
7175 			off--;
7176 		redo_srr:
7177 			if (optlen < IP_ADDR_LEN ||
7178 			    off > optlen - IP_ADDR_LEN) {
7179 				/* End of source route */
7180 				ip1dbg(("ip_massage_options: end of SR\n"));
7181 				break;
7182 			}
7183 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7184 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7185 			    ntohl(dst)));
7186 			/*
7187 			 * Check if our address is present more than
7188 			 * once as consecutive hops in source route.
7189 			 * XXX verify per-interface ip_forwarding
7190 			 * for source route?
7191 			 */
7192 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7193 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
7194 			if (ire != NULL) {
7195 				ire_refrele(ire);
7196 				off += IP_ADDR_LEN;
7197 				goto redo_srr;
7198 			}
7199 			if (dst == htonl(INADDR_LOOPBACK)) {
7200 				ip1dbg(("ip_massage_options: loopback addr in "
7201 				    "source route!\n"));
7202 				break;
7203 			}
7204 			/*
7205 			 * Update ipha_dst to be the first hop and remove the
7206 			 * first hop from the source route (by overwriting
7207 			 * part of the option with NOP options).
7208 			 */
7209 			ipha->ipha_dst = dst;
7210 			/* Put the last entry in dst */
7211 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7212 			    3;
7213 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7214 
7215 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7216 			    ntohl(dst)));
7217 			/* Move down and overwrite */
7218 			opt[IP_ADDR_LEN] = opt[0];
7219 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7220 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7221 			for (i = 0; i < IP_ADDR_LEN; i++)
7222 				opt[i] = IPOPT_NOP;
7223 			break;
7224 		}
7225 	}
7226 	return (dst);
7227 }
7228 
7229 /*
7230  * This function's job is to forward data to the reverse tunnel (FA->HA)
7231  * after doing a few checks. It is assumed that the incoming interface
7232  * of the packet is always different than the outgoing interface and the
7233  * ire_type of the found ire has to be a non-resolver type.
7234  *
7235  * IPQoS notes
7236  * IP policy is invoked twice for a forwarded packet, once on the read side
7237  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7238  * enabled.
7239  */
7240 static void
7241 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7242 {
7243 	ipha_t		*ipha;
7244 	queue_t		*q;
7245 	uint32_t 	pkt_len;
7246 #define	rptr    ((uchar_t *)ipha)
7247 	uint32_t 	sum;
7248 	uint32_t 	max_frag;
7249 	mblk_t		*first_mp;
7250 	uint32_t	ill_index;
7251 	ipxmit_state_t	pktxmit_state;
7252 	ill_t		*out_ill;
7253 
7254 	ASSERT(ire != NULL);
7255 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7256 	ASSERT(ire->ire_stq != NULL);
7257 
7258 	/* Initiate read side IPPF processing */
7259 	if (IPP_ENABLED(IPP_FWD_IN)) {
7260 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7261 		ip_process(IPP_FWD_IN, &mp, ill_index);
7262 		if (mp == NULL) {
7263 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7264 			    "dropped during IPPF processing\n"));
7265 			return;
7266 		}
7267 	}
7268 
7269 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7270 		ILLF_ROUTER) == 0) ||
7271 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7272 		BUMP_MIB(&ip_mib, ipForwProhibits);
7273 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7274 		    "forwarding is not turned on\n"));
7275 		goto drop_pkt;
7276 	}
7277 
7278 	/*
7279 	 * Don't forward if the interface is down
7280 	 */
7281 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7282 		BUMP_MIB(&ip_mib, ipInDiscards);
7283 		goto drop_pkt;
7284 	}
7285 
7286 	ipha = (ipha_t *)mp->b_rptr;
7287 	pkt_len = ntohs(ipha->ipha_length);
7288 	/* Adjust the checksum to reflect the ttl decrement. */
7289 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7290 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7291 	if (ipha->ipha_ttl-- <= 1) {
7292 		if (ip_csum_hdr(ipha)) {
7293 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7294 			goto drop_pkt;
7295 		}
7296 		q = ire->ire_stq;
7297 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7298 		    BPRI_HI)) == NULL) {
7299 			goto drop_pkt;
7300 		}
7301 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7302 		/* Sent by forwarding path, and router is global zone */
7303 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7304 		    GLOBAL_ZONEID);
7305 		return;
7306 	}
7307 
7308 	/* Get the ill_index of the ILL */
7309 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7310 
7311 	/*
7312 	 * This location is chosen for the placement of the forwarding hook
7313 	 * because at this point we know that we have a path out for the
7314 	 * packet but haven't yet applied any logic (such as fragmenting)
7315 	 * that happen as part of transmitting the packet out.
7316 	 */
7317 	out_ill = ire->ire_ipif->ipif_ill;
7318 
7319 	DTRACE_PROBE4(ip4__forwarding__start,
7320 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7321 
7322 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
7323 	    in_ill, out_ill, ipha, mp, mp);
7324 
7325 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7326 
7327 	if (mp == NULL)
7328 		return;
7329 	pkt_len = ntohs(ipha->ipha_length);
7330 
7331 	/*
7332 	 * ip_mrtun_forward is only used by foreign agent to reverse
7333 	 * tunnel the incoming packet. So it does not do any option
7334 	 * processing for source routing.
7335 	 */
7336 	max_frag = ire->ire_max_frag;
7337 	if (pkt_len > max_frag) {
7338 		/*
7339 		 * It needs fragging on its way out.  We haven't
7340 		 * verified the header checksum yet.  Since we
7341 		 * are going to put a surely good checksum in the
7342 		 * outgoing header, we have to make sure that it
7343 		 * was good coming in.
7344 		 */
7345 		if (ip_csum_hdr(ipha)) {
7346 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7347 			goto drop_pkt;
7348 		}
7349 
7350 		/* Initiate write side IPPF processing */
7351 		if (IPP_ENABLED(IPP_FWD_OUT)) {
7352 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7353 			if (mp == NULL) {
7354 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7355 				    "dropped/deferred during ip policy "\
7356 				    "processing\n"));
7357 				return;
7358 			}
7359 		}
7360 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7361 		    BPRI_HI)) == NULL) {
7362 			goto drop_pkt;
7363 		}
7364 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7365 		mp = first_mp;
7366 
7367 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
7368 		return;
7369 	}
7370 
7371 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7372 
7373 	ASSERT(ire->ire_ipif != NULL);
7374 
7375 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7376 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7377 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
7378 	    NULL, out_ill, ipha, mp, mp);
7379 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7380 	if (mp == NULL)
7381 		return;
7382 
7383 	/* Now send the packet to the tunnel interface */
7384 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7385 	q = ire->ire_stq;
7386 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7387 	if ((pktxmit_state == SEND_FAILED) ||
7388 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7389 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7390 		    q->q_ptr));
7391 	}
7392 
7393 	return;
7394 
7395 drop_pkt:;
7396 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7397 	freemsg(mp);
7398 #undef	rptr
7399 }
7400 
7401 /*
7402  * Fills the ipsec_out_t data structure with appropriate fields and
7403  * prepends it to mp which contains the IP hdr + data that was meant
7404  * to be forwarded. Please note that ipsec_out_info data structure
7405  * is used here to communicate the outgoing ill path at ip_wput()
7406  * for the ICMP error packet. This has nothing to do with ipsec IP
7407  * security. ipsec_out_t is really used to pass the info to the module
7408  * IP where this information cannot be extracted from conn.
7409  * This functions is called by ip_mrtun_forward().
7410  */
7411 void
7412 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7413 {
7414 	ipsec_out_t	*io;
7415 
7416 	ASSERT(xmit_ill != NULL);
7417 	first_mp->b_datap->db_type = M_CTL;
7418 	first_mp->b_wptr += sizeof (ipsec_info_t);
7419 	/*
7420 	 * This is to pass info to ip_wput in absence of conn.
7421 	 * ipsec_out_secure will be B_FALSE because of this.
7422 	 * Thus ipsec_out_secure being B_FALSE indicates that
7423 	 * this is not IPSEC security related information.
7424 	 */
7425 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7426 	io = (ipsec_out_t *)first_mp->b_rptr;
7427 	io->ipsec_out_type = IPSEC_OUT;
7428 	io->ipsec_out_len = sizeof (ipsec_out_t);
7429 	first_mp->b_cont = mp;
7430 	io->ipsec_out_ill_index =
7431 	    xmit_ill->ill_phyint->phyint_ifindex;
7432 	io->ipsec_out_xmit_if = B_TRUE;
7433 }
7434 
7435 /*
7436  * Return the network mask
7437  * associated with the specified address.
7438  */
7439 ipaddr_t
7440 ip_net_mask(ipaddr_t addr)
7441 {
7442 	uchar_t	*up = (uchar_t *)&addr;
7443 	ipaddr_t mask = 0;
7444 	uchar_t	*maskp = (uchar_t *)&mask;
7445 
7446 #if defined(__i386) || defined(__amd64)
7447 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7448 #endif
7449 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7450 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7451 #endif
7452 	if (CLASSD(addr)) {
7453 		maskp[0] = 0xF0;
7454 		return (mask);
7455 	}
7456 	if (addr == 0)
7457 		return (0);
7458 	maskp[0] = 0xFF;
7459 	if ((up[0] & 0x80) == 0)
7460 		return (mask);
7461 
7462 	maskp[1] = 0xFF;
7463 	if ((up[0] & 0xC0) == 0x80)
7464 		return (mask);
7465 
7466 	maskp[2] = 0xFF;
7467 	if ((up[0] & 0xE0) == 0xC0)
7468 		return (mask);
7469 
7470 	/* Must be experimental or multicast, indicate as much */
7471 	return ((ipaddr_t)0);
7472 }
7473 
7474 /*
7475  * Select an ill for the packet by considering load spreading across
7476  * a different ill in the group if dst_ill is part of some group.
7477  */
7478 ill_t *
7479 ip_newroute_get_dst_ill(ill_t *dst_ill)
7480 {
7481 	ill_t *ill;
7482 
7483 	/*
7484 	 * We schedule irrespective of whether the source address is
7485 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7486 	 */
7487 	ill = illgrp_scheduler(dst_ill);
7488 	if (ill == NULL)
7489 		return (NULL);
7490 
7491 	/*
7492 	 * For groups with names ip_sioctl_groupname ensures that all
7493 	 * ills are of same type. For groups without names, ifgrp_insert
7494 	 * ensures this.
7495 	 */
7496 	ASSERT(dst_ill->ill_type == ill->ill_type);
7497 
7498 	return (ill);
7499 }
7500 
7501 /*
7502  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7503  */
7504 ill_t *
7505 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7506 {
7507 	ill_t *ret_ill;
7508 
7509 	ASSERT(ifindex != 0);
7510 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7511 	if (ret_ill == NULL ||
7512 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7513 		if (isv6) {
7514 			if (ill != NULL) {
7515 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7516 			} else {
7517 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7518 			}
7519 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7520 			    "bad ifindex %d.\n", ifindex));
7521 		} else {
7522 			BUMP_MIB(&ip_mib, ipOutDiscards);
7523 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7524 			    "bad ifindex %d.\n", ifindex));
7525 		}
7526 		if (ret_ill != NULL)
7527 			ill_refrele(ret_ill);
7528 		freemsg(first_mp);
7529 		return (NULL);
7530 	}
7531 
7532 	return (ret_ill);
7533 }
7534 
7535 /*
7536  * IPv4 -
7537  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7538  * out a packet to a destination address for which we do not have specific
7539  * (or sufficient) routing information.
7540  *
7541  * NOTE : These are the scopes of some of the variables that point at IRE,
7542  *	  which needs to be followed while making any future modifications
7543  *	  to avoid memory leaks.
7544  *
7545  *	- ire and sire are the entries looked up initially by
7546  *	  ire_ftable_lookup.
7547  *	- ipif_ire is used to hold the interface ire associated with
7548  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7549  *	  it before branching out to error paths.
7550  *	- save_ire is initialized before ire_create, so that ire returned
7551  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7552  *	  before breaking out of the switch.
7553  *
7554  *	Thus on failures, we have to REFRELE only ire and sire, if they
7555  *	are not NULL.
7556  */
7557 void
7558 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7559     zoneid_t zoneid)
7560 {
7561 	areq_t	*areq;
7562 	ipaddr_t gw = 0;
7563 	ire_t	*ire = NULL;
7564 	mblk_t	*res_mp;
7565 	ipaddr_t *addrp;
7566 	ipaddr_t nexthop_addr;
7567 	ipif_t  *src_ipif = NULL;
7568 	ill_t	*dst_ill = NULL;
7569 	ipha_t  *ipha;
7570 	ire_t	*sire = NULL;
7571 	mblk_t	*first_mp;
7572 	ire_t	*save_ire;
7573 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7574 	ushort_t ire_marks = 0;
7575 	boolean_t mctl_present;
7576 	ipsec_out_t *io;
7577 	mblk_t	*saved_mp;
7578 	ire_t	*first_sire = NULL;
7579 	mblk_t	*copy_mp = NULL;
7580 	mblk_t	*xmit_mp = NULL;
7581 	ipaddr_t save_dst;
7582 	uint32_t multirt_flags =
7583 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7584 	boolean_t multirt_is_resolvable;
7585 	boolean_t multirt_resolve_next;
7586 	boolean_t do_attach_ill = B_FALSE;
7587 	boolean_t ip_nexthop = B_FALSE;
7588 	tsol_ire_gw_secattr_t *attrp = NULL;
7589 	tsol_gcgrp_t *gcgrp = NULL;
7590 	tsol_gcgrp_addr_t ga;
7591 
7592 	if (ip_debug > 2) {
7593 		/* ip1dbg */
7594 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7595 	}
7596 
7597 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7598 	if (mctl_present) {
7599 		io = (ipsec_out_t *)first_mp->b_rptr;
7600 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7601 		ASSERT(zoneid == io->ipsec_out_zoneid);
7602 		ASSERT(zoneid != ALL_ZONES);
7603 	}
7604 
7605 	ipha = (ipha_t *)mp->b_rptr;
7606 
7607 	/* All multicast lookups come through ip_newroute_ipif() */
7608 	if (CLASSD(dst)) {
7609 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7610 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7611 		freemsg(first_mp);
7612 		return;
7613 	}
7614 
7615 	if (mctl_present && io->ipsec_out_attach_if) {
7616 		/* ip_grab_attach_ill returns a held ill */
7617 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7618 		    io->ipsec_out_ill_index, B_FALSE);
7619 
7620 		/* Failure case frees things for us. */
7621 		if (attach_ill == NULL)
7622 			return;
7623 
7624 		/*
7625 		 * Check if we need an ire that will not be
7626 		 * looked up by anybody else i.e. HIDDEN.
7627 		 */
7628 		if (ill_is_probeonly(attach_ill))
7629 			ire_marks = IRE_MARK_HIDDEN;
7630 	}
7631 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7632 		ip_nexthop = B_TRUE;
7633 		nexthop_addr = io->ipsec_out_nexthop_addr;
7634 	}
7635 	/*
7636 	 * If this IRE is created for forwarding or it is not for
7637 	 * traffic for congestion controlled protocols, mark it as temporary.
7638 	 */
7639 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7640 		ire_marks |= IRE_MARK_TEMPORARY;
7641 
7642 	/*
7643 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7644 	 * chain until it gets the most specific information available.
7645 	 * For example, we know that there is no IRE_CACHE for this dest,
7646 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7647 	 * ire_ftable_lookup will look up the gateway, etc.
7648 	 * Check if in_ill != NULL. If it is true, the packet must be
7649 	 * from an incoming interface where RTA_SRCIFP is set.
7650 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7651 	 * to the destination, of equal netmask length in the forward table,
7652 	 * will be recursively explored. If no information is available
7653 	 * for the final gateway of that route, we force the returned ire
7654 	 * to be equal to sire using MATCH_IRE_PARENT.
7655 	 * At least, in this case we have a starting point (in the buckets)
7656 	 * to look for other routes to the destination in the forward table.
7657 	 * This is actually used only for multirouting, where a list
7658 	 * of routes has to be processed in sequence.
7659 	 *
7660 	 * In the process of coming up with the most specific information,
7661 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7662 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7663 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7664 	 * Two caveats when handling incomplete ire's in ip_newroute:
7665 	 * - we should be careful when accessing its ire_nce (specifically
7666 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7667 	 * - not all legacy code path callers are prepared to handle
7668 	 *   incomplete ire's, so we should not create/add incomplete
7669 	 *   ire_cache entries here. (See discussion about temporary solution
7670 	 *   further below).
7671 	 *
7672 	 * In order to minimize packet dropping, and to preserve existing
7673 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7674 	 * gateway, and instead use the IF_RESOLVER ire to send out
7675 	 * another request to ARP (this is achieved by passing the
7676 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7677 	 * arp response comes back in ip_wput_nondata, we will create
7678 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7679 	 *
7680 	 * Note that this is a temporary solution; the correct solution is
7681 	 * to create an incomplete  per-dst ire_cache entry, and send the
7682 	 * packet out when the gw's nce is resolved. In order to achieve this,
7683 	 * all packet processing must have been completed prior to calling
7684 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7685 	 * to be modified to accomodate this solution.
7686 	 */
7687 	if (in_ill != NULL) {
7688 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7689 		    in_ill, MATCH_IRE_TYPE);
7690 	} else if (ip_nexthop) {
7691 		/*
7692 		 * The first time we come here, we look for an IRE_INTERFACE
7693 		 * entry for the specified nexthop, set the dst to be the
7694 		 * nexthop address and create an IRE_CACHE entry for the
7695 		 * nexthop. The next time around, we are able to find an
7696 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7697 		 * nexthop address and create an IRE_CACHE entry for the
7698 		 * destination address via the specified nexthop.
7699 		 */
7700 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7701 		    MBLK_GETLABEL(mp));
7702 		if (ire != NULL) {
7703 			gw = nexthop_addr;
7704 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7705 		} else {
7706 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7707 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7708 			    MBLK_GETLABEL(mp),
7709 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7710 			if (ire != NULL) {
7711 				dst = nexthop_addr;
7712 			}
7713 		}
7714 	} else if (attach_ill == NULL) {
7715 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7716 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7717 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7718 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7719 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7720 	} else {
7721 		/*
7722 		 * attach_ill is set only for communicating with
7723 		 * on-link hosts. So, don't look for DEFAULT.
7724 		 */
7725 		ipif_t	*attach_ipif;
7726 
7727 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7728 		if (attach_ipif == NULL) {
7729 			ill_refrele(attach_ill);
7730 			goto icmp_err_ret;
7731 		}
7732 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7733 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7734 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7735 		    MATCH_IRE_SECATTR);
7736 		ipif_refrele(attach_ipif);
7737 	}
7738 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7739 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7740 
7741 	/*
7742 	 * This loop is run only once in most cases.
7743 	 * We loop to resolve further routes only when the destination
7744 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7745 	 */
7746 	do {
7747 		/* Clear the previous iteration's values */
7748 		if (src_ipif != NULL) {
7749 			ipif_refrele(src_ipif);
7750 			src_ipif = NULL;
7751 		}
7752 		if (dst_ill != NULL) {
7753 			ill_refrele(dst_ill);
7754 			dst_ill = NULL;
7755 		}
7756 
7757 		multirt_resolve_next = B_FALSE;
7758 		/*
7759 		 * We check if packets have to be multirouted.
7760 		 * In this case, given the current <ire, sire> couple,
7761 		 * we look for the next suitable <ire, sire>.
7762 		 * This check is done in ire_multirt_lookup(),
7763 		 * which applies various criteria to find the next route
7764 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7765 		 * unchanged if it detects it has not been tried yet.
7766 		 */
7767 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7768 			ip3dbg(("ip_newroute: starting next_resolution "
7769 			    "with first_mp %p, tag %d\n",
7770 			    (void *)first_mp,
7771 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7772 
7773 			ASSERT(sire != NULL);
7774 			multirt_is_resolvable =
7775 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7776 				MBLK_GETLABEL(mp));
7777 
7778 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7779 			    "ire %p, sire %p\n",
7780 			    multirt_is_resolvable,
7781 			    (void *)ire, (void *)sire));
7782 
7783 			if (!multirt_is_resolvable) {
7784 				/*
7785 				 * No more multirt route to resolve; give up
7786 				 * (all routes resolved or no more
7787 				 * resolvable routes).
7788 				 */
7789 				if (ire != NULL) {
7790 					ire_refrele(ire);
7791 					ire = NULL;
7792 				}
7793 			} else {
7794 				ASSERT(sire != NULL);
7795 				ASSERT(ire != NULL);
7796 				/*
7797 				 * We simply use first_sire as a flag that
7798 				 * indicates if a resolvable multirt route
7799 				 * has already been found.
7800 				 * If it is not the case, we may have to send
7801 				 * an ICMP error to report that the
7802 				 * destination is unreachable.
7803 				 * We do not IRE_REFHOLD first_sire.
7804 				 */
7805 				if (first_sire == NULL) {
7806 					first_sire = sire;
7807 				}
7808 			}
7809 		}
7810 		if (ire == NULL) {
7811 			if (ip_debug > 3) {
7812 				/* ip2dbg */
7813 				pr_addr_dbg("ip_newroute: "
7814 				    "can't resolve %s\n", AF_INET, &dst);
7815 			}
7816 			ip3dbg(("ip_newroute: "
7817 			    "ire %p, sire %p, first_sire %p\n",
7818 			    (void *)ire, (void *)sire, (void *)first_sire));
7819 
7820 			if (sire != NULL) {
7821 				ire_refrele(sire);
7822 				sire = NULL;
7823 			}
7824 
7825 			if (first_sire != NULL) {
7826 				/*
7827 				 * At least one multirt route has been found
7828 				 * in the same call to ip_newroute();
7829 				 * there is no need to report an ICMP error.
7830 				 * first_sire was not IRE_REFHOLDed.
7831 				 */
7832 				MULTIRT_DEBUG_UNTAG(first_mp);
7833 				freemsg(first_mp);
7834 				return;
7835 			}
7836 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7837 			    RTA_DST);
7838 			if (attach_ill != NULL)
7839 				ill_refrele(attach_ill);
7840 			goto icmp_err_ret;
7841 		}
7842 
7843 		/*
7844 		 * When RTA_SRCIFP is used to add a route, then an interface
7845 		 * route is added in the source interface's routing table.
7846 		 * If the outgoing interface of this route is of type
7847 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7848 		 * ire_nce->nce_res_mp is set to NULL.
7849 		 * Later, when this route is first used for forwarding
7850 		 * a packet, ip_newroute() is called
7851 		 * to resolve the hardware address of the outgoing ipif.
7852 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7853 		 * source interface based table. We only come here if the
7854 		 * outgoing interface is a resolver interface and we don't
7855 		 * have the ire_nce->nce_res_mp information yet.
7856 		 * If in_ill is not null that means it is called from
7857 		 * ip_rput.
7858 		 */
7859 
7860 		ASSERT(ire->ire_in_ill == NULL ||
7861 		    (ire->ire_type == IRE_IF_RESOLVER &&
7862 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
7863 
7864 		/*
7865 		 * Verify that the returned IRE does not have either
7866 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7867 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7868 		 */
7869 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7870 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7871 			if (attach_ill != NULL)
7872 				ill_refrele(attach_ill);
7873 			goto icmp_err_ret;
7874 		}
7875 		/*
7876 		 * Increment the ire_ob_pkt_count field for ire if it is an
7877 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7878 		 * increment the same for the parent IRE, sire, if it is some
7879 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7880 		 * and HOST_REDIRECT).
7881 		 */
7882 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7883 			UPDATE_OB_PKT_COUNT(ire);
7884 			ire->ire_last_used_time = lbolt;
7885 		}
7886 
7887 		if (sire != NULL) {
7888 			gw = sire->ire_gateway_addr;
7889 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7890 			    IRE_INTERFACE)) == 0);
7891 			UPDATE_OB_PKT_COUNT(sire);
7892 			sire->ire_last_used_time = lbolt;
7893 		}
7894 		/*
7895 		 * We have a route to reach the destination.
7896 		 *
7897 		 * 1) If the interface is part of ill group, try to get a new
7898 		 *    ill taking load spreading into account.
7899 		 *
7900 		 * 2) After selecting the ill, get a source address that
7901 		 *    might create good inbound load spreading.
7902 		 *    ipif_select_source does this for us.
7903 		 *
7904 		 * If the application specified the ill (ifindex), we still
7905 		 * load spread. Only if the packets needs to go out
7906 		 * specifically on a given ill e.g. binding to
7907 		 * IPIF_NOFAILOVER address, then we don't try to use a
7908 		 * different ill for load spreading.
7909 		 */
7910 		if (attach_ill == NULL) {
7911 			/*
7912 			 * Don't perform outbound load spreading in the
7913 			 * case of an RTF_MULTIRT route, as we actually
7914 			 * typically want to replicate outgoing packets
7915 			 * through particular interfaces.
7916 			 */
7917 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7918 				dst_ill = ire->ire_ipif->ipif_ill;
7919 				/* for uniformity */
7920 				ill_refhold(dst_ill);
7921 			} else {
7922 				/*
7923 				 * If we are here trying to create an IRE_CACHE
7924 				 * for an offlink destination and have the
7925 				 * IRE_CACHE for the next hop and the latter is
7926 				 * using virtual IP source address selection i.e
7927 				 * it's ire->ire_ipif is pointing to a virtual
7928 				 * network interface (vni) then
7929 				 * ip_newroute_get_dst_ll() will return the vni
7930 				 * interface as the dst_ill. Since the vni is
7931 				 * virtual i.e not associated with any physical
7932 				 * interface, it cannot be the dst_ill, hence
7933 				 * in such a case call ip_newroute_get_dst_ll()
7934 				 * with the stq_ill instead of the ire_ipif ILL.
7935 				 * The function returns a refheld ill.
7936 				 */
7937 				if ((ire->ire_type == IRE_CACHE) &&
7938 				    IS_VNI(ire->ire_ipif->ipif_ill))
7939 					dst_ill = ip_newroute_get_dst_ill(
7940 						ire->ire_stq->q_ptr);
7941 				else
7942 					dst_ill = ip_newroute_get_dst_ill(
7943 						ire->ire_ipif->ipif_ill);
7944 			}
7945 			if (dst_ill == NULL) {
7946 				if (ip_debug > 2) {
7947 					pr_addr_dbg("ip_newroute: "
7948 					    "no dst ill for dst"
7949 					    " %s\n", AF_INET, &dst);
7950 				}
7951 				goto icmp_err_ret;
7952 			}
7953 		} else {
7954 			dst_ill = ire->ire_ipif->ipif_ill;
7955 			/* for uniformity */
7956 			ill_refhold(dst_ill);
7957 			/*
7958 			 * We should have found a route matching ill as we
7959 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7960 			 * Rather than asserting, when there is a mismatch,
7961 			 * we just drop the packet.
7962 			 */
7963 			if (dst_ill != attach_ill) {
7964 				ip0dbg(("ip_newroute: Packet dropped as "
7965 				    "IPIF_NOFAILOVER ill is %s, "
7966 				    "ire->ire_ipif->ipif_ill is %s\n",
7967 				    attach_ill->ill_name,
7968 				    dst_ill->ill_name));
7969 				ill_refrele(attach_ill);
7970 				goto icmp_err_ret;
7971 			}
7972 		}
7973 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7974 		if (attach_ill != NULL) {
7975 			ill_refrele(attach_ill);
7976 			attach_ill = NULL;
7977 			do_attach_ill = B_TRUE;
7978 		}
7979 		ASSERT(dst_ill != NULL);
7980 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7981 
7982 		/*
7983 		 * Pick the best source address from dst_ill.
7984 		 *
7985 		 * 1) If it is part of a multipathing group, we would
7986 		 *    like to spread the inbound packets across different
7987 		 *    interfaces. ipif_select_source picks a random source
7988 		 *    across the different ills in the group.
7989 		 *
7990 		 * 2) If it is not part of a multipathing group, we try
7991 		 *    to pick the source address from the destination
7992 		 *    route. Clustering assumes that when we have multiple
7993 		 *    prefixes hosted on an interface, the prefix of the
7994 		 *    source address matches the prefix of the destination
7995 		 *    route. We do this only if the address is not
7996 		 *    DEPRECATED.
7997 		 *
7998 		 * 3) If the conn is in a different zone than the ire, we
7999 		 *    need to pick a source address from the right zone.
8000 		 *
8001 		 * NOTE : If we hit case (1) above, the prefix of the source
8002 		 *	  address picked may not match the prefix of the
8003 		 *	  destination routes prefix as ipif_select_source
8004 		 *	  does not look at "dst" while picking a source
8005 		 *	  address.
8006 		 *	  If we want the same behavior as (2), we will need
8007 		 *	  to change the behavior of ipif_select_source.
8008 		 */
8009 		ASSERT(src_ipif == NULL);
8010 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8011 			/*
8012 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8013 			 * Check that the ipif matching the requested source
8014 			 * address still exists.
8015 			 */
8016 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8017 			    zoneid, NULL, NULL, NULL, NULL);
8018 		}
8019 		if (src_ipif == NULL) {
8020 			ire_marks |= IRE_MARK_USESRC_CHECK;
8021 			if ((dst_ill->ill_group != NULL) ||
8022 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8023 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8024 			    ire->ire_zoneid != ALL_ZONES) ||
8025 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8026 				/*
8027 				 * If the destination is reachable via a
8028 				 * given gateway, the selected source address
8029 				 * should be in the same subnet as the gateway.
8030 				 * Otherwise, the destination is not reachable.
8031 				 *
8032 				 * If there are no interfaces on the same subnet
8033 				 * as the destination, ipif_select_source gives
8034 				 * first non-deprecated interface which might be
8035 				 * on a different subnet than the gateway.
8036 				 * This is not desirable. Hence pass the dst_ire
8037 				 * source address to ipif_select_source.
8038 				 * It is sure that the destination is reachable
8039 				 * with the dst_ire source address subnet.
8040 				 * So passing dst_ire source address to
8041 				 * ipif_select_source will make sure that the
8042 				 * selected source will be on the same subnet
8043 				 * as dst_ire source address.
8044 				 */
8045 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8046 				src_ipif = ipif_select_source(dst_ill, saddr,
8047 				    zoneid);
8048 				if (src_ipif == NULL) {
8049 					if (ip_debug > 2) {
8050 						pr_addr_dbg("ip_newroute: "
8051 						    "no src for dst %s ",
8052 						    AF_INET, &dst);
8053 						printf("through interface %s\n",
8054 						    dst_ill->ill_name);
8055 					}
8056 					goto icmp_err_ret;
8057 				}
8058 			} else {
8059 				src_ipif = ire->ire_ipif;
8060 				ASSERT(src_ipif != NULL);
8061 				/* hold src_ipif for uniformity */
8062 				ipif_refhold(src_ipif);
8063 			}
8064 		}
8065 
8066 		/*
8067 		 * Assign a source address while we have the conn.
8068 		 * We can't have ip_wput_ire pick a source address when the
8069 		 * packet returns from arp since we need to look at
8070 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8071 		 * going through arp.
8072 		 *
8073 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8074 		 *	  it uses ip6i to store this information.
8075 		 */
8076 		if (ipha->ipha_src == INADDR_ANY &&
8077 		    (connp == NULL || !connp->conn_unspec_src)) {
8078 			ipha->ipha_src = src_ipif->ipif_src_addr;
8079 		}
8080 		if (ip_debug > 3) {
8081 			/* ip2dbg */
8082 			pr_addr_dbg("ip_newroute: first hop %s\n",
8083 			    AF_INET, &gw);
8084 		}
8085 		ip2dbg(("\tire type %s (%d)\n",
8086 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8087 
8088 		/*
8089 		 * The TTL of multirouted packets is bounded by the
8090 		 * ip_multirt_ttl ndd variable.
8091 		 */
8092 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8093 			/* Force TTL of multirouted packets */
8094 			if ((ip_multirt_ttl > 0) &&
8095 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
8096 				ip2dbg(("ip_newroute: forcing multirt TTL "
8097 				    "to %d (was %d), dst 0x%08x\n",
8098 				    ip_multirt_ttl, ipha->ipha_ttl,
8099 				    ntohl(sire->ire_addr)));
8100 				ipha->ipha_ttl = ip_multirt_ttl;
8101 			}
8102 		}
8103 		/*
8104 		 * At this point in ip_newroute(), ire is either the
8105 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8106 		 * destination or an IRE_INTERFACE type that should be used
8107 		 * to resolve an on-subnet destination or an on-subnet
8108 		 * next-hop gateway.
8109 		 *
8110 		 * In the IRE_CACHE case, we have the following :
8111 		 *
8112 		 * 1) src_ipif - used for getting a source address.
8113 		 *
8114 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8115 		 *    means packets using this IRE_CACHE will go out on
8116 		 *    dst_ill.
8117 		 *
8118 		 * 3) The IRE sire will point to the prefix that is the
8119 		 *    longest  matching route for the destination. These
8120 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8121 		 *
8122 		 *    The newly created IRE_CACHE entry for the off-subnet
8123 		 *    destination is tied to both the prefix route and the
8124 		 *    interface route used to resolve the next-hop gateway
8125 		 *    via the ire_phandle and ire_ihandle fields,
8126 		 *    respectively.
8127 		 *
8128 		 * In the IRE_INTERFACE case, we have the following :
8129 		 *
8130 		 * 1) src_ipif - used for getting a source address.
8131 		 *
8132 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8133 		 *    means packets using the IRE_CACHE that we will build
8134 		 *    here will go out on dst_ill.
8135 		 *
8136 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8137 		 *    to be created will only be tied to the IRE_INTERFACE
8138 		 *    that was derived from the ire_ihandle field.
8139 		 *
8140 		 *    If sire is non-NULL, it means the destination is
8141 		 *    off-link and we will first create the IRE_CACHE for the
8142 		 *    gateway. Next time through ip_newroute, we will create
8143 		 *    the IRE_CACHE for the final destination as described
8144 		 *    above.
8145 		 *
8146 		 * In both cases, after the current resolution has been
8147 		 * completed (or possibly initialised, in the IRE_INTERFACE
8148 		 * case), the loop may be re-entered to attempt the resolution
8149 		 * of another RTF_MULTIRT route.
8150 		 *
8151 		 * When an IRE_CACHE entry for the off-subnet destination is
8152 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8153 		 * for further processing in emission loops.
8154 		 */
8155 		save_ire = ire;
8156 		switch (ire->ire_type) {
8157 		case IRE_CACHE: {
8158 			ire_t	*ipif_ire;
8159 			mblk_t	*ire_fp_mp;
8160 
8161 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8162 			if (gw == 0)
8163 				gw = ire->ire_gateway_addr;
8164 			/*
8165 			 * We need 3 ire's to create a new cache ire for an
8166 			 * off-link destination from the cache ire of the
8167 			 * gateway.
8168 			 *
8169 			 *	1. The prefix ire 'sire' (Note that this does
8170 			 *	   not apply to the conn_nexthop_set case)
8171 			 *	2. The cache ire of the gateway 'ire'
8172 			 *	3. The interface ire 'ipif_ire'
8173 			 *
8174 			 * We have (1) and (2). We lookup (3) below.
8175 			 *
8176 			 * If there is no interface route to the gateway,
8177 			 * it is a race condition, where we found the cache
8178 			 * but the interface route has been deleted.
8179 			 */
8180 			if (ip_nexthop) {
8181 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8182 			} else {
8183 				ipif_ire =
8184 				    ire_ihandle_lookup_offlink(ire, sire);
8185 			}
8186 			if (ipif_ire == NULL) {
8187 				ip1dbg(("ip_newroute: "
8188 				    "ire_ihandle_lookup_offlink failed\n"));
8189 				goto icmp_err_ret;
8190 			}
8191 			/*
8192 			 * XXX We are using the same res_mp
8193 			 * (DL_UNITDATA_REQ) though the save_ire is not
8194 			 * pointing at the same ill.
8195 			 * This is incorrect. We need to send it up to the
8196 			 * resolver to get the right res_mp. For ethernets
8197 			 * this may be okay (ill_type == DL_ETHER).
8198 			 */
8199 			res_mp = save_ire->ire_nce->nce_res_mp;
8200 			ire_fp_mp = NULL;
8201 			/*
8202 			 * save_ire's nce_fp_mp can't change since it is
8203 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8204 			 * LOCK_IRE_FP_MP does not do any useful work in
8205 			 * the case of IRE_CACHE. So we don't use it below.
8206 			 */
8207 			if (save_ire->ire_stq == dst_ill->ill_wq)
8208 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8209 
8210 			/*
8211 			 * Check cached gateway IRE for any security
8212 			 * attributes; if found, associate the gateway
8213 			 * credentials group to the destination IRE.
8214 			 */
8215 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8216 				mutex_enter(&attrp->igsa_lock);
8217 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8218 					GCGRP_REFHOLD(gcgrp);
8219 				mutex_exit(&attrp->igsa_lock);
8220 			}
8221 
8222 			ire = ire_create(
8223 			    (uchar_t *)&dst,		/* dest address */
8224 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8225 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8226 			    (uchar_t *)&gw,		/* gateway address */
8227 			    NULL,
8228 			    &save_ire->ire_max_frag,
8229 			    ire_fp_mp,			/* Fast Path header */
8230 			    dst_ill->ill_rq,		/* recv-from queue */
8231 			    dst_ill->ill_wq,		/* send-to queue */
8232 			    IRE_CACHE,			/* IRE type */
8233 			    res_mp,
8234 			    src_ipif,
8235 			    in_ill,			/* incoming ill */
8236 			    (sire != NULL) ?
8237 				sire->ire_mask : 0, 	/* Parent mask */
8238 			    (sire != NULL) ?
8239 				sire->ire_phandle : 0,  /* Parent handle */
8240 			    ipif_ire->ire_ihandle,	/* Interface handle */
8241 			    (sire != NULL) ? (sire->ire_flags &
8242 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8243 			    (sire != NULL) ?
8244 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8245 			    NULL,
8246 			    gcgrp);
8247 
8248 			if (ire == NULL) {
8249 				if (gcgrp != NULL) {
8250 					GCGRP_REFRELE(gcgrp);
8251 					gcgrp = NULL;
8252 				}
8253 				ire_refrele(ipif_ire);
8254 				ire_refrele(save_ire);
8255 				break;
8256 			}
8257 
8258 			/* reference now held by IRE */
8259 			gcgrp = NULL;
8260 
8261 			ire->ire_marks |= ire_marks;
8262 
8263 			/*
8264 			 * Prevent sire and ipif_ire from getting deleted.
8265 			 * The newly created ire is tied to both of them via
8266 			 * the phandle and ihandle respectively.
8267 			 */
8268 			if (sire != NULL) {
8269 				IRB_REFHOLD(sire->ire_bucket);
8270 				/* Has it been removed already ? */
8271 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8272 					IRB_REFRELE(sire->ire_bucket);
8273 					ire_refrele(ipif_ire);
8274 					ire_refrele(save_ire);
8275 					break;
8276 				}
8277 			}
8278 
8279 			IRB_REFHOLD(ipif_ire->ire_bucket);
8280 			/* Has it been removed already ? */
8281 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8282 				IRB_REFRELE(ipif_ire->ire_bucket);
8283 				if (sire != NULL)
8284 					IRB_REFRELE(sire->ire_bucket);
8285 				ire_refrele(ipif_ire);
8286 				ire_refrele(save_ire);
8287 				break;
8288 			}
8289 
8290 			xmit_mp = first_mp;
8291 			/*
8292 			 * In the case of multirouting, a copy
8293 			 * of the packet is done before its sending.
8294 			 * The copy is used to attempt another
8295 			 * route resolution, in a next loop.
8296 			 */
8297 			if (ire->ire_flags & RTF_MULTIRT) {
8298 				copy_mp = copymsg(first_mp);
8299 				if (copy_mp != NULL) {
8300 					xmit_mp = copy_mp;
8301 					MULTIRT_DEBUG_TAG(first_mp);
8302 				}
8303 			}
8304 			ire_add_then_send(q, ire, xmit_mp);
8305 			ire_refrele(save_ire);
8306 
8307 			/* Assert that sire is not deleted yet. */
8308 			if (sire != NULL) {
8309 				ASSERT(sire->ire_ptpn != NULL);
8310 				IRB_REFRELE(sire->ire_bucket);
8311 			}
8312 
8313 			/* Assert that ipif_ire is not deleted yet. */
8314 			ASSERT(ipif_ire->ire_ptpn != NULL);
8315 			IRB_REFRELE(ipif_ire->ire_bucket);
8316 			ire_refrele(ipif_ire);
8317 
8318 			/*
8319 			 * If copy_mp is not NULL, multirouting was
8320 			 * requested. We loop to initiate a next
8321 			 * route resolution attempt, starting from sire.
8322 			 */
8323 			if (copy_mp != NULL) {
8324 				/*
8325 				 * Search for the next unresolved
8326 				 * multirt route.
8327 				 */
8328 				copy_mp = NULL;
8329 				ipif_ire = NULL;
8330 				ire = NULL;
8331 				multirt_resolve_next = B_TRUE;
8332 				continue;
8333 			}
8334 			if (sire != NULL)
8335 				ire_refrele(sire);
8336 			ipif_refrele(src_ipif);
8337 			ill_refrele(dst_ill);
8338 			return;
8339 		}
8340 		case IRE_IF_NORESOLVER: {
8341 			/*
8342 			 * We have what we need to build an IRE_CACHE.
8343 			 *
8344 			 * Create a new res_mp with the IP gateway address
8345 			 * in destination address in the DLPI hdr if the
8346 			 * physical length is exactly 4 bytes.
8347 			 */
8348 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8349 				uchar_t *addr;
8350 
8351 				if (gw)
8352 					addr = (uchar_t *)&gw;
8353 				else
8354 					addr = (uchar_t *)&dst;
8355 
8356 				res_mp = ill_dlur_gen(addr,
8357 				    dst_ill->ill_phys_addr_length,
8358 				    dst_ill->ill_sap,
8359 				    dst_ill->ill_sap_length);
8360 
8361 				if (res_mp == NULL) {
8362 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8363 					break;
8364 				}
8365 			} else {
8366 				res_mp = NULL;
8367 			}
8368 
8369 			/*
8370 			 * TSol note: We are creating the ire cache for the
8371 			 * destination 'dst'. If 'dst' is offlink, going
8372 			 * through the first hop 'gw', the security attributes
8373 			 * of 'dst' must be set to point to the gateway
8374 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8375 			 * is possible that 'dst' is a potential gateway that is
8376 			 * referenced by some route that has some security
8377 			 * attributes. Thus in the former case, we need to do a
8378 			 * gcgrp_lookup of 'gw' while in the latter case we
8379 			 * need to do gcgrp_lookup of 'dst' itself.
8380 			 */
8381 			ga.ga_af = AF_INET;
8382 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8383 			    &ga.ga_addr);
8384 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8385 
8386 			ire = ire_create(
8387 			    (uchar_t *)&dst,		/* dest address */
8388 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8389 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8390 			    (uchar_t *)&gw,		/* gateway address */
8391 			    NULL,
8392 			    &save_ire->ire_max_frag,
8393 			    NULL,			/* Fast Path header */
8394 			    dst_ill->ill_rq,		/* recv-from queue */
8395 			    dst_ill->ill_wq,		/* send-to queue */
8396 			    IRE_CACHE,
8397 			    res_mp,
8398 			    src_ipif,
8399 			    in_ill,			/* Incoming ill */
8400 			    save_ire->ire_mask,		/* Parent mask */
8401 			    (sire != NULL) ?		/* Parent handle */
8402 				sire->ire_phandle : 0,
8403 			    save_ire->ire_ihandle,	/* Interface handle */
8404 			    (sire != NULL) ? sire->ire_flags &
8405 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8406 			    &(save_ire->ire_uinfo),
8407 			    NULL,
8408 			    gcgrp);
8409 
8410 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8411 				freeb(res_mp);
8412 
8413 			if (ire == NULL) {
8414 				if (gcgrp != NULL) {
8415 					GCGRP_REFRELE(gcgrp);
8416 					gcgrp = NULL;
8417 				}
8418 				ire_refrele(save_ire);
8419 				break;
8420 			}
8421 
8422 			/* reference now held by IRE */
8423 			gcgrp = NULL;
8424 
8425 			ire->ire_marks |= ire_marks;
8426 
8427 			/* Prevent save_ire from getting deleted */
8428 			IRB_REFHOLD(save_ire->ire_bucket);
8429 			/* Has it been removed already ? */
8430 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8431 				IRB_REFRELE(save_ire->ire_bucket);
8432 				ire_refrele(save_ire);
8433 				break;
8434 			}
8435 
8436 			/*
8437 			 * In the case of multirouting, a copy
8438 			 * of the packet is made before it is sent.
8439 			 * The copy is used in the next
8440 			 * loop to attempt another resolution.
8441 			 */
8442 			xmit_mp = first_mp;
8443 			if ((sire != NULL) &&
8444 			    (sire->ire_flags & RTF_MULTIRT)) {
8445 				copy_mp = copymsg(first_mp);
8446 				if (copy_mp != NULL) {
8447 					xmit_mp = copy_mp;
8448 					MULTIRT_DEBUG_TAG(first_mp);
8449 				}
8450 			}
8451 			ire_add_then_send(q, ire, xmit_mp);
8452 
8453 			/* Assert that it is not deleted yet. */
8454 			ASSERT(save_ire->ire_ptpn != NULL);
8455 			IRB_REFRELE(save_ire->ire_bucket);
8456 			ire_refrele(save_ire);
8457 
8458 			if (copy_mp != NULL) {
8459 				/*
8460 				 * If we found a (no)resolver, we ignore any
8461 				 * trailing top priority IRE_CACHE in further
8462 				 * loops. This ensures that we do not omit any
8463 				 * (no)resolver.
8464 				 * This IRE_CACHE, if any, will be processed
8465 				 * by another thread entering ip_newroute().
8466 				 * IRE_CACHE entries, if any, will be processed
8467 				 * by another thread entering ip_newroute(),
8468 				 * (upon resolver response, for instance).
8469 				 * This aims to force parallel multirt
8470 				 * resolutions as soon as a packet must be sent.
8471 				 * In the best case, after the tx of only one
8472 				 * packet, all reachable routes are resolved.
8473 				 * Otherwise, the resolution of all RTF_MULTIRT
8474 				 * routes would require several emissions.
8475 				 */
8476 				multirt_flags &= ~MULTIRT_CACHEGW;
8477 
8478 				/*
8479 				 * Search for the next unresolved multirt
8480 				 * route.
8481 				 */
8482 				copy_mp = NULL;
8483 				save_ire = NULL;
8484 				ire = NULL;
8485 				multirt_resolve_next = B_TRUE;
8486 				continue;
8487 			}
8488 
8489 			/*
8490 			 * Don't need sire anymore
8491 			 */
8492 			if (sire != NULL)
8493 				ire_refrele(sire);
8494 
8495 			ipif_refrele(src_ipif);
8496 			ill_refrele(dst_ill);
8497 			return;
8498 		}
8499 		case IRE_IF_RESOLVER:
8500 			/*
8501 			 * We can't build an IRE_CACHE yet, but at least we
8502 			 * found a resolver that can help.
8503 			 */
8504 			res_mp = dst_ill->ill_resolver_mp;
8505 			if (!OK_RESOLVER_MP(res_mp))
8506 				break;
8507 
8508 			/*
8509 			 * To be at this point in the code with a non-zero gw
8510 			 * means that dst is reachable through a gateway that
8511 			 * we have never resolved.  By changing dst to the gw
8512 			 * addr we resolve the gateway first.
8513 			 * When ire_add_then_send() tries to put the IP dg
8514 			 * to dst, it will reenter ip_newroute() at which
8515 			 * time we will find the IRE_CACHE for the gw and
8516 			 * create another IRE_CACHE in case IRE_CACHE above.
8517 			 */
8518 			if (gw != INADDR_ANY) {
8519 				/*
8520 				 * The source ipif that was determined above was
8521 				 * relative to the destination address, not the
8522 				 * gateway's. If src_ipif was not taken out of
8523 				 * the IRE_IF_RESOLVER entry, we'll need to call
8524 				 * ipif_select_source() again.
8525 				 */
8526 				if (src_ipif != ire->ire_ipif) {
8527 					ipif_refrele(src_ipif);
8528 					src_ipif = ipif_select_source(dst_ill,
8529 					    gw, zoneid);
8530 					if (src_ipif == NULL) {
8531 						if (ip_debug > 2) {
8532 							pr_addr_dbg(
8533 							    "ip_newroute: no "
8534 							    "src for gw %s ",
8535 							    AF_INET, &gw);
8536 							printf("through "
8537 							    "interface %s\n",
8538 							    dst_ill->ill_name);
8539 						}
8540 						goto icmp_err_ret;
8541 					}
8542 				}
8543 				save_dst = dst;
8544 				dst = gw;
8545 				gw = INADDR_ANY;
8546 			}
8547 
8548 			/*
8549 			 * We obtain a partial IRE_CACHE which we will pass
8550 			 * along with the resolver query.  When the response
8551 			 * comes back it will be there ready for us to add.
8552 			 * The ire_max_frag is atomically set under the
8553 			 * irebucket lock in ire_add_v[46].
8554 			 */
8555 
8556 			ire = ire_create_mp(
8557 			    (uchar_t *)&dst,		/* dest address */
8558 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8559 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8560 			    (uchar_t *)&gw,		/* gateway address */
8561 			    NULL,			/* no in_src_addr */
8562 			    NULL,			/* ire_max_frag */
8563 			    NULL,			/* Fast Path header */
8564 			    dst_ill->ill_rq,		/* recv-from queue */
8565 			    dst_ill->ill_wq,		/* send-to queue */
8566 			    IRE_CACHE,
8567 			    NULL,
8568 			    src_ipif,			/* Interface ipif */
8569 			    in_ill,			/* Incoming ILL */
8570 			    save_ire->ire_mask,		/* Parent mask */
8571 			    0,
8572 			    save_ire->ire_ihandle,	/* Interface handle */
8573 			    0,				/* flags if any */
8574 			    &(save_ire->ire_uinfo),
8575 			    NULL,
8576 			    NULL);
8577 
8578 			if (ire == NULL) {
8579 				ire_refrele(save_ire);
8580 				break;
8581 			}
8582 
8583 			if ((sire != NULL) &&
8584 			    (sire->ire_flags & RTF_MULTIRT)) {
8585 				copy_mp = copymsg(first_mp);
8586 				if (copy_mp != NULL)
8587 					MULTIRT_DEBUG_TAG(copy_mp);
8588 			}
8589 
8590 			ire->ire_marks |= ire_marks;
8591 
8592 			/*
8593 			 * Construct message chain for the resolver
8594 			 * of the form:
8595 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8596 			 * Packet could contain a IPSEC_OUT mp.
8597 			 *
8598 			 * NOTE : ire will be added later when the response
8599 			 * comes back from ARP. If the response does not
8600 			 * come back, ARP frees the packet. For this reason,
8601 			 * we can't REFHOLD the bucket of save_ire to prevent
8602 			 * deletions. We may not be able to REFRELE the bucket
8603 			 * if the response never comes back. Thus, before
8604 			 * adding the ire, ire_add_v4 will make sure that the
8605 			 * interface route does not get deleted. This is the
8606 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8607 			 * where we can always prevent deletions because of
8608 			 * the synchronous nature of adding IRES i.e
8609 			 * ire_add_then_send is called after creating the IRE.
8610 			 */
8611 			ASSERT(ire->ire_mp != NULL);
8612 			ire->ire_mp->b_cont = first_mp;
8613 			/* Have saved_mp handy, for cleanup if canput fails */
8614 			saved_mp = mp;
8615 			mp = copyb(res_mp);
8616 			if (mp == NULL) {
8617 				/* Prepare for cleanup */
8618 				mp = saved_mp; /* pkt */
8619 				ire_delete(ire); /* ire_mp */
8620 				ire = NULL;
8621 				ire_refrele(save_ire);
8622 				if (copy_mp != NULL) {
8623 					MULTIRT_DEBUG_UNTAG(copy_mp);
8624 					freemsg(copy_mp);
8625 					copy_mp = NULL;
8626 				}
8627 				break;
8628 			}
8629 			linkb(mp, ire->ire_mp);
8630 
8631 			/*
8632 			 * Fill in the source and dest addrs for the resolver.
8633 			 * NOTE: this depends on memory layouts imposed by
8634 			 * ill_init().
8635 			 */
8636 			areq = (areq_t *)mp->b_rptr;
8637 			addrp = (ipaddr_t *)((char *)areq +
8638 			    areq->areq_sender_addr_offset);
8639 			if (do_attach_ill) {
8640 				/*
8641 				 * This is bind to no failover case.
8642 				 * arp packet also must go out on attach_ill.
8643 				 */
8644 				ASSERT(ipha->ipha_src != NULL);
8645 				*addrp = ipha->ipha_src;
8646 			} else {
8647 				*addrp = save_ire->ire_src_addr;
8648 			}
8649 
8650 			ire_refrele(save_ire);
8651 			addrp = (ipaddr_t *)((char *)areq +
8652 			    areq->areq_target_addr_offset);
8653 			*addrp = dst;
8654 			/* Up to the resolver. */
8655 			if (canputnext(dst_ill->ill_rq) &&
8656 			    !(dst_ill->ill_arp_closing)) {
8657 				putnext(dst_ill->ill_rq, mp);
8658 				ire = NULL;
8659 				if (copy_mp != NULL) {
8660 					/*
8661 					 * If we found a resolver, we ignore
8662 					 * any trailing top priority IRE_CACHE
8663 					 * in the further loops. This ensures
8664 					 * that we do not omit any resolver.
8665 					 * IRE_CACHE entries, if any, will be
8666 					 * processed next time we enter
8667 					 * ip_newroute().
8668 					 */
8669 					multirt_flags &= ~MULTIRT_CACHEGW;
8670 					/*
8671 					 * Search for the next unresolved
8672 					 * multirt route.
8673 					 */
8674 					first_mp = copy_mp;
8675 					copy_mp = NULL;
8676 					/* Prepare the next resolution loop. */
8677 					mp = first_mp;
8678 					EXTRACT_PKT_MP(mp, first_mp,
8679 					    mctl_present);
8680 					if (mctl_present)
8681 						io = (ipsec_out_t *)
8682 						    first_mp->b_rptr;
8683 					ipha = (ipha_t *)mp->b_rptr;
8684 
8685 					ASSERT(sire != NULL);
8686 
8687 					dst = save_dst;
8688 					multirt_resolve_next = B_TRUE;
8689 					continue;
8690 				}
8691 
8692 				if (sire != NULL)
8693 					ire_refrele(sire);
8694 
8695 				/*
8696 				 * The response will come back in ip_wput
8697 				 * with db_type IRE_DB_TYPE.
8698 				 */
8699 				ipif_refrele(src_ipif);
8700 				ill_refrele(dst_ill);
8701 				return;
8702 			} else {
8703 				/* Prepare for cleanup */
8704 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8705 				    mp);
8706 				mp->b_cont = NULL;
8707 				freeb(mp); /* areq */
8708 				/*
8709 				 * this is an ire that is not added to the
8710 				 * cache. ire_freemblk will handle the release
8711 				 * of any resources associated with the ire.
8712 				 */
8713 				ire_delete(ire); /* ire_mp */
8714 				mp = saved_mp; /* pkt */
8715 				ire = NULL;
8716 				if (copy_mp != NULL) {
8717 					MULTIRT_DEBUG_UNTAG(copy_mp);
8718 					freemsg(copy_mp);
8719 					copy_mp = NULL;
8720 				}
8721 				break;
8722 			}
8723 		default:
8724 			break;
8725 		}
8726 	} while (multirt_resolve_next);
8727 
8728 	ip1dbg(("ip_newroute: dropped\n"));
8729 	/* Did this packet originate externally? */
8730 	if (mp->b_prev) {
8731 		mp->b_next = NULL;
8732 		mp->b_prev = NULL;
8733 		BUMP_MIB(&ip_mib, ipInDiscards);
8734 	} else {
8735 		BUMP_MIB(&ip_mib, ipOutDiscards);
8736 	}
8737 	ASSERT(copy_mp == NULL);
8738 	MULTIRT_DEBUG_UNTAG(first_mp);
8739 	freemsg(first_mp);
8740 	if (ire != NULL)
8741 		ire_refrele(ire);
8742 	if (sire != NULL)
8743 		ire_refrele(sire);
8744 	if (src_ipif != NULL)
8745 		ipif_refrele(src_ipif);
8746 	if (dst_ill != NULL)
8747 		ill_refrele(dst_ill);
8748 	return;
8749 
8750 icmp_err_ret:
8751 	ip1dbg(("ip_newroute: no route\n"));
8752 	if (src_ipif != NULL)
8753 		ipif_refrele(src_ipif);
8754 	if (dst_ill != NULL)
8755 		ill_refrele(dst_ill);
8756 	if (sire != NULL)
8757 		ire_refrele(sire);
8758 	/* Did this packet originate externally? */
8759 	if (mp->b_prev) {
8760 		mp->b_next = NULL;
8761 		mp->b_prev = NULL;
8762 		/* XXX ipInNoRoutes */
8763 		q = WR(q);
8764 	} else {
8765 		/*
8766 		 * Since ip_wput() isn't close to finished, we fill
8767 		 * in enough of the header for credible error reporting.
8768 		 */
8769 		if (ip_hdr_complete(ipha, zoneid)) {
8770 			/* Failed */
8771 			MULTIRT_DEBUG_UNTAG(first_mp);
8772 			freemsg(first_mp);
8773 			if (ire != NULL)
8774 				ire_refrele(ire);
8775 			return;
8776 		}
8777 	}
8778 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8779 
8780 	/*
8781 	 * At this point we will have ire only if RTF_BLACKHOLE
8782 	 * or RTF_REJECT flags are set on the IRE. It will not
8783 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8784 	 */
8785 	if (ire != NULL) {
8786 		if (ire->ire_flags & RTF_BLACKHOLE) {
8787 			ire_refrele(ire);
8788 			MULTIRT_DEBUG_UNTAG(first_mp);
8789 			freemsg(first_mp);
8790 			return;
8791 		}
8792 		ire_refrele(ire);
8793 	}
8794 	if (ip_source_routed(ipha)) {
8795 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8796 		    zoneid);
8797 		return;
8798 	}
8799 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
8800 }
8801 
8802 /*
8803  * IPv4 -
8804  * ip_newroute_ipif is called by ip_wput_multicast and
8805  * ip_rput_forward_multicast whenever we need to send
8806  * out a packet to a destination address for which we do not have specific
8807  * routing information. It is used when the packet will be sent out
8808  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8809  * socket option is set or icmp error message wants to go out on a particular
8810  * interface for a unicast packet.
8811  *
8812  * In most cases, the destination address is resolved thanks to the ipif
8813  * intrinsic resolver. However, there are some cases where the call to
8814  * ip_newroute_ipif must take into account the potential presence of
8815  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8816  * that uses the interface. This is specified through flags,
8817  * which can be a combination of:
8818  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8819  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8820  *   and flags. Additionally, the packet source address has to be set to
8821  *   the specified address. The caller is thus expected to set this flag
8822  *   if the packet has no specific source address yet.
8823  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8824  *   flag, the resulting ire will inherit the flag. All unresolved routes
8825  *   to the destination must be explored in the same call to
8826  *   ip_newroute_ipif().
8827  */
8828 static void
8829 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8830     conn_t *connp, uint32_t flags, zoneid_t zoneid)
8831 {
8832 	areq_t	*areq;
8833 	ire_t	*ire = NULL;
8834 	mblk_t	*res_mp;
8835 	ipaddr_t *addrp;
8836 	mblk_t *first_mp;
8837 	ire_t	*save_ire = NULL;
8838 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8839 	ipif_t	*src_ipif = NULL;
8840 	ushort_t ire_marks = 0;
8841 	ill_t	*dst_ill = NULL;
8842 	boolean_t mctl_present;
8843 	ipsec_out_t *io;
8844 	ipha_t *ipha;
8845 	int	ihandle = 0;
8846 	mblk_t	*saved_mp;
8847 	ire_t   *fire = NULL;
8848 	mblk_t  *copy_mp = NULL;
8849 	boolean_t multirt_resolve_next;
8850 	ipaddr_t ipha_dst;
8851 
8852 	/*
8853 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8854 	 * here for uniformity
8855 	 */
8856 	ipif_refhold(ipif);
8857 
8858 	/*
8859 	 * This loop is run only once in most cases.
8860 	 * We loop to resolve further routes only when the destination
8861 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8862 	 */
8863 	do {
8864 		if (dst_ill != NULL) {
8865 			ill_refrele(dst_ill);
8866 			dst_ill = NULL;
8867 		}
8868 		if (src_ipif != NULL) {
8869 			ipif_refrele(src_ipif);
8870 			src_ipif = NULL;
8871 		}
8872 		multirt_resolve_next = B_FALSE;
8873 
8874 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8875 		    ipif->ipif_ill->ill_name));
8876 
8877 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8878 		if (mctl_present)
8879 			io = (ipsec_out_t *)first_mp->b_rptr;
8880 
8881 		ipha = (ipha_t *)mp->b_rptr;
8882 
8883 		/*
8884 		 * Save the packet destination address, we may need it after
8885 		 * the packet has been consumed.
8886 		 */
8887 		ipha_dst = ipha->ipha_dst;
8888 
8889 		/*
8890 		 * If the interface is a pt-pt interface we look for an
8891 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8892 		 * local_address and the pt-pt destination address. Otherwise
8893 		 * we just match the local address.
8894 		 * NOTE: dst could be different than ipha->ipha_dst in case
8895 		 * of sending igmp multicast packets over a point-to-point
8896 		 * connection.
8897 		 * Thus we must be careful enough to check ipha_dst to be a
8898 		 * multicast address, otherwise it will take xmit_if path for
8899 		 * multicast packets resulting into kernel stack overflow by
8900 		 * repeated calls to ip_newroute_ipif from ire_send().
8901 		 */
8902 		if (CLASSD(ipha_dst) &&
8903 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8904 			goto err_ret;
8905 		}
8906 
8907 		/*
8908 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8909 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8910 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8911 		 * propagate its flags to the new ire.
8912 		 */
8913 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8914 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8915 			ip2dbg(("ip_newroute_ipif: "
8916 			    "ipif_lookup_multi_ire("
8917 			    "ipif %p, dst %08x) = fire %p\n",
8918 			    (void *)ipif, ntohl(dst), (void *)fire));
8919 		}
8920 
8921 		if (mctl_present && io->ipsec_out_attach_if) {
8922 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8923 			    io->ipsec_out_ill_index, B_FALSE);
8924 
8925 			/* Failure case frees things for us. */
8926 			if (attach_ill == NULL) {
8927 				ipif_refrele(ipif);
8928 				if (fire != NULL)
8929 					ire_refrele(fire);
8930 				return;
8931 			}
8932 
8933 			/*
8934 			 * Check if we need an ire that will not be
8935 			 * looked up by anybody else i.e. HIDDEN.
8936 			 */
8937 			if (ill_is_probeonly(attach_ill)) {
8938 				ire_marks = IRE_MARK_HIDDEN;
8939 			}
8940 			/*
8941 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8942 			 * case.
8943 			 */
8944 			dst_ill = ipif->ipif_ill;
8945 			/* attach_ill has been refheld by ip_grab_attach_ill */
8946 			ASSERT(dst_ill == attach_ill);
8947 		} else {
8948 			/*
8949 			 * If this is set by IP_XMIT_IF, then make sure that
8950 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8951 			 * specified ill.
8952 			 */
8953 			ASSERT((connp == NULL) ||
8954 			    (connp->conn_xmit_if_ill == NULL) ||
8955 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8956 			/*
8957 			 * If the interface belongs to an interface group,
8958 			 * make sure the next possible interface in the group
8959 			 * is used.  This encourages load spreading among
8960 			 * peers in an interface group.
8961 			 * Note: load spreading is disabled for RTF_MULTIRT
8962 			 * routes.
8963 			 */
8964 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8965 			    (fire->ire_flags & RTF_MULTIRT)) {
8966 				/*
8967 				 * Don't perform outbound load spreading
8968 				 * in the case of an RTF_MULTIRT issued route,
8969 				 * we actually typically want to replicate
8970 				 * outgoing packets through particular
8971 				 * interfaces.
8972 				 */
8973 				dst_ill = ipif->ipif_ill;
8974 				ill_refhold(dst_ill);
8975 			} else {
8976 				dst_ill = ip_newroute_get_dst_ill(
8977 				    ipif->ipif_ill);
8978 			}
8979 			if (dst_ill == NULL) {
8980 				if (ip_debug > 2) {
8981 					pr_addr_dbg("ip_newroute_ipif: "
8982 					    "no dst ill for dst %s\n",
8983 					    AF_INET, &dst);
8984 				}
8985 				goto err_ret;
8986 			}
8987 		}
8988 
8989 		/*
8990 		 * Pick a source address preferring non-deprecated ones.
8991 		 * Unlike ip_newroute, we don't do any source address
8992 		 * selection here since for multicast it really does not help
8993 		 * in inbound load spreading as in the unicast case.
8994 		 */
8995 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8996 		    (fire->ire_flags & RTF_SETSRC)) {
8997 			/*
8998 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8999 			 * on that interface. This ire has RTF_SETSRC flag, so
9000 			 * the source address of the packet must be changed.
9001 			 * Check that the ipif matching the requested source
9002 			 * address still exists.
9003 			 */
9004 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9005 			    zoneid, NULL, NULL, NULL, NULL);
9006 		}
9007 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9008 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9009 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9010 		    (src_ipif == NULL)) {
9011 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9012 			if (src_ipif == NULL) {
9013 				if (ip_debug > 2) {
9014 					/* ip1dbg */
9015 					pr_addr_dbg("ip_newroute_ipif: "
9016 					    "no src for dst %s",
9017 					    AF_INET, &dst);
9018 				}
9019 				ip1dbg((" through interface %s\n",
9020 				    dst_ill->ill_name));
9021 				goto err_ret;
9022 			}
9023 			ipif_refrele(ipif);
9024 			ipif = src_ipif;
9025 			ipif_refhold(ipif);
9026 		}
9027 		if (src_ipif == NULL) {
9028 			src_ipif = ipif;
9029 			ipif_refhold(src_ipif);
9030 		}
9031 
9032 		/*
9033 		 * Assign a source address while we have the conn.
9034 		 * We can't have ip_wput_ire pick a source address when the
9035 		 * packet returns from arp since conn_unspec_src might be set
9036 		 * and we loose the conn when going through arp.
9037 		 */
9038 		if (ipha->ipha_src == INADDR_ANY &&
9039 		    (connp == NULL || !connp->conn_unspec_src)) {
9040 			ipha->ipha_src = src_ipif->ipif_src_addr;
9041 		}
9042 
9043 		/*
9044 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9045 		 * interface does not have an interface ire.
9046 		 * Example: Thousands of mobileip PPP interfaces to mobile
9047 		 * nodes. We don't want to create interface ires because
9048 		 * packets from other mobile nodes must not take the route
9049 		 * via interface ires to the visiting mobile node without
9050 		 * going through the home agent, in absence of mobileip
9051 		 * route optimization.
9052 		 */
9053 		if (CLASSD(ipha_dst) && (connp == NULL ||
9054 		    connp->conn_xmit_if_ill == NULL)) {
9055 			/* ipif_to_ire returns an held ire */
9056 			ire = ipif_to_ire(ipif);
9057 			if (ire == NULL)
9058 				goto err_ret;
9059 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9060 				goto err_ret;
9061 			/*
9062 			 * ihandle is needed when the ire is added to
9063 			 * cache table.
9064 			 */
9065 			save_ire = ire;
9066 			ihandle = save_ire->ire_ihandle;
9067 
9068 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9069 			    "flags %04x\n",
9070 			    (void *)ire, (void *)ipif, flags));
9071 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9072 			    (fire->ire_flags & RTF_MULTIRT)) {
9073 				/*
9074 				 * As requested by flags, an IRE_OFFSUBNET was
9075 				 * looked up on that interface. This ire has
9076 				 * RTF_MULTIRT flag, so the resolution loop will
9077 				 * be re-entered to resolve additional routes on
9078 				 * other interfaces. For that purpose, a copy of
9079 				 * the packet is performed at this point.
9080 				 */
9081 				fire->ire_last_used_time = lbolt;
9082 				copy_mp = copymsg(first_mp);
9083 				if (copy_mp) {
9084 					MULTIRT_DEBUG_TAG(copy_mp);
9085 				}
9086 			}
9087 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9088 			    (fire->ire_flags & RTF_SETSRC)) {
9089 				/*
9090 				 * As requested by flags, an IRE_OFFSUBET was
9091 				 * looked up on that interface. This ire has
9092 				 * RTF_SETSRC flag, so the source address of the
9093 				 * packet must be changed.
9094 				 */
9095 				ipha->ipha_src = fire->ire_src_addr;
9096 			}
9097 		} else {
9098 			ASSERT((connp == NULL) ||
9099 			    (connp->conn_xmit_if_ill != NULL) ||
9100 			    (connp->conn_dontroute));
9101 			/*
9102 			 * The only ways we can come here are:
9103 			 * 1) IP_XMIT_IF socket option is set
9104 			 * 2) ICMP error message generated from
9105 			 *    ip_mrtun_forward() routine and it needs
9106 			 *    to go through the specified ill.
9107 			 * 3) SO_DONTROUTE socket option is set
9108 			 * In all cases, the new ire will not be added
9109 			 * into cache table.
9110 			 */
9111 			ire_marks |= IRE_MARK_NOADD;
9112 		}
9113 
9114 		switch (ipif->ipif_net_type) {
9115 		case IRE_IF_NORESOLVER: {
9116 			/* We have what we need to build an IRE_CACHE. */
9117 			mblk_t	*res_mp;
9118 
9119 			/*
9120 			 * Create a new res_mp with the
9121 			 * IP gateway address as destination address in the
9122 			 * DLPI hdr if the physical length is exactly 4 bytes.
9123 			 */
9124 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9125 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9126 				    dst_ill->ill_phys_addr_length,
9127 				    dst_ill->ill_sap,
9128 				    dst_ill->ill_sap_length);
9129 			} else {
9130 				/* use the value set in ip_ll_subnet_defaults */
9131 				res_mp = ill_dlur_gen(NULL,
9132 				    dst_ill->ill_phys_addr_length,
9133 				    dst_ill->ill_sap,
9134 				    dst_ill->ill_sap_length);
9135 			}
9136 
9137 			if (res_mp == NULL)
9138 				break;
9139 			/*
9140 			 * The new ire inherits the IRE_OFFSUBNET flags
9141 			 * and source address, if this was requested.
9142 			 */
9143 			ire = ire_create(
9144 			    (uchar_t *)&dst,		/* dest address */
9145 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9146 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9147 			    NULL,			/* gateway address */
9148 			    NULL,
9149 			    &ipif->ipif_mtu,
9150 			    NULL,			/* Fast Path header */
9151 			    dst_ill->ill_rq,		/* recv-from queue */
9152 			    dst_ill->ill_wq,		/* send-to queue */
9153 			    IRE_CACHE,
9154 			    res_mp,
9155 			    src_ipif,
9156 			    NULL,
9157 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9158 			    (fire != NULL) ?		/* Parent handle */
9159 				fire->ire_phandle : 0,
9160 			    ihandle,			/* Interface handle */
9161 			    (fire != NULL) ?
9162 				(fire->ire_flags &
9163 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9164 			    (save_ire == NULL ? &ire_uinfo_null :
9165 				&save_ire->ire_uinfo),
9166 			    NULL,
9167 			    NULL);
9168 
9169 			freeb(res_mp);
9170 
9171 			if (ire == NULL) {
9172 				if (save_ire != NULL)
9173 					ire_refrele(save_ire);
9174 				break;
9175 			}
9176 
9177 			ire->ire_marks |= ire_marks;
9178 
9179 			/*
9180 			 * If IRE_MARK_NOADD is set then we need to convert
9181 			 * the max_fragp to a useable value now. This is
9182 			 * normally done in ire_add_v[46]. We also need to
9183 			 * associate the ire with an nce (normally would be
9184 			 * done in ip_wput_nondata()).
9185 			 *
9186 			 * Note that IRE_MARK_NOADD packets created here
9187 			 * do not have a non-null ire_mp pointer. The null
9188 			 * value of ire_bucket indicates that they were
9189 			 * never added.
9190 			 */
9191 			if (ire->ire_marks & IRE_MARK_NOADD) {
9192 				uint_t  max_frag;
9193 
9194 				max_frag = *ire->ire_max_fragp;
9195 				ire->ire_max_fragp = NULL;
9196 				ire->ire_max_frag = max_frag;
9197 
9198 				if ((ire->ire_nce = ndp_lookup_v4(
9199 				    ire_to_ill(ire),
9200 				    (ire->ire_gateway_addr != INADDR_ANY ?
9201 				    &ire->ire_gateway_addr : &ire->ire_addr),
9202 				    B_FALSE)) == NULL) {
9203 					if (save_ire != NULL)
9204 						ire_refrele(save_ire);
9205 					break;
9206 				}
9207 				ASSERT(ire->ire_nce->nce_state ==
9208 				    ND_REACHABLE);
9209 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9210 			}
9211 
9212 			/* Prevent save_ire from getting deleted */
9213 			if (save_ire != NULL) {
9214 				IRB_REFHOLD(save_ire->ire_bucket);
9215 				/* Has it been removed already ? */
9216 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9217 					IRB_REFRELE(save_ire->ire_bucket);
9218 					ire_refrele(save_ire);
9219 					break;
9220 				}
9221 			}
9222 
9223 			ire_add_then_send(q, ire, first_mp);
9224 
9225 			/* Assert that save_ire is not deleted yet. */
9226 			if (save_ire != NULL) {
9227 				ASSERT(save_ire->ire_ptpn != NULL);
9228 				IRB_REFRELE(save_ire->ire_bucket);
9229 				ire_refrele(save_ire);
9230 				save_ire = NULL;
9231 			}
9232 			if (fire != NULL) {
9233 				ire_refrele(fire);
9234 				fire = NULL;
9235 			}
9236 
9237 			/*
9238 			 * the resolution loop is re-entered if this
9239 			 * was requested through flags and if we
9240 			 * actually are in a multirouting case.
9241 			 */
9242 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9243 				boolean_t need_resolve =
9244 				    ire_multirt_need_resolve(ipha_dst,
9245 					MBLK_GETLABEL(copy_mp));
9246 				if (!need_resolve) {
9247 					MULTIRT_DEBUG_UNTAG(copy_mp);
9248 					freemsg(copy_mp);
9249 					copy_mp = NULL;
9250 				} else {
9251 					/*
9252 					 * ipif_lookup_group() calls
9253 					 * ire_lookup_multi() that uses
9254 					 * ire_ftable_lookup() to find
9255 					 * an IRE_INTERFACE for the group.
9256 					 * In the multirt case,
9257 					 * ire_lookup_multi() then invokes
9258 					 * ire_multirt_lookup() to find
9259 					 * the next resolvable ire.
9260 					 * As a result, we obtain an new
9261 					 * interface, derived from the
9262 					 * next ire.
9263 					 */
9264 					ipif_refrele(ipif);
9265 					ipif = ipif_lookup_group(ipha_dst,
9266 					    zoneid);
9267 					ip2dbg(("ip_newroute_ipif: "
9268 					    "multirt dst %08x, ipif %p\n",
9269 					    htonl(dst), (void *)ipif));
9270 					if (ipif != NULL) {
9271 						mp = copy_mp;
9272 						copy_mp = NULL;
9273 						multirt_resolve_next = B_TRUE;
9274 						continue;
9275 					} else {
9276 						freemsg(copy_mp);
9277 					}
9278 				}
9279 			}
9280 			if (ipif != NULL)
9281 				ipif_refrele(ipif);
9282 			ill_refrele(dst_ill);
9283 			ipif_refrele(src_ipif);
9284 			return;
9285 		}
9286 		case IRE_IF_RESOLVER:
9287 			/*
9288 			 * We can't build an IRE_CACHE yet, but at least
9289 			 * we found a resolver that can help.
9290 			 */
9291 			res_mp = dst_ill->ill_resolver_mp;
9292 			if (!OK_RESOLVER_MP(res_mp))
9293 				break;
9294 
9295 			/*
9296 			 * We obtain a partial IRE_CACHE which we will pass
9297 			 * along with the resolver query.  When the response
9298 			 * comes back it will be there ready for us to add.
9299 			 * The new ire inherits the IRE_OFFSUBNET flags
9300 			 * and source address, if this was requested.
9301 			 * The ire_max_frag is atomically set under the
9302 			 * irebucket lock in ire_add_v[46]. Only in the
9303 			 * case of IRE_MARK_NOADD, we set it here itself.
9304 			 */
9305 			ire = ire_create_mp(
9306 			    (uchar_t *)&dst,		/* dest address */
9307 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9308 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9309 			    NULL,			/* gateway address */
9310 			    NULL,			/* no in_src_addr */
9311 			    (ire_marks & IRE_MARK_NOADD) ?
9312 				ipif->ipif_mtu : 0,	/* max_frag */
9313 			    NULL,			/* Fast path header */
9314 			    dst_ill->ill_rq,		/* recv-from queue */
9315 			    dst_ill->ill_wq,		/* send-to queue */
9316 			    IRE_CACHE,
9317 			    NULL,	/* let ire_nce_init figure res_mp out */
9318 			    src_ipif,
9319 			    NULL,
9320 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9321 			    (fire != NULL) ?		/* Parent handle */
9322 				fire->ire_phandle : 0,
9323 			    ihandle,			/* Interface handle */
9324 			    (fire != NULL) ?		/* flags if any */
9325 				(fire->ire_flags &
9326 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9327 			    (save_ire == NULL ? &ire_uinfo_null :
9328 				&save_ire->ire_uinfo),
9329 			    NULL,
9330 			    NULL);
9331 
9332 			if (save_ire != NULL) {
9333 				ire_refrele(save_ire);
9334 				save_ire = NULL;
9335 			}
9336 			if (ire == NULL)
9337 				break;
9338 
9339 			ire->ire_marks |= ire_marks;
9340 			/*
9341 			 * Construct message chain for the resolver of the
9342 			 * form:
9343 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9344 			 *
9345 			 * NOTE : ire will be added later when the response
9346 			 * comes back from ARP. If the response does not
9347 			 * come back, ARP frees the packet. For this reason,
9348 			 * we can't REFHOLD the bucket of save_ire to prevent
9349 			 * deletions. We may not be able to REFRELE the
9350 			 * bucket if the response never comes back.
9351 			 * Thus, before adding the ire, ire_add_v4 will make
9352 			 * sure that the interface route does not get deleted.
9353 			 * This is the only case unlike ip_newroute_v6,
9354 			 * ip_newroute_ipif_v6 where we can always prevent
9355 			 * deletions because ire_add_then_send is called after
9356 			 * creating the IRE.
9357 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9358 			 * does not add this IRE into the IRE CACHE.
9359 			 */
9360 			ASSERT(ire->ire_mp != NULL);
9361 			ire->ire_mp->b_cont = first_mp;
9362 			/* Have saved_mp handy, for cleanup if canput fails */
9363 			saved_mp = mp;
9364 			mp = copyb(res_mp);
9365 			if (mp == NULL) {
9366 				/* Prepare for cleanup */
9367 				mp = saved_mp; /* pkt */
9368 				ire_delete(ire); /* ire_mp */
9369 				ire = NULL;
9370 				if (copy_mp != NULL) {
9371 					MULTIRT_DEBUG_UNTAG(copy_mp);
9372 					freemsg(copy_mp);
9373 					copy_mp = NULL;
9374 				}
9375 				break;
9376 			}
9377 			linkb(mp, ire->ire_mp);
9378 
9379 			/*
9380 			 * Fill in the source and dest addrs for the resolver.
9381 			 * NOTE: this depends on memory layouts imposed by
9382 			 * ill_init().
9383 			 */
9384 			areq = (areq_t *)mp->b_rptr;
9385 			addrp = (ipaddr_t *)((char *)areq +
9386 			    areq->areq_sender_addr_offset);
9387 			*addrp = ire->ire_src_addr;
9388 			addrp = (ipaddr_t *)((char *)areq +
9389 			    areq->areq_target_addr_offset);
9390 			*addrp = dst;
9391 			/* Up to the resolver. */
9392 			if (canputnext(dst_ill->ill_rq) &&
9393 			    !(dst_ill->ill_arp_closing)) {
9394 				putnext(dst_ill->ill_rq, mp);
9395 				/*
9396 				 * The response will come back in ip_wput
9397 				 * with db_type IRE_DB_TYPE.
9398 				 */
9399 			} else {
9400 				mp->b_cont = NULL;
9401 				freeb(mp); /* areq */
9402 				ire_delete(ire); /* ire_mp */
9403 				saved_mp->b_next = NULL;
9404 				saved_mp->b_prev = NULL;
9405 				freemsg(first_mp); /* pkt */
9406 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9407 			}
9408 
9409 			if (fire != NULL) {
9410 				ire_refrele(fire);
9411 				fire = NULL;
9412 			}
9413 
9414 
9415 			/*
9416 			 * The resolution loop is re-entered if this was
9417 			 * requested through flags and we actually are
9418 			 * in a multirouting case.
9419 			 */
9420 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9421 				boolean_t need_resolve =
9422 				    ire_multirt_need_resolve(ipha_dst,
9423 					MBLK_GETLABEL(copy_mp));
9424 				if (!need_resolve) {
9425 					MULTIRT_DEBUG_UNTAG(copy_mp);
9426 					freemsg(copy_mp);
9427 					copy_mp = NULL;
9428 				} else {
9429 					/*
9430 					 * ipif_lookup_group() calls
9431 					 * ire_lookup_multi() that uses
9432 					 * ire_ftable_lookup() to find
9433 					 * an IRE_INTERFACE for the group.
9434 					 * In the multirt case,
9435 					 * ire_lookup_multi() then invokes
9436 					 * ire_multirt_lookup() to find
9437 					 * the next resolvable ire.
9438 					 * As a result, we obtain an new
9439 					 * interface, derived from the
9440 					 * next ire.
9441 					 */
9442 					ipif_refrele(ipif);
9443 					ipif = ipif_lookup_group(ipha_dst,
9444 					    zoneid);
9445 					if (ipif != NULL) {
9446 						mp = copy_mp;
9447 						copy_mp = NULL;
9448 						multirt_resolve_next = B_TRUE;
9449 						continue;
9450 					} else {
9451 						freemsg(copy_mp);
9452 					}
9453 				}
9454 			}
9455 			if (ipif != NULL)
9456 				ipif_refrele(ipif);
9457 			ill_refrele(dst_ill);
9458 			ipif_refrele(src_ipif);
9459 			return;
9460 		default:
9461 			break;
9462 		}
9463 	} while (multirt_resolve_next);
9464 
9465 err_ret:
9466 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9467 	if (fire != NULL)
9468 		ire_refrele(fire);
9469 	ipif_refrele(ipif);
9470 	/* Did this packet originate externally? */
9471 	if (dst_ill != NULL)
9472 		ill_refrele(dst_ill);
9473 	if (src_ipif != NULL)
9474 		ipif_refrele(src_ipif);
9475 	if (mp->b_prev || mp->b_next) {
9476 		mp->b_next = NULL;
9477 		mp->b_prev = NULL;
9478 	} else {
9479 		/*
9480 		 * Since ip_wput() isn't close to finished, we fill
9481 		 * in enough of the header for credible error reporting.
9482 		 */
9483 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9484 			/* Failed */
9485 			freemsg(first_mp);
9486 			if (ire != NULL)
9487 				ire_refrele(ire);
9488 			return;
9489 		}
9490 	}
9491 	/*
9492 	 * At this point we will have ire only if RTF_BLACKHOLE
9493 	 * or RTF_REJECT flags are set on the IRE. It will not
9494 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9495 	 */
9496 	if (ire != NULL) {
9497 		if (ire->ire_flags & RTF_BLACKHOLE) {
9498 			ire_refrele(ire);
9499 			freemsg(first_mp);
9500 			return;
9501 		}
9502 		ire_refrele(ire);
9503 	}
9504 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9505 }
9506 
9507 /* Name/Value Table Lookup Routine */
9508 char *
9509 ip_nv_lookup(nv_t *nv, int value)
9510 {
9511 	if (!nv)
9512 		return (NULL);
9513 	for (; nv->nv_name; nv++) {
9514 		if (nv->nv_value == value)
9515 			return (nv->nv_name);
9516 	}
9517 	return ("unknown");
9518 }
9519 
9520 /*
9521  * one day it can be patched to 1 from /etc/system for machines that have few
9522  * fast network interfaces feeding multiple cpus.
9523  */
9524 int ill_stream_putlocks = 0;
9525 
9526 /*
9527  * This is a module open, i.e. this is a control stream for access
9528  * to a DLPI device.  We allocate an ill_t as the instance data in
9529  * this case.
9530  */
9531 int
9532 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9533 {
9534 	uint32_t mem_cnt;
9535 	uint32_t cpu_cnt;
9536 	uint32_t min_cnt;
9537 	pgcnt_t mem_avail;
9538 	ill_t	*ill;
9539 	int	err;
9540 
9541 	/*
9542 	 * Prevent unprivileged processes from pushing IP so that
9543 	 * they can't send raw IP.
9544 	 */
9545 	if (secpolicy_net_rawaccess(credp) != 0)
9546 		return (EPERM);
9547 
9548 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9549 	q->q_ptr = WR(q)->q_ptr = ill;
9550 
9551 	/*
9552 	 * ill_init initializes the ill fields and then sends down
9553 	 * down a DL_INFO_REQ after calling qprocson.
9554 	 */
9555 	err = ill_init(q, ill);
9556 	if (err != 0) {
9557 		mi_free(ill);
9558 		q->q_ptr = NULL;
9559 		WR(q)->q_ptr = NULL;
9560 		return (err);
9561 	}
9562 
9563 	/* ill_init initializes the ipsq marking this thread as writer */
9564 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9565 	/* Wait for the DL_INFO_ACK */
9566 	mutex_enter(&ill->ill_lock);
9567 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9568 		/*
9569 		 * Return value of 0 indicates a pending signal.
9570 		 */
9571 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9572 		if (err == 0) {
9573 			mutex_exit(&ill->ill_lock);
9574 			(void) ip_close(q, 0);
9575 			return (EINTR);
9576 		}
9577 	}
9578 	mutex_exit(&ill->ill_lock);
9579 
9580 	/*
9581 	 * ip_rput_other could have set an error  in ill_error on
9582 	 * receipt of M_ERROR.
9583 	 */
9584 
9585 	err = ill->ill_error;
9586 	if (err != 0) {
9587 		(void) ip_close(q, 0);
9588 		return (err);
9589 	}
9590 
9591 	/*
9592 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9593 	 * size and the cpu speed of the machine. This is upper
9594 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9595 	 * and is lower bounded by the compile time value of
9596 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9597 	 * ip6_ire_max_bucket_cnt.
9598 	 */
9599 	mem_avail = kmem_avail();
9600 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9601 	    ip_cache_table_size / sizeof (ire_t);
9602 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9603 
9604 	min_cnt = MIN(cpu_cnt, mem_cnt);
9605 	if (min_cnt < ip_ire_min_bucket_cnt)
9606 		min_cnt = ip_ire_min_bucket_cnt;
9607 	if (ip_ire_max_bucket_cnt > min_cnt) {
9608 		ip_ire_max_bucket_cnt = min_cnt;
9609 	}
9610 
9611 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9612 	    ip6_cache_table_size / sizeof (ire_t);
9613 	min_cnt = MIN(cpu_cnt, mem_cnt);
9614 	if (min_cnt < ip6_ire_min_bucket_cnt)
9615 		min_cnt = ip6_ire_min_bucket_cnt;
9616 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9617 		ip6_ire_max_bucket_cnt = min_cnt;
9618 	}
9619 
9620 	ill->ill_credp = credp;
9621 	crhold(credp);
9622 
9623 	mutex_enter(&ip_mi_lock);
9624 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9625 	mutex_exit(&ip_mi_lock);
9626 	if (err) {
9627 		(void) ip_close(q, 0);
9628 		return (err);
9629 	}
9630 	return (0);
9631 }
9632 
9633 /* IP open routine. */
9634 int
9635 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9636 {
9637 	conn_t 		*connp;
9638 	major_t		maj;
9639 
9640 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9641 
9642 	/* Allow reopen. */
9643 	if (q->q_ptr != NULL)
9644 		return (0);
9645 
9646 	if (sflag & MODOPEN) {
9647 		/* This is a module open */
9648 		return (ip_modopen(q, devp, flag, sflag, credp));
9649 	}
9650 
9651 	/*
9652 	 * We are opening as a device. This is an IP client stream, and we
9653 	 * allocate an conn_t as the instance data.
9654 	 */
9655 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9656 	connp->conn_upq = q;
9657 	q->q_ptr = WR(q)->q_ptr = connp;
9658 
9659 	if (flag & SO_SOCKSTR)
9660 		connp->conn_flags |= IPCL_SOCKET;
9661 
9662 	/* Minor tells us which /dev entry was opened */
9663 	if (geteminor(*devp) == IPV6_MINOR) {
9664 		connp->conn_flags |= IPCL_ISV6;
9665 		connp->conn_af_isv6 = B_TRUE;
9666 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9667 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9668 	} else {
9669 		connp->conn_af_isv6 = B_FALSE;
9670 		connp->conn_pkt_isv6 = B_FALSE;
9671 	}
9672 
9673 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9674 		q->q_ptr = WR(q)->q_ptr = NULL;
9675 		CONN_DEC_REF(connp);
9676 		return (EBUSY);
9677 	}
9678 
9679 	maj = getemajor(*devp);
9680 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9681 
9682 	/*
9683 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9684 	 */
9685 	connp->conn_cred = credp;
9686 	crhold(connp->conn_cred);
9687 
9688 	/*
9689 	 * If the caller has the process-wide flag set, then default to MAC
9690 	 * exempt mode.  This allows read-down to unlabeled hosts.
9691 	 */
9692 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9693 		connp->conn_mac_exempt = B_TRUE;
9694 
9695 	connp->conn_zoneid = getzoneid();
9696 
9697 	/*
9698 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9699 	 * administrative ops.  In these cases, we just need a normal conn_t
9700 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9701 	 * an error will be returned.
9702 	 */
9703 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9704 		connp->conn_rq = q;
9705 		connp->conn_wq = WR(q);
9706 	} else {
9707 		connp->conn_ulp = IPPROTO_SCTP;
9708 		connp->conn_rq = connp->conn_wq = NULL;
9709 	}
9710 	/* Non-zero default values */
9711 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9712 
9713 	/*
9714 	 * Make the conn globally visible to walkers
9715 	 */
9716 	mutex_enter(&connp->conn_lock);
9717 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9718 	mutex_exit(&connp->conn_lock);
9719 	ASSERT(connp->conn_ref == 1);
9720 
9721 	qprocson(q);
9722 
9723 	return (0);
9724 }
9725 
9726 /*
9727  * Change q_qinfo based on the value of isv6.
9728  * This can not called on an ill queue.
9729  * Note that there is no race since either q_qinfo works for conn queues - it
9730  * is just an optimization to enter the best wput routine directly.
9731  */
9732 void
9733 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9734 {
9735 	ASSERT(q->q_flag & QREADR);
9736 	ASSERT(WR(q)->q_next == NULL);
9737 	ASSERT(q->q_ptr != NULL);
9738 
9739 	if (minor == IPV6_MINOR)  {
9740 		if (bump_mib)
9741 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9742 		q->q_qinfo = &rinit_ipv6;
9743 		WR(q)->q_qinfo = &winit_ipv6;
9744 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9745 	} else {
9746 		if (bump_mib)
9747 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9748 		q->q_qinfo = &iprinit;
9749 		WR(q)->q_qinfo = &ipwinit;
9750 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9751 	}
9752 
9753 }
9754 
9755 /*
9756  * See if IPsec needs loading because of the options in mp.
9757  */
9758 static boolean_t
9759 ipsec_opt_present(mblk_t *mp)
9760 {
9761 	uint8_t *optcp, *next_optcp, *opt_endcp;
9762 	struct opthdr *opt;
9763 	struct T_opthdr *topt;
9764 	int opthdr_len;
9765 	t_uscalar_t optname, optlevel;
9766 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9767 	ipsec_req_t *ipsr;
9768 
9769 	/*
9770 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9771 	 * return TRUE.
9772 	 */
9773 
9774 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9775 	opt_endcp = optcp + tor->OPT_length;
9776 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9777 		opthdr_len = sizeof (struct T_opthdr);
9778 	} else {		/* O_OPTMGMT_REQ */
9779 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9780 		opthdr_len = sizeof (struct opthdr);
9781 	}
9782 	for (; optcp < opt_endcp; optcp = next_optcp) {
9783 		if (optcp + opthdr_len > opt_endcp)
9784 			return (B_FALSE);	/* Not enough option header. */
9785 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9786 			topt = (struct T_opthdr *)optcp;
9787 			optlevel = topt->level;
9788 			optname = topt->name;
9789 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9790 		} else {
9791 			opt = (struct opthdr *)optcp;
9792 			optlevel = opt->level;
9793 			optname = opt->name;
9794 			next_optcp = optcp + opthdr_len +
9795 			    _TPI_ALIGN_OPT(opt->len);
9796 		}
9797 		if ((next_optcp < optcp) || /* wraparound pointer space */
9798 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9799 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9800 			return (B_FALSE); /* bad option buffer */
9801 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9802 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9803 			/*
9804 			 * Check to see if it's an all-bypass or all-zeroes
9805 			 * IPsec request.  Don't bother loading IPsec if
9806 			 * the socket doesn't want to use it.  (A good example
9807 			 * is a bypass request.)
9808 			 *
9809 			 * Basically, if any of the non-NEVER bits are set,
9810 			 * load IPsec.
9811 			 */
9812 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9813 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9814 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9815 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9816 			    != 0)
9817 				return (B_TRUE);
9818 		}
9819 	}
9820 	return (B_FALSE);
9821 }
9822 
9823 /*
9824  * If conn is is waiting for ipsec to finish loading, kick it.
9825  */
9826 /* ARGSUSED */
9827 static void
9828 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9829 {
9830 	t_scalar_t	optreq_prim;
9831 	mblk_t		*mp;
9832 	cred_t		*cr;
9833 	int		err = 0;
9834 
9835 	/*
9836 	 * This function is called, after ipsec loading is complete.
9837 	 * Since IP checks exclusively and atomically (i.e it prevents
9838 	 * ipsec load from completing until ip_optcom_req completes)
9839 	 * whether ipsec load is complete, there cannot be a race with IP
9840 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9841 	 */
9842 	mutex_enter(&connp->conn_lock);
9843 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9844 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9845 		mp = connp->conn_ipsec_opt_mp;
9846 		connp->conn_ipsec_opt_mp = NULL;
9847 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9848 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9849 		mutex_exit(&connp->conn_lock);
9850 
9851 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9852 
9853 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9854 		if (optreq_prim == T_OPTMGMT_REQ) {
9855 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9856 			    &ip_opt_obj);
9857 		} else {
9858 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9859 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9860 			    &ip_opt_obj);
9861 		}
9862 		if (err != EINPROGRESS)
9863 			CONN_OPER_PENDING_DONE(connp);
9864 		return;
9865 	}
9866 	mutex_exit(&connp->conn_lock);
9867 }
9868 
9869 /*
9870  * Called from the ipsec_loader thread, outside any perimeter, to tell
9871  * ip qenable any of the queues waiting for the ipsec loader to
9872  * complete.
9873  *
9874  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9875  * are done with this lock held, so it's guaranteed that none of the
9876  * links will change along the way.
9877  */
9878 void
9879 ip_ipsec_load_complete()
9880 {
9881 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9882 }
9883 
9884 /*
9885  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9886  * determines the grp on which it has to become exclusive, queues the mp
9887  * and sq draining restarts the optmgmt
9888  */
9889 static boolean_t
9890 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9891 {
9892 	conn_t *connp;
9893 
9894 	/*
9895 	 * Take IPsec requests and treat them special.
9896 	 */
9897 	if (ipsec_opt_present(mp)) {
9898 		/* First check if IPsec is loaded. */
9899 		mutex_enter(&ipsec_loader_lock);
9900 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9901 			mutex_exit(&ipsec_loader_lock);
9902 			return (B_FALSE);
9903 		}
9904 		connp = Q_TO_CONN(q);
9905 		mutex_enter(&connp->conn_lock);
9906 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9907 
9908 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9909 		connp->conn_ipsec_opt_mp = mp;
9910 		mutex_exit(&connp->conn_lock);
9911 		mutex_exit(&ipsec_loader_lock);
9912 
9913 		ipsec_loader_loadnow();
9914 		return (B_TRUE);
9915 	}
9916 	return (B_FALSE);
9917 }
9918 
9919 /*
9920  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9921  * all of them are copied to the conn_t. If the req is "zero", the policy is
9922  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9923  * fields.
9924  * We keep only the latest setting of the policy and thus policy setting
9925  * is not incremental/cumulative.
9926  *
9927  * Requests to set policies with multiple alternative actions will
9928  * go through a different API.
9929  */
9930 int
9931 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9932 {
9933 	uint_t ah_req = 0;
9934 	uint_t esp_req = 0;
9935 	uint_t se_req = 0;
9936 	ipsec_selkey_t sel;
9937 	ipsec_act_t *actp = NULL;
9938 	uint_t nact;
9939 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9940 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9941 	ipsec_policy_root_t *pr;
9942 	ipsec_policy_head_t *ph;
9943 	int fam;
9944 	boolean_t is_pol_reset;
9945 	int error = 0;
9946 
9947 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9948 
9949 	/*
9950 	 * The IP_SEC_OPT option does not allow variable length parameters,
9951 	 * hence a request cannot be NULL.
9952 	 */
9953 	if (req == NULL)
9954 		return (EINVAL);
9955 
9956 	ah_req = req->ipsr_ah_req;
9957 	esp_req = req->ipsr_esp_req;
9958 	se_req = req->ipsr_self_encap_req;
9959 
9960 	/*
9961 	 * Are we dealing with a request to reset the policy (i.e.
9962 	 * zero requests).
9963 	 */
9964 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9965 	    (esp_req & REQ_MASK) == 0 &&
9966 	    (se_req & REQ_MASK) == 0);
9967 
9968 	if (!is_pol_reset) {
9969 		/*
9970 		 * If we couldn't load IPsec, fail with "protocol
9971 		 * not supported".
9972 		 * IPsec may not have been loaded for a request with zero
9973 		 * policies, so we don't fail in this case.
9974 		 */
9975 		mutex_enter(&ipsec_loader_lock);
9976 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9977 			mutex_exit(&ipsec_loader_lock);
9978 			return (EPROTONOSUPPORT);
9979 		}
9980 		mutex_exit(&ipsec_loader_lock);
9981 
9982 		/*
9983 		 * Test for valid requests. Invalid algorithms
9984 		 * need to be tested by IPSEC code because new
9985 		 * algorithms can be added dynamically.
9986 		 */
9987 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9988 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9989 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9990 			return (EINVAL);
9991 		}
9992 
9993 		/*
9994 		 * Only privileged users can issue these
9995 		 * requests.
9996 		 */
9997 		if (((ah_req & IPSEC_PREF_NEVER) ||
9998 		    (esp_req & IPSEC_PREF_NEVER) ||
9999 		    (se_req & IPSEC_PREF_NEVER)) &&
10000 		    secpolicy_net_config(cr, B_FALSE) != 0) {
10001 			return (EPERM);
10002 		}
10003 
10004 		/*
10005 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10006 		 * are mutually exclusive.
10007 		 */
10008 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10009 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10010 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10011 			/* Both of them are set */
10012 			return (EINVAL);
10013 		}
10014 	}
10015 
10016 	mutex_enter(&connp->conn_lock);
10017 
10018 	/*
10019 	 * If we have already cached policies in ip_bind_connected*(), don't
10020 	 * let them change now. We cache policies for connections
10021 	 * whose src,dst [addr, port] is known.
10022 	 */
10023 	if (connp->conn_policy_cached) {
10024 		mutex_exit(&connp->conn_lock);
10025 		return (EINVAL);
10026 	}
10027 
10028 	/*
10029 	 * We have a zero policies, reset the connection policy if already
10030 	 * set. This will cause the connection to inherit the
10031 	 * global policy, if any.
10032 	 */
10033 	if (is_pol_reset) {
10034 		if (connp->conn_policy != NULL) {
10035 			IPPH_REFRELE(connp->conn_policy);
10036 			connp->conn_policy = NULL;
10037 		}
10038 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10039 		connp->conn_in_enforce_policy = B_FALSE;
10040 		connp->conn_out_enforce_policy = B_FALSE;
10041 		mutex_exit(&connp->conn_lock);
10042 		return (0);
10043 	}
10044 
10045 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
10046 	if (ph == NULL)
10047 		goto enomem;
10048 
10049 	ipsec_actvec_from_req(req, &actp, &nact);
10050 	if (actp == NULL)
10051 		goto enomem;
10052 
10053 	/*
10054 	 * Always allocate IPv4 policy entries, since they can also
10055 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10056 	 */
10057 	bzero(&sel, sizeof (sel));
10058 	sel.ipsl_valid = IPSL_IPV4;
10059 
10060 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10061 	if (pin4 == NULL)
10062 		goto enomem;
10063 
10064 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10065 	if (pout4 == NULL)
10066 		goto enomem;
10067 
10068 	if (connp->conn_pkt_isv6) {
10069 		/*
10070 		 * We're looking at a v6 socket, also allocate the
10071 		 * v6-specific entries...
10072 		 */
10073 		sel.ipsl_valid = IPSL_IPV6;
10074 		pin6 = ipsec_policy_create(&sel, actp, nact,
10075 		    IPSEC_PRIO_SOCKET, NULL);
10076 		if (pin6 == NULL)
10077 			goto enomem;
10078 
10079 		pout6 = ipsec_policy_create(&sel, actp, nact,
10080 		    IPSEC_PRIO_SOCKET, NULL);
10081 		if (pout6 == NULL)
10082 			goto enomem;
10083 
10084 		/*
10085 		 * .. and file them away in the right place.
10086 		 */
10087 		fam = IPSEC_AF_V6;
10088 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10089 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10090 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10091 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10092 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10093 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10094 	}
10095 
10096 	ipsec_actvec_free(actp, nact);
10097 
10098 	/*
10099 	 * File the v4 policies.
10100 	 */
10101 	fam = IPSEC_AF_V4;
10102 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10103 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10104 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10105 
10106 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10107 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10108 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10109 
10110 	/*
10111 	 * If the requests need security, set enforce_policy.
10112 	 * If the requests are IPSEC_PREF_NEVER, one should
10113 	 * still set conn_out_enforce_policy so that an ipsec_out
10114 	 * gets attached in ip_wput. This is needed so that
10115 	 * for connections that we don't cache policy in ip_bind,
10116 	 * if global policy matches in ip_wput_attach_policy, we
10117 	 * don't wrongly inherit global policy. Similarly, we need
10118 	 * to set conn_in_enforce_policy also so that we don't verify
10119 	 * policy wrongly.
10120 	 */
10121 	if ((ah_req & REQ_MASK) != 0 ||
10122 	    (esp_req & REQ_MASK) != 0 ||
10123 	    (se_req & REQ_MASK) != 0) {
10124 		connp->conn_in_enforce_policy = B_TRUE;
10125 		connp->conn_out_enforce_policy = B_TRUE;
10126 		connp->conn_flags |= IPCL_CHECK_POLICY;
10127 	}
10128 
10129 	mutex_exit(&connp->conn_lock);
10130 	return (error);
10131 #undef REQ_MASK
10132 
10133 	/*
10134 	 * Common memory-allocation-failure exit path.
10135 	 */
10136 enomem:
10137 	mutex_exit(&connp->conn_lock);
10138 	if (actp != NULL)
10139 		ipsec_actvec_free(actp, nact);
10140 	if (pin4 != NULL)
10141 		IPPOL_REFRELE(pin4);
10142 	if (pout4 != NULL)
10143 		IPPOL_REFRELE(pout4);
10144 	if (pin6 != NULL)
10145 		IPPOL_REFRELE(pin6);
10146 	if (pout6 != NULL)
10147 		IPPOL_REFRELE(pout6);
10148 	return (ENOMEM);
10149 }
10150 
10151 /*
10152  * Only for options that pass in an IP addr. Currently only V4 options
10153  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10154  * So this function assumes level is IPPROTO_IP
10155  */
10156 int
10157 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10158     mblk_t *first_mp)
10159 {
10160 	ipif_t *ipif = NULL;
10161 	int error;
10162 	ill_t *ill;
10163 	int zoneid;
10164 
10165 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10166 
10167 	if (addr != INADDR_ANY || checkonly) {
10168 		ASSERT(connp != NULL);
10169 		zoneid = IPCL_ZONEID(connp);
10170 		if (option == IP_NEXTHOP) {
10171 			ipif = ipif_lookup_onlink_addr(addr,
10172 			    connp->conn_zoneid);
10173 		} else {
10174 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10175 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10176 			    &error);
10177 		}
10178 		if (ipif == NULL) {
10179 			if (error == EINPROGRESS)
10180 				return (error);
10181 			else if ((option == IP_MULTICAST_IF) ||
10182 			    (option == IP_NEXTHOP))
10183 				return (EHOSTUNREACH);
10184 			else
10185 				return (EINVAL);
10186 		} else if (checkonly) {
10187 			if (option == IP_MULTICAST_IF) {
10188 				ill = ipif->ipif_ill;
10189 				/* not supported by the virtual network iface */
10190 				if (IS_VNI(ill)) {
10191 					ipif_refrele(ipif);
10192 					return (EINVAL);
10193 				}
10194 			}
10195 			ipif_refrele(ipif);
10196 			return (0);
10197 		}
10198 		ill = ipif->ipif_ill;
10199 		mutex_enter(&connp->conn_lock);
10200 		mutex_enter(&ill->ill_lock);
10201 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10202 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10203 			mutex_exit(&ill->ill_lock);
10204 			mutex_exit(&connp->conn_lock);
10205 			ipif_refrele(ipif);
10206 			return (option == IP_MULTICAST_IF ?
10207 			    EHOSTUNREACH : EINVAL);
10208 		}
10209 	} else {
10210 		mutex_enter(&connp->conn_lock);
10211 	}
10212 
10213 	/* None of the options below are supported on the VNI */
10214 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10215 		mutex_exit(&ill->ill_lock);
10216 		mutex_exit(&connp->conn_lock);
10217 		ipif_refrele(ipif);
10218 		return (EINVAL);
10219 	}
10220 
10221 	switch (option) {
10222 	case IP_DONTFAILOVER_IF:
10223 		/*
10224 		 * This option is used by in.mpathd to ensure
10225 		 * that IPMP probe packets only go out on the
10226 		 * test interfaces. in.mpathd sets this option
10227 		 * on the non-failover interfaces.
10228 		 * For backward compatibility, this option
10229 		 * implicitly sets IP_MULTICAST_IF, as used
10230 		 * be done in bind(), so that ip_wput gets
10231 		 * this ipif to send mcast packets.
10232 		 */
10233 		if (ipif != NULL) {
10234 			ASSERT(addr != INADDR_ANY);
10235 			connp->conn_nofailover_ill = ipif->ipif_ill;
10236 			connp->conn_multicast_ipif = ipif;
10237 		} else {
10238 			ASSERT(addr == INADDR_ANY);
10239 			connp->conn_nofailover_ill = NULL;
10240 			connp->conn_multicast_ipif = NULL;
10241 		}
10242 		break;
10243 
10244 	case IP_MULTICAST_IF:
10245 		connp->conn_multicast_ipif = ipif;
10246 		break;
10247 	case IP_NEXTHOP:
10248 		connp->conn_nexthop_v4 = addr;
10249 		connp->conn_nexthop_set = B_TRUE;
10250 		break;
10251 	}
10252 
10253 	if (ipif != NULL) {
10254 		mutex_exit(&ill->ill_lock);
10255 		mutex_exit(&connp->conn_lock);
10256 		ipif_refrele(ipif);
10257 		return (0);
10258 	}
10259 	mutex_exit(&connp->conn_lock);
10260 	/* We succeded in cleared the option */
10261 	return (0);
10262 }
10263 
10264 /*
10265  * For options that pass in an ifindex specifying the ill. V6 options always
10266  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10267  */
10268 int
10269 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10270     int level, int option, mblk_t *first_mp)
10271 {
10272 	ill_t *ill = NULL;
10273 	int error = 0;
10274 
10275 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10276 	if (ifindex != 0) {
10277 		ASSERT(connp != NULL);
10278 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10279 		    first_mp, ip_restart_optmgmt, &error);
10280 		if (ill != NULL) {
10281 			if (checkonly) {
10282 				/* not supported by the virtual network iface */
10283 				if (IS_VNI(ill)) {
10284 					ill_refrele(ill);
10285 					return (EINVAL);
10286 				}
10287 				ill_refrele(ill);
10288 				return (0);
10289 			}
10290 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10291 			    0, NULL)) {
10292 				ill_refrele(ill);
10293 				ill = NULL;
10294 				mutex_enter(&connp->conn_lock);
10295 				goto setit;
10296 			}
10297 			mutex_enter(&connp->conn_lock);
10298 			mutex_enter(&ill->ill_lock);
10299 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10300 				mutex_exit(&ill->ill_lock);
10301 				mutex_exit(&connp->conn_lock);
10302 				ill_refrele(ill);
10303 				ill = NULL;
10304 				mutex_enter(&connp->conn_lock);
10305 			}
10306 			goto setit;
10307 		} else if (error == EINPROGRESS) {
10308 			return (error);
10309 		} else {
10310 			error = 0;
10311 		}
10312 	}
10313 	mutex_enter(&connp->conn_lock);
10314 setit:
10315 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10316 
10317 	/*
10318 	 * The options below assume that the ILL (if any) transmits and/or
10319 	 * receives traffic. Neither of which is true for the virtual network
10320 	 * interface, so fail setting these on a VNI.
10321 	 */
10322 	if (IS_VNI(ill)) {
10323 		ASSERT(ill != NULL);
10324 		mutex_exit(&ill->ill_lock);
10325 		mutex_exit(&connp->conn_lock);
10326 		ill_refrele(ill);
10327 		return (EINVAL);
10328 	}
10329 
10330 	if (level == IPPROTO_IP) {
10331 		switch (option) {
10332 		case IP_BOUND_IF:
10333 			connp->conn_incoming_ill = ill;
10334 			connp->conn_outgoing_ill = ill;
10335 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10336 			    0 : ifindex;
10337 			break;
10338 
10339 		case IP_XMIT_IF:
10340 			/*
10341 			 * Similar to IP_BOUND_IF, but this only
10342 			 * determines the outgoing interface for
10343 			 * unicast packets. Also no IRE_CACHE entry
10344 			 * is added for the destination of the
10345 			 * outgoing packets. This feature is needed
10346 			 * for mobile IP.
10347 			 */
10348 			connp->conn_xmit_if_ill = ill;
10349 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10350 			    0 : ifindex;
10351 			break;
10352 
10353 		case IP_MULTICAST_IF:
10354 			/*
10355 			 * This option is an internal special. The socket
10356 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10357 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10358 			 * specifies an ifindex and we try first on V6 ill's.
10359 			 * If we don't find one, we they try using on v4 ill's
10360 			 * intenally and we come here.
10361 			 */
10362 			if (!checkonly && ill != NULL) {
10363 				ipif_t	*ipif;
10364 				ipif = ill->ill_ipif;
10365 
10366 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10367 					mutex_exit(&ill->ill_lock);
10368 					mutex_exit(&connp->conn_lock);
10369 					ill_refrele(ill);
10370 					ill = NULL;
10371 					mutex_enter(&connp->conn_lock);
10372 				} else {
10373 					connp->conn_multicast_ipif = ipif;
10374 				}
10375 			}
10376 			break;
10377 		}
10378 	} else {
10379 		switch (option) {
10380 		case IPV6_BOUND_IF:
10381 			connp->conn_incoming_ill = ill;
10382 			connp->conn_outgoing_ill = ill;
10383 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10384 			    0 : ifindex;
10385 			break;
10386 
10387 		case IPV6_BOUND_PIF:
10388 			/*
10389 			 * Limit all transmit to this ill.
10390 			 * Unlike IPV6_BOUND_IF, using this option
10391 			 * prevents load spreading and failover from
10392 			 * happening when the interface is part of the
10393 			 * group. That's why we don't need to remember
10394 			 * the ifindex in orig_bound_ifindex as in
10395 			 * IPV6_BOUND_IF.
10396 			 */
10397 			connp->conn_outgoing_pill = ill;
10398 			break;
10399 
10400 		case IPV6_DONTFAILOVER_IF:
10401 			/*
10402 			 * This option is used by in.mpathd to ensure
10403 			 * that IPMP probe packets only go out on the
10404 			 * test interfaces. in.mpathd sets this option
10405 			 * on the non-failover interfaces.
10406 			 */
10407 			connp->conn_nofailover_ill = ill;
10408 			/*
10409 			 * For backward compatibility, this option
10410 			 * implicitly sets ip_multicast_ill as used in
10411 			 * IP_MULTICAST_IF so that ip_wput gets
10412 			 * this ipif to send mcast packets.
10413 			 */
10414 			connp->conn_multicast_ill = ill;
10415 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10416 			    0 : ifindex;
10417 			break;
10418 
10419 		case IPV6_MULTICAST_IF:
10420 			/*
10421 			 * Set conn_multicast_ill to be the IPv6 ill.
10422 			 * Set conn_multicast_ipif to be an IPv4 ipif
10423 			 * for ifindex to make IPv4 mapped addresses
10424 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10425 			 * Even if no IPv6 ill exists for the ifindex
10426 			 * we need to check for an IPv4 ifindex in order
10427 			 * for this to work with mapped addresses. In that
10428 			 * case only set conn_multicast_ipif.
10429 			 */
10430 			if (!checkonly) {
10431 				if (ifindex == 0) {
10432 					connp->conn_multicast_ill = NULL;
10433 					connp->conn_orig_multicast_ifindex = 0;
10434 					connp->conn_multicast_ipif = NULL;
10435 				} else if (ill != NULL) {
10436 					connp->conn_multicast_ill = ill;
10437 					connp->conn_orig_multicast_ifindex =
10438 					    ifindex;
10439 				}
10440 			}
10441 			break;
10442 		}
10443 	}
10444 
10445 	if (ill != NULL) {
10446 		mutex_exit(&ill->ill_lock);
10447 		mutex_exit(&connp->conn_lock);
10448 		ill_refrele(ill);
10449 		return (0);
10450 	}
10451 	mutex_exit(&connp->conn_lock);
10452 	/*
10453 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10454 	 * locate the ill and could not set the option (ifindex != 0)
10455 	 */
10456 	return (ifindex == 0 ? 0 : EINVAL);
10457 }
10458 
10459 /* This routine sets socket options. */
10460 /* ARGSUSED */
10461 int
10462 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10463     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10464     void *dummy, cred_t *cr, mblk_t *first_mp)
10465 {
10466 	int		*i1 = (int *)invalp;
10467 	conn_t		*connp = Q_TO_CONN(q);
10468 	int		error = 0;
10469 	boolean_t	checkonly;
10470 	ire_t		*ire;
10471 	boolean_t	found;
10472 
10473 	switch (optset_context) {
10474 
10475 	case SETFN_OPTCOM_CHECKONLY:
10476 		checkonly = B_TRUE;
10477 		/*
10478 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10479 		 * inlen != 0 implies value supplied and
10480 		 * 	we have to "pretend" to set it.
10481 		 * inlen == 0 implies that there is no
10482 		 * 	value part in T_CHECK request and just validation
10483 		 * done elsewhere should be enough, we just return here.
10484 		 */
10485 		if (inlen == 0) {
10486 			*outlenp = 0;
10487 			return (0);
10488 		}
10489 		break;
10490 	case SETFN_OPTCOM_NEGOTIATE:
10491 	case SETFN_UD_NEGOTIATE:
10492 	case SETFN_CONN_NEGOTIATE:
10493 		checkonly = B_FALSE;
10494 		break;
10495 	default:
10496 		/*
10497 		 * We should never get here
10498 		 */
10499 		*outlenp = 0;
10500 		return (EINVAL);
10501 	}
10502 
10503 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10504 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10505 
10506 	/*
10507 	 * For fixed length options, no sanity check
10508 	 * of passed in length is done. It is assumed *_optcom_req()
10509 	 * routines do the right thing.
10510 	 */
10511 
10512 	switch (level) {
10513 	case SOL_SOCKET:
10514 		/*
10515 		 * conn_lock protects the bitfields, and is used to
10516 		 * set the fields atomically.
10517 		 */
10518 		switch (name) {
10519 		case SO_BROADCAST:
10520 			if (!checkonly) {
10521 				/* TODO: use value someplace? */
10522 				mutex_enter(&connp->conn_lock);
10523 				connp->conn_broadcast = *i1 ? 1 : 0;
10524 				mutex_exit(&connp->conn_lock);
10525 			}
10526 			break;	/* goto sizeof (int) option return */
10527 		case SO_USELOOPBACK:
10528 			if (!checkonly) {
10529 				/* TODO: use value someplace? */
10530 				mutex_enter(&connp->conn_lock);
10531 				connp->conn_loopback = *i1 ? 1 : 0;
10532 				mutex_exit(&connp->conn_lock);
10533 			}
10534 			break;	/* goto sizeof (int) option return */
10535 		case SO_DONTROUTE:
10536 			if (!checkonly) {
10537 				mutex_enter(&connp->conn_lock);
10538 				connp->conn_dontroute = *i1 ? 1 : 0;
10539 				mutex_exit(&connp->conn_lock);
10540 			}
10541 			break;	/* goto sizeof (int) option return */
10542 		case SO_REUSEADDR:
10543 			if (!checkonly) {
10544 				mutex_enter(&connp->conn_lock);
10545 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10546 				mutex_exit(&connp->conn_lock);
10547 			}
10548 			break;	/* goto sizeof (int) option return */
10549 		case SO_PROTOTYPE:
10550 			if (!checkonly) {
10551 				mutex_enter(&connp->conn_lock);
10552 				connp->conn_proto = *i1;
10553 				mutex_exit(&connp->conn_lock);
10554 			}
10555 			break;	/* goto sizeof (int) option return */
10556 		case SO_ALLZONES:
10557 			if (!checkonly) {
10558 				mutex_enter(&connp->conn_lock);
10559 				if (IPCL_IS_BOUND(connp)) {
10560 					mutex_exit(&connp->conn_lock);
10561 					return (EINVAL);
10562 				}
10563 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10564 				mutex_exit(&connp->conn_lock);
10565 			}
10566 			break;	/* goto sizeof (int) option return */
10567 		case SO_ANON_MLP:
10568 			if (!checkonly) {
10569 				mutex_enter(&connp->conn_lock);
10570 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10571 				mutex_exit(&connp->conn_lock);
10572 			}
10573 			break;	/* goto sizeof (int) option return */
10574 		case SO_MAC_EXEMPT:
10575 			if (secpolicy_net_mac_aware(cr) != 0 ||
10576 			    IPCL_IS_BOUND(connp))
10577 				return (EACCES);
10578 			if (!checkonly) {
10579 				mutex_enter(&connp->conn_lock);
10580 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10581 				mutex_exit(&connp->conn_lock);
10582 			}
10583 			break;	/* goto sizeof (int) option return */
10584 		default:
10585 			/*
10586 			 * "soft" error (negative)
10587 			 * option not handled at this level
10588 			 * Note: Do not modify *outlenp
10589 			 */
10590 			return (-EINVAL);
10591 		}
10592 		break;
10593 	case IPPROTO_IP:
10594 		switch (name) {
10595 		case IP_NEXTHOP:
10596 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10597 				return (EPERM);
10598 			/* FALLTHRU */
10599 		case IP_MULTICAST_IF:
10600 		case IP_DONTFAILOVER_IF: {
10601 			ipaddr_t addr = *i1;
10602 
10603 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10604 			    first_mp);
10605 			if (error != 0)
10606 				return (error);
10607 			break;	/* goto sizeof (int) option return */
10608 		}
10609 
10610 		case IP_MULTICAST_TTL:
10611 			/* Recorded in transport above IP */
10612 			*outvalp = *invalp;
10613 			*outlenp = sizeof (uchar_t);
10614 			return (0);
10615 		case IP_MULTICAST_LOOP:
10616 			if (!checkonly) {
10617 				mutex_enter(&connp->conn_lock);
10618 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10619 				mutex_exit(&connp->conn_lock);
10620 			}
10621 			*outvalp = *invalp;
10622 			*outlenp = sizeof (uchar_t);
10623 			return (0);
10624 		case IP_ADD_MEMBERSHIP:
10625 		case MCAST_JOIN_GROUP:
10626 		case IP_DROP_MEMBERSHIP:
10627 		case MCAST_LEAVE_GROUP: {
10628 			struct ip_mreq *mreqp;
10629 			struct group_req *greqp;
10630 			ire_t *ire;
10631 			boolean_t done = B_FALSE;
10632 			ipaddr_t group, ifaddr;
10633 			struct sockaddr_in *sin;
10634 			uint32_t *ifindexp;
10635 			boolean_t mcast_opt = B_TRUE;
10636 			mcast_record_t fmode;
10637 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10638 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10639 
10640 			switch (name) {
10641 			case IP_ADD_MEMBERSHIP:
10642 				mcast_opt = B_FALSE;
10643 				/* FALLTHRU */
10644 			case MCAST_JOIN_GROUP:
10645 				fmode = MODE_IS_EXCLUDE;
10646 				optfn = ip_opt_add_group;
10647 				break;
10648 
10649 			case IP_DROP_MEMBERSHIP:
10650 				mcast_opt = B_FALSE;
10651 				/* FALLTHRU */
10652 			case MCAST_LEAVE_GROUP:
10653 				fmode = MODE_IS_INCLUDE;
10654 				optfn = ip_opt_delete_group;
10655 				break;
10656 			}
10657 
10658 			if (mcast_opt) {
10659 				greqp = (struct group_req *)i1;
10660 				sin = (struct sockaddr_in *)&greqp->gr_group;
10661 				if (sin->sin_family != AF_INET) {
10662 					*outlenp = 0;
10663 					return (ENOPROTOOPT);
10664 				}
10665 				group = (ipaddr_t)sin->sin_addr.s_addr;
10666 				ifaddr = INADDR_ANY;
10667 				ifindexp = &greqp->gr_interface;
10668 			} else {
10669 				mreqp = (struct ip_mreq *)i1;
10670 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10671 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10672 				ifindexp = NULL;
10673 			}
10674 
10675 			/*
10676 			 * In the multirouting case, we need to replicate
10677 			 * the request on all interfaces that will take part
10678 			 * in replication.  We do so because multirouting is
10679 			 * reflective, thus we will probably receive multi-
10680 			 * casts on those interfaces.
10681 			 * The ip_multirt_apply_membership() succeeds if the
10682 			 * operation succeeds on at least one interface.
10683 			 */
10684 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10685 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10686 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10687 			if (ire != NULL) {
10688 				if (ire->ire_flags & RTF_MULTIRT) {
10689 					error = ip_multirt_apply_membership(
10690 					    optfn, ire, connp, checkonly, group,
10691 					    fmode, INADDR_ANY, first_mp);
10692 					done = B_TRUE;
10693 				}
10694 				ire_refrele(ire);
10695 			}
10696 			if (!done) {
10697 				error = optfn(connp, checkonly, group, ifaddr,
10698 				    ifindexp, fmode, INADDR_ANY, first_mp);
10699 			}
10700 			if (error) {
10701 				/*
10702 				 * EINPROGRESS is a soft error, needs retry
10703 				 * so don't make *outlenp zero.
10704 				 */
10705 				if (error != EINPROGRESS)
10706 					*outlenp = 0;
10707 				return (error);
10708 			}
10709 			/* OK return - copy input buffer into output buffer */
10710 			if (invalp != outvalp) {
10711 				/* don't trust bcopy for identical src/dst */
10712 				bcopy(invalp, outvalp, inlen);
10713 			}
10714 			*outlenp = inlen;
10715 			return (0);
10716 		}
10717 		case IP_BLOCK_SOURCE:
10718 		case IP_UNBLOCK_SOURCE:
10719 		case IP_ADD_SOURCE_MEMBERSHIP:
10720 		case IP_DROP_SOURCE_MEMBERSHIP:
10721 		case MCAST_BLOCK_SOURCE:
10722 		case MCAST_UNBLOCK_SOURCE:
10723 		case MCAST_JOIN_SOURCE_GROUP:
10724 		case MCAST_LEAVE_SOURCE_GROUP: {
10725 			struct ip_mreq_source *imreqp;
10726 			struct group_source_req *gsreqp;
10727 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10728 			uint32_t ifindex = 0;
10729 			mcast_record_t fmode;
10730 			struct sockaddr_in *sin;
10731 			ire_t *ire;
10732 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10733 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10734 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10735 
10736 			switch (name) {
10737 			case IP_BLOCK_SOURCE:
10738 				mcast_opt = B_FALSE;
10739 				/* FALLTHRU */
10740 			case MCAST_BLOCK_SOURCE:
10741 				fmode = MODE_IS_EXCLUDE;
10742 				optfn = ip_opt_add_group;
10743 				break;
10744 
10745 			case IP_UNBLOCK_SOURCE:
10746 				mcast_opt = B_FALSE;
10747 				/* FALLTHRU */
10748 			case MCAST_UNBLOCK_SOURCE:
10749 				fmode = MODE_IS_EXCLUDE;
10750 				optfn = ip_opt_delete_group;
10751 				break;
10752 
10753 			case IP_ADD_SOURCE_MEMBERSHIP:
10754 				mcast_opt = B_FALSE;
10755 				/* FALLTHRU */
10756 			case MCAST_JOIN_SOURCE_GROUP:
10757 				fmode = MODE_IS_INCLUDE;
10758 				optfn = ip_opt_add_group;
10759 				break;
10760 
10761 			case IP_DROP_SOURCE_MEMBERSHIP:
10762 				mcast_opt = B_FALSE;
10763 				/* FALLTHRU */
10764 			case MCAST_LEAVE_SOURCE_GROUP:
10765 				fmode = MODE_IS_INCLUDE;
10766 				optfn = ip_opt_delete_group;
10767 				break;
10768 			}
10769 
10770 			if (mcast_opt) {
10771 				gsreqp = (struct group_source_req *)i1;
10772 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10773 					*outlenp = 0;
10774 					return (ENOPROTOOPT);
10775 				}
10776 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10777 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10778 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10779 				src = (ipaddr_t)sin->sin_addr.s_addr;
10780 				ifindex = gsreqp->gsr_interface;
10781 			} else {
10782 				imreqp = (struct ip_mreq_source *)i1;
10783 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10784 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10785 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10786 			}
10787 
10788 			/*
10789 			 * In the multirouting case, we need to replicate
10790 			 * the request as noted in the mcast cases above.
10791 			 */
10792 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10793 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10794 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10795 			if (ire != NULL) {
10796 				if (ire->ire_flags & RTF_MULTIRT) {
10797 					error = ip_multirt_apply_membership(
10798 					    optfn, ire, connp, checkonly, grp,
10799 					    fmode, src, first_mp);
10800 					done = B_TRUE;
10801 				}
10802 				ire_refrele(ire);
10803 			}
10804 			if (!done) {
10805 				error = optfn(connp, checkonly, grp, ifaddr,
10806 				    &ifindex, fmode, src, first_mp);
10807 			}
10808 			if (error != 0) {
10809 				/*
10810 				 * EINPROGRESS is a soft error, needs retry
10811 				 * so don't make *outlenp zero.
10812 				 */
10813 				if (error != EINPROGRESS)
10814 					*outlenp = 0;
10815 				return (error);
10816 			}
10817 			/* OK return - copy input buffer into output buffer */
10818 			if (invalp != outvalp) {
10819 				bcopy(invalp, outvalp, inlen);
10820 			}
10821 			*outlenp = inlen;
10822 			return (0);
10823 		}
10824 		case IP_SEC_OPT:
10825 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10826 			if (error != 0) {
10827 				*outlenp = 0;
10828 				return (error);
10829 			}
10830 			break;
10831 		case IP_HDRINCL:
10832 		case IP_OPTIONS:
10833 		case T_IP_OPTIONS:
10834 		case IP_TOS:
10835 		case T_IP_TOS:
10836 		case IP_TTL:
10837 		case IP_RECVDSTADDR:
10838 		case IP_RECVOPTS:
10839 			/* OK return - copy input buffer into output buffer */
10840 			if (invalp != outvalp) {
10841 				/* don't trust bcopy for identical src/dst */
10842 				bcopy(invalp, outvalp, inlen);
10843 			}
10844 			*outlenp = inlen;
10845 			return (0);
10846 		case IP_RECVIF:
10847 			/* Retrieve the inbound interface index */
10848 			if (!checkonly) {
10849 				mutex_enter(&connp->conn_lock);
10850 				connp->conn_recvif = *i1 ? 1 : 0;
10851 				mutex_exit(&connp->conn_lock);
10852 			}
10853 			break;	/* goto sizeof (int) option return */
10854 		case IP_RECVSLLA:
10855 			/* Retrieve the source link layer address */
10856 			if (!checkonly) {
10857 				mutex_enter(&connp->conn_lock);
10858 				connp->conn_recvslla = *i1 ? 1 : 0;
10859 				mutex_exit(&connp->conn_lock);
10860 			}
10861 			break;	/* goto sizeof (int) option return */
10862 		case MRT_INIT:
10863 		case MRT_DONE:
10864 		case MRT_ADD_VIF:
10865 		case MRT_DEL_VIF:
10866 		case MRT_ADD_MFC:
10867 		case MRT_DEL_MFC:
10868 		case MRT_ASSERT:
10869 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10870 				*outlenp = 0;
10871 				return (error);
10872 			}
10873 			error = ip_mrouter_set((int)name, q, checkonly,
10874 			    (uchar_t *)invalp, inlen, first_mp);
10875 			if (error) {
10876 				*outlenp = 0;
10877 				return (error);
10878 			}
10879 			/* OK return - copy input buffer into output buffer */
10880 			if (invalp != outvalp) {
10881 				/* don't trust bcopy for identical src/dst */
10882 				bcopy(invalp, outvalp, inlen);
10883 			}
10884 			*outlenp = inlen;
10885 			return (0);
10886 		case IP_BOUND_IF:
10887 		case IP_XMIT_IF:
10888 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10889 			    level, name, first_mp);
10890 			if (error != 0)
10891 				return (error);
10892 			break; 		/* goto sizeof (int) option return */
10893 
10894 		case IP_UNSPEC_SRC:
10895 			/* Allow sending with a zero source address */
10896 			if (!checkonly) {
10897 				mutex_enter(&connp->conn_lock);
10898 				connp->conn_unspec_src = *i1 ? 1 : 0;
10899 				mutex_exit(&connp->conn_lock);
10900 			}
10901 			break;	/* goto sizeof (int) option return */
10902 		default:
10903 			/*
10904 			 * "soft" error (negative)
10905 			 * option not handled at this level
10906 			 * Note: Do not modify *outlenp
10907 			 */
10908 			return (-EINVAL);
10909 		}
10910 		break;
10911 	case IPPROTO_IPV6:
10912 		switch (name) {
10913 		case IPV6_BOUND_IF:
10914 		case IPV6_BOUND_PIF:
10915 		case IPV6_DONTFAILOVER_IF:
10916 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10917 			    level, name, first_mp);
10918 			if (error != 0)
10919 				return (error);
10920 			break; 		/* goto sizeof (int) option return */
10921 
10922 		case IPV6_MULTICAST_IF:
10923 			/*
10924 			 * The only possible errors are EINPROGRESS and
10925 			 * EINVAL. EINPROGRESS will be restarted and is not
10926 			 * a hard error. We call this option on both V4 and V6
10927 			 * If both return EINVAL, then this call returns
10928 			 * EINVAL. If at least one of them succeeds we
10929 			 * return success.
10930 			 */
10931 			found = B_FALSE;
10932 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10933 			    level, name, first_mp);
10934 			if (error == EINPROGRESS)
10935 				return (error);
10936 			if (error == 0)
10937 				found = B_TRUE;
10938 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10939 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10940 			if (error == 0)
10941 				found = B_TRUE;
10942 			if (!found)
10943 				return (error);
10944 			break; 		/* goto sizeof (int) option return */
10945 
10946 		case IPV6_MULTICAST_HOPS:
10947 			/* Recorded in transport above IP */
10948 			break;	/* goto sizeof (int) option return */
10949 		case IPV6_MULTICAST_LOOP:
10950 			if (!checkonly) {
10951 				mutex_enter(&connp->conn_lock);
10952 				connp->conn_multicast_loop = *i1;
10953 				mutex_exit(&connp->conn_lock);
10954 			}
10955 			break;	/* goto sizeof (int) option return */
10956 		case IPV6_JOIN_GROUP:
10957 		case MCAST_JOIN_GROUP:
10958 		case IPV6_LEAVE_GROUP:
10959 		case MCAST_LEAVE_GROUP: {
10960 			struct ipv6_mreq *ip_mreqp;
10961 			struct group_req *greqp;
10962 			ire_t *ire;
10963 			boolean_t done = B_FALSE;
10964 			in6_addr_t groupv6;
10965 			uint32_t ifindex;
10966 			boolean_t mcast_opt = B_TRUE;
10967 			mcast_record_t fmode;
10968 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10969 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10970 
10971 			switch (name) {
10972 			case IPV6_JOIN_GROUP:
10973 				mcast_opt = B_FALSE;
10974 				/* FALLTHRU */
10975 			case MCAST_JOIN_GROUP:
10976 				fmode = MODE_IS_EXCLUDE;
10977 				optfn = ip_opt_add_group_v6;
10978 				break;
10979 
10980 			case IPV6_LEAVE_GROUP:
10981 				mcast_opt = B_FALSE;
10982 				/* FALLTHRU */
10983 			case MCAST_LEAVE_GROUP:
10984 				fmode = MODE_IS_INCLUDE;
10985 				optfn = ip_opt_delete_group_v6;
10986 				break;
10987 			}
10988 
10989 			if (mcast_opt) {
10990 				struct sockaddr_in *sin;
10991 				struct sockaddr_in6 *sin6;
10992 				greqp = (struct group_req *)i1;
10993 				if (greqp->gr_group.ss_family == AF_INET) {
10994 					sin = (struct sockaddr_in *)
10995 					    &(greqp->gr_group);
10996 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10997 					    &groupv6);
10998 				} else {
10999 					sin6 = (struct sockaddr_in6 *)
11000 					    &(greqp->gr_group);
11001 					groupv6 = sin6->sin6_addr;
11002 				}
11003 				ifindex = greqp->gr_interface;
11004 			} else {
11005 				ip_mreqp = (struct ipv6_mreq *)i1;
11006 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11007 				ifindex = ip_mreqp->ipv6mr_interface;
11008 			}
11009 			/*
11010 			 * In the multirouting case, we need to replicate
11011 			 * the request on all interfaces that will take part
11012 			 * in replication.  We do so because multirouting is
11013 			 * reflective, thus we will probably receive multi-
11014 			 * casts on those interfaces.
11015 			 * The ip_multirt_apply_membership_v6() succeeds if
11016 			 * the operation succeeds on at least one interface.
11017 			 */
11018 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11019 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11020 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11021 			if (ire != NULL) {
11022 				if (ire->ire_flags & RTF_MULTIRT) {
11023 					error = ip_multirt_apply_membership_v6(
11024 					    optfn, ire, connp, checkonly,
11025 					    &groupv6, fmode, &ipv6_all_zeros,
11026 					    first_mp);
11027 					done = B_TRUE;
11028 				}
11029 				ire_refrele(ire);
11030 			}
11031 			if (!done) {
11032 				error = optfn(connp, checkonly, &groupv6,
11033 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11034 			}
11035 			if (error) {
11036 				/*
11037 				 * EINPROGRESS is a soft error, needs retry
11038 				 * so don't make *outlenp zero.
11039 				 */
11040 				if (error != EINPROGRESS)
11041 					*outlenp = 0;
11042 				return (error);
11043 			}
11044 			/* OK return - copy input buffer into output buffer */
11045 			if (invalp != outvalp) {
11046 				/* don't trust bcopy for identical src/dst */
11047 				bcopy(invalp, outvalp, inlen);
11048 			}
11049 			*outlenp = inlen;
11050 			return (0);
11051 		}
11052 		case MCAST_BLOCK_SOURCE:
11053 		case MCAST_UNBLOCK_SOURCE:
11054 		case MCAST_JOIN_SOURCE_GROUP:
11055 		case MCAST_LEAVE_SOURCE_GROUP: {
11056 			struct group_source_req *gsreqp;
11057 			in6_addr_t v6grp, v6src;
11058 			uint32_t ifindex;
11059 			mcast_record_t fmode;
11060 			ire_t *ire;
11061 			boolean_t done = B_FALSE;
11062 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11063 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11064 
11065 			switch (name) {
11066 			case MCAST_BLOCK_SOURCE:
11067 				fmode = MODE_IS_EXCLUDE;
11068 				optfn = ip_opt_add_group_v6;
11069 				break;
11070 			case MCAST_UNBLOCK_SOURCE:
11071 				fmode = MODE_IS_EXCLUDE;
11072 				optfn = ip_opt_delete_group_v6;
11073 				break;
11074 			case MCAST_JOIN_SOURCE_GROUP:
11075 				fmode = MODE_IS_INCLUDE;
11076 				optfn = ip_opt_add_group_v6;
11077 				break;
11078 			case MCAST_LEAVE_SOURCE_GROUP:
11079 				fmode = MODE_IS_INCLUDE;
11080 				optfn = ip_opt_delete_group_v6;
11081 				break;
11082 			}
11083 
11084 			gsreqp = (struct group_source_req *)i1;
11085 			ifindex = gsreqp->gsr_interface;
11086 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11087 				struct sockaddr_in *s;
11088 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11089 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11090 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11091 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11092 			} else {
11093 				struct sockaddr_in6 *s6;
11094 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11095 				v6grp = s6->sin6_addr;
11096 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11097 				v6src = s6->sin6_addr;
11098 			}
11099 
11100 			/*
11101 			 * In the multirouting case, we need to replicate
11102 			 * the request as noted in the mcast cases above.
11103 			 */
11104 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11105 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11106 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11107 			if (ire != NULL) {
11108 				if (ire->ire_flags & RTF_MULTIRT) {
11109 					error = ip_multirt_apply_membership_v6(
11110 					    optfn, ire, connp, checkonly,
11111 					    &v6grp, fmode, &v6src, first_mp);
11112 					done = B_TRUE;
11113 				}
11114 				ire_refrele(ire);
11115 			}
11116 			if (!done) {
11117 				error = optfn(connp, checkonly, &v6grp,
11118 				    ifindex, fmode, &v6src, first_mp);
11119 			}
11120 			if (error != 0) {
11121 				/*
11122 				 * EINPROGRESS is a soft error, needs retry
11123 				 * so don't make *outlenp zero.
11124 				 */
11125 				if (error != EINPROGRESS)
11126 					*outlenp = 0;
11127 				return (error);
11128 			}
11129 			/* OK return - copy input buffer into output buffer */
11130 			if (invalp != outvalp) {
11131 				bcopy(invalp, outvalp, inlen);
11132 			}
11133 			*outlenp = inlen;
11134 			return (0);
11135 		}
11136 		case IPV6_UNICAST_HOPS:
11137 			/* Recorded in transport above IP */
11138 			break;	/* goto sizeof (int) option return */
11139 		case IPV6_UNSPEC_SRC:
11140 			/* Allow sending with a zero source address */
11141 			if (!checkonly) {
11142 				mutex_enter(&connp->conn_lock);
11143 				connp->conn_unspec_src = *i1 ? 1 : 0;
11144 				mutex_exit(&connp->conn_lock);
11145 			}
11146 			break;	/* goto sizeof (int) option return */
11147 		case IPV6_RECVPKTINFO:
11148 			if (!checkonly) {
11149 				mutex_enter(&connp->conn_lock);
11150 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
11151 				mutex_exit(&connp->conn_lock);
11152 			}
11153 			break;	/* goto sizeof (int) option return */
11154 		case IPV6_RECVTCLASS:
11155 			if (!checkonly) {
11156 				if (*i1 < 0 || *i1 > 1) {
11157 					return (EINVAL);
11158 				}
11159 				mutex_enter(&connp->conn_lock);
11160 				connp->conn_ipv6_recvtclass = *i1;
11161 				mutex_exit(&connp->conn_lock);
11162 			}
11163 			break;
11164 		case IPV6_RECVPATHMTU:
11165 			if (!checkonly) {
11166 				if (*i1 < 0 || *i1 > 1) {
11167 					return (EINVAL);
11168 				}
11169 				mutex_enter(&connp->conn_lock);
11170 				connp->conn_ipv6_recvpathmtu = *i1;
11171 				mutex_exit(&connp->conn_lock);
11172 			}
11173 			break;
11174 		case IPV6_RECVHOPLIMIT:
11175 			if (!checkonly) {
11176 				mutex_enter(&connp->conn_lock);
11177 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11178 				mutex_exit(&connp->conn_lock);
11179 			}
11180 			break;	/* goto sizeof (int) option return */
11181 		case IPV6_RECVHOPOPTS:
11182 			if (!checkonly) {
11183 				mutex_enter(&connp->conn_lock);
11184 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11185 				mutex_exit(&connp->conn_lock);
11186 			}
11187 			break;	/* goto sizeof (int) option return */
11188 		case IPV6_RECVDSTOPTS:
11189 			if (!checkonly) {
11190 				mutex_enter(&connp->conn_lock);
11191 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11192 				mutex_exit(&connp->conn_lock);
11193 			}
11194 			break;	/* goto sizeof (int) option return */
11195 		case IPV6_RECVRTHDR:
11196 			if (!checkonly) {
11197 				mutex_enter(&connp->conn_lock);
11198 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11199 				mutex_exit(&connp->conn_lock);
11200 			}
11201 			break;	/* goto sizeof (int) option return */
11202 		case IPV6_RECVRTHDRDSTOPTS:
11203 			if (!checkonly) {
11204 				mutex_enter(&connp->conn_lock);
11205 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11206 				mutex_exit(&connp->conn_lock);
11207 			}
11208 			break;	/* goto sizeof (int) option return */
11209 		case IPV6_PKTINFO:
11210 			if (inlen == 0)
11211 				return (-EINVAL);	/* clearing option */
11212 			error = ip6_set_pktinfo(cr, connp,
11213 			    (struct in6_pktinfo *)invalp, first_mp);
11214 			if (error != 0)
11215 				*outlenp = 0;
11216 			else
11217 				*outlenp = inlen;
11218 			return (error);
11219 		case IPV6_NEXTHOP: {
11220 			struct sockaddr_in6 *sin6;
11221 
11222 			/* Verify that the nexthop is reachable */
11223 			if (inlen == 0)
11224 				return (-EINVAL);	/* clearing option */
11225 
11226 			sin6 = (struct sockaddr_in6 *)invalp;
11227 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11228 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11229 			    NULL, MATCH_IRE_DEFAULT);
11230 
11231 			if (ire == NULL) {
11232 				*outlenp = 0;
11233 				return (EHOSTUNREACH);
11234 			}
11235 			ire_refrele(ire);
11236 			return (-EINVAL);
11237 		}
11238 		case IPV6_SEC_OPT:
11239 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11240 			if (error != 0) {
11241 				*outlenp = 0;
11242 				return (error);
11243 			}
11244 			break;
11245 		case IPV6_SRC_PREFERENCES: {
11246 			/*
11247 			 * This is implemented strictly in the ip module
11248 			 * (here and in tcp_opt_*() to accomodate tcp
11249 			 * sockets).  Modules above ip pass this option
11250 			 * down here since ip is the only one that needs to
11251 			 * be aware of source address preferences.
11252 			 *
11253 			 * This socket option only affects connected
11254 			 * sockets that haven't already bound to a specific
11255 			 * IPv6 address.  In other words, sockets that
11256 			 * don't call bind() with an address other than the
11257 			 * unspecified address and that call connect().
11258 			 * ip_bind_connected_v6() passes these preferences
11259 			 * to the ipif_select_source_v6() function.
11260 			 */
11261 			if (inlen != sizeof (uint32_t))
11262 				return (EINVAL);
11263 			error = ip6_set_src_preferences(connp,
11264 			    *(uint32_t *)invalp);
11265 			if (error != 0) {
11266 				*outlenp = 0;
11267 				return (error);
11268 			} else {
11269 				*outlenp = sizeof (uint32_t);
11270 			}
11271 			break;
11272 		}
11273 		case IPV6_V6ONLY:
11274 			if (*i1 < 0 || *i1 > 1) {
11275 				return (EINVAL);
11276 			}
11277 			mutex_enter(&connp->conn_lock);
11278 			connp->conn_ipv6_v6only = *i1;
11279 			mutex_exit(&connp->conn_lock);
11280 			break;
11281 		default:
11282 			return (-EINVAL);
11283 		}
11284 		break;
11285 	default:
11286 		/*
11287 		 * "soft" error (negative)
11288 		 * option not handled at this level
11289 		 * Note: Do not modify *outlenp
11290 		 */
11291 		return (-EINVAL);
11292 	}
11293 	/*
11294 	 * Common case of return from an option that is sizeof (int)
11295 	 */
11296 	*(int *)outvalp = *i1;
11297 	*outlenp = sizeof (int);
11298 	return (0);
11299 }
11300 
11301 /*
11302  * This routine gets default values of certain options whose default
11303  * values are maintained by protocol specific code
11304  */
11305 /* ARGSUSED */
11306 int
11307 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11308 {
11309 	int *i1 = (int *)ptr;
11310 
11311 	switch (level) {
11312 	case IPPROTO_IP:
11313 		switch (name) {
11314 		case IP_MULTICAST_TTL:
11315 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11316 			return (sizeof (uchar_t));
11317 		case IP_MULTICAST_LOOP:
11318 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11319 			return (sizeof (uchar_t));
11320 		default:
11321 			return (-1);
11322 		}
11323 	case IPPROTO_IPV6:
11324 		switch (name) {
11325 		case IPV6_UNICAST_HOPS:
11326 			*i1 = ipv6_def_hops;
11327 			return (sizeof (int));
11328 		case IPV6_MULTICAST_HOPS:
11329 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11330 			return (sizeof (int));
11331 		case IPV6_MULTICAST_LOOP:
11332 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11333 			return (sizeof (int));
11334 		case IPV6_V6ONLY:
11335 			*i1 = 1;
11336 			return (sizeof (int));
11337 		default:
11338 			return (-1);
11339 		}
11340 	default:
11341 		return (-1);
11342 	}
11343 	/* NOTREACHED */
11344 }
11345 
11346 /*
11347  * Given a destination address and a pointer to where to put the information
11348  * this routine fills in the mtuinfo.
11349  */
11350 int
11351 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11352     struct ip6_mtuinfo *mtuinfo)
11353 {
11354 	ire_t *ire;
11355 
11356 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11357 		return (-1);
11358 
11359 	bzero(mtuinfo, sizeof (*mtuinfo));
11360 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11361 	mtuinfo->ip6m_addr.sin6_port = port;
11362 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11363 
11364 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11365 	if (ire != NULL) {
11366 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11367 		ire_refrele(ire);
11368 	} else {
11369 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11370 	}
11371 	return (sizeof (struct ip6_mtuinfo));
11372 }
11373 
11374 /*
11375  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11376  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11377  * isn't.  This doesn't matter as the error checking is done properly for the
11378  * other MRT options coming in through ip_opt_set.
11379  */
11380 int
11381 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11382 {
11383 	conn_t		*connp = Q_TO_CONN(q);
11384 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11385 
11386 	switch (level) {
11387 	case IPPROTO_IP:
11388 		switch (name) {
11389 		case MRT_VERSION:
11390 		case MRT_ASSERT:
11391 			(void) ip_mrouter_get(name, q, ptr);
11392 			return (sizeof (int));
11393 		case IP_SEC_OPT:
11394 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11395 		case IP_NEXTHOP:
11396 			if (connp->conn_nexthop_set) {
11397 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11398 				return (sizeof (ipaddr_t));
11399 			} else
11400 				return (0);
11401 		default:
11402 			break;
11403 		}
11404 		break;
11405 	case IPPROTO_IPV6:
11406 		switch (name) {
11407 		case IPV6_SEC_OPT:
11408 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11409 		case IPV6_SRC_PREFERENCES: {
11410 			return (ip6_get_src_preferences(connp,
11411 			    (uint32_t *)ptr));
11412 		}
11413 		case IPV6_V6ONLY:
11414 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11415 			return (sizeof (int));
11416 		case IPV6_PATHMTU:
11417 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11418 				(struct ip6_mtuinfo *)ptr));
11419 		default:
11420 			break;
11421 		}
11422 		break;
11423 	default:
11424 		break;
11425 	}
11426 	return (-1);
11427 }
11428 
11429 /* Named Dispatch routine to get a current value out of our parameter table. */
11430 /* ARGSUSED */
11431 static int
11432 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11433 {
11434 	ipparam_t *ippa = (ipparam_t *)cp;
11435 
11436 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11437 	return (0);
11438 }
11439 
11440 /* ARGSUSED */
11441 static int
11442 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11443 {
11444 
11445 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11446 	return (0);
11447 }
11448 
11449 /*
11450  * Set ip{,6}_forwarding values.  This means walking through all of the
11451  * ill's and toggling their forwarding values.
11452  */
11453 /* ARGSUSED */
11454 static int
11455 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11456 {
11457 	long new_value;
11458 	int *forwarding_value = (int *)cp;
11459 	ill_t *walker;
11460 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11461 	ill_walk_context_t ctx;
11462 
11463 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11464 	    new_value < 0 || new_value > 1) {
11465 		return (EINVAL);
11466 	}
11467 
11468 	*forwarding_value = new_value;
11469 
11470 	/*
11471 	 * Regardless of the current value of ip_forwarding, set all per-ill
11472 	 * values of ip_forwarding to the value being set.
11473 	 *
11474 	 * Bring all the ill's up to date with the new global value.
11475 	 */
11476 	rw_enter(&ill_g_lock, RW_READER);
11477 
11478 	if (isv6)
11479 		walker = ILL_START_WALK_V6(&ctx);
11480 	else
11481 		walker = ILL_START_WALK_V4(&ctx);
11482 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11483 		(void) ill_forward_set(q, mp, (new_value != 0),
11484 		    (caddr_t)walker);
11485 	}
11486 	rw_exit(&ill_g_lock);
11487 
11488 	return (0);
11489 }
11490 
11491 /*
11492  * Walk through the param array specified registering each element with the
11493  * Named Dispatch handler. This is called only during init. So it is ok
11494  * not to acquire any locks
11495  */
11496 static boolean_t
11497 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11498     ipndp_t *ipnd, size_t ipnd_cnt)
11499 {
11500 	for (; ippa_cnt-- > 0; ippa++) {
11501 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11502 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11503 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11504 				nd_free(&ip_g_nd);
11505 				return (B_FALSE);
11506 			}
11507 		}
11508 	}
11509 
11510 	for (; ipnd_cnt-- > 0; ipnd++) {
11511 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11512 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11513 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11514 			    ipnd->ip_ndp_data)) {
11515 				nd_free(&ip_g_nd);
11516 				return (B_FALSE);
11517 			}
11518 		}
11519 	}
11520 
11521 	return (B_TRUE);
11522 }
11523 
11524 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11525 /* ARGSUSED */
11526 static int
11527 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11528 {
11529 	long		new_value;
11530 	ipparam_t	*ippa = (ipparam_t *)cp;
11531 
11532 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11533 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11534 		return (EINVAL);
11535 	}
11536 	ippa->ip_param_value = new_value;
11537 	return (0);
11538 }
11539 
11540 /*
11541  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11542  * When an ipf is passed here for the first time, if
11543  * we already have in-order fragments on the queue, we convert from the fast-
11544  * path reassembly scheme to the hard-case scheme.  From then on, additional
11545  * fragments are reassembled here.  We keep track of the start and end offsets
11546  * of each piece, and the number of holes in the chain.  When the hole count
11547  * goes to zero, we are done!
11548  *
11549  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11550  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11551  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11552  * after the call to ip_reassemble().
11553  */
11554 int
11555 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11556     size_t msg_len)
11557 {
11558 	uint_t	end;
11559 	mblk_t	*next_mp;
11560 	mblk_t	*mp1;
11561 	uint_t	offset;
11562 	boolean_t incr_dups = B_TRUE;
11563 	boolean_t offset_zero_seen = B_FALSE;
11564 	boolean_t pkt_boundary_checked = B_FALSE;
11565 
11566 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11567 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11568 
11569 	/* Add in byte count */
11570 	ipf->ipf_count += msg_len;
11571 	if (ipf->ipf_end) {
11572 		/*
11573 		 * We were part way through in-order reassembly, but now there
11574 		 * is a hole.  We walk through messages already queued, and
11575 		 * mark them for hard case reassembly.  We know that up till
11576 		 * now they were in order starting from offset zero.
11577 		 */
11578 		offset = 0;
11579 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11580 			IP_REASS_SET_START(mp1, offset);
11581 			if (offset == 0) {
11582 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11583 				offset = -ipf->ipf_nf_hdr_len;
11584 			}
11585 			offset += mp1->b_wptr - mp1->b_rptr;
11586 			IP_REASS_SET_END(mp1, offset);
11587 		}
11588 		/* One hole at the end. */
11589 		ipf->ipf_hole_cnt = 1;
11590 		/* Brand it as a hard case, forever. */
11591 		ipf->ipf_end = 0;
11592 	}
11593 	/* Walk through all the new pieces. */
11594 	do {
11595 		end = start + (mp->b_wptr - mp->b_rptr);
11596 		/*
11597 		 * If start is 0, decrease 'end' only for the first mblk of
11598 		 * the fragment. Otherwise 'end' can get wrong value in the
11599 		 * second pass of the loop if first mblk is exactly the
11600 		 * size of ipf_nf_hdr_len.
11601 		 */
11602 		if (start == 0 && !offset_zero_seen) {
11603 			/* First segment */
11604 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11605 			end -= ipf->ipf_nf_hdr_len;
11606 			offset_zero_seen = B_TRUE;
11607 		}
11608 		next_mp = mp->b_cont;
11609 		/*
11610 		 * We are checking to see if there is any interesing data
11611 		 * to process.  If there isn't and the mblk isn't the
11612 		 * one which carries the unfragmentable header then we
11613 		 * drop it.  It's possible to have just the unfragmentable
11614 		 * header come through without any data.  That needs to be
11615 		 * saved.
11616 		 *
11617 		 * If the assert at the top of this function holds then the
11618 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11619 		 * is infrequently traveled enough that the test is left in
11620 		 * to protect against future code changes which break that
11621 		 * invariant.
11622 		 */
11623 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11624 			/* Empty.  Blast it. */
11625 			IP_REASS_SET_START(mp, 0);
11626 			IP_REASS_SET_END(mp, 0);
11627 			/*
11628 			 * If the ipf points to the mblk we are about to free,
11629 			 * update ipf to point to the next mblk (or NULL
11630 			 * if none).
11631 			 */
11632 			if (ipf->ipf_mp->b_cont == mp)
11633 				ipf->ipf_mp->b_cont = next_mp;
11634 			freeb(mp);
11635 			continue;
11636 		}
11637 		mp->b_cont = NULL;
11638 		IP_REASS_SET_START(mp, start);
11639 		IP_REASS_SET_END(mp, end);
11640 		if (!ipf->ipf_tail_mp) {
11641 			ipf->ipf_tail_mp = mp;
11642 			ipf->ipf_mp->b_cont = mp;
11643 			if (start == 0 || !more) {
11644 				ipf->ipf_hole_cnt = 1;
11645 				/*
11646 				 * if the first fragment comes in more than one
11647 				 * mblk, this loop will be executed for each
11648 				 * mblk. Need to adjust hole count so exiting
11649 				 * this routine will leave hole count at 1.
11650 				 */
11651 				if (next_mp)
11652 					ipf->ipf_hole_cnt++;
11653 			} else
11654 				ipf->ipf_hole_cnt = 2;
11655 			continue;
11656 		} else if (ipf->ipf_last_frag_seen && !more &&
11657 			    !pkt_boundary_checked) {
11658 			/*
11659 			 * We check datagram boundary only if this fragment
11660 			 * claims to be the last fragment and we have seen a
11661 			 * last fragment in the past too. We do this only
11662 			 * once for a given fragment.
11663 			 *
11664 			 * start cannot be 0 here as fragments with start=0
11665 			 * and MF=0 gets handled as a complete packet. These
11666 			 * fragments should not reach here.
11667 			 */
11668 
11669 			if (start + msgdsize(mp) !=
11670 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11671 				/*
11672 				 * We have two fragments both of which claim
11673 				 * to be the last fragment but gives conflicting
11674 				 * information about the whole datagram size.
11675 				 * Something fishy is going on. Drop the
11676 				 * fragment and free up the reassembly list.
11677 				 */
11678 				return (IP_REASS_FAILED);
11679 			}
11680 
11681 			/*
11682 			 * We shouldn't come to this code block again for this
11683 			 * particular fragment.
11684 			 */
11685 			pkt_boundary_checked = B_TRUE;
11686 		}
11687 
11688 		/* New stuff at or beyond tail? */
11689 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11690 		if (start >= offset) {
11691 			if (ipf->ipf_last_frag_seen) {
11692 				/* current fragment is beyond last fragment */
11693 				return (IP_REASS_FAILED);
11694 			}
11695 			/* Link it on end. */
11696 			ipf->ipf_tail_mp->b_cont = mp;
11697 			ipf->ipf_tail_mp = mp;
11698 			if (more) {
11699 				if (start != offset)
11700 					ipf->ipf_hole_cnt++;
11701 			} else if (start == offset && next_mp == NULL)
11702 					ipf->ipf_hole_cnt--;
11703 			continue;
11704 		}
11705 		mp1 = ipf->ipf_mp->b_cont;
11706 		offset = IP_REASS_START(mp1);
11707 		/* New stuff at the front? */
11708 		if (start < offset) {
11709 			if (start == 0) {
11710 				if (end >= offset) {
11711 					/* Nailed the hole at the begining. */
11712 					ipf->ipf_hole_cnt--;
11713 				}
11714 			} else if (end < offset) {
11715 				/*
11716 				 * A hole, stuff, and a hole where there used
11717 				 * to be just a hole.
11718 				 */
11719 				ipf->ipf_hole_cnt++;
11720 			}
11721 			mp->b_cont = mp1;
11722 			/* Check for overlap. */
11723 			while (end > offset) {
11724 				if (end < IP_REASS_END(mp1)) {
11725 					mp->b_wptr -= end - offset;
11726 					IP_REASS_SET_END(mp, offset);
11727 					if (ill->ill_isv6) {
11728 						BUMP_MIB(ill->ill_ip6_mib,
11729 						    ipv6ReasmPartDups);
11730 					} else {
11731 						BUMP_MIB(&ip_mib,
11732 						    ipReasmPartDups);
11733 					}
11734 					break;
11735 				}
11736 				/* Did we cover another hole? */
11737 				if ((mp1->b_cont &&
11738 				    IP_REASS_END(mp1) !=
11739 				    IP_REASS_START(mp1->b_cont) &&
11740 				    end >= IP_REASS_START(mp1->b_cont)) ||
11741 				    (!ipf->ipf_last_frag_seen && !more)) {
11742 					ipf->ipf_hole_cnt--;
11743 				}
11744 				/* Clip out mp1. */
11745 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11746 					/*
11747 					 * After clipping out mp1, this guy
11748 					 * is now hanging off the end.
11749 					 */
11750 					ipf->ipf_tail_mp = mp;
11751 				}
11752 				IP_REASS_SET_START(mp1, 0);
11753 				IP_REASS_SET_END(mp1, 0);
11754 				/* Subtract byte count */
11755 				ipf->ipf_count -= mp1->b_datap->db_lim -
11756 				    mp1->b_datap->db_base;
11757 				freeb(mp1);
11758 				if (ill->ill_isv6) {
11759 					BUMP_MIB(ill->ill_ip6_mib,
11760 					    ipv6ReasmPartDups);
11761 				} else {
11762 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11763 				}
11764 				mp1 = mp->b_cont;
11765 				if (!mp1)
11766 					break;
11767 				offset = IP_REASS_START(mp1);
11768 			}
11769 			ipf->ipf_mp->b_cont = mp;
11770 			continue;
11771 		}
11772 		/*
11773 		 * The new piece starts somewhere between the start of the head
11774 		 * and before the end of the tail.
11775 		 */
11776 		for (; mp1; mp1 = mp1->b_cont) {
11777 			offset = IP_REASS_END(mp1);
11778 			if (start < offset) {
11779 				if (end <= offset) {
11780 					/* Nothing new. */
11781 					IP_REASS_SET_START(mp, 0);
11782 					IP_REASS_SET_END(mp, 0);
11783 					/* Subtract byte count */
11784 					ipf->ipf_count -= mp->b_datap->db_lim -
11785 					    mp->b_datap->db_base;
11786 					if (incr_dups) {
11787 						ipf->ipf_num_dups++;
11788 						incr_dups = B_FALSE;
11789 					}
11790 					freeb(mp);
11791 					if (ill->ill_isv6) {
11792 						BUMP_MIB(ill->ill_ip6_mib,
11793 						    ipv6ReasmDuplicates);
11794 					} else {
11795 						BUMP_MIB(&ip_mib,
11796 						    ipReasmDuplicates);
11797 					}
11798 					break;
11799 				}
11800 				/*
11801 				 * Trim redundant stuff off beginning of new
11802 				 * piece.
11803 				 */
11804 				IP_REASS_SET_START(mp, offset);
11805 				mp->b_rptr += offset - start;
11806 				if (ill->ill_isv6) {
11807 					BUMP_MIB(ill->ill_ip6_mib,
11808 					    ipv6ReasmPartDups);
11809 				} else {
11810 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11811 				}
11812 				start = offset;
11813 				if (!mp1->b_cont) {
11814 					/*
11815 					 * After trimming, this guy is now
11816 					 * hanging off the end.
11817 					 */
11818 					mp1->b_cont = mp;
11819 					ipf->ipf_tail_mp = mp;
11820 					if (!more) {
11821 						ipf->ipf_hole_cnt--;
11822 					}
11823 					break;
11824 				}
11825 			}
11826 			if (start >= IP_REASS_START(mp1->b_cont))
11827 				continue;
11828 			/* Fill a hole */
11829 			if (start > offset)
11830 				ipf->ipf_hole_cnt++;
11831 			mp->b_cont = mp1->b_cont;
11832 			mp1->b_cont = mp;
11833 			mp1 = mp->b_cont;
11834 			offset = IP_REASS_START(mp1);
11835 			if (end >= offset) {
11836 				ipf->ipf_hole_cnt--;
11837 				/* Check for overlap. */
11838 				while (end > offset) {
11839 					if (end < IP_REASS_END(mp1)) {
11840 						mp->b_wptr -= end - offset;
11841 						IP_REASS_SET_END(mp, offset);
11842 						/*
11843 						 * TODO we might bump
11844 						 * this up twice if there is
11845 						 * overlap at both ends.
11846 						 */
11847 						if (ill->ill_isv6) {
11848 							BUMP_MIB(
11849 							    ill->ill_ip6_mib,
11850 							    ipv6ReasmPartDups);
11851 						} else {
11852 							BUMP_MIB(&ip_mib,
11853 							    ipReasmPartDups);
11854 						}
11855 						break;
11856 					}
11857 					/* Did we cover another hole? */
11858 					if ((mp1->b_cont &&
11859 					    IP_REASS_END(mp1)
11860 					    != IP_REASS_START(mp1->b_cont) &&
11861 					    end >=
11862 					    IP_REASS_START(mp1->b_cont)) ||
11863 					    (!ipf->ipf_last_frag_seen &&
11864 					    !more)) {
11865 						ipf->ipf_hole_cnt--;
11866 					}
11867 					/* Clip out mp1. */
11868 					if ((mp->b_cont = mp1->b_cont) ==
11869 					    NULL) {
11870 						/*
11871 						 * After clipping out mp1,
11872 						 * this guy is now hanging
11873 						 * off the end.
11874 						 */
11875 						ipf->ipf_tail_mp = mp;
11876 					}
11877 					IP_REASS_SET_START(mp1, 0);
11878 					IP_REASS_SET_END(mp1, 0);
11879 					/* Subtract byte count */
11880 					ipf->ipf_count -=
11881 					    mp1->b_datap->db_lim -
11882 					    mp1->b_datap->db_base;
11883 					freeb(mp1);
11884 					if (ill->ill_isv6) {
11885 						BUMP_MIB(ill->ill_ip6_mib,
11886 						    ipv6ReasmPartDups);
11887 					} else {
11888 						BUMP_MIB(&ip_mib,
11889 						    ipReasmPartDups);
11890 					}
11891 					mp1 = mp->b_cont;
11892 					if (!mp1)
11893 						break;
11894 					offset = IP_REASS_START(mp1);
11895 				}
11896 			}
11897 			break;
11898 		}
11899 	} while (start = end, mp = next_mp);
11900 
11901 	/* Fragment just processed could be the last one. Remember this fact */
11902 	if (!more)
11903 		ipf->ipf_last_frag_seen = B_TRUE;
11904 
11905 	/* Still got holes? */
11906 	if (ipf->ipf_hole_cnt)
11907 		return (IP_REASS_PARTIAL);
11908 	/* Clean up overloaded fields to avoid upstream disasters. */
11909 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11910 		IP_REASS_SET_START(mp1, 0);
11911 		IP_REASS_SET_END(mp1, 0);
11912 	}
11913 	return (IP_REASS_COMPLETE);
11914 }
11915 
11916 /*
11917  * ipsec processing for the fast path, used for input UDP Packets
11918  */
11919 static boolean_t
11920 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11921     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11922 {
11923 	uint32_t	ill_index;
11924 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11925 
11926 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11927 	/* The ill_index of the incoming ILL */
11928 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11929 
11930 	/* pass packet up to the transport */
11931 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11932 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11933 		    NULL, mctl_present);
11934 		if (*first_mpp == NULL) {
11935 			return (B_FALSE);
11936 		}
11937 	}
11938 
11939 	/* Initiate IPPF processing for fastpath UDP */
11940 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11941 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11942 		if (*mpp == NULL) {
11943 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11944 			    "deferred/dropped during IPPF processing\n"));
11945 			return (B_FALSE);
11946 		}
11947 	}
11948 	/*
11949 	 * We make the checks as below since we are in the fast path
11950 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11951 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11952 	 */
11953 	if (connp->conn_recvif || connp->conn_recvslla ||
11954 	    connp->conn_ipv6_recvpktinfo) {
11955 		if (connp->conn_recvif ||
11956 		    connp->conn_ipv6_recvpktinfo) {
11957 			in_flags = IPF_RECVIF;
11958 		}
11959 		if (connp->conn_recvslla) {
11960 			in_flags |= IPF_RECVSLLA;
11961 		}
11962 		/*
11963 		 * since in_flags are being set ill will be
11964 		 * referenced in ip_add_info, so it better not
11965 		 * be NULL.
11966 		 */
11967 		/*
11968 		 * the actual data will be contained in b_cont
11969 		 * upon successful return of the following call.
11970 		 * If the call fails then the original mblk is
11971 		 * returned.
11972 		 */
11973 		*mpp = ip_add_info(*mpp, ill, in_flags);
11974 	}
11975 
11976 	return (B_TRUE);
11977 }
11978 
11979 /*
11980  * Fragmentation reassembly.  Each ILL has a hash table for
11981  * queuing packets undergoing reassembly for all IPIFs
11982  * associated with the ILL.  The hash is based on the packet
11983  * IP ident field.  The ILL frag hash table was allocated
11984  * as a timer block at the time the ILL was created.  Whenever
11985  * there is anything on the reassembly queue, the timer will
11986  * be running.  Returns B_TRUE if successful else B_FALSE;
11987  * frees mp on failure.
11988  */
11989 static boolean_t
11990 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11991     uint32_t *cksum_val, uint16_t *cksum_flags)
11992 {
11993 	uint32_t	frag_offset_flags;
11994 	ill_t		*ill = (ill_t *)q->q_ptr;
11995 	mblk_t		*mp = *mpp;
11996 	mblk_t		*t_mp;
11997 	ipaddr_t	dst;
11998 	uint8_t		proto = ipha->ipha_protocol;
11999 	uint32_t	sum_val;
12000 	uint16_t	sum_flags;
12001 	ipf_t		*ipf;
12002 	ipf_t		**ipfp;
12003 	ipfb_t		*ipfb;
12004 	uint16_t	ident;
12005 	uint32_t	offset;
12006 	ipaddr_t	src;
12007 	uint_t		hdr_length;
12008 	uint32_t	end;
12009 	mblk_t		*mp1;
12010 	mblk_t		*tail_mp;
12011 	size_t		count;
12012 	size_t		msg_len;
12013 	uint8_t		ecn_info = 0;
12014 	uint32_t	packet_size;
12015 	boolean_t	pruned = B_FALSE;
12016 
12017 	if (cksum_val != NULL)
12018 		*cksum_val = 0;
12019 	if (cksum_flags != NULL)
12020 		*cksum_flags = 0;
12021 
12022 	/*
12023 	 * Drop the fragmented as early as possible, if
12024 	 * we don't have resource(s) to re-assemble.
12025 	 */
12026 	if (ip_reass_queue_bytes == 0) {
12027 		freemsg(mp);
12028 		return (B_FALSE);
12029 	}
12030 
12031 	/* Check for fragmentation offset; return if there's none */
12032 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12033 	    (IPH_MF | IPH_OFFSET)) == 0)
12034 		return (B_TRUE);
12035 
12036 	/*
12037 	 * We utilize hardware computed checksum info only for UDP since
12038 	 * IP fragmentation is a normal occurence for the protocol.  In
12039 	 * addition, checksum offload support for IP fragments carrying
12040 	 * UDP payload is commonly implemented across network adapters.
12041 	 */
12042 	ASSERT(ill != NULL);
12043 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12044 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12045 		mblk_t *mp1 = mp->b_cont;
12046 		int32_t len;
12047 
12048 		/* Record checksum information from the packet */
12049 		sum_val = (uint32_t)DB_CKSUM16(mp);
12050 		sum_flags = DB_CKSUMFLAGS(mp);
12051 
12052 		/* IP payload offset from beginning of mblk */
12053 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12054 
12055 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12056 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12057 		    offset >= DB_CKSUMSTART(mp) &&
12058 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12059 			uint32_t adj;
12060 			/*
12061 			 * Partial checksum has been calculated by hardware
12062 			 * and attached to the packet; in addition, any
12063 			 * prepended extraneous data is even byte aligned.
12064 			 * If any such data exists, we adjust the checksum;
12065 			 * this would also handle any postpended data.
12066 			 */
12067 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12068 			    mp, mp1, len, adj);
12069 
12070 			/* One's complement subtract extraneous checksum */
12071 			if (adj >= sum_val)
12072 				sum_val = ~(adj - sum_val) & 0xFFFF;
12073 			else
12074 				sum_val -= adj;
12075 		}
12076 	} else {
12077 		sum_val = 0;
12078 		sum_flags = 0;
12079 	}
12080 
12081 	/* Clear hardware checksumming flag */
12082 	DB_CKSUMFLAGS(mp) = 0;
12083 
12084 	ident = ipha->ipha_ident;
12085 	offset = (frag_offset_flags << 3) & 0xFFFF;
12086 	src = ipha->ipha_src;
12087 	dst = ipha->ipha_dst;
12088 	hdr_length = IPH_HDR_LENGTH(ipha);
12089 	end = ntohs(ipha->ipha_length) - hdr_length;
12090 
12091 	/* If end == 0 then we have a packet with no data, so just free it */
12092 	if (end == 0) {
12093 		freemsg(mp);
12094 		return (B_FALSE);
12095 	}
12096 
12097 	/* Record the ECN field info. */
12098 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12099 	if (offset != 0) {
12100 		/*
12101 		 * If this isn't the first piece, strip the header, and
12102 		 * add the offset to the end value.
12103 		 */
12104 		mp->b_rptr += hdr_length;
12105 		end += offset;
12106 	}
12107 
12108 	msg_len = MBLKSIZE(mp);
12109 	tail_mp = mp;
12110 	while (tail_mp->b_cont != NULL) {
12111 		tail_mp = tail_mp->b_cont;
12112 		msg_len += MBLKSIZE(tail_mp);
12113 	}
12114 
12115 	/* If the reassembly list for this ILL will get too big, prune it */
12116 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12117 	    ip_reass_queue_bytes) {
12118 		ill_frag_prune(ill,
12119 		    (ip_reass_queue_bytes < msg_len) ? 0 :
12120 		    (ip_reass_queue_bytes - msg_len));
12121 		pruned = B_TRUE;
12122 	}
12123 
12124 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12125 	mutex_enter(&ipfb->ipfb_lock);
12126 
12127 	ipfp = &ipfb->ipfb_ipf;
12128 	/* Try to find an existing fragment queue for this packet. */
12129 	for (;;) {
12130 		ipf = ipfp[0];
12131 		if (ipf != NULL) {
12132 			/*
12133 			 * It has to match on ident and src/dst address.
12134 			 */
12135 			if (ipf->ipf_ident == ident &&
12136 			    ipf->ipf_src == src &&
12137 			    ipf->ipf_dst == dst &&
12138 			    ipf->ipf_protocol == proto) {
12139 				/*
12140 				 * If we have received too many
12141 				 * duplicate fragments for this packet
12142 				 * free it.
12143 				 */
12144 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12145 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12146 					freemsg(mp);
12147 					mutex_exit(&ipfb->ipfb_lock);
12148 					return (B_FALSE);
12149 				}
12150 				/* Found it. */
12151 				break;
12152 			}
12153 			ipfp = &ipf->ipf_hash_next;
12154 			continue;
12155 		}
12156 
12157 		/*
12158 		 * If we pruned the list, do we want to store this new
12159 		 * fragment?. We apply an optimization here based on the
12160 		 * fact that most fragments will be received in order.
12161 		 * So if the offset of this incoming fragment is zero,
12162 		 * it is the first fragment of a new packet. We will
12163 		 * keep it.  Otherwise drop the fragment, as we have
12164 		 * probably pruned the packet already (since the
12165 		 * packet cannot be found).
12166 		 */
12167 		if (pruned && offset != 0) {
12168 			mutex_exit(&ipfb->ipfb_lock);
12169 			freemsg(mp);
12170 			return (B_FALSE);
12171 		}
12172 
12173 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12174 			/*
12175 			 * Too many fragmented packets in this hash
12176 			 * bucket. Free the oldest.
12177 			 */
12178 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12179 		}
12180 
12181 		/* New guy.  Allocate a frag message. */
12182 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12183 		if (mp1 == NULL) {
12184 			BUMP_MIB(&ip_mib, ipInDiscards);
12185 			freemsg(mp);
12186 reass_done:
12187 			mutex_exit(&ipfb->ipfb_lock);
12188 			return (B_FALSE);
12189 		}
12190 
12191 
12192 		BUMP_MIB(&ip_mib, ipReasmReqds);
12193 		mp1->b_cont = mp;
12194 
12195 		/* Initialize the fragment header. */
12196 		ipf = (ipf_t *)mp1->b_rptr;
12197 		ipf->ipf_mp = mp1;
12198 		ipf->ipf_ptphn = ipfp;
12199 		ipfp[0] = ipf;
12200 		ipf->ipf_hash_next = NULL;
12201 		ipf->ipf_ident = ident;
12202 		ipf->ipf_protocol = proto;
12203 		ipf->ipf_src = src;
12204 		ipf->ipf_dst = dst;
12205 		ipf->ipf_nf_hdr_len = 0;
12206 		/* Record reassembly start time. */
12207 		ipf->ipf_timestamp = gethrestime_sec();
12208 		/* Record ipf generation and account for frag header */
12209 		ipf->ipf_gen = ill->ill_ipf_gen++;
12210 		ipf->ipf_count = MBLKSIZE(mp1);
12211 		ipf->ipf_last_frag_seen = B_FALSE;
12212 		ipf->ipf_ecn = ecn_info;
12213 		ipf->ipf_num_dups = 0;
12214 		ipfb->ipfb_frag_pkts++;
12215 		ipf->ipf_checksum = 0;
12216 		ipf->ipf_checksum_flags = 0;
12217 
12218 		/* Store checksum value in fragment header */
12219 		if (sum_flags != 0) {
12220 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12221 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12222 			ipf->ipf_checksum = sum_val;
12223 			ipf->ipf_checksum_flags = sum_flags;
12224 		}
12225 
12226 		/*
12227 		 * We handle reassembly two ways.  In the easy case,
12228 		 * where all the fragments show up in order, we do
12229 		 * minimal bookkeeping, and just clip new pieces on
12230 		 * the end.  If we ever see a hole, then we go off
12231 		 * to ip_reassemble which has to mark the pieces and
12232 		 * keep track of the number of holes, etc.  Obviously,
12233 		 * the point of having both mechanisms is so we can
12234 		 * handle the easy case as efficiently as possible.
12235 		 */
12236 		if (offset == 0) {
12237 			/* Easy case, in-order reassembly so far. */
12238 			ipf->ipf_count += msg_len;
12239 			ipf->ipf_tail_mp = tail_mp;
12240 			/*
12241 			 * Keep track of next expected offset in
12242 			 * ipf_end.
12243 			 */
12244 			ipf->ipf_end = end;
12245 			ipf->ipf_nf_hdr_len = hdr_length;
12246 		} else {
12247 			/* Hard case, hole at the beginning. */
12248 			ipf->ipf_tail_mp = NULL;
12249 			/*
12250 			 * ipf_end == 0 means that we have given up
12251 			 * on easy reassembly.
12252 			 */
12253 			ipf->ipf_end = 0;
12254 
12255 			/* Forget checksum offload from now on */
12256 			ipf->ipf_checksum_flags = 0;
12257 
12258 			/*
12259 			 * ipf_hole_cnt is set by ip_reassemble.
12260 			 * ipf_count is updated by ip_reassemble.
12261 			 * No need to check for return value here
12262 			 * as we don't expect reassembly to complete
12263 			 * or fail for the first fragment itself.
12264 			 */
12265 			(void) ip_reassemble(mp, ipf,
12266 			    (frag_offset_flags & IPH_OFFSET) << 3,
12267 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12268 		}
12269 		/* Update per ipfb and ill byte counts */
12270 		ipfb->ipfb_count += ipf->ipf_count;
12271 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12272 		ill->ill_frag_count += ipf->ipf_count;
12273 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12274 		/* If the frag timer wasn't already going, start it. */
12275 		mutex_enter(&ill->ill_lock);
12276 		ill_frag_timer_start(ill);
12277 		mutex_exit(&ill->ill_lock);
12278 		goto reass_done;
12279 	}
12280 
12281 	/*
12282 	 * If the packet's flag has changed (it could be coming up
12283 	 * from an interface different than the previous, therefore
12284 	 * possibly different checksum capability), then forget about
12285 	 * any stored checksum states.  Otherwise add the value to
12286 	 * the existing one stored in the fragment header.
12287 	 */
12288 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12289 		sum_val += ipf->ipf_checksum;
12290 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12291 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12292 		ipf->ipf_checksum = sum_val;
12293 	} else if (ipf->ipf_checksum_flags != 0) {
12294 		/* Forget checksum offload from now on */
12295 		ipf->ipf_checksum_flags = 0;
12296 	}
12297 
12298 	/*
12299 	 * We have a new piece of a datagram which is already being
12300 	 * reassembled.  Update the ECN info if all IP fragments
12301 	 * are ECN capable.  If there is one which is not, clear
12302 	 * all the info.  If there is at least one which has CE
12303 	 * code point, IP needs to report that up to transport.
12304 	 */
12305 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12306 		if (ecn_info == IPH_ECN_CE)
12307 			ipf->ipf_ecn = IPH_ECN_CE;
12308 	} else {
12309 		ipf->ipf_ecn = IPH_ECN_NECT;
12310 	}
12311 	if (offset && ipf->ipf_end == offset) {
12312 		/* The new fragment fits at the end */
12313 		ipf->ipf_tail_mp->b_cont = mp;
12314 		/* Update the byte count */
12315 		ipf->ipf_count += msg_len;
12316 		/* Update per ipfb and ill byte counts */
12317 		ipfb->ipfb_count += msg_len;
12318 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12319 		ill->ill_frag_count += msg_len;
12320 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12321 		if (frag_offset_flags & IPH_MF) {
12322 			/* More to come. */
12323 			ipf->ipf_end = end;
12324 			ipf->ipf_tail_mp = tail_mp;
12325 			goto reass_done;
12326 		}
12327 	} else {
12328 		/* Go do the hard cases. */
12329 		int ret;
12330 
12331 		if (offset == 0)
12332 			ipf->ipf_nf_hdr_len = hdr_length;
12333 
12334 		/* Save current byte count */
12335 		count = ipf->ipf_count;
12336 		ret = ip_reassemble(mp, ipf,
12337 		    (frag_offset_flags & IPH_OFFSET) << 3,
12338 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12339 		/* Count of bytes added and subtracted (freeb()ed) */
12340 		count = ipf->ipf_count - count;
12341 		if (count) {
12342 			/* Update per ipfb and ill byte counts */
12343 			ipfb->ipfb_count += count;
12344 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12345 			ill->ill_frag_count += count;
12346 			ASSERT(ill->ill_frag_count > 0);
12347 		}
12348 		if (ret == IP_REASS_PARTIAL) {
12349 			goto reass_done;
12350 		} else if (ret == IP_REASS_FAILED) {
12351 			/* Reassembly failed. Free up all resources */
12352 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12353 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12354 				IP_REASS_SET_START(t_mp, 0);
12355 				IP_REASS_SET_END(t_mp, 0);
12356 			}
12357 			freemsg(mp);
12358 			goto reass_done;
12359 		}
12360 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12361 	}
12362 	/*
12363 	 * We have completed reassembly.  Unhook the frag header from
12364 	 * the reassembly list.
12365 	 *
12366 	 * Before we free the frag header, record the ECN info
12367 	 * to report back to the transport.
12368 	 */
12369 	ecn_info = ipf->ipf_ecn;
12370 	BUMP_MIB(&ip_mib, ipReasmOKs);
12371 	ipfp = ipf->ipf_ptphn;
12372 
12373 	/* We need to supply these to caller */
12374 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12375 		sum_val = ipf->ipf_checksum;
12376 	else
12377 		sum_val = 0;
12378 
12379 	mp1 = ipf->ipf_mp;
12380 	count = ipf->ipf_count;
12381 	ipf = ipf->ipf_hash_next;
12382 	if (ipf != NULL)
12383 		ipf->ipf_ptphn = ipfp;
12384 	ipfp[0] = ipf;
12385 	ill->ill_frag_count -= count;
12386 	ASSERT(ipfb->ipfb_count >= count);
12387 	ipfb->ipfb_count -= count;
12388 	ipfb->ipfb_frag_pkts--;
12389 	mutex_exit(&ipfb->ipfb_lock);
12390 	/* Ditch the frag header. */
12391 	mp = mp1->b_cont;
12392 
12393 	freeb(mp1);
12394 
12395 	/* Restore original IP length in header. */
12396 	packet_size = (uint32_t)msgdsize(mp);
12397 	if (packet_size > IP_MAXPACKET) {
12398 		freemsg(mp);
12399 		BUMP_MIB(&ip_mib, ipInHdrErrors);
12400 		return (B_FALSE);
12401 	}
12402 
12403 	if (DB_REF(mp) > 1) {
12404 		mblk_t *mp2 = copymsg(mp);
12405 
12406 		freemsg(mp);
12407 		if (mp2 == NULL) {
12408 			BUMP_MIB(&ip_mib, ipInDiscards);
12409 			return (B_FALSE);
12410 		}
12411 		mp = mp2;
12412 	}
12413 	ipha = (ipha_t *)mp->b_rptr;
12414 
12415 	ipha->ipha_length = htons((uint16_t)packet_size);
12416 	/* We're now complete, zip the frag state */
12417 	ipha->ipha_fragment_offset_and_flags = 0;
12418 	/* Record the ECN info. */
12419 	ipha->ipha_type_of_service &= 0xFC;
12420 	ipha->ipha_type_of_service |= ecn_info;
12421 	*mpp = mp;
12422 
12423 	/* Reassembly is successful; return checksum information if needed */
12424 	if (cksum_val != NULL)
12425 		*cksum_val = sum_val;
12426 	if (cksum_flags != NULL)
12427 		*cksum_flags = sum_flags;
12428 
12429 	return (B_TRUE);
12430 }
12431 
12432 /*
12433  * Perform ip header check sum update local options.
12434  * return B_TRUE if all is well, else return B_FALSE and release
12435  * the mp. caller is responsible for decrementing ire ref cnt.
12436  */
12437 static boolean_t
12438 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12439 {
12440 	mblk_t		*first_mp;
12441 	boolean_t	mctl_present;
12442 	uint16_t	sum;
12443 
12444 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12445 	/*
12446 	 * Don't do the checksum if it has gone through AH/ESP
12447 	 * processing.
12448 	 */
12449 	if (!mctl_present) {
12450 		sum = ip_csum_hdr(ipha);
12451 		if (sum != 0) {
12452 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12453 			freemsg(first_mp);
12454 			return (B_FALSE);
12455 		}
12456 	}
12457 
12458 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12459 		if (mctl_present)
12460 			freeb(first_mp);
12461 		return (B_FALSE);
12462 	}
12463 
12464 	return (B_TRUE);
12465 }
12466 
12467 /*
12468  * All udp packet are delivered to the local host via this routine.
12469  */
12470 void
12471 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12472     ill_t *recv_ill)
12473 {
12474 	uint32_t	sum;
12475 	uint32_t	u1;
12476 	boolean_t	mctl_present;
12477 	conn_t		*connp;
12478 	mblk_t		*first_mp;
12479 	uint16_t	*up;
12480 	ill_t		*ill = (ill_t *)q->q_ptr;
12481 	uint16_t	reass_hck_flags = 0;
12482 
12483 #define	rptr    ((uchar_t *)ipha)
12484 
12485 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12486 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12487 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12488 
12489 	/*
12490 	 * FAST PATH for udp packets
12491 	 */
12492 
12493 	/* u1 is # words of IP options */
12494 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12495 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12496 
12497 	/* IP options present */
12498 	if (u1 != 0)
12499 		goto ipoptions;
12500 
12501 	/* Check the IP header checksum.  */
12502 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12503 		/* Clear the IP header h/w cksum flag */
12504 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12505 	} else {
12506 #define	uph	((uint16_t *)ipha)
12507 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12508 		    uph[6] + uph[7] + uph[8] + uph[9];
12509 #undef	uph
12510 		/* finish doing IP checksum */
12511 		sum = (sum & 0xFFFF) + (sum >> 16);
12512 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12513 		/*
12514 		 * Don't verify header checksum if this packet is coming
12515 		 * back from AH/ESP as we already did it.
12516 		 */
12517 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12518 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12519 			freemsg(first_mp);
12520 			return;
12521 		}
12522 	}
12523 
12524 	/*
12525 	 * Count for SNMP of inbound packets for ire.
12526 	 * if mctl is present this might be a secure packet and
12527 	 * has already been counted for in ip_proto_input().
12528 	 */
12529 	if (!mctl_present) {
12530 		UPDATE_IB_PKT_COUNT(ire);
12531 		ire->ire_last_used_time = lbolt;
12532 	}
12533 
12534 	/* packet part of fragmented IP packet? */
12535 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12536 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12537 		goto fragmented;
12538 	}
12539 
12540 	/* u1 = IP header length (20 bytes) */
12541 	u1 = IP_SIMPLE_HDR_LENGTH;
12542 
12543 	/* packet does not contain complete IP & UDP headers */
12544 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12545 		goto udppullup;
12546 
12547 	/* up points to UDP header */
12548 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12549 #define	iphs    ((uint16_t *)ipha)
12550 
12551 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12552 	if (up[3] != 0) {
12553 		mblk_t *mp1 = mp->b_cont;
12554 		boolean_t cksum_err;
12555 		uint16_t hck_flags = 0;
12556 
12557 		/* Pseudo-header checksum */
12558 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12559 		    iphs[9] + up[2];
12560 
12561 		/*
12562 		 * Revert to software checksum calculation if the interface
12563 		 * isn't capable of checksum offload or if IPsec is present.
12564 		 */
12565 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12566 			hck_flags = DB_CKSUMFLAGS(mp);
12567 
12568 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12569 			IP_STAT(ip_in_sw_cksum);
12570 
12571 		IP_CKSUM_RECV(hck_flags, u1,
12572 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12573 		    (int32_t)((uchar_t *)up - rptr),
12574 		    mp, mp1, cksum_err);
12575 
12576 		if (cksum_err) {
12577 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12578 
12579 			if (hck_flags & HCK_FULLCKSUM)
12580 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12581 			else if (hck_flags & HCK_PARTIALCKSUM)
12582 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12583 			else
12584 				IP_STAT(ip_udp_in_sw_cksum_err);
12585 
12586 			freemsg(first_mp);
12587 			return;
12588 		}
12589 	}
12590 
12591 	/* Non-fragmented broadcast or multicast packet? */
12592 	if (ire->ire_type == IRE_BROADCAST)
12593 		goto udpslowpath;
12594 
12595 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12596 	    ire->ire_zoneid)) != NULL) {
12597 		ASSERT(connp->conn_upq != NULL);
12598 		IP_STAT(ip_udp_fast_path);
12599 
12600 		if (CONN_UDP_FLOWCTLD(connp)) {
12601 			freemsg(mp);
12602 			BUMP_MIB(&ip_mib, udpInOverflows);
12603 		} else {
12604 			if (!mctl_present) {
12605 				BUMP_MIB(&ip_mib, ipInDelivers);
12606 			}
12607 			/*
12608 			 * mp and first_mp can change.
12609 			 */
12610 			if (ip_udp_check(q, connp, recv_ill,
12611 			    ipha, &mp, &first_mp, mctl_present)) {
12612 				/* Send it upstream */
12613 				CONN_UDP_RECV(connp, mp);
12614 			}
12615 		}
12616 		/*
12617 		 * freeb() cannot deal with null mblk being passed
12618 		 * in and first_mp can be set to null in the call
12619 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12620 		 */
12621 		if (mctl_present && first_mp != NULL) {
12622 			freeb(first_mp);
12623 		}
12624 		CONN_DEC_REF(connp);
12625 		return;
12626 	}
12627 
12628 	/*
12629 	 * if we got here we know the packet is not fragmented and
12630 	 * has no options. The classifier could not find a conn_t and
12631 	 * most likely its an icmp packet so send it through slow path.
12632 	 */
12633 
12634 	goto udpslowpath;
12635 
12636 ipoptions:
12637 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12638 		goto slow_done;
12639 	}
12640 
12641 	UPDATE_IB_PKT_COUNT(ire);
12642 	ire->ire_last_used_time = lbolt;
12643 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12644 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12645 fragmented:
12646 		/*
12647 		 * "sum" and "reass_hck_flags" are non-zero if the
12648 		 * reassembled packet has a valid hardware computed
12649 		 * checksum information associated with it.
12650 		 */
12651 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12652 			goto slow_done;
12653 		/*
12654 		 * Make sure that first_mp points back to mp as
12655 		 * the mp we came in with could have changed in
12656 		 * ip_rput_fragment().
12657 		 */
12658 		ASSERT(!mctl_present);
12659 		ipha = (ipha_t *)mp->b_rptr;
12660 		first_mp = mp;
12661 	}
12662 
12663 	/* Now we have a complete datagram, destined for this machine. */
12664 	u1 = IPH_HDR_LENGTH(ipha);
12665 	/* Pull up the UDP header, if necessary. */
12666 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12667 udppullup:
12668 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12669 			BUMP_MIB(&ip_mib, ipInDiscards);
12670 			freemsg(first_mp);
12671 			goto slow_done;
12672 		}
12673 		ipha = (ipha_t *)mp->b_rptr;
12674 	}
12675 
12676 	/*
12677 	 * Validate the checksum for the reassembled packet; for the
12678 	 * pullup case we calculate the payload checksum in software.
12679 	 */
12680 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12681 	if (up[3] != 0) {
12682 		boolean_t cksum_err;
12683 
12684 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12685 			IP_STAT(ip_in_sw_cksum);
12686 
12687 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12688 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12689 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12690 		    iphs[9] + up[2], sum, cksum_err);
12691 
12692 		if (cksum_err) {
12693 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12694 
12695 			if (reass_hck_flags & HCK_FULLCKSUM)
12696 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12697 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12698 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12699 			else
12700 				IP_STAT(ip_udp_in_sw_cksum_err);
12701 
12702 			freemsg(first_mp);
12703 			goto slow_done;
12704 		}
12705 	}
12706 udpslowpath:
12707 
12708 	/* Clear hardware checksum flag to be safe */
12709 	DB_CKSUMFLAGS(mp) = 0;
12710 
12711 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12712 	    (ire->ire_type == IRE_BROADCAST),
12713 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12714 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12715 
12716 slow_done:
12717 	IP_STAT(ip_udp_slow_path);
12718 	return;
12719 
12720 #undef  iphs
12721 #undef  rptr
12722 }
12723 
12724 /* ARGSUSED */
12725 static mblk_t *
12726 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12727     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12728     ill_rx_ring_t *ill_ring)
12729 {
12730 	conn_t		*connp;
12731 	uint32_t	sum;
12732 	uint32_t	u1;
12733 	uint16_t	*up;
12734 	int		offset;
12735 	ssize_t		len;
12736 	mblk_t		*mp1;
12737 	boolean_t	syn_present = B_FALSE;
12738 	tcph_t		*tcph;
12739 	uint_t		ip_hdr_len;
12740 	ill_t		*ill = (ill_t *)q->q_ptr;
12741 	zoneid_t	zoneid = ire->ire_zoneid;
12742 	boolean_t	cksum_err;
12743 	uint16_t	hck_flags = 0;
12744 
12745 #define	rptr	((uchar_t *)ipha)
12746 
12747 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12748 
12749 	/*
12750 	 * FAST PATH for tcp packets
12751 	 */
12752 
12753 	/* u1 is # words of IP options */
12754 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12755 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12756 
12757 	/* IP options present */
12758 	if (u1) {
12759 		goto ipoptions;
12760 	} else {
12761 		/* Check the IP header checksum.  */
12762 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12763 			/* Clear the IP header h/w cksum flag */
12764 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12765 		} else {
12766 #define	uph	((uint16_t *)ipha)
12767 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12768 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12769 #undef	uph
12770 			/* finish doing IP checksum */
12771 			sum = (sum & 0xFFFF) + (sum >> 16);
12772 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12773 			/*
12774 			 * Don't verify header checksum if this packet
12775 			 * is coming back from AH/ESP as we already did it.
12776 			 */
12777 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12778 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12779 				goto error;
12780 			}
12781 		}
12782 	}
12783 
12784 	if (!mctl_present) {
12785 		UPDATE_IB_PKT_COUNT(ire);
12786 		ire->ire_last_used_time = lbolt;
12787 	}
12788 
12789 	/* packet part of fragmented IP packet? */
12790 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12791 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12792 		goto fragmented;
12793 	}
12794 
12795 	/* u1 = IP header length (20 bytes) */
12796 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12797 
12798 	/* does packet contain IP+TCP headers? */
12799 	len = mp->b_wptr - rptr;
12800 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12801 		IP_STAT(ip_tcppullup);
12802 		goto tcppullup;
12803 	}
12804 
12805 	/* TCP options present? */
12806 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12807 
12808 	/*
12809 	 * If options need to be pulled up, then goto tcpoptions.
12810 	 * otherwise we are still in the fast path
12811 	 */
12812 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12813 		IP_STAT(ip_tcpoptions);
12814 		goto tcpoptions;
12815 	}
12816 
12817 	/* multiple mblks of tcp data? */
12818 	if ((mp1 = mp->b_cont) != NULL) {
12819 		/* more then two? */
12820 		if (mp1->b_cont != NULL) {
12821 			IP_STAT(ip_multipkttcp);
12822 			goto multipkttcp;
12823 		}
12824 		len += mp1->b_wptr - mp1->b_rptr;
12825 	}
12826 
12827 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12828 
12829 	/* part of pseudo checksum */
12830 
12831 	/* TCP datagram length */
12832 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12833 
12834 #define	iphs    ((uint16_t *)ipha)
12835 
12836 #ifdef	_BIG_ENDIAN
12837 	u1 += IPPROTO_TCP;
12838 #else
12839 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12840 #endif
12841 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12842 
12843 	/*
12844 	 * Revert to software checksum calculation if the interface
12845 	 * isn't capable of checksum offload or if IPsec is present.
12846 	 */
12847 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12848 		hck_flags = DB_CKSUMFLAGS(mp);
12849 
12850 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12851 		IP_STAT(ip_in_sw_cksum);
12852 
12853 	IP_CKSUM_RECV(hck_flags, u1,
12854 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12855 	    (int32_t)((uchar_t *)up - rptr),
12856 	    mp, mp1, cksum_err);
12857 
12858 	if (cksum_err) {
12859 		BUMP_MIB(&ip_mib, tcpInErrs);
12860 
12861 		if (hck_flags & HCK_FULLCKSUM)
12862 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12863 		else if (hck_flags & HCK_PARTIALCKSUM)
12864 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12865 		else
12866 			IP_STAT(ip_tcp_in_sw_cksum_err);
12867 
12868 		goto error;
12869 	}
12870 
12871 try_again:
12872 
12873 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12874 	    NULL) {
12875 		/* Send the TH_RST */
12876 		goto no_conn;
12877 	}
12878 
12879 	/*
12880 	 * TCP FAST PATH for AF_INET socket.
12881 	 *
12882 	 * TCP fast path to avoid extra work. An AF_INET socket type
12883 	 * does not have facility to receive extra information via
12884 	 * ip_process or ip_add_info. Also, when the connection was
12885 	 * established, we made a check if this connection is impacted
12886 	 * by any global IPSec policy or per connection policy (a
12887 	 * policy that comes in effect later will not apply to this
12888 	 * connection). Since all this can be determined at the
12889 	 * connection establishment time, a quick check of flags
12890 	 * can avoid extra work.
12891 	 */
12892 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12893 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12894 		ASSERT(first_mp == mp);
12895 		SET_SQUEUE(mp, tcp_rput_data, connp);
12896 		return (mp);
12897 	}
12898 
12899 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12900 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12901 		if (IPCL_IS_TCP(connp)) {
12902 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12903 			DB_CKSUMSTART(mp) =
12904 			    (intptr_t)ip_squeue_get(ill_ring);
12905 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12906 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12907 				SET_SQUEUE(mp, connp->conn_recv, connp);
12908 				return (mp);
12909 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12910 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12911 				ip_squeue_enter_unbound++;
12912 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12913 				    connp);
12914 				return (mp);
12915 			}
12916 			syn_present = B_TRUE;
12917 		}
12918 
12919 	}
12920 
12921 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12922 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12923 
12924 		/* No need to send this packet to TCP */
12925 		if ((flags & TH_RST) || (flags & TH_URG)) {
12926 			CONN_DEC_REF(connp);
12927 			freemsg(first_mp);
12928 			return (NULL);
12929 		}
12930 		if (flags & TH_ACK) {
12931 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
12932 			CONN_DEC_REF(connp);
12933 			return (NULL);
12934 		}
12935 
12936 		CONN_DEC_REF(connp);
12937 		freemsg(first_mp);
12938 		return (NULL);
12939 	}
12940 
12941 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12942 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12943 		    ipha, NULL, mctl_present);
12944 		if (first_mp == NULL) {
12945 			CONN_DEC_REF(connp);
12946 			return (NULL);
12947 		}
12948 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12949 			ASSERT(syn_present);
12950 			if (mctl_present) {
12951 				ASSERT(first_mp != mp);
12952 				first_mp->b_datap->db_struioflag |=
12953 				    STRUIO_POLICY;
12954 			} else {
12955 				ASSERT(first_mp == mp);
12956 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12957 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12958 			}
12959 		} else {
12960 			/*
12961 			 * Discard first_mp early since we're dealing with a
12962 			 * fully-connected conn_t and tcp doesn't do policy in
12963 			 * this case.
12964 			 */
12965 			if (mctl_present) {
12966 				freeb(first_mp);
12967 				mctl_present = B_FALSE;
12968 			}
12969 			first_mp = mp;
12970 		}
12971 	}
12972 
12973 	/* Initiate IPPF processing for fastpath */
12974 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12975 		uint32_t	ill_index;
12976 
12977 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12978 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12979 		if (mp == NULL) {
12980 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12981 			    "deferred/dropped during IPPF processing\n"));
12982 			CONN_DEC_REF(connp);
12983 			if (mctl_present)
12984 				freeb(first_mp);
12985 			return (NULL);
12986 		} else if (mctl_present) {
12987 			/*
12988 			 * ip_process might return a new mp.
12989 			 */
12990 			ASSERT(first_mp != mp);
12991 			first_mp->b_cont = mp;
12992 		} else {
12993 			first_mp = mp;
12994 		}
12995 
12996 	}
12997 
12998 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12999 		mp = ip_add_info(mp, recv_ill, flags);
13000 		if (mp == NULL) {
13001 			CONN_DEC_REF(connp);
13002 			if (mctl_present)
13003 				freeb(first_mp);
13004 			return (NULL);
13005 		} else if (mctl_present) {
13006 			/*
13007 			 * ip_add_info might return a new mp.
13008 			 */
13009 			ASSERT(first_mp != mp);
13010 			first_mp->b_cont = mp;
13011 		} else {
13012 			first_mp = mp;
13013 		}
13014 	}
13015 
13016 	if (IPCL_IS_TCP(connp)) {
13017 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13018 		return (first_mp);
13019 	} else {
13020 		putnext(connp->conn_rq, first_mp);
13021 		CONN_DEC_REF(connp);
13022 		return (NULL);
13023 	}
13024 
13025 no_conn:
13026 	/* Initiate IPPf processing, if needed. */
13027 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13028 		uint32_t ill_index;
13029 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13030 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13031 		if (first_mp == NULL) {
13032 			return (NULL);
13033 		}
13034 	}
13035 	BUMP_MIB(&ip_mib, ipInDelivers);
13036 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid);
13037 	return (NULL);
13038 ipoptions:
13039 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
13040 		goto slow_done;
13041 	}
13042 
13043 	UPDATE_IB_PKT_COUNT(ire);
13044 	ire->ire_last_used_time = lbolt;
13045 
13046 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13047 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13048 fragmented:
13049 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13050 			if (mctl_present)
13051 				freeb(first_mp);
13052 			goto slow_done;
13053 		}
13054 		/*
13055 		 * Make sure that first_mp points back to mp as
13056 		 * the mp we came in with could have changed in
13057 		 * ip_rput_fragment().
13058 		 */
13059 		ASSERT(!mctl_present);
13060 		ipha = (ipha_t *)mp->b_rptr;
13061 		first_mp = mp;
13062 	}
13063 
13064 	/* Now we have a complete datagram, destined for this machine. */
13065 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13066 
13067 	len = mp->b_wptr - mp->b_rptr;
13068 	/* Pull up a minimal TCP header, if necessary. */
13069 	if (len < (u1 + 20)) {
13070 tcppullup:
13071 		if (!pullupmsg(mp, u1 + 20)) {
13072 			BUMP_MIB(&ip_mib, ipInDiscards);
13073 			goto error;
13074 		}
13075 		ipha = (ipha_t *)mp->b_rptr;
13076 		len = mp->b_wptr - mp->b_rptr;
13077 	}
13078 
13079 	/*
13080 	 * Extract the offset field from the TCP header.  As usual, we
13081 	 * try to help the compiler more than the reader.
13082 	 */
13083 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13084 	if (offset != 5) {
13085 tcpoptions:
13086 		if (offset < 5) {
13087 			BUMP_MIB(&ip_mib, ipInDiscards);
13088 			goto error;
13089 		}
13090 		/*
13091 		 * There must be TCP options.
13092 		 * Make sure we can grab them.
13093 		 */
13094 		offset <<= 2;
13095 		offset += u1;
13096 		if (len < offset) {
13097 			if (!pullupmsg(mp, offset)) {
13098 				BUMP_MIB(&ip_mib, ipInDiscards);
13099 				goto error;
13100 			}
13101 			ipha = (ipha_t *)mp->b_rptr;
13102 			len = mp->b_wptr - rptr;
13103 		}
13104 	}
13105 
13106 	/* Get the total packet length in len, including headers. */
13107 	if (mp->b_cont) {
13108 multipkttcp:
13109 		len = msgdsize(mp);
13110 	}
13111 
13112 	/*
13113 	 * Check the TCP checksum by pulling together the pseudo-
13114 	 * header checksum, and passing it to ip_csum to be added in
13115 	 * with the TCP datagram.
13116 	 *
13117 	 * Since we are not using the hwcksum if available we must
13118 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13119 	 * If either of these fails along the way the mblk is freed.
13120 	 * If this logic ever changes and mblk is reused to say send
13121 	 * ICMP's back, then this flag may need to be cleared in
13122 	 * other places as well.
13123 	 */
13124 	DB_CKSUMFLAGS(mp) = 0;
13125 
13126 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13127 
13128 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13129 #ifdef	_BIG_ENDIAN
13130 	u1 += IPPROTO_TCP;
13131 #else
13132 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13133 #endif
13134 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13135 	/*
13136 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13137 	 */
13138 	IP_STAT(ip_in_sw_cksum);
13139 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13140 		BUMP_MIB(&ip_mib, tcpInErrs);
13141 		goto error;
13142 	}
13143 
13144 	IP_STAT(ip_tcp_slow_path);
13145 	goto try_again;
13146 #undef  iphs
13147 #undef  rptr
13148 
13149 error:
13150 	freemsg(first_mp);
13151 slow_done:
13152 	return (NULL);
13153 }
13154 
13155 /* ARGSUSED */
13156 static void
13157 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13158     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13159 {
13160 	conn_t		*connp;
13161 	uint32_t	sum;
13162 	uint32_t	u1;
13163 	ssize_t		len;
13164 	sctp_hdr_t	*sctph;
13165 	zoneid_t	zoneid = ire->ire_zoneid;
13166 	uint32_t	pktsum;
13167 	uint32_t	calcsum;
13168 	uint32_t	ports;
13169 	uint_t		ipif_seqid;
13170 	in6_addr_t	map_src, map_dst;
13171 	ill_t		*ill = (ill_t *)q->q_ptr;
13172 
13173 #define	rptr	((uchar_t *)ipha)
13174 
13175 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13176 
13177 	/* u1 is # words of IP options */
13178 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13179 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13180 
13181 	/* IP options present */
13182 	if (u1 > 0) {
13183 		goto ipoptions;
13184 	} else {
13185 		/* Check the IP header checksum.  */
13186 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13187 #define	uph	((uint16_t *)ipha)
13188 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13189 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13190 #undef	uph
13191 			/* finish doing IP checksum */
13192 			sum = (sum & 0xFFFF) + (sum >> 16);
13193 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13194 			/*
13195 			 * Don't verify header checksum if this packet
13196 			 * is coming back from AH/ESP as we already did it.
13197 			 */
13198 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13199 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13200 				goto error;
13201 			}
13202 		}
13203 		/*
13204 		 * Since there is no SCTP h/w cksum support yet, just
13205 		 * clear the flag.
13206 		 */
13207 		DB_CKSUMFLAGS(mp) = 0;
13208 	}
13209 
13210 	/*
13211 	 * Don't verify header checksum if this packet is coming
13212 	 * back from AH/ESP as we already did it.
13213 	 */
13214 	if (!mctl_present) {
13215 		UPDATE_IB_PKT_COUNT(ire);
13216 		ire->ire_last_used_time = lbolt;
13217 	}
13218 
13219 	/* packet part of fragmented IP packet? */
13220 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13221 	if (u1 & (IPH_MF | IPH_OFFSET))
13222 		goto fragmented;
13223 
13224 	/* u1 = IP header length (20 bytes) */
13225 	u1 = IP_SIMPLE_HDR_LENGTH;
13226 
13227 find_sctp_client:
13228 	/* Pullup if we don't have the sctp common header. */
13229 	len = MBLKL(mp);
13230 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13231 		if (mp->b_cont == NULL ||
13232 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13233 			BUMP_MIB(&ip_mib, ipInDiscards);
13234 			goto error;
13235 		}
13236 		ipha = (ipha_t *)mp->b_rptr;
13237 		len = MBLKL(mp);
13238 	}
13239 
13240 	sctph = (sctp_hdr_t *)(rptr + u1);
13241 #ifdef	DEBUG
13242 	if (!skip_sctp_cksum) {
13243 #endif
13244 		pktsum = sctph->sh_chksum;
13245 		sctph->sh_chksum = 0;
13246 		calcsum = sctp_cksum(mp, u1);
13247 		if (calcsum != pktsum) {
13248 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13249 			goto error;
13250 		}
13251 		sctph->sh_chksum = pktsum;
13252 #ifdef	DEBUG	/* skip_sctp_cksum */
13253 	}
13254 #endif
13255 	/* get the ports */
13256 	ports = *(uint32_t *)&sctph->sh_sport;
13257 
13258 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13259 	IRE_REFRELE(ire);
13260 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13261 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13262 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13263 	    mp)) == NULL) {
13264 		/* Check for raw socket or OOTB handling */
13265 		goto no_conn;
13266 	}
13267 
13268 	/* Found a client; up it goes */
13269 	BUMP_MIB(&ip_mib, ipInDelivers);
13270 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13271 	return;
13272 
13273 no_conn:
13274 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13275 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13276 	return;
13277 
13278 ipoptions:
13279 	DB_CKSUMFLAGS(mp) = 0;
13280 	if (!ip_options_cksum(q, first_mp, ipha, ire))
13281 		goto slow_done;
13282 
13283 	UPDATE_IB_PKT_COUNT(ire);
13284 	ire->ire_last_used_time = lbolt;
13285 
13286 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13287 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13288 fragmented:
13289 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13290 			goto slow_done;
13291 		/*
13292 		 * Make sure that first_mp points back to mp as
13293 		 * the mp we came in with could have changed in
13294 		 * ip_rput_fragment().
13295 		 */
13296 		ASSERT(!mctl_present);
13297 		ipha = (ipha_t *)mp->b_rptr;
13298 		first_mp = mp;
13299 	}
13300 
13301 	/* Now we have a complete datagram, destined for this machine. */
13302 	u1 = IPH_HDR_LENGTH(ipha);
13303 	goto find_sctp_client;
13304 #undef  iphs
13305 #undef  rptr
13306 
13307 error:
13308 	freemsg(first_mp);
13309 slow_done:
13310 	IRE_REFRELE(ire);
13311 }
13312 
13313 #define	VER_BITS	0xF0
13314 #define	VERSION_6	0x60
13315 
13316 static boolean_t
13317 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
13318     ipaddr_t *dstp)
13319 {
13320 	uint_t	opt_len;
13321 	ipha_t *ipha;
13322 	ssize_t len;
13323 	uint_t	pkt_len;
13324 
13325 	IP_STAT(ip_ipoptions);
13326 	ipha = *iphapp;
13327 
13328 #define	rptr    ((uchar_t *)ipha)
13329 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13330 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13331 		BUMP_MIB(&ip_mib, ipInIPv6);
13332 		freemsg(mp);
13333 		return (B_FALSE);
13334 	}
13335 
13336 	/* multiple mblk or too short */
13337 	pkt_len = ntohs(ipha->ipha_length);
13338 
13339 	/* Get the number of words of IP options in the IP header. */
13340 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13341 	if (opt_len) {
13342 		/* IP Options present!  Validate and process. */
13343 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13344 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13345 			goto done;
13346 		}
13347 		/*
13348 		 * Recompute complete header length and make sure we
13349 		 * have access to all of it.
13350 		 */
13351 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13352 		if (len > (mp->b_wptr - rptr)) {
13353 			if (len > pkt_len) {
13354 				BUMP_MIB(&ip_mib, ipInHdrErrors);
13355 				goto done;
13356 			}
13357 			if (!pullupmsg(mp, len)) {
13358 				BUMP_MIB(&ip_mib, ipInDiscards);
13359 				goto done;
13360 			}
13361 			ipha = (ipha_t *)mp->b_rptr;
13362 		}
13363 		/*
13364 		 * Go off to ip_rput_options which returns the next hop
13365 		 * destination address, which may have been affected
13366 		 * by source routing.
13367 		 */
13368 		IP_STAT(ip_opt);
13369 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13370 			return (B_FALSE);
13371 		}
13372 	}
13373 	*iphapp = ipha;
13374 	return (B_TRUE);
13375 done:
13376 	/* clear b_prev - used by ip_mroute_decap */
13377 	mp->b_prev = NULL;
13378 	freemsg(mp);
13379 	return (B_FALSE);
13380 #undef  rptr
13381 }
13382 
13383 /*
13384  * Deal with the fact that there is no ire for the destination.
13385  * The incoming ill (in_ill) is passed in to ip_newroute only
13386  * in the case of packets coming from mobile ip forward tunnel.
13387  * It must be null otherwise.
13388  */
13389 static ire_t *
13390 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13391     ipaddr_t dst)
13392 {
13393 	ipha_t	*ipha;
13394 	ill_t	*ill;
13395 	ire_t	*ire;
13396 	boolean_t	check_multirt = B_FALSE;
13397 
13398 	ipha = (ipha_t *)mp->b_rptr;
13399 	ill = (ill_t *)q->q_ptr;
13400 
13401 	ASSERT(ill != NULL);
13402 	/*
13403 	 * No IRE for this destination, so it can't be for us.
13404 	 * Unless we are forwarding, drop the packet.
13405 	 * We have to let source routed packets through
13406 	 * since we don't yet know if they are 'ping -l'
13407 	 * packets i.e. if they will go out over the
13408 	 * same interface as they came in on.
13409 	 */
13410 	if (ll_multicast) {
13411 		freemsg(mp);
13412 		return (NULL);
13413 	}
13414 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13415 		BUMP_MIB(&ip_mib, ipForwProhibits);
13416 		freemsg(mp);
13417 		return (NULL);
13418 	}
13419 
13420 	/*
13421 	 * Mark this packet as having originated externally.
13422 	 *
13423 	 * For non-forwarding code path, ire_send later double
13424 	 * checks this interface to see if it is still exists
13425 	 * post-ARP resolution.
13426 	 *
13427 	 * Also, IPQOS uses this to differentiate between
13428 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13429 	 * QOS packet processing in ip_wput_attach_llhdr().
13430 	 * The QoS module can mark the b_band for a fastpath message
13431 	 * or the dl_priority field in a unitdata_req header for
13432 	 * CoS marking. This info can only be found in
13433 	 * ip_wput_attach_llhdr().
13434 	 */
13435 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13436 	/*
13437 	 * Clear the indication that this may have a hardware checksum
13438 	 * as we are not using it
13439 	 */
13440 	DB_CKSUMFLAGS(mp) = 0;
13441 
13442 	if (in_ill != NULL) {
13443 		/*
13444 		 * Now hand the packet to ip_newroute.
13445 		 */
13446 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13447 		return (NULL);
13448 	}
13449 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13450 	    MBLK_GETLABEL(mp));
13451 
13452 	if (ire == NULL && check_multirt) {
13453 		/* Let ip_newroute handle CGTP  */
13454 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13455 		return (NULL);
13456 	}
13457 
13458 	if (ire != NULL)
13459 		return (ire);
13460 
13461 	mp->b_prev = mp->b_next = 0;
13462 	/* send icmp unreachable */
13463 	q = WR(q);
13464 	/* Sent by forwarding path, and router is global zone */
13465 	if (ip_source_routed(ipha)) {
13466 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13467 		    GLOBAL_ZONEID);
13468 	} else {
13469 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13470 	}
13471 
13472 	return (NULL);
13473 
13474 }
13475 
13476 /*
13477  * check ip header length and align it.
13478  */
13479 static boolean_t
13480 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13481 {
13482 	ssize_t len;
13483 	ill_t *ill;
13484 	ipha_t	*ipha;
13485 
13486 	len = MBLKL(mp);
13487 
13488 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13489 		if (!OK_32PTR(mp->b_rptr))
13490 			IP_STAT(ip_notaligned1);
13491 		else
13492 			IP_STAT(ip_notaligned2);
13493 		/* Guard against bogus device drivers */
13494 		if (len < 0) {
13495 			/* clear b_prev - used by ip_mroute_decap */
13496 			mp->b_prev = NULL;
13497 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13498 			freemsg(mp);
13499 			return (B_FALSE);
13500 		}
13501 
13502 		if (ip_rput_pullups++ == 0) {
13503 			ill = (ill_t *)q->q_ptr;
13504 			ipha = (ipha_t *)mp->b_rptr;
13505 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13506 			    "ip_check_and_align_header: %s forced us to "
13507 			    " pullup pkt, hdr len %ld, hdr addr %p",
13508 			    ill->ill_name, len, ipha);
13509 		}
13510 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13511 			/* clear b_prev - used by ip_mroute_decap */
13512 			mp->b_prev = NULL;
13513 			BUMP_MIB(&ip_mib, ipInDiscards);
13514 			freemsg(mp);
13515 			return (B_FALSE);
13516 		}
13517 	}
13518 	return (B_TRUE);
13519 }
13520 
13521 static boolean_t
13522 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13523 {
13524 	ill_group_t	*ill_group;
13525 	ill_group_t	*ire_group;
13526 	queue_t 	*q;
13527 	ill_t		*ire_ill;
13528 	uint_t		ill_ifindex;
13529 
13530 	q = *qp;
13531 	/*
13532 	 * We need to check to make sure the packet came in
13533 	 * on the queue associated with the destination IRE.
13534 	 * Note that for multicast packets and broadcast packets sent to
13535 	 * a broadcast address which is shared between multiple interfaces
13536 	 * we should not do this since we just got a random broadcast ire.
13537 	 */
13538 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13539 		boolean_t check_multi = B_TRUE;
13540 
13541 		/*
13542 		 * This packet came in on an interface other than the
13543 		 * one associated with the destination address.
13544 		 * "Gateway" it to the appropriate interface here.
13545 		 * As long as the ills belong to the same group,
13546 		 * we don't consider them to arriving on the wrong
13547 		 * interface. Thus, when the switch is doing inbound
13548 		 * load spreading, we won't drop packets when we
13549 		 * are doing strict multihoming checks. Note, the
13550 		 * same holds true for 'usesrc groups' where the
13551 		 * destination address may belong to another interface
13552 		 * to allow multipathing to happen
13553 		 */
13554 		ill_group = ill->ill_group;
13555 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13556 		ill_ifindex = ill->ill_usesrc_ifindex;
13557 		ire_group = ire_ill->ill_group;
13558 
13559 		/*
13560 		 * If it's part of the same IPMP group, or if it's a legal
13561 		 * address on the 'usesrc' interface, then bypass strict
13562 		 * checks.
13563 		 */
13564 		if (ill_group != NULL && ill_group == ire_group) {
13565 			check_multi = B_FALSE;
13566 		} else if (ill_ifindex != 0 &&
13567 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13568 			check_multi = B_FALSE;
13569 		}
13570 
13571 		if (check_multi &&
13572 		    ip_strict_dst_multihoming &&
13573 		    ((ill->ill_flags &
13574 		    ire->ire_ipif->ipif_ill->ill_flags &
13575 		    ILLF_ROUTER) == 0)) {
13576 			/* Drop packet */
13577 			BUMP_MIB(&ip_mib, ipForwProhibits);
13578 			freemsg(mp);
13579 			return (B_TRUE);
13580 		}
13581 
13582 		/*
13583 		 * Change the queue (for non-virtual destination network
13584 		 * interfaces) and ip_rput_local will be called with the right
13585 		 * queue
13586 		 */
13587 		q = ire->ire_rfq;
13588 	}
13589 	/* Must be broadcast.  We'll take it. */
13590 	*qp = q;
13591 	return (B_FALSE);
13592 }
13593 
13594 ire_t *
13595 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13596 {
13597 	ipha_t	*ipha;
13598 	ipaddr_t ip_dst, ip_src;
13599 	ire_t	*src_ire = NULL;
13600 	ill_t	*stq_ill;
13601 	uint_t	hlen;
13602 	uint32_t sum;
13603 	queue_t	*dev_q;
13604 	boolean_t check_multirt = B_FALSE;
13605 
13606 
13607 	ipha = (ipha_t *)mp->b_rptr;
13608 
13609 	/*
13610 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13611 	 * The loopback address check for both src and dst has already
13612 	 * been checked in ip_input
13613 	 */
13614 	ip_dst = ntohl(dst);
13615 	ip_src = ntohl(ipha->ipha_src);
13616 
13617 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13618 	    IN_CLASSD(ip_src)) {
13619 		BUMP_MIB(&ip_mib, ipForwProhibits);
13620 		goto drop;
13621 	}
13622 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13623 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13624 
13625 	if (src_ire != NULL) {
13626 		BUMP_MIB(&ip_mib, ipForwProhibits);
13627 		goto drop;
13628 	}
13629 
13630 	/* No ire cache of nexthop. So first create one  */
13631 	if (ire == NULL) {
13632 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13633 		/*
13634 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13635 		 * is not set. So upon return from ire_forward
13636 		 * check_multirt should remain as false.
13637 		 */
13638 		ASSERT(!check_multirt);
13639 		if (ire == NULL) {
13640 			BUMP_MIB(&ip_mib, ipInDiscards);
13641 			mp->b_prev = mp->b_next = 0;
13642 			/* send icmp unreachable */
13643 			/* Sent by forwarding path, and router is global zone */
13644 			if (ip_source_routed(ipha)) {
13645 				icmp_unreachable(ill->ill_wq, mp,
13646 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13647 			} else {
13648 				icmp_unreachable(ill->ill_wq, mp,
13649 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13650 			}
13651 			return (ire);
13652 		}
13653 	}
13654 
13655 	/*
13656 	 * Forwarding fastpath exception case:
13657 	 * If either of the follwoing case is true, we take
13658 	 * the slowpath
13659 	 *	o forwarding is not enabled
13660 	 *	o incoming and outgoing interface are the same, or the same
13661 	 *	  IPMP group
13662 	 *	o corresponding ire is in incomplete state
13663 	 *	o packet needs fragmentation
13664 	 *
13665 	 * The codeflow from here on is thus:
13666 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13667 	 */
13668 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13669 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13670 	    !(ill->ill_flags & ILLF_ROUTER) ||
13671 	    (ill == stq_ill) ||
13672 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13673 	    (ire->ire_nce == NULL) ||
13674 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13675 	    (ntohs(ipha->ipha_length) > ire->ire_max_frag) ||
13676 	    ipha->ipha_ttl <= 1) {
13677 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13678 		    ipha, ill, B_FALSE);
13679 		return (ire);
13680 	}
13681 
13682 	DTRACE_PROBE4(ip4__forwarding__start,
13683 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13684 
13685 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
13686 	    ill, stq_ill, ipha, mp, mp);
13687 
13688 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13689 
13690 	if (mp == NULL)
13691 		goto drop;
13692 
13693 	mp->b_datap->db_struioun.cksum.flags = 0;
13694 	/* Adjust the checksum to reflect the ttl decrement. */
13695 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13696 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13697 	ipha->ipha_ttl--;
13698 
13699 	dev_q = ire->ire_stq->q_next;
13700 	if ((dev_q->q_next != NULL ||
13701 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13702 		goto indiscard;
13703 	}
13704 
13705 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13706 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13707 
13708 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13709 		mblk_t *mpip = mp;
13710 
13711 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13712 		if (mp != NULL) {
13713 			DTRACE_PROBE4(ip4__physical__out__start,
13714 			    ill_t *, NULL, ill_t *, stq_ill,
13715 			    ipha_t *, ipha, mblk_t *, mp);
13716 			FW_HOOKS(ip4_physical_out_event,
13717 			    ipv4firewall_physical_out,
13718 			    NULL, stq_ill, ipha, mp, mpip);
13719 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13720 			    mp);
13721 			if (mp == NULL)
13722 				goto drop;
13723 
13724 			UPDATE_IB_PKT_COUNT(ire);
13725 			ire->ire_last_used_time = lbolt;
13726 			BUMP_MIB(&ip_mib, ipForwDatagrams);
13727 			putnext(ire->ire_stq, mp);
13728 			return (ire);
13729 		}
13730 	}
13731 
13732 indiscard:
13733 	BUMP_MIB(&ip_mib, ipInDiscards);
13734 drop:
13735 	if (mp != NULL)
13736 		freemsg(mp);
13737 	if (src_ire != NULL)
13738 		ire_refrele(src_ire);
13739 	return (ire);
13740 
13741 }
13742 
13743 /*
13744  * This function is called in the forwarding slowpath, when
13745  * either the ire lacks the link-layer address, or the packet needs
13746  * further processing(eg. fragmentation), before transmission.
13747  */
13748 
13749 static void
13750 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13751     ill_t *ill, boolean_t ll_multicast)
13752 {
13753 	ill_group_t	*ill_group;
13754 	ill_group_t	*ire_group;
13755 	queue_t		*dev_q;
13756 	ire_t		*src_ire;
13757 
13758 	ASSERT(ire->ire_stq != NULL);
13759 
13760 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13761 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13762 
13763 	if (ll_multicast != 0)
13764 		goto drop_pkt;
13765 
13766 	/*
13767 	 * check if ipha_src is a broadcast address. Note that this
13768 	 * check is redundant when we get here from ip_fast_forward()
13769 	 * which has already done this check. However, since we can
13770 	 * also get here from ip_rput_process_broadcast() or, for
13771 	 * for the slow path through ip_fast_forward(), we perform
13772 	 * the check again for code-reusability
13773 	 */
13774 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13775 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13776 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13777 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13778 		if (src_ire != NULL)
13779 			ire_refrele(src_ire);
13780 		BUMP_MIB(&ip_mib, ipForwProhibits);
13781 		ip2dbg(("ip_rput_process_forward: Received packet with"
13782 		    " bad src/dst address on %s\n", ill->ill_name));
13783 		goto drop_pkt;
13784 	}
13785 
13786 	ill_group = ill->ill_group;
13787 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13788 	/*
13789 	 * Check if we want to forward this one at this time.
13790 	 * We allow source routed packets on a host provided that
13791 	 * they go out the same interface or same interface group
13792 	 * as they came in on.
13793 	 *
13794 	 * XXX To be quicker, we may wish to not chase pointers to
13795 	 * get the ILLF_ROUTER flag and instead store the
13796 	 * forwarding policy in the ire.  An unfortunate
13797 	 * side-effect of that would be requiring an ire flush
13798 	 * whenever the ILLF_ROUTER flag changes.
13799 	 */
13800 	if (((ill->ill_flags &
13801 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13802 	    ILLF_ROUTER) == 0) &&
13803 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13804 	    (ill_group != NULL && ill_group == ire_group)))) {
13805 		BUMP_MIB(&ip_mib, ipForwProhibits);
13806 		if (ip_source_routed(ipha)) {
13807 			q = WR(q);
13808 			/*
13809 			 * Clear the indication that this may have
13810 			 * hardware checksum as we are not using it.
13811 			 */
13812 			DB_CKSUMFLAGS(mp) = 0;
13813 			/* Sent by forwarding path, and router is global zone */
13814 			icmp_unreachable(q, mp,
13815 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13816 			return;
13817 		}
13818 		goto drop_pkt;
13819 	}
13820 
13821 	/* Packet is being forwarded. Turning off hwcksum flag. */
13822 	DB_CKSUMFLAGS(mp) = 0;
13823 	if (ip_g_send_redirects) {
13824 		/*
13825 		 * Check whether the incoming interface and outgoing
13826 		 * interface is part of the same group. If so,
13827 		 * send redirects.
13828 		 *
13829 		 * Check the source address to see if it originated
13830 		 * on the same logical subnet it is going back out on.
13831 		 * If so, we should be able to send it a redirect.
13832 		 * Avoid sending a redirect if the destination
13833 		 * is directly connected (i.e., ipha_dst is the same
13834 		 * as ire_gateway_addr or the ire_addr of the
13835 		 * nexthop IRE_CACHE ), or if the packet was source
13836 		 * routed out this interface.
13837 		 */
13838 		ipaddr_t src, nhop;
13839 		mblk_t	*mp1;
13840 		ire_t	*nhop_ire = NULL;
13841 
13842 		/*
13843 		 * Check whether ire_rfq and q are from the same ill
13844 		 * or if they are not same, they at least belong
13845 		 * to the same group. If so, send redirects.
13846 		 */
13847 		if ((ire->ire_rfq == q ||
13848 		    (ill_group != NULL && ill_group == ire_group)) &&
13849 		    !ip_source_routed(ipha)) {
13850 
13851 			nhop = (ire->ire_gateway_addr != 0 ?
13852 			    ire->ire_gateway_addr : ire->ire_addr);
13853 
13854 			if (ipha->ipha_dst == nhop) {
13855 				/*
13856 				 * We avoid sending a redirect if the
13857 				 * destination is directly connected
13858 				 * because it is possible that multiple
13859 				 * IP subnets may have been configured on
13860 				 * the link, and the source may not
13861 				 * be on the same subnet as ip destination,
13862 				 * even though they are on the same
13863 				 * physical link.
13864 				 */
13865 				goto sendit;
13866 			}
13867 
13868 			src = ipha->ipha_src;
13869 
13870 			/*
13871 			 * We look up the interface ire for the nexthop,
13872 			 * to see if ipha_src is in the same subnet
13873 			 * as the nexthop.
13874 			 *
13875 			 * Note that, if, in the future, IRE_CACHE entries
13876 			 * are obsoleted,  this lookup will not be needed,
13877 			 * as the ire passed to this function will be the
13878 			 * same as the nhop_ire computed below.
13879 			 */
13880 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
13881 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
13882 			    0, NULL, MATCH_IRE_TYPE);
13883 
13884 			if (nhop_ire != NULL) {
13885 				if ((src & nhop_ire->ire_mask) ==
13886 				    (nhop & nhop_ire->ire_mask)) {
13887 					/*
13888 					 * The source is directly connected.
13889 					 * Just copy the ip header (which is
13890 					 * in the first mblk)
13891 					 */
13892 					mp1 = copyb(mp);
13893 					if (mp1 != NULL) {
13894 						icmp_send_redirect(WR(q), mp1,
13895 						    nhop);
13896 					}
13897 				}
13898 				ire_refrele(nhop_ire);
13899 			}
13900 		}
13901 	}
13902 sendit:
13903 	dev_q = ire->ire_stq->q_next;
13904 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13905 		BUMP_MIB(&ip_mib, ipInDiscards);
13906 		freemsg(mp);
13907 		return;
13908 	}
13909 
13910 	ip_rput_forward(ire, ipha, mp, ill);
13911 	return;
13912 
13913 drop_pkt:
13914 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
13915 	freemsg(mp);
13916 }
13917 
13918 ire_t *
13919 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13920     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13921 {
13922 	queue_t		*q;
13923 	uint16_t	hcksumflags;
13924 
13925 	q = *qp;
13926 
13927 	/*
13928 	 * Clear the indication that this may have hardware
13929 	 * checksum as we are not using it for forwarding.
13930 	 */
13931 	hcksumflags = DB_CKSUMFLAGS(mp);
13932 	DB_CKSUMFLAGS(mp) = 0;
13933 
13934 	/*
13935 	 * Directed broadcast forwarding: if the packet came in over a
13936 	 * different interface then it is routed out over we can forward it.
13937 	 */
13938 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13939 		ire_refrele(ire);
13940 		freemsg(mp);
13941 		BUMP_MIB(&ip_mib, ipInDiscards);
13942 		return (NULL);
13943 	}
13944 	/*
13945 	 * For multicast we have set dst to be INADDR_BROADCAST
13946 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13947 	 * only for broadcast packets.
13948 	 */
13949 	if (!CLASSD(ipha->ipha_dst)) {
13950 		ire_t *new_ire;
13951 		ipif_t *ipif;
13952 		/*
13953 		 * For ill groups, as the switch duplicates broadcasts
13954 		 * across all the ports, we need to filter out and
13955 		 * send up only one copy. There is one copy for every
13956 		 * broadcast address on each ill. Thus, we look for a
13957 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13958 		 * later to see whether this ill is eligible to receive
13959 		 * them or not. ill_nominate_bcast_rcv() nominates only
13960 		 * one set of IREs for receiving.
13961 		 */
13962 
13963 		ipif = ipif_get_next_ipif(NULL, ill);
13964 		if (ipif == NULL) {
13965 			ire_refrele(ire);
13966 			freemsg(mp);
13967 			BUMP_MIB(&ip_mib, ipInDiscards);
13968 			return (NULL);
13969 		}
13970 		new_ire = ire_ctable_lookup(dst, 0, 0,
13971 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13972 		ipif_refrele(ipif);
13973 
13974 		if (new_ire != NULL) {
13975 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13976 				ire_refrele(ire);
13977 				ire_refrele(new_ire);
13978 				freemsg(mp);
13979 				BUMP_MIB(&ip_mib, ipInDiscards);
13980 				return (NULL);
13981 			}
13982 			/*
13983 			 * In the special case of multirouted broadcast
13984 			 * packets, we unconditionally need to "gateway"
13985 			 * them to the appropriate interface here.
13986 			 * In the normal case, this cannot happen, because
13987 			 * there is no broadcast IRE tagged with the
13988 			 * RTF_MULTIRT flag.
13989 			 */
13990 			if (new_ire->ire_flags & RTF_MULTIRT) {
13991 				ire_refrele(new_ire);
13992 				if (ire->ire_rfq != NULL) {
13993 					q = ire->ire_rfq;
13994 					*qp = q;
13995 				}
13996 			} else {
13997 				ire_refrele(ire);
13998 				ire = new_ire;
13999 			}
14000 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14001 			if (!ip_g_forward_directed_bcast) {
14002 				/*
14003 				 * Free the message if
14004 				 * ip_g_forward_directed_bcast is turned
14005 				 * off for non-local broadcast.
14006 				 */
14007 				ire_refrele(ire);
14008 				freemsg(mp);
14009 				BUMP_MIB(&ip_mib, ipInDiscards);
14010 				return (NULL);
14011 			}
14012 		} else {
14013 			/*
14014 			 * This CGTP packet successfully passed the
14015 			 * CGTP filter, but the related CGTP
14016 			 * broadcast IRE has not been found,
14017 			 * meaning that the redundant ipif is
14018 			 * probably down. However, if we discarded
14019 			 * this packet, its duplicate would be
14020 			 * filtered out by the CGTP filter so none
14021 			 * of them would get through. So we keep
14022 			 * going with this one.
14023 			 */
14024 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14025 			if (ire->ire_rfq != NULL) {
14026 				q = ire->ire_rfq;
14027 				*qp = q;
14028 			}
14029 		}
14030 	}
14031 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
14032 		/*
14033 		 * Verify that there are not more then one
14034 		 * IRE_BROADCAST with this broadcast address which
14035 		 * has ire_stq set.
14036 		 * TODO: simplify, loop over all IRE's
14037 		 */
14038 		ire_t	*ire1;
14039 		int	num_stq = 0;
14040 		mblk_t	*mp1;
14041 
14042 		/* Find the first one with ire_stq set */
14043 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14044 		for (ire1 = ire; ire1 &&
14045 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14046 		    ire1 = ire1->ire_next)
14047 			;
14048 		if (ire1) {
14049 			ire_refrele(ire);
14050 			ire = ire1;
14051 			IRE_REFHOLD(ire);
14052 		}
14053 
14054 		/* Check if there are additional ones with stq set */
14055 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14056 			if (ire->ire_addr != ire1->ire_addr)
14057 				break;
14058 			if (ire1->ire_stq) {
14059 				num_stq++;
14060 				break;
14061 			}
14062 		}
14063 		rw_exit(&ire->ire_bucket->irb_lock);
14064 		if (num_stq == 1 && ire->ire_stq != NULL) {
14065 			ip1dbg(("ip_rput_process_broadcast: directed "
14066 			    "broadcast to 0x%x\n",
14067 			    ntohl(ire->ire_addr)));
14068 			mp1 = copymsg(mp);
14069 			if (mp1) {
14070 				switch (ipha->ipha_protocol) {
14071 				case IPPROTO_UDP:
14072 					ip_udp_input(q, mp1, ipha, ire, ill);
14073 					break;
14074 				default:
14075 					ip_proto_input(q, mp1, ipha, ire, ill);
14076 					break;
14077 				}
14078 			}
14079 			/*
14080 			 * Adjust ttl to 2 (1+1 - the forward engine
14081 			 * will decrement it by one.
14082 			 */
14083 			if (ip_csum_hdr(ipha)) {
14084 				BUMP_MIB(&ip_mib, ipInCksumErrs);
14085 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14086 				freemsg(mp);
14087 				ire_refrele(ire);
14088 				return (NULL);
14089 			}
14090 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
14091 			ipha->ipha_hdr_checksum = 0;
14092 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14093 			ip_rput_process_forward(q, mp, ire, ipha,
14094 			    ill, ll_multicast);
14095 			ire_refrele(ire);
14096 			return (NULL);
14097 		}
14098 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14099 		    ntohl(ire->ire_addr)));
14100 	}
14101 
14102 
14103 	/* Restore any hardware checksum flags */
14104 	DB_CKSUMFLAGS(mp) = hcksumflags;
14105 	return (ire);
14106 }
14107 
14108 /* ARGSUSED */
14109 static boolean_t
14110 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14111     int *ll_multicast, ipaddr_t *dstp)
14112 {
14113 	/*
14114 	 * Forward packets only if we have joined the allmulti
14115 	 * group on this interface.
14116 	 */
14117 	if (ip_g_mrouter && ill->ill_join_allmulti) {
14118 		int retval;
14119 
14120 		/*
14121 		 * Clear the indication that this may have hardware
14122 		 * checksum as we are not using it.
14123 		 */
14124 		DB_CKSUMFLAGS(mp) = 0;
14125 		retval = ip_mforward(ill, ipha, mp);
14126 		/* ip_mforward updates mib variables if needed */
14127 		/* clear b_prev - used by ip_mroute_decap */
14128 		mp->b_prev = NULL;
14129 
14130 		switch (retval) {
14131 		case 0:
14132 			/*
14133 			 * pkt is okay and arrived on phyint.
14134 			 *
14135 			 * If we are running as a multicast router
14136 			 * we need to see all IGMP and/or PIM packets.
14137 			 */
14138 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14139 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14140 				goto done;
14141 			}
14142 			break;
14143 		case -1:
14144 			/* pkt is mal-formed, toss it */
14145 			goto drop_pkt;
14146 		case 1:
14147 			/* pkt is okay and arrived on a tunnel */
14148 			/*
14149 			 * If we are running a multicast router
14150 			 *  we need to see all igmp packets.
14151 			 */
14152 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14153 				*dstp = INADDR_BROADCAST;
14154 				*ll_multicast = 1;
14155 				return (B_FALSE);
14156 			}
14157 
14158 			goto drop_pkt;
14159 		}
14160 	}
14161 
14162 	ILM_WALKER_HOLD(ill);
14163 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14164 		/*
14165 		 * This might just be caused by the fact that
14166 		 * multiple IP Multicast addresses map to the same
14167 		 * link layer multicast - no need to increment counter!
14168 		 */
14169 		ILM_WALKER_RELE(ill);
14170 		freemsg(mp);
14171 		return (B_TRUE);
14172 	}
14173 	ILM_WALKER_RELE(ill);
14174 done:
14175 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14176 	/*
14177 	 * This assumes the we deliver to all streams for multicast
14178 	 * and broadcast packets.
14179 	 */
14180 	*dstp = INADDR_BROADCAST;
14181 	*ll_multicast = 1;
14182 	return (B_FALSE);
14183 drop_pkt:
14184 	ip2dbg(("ip_rput: drop pkt\n"));
14185 	freemsg(mp);
14186 	return (B_TRUE);
14187 }
14188 
14189 static boolean_t
14190 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14191     int *ll_multicast, mblk_t **mpp)
14192 {
14193 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14194 	boolean_t must_copy = B_FALSE;
14195 	struct iocblk   *iocp;
14196 	ipha_t		*ipha;
14197 
14198 #define	rptr    ((uchar_t *)ipha)
14199 
14200 	first_mp = *first_mpp;
14201 	mp = *mpp;
14202 
14203 	ASSERT(first_mp == mp);
14204 
14205 	/*
14206 	 * if db_ref > 1 then copymsg and free original. Packet may be
14207 	 * changed and do not want other entity who has a reference to this
14208 	 * message to trip over the changes. This is a blind change because
14209 	 * trying to catch all places that might change packet is too
14210 	 * difficult (since it may be a module above this one)
14211 	 *
14212 	 * This corresponds to the non-fast path case. We walk down the full
14213 	 * chain in this case, and check the db_ref count of all the dblks,
14214 	 * and do a copymsg if required. It is possible that the db_ref counts
14215 	 * of the data blocks in the mblk chain can be different.
14216 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14217 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14218 	 * 'snoop' is running.
14219 	 */
14220 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14221 		if (mp1->b_datap->db_ref > 1) {
14222 			must_copy = B_TRUE;
14223 			break;
14224 		}
14225 	}
14226 
14227 	if (must_copy) {
14228 		mp1 = copymsg(mp);
14229 		if (mp1 == NULL) {
14230 			for (mp1 = mp; mp1 != NULL;
14231 			    mp1 = mp1->b_cont) {
14232 				mp1->b_next = NULL;
14233 				mp1->b_prev = NULL;
14234 			}
14235 			freemsg(mp);
14236 			BUMP_MIB(&ip_mib, ipInDiscards);
14237 			return (B_TRUE);
14238 		}
14239 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14240 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14241 			/* Copy b_prev - used by ip_mroute_decap */
14242 			to_mp->b_prev = from_mp->b_prev;
14243 			from_mp->b_prev = NULL;
14244 		}
14245 		*first_mpp = first_mp = mp1;
14246 		freemsg(mp);
14247 		mp = mp1;
14248 		*mpp = mp1;
14249 	}
14250 
14251 	ipha = (ipha_t *)mp->b_rptr;
14252 
14253 	/*
14254 	 * previous code has a case for M_DATA.
14255 	 * We want to check how that happens.
14256 	 */
14257 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14258 	switch (first_mp->b_datap->db_type) {
14259 	case M_PROTO:
14260 	case M_PCPROTO:
14261 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14262 		    DL_UNITDATA_IND) {
14263 			/* Go handle anything other than data elsewhere. */
14264 			ip_rput_dlpi(q, mp);
14265 			return (B_TRUE);
14266 		}
14267 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14268 		/* Ditch the DLPI header. */
14269 		mp1 = mp->b_cont;
14270 		ASSERT(first_mp == mp);
14271 		*first_mpp = mp1;
14272 		freeb(mp);
14273 		*mpp = mp1;
14274 		return (B_FALSE);
14275 	case M_IOCACK:
14276 		ip1dbg(("got iocack "));
14277 		iocp = (struct iocblk *)mp->b_rptr;
14278 		switch (iocp->ioc_cmd) {
14279 		case DL_IOC_HDR_INFO:
14280 			ill = (ill_t *)q->q_ptr;
14281 			ill_fastpath_ack(ill, mp);
14282 			return (B_TRUE);
14283 		case SIOCSTUNPARAM:
14284 		case OSIOCSTUNPARAM:
14285 			/* Go through qwriter_ip */
14286 			break;
14287 		case SIOCGTUNPARAM:
14288 		case OSIOCGTUNPARAM:
14289 			ip_rput_other(NULL, q, mp, NULL);
14290 			return (B_TRUE);
14291 		default:
14292 			putnext(q, mp);
14293 			return (B_TRUE);
14294 		}
14295 		/* FALLTHRU */
14296 	case M_ERROR:
14297 	case M_HANGUP:
14298 		/*
14299 		 * Since this is on the ill stream we unconditionally
14300 		 * bump up the refcount
14301 		 */
14302 		ill_refhold(ill);
14303 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14304 		    B_FALSE);
14305 		return (B_TRUE);
14306 	case M_CTL:
14307 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14308 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14309 			IPHADA_M_CTL)) {
14310 			/*
14311 			 * It's an IPsec accelerated packet.
14312 			 * Make sure that the ill from which we received the
14313 			 * packet has enabled IPsec hardware acceleration.
14314 			 */
14315 			if (!(ill->ill_capabilities &
14316 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14317 				/* IPsec kstats: bean counter */
14318 				freemsg(mp);
14319 				return (B_TRUE);
14320 			}
14321 
14322 			/*
14323 			 * Make mp point to the mblk following the M_CTL,
14324 			 * then process according to type of mp.
14325 			 * After this processing, first_mp will point to
14326 			 * the data-attributes and mp to the pkt following
14327 			 * the M_CTL.
14328 			 */
14329 			mp = first_mp->b_cont;
14330 			if (mp == NULL) {
14331 				freemsg(first_mp);
14332 				return (B_TRUE);
14333 			}
14334 			/*
14335 			 * A Hardware Accelerated packet can only be M_DATA
14336 			 * ESP or AH packet.
14337 			 */
14338 			if (mp->b_datap->db_type != M_DATA) {
14339 				/* non-M_DATA IPsec accelerated packet */
14340 				IPSECHW_DEBUG(IPSECHW_PKT,
14341 				    ("non-M_DATA IPsec accelerated pkt\n"));
14342 				freemsg(first_mp);
14343 				return (B_TRUE);
14344 			}
14345 			ipha = (ipha_t *)mp->b_rptr;
14346 			if (ipha->ipha_protocol != IPPROTO_AH &&
14347 			    ipha->ipha_protocol != IPPROTO_ESP) {
14348 				IPSECHW_DEBUG(IPSECHW_PKT,
14349 				    ("non-M_DATA IPsec accelerated pkt\n"));
14350 				freemsg(first_mp);
14351 				return (B_TRUE);
14352 			}
14353 			*mpp = mp;
14354 			return (B_FALSE);
14355 		}
14356 		putnext(q, mp);
14357 		return (B_TRUE);
14358 	case M_FLUSH:
14359 		if (*mp->b_rptr & FLUSHW) {
14360 			*mp->b_rptr &= ~FLUSHR;
14361 			qreply(q, mp);
14362 			return (B_TRUE);
14363 		}
14364 		freemsg(mp);
14365 		return (B_TRUE);
14366 	case M_IOCNAK:
14367 		ip1dbg(("got iocnak "));
14368 		iocp = (struct iocblk *)mp->b_rptr;
14369 		switch (iocp->ioc_cmd) {
14370 		case DL_IOC_HDR_INFO:
14371 		case SIOCSTUNPARAM:
14372 		case OSIOCSTUNPARAM:
14373 			/*
14374 			 * Since this is on the ill stream we unconditionally
14375 			 * bump up the refcount
14376 			 */
14377 			ill_refhold(ill);
14378 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14379 			    CUR_OP, B_FALSE);
14380 			return (B_TRUE);
14381 		case SIOCGTUNPARAM:
14382 		case OSIOCGTUNPARAM:
14383 			ip_rput_other(NULL, q, mp, NULL);
14384 			return (B_TRUE);
14385 		default:
14386 			break;
14387 		}
14388 		/* FALLTHRU */
14389 	default:
14390 		putnext(q, mp);
14391 		return (B_TRUE);
14392 	}
14393 }
14394 
14395 /* Read side put procedure.  Packets coming from the wire arrive here. */
14396 void
14397 ip_rput(queue_t *q, mblk_t *mp)
14398 {
14399 	ill_t	*ill;
14400 	mblk_t	 *dmp = NULL;
14401 
14402 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14403 
14404 	ill = (ill_t *)q->q_ptr;
14405 
14406 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14407 		union DL_primitives *dl;
14408 
14409 		/*
14410 		 * Things are opening or closing. Only accept DLPI control
14411 		 * messages. In the open case, the ill->ill_ipif has not yet
14412 		 * been created. In the close case, things hanging off the
14413 		 * ill could have been freed already. In either case it
14414 		 * may not be safe to proceed further.
14415 		 */
14416 
14417 		dl = (union DL_primitives *)mp->b_rptr;
14418 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14419 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14420 			/*
14421 			 * Also SIOC[GS]TUN* ioctls can come here.
14422 			 */
14423 			inet_freemsg(mp);
14424 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14425 			    "ip_input_end: q %p (%S)", q, "uninit");
14426 			return;
14427 		}
14428 	}
14429 
14430 	/*
14431 	 * if db_ref > 1 then copymsg and free original. Packet may be
14432 	 * changed and we do not want the other entity who has a reference to
14433 	 * this message to trip over the changes. This is a blind change because
14434 	 * trying to catch all places that might change the packet is too
14435 	 * difficult.
14436 	 *
14437 	 * This corresponds to the fast path case, where we have a chain of
14438 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14439 	 * in the mblk chain. There doesn't seem to be a reason why a device
14440 	 * driver would send up data with varying db_ref counts in the mblk
14441 	 * chain. In any case the Fast path is a private interface, and our
14442 	 * drivers don't do such a thing. Given the above assumption, there is
14443 	 * no need to walk down the entire mblk chain (which could have a
14444 	 * potential performance problem)
14445 	 */
14446 	if (mp->b_datap->db_ref > 1) {
14447 		mblk_t  *mp1;
14448 		boolean_t adjusted = B_FALSE;
14449 		IP_STAT(ip_db_ref);
14450 
14451 		/*
14452 		 * The IP_RECVSLLA option depends on having the link layer
14453 		 * header. First check that:
14454 		 * a> the underlying device is of type ether, since this
14455 		 * option is currently supported only over ethernet.
14456 		 * b> there is enough room to copy over the link layer header.
14457 		 *
14458 		 * Once the checks are done, adjust rptr so that the link layer
14459 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14460 		 * be returned by some non-ethernet drivers but in this case the
14461 		 * second check will fail.
14462 		 */
14463 		if (ill->ill_type == IFT_ETHER &&
14464 		    (mp->b_rptr - mp->b_datap->db_base) >=
14465 		    sizeof (struct ether_header)) {
14466 			mp->b_rptr -= sizeof (struct ether_header);
14467 			adjusted = B_TRUE;
14468 		}
14469 		mp1 = copymsg(mp);
14470 		if (mp1 == NULL) {
14471 			mp->b_next = NULL;
14472 			/* clear b_prev - used by ip_mroute_decap */
14473 			mp->b_prev = NULL;
14474 			freemsg(mp);
14475 			BUMP_MIB(&ip_mib, ipInDiscards);
14476 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14477 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14478 			return;
14479 		}
14480 		if (adjusted) {
14481 			/*
14482 			 * Copy is done. Restore the pointer in the _new_ mblk
14483 			 */
14484 			mp1->b_rptr += sizeof (struct ether_header);
14485 		}
14486 		/* Copy b_prev - used by ip_mroute_decap */
14487 		mp1->b_prev = mp->b_prev;
14488 		mp->b_prev = NULL;
14489 		freemsg(mp);
14490 		mp = mp1;
14491 	}
14492 	if (DB_TYPE(mp) == M_DATA) {
14493 		dmp = mp;
14494 	} else if (DB_TYPE(mp) == M_PROTO &&
14495 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14496 		dmp = mp->b_cont;
14497 	}
14498 	if (dmp != NULL) {
14499 		/*
14500 		 * IP header ptr not aligned?
14501 		 * OR IP header not complete in first mblk
14502 		 */
14503 		if (!OK_32PTR(dmp->b_rptr) ||
14504 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14505 			if (!ip_check_and_align_header(q, dmp))
14506 				return;
14507 		}
14508 	}
14509 
14510 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14511 	    "ip_rput_end: q %p (%S)", q, "end");
14512 
14513 	ip_input(ill, NULL, mp, NULL);
14514 }
14515 
14516 /*
14517  * Direct read side procedure capable of dealing with chains. GLDv3 based
14518  * drivers call this function directly with mblk chains while STREAMS
14519  * read side procedure ip_rput() calls this for single packet with ip_ring
14520  * set to NULL to process one packet at a time.
14521  *
14522  * The ill will always be valid if this function is called directly from
14523  * the driver.
14524  *
14525  * If ip_input() is called from GLDv3:
14526  *
14527  *   - This must be a non-VLAN IP stream.
14528  *   - 'mp' is either an untagged or a special priority-tagged packet.
14529  *   - Any VLAN tag that was in the MAC header has been stripped.
14530  *
14531  * Thus, there is no need to adjust b_rptr in this function.
14532  */
14533 /* ARGSUSED */
14534 void
14535 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14536     struct mac_header_info_s *mhip)
14537 {
14538 	ipaddr_t		dst = NULL;
14539 	ipaddr_t		prev_dst;
14540 	ire_t			*ire = NULL;
14541 	ipha_t			*ipha;
14542 	uint_t			pkt_len;
14543 	ssize_t			len;
14544 	uint_t			opt_len;
14545 	int			ll_multicast;
14546 	int			cgtp_flt_pkt;
14547 	queue_t			*q = ill->ill_rq;
14548 	squeue_t		*curr_sqp = NULL;
14549 	mblk_t 			*head = NULL;
14550 	mblk_t			*tail = NULL;
14551 	mblk_t			*first_mp;
14552 	mblk_t 			*mp;
14553 	int			cnt = 0;
14554 
14555 	ASSERT(mp_chain != NULL);
14556 	ASSERT(ill != NULL);
14557 
14558 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14559 
14560 #define	rptr	((uchar_t *)ipha)
14561 
14562 	while (mp_chain != NULL) {
14563 		first_mp = mp = mp_chain;
14564 		mp_chain = mp_chain->b_next;
14565 		mp->b_next = NULL;
14566 		ll_multicast = 0;
14567 
14568 		/*
14569 		 * We do ire caching from one iteration to
14570 		 * another. In the event the packet chain contains
14571 		 * all packets from the same dst, this caching saves
14572 		 * an ire_cache_lookup for each of the succeeding
14573 		 * packets in a packet chain.
14574 		 */
14575 		prev_dst = dst;
14576 
14577 		/*
14578 		 * ip_input fast path
14579 		 */
14580 
14581 		/* mblk type is not M_DATA */
14582 		if (mp->b_datap->db_type != M_DATA) {
14583 			if (ip_rput_process_notdata(q, &first_mp, ill,
14584 			    &ll_multicast, &mp))
14585 				continue;
14586 		}
14587 
14588 		/* Make sure its an M_DATA and that its aligned */
14589 		ASSERT(mp->b_datap->db_type == M_DATA);
14590 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14591 
14592 		ipha = (ipha_t *)mp->b_rptr;
14593 		len = mp->b_wptr - rptr;
14594 
14595 		BUMP_MIB(&ip_mib, ipInReceives);
14596 
14597 
14598 		/* multiple mblk or too short */
14599 		pkt_len = ntohs(ipha->ipha_length);
14600 		len -= pkt_len;
14601 		if (len != 0) {
14602 			/*
14603 			 * Make sure we have data length consistent
14604 			 * with the IP header.
14605 			 */
14606 			if (mp->b_cont == NULL) {
14607 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14608 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14609 					ip2dbg(("ip_input: drop pkt\n"));
14610 					freemsg(mp);
14611 					continue;
14612 				}
14613 				mp->b_wptr = rptr + pkt_len;
14614 			} else if (len += msgdsize(mp->b_cont)) {
14615 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14616 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14617 					ip2dbg(("ip_input: drop pkt\n"));
14618 					freemsg(mp);
14619 					continue;
14620 				}
14621 				(void) adjmsg(mp, -len);
14622 				IP_STAT(ip_multimblk3);
14623 			}
14624 		}
14625 
14626 		/* Obtain the dst of the current packet */
14627 		dst = ipha->ipha_dst;
14628 
14629 		if (IP_LOOPBACK_ADDR(dst) ||
14630 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14631 			BUMP_MIB(&ip_mib, ipInAddrErrors);
14632 			cmn_err(CE_CONT, "dst %X src %X\n",
14633 			    dst, ipha->ipha_src);
14634 			freemsg(mp);
14635 			continue;
14636 		}
14637 
14638 		/*
14639 		 * The event for packets being received from a 'physical'
14640 		 * interface is placed after validation of the source and/or
14641 		 * destination address as being local so that packets can be
14642 		 * redirected to loopback addresses using ipnat.
14643 		 */
14644 		DTRACE_PROBE4(ip4__physical__in__start,
14645 		    ill_t *, ill, ill_t *, NULL,
14646 		    ipha_t *, ipha, mblk_t *, first_mp);
14647 
14648 		FW_HOOKS(ip4_physical_in_event, ipv4firewall_physical_in,
14649 		    ill, NULL, ipha, first_mp, mp);
14650 
14651 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14652 
14653 		if (first_mp == NULL) {
14654 			continue;
14655 		}
14656 		dst = ipha->ipha_dst;
14657 
14658 		/*
14659 		 * Attach any necessary label information to
14660 		 * this packet
14661 		 */
14662 		if (is_system_labeled() &&
14663 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14664 			BUMP_MIB(&ip_mib, ipInDiscards);
14665 			freemsg(mp);
14666 			continue;
14667 		}
14668 
14669 		/*
14670 		 * Reuse the cached ire only if the ipha_dst of the previous
14671 		 * packet is the same as the current packet AND it is not
14672 		 * INADDR_ANY.
14673 		 */
14674 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14675 		    (ire != NULL)) {
14676 			ire_refrele(ire);
14677 			ire = NULL;
14678 		}
14679 		opt_len = ipha->ipha_version_and_hdr_length -
14680 		    IP_SIMPLE_HDR_VERSION;
14681 
14682 		/*
14683 		 * Check to see if we can take the fastpath.
14684 		 * That is possible if the following conditions are met
14685 		 *	o Tsol disabled
14686 		 *	o CGTP disabled
14687 		 *	o ipp_action_count is 0
14688 		 *	o Mobile IP not running
14689 		 *	o no options in the packet
14690 		 *	o not a RSVP packet
14691 		 * 	o not a multicast packet
14692 		 */
14693 		if (!is_system_labeled() &&
14694 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14695 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14696 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14697 		    !ll_multicast && !CLASSD(dst)) {
14698 			if (ire == NULL)
14699 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14700 
14701 			/* incoming packet is for forwarding */
14702 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14703 				ire = ip_fast_forward(ire, dst, ill, mp);
14704 				continue;
14705 			}
14706 			/* incoming packet is for local consumption */
14707 			if (ire->ire_type & IRE_LOCAL)
14708 				goto local;
14709 		}
14710 
14711 		/*
14712 		 * Disable ire caching for anything more complex
14713 		 * than the simple fast path case we checked for above.
14714 		 */
14715 		if (ire != NULL) {
14716 			ire_refrele(ire);
14717 			ire = NULL;
14718 		}
14719 
14720 		/* Full-blown slow path */
14721 		if (opt_len != 0) {
14722 			if (len != 0)
14723 				IP_STAT(ip_multimblk4);
14724 			else
14725 				IP_STAT(ip_ipoptions);
14726 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
14727 				continue;
14728 		}
14729 
14730 		/*
14731 		 * Invoke the CGTP (multirouting) filtering module to process
14732 		 * the incoming packet. Packets identified as duplicates
14733 		 * must be discarded. Filtering is active only if the
14734 		 * the ip_cgtp_filter ndd variable is non-zero.
14735 		 */
14736 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14737 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
14738 			cgtp_flt_pkt =
14739 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14740 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14741 				freemsg(first_mp);
14742 				continue;
14743 			}
14744 		}
14745 
14746 		/*
14747 		 * If rsvpd is running, let RSVP daemon handle its processing
14748 		 * and forwarding of RSVP multicast/unicast packets.
14749 		 * If rsvpd is not running but mrouted is running, RSVP
14750 		 * multicast packets are forwarded as multicast traffic
14751 		 * and RSVP unicast packets are forwarded by unicast router.
14752 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14753 		 * packets are not forwarded, but the unicast packets are
14754 		 * forwarded like unicast traffic.
14755 		 */
14756 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14757 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
14758 			/* RSVP packet and rsvpd running. Treat as ours */
14759 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14760 			/*
14761 			 * This assumes that we deliver to all streams for
14762 			 * multicast and broadcast packets.
14763 			 * We have to force ll_multicast to 1 to handle the
14764 			 * M_DATA messages passed in from ip_mroute_decap.
14765 			 */
14766 			dst = INADDR_BROADCAST;
14767 			ll_multicast = 1;
14768 		} else if (CLASSD(dst)) {
14769 			/* packet is multicast */
14770 			mp->b_next = NULL;
14771 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14772 			    &ll_multicast, &dst))
14773 				continue;
14774 		}
14775 
14776 
14777 		/*
14778 		 * Check if the packet is coming from the Mobile IP
14779 		 * forward tunnel interface
14780 		 */
14781 		if (ill->ill_srcif_refcnt > 0) {
14782 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
14783 			    NULL, ill, MATCH_IRE_TYPE);
14784 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
14785 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
14786 
14787 				/* We need to resolve the link layer info */
14788 				ire_refrele(ire);
14789 				ire = NULL;
14790 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
14791 				    ll_multicast, dst);
14792 				continue;
14793 			}
14794 		}
14795 
14796 		if (ire == NULL) {
14797 			ire = ire_cache_lookup(dst, ALL_ZONES,
14798 			    MBLK_GETLABEL(mp));
14799 		}
14800 
14801 		/*
14802 		 * If mipagent is running and reverse tunnel is created as per
14803 		 * mobile node request, then any packet coming through the
14804 		 * incoming interface from the mobile-node, should be reverse
14805 		 * tunneled to it's home agent except those that are destined
14806 		 * to foreign agent only.
14807 		 * This needs source address based ire lookup. The routing
14808 		 * entries for source address based lookup are only created by
14809 		 * mipagent program only when a reverse tunnel is created.
14810 		 * Reference : RFC2002, RFC2344
14811 		 */
14812 		if (ill->ill_mrtun_refcnt > 0) {
14813 			ipaddr_t	srcaddr;
14814 			ire_t		*tmp_ire;
14815 
14816 			tmp_ire = ire;	/* Save, we might need it later */
14817 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14818 			    ire->ire_type != IRE_BROADCAST)) {
14819 				srcaddr = ipha->ipha_src;
14820 				ire = ire_mrtun_lookup(srcaddr, ill);
14821 				if (ire != NULL) {
14822 					/*
14823 					 * Should not be getting iphada packet
14824 					 * here. we should only get those for
14825 					 * IRE_LOCAL traffic, excluded above.
14826 					 * Fail-safe (drop packet) in the event
14827 					 * hardware is misbehaving.
14828 					 */
14829 					if (first_mp != mp) {
14830 						/* IPsec KSTATS: beancount me */
14831 						freemsg(first_mp);
14832 					} else {
14833 						/*
14834 						 * This packet must be forwarded
14835 						 * to Reverse Tunnel
14836 						 */
14837 						ip_mrtun_forward(ire, ill, mp);
14838 					}
14839 					ire_refrele(ire);
14840 					ire = NULL;
14841 					if (tmp_ire != NULL) {
14842 						ire_refrele(tmp_ire);
14843 						tmp_ire = NULL;
14844 					}
14845 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14846 					    "ip_input_end: q %p (%S)",
14847 					    q, "uninit");
14848 					continue;
14849 				}
14850 			}
14851 			/*
14852 			 * If this packet is from a non-mobilenode  or a
14853 			 * mobile-node which does not request reverse
14854 			 * tunnel service
14855 			 */
14856 			ire = tmp_ire;
14857 		}
14858 
14859 
14860 		/*
14861 		 * If we reach here that means the incoming packet satisfies
14862 		 * one of the following conditions:
14863 		 *   - packet is from a mobile node which does not request
14864 		 *	reverse tunnel
14865 		 *   - packet is from a non-mobile node, which is the most
14866 		 *	common case
14867 		 *   - packet is from a reverse tunnel enabled mobile node
14868 		 *	and destined to foreign agent only
14869 		 */
14870 
14871 		if (ire == NULL) {
14872 			/*
14873 			 * No IRE for this destination, so it can't be for us.
14874 			 * Unless we are forwarding, drop the packet.
14875 			 * We have to let source routed packets through
14876 			 * since we don't yet know if they are 'ping -l'
14877 			 * packets i.e. if they will go out over the
14878 			 * same interface as they came in on.
14879 			 */
14880 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14881 			if (ire == NULL)
14882 				continue;
14883 		}
14884 
14885 		/*
14886 		 * Broadcast IRE may indicate either broadcast or
14887 		 * multicast packet
14888 		 */
14889 		if (ire->ire_type == IRE_BROADCAST) {
14890 			/*
14891 			 * Skip broadcast checks if packet is UDP multicast;
14892 			 * we'd rather not enter ip_rput_process_broadcast()
14893 			 * unless the packet is broadcast for real, since
14894 			 * that routine is a no-op for multicast.
14895 			 */
14896 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14897 			    !CLASSD(ipha->ipha_dst)) {
14898 				ire = ip_rput_process_broadcast(&q, mp,
14899 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14900 				    ll_multicast);
14901 				if (ire == NULL)
14902 					continue;
14903 			}
14904 		} else if (ire->ire_stq != NULL) {
14905 			/* fowarding? */
14906 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14907 			    ll_multicast);
14908 			/* ip_rput_process_forward consumed the packet */
14909 			continue;
14910 		}
14911 
14912 local:
14913 		/* packet not for us */
14914 		if (ire->ire_rfq != q) {
14915 			if (ip_rput_notforus(&q, mp, ire, ill))
14916 				continue;
14917 		}
14918 
14919 		switch (ipha->ipha_protocol) {
14920 		case IPPROTO_TCP:
14921 			ASSERT(first_mp == mp);
14922 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14923 				mp, 0, q, ip_ring)) != NULL) {
14924 				if (curr_sqp == NULL) {
14925 					curr_sqp = GET_SQUEUE(mp);
14926 					ASSERT(cnt == 0);
14927 					cnt++;
14928 					head = tail = mp;
14929 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14930 					ASSERT(tail != NULL);
14931 					cnt++;
14932 					tail->b_next = mp;
14933 					tail = mp;
14934 				} else {
14935 					/*
14936 					 * A different squeue. Send the
14937 					 * chain for the previous squeue on
14938 					 * its way. This shouldn't happen
14939 					 * often unless interrupt binding
14940 					 * changes.
14941 					 */
14942 					IP_STAT(ip_input_multi_squeue);
14943 					squeue_enter_chain(curr_sqp, head,
14944 					    tail, cnt, SQTAG_IP_INPUT);
14945 					curr_sqp = GET_SQUEUE(mp);
14946 					head = mp;
14947 					tail = mp;
14948 					cnt = 1;
14949 				}
14950 			}
14951 			continue;
14952 		case IPPROTO_UDP:
14953 			ASSERT(first_mp == mp);
14954 			ip_udp_input(q, mp, ipha, ire, ill);
14955 			continue;
14956 		case IPPROTO_SCTP:
14957 			ASSERT(first_mp == mp);
14958 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14959 			    q, dst);
14960 			/* ire has been released by ip_sctp_input */
14961 			ire = NULL;
14962 			continue;
14963 		default:
14964 			ip_proto_input(q, first_mp, ipha, ire, ill);
14965 			continue;
14966 		}
14967 	}
14968 
14969 	if (ire != NULL)
14970 		ire_refrele(ire);
14971 
14972 	if (head != NULL)
14973 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14974 
14975 	/*
14976 	 * This code is there just to make netperf/ttcp look good.
14977 	 *
14978 	 * Its possible that after being in polling mode (and having cleared
14979 	 * the backlog), squeues have turned the interrupt frequency higher
14980 	 * to improve latency at the expense of more CPU utilization (less
14981 	 * packets per interrupts or more number of interrupts). Workloads
14982 	 * like ttcp/netperf do manage to tickle polling once in a while
14983 	 * but for the remaining time, stay in higher interrupt mode since
14984 	 * their packet arrival rate is pretty uniform and this shows up
14985 	 * as higher CPU utilization. Since people care about CPU utilization
14986 	 * while running netperf/ttcp, turn the interrupt frequency back to
14987 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14988 	 */
14989 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14990 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14991 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14992 			ip_ring->rr_blank(ip_ring->rr_handle,
14993 			    ip_ring->rr_normal_blank_time,
14994 			    ip_ring->rr_normal_pkt_cnt);
14995 		}
14996 	}
14997 
14998 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14999 	    "ip_input_end: q %p (%S)", q, "end");
15000 #undef	rptr
15001 }
15002 
15003 static void
15004 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15005     t_uscalar_t err)
15006 {
15007 	if (dl_err == DL_SYSERR) {
15008 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15009 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15010 		    ill->ill_name, dlpi_prim_str(prim), err);
15011 		return;
15012 	}
15013 
15014 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15015 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15016 	    dlpi_err_str(dl_err));
15017 }
15018 
15019 /*
15020  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15021  * than DL_UNITDATA_IND messages. If we need to process this message
15022  * exclusively, we call qwriter_ip, in which case we also need to call
15023  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15024  */
15025 void
15026 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15027 {
15028 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15029 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15030 	ill_t		*ill;
15031 
15032 	ip1dbg(("ip_rput_dlpi"));
15033 	ill = (ill_t *)q->q_ptr;
15034 	switch (dloa->dl_primitive) {
15035 	case DL_ERROR_ACK:
15036 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15037 		    "%s (0x%x), unix %u\n", ill->ill_name,
15038 		    dlpi_prim_str(dlea->dl_error_primitive),
15039 		    dlea->dl_error_primitive,
15040 		    dlpi_err_str(dlea->dl_errno),
15041 		    dlea->dl_errno,
15042 		    dlea->dl_unix_errno));
15043 		switch (dlea->dl_error_primitive) {
15044 		case DL_UNBIND_REQ:
15045 			mutex_enter(&ill->ill_lock);
15046 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15047 			cv_signal(&ill->ill_cv);
15048 			mutex_exit(&ill->ill_lock);
15049 			/* FALLTHRU */
15050 		case DL_NOTIFY_REQ:
15051 		case DL_ATTACH_REQ:
15052 		case DL_DETACH_REQ:
15053 		case DL_INFO_REQ:
15054 		case DL_BIND_REQ:
15055 		case DL_ENABMULTI_REQ:
15056 		case DL_PHYS_ADDR_REQ:
15057 		case DL_CAPABILITY_REQ:
15058 		case DL_CONTROL_REQ:
15059 			/*
15060 			 * Refhold the ill to match qwriter_ip which does a
15061 			 * refrele. Since this is on the ill stream we
15062 			 * unconditionally bump up the refcount without
15063 			 * checking for ILL_CAN_LOOKUP
15064 			 */
15065 			ill_refhold(ill);
15066 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15067 			    CUR_OP, B_FALSE);
15068 			return;
15069 		case DL_DISABMULTI_REQ:
15070 			freemsg(mp);	/* Don't want to pass this up */
15071 			return;
15072 		default:
15073 			break;
15074 		}
15075 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15076 		    dlea->dl_errno, dlea->dl_unix_errno);
15077 		freemsg(mp);
15078 		return;
15079 	case DL_INFO_ACK:
15080 	case DL_BIND_ACK:
15081 	case DL_PHYS_ADDR_ACK:
15082 	case DL_NOTIFY_ACK:
15083 	case DL_CAPABILITY_ACK:
15084 	case DL_CONTROL_ACK:
15085 		/*
15086 		 * Refhold the ill to match qwriter_ip which does a refrele
15087 		 * Since this is on the ill stream we unconditionally
15088 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15089 		 */
15090 		ill_refhold(ill);
15091 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15092 		    CUR_OP, B_FALSE);
15093 		return;
15094 	case DL_NOTIFY_IND:
15095 		ill_refhold(ill);
15096 		/*
15097 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15098 		 * relation to the current ioctl in progress (if any). Hence we
15099 		 * pass in NEW_OP in this case.
15100 		 */
15101 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15102 		    NEW_OP, B_FALSE);
15103 		return;
15104 	case DL_OK_ACK:
15105 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15106 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15107 		switch (dloa->dl_correct_primitive) {
15108 		case DL_UNBIND_REQ:
15109 			mutex_enter(&ill->ill_lock);
15110 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15111 			cv_signal(&ill->ill_cv);
15112 			mutex_exit(&ill->ill_lock);
15113 			/* FALLTHRU */
15114 		case DL_ATTACH_REQ:
15115 		case DL_DETACH_REQ:
15116 			/*
15117 			 * Refhold the ill to match qwriter_ip which does a
15118 			 * refrele. Since this is on the ill stream we
15119 			 * unconditionally bump up the refcount
15120 			 */
15121 			ill_refhold(ill);
15122 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15123 			    CUR_OP, B_FALSE);
15124 			return;
15125 		case DL_ENABMULTI_REQ:
15126 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15127 				ill->ill_dlpi_multicast_state = IDS_OK;
15128 			break;
15129 
15130 		}
15131 		break;
15132 	default:
15133 		break;
15134 	}
15135 	freemsg(mp);
15136 }
15137 
15138 /*
15139  * Handling of DLPI messages that require exclusive access to the ipsq.
15140  *
15141  * Need to do ill_pending_mp_release on ioctl completion, which could
15142  * happen here. (along with mi_copy_done)
15143  */
15144 /* ARGSUSED */
15145 static void
15146 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15147 {
15148 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15149 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15150 	int		err = 0;
15151 	ill_t		*ill;
15152 	ipif_t		*ipif = NULL;
15153 	mblk_t		*mp1 = NULL;
15154 	conn_t		*connp = NULL;
15155 	t_uscalar_t	physaddr_req;
15156 	mblk_t		*mp_hw;
15157 	union DL_primitives *dlp;
15158 	boolean_t	success;
15159 	boolean_t	ioctl_aborted = B_FALSE;
15160 	boolean_t	log = B_TRUE;
15161 	hook_nic_event_t	*info;
15162 
15163 	ip1dbg(("ip_rput_dlpi_writer .."));
15164 	ill = (ill_t *)q->q_ptr;
15165 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15166 
15167 	ASSERT(IAM_WRITER_ILL(ill));
15168 
15169 	/*
15170 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15171 	 * both are null or non-null. However we can assert that only
15172 	 * after grabbing the ipsq_lock. So we don't make any assertion
15173 	 * here and in other places in the code.
15174 	 */
15175 	ipif = ipsq->ipsq_pending_ipif;
15176 	/*
15177 	 * The current ioctl could have been aborted by the user and a new
15178 	 * ioctl to bring up another ill could have started. We could still
15179 	 * get a response from the driver later.
15180 	 */
15181 	if (ipif != NULL && ipif->ipif_ill != ill)
15182 		ioctl_aborted = B_TRUE;
15183 
15184 	switch (dloa->dl_primitive) {
15185 	case DL_ERROR_ACK:
15186 		switch (dlea->dl_error_primitive) {
15187 		case DL_UNBIND_REQ:
15188 		case DL_ATTACH_REQ:
15189 		case DL_DETACH_REQ:
15190 		case DL_INFO_REQ:
15191 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15192 			break;
15193 		case DL_NOTIFY_REQ:
15194 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15195 			log = B_FALSE;
15196 			break;
15197 		case DL_PHYS_ADDR_REQ:
15198 			/*
15199 			 * For IPv6 only, there are two additional
15200 			 * phys_addr_req's sent to the driver to get the
15201 			 * IPv6 token and lla. This allows IP to acquire
15202 			 * the hardware address format for a given interface
15203 			 * without having built in knowledge of the hardware
15204 			 * address. ill_phys_addr_pend keeps track of the last
15205 			 * DL_PAR sent so we know which response we are
15206 			 * dealing with. ill_dlpi_done will update
15207 			 * ill_phys_addr_pend when it sends the next req.
15208 			 * We don't complete the IOCTL until all three DL_PARs
15209 			 * have been attempted, so set *_len to 0 and break.
15210 			 */
15211 			physaddr_req = ill->ill_phys_addr_pend;
15212 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15213 			if (physaddr_req == DL_IPV6_TOKEN) {
15214 				ill->ill_token_length = 0;
15215 				log = B_FALSE;
15216 				break;
15217 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15218 				ill->ill_nd_lla_len = 0;
15219 				log = B_FALSE;
15220 				break;
15221 			}
15222 			/*
15223 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15224 			 * We presumably have an IOCTL hanging out waiting
15225 			 * for completion. Find it and complete the IOCTL
15226 			 * with the error noted.
15227 			 * However, ill_dl_phys was called on an ill queue
15228 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15229 			 * set. But the ioctl is known to be pending on ill_wq.
15230 			 */
15231 			if (!ill->ill_ifname_pending)
15232 				break;
15233 			ill->ill_ifname_pending = 0;
15234 			if (!ioctl_aborted)
15235 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15236 			if (mp1 != NULL) {
15237 				/*
15238 				 * This operation (SIOCSLIFNAME) must have
15239 				 * happened on the ill. Assert there is no conn
15240 				 */
15241 				ASSERT(connp == NULL);
15242 				q = ill->ill_wq;
15243 			}
15244 			break;
15245 		case DL_BIND_REQ:
15246 			ill_dlpi_done(ill, DL_BIND_REQ);
15247 			if (ill->ill_ifname_pending)
15248 				break;
15249 			/*
15250 			 * Something went wrong with the bind.  We presumably
15251 			 * have an IOCTL hanging out waiting for completion.
15252 			 * Find it, take down the interface that was coming
15253 			 * up, and complete the IOCTL with the error noted.
15254 			 */
15255 			if (!ioctl_aborted)
15256 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15257 			if (mp1 != NULL) {
15258 				/*
15259 				 * This operation (SIOCSLIFFLAGS) must have
15260 				 * happened from a conn.
15261 				 */
15262 				ASSERT(connp != NULL);
15263 				q = CONNP_TO_WQ(connp);
15264 				if (ill->ill_move_in_progress) {
15265 					ILL_CLEAR_MOVE(ill);
15266 				}
15267 				(void) ipif_down(ipif, NULL, NULL);
15268 				/* error is set below the switch */
15269 			}
15270 			break;
15271 		case DL_ENABMULTI_REQ:
15272 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15273 
15274 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15275 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15276 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15277 				ipif_t *ipif;
15278 
15279 				log = B_FALSE;
15280 				printf("ip: joining multicasts failed (%d)"
15281 				    " on %s - will use link layer "
15282 				    "broadcasts for multicast\n",
15283 				    dlea->dl_errno, ill->ill_name);
15284 
15285 				/*
15286 				 * Set up the multicast mapping alone.
15287 				 * writer, so ok to access ill->ill_ipif
15288 				 * without any lock.
15289 				 */
15290 				ipif = ill->ill_ipif;
15291 				mutex_enter(&ill->ill_phyint->phyint_lock);
15292 				ill->ill_phyint->phyint_flags |=
15293 				    PHYI_MULTI_BCAST;
15294 				mutex_exit(&ill->ill_phyint->phyint_lock);
15295 
15296 				if (!ill->ill_isv6) {
15297 					(void) ipif_arp_setup_multicast(ipif,
15298 					    NULL);
15299 				} else {
15300 					(void) ipif_ndp_setup_multicast(ipif,
15301 					    NULL);
15302 				}
15303 			}
15304 			freemsg(mp);	/* Don't want to pass this up */
15305 			return;
15306 		case DL_CAPABILITY_REQ:
15307 		case DL_CONTROL_REQ:
15308 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15309 			    "DL_CAPABILITY/CONTROL REQ\n"));
15310 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15311 			ill->ill_dlpi_capab_state = IDS_FAILED;
15312 			freemsg(mp);
15313 			return;
15314 		}
15315 		/*
15316 		 * Note the error for IOCTL completion (mp1 is set when
15317 		 * ready to complete ioctl). If ill_ifname_pending_err is
15318 		 * set, an error occured during plumbing (ill_ifname_pending),
15319 		 * so we want to report that error.
15320 		 *
15321 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15322 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15323 		 * expected to get errack'd if the driver doesn't support
15324 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15325 		 * if these error conditions are encountered.
15326 		 */
15327 		if (mp1 != NULL) {
15328 			if (ill->ill_ifname_pending_err != 0)  {
15329 				err = ill->ill_ifname_pending_err;
15330 				ill->ill_ifname_pending_err = 0;
15331 			} else {
15332 				err = dlea->dl_unix_errno ?
15333 				    dlea->dl_unix_errno : ENXIO;
15334 			}
15335 		/*
15336 		 * If we're plumbing an interface and an error hasn't already
15337 		 * been saved, set ill_ifname_pending_err to the error passed
15338 		 * up. Ignore the error if log is B_FALSE (see comment above).
15339 		 */
15340 		} else if (log && ill->ill_ifname_pending &&
15341 		    ill->ill_ifname_pending_err == 0) {
15342 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15343 			dlea->dl_unix_errno : ENXIO;
15344 		}
15345 
15346 		if (log)
15347 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15348 			    dlea->dl_errno, dlea->dl_unix_errno);
15349 		break;
15350 	case DL_CAPABILITY_ACK: {
15351 		boolean_t reneg_flag = B_FALSE;
15352 		/* Call a routine to handle this one. */
15353 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15354 		/*
15355 		 * Check if the ACK is due to renegotiation case since we
15356 		 * will need to send a new CAPABILITY_REQ later.
15357 		 */
15358 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15359 			/* This is the ack for a renogiation case */
15360 			reneg_flag = B_TRUE;
15361 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15362 		}
15363 		ill_capability_ack(ill, mp);
15364 		if (reneg_flag)
15365 			ill_capability_probe(ill);
15366 		break;
15367 	}
15368 	case DL_CONTROL_ACK:
15369 		/* We treat all of these as "fire and forget" */
15370 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15371 		break;
15372 	case DL_INFO_ACK:
15373 		/* Call a routine to handle this one. */
15374 		ill_dlpi_done(ill, DL_INFO_REQ);
15375 		ip_ll_subnet_defaults(ill, mp);
15376 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15377 		return;
15378 	case DL_BIND_ACK:
15379 		/*
15380 		 * We should have an IOCTL waiting on this unless
15381 		 * sent by ill_dl_phys, in which case just return
15382 		 */
15383 		ill_dlpi_done(ill, DL_BIND_REQ);
15384 		if (ill->ill_ifname_pending)
15385 			break;
15386 
15387 		if (!ioctl_aborted)
15388 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15389 		if (mp1 == NULL)
15390 			break;
15391 		ASSERT(connp != NULL);
15392 		q = CONNP_TO_WQ(connp);
15393 
15394 		/*
15395 		 * We are exclusive. So nothing can change even after
15396 		 * we get the pending mp. If need be we can put it back
15397 		 * and restart, as in calling ipif_arp_up()  below.
15398 		 */
15399 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15400 
15401 		mutex_enter(&ill->ill_lock);
15402 
15403 		ill->ill_dl_up = 1;
15404 
15405 		if ((info = ill->ill_nic_event_info) != NULL) {
15406 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15407 			    "attached for %s\n", info->hne_event,
15408 			    ill->ill_name));
15409 			if (info->hne_data != NULL)
15410 				kmem_free(info->hne_data, info->hne_datalen);
15411 			kmem_free(info, sizeof (hook_nic_event_t));
15412 		}
15413 
15414 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15415 		if (info != NULL) {
15416 			info->hne_nic = ill->ill_phyint->phyint_ifindex;
15417 			info->hne_lif = 0;
15418 			info->hne_event = NE_UP;
15419 			info->hne_data = NULL;
15420 			info->hne_datalen = 0;
15421 			info->hne_family = ill->ill_isv6 ? ipv6 : ipv4;
15422 		} else
15423 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15424 			    "event information for %s (ENOMEM)\n",
15425 			    ill->ill_name));
15426 
15427 		ill->ill_nic_event_info = info;
15428 
15429 		mutex_exit(&ill->ill_lock);
15430 
15431 		/*
15432 		 * Now bring up the resolver; when that is complete, we'll
15433 		 * create IREs.  Note that we intentionally mirror what
15434 		 * ipif_up() would have done, because we got here by way of
15435 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15436 		 */
15437 		if (ill->ill_isv6) {
15438 			/*
15439 			 * v6 interfaces.
15440 			 * Unlike ARP which has to do another bind
15441 			 * and attach, once we get here we are
15442 			 * done with NDP. Except in the case of
15443 			 * ILLF_XRESOLV, in which case we send an
15444 			 * AR_INTERFACE_UP to the external resolver.
15445 			 * If all goes well, the ioctl will complete
15446 			 * in ip_rput(). If there's an error, we
15447 			 * complete it here.
15448 			 */
15449 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15450 			    B_FALSE);
15451 			if (err == 0) {
15452 				if (ill->ill_flags & ILLF_XRESOLV) {
15453 					mutex_enter(&connp->conn_lock);
15454 					mutex_enter(&ill->ill_lock);
15455 					success = ipsq_pending_mp_add(
15456 					    connp, ipif, q, mp1, 0);
15457 					mutex_exit(&ill->ill_lock);
15458 					mutex_exit(&connp->conn_lock);
15459 					if (success) {
15460 						err = ipif_resolver_up(ipif,
15461 						    Res_act_initial);
15462 						if (err == EINPROGRESS) {
15463 							freemsg(mp);
15464 							return;
15465 						}
15466 						ASSERT(err != 0);
15467 						mp1 = ipsq_pending_mp_get(ipsq,
15468 						    &connp);
15469 						ASSERT(mp1 != NULL);
15470 					} else {
15471 						/* conn has started closing */
15472 						err = EINTR;
15473 					}
15474 				} else { /* Non XRESOLV interface */
15475 					(void) ipif_resolver_up(ipif,
15476 					    Res_act_initial);
15477 					err = ipif_up_done_v6(ipif);
15478 				}
15479 			}
15480 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15481 			/*
15482 			 * ARP and other v4 external resolvers.
15483 			 * Leave the pending mblk intact so that
15484 			 * the ioctl completes in ip_rput().
15485 			 */
15486 			mutex_enter(&connp->conn_lock);
15487 			mutex_enter(&ill->ill_lock);
15488 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15489 			mutex_exit(&ill->ill_lock);
15490 			mutex_exit(&connp->conn_lock);
15491 			if (success) {
15492 				err = ipif_resolver_up(ipif, Res_act_initial);
15493 				if (err == EINPROGRESS) {
15494 					freemsg(mp);
15495 					return;
15496 				}
15497 				ASSERT(err != 0);
15498 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15499 			} else {
15500 				/* The conn has started closing */
15501 				err = EINTR;
15502 			}
15503 		} else {
15504 			/*
15505 			 * This one is complete. Reply to pending ioctl.
15506 			 */
15507 			(void) ipif_resolver_up(ipif, Res_act_initial);
15508 			err = ipif_up_done(ipif);
15509 		}
15510 
15511 		if ((err == 0) && (ill->ill_up_ipifs)) {
15512 			err = ill_up_ipifs(ill, q, mp1);
15513 			if (err == EINPROGRESS) {
15514 				freemsg(mp);
15515 				return;
15516 			}
15517 		}
15518 
15519 		if (ill->ill_up_ipifs) {
15520 			ill_group_cleanup(ill);
15521 		}
15522 
15523 		break;
15524 	case DL_NOTIFY_IND: {
15525 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15526 		ire_t *ire;
15527 		boolean_t need_ire_walk_v4 = B_FALSE;
15528 		boolean_t need_ire_walk_v6 = B_FALSE;
15529 
15530 		/*
15531 		 * Change the address everywhere we need to.
15532 		 * What we're getting here is a link-level addr or phys addr.
15533 		 * The new addr is at notify + notify->dl_addr_offset
15534 		 * The address length is notify->dl_addr_length;
15535 		 */
15536 		switch (notify->dl_notification) {
15537 		case DL_NOTE_PHYS_ADDR:
15538 			mp_hw = copyb(mp);
15539 			if (mp_hw == NULL) {
15540 				err = ENOMEM;
15541 				break;
15542 			}
15543 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15544 			/*
15545 			 * We currently don't support changing
15546 			 * the token via DL_NOTIFY_IND.
15547 			 * When we do support it, we have to consider
15548 			 * what the implications are with respect to
15549 			 * the token and the link local address.
15550 			 */
15551 			mutex_enter(&ill->ill_lock);
15552 			if (dlp->notify_ind.dl_data ==
15553 			    DL_IPV6_LINK_LAYER_ADDR) {
15554 				if (ill->ill_nd_lla_mp != NULL)
15555 					freemsg(ill->ill_nd_lla_mp);
15556 				ill->ill_nd_lla_mp = mp_hw;
15557 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15558 				    dlp->notify_ind.dl_addr_offset;
15559 				ill->ill_nd_lla_len =
15560 				    dlp->notify_ind.dl_addr_length -
15561 				    ABS(ill->ill_sap_length);
15562 				mutex_exit(&ill->ill_lock);
15563 				break;
15564 			} else if (dlp->notify_ind.dl_data ==
15565 			    DL_CURR_PHYS_ADDR) {
15566 				if (ill->ill_phys_addr_mp != NULL)
15567 					freemsg(ill->ill_phys_addr_mp);
15568 				ill->ill_phys_addr_mp = mp_hw;
15569 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15570 				    dlp->notify_ind.dl_addr_offset;
15571 				ill->ill_phys_addr_length =
15572 				    dlp->notify_ind.dl_addr_length -
15573 				    ABS(ill->ill_sap_length);
15574 				if (ill->ill_isv6 &&
15575 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15576 					if (ill->ill_nd_lla_mp != NULL)
15577 						freemsg(ill->ill_nd_lla_mp);
15578 					ill->ill_nd_lla_mp = copyb(mp_hw);
15579 					ill->ill_nd_lla = (uchar_t *)
15580 					    ill->ill_nd_lla_mp->b_rptr +
15581 					    dlp->notify_ind.dl_addr_offset;
15582 					ill->ill_nd_lla_len =
15583 					    ill->ill_phys_addr_length;
15584 				}
15585 			}
15586 			mutex_exit(&ill->ill_lock);
15587 			/*
15588 			 * Send out gratuitous arp request for our new
15589 			 * hardware address.
15590 			 */
15591 			for (ipif = ill->ill_ipif; ipif != NULL;
15592 			    ipif = ipif->ipif_next) {
15593 				if (!(ipif->ipif_flags & IPIF_UP))
15594 					continue;
15595 				if (ill->ill_isv6) {
15596 					ipif_ndp_down(ipif);
15597 					/*
15598 					 * Set B_TRUE to enable
15599 					 * ipif_ndp_up() to send out
15600 					 * unsolicited advertisements.
15601 					 */
15602 					err = ipif_ndp_up(ipif,
15603 					    &ipif->ipif_v6lcl_addr,
15604 					    B_TRUE);
15605 					if (err) {
15606 						ip1dbg((
15607 						    "ip_rput_dlpi_writer: "
15608 						    "Failed to update ndp "
15609 						    "err %d\n", err));
15610 					}
15611 				} else {
15612 					/*
15613 					 * IPv4 ARP case
15614 					 *
15615 					 * Set Res_act_move, as we only want
15616 					 * ipif_resolver_up to send an
15617 					 * AR_ENTRY_ADD request up to
15618 					 * ARP.
15619 					 */
15620 					err = ipif_resolver_up(ipif,
15621 					    Res_act_move);
15622 					if (err) {
15623 						ip1dbg((
15624 						    "ip_rput_dlpi_writer: "
15625 						    "Failed to update arp "
15626 						    "err %d\n", err));
15627 					}
15628 				}
15629 			}
15630 			/*
15631 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15632 			 * case so that all old fastpath information can be
15633 			 * purged from IRE caches.
15634 			 */
15635 		/* FALLTHRU */
15636 		case DL_NOTE_FASTPATH_FLUSH:
15637 			/*
15638 			 * Any fastpath probe sent henceforth will get the
15639 			 * new fp mp. So we first delete any ires that are
15640 			 * waiting for the fastpath. Then walk all ires and
15641 			 * delete the ire or delete the fp mp. In the case of
15642 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15643 			 * recreate the ire's without going through a complex
15644 			 * ipif up/down dance. So we don't delete the ire
15645 			 * itself, but just the nce_fp_mp for these 2 ire's
15646 			 * In the case of the other ire's we delete the ire's
15647 			 * themselves. Access to nce_fp_mp is completely
15648 			 * protected by ire_lock for IRE_MIPRTUN and
15649 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15650 			 * other cases for performance.
15651 			 */
15652 			if (ill->ill_isv6) {
15653 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15654 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15655 				    NULL);
15656 			} else {
15657 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15658 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15659 				    IRE_CACHE | IRE_BROADCAST,
15660 				    ire_fastpath_flush, NULL, ill);
15661 				mutex_enter(&ire_mrtun_lock);
15662 				if (ire_mrtun_count != 0) {
15663 					mutex_exit(&ire_mrtun_lock);
15664 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15665 					    IRE_MIPRTUN, ire_fastpath_flush,
15666 					    NULL, ill);
15667 				} else {
15668 					mutex_exit(&ire_mrtun_lock);
15669 				}
15670 			}
15671 			break;
15672 		case DL_NOTE_SDU_SIZE:
15673 			/*
15674 			 * Change the MTU size of the interface, of all
15675 			 * attached ipif's, and of all relevant ire's.  The
15676 			 * new value's a uint32_t at notify->dl_data.
15677 			 * Mtu change Vs. new ire creation - protocol below.
15678 			 *
15679 			 * a Mark the ipif as IPIF_CHANGING.
15680 			 * b Set the new mtu in the ipif.
15681 			 * c Change the ire_max_frag on all affected ires
15682 			 * d Unmark the IPIF_CHANGING
15683 			 *
15684 			 * To see how the protocol works, assume an interface
15685 			 * route is also being added simultaneously by
15686 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15687 			 * the ire. If the ire is created before step a,
15688 			 * it will be cleaned up by step c. If the ire is
15689 			 * created after step d, it will see the new value of
15690 			 * ipif_mtu. Any attempt to create the ire between
15691 			 * steps a to d will fail because of the IPIF_CHANGING
15692 			 * flag. Note that ire_create() is passed a pointer to
15693 			 * the ipif_mtu, and not the value. During ire_add
15694 			 * under the bucket lock, the ire_max_frag of the
15695 			 * new ire being created is set from the ipif/ire from
15696 			 * which it is being derived.
15697 			 */
15698 			mutex_enter(&ill->ill_lock);
15699 			ill->ill_max_frag = (uint_t)notify->dl_data;
15700 
15701 			/*
15702 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15703 			 * leave it alone
15704 			 */
15705 			if (ill->ill_mtu_userspecified) {
15706 				mutex_exit(&ill->ill_lock);
15707 				break;
15708 			}
15709 			ill->ill_max_mtu = ill->ill_max_frag;
15710 			if (ill->ill_isv6) {
15711 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15712 					ill->ill_max_mtu = IPV6_MIN_MTU;
15713 			} else {
15714 				if (ill->ill_max_mtu < IP_MIN_MTU)
15715 					ill->ill_max_mtu = IP_MIN_MTU;
15716 			}
15717 			for (ipif = ill->ill_ipif; ipif != NULL;
15718 			    ipif = ipif->ipif_next) {
15719 				/*
15720 				 * Don't override the mtu if the user
15721 				 * has explicitly set it.
15722 				 */
15723 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15724 					continue;
15725 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15726 				if (ipif->ipif_isv6)
15727 					ire = ipif_to_ire_v6(ipif);
15728 				else
15729 					ire = ipif_to_ire(ipif);
15730 				if (ire != NULL) {
15731 					ire->ire_max_frag = ipif->ipif_mtu;
15732 					ire_refrele(ire);
15733 				}
15734 				if (ipif->ipif_flags & IPIF_UP) {
15735 					if (ill->ill_isv6)
15736 						need_ire_walk_v6 = B_TRUE;
15737 					else
15738 						need_ire_walk_v4 = B_TRUE;
15739 				}
15740 			}
15741 			mutex_exit(&ill->ill_lock);
15742 			if (need_ire_walk_v4)
15743 				ire_walk_v4(ill_mtu_change, (char *)ill,
15744 				    ALL_ZONES);
15745 			if (need_ire_walk_v6)
15746 				ire_walk_v6(ill_mtu_change, (char *)ill,
15747 				    ALL_ZONES);
15748 			break;
15749 		case DL_NOTE_LINK_UP:
15750 		case DL_NOTE_LINK_DOWN: {
15751 			/*
15752 			 * We are writer. ill / phyint / ipsq assocs stable.
15753 			 * The RUNNING flag reflects the state of the link.
15754 			 */
15755 			phyint_t *phyint = ill->ill_phyint;
15756 			uint64_t new_phyint_flags;
15757 			boolean_t changed = B_FALSE;
15758 			boolean_t went_up;
15759 
15760 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15761 			mutex_enter(&phyint->phyint_lock);
15762 			new_phyint_flags = went_up ?
15763 			    phyint->phyint_flags | PHYI_RUNNING :
15764 			    phyint->phyint_flags & ~PHYI_RUNNING;
15765 			if (new_phyint_flags != phyint->phyint_flags) {
15766 				phyint->phyint_flags = new_phyint_flags;
15767 				changed = B_TRUE;
15768 			}
15769 			mutex_exit(&phyint->phyint_lock);
15770 			/*
15771 			 * ill_restart_dad handles the DAD restart and routing
15772 			 * socket notification logic.
15773 			 */
15774 			if (changed) {
15775 				ill_restart_dad(phyint->phyint_illv4, went_up);
15776 				ill_restart_dad(phyint->phyint_illv6, went_up);
15777 			}
15778 			break;
15779 		}
15780 		case DL_NOTE_PROMISC_ON_PHYS:
15781 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15782 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15783 			mutex_enter(&ill->ill_lock);
15784 			ill->ill_promisc_on_phys = B_TRUE;
15785 			mutex_exit(&ill->ill_lock);
15786 			break;
15787 		case DL_NOTE_PROMISC_OFF_PHYS:
15788 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15789 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15790 			mutex_enter(&ill->ill_lock);
15791 			ill->ill_promisc_on_phys = B_FALSE;
15792 			mutex_exit(&ill->ill_lock);
15793 			break;
15794 		case DL_NOTE_CAPAB_RENEG:
15795 			/*
15796 			 * Something changed on the driver side.
15797 			 * It wants us to renegotiate the capabilities
15798 			 * on this ill. The most likely cause is the
15799 			 * aggregation interface under us where a
15800 			 * port got added or went away.
15801 			 *
15802 			 * We reset the capabilities and set the
15803 			 * state to IDS_RENG so that when the ack
15804 			 * comes back, we can start the
15805 			 * renegotiation process.
15806 			 */
15807 			ill_capability_reset(ill);
15808 			ill->ill_dlpi_capab_state = IDS_RENEG;
15809 			break;
15810 		default:
15811 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15812 			    "type 0x%x for DL_NOTIFY_IND\n",
15813 			    notify->dl_notification));
15814 			break;
15815 		}
15816 
15817 		/*
15818 		 * As this is an asynchronous operation, we
15819 		 * should not call ill_dlpi_done
15820 		 */
15821 		break;
15822 	}
15823 	case DL_NOTIFY_ACK: {
15824 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15825 
15826 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15827 			ill->ill_note_link = 1;
15828 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15829 		break;
15830 	}
15831 	case DL_PHYS_ADDR_ACK: {
15832 		/*
15833 		 * We should have an IOCTL waiting on this when request
15834 		 * sent by ill_dl_phys.
15835 		 * However, ill_dl_phys was called on an ill queue (from
15836 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15837 		 * ioctl is known to be pending on ill_wq.
15838 		 * There are two additional phys_addr_req's sent to the
15839 		 * driver to get the token and lla. ill_phys_addr_pend
15840 		 * keeps track of the last one sent so we know which
15841 		 * response we are dealing with. ill_dlpi_done will
15842 		 * update ill_phys_addr_pend when it sends the next req.
15843 		 * We don't complete the IOCTL until all three DL_PARs
15844 		 * have been attempted.
15845 		 *
15846 		 * We don't need any lock to update ill_nd_lla* fields,
15847 		 * since the ill is not yet up, We grab the lock just
15848 		 * for uniformity with other code that accesses ill_nd_lla.
15849 		 */
15850 		physaddr_req = ill->ill_phys_addr_pend;
15851 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15852 		if (physaddr_req == DL_IPV6_TOKEN ||
15853 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15854 			if (physaddr_req == DL_IPV6_TOKEN) {
15855 				/*
15856 				 * bcopy to low-order bits of ill_token
15857 				 *
15858 				 * XXX Temporary hack - currently,
15859 				 * all known tokens are 64 bits,
15860 				 * so I'll cheat for the moment.
15861 				 */
15862 				dlp = (union DL_primitives *)mp->b_rptr;
15863 
15864 				mutex_enter(&ill->ill_lock);
15865 				bcopy((uchar_t *)(mp->b_rptr +
15866 				dlp->physaddr_ack.dl_addr_offset),
15867 				(void *)&ill->ill_token.s6_addr32[2],
15868 				dlp->physaddr_ack.dl_addr_length);
15869 				ill->ill_token_length =
15870 					dlp->physaddr_ack.dl_addr_length;
15871 				mutex_exit(&ill->ill_lock);
15872 			} else {
15873 				ASSERT(ill->ill_nd_lla_mp == NULL);
15874 				mp_hw = copyb(mp);
15875 				if (mp_hw == NULL) {
15876 					err = ENOMEM;
15877 					break;
15878 				}
15879 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15880 				mutex_enter(&ill->ill_lock);
15881 				ill->ill_nd_lla_mp = mp_hw;
15882 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15883 				dlp->physaddr_ack.dl_addr_offset;
15884 				ill->ill_nd_lla_len =
15885 					dlp->physaddr_ack.dl_addr_length;
15886 				mutex_exit(&ill->ill_lock);
15887 			}
15888 			break;
15889 		}
15890 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15891 		ASSERT(ill->ill_phys_addr_mp == NULL);
15892 		if (!ill->ill_ifname_pending)
15893 			break;
15894 		ill->ill_ifname_pending = 0;
15895 		if (!ioctl_aborted)
15896 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15897 		if (mp1 != NULL) {
15898 			ASSERT(connp == NULL);
15899 			q = ill->ill_wq;
15900 		}
15901 		/*
15902 		 * If any error acks received during the plumbing sequence,
15903 		 * ill_ifname_pending_err will be set. Break out and send up
15904 		 * the error to the pending ioctl.
15905 		 */
15906 		if (ill->ill_ifname_pending_err != 0) {
15907 			err = ill->ill_ifname_pending_err;
15908 			ill->ill_ifname_pending_err = 0;
15909 			break;
15910 		}
15911 		/*
15912 		 * Get the interface token.  If the zeroth interface
15913 		 * address is zero then set the address to the link local
15914 		 * address
15915 		 */
15916 		mp_hw = copyb(mp);
15917 		if (mp_hw == NULL) {
15918 			err = ENOMEM;
15919 			break;
15920 		}
15921 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15922 		ill->ill_phys_addr_mp = mp_hw;
15923 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15924 				dlp->physaddr_ack.dl_addr_offset;
15925 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15926 		    ill->ill_phys_addr_length == 0 ||
15927 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15928 			/*
15929 			 * Compatibility: atun driver returns a length of 0.
15930 			 * ipdptp has an ill_phys_addr_length of zero(from
15931 			 * DL_BIND_ACK) but a non-zero length here.
15932 			 * ipd has an ill_phys_addr_length of 4(from
15933 			 * DL_BIND_ACK) but a non-zero length here.
15934 			 */
15935 			ill->ill_phys_addr = NULL;
15936 		} else if (dlp->physaddr_ack.dl_addr_length !=
15937 		    ill->ill_phys_addr_length) {
15938 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15939 			    "Address length mismatch %d %d\n",
15940 			    dlp->physaddr_ack.dl_addr_length,
15941 			    ill->ill_phys_addr_length));
15942 			err = EINVAL;
15943 			break;
15944 		}
15945 		mutex_enter(&ill->ill_lock);
15946 		if (ill->ill_nd_lla_mp == NULL) {
15947 			ill->ill_nd_lla_mp = copyb(mp_hw);
15948 			if (ill->ill_nd_lla_mp == NULL) {
15949 				err = ENOMEM;
15950 				mutex_exit(&ill->ill_lock);
15951 				break;
15952 			}
15953 			ill->ill_nd_lla =
15954 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15955 			    dlp->physaddr_ack.dl_addr_offset;
15956 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15957 		}
15958 		mutex_exit(&ill->ill_lock);
15959 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15960 			(void) ill_setdefaulttoken(ill);
15961 
15962 		/*
15963 		 * If the ill zero interface has a zero address assign
15964 		 * it the proper link local address.
15965 		 */
15966 		ASSERT(ill->ill_ipif->ipif_id == 0);
15967 		if (ipif != NULL &&
15968 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15969 			(void) ipif_setlinklocal(ipif);
15970 		break;
15971 	}
15972 	case DL_OK_ACK:
15973 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15974 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15975 		    dloa->dl_correct_primitive));
15976 		switch (dloa->dl_correct_primitive) {
15977 		case DL_UNBIND_REQ:
15978 		case DL_ATTACH_REQ:
15979 		case DL_DETACH_REQ:
15980 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15981 			break;
15982 		}
15983 		break;
15984 	default:
15985 		break;
15986 	}
15987 
15988 	freemsg(mp);
15989 	if (mp1) {
15990 		struct iocblk *iocp;
15991 		int mode;
15992 
15993 		/*
15994 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15995 		 * SIOCSLIFNAME do a copyout.
15996 		 */
15997 		iocp = (struct iocblk *)mp1->b_rptr;
15998 
15999 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
16000 		    iocp->ioc_cmd == SIOCSLIFNAME)
16001 			mode = COPYOUT;
16002 		else
16003 			mode = NO_COPYOUT;
16004 		/*
16005 		 * The ioctl must complete now without EINPROGRESS
16006 		 * since ipsq_pending_mp_get has removed the ioctl mblk
16007 		 * from ipsq_pending_mp. Otherwise the ioctl will be
16008 		 * stuck for ever in the ipsq.
16009 		 */
16010 		ASSERT(err != EINPROGRESS);
16011 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
16012 
16013 	}
16014 }
16015 
16016 /*
16017  * ip_rput_other is called by ip_rput to handle messages modifying the global
16018  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16019  */
16020 /* ARGSUSED */
16021 void
16022 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16023 {
16024 	ill_t		*ill;
16025 	struct iocblk	*iocp;
16026 	mblk_t		*mp1;
16027 	conn_t		*connp = NULL;
16028 
16029 	ip1dbg(("ip_rput_other "));
16030 	ill = (ill_t *)q->q_ptr;
16031 	/*
16032 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16033 	 * in which case ipsq is NULL.
16034 	 */
16035 	if (ipsq != NULL) {
16036 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16037 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16038 	}
16039 
16040 	switch (mp->b_datap->db_type) {
16041 	case M_ERROR:
16042 	case M_HANGUP:
16043 		/*
16044 		 * The device has a problem.  We force the ILL down.  It can
16045 		 * be brought up again manually using SIOCSIFFLAGS (via
16046 		 * ifconfig or equivalent).
16047 		 */
16048 		ASSERT(ipsq != NULL);
16049 		if (mp->b_rptr < mp->b_wptr)
16050 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16051 		if (ill->ill_error == 0)
16052 			ill->ill_error = ENXIO;
16053 		if (!ill_down_start(q, mp))
16054 			return;
16055 		ipif_all_down_tail(ipsq, q, mp, NULL);
16056 		break;
16057 	case M_IOCACK:
16058 		iocp = (struct iocblk *)mp->b_rptr;
16059 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16060 		switch (iocp->ioc_cmd) {
16061 		case SIOCSTUNPARAM:
16062 		case OSIOCSTUNPARAM:
16063 			ASSERT(ipsq != NULL);
16064 			/*
16065 			 * Finish socket ioctl passed through to tun.
16066 			 * We should have an IOCTL waiting on this.
16067 			 */
16068 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16069 			if (ill->ill_isv6) {
16070 				struct iftun_req *ta;
16071 
16072 				/*
16073 				 * if a source or destination is
16074 				 * being set, try and set the link
16075 				 * local address for the tunnel
16076 				 */
16077 				ta = (struct iftun_req *)mp->b_cont->
16078 				    b_cont->b_rptr;
16079 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16080 					ipif_set_tun_llink(ill, ta);
16081 				}
16082 
16083 			}
16084 			if (mp1 != NULL) {
16085 				/*
16086 				 * Now copy back the b_next/b_prev used by
16087 				 * mi code for the mi_copy* functions.
16088 				 * See ip_sioctl_tunparam() for the reason.
16089 				 * Also protect against missing b_cont.
16090 				 */
16091 				if (mp->b_cont != NULL) {
16092 					mp->b_cont->b_next =
16093 					    mp1->b_cont->b_next;
16094 					mp->b_cont->b_prev =
16095 					    mp1->b_cont->b_prev;
16096 				}
16097 				inet_freemsg(mp1);
16098 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16099 				ASSERT(connp != NULL);
16100 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16101 				    iocp->ioc_error, NO_COPYOUT,
16102 				    ipsq->ipsq_current_ipif, ipsq);
16103 			} else {
16104 				ASSERT(connp == NULL);
16105 				putnext(q, mp);
16106 			}
16107 			break;
16108 		case SIOCGTUNPARAM:
16109 		case OSIOCGTUNPARAM:
16110 			/*
16111 			 * This is really M_IOCDATA from the tunnel driver.
16112 			 * convert back and complete the ioctl.
16113 			 * We should have an IOCTL waiting on this.
16114 			 */
16115 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16116 			if (mp1) {
16117 				/*
16118 				 * Now copy back the b_next/b_prev used by
16119 				 * mi code for the mi_copy* functions.
16120 				 * See ip_sioctl_tunparam() for the reason.
16121 				 * Also protect against missing b_cont.
16122 				 */
16123 				if (mp->b_cont != NULL) {
16124 					mp->b_cont->b_next =
16125 					    mp1->b_cont->b_next;
16126 					mp->b_cont->b_prev =
16127 					    mp1->b_cont->b_prev;
16128 				}
16129 				inet_freemsg(mp1);
16130 				if (iocp->ioc_error == 0)
16131 					mp->b_datap->db_type = M_IOCDATA;
16132 				ASSERT(connp != NULL);
16133 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16134 				    iocp->ioc_error, COPYOUT, NULL, NULL);
16135 			} else {
16136 				ASSERT(connp == NULL);
16137 				putnext(q, mp);
16138 			}
16139 			break;
16140 		default:
16141 			break;
16142 		}
16143 		break;
16144 	case M_IOCNAK:
16145 		iocp = (struct iocblk *)mp->b_rptr;
16146 
16147 		switch (iocp->ioc_cmd) {
16148 		int mode;
16149 		ipif_t	*ipif;
16150 
16151 		case DL_IOC_HDR_INFO:
16152 			/*
16153 			 * If this was the first attempt turn of the
16154 			 * fastpath probing.
16155 			 */
16156 			mutex_enter(&ill->ill_lock);
16157 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16158 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16159 				mutex_exit(&ill->ill_lock);
16160 				ill_fastpath_nack(ill);
16161 				ip1dbg(("ip_rput: DLPI fastpath off on "
16162 				    "interface %s\n",
16163 				    ill->ill_name));
16164 			} else {
16165 				mutex_exit(&ill->ill_lock);
16166 			}
16167 			freemsg(mp);
16168 			break;
16169 		case SIOCSTUNPARAM:
16170 		case OSIOCSTUNPARAM:
16171 			ASSERT(ipsq != NULL);
16172 			/*
16173 			 * Finish socket ioctl passed through to tun
16174 			 * We should have an IOCTL waiting on this.
16175 			 */
16176 			/* FALLTHRU */
16177 		case SIOCGTUNPARAM:
16178 		case OSIOCGTUNPARAM:
16179 			/*
16180 			 * This is really M_IOCDATA from the tunnel driver.
16181 			 * convert back and complete the ioctl.
16182 			 * We should have an IOCTL waiting on this.
16183 			 */
16184 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16185 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16186 				mp1 = ill_pending_mp_get(ill, &connp,
16187 				    iocp->ioc_id);
16188 				mode = COPYOUT;
16189 				ipsq = NULL;
16190 				ipif = NULL;
16191 			} else {
16192 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16193 				mode = NO_COPYOUT;
16194 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16195 				ipif = ipsq->ipsq_current_ipif;
16196 			}
16197 			if (mp1 != NULL) {
16198 				/*
16199 				 * Now copy back the b_next/b_prev used by
16200 				 * mi code for the mi_copy* functions.
16201 				 * See ip_sioctl_tunparam() for the reason.
16202 				 * Also protect against missing b_cont.
16203 				 */
16204 				if (mp->b_cont != NULL) {
16205 					mp->b_cont->b_next =
16206 					    mp1->b_cont->b_next;
16207 					mp->b_cont->b_prev =
16208 					    mp1->b_cont->b_prev;
16209 				}
16210 				inet_freemsg(mp1);
16211 				if (iocp->ioc_error == 0)
16212 					iocp->ioc_error = EINVAL;
16213 				ASSERT(connp != NULL);
16214 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16215 				    iocp->ioc_error, mode, ipif, ipsq);
16216 			} else {
16217 				ASSERT(connp == NULL);
16218 				putnext(q, mp);
16219 			}
16220 			break;
16221 		default:
16222 			break;
16223 		}
16224 	default:
16225 		break;
16226 	}
16227 }
16228 
16229 /*
16230  * NOTE : This function does not ire_refrele the ire argument passed in.
16231  *
16232  * IPQoS notes
16233  * IP policy is invoked twice for a forwarded packet, once on the read side
16234  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16235  * enabled. An additional parameter, in_ill, has been added for this purpose.
16236  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16237  * because ip_mroute drops this information.
16238  *
16239  */
16240 void
16241 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16242 {
16243 	uint32_t	pkt_len;
16244 	queue_t	*q;
16245 	uint32_t	sum;
16246 #define	rptr	((uchar_t *)ipha)
16247 	uint32_t	max_frag;
16248 	uint32_t	ill_index;
16249 	ill_t		*out_ill;
16250 
16251 	/* Get the ill_index of the incoming ILL */
16252 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16253 
16254 	/* Initiate Read side IPPF processing */
16255 	if (IPP_ENABLED(IPP_FWD_IN)) {
16256 		ip_process(IPP_FWD_IN, &mp, ill_index);
16257 		if (mp == NULL) {
16258 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16259 			    "during IPPF processing\n"));
16260 			return;
16261 		}
16262 	}
16263 
16264 	pkt_len = ntohs(ipha->ipha_length);
16265 
16266 	/* Adjust the checksum to reflect the ttl decrement. */
16267 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16268 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16269 
16270 	if (ipha->ipha_ttl-- <= 1) {
16271 		if (ip_csum_hdr(ipha)) {
16272 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16273 			goto drop_pkt;
16274 		}
16275 		/*
16276 		 * Note: ire_stq this will be NULL for multicast
16277 		 * datagrams using the long path through arp (the IRE
16278 		 * is not an IRE_CACHE). This should not cause
16279 		 * problems since we don't generate ICMP errors for
16280 		 * multicast packets.
16281 		 */
16282 		q = ire->ire_stq;
16283 		if (q != NULL) {
16284 			/* Sent by forwarding path, and router is global zone */
16285 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16286 			    GLOBAL_ZONEID);
16287 		} else
16288 			freemsg(mp);
16289 		return;
16290 	}
16291 
16292 	/*
16293 	 * Don't forward if the interface is down
16294 	 */
16295 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16296 		BUMP_MIB(&ip_mib, ipInDiscards);
16297 		ip2dbg(("ip_rput_forward:interface is down\n"));
16298 		goto drop_pkt;
16299 	}
16300 
16301 	/* Get the ill_index of the outgoing ILL */
16302 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16303 
16304 	out_ill = ire->ire_ipif->ipif_ill;
16305 
16306 	DTRACE_PROBE4(ip4__forwarding__start,
16307 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16308 
16309 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
16310 	    in_ill, out_ill, ipha, mp, mp);
16311 
16312 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16313 
16314 	if (mp == NULL)
16315 		return;
16316 	pkt_len = ntohs(ipha->ipha_length);
16317 
16318 	if (is_system_labeled()) {
16319 		mblk_t *mp1;
16320 
16321 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16322 			BUMP_MIB(&ip_mib, ipForwProhibits);
16323 			goto drop_pkt;
16324 		}
16325 		/* Size may have changed */
16326 		mp = mp1;
16327 		ipha = (ipha_t *)mp->b_rptr;
16328 		pkt_len = ntohs(ipha->ipha_length);
16329 	}
16330 
16331 	/* Check if there are options to update */
16332 	if (!IS_SIMPLE_IPH(ipha)) {
16333 		if (ip_csum_hdr(ipha)) {
16334 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16335 			goto drop_pkt;
16336 		}
16337 		if (ip_rput_forward_options(mp, ipha, ire)) {
16338 			return;
16339 		}
16340 
16341 		ipha->ipha_hdr_checksum = 0;
16342 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16343 	}
16344 	max_frag = ire->ire_max_frag;
16345 	if (pkt_len > max_frag) {
16346 		/*
16347 		 * It needs fragging on its way out.  We haven't
16348 		 * verified the header checksum yet.  Since we
16349 		 * are going to put a surely good checksum in the
16350 		 * outgoing header, we have to make sure that it
16351 		 * was good coming in.
16352 		 */
16353 		if (ip_csum_hdr(ipha)) {
16354 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16355 			goto drop_pkt;
16356 		}
16357 		/* Initiate Write side IPPF processing */
16358 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16359 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16360 			if (mp == NULL) {
16361 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16362 				    " during IPPF processing\n"));
16363 				return;
16364 			}
16365 		}
16366 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
16367 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16368 		return;
16369 	}
16370 
16371 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16372 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16373 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
16374 	    NULL, out_ill, ipha, mp, mp);
16375 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16376 	if (mp == NULL)
16377 		return;
16378 
16379 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16380 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16381 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16382 	/* ip_xmit_v4 always consumes the packet */
16383 	return;
16384 
16385 drop_pkt:;
16386 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16387 	freemsg(mp);
16388 #undef	rptr
16389 }
16390 
16391 void
16392 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16393 {
16394 	ire_t	*ire;
16395 
16396 	ASSERT(!ipif->ipif_isv6);
16397 	/*
16398 	 * Find an IRE which matches the destination and the outgoing
16399 	 * queue in the cache table. All we need is an IRE_CACHE which
16400 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16401 	 * then it is enough to have some IRE_CACHE in the group.
16402 	 */
16403 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16404 		dst = ipif->ipif_pp_dst_addr;
16405 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16406 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16407 	if (ire == NULL) {
16408 		/*
16409 		 * Mark this packet to make it be delivered to
16410 		 * ip_rput_forward after the new ire has been
16411 		 * created.
16412 		 */
16413 		mp->b_prev = NULL;
16414 		mp->b_next = mp;
16415 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16416 		    NULL, 0, GLOBAL_ZONEID);
16417 	} else {
16418 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16419 		IRE_REFRELE(ire);
16420 	}
16421 }
16422 
16423 /* Update any source route, record route or timestamp options */
16424 static int
16425 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16426 {
16427 	ipoptp_t	opts;
16428 	uchar_t		*opt;
16429 	uint8_t		optval;
16430 	uint8_t		optlen;
16431 	ipaddr_t	dst;
16432 	uint32_t	ts;
16433 	ire_t		*dst_ire = NULL;
16434 	ire_t		*tmp_ire = NULL;
16435 	timestruc_t	now;
16436 
16437 	ip2dbg(("ip_rput_forward_options\n"));
16438 	dst = ipha->ipha_dst;
16439 	for (optval = ipoptp_first(&opts, ipha);
16440 	    optval != IPOPT_EOL;
16441 	    optval = ipoptp_next(&opts)) {
16442 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16443 		opt = opts.ipoptp_cur;
16444 		optlen = opts.ipoptp_len;
16445 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16446 		    optval, opts.ipoptp_len));
16447 		switch (optval) {
16448 			uint32_t off;
16449 		case IPOPT_SSRR:
16450 		case IPOPT_LSRR:
16451 			/* Check if adminstratively disabled */
16452 			if (!ip_forward_src_routed) {
16453 				BUMP_MIB(&ip_mib, ipForwProhibits);
16454 				if (ire->ire_stq != NULL) {
16455 					/*
16456 					 * Sent by forwarding path, and router
16457 					 * is global zone
16458 					 */
16459 					icmp_unreachable(ire->ire_stq, mp,
16460 					    ICMP_SOURCE_ROUTE_FAILED,
16461 					    GLOBAL_ZONEID);
16462 				} else {
16463 					ip0dbg(("ip_rput_forward_options: "
16464 					    "unable to send unreach\n"));
16465 					freemsg(mp);
16466 				}
16467 				return (-1);
16468 			}
16469 
16470 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16471 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16472 			if (dst_ire == NULL) {
16473 				/*
16474 				 * Must be partial since ip_rput_options
16475 				 * checked for strict.
16476 				 */
16477 				break;
16478 			}
16479 			off = opt[IPOPT_OFFSET];
16480 			off--;
16481 		redo_srr:
16482 			if (optlen < IP_ADDR_LEN ||
16483 			    off > optlen - IP_ADDR_LEN) {
16484 				/* End of source route */
16485 				ip1dbg((
16486 				    "ip_rput_forward_options: end of SR\n"));
16487 				ire_refrele(dst_ire);
16488 				break;
16489 			}
16490 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16491 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16492 			    IP_ADDR_LEN);
16493 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16494 			    ntohl(dst)));
16495 
16496 			/*
16497 			 * Check if our address is present more than
16498 			 * once as consecutive hops in source route.
16499 			 */
16500 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16501 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16502 			if (tmp_ire != NULL) {
16503 				ire_refrele(tmp_ire);
16504 				off += IP_ADDR_LEN;
16505 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16506 				goto redo_srr;
16507 			}
16508 			ipha->ipha_dst = dst;
16509 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16510 			ire_refrele(dst_ire);
16511 			break;
16512 		case IPOPT_RR:
16513 			off = opt[IPOPT_OFFSET];
16514 			off--;
16515 			if (optlen < IP_ADDR_LEN ||
16516 			    off > optlen - IP_ADDR_LEN) {
16517 				/* No more room - ignore */
16518 				ip1dbg((
16519 				    "ip_rput_forward_options: end of RR\n"));
16520 				break;
16521 			}
16522 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16523 			    IP_ADDR_LEN);
16524 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16525 			break;
16526 		case IPOPT_TS:
16527 			/* Insert timestamp if there is room */
16528 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16529 			case IPOPT_TS_TSONLY:
16530 				off = IPOPT_TS_TIMELEN;
16531 				break;
16532 			case IPOPT_TS_PRESPEC:
16533 			case IPOPT_TS_PRESPEC_RFC791:
16534 				/* Verify that the address matched */
16535 				off = opt[IPOPT_OFFSET] - 1;
16536 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16537 				dst_ire = ire_ctable_lookup(dst, 0,
16538 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16539 				    MATCH_IRE_TYPE);
16540 
16541 				if (dst_ire == NULL) {
16542 					/* Not for us */
16543 					break;
16544 				}
16545 				ire_refrele(dst_ire);
16546 				/* FALLTHRU */
16547 			case IPOPT_TS_TSANDADDR:
16548 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16549 				break;
16550 			default:
16551 				/*
16552 				 * ip_*put_options should have already
16553 				 * dropped this packet.
16554 				 */
16555 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16556 				    "unknown IT - bug in ip_rput_options?\n");
16557 				return (0);	/* Keep "lint" happy */
16558 			}
16559 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16560 				/* Increase overflow counter */
16561 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16562 				opt[IPOPT_POS_OV_FLG] =
16563 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16564 				    (off << 4));
16565 				break;
16566 			}
16567 			off = opt[IPOPT_OFFSET] - 1;
16568 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16569 			case IPOPT_TS_PRESPEC:
16570 			case IPOPT_TS_PRESPEC_RFC791:
16571 			case IPOPT_TS_TSANDADDR:
16572 				bcopy(&ire->ire_src_addr,
16573 				    (char *)opt + off, IP_ADDR_LEN);
16574 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16575 				/* FALLTHRU */
16576 			case IPOPT_TS_TSONLY:
16577 				off = opt[IPOPT_OFFSET] - 1;
16578 				/* Compute # of milliseconds since midnight */
16579 				gethrestime(&now);
16580 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16581 				    now.tv_nsec / (NANOSEC / MILLISEC);
16582 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16583 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16584 				break;
16585 			}
16586 			break;
16587 		}
16588 	}
16589 	return (0);
16590 }
16591 
16592 /*
16593  * This is called after processing at least one of AH/ESP headers.
16594  *
16595  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16596  * the actual, physical interface on which the packet was received,
16597  * but, when ip_strict_dst_multihoming is set to 1, could be the
16598  * interface which had the ipha_dst configured when the packet went
16599  * through ip_rput. The ill_index corresponding to the recv_ill
16600  * is saved in ipsec_in_rill_index
16601  */
16602 void
16603 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16604 {
16605 	mblk_t *mp;
16606 	ipaddr_t dst;
16607 	in6_addr_t *v6dstp;
16608 	ipha_t *ipha;
16609 	ip6_t *ip6h;
16610 	ipsec_in_t *ii;
16611 	boolean_t ill_need_rele = B_FALSE;
16612 	boolean_t rill_need_rele = B_FALSE;
16613 	boolean_t ire_need_rele = B_FALSE;
16614 
16615 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16616 	ASSERT(ii->ipsec_in_ill_index != 0);
16617 
16618 	mp = ipsec_mp->b_cont;
16619 	ASSERT(mp != NULL);
16620 
16621 
16622 	if (ill == NULL) {
16623 		ASSERT(recv_ill == NULL);
16624 		/*
16625 		 * We need to get the original queue on which ip_rput_local
16626 		 * or ip_rput_data_v6 was called.
16627 		 */
16628 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16629 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16630 		ill_need_rele = B_TRUE;
16631 
16632 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16633 			recv_ill = ill_lookup_on_ifindex(
16634 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16635 			    NULL, NULL, NULL, NULL);
16636 			rill_need_rele = B_TRUE;
16637 		} else {
16638 			recv_ill = ill;
16639 		}
16640 
16641 		if ((ill == NULL) || (recv_ill == NULL)) {
16642 			ip0dbg(("ip_fanout_proto_again: interface "
16643 			    "disappeared\n"));
16644 			if (ill != NULL)
16645 				ill_refrele(ill);
16646 			if (recv_ill != NULL)
16647 				ill_refrele(recv_ill);
16648 			freemsg(ipsec_mp);
16649 			return;
16650 		}
16651 	}
16652 
16653 	ASSERT(ill != NULL && recv_ill != NULL);
16654 
16655 	if (mp->b_datap->db_type == M_CTL) {
16656 		/*
16657 		 * AH/ESP is returning the ICMP message after
16658 		 * removing their headers. Fanout again till
16659 		 * it gets to the right protocol.
16660 		 */
16661 		if (ii->ipsec_in_v4) {
16662 			icmph_t *icmph;
16663 			int iph_hdr_length;
16664 			int hdr_length;
16665 
16666 			ipha = (ipha_t *)mp->b_rptr;
16667 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16668 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16669 			ipha = (ipha_t *)&icmph[1];
16670 			hdr_length = IPH_HDR_LENGTH(ipha);
16671 			/*
16672 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16673 			 * Reset the type to M_DATA.
16674 			 */
16675 			mp->b_datap->db_type = M_DATA;
16676 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16677 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16678 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16679 		} else {
16680 			icmp6_t *icmp6;
16681 			int hdr_length;
16682 
16683 			ip6h = (ip6_t *)mp->b_rptr;
16684 			/* Don't call hdr_length_v6() unless you have to. */
16685 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16686 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16687 			else
16688 				hdr_length = IPV6_HDR_LEN;
16689 
16690 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16691 			/*
16692 			 * icmp_inbound_error_fanout_v6 may need to do
16693 			 * pullupmsg.  Reset the type to M_DATA.
16694 			 */
16695 			mp->b_datap->db_type = M_DATA;
16696 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16697 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16698 		}
16699 		if (ill_need_rele)
16700 			ill_refrele(ill);
16701 		if (rill_need_rele)
16702 			ill_refrele(recv_ill);
16703 		return;
16704 	}
16705 
16706 	if (ii->ipsec_in_v4) {
16707 		ipha = (ipha_t *)mp->b_rptr;
16708 		dst = ipha->ipha_dst;
16709 		if (CLASSD(dst)) {
16710 			/*
16711 			 * Multicast has to be delivered to all streams.
16712 			 */
16713 			dst = INADDR_BROADCAST;
16714 		}
16715 
16716 		if (ire == NULL) {
16717 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16718 			    MBLK_GETLABEL(mp));
16719 			if (ire == NULL) {
16720 				if (ill_need_rele)
16721 					ill_refrele(ill);
16722 				if (rill_need_rele)
16723 					ill_refrele(recv_ill);
16724 				ip1dbg(("ip_fanout_proto_again: "
16725 				    "IRE not found"));
16726 				freemsg(ipsec_mp);
16727 				return;
16728 			}
16729 			ire_need_rele = B_TRUE;
16730 		}
16731 
16732 		switch (ipha->ipha_protocol) {
16733 			case IPPROTO_UDP:
16734 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16735 				    recv_ill);
16736 				if (ire_need_rele)
16737 					ire_refrele(ire);
16738 				break;
16739 			case IPPROTO_TCP:
16740 				if (!ire_need_rele)
16741 					IRE_REFHOLD(ire);
16742 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16743 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16744 				IRE_REFRELE(ire);
16745 				if (mp != NULL)
16746 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16747 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16748 				break;
16749 			case IPPROTO_SCTP:
16750 				if (!ire_need_rele)
16751 					IRE_REFHOLD(ire);
16752 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16753 				    ipsec_mp, 0, ill->ill_rq, dst);
16754 				break;
16755 			default:
16756 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16757 				    recv_ill);
16758 				if (ire_need_rele)
16759 					ire_refrele(ire);
16760 				break;
16761 		}
16762 	} else {
16763 		uint32_t rput_flags = 0;
16764 
16765 		ip6h = (ip6_t *)mp->b_rptr;
16766 		v6dstp = &ip6h->ip6_dst;
16767 		/*
16768 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16769 		 * address.
16770 		 *
16771 		 * Currently, we don't store that state in the IPSEC_IN
16772 		 * message, and we may need to.
16773 		 */
16774 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16775 		    IP6_IN_LLMCAST : 0);
16776 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16777 		    NULL, NULL);
16778 	}
16779 	if (ill_need_rele)
16780 		ill_refrele(ill);
16781 	if (rill_need_rele)
16782 		ill_refrele(recv_ill);
16783 }
16784 
16785 /*
16786  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16787  * returns 'true' if there are still fragments left on the queue, in
16788  * which case we restart the timer.
16789  */
16790 void
16791 ill_frag_timer(void *arg)
16792 {
16793 	ill_t	*ill = (ill_t *)arg;
16794 	boolean_t frag_pending;
16795 
16796 	mutex_enter(&ill->ill_lock);
16797 	ASSERT(!ill->ill_fragtimer_executing);
16798 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16799 		ill->ill_frag_timer_id = 0;
16800 		mutex_exit(&ill->ill_lock);
16801 		return;
16802 	}
16803 	ill->ill_fragtimer_executing = 1;
16804 	mutex_exit(&ill->ill_lock);
16805 
16806 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16807 
16808 	/*
16809 	 * Restart the timer, if we have fragments pending or if someone
16810 	 * wanted us to be scheduled again.
16811 	 */
16812 	mutex_enter(&ill->ill_lock);
16813 	ill->ill_fragtimer_executing = 0;
16814 	ill->ill_frag_timer_id = 0;
16815 	if (frag_pending || ill->ill_fragtimer_needrestart)
16816 		ill_frag_timer_start(ill);
16817 	mutex_exit(&ill->ill_lock);
16818 }
16819 
16820 void
16821 ill_frag_timer_start(ill_t *ill)
16822 {
16823 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16824 
16825 	/* If the ill is closing or opening don't proceed */
16826 	if (ill->ill_state_flags & ILL_CONDEMNED)
16827 		return;
16828 
16829 	if (ill->ill_fragtimer_executing) {
16830 		/*
16831 		 * ill_frag_timer is currently executing. Just record the
16832 		 * the fact that we want the timer to be restarted.
16833 		 * ill_frag_timer will post a timeout before it returns,
16834 		 * ensuring it will be called again.
16835 		 */
16836 		ill->ill_fragtimer_needrestart = 1;
16837 		return;
16838 	}
16839 
16840 	if (ill->ill_frag_timer_id == 0) {
16841 		/*
16842 		 * The timer is neither running nor is the timeout handler
16843 		 * executing. Post a timeout so that ill_frag_timer will be
16844 		 * called
16845 		 */
16846 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16847 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16848 		ill->ill_fragtimer_needrestart = 0;
16849 	}
16850 }
16851 
16852 /*
16853  * This routine is needed for loopback when forwarding multicasts.
16854  *
16855  * IPQoS Notes:
16856  * IPPF processing is done in fanout routines.
16857  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16858  * processing for IPSec packets is done when it comes back in clear.
16859  * NOTE : The callers of this function need to do the ire_refrele for the
16860  *	  ire that is being passed in.
16861  */
16862 void
16863 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16864     ill_t *recv_ill)
16865 {
16866 	ill_t	*ill = (ill_t *)q->q_ptr;
16867 	uint32_t	sum;
16868 	uint32_t	u1;
16869 	uint32_t	u2;
16870 	int		hdr_length;
16871 	boolean_t	mctl_present;
16872 	mblk_t		*first_mp = mp;
16873 	mblk_t		*hada_mp = NULL;
16874 	ipha_t		*inner_ipha;
16875 
16876 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16877 	    "ip_rput_locl_start: q %p", q);
16878 
16879 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16880 
16881 
16882 #define	rptr	((uchar_t *)ipha)
16883 #define	iphs	((uint16_t *)ipha)
16884 
16885 	/*
16886 	 * no UDP or TCP packet should come here anymore.
16887 	 */
16888 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16889 	    (ipha->ipha_protocol != IPPROTO_UDP));
16890 
16891 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16892 	if (mctl_present &&
16893 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16894 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16895 
16896 		/*
16897 		 * It's an IPsec accelerated packet.
16898 		 * Keep a pointer to the data attributes around until
16899 		 * we allocate the ipsec_info_t.
16900 		 */
16901 		IPSECHW_DEBUG(IPSECHW_PKT,
16902 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16903 		hada_mp = first_mp;
16904 		hada_mp->b_cont = NULL;
16905 		/*
16906 		 * Since it is accelerated, it comes directly from
16907 		 * the ill and the data attributes is followed by
16908 		 * the packet data.
16909 		 */
16910 		ASSERT(mp->b_datap->db_type != M_CTL);
16911 		first_mp = mp;
16912 		mctl_present = B_FALSE;
16913 	}
16914 
16915 	/*
16916 	 * IF M_CTL is not present, then ipsec_in_is_secure
16917 	 * should return B_TRUE. There is a case where loopback
16918 	 * packets has an M_CTL in the front with all the
16919 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16920 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16921 	 * packets never comes here, it is safe to ASSERT the
16922 	 * following.
16923 	 */
16924 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16925 
16926 
16927 	/* u1 is # words of IP options */
16928 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16929 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16930 
16931 	if (u1) {
16932 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16933 			if (hada_mp != NULL)
16934 				freemsg(hada_mp);
16935 			return;
16936 		}
16937 	} else {
16938 		/* Check the IP header checksum.  */
16939 #define	uph	((uint16_t *)ipha)
16940 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16941 		    uph[6] + uph[7] + uph[8] + uph[9];
16942 #undef  uph
16943 		/* finish doing IP checksum */
16944 		sum = (sum & 0xFFFF) + (sum >> 16);
16945 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16946 		/*
16947 		 * Don't verify header checksum if this packet is coming
16948 		 * back from AH/ESP as we already did it.
16949 		 */
16950 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16951 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16952 			goto drop_pkt;
16953 		}
16954 	}
16955 
16956 	/*
16957 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16958 	 * might be called more than once for secure packets, count only
16959 	 * the first time.
16960 	 */
16961 	if (!mctl_present) {
16962 		UPDATE_IB_PKT_COUNT(ire);
16963 		ire->ire_last_used_time = lbolt;
16964 	}
16965 
16966 	/* Check for fragmentation offset. */
16967 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16968 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16969 	if (u1) {
16970 		/*
16971 		 * We re-assemble fragments before we do the AH/ESP
16972 		 * processing. Thus, M_CTL should not be present
16973 		 * while we are re-assembling.
16974 		 */
16975 		ASSERT(!mctl_present);
16976 		ASSERT(first_mp == mp);
16977 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16978 			return;
16979 		}
16980 		/*
16981 		 * Make sure that first_mp points back to mp as
16982 		 * the mp we came in with could have changed in
16983 		 * ip_rput_fragment().
16984 		 */
16985 		ipha = (ipha_t *)mp->b_rptr;
16986 		first_mp = mp;
16987 	}
16988 
16989 	/*
16990 	 * Clear hardware checksumming flag as it is currently only
16991 	 * used by TCP and UDP.
16992 	 */
16993 	DB_CKSUMFLAGS(mp) = 0;
16994 
16995 	/* Now we have a complete datagram, destined for this machine. */
16996 	u1 = IPH_HDR_LENGTH(ipha);
16997 	switch (ipha->ipha_protocol) {
16998 	case IPPROTO_ICMP: {
16999 		ire_t		*ire_zone;
17000 		ilm_t		*ilm;
17001 		mblk_t		*mp1;
17002 		zoneid_t	last_zoneid;
17003 
17004 		if (CLASSD(ipha->ipha_dst) &&
17005 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17006 			ASSERT(ire->ire_type == IRE_BROADCAST);
17007 			/*
17008 			 * In the multicast case, applications may have joined
17009 			 * the group from different zones, so we need to deliver
17010 			 * the packet to each of them. Loop through the
17011 			 * multicast memberships structures (ilm) on the receive
17012 			 * ill and send a copy of the packet up each matching
17013 			 * one. However, we don't do this for multicasts sent on
17014 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17015 			 * they must stay in the sender's zone.
17016 			 *
17017 			 * ilm_add_v6() ensures that ilms in the same zone are
17018 			 * contiguous in the ill_ilm list. We use this property
17019 			 * to avoid sending duplicates needed when two
17020 			 * applications in the same zone join the same group on
17021 			 * different logical interfaces: we ignore the ilm if
17022 			 * its zoneid is the same as the last matching one.
17023 			 * In addition, the sending of the packet for
17024 			 * ire_zoneid is delayed until all of the other ilms
17025 			 * have been exhausted.
17026 			 */
17027 			last_zoneid = -1;
17028 			ILM_WALKER_HOLD(recv_ill);
17029 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17030 			    ilm = ilm->ilm_next) {
17031 				if ((ilm->ilm_flags & ILM_DELETED) ||
17032 				    ipha->ipha_dst != ilm->ilm_addr ||
17033 				    ilm->ilm_zoneid == last_zoneid ||
17034 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17035 				    ilm->ilm_zoneid == ALL_ZONES ||
17036 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17037 					continue;
17038 				mp1 = ip_copymsg(first_mp);
17039 				if (mp1 == NULL)
17040 					continue;
17041 				icmp_inbound(q, mp1, B_TRUE, ill,
17042 				    0, sum, mctl_present, B_TRUE,
17043 				    recv_ill, ilm->ilm_zoneid);
17044 				last_zoneid = ilm->ilm_zoneid;
17045 			}
17046 			ILM_WALKER_RELE(recv_ill);
17047 		} else if (ire->ire_type == IRE_BROADCAST) {
17048 			/*
17049 			 * In the broadcast case, there may be many zones
17050 			 * which need a copy of the packet delivered to them.
17051 			 * There is one IRE_BROADCAST per broadcast address
17052 			 * and per zone; we walk those using a helper function.
17053 			 * In addition, the sending of the packet for ire is
17054 			 * delayed until all of the other ires have been
17055 			 * processed.
17056 			 */
17057 			IRB_REFHOLD(ire->ire_bucket);
17058 			ire_zone = NULL;
17059 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17060 			    ire)) != NULL) {
17061 				mp1 = ip_copymsg(first_mp);
17062 				if (mp1 == NULL)
17063 					continue;
17064 
17065 				UPDATE_IB_PKT_COUNT(ire_zone);
17066 				ire_zone->ire_last_used_time = lbolt;
17067 				icmp_inbound(q, mp1, B_TRUE, ill,
17068 				    0, sum, mctl_present, B_TRUE,
17069 				    recv_ill, ire_zone->ire_zoneid);
17070 			}
17071 			IRB_REFRELE(ire->ire_bucket);
17072 		}
17073 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17074 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17075 		    ire->ire_zoneid);
17076 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17077 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17078 		return;
17079 	}
17080 	case IPPROTO_IGMP:
17081 		/*
17082 		 * If we are not willing to accept IGMP packets in clear,
17083 		 * then check with global policy.
17084 		 */
17085 		if (igmp_accept_clear_messages == 0) {
17086 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17087 			    ipha, NULL, mctl_present);
17088 			if (first_mp == NULL)
17089 				return;
17090 		}
17091 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17092 			freemsg(first_mp);
17093 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17094 			BUMP_MIB(&ip_mib, ipInDiscards);
17095 			return;
17096 		}
17097 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17098 			/* Bad packet - discarded by igmp_input */
17099 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17100 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17101 			if (mctl_present)
17102 				freeb(first_mp);
17103 			return;
17104 		}
17105 		/*
17106 		 * igmp_input() may have returned the pulled up message.
17107 		 * So first_mp and ipha need to be reinitialized.
17108 		 */
17109 		ipha = (ipha_t *)mp->b_rptr;
17110 		if (mctl_present)
17111 			first_mp->b_cont = mp;
17112 		else
17113 			first_mp = mp;
17114 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17115 			/* No user-level listener for IGMP packets */
17116 			goto drop_pkt;
17117 		}
17118 		/* deliver to local raw users */
17119 		break;
17120 	case IPPROTO_PIM:
17121 		/*
17122 		 * If we are not willing to accept PIM packets in clear,
17123 		 * then check with global policy.
17124 		 */
17125 		if (pim_accept_clear_messages == 0) {
17126 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17127 			    ipha, NULL, mctl_present);
17128 			if (first_mp == NULL)
17129 				return;
17130 		}
17131 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17132 			freemsg(first_mp);
17133 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17134 			BUMP_MIB(&ip_mib, ipInDiscards);
17135 			return;
17136 		}
17137 		if (pim_input(q, mp) != 0) {
17138 			/* Bad packet - discarded by pim_input */
17139 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17140 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17141 			if (mctl_present)
17142 				freeb(first_mp);
17143 			return;
17144 		}
17145 
17146 		/*
17147 		 * pim_input() may have pulled up the message so ipha needs to
17148 		 * be reinitialized.
17149 		 */
17150 		ipha = (ipha_t *)mp->b_rptr;
17151 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17152 			/* No user-level listener for PIM packets */
17153 			goto drop_pkt;
17154 		}
17155 		/* deliver to local raw users */
17156 		break;
17157 	case IPPROTO_ENCAP:
17158 		/*
17159 		 * Handle self-encapsulated packets (IP-in-IP where
17160 		 * the inner addresses == the outer addresses).
17161 		 */
17162 		hdr_length = IPH_HDR_LENGTH(ipha);
17163 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17164 		    mp->b_wptr) {
17165 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17166 			    sizeof (ipha_t) - mp->b_rptr)) {
17167 				BUMP_MIB(&ip_mib, ipInDiscards);
17168 				freemsg(first_mp);
17169 				return;
17170 			}
17171 			ipha = (ipha_t *)mp->b_rptr;
17172 		}
17173 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17174 		/*
17175 		 * Check the sanity of the inner IP header.
17176 		 */
17177 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17178 			BUMP_MIB(&ip_mib, ipInDiscards);
17179 			freemsg(first_mp);
17180 			return;
17181 		}
17182 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17183 			BUMP_MIB(&ip_mib, ipInDiscards);
17184 			freemsg(first_mp);
17185 			return;
17186 		}
17187 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17188 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17189 			ipsec_in_t *ii;
17190 
17191 			/*
17192 			 * Self-encapsulated tunnel packet. Remove
17193 			 * the outer IP header and fanout again.
17194 			 * We also need to make sure that the inner
17195 			 * header is pulled up until options.
17196 			 */
17197 			mp->b_rptr = (uchar_t *)inner_ipha;
17198 			ipha = inner_ipha;
17199 			hdr_length = IPH_HDR_LENGTH(ipha);
17200 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17201 				if (!pullupmsg(mp, (uchar_t *)ipha +
17202 				    + hdr_length - mp->b_rptr)) {
17203 					freemsg(first_mp);
17204 					return;
17205 				}
17206 				ipha = (ipha_t *)mp->b_rptr;
17207 			}
17208 			if (!mctl_present) {
17209 				ASSERT(first_mp == mp);
17210 				/*
17211 				 * This means that somebody is sending
17212 				 * Self-encapsualted packets without AH/ESP.
17213 				 * If AH/ESP was present, we would have already
17214 				 * allocated the first_mp.
17215 				 */
17216 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
17217 				    NULL) {
17218 					ip1dbg(("ip_proto_input: IPSEC_IN "
17219 					    "allocation failure.\n"));
17220 					BUMP_MIB(&ip_mib, ipInDiscards);
17221 					freemsg(mp);
17222 					return;
17223 				}
17224 				first_mp->b_cont = mp;
17225 			}
17226 			/*
17227 			 * We generally store the ill_index if we need to
17228 			 * do IPSEC processing as we lose the ill queue when
17229 			 * we come back. But in this case, we never should
17230 			 * have to store the ill_index here as it should have
17231 			 * been stored previously when we processed the
17232 			 * AH/ESP header in this routine or for non-ipsec
17233 			 * cases, we still have the queue. But for some bad
17234 			 * packets from the wire, we can get to IPSEC after
17235 			 * this and we better store the index for that case.
17236 			 */
17237 			ill = (ill_t *)q->q_ptr;
17238 			ii = (ipsec_in_t *)first_mp->b_rptr;
17239 			ii->ipsec_in_ill_index =
17240 			    ill->ill_phyint->phyint_ifindex;
17241 			ii->ipsec_in_rill_index =
17242 			    recv_ill->ill_phyint->phyint_ifindex;
17243 			if (ii->ipsec_in_decaps) {
17244 				/*
17245 				 * This packet is self-encapsulated multiple
17246 				 * times. We don't want to recurse infinitely.
17247 				 * To keep it simple, drop the packet.
17248 				 */
17249 				BUMP_MIB(&ip_mib, ipInDiscards);
17250 				freemsg(first_mp);
17251 				return;
17252 			}
17253 			ii->ipsec_in_decaps = B_TRUE;
17254 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17255 			    ire);
17256 			return;
17257 		}
17258 		break;
17259 	case IPPROTO_AH:
17260 	case IPPROTO_ESP: {
17261 		/*
17262 		 * Fast path for AH/ESP. If this is the first time
17263 		 * we are sending a datagram to AH/ESP, allocate
17264 		 * a IPSEC_IN message and prepend it. Otherwise,
17265 		 * just fanout.
17266 		 */
17267 
17268 		int ipsec_rc;
17269 		ipsec_in_t *ii;
17270 
17271 		IP_STAT(ipsec_proto_ahesp);
17272 		if (!mctl_present) {
17273 			ASSERT(first_mp == mp);
17274 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
17275 				ip1dbg(("ip_proto_input: IPSEC_IN "
17276 				    "allocation failure.\n"));
17277 				freemsg(hada_mp); /* okay ifnull */
17278 				BUMP_MIB(&ip_mib, ipInDiscards);
17279 				freemsg(mp);
17280 				return;
17281 			}
17282 			/*
17283 			 * Store the ill_index so that when we come back
17284 			 * from IPSEC we ride on the same queue.
17285 			 */
17286 			ill = (ill_t *)q->q_ptr;
17287 			ii = (ipsec_in_t *)first_mp->b_rptr;
17288 			ii->ipsec_in_ill_index =
17289 			    ill->ill_phyint->phyint_ifindex;
17290 			ii->ipsec_in_rill_index =
17291 			    recv_ill->ill_phyint->phyint_ifindex;
17292 			first_mp->b_cont = mp;
17293 			/*
17294 			 * Cache hardware acceleration info.
17295 			 */
17296 			if (hada_mp != NULL) {
17297 				IPSECHW_DEBUG(IPSECHW_PKT,
17298 				    ("ip_rput_local: caching data attr.\n"));
17299 				ii->ipsec_in_accelerated = B_TRUE;
17300 				ii->ipsec_in_da = hada_mp;
17301 				hada_mp = NULL;
17302 			}
17303 		} else {
17304 			ii = (ipsec_in_t *)first_mp->b_rptr;
17305 		}
17306 
17307 		if (!ipsec_loaded()) {
17308 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17309 			    ire->ire_zoneid);
17310 			return;
17311 		}
17312 
17313 		/* select inbound SA and have IPsec process the pkt */
17314 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17315 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17316 			if (esph == NULL)
17317 				return;
17318 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17319 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17320 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17321 			    first_mp, esph);
17322 		} else {
17323 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17324 			if (ah == NULL)
17325 				return;
17326 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17327 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17328 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17329 			    first_mp, ah);
17330 		}
17331 
17332 		switch (ipsec_rc) {
17333 		case IPSEC_STATUS_SUCCESS:
17334 			break;
17335 		case IPSEC_STATUS_FAILED:
17336 			BUMP_MIB(&ip_mib, ipInDiscards);
17337 			/* FALLTHRU */
17338 		case IPSEC_STATUS_PENDING:
17339 			return;
17340 		}
17341 		/* we're done with IPsec processing, send it up */
17342 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17343 		return;
17344 	}
17345 	default:
17346 		break;
17347 	}
17348 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17349 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17350 		    ire->ire_zoneid));
17351 		goto drop_pkt;
17352 	}
17353 	/*
17354 	 * Handle protocols with which IP is less intimate.  There
17355 	 * can be more than one stream bound to a particular
17356 	 * protocol.  When this is the case, each one gets a copy
17357 	 * of any incoming packets.
17358 	 */
17359 	ip_fanout_proto(q, first_mp, ill, ipha,
17360 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17361 	    B_TRUE, recv_ill, ire->ire_zoneid);
17362 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17363 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17364 	return;
17365 
17366 drop_pkt:
17367 	freemsg(first_mp);
17368 	if (hada_mp != NULL)
17369 		freeb(hada_mp);
17370 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17371 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17372 #undef	rptr
17373 #undef  iphs
17374 
17375 }
17376 
17377 /*
17378  * Update any source route, record route or timestamp options.
17379  * Check that we are at end of strict source route.
17380  * The options have already been checked for sanity in ip_rput_options().
17381  */
17382 static boolean_t
17383 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17384 {
17385 	ipoptp_t	opts;
17386 	uchar_t		*opt;
17387 	uint8_t		optval;
17388 	uint8_t		optlen;
17389 	ipaddr_t	dst;
17390 	uint32_t	ts;
17391 	ire_t		*dst_ire;
17392 	timestruc_t	now;
17393 	zoneid_t	zoneid;
17394 	ill_t		*ill;
17395 
17396 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17397 
17398 	ip2dbg(("ip_rput_local_options\n"));
17399 
17400 	for (optval = ipoptp_first(&opts, ipha);
17401 	    optval != IPOPT_EOL;
17402 	    optval = ipoptp_next(&opts)) {
17403 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17404 		opt = opts.ipoptp_cur;
17405 		optlen = opts.ipoptp_len;
17406 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17407 		    optval, optlen));
17408 		switch (optval) {
17409 			uint32_t off;
17410 		case IPOPT_SSRR:
17411 		case IPOPT_LSRR:
17412 			off = opt[IPOPT_OFFSET];
17413 			off--;
17414 			if (optlen < IP_ADDR_LEN ||
17415 			    off > optlen - IP_ADDR_LEN) {
17416 				/* End of source route */
17417 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17418 				break;
17419 			}
17420 			/*
17421 			 * This will only happen if two consecutive entries
17422 			 * in the source route contains our address or if
17423 			 * it is a packet with a loose source route which
17424 			 * reaches us before consuming the whole source route
17425 			 */
17426 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17427 			if (optval == IPOPT_SSRR) {
17428 				goto bad_src_route;
17429 			}
17430 			/*
17431 			 * Hack: instead of dropping the packet truncate the
17432 			 * source route to what has been used by filling the
17433 			 * rest with IPOPT_NOP.
17434 			 */
17435 			opt[IPOPT_OLEN] = (uint8_t)off;
17436 			while (off < optlen) {
17437 				opt[off++] = IPOPT_NOP;
17438 			}
17439 			break;
17440 		case IPOPT_RR:
17441 			off = opt[IPOPT_OFFSET];
17442 			off--;
17443 			if (optlen < IP_ADDR_LEN ||
17444 			    off > optlen - IP_ADDR_LEN) {
17445 				/* No more room - ignore */
17446 				ip1dbg((
17447 				    "ip_rput_local_options: end of RR\n"));
17448 				break;
17449 			}
17450 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17451 			    IP_ADDR_LEN);
17452 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17453 			break;
17454 		case IPOPT_TS:
17455 			/* Insert timestamp if there is romm */
17456 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17457 			case IPOPT_TS_TSONLY:
17458 				off = IPOPT_TS_TIMELEN;
17459 				break;
17460 			case IPOPT_TS_PRESPEC:
17461 			case IPOPT_TS_PRESPEC_RFC791:
17462 				/* Verify that the address matched */
17463 				off = opt[IPOPT_OFFSET] - 1;
17464 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17465 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17466 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17467 				if (dst_ire == NULL) {
17468 					/* Not for us */
17469 					break;
17470 				}
17471 				ire_refrele(dst_ire);
17472 				/* FALLTHRU */
17473 			case IPOPT_TS_TSANDADDR:
17474 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17475 				break;
17476 			default:
17477 				/*
17478 				 * ip_*put_options should have already
17479 				 * dropped this packet.
17480 				 */
17481 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17482 				    "unknown IT - bug in ip_rput_options?\n");
17483 				return (B_TRUE);	/* Keep "lint" happy */
17484 			}
17485 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17486 				/* Increase overflow counter */
17487 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17488 				opt[IPOPT_POS_OV_FLG] =
17489 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17490 				    (off << 4));
17491 				break;
17492 			}
17493 			off = opt[IPOPT_OFFSET] - 1;
17494 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17495 			case IPOPT_TS_PRESPEC:
17496 			case IPOPT_TS_PRESPEC_RFC791:
17497 			case IPOPT_TS_TSANDADDR:
17498 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17499 				    IP_ADDR_LEN);
17500 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17501 				/* FALLTHRU */
17502 			case IPOPT_TS_TSONLY:
17503 				off = opt[IPOPT_OFFSET] - 1;
17504 				/* Compute # of milliseconds since midnight */
17505 				gethrestime(&now);
17506 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17507 				    now.tv_nsec / (NANOSEC / MILLISEC);
17508 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17509 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17510 				break;
17511 			}
17512 			break;
17513 		}
17514 	}
17515 	return (B_TRUE);
17516 
17517 bad_src_route:
17518 	q = WR(q);
17519 	if (q->q_next != NULL)
17520 		ill = q->q_ptr;
17521 	else
17522 		ill = NULL;
17523 
17524 	/* make sure we clear any indication of a hardware checksum */
17525 	DB_CKSUMFLAGS(mp) = 0;
17526 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill);
17527 	if (zoneid == ALL_ZONES)
17528 		freemsg(mp);
17529 	else
17530 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17531 	return (B_FALSE);
17532 
17533 }
17534 
17535 /*
17536  * Process IP options in an inbound packet.  If an option affects the
17537  * effective destination address, return the next hop address via dstp.
17538  * Returns -1 if something fails in which case an ICMP error has been sent
17539  * and mp freed.
17540  */
17541 static int
17542 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17543 {
17544 	ipoptp_t	opts;
17545 	uchar_t		*opt;
17546 	uint8_t		optval;
17547 	uint8_t		optlen;
17548 	ipaddr_t	dst;
17549 	intptr_t	code = 0;
17550 	ire_t		*ire = NULL;
17551 	zoneid_t	zoneid;
17552 	ill_t		*ill;
17553 
17554 	ip2dbg(("ip_rput_options\n"));
17555 	dst = ipha->ipha_dst;
17556 	for (optval = ipoptp_first(&opts, ipha);
17557 	    optval != IPOPT_EOL;
17558 	    optval = ipoptp_next(&opts)) {
17559 		opt = opts.ipoptp_cur;
17560 		optlen = opts.ipoptp_len;
17561 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17562 		    optval, optlen));
17563 		/*
17564 		 * Note: we need to verify the checksum before we
17565 		 * modify anything thus this routine only extracts the next
17566 		 * hop dst from any source route.
17567 		 */
17568 		switch (optval) {
17569 			uint32_t off;
17570 		case IPOPT_SSRR:
17571 		case IPOPT_LSRR:
17572 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17573 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17574 			if (ire == NULL) {
17575 				if (optval == IPOPT_SSRR) {
17576 					ip1dbg(("ip_rput_options: not next"
17577 					    " strict source route 0x%x\n",
17578 					    ntohl(dst)));
17579 					code = (char *)&ipha->ipha_dst -
17580 					    (char *)ipha;
17581 					goto param_prob; /* RouterReq's */
17582 				}
17583 				ip2dbg(("ip_rput_options: "
17584 				    "not next source route 0x%x\n",
17585 				    ntohl(dst)));
17586 				break;
17587 			}
17588 			ire_refrele(ire);
17589 
17590 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17591 				ip1dbg((
17592 				    "ip_rput_options: bad option offset\n"));
17593 				code = (char *)&opt[IPOPT_OLEN] -
17594 				    (char *)ipha;
17595 				goto param_prob;
17596 			}
17597 			off = opt[IPOPT_OFFSET];
17598 			off--;
17599 		redo_srr:
17600 			if (optlen < IP_ADDR_LEN ||
17601 			    off > optlen - IP_ADDR_LEN) {
17602 				/* End of source route */
17603 				ip1dbg(("ip_rput_options: end of SR\n"));
17604 				break;
17605 			}
17606 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17607 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17608 			    ntohl(dst)));
17609 
17610 			/*
17611 			 * Check if our address is present more than
17612 			 * once as consecutive hops in source route.
17613 			 * XXX verify per-interface ip_forwarding
17614 			 * for source route?
17615 			 */
17616 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17617 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17618 
17619 			if (ire != NULL) {
17620 				ire_refrele(ire);
17621 				off += IP_ADDR_LEN;
17622 				goto redo_srr;
17623 			}
17624 
17625 			if (dst == htonl(INADDR_LOOPBACK)) {
17626 				ip1dbg(("ip_rput_options: loopback addr in "
17627 				    "source route!\n"));
17628 				goto bad_src_route;
17629 			}
17630 			/*
17631 			 * For strict: verify that dst is directly
17632 			 * reachable.
17633 			 */
17634 			if (optval == IPOPT_SSRR) {
17635 				ire = ire_ftable_lookup(dst, 0, 0,
17636 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17637 				    MBLK_GETLABEL(mp),
17638 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17639 				if (ire == NULL) {
17640 					ip1dbg(("ip_rput_options: SSRR not "
17641 					    "directly reachable: 0x%x\n",
17642 					    ntohl(dst)));
17643 					goto bad_src_route;
17644 				}
17645 				ire_refrele(ire);
17646 			}
17647 			/*
17648 			 * Defer update of the offset and the record route
17649 			 * until the packet is forwarded.
17650 			 */
17651 			break;
17652 		case IPOPT_RR:
17653 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17654 				ip1dbg((
17655 				    "ip_rput_options: bad option offset\n"));
17656 				code = (char *)&opt[IPOPT_OLEN] -
17657 				    (char *)ipha;
17658 				goto param_prob;
17659 			}
17660 			break;
17661 		case IPOPT_TS:
17662 			/*
17663 			 * Verify that length >= 5 and that there is either
17664 			 * room for another timestamp or that the overflow
17665 			 * counter is not maxed out.
17666 			 */
17667 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17668 			if (optlen < IPOPT_MINLEN_IT) {
17669 				goto param_prob;
17670 			}
17671 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17672 				ip1dbg((
17673 				    "ip_rput_options: bad option offset\n"));
17674 				code = (char *)&opt[IPOPT_OFFSET] -
17675 				    (char *)ipha;
17676 				goto param_prob;
17677 			}
17678 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17679 			case IPOPT_TS_TSONLY:
17680 				off = IPOPT_TS_TIMELEN;
17681 				break;
17682 			case IPOPT_TS_TSANDADDR:
17683 			case IPOPT_TS_PRESPEC:
17684 			case IPOPT_TS_PRESPEC_RFC791:
17685 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17686 				break;
17687 			default:
17688 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17689 				    (char *)ipha;
17690 				goto param_prob;
17691 			}
17692 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17693 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17694 				/*
17695 				 * No room and the overflow counter is 15
17696 				 * already.
17697 				 */
17698 				goto param_prob;
17699 			}
17700 			break;
17701 		}
17702 	}
17703 
17704 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17705 		*dstp = dst;
17706 		return (0);
17707 	}
17708 
17709 	ip1dbg(("ip_rput_options: error processing IP options."));
17710 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17711 
17712 param_prob:
17713 	q = WR(q);
17714 	if (q->q_next != NULL)
17715 		ill = q->q_ptr;
17716 	else
17717 		ill = NULL;
17718 
17719 	/* make sure we clear any indication of a hardware checksum */
17720 	DB_CKSUMFLAGS(mp) = 0;
17721 	/* Don't know whether this is for non-global or global/forwarding */
17722 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17723 	if (zoneid == ALL_ZONES)
17724 		freemsg(mp);
17725 	else
17726 		icmp_param_problem(q, mp, (uint8_t)code, zoneid);
17727 	return (-1);
17728 
17729 bad_src_route:
17730 	q = WR(q);
17731 	if (q->q_next != NULL)
17732 		ill = q->q_ptr;
17733 	else
17734 		ill = NULL;
17735 
17736 	/* make sure we clear any indication of a hardware checksum */
17737 	DB_CKSUMFLAGS(mp) = 0;
17738 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17739 	if (zoneid == ALL_ZONES)
17740 		freemsg(mp);
17741 	else
17742 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17743 	return (-1);
17744 }
17745 
17746 /*
17747  * IP & ICMP info in >=14 msg's ...
17748  *  - ip fixed part (mib2_ip_t)
17749  *  - icmp fixed part (mib2_icmp_t)
17750  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17751  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17752  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
17753  *  - ipRouteAttributeTable (ip 102)	labeled routes
17754  *  - ip multicast membership (ip_member_t)
17755  *  - ip multicast source filtering (ip_grpsrc_t)
17756  *  - igmp fixed part (struct igmpstat)
17757  *  - multicast routing stats (struct mrtstat)
17758  *  - multicast routing vifs (array of struct vifctl)
17759  *  - multicast routing routes (array of struct mfcctl)
17760  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17761  *					One per ill plus one generic
17762  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17763  *					One per ill plus one generic
17764  *  - ipv6RouteEntry			all IPv6 IREs
17765  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17766  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17767  *  - ipv6AddrEntry			all IPv6 ipifs
17768  *  - ipv6 multicast membership (ipv6_member_t)
17769  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17770  *
17771  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
17772  * already present.
17773  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17774  * already filled in by the caller.
17775  * Return value of 0 indicates that no messages were sent and caller
17776  * should free mpctl.
17777  */
17778 int
17779 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17780 {
17781 
17782 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17783 		return (0);
17784 	}
17785 
17786 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
17787 		return (1);
17788 	}
17789 
17790 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17791 		return (1);
17792 	}
17793 
17794 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17795 		return (1);
17796 	}
17797 
17798 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17799 		return (1);
17800 	}
17801 
17802 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17803 		return (1);
17804 	}
17805 
17806 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17807 		return (1);
17808 	}
17809 
17810 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17811 		return (1);
17812 	}
17813 
17814 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17815 		return (1);
17816 	}
17817 
17818 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17819 		return (1);
17820 	}
17821 
17822 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17823 		return (1);
17824 	}
17825 
17826 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17827 		return (1);
17828 	}
17829 
17830 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17831 		return (1);
17832 	}
17833 
17834 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17835 		return (1);
17836 	}
17837 
17838 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17839 		return (1);
17840 	}
17841 
17842 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17843 		return (1);
17844 	}
17845 
17846 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17847 		return (1);
17848 	}
17849 
17850 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17851 		return (1);
17852 	}
17853 	freemsg(mpctl);
17854 	return (1);
17855 }
17856 
17857 
17858 /* Get global IPv4 statistics */
17859 static mblk_t *
17860 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
17861 {
17862 	struct opthdr		*optp;
17863 	mblk_t			*mp2ctl;
17864 
17865 	/*
17866 	 * make a copy of the original message
17867 	 */
17868 	mp2ctl = copymsg(mpctl);
17869 
17870 	/* fixed length IP structure... */
17871 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17872 	optp->level = MIB2_IP;
17873 	optp->name = 0;
17874 	SET_MIB(ip_mib.ipForwarding,
17875 	    (WE_ARE_FORWARDING ? 1 : 2));
17876 	SET_MIB(ip_mib.ipDefaultTTL,
17877 	    (uint32_t)ip_def_ttl);
17878 	SET_MIB(ip_mib.ipReasmTimeout,
17879 	    ip_g_frag_timeout);
17880 	SET_MIB(ip_mib.ipAddrEntrySize,
17881 	    sizeof (mib2_ipAddrEntry_t));
17882 	SET_MIB(ip_mib.ipRouteEntrySize,
17883 	    sizeof (mib2_ipRouteEntry_t));
17884 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
17885 	    sizeof (mib2_ipNetToMediaEntry_t));
17886 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17887 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17888 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
17889 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17890 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
17891 	    (int)sizeof (ip_mib))) {
17892 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17893 		    (uint_t)sizeof (ip_mib)));
17894 	}
17895 
17896 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17897 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17898 	    (int)optp->level, (int)optp->name, (int)optp->len));
17899 	qreply(q, mpctl);
17900 	return (mp2ctl);
17901 }
17902 
17903 /* Global IPv4 ICMP statistics */
17904 static mblk_t *
17905 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
17906 {
17907 	struct opthdr		*optp;
17908 	mblk_t			*mp2ctl;
17909 
17910 	/*
17911 	 * Make a copy of the original message
17912 	 */
17913 	mp2ctl = copymsg(mpctl);
17914 
17915 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17916 	optp->level = MIB2_ICMP;
17917 	optp->name = 0;
17918 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17919 	    (int)sizeof (icmp_mib))) {
17920 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17921 		    (uint_t)sizeof (icmp_mib)));
17922 	}
17923 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17924 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17925 	    (int)optp->level, (int)optp->name, (int)optp->len));
17926 	qreply(q, mpctl);
17927 	return (mp2ctl);
17928 }
17929 
17930 /* Global IPv4 IGMP statistics */
17931 static mblk_t *
17932 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17933 {
17934 	struct opthdr		*optp;
17935 	mblk_t			*mp2ctl;
17936 
17937 	/*
17938 	 * make a copy of the original message
17939 	 */
17940 	mp2ctl = copymsg(mpctl);
17941 
17942 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17943 	optp->level = EXPER_IGMP;
17944 	optp->name = 0;
17945 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17946 	    (int)sizeof (igmpstat))) {
17947 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17948 		    (uint_t)sizeof (igmpstat)));
17949 	}
17950 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17951 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17952 	    (int)optp->level, (int)optp->name, (int)optp->len));
17953 	qreply(q, mpctl);
17954 	return (mp2ctl);
17955 }
17956 
17957 /* Global IPv4 Multicast Routing statistics */
17958 static mblk_t *
17959 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17960 {
17961 	struct opthdr		*optp;
17962 	mblk_t			*mp2ctl;
17963 
17964 	/*
17965 	 * make a copy of the original message
17966 	 */
17967 	mp2ctl = copymsg(mpctl);
17968 
17969 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17970 	optp->level = EXPER_DVMRP;
17971 	optp->name = 0;
17972 	if (!ip_mroute_stats(mpctl->b_cont)) {
17973 		ip0dbg(("ip_mroute_stats: failed\n"));
17974 	}
17975 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17976 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17977 	    (int)optp->level, (int)optp->name, (int)optp->len));
17978 	qreply(q, mpctl);
17979 	return (mp2ctl);
17980 }
17981 
17982 /* IPv4 address information */
17983 static mblk_t *
17984 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17985 {
17986 	struct opthdr		*optp;
17987 	mblk_t			*mp2ctl;
17988 	mblk_t			*mp_tail = NULL;
17989 	ill_t			*ill;
17990 	ipif_t			*ipif;
17991 	uint_t			bitval;
17992 	mib2_ipAddrEntry_t	mae;
17993 	zoneid_t		zoneid;
17994 	ill_walk_context_t ctx;
17995 
17996 	/*
17997 	 * make a copy of the original message
17998 	 */
17999 	mp2ctl = copymsg(mpctl);
18000 
18001 	/* ipAddrEntryTable */
18002 
18003 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18004 	optp->level = MIB2_IP;
18005 	optp->name = MIB2_IP_ADDR;
18006 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18007 
18008 	rw_enter(&ill_g_lock, RW_READER);
18009 	ill = ILL_START_WALK_V4(&ctx);
18010 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18011 		for (ipif = ill->ill_ipif; ipif != NULL;
18012 		    ipif = ipif->ipif_next) {
18013 			if (ipif->ipif_zoneid != zoneid &&
18014 			    ipif->ipif_zoneid != ALL_ZONES)
18015 				continue;
18016 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18017 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18018 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18019 
18020 			(void) ipif_get_name(ipif,
18021 			    mae.ipAdEntIfIndex.o_bytes,
18022 			    OCTET_LENGTH);
18023 			mae.ipAdEntIfIndex.o_length =
18024 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18025 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18026 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18027 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18028 			mae.ipAdEntInfo.ae_subnet_len =
18029 			    ip_mask_to_plen(ipif->ipif_net_mask);
18030 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18031 			for (bitval = 1;
18032 			    bitval &&
18033 			    !(bitval & ipif->ipif_brd_addr);
18034 			    bitval <<= 1)
18035 				noop;
18036 			mae.ipAdEntBcastAddr = bitval;
18037 			mae.ipAdEntReasmMaxSize = 65535;
18038 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18039 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18040 			mae.ipAdEntInfo.ae_broadcast_addr =
18041 			    ipif->ipif_brd_addr;
18042 			mae.ipAdEntInfo.ae_pp_dst_addr =
18043 			    ipif->ipif_pp_dst_addr;
18044 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18045 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18046 
18047 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18048 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18049 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18050 				    "allocate %u bytes\n",
18051 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18052 			}
18053 		}
18054 	}
18055 	rw_exit(&ill_g_lock);
18056 
18057 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18058 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18059 	    (int)optp->level, (int)optp->name, (int)optp->len));
18060 	qreply(q, mpctl);
18061 	return (mp2ctl);
18062 }
18063 
18064 /* IPv6 address information */
18065 static mblk_t *
18066 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
18067 {
18068 	struct opthdr		*optp;
18069 	mblk_t			*mp2ctl;
18070 	mblk_t			*mp_tail = NULL;
18071 	ill_t			*ill;
18072 	ipif_t			*ipif;
18073 	mib2_ipv6AddrEntry_t	mae6;
18074 	zoneid_t		zoneid;
18075 	ill_walk_context_t	ctx;
18076 
18077 	/*
18078 	 * make a copy of the original message
18079 	 */
18080 	mp2ctl = copymsg(mpctl);
18081 
18082 	/* ipv6AddrEntryTable */
18083 
18084 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18085 	optp->level = MIB2_IP6;
18086 	optp->name = MIB2_IP6_ADDR;
18087 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18088 
18089 	rw_enter(&ill_g_lock, RW_READER);
18090 	ill = ILL_START_WALK_V6(&ctx);
18091 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18092 		for (ipif = ill->ill_ipif; ipif != NULL;
18093 		    ipif = ipif->ipif_next) {
18094 			if (ipif->ipif_zoneid != zoneid &&
18095 			    ipif->ipif_zoneid != ALL_ZONES)
18096 				continue;
18097 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18098 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18099 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18100 
18101 			(void) ipif_get_name(ipif,
18102 			    mae6.ipv6AddrIfIndex.o_bytes,
18103 			    OCTET_LENGTH);
18104 			mae6.ipv6AddrIfIndex.o_length =
18105 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18106 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18107 			mae6.ipv6AddrPfxLength =
18108 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18109 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18110 			mae6.ipv6AddrInfo.ae_subnet_len =
18111 			    mae6.ipv6AddrPfxLength;
18112 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18113 
18114 			/* Type: stateless(1), stateful(2), unknown(3) */
18115 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18116 				mae6.ipv6AddrType = 1;
18117 			else
18118 				mae6.ipv6AddrType = 2;
18119 			/* Anycast: true(1), false(2) */
18120 			if (ipif->ipif_flags & IPIF_ANYCAST)
18121 				mae6.ipv6AddrAnycastFlag = 1;
18122 			else
18123 				mae6.ipv6AddrAnycastFlag = 2;
18124 
18125 			/*
18126 			 * Address status: preferred(1), deprecated(2),
18127 			 * invalid(3), inaccessible(4), unknown(5)
18128 			 */
18129 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18130 				mae6.ipv6AddrStatus = 3;
18131 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18132 				mae6.ipv6AddrStatus = 2;
18133 			else
18134 				mae6.ipv6AddrStatus = 1;
18135 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18136 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18137 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18138 						ipif->ipif_v6pp_dst_addr;
18139 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18140 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18141 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18142 				(char *)&mae6,
18143 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18144 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18145 				    "allocate %u bytes\n",
18146 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18147 			}
18148 		}
18149 	}
18150 	rw_exit(&ill_g_lock);
18151 
18152 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18153 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18154 	    (int)optp->level, (int)optp->name, (int)optp->len));
18155 	qreply(q, mpctl);
18156 	return (mp2ctl);
18157 }
18158 
18159 /* IPv4 multicast group membership. */
18160 static mblk_t *
18161 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
18162 {
18163 	struct opthdr		*optp;
18164 	mblk_t			*mp2ctl;
18165 	ill_t			*ill;
18166 	ipif_t			*ipif;
18167 	ilm_t			*ilm;
18168 	ip_member_t		ipm;
18169 	mblk_t			*mp_tail = NULL;
18170 	ill_walk_context_t	ctx;
18171 	zoneid_t		zoneid;
18172 
18173 	/*
18174 	 * make a copy of the original message
18175 	 */
18176 	mp2ctl = copymsg(mpctl);
18177 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18178 
18179 	/* ipGroupMember table */
18180 	optp = (struct opthdr *)&mpctl->b_rptr[
18181 	    sizeof (struct T_optmgmt_ack)];
18182 	optp->level = MIB2_IP;
18183 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18184 
18185 	rw_enter(&ill_g_lock, RW_READER);
18186 	ill = ILL_START_WALK_V4(&ctx);
18187 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18188 		ILM_WALKER_HOLD(ill);
18189 		for (ipif = ill->ill_ipif; ipif != NULL;
18190 		    ipif = ipif->ipif_next) {
18191 			if (ipif->ipif_zoneid != zoneid &&
18192 			    ipif->ipif_zoneid != ALL_ZONES)
18193 				continue;	/* not this zone */
18194 			(void) ipif_get_name(ipif,
18195 			    ipm.ipGroupMemberIfIndex.o_bytes,
18196 			    OCTET_LENGTH);
18197 			ipm.ipGroupMemberIfIndex.o_length =
18198 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18199 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18200 				ASSERT(ilm->ilm_ipif != NULL);
18201 				ASSERT(ilm->ilm_ill == NULL);
18202 				if (ilm->ilm_ipif != ipif)
18203 					continue;
18204 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18205 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18206 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18207 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18208 				    (char *)&ipm, (int)sizeof (ipm))) {
18209 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18210 					    "failed to allocate %u bytes\n",
18211 						(uint_t)sizeof (ipm)));
18212 				}
18213 			}
18214 		}
18215 		ILM_WALKER_RELE(ill);
18216 	}
18217 	rw_exit(&ill_g_lock);
18218 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18219 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18220 	    (int)optp->level, (int)optp->name, (int)optp->len));
18221 	qreply(q, mpctl);
18222 	return (mp2ctl);
18223 }
18224 
18225 /* IPv6 multicast group membership. */
18226 static mblk_t *
18227 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
18228 {
18229 	struct opthdr		*optp;
18230 	mblk_t			*mp2ctl;
18231 	ill_t			*ill;
18232 	ilm_t			*ilm;
18233 	ipv6_member_t		ipm6;
18234 	mblk_t			*mp_tail = NULL;
18235 	ill_walk_context_t	ctx;
18236 	zoneid_t		zoneid;
18237 
18238 	/*
18239 	 * make a copy of the original message
18240 	 */
18241 	mp2ctl = copymsg(mpctl);
18242 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18243 
18244 	/* ip6GroupMember table */
18245 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18246 	optp->level = MIB2_IP6;
18247 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18248 
18249 	rw_enter(&ill_g_lock, RW_READER);
18250 	ill = ILL_START_WALK_V6(&ctx);
18251 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18252 		ILM_WALKER_HOLD(ill);
18253 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18254 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18255 			ASSERT(ilm->ilm_ipif == NULL);
18256 			ASSERT(ilm->ilm_ill != NULL);
18257 			if (ilm->ilm_zoneid != zoneid)
18258 				continue;	/* not this zone */
18259 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18260 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18261 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18262 			if (!snmp_append_data2(mpctl->b_cont,
18263 			    &mp_tail,
18264 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18265 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18266 				    "failed to allocate %u bytes\n",
18267 				    (uint_t)sizeof (ipm6)));
18268 			}
18269 		}
18270 		ILM_WALKER_RELE(ill);
18271 	}
18272 	rw_exit(&ill_g_lock);
18273 
18274 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18275 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18276 	    (int)optp->level, (int)optp->name, (int)optp->len));
18277 	qreply(q, mpctl);
18278 	return (mp2ctl);
18279 }
18280 
18281 /* IP multicast filtered sources */
18282 static mblk_t *
18283 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
18284 {
18285 	struct opthdr		*optp;
18286 	mblk_t			*mp2ctl;
18287 	ill_t			*ill;
18288 	ipif_t			*ipif;
18289 	ilm_t			*ilm;
18290 	ip_grpsrc_t		ips;
18291 	mblk_t			*mp_tail = NULL;
18292 	ill_walk_context_t	ctx;
18293 	zoneid_t		zoneid;
18294 	int			i;
18295 	slist_t			*sl;
18296 
18297 	/*
18298 	 * make a copy of the original message
18299 	 */
18300 	mp2ctl = copymsg(mpctl);
18301 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18302 
18303 	/* ipGroupSource table */
18304 	optp = (struct opthdr *)&mpctl->b_rptr[
18305 	    sizeof (struct T_optmgmt_ack)];
18306 	optp->level = MIB2_IP;
18307 	optp->name = EXPER_IP_GROUP_SOURCES;
18308 
18309 	rw_enter(&ill_g_lock, RW_READER);
18310 	ill = ILL_START_WALK_V4(&ctx);
18311 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18312 		ILM_WALKER_HOLD(ill);
18313 		for (ipif = ill->ill_ipif; ipif != NULL;
18314 		    ipif = ipif->ipif_next) {
18315 			if (ipif->ipif_zoneid != zoneid)
18316 				continue;	/* not this zone */
18317 			(void) ipif_get_name(ipif,
18318 			    ips.ipGroupSourceIfIndex.o_bytes,
18319 			    OCTET_LENGTH);
18320 			ips.ipGroupSourceIfIndex.o_length =
18321 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18322 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18323 				ASSERT(ilm->ilm_ipif != NULL);
18324 				ASSERT(ilm->ilm_ill == NULL);
18325 				sl = ilm->ilm_filter;
18326 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18327 					continue;
18328 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18329 				for (i = 0; i < sl->sl_numsrc; i++) {
18330 					if (!IN6_IS_ADDR_V4MAPPED(
18331 					    &sl->sl_addr[i]))
18332 						continue;
18333 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18334 					    ips.ipGroupSourceAddress);
18335 					if (snmp_append_data2(mpctl->b_cont,
18336 					    &mp_tail, (char *)&ips,
18337 					    (int)sizeof (ips)) == 0) {
18338 						ip1dbg(("ip_snmp_get_mib2_"
18339 						    "ip_group_src: failed to "
18340 						    "allocate %u bytes\n",
18341 						    (uint_t)sizeof (ips)));
18342 					}
18343 				}
18344 			}
18345 		}
18346 		ILM_WALKER_RELE(ill);
18347 	}
18348 	rw_exit(&ill_g_lock);
18349 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18350 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18351 	    (int)optp->level, (int)optp->name, (int)optp->len));
18352 	qreply(q, mpctl);
18353 	return (mp2ctl);
18354 }
18355 
18356 /* IPv6 multicast filtered sources. */
18357 static mblk_t *
18358 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18359 {
18360 	struct opthdr		*optp;
18361 	mblk_t			*mp2ctl;
18362 	ill_t			*ill;
18363 	ilm_t			*ilm;
18364 	ipv6_grpsrc_t		ips6;
18365 	mblk_t			*mp_tail = NULL;
18366 	ill_walk_context_t	ctx;
18367 	zoneid_t		zoneid;
18368 	int			i;
18369 	slist_t			*sl;
18370 
18371 	/*
18372 	 * make a copy of the original message
18373 	 */
18374 	mp2ctl = copymsg(mpctl);
18375 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18376 
18377 	/* ip6GroupMember table */
18378 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18379 	optp->level = MIB2_IP6;
18380 	optp->name = EXPER_IP6_GROUP_SOURCES;
18381 
18382 	rw_enter(&ill_g_lock, RW_READER);
18383 	ill = ILL_START_WALK_V6(&ctx);
18384 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18385 		ILM_WALKER_HOLD(ill);
18386 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18387 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18388 			ASSERT(ilm->ilm_ipif == NULL);
18389 			ASSERT(ilm->ilm_ill != NULL);
18390 			sl = ilm->ilm_filter;
18391 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18392 				continue;
18393 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18394 			for (i = 0; i < sl->sl_numsrc; i++) {
18395 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18396 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18397 				    (char *)&ips6, (int)sizeof (ips6))) {
18398 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18399 					    "group_src: failed to allocate "
18400 					    "%u bytes\n",
18401 					    (uint_t)sizeof (ips6)));
18402 				}
18403 			}
18404 		}
18405 		ILM_WALKER_RELE(ill);
18406 	}
18407 	rw_exit(&ill_g_lock);
18408 
18409 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18410 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18411 	    (int)optp->level, (int)optp->name, (int)optp->len));
18412 	qreply(q, mpctl);
18413 	return (mp2ctl);
18414 }
18415 
18416 /* Multicast routing virtual interface table. */
18417 static mblk_t *
18418 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18419 {
18420 	struct opthdr		*optp;
18421 	mblk_t			*mp2ctl;
18422 
18423 	/*
18424 	 * make a copy of the original message
18425 	 */
18426 	mp2ctl = copymsg(mpctl);
18427 
18428 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18429 	optp->level = EXPER_DVMRP;
18430 	optp->name = EXPER_DVMRP_VIF;
18431 	if (!ip_mroute_vif(mpctl->b_cont)) {
18432 		ip0dbg(("ip_mroute_vif: failed\n"));
18433 	}
18434 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18435 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18436 	    (int)optp->level, (int)optp->name, (int)optp->len));
18437 	qreply(q, mpctl);
18438 	return (mp2ctl);
18439 }
18440 
18441 /* Multicast routing table. */
18442 static mblk_t *
18443 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18444 {
18445 	struct opthdr		*optp;
18446 	mblk_t			*mp2ctl;
18447 
18448 	/*
18449 	 * make a copy of the original message
18450 	 */
18451 	mp2ctl = copymsg(mpctl);
18452 
18453 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18454 	optp->level = EXPER_DVMRP;
18455 	optp->name = EXPER_DVMRP_MRT;
18456 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18457 		ip0dbg(("ip_mroute_mrt: failed\n"));
18458 	}
18459 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18460 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18461 	    (int)optp->level, (int)optp->name, (int)optp->len));
18462 	qreply(q, mpctl);
18463 	return (mp2ctl);
18464 }
18465 
18466 /*
18467  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18468  * in one IRE walk.
18469  */
18470 static mblk_t *
18471 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18472 {
18473 	struct opthdr	*optp;
18474 	mblk_t		*mp2ctl;	/* Returned */
18475 	mblk_t		*mp3ctl;	/* nettomedia */
18476 	mblk_t		*mp4ctl;	/* routeattrs */
18477 	iproutedata_t	ird;
18478 	zoneid_t	zoneid;
18479 
18480 	/*
18481 	 * make copies of the original message
18482 	 *	- mp2ctl is returned unchanged to the caller for his use
18483 	 *	- mpctl is sent upstream as ipRouteEntryTable
18484 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18485 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18486 	 */
18487 	mp2ctl = copymsg(mpctl);
18488 	mp3ctl = copymsg(mpctl);
18489 	mp4ctl = copymsg(mpctl);
18490 	if (mp3ctl == NULL || mp4ctl == NULL) {
18491 		freemsg(mp4ctl);
18492 		freemsg(mp3ctl);
18493 		freemsg(mp2ctl);
18494 		freemsg(mpctl);
18495 		return (NULL);
18496 	}
18497 
18498 	bzero(&ird, sizeof (ird));
18499 
18500 	ird.ird_route.lp_head = mpctl->b_cont;
18501 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18502 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18503 
18504 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18505 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18506 	if (zoneid == GLOBAL_ZONEID) {
18507 		/*
18508 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18509 		 * the sys_net_config privilege, it can only run in the global
18510 		 * zone, so we don't display these IREs in the other zones.
18511 		 */
18512 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18513 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18514 	}
18515 
18516 	/* ipRouteEntryTable in mpctl */
18517 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18518 	optp->level = MIB2_IP;
18519 	optp->name = MIB2_IP_ROUTE;
18520 	optp->len = msgdsize(ird.ird_route.lp_head);
18521 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18522 	    (int)optp->level, (int)optp->name, (int)optp->len));
18523 	qreply(q, mpctl);
18524 
18525 	/* ipNetToMediaEntryTable in mp3ctl */
18526 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18527 	optp->level = MIB2_IP;
18528 	optp->name = MIB2_IP_MEDIA;
18529 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18530 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18531 	    (int)optp->level, (int)optp->name, (int)optp->len));
18532 	qreply(q, mp3ctl);
18533 
18534 	/* ipRouteAttributeTable in mp4ctl */
18535 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18536 	optp->level = MIB2_IP;
18537 	optp->name = EXPER_IP_RTATTR;
18538 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18539 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18540 	    (int)optp->level, (int)optp->name, (int)optp->len));
18541 	if (optp->len == 0)
18542 		freemsg(mp4ctl);
18543 	else
18544 		qreply(q, mp4ctl);
18545 
18546 	return (mp2ctl);
18547 }
18548 
18549 /*
18550  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18551  * ipv6NetToMediaEntryTable in an NDP walk.
18552  */
18553 static mblk_t *
18554 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18555 {
18556 	struct opthdr	*optp;
18557 	mblk_t		*mp2ctl;	/* Returned */
18558 	mblk_t		*mp3ctl;	/* nettomedia */
18559 	mblk_t		*mp4ctl;	/* routeattrs */
18560 	iproutedata_t	ird;
18561 	zoneid_t	zoneid;
18562 
18563 	/*
18564 	 * make copies of the original message
18565 	 *	- mp2ctl is returned unchanged to the caller for his use
18566 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18567 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18568 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18569 	 */
18570 	mp2ctl = copymsg(mpctl);
18571 	mp3ctl = copymsg(mpctl);
18572 	mp4ctl = copymsg(mpctl);
18573 	if (mp3ctl == NULL || mp4ctl == NULL) {
18574 		freemsg(mp4ctl);
18575 		freemsg(mp3ctl);
18576 		freemsg(mp2ctl);
18577 		freemsg(mpctl);
18578 		return (NULL);
18579 	}
18580 
18581 	bzero(&ird, sizeof (ird));
18582 
18583 	ird.ird_route.lp_head = mpctl->b_cont;
18584 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18585 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18586 
18587 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18588 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18589 
18590 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18591 	optp->level = MIB2_IP6;
18592 	optp->name = MIB2_IP6_ROUTE;
18593 	optp->len = msgdsize(ird.ird_route.lp_head);
18594 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18595 	    (int)optp->level, (int)optp->name, (int)optp->len));
18596 	qreply(q, mpctl);
18597 
18598 	/* ipv6NetToMediaEntryTable in mp3ctl */
18599 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18600 
18601 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18602 	optp->level = MIB2_IP6;
18603 	optp->name = MIB2_IP6_MEDIA;
18604 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18605 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18606 	    (int)optp->level, (int)optp->name, (int)optp->len));
18607 	qreply(q, mp3ctl);
18608 
18609 	/* ipv6RouteAttributeTable in mp4ctl */
18610 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18611 	optp->level = MIB2_IP6;
18612 	optp->name = EXPER_IP_RTATTR;
18613 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18614 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18615 	    (int)optp->level, (int)optp->name, (int)optp->len));
18616 	if (optp->len == 0)
18617 		freemsg(mp4ctl);
18618 	else
18619 		qreply(q, mp4ctl);
18620 
18621 	return (mp2ctl);
18622 }
18623 
18624 /*
18625  * ICMPv6 mib: One per ill
18626  */
18627 static mblk_t *
18628 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18629 {
18630 	struct opthdr		*optp;
18631 	mblk_t			*mp2ctl;
18632 	ill_t			*ill;
18633 	ill_walk_context_t	ctx;
18634 	mblk_t			*mp_tail = NULL;
18635 
18636 	/*
18637 	 * Make a copy of the original message
18638 	 */
18639 	mp2ctl = copymsg(mpctl);
18640 
18641 	/* fixed length IPv6 structure ... */
18642 
18643 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18644 	optp->level = MIB2_IP6;
18645 	optp->name = 0;
18646 	/* Include "unknown interface" ip6_mib */
18647 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
18648 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
18649 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
18650 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
18651 	    sizeof (mib2_ipv6IfStatsEntry_t));
18652 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18653 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
18654 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
18655 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18656 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
18657 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18658 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18659 	    (int)sizeof (ip6_mib))) {
18660 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18661 		    (uint_t)sizeof (ip6_mib)));
18662 	}
18663 
18664 	rw_enter(&ill_g_lock, RW_READER);
18665 	ill = ILL_START_WALK_V6(&ctx);
18666 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18667 		ill->ill_ip6_mib->ipv6IfIndex =
18668 		    ill->ill_phyint->phyint_ifindex;
18669 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
18670 		    ipv6_forward ? 1 : 2);
18671 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
18672 		    ill->ill_max_hops);
18673 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
18674 		    sizeof (mib2_ipv6IfStatsEntry_t));
18675 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
18676 		    sizeof (mib2_ipv6AddrEntry_t));
18677 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
18678 		    sizeof (mib2_ipv6RouteEntry_t));
18679 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
18680 		    sizeof (mib2_ipv6NetToMediaEntry_t));
18681 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
18682 		    sizeof (ipv6_member_t));
18683 
18684 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18685 		    (char *)ill->ill_ip6_mib,
18686 		    (int)sizeof (*ill->ill_ip6_mib))) {
18687 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18688 				"%u bytes\n",
18689 				(uint_t)sizeof (*ill->ill_ip6_mib)));
18690 		}
18691 	}
18692 	rw_exit(&ill_g_lock);
18693 
18694 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18695 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18696 	    (int)optp->level, (int)optp->name, (int)optp->len));
18697 	qreply(q, mpctl);
18698 	return (mp2ctl);
18699 }
18700 
18701 /*
18702  * ICMPv6 mib: One per ill
18703  */
18704 static mblk_t *
18705 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18706 {
18707 	struct opthdr		*optp;
18708 	mblk_t			*mp2ctl;
18709 	ill_t			*ill;
18710 	ill_walk_context_t	ctx;
18711 	mblk_t			*mp_tail = NULL;
18712 	/*
18713 	 * Make a copy of the original message
18714 	 */
18715 	mp2ctl = copymsg(mpctl);
18716 
18717 	/* fixed length ICMPv6 structure ... */
18718 
18719 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18720 	optp->level = MIB2_ICMP6;
18721 	optp->name = 0;
18722 	/* Include "unknown interface" icmp6_mib */
18723 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
18724 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18725 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18726 	    (int)sizeof (icmp6_mib))) {
18727 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18728 		    (uint_t)sizeof (icmp6_mib)));
18729 	}
18730 
18731 	rw_enter(&ill_g_lock, RW_READER);
18732 	ill = ILL_START_WALK_V6(&ctx);
18733 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18734 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18735 		    ill->ill_phyint->phyint_ifindex;
18736 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
18737 		    sizeof (mib2_ipv6IfIcmpEntry_t);
18738 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18739 		    (char *)ill->ill_icmp6_mib,
18740 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18741 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18742 			    "%u bytes\n",
18743 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18744 		}
18745 	}
18746 	rw_exit(&ill_g_lock);
18747 
18748 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18749 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18750 	    (int)optp->level, (int)optp->name, (int)optp->len));
18751 	qreply(q, mpctl);
18752 	return (mp2ctl);
18753 }
18754 
18755 /*
18756  * ire_walk routine to create both ipRouteEntryTable and
18757  * ipNetToMediaEntryTable in one IRE walk
18758  */
18759 static void
18760 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18761 {
18762 	ill_t				*ill;
18763 	ipif_t				*ipif;
18764 	mblk_t				*llmp;
18765 	dl_unitdata_req_t		*dlup;
18766 	mib2_ipRouteEntry_t		*re;
18767 	mib2_ipNetToMediaEntry_t	ntme;
18768 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18769 	ipaddr_t			gw_addr;
18770 	tsol_ire_gw_secattr_t		*attrp;
18771 	tsol_gc_t			*gc = NULL;
18772 	tsol_gcgrp_t			*gcgrp = NULL;
18773 	uint_t				sacnt = 0;
18774 	int				i;
18775 
18776 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18777 
18778 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18779 		return;
18780 
18781 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18782 		mutex_enter(&attrp->igsa_lock);
18783 		if ((gc = attrp->igsa_gc) != NULL) {
18784 			gcgrp = gc->gc_grp;
18785 			ASSERT(gcgrp != NULL);
18786 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18787 			sacnt = 1;
18788 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18789 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18790 			gc = gcgrp->gcgrp_head;
18791 			sacnt = gcgrp->gcgrp_count;
18792 		}
18793 		mutex_exit(&attrp->igsa_lock);
18794 
18795 		/* do nothing if there's no gc to report */
18796 		if (gc == NULL) {
18797 			ASSERT(sacnt == 0);
18798 			if (gcgrp != NULL) {
18799 				/* we might as well drop the lock now */
18800 				rw_exit(&gcgrp->gcgrp_rwlock);
18801 				gcgrp = NULL;
18802 			}
18803 			attrp = NULL;
18804 		}
18805 
18806 		ASSERT(gc == NULL || (gcgrp != NULL &&
18807 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18808 	}
18809 	ASSERT(sacnt == 0 || gc != NULL);
18810 
18811 	if (sacnt != 0 &&
18812 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18813 		kmem_free(re, sizeof (*re));
18814 		rw_exit(&gcgrp->gcgrp_rwlock);
18815 		return;
18816 	}
18817 
18818 	/*
18819 	 * Return all IRE types for route table... let caller pick and choose
18820 	 */
18821 	re->ipRouteDest = ire->ire_addr;
18822 	ipif = ire->ire_ipif;
18823 	re->ipRouteIfIndex.o_length = 0;
18824 	if (ire->ire_type == IRE_CACHE) {
18825 		ill = (ill_t *)ire->ire_stq->q_ptr;
18826 		re->ipRouteIfIndex.o_length =
18827 		    ill->ill_name_length == 0 ? 0 :
18828 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18829 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18830 		    re->ipRouteIfIndex.o_length);
18831 	} else if (ipif != NULL) {
18832 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18833 		    OCTET_LENGTH);
18834 		re->ipRouteIfIndex.o_length =
18835 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18836 	}
18837 	re->ipRouteMetric1 = -1;
18838 	re->ipRouteMetric2 = -1;
18839 	re->ipRouteMetric3 = -1;
18840 	re->ipRouteMetric4 = -1;
18841 
18842 	gw_addr = ire->ire_gateway_addr;
18843 
18844 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18845 		re->ipRouteNextHop = ire->ire_src_addr;
18846 	else
18847 		re->ipRouteNextHop = gw_addr;
18848 	/* indirect(4), direct(3), or invalid(2) */
18849 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18850 		re->ipRouteType = 2;
18851 	else
18852 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18853 	re->ipRouteProto = -1;
18854 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18855 	re->ipRouteMask = ire->ire_mask;
18856 	re->ipRouteMetric5 = -1;
18857 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
18858 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
18859 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
18860 	if (ire->ire_nce &&
18861 	    ire->ire_nce->nce_state == ND_REACHABLE)
18862 		llmp = ire->ire_nce->nce_res_mp;
18863 	else
18864 		llmp = NULL;
18865 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
18866 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
18867 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18868 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18869 	re->ipRouteInfo.re_flags	= ire->ire_flags;
18870 	re->ipRouteInfo.re_in_ill.o_length = 0;
18871 
18872 	if (ire->ire_flags & RTF_DYNAMIC) {
18873 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
18874 	} else {
18875 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
18876 	}
18877 
18878 	if (ire->ire_in_ill != NULL) {
18879 		re->ipRouteInfo.re_in_ill.o_length =
18880 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
18881 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
18882 		bcopy(ire->ire_in_ill->ill_name,
18883 		    re->ipRouteInfo.re_in_ill.o_bytes,
18884 		    re->ipRouteInfo.re_in_ill.o_length);
18885 	}
18886 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
18887 
18888 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18889 	    (char *)re, (int)sizeof (*re))) {
18890 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18891 		    (uint_t)sizeof (*re)));
18892 	}
18893 
18894 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18895 		iaeptr->iae_routeidx = ird->ird_idx;
18896 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18897 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18898 	}
18899 
18900 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18901 	    (char *)iae, sacnt * sizeof (*iae))) {
18902 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18903 		    (unsigned)(sacnt * sizeof (*iae))));
18904 	}
18905 
18906 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
18907 		goto done;
18908 	/*
18909 	 * only IRE_CACHE entries that are for a directly connected subnet
18910 	 * get appended to net -> phys addr table
18911 	 * (others in arp)
18912 	 */
18913 	ntme.ipNetToMediaIfIndex.o_length = 0;
18914 	ill = ire_to_ill(ire);
18915 	ASSERT(ill != NULL);
18916 	ntme.ipNetToMediaIfIndex.o_length =
18917 	    ill->ill_name_length == 0 ? 0 :
18918 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18919 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
18920 		    ntme.ipNetToMediaIfIndex.o_length);
18921 
18922 	ntme.ipNetToMediaPhysAddress.o_length = 0;
18923 	if (llmp) {
18924 		uchar_t *addr;
18925 
18926 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
18927 		/* Remove sap from  address */
18928 		if (ill->ill_sap_length < 0)
18929 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
18930 		else
18931 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
18932 			    ill->ill_sap_length;
18933 
18934 		ntme.ipNetToMediaPhysAddress.o_length =
18935 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18936 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18937 		    ntme.ipNetToMediaPhysAddress.o_length);
18938 	}
18939 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18940 	/* assume dynamic (may be changed in arp) */
18941 	ntme.ipNetToMediaType = 3;
18942 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18943 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18944 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18945 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18946 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18947 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18948 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18949 		    (uint_t)sizeof (ntme)));
18950 	}
18951 done:
18952 	/* bump route index for next pass */
18953 	ird->ird_idx++;
18954 
18955 	kmem_free(re, sizeof (*re));
18956 	if (sacnt != 0)
18957 		kmem_free(iae, sacnt * sizeof (*iae));
18958 
18959 	if (gcgrp != NULL)
18960 		rw_exit(&gcgrp->gcgrp_rwlock);
18961 }
18962 
18963 /*
18964  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18965  */
18966 static void
18967 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18968 {
18969 	ill_t				*ill;
18970 	ipif_t				*ipif;
18971 	mib2_ipv6RouteEntry_t		*re;
18972 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18973 	in6_addr_t			gw_addr_v6;
18974 	tsol_ire_gw_secattr_t		*attrp;
18975 	tsol_gc_t			*gc = NULL;
18976 	tsol_gcgrp_t			*gcgrp = NULL;
18977 	uint_t				sacnt = 0;
18978 	int				i;
18979 
18980 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18981 
18982 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18983 		return;
18984 
18985 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18986 		mutex_enter(&attrp->igsa_lock);
18987 		if ((gc = attrp->igsa_gc) != NULL) {
18988 			gcgrp = gc->gc_grp;
18989 			ASSERT(gcgrp != NULL);
18990 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18991 			sacnt = 1;
18992 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18993 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18994 			gc = gcgrp->gcgrp_head;
18995 			sacnt = gcgrp->gcgrp_count;
18996 		}
18997 		mutex_exit(&attrp->igsa_lock);
18998 
18999 		/* do nothing if there's no gc to report */
19000 		if (gc == NULL) {
19001 			ASSERT(sacnt == 0);
19002 			if (gcgrp != NULL) {
19003 				/* we might as well drop the lock now */
19004 				rw_exit(&gcgrp->gcgrp_rwlock);
19005 				gcgrp = NULL;
19006 			}
19007 			attrp = NULL;
19008 		}
19009 
19010 		ASSERT(gc == NULL || (gcgrp != NULL &&
19011 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19012 	}
19013 	ASSERT(sacnt == 0 || gc != NULL);
19014 
19015 	if (sacnt != 0 &&
19016 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19017 		kmem_free(re, sizeof (*re));
19018 		rw_exit(&gcgrp->gcgrp_rwlock);
19019 		return;
19020 	}
19021 
19022 	/*
19023 	 * Return all IRE types for route table... let caller pick and choose
19024 	 */
19025 	re->ipv6RouteDest = ire->ire_addr_v6;
19026 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19027 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19028 	re->ipv6RouteIfIndex.o_length = 0;
19029 	ipif = ire->ire_ipif;
19030 	if (ire->ire_type == IRE_CACHE) {
19031 		ill = (ill_t *)ire->ire_stq->q_ptr;
19032 		re->ipv6RouteIfIndex.o_length =
19033 		    ill->ill_name_length == 0 ? 0 :
19034 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19035 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19036 		    re->ipv6RouteIfIndex.o_length);
19037 	} else if (ipif != NULL) {
19038 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19039 		    OCTET_LENGTH);
19040 		re->ipv6RouteIfIndex.o_length =
19041 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19042 	}
19043 
19044 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19045 
19046 	mutex_enter(&ire->ire_lock);
19047 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19048 	mutex_exit(&ire->ire_lock);
19049 
19050 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19051 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19052 	else
19053 		re->ipv6RouteNextHop = gw_addr_v6;
19054 
19055 	/* remote(4), local(3), or discard(2) */
19056 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19057 		re->ipv6RouteType = 2;
19058 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19059 		re->ipv6RouteType = 3;
19060 	else
19061 		re->ipv6RouteType = 4;
19062 
19063 	re->ipv6RouteProtocol	= -1;
19064 	re->ipv6RoutePolicy	= 0;
19065 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19066 	re->ipv6RouteNextHopRDI	= 0;
19067 	re->ipv6RouteWeight	= 0;
19068 	re->ipv6RouteMetric	= 0;
19069 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19070 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19071 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19072 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19073 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19074 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19075 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19076 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19077 
19078 	if (ire->ire_flags & RTF_DYNAMIC) {
19079 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19080 	} else {
19081 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19082 	}
19083 
19084 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19085 	    (char *)re, (int)sizeof (*re))) {
19086 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19087 		    (uint_t)sizeof (*re)));
19088 	}
19089 
19090 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19091 		iaeptr->iae_routeidx = ird->ird_idx;
19092 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19093 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19094 	}
19095 
19096 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19097 	    (char *)iae, sacnt * sizeof (*iae))) {
19098 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19099 		    (unsigned)(sacnt * sizeof (*iae))));
19100 	}
19101 
19102 	/* bump route index for next pass */
19103 	ird->ird_idx++;
19104 
19105 	kmem_free(re, sizeof (*re));
19106 	if (sacnt != 0)
19107 		kmem_free(iae, sacnt * sizeof (*iae));
19108 
19109 	if (gcgrp != NULL)
19110 		rw_exit(&gcgrp->gcgrp_rwlock);
19111 }
19112 
19113 /*
19114  * ndp_walk routine to create ipv6NetToMediaEntryTable
19115  */
19116 static int
19117 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19118 {
19119 	ill_t				*ill;
19120 	mib2_ipv6NetToMediaEntry_t	ntme;
19121 	dl_unitdata_req_t		*dl;
19122 
19123 	ill = nce->nce_ill;
19124 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19125 		return (0);
19126 
19127 	/*
19128 	 * Neighbor cache entry attached to IRE with on-link
19129 	 * destination.
19130 	 */
19131 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19132 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19133 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19134 	    (nce->nce_res_mp != NULL)) {
19135 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19136 		ntme.ipv6NetToMediaPhysAddress.o_length =
19137 		    dl->dl_dest_addr_length;
19138 	} else {
19139 		ntme.ipv6NetToMediaPhysAddress.o_length =
19140 		    ill->ill_phys_addr_length;
19141 	}
19142 	if (nce->nce_res_mp != NULL) {
19143 		bcopy((char *)nce->nce_res_mp->b_rptr +
19144 		    NCE_LL_ADDR_OFFSET(ill),
19145 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19146 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19147 	} else {
19148 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19149 		    ill->ill_phys_addr_length);
19150 	}
19151 	/*
19152 	 * Note: Returns ND_* states. Should be:
19153 	 * reachable(1), stale(2), delay(3), probe(4),
19154 	 * invalid(5), unknown(6)
19155 	 */
19156 	ntme.ipv6NetToMediaState = nce->nce_state;
19157 	ntme.ipv6NetToMediaLastUpdated = 0;
19158 
19159 	/* other(1), dynamic(2), static(3), local(4) */
19160 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19161 		ntme.ipv6NetToMediaType = 4;
19162 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19163 		ntme.ipv6NetToMediaType = 1;
19164 	} else {
19165 		ntme.ipv6NetToMediaType = 2;
19166 	}
19167 
19168 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19169 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19170 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19171 		    (uint_t)sizeof (ntme)));
19172 	}
19173 	return (0);
19174 }
19175 
19176 /*
19177  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19178  */
19179 /* ARGSUSED */
19180 int
19181 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19182 {
19183 	switch (level) {
19184 	case MIB2_IP:
19185 	case MIB2_ICMP:
19186 		switch (name) {
19187 		default:
19188 			break;
19189 		}
19190 		return (1);
19191 	default:
19192 		return (1);
19193 	}
19194 }
19195 
19196 /*
19197  * Called before the options are updated to check if this packet will
19198  * be source routed from here.
19199  * This routine assumes that the options are well formed i.e. that they
19200  * have already been checked.
19201  */
19202 static boolean_t
19203 ip_source_routed(ipha_t *ipha)
19204 {
19205 	ipoptp_t	opts;
19206 	uchar_t		*opt;
19207 	uint8_t		optval;
19208 	uint8_t		optlen;
19209 	ipaddr_t	dst;
19210 	ire_t		*ire;
19211 
19212 	if (IS_SIMPLE_IPH(ipha)) {
19213 		ip2dbg(("not source routed\n"));
19214 		return (B_FALSE);
19215 	}
19216 	dst = ipha->ipha_dst;
19217 	for (optval = ipoptp_first(&opts, ipha);
19218 	    optval != IPOPT_EOL;
19219 	    optval = ipoptp_next(&opts)) {
19220 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19221 		opt = opts.ipoptp_cur;
19222 		optlen = opts.ipoptp_len;
19223 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19224 		    optval, optlen));
19225 		switch (optval) {
19226 			uint32_t off;
19227 		case IPOPT_SSRR:
19228 		case IPOPT_LSRR:
19229 			/*
19230 			 * If dst is one of our addresses and there are some
19231 			 * entries left in the source route return (true).
19232 			 */
19233 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19234 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
19235 			if (ire == NULL) {
19236 				ip2dbg(("ip_source_routed: not next"
19237 				    " source route 0x%x\n",
19238 				    ntohl(dst)));
19239 				return (B_FALSE);
19240 			}
19241 			ire_refrele(ire);
19242 			off = opt[IPOPT_OFFSET];
19243 			off--;
19244 			if (optlen < IP_ADDR_LEN ||
19245 			    off > optlen - IP_ADDR_LEN) {
19246 				/* End of source route */
19247 				ip1dbg(("ip_source_routed: end of SR\n"));
19248 				return (B_FALSE);
19249 			}
19250 			return (B_TRUE);
19251 		}
19252 	}
19253 	ip2dbg(("not source routed\n"));
19254 	return (B_FALSE);
19255 }
19256 
19257 /*
19258  * Check if the packet contains any source route.
19259  */
19260 static boolean_t
19261 ip_source_route_included(ipha_t *ipha)
19262 {
19263 	ipoptp_t	opts;
19264 	uint8_t		optval;
19265 
19266 	if (IS_SIMPLE_IPH(ipha))
19267 		return (B_FALSE);
19268 	for (optval = ipoptp_first(&opts, ipha);
19269 	    optval != IPOPT_EOL;
19270 	    optval = ipoptp_next(&opts)) {
19271 		switch (optval) {
19272 		case IPOPT_SSRR:
19273 		case IPOPT_LSRR:
19274 			return (B_TRUE);
19275 		}
19276 	}
19277 	return (B_FALSE);
19278 }
19279 
19280 /*
19281  * Called when the IRE expiration timer fires.
19282  */
19283 /* ARGSUSED */
19284 void
19285 ip_trash_timer_expire(void *args)
19286 {
19287 	int	flush_flag = 0;
19288 
19289 	/*
19290 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19291 	 * This lock makes sure that a new invocation of this function
19292 	 * that occurs due to an almost immediate timer firing will not
19293 	 * progress beyond this point until the current invocation is done
19294 	 */
19295 	mutex_enter(&ip_trash_timer_lock);
19296 	ip_ire_expire_id = 0;
19297 	mutex_exit(&ip_trash_timer_lock);
19298 
19299 	/* Periodic timer */
19300 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
19301 		/*
19302 		 * Remove all IRE_CACHE entries since they might
19303 		 * contain arp information.
19304 		 */
19305 		flush_flag |= FLUSH_ARP_TIME;
19306 		ip_ire_arp_time_elapsed = 0;
19307 		IP_STAT(ip_ire_arp_timer_expired);
19308 	}
19309 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
19310 		/* Remove all redirects */
19311 		flush_flag |= FLUSH_REDIRECT_TIME;
19312 		ip_ire_rd_time_elapsed = 0;
19313 		IP_STAT(ip_ire_redirect_timer_expired);
19314 	}
19315 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
19316 		/* Increase path mtu */
19317 		flush_flag |= FLUSH_MTU_TIME;
19318 		ip_ire_pmtu_time_elapsed = 0;
19319 		IP_STAT(ip_ire_pmtu_timer_expired);
19320 	}
19321 
19322 	/*
19323 	 * Optimize for the case when there are no redirects in the
19324 	 * ftable, that is, no need to walk the ftable in that case.
19325 	 */
19326 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19327 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19328 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
19329 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
19330 	}
19331 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
19332 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19333 		    ire_expire, (char *)(uintptr_t)flush_flag,
19334 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
19335 	}
19336 	if (flush_flag & FLUSH_MTU_TIME) {
19337 		/*
19338 		 * Walk all IPv6 IRE's and update them
19339 		 * Note that ARP and redirect timers are not
19340 		 * needed since NUD handles stale entries.
19341 		 */
19342 		flush_flag = FLUSH_MTU_TIME;
19343 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
19344 		    ALL_ZONES);
19345 	}
19346 
19347 	ip_ire_arp_time_elapsed += ip_timer_interval;
19348 	ip_ire_rd_time_elapsed += ip_timer_interval;
19349 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19350 
19351 	/*
19352 	 * Hold the lock to serialize timeout calls and prevent
19353 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19354 	 * for the timer to fire and a new invocation of this function
19355 	 * to start before the return value of timeout has been stored
19356 	 * in ip_ire_expire_id by the current invocation.
19357 	 */
19358 	mutex_enter(&ip_trash_timer_lock);
19359 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19360 	    MSEC_TO_TICK(ip_timer_interval));
19361 	mutex_exit(&ip_trash_timer_lock);
19362 }
19363 
19364 /*
19365  * Called by the memory allocator subsystem directly, when the system
19366  * is running low on memory.
19367  */
19368 /* ARGSUSED */
19369 void
19370 ip_trash_ire_reclaim(void *args)
19371 {
19372 	ire_cache_count_t icc;
19373 	ire_cache_reclaim_t icr;
19374 	ncc_cache_count_t ncc;
19375 	nce_cache_reclaim_t ncr;
19376 	uint_t delete_cnt;
19377 	/*
19378 	 * Memory reclaim call back.
19379 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19380 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19381 	 * entries, determine what fraction to free for
19382 	 * each category of IRE_CACHE entries giving absolute priority
19383 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19384 	 * entry will be freed unless all offlink entries are freed).
19385 	 */
19386 	icc.icc_total = 0;
19387 	icc.icc_unused = 0;
19388 	icc.icc_offlink = 0;
19389 	icc.icc_pmtu = 0;
19390 	icc.icc_onlink = 0;
19391 	ire_walk(ire_cache_count, (char *)&icc);
19392 
19393 	/*
19394 	 * Free NCEs for IPv6 like the onlink ires.
19395 	 */
19396 	ncc.ncc_total = 0;
19397 	ncc.ncc_host = 0;
19398 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19399 
19400 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19401 	    icc.icc_pmtu + icc.icc_onlink);
19402 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19403 	IP_STAT(ip_trash_ire_reclaim_calls);
19404 	if (delete_cnt == 0)
19405 		return;
19406 	IP_STAT(ip_trash_ire_reclaim_success);
19407 	/* Always delete all unused offlink entries */
19408 	icr.icr_unused = 1;
19409 	if (delete_cnt <= icc.icc_unused) {
19410 		/*
19411 		 * Only need to free unused entries.  In other words,
19412 		 * there are enough unused entries to free to meet our
19413 		 * target number of freed ire cache entries.
19414 		 */
19415 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19416 		ncr.ncr_host = 0;
19417 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19418 		/*
19419 		 * Only need to free unused entries, plus a fraction of offlink
19420 		 * entries.  It follows from the first if statement that
19421 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19422 		 */
19423 		delete_cnt -= icc.icc_unused;
19424 		/* Round up # deleted by truncating fraction */
19425 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19426 		icr.icr_pmtu = icr.icr_onlink = 0;
19427 		ncr.ncr_host = 0;
19428 	} else if (delete_cnt <=
19429 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19430 		/*
19431 		 * Free all unused and offlink entries, plus a fraction of
19432 		 * pmtu entries.  It follows from the previous if statement
19433 		 * that icc_pmtu is non-zero, and that
19434 		 * delete_cnt != icc_unused + icc_offlink.
19435 		 */
19436 		icr.icr_offlink = 1;
19437 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19438 		/* Round up # deleted by truncating fraction */
19439 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19440 		icr.icr_onlink = 0;
19441 		ncr.ncr_host = 0;
19442 	} else {
19443 		/*
19444 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19445 		 * of onlink entries.  If we're here, then we know that
19446 		 * icc_onlink is non-zero, and that
19447 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19448 		 */
19449 		icr.icr_offlink = icr.icr_pmtu = 1;
19450 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19451 		    icc.icc_pmtu;
19452 		/* Round up # deleted by truncating fraction */
19453 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19454 		/* Using the same delete fraction as for onlink IREs */
19455 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19456 	}
19457 #ifdef DEBUG
19458 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19459 	    "fractions %d/%d/%d/%d\n",
19460 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19461 	    icc.icc_unused, icc.icc_offlink,
19462 	    icc.icc_pmtu, icc.icc_onlink,
19463 	    icr.icr_unused, icr.icr_offlink,
19464 	    icr.icr_pmtu, icr.icr_onlink));
19465 #endif
19466 	ire_walk(ire_cache_reclaim, (char *)&icr);
19467 	if (ncr.ncr_host != 0)
19468 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19469 		    (uchar_t *)&ncr);
19470 #ifdef DEBUG
19471 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19472 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19473 	ire_walk(ire_cache_count, (char *)&icc);
19474 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19475 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19476 	    icc.icc_pmtu, icc.icc_onlink));
19477 #endif
19478 }
19479 
19480 /*
19481  * ip_unbind is called when a copy of an unbind request is received from the
19482  * upper level protocol.  We remove this conn from any fanout hash list it is
19483  * on, and zero out the bind information.  No reply is expected up above.
19484  */
19485 mblk_t *
19486 ip_unbind(queue_t *q, mblk_t *mp)
19487 {
19488 	conn_t	*connp = Q_TO_CONN(q);
19489 
19490 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19491 
19492 	if (is_system_labeled() && connp->conn_anon_port) {
19493 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19494 		    connp->conn_mlp_type, connp->conn_ulp,
19495 		    ntohs(connp->conn_lport), B_FALSE);
19496 		connp->conn_anon_port = 0;
19497 	}
19498 	connp->conn_mlp_type = mlptSingle;
19499 
19500 	ipcl_hash_remove(connp);
19501 
19502 	ASSERT(mp->b_cont == NULL);
19503 	/*
19504 	 * Convert mp into a T_OK_ACK
19505 	 */
19506 	mp = mi_tpi_ok_ack_alloc(mp);
19507 
19508 	/*
19509 	 * should not happen in practice... T_OK_ACK is smaller than the
19510 	 * original message.
19511 	 */
19512 	if (mp == NULL)
19513 		return (NULL);
19514 
19515 	/*
19516 	 * Don't bzero the ports if its TCP since TCP still needs the
19517 	 * lport to remove it from its own bind hash. TCP will do the
19518 	 * cleanup.
19519 	 */
19520 	if (!IPCL_IS_TCP(connp))
19521 		bzero(&connp->u_port, sizeof (connp->u_port));
19522 
19523 	return (mp);
19524 }
19525 
19526 /*
19527  * Write side put procedure.  Outbound data, IOCTLs, responses from
19528  * resolvers, etc, come down through here.
19529  *
19530  * arg2 is always a queue_t *.
19531  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19532  * the zoneid.
19533  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19534  */
19535 void
19536 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19537 {
19538 	conn_t		*connp = NULL;
19539 	queue_t		*q = (queue_t *)arg2;
19540 	ipha_t		*ipha;
19541 #define	rptr	((uchar_t *)ipha)
19542 	ire_t		*ire = NULL;
19543 	ire_t		*sctp_ire = NULL;
19544 	uint32_t	v_hlen_tos_len;
19545 	ipaddr_t	dst;
19546 	mblk_t		*first_mp = NULL;
19547 	boolean_t	mctl_present;
19548 	ipsec_out_t	*io;
19549 	int		match_flags;
19550 	ill_t		*attach_ill = NULL;
19551 					/* Bind to IPIF_NOFAILOVER ill etc. */
19552 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19553 	ipif_t		*dst_ipif;
19554 	boolean_t	multirt_need_resolve = B_FALSE;
19555 	mblk_t		*copy_mp = NULL;
19556 	int		err;
19557 	zoneid_t	zoneid;
19558 	int	adjust;
19559 	uint16_t iplen;
19560 	boolean_t	need_decref = B_FALSE;
19561 	boolean_t	ignore_dontroute = B_FALSE;
19562 	boolean_t	ignore_nexthop = B_FALSE;
19563 	boolean_t	ip_nexthop = B_FALSE;
19564 	ipaddr_t	nexthop_addr;
19565 
19566 #ifdef	_BIG_ENDIAN
19567 #define	V_HLEN	(v_hlen_tos_len >> 24)
19568 #else
19569 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19570 #endif
19571 
19572 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19573 	    "ip_wput_start: q %p", q);
19574 
19575 	/*
19576 	 * ip_wput fast path
19577 	 */
19578 
19579 	/* is packet from ARP ? */
19580 	if (q->q_next != NULL) {
19581 		zoneid = (zoneid_t)(uintptr_t)arg;
19582 		goto qnext;
19583 	}
19584 
19585 	connp = (conn_t *)arg;
19586 	ASSERT(connp != NULL);
19587 	zoneid = connp->conn_zoneid;
19588 
19589 	/* is queue flow controlled? */
19590 	if ((q->q_first != NULL || connp->conn_draining) &&
19591 	    (caller == IP_WPUT)) {
19592 		ASSERT(!need_decref);
19593 		(void) putq(q, mp);
19594 		return;
19595 	}
19596 
19597 	/* Multidata transmit? */
19598 	if (DB_TYPE(mp) == M_MULTIDATA) {
19599 		/*
19600 		 * We should never get here, since all Multidata messages
19601 		 * originating from tcp should have been directed over to
19602 		 * tcp_multisend() in the first place.
19603 		 */
19604 		BUMP_MIB(&ip_mib, ipOutDiscards);
19605 		freemsg(mp);
19606 		return;
19607 	} else if (DB_TYPE(mp) != M_DATA)
19608 		goto notdata;
19609 
19610 	if (mp->b_flag & MSGHASREF) {
19611 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19612 		mp->b_flag &= ~MSGHASREF;
19613 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19614 		need_decref = B_TRUE;
19615 	}
19616 	ipha = (ipha_t *)mp->b_rptr;
19617 
19618 	/* is IP header non-aligned or mblk smaller than basic IP header */
19619 #ifndef SAFETY_BEFORE_SPEED
19620 	if (!OK_32PTR(rptr) ||
19621 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19622 		goto hdrtoosmall;
19623 #endif
19624 
19625 	ASSERT(OK_32PTR(ipha));
19626 
19627 	/*
19628 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19629 	 * wrong version, we'll catch it again in ip_output_v6.
19630 	 *
19631 	 * Note that this is *only* locally-generated output here, and never
19632 	 * forwarded data, and that we need to deal only with transports that
19633 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19634 	 * label.)
19635 	 */
19636 	if (is_system_labeled() &&
19637 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19638 	    !connp->conn_ulp_labeled) {
19639 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19640 		    connp->conn_mac_exempt);
19641 		ipha = (ipha_t *)mp->b_rptr;
19642 		if (err != 0) {
19643 			first_mp = mp;
19644 			if (err == EINVAL)
19645 				goto icmp_parameter_problem;
19646 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19647 			goto drop_pkt;
19648 		}
19649 		iplen = ntohs(ipha->ipha_length) + adjust;
19650 		ipha->ipha_length = htons(iplen);
19651 	}
19652 
19653 	/*
19654 	 * If there is a policy, try to attach an ipsec_out in
19655 	 * the front. At the end, first_mp either points to a
19656 	 * M_DATA message or IPSEC_OUT message linked to a
19657 	 * M_DATA message. We have to do it now as we might
19658 	 * lose the "conn" if we go through ip_newroute.
19659 	 */
19660 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19661 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
19662 		    ipha->ipha_protocol)) == NULL)) {
19663 			if (need_decref)
19664 				CONN_DEC_REF(connp);
19665 			return;
19666 		} else {
19667 			ASSERT(mp->b_datap->db_type == M_CTL);
19668 			first_mp = mp;
19669 			mp = mp->b_cont;
19670 			mctl_present = B_TRUE;
19671 		}
19672 	} else {
19673 		first_mp = mp;
19674 		mctl_present = B_FALSE;
19675 	}
19676 
19677 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19678 
19679 	/* is wrong version or IP options present */
19680 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19681 		goto version_hdrlen_check;
19682 	dst = ipha->ipha_dst;
19683 
19684 	if (connp->conn_nofailover_ill != NULL) {
19685 		attach_ill = conn_get_held_ill(connp,
19686 		    &connp->conn_nofailover_ill, &err);
19687 		if (err == ILL_LOOKUP_FAILED) {
19688 			if (need_decref)
19689 				CONN_DEC_REF(connp);
19690 			freemsg(first_mp);
19691 			return;
19692 		}
19693 	}
19694 
19695 	/* is packet multicast? */
19696 	if (CLASSD(dst))
19697 		goto multicast;
19698 
19699 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19700 	    (connp->conn_nexthop_set)) {
19701 		/*
19702 		 * If the destination is a broadcast or a loopback
19703 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
19704 		 * through the standard path. But in the case of local
19705 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
19706 		 * the standard path not IP_XMIT_IF.
19707 		 */
19708 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19709 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
19710 		    (ire->ire_type != IRE_LOOPBACK))) {
19711 			if ((connp->conn_dontroute ||
19712 			    connp->conn_nexthop_set) && (ire != NULL) &&
19713 			    (ire->ire_type == IRE_LOCAL))
19714 				goto standard_path;
19715 
19716 			if (ire != NULL) {
19717 				ire_refrele(ire);
19718 				/* No more access to ire */
19719 				ire = NULL;
19720 			}
19721 			/*
19722 			 * bypass routing checks and go directly to
19723 			 * interface.
19724 			 */
19725 			if (connp->conn_dontroute) {
19726 				goto dontroute;
19727 			} else if (connp->conn_nexthop_set) {
19728 				ip_nexthop = B_TRUE;
19729 				nexthop_addr = connp->conn_nexthop_v4;
19730 				goto send_from_ill;
19731 			}
19732 
19733 			/*
19734 			 * If IP_XMIT_IF socket option is set,
19735 			 * then we allow unicast and multicast
19736 			 * packets to go through the ill. It is
19737 			 * quite possible that the destination
19738 			 * is not in the ire cache table and we
19739 			 * do not want to go to ip_newroute()
19740 			 * instead we call ip_newroute_ipif.
19741 			 */
19742 			xmit_ill = conn_get_held_ill(connp,
19743 			    &connp->conn_xmit_if_ill, &err);
19744 			if (err == ILL_LOOKUP_FAILED) {
19745 				if (attach_ill != NULL)
19746 					ill_refrele(attach_ill);
19747 				if (need_decref)
19748 					CONN_DEC_REF(connp);
19749 				freemsg(first_mp);
19750 				return;
19751 			}
19752 			goto send_from_ill;
19753 		}
19754 standard_path:
19755 		/* Must be a broadcast, a loopback or a local ire */
19756 		if (ire != NULL) {
19757 			ire_refrele(ire);
19758 			/* No more access to ire */
19759 			ire = NULL;
19760 		}
19761 	}
19762 
19763 	if (attach_ill != NULL)
19764 		goto send_from_ill;
19765 
19766 	/*
19767 	 * We cache IRE_CACHEs to avoid lookups. We don't do
19768 	 * this for the tcp global queue and listen end point
19769 	 * as it does not really have a real destination to
19770 	 * talk to.  This is also true for SCTP.
19771 	 */
19772 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
19773 	    !connp->conn_fully_bound) {
19774 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19775 		if (ire == NULL)
19776 			goto noirefound;
19777 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19778 		    "ip_wput_end: q %p (%S)", q, "end");
19779 
19780 		/*
19781 		 * Check if the ire has the RTF_MULTIRT flag, inherited
19782 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19783 		 */
19784 		if (ire->ire_flags & RTF_MULTIRT) {
19785 
19786 			/*
19787 			 * Force the TTL of multirouted packets if required.
19788 			 * The TTL of such packets is bounded by the
19789 			 * ip_multirt_ttl ndd variable.
19790 			 */
19791 			if ((ip_multirt_ttl > 0) &&
19792 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
19793 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
19794 				    "(was %d), dst 0x%08x\n",
19795 				    ip_multirt_ttl, ipha->ipha_ttl,
19796 				    ntohl(ire->ire_addr)));
19797 				ipha->ipha_ttl = ip_multirt_ttl;
19798 			}
19799 			/*
19800 			 * We look at this point if there are pending
19801 			 * unresolved routes. ire_multirt_resolvable()
19802 			 * checks in O(n) that all IRE_OFFSUBNET ire
19803 			 * entries for the packet's destination and
19804 			 * flagged RTF_MULTIRT are currently resolved.
19805 			 * If some remain unresolved, we make a copy
19806 			 * of the current message. It will be used
19807 			 * to initiate additional route resolutions.
19808 			 */
19809 			multirt_need_resolve =
19810 			    ire_multirt_need_resolve(ire->ire_addr,
19811 			    MBLK_GETLABEL(first_mp));
19812 			ip2dbg(("ip_wput[TCP]: ire %p, "
19813 			    "multirt_need_resolve %d, first_mp %p\n",
19814 			    (void *)ire, multirt_need_resolve,
19815 			    (void *)first_mp));
19816 			if (multirt_need_resolve) {
19817 				copy_mp = copymsg(first_mp);
19818 				if (copy_mp != NULL) {
19819 					MULTIRT_DEBUG_TAG(copy_mp);
19820 				}
19821 			}
19822 		}
19823 
19824 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19825 
19826 		/*
19827 		 * Try to resolve another multiroute if
19828 		 * ire_multirt_need_resolve() deemed it necessary.
19829 		 */
19830 		if (copy_mp != NULL) {
19831 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19832 		}
19833 		if (need_decref)
19834 			CONN_DEC_REF(connp);
19835 		return;
19836 	}
19837 
19838 	/*
19839 	 * Access to conn_ire_cache. (protected by conn_lock)
19840 	 *
19841 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
19842 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
19843 	 * send a packet or two with the IRE_CACHE that is going away.
19844 	 * Access to the ire requires an ire refhold on the ire prior to
19845 	 * its use since an interface unplumb thread may delete the cached
19846 	 * ire and release the refhold at any time.
19847 	 *
19848 	 * Caching an ire in the conn_ire_cache
19849 	 *
19850 	 * o Caching an ire pointer in the conn requires a strict check for
19851 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
19852 	 * ires  before cleaning up the conns. So the caching of an ire pointer
19853 	 * in the conn is done after making sure under the bucket lock that the
19854 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
19855 	 * caching an ire after the unplumb thread has cleaned up the conn.
19856 	 * If the conn does not send a packet subsequently the unplumb thread
19857 	 * will be hanging waiting for the ire count to drop to zero.
19858 	 *
19859 	 * o We also need to atomically test for a null conn_ire_cache and
19860 	 * set the conn_ire_cache under the the protection of the conn_lock
19861 	 * to avoid races among concurrent threads trying to simultaneously
19862 	 * cache an ire in the conn_ire_cache.
19863 	 */
19864 	mutex_enter(&connp->conn_lock);
19865 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
19866 
19867 	if (ire != NULL && ire->ire_addr == dst &&
19868 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19869 
19870 		IRE_REFHOLD(ire);
19871 		mutex_exit(&connp->conn_lock);
19872 
19873 	} else {
19874 		boolean_t cached = B_FALSE;
19875 		connp->conn_ire_cache = NULL;
19876 		mutex_exit(&connp->conn_lock);
19877 		/* Release the old ire */
19878 		if (ire != NULL && sctp_ire == NULL)
19879 			IRE_REFRELE_NOTR(ire);
19880 
19881 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19882 		if (ire == NULL)
19883 			goto noirefound;
19884 		IRE_REFHOLD_NOTR(ire);
19885 
19886 		mutex_enter(&connp->conn_lock);
19887 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
19888 		    connp->conn_ire_cache == NULL) {
19889 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19890 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19891 				connp->conn_ire_cache = ire;
19892 				cached = B_TRUE;
19893 			}
19894 			rw_exit(&ire->ire_bucket->irb_lock);
19895 		}
19896 		mutex_exit(&connp->conn_lock);
19897 
19898 		/*
19899 		 * We can continue to use the ire but since it was
19900 		 * not cached, we should drop the extra reference.
19901 		 */
19902 		if (!cached)
19903 			IRE_REFRELE_NOTR(ire);
19904 	}
19905 
19906 
19907 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19908 	    "ip_wput_end: q %p (%S)", q, "end");
19909 
19910 	/*
19911 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19912 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19913 	 */
19914 	if (ire->ire_flags & RTF_MULTIRT) {
19915 
19916 		/*
19917 		 * Force the TTL of multirouted packets if required.
19918 		 * The TTL of such packets is bounded by the
19919 		 * ip_multirt_ttl ndd variable.
19920 		 */
19921 		if ((ip_multirt_ttl > 0) &&
19922 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19923 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19924 			    "(was %d), dst 0x%08x\n",
19925 			    ip_multirt_ttl, ipha->ipha_ttl,
19926 			    ntohl(ire->ire_addr)));
19927 			ipha->ipha_ttl = ip_multirt_ttl;
19928 		}
19929 
19930 		/*
19931 		 * At this point, we check to see if there are any pending
19932 		 * unresolved routes. ire_multirt_resolvable()
19933 		 * checks in O(n) that all IRE_OFFSUBNET ire
19934 		 * entries for the packet's destination and
19935 		 * flagged RTF_MULTIRT are currently resolved.
19936 		 * If some remain unresolved, we make a copy
19937 		 * of the current message. It will be used
19938 		 * to initiate additional route resolutions.
19939 		 */
19940 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19941 		    MBLK_GETLABEL(first_mp));
19942 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19943 		    "multirt_need_resolve %d, first_mp %p\n",
19944 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19945 		if (multirt_need_resolve) {
19946 			copy_mp = copymsg(first_mp);
19947 			if (copy_mp != NULL) {
19948 				MULTIRT_DEBUG_TAG(copy_mp);
19949 			}
19950 		}
19951 	}
19952 
19953 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19954 
19955 	/*
19956 	 * Try to resolve another multiroute if
19957 	 * ire_multirt_resolvable() deemed it necessary
19958 	 */
19959 	if (copy_mp != NULL) {
19960 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19961 	}
19962 	if (need_decref)
19963 		CONN_DEC_REF(connp);
19964 	return;
19965 
19966 qnext:
19967 	/*
19968 	 * Upper Level Protocols pass down complete IP datagrams
19969 	 * as M_DATA messages.	Everything else is a sideshow.
19970 	 *
19971 	 * 1) We could be re-entering ip_wput because of ip_neworute
19972 	 *    in which case we could have a IPSEC_OUT message. We
19973 	 *    need to pass through ip_wput like other datagrams and
19974 	 *    hence cannot branch to ip_wput_nondata.
19975 	 *
19976 	 * 2) ARP, AH, ESP, and other clients who are on the module
19977 	 *    instance of IP stream, give us something to deal with.
19978 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19979 	 *
19980 	 * 3) ICMP replies also could come here.
19981 	 */
19982 	if (DB_TYPE(mp) != M_DATA) {
19983 	    notdata:
19984 		if (DB_TYPE(mp) == M_CTL) {
19985 			/*
19986 			 * M_CTL messages are used by ARP, AH and ESP to
19987 			 * communicate with IP. We deal with IPSEC_IN and
19988 			 * IPSEC_OUT here. ip_wput_nondata handles other
19989 			 * cases.
19990 			 */
19991 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19992 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19993 				first_mp = mp->b_cont;
19994 				first_mp->b_flag &= ~MSGHASREF;
19995 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19996 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19997 				CONN_DEC_REF(connp);
19998 				connp = NULL;
19999 			}
20000 			if (ii->ipsec_info_type == IPSEC_IN) {
20001 				/*
20002 				 * Either this message goes back to
20003 				 * IPSEC for further processing or to
20004 				 * ULP after policy checks.
20005 				 */
20006 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20007 				return;
20008 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20009 				io = (ipsec_out_t *)ii;
20010 				if (io->ipsec_out_proc_begin) {
20011 					/*
20012 					 * IPSEC processing has already started.
20013 					 * Complete it.
20014 					 * IPQoS notes: We don't care what is
20015 					 * in ipsec_out_ill_index since this
20016 					 * won't be processed for IPQoS policies
20017 					 * in ipsec_out_process.
20018 					 */
20019 					ipsec_out_process(q, mp, NULL,
20020 					    io->ipsec_out_ill_index);
20021 					return;
20022 				} else {
20023 					connp = (q->q_next != NULL) ?
20024 					    NULL : Q_TO_CONN(q);
20025 					first_mp = mp;
20026 					mp = mp->b_cont;
20027 					mctl_present = B_TRUE;
20028 				}
20029 				zoneid = io->ipsec_out_zoneid;
20030 				ASSERT(zoneid != ALL_ZONES);
20031 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20032 				/*
20033 				 * It's an IPsec control message requesting
20034 				 * an SADB update to be sent to the IPsec
20035 				 * hardware acceleration capable ills.
20036 				 */
20037 				ipsec_ctl_t *ipsec_ctl =
20038 				    (ipsec_ctl_t *)mp->b_rptr;
20039 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20040 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20041 				mblk_t *cmp = mp->b_cont;
20042 
20043 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20044 				ASSERT(cmp != NULL);
20045 
20046 				freeb(mp);
20047 				ill_ipsec_capab_send_all(satype, cmp, sa);
20048 				return;
20049 			} else {
20050 				/*
20051 				 * This must be ARP or special TSOL signaling.
20052 				 */
20053 				ip_wput_nondata(NULL, q, mp, NULL);
20054 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20055 				    "ip_wput_end: q %p (%S)", q, "nondata");
20056 				return;
20057 			}
20058 		} else {
20059 			/*
20060 			 * This must be non-(ARP/AH/ESP) messages.
20061 			 */
20062 			ASSERT(!need_decref);
20063 			ip_wput_nondata(NULL, q, mp, NULL);
20064 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20065 			    "ip_wput_end: q %p (%S)", q, "nondata");
20066 			return;
20067 		}
20068 	} else {
20069 		first_mp = mp;
20070 		mctl_present = B_FALSE;
20071 	}
20072 
20073 	ASSERT(first_mp != NULL);
20074 	/*
20075 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20076 	 * to make sure that this packet goes out on the same interface it
20077 	 * came in. We handle that here.
20078 	 */
20079 	if (mctl_present) {
20080 		uint_t ifindex;
20081 
20082 		io = (ipsec_out_t *)first_mp->b_rptr;
20083 		if (io->ipsec_out_attach_if ||
20084 		    io->ipsec_out_xmit_if ||
20085 		    io->ipsec_out_ip_nexthop) {
20086 			ill_t	*ill;
20087 
20088 			/*
20089 			 * We may have lost the conn context if we are
20090 			 * coming here from ip_newroute(). Copy the
20091 			 * nexthop information.
20092 			 */
20093 			if (io->ipsec_out_ip_nexthop) {
20094 				ip_nexthop = B_TRUE;
20095 				nexthop_addr = io->ipsec_out_nexthop_addr;
20096 
20097 				ipha = (ipha_t *)mp->b_rptr;
20098 				dst = ipha->ipha_dst;
20099 				goto send_from_ill;
20100 			} else {
20101 				ASSERT(io->ipsec_out_ill_index != 0);
20102 				ifindex = io->ipsec_out_ill_index;
20103 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20104 				    NULL, NULL, NULL, NULL);
20105 				/*
20106 				 * ipsec_out_xmit_if bit is used to tell
20107 				 * ip_wput to use the ill to send outgoing data
20108 				 * as we have no conn when data comes from ICMP
20109 				 * error msg routines. Currently this feature is
20110 				 * only used by ip_mrtun_forward routine.
20111 				 */
20112 				if (io->ipsec_out_xmit_if) {
20113 					xmit_ill = ill;
20114 					if (xmit_ill == NULL) {
20115 						ip1dbg(("ip_output:bad ifindex "
20116 						    "for xmit_ill %d\n",
20117 						    ifindex));
20118 						freemsg(first_mp);
20119 						BUMP_MIB(&ip_mib,
20120 						    ipOutDiscards);
20121 						ASSERT(!need_decref);
20122 						return;
20123 					}
20124 					/* Free up the ipsec_out_t mblk */
20125 					ASSERT(first_mp->b_cont == mp);
20126 					first_mp->b_cont = NULL;
20127 					freeb(first_mp);
20128 					/* Just send the IP header+ICMP+data */
20129 					first_mp = mp;
20130 					ipha = (ipha_t *)mp->b_rptr;
20131 					dst = ipha->ipha_dst;
20132 					goto send_from_ill;
20133 				} else {
20134 					attach_ill = ill;
20135 				}
20136 
20137 				if (attach_ill == NULL) {
20138 					ASSERT(xmit_ill == NULL);
20139 					ip1dbg(("ip_output: bad ifindex for "
20140 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20141 					    ifindex));
20142 					freemsg(first_mp);
20143 					BUMP_MIB(&ip_mib, ipOutDiscards);
20144 					ASSERT(!need_decref);
20145 					return;
20146 				}
20147 			}
20148 		}
20149 	}
20150 
20151 	ASSERT(xmit_ill == NULL);
20152 
20153 	/* We have a complete IP datagram heading outbound. */
20154 	ipha = (ipha_t *)mp->b_rptr;
20155 
20156 #ifndef SPEED_BEFORE_SAFETY
20157 	/*
20158 	 * Make sure we have a full-word aligned message and that at least
20159 	 * a simple IP header is accessible in the first message.  If not,
20160 	 * try a pullup.
20161 	 */
20162 	if (!OK_32PTR(rptr) ||
20163 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20164 	    hdrtoosmall:
20165 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20166 			BUMP_MIB(&ip_mib, ipOutDiscards);
20167 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20168 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20169 			if (first_mp == NULL)
20170 				first_mp = mp;
20171 			goto drop_pkt;
20172 		}
20173 
20174 		/* This function assumes that mp points to an IPv4 packet. */
20175 		if (is_system_labeled() && q->q_next == NULL &&
20176 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20177 		    !connp->conn_ulp_labeled) {
20178 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20179 			    &adjust, connp->conn_mac_exempt);
20180 			ipha = (ipha_t *)mp->b_rptr;
20181 			if (first_mp != NULL)
20182 				first_mp->b_cont = mp;
20183 			if (err != 0) {
20184 				if (first_mp == NULL)
20185 					first_mp = mp;
20186 				if (err == EINVAL)
20187 					goto icmp_parameter_problem;
20188 				ip2dbg(("ip_wput: label check failed (%d)\n",
20189 				    err));
20190 				goto drop_pkt;
20191 			}
20192 			iplen = ntohs(ipha->ipha_length) + adjust;
20193 			ipha->ipha_length = htons(iplen);
20194 		}
20195 
20196 		ipha = (ipha_t *)mp->b_rptr;
20197 		if (first_mp == NULL) {
20198 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20199 			/*
20200 			 * If we got here because of "goto hdrtoosmall"
20201 			 * We need to attach a IPSEC_OUT.
20202 			 */
20203 			if (connp->conn_out_enforce_policy) {
20204 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20205 				    NULL, ipha->ipha_protocol)) == NULL)) {
20206 					if (need_decref)
20207 						CONN_DEC_REF(connp);
20208 					return;
20209 				} else {
20210 					ASSERT(mp->b_datap->db_type == M_CTL);
20211 					first_mp = mp;
20212 					mp = mp->b_cont;
20213 					mctl_present = B_TRUE;
20214 				}
20215 			} else {
20216 				first_mp = mp;
20217 				mctl_present = B_FALSE;
20218 			}
20219 		}
20220 	}
20221 #endif
20222 
20223 	/* Most of the code below is written for speed, not readability */
20224 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20225 
20226 	/*
20227 	 * If ip_newroute() fails, we're going to need a full
20228 	 * header for the icmp wraparound.
20229 	 */
20230 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20231 		uint_t	v_hlen;
20232 	    version_hdrlen_check:
20233 		ASSERT(first_mp != NULL);
20234 		v_hlen = V_HLEN;
20235 		/*
20236 		 * siphon off IPv6 packets coming down from transport
20237 		 * layer modules here.
20238 		 * Note: high-order bit carries NUD reachability confirmation
20239 		 */
20240 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20241 			/*
20242 			 * XXX implement a IPv4 and IPv6 packet counter per
20243 			 * conn and switch when ratio exceeds e.g. 10:1
20244 			 */
20245 #ifdef notyet
20246 			if (q->q_next == NULL) /* Avoid ill queue */
20247 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
20248 #endif
20249 			BUMP_MIB(&ip_mib, ipOutIPv6);
20250 			ASSERT(xmit_ill == NULL);
20251 			if (attach_ill != NULL)
20252 				ill_refrele(attach_ill);
20253 			if (need_decref)
20254 				mp->b_flag |= MSGHASREF;
20255 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20256 			return;
20257 		}
20258 
20259 		if ((v_hlen >> 4) != IP_VERSION) {
20260 			BUMP_MIB(&ip_mib, ipOutDiscards);
20261 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20262 			    "ip_wput_end: q %p (%S)", q, "badvers");
20263 			goto drop_pkt;
20264 		}
20265 		/*
20266 		 * Is the header length at least 20 bytes?
20267 		 *
20268 		 * Are there enough bytes accessible in the header?  If
20269 		 * not, try a pullup.
20270 		 */
20271 		v_hlen &= 0xF;
20272 		v_hlen <<= 2;
20273 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20274 			BUMP_MIB(&ip_mib, ipOutDiscards);
20275 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20276 			    "ip_wput_end: q %p (%S)", q, "badlen");
20277 			goto drop_pkt;
20278 		}
20279 		if (v_hlen > (mp->b_wptr - rptr)) {
20280 			if (!pullupmsg(mp, v_hlen)) {
20281 				BUMP_MIB(&ip_mib, ipOutDiscards);
20282 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20283 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20284 				goto drop_pkt;
20285 			}
20286 			ipha = (ipha_t *)mp->b_rptr;
20287 		}
20288 		/*
20289 		 * Move first entry from any source route into ipha_dst and
20290 		 * verify the options
20291 		 */
20292 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
20293 			ASSERT(xmit_ill == NULL);
20294 			if (attach_ill != NULL)
20295 				ill_refrele(attach_ill);
20296 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20297 			    "ip_wput_end: q %p (%S)", q, "badopts");
20298 			if (need_decref)
20299 				CONN_DEC_REF(connp);
20300 			return;
20301 		}
20302 	}
20303 	dst = ipha->ipha_dst;
20304 
20305 	/*
20306 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20307 	 * we have to run the packet through ip_newroute which will take
20308 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20309 	 * a resolver, or assigning a default gateway, etc.
20310 	 */
20311 	if (CLASSD(dst)) {
20312 		ipif_t	*ipif;
20313 		uint32_t setsrc = 0;
20314 
20315 	    multicast:
20316 		ASSERT(first_mp != NULL);
20317 		ASSERT(xmit_ill == NULL);
20318 		ip2dbg(("ip_wput: CLASSD\n"));
20319 		if (connp == NULL) {
20320 			/*
20321 			 * Use the first good ipif on the ill.
20322 			 * XXX Should this ever happen? (Appears
20323 			 * to show up with just ppp and no ethernet due
20324 			 * to in.rdisc.)
20325 			 * However, ire_send should be able to
20326 			 * call ip_wput_ire directly.
20327 			 *
20328 			 * XXX Also, this can happen for ICMP and other packets
20329 			 * with multicast source addresses.  Perhaps we should
20330 			 * fix things so that we drop the packet in question,
20331 			 * but for now, just run with it.
20332 			 */
20333 			ill_t *ill = (ill_t *)q->q_ptr;
20334 
20335 			/*
20336 			 * Don't honor attach_if for this case. If ill
20337 			 * is part of the group, ipif could belong to
20338 			 * any ill and we cannot maintain attach_ill
20339 			 * and ipif_ill same anymore and the assert
20340 			 * below would fail.
20341 			 */
20342 			if (mctl_present && io->ipsec_out_attach_if) {
20343 				io->ipsec_out_ill_index = 0;
20344 				io->ipsec_out_attach_if = B_FALSE;
20345 				ASSERT(attach_ill != NULL);
20346 				ill_refrele(attach_ill);
20347 				attach_ill = NULL;
20348 			}
20349 
20350 			ASSERT(attach_ill == NULL);
20351 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20352 			if (ipif == NULL) {
20353 				if (need_decref)
20354 					CONN_DEC_REF(connp);
20355 				freemsg(first_mp);
20356 				return;
20357 			}
20358 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20359 			    ntohl(dst), ill->ill_name));
20360 		} else {
20361 			/*
20362 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
20363 			 * IP_XMIT_IF is honoured.
20364 			 * Block comment above this function explains the
20365 			 * locking mechanism used here
20366 			 */
20367 			xmit_ill = conn_get_held_ill(connp,
20368 			    &connp->conn_xmit_if_ill, &err);
20369 			if (err == ILL_LOOKUP_FAILED) {
20370 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
20371 				goto drop_pkt;
20372 			}
20373 			if (xmit_ill == NULL) {
20374 				ipif = conn_get_held_ipif(connp,
20375 				    &connp->conn_multicast_ipif, &err);
20376 				if (err == IPIF_LOOKUP_FAILED) {
20377 					ip1dbg(("ip_wput: No ipif for "
20378 					    "multicast\n"));
20379 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20380 					goto drop_pkt;
20381 				}
20382 			}
20383 			if (xmit_ill != NULL) {
20384 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20385 				if (ipif == NULL) {
20386 					ip1dbg(("ip_wput: No ipif for "
20387 					    "IP_XMIT_IF\n"));
20388 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20389 					goto drop_pkt;
20390 				}
20391 			} else if (ipif == NULL || ipif->ipif_isv6) {
20392 				/*
20393 				 * We must do this ipif determination here
20394 				 * else we could pass through ip_newroute
20395 				 * and come back here without the conn context.
20396 				 *
20397 				 * Note: we do late binding i.e. we bind to
20398 				 * the interface when the first packet is sent.
20399 				 * For performance reasons we do not rebind on
20400 				 * each packet but keep the binding until the
20401 				 * next IP_MULTICAST_IF option.
20402 				 *
20403 				 * conn_multicast_{ipif,ill} are shared between
20404 				 * IPv4 and IPv6 and AF_INET6 sockets can
20405 				 * send both IPv4 and IPv6 packets. Hence
20406 				 * we have to check that "isv6" matches above.
20407 				 */
20408 				if (ipif != NULL)
20409 					ipif_refrele(ipif);
20410 				ipif = ipif_lookup_group(dst, zoneid);
20411 				if (ipif == NULL) {
20412 					ip1dbg(("ip_wput: No ipif for "
20413 					    "multicast\n"));
20414 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20415 					goto drop_pkt;
20416 				}
20417 				err = conn_set_held_ipif(connp,
20418 				    &connp->conn_multicast_ipif, ipif);
20419 				if (err == IPIF_LOOKUP_FAILED) {
20420 					ipif_refrele(ipif);
20421 					ip1dbg(("ip_wput: No ipif for "
20422 					    "multicast\n"));
20423 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20424 					goto drop_pkt;
20425 				}
20426 			}
20427 		}
20428 		ASSERT(!ipif->ipif_isv6);
20429 		/*
20430 		 * As we may lose the conn by the time we reach ip_wput_ire,
20431 		 * we copy conn_multicast_loop and conn_dontroute on to an
20432 		 * ipsec_out. In case if this datagram goes out secure,
20433 		 * we need the ill_index also. Copy that also into the
20434 		 * ipsec_out.
20435 		 */
20436 		if (mctl_present) {
20437 			io = (ipsec_out_t *)first_mp->b_rptr;
20438 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20439 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20440 		} else {
20441 			ASSERT(mp == first_mp);
20442 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20443 			    BPRI_HI)) == NULL) {
20444 				ipif_refrele(ipif);
20445 				first_mp = mp;
20446 				goto drop_pkt;
20447 			}
20448 			first_mp->b_datap->db_type = M_CTL;
20449 			first_mp->b_wptr += sizeof (ipsec_info_t);
20450 			/* ipsec_out_secure is B_FALSE now */
20451 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20452 			io = (ipsec_out_t *)first_mp->b_rptr;
20453 			io->ipsec_out_type = IPSEC_OUT;
20454 			io->ipsec_out_len = sizeof (ipsec_out_t);
20455 			io->ipsec_out_use_global_policy = B_TRUE;
20456 			first_mp->b_cont = mp;
20457 			mctl_present = B_TRUE;
20458 		}
20459 		if (attach_ill != NULL) {
20460 			ASSERT(attach_ill == ipif->ipif_ill);
20461 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20462 
20463 			/*
20464 			 * Check if we need an ire that will not be
20465 			 * looked up by anybody else i.e. HIDDEN.
20466 			 */
20467 			if (ill_is_probeonly(attach_ill)) {
20468 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20469 			}
20470 			io->ipsec_out_ill_index =
20471 			    attach_ill->ill_phyint->phyint_ifindex;
20472 			io->ipsec_out_attach_if = B_TRUE;
20473 		} else {
20474 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20475 			io->ipsec_out_ill_index =
20476 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20477 		}
20478 		if (connp != NULL) {
20479 			io->ipsec_out_multicast_loop =
20480 			    connp->conn_multicast_loop;
20481 			io->ipsec_out_dontroute = connp->conn_dontroute;
20482 			io->ipsec_out_zoneid = connp->conn_zoneid;
20483 		}
20484 		/*
20485 		 * If the application uses IP_MULTICAST_IF with
20486 		 * different logical addresses of the same ILL, we
20487 		 * need to make sure that the soruce address of
20488 		 * the packet matches the logical IP address used
20489 		 * in the option. We do it by initializing ipha_src
20490 		 * here. This should keep IPSEC also happy as
20491 		 * when we return from IPSEC processing, we don't
20492 		 * have to worry about getting the right address on
20493 		 * the packet. Thus it is sufficient to look for
20494 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20495 		 * MATCH_IRE_IPIF.
20496 		 *
20497 		 * NOTE : We need to do it for non-secure case also as
20498 		 * this might go out secure if there is a global policy
20499 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20500 		 * address, the source should be initialized already and
20501 		 * hence we won't be initializing here.
20502 		 *
20503 		 * As we do not have the ire yet, it is possible that
20504 		 * we set the source address here and then later discover
20505 		 * that the ire implies the source address to be assigned
20506 		 * through the RTF_SETSRC flag.
20507 		 * In that case, the setsrc variable will remind us
20508 		 * that overwritting the source address by the one
20509 		 * of the RTF_SETSRC-flagged ire is allowed.
20510 		 */
20511 		if (ipha->ipha_src == INADDR_ANY &&
20512 		    (connp == NULL || !connp->conn_unspec_src)) {
20513 			ipha->ipha_src = ipif->ipif_src_addr;
20514 			setsrc = RTF_SETSRC;
20515 		}
20516 		/*
20517 		 * Find an IRE which matches the destination and the outgoing
20518 		 * queue (i.e. the outgoing interface.)
20519 		 * For loopback use a unicast IP address for
20520 		 * the ire lookup.
20521 		 */
20522 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20523 		    PHYI_LOOPBACK) {
20524 			dst = ipif->ipif_lcl_addr;
20525 		}
20526 		/*
20527 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20528 		 * We don't need to lookup ire in ctable as the packet
20529 		 * needs to be sent to the destination through the specified
20530 		 * ill irrespective of ires in the cache table.
20531 		 */
20532 		ire = NULL;
20533 		if (xmit_ill == NULL) {
20534 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20535 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20536 		}
20537 
20538 		/*
20539 		 * refrele attach_ill as its not needed anymore.
20540 		 */
20541 		if (attach_ill != NULL) {
20542 			ill_refrele(attach_ill);
20543 			attach_ill = NULL;
20544 		}
20545 
20546 		if (ire == NULL) {
20547 			/*
20548 			 * Multicast loopback and multicast forwarding is
20549 			 * done in ip_wput_ire.
20550 			 *
20551 			 * Mark this packet to make it be delivered to
20552 			 * ip_wput_ire after the new ire has been
20553 			 * created.
20554 			 *
20555 			 * The call to ip_newroute_ipif takes into account
20556 			 * the setsrc reminder. In any case, we take care
20557 			 * of the RTF_MULTIRT flag.
20558 			 */
20559 			mp->b_prev = mp->b_next = NULL;
20560 			if (xmit_ill == NULL ||
20561 			    xmit_ill->ill_ipif_up_count > 0) {
20562 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20563 				    setsrc | RTF_MULTIRT, zoneid);
20564 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20565 				    "ip_wput_end: q %p (%S)", q, "noire");
20566 			} else {
20567 				freemsg(first_mp);
20568 			}
20569 			ipif_refrele(ipif);
20570 			if (xmit_ill != NULL)
20571 				ill_refrele(xmit_ill);
20572 			if (need_decref)
20573 				CONN_DEC_REF(connp);
20574 			return;
20575 		}
20576 
20577 		ipif_refrele(ipif);
20578 		ipif = NULL;
20579 		ASSERT(xmit_ill == NULL);
20580 
20581 		/*
20582 		 * Honor the RTF_SETSRC flag for multicast packets,
20583 		 * if allowed by the setsrc reminder.
20584 		 */
20585 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20586 			ipha->ipha_src = ire->ire_src_addr;
20587 		}
20588 
20589 		/*
20590 		 * Unconditionally force the TTL to 1 for
20591 		 * multirouted multicast packets:
20592 		 * multirouted multicast should not cross
20593 		 * multicast routers.
20594 		 */
20595 		if (ire->ire_flags & RTF_MULTIRT) {
20596 			if (ipha->ipha_ttl > 1) {
20597 				ip2dbg(("ip_wput: forcing multicast "
20598 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20599 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20600 				ipha->ipha_ttl = 1;
20601 			}
20602 		}
20603 	} else {
20604 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20605 		if ((ire != NULL) && (ire->ire_type &
20606 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20607 			ignore_dontroute = B_TRUE;
20608 			ignore_nexthop = B_TRUE;
20609 		}
20610 		if (ire != NULL) {
20611 			ire_refrele(ire);
20612 			ire = NULL;
20613 		}
20614 		/*
20615 		 * Guard against coming in from arp in which case conn is NULL.
20616 		 * Also guard against non M_DATA with dontroute set but
20617 		 * destined to local, loopback or broadcast addresses.
20618 		 */
20619 		if (connp != NULL && connp->conn_dontroute &&
20620 		    !ignore_dontroute) {
20621 dontroute:
20622 			/*
20623 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20624 			 * routing protocols from seeing false direct
20625 			 * connectivity.
20626 			 */
20627 			ipha->ipha_ttl = 1;
20628 			/*
20629 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20630 			 * along with SO_DONTROUTE, higher precedence is
20631 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20632 			 */
20633 			if (connp->conn_xmit_if_ill == NULL) {
20634 				/* If suitable ipif not found, drop packet */
20635 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20636 				if (dst_ipif == NULL) {
20637 					ip1dbg(("ip_wput: no route for "
20638 					    "dst using SO_DONTROUTE\n"));
20639 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20640 					mp->b_prev = mp->b_next = NULL;
20641 					if (first_mp == NULL)
20642 						first_mp = mp;
20643 					goto drop_pkt;
20644 				} else {
20645 					/*
20646 					 * If suitable ipif has been found, set
20647 					 * xmit_ill to the corresponding
20648 					 * ipif_ill because we'll be following
20649 					 * the IP_XMIT_IF logic.
20650 					 */
20651 					ASSERT(xmit_ill == NULL);
20652 					xmit_ill = dst_ipif->ipif_ill;
20653 					mutex_enter(&xmit_ill->ill_lock);
20654 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20655 						mutex_exit(&xmit_ill->ill_lock);
20656 						xmit_ill = NULL;
20657 						ipif_refrele(dst_ipif);
20658 						ip1dbg(("ip_wput: no route for"
20659 						    " dst using"
20660 						    " SO_DONTROUTE\n"));
20661 						BUMP_MIB(&ip_mib,
20662 						    ipOutNoRoutes);
20663 						mp->b_prev = mp->b_next = NULL;
20664 						if (first_mp == NULL)
20665 							first_mp = mp;
20666 						goto drop_pkt;
20667 					}
20668 					ill_refhold_locked(xmit_ill);
20669 					mutex_exit(&xmit_ill->ill_lock);
20670 					ipif_refrele(dst_ipif);
20671 				}
20672 			}
20673 
20674 		}
20675 		/*
20676 		 * If we are bound to IPIF_NOFAILOVER address, look for
20677 		 * an IRE_CACHE matching the ill.
20678 		 */
20679 send_from_ill:
20680 		if (attach_ill != NULL) {
20681 			ipif_t	*attach_ipif;
20682 
20683 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20684 
20685 			/*
20686 			 * Check if we need an ire that will not be
20687 			 * looked up by anybody else i.e. HIDDEN.
20688 			 */
20689 			if (ill_is_probeonly(attach_ill)) {
20690 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20691 			}
20692 
20693 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20694 			if (attach_ipif == NULL) {
20695 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20696 				goto drop_pkt;
20697 			}
20698 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20699 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20700 			ipif_refrele(attach_ipif);
20701 		} else if (xmit_ill != NULL || (connp != NULL &&
20702 			    connp->conn_xmit_if_ill != NULL)) {
20703 			/*
20704 			 * Mark this packet as originated locally
20705 			 */
20706 			mp->b_prev = mp->b_next = NULL;
20707 			/*
20708 			 * xmit_ill could be NULL if SO_DONTROUTE
20709 			 * is also set.
20710 			 */
20711 			if (xmit_ill == NULL) {
20712 				xmit_ill = conn_get_held_ill(connp,
20713 				    &connp->conn_xmit_if_ill, &err);
20714 				if (err == ILL_LOOKUP_FAILED) {
20715 					if (need_decref)
20716 						CONN_DEC_REF(connp);
20717 					freemsg(first_mp);
20718 					return;
20719 				}
20720 				if (xmit_ill == NULL) {
20721 					if (connp->conn_dontroute)
20722 						goto dontroute;
20723 					goto send_from_ill;
20724 				}
20725 			}
20726 			/*
20727 			 * could be SO_DONTROUTE case also.
20728 			 * check at least one interface is UP as
20729 			 * spcified by this ILL, and then call
20730 			 * ip_newroute_ipif()
20731 			 */
20732 			if (xmit_ill->ill_ipif_up_count > 0) {
20733 				ipif_t *ipif;
20734 
20735 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20736 				if (ipif != NULL) {
20737 					ip_newroute_ipif(q, first_mp, ipif,
20738 					    dst, connp, 0, zoneid);
20739 					ipif_refrele(ipif);
20740 					ip1dbg(("ip_wput: ip_unicast_if\n"));
20741 				}
20742 			} else {
20743 				freemsg(first_mp);
20744 			}
20745 			ill_refrele(xmit_ill);
20746 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20747 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
20748 			if (need_decref)
20749 				CONN_DEC_REF(connp);
20750 			return;
20751 		} else if (ip_nexthop || (connp != NULL &&
20752 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
20753 			if (!ip_nexthop) {
20754 				ip_nexthop = B_TRUE;
20755 				nexthop_addr = connp->conn_nexthop_v4;
20756 			}
20757 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
20758 			    MATCH_IRE_GW;
20759 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
20760 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
20761 		} else {
20762 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20763 		}
20764 		if (!ire) {
20765 			/*
20766 			 * Make sure we don't load spread if this
20767 			 * is IPIF_NOFAILOVER case.
20768 			 */
20769 			if ((attach_ill != NULL) ||
20770 			    (ip_nexthop && !ignore_nexthop)) {
20771 				if (mctl_present) {
20772 					io = (ipsec_out_t *)first_mp->b_rptr;
20773 					ASSERT(first_mp->b_datap->db_type ==
20774 					    M_CTL);
20775 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
20776 				} else {
20777 					ASSERT(mp == first_mp);
20778 					first_mp = allocb(
20779 					    sizeof (ipsec_info_t), BPRI_HI);
20780 					if (first_mp == NULL) {
20781 						first_mp = mp;
20782 						goto drop_pkt;
20783 					}
20784 					first_mp->b_datap->db_type = M_CTL;
20785 					first_mp->b_wptr +=
20786 					    sizeof (ipsec_info_t);
20787 					/* ipsec_out_secure is B_FALSE now */
20788 					bzero(first_mp->b_rptr,
20789 					    sizeof (ipsec_info_t));
20790 					io = (ipsec_out_t *)first_mp->b_rptr;
20791 					io->ipsec_out_type = IPSEC_OUT;
20792 					io->ipsec_out_len =
20793 					    sizeof (ipsec_out_t);
20794 					io->ipsec_out_use_global_policy =
20795 					    B_TRUE;
20796 					first_mp->b_cont = mp;
20797 					mctl_present = B_TRUE;
20798 				}
20799 				if (attach_ill != NULL) {
20800 					io->ipsec_out_ill_index = attach_ill->
20801 					    ill_phyint->phyint_ifindex;
20802 					io->ipsec_out_attach_if = B_TRUE;
20803 				} else {
20804 					io->ipsec_out_ip_nexthop = ip_nexthop;
20805 					io->ipsec_out_nexthop_addr =
20806 					    nexthop_addr;
20807 				}
20808 			}
20809 noirefound:
20810 			/*
20811 			 * Mark this packet as having originated on
20812 			 * this machine.  This will be noted in
20813 			 * ire_add_then_send, which needs to know
20814 			 * whether to run it back through ip_wput or
20815 			 * ip_rput following successful resolution.
20816 			 */
20817 			mp->b_prev = NULL;
20818 			mp->b_next = NULL;
20819 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid);
20820 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20821 			    "ip_wput_end: q %p (%S)", q, "newroute");
20822 			if (attach_ill != NULL)
20823 				ill_refrele(attach_ill);
20824 			if (xmit_ill != NULL)
20825 				ill_refrele(xmit_ill);
20826 			if (need_decref)
20827 				CONN_DEC_REF(connp);
20828 			return;
20829 		}
20830 	}
20831 
20832 	/* We now know where we are going with it. */
20833 
20834 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20835 	    "ip_wput_end: q %p (%S)", q, "end");
20836 
20837 	/*
20838 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20839 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
20840 	 */
20841 	if (ire->ire_flags & RTF_MULTIRT) {
20842 		/*
20843 		 * Force the TTL of multirouted packets if required.
20844 		 * The TTL of such packets is bounded by the
20845 		 * ip_multirt_ttl ndd variable.
20846 		 */
20847 		if ((ip_multirt_ttl > 0) &&
20848 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20849 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20850 			    "(was %d), dst 0x%08x\n",
20851 			    ip_multirt_ttl, ipha->ipha_ttl,
20852 			    ntohl(ire->ire_addr)));
20853 			ipha->ipha_ttl = ip_multirt_ttl;
20854 		}
20855 		/*
20856 		 * At this point, we check to see if there are any pending
20857 		 * unresolved routes. ire_multirt_resolvable()
20858 		 * checks in O(n) that all IRE_OFFSUBNET ire
20859 		 * entries for the packet's destination and
20860 		 * flagged RTF_MULTIRT are currently resolved.
20861 		 * If some remain unresolved, we make a copy
20862 		 * of the current message. It will be used
20863 		 * to initiate additional route resolutions.
20864 		 */
20865 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20866 		    MBLK_GETLABEL(first_mp));
20867 		ip2dbg(("ip_wput[noirefound]: ire %p, "
20868 		    "multirt_need_resolve %d, first_mp %p\n",
20869 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20870 		if (multirt_need_resolve) {
20871 			copy_mp = copymsg(first_mp);
20872 			if (copy_mp != NULL) {
20873 				MULTIRT_DEBUG_TAG(copy_mp);
20874 			}
20875 		}
20876 	}
20877 
20878 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20879 	/*
20880 	 * Try to resolve another multiroute if
20881 	 * ire_multirt_resolvable() deemed it necessary.
20882 	 * At this point, we need to distinguish
20883 	 * multicasts from other packets. For multicasts,
20884 	 * we call ip_newroute_ipif() and request that both
20885 	 * multirouting and setsrc flags are checked.
20886 	 */
20887 	if (copy_mp != NULL) {
20888 		if (CLASSD(dst)) {
20889 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
20890 			if (ipif) {
20891 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
20892 				    RTF_SETSRC | RTF_MULTIRT, zoneid);
20893 				ipif_refrele(ipif);
20894 			} else {
20895 				MULTIRT_DEBUG_UNTAG(copy_mp);
20896 				freemsg(copy_mp);
20897 				copy_mp = NULL;
20898 			}
20899 		} else {
20900 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20901 		}
20902 	}
20903 	if (attach_ill != NULL)
20904 		ill_refrele(attach_ill);
20905 	if (xmit_ill != NULL)
20906 		ill_refrele(xmit_ill);
20907 	if (need_decref)
20908 		CONN_DEC_REF(connp);
20909 	return;
20910 
20911 icmp_parameter_problem:
20912 	/* could not have originated externally */
20913 	ASSERT(mp->b_prev == NULL);
20914 	if (ip_hdr_complete(ipha, zoneid) == 0) {
20915 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
20916 		/* it's the IP header length that's in trouble */
20917 		icmp_param_problem(q, first_mp, 0, zoneid);
20918 		first_mp = NULL;
20919 	}
20920 
20921 drop_pkt:
20922 	ip1dbg(("ip_wput: dropped packet\n"));
20923 	if (ire != NULL)
20924 		ire_refrele(ire);
20925 	if (need_decref)
20926 		CONN_DEC_REF(connp);
20927 	freemsg(first_mp);
20928 	if (attach_ill != NULL)
20929 		ill_refrele(attach_ill);
20930 	if (xmit_ill != NULL)
20931 		ill_refrele(xmit_ill);
20932 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20933 	    "ip_wput_end: q %p (%S)", q, "droppkt");
20934 }
20935 
20936 /*
20937  * If this is a conn_t queue, then we pass in the conn. This includes the
20938  * zoneid.
20939  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
20940  * in which case we use the global zoneid since those are all part of
20941  * the global zone.
20942  */
20943 void
20944 ip_wput(queue_t *q, mblk_t *mp)
20945 {
20946 	if (CONN_Q(q))
20947 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20948 	else
20949 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
20950 }
20951 
20952 /*
20953  *
20954  * The following rules must be observed when accessing any ipif or ill
20955  * that has been cached in the conn. Typically conn_nofailover_ill,
20956  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20957  *
20958  * Access: The ipif or ill pointed to from the conn can be accessed under
20959  * the protection of the conn_lock or after it has been refheld under the
20960  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20961  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20962  * The reason for this is that a concurrent unplumb could actually be
20963  * cleaning up these cached pointers by walking the conns and might have
20964  * finished cleaning up the conn in question. The macros check that an
20965  * unplumb has not yet started on the ipif or ill.
20966  *
20967  * Caching: An ipif or ill pointer may be cached in the conn only after
20968  * making sure that an unplumb has not started. So the caching is done
20969  * while holding both the conn_lock and the ill_lock and after using the
20970  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20971  * flag before starting the cleanup of conns.
20972  *
20973  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20974  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20975  * or a reference to the ipif or a reference to an ire that references the
20976  * ipif. An ipif does not change its ill except for failover/failback. Since
20977  * failover/failback happens only after bringing down the ipif and making sure
20978  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20979  * the above holds.
20980  */
20981 ipif_t *
20982 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20983 {
20984 	ipif_t	*ipif;
20985 	ill_t	*ill;
20986 
20987 	*err = 0;
20988 	rw_enter(&ill_g_lock, RW_READER);
20989 	mutex_enter(&connp->conn_lock);
20990 	ipif = *ipifp;
20991 	if (ipif != NULL) {
20992 		ill = ipif->ipif_ill;
20993 		mutex_enter(&ill->ill_lock);
20994 		if (IPIF_CAN_LOOKUP(ipif)) {
20995 			ipif_refhold_locked(ipif);
20996 			mutex_exit(&ill->ill_lock);
20997 			mutex_exit(&connp->conn_lock);
20998 			rw_exit(&ill_g_lock);
20999 			return (ipif);
21000 		} else {
21001 			*err = IPIF_LOOKUP_FAILED;
21002 		}
21003 		mutex_exit(&ill->ill_lock);
21004 	}
21005 	mutex_exit(&connp->conn_lock);
21006 	rw_exit(&ill_g_lock);
21007 	return (NULL);
21008 }
21009 
21010 ill_t *
21011 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21012 {
21013 	ill_t	*ill;
21014 
21015 	*err = 0;
21016 	mutex_enter(&connp->conn_lock);
21017 	ill = *illp;
21018 	if (ill != NULL) {
21019 		mutex_enter(&ill->ill_lock);
21020 		if (ILL_CAN_LOOKUP(ill)) {
21021 			ill_refhold_locked(ill);
21022 			mutex_exit(&ill->ill_lock);
21023 			mutex_exit(&connp->conn_lock);
21024 			return (ill);
21025 		} else {
21026 			*err = ILL_LOOKUP_FAILED;
21027 		}
21028 		mutex_exit(&ill->ill_lock);
21029 	}
21030 	mutex_exit(&connp->conn_lock);
21031 	return (NULL);
21032 }
21033 
21034 static int
21035 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21036 {
21037 	ill_t	*ill;
21038 
21039 	ill = ipif->ipif_ill;
21040 	mutex_enter(&connp->conn_lock);
21041 	mutex_enter(&ill->ill_lock);
21042 	if (IPIF_CAN_LOOKUP(ipif)) {
21043 		*ipifp = ipif;
21044 		mutex_exit(&ill->ill_lock);
21045 		mutex_exit(&connp->conn_lock);
21046 		return (0);
21047 	}
21048 	mutex_exit(&ill->ill_lock);
21049 	mutex_exit(&connp->conn_lock);
21050 	return (IPIF_LOOKUP_FAILED);
21051 }
21052 
21053 /*
21054  * This is called if the outbound datagram needs fragmentation.
21055  *
21056  * NOTE : This function does not ire_refrele the ire argument passed in.
21057  */
21058 static void
21059 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid)
21060 {
21061 	ipha_t		*ipha;
21062 	mblk_t		*mp;
21063 	uint32_t	v_hlen_tos_len;
21064 	uint32_t	max_frag;
21065 	uint32_t	frag_flag;
21066 	boolean_t	dont_use;
21067 
21068 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21069 		mp = ipsec_mp->b_cont;
21070 	} else {
21071 		mp = ipsec_mp;
21072 	}
21073 
21074 	ipha = (ipha_t *)mp->b_rptr;
21075 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21076 
21077 #ifdef	_BIG_ENDIAN
21078 #define	V_HLEN	(v_hlen_tos_len >> 24)
21079 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21080 #else
21081 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21082 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21083 #endif
21084 
21085 #ifndef SPEED_BEFORE_SAFETY
21086 	/*
21087 	 * Check that ipha_length is consistent with
21088 	 * the mblk length
21089 	 */
21090 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21091 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21092 		    LENGTH, msgdsize(mp)));
21093 		freemsg(ipsec_mp);
21094 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21095 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21096 		    "packet length mismatch");
21097 		return;
21098 	}
21099 #endif
21100 	/*
21101 	 * Don't use frag_flag if pre-built packet or source
21102 	 * routed or if multicast (since multicast packets do not solicit
21103 	 * ICMP "packet too big" messages). Get the values of
21104 	 * max_frag and frag_flag atomically by acquiring the
21105 	 * ire_lock.
21106 	 */
21107 	mutex_enter(&ire->ire_lock);
21108 	max_frag = ire->ire_max_frag;
21109 	frag_flag = ire->ire_frag_flag;
21110 	mutex_exit(&ire->ire_lock);
21111 
21112 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21113 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21114 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21115 
21116 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21117 	    (dont_use ? 0 : frag_flag), zoneid);
21118 }
21119 
21120 /*
21121  * Used for deciding the MSS size for the upper layer. Thus
21122  * we need to check the outbound policy values in the conn.
21123  */
21124 int
21125 conn_ipsec_length(conn_t *connp)
21126 {
21127 	ipsec_latch_t *ipl;
21128 
21129 	ipl = connp->conn_latch;
21130 	if (ipl == NULL)
21131 		return (0);
21132 
21133 	if (ipl->ipl_out_policy == NULL)
21134 		return (0);
21135 
21136 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21137 }
21138 
21139 /*
21140  * Returns an estimate of the IPSEC headers size. This is used if
21141  * we don't want to call into IPSEC to get the exact size.
21142  */
21143 int
21144 ipsec_out_extra_length(mblk_t *ipsec_mp)
21145 {
21146 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21147 	ipsec_action_t *a;
21148 
21149 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21150 	if (!io->ipsec_out_secure)
21151 		return (0);
21152 
21153 	a = io->ipsec_out_act;
21154 
21155 	if (a == NULL) {
21156 		ASSERT(io->ipsec_out_policy != NULL);
21157 		a = io->ipsec_out_policy->ipsp_act;
21158 	}
21159 	ASSERT(a != NULL);
21160 
21161 	return (a->ipa_ovhd);
21162 }
21163 
21164 /*
21165  * Returns an estimate of the IPSEC headers size. This is used if
21166  * we don't want to call into IPSEC to get the exact size.
21167  */
21168 int
21169 ipsec_in_extra_length(mblk_t *ipsec_mp)
21170 {
21171 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21172 	ipsec_action_t *a;
21173 
21174 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21175 
21176 	a = ii->ipsec_in_action;
21177 	return (a == NULL ? 0 : a->ipa_ovhd);
21178 }
21179 
21180 /*
21181  * If there are any source route options, return the true final
21182  * destination. Otherwise, return the destination.
21183  */
21184 ipaddr_t
21185 ip_get_dst(ipha_t *ipha)
21186 {
21187 	ipoptp_t	opts;
21188 	uchar_t		*opt;
21189 	uint8_t		optval;
21190 	uint8_t		optlen;
21191 	ipaddr_t	dst;
21192 	uint32_t off;
21193 
21194 	dst = ipha->ipha_dst;
21195 
21196 	if (IS_SIMPLE_IPH(ipha))
21197 		return (dst);
21198 
21199 	for (optval = ipoptp_first(&opts, ipha);
21200 	    optval != IPOPT_EOL;
21201 	    optval = ipoptp_next(&opts)) {
21202 		opt = opts.ipoptp_cur;
21203 		optlen = opts.ipoptp_len;
21204 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21205 		switch (optval) {
21206 		case IPOPT_SSRR:
21207 		case IPOPT_LSRR:
21208 			off = opt[IPOPT_OFFSET];
21209 			/*
21210 			 * If one of the conditions is true, it means
21211 			 * end of options and dst already has the right
21212 			 * value.
21213 			 */
21214 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21215 				off = optlen - IP_ADDR_LEN;
21216 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21217 			}
21218 			return (dst);
21219 		default:
21220 			break;
21221 		}
21222 	}
21223 
21224 	return (dst);
21225 }
21226 
21227 mblk_t *
21228 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21229     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21230 {
21231 	ipsec_out_t	*io;
21232 	mblk_t		*first_mp;
21233 	boolean_t policy_present;
21234 
21235 	first_mp = mp;
21236 	if (mp->b_datap->db_type == M_CTL) {
21237 		io = (ipsec_out_t *)first_mp->b_rptr;
21238 		/*
21239 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21240 		 *
21241 		 * 1) There is per-socket policy (including cached global
21242 		 *    policy) or a policy on the IP-in-IP tunnel.
21243 		 * 2) There is no per-socket policy, but it is
21244 		 *    a multicast packet that needs to go out
21245 		 *    on a specific interface. This is the case
21246 		 *    where (ip_wput and ip_wput_multicast) attaches
21247 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21248 		 *
21249 		 * In case (2) we check with global policy to
21250 		 * see if there is a match and set the ill_index
21251 		 * appropriately so that we can lookup the ire
21252 		 * properly in ip_wput_ipsec_out.
21253 		 */
21254 
21255 		/*
21256 		 * ipsec_out_use_global_policy is set to B_FALSE
21257 		 * in ipsec_in_to_out(). Refer to that function for
21258 		 * details.
21259 		 */
21260 		if ((io->ipsec_out_latch == NULL) &&
21261 		    (io->ipsec_out_use_global_policy)) {
21262 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21263 				    ire, connp, unspec_src, zoneid));
21264 		}
21265 		if (!io->ipsec_out_secure) {
21266 			/*
21267 			 * If this is not a secure packet, drop
21268 			 * the IPSEC_OUT mp and treat it as a clear
21269 			 * packet. This happens when we are sending
21270 			 * a ICMP reply back to a clear packet. See
21271 			 * ipsec_in_to_out() for details.
21272 			 */
21273 			mp = first_mp->b_cont;
21274 			freeb(first_mp);
21275 		}
21276 		return (mp);
21277 	}
21278 	/*
21279 	 * See whether we need to attach a global policy here. We
21280 	 * don't depend on the conn (as it could be null) for deciding
21281 	 * what policy this datagram should go through because it
21282 	 * should have happened in ip_wput if there was some
21283 	 * policy. This normally happens for connections which are not
21284 	 * fully bound preventing us from caching policies in
21285 	 * ip_bind. Packets coming from the TCP listener/global queue
21286 	 * - which are non-hard_bound - could also be affected by
21287 	 * applying policy here.
21288 	 *
21289 	 * If this packet is coming from tcp global queue or listener,
21290 	 * we will be applying policy here.  This may not be *right*
21291 	 * if these packets are coming from the detached connection as
21292 	 * it could have gone in clear before. This happens only if a
21293 	 * TCP connection started when there is no policy and somebody
21294 	 * added policy before it became detached. Thus packets of the
21295 	 * detached connection could go out secure and the other end
21296 	 * would drop it because it will be expecting in clear. The
21297 	 * converse is not true i.e if somebody starts a TCP
21298 	 * connection and deletes the policy, all the packets will
21299 	 * still go out with the policy that existed before deleting
21300 	 * because ip_unbind sends up policy information which is used
21301 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21302 	 * TCP to attach a dummy IPSEC_OUT and set
21303 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21304 	 * affect performance for normal cases, we are not doing it.
21305 	 * Thus, set policy before starting any TCP connections.
21306 	 *
21307 	 * NOTE - We might apply policy even for a hard bound connection
21308 	 * - for which we cached policy in ip_bind - if somebody added
21309 	 * global policy after we inherited the policy in ip_bind.
21310 	 * This means that the packets that were going out in clear
21311 	 * previously would start going secure and hence get dropped
21312 	 * on the other side. To fix this, TCP attaches a dummy
21313 	 * ipsec_out and make sure that we don't apply global policy.
21314 	 */
21315 	if (ipha != NULL)
21316 		policy_present = ipsec_outbound_v4_policy_present;
21317 	else
21318 		policy_present = ipsec_outbound_v6_policy_present;
21319 	if (!policy_present)
21320 		return (mp);
21321 
21322 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21323 		    zoneid));
21324 }
21325 
21326 ire_t *
21327 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21328 {
21329 	ipaddr_t addr;
21330 	ire_t *save_ire;
21331 	irb_t *irb;
21332 	ill_group_t *illgrp;
21333 	int	err;
21334 
21335 	save_ire = ire;
21336 	addr = ire->ire_addr;
21337 
21338 	ASSERT(ire->ire_type == IRE_BROADCAST);
21339 
21340 	illgrp = connp->conn_outgoing_ill->ill_group;
21341 	if (illgrp == NULL) {
21342 		*conn_outgoing_ill = conn_get_held_ill(connp,
21343 		    &connp->conn_outgoing_ill, &err);
21344 		if (err == ILL_LOOKUP_FAILED) {
21345 			ire_refrele(save_ire);
21346 			return (NULL);
21347 		}
21348 		return (save_ire);
21349 	}
21350 	/*
21351 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21352 	 * If it is part of the group, we need to send on the ire
21353 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21354 	 * to this group. This is okay as IP_BOUND_IF really means
21355 	 * any ill in the group. We depend on the fact that the
21356 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21357 	 * if such an ire exists. This is possible only if you have
21358 	 * at least one ill in the group that has not failed.
21359 	 *
21360 	 * First get to the ire that matches the address and group.
21361 	 *
21362 	 * We don't look for an ire with a matching zoneid because a given zone
21363 	 * won't always have broadcast ires on all ills in the group.
21364 	 */
21365 	irb = ire->ire_bucket;
21366 	rw_enter(&irb->irb_lock, RW_READER);
21367 	if (ire->ire_marks & IRE_MARK_NORECV) {
21368 		/*
21369 		 * If the current zone only has an ire broadcast for this
21370 		 * address marked NORECV, the ire we want is ahead in the
21371 		 * bucket, so we look it up deliberately ignoring the zoneid.
21372 		 */
21373 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21374 			if (ire->ire_addr != addr)
21375 				continue;
21376 			/* skip over deleted ires */
21377 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21378 				continue;
21379 		}
21380 	}
21381 	while (ire != NULL) {
21382 		/*
21383 		 * If a new interface is coming up, we could end up
21384 		 * seeing the loopback ire and the non-loopback ire
21385 		 * may not have been added yet. So check for ire_stq
21386 		 */
21387 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21388 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21389 			break;
21390 		}
21391 		ire = ire->ire_next;
21392 	}
21393 	if (ire != NULL && ire->ire_addr == addr &&
21394 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21395 		IRE_REFHOLD(ire);
21396 		rw_exit(&irb->irb_lock);
21397 		ire_refrele(save_ire);
21398 		*conn_outgoing_ill = ire_to_ill(ire);
21399 		/*
21400 		 * Refhold the ill to make the conn_outgoing_ill
21401 		 * independent of the ire. ip_wput_ire goes in a loop
21402 		 * and may refrele the ire. Since we have an ire at this
21403 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21404 		 */
21405 		ill_refhold(*conn_outgoing_ill);
21406 		return (ire);
21407 	}
21408 	rw_exit(&irb->irb_lock);
21409 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21410 	/*
21411 	 * If we can't find a suitable ire, return the original ire.
21412 	 */
21413 	return (save_ire);
21414 }
21415 
21416 /*
21417  * This function does the ire_refrele of the ire passed in as the
21418  * argument. As this function looks up more ires i.e broadcast ires,
21419  * it needs to REFRELE them. Currently, for simplicity we don't
21420  * differentiate the one passed in and looked up here. We always
21421  * REFRELE.
21422  * IPQoS Notes:
21423  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21424  * IPSec packets are done in ipsec_out_process.
21425  *
21426  */
21427 void
21428 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21429     zoneid_t zoneid)
21430 {
21431 	ipha_t		*ipha;
21432 #define	rptr	((uchar_t *)ipha)
21433 	queue_t		*stq;
21434 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21435 	uint32_t	v_hlen_tos_len;
21436 	uint32_t	ttl_protocol;
21437 	ipaddr_t	src;
21438 	ipaddr_t	dst;
21439 	uint32_t	cksum;
21440 	ipaddr_t	orig_src;
21441 	ire_t		*ire1;
21442 	mblk_t		*next_mp;
21443 	uint_t		hlen;
21444 	uint16_t	*up;
21445 	uint32_t	max_frag = ire->ire_max_frag;
21446 	ill_t		*ill = ire_to_ill(ire);
21447 	int		clusterwide;
21448 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21449 	int		ipsec_len;
21450 	mblk_t		*first_mp;
21451 	ipsec_out_t	*io;
21452 	boolean_t	conn_dontroute;		/* conn value for multicast */
21453 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21454 	boolean_t	multicast_forward;	/* Should we forward ? */
21455 	boolean_t	unspec_src;
21456 	ill_t		*conn_outgoing_ill = NULL;
21457 	ill_t		*ire_ill;
21458 	ill_t		*ire1_ill;
21459 	ill_t		*out_ill;
21460 	uint32_t 	ill_index = 0;
21461 	boolean_t	multirt_send = B_FALSE;
21462 	int		err;
21463 	ipxmit_state_t	pktxmit_state;
21464 
21465 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21466 	    "ip_wput_ire_start: q %p", q);
21467 
21468 	multicast_forward = B_FALSE;
21469 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21470 
21471 	if (ire->ire_flags & RTF_MULTIRT) {
21472 		/*
21473 		 * Multirouting case. The bucket where ire is stored
21474 		 * probably holds other RTF_MULTIRT flagged ire
21475 		 * to the destination. In this call to ip_wput_ire,
21476 		 * we attempt to send the packet through all
21477 		 * those ires. Thus, we first ensure that ire is the
21478 		 * first RTF_MULTIRT ire in the bucket,
21479 		 * before walking the ire list.
21480 		 */
21481 		ire_t *first_ire;
21482 		irb_t *irb = ire->ire_bucket;
21483 		ASSERT(irb != NULL);
21484 
21485 		/* Make sure we do not omit any multiroute ire. */
21486 		IRB_REFHOLD(irb);
21487 		for (first_ire = irb->irb_ire;
21488 		    first_ire != NULL;
21489 		    first_ire = first_ire->ire_next) {
21490 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21491 			    (first_ire->ire_addr == ire->ire_addr) &&
21492 			    !(first_ire->ire_marks &
21493 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21494 				break;
21495 		}
21496 
21497 		if ((first_ire != NULL) && (first_ire != ire)) {
21498 			IRE_REFHOLD(first_ire);
21499 			ire_refrele(ire);
21500 			ire = first_ire;
21501 			ill = ire_to_ill(ire);
21502 		}
21503 		IRB_REFRELE(irb);
21504 	}
21505 
21506 	/*
21507 	 * conn_outgoing_ill is used only in the broadcast loop.
21508 	 * for performance we don't grab the mutexs in the fastpath
21509 	 */
21510 	if ((connp != NULL) &&
21511 	    (connp->conn_xmit_if_ill == NULL) &&
21512 	    (ire->ire_type == IRE_BROADCAST) &&
21513 	    ((connp->conn_nofailover_ill != NULL) ||
21514 	    (connp->conn_outgoing_ill != NULL))) {
21515 		/*
21516 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21517 		 * option. So, see if this endpoint is bound to a
21518 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21519 		 * that if the interface is failed, we will still send
21520 		 * the packet on the same ill which is what we want.
21521 		 */
21522 		conn_outgoing_ill = conn_get_held_ill(connp,
21523 		    &connp->conn_nofailover_ill, &err);
21524 		if (err == ILL_LOOKUP_FAILED) {
21525 			ire_refrele(ire);
21526 			freemsg(mp);
21527 			return;
21528 		}
21529 		if (conn_outgoing_ill == NULL) {
21530 			/*
21531 			 * Choose a good ill in the group to send the
21532 			 * packets on.
21533 			 */
21534 			ire = conn_set_outgoing_ill(connp, ire,
21535 			    &conn_outgoing_ill);
21536 			if (ire == NULL) {
21537 				freemsg(mp);
21538 				return;
21539 			}
21540 		}
21541 	}
21542 
21543 	if (mp->b_datap->db_type != M_CTL) {
21544 		ipha = (ipha_t *)mp->b_rptr;
21545 	} else {
21546 		io = (ipsec_out_t *)mp->b_rptr;
21547 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21548 		ASSERT(zoneid == io->ipsec_out_zoneid);
21549 		ASSERT(zoneid != ALL_ZONES);
21550 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21551 		dst = ipha->ipha_dst;
21552 		/*
21553 		 * For the multicast case, ipsec_out carries conn_dontroute and
21554 		 * conn_multicast_loop as conn may not be available here. We
21555 		 * need this for multicast loopback and forwarding which is done
21556 		 * later in the code.
21557 		 */
21558 		if (CLASSD(dst)) {
21559 			conn_dontroute = io->ipsec_out_dontroute;
21560 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21561 			/*
21562 			 * If conn_dontroute is not set or conn_multicast_loop
21563 			 * is set, we need to do forwarding/loopback. For
21564 			 * datagrams from ip_wput_multicast, conn_dontroute is
21565 			 * set to B_TRUE and conn_multicast_loop is set to
21566 			 * B_FALSE so that we neither do forwarding nor
21567 			 * loopback.
21568 			 */
21569 			if (!conn_dontroute || conn_multicast_loop)
21570 				multicast_forward = B_TRUE;
21571 		}
21572 	}
21573 
21574 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21575 	    ire->ire_zoneid != ALL_ZONES) {
21576 		/*
21577 		 * When a zone sends a packet to another zone, we try to deliver
21578 		 * the packet under the same conditions as if the destination
21579 		 * was a real node on the network. To do so, we look for a
21580 		 * matching route in the forwarding table.
21581 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21582 		 * ip_newroute() does.
21583 		 * Note that IRE_LOCAL are special, since they are used
21584 		 * when the zoneid doesn't match in some cases. This means that
21585 		 * we need to handle ipha_src differently since ire_src_addr
21586 		 * belongs to the receiving zone instead of the sending zone.
21587 		 * When ip_restrict_interzone_loopback is set, then
21588 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
21589 		 * for loopback between zones when the logical "Ethernet" would
21590 		 * have looped them back.
21591 		 */
21592 		ire_t *src_ire;
21593 
21594 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21595 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21596 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
21597 		if (src_ire != NULL &&
21598 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
21599 		    (!ip_restrict_interzone_loopback ||
21600 		    ire_local_same_ill_group(ire, src_ire))) {
21601 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21602 				ipha->ipha_src = src_ire->ire_src_addr;
21603 			ire_refrele(src_ire);
21604 		} else {
21605 			ire_refrele(ire);
21606 			if (conn_outgoing_ill != NULL)
21607 				ill_refrele(conn_outgoing_ill);
21608 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
21609 			if (src_ire != NULL) {
21610 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21611 					ire_refrele(src_ire);
21612 					freemsg(mp);
21613 					return;
21614 				}
21615 				ire_refrele(src_ire);
21616 			}
21617 			if (ip_hdr_complete(ipha, zoneid)) {
21618 				/* Failed */
21619 				freemsg(mp);
21620 				return;
21621 			}
21622 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid);
21623 			return;
21624 		}
21625 	}
21626 
21627 	if (mp->b_datap->db_type == M_CTL ||
21628 	    ipsec_outbound_v4_policy_present) {
21629 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21630 		    unspec_src, zoneid);
21631 		if (mp == NULL) {
21632 			ire_refrele(ire);
21633 			if (conn_outgoing_ill != NULL)
21634 				ill_refrele(conn_outgoing_ill);
21635 			return;
21636 		}
21637 	}
21638 
21639 	first_mp = mp;
21640 	ipsec_len = 0;
21641 
21642 	if (first_mp->b_datap->db_type == M_CTL) {
21643 		io = (ipsec_out_t *)first_mp->b_rptr;
21644 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21645 		mp = first_mp->b_cont;
21646 		ipsec_len = ipsec_out_extra_length(first_mp);
21647 		ASSERT(ipsec_len >= 0);
21648 		/* We already picked up the zoneid from the M_CTL above */
21649 		ASSERT(zoneid == io->ipsec_out_zoneid);
21650 		ASSERT(zoneid != ALL_ZONES);
21651 
21652 		/*
21653 		 * Drop M_CTL here if IPsec processing is not needed.
21654 		 * (Non-IPsec use of M_CTL extracted any information it
21655 		 * needed above).
21656 		 */
21657 		if (ipsec_len == 0) {
21658 			freeb(first_mp);
21659 			first_mp = mp;
21660 		}
21661 	}
21662 
21663 	/*
21664 	 * Fast path for ip_wput_ire
21665 	 */
21666 
21667 	ipha = (ipha_t *)mp->b_rptr;
21668 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21669 	dst = ipha->ipha_dst;
21670 
21671 	/*
21672 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21673 	 * if the socket is a SOCK_RAW type. The transport checksum should
21674 	 * be provided in the pre-built packet, so we don't need to compute it.
21675 	 * Also, other application set flags, like DF, should not be altered.
21676 	 * Other transport MUST pass down zero.
21677 	 */
21678 	ip_hdr_included = ipha->ipha_ident;
21679 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21680 
21681 	if (CLASSD(dst)) {
21682 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
21683 		    ntohl(dst),
21684 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
21685 		    ntohl(ire->ire_addr)));
21686 	}
21687 
21688 /* Macros to extract header fields from data already in registers */
21689 #ifdef	_BIG_ENDIAN
21690 #define	V_HLEN	(v_hlen_tos_len >> 24)
21691 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21692 #define	PROTO	(ttl_protocol & 0xFF)
21693 #else
21694 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21695 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21696 #define	PROTO	(ttl_protocol >> 8)
21697 #endif
21698 
21699 
21700 	orig_src = src = ipha->ipha_src;
21701 	/* (The loop back to "another" is explained down below.) */
21702 another:;
21703 	/*
21704 	 * Assign an ident value for this packet.  We assign idents on
21705 	 * a per destination basis out of the IRE.  There could be
21706 	 * other threads targeting the same destination, so we have to
21707 	 * arrange for a atomic increment.  Note that we use a 32-bit
21708 	 * atomic add because it has better performance than its
21709 	 * 16-bit sibling.
21710 	 *
21711 	 * If running in cluster mode and if the source address
21712 	 * belongs to a replicated service then vector through
21713 	 * cl_inet_ipident vector to allocate ip identifier
21714 	 * NOTE: This is a contract private interface with the
21715 	 * clustering group.
21716 	 */
21717 	clusterwide = 0;
21718 	if (cl_inet_ipident) {
21719 		ASSERT(cl_inet_isclusterwide);
21720 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21721 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
21722 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
21723 			    AF_INET, (uint8_t *)(uintptr_t)src,
21724 			    (uint8_t *)(uintptr_t)dst);
21725 			clusterwide = 1;
21726 		}
21727 	}
21728 	if (!clusterwide) {
21729 		ipha->ipha_ident =
21730 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
21731 	}
21732 
21733 #ifndef _BIG_ENDIAN
21734 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21735 #endif
21736 
21737 	/*
21738 	 * Set source address unless sent on an ill or conn_unspec_src is set.
21739 	 * This is needed to obey conn_unspec_src when packets go through
21740 	 * ip_newroute + arp.
21741 	 * Assumes ip_newroute{,_multi} sets the source address as well.
21742 	 */
21743 	if (src == INADDR_ANY && !unspec_src) {
21744 		/*
21745 		 * Assign the appropriate source address from the IRE if none
21746 		 * was specified.
21747 		 */
21748 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
21749 
21750 		/*
21751 		 * With IP multipathing, broadcast packets are sent on the ire
21752 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
21753 		 * the group. However, this ire might not be in the same zone so
21754 		 * we can't always use its source address. We look for a
21755 		 * broadcast ire in the same group and in the right zone.
21756 		 */
21757 		if (ire->ire_type == IRE_BROADCAST &&
21758 		    ire->ire_zoneid != zoneid) {
21759 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
21760 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
21761 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
21762 			if (src_ire != NULL) {
21763 				src = src_ire->ire_src_addr;
21764 				ire_refrele(src_ire);
21765 			} else {
21766 				ire_refrele(ire);
21767 				if (conn_outgoing_ill != NULL)
21768 					ill_refrele(conn_outgoing_ill);
21769 				freemsg(first_mp);
21770 				BUMP_MIB(&ip_mib, ipOutDiscards);
21771 				return;
21772 			}
21773 		} else {
21774 			src = ire->ire_src_addr;
21775 		}
21776 
21777 		if (connp == NULL) {
21778 			ip1dbg(("ip_wput_ire: no connp and no src "
21779 			    "address for dst 0x%x, using src 0x%x\n",
21780 			    ntohl(dst),
21781 			    ntohl(src)));
21782 		}
21783 		ipha->ipha_src = src;
21784 	}
21785 	stq = ire->ire_stq;
21786 
21787 	/*
21788 	 * We only allow ire chains for broadcasts since there will
21789 	 * be multiple IRE_CACHE entries for the same multicast
21790 	 * address (one per ipif).
21791 	 */
21792 	next_mp = NULL;
21793 
21794 	/* broadcast packet */
21795 	if (ire->ire_type == IRE_BROADCAST)
21796 		goto broadcast;
21797 
21798 	/* loopback ? */
21799 	if (stq == NULL)
21800 		goto nullstq;
21801 
21802 	/* The ill_index for outbound ILL */
21803 	ill_index = Q_TO_INDEX(stq);
21804 
21805 	BUMP_MIB(&ip_mib, ipOutRequests);
21806 	ttl_protocol = ((uint16_t *)ipha)[4];
21807 
21808 	/* pseudo checksum (do it in parts for IP header checksum) */
21809 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21810 
21811 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
21812 		queue_t *dev_q = stq->q_next;
21813 
21814 		/* flow controlled */
21815 		if ((dev_q->q_next || dev_q->q_first) &&
21816 		    !canput(dev_q))
21817 			goto blocked;
21818 		if ((PROTO == IPPROTO_UDP) &&
21819 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21820 			hlen = (V_HLEN & 0xF) << 2;
21821 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21822 			if (*up != 0) {
21823 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
21824 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
21825 				/* Software checksum? */
21826 				if (DB_CKSUMFLAGS(mp) == 0) {
21827 					IP_STAT(ip_out_sw_cksum);
21828 					IP_STAT_UPDATE(
21829 					    ip_udp_out_sw_cksum_bytes,
21830 					    LENGTH - hlen);
21831 				}
21832 			}
21833 		}
21834 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
21835 		hlen = (V_HLEN & 0xF) << 2;
21836 		if (PROTO == IPPROTO_TCP) {
21837 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21838 			/*
21839 			 * The packet header is processed once and for all, even
21840 			 * in the multirouting case. We disable hardware
21841 			 * checksum if the packet is multirouted, as it will be
21842 			 * replicated via several interfaces, and not all of
21843 			 * them may have this capability.
21844 			 */
21845 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
21846 			    LENGTH, max_frag, ipsec_len, cksum);
21847 			/* Software checksum? */
21848 			if (DB_CKSUMFLAGS(mp) == 0) {
21849 				IP_STAT(ip_out_sw_cksum);
21850 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21851 				    LENGTH - hlen);
21852 			}
21853 		} else {
21854 			sctp_hdr_t	*sctph;
21855 
21856 			ASSERT(PROTO == IPPROTO_SCTP);
21857 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21858 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21859 			/*
21860 			 * Zero out the checksum field to ensure proper
21861 			 * checksum calculation.
21862 			 */
21863 			sctph->sh_chksum = 0;
21864 #ifdef	DEBUG
21865 			if (!skip_sctp_cksum)
21866 #endif
21867 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21868 		}
21869 	}
21870 
21871 	/*
21872 	 * If this is a multicast packet and originated from ip_wput
21873 	 * we need to do loopback and forwarding checks. If it comes
21874 	 * from ip_wput_multicast, we SHOULD not do this.
21875 	 */
21876 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
21877 
21878 	/* checksum */
21879 	cksum += ttl_protocol;
21880 
21881 	/* fragment the packet */
21882 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
21883 		goto fragmentit;
21884 	/*
21885 	 * Don't use frag_flag if packet is pre-built or source
21886 	 * routed or if multicast (since multicast packets do
21887 	 * not solicit ICMP "packet too big" messages).
21888 	 */
21889 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21890 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21891 	    !ip_source_route_included(ipha)) &&
21892 	    !CLASSD(ipha->ipha_dst))
21893 		ipha->ipha_fragment_offset_and_flags |=
21894 		    htons(ire->ire_frag_flag);
21895 
21896 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21897 		/* calculate IP header checksum */
21898 		cksum += ipha->ipha_ident;
21899 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
21900 		cksum += ipha->ipha_fragment_offset_and_flags;
21901 
21902 		/* IP options present */
21903 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21904 		if (hlen)
21905 			goto checksumoptions;
21906 
21907 		/* calculate hdr checksum */
21908 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21909 		cksum = ~(cksum + (cksum >> 16));
21910 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
21911 	}
21912 	if (ipsec_len != 0) {
21913 		/*
21914 		 * We will do the rest of the processing after
21915 		 * we come back from IPSEC in ip_wput_ipsec_out().
21916 		 */
21917 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
21918 
21919 		io = (ipsec_out_t *)first_mp->b_rptr;
21920 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
21921 				ill_phyint->phyint_ifindex;
21922 
21923 		ipsec_out_process(q, first_mp, ire, ill_index);
21924 		ire_refrele(ire);
21925 		if (conn_outgoing_ill != NULL)
21926 			ill_refrele(conn_outgoing_ill);
21927 		return;
21928 	}
21929 
21930 	/*
21931 	 * In most cases, the emission loop below is entered only
21932 	 * once. Only in the case where the ire holds the
21933 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
21934 	 * flagged ires in the bucket, and send the packet
21935 	 * through all crossed RTF_MULTIRT routes.
21936 	 */
21937 	if (ire->ire_flags & RTF_MULTIRT) {
21938 		multirt_send = B_TRUE;
21939 	}
21940 	do {
21941 		if (multirt_send) {
21942 			irb_t *irb;
21943 			/*
21944 			 * We are in a multiple send case, need to get
21945 			 * the next ire and make a duplicate of the packet.
21946 			 * ire1 holds here the next ire to process in the
21947 			 * bucket. If multirouting is expected,
21948 			 * any non-RTF_MULTIRT ire that has the
21949 			 * right destination address is ignored.
21950 			 */
21951 			irb = ire->ire_bucket;
21952 			ASSERT(irb != NULL);
21953 
21954 			IRB_REFHOLD(irb);
21955 			for (ire1 = ire->ire_next;
21956 			    ire1 != NULL;
21957 			    ire1 = ire1->ire_next) {
21958 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21959 					continue;
21960 				if (ire1->ire_addr != ire->ire_addr)
21961 					continue;
21962 				if (ire1->ire_marks &
21963 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21964 					continue;
21965 
21966 				/* Got one */
21967 				IRE_REFHOLD(ire1);
21968 				break;
21969 			}
21970 			IRB_REFRELE(irb);
21971 
21972 			if (ire1 != NULL) {
21973 				next_mp = copyb(mp);
21974 				if ((next_mp == NULL) ||
21975 				    ((mp->b_cont != NULL) &&
21976 				    ((next_mp->b_cont =
21977 				    dupmsg(mp->b_cont)) == NULL))) {
21978 					freemsg(next_mp);
21979 					next_mp = NULL;
21980 					ire_refrele(ire1);
21981 					ire1 = NULL;
21982 				}
21983 			}
21984 
21985 			/* Last multiroute ire; don't loop anymore. */
21986 			if (ire1 == NULL) {
21987 				multirt_send = B_FALSE;
21988 			}
21989 		}
21990 
21991 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
21992 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
21993 		    mblk_t *, mp);
21994 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
21995 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp);
21996 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21997 		if (mp == NULL)
21998 			goto release_ire_and_ill;
21999 
22000 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22001 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22002 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22003 		if ((pktxmit_state == SEND_FAILED) ||
22004 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22005 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22006 			    "- packet dropped\n"));
22007 release_ire_and_ill:
22008 			ire_refrele(ire);
22009 			if (next_mp != NULL) {
22010 				freemsg(next_mp);
22011 				ire_refrele(ire1);
22012 			}
22013 			if (conn_outgoing_ill != NULL)
22014 				ill_refrele(conn_outgoing_ill);
22015 			return;
22016 		}
22017 
22018 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22019 		    "ip_wput_ire_end: q %p (%S)",
22020 		    q, "last copy out");
22021 		IRE_REFRELE(ire);
22022 
22023 		if (multirt_send) {
22024 			ASSERT(ire1);
22025 			/*
22026 			 * Proceed with the next RTF_MULTIRT ire,
22027 			 * Also set up the send-to queue accordingly.
22028 			 */
22029 			ire = ire1;
22030 			ire1 = NULL;
22031 			stq = ire->ire_stq;
22032 			mp = next_mp;
22033 			next_mp = NULL;
22034 			ipha = (ipha_t *)mp->b_rptr;
22035 			ill_index = Q_TO_INDEX(stq);
22036 		}
22037 	} while (multirt_send);
22038 	if (conn_outgoing_ill != NULL)
22039 		ill_refrele(conn_outgoing_ill);
22040 	return;
22041 
22042 	/*
22043 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22044 	 */
22045 broadcast:
22046 	{
22047 		/*
22048 		 * Avoid broadcast storms by setting the ttl to 1
22049 		 * for broadcasts. This parameter can be set
22050 		 * via ndd, so make sure that for the SO_DONTROUTE
22051 		 * case that ipha_ttl is always set to 1.
22052 		 * In the event that we are replying to incoming
22053 		 * ICMP packets, conn could be NULL.
22054 		 */
22055 		if ((connp != NULL) && connp->conn_dontroute)
22056 			ipha->ipha_ttl = 1;
22057 		else
22058 			ipha->ipha_ttl = ip_broadcast_ttl;
22059 
22060 		/*
22061 		 * Note that we are not doing a IRB_REFHOLD here.
22062 		 * Actually we don't care if the list changes i.e
22063 		 * if somebody deletes an IRE from the list while
22064 		 * we drop the lock, the next time we come around
22065 		 * ire_next will be NULL and hence we won't send
22066 		 * out multiple copies which is fine.
22067 		 */
22068 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22069 		ire1 = ire->ire_next;
22070 		if (conn_outgoing_ill != NULL) {
22071 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22072 				ASSERT(ire1 == ire->ire_next);
22073 				if (ire1 != NULL && ire1->ire_addr == dst) {
22074 					ire_refrele(ire);
22075 					ire = ire1;
22076 					IRE_REFHOLD(ire);
22077 					ire1 = ire->ire_next;
22078 					continue;
22079 				}
22080 				rw_exit(&ire->ire_bucket->irb_lock);
22081 				/* Did not find a matching ill */
22082 				ip1dbg(("ip_wput_ire: broadcast with no "
22083 				    "matching IP_BOUND_IF ill %s\n",
22084 				    conn_outgoing_ill->ill_name));
22085 				freemsg(first_mp);
22086 				if (ire != NULL)
22087 					ire_refrele(ire);
22088 				ill_refrele(conn_outgoing_ill);
22089 				return;
22090 			}
22091 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22092 			/*
22093 			 * If the next IRE has the same address and is not one
22094 			 * of the two copies that we need to send, try to see
22095 			 * whether this copy should be sent at all. This
22096 			 * assumes that we insert loopbacks first and then
22097 			 * non-loopbacks. This is acheived by inserting the
22098 			 * loopback always before non-loopback.
22099 			 * This is used to send a single copy of a broadcast
22100 			 * packet out all physical interfaces that have an
22101 			 * matching IRE_BROADCAST while also looping
22102 			 * back one copy (to ip_wput_local) for each
22103 			 * matching physical interface. However, we avoid
22104 			 * sending packets out different logical that match by
22105 			 * having ipif_up/ipif_down supress duplicate
22106 			 * IRE_BROADCASTS.
22107 			 *
22108 			 * This feature is currently used to get broadcasts
22109 			 * sent to multiple interfaces, when the broadcast
22110 			 * address being used applies to multiple interfaces.
22111 			 * For example, a whole net broadcast will be
22112 			 * replicated on every connected subnet of
22113 			 * the target net.
22114 			 *
22115 			 * Each zone has its own set of IRE_BROADCASTs, so that
22116 			 * we're able to distribute inbound packets to multiple
22117 			 * zones who share a broadcast address. We avoid looping
22118 			 * back outbound packets in different zones but on the
22119 			 * same ill, as the application would see duplicates.
22120 			 *
22121 			 * If the interfaces are part of the same group,
22122 			 * we would want to send only one copy out for
22123 			 * whole group.
22124 			 *
22125 			 * This logic assumes that ire_add_v4() groups the
22126 			 * IRE_BROADCAST entries so that those with the same
22127 			 * ire_addr and ill_group are kept together.
22128 			 */
22129 			ire_ill = ire->ire_ipif->ipif_ill;
22130 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22131 				if (ire_ill->ill_group != NULL &&
22132 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22133 					/*
22134 					 * If the current zone only has an ire
22135 					 * broadcast for this address marked
22136 					 * NORECV, the ire we want is ahead in
22137 					 * the bucket, so we look it up
22138 					 * deliberately ignoring the zoneid.
22139 					 */
22140 					for (ire1 = ire->ire_bucket->irb_ire;
22141 					    ire1 != NULL;
22142 					    ire1 = ire1->ire_next) {
22143 						ire1_ill =
22144 						    ire1->ire_ipif->ipif_ill;
22145 						if (ire1->ire_addr != dst)
22146 							continue;
22147 						/* skip over the current ire */
22148 						if (ire1 == ire)
22149 							continue;
22150 						/* skip over deleted ires */
22151 						if (ire1->ire_marks &
22152 						    IRE_MARK_CONDEMNED)
22153 							continue;
22154 						/*
22155 						 * non-loopback ire in our
22156 						 * group: use it for the next
22157 						 * pass in the loop
22158 						 */
22159 						if (ire1->ire_stq != NULL &&
22160 						    ire1_ill->ill_group ==
22161 						    ire_ill->ill_group)
22162 							break;
22163 					}
22164 				}
22165 			} else {
22166 				while (ire1 != NULL && ire1->ire_addr == dst) {
22167 					ire1_ill = ire1->ire_ipif->ipif_ill;
22168 					/*
22169 					 * We can have two broadcast ires on the
22170 					 * same ill in different zones; here
22171 					 * we'll send a copy of the packet on
22172 					 * each ill and the fanout code will
22173 					 * call conn_wantpacket() to check that
22174 					 * the zone has the broadcast address
22175 					 * configured on the ill. If the two
22176 					 * ires are in the same group we only
22177 					 * send one copy up.
22178 					 */
22179 					if (ire1_ill != ire_ill &&
22180 					    (ire1_ill->ill_group == NULL ||
22181 					    ire_ill->ill_group == NULL ||
22182 					    ire1_ill->ill_group !=
22183 					    ire_ill->ill_group)) {
22184 						break;
22185 					}
22186 					ire1 = ire1->ire_next;
22187 				}
22188 			}
22189 		}
22190 		ASSERT(multirt_send == B_FALSE);
22191 		if (ire1 != NULL && ire1->ire_addr == dst) {
22192 			if ((ire->ire_flags & RTF_MULTIRT) &&
22193 			    (ire1->ire_flags & RTF_MULTIRT)) {
22194 				/*
22195 				 * We are in the multirouting case.
22196 				 * The message must be sent at least
22197 				 * on both ires. These ires have been
22198 				 * inserted AFTER the standard ones
22199 				 * in ip_rt_add(). There are thus no
22200 				 * other ire entries for the destination
22201 				 * address in the rest of the bucket
22202 				 * that do not have the RTF_MULTIRT
22203 				 * flag. We don't process a copy
22204 				 * of the message here. This will be
22205 				 * done in the final sending loop.
22206 				 */
22207 				multirt_send = B_TRUE;
22208 			} else {
22209 				next_mp = ip_copymsg(first_mp);
22210 				if (next_mp != NULL)
22211 					IRE_REFHOLD(ire1);
22212 			}
22213 		}
22214 		rw_exit(&ire->ire_bucket->irb_lock);
22215 	}
22216 
22217 	if (stq) {
22218 		/*
22219 		 * A non-NULL send-to queue means this packet is going
22220 		 * out of this machine.
22221 		 */
22222 
22223 		BUMP_MIB(&ip_mib, ipOutRequests);
22224 		ttl_protocol = ((uint16_t *)ipha)[4];
22225 		/*
22226 		 * We accumulate the pseudo header checksum in cksum.
22227 		 * This is pretty hairy code, so watch close.  One
22228 		 * thing to keep in mind is that UDP and TCP have
22229 		 * stored their respective datagram lengths in their
22230 		 * checksum fields.  This lines things up real nice.
22231 		 */
22232 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22233 		    (src >> 16) + (src & 0xFFFF);
22234 		/*
22235 		 * We assume the udp checksum field contains the
22236 		 * length, so to compute the pseudo header checksum,
22237 		 * all we need is the protocol number and src/dst.
22238 		 */
22239 		/* Provide the checksums for UDP and TCP. */
22240 		if ((PROTO == IPPROTO_TCP) &&
22241 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22242 			/* hlen gets the number of uchar_ts in the IP header */
22243 			hlen = (V_HLEN & 0xF) << 2;
22244 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22245 			IP_STAT(ip_out_sw_cksum);
22246 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22247 			    LENGTH - hlen);
22248 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22249 			if (*up == 0)
22250 				*up = 0xFFFF;
22251 		} else if (PROTO == IPPROTO_SCTP &&
22252 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22253 			sctp_hdr_t	*sctph;
22254 
22255 			hlen = (V_HLEN & 0xF) << 2;
22256 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22257 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22258 			sctph->sh_chksum = 0;
22259 #ifdef	DEBUG
22260 			if (!skip_sctp_cksum)
22261 #endif
22262 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22263 		} else {
22264 			queue_t *dev_q = stq->q_next;
22265 
22266 			if ((dev_q->q_next || dev_q->q_first) &&
22267 			    !canput(dev_q)) {
22268 			    blocked:
22269 				ipha->ipha_ident = ip_hdr_included;
22270 				/*
22271 				 * If we don't have a conn to apply
22272 				 * backpressure, free the message.
22273 				 * In the ire_send path, we don't know
22274 				 * the position to requeue the packet. Rather
22275 				 * than reorder packets, we just drop this
22276 				 * packet.
22277 				 */
22278 				if (ip_output_queue && connp != NULL &&
22279 				    caller != IRE_SEND) {
22280 					if (caller == IP_WSRV) {
22281 						connp->conn_did_putbq = 1;
22282 						(void) putbq(connp->conn_wq,
22283 						    first_mp);
22284 						conn_drain_insert(connp);
22285 						/*
22286 						 * This is the service thread,
22287 						 * and the queue is already
22288 						 * noenabled. The check for
22289 						 * canput and the putbq is not
22290 						 * atomic. So we need to check
22291 						 * again.
22292 						 */
22293 						if (canput(stq->q_next))
22294 							connp->conn_did_putbq
22295 							    = 0;
22296 						IP_STAT(ip_conn_flputbq);
22297 					} else {
22298 						/*
22299 						 * We are not the service proc.
22300 						 * ip_wsrv will be scheduled or
22301 						 * is already running.
22302 						 */
22303 						(void) putq(connp->conn_wq,
22304 						    first_mp);
22305 					}
22306 				} else {
22307 					BUMP_MIB(&ip_mib, ipOutDiscards);
22308 					freemsg(first_mp);
22309 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22310 					    "ip_wput_ire_end: q %p (%S)",
22311 					    q, "discard");
22312 				}
22313 				ire_refrele(ire);
22314 				if (next_mp) {
22315 					ire_refrele(ire1);
22316 					freemsg(next_mp);
22317 				}
22318 				if (conn_outgoing_ill != NULL)
22319 					ill_refrele(conn_outgoing_ill);
22320 				return;
22321 			}
22322 			if ((PROTO == IPPROTO_UDP) &&
22323 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22324 				/*
22325 				 * hlen gets the number of uchar_ts in the
22326 				 * IP header
22327 				 */
22328 				hlen = (V_HLEN & 0xF) << 2;
22329 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22330 				max_frag = ire->ire_max_frag;
22331 				if (*up != 0) {
22332 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22333 					    up, PROTO, hlen, LENGTH, max_frag,
22334 					    ipsec_len, cksum);
22335 					/* Software checksum? */
22336 					if (DB_CKSUMFLAGS(mp) == 0) {
22337 						IP_STAT(ip_out_sw_cksum);
22338 						IP_STAT_UPDATE(
22339 						    ip_udp_out_sw_cksum_bytes,
22340 						    LENGTH - hlen);
22341 					}
22342 				}
22343 			}
22344 		}
22345 		/*
22346 		 * Need to do this even when fragmenting. The local
22347 		 * loopback can be done without computing checksums
22348 		 * but forwarding out other interface must be done
22349 		 * after the IP checksum (and ULP checksums) have been
22350 		 * computed.
22351 		 *
22352 		 * NOTE : multicast_forward is set only if this packet
22353 		 * originated from ip_wput. For packets originating from
22354 		 * ip_wput_multicast, it is not set.
22355 		 */
22356 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22357 		    multi_loopback:
22358 			ip2dbg(("ip_wput: multicast, loop %d\n",
22359 			    conn_multicast_loop));
22360 
22361 			/*  Forget header checksum offload */
22362 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22363 
22364 			/*
22365 			 * Local loopback of multicasts?  Check the
22366 			 * ill.
22367 			 *
22368 			 * Note that the loopback function will not come
22369 			 * in through ip_rput - it will only do the
22370 			 * client fanout thus we need to do an mforward
22371 			 * as well.  The is different from the BSD
22372 			 * logic.
22373 			 */
22374 			if (ill != NULL) {
22375 				ilm_t	*ilm;
22376 
22377 				ILM_WALKER_HOLD(ill);
22378 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22379 				    ALL_ZONES);
22380 				ILM_WALKER_RELE(ill);
22381 				if (ilm != NULL) {
22382 					/*
22383 					 * Pass along the virtual output q.
22384 					 * ip_wput_local() will distribute the
22385 					 * packet to all the matching zones,
22386 					 * except the sending zone when
22387 					 * IP_MULTICAST_LOOP is false.
22388 					 */
22389 					ip_multicast_loopback(q, ill, first_mp,
22390 					    conn_multicast_loop ? 0 :
22391 					    IP_FF_NO_MCAST_LOOP, zoneid);
22392 				}
22393 			}
22394 			if (ipha->ipha_ttl == 0) {
22395 				/*
22396 				 * 0 => only to this host i.e. we are
22397 				 * done. We are also done if this was the
22398 				 * loopback interface since it is sufficient
22399 				 * to loopback one copy of a multicast packet.
22400 				 */
22401 				freemsg(first_mp);
22402 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22403 				    "ip_wput_ire_end: q %p (%S)",
22404 				    q, "loopback");
22405 				ire_refrele(ire);
22406 				if (conn_outgoing_ill != NULL)
22407 					ill_refrele(conn_outgoing_ill);
22408 				return;
22409 			}
22410 			/*
22411 			 * ILLF_MULTICAST is checked in ip_newroute
22412 			 * i.e. we don't need to check it here since
22413 			 * all IRE_CACHEs come from ip_newroute.
22414 			 * For multicast traffic, SO_DONTROUTE is interpreted
22415 			 * to mean only send the packet out the interface
22416 			 * (optionally specified with IP_MULTICAST_IF)
22417 			 * and do not forward it out additional interfaces.
22418 			 * RSVP and the rsvp daemon is an example of a
22419 			 * protocol and user level process that
22420 			 * handles it's own routing. Hence, it uses the
22421 			 * SO_DONTROUTE option to accomplish this.
22422 			 */
22423 
22424 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22425 				/* Unconditionally redo the checksum */
22426 				ipha->ipha_hdr_checksum = 0;
22427 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22428 
22429 				/*
22430 				 * If this needs to go out secure, we need
22431 				 * to wait till we finish the IPSEC
22432 				 * processing.
22433 				 */
22434 				if (ipsec_len == 0 &&
22435 				    ip_mforward(ill, ipha, mp)) {
22436 					freemsg(first_mp);
22437 					ip1dbg(("ip_wput: mforward failed\n"));
22438 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22439 					    "ip_wput_ire_end: q %p (%S)",
22440 					    q, "mforward failed");
22441 					ire_refrele(ire);
22442 					if (conn_outgoing_ill != NULL)
22443 						ill_refrele(conn_outgoing_ill);
22444 					return;
22445 				}
22446 			}
22447 		}
22448 		max_frag = ire->ire_max_frag;
22449 		cksum += ttl_protocol;
22450 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22451 			/* No fragmentation required for this one. */
22452 			/*
22453 			 * Don't use frag_flag if packet is pre-built or source
22454 			 * routed or if multicast (since multicast packets do
22455 			 * not solicit ICMP "packet too big" messages).
22456 			 */
22457 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22458 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22459 			    !ip_source_route_included(ipha)) &&
22460 			    !CLASSD(ipha->ipha_dst))
22461 				ipha->ipha_fragment_offset_and_flags |=
22462 				    htons(ire->ire_frag_flag);
22463 
22464 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22465 				/* Complete the IP header checksum. */
22466 				cksum += ipha->ipha_ident;
22467 				cksum += (v_hlen_tos_len >> 16)+
22468 				    (v_hlen_tos_len & 0xFFFF);
22469 				cksum += ipha->ipha_fragment_offset_and_flags;
22470 				hlen = (V_HLEN & 0xF) -
22471 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22472 				if (hlen) {
22473 				    checksumoptions:
22474 					/*
22475 					 * Account for the IP Options in the IP
22476 					 * header checksum.
22477 					 */
22478 					up = (uint16_t *)(rptr+
22479 					    IP_SIMPLE_HDR_LENGTH);
22480 					do {
22481 						cksum += up[0];
22482 						cksum += up[1];
22483 						up += 2;
22484 					} while (--hlen);
22485 				}
22486 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22487 				cksum = ~(cksum + (cksum >> 16));
22488 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22489 			}
22490 			if (ipsec_len != 0) {
22491 				ipsec_out_process(q, first_mp, ire, ill_index);
22492 				if (!next_mp) {
22493 					ire_refrele(ire);
22494 					if (conn_outgoing_ill != NULL)
22495 						ill_refrele(conn_outgoing_ill);
22496 					return;
22497 				}
22498 				goto next;
22499 			}
22500 
22501 			/*
22502 			 * multirt_send has already been handled
22503 			 * for broadcast, but not yet for multicast
22504 			 * or IP options.
22505 			 */
22506 			if (next_mp == NULL) {
22507 				if (ire->ire_flags & RTF_MULTIRT) {
22508 					multirt_send = B_TRUE;
22509 				}
22510 			}
22511 
22512 			/*
22513 			 * In most cases, the emission loop below is
22514 			 * entered only once. Only in the case where
22515 			 * the ire holds the RTF_MULTIRT flag, do we loop
22516 			 * to process all RTF_MULTIRT ires in the bucket,
22517 			 * and send the packet through all crossed
22518 			 * RTF_MULTIRT routes.
22519 			 */
22520 			do {
22521 				if (multirt_send) {
22522 					irb_t *irb;
22523 
22524 					irb = ire->ire_bucket;
22525 					ASSERT(irb != NULL);
22526 					/*
22527 					 * We are in a multiple send case,
22528 					 * need to get the next IRE and make
22529 					 * a duplicate of the packet.
22530 					 */
22531 					IRB_REFHOLD(irb);
22532 					for (ire1 = ire->ire_next;
22533 					    ire1 != NULL;
22534 					    ire1 = ire1->ire_next) {
22535 						if (!(ire1->ire_flags &
22536 						    RTF_MULTIRT))
22537 							continue;
22538 						if (ire1->ire_addr !=
22539 						    ire->ire_addr)
22540 							continue;
22541 						if (ire1->ire_marks &
22542 						    (IRE_MARK_CONDEMNED|
22543 							IRE_MARK_HIDDEN))
22544 							continue;
22545 
22546 						/* Got one */
22547 						IRE_REFHOLD(ire1);
22548 						break;
22549 					}
22550 					IRB_REFRELE(irb);
22551 
22552 					if (ire1 != NULL) {
22553 						next_mp = copyb(mp);
22554 						if ((next_mp == NULL) ||
22555 						    ((mp->b_cont != NULL) &&
22556 						    ((next_mp->b_cont =
22557 						    dupmsg(mp->b_cont))
22558 						    == NULL))) {
22559 							freemsg(next_mp);
22560 							next_mp = NULL;
22561 							ire_refrele(ire1);
22562 							ire1 = NULL;
22563 						}
22564 					}
22565 
22566 					/*
22567 					 * Last multiroute ire; don't loop
22568 					 * anymore. The emission is over
22569 					 * and next_mp is NULL.
22570 					 */
22571 					if (ire1 == NULL) {
22572 						multirt_send = B_FALSE;
22573 					}
22574 				}
22575 
22576 				out_ill = ire->ire_ipif->ipif_ill;
22577 				DTRACE_PROBE4(ip4__physical__out__start,
22578 				    ill_t *, NULL,
22579 				    ill_t *, out_ill,
22580 				    ipha_t *, ipha, mblk_t *, mp);
22581 				FW_HOOKS(ip4_physical_out_event,
22582 				    ipv4firewall_physical_out,
22583 				    NULL, out_ill, ipha, mp, mp);
22584 				DTRACE_PROBE1(ip4__physical__out__end,
22585 				    mblk_t *, mp);
22586 				if (mp == NULL)
22587 					goto release_ire_and_ill_2;
22588 
22589 				ASSERT(ipsec_len == 0);
22590 				mp->b_prev =
22591 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22592 				DTRACE_PROBE2(ip__xmit__2,
22593 				    mblk_t *, mp, ire_t *, ire);
22594 				pktxmit_state = ip_xmit_v4(mp, ire,
22595 				    NULL, B_TRUE);
22596 				if ((pktxmit_state == SEND_FAILED) ||
22597 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22598 release_ire_and_ill_2:
22599 					if (next_mp) {
22600 						freemsg(next_mp);
22601 						ire_refrele(ire1);
22602 					}
22603 					ire_refrele(ire);
22604 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22605 					    "ip_wput_ire_end: q %p (%S)",
22606 					    q, "discard MDATA");
22607 					if (conn_outgoing_ill != NULL)
22608 						ill_refrele(conn_outgoing_ill);
22609 					return;
22610 				}
22611 
22612 				if (multirt_send) {
22613 					/*
22614 					 * We are in a multiple send case,
22615 					 * need to re-enter the sending loop
22616 					 * using the next ire.
22617 					 */
22618 					ire_refrele(ire);
22619 					ire = ire1;
22620 					stq = ire->ire_stq;
22621 					mp = next_mp;
22622 					next_mp = NULL;
22623 					ipha = (ipha_t *)mp->b_rptr;
22624 					ill_index = Q_TO_INDEX(stq);
22625 				}
22626 			} while (multirt_send);
22627 
22628 			if (!next_mp) {
22629 				/*
22630 				 * Last copy going out (the ultra-common
22631 				 * case).  Note that we intentionally replicate
22632 				 * the putnext rather than calling it before
22633 				 * the next_mp check in hopes of a little
22634 				 * tail-call action out of the compiler.
22635 				 */
22636 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22637 				    "ip_wput_ire_end: q %p (%S)",
22638 				    q, "last copy out(1)");
22639 				ire_refrele(ire);
22640 				if (conn_outgoing_ill != NULL)
22641 					ill_refrele(conn_outgoing_ill);
22642 				return;
22643 			}
22644 			/* More copies going out below. */
22645 		} else {
22646 			int offset;
22647 		    fragmentit:
22648 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22649 			/*
22650 			 * If this would generate a icmp_frag_needed message,
22651 			 * we need to handle it before we do the IPSEC
22652 			 * processing. Otherwise, we need to strip the IPSEC
22653 			 * headers before we send up the message to the ULPs
22654 			 * which becomes messy and difficult.
22655 			 */
22656 			if (ipsec_len != 0) {
22657 				if ((max_frag < (unsigned int)(LENGTH +
22658 				    ipsec_len)) && (offset & IPH_DF)) {
22659 
22660 					BUMP_MIB(&ip_mib, ipFragFails);
22661 					ipha->ipha_hdr_checksum = 0;
22662 					ipha->ipha_hdr_checksum =
22663 					    (uint16_t)ip_csum_hdr(ipha);
22664 					icmp_frag_needed(ire->ire_stq, first_mp,
22665 					    max_frag, zoneid);
22666 					if (!next_mp) {
22667 						ire_refrele(ire);
22668 						if (conn_outgoing_ill != NULL) {
22669 							ill_refrele(
22670 							    conn_outgoing_ill);
22671 						}
22672 						return;
22673 					}
22674 				} else {
22675 					/*
22676 					 * This won't cause a icmp_frag_needed
22677 					 * message. to be gnerated. Send it on
22678 					 * the wire. Note that this could still
22679 					 * cause fragmentation and all we
22680 					 * do is the generation of the message
22681 					 * to the ULP if needed before IPSEC.
22682 					 */
22683 					if (!next_mp) {
22684 						ipsec_out_process(q, first_mp,
22685 						    ire, ill_index);
22686 						TRACE_2(TR_FAC_IP,
22687 						    TR_IP_WPUT_IRE_END,
22688 						    "ip_wput_ire_end: q %p "
22689 						    "(%S)", q,
22690 						    "last ipsec_out_process");
22691 						ire_refrele(ire);
22692 						if (conn_outgoing_ill != NULL) {
22693 							ill_refrele(
22694 							    conn_outgoing_ill);
22695 						}
22696 						return;
22697 					}
22698 					ipsec_out_process(q, first_mp,
22699 					    ire, ill_index);
22700 				}
22701 			} else {
22702 				/*
22703 				 * Initiate IPPF processing. For
22704 				 * fragmentable packets we finish
22705 				 * all QOS packet processing before
22706 				 * calling:
22707 				 * ip_wput_ire_fragmentit->ip_wput_frag
22708 				 */
22709 
22710 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22711 					ip_process(IPP_LOCAL_OUT, &mp,
22712 					    ill_index);
22713 					if (mp == NULL) {
22714 						BUMP_MIB(&ip_mib,
22715 						    ipOutDiscards);
22716 						if (next_mp != NULL) {
22717 							freemsg(next_mp);
22718 							ire_refrele(ire1);
22719 						}
22720 						ire_refrele(ire);
22721 						TRACE_2(TR_FAC_IP,
22722 						    TR_IP_WPUT_IRE_END,
22723 						    "ip_wput_ire: q %p (%S)",
22724 						    q, "discard MDATA");
22725 						if (conn_outgoing_ill != NULL) {
22726 							ill_refrele(
22727 							    conn_outgoing_ill);
22728 						}
22729 						return;
22730 					}
22731 				}
22732 				if (!next_mp) {
22733 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22734 					    "ip_wput_ire_end: q %p (%S)",
22735 					    q, "last fragmentation");
22736 					ip_wput_ire_fragmentit(mp, ire,
22737 					    zoneid);
22738 					ire_refrele(ire);
22739 					if (conn_outgoing_ill != NULL)
22740 						ill_refrele(conn_outgoing_ill);
22741 					return;
22742 				}
22743 				ip_wput_ire_fragmentit(mp, ire, zoneid);
22744 			}
22745 		}
22746 	} else {
22747 	    nullstq:
22748 		/* A NULL stq means the destination address is local. */
22749 		UPDATE_OB_PKT_COUNT(ire);
22750 		ire->ire_last_used_time = lbolt;
22751 		ASSERT(ire->ire_ipif != NULL);
22752 		if (!next_mp) {
22753 			/*
22754 			 * Is there an "in" and "out" for traffic local
22755 			 * to a host (loopback)?  The code in Solaris doesn't
22756 			 * explicitly draw a line in its code for in vs out,
22757 			 * so we've had to draw a line in the sand: ip_wput_ire
22758 			 * is considered to be the "output" side and
22759 			 * ip_wput_local to be the "input" side.
22760 			 */
22761 			out_ill = ire->ire_ipif->ipif_ill;
22762 
22763 			DTRACE_PROBE4(ip4__loopback__out__start,
22764 			    ill_t *, NULL, ill_t *, out_ill,
22765 			    ipha_t *, ipha, mblk_t *, first_mp);
22766 
22767 			FW_HOOKS(ip4_loopback_out_event,
22768 			    ipv4firewall_loopback_out,
22769 			    NULL, out_ill, ipha, first_mp, mp);
22770 
22771 			DTRACE_PROBE1(ip4__loopback__out_end,
22772 			    mblk_t *, first_mp);
22773 
22774 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22775 			    "ip_wput_ire_end: q %p (%S)",
22776 			    q, "local address");
22777 
22778 			if (first_mp != NULL)
22779 				ip_wput_local(q, out_ill, ipha,
22780 				    first_mp, ire, 0, ire->ire_zoneid);
22781 			ire_refrele(ire);
22782 			if (conn_outgoing_ill != NULL)
22783 				ill_refrele(conn_outgoing_ill);
22784 			return;
22785 		}
22786 
22787 		out_ill = ire->ire_ipif->ipif_ill;
22788 
22789 		DTRACE_PROBE4(ip4__loopback__out__start,
22790 		    ill_t *, NULL, ill_t *, out_ill,
22791 		    ipha_t *, ipha, mblk_t *, first_mp);
22792 
22793 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
22794 		    NULL, out_ill, ipha, first_mp, mp);
22795 
22796 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
22797 
22798 		if (first_mp != NULL)
22799 			ip_wput_local(q, out_ill, ipha,
22800 			    first_mp, ire, 0, ire->ire_zoneid);
22801 	}
22802 next:
22803 	/*
22804 	 * More copies going out to additional interfaces.
22805 	 * ire1 has already been held. We don't need the
22806 	 * "ire" anymore.
22807 	 */
22808 	ire_refrele(ire);
22809 	ire = ire1;
22810 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
22811 	mp = next_mp;
22812 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
22813 	ill = ire_to_ill(ire);
22814 	first_mp = mp;
22815 	if (ipsec_len != 0) {
22816 		ASSERT(first_mp->b_datap->db_type == M_CTL);
22817 		mp = mp->b_cont;
22818 	}
22819 	dst = ire->ire_addr;
22820 	ipha = (ipha_t *)mp->b_rptr;
22821 	/*
22822 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
22823 	 * Restore ipha_ident "no checksum" flag.
22824 	 */
22825 	src = orig_src;
22826 	ipha->ipha_ident = ip_hdr_included;
22827 	goto another;
22828 
22829 #undef	rptr
22830 #undef	Q_TO_INDEX
22831 }
22832 
22833 /*
22834  * Routine to allocate a message that is used to notify the ULP about MDT.
22835  * The caller may provide a pointer to the link-layer MDT capabilities,
22836  * or NULL if MDT is to be disabled on the stream.
22837  */
22838 mblk_t *
22839 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
22840 {
22841 	mblk_t *mp;
22842 	ip_mdt_info_t *mdti;
22843 	ill_mdt_capab_t *idst;
22844 
22845 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
22846 		DB_TYPE(mp) = M_CTL;
22847 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
22848 		mdti = (ip_mdt_info_t *)mp->b_rptr;
22849 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
22850 		idst = &(mdti->mdt_capab);
22851 
22852 		/*
22853 		 * If the caller provides us with the capability, copy
22854 		 * it over into our notification message; otherwise
22855 		 * we zero out the capability portion.
22856 		 */
22857 		if (isrc != NULL)
22858 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22859 		else
22860 			bzero((caddr_t)idst, sizeof (*idst));
22861 	}
22862 	return (mp);
22863 }
22864 
22865 /*
22866  * Routine which determines whether MDT can be enabled on the destination
22867  * IRE and IPC combination, and if so, allocates and returns the MDT
22868  * notification mblk that may be used by ULP.  We also check if we need to
22869  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
22870  * MDT usage in the past have been lifted.  This gets called during IP
22871  * and ULP binding.
22872  */
22873 mblk_t *
22874 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22875     ill_mdt_capab_t *mdt_cap)
22876 {
22877 	mblk_t *mp;
22878 	boolean_t rc = B_FALSE;
22879 
22880 	ASSERT(dst_ire != NULL);
22881 	ASSERT(connp != NULL);
22882 	ASSERT(mdt_cap != NULL);
22883 
22884 	/*
22885 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
22886 	 * Multidata, which is handled in tcp_multisend().  This
22887 	 * is the reason why we do all these checks here, to ensure
22888 	 * that we don't enable Multidata for the cases which we
22889 	 * can't handle at the moment.
22890 	 */
22891 	do {
22892 		/* Only do TCP at the moment */
22893 		if (connp->conn_ulp != IPPROTO_TCP)
22894 			break;
22895 
22896 		/*
22897 		 * IPSEC outbound policy present?  Note that we get here
22898 		 * after calling ipsec_conn_cache_policy() where the global
22899 		 * policy checking is performed.  conn_latch will be
22900 		 * non-NULL as long as there's a policy defined,
22901 		 * i.e. conn_out_enforce_policy may be NULL in such case
22902 		 * when the connection is non-secure, and hence we check
22903 		 * further if the latch refers to an outbound policy.
22904 		 */
22905 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
22906 			break;
22907 
22908 		/* CGTP (multiroute) is enabled? */
22909 		if (dst_ire->ire_flags & RTF_MULTIRT)
22910 			break;
22911 
22912 		/* Outbound IPQoS enabled? */
22913 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22914 			/*
22915 			 * In this case, we disable MDT for this and all
22916 			 * future connections going over the interface.
22917 			 */
22918 			mdt_cap->ill_mdt_on = 0;
22919 			break;
22920 		}
22921 
22922 		/* socket option(s) present? */
22923 		if (!CONN_IS_MD_FASTPATH(connp))
22924 			break;
22925 
22926 		rc = B_TRUE;
22927 	/* CONSTCOND */
22928 	} while (0);
22929 
22930 	/* Remember the result */
22931 	connp->conn_mdt_ok = rc;
22932 
22933 	if (!rc)
22934 		return (NULL);
22935 	else if (!mdt_cap->ill_mdt_on) {
22936 		/*
22937 		 * If MDT has been previously turned off in the past, and we
22938 		 * currently can do MDT (due to IPQoS policy removal, etc.)
22939 		 * then enable it for this interface.
22940 		 */
22941 		mdt_cap->ill_mdt_on = 1;
22942 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
22943 		    "interface %s\n", ill_name));
22944 	}
22945 
22946 	/* Allocate the MDT info mblk */
22947 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
22948 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
22949 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
22950 		return (NULL);
22951 	}
22952 	return (mp);
22953 }
22954 
22955 /*
22956  * Create destination address attribute, and fill it with the physical
22957  * destination address and SAP taken from the template DL_UNITDATA_REQ
22958  * message block.
22959  */
22960 boolean_t
22961 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
22962 {
22963 	dl_unitdata_req_t *dlurp;
22964 	pattr_t *pa;
22965 	pattrinfo_t pa_info;
22966 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
22967 	uint_t das_len, das_off;
22968 
22969 	ASSERT(dlmp != NULL);
22970 
22971 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
22972 	das_len = dlurp->dl_dest_addr_length;
22973 	das_off = dlurp->dl_dest_addr_offset;
22974 
22975 	pa_info.type = PATTR_DSTADDRSAP;
22976 	pa_info.len = sizeof (**das) + das_len - 1;
22977 
22978 	/* create and associate the attribute */
22979 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22980 	if (pa != NULL) {
22981 		ASSERT(*das != NULL);
22982 		(*das)->addr_is_group = 0;
22983 		(*das)->addr_len = (uint8_t)das_len;
22984 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
22985 	}
22986 
22987 	return (pa != NULL);
22988 }
22989 
22990 /*
22991  * Create hardware checksum attribute and fill it with the values passed.
22992  */
22993 boolean_t
22994 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
22995     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
22996 {
22997 	pattr_t *pa;
22998 	pattrinfo_t pa_info;
22999 
23000 	ASSERT(mmd != NULL);
23001 
23002 	pa_info.type = PATTR_HCKSUM;
23003 	pa_info.len = sizeof (pattr_hcksum_t);
23004 
23005 	/* create and associate the attribute */
23006 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23007 	if (pa != NULL) {
23008 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23009 
23010 		hck->hcksum_start_offset = start_offset;
23011 		hck->hcksum_stuff_offset = stuff_offset;
23012 		hck->hcksum_end_offset = end_offset;
23013 		hck->hcksum_flags = flags;
23014 	}
23015 	return (pa != NULL);
23016 }
23017 
23018 /*
23019  * Create zerocopy attribute and fill it with the specified flags
23020  */
23021 boolean_t
23022 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23023 {
23024 	pattr_t *pa;
23025 	pattrinfo_t pa_info;
23026 
23027 	ASSERT(mmd != NULL);
23028 	pa_info.type = PATTR_ZCOPY;
23029 	pa_info.len = sizeof (pattr_zcopy_t);
23030 
23031 	/* create and associate the attribute */
23032 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23033 	if (pa != NULL) {
23034 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23035 
23036 		zcopy->zcopy_flags = flags;
23037 	}
23038 	return (pa != NULL);
23039 }
23040 
23041 /*
23042  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23043  * block chain. We could rewrite to handle arbitrary message block chains but
23044  * that would make the code complicated and slow. Right now there three
23045  * restrictions:
23046  *
23047  *   1. The first message block must contain the complete IP header and
23048  *	at least 1 byte of payload data.
23049  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23050  *	so that we can use a single Multidata message.
23051  *   3. No frag must be distributed over two or more message blocks so
23052  *	that we don't need more than two packet descriptors per frag.
23053  *
23054  * The above restrictions allow us to support userland applications (which
23055  * will send down a single message block) and NFS over UDP (which will
23056  * send down a chain of at most three message blocks).
23057  *
23058  * We also don't use MDT for payloads with less than or equal to
23059  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23060  */
23061 boolean_t
23062 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23063 {
23064 	int	blocks;
23065 	ssize_t	total, missing, size;
23066 
23067 	ASSERT(mp != NULL);
23068 	ASSERT(hdr_len > 0);
23069 
23070 	size = MBLKL(mp) - hdr_len;
23071 	if (size <= 0)
23072 		return (B_FALSE);
23073 
23074 	/* The first mblk contains the header and some payload. */
23075 	blocks = 1;
23076 	total = size;
23077 	size %= len;
23078 	missing = (size == 0) ? 0 : (len - size);
23079 	mp = mp->b_cont;
23080 
23081 	while (mp != NULL) {
23082 		/*
23083 		 * Give up if we encounter a zero length message block.
23084 		 * In practice, this should rarely happen and therefore
23085 		 * not worth the trouble of freeing and re-linking the
23086 		 * mblk from the chain to handle such case.
23087 		 */
23088 		if ((size = MBLKL(mp)) == 0)
23089 			return (B_FALSE);
23090 
23091 		/* Too many payload buffers for a single Multidata message? */
23092 		if (++blocks > MULTIDATA_MAX_PBUFS)
23093 			return (B_FALSE);
23094 
23095 		total += size;
23096 		/* Is a frag distributed over two or more message blocks? */
23097 		if (missing > size)
23098 			return (B_FALSE);
23099 		size -= missing;
23100 
23101 		size %= len;
23102 		missing = (size == 0) ? 0 : (len - size);
23103 
23104 		mp = mp->b_cont;
23105 	}
23106 
23107 	return (total > ip_wput_frag_mdt_min);
23108 }
23109 
23110 /*
23111  * Outbound IPv4 fragmentation routine using MDT.
23112  */
23113 static void
23114 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23115     uint32_t frag_flag, int offset)
23116 {
23117 	ipha_t		*ipha_orig;
23118 	int		i1, ip_data_end;
23119 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23120 	mblk_t		*hdr_mp, *md_mp = NULL;
23121 	unsigned char	*hdr_ptr, *pld_ptr;
23122 	multidata_t	*mmd;
23123 	ip_pdescinfo_t	pdi;
23124 
23125 	ASSERT(DB_TYPE(mp) == M_DATA);
23126 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23127 
23128 	ipha_orig = (ipha_t *)mp->b_rptr;
23129 	mp->b_rptr += sizeof (ipha_t);
23130 
23131 	/* Calculate how many packets we will send out */
23132 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23133 	pkts = (i1 + len - 1) / len;
23134 	ASSERT(pkts > 1);
23135 
23136 	/* Allocate a message block which will hold all the IP Headers. */
23137 	wroff = ip_wroff_extra;
23138 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23139 
23140 	i1 = pkts * hdr_chunk_len;
23141 	/*
23142 	 * Create the header buffer, Multidata and destination address
23143 	 * and SAP attribute that should be associated with it.
23144 	 */
23145 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23146 	    ((hdr_mp->b_wptr += i1),
23147 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23148 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23149 		freemsg(mp);
23150 		if (md_mp == NULL) {
23151 			freemsg(hdr_mp);
23152 		} else {
23153 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
23154 			freemsg(md_mp);
23155 		}
23156 		IP_STAT(ip_frag_mdt_allocfail);
23157 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
23158 		return;
23159 	}
23160 	IP_STAT(ip_frag_mdt_allocd);
23161 
23162 	/*
23163 	 * Add a payload buffer to the Multidata; this operation must not
23164 	 * fail, or otherwise our logic in this routine is broken.  There
23165 	 * is no memory allocation done by the routine, so any returned
23166 	 * failure simply tells us that we've done something wrong.
23167 	 *
23168 	 * A failure tells us that either we're adding the same payload
23169 	 * buffer more than once, or we're trying to add more buffers than
23170 	 * allowed.  None of the above cases should happen, and we panic
23171 	 * because either there's horrible heap corruption, and/or
23172 	 * programming mistake.
23173 	 */
23174 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23175 		goto pbuf_panic;
23176 
23177 	hdr_ptr = hdr_mp->b_rptr;
23178 	pld_ptr = mp->b_rptr;
23179 
23180 	/* Establish the ending byte offset, based on the starting offset. */
23181 	offset <<= 3;
23182 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23183 	    IP_SIMPLE_HDR_LENGTH;
23184 
23185 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23186 
23187 	while (pld_ptr < mp->b_wptr) {
23188 		ipha_t		*ipha;
23189 		uint16_t	offset_and_flags;
23190 		uint16_t	ip_len;
23191 		int		error;
23192 
23193 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23194 		ipha = (ipha_t *)(hdr_ptr + wroff);
23195 		ASSERT(OK_32PTR(ipha));
23196 		*ipha = *ipha_orig;
23197 
23198 		if (ip_data_end - offset > len) {
23199 			offset_and_flags = IPH_MF;
23200 		} else {
23201 			/*
23202 			 * Last frag. Set len to the length of this last piece.
23203 			 */
23204 			len = ip_data_end - offset;
23205 			/* A frag of a frag might have IPH_MF non-zero */
23206 			offset_and_flags =
23207 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23208 			    IPH_MF;
23209 		}
23210 		offset_and_flags |= (uint16_t)(offset >> 3);
23211 		offset_and_flags |= (uint16_t)frag_flag;
23212 		/* Store the offset and flags in the IP header. */
23213 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23214 
23215 		/* Store the length in the IP header. */
23216 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23217 		ipha->ipha_length = htons(ip_len);
23218 
23219 		/*
23220 		 * Set the IP header checksum.  Note that mp is just
23221 		 * the header, so this is easy to pass to ip_csum.
23222 		 */
23223 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23224 
23225 		/*
23226 		 * Record offset and size of header and data of the next packet
23227 		 * in the multidata message.
23228 		 */
23229 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23230 		PDESC_PLD_INIT(&pdi);
23231 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23232 		ASSERT(i1 > 0);
23233 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23234 		if (i1 == len) {
23235 			pld_ptr += len;
23236 		} else {
23237 			i1 = len - i1;
23238 			mp = mp->b_cont;
23239 			ASSERT(mp != NULL);
23240 			ASSERT(MBLKL(mp) >= i1);
23241 			/*
23242 			 * Attach the next payload message block to the
23243 			 * multidata message.
23244 			 */
23245 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23246 				goto pbuf_panic;
23247 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23248 			pld_ptr = mp->b_rptr + i1;
23249 		}
23250 
23251 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23252 		    KM_NOSLEEP)) == NULL) {
23253 			/*
23254 			 * Any failure other than ENOMEM indicates that we
23255 			 * have passed in invalid pdesc info or parameters
23256 			 * to mmd_addpdesc, which must not happen.
23257 			 *
23258 			 * EINVAL is a result of failure on boundary checks
23259 			 * against the pdesc info contents.  It should not
23260 			 * happen, and we panic because either there's
23261 			 * horrible heap corruption, and/or programming
23262 			 * mistake.
23263 			 */
23264 			if (error != ENOMEM) {
23265 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23266 				    "pdesc logic error detected for "
23267 				    "mmd %p pinfo %p (%d)\n",
23268 				    (void *)mmd, (void *)&pdi, error);
23269 				/* NOTREACHED */
23270 			}
23271 			IP_STAT(ip_frag_mdt_addpdescfail);
23272 			/* Free unattached payload message blocks as well */
23273 			md_mp->b_cont = mp->b_cont;
23274 			goto free_mmd;
23275 		}
23276 
23277 		/* Advance fragment offset. */
23278 		offset += len;
23279 
23280 		/* Advance to location for next header in the buffer. */
23281 		hdr_ptr += hdr_chunk_len;
23282 
23283 		/* Did we reach the next payload message block? */
23284 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23285 			mp = mp->b_cont;
23286 			/*
23287 			 * Attach the next message block with payload
23288 			 * data to the multidata message.
23289 			 */
23290 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23291 				goto pbuf_panic;
23292 			pld_ptr = mp->b_rptr;
23293 		}
23294 	}
23295 
23296 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23297 	ASSERT(mp->b_wptr == pld_ptr);
23298 
23299 	/* Update IP statistics */
23300 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
23301 	BUMP_MIB(&ip_mib, ipFragOKs);
23302 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
23303 
23304 	if (pkt_type == OB_PKT) {
23305 		ire->ire_ob_pkt_count += pkts;
23306 		if (ire->ire_ipif != NULL)
23307 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23308 	} else {
23309 		/*
23310 		 * The type is IB_PKT in the forwarding path and in
23311 		 * the mobile IP case when the packet is being reverse-
23312 		 * tunneled to the home agent.
23313 		 */
23314 		ire->ire_ib_pkt_count += pkts;
23315 		ASSERT(!IRE_IS_LOCAL(ire));
23316 		if (ire->ire_type & IRE_BROADCAST)
23317 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23318 		else
23319 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23320 	}
23321 	ire->ire_last_used_time = lbolt;
23322 	/* Send it down */
23323 	putnext(ire->ire_stq, md_mp);
23324 	return;
23325 
23326 pbuf_panic:
23327 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23328 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23329 	    pbuf_idx);
23330 	/* NOTREACHED */
23331 }
23332 
23333 /*
23334  * Outbound IP fragmentation routine.
23335  *
23336  * NOTE : This routine does not ire_refrele the ire that is passed in
23337  * as the argument.
23338  */
23339 static void
23340 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23341     uint32_t frag_flag, zoneid_t zoneid)
23342 {
23343 	int		i1;
23344 	mblk_t		*ll_hdr_mp;
23345 	int 		ll_hdr_len;
23346 	int		hdr_len;
23347 	mblk_t		*hdr_mp;
23348 	ipha_t		*ipha;
23349 	int		ip_data_end;
23350 	int		len;
23351 	mblk_t		*mp = mp_orig, *mp1;
23352 	int		offset;
23353 	queue_t		*q;
23354 	uint32_t	v_hlen_tos_len;
23355 	mblk_t		*first_mp;
23356 	boolean_t	mctl_present;
23357 	ill_t		*ill;
23358 	ill_t		*out_ill;
23359 	mblk_t		*xmit_mp;
23360 	mblk_t		*carve_mp;
23361 	ire_t		*ire1 = NULL;
23362 	ire_t		*save_ire = NULL;
23363 	mblk_t  	*next_mp = NULL;
23364 	boolean_t	last_frag = B_FALSE;
23365 	boolean_t	multirt_send = B_FALSE;
23366 	ire_t		*first_ire = NULL;
23367 	irb_t		*irb = NULL;
23368 
23369 	/*
23370 	 * IPSEC does not allow hw accelerated packets to be fragmented
23371 	 * This check is made in ip_wput_ipsec_out prior to coming here
23372 	 * via ip_wput_ire_fragmentit.
23373 	 *
23374 	 * If at this point we have an ire whose ARP request has not
23375 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23376 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23377 	 * This packet and all fragmentable packets for this ire will
23378 	 * continue to get dropped while ire_nce->nce_state remains in
23379 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23380 	 * ND_REACHABLE, all subsquent large packets for this ire will
23381 	 * get fragemented and sent out by this function.
23382 	 */
23383 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23384 		/* If nce_state is ND_INITIAL, trigger ARP query */
23385 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23386 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23387 		    " -  dropping packet\n"));
23388 		BUMP_MIB(&ip_mib, ipFragFails);
23389 		freemsg(mp);
23390 		return;
23391 	}
23392 
23393 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23394 	    "ip_wput_frag_start:");
23395 
23396 	if (mp->b_datap->db_type == M_CTL) {
23397 		first_mp = mp;
23398 		mp_orig = mp = mp->b_cont;
23399 		mctl_present = B_TRUE;
23400 	} else {
23401 		first_mp = mp;
23402 		mctl_present = B_FALSE;
23403 	}
23404 
23405 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23406 	ipha = (ipha_t *)mp->b_rptr;
23407 
23408 	/*
23409 	 * If the Don't Fragment flag is on, generate an ICMP destination
23410 	 * unreachable, fragmentation needed.
23411 	 */
23412 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23413 	if (offset & IPH_DF) {
23414 		BUMP_MIB(&ip_mib, ipFragFails);
23415 		/*
23416 		 * Need to compute hdr checksum if called from ip_wput_ire.
23417 		 * Note that ip_rput_forward verifies the checksum before
23418 		 * calling this routine so in that case this is a noop.
23419 		 */
23420 		ipha->ipha_hdr_checksum = 0;
23421 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23422 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid);
23423 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23424 		    "ip_wput_frag_end:(%S)",
23425 		    "don't fragment");
23426 		return;
23427 	}
23428 	if (mctl_present)
23429 		freeb(first_mp);
23430 	/*
23431 	 * Establish the starting offset.  May not be zero if we are fragging
23432 	 * a fragment that is being forwarded.
23433 	 */
23434 	offset = offset & IPH_OFFSET;
23435 
23436 	/* TODO why is this test needed? */
23437 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23438 	if (((max_frag - LENGTH) & ~7) < 8) {
23439 		/* TODO: notify ulp somehow */
23440 		BUMP_MIB(&ip_mib, ipFragFails);
23441 		freemsg(mp);
23442 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23443 		    "ip_wput_frag_end:(%S)",
23444 		    "len < 8");
23445 		return;
23446 	}
23447 
23448 	hdr_len = (V_HLEN & 0xF) << 2;
23449 
23450 	ipha->ipha_hdr_checksum = 0;
23451 
23452 	/*
23453 	 * Establish the number of bytes maximum per frag, after putting
23454 	 * in the header.
23455 	 */
23456 	len = (max_frag - hdr_len) & ~7;
23457 
23458 	/* Check if we can use MDT to send out the frags. */
23459 	ASSERT(!IRE_IS_LOCAL(ire));
23460 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
23461 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
23462 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
23463 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23464 		ASSERT(ill->ill_mdt_capab != NULL);
23465 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23466 			/*
23467 			 * If MDT has been previously turned off in the past,
23468 			 * and we currently can do MDT (due to IPQoS policy
23469 			 * removal, etc.) then enable it for this interface.
23470 			 */
23471 			ill->ill_mdt_capab->ill_mdt_on = 1;
23472 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23473 			    ill->ill_name));
23474 		}
23475 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23476 		    offset);
23477 		return;
23478 	}
23479 
23480 	/* Get a copy of the header for the trailing frags */
23481 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
23482 	if (!hdr_mp) {
23483 		BUMP_MIB(&ip_mib, ipOutDiscards);
23484 		freemsg(mp);
23485 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23486 		    "ip_wput_frag_end:(%S)",
23487 		    "couldn't copy hdr");
23488 		return;
23489 	}
23490 	if (DB_CRED(mp) != NULL)
23491 		mblk_setcred(hdr_mp, DB_CRED(mp));
23492 
23493 	/* Store the starting offset, with the MoreFrags flag. */
23494 	i1 = offset | IPH_MF | frag_flag;
23495 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23496 
23497 	/* Establish the ending byte offset, based on the starting offset. */
23498 	offset <<= 3;
23499 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23500 
23501 	/* Store the length of the first fragment in the IP header. */
23502 	i1 = len + hdr_len;
23503 	ASSERT(i1 <= IP_MAXPACKET);
23504 	ipha->ipha_length = htons((uint16_t)i1);
23505 
23506 	/*
23507 	 * Compute the IP header checksum for the first frag.  We have to
23508 	 * watch out that we stop at the end of the header.
23509 	 */
23510 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23511 
23512 	/*
23513 	 * Now carve off the first frag.  Note that this will include the
23514 	 * original IP header.
23515 	 */
23516 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
23517 		BUMP_MIB(&ip_mib, ipOutDiscards);
23518 		freeb(hdr_mp);
23519 		freemsg(mp_orig);
23520 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23521 		    "ip_wput_frag_end:(%S)",
23522 		    "couldn't carve first");
23523 		return;
23524 	}
23525 
23526 	/*
23527 	 * Multirouting case. Each fragment is replicated
23528 	 * via all non-condemned RTF_MULTIRT routes
23529 	 * currently resolved.
23530 	 * We ensure that first_ire is the first RTF_MULTIRT
23531 	 * ire in the bucket.
23532 	 */
23533 	if (ire->ire_flags & RTF_MULTIRT) {
23534 		irb = ire->ire_bucket;
23535 		ASSERT(irb != NULL);
23536 
23537 		multirt_send = B_TRUE;
23538 
23539 		/* Make sure we do not omit any multiroute ire. */
23540 		IRB_REFHOLD(irb);
23541 		for (first_ire = irb->irb_ire;
23542 		    first_ire != NULL;
23543 		    first_ire = first_ire->ire_next) {
23544 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23545 			    (first_ire->ire_addr == ire->ire_addr) &&
23546 			    !(first_ire->ire_marks &
23547 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23548 				break;
23549 		}
23550 
23551 		if (first_ire != NULL) {
23552 			if (first_ire != ire) {
23553 				IRE_REFHOLD(first_ire);
23554 				/*
23555 				 * Do not release the ire passed in
23556 				 * as the argument.
23557 				 */
23558 				ire = first_ire;
23559 			} else {
23560 				first_ire = NULL;
23561 			}
23562 		}
23563 		IRB_REFRELE(irb);
23564 
23565 		/*
23566 		 * Save the first ire; we will need to restore it
23567 		 * for the trailing frags.
23568 		 * We REFHOLD save_ire, as each iterated ire will be
23569 		 * REFRELEd.
23570 		 */
23571 		save_ire = ire;
23572 		IRE_REFHOLD(save_ire);
23573 	}
23574 
23575 	/*
23576 	 * First fragment emission loop.
23577 	 * In most cases, the emission loop below is entered only
23578 	 * once. Only in the case where the ire holds the RTF_MULTIRT
23579 	 * flag, do we loop to process all RTF_MULTIRT ires in the
23580 	 * bucket, and send the fragment through all crossed
23581 	 * RTF_MULTIRT routes.
23582 	 */
23583 	do {
23584 		if (ire->ire_flags & RTF_MULTIRT) {
23585 			/*
23586 			 * We are in a multiple send case, need to get
23587 			 * the next ire and make a copy of the packet.
23588 			 * ire1 holds here the next ire to process in the
23589 			 * bucket. If multirouting is expected,
23590 			 * any non-RTF_MULTIRT ire that has the
23591 			 * right destination address is ignored.
23592 			 *
23593 			 * We have to take into account the MTU of
23594 			 * each walked ire. max_frag is set by the
23595 			 * the caller and generally refers to
23596 			 * the primary ire entry. Here we ensure that
23597 			 * no route with a lower MTU will be used, as
23598 			 * fragments are carved once for all ires,
23599 			 * then replicated.
23600 			 */
23601 			ASSERT(irb != NULL);
23602 			IRB_REFHOLD(irb);
23603 			for (ire1 = ire->ire_next;
23604 			    ire1 != NULL;
23605 			    ire1 = ire1->ire_next) {
23606 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23607 					continue;
23608 				if (ire1->ire_addr != ire->ire_addr)
23609 					continue;
23610 				if (ire1->ire_marks &
23611 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23612 					continue;
23613 				/*
23614 				 * Ensure we do not exceed the MTU
23615 				 * of the next route.
23616 				 */
23617 				if (ire1->ire_max_frag < max_frag) {
23618 					ip_multirt_bad_mtu(ire1, max_frag);
23619 					continue;
23620 				}
23621 
23622 				/* Got one. */
23623 				IRE_REFHOLD(ire1);
23624 				break;
23625 			}
23626 			IRB_REFRELE(irb);
23627 
23628 			if (ire1 != NULL) {
23629 				next_mp = copyb(mp);
23630 				if ((next_mp == NULL) ||
23631 				    ((mp->b_cont != NULL) &&
23632 				    ((next_mp->b_cont =
23633 				    dupmsg(mp->b_cont)) == NULL))) {
23634 					freemsg(next_mp);
23635 					next_mp = NULL;
23636 					ire_refrele(ire1);
23637 					ire1 = NULL;
23638 				}
23639 			}
23640 
23641 			/* Last multiroute ire; don't loop anymore. */
23642 			if (ire1 == NULL) {
23643 				multirt_send = B_FALSE;
23644 			}
23645 		}
23646 
23647 		ll_hdr_len = 0;
23648 		LOCK_IRE_FP_MP(ire);
23649 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23650 		if (ll_hdr_mp != NULL) {
23651 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23652 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
23653 		} else {
23654 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
23655 		}
23656 
23657 		/* If there is a transmit header, get a copy for this frag. */
23658 		/*
23659 		 * TODO: should check db_ref before calling ip_carve_mp since
23660 		 * it might give us a dup.
23661 		 */
23662 		if (!ll_hdr_mp) {
23663 			/* No xmit header. */
23664 			xmit_mp = mp;
23665 
23666 		/* We have a link-layer header that can fit in our mblk. */
23667 		} else if (mp->b_datap->db_ref == 1 &&
23668 		    ll_hdr_len != 0 &&
23669 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23670 			/* M_DATA fastpath */
23671 			mp->b_rptr -= ll_hdr_len;
23672 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
23673 			xmit_mp = mp;
23674 
23675 		/* Corner case if copyb has failed */
23676 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
23677 			UNLOCK_IRE_FP_MP(ire);
23678 			BUMP_MIB(&ip_mib, ipOutDiscards);
23679 			freeb(hdr_mp);
23680 			freemsg(mp);
23681 			freemsg(mp_orig);
23682 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23683 			    "ip_wput_frag_end:(%S)",
23684 			    "discard");
23685 
23686 			if (multirt_send) {
23687 				ASSERT(ire1);
23688 				ASSERT(next_mp);
23689 
23690 				freemsg(next_mp);
23691 				ire_refrele(ire1);
23692 			}
23693 			if (save_ire != NULL)
23694 				IRE_REFRELE(save_ire);
23695 
23696 			if (first_ire != NULL)
23697 				ire_refrele(first_ire);
23698 			return;
23699 
23700 		/*
23701 		 * Case of res_mp OR the fastpath mp can't fit
23702 		 * in the mblk
23703 		 */
23704 		} else {
23705 			xmit_mp->b_cont = mp;
23706 			if (DB_CRED(mp) != NULL)
23707 				mblk_setcred(xmit_mp, DB_CRED(mp));
23708 			/*
23709 			 * Get priority marking, if any.
23710 			 * We propagate the CoS marking from the
23711 			 * original packet that went to QoS processing
23712 			 * in ip_wput_ire to the newly carved mp.
23713 			 */
23714 			if (DB_TYPE(xmit_mp) == M_DATA)
23715 				xmit_mp->b_band = mp->b_band;
23716 		}
23717 		UNLOCK_IRE_FP_MP(ire);
23718 		q = ire->ire_stq;
23719 		BUMP_MIB(&ip_mib, ipFragCreates);
23720 
23721 		out_ill = (ill_t *)q->q_ptr;
23722 
23723 		DTRACE_PROBE4(ip4__physical__out__start,
23724 		    ill_t *, NULL, ill_t *, out_ill,
23725 		    ipha_t *, ipha, mblk_t *, xmit_mp);
23726 
23727 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
23728 		    NULL, out_ill, ipha, xmit_mp, mp);
23729 
23730 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
23731 
23732 		if (xmit_mp != NULL) {
23733 			putnext(q, xmit_mp);
23734 			if (pkt_type != OB_PKT) {
23735 				/*
23736 				 * Update the packet count of trailing
23737 				 * RTF_MULTIRT ires.
23738 				 */
23739 				UPDATE_OB_PKT_COUNT(ire);
23740 			}
23741 		}
23742 
23743 		if (multirt_send) {
23744 			/*
23745 			 * We are in a multiple send case; look for
23746 			 * the next ire and re-enter the loop.
23747 			 */
23748 			ASSERT(ire1);
23749 			ASSERT(next_mp);
23750 			/* REFRELE the current ire before looping */
23751 			ire_refrele(ire);
23752 			ire = ire1;
23753 			ire1 = NULL;
23754 			mp = next_mp;
23755 			next_mp = NULL;
23756 		}
23757 	} while (multirt_send);
23758 
23759 	ASSERT(ire1 == NULL);
23760 
23761 	/* Restore the original ire; we need it for the trailing frags */
23762 	if (save_ire != NULL) {
23763 		/* REFRELE the last iterated ire */
23764 		ire_refrele(ire);
23765 		/* save_ire has been REFHOLDed */
23766 		ire = save_ire;
23767 		save_ire = NULL;
23768 		q = ire->ire_stq;
23769 	}
23770 
23771 	if (pkt_type == OB_PKT) {
23772 		UPDATE_OB_PKT_COUNT(ire);
23773 	} else {
23774 		UPDATE_IB_PKT_COUNT(ire);
23775 	}
23776 
23777 	/* Advance the offset to the second frag starting point. */
23778 	offset += len;
23779 	/*
23780 	 * Update hdr_len from the copied header - there might be less options
23781 	 * in the later fragments.
23782 	 */
23783 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
23784 	/* Loop until done. */
23785 	for (;;) {
23786 		uint16_t	offset_and_flags;
23787 		uint16_t	ip_len;
23788 
23789 		if (ip_data_end - offset > len) {
23790 			/*
23791 			 * Carve off the appropriate amount from the original
23792 			 * datagram.
23793 			 */
23794 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23795 				mp = NULL;
23796 				break;
23797 			}
23798 			/*
23799 			 * More frags after this one.  Get another copy
23800 			 * of the header.
23801 			 */
23802 			if (carve_mp->b_datap->db_ref == 1 &&
23803 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23804 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23805 				/* Inline IP header */
23806 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23807 				    hdr_mp->b_rptr;
23808 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23809 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23810 				mp = carve_mp;
23811 			} else {
23812 				if (!(mp = copyb(hdr_mp))) {
23813 					freemsg(carve_mp);
23814 					break;
23815 				}
23816 				/* Get priority marking, if any. */
23817 				mp->b_band = carve_mp->b_band;
23818 				mp->b_cont = carve_mp;
23819 			}
23820 			ipha = (ipha_t *)mp->b_rptr;
23821 			offset_and_flags = IPH_MF;
23822 		} else {
23823 			/*
23824 			 * Last frag.  Consume the header. Set len to
23825 			 * the length of this last piece.
23826 			 */
23827 			len = ip_data_end - offset;
23828 
23829 			/*
23830 			 * Carve off the appropriate amount from the original
23831 			 * datagram.
23832 			 */
23833 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23834 				mp = NULL;
23835 				break;
23836 			}
23837 			if (carve_mp->b_datap->db_ref == 1 &&
23838 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23839 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23840 				/* Inline IP header */
23841 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23842 				    hdr_mp->b_rptr;
23843 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23844 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23845 				mp = carve_mp;
23846 				freeb(hdr_mp);
23847 				hdr_mp = mp;
23848 			} else {
23849 				mp = hdr_mp;
23850 				/* Get priority marking, if any. */
23851 				mp->b_band = carve_mp->b_band;
23852 				mp->b_cont = carve_mp;
23853 			}
23854 			ipha = (ipha_t *)mp->b_rptr;
23855 			/* A frag of a frag might have IPH_MF non-zero */
23856 			offset_and_flags =
23857 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23858 			    IPH_MF;
23859 		}
23860 		offset_and_flags |= (uint16_t)(offset >> 3);
23861 		offset_and_flags |= (uint16_t)frag_flag;
23862 		/* Store the offset and flags in the IP header. */
23863 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23864 
23865 		/* Store the length in the IP header. */
23866 		ip_len = (uint16_t)(len + hdr_len);
23867 		ipha->ipha_length = htons(ip_len);
23868 
23869 		/*
23870 		 * Set the IP header checksum.	Note that mp is just
23871 		 * the header, so this is easy to pass to ip_csum.
23872 		 */
23873 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23874 
23875 		/* Attach a transmit header, if any, and ship it. */
23876 		if (pkt_type == OB_PKT) {
23877 			UPDATE_OB_PKT_COUNT(ire);
23878 		} else {
23879 			UPDATE_IB_PKT_COUNT(ire);
23880 		}
23881 
23882 		if (ire->ire_flags & RTF_MULTIRT) {
23883 			irb = ire->ire_bucket;
23884 			ASSERT(irb != NULL);
23885 
23886 			multirt_send = B_TRUE;
23887 
23888 			/*
23889 			 * Save the original ire; we will need to restore it
23890 			 * for the tailing frags.
23891 			 */
23892 			save_ire = ire;
23893 			IRE_REFHOLD(save_ire);
23894 		}
23895 		/*
23896 		 * Emission loop for this fragment, similar
23897 		 * to what is done for the first fragment.
23898 		 */
23899 		do {
23900 			if (multirt_send) {
23901 				/*
23902 				 * We are in a multiple send case, need to get
23903 				 * the next ire and make a copy of the packet.
23904 				 */
23905 				ASSERT(irb != NULL);
23906 				IRB_REFHOLD(irb);
23907 				for (ire1 = ire->ire_next;
23908 				    ire1 != NULL;
23909 				    ire1 = ire1->ire_next) {
23910 					if (!(ire1->ire_flags & RTF_MULTIRT))
23911 						continue;
23912 					if (ire1->ire_addr != ire->ire_addr)
23913 						continue;
23914 					if (ire1->ire_marks &
23915 					    (IRE_MARK_CONDEMNED|
23916 						IRE_MARK_HIDDEN))
23917 						continue;
23918 					/*
23919 					 * Ensure we do not exceed the MTU
23920 					 * of the next route.
23921 					 */
23922 					if (ire1->ire_max_frag < max_frag) {
23923 						ip_multirt_bad_mtu(ire1,
23924 						    max_frag);
23925 						continue;
23926 					}
23927 
23928 					/* Got one. */
23929 					IRE_REFHOLD(ire1);
23930 					break;
23931 				}
23932 				IRB_REFRELE(irb);
23933 
23934 				if (ire1 != NULL) {
23935 					next_mp = copyb(mp);
23936 					if ((next_mp == NULL) ||
23937 					    ((mp->b_cont != NULL) &&
23938 					    ((next_mp->b_cont =
23939 					    dupmsg(mp->b_cont)) == NULL))) {
23940 						freemsg(next_mp);
23941 						next_mp = NULL;
23942 						ire_refrele(ire1);
23943 						ire1 = NULL;
23944 					}
23945 				}
23946 
23947 				/* Last multiroute ire; don't loop anymore. */
23948 				if (ire1 == NULL) {
23949 					multirt_send = B_FALSE;
23950 				}
23951 			}
23952 
23953 			/* Update transmit header */
23954 			ll_hdr_len = 0;
23955 			LOCK_IRE_FP_MP(ire);
23956 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23957 			if (ll_hdr_mp != NULL) {
23958 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23959 				ll_hdr_len = MBLKL(ll_hdr_mp);
23960 			} else {
23961 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
23962 			}
23963 
23964 			if (!ll_hdr_mp) {
23965 				xmit_mp = mp;
23966 
23967 			/*
23968 			 * We have link-layer header that can fit in
23969 			 * our mblk.
23970 			 */
23971 			} else if (mp->b_datap->db_ref == 1 &&
23972 			    ll_hdr_len != 0 &&
23973 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23974 				/* M_DATA fastpath */
23975 				mp->b_rptr -= ll_hdr_len;
23976 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
23977 				    ll_hdr_len);
23978 				xmit_mp = mp;
23979 
23980 			/*
23981 			 * Case of res_mp OR the fastpath mp can't fit
23982 			 * in the mblk
23983 			 */
23984 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
23985 				xmit_mp->b_cont = mp;
23986 				if (DB_CRED(mp) != NULL)
23987 					mblk_setcred(xmit_mp, DB_CRED(mp));
23988 				/* Get priority marking, if any. */
23989 				if (DB_TYPE(xmit_mp) == M_DATA)
23990 					xmit_mp->b_band = mp->b_band;
23991 
23992 			/* Corner case if copyb failed */
23993 			} else {
23994 				/*
23995 				 * Exit both the replication and
23996 				 * fragmentation loops.
23997 				 */
23998 				UNLOCK_IRE_FP_MP(ire);
23999 				goto drop_pkt;
24000 			}
24001 			UNLOCK_IRE_FP_MP(ire);
24002 			BUMP_MIB(&ip_mib, ipFragCreates);
24003 
24004 			mp1 = mp;
24005 			out_ill = (ill_t *)q->q_ptr;
24006 
24007 			DTRACE_PROBE4(ip4__physical__out__start,
24008 			    ill_t *, NULL, ill_t *, out_ill,
24009 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24010 
24011 			FW_HOOKS(ip4_physical_out_event,
24012 			    ipv4firewall_physical_out,
24013 			    NULL, out_ill, ipha, xmit_mp, mp);
24014 
24015 			DTRACE_PROBE1(ip4__physical__out__end,
24016 			    mblk_t *, xmit_mp);
24017 
24018 			if (mp != mp1 && hdr_mp == mp1)
24019 				hdr_mp = mp;
24020 			if (mp != mp1 && mp_orig == mp1)
24021 				mp_orig = mp;
24022 
24023 			if (xmit_mp != NULL) {
24024 				putnext(q, xmit_mp);
24025 
24026 				if (pkt_type != OB_PKT) {
24027 					/*
24028 					 * Update the packet count of trailing
24029 					 * RTF_MULTIRT ires.
24030 					 */
24031 					UPDATE_OB_PKT_COUNT(ire);
24032 				}
24033 			}
24034 
24035 			/* All done if we just consumed the hdr_mp. */
24036 			if (mp == hdr_mp) {
24037 				last_frag = B_TRUE;
24038 			}
24039 
24040 			if (multirt_send) {
24041 				/*
24042 				 * We are in a multiple send case; look for
24043 				 * the next ire and re-enter the loop.
24044 				 */
24045 				ASSERT(ire1);
24046 				ASSERT(next_mp);
24047 				/* REFRELE the current ire before looping */
24048 				ire_refrele(ire);
24049 				ire = ire1;
24050 				ire1 = NULL;
24051 				q = ire->ire_stq;
24052 				mp = next_mp;
24053 				next_mp = NULL;
24054 			}
24055 		} while (multirt_send);
24056 		/*
24057 		 * Restore the original ire; we need it for the
24058 		 * trailing frags
24059 		 */
24060 		if (save_ire != NULL) {
24061 			ASSERT(ire1 == NULL);
24062 			/* REFRELE the last iterated ire */
24063 			ire_refrele(ire);
24064 			/* save_ire has been REFHOLDed */
24065 			ire = save_ire;
24066 			q = ire->ire_stq;
24067 			save_ire = NULL;
24068 		}
24069 
24070 		if (last_frag) {
24071 			BUMP_MIB(&ip_mib, ipFragOKs);
24072 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24073 			    "ip_wput_frag_end:(%S)",
24074 			    "consumed hdr_mp");
24075 
24076 			if (first_ire != NULL)
24077 				ire_refrele(first_ire);
24078 			return;
24079 		}
24080 		/* Otherwise, advance and loop. */
24081 		offset += len;
24082 	}
24083 
24084 drop_pkt:
24085 	/* Clean up following allocation failure. */
24086 	BUMP_MIB(&ip_mib, ipOutDiscards);
24087 	freemsg(mp);
24088 	if (mp != hdr_mp)
24089 		freeb(hdr_mp);
24090 	if (mp != mp_orig)
24091 		freemsg(mp_orig);
24092 
24093 	if (save_ire != NULL)
24094 		IRE_REFRELE(save_ire);
24095 	if (first_ire != NULL)
24096 		ire_refrele(first_ire);
24097 
24098 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24099 	    "ip_wput_frag_end:(%S)",
24100 	    "end--alloc failure");
24101 }
24102 
24103 /*
24104  * Copy the header plus those options which have the copy bit set
24105  */
24106 static mblk_t *
24107 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
24108 {
24109 	mblk_t	*mp;
24110 	uchar_t	*up;
24111 
24112 	/*
24113 	 * Quick check if we need to look for options without the copy bit
24114 	 * set
24115 	 */
24116 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
24117 	if (!mp)
24118 		return (mp);
24119 	mp->b_rptr += ip_wroff_extra;
24120 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24121 		bcopy(rptr, mp->b_rptr, hdr_len);
24122 		mp->b_wptr += hdr_len + ip_wroff_extra;
24123 		return (mp);
24124 	}
24125 	up  = mp->b_rptr;
24126 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24127 	up += IP_SIMPLE_HDR_LENGTH;
24128 	rptr += IP_SIMPLE_HDR_LENGTH;
24129 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24130 	while (hdr_len > 0) {
24131 		uint32_t optval;
24132 		uint32_t optlen;
24133 
24134 		optval = *rptr;
24135 		if (optval == IPOPT_EOL)
24136 			break;
24137 		if (optval == IPOPT_NOP)
24138 			optlen = 1;
24139 		else
24140 			optlen = rptr[1];
24141 		if (optval & IPOPT_COPY) {
24142 			bcopy(rptr, up, optlen);
24143 			up += optlen;
24144 		}
24145 		rptr += optlen;
24146 		hdr_len -= optlen;
24147 	}
24148 	/*
24149 	 * Make sure that we drop an even number of words by filling
24150 	 * with EOL to the next word boundary.
24151 	 */
24152 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24153 	    hdr_len & 0x3; hdr_len++)
24154 		*up++ = IPOPT_EOL;
24155 	mp->b_wptr = up;
24156 	/* Update header length */
24157 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24158 	return (mp);
24159 }
24160 
24161 /*
24162  * Delivery to local recipients including fanout to multiple recipients.
24163  * Does not do checksumming of UDP/TCP.
24164  * Note: q should be the read side queue for either the ill or conn.
24165  * Note: rq should be the read side q for the lower (ill) stream.
24166  * We don't send packets to IPPF processing, thus the last argument
24167  * to all the fanout calls are B_FALSE.
24168  */
24169 void
24170 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24171     int fanout_flags, zoneid_t zoneid)
24172 {
24173 	uint32_t	protocol;
24174 	mblk_t		*first_mp;
24175 	boolean_t	mctl_present;
24176 	int		ire_type;
24177 #define	rptr	((uchar_t *)ipha)
24178 
24179 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24180 	    "ip_wput_local_start: q %p", q);
24181 
24182 	if (ire != NULL) {
24183 		ire_type = ire->ire_type;
24184 	} else {
24185 		/*
24186 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24187 		 * packet is not multicast, we can't tell the ire type.
24188 		 */
24189 		ASSERT(CLASSD(ipha->ipha_dst));
24190 		ire_type = IRE_BROADCAST;
24191 	}
24192 
24193 	first_mp = mp;
24194 	if (first_mp->b_datap->db_type == M_CTL) {
24195 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24196 		if (!io->ipsec_out_secure) {
24197 			/*
24198 			 * This ipsec_out_t was allocated in ip_wput
24199 			 * for multicast packets to store the ill_index.
24200 			 * As this is being delivered locally, we don't
24201 			 * need this anymore.
24202 			 */
24203 			mp = first_mp->b_cont;
24204 			freeb(first_mp);
24205 			first_mp = mp;
24206 			mctl_present = B_FALSE;
24207 		} else {
24208 			/*
24209 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24210 			 * security properties for the looped-back packet.
24211 			 */
24212 			mctl_present = B_TRUE;
24213 			mp = first_mp->b_cont;
24214 			ASSERT(mp != NULL);
24215 			ipsec_out_to_in(first_mp);
24216 		}
24217 	} else {
24218 		mctl_present = B_FALSE;
24219 	}
24220 
24221 	DTRACE_PROBE4(ip4__loopback__in__start,
24222 	    ill_t *, ill, ill_t *, NULL,
24223 	    ipha_t *, ipha, mblk_t *, first_mp);
24224 
24225 	FW_HOOKS(ip4_loopback_in_event, ipv4firewall_loopback_in,
24226 	    ill, NULL, ipha, first_mp, mp);
24227 
24228 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24229 
24230 	if (first_mp == NULL)
24231 		return;
24232 
24233 	loopback_packets++;
24234 
24235 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24236 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24237 	if (!IS_SIMPLE_IPH(ipha)) {
24238 		ip_wput_local_options(ipha);
24239 	}
24240 
24241 	protocol = ipha->ipha_protocol;
24242 	switch (protocol) {
24243 	case IPPROTO_ICMP: {
24244 		ire_t		*ire_zone;
24245 		ilm_t		*ilm;
24246 		mblk_t		*mp1;
24247 		zoneid_t	last_zoneid;
24248 
24249 		if (CLASSD(ipha->ipha_dst) &&
24250 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
24251 			ASSERT(ire_type == IRE_BROADCAST);
24252 			/*
24253 			 * In the multicast case, applications may have joined
24254 			 * the group from different zones, so we need to deliver
24255 			 * the packet to each of them. Loop through the
24256 			 * multicast memberships structures (ilm) on the receive
24257 			 * ill and send a copy of the packet up each matching
24258 			 * one. However, we don't do this for multicasts sent on
24259 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24260 			 * they must stay in the sender's zone.
24261 			 *
24262 			 * ilm_add_v6() ensures that ilms in the same zone are
24263 			 * contiguous in the ill_ilm list. We use this property
24264 			 * to avoid sending duplicates needed when two
24265 			 * applications in the same zone join the same group on
24266 			 * different logical interfaces: we ignore the ilm if
24267 			 * it's zoneid is the same as the last matching one.
24268 			 * In addition, the sending of the packet for
24269 			 * ire_zoneid is delayed until all of the other ilms
24270 			 * have been exhausted.
24271 			 */
24272 			last_zoneid = -1;
24273 			ILM_WALKER_HOLD(ill);
24274 			for (ilm = ill->ill_ilm; ilm != NULL;
24275 			    ilm = ilm->ilm_next) {
24276 				if ((ilm->ilm_flags & ILM_DELETED) ||
24277 				    ipha->ipha_dst != ilm->ilm_addr ||
24278 				    ilm->ilm_zoneid == last_zoneid ||
24279 				    ilm->ilm_zoneid == zoneid ||
24280 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24281 					continue;
24282 				mp1 = ip_copymsg(first_mp);
24283 				if (mp1 == NULL)
24284 					continue;
24285 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24286 				    mctl_present, B_FALSE, ill,
24287 				    ilm->ilm_zoneid);
24288 				last_zoneid = ilm->ilm_zoneid;
24289 			}
24290 			ILM_WALKER_RELE(ill);
24291 			/*
24292 			 * Loopback case: the sending endpoint has
24293 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24294 			 * dispatch the multicast packet to the sending zone.
24295 			 */
24296 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24297 				freemsg(first_mp);
24298 				return;
24299 			}
24300 		} else if (ire_type == IRE_BROADCAST) {
24301 			/*
24302 			 * In the broadcast case, there may be many zones
24303 			 * which need a copy of the packet delivered to them.
24304 			 * There is one IRE_BROADCAST per broadcast address
24305 			 * and per zone; we walk those using a helper function.
24306 			 * In addition, the sending of the packet for zoneid is
24307 			 * delayed until all of the other ires have been
24308 			 * processed.
24309 			 */
24310 			IRB_REFHOLD(ire->ire_bucket);
24311 			ire_zone = NULL;
24312 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24313 			    ire)) != NULL) {
24314 				mp1 = ip_copymsg(first_mp);
24315 				if (mp1 == NULL)
24316 					continue;
24317 
24318 				UPDATE_IB_PKT_COUNT(ire_zone);
24319 				ire_zone->ire_last_used_time = lbolt;
24320 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24321 				    mctl_present, B_FALSE, ill,
24322 				    ire_zone->ire_zoneid);
24323 			}
24324 			IRB_REFRELE(ire->ire_bucket);
24325 		}
24326 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
24327 		    0, mctl_present, B_FALSE, ill, zoneid);
24328 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24329 		    "ip_wput_local_end: q %p (%S)",
24330 		    q, "icmp");
24331 		return;
24332 	}
24333 	case IPPROTO_IGMP:
24334 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
24335 			/* Bad packet - discarded by igmp_input */
24336 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24337 			    "ip_wput_local_end: q %p (%S)",
24338 			    q, "igmp_input--bad packet");
24339 			if (mctl_present)
24340 				freeb(first_mp);
24341 			return;
24342 		}
24343 		/*
24344 		 * igmp_input() may have returned the pulled up message.
24345 		 * So first_mp and ipha need to be reinitialized.
24346 		 */
24347 		ipha = (ipha_t *)mp->b_rptr;
24348 		if (mctl_present)
24349 			first_mp->b_cont = mp;
24350 		else
24351 			first_mp = mp;
24352 		/* deliver to local raw users */
24353 		break;
24354 	case IPPROTO_ENCAP:
24355 		/*
24356 		 * This case is covered by either ip_fanout_proto, or by
24357 		 * the above security processing for self-tunneled packets.
24358 		 */
24359 		break;
24360 	case IPPROTO_UDP: {
24361 		uint16_t	*up;
24362 		uint32_t	ports;
24363 
24364 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
24365 		    UDP_PORTS_OFFSET);
24366 		/* Force a 'valid' checksum. */
24367 		up[3] = 0;
24368 
24369 		ports = *(uint32_t *)up;
24370 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24371 		    (ire_type == IRE_BROADCAST),
24372 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24373 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
24374 		    ill, zoneid);
24375 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24376 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24377 		return;
24378 	}
24379 	case IPPROTO_TCP: {
24380 
24381 		/*
24382 		 * For TCP, discard broadcast packets.
24383 		 */
24384 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24385 			freemsg(first_mp);
24386 			BUMP_MIB(&ip_mib, ipInDiscards);
24387 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24388 			return;
24389 		}
24390 
24391 		if (mp->b_datap->db_type == M_DATA) {
24392 			/*
24393 			 * M_DATA mblk, so init mblk (chain) for no struio().
24394 			 */
24395 			mblk_t	*mp1 = mp;
24396 
24397 			do
24398 				mp1->b_datap->db_struioflag = 0;
24399 			while ((mp1 = mp1->b_cont) != NULL);
24400 		}
24401 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24402 		    <= mp->b_wptr);
24403 		ip_fanout_tcp(q, first_mp, ill, ipha,
24404 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24405 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
24406 		    mctl_present, B_FALSE, zoneid);
24407 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24408 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24409 		return;
24410 	}
24411 	case IPPROTO_SCTP:
24412 	{
24413 		uint32_t	ports;
24414 
24415 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24416 		ip_fanout_sctp(first_mp, ill, ipha, ports,
24417 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24418 		    IP_FF_IP6INFO,
24419 		    mctl_present, B_FALSE, 0, zoneid);
24420 		return;
24421 	}
24422 
24423 	default:
24424 		break;
24425 	}
24426 	/*
24427 	 * Find a client for some other protocol.  We give
24428 	 * copies to multiple clients, if more than one is
24429 	 * bound.
24430 	 */
24431 	ip_fanout_proto(q, first_mp, ill, ipha,
24432 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
24433 	    mctl_present, B_FALSE, ill, zoneid);
24434 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24435 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
24436 #undef	rptr
24437 }
24438 
24439 /*
24440  * Update any source route, record route, or timestamp options.
24441  * Check that we are at end of strict source route.
24442  * The options have been sanity checked by ip_wput_options().
24443  */
24444 static void
24445 ip_wput_local_options(ipha_t *ipha)
24446 {
24447 	ipoptp_t	opts;
24448 	uchar_t		*opt;
24449 	uint8_t		optval;
24450 	uint8_t		optlen;
24451 	ipaddr_t	dst;
24452 	uint32_t	ts;
24453 	ire_t		*ire;
24454 	timestruc_t	now;
24455 
24456 	ip2dbg(("ip_wput_local_options\n"));
24457 	for (optval = ipoptp_first(&opts, ipha);
24458 	    optval != IPOPT_EOL;
24459 	    optval = ipoptp_next(&opts)) {
24460 		opt = opts.ipoptp_cur;
24461 		optlen = opts.ipoptp_len;
24462 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
24463 		switch (optval) {
24464 			uint32_t off;
24465 		case IPOPT_SSRR:
24466 		case IPOPT_LSRR:
24467 			off = opt[IPOPT_OFFSET];
24468 			off--;
24469 			if (optlen < IP_ADDR_LEN ||
24470 			    off > optlen - IP_ADDR_LEN) {
24471 				/* End of source route */
24472 				break;
24473 			}
24474 			/*
24475 			 * This will only happen if two consecutive entries
24476 			 * in the source route contains our address or if
24477 			 * it is a packet with a loose source route which
24478 			 * reaches us before consuming the whole source route
24479 			 */
24480 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
24481 			if (optval == IPOPT_SSRR) {
24482 				return;
24483 			}
24484 			/*
24485 			 * Hack: instead of dropping the packet truncate the
24486 			 * source route to what has been used by filling the
24487 			 * rest with IPOPT_NOP.
24488 			 */
24489 			opt[IPOPT_OLEN] = (uint8_t)off;
24490 			while (off < optlen) {
24491 				opt[off++] = IPOPT_NOP;
24492 			}
24493 			break;
24494 		case IPOPT_RR:
24495 			off = opt[IPOPT_OFFSET];
24496 			off--;
24497 			if (optlen < IP_ADDR_LEN ||
24498 			    off > optlen - IP_ADDR_LEN) {
24499 				/* No more room - ignore */
24500 				ip1dbg((
24501 				    "ip_wput_forward_options: end of RR\n"));
24502 				break;
24503 			}
24504 			dst = htonl(INADDR_LOOPBACK);
24505 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24506 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24507 			break;
24508 		case IPOPT_TS:
24509 			/* Insert timestamp if there is romm */
24510 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24511 			case IPOPT_TS_TSONLY:
24512 				off = IPOPT_TS_TIMELEN;
24513 				break;
24514 			case IPOPT_TS_PRESPEC:
24515 			case IPOPT_TS_PRESPEC_RFC791:
24516 				/* Verify that the address matched */
24517 				off = opt[IPOPT_OFFSET] - 1;
24518 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
24519 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
24520 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
24521 				if (ire == NULL) {
24522 					/* Not for us */
24523 					break;
24524 				}
24525 				ire_refrele(ire);
24526 				/* FALLTHRU */
24527 			case IPOPT_TS_TSANDADDR:
24528 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24529 				break;
24530 			default:
24531 				/*
24532 				 * ip_*put_options should have already
24533 				 * dropped this packet.
24534 				 */
24535 				cmn_err(CE_PANIC, "ip_wput_local_options: "
24536 				    "unknown IT - bug in ip_wput_options?\n");
24537 				return;	/* Keep "lint" happy */
24538 			}
24539 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
24540 				/* Increase overflow counter */
24541 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
24542 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
24543 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
24544 				    (off << 4);
24545 				break;
24546 			}
24547 			off = opt[IPOPT_OFFSET] - 1;
24548 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24549 			case IPOPT_TS_PRESPEC:
24550 			case IPOPT_TS_PRESPEC_RFC791:
24551 			case IPOPT_TS_TSANDADDR:
24552 				dst = htonl(INADDR_LOOPBACK);
24553 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24554 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24555 				/* FALLTHRU */
24556 			case IPOPT_TS_TSONLY:
24557 				off = opt[IPOPT_OFFSET] - 1;
24558 				/* Compute # of milliseconds since midnight */
24559 				gethrestime(&now);
24560 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
24561 				    now.tv_nsec / (NANOSEC / MILLISEC);
24562 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
24563 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
24564 				break;
24565 			}
24566 			break;
24567 		}
24568 	}
24569 }
24570 
24571 /*
24572  * Send out a multicast packet on interface ipif.
24573  * The sender does not have an conn.
24574  * Caller verifies that this isn't a PHYI_LOOPBACK.
24575  */
24576 void
24577 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
24578 {
24579 	ipha_t	*ipha;
24580 	ire_t	*ire;
24581 	ipaddr_t	dst;
24582 	mblk_t		*first_mp;
24583 
24584 	/* igmp_sendpkt always allocates a ipsec_out_t */
24585 	ASSERT(mp->b_datap->db_type == M_CTL);
24586 	ASSERT(!ipif->ipif_isv6);
24587 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
24588 
24589 	first_mp = mp;
24590 	mp = first_mp->b_cont;
24591 	ASSERT(mp->b_datap->db_type == M_DATA);
24592 	ipha = (ipha_t *)mp->b_rptr;
24593 
24594 	/*
24595 	 * Find an IRE which matches the destination and the outgoing
24596 	 * queue (i.e. the outgoing interface.)
24597 	 */
24598 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
24599 		dst = ipif->ipif_pp_dst_addr;
24600 	else
24601 		dst = ipha->ipha_dst;
24602 	/*
24603 	 * The source address has already been initialized by the
24604 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
24605 	 * be sufficient rather than MATCH_IRE_IPIF.
24606 	 *
24607 	 * This function is used for sending IGMP packets. We need
24608 	 * to make sure that we send the packet out of the interface
24609 	 * (ipif->ipif_ill) where we joined the group. This is to
24610 	 * prevent from switches doing IGMP snooping to send us multicast
24611 	 * packets for a given group on the interface we have joined.
24612 	 * If we can't find an ire, igmp_sendpkt has already initialized
24613 	 * ipsec_out_attach_if so that this will not be load spread in
24614 	 * ip_newroute_ipif.
24615 	 */
24616 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
24617 	    MATCH_IRE_ILL);
24618 	if (!ire) {
24619 		/*
24620 		 * Mark this packet to make it be delivered to
24621 		 * ip_wput_ire after the new ire has been
24622 		 * created.
24623 		 */
24624 		mp->b_prev = NULL;
24625 		mp->b_next = NULL;
24626 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
24627 		    zoneid);
24628 		return;
24629 	}
24630 
24631 	/*
24632 	 * Honor the RTF_SETSRC flag; this is the only case
24633 	 * where we force this addr whatever the current src addr is,
24634 	 * because this address is set by igmp_sendpkt(), and
24635 	 * cannot be specified by any user.
24636 	 */
24637 	if (ire->ire_flags & RTF_SETSRC) {
24638 		ipha->ipha_src = ire->ire_src_addr;
24639 	}
24640 
24641 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
24642 }
24643 
24644 /*
24645  * NOTE : This function does not ire_refrele the ire argument passed in.
24646  *
24647  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
24648  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
24649  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
24650  * the ire_lock to access the nce_fp_mp in this case.
24651  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
24652  * prepending a fastpath message IPQoS processing must precede it, we also set
24653  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
24654  * (IPQoS might have set the b_band for CoS marking).
24655  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
24656  * must follow it so that IPQoS can mark the dl_priority field for CoS
24657  * marking, if needed.
24658  */
24659 static mblk_t *
24660 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
24661 {
24662 	uint_t	hlen;
24663 	ipha_t *ipha;
24664 	mblk_t *mp1;
24665 	boolean_t qos_done = B_FALSE;
24666 	uchar_t	*ll_hdr;
24667 
24668 #define	rptr	((uchar_t *)ipha)
24669 
24670 	ipha = (ipha_t *)mp->b_rptr;
24671 	hlen = 0;
24672 	LOCK_IRE_FP_MP(ire);
24673 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
24674 		ASSERT(DB_TYPE(mp1) == M_DATA);
24675 		/* Initiate IPPF processing */
24676 		if ((proc != 0) && IPP_ENABLED(proc)) {
24677 			UNLOCK_IRE_FP_MP(ire);
24678 			ip_process(proc, &mp, ill_index);
24679 			if (mp == NULL)
24680 				return (NULL);
24681 
24682 			ipha = (ipha_t *)mp->b_rptr;
24683 			LOCK_IRE_FP_MP(ire);
24684 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
24685 				qos_done = B_TRUE;
24686 				goto no_fp_mp;
24687 			}
24688 			ASSERT(DB_TYPE(mp1) == M_DATA);
24689 		}
24690 		hlen = MBLKL(mp1);
24691 		/*
24692 		 * Check if we have enough room to prepend fastpath
24693 		 * header
24694 		 */
24695 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
24696 			ll_hdr = rptr - hlen;
24697 			bcopy(mp1->b_rptr, ll_hdr, hlen);
24698 			/*
24699 			 * Set the b_rptr to the start of the link layer
24700 			 * header
24701 			 */
24702 			mp->b_rptr = ll_hdr;
24703 			mp1 = mp;
24704 		} else {
24705 			mp1 = copyb(mp1);
24706 			if (mp1 == NULL)
24707 				goto unlock_err;
24708 			mp1->b_band = mp->b_band;
24709 			mp1->b_cont = mp;
24710 			/*
24711 			 * certain system generated traffic may not
24712 			 * have cred/label in ip header block. This
24713 			 * is true even for a labeled system. But for
24714 			 * labeled traffic, inherit the label in the
24715 			 * new header.
24716 			 */
24717 			if (DB_CRED(mp) != NULL)
24718 				mblk_setcred(mp1, DB_CRED(mp));
24719 			/*
24720 			 * XXX disable ICK_VALID and compute checksum
24721 			 * here; can happen if nce_fp_mp changes and
24722 			 * it can't be copied now due to insufficient
24723 			 * space. (unlikely, fp mp can change, but it
24724 			 * does not increase in length)
24725 			 */
24726 		}
24727 		UNLOCK_IRE_FP_MP(ire);
24728 	} else {
24729 no_fp_mp:
24730 		mp1 = copyb(ire->ire_nce->nce_res_mp);
24731 		if (mp1 == NULL) {
24732 unlock_err:
24733 			UNLOCK_IRE_FP_MP(ire);
24734 			freemsg(mp);
24735 			return (NULL);
24736 		}
24737 		UNLOCK_IRE_FP_MP(ire);
24738 		mp1->b_cont = mp;
24739 		/*
24740 		 * certain system generated traffic may not
24741 		 * have cred/label in ip header block. This
24742 		 * is true even for a labeled system. But for
24743 		 * labeled traffic, inherit the label in the
24744 		 * new header.
24745 		 */
24746 		if (DB_CRED(mp) != NULL)
24747 			mblk_setcred(mp1, DB_CRED(mp));
24748 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
24749 			ip_process(proc, &mp1, ill_index);
24750 			if (mp1 == NULL)
24751 				return (NULL);
24752 		}
24753 	}
24754 	return (mp1);
24755 #undef rptr
24756 }
24757 
24758 /*
24759  * Finish the outbound IPsec processing for an IPv6 packet. This function
24760  * is called from ipsec_out_process() if the IPsec packet was processed
24761  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24762  * asynchronously.
24763  */
24764 void
24765 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
24766     ire_t *ire_arg)
24767 {
24768 	in6_addr_t *v6dstp;
24769 	ire_t *ire;
24770 	mblk_t *mp;
24771 	ip6_t *ip6h1;
24772 	uint_t	ill_index;
24773 	ipsec_out_t *io;
24774 	boolean_t attach_if, hwaccel;
24775 	uint32_t flags = IP6_NO_IPPOLICY;
24776 	int match_flags;
24777 	zoneid_t zoneid;
24778 	boolean_t ill_need_rele = B_FALSE;
24779 	boolean_t ire_need_rele = B_FALSE;
24780 
24781 	mp = ipsec_mp->b_cont;
24782 	ip6h1 = (ip6_t *)mp->b_rptr;
24783 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24784 	ill_index = io->ipsec_out_ill_index;
24785 	if (io->ipsec_out_reachable) {
24786 		flags |= IPV6_REACHABILITY_CONFIRMATION;
24787 	}
24788 	attach_if = io->ipsec_out_attach_if;
24789 	hwaccel = io->ipsec_out_accelerated;
24790 	zoneid = io->ipsec_out_zoneid;
24791 	ASSERT(zoneid != ALL_ZONES);
24792 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24793 	/* Multicast addresses should have non-zero ill_index. */
24794 	v6dstp = &ip6h->ip6_dst;
24795 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
24796 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
24797 	ASSERT(!attach_if || ill_index != 0);
24798 	if (ill_index != 0) {
24799 		if (ill == NULL) {
24800 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
24801 			    B_TRUE);
24802 
24803 			/* Failure case frees things for us. */
24804 			if (ill == NULL)
24805 				return;
24806 
24807 			ill_need_rele = B_TRUE;
24808 		}
24809 		/*
24810 		 * If this packet needs to go out on a particular interface
24811 		 * honor it.
24812 		 */
24813 		if (attach_if) {
24814 			match_flags = MATCH_IRE_ILL;
24815 
24816 			/*
24817 			 * Check if we need an ire that will not be
24818 			 * looked up by anybody else i.e. HIDDEN.
24819 			 */
24820 			if (ill_is_probeonly(ill)) {
24821 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24822 			}
24823 		}
24824 	}
24825 	ASSERT(mp != NULL);
24826 
24827 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
24828 		boolean_t unspec_src;
24829 		ipif_t	*ipif;
24830 
24831 		/*
24832 		 * Use the ill_index to get the right ill.
24833 		 */
24834 		unspec_src = io->ipsec_out_unspec_src;
24835 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24836 		if (ipif == NULL) {
24837 			if (ill_need_rele)
24838 				ill_refrele(ill);
24839 			freemsg(ipsec_mp);
24840 			return;
24841 		}
24842 
24843 		if (ire_arg != NULL) {
24844 			ire = ire_arg;
24845 		} else {
24846 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24847 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24848 			ire_need_rele = B_TRUE;
24849 		}
24850 		if (ire != NULL) {
24851 			ipif_refrele(ipif);
24852 			/*
24853 			 * XXX Do the multicast forwarding now, as the IPSEC
24854 			 * processing has been done.
24855 			 */
24856 			goto send;
24857 		}
24858 
24859 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
24860 		mp->b_prev = NULL;
24861 		mp->b_next = NULL;
24862 
24863 		/*
24864 		 * If the IPsec packet was processed asynchronously,
24865 		 * drop it now.
24866 		 */
24867 		if (q == NULL) {
24868 			if (ill_need_rele)
24869 				ill_refrele(ill);
24870 			freemsg(ipsec_mp);
24871 			return;
24872 		}
24873 
24874 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
24875 		    unspec_src, zoneid);
24876 		ipif_refrele(ipif);
24877 	} else {
24878 		if (attach_if) {
24879 			ipif_t	*ipif;
24880 
24881 			ipif = ipif_get_next_ipif(NULL, ill);
24882 			if (ipif == NULL) {
24883 				if (ill_need_rele)
24884 					ill_refrele(ill);
24885 				freemsg(ipsec_mp);
24886 				return;
24887 			}
24888 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24889 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24890 			ire_need_rele = B_TRUE;
24891 			ipif_refrele(ipif);
24892 		} else {
24893 			if (ire_arg != NULL) {
24894 				ire = ire_arg;
24895 			} else {
24896 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
24897 				ire_need_rele = B_TRUE;
24898 			}
24899 		}
24900 		if (ire != NULL)
24901 			goto send;
24902 		/*
24903 		 * ire disappeared underneath.
24904 		 *
24905 		 * What we need to do here is the ip_newroute
24906 		 * logic to get the ire without doing the IPSEC
24907 		 * processing. Follow the same old path. But this
24908 		 * time, ip_wput or ire_add_then_send will call us
24909 		 * directly as all the IPSEC operations are done.
24910 		 */
24911 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
24912 		mp->b_prev = NULL;
24913 		mp->b_next = NULL;
24914 
24915 		/*
24916 		 * If the IPsec packet was processed asynchronously,
24917 		 * drop it now.
24918 		 */
24919 		if (q == NULL) {
24920 			if (ill_need_rele)
24921 				ill_refrele(ill);
24922 			freemsg(ipsec_mp);
24923 			return;
24924 		}
24925 
24926 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
24927 		    zoneid);
24928 	}
24929 	if (ill != NULL && ill_need_rele)
24930 		ill_refrele(ill);
24931 	return;
24932 send:
24933 	if (ill != NULL && ill_need_rele)
24934 		ill_refrele(ill);
24935 
24936 	/* Local delivery */
24937 	if (ire->ire_stq == NULL) {
24938 		ill_t	*out_ill;
24939 		ASSERT(q != NULL);
24940 
24941 		/* PFHooks: LOOPBACK_OUT */
24942 		out_ill = ire->ire_ipif->ipif_ill;
24943 
24944 		DTRACE_PROBE4(ip6__loopback__out__start,
24945 		    ill_t *, NULL, ill_t *, out_ill,
24946 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
24947 
24948 		FW_HOOKS6(ip6_loopback_out_event, ipv6firewall_loopback_out,
24949 		    NULL, out_ill, ip6h1, ipsec_mp, mp);
24950 
24951 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
24952 
24953 		if (ipsec_mp != NULL)
24954 			ip_wput_local_v6(RD(q), out_ill,
24955 			    ip6h, ipsec_mp, ire, 0);
24956 		if (ire_need_rele)
24957 			ire_refrele(ire);
24958 		return;
24959 	}
24960 	/*
24961 	 * Everything is done. Send it out on the wire.
24962 	 * We force the insertion of a fragment header using the
24963 	 * IPH_FRAG_HDR flag in two cases:
24964 	 * - after reception of an ICMPv6 "packet too big" message
24965 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
24966 	 * - for multirouted IPv6 packets, so that the receiver can
24967 	 *   discard duplicates according to their fragment identifier
24968 	 */
24969 	/* XXX fix flow control problems. */
24970 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
24971 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
24972 		if (hwaccel) {
24973 			/*
24974 			 * hardware acceleration does not handle these
24975 			 * "slow path" cases.
24976 			 */
24977 			/* IPsec KSTATS: should bump bean counter here. */
24978 			if (ire_need_rele)
24979 				ire_refrele(ire);
24980 			freemsg(ipsec_mp);
24981 			return;
24982 		}
24983 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
24984 		    (mp->b_cont ? msgdsize(mp) :
24985 		    mp->b_wptr - (uchar_t *)ip6h)) {
24986 			/* IPsec KSTATS: should bump bean counter here. */
24987 			ip0dbg(("Packet length mismatch: %d, %ld\n",
24988 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
24989 			    msgdsize(mp)));
24990 			if (ire_need_rele)
24991 				ire_refrele(ire);
24992 			freemsg(ipsec_mp);
24993 			return;
24994 		}
24995 		ASSERT(mp->b_prev == NULL);
24996 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
24997 		    ntohs(ip6h->ip6_plen) +
24998 		    IPV6_HDR_LEN, ire->ire_max_frag));
24999 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25000 		    ire->ire_max_frag);
25001 	} else {
25002 		UPDATE_OB_PKT_COUNT(ire);
25003 		ire->ire_last_used_time = lbolt;
25004 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25005 	}
25006 	if (ire_need_rele)
25007 		ire_refrele(ire);
25008 	freeb(ipsec_mp);
25009 }
25010 
25011 void
25012 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25013 {
25014 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25015 	da_ipsec_t *hada;	/* data attributes */
25016 	ill_t *ill = (ill_t *)q->q_ptr;
25017 
25018 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25019 
25020 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25021 		/* IPsec KSTATS: Bump lose counter here! */
25022 		freemsg(mp);
25023 		return;
25024 	}
25025 
25026 	/*
25027 	 * It's an IPsec packet that must be
25028 	 * accelerated by the Provider, and the
25029 	 * outbound ill is IPsec acceleration capable.
25030 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25031 	 * to the ill.
25032 	 * IPsec KSTATS: should bump packet counter here.
25033 	 */
25034 
25035 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25036 	if (hada_mp == NULL) {
25037 		/* IPsec KSTATS: should bump packet counter here. */
25038 		freemsg(mp);
25039 		return;
25040 	}
25041 
25042 	hada_mp->b_datap->db_type = M_CTL;
25043 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25044 	hada_mp->b_cont = mp;
25045 
25046 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25047 	bzero(hada, sizeof (da_ipsec_t));
25048 	hada->da_type = IPHADA_M_CTL;
25049 
25050 	putnext(q, hada_mp);
25051 }
25052 
25053 /*
25054  * Finish the outbound IPsec processing. This function is called from
25055  * ipsec_out_process() if the IPsec packet was processed
25056  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25057  * asynchronously.
25058  */
25059 void
25060 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25061     ire_t *ire_arg)
25062 {
25063 	uint32_t v_hlen_tos_len;
25064 	ipaddr_t	dst;
25065 	ipif_t	*ipif = NULL;
25066 	ire_t *ire;
25067 	ire_t *ire1 = NULL;
25068 	mblk_t *next_mp = NULL;
25069 	uint32_t max_frag;
25070 	boolean_t multirt_send = B_FALSE;
25071 	mblk_t *mp;
25072 	mblk_t *mp1;
25073 	ipha_t *ipha1;
25074 	uint_t	ill_index;
25075 	ipsec_out_t *io;
25076 	boolean_t attach_if;
25077 	int match_flags, offset;
25078 	irb_t *irb = NULL;
25079 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25080 	zoneid_t zoneid;
25081 	uint32_t cksum;
25082 	uint16_t *up;
25083 	ipxmit_state_t	pktxmit_state;
25084 #ifdef	_BIG_ENDIAN
25085 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25086 #else
25087 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25088 #endif
25089 
25090 	mp = ipsec_mp->b_cont;
25091 	ipha1 = (ipha_t *)mp->b_rptr;
25092 	ASSERT(mp != NULL);
25093 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25094 	dst = ipha->ipha_dst;
25095 
25096 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25097 	ill_index = io->ipsec_out_ill_index;
25098 	attach_if = io->ipsec_out_attach_if;
25099 	zoneid = io->ipsec_out_zoneid;
25100 	ASSERT(zoneid != ALL_ZONES);
25101 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25102 	if (ill_index != 0) {
25103 		if (ill == NULL) {
25104 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25105 			    ill_index, B_FALSE);
25106 
25107 			/* Failure case frees things for us. */
25108 			if (ill == NULL)
25109 				return;
25110 
25111 			ill_need_rele = B_TRUE;
25112 		}
25113 		/*
25114 		 * If this packet needs to go out on a particular interface
25115 		 * honor it.
25116 		 */
25117 		if (attach_if) {
25118 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25119 
25120 			/*
25121 			 * Check if we need an ire that will not be
25122 			 * looked up by anybody else i.e. HIDDEN.
25123 			 */
25124 			if (ill_is_probeonly(ill)) {
25125 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25126 			}
25127 		}
25128 	}
25129 
25130 	if (CLASSD(dst)) {
25131 		boolean_t conn_dontroute;
25132 		/*
25133 		 * Use the ill_index to get the right ipif.
25134 		 */
25135 		conn_dontroute = io->ipsec_out_dontroute;
25136 		if (ill_index == 0)
25137 			ipif = ipif_lookup_group(dst, zoneid);
25138 		else
25139 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25140 		if (ipif == NULL) {
25141 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25142 			    " multicast\n"));
25143 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
25144 			freemsg(ipsec_mp);
25145 			goto done;
25146 		}
25147 		/*
25148 		 * ipha_src has already been intialized with the
25149 		 * value of the ipif in ip_wput. All we need now is
25150 		 * an ire to send this downstream.
25151 		 */
25152 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25153 		    MBLK_GETLABEL(mp), match_flags);
25154 		if (ire != NULL) {
25155 			ill_t *ill1;
25156 			/*
25157 			 * Do the multicast forwarding now, as the IPSEC
25158 			 * processing has been done.
25159 			 */
25160 			if (ip_g_mrouter && !conn_dontroute &&
25161 			    (ill1 = ire_to_ill(ire))) {
25162 				if (ip_mforward(ill1, ipha, mp)) {
25163 					freemsg(ipsec_mp);
25164 					ip1dbg(("ip_wput_ipsec_out: mforward "
25165 					    "failed\n"));
25166 					ire_refrele(ire);
25167 					goto done;
25168 				}
25169 			}
25170 			goto send;
25171 		}
25172 
25173 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25174 		mp->b_prev = NULL;
25175 		mp->b_next = NULL;
25176 
25177 		/*
25178 		 * If the IPsec packet was processed asynchronously,
25179 		 * drop it now.
25180 		 */
25181 		if (q == NULL) {
25182 			freemsg(ipsec_mp);
25183 			goto done;
25184 		}
25185 
25186 		/*
25187 		 * We may be using a wrong ipif to create the ire.
25188 		 * But it is okay as the source address is assigned
25189 		 * for the packet already. Next outbound packet would
25190 		 * create the IRE with the right IPIF in ip_wput.
25191 		 *
25192 		 * Also handle RTF_MULTIRT routes.
25193 		 */
25194 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25195 		    zoneid);
25196 	} else {
25197 		if (attach_if) {
25198 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25199 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25200 		} else {
25201 			if (ire_arg != NULL) {
25202 				ire = ire_arg;
25203 				ire_need_rele = B_FALSE;
25204 			} else {
25205 				ire = ire_cache_lookup(dst, zoneid,
25206 				    MBLK_GETLABEL(mp));
25207 			}
25208 		}
25209 		if (ire != NULL) {
25210 			goto send;
25211 		}
25212 
25213 		/*
25214 		 * ire disappeared underneath.
25215 		 *
25216 		 * What we need to do here is the ip_newroute
25217 		 * logic to get the ire without doing the IPSEC
25218 		 * processing. Follow the same old path. But this
25219 		 * time, ip_wput or ire_add_then_put will call us
25220 		 * directly as all the IPSEC operations are done.
25221 		 */
25222 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25223 		mp->b_prev = NULL;
25224 		mp->b_next = NULL;
25225 
25226 		/*
25227 		 * If the IPsec packet was processed asynchronously,
25228 		 * drop it now.
25229 		 */
25230 		if (q == NULL) {
25231 			freemsg(ipsec_mp);
25232 			goto done;
25233 		}
25234 
25235 		/*
25236 		 * Since we're going through ip_newroute() again, we
25237 		 * need to make sure we don't:
25238 		 *
25239 		 *	1.) Trigger the ASSERT() with the ipha_ident
25240 		 *	    overloading.
25241 		 *	2.) Redo transport-layer checksumming, since we've
25242 		 *	    already done all that to get this far.
25243 		 *
25244 		 * The easiest way not do either of the above is to set
25245 		 * the ipha_ident field to IP_HDR_INCLUDED.
25246 		 */
25247 		ipha->ipha_ident = IP_HDR_INCLUDED;
25248 		ip_newroute(q, ipsec_mp, dst, NULL,
25249 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid);
25250 	}
25251 	goto done;
25252 send:
25253 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
25254 		/*
25255 		 * ESP NAT-Traversal packet.
25256 		 *
25257 		 * Just do software checksum for now.
25258 		 */
25259 
25260 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
25261 		IP_STAT(ip_out_sw_cksum);
25262 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
25263 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
25264 #define	iphs	((uint16_t *)ipha)
25265 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
25266 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
25267 		    IP_SIMPLE_HDR_LENGTH);
25268 #undef iphs
25269 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
25270 			cksum = 0xFFFF;
25271 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
25272 			if (mp1->b_wptr - mp1->b_rptr >=
25273 			    offset + sizeof (uint16_t)) {
25274 				up = (uint16_t *)(mp1->b_rptr + offset);
25275 				*up = cksum;
25276 				break;	/* out of for loop */
25277 			} else {
25278 				offset -= (mp->b_wptr - mp->b_rptr);
25279 			}
25280 	} /* Otherwise, just keep the all-zero checksum. */
25281 
25282 	if (ire->ire_stq == NULL) {
25283 		ill_t	*out_ill;
25284 		/*
25285 		 * Loopbacks go through ip_wput_local except for one case.
25286 		 * We come here if we generate a icmp_frag_needed message
25287 		 * after IPSEC processing is over. When this function calls
25288 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25289 		 * icmp_frag_needed. The message generated comes back here
25290 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25291 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25292 		 * source address as it is usually set in ip_wput_ire. As
25293 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25294 		 * and we end up here. We can't enter ip_wput_ire once the
25295 		 * IPSEC processing is over and hence we need to do it here.
25296 		 */
25297 		ASSERT(q != NULL);
25298 		UPDATE_OB_PKT_COUNT(ire);
25299 		ire->ire_last_used_time = lbolt;
25300 		if (ipha->ipha_src == 0)
25301 			ipha->ipha_src = ire->ire_src_addr;
25302 
25303 		/* PFHooks: LOOPBACK_OUT */
25304 		out_ill = ire->ire_ipif->ipif_ill;
25305 
25306 		DTRACE_PROBE4(ip4__loopback__out__start,
25307 		    ill_t *, NULL, ill_t *, out_ill,
25308 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25309 
25310 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
25311 		    NULL, out_ill, ipha1, ipsec_mp, mp);
25312 
25313 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25314 
25315 		if (ipsec_mp != NULL)
25316 			ip_wput_local(RD(q), out_ill,
25317 			    ipha, ipsec_mp, ire, 0, zoneid);
25318 		if (ire_need_rele)
25319 			ire_refrele(ire);
25320 		goto done;
25321 	}
25322 
25323 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25324 		/*
25325 		 * We are through with IPSEC processing.
25326 		 * Fragment this and send it on the wire.
25327 		 */
25328 		if (io->ipsec_out_accelerated) {
25329 			/*
25330 			 * The packet has been accelerated but must
25331 			 * be fragmented. This should not happen
25332 			 * since AH and ESP must not accelerate
25333 			 * packets that need fragmentation, however
25334 			 * the configuration could have changed
25335 			 * since the AH or ESP processing.
25336 			 * Drop packet.
25337 			 * IPsec KSTATS: bump bean counter here.
25338 			 */
25339 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25340 			    "fragmented accelerated packet!\n"));
25341 			freemsg(ipsec_mp);
25342 		} else {
25343 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid);
25344 		}
25345 		if (ire_need_rele)
25346 			ire_refrele(ire);
25347 		goto done;
25348 	}
25349 
25350 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25351 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25352 	    (void *)ire->ire_ipif, (void *)ipif));
25353 
25354 	/*
25355 	 * Multiroute the secured packet, unless IPsec really
25356 	 * requires the packet to go out only through a particular
25357 	 * interface.
25358 	 */
25359 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
25360 		ire_t *first_ire;
25361 		irb = ire->ire_bucket;
25362 		ASSERT(irb != NULL);
25363 		/*
25364 		 * This ire has been looked up as the one that
25365 		 * goes through the given ipif;
25366 		 * make sure we do not omit any other multiroute ire
25367 		 * that may be present in the bucket before this one.
25368 		 */
25369 		IRB_REFHOLD(irb);
25370 		for (first_ire = irb->irb_ire;
25371 		    first_ire != NULL;
25372 		    first_ire = first_ire->ire_next) {
25373 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25374 			    (first_ire->ire_addr == ire->ire_addr) &&
25375 			    !(first_ire->ire_marks &
25376 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
25377 				break;
25378 		}
25379 
25380 		if ((first_ire != NULL) && (first_ire != ire)) {
25381 			/*
25382 			 * Don't change the ire if the packet must
25383 			 * be fragmented if sent via this new one.
25384 			 */
25385 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25386 				IRE_REFHOLD(first_ire);
25387 				if (ire_need_rele)
25388 					ire_refrele(ire);
25389 				else
25390 					ire_need_rele = B_TRUE;
25391 				ire = first_ire;
25392 			}
25393 		}
25394 		IRB_REFRELE(irb);
25395 
25396 		multirt_send = B_TRUE;
25397 		max_frag = ire->ire_max_frag;
25398 	} else {
25399 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
25400 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25401 			    "flag, attach_if %d\n", attach_if));
25402 		}
25403 	}
25404 
25405 	/*
25406 	 * In most cases, the emission loop below is entered only once.
25407 	 * Only in the case where the ire holds the RTF_MULTIRT
25408 	 * flag, we loop to process all RTF_MULTIRT ires in the
25409 	 * bucket, and send the packet through all crossed
25410 	 * RTF_MULTIRT routes.
25411 	 */
25412 	do {
25413 		if (multirt_send) {
25414 			/*
25415 			 * ire1 holds here the next ire to process in the
25416 			 * bucket. If multirouting is expected,
25417 			 * any non-RTF_MULTIRT ire that has the
25418 			 * right destination address is ignored.
25419 			 */
25420 			ASSERT(irb != NULL);
25421 			IRB_REFHOLD(irb);
25422 			for (ire1 = ire->ire_next;
25423 			    ire1 != NULL;
25424 			    ire1 = ire1->ire_next) {
25425 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
25426 					continue;
25427 				if (ire1->ire_addr != ire->ire_addr)
25428 					continue;
25429 				if (ire1->ire_marks &
25430 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
25431 					continue;
25432 				/* No loopback here */
25433 				if (ire1->ire_stq == NULL)
25434 					continue;
25435 				/*
25436 				 * Ensure we do not exceed the MTU
25437 				 * of the next route.
25438 				 */
25439 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
25440 					ip_multirt_bad_mtu(ire1, max_frag);
25441 					continue;
25442 				}
25443 
25444 				IRE_REFHOLD(ire1);
25445 				break;
25446 			}
25447 			IRB_REFRELE(irb);
25448 			if (ire1 != NULL) {
25449 				/*
25450 				 * We are in a multiple send case, need to
25451 				 * make a copy of the packet.
25452 				 */
25453 				next_mp = copymsg(ipsec_mp);
25454 				if (next_mp == NULL) {
25455 					ire_refrele(ire1);
25456 					ire1 = NULL;
25457 				}
25458 			}
25459 		}
25460 		/*
25461 		 * Everything is done. Send it out on the wire
25462 		 *
25463 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
25464 		 * either send it on the wire or, in the case of
25465 		 * HW acceleration, call ipsec_hw_putnext.
25466 		 */
25467 		if (ire->ire_nce &&
25468 		    ire->ire_nce->nce_state != ND_REACHABLE) {
25469 			DTRACE_PROBE2(ip__wput__ipsec__bail,
25470 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
25471 			/*
25472 			 * If ire's link-layer is unresolved (this
25473 			 * would only happen if the incomplete ire
25474 			 * was added to cachetable via forwarding path)
25475 			 * don't bother going to ip_xmit_v4. Just drop the
25476 			 * packet.
25477 			 * There is a slight risk here, in that, if we
25478 			 * have the forwarding path create an incomplete
25479 			 * IRE, then until the IRE is completed, any
25480 			 * transmitted IPSEC packets will be dropped
25481 			 * instead of being queued waiting for resolution.
25482 			 *
25483 			 * But the likelihood of a forwarding packet and a wput
25484 			 * packet sending to the same dst at the same time
25485 			 * and there not yet be an ARP entry for it is small.
25486 			 * Furthermore, if this actually happens, it might
25487 			 * be likely that wput would generate multiple
25488 			 * packets (and forwarding would also have a train
25489 			 * of packets) for that destination. If this is
25490 			 * the case, some of them would have been dropped
25491 			 * anyway, since ARP only queues a few packets while
25492 			 * waiting for resolution
25493 			 *
25494 			 * NOTE: We should really call ip_xmit_v4,
25495 			 * and let it queue the packet and send the
25496 			 * ARP query and have ARP come back thus:
25497 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
25498 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
25499 			 * hw accel work. But it's too complex to get
25500 			 * the IPsec hw  acceleration approach to fit
25501 			 * well with ip_xmit_v4 doing ARP without
25502 			 * doing IPSEC simplification. For now, we just
25503 			 * poke ip_xmit_v4 to trigger the arp resolve, so
25504 			 * that we can continue with the send on the next
25505 			 * attempt.
25506 			 *
25507 			 * XXX THis should be revisited, when
25508 			 * the IPsec/IP interaction is cleaned up
25509 			 */
25510 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
25511 			    " - dropping packet\n"));
25512 			freemsg(ipsec_mp);
25513 			/*
25514 			 * Call ip_xmit_v4() to trigger ARP query
25515 			 * in case the nce_state is ND_INITIAL
25516 			 */
25517 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
25518 			goto drop_pkt;
25519 		}
25520 
25521 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
25522 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
25523 		    mblk_t *, mp);
25524 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
25525 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp);
25526 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
25527 		if (mp == NULL)
25528 			goto drop_pkt;
25529 
25530 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
25531 		pktxmit_state = ip_xmit_v4(mp, ire,
25532 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
25533 
25534 		if ((pktxmit_state ==  SEND_FAILED) ||
25535 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
25536 
25537 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
25538 drop_pkt:
25539 			BUMP_MIB(&ip_mib, ipOutDiscards);
25540 			if (ire_need_rele)
25541 				ire_refrele(ire);
25542 			if (ire1 != NULL) {
25543 				ire_refrele(ire1);
25544 				freemsg(next_mp);
25545 			}
25546 			goto done;
25547 		}
25548 
25549 		freeb(ipsec_mp);
25550 		if (ire_need_rele)
25551 			ire_refrele(ire);
25552 
25553 		if (ire1 != NULL) {
25554 			ire = ire1;
25555 			ire_need_rele = B_TRUE;
25556 			ASSERT(next_mp);
25557 			ipsec_mp = next_mp;
25558 			mp = ipsec_mp->b_cont;
25559 			ire1 = NULL;
25560 			next_mp = NULL;
25561 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
25562 		} else {
25563 			multirt_send = B_FALSE;
25564 		}
25565 	} while (multirt_send);
25566 done:
25567 	if (ill != NULL && ill_need_rele)
25568 		ill_refrele(ill);
25569 	if (ipif != NULL)
25570 		ipif_refrele(ipif);
25571 }
25572 
25573 /*
25574  * Get the ill corresponding to the specified ire, and compare its
25575  * capabilities with the protocol and algorithms specified by the
25576  * the SA obtained from ipsec_out. If they match, annotate the
25577  * ipsec_out structure to indicate that the packet needs acceleration.
25578  *
25579  *
25580  * A packet is eligible for outbound hardware acceleration if the
25581  * following conditions are satisfied:
25582  *
25583  * 1. the packet will not be fragmented
25584  * 2. the provider supports the algorithm
25585  * 3. there is no pending control message being exchanged
25586  * 4. snoop is not attached
25587  * 5. the destination address is not a broadcast or multicast address.
25588  *
25589  * Rationale:
25590  *	- Hardware drivers do not support fragmentation with
25591  *	  the current interface.
25592  *	- snoop, multicast, and broadcast may result in exposure of
25593  *	  a cleartext datagram.
25594  * We check all five of these conditions here.
25595  *
25596  * XXX would like to nuke "ire_t *" parameter here; problem is that
25597  * IRE is only way to figure out if a v4 address is a broadcast and
25598  * thus ineligible for acceleration...
25599  */
25600 static void
25601 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
25602 {
25603 	ipsec_out_t *io;
25604 	mblk_t *data_mp;
25605 	uint_t plen, overhead;
25606 
25607 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
25608 		return;
25609 
25610 	if (ill == NULL)
25611 		return;
25612 
25613 	/*
25614 	 * Destination address is a broadcast or multicast.  Punt.
25615 	 */
25616 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
25617 	    IRE_LOCAL)))
25618 		return;
25619 
25620 	data_mp = ipsec_mp->b_cont;
25621 
25622 	if (ill->ill_isv6) {
25623 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
25624 
25625 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
25626 			return;
25627 
25628 		plen = ip6h->ip6_plen;
25629 	} else {
25630 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
25631 
25632 		if (CLASSD(ipha->ipha_dst))
25633 			return;
25634 
25635 		plen = ipha->ipha_length;
25636 	}
25637 	/*
25638 	 * Is there a pending DLPI control message being exchanged
25639 	 * between IP/IPsec and the DLS Provider? If there is, it
25640 	 * could be a SADB update, and the state of the DLS Provider
25641 	 * SADB might not be in sync with the SADB maintained by
25642 	 * IPsec. To avoid dropping packets or using the wrong keying
25643 	 * material, we do not accelerate this packet.
25644 	 */
25645 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
25646 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25647 		    "ill_dlpi_pending! don't accelerate packet\n"));
25648 		return;
25649 	}
25650 
25651 	/*
25652 	 * Is the Provider in promiscous mode? If it does, we don't
25653 	 * accelerate the packet since it will bounce back up to the
25654 	 * listeners in the clear.
25655 	 */
25656 	if (ill->ill_promisc_on_phys) {
25657 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25658 		    "ill in promiscous mode, don't accelerate packet\n"));
25659 		return;
25660 	}
25661 
25662 	/*
25663 	 * Will the packet require fragmentation?
25664 	 */
25665 
25666 	/*
25667 	 * IPsec ESP note: this is a pessimistic estimate, but the same
25668 	 * as is used elsewhere.
25669 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
25670 	 *	+ 2-byte trailer
25671 	 */
25672 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
25673 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
25674 
25675 	if ((plen + overhead) > ill->ill_max_mtu)
25676 		return;
25677 
25678 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25679 
25680 	/*
25681 	 * Can the ill accelerate this IPsec protocol and algorithm
25682 	 * specified by the SA?
25683 	 */
25684 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
25685 	    ill->ill_isv6, sa)) {
25686 		return;
25687 	}
25688 
25689 	/*
25690 	 * Tell AH or ESP that the outbound ill is capable of
25691 	 * accelerating this packet.
25692 	 */
25693 	io->ipsec_out_is_capab_ill = B_TRUE;
25694 }
25695 
25696 /*
25697  * Select which AH & ESP SA's to use (if any) for the outbound packet.
25698  *
25699  * If this function returns B_TRUE, the requested SA's have been filled
25700  * into the ipsec_out_*_sa pointers.
25701  *
25702  * If the function returns B_FALSE, the packet has been "consumed", most
25703  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
25704  *
25705  * The SA references created by the protocol-specific "select"
25706  * function will be released when the ipsec_mp is freed, thanks to the
25707  * ipsec_out_free destructor -- see spd.c.
25708  */
25709 static boolean_t
25710 ipsec_out_select_sa(mblk_t *ipsec_mp)
25711 {
25712 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
25713 	ipsec_out_t *io;
25714 	ipsec_policy_t *pp;
25715 	ipsec_action_t *ap;
25716 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25717 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25718 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25719 
25720 	if (!io->ipsec_out_secure) {
25721 		/*
25722 		 * We came here by mistake.
25723 		 * Don't bother with ipsec processing
25724 		 * We should "discourage" this path in the future.
25725 		 */
25726 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25727 		return (B_FALSE);
25728 	}
25729 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25730 	ASSERT((io->ipsec_out_policy != NULL) ||
25731 	    (io->ipsec_out_act != NULL));
25732 
25733 	ASSERT(io->ipsec_out_failed == B_FALSE);
25734 
25735 	/*
25736 	 * IPSEC processing has started.
25737 	 */
25738 	io->ipsec_out_proc_begin = B_TRUE;
25739 	ap = io->ipsec_out_act;
25740 	if (ap == NULL) {
25741 		pp = io->ipsec_out_policy;
25742 		ASSERT(pp != NULL);
25743 		ap = pp->ipsp_act;
25744 		ASSERT(ap != NULL);
25745 	}
25746 
25747 	/*
25748 	 * We have an action.  now, let's select SA's.
25749 	 * (In the future, we can cache this in the conn_t..)
25750 	 */
25751 	if (ap->ipa_want_esp) {
25752 		if (io->ipsec_out_esp_sa == NULL) {
25753 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
25754 			    IPPROTO_ESP);
25755 		}
25756 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
25757 	}
25758 
25759 	if (ap->ipa_want_ah) {
25760 		if (io->ipsec_out_ah_sa == NULL) {
25761 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
25762 			    IPPROTO_AH);
25763 		}
25764 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
25765 		/*
25766 		 * The ESP and AH processing order needs to be preserved
25767 		 * when both protocols are required (ESP should be applied
25768 		 * before AH for an outbound packet). Force an ESP ACQUIRE
25769 		 * when both ESP and AH are required, and an AH ACQUIRE
25770 		 * is needed.
25771 		 */
25772 		if (ap->ipa_want_esp && need_ah_acquire)
25773 			need_esp_acquire = B_TRUE;
25774 	}
25775 
25776 	/*
25777 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
25778 	 * Release SAs that got referenced, but will not be used until we
25779 	 * acquire _all_ of the SAs we need.
25780 	 */
25781 	if (need_ah_acquire || need_esp_acquire) {
25782 		if (io->ipsec_out_ah_sa != NULL) {
25783 			IPSA_REFRELE(io->ipsec_out_ah_sa);
25784 			io->ipsec_out_ah_sa = NULL;
25785 		}
25786 		if (io->ipsec_out_esp_sa != NULL) {
25787 			IPSA_REFRELE(io->ipsec_out_esp_sa);
25788 			io->ipsec_out_esp_sa = NULL;
25789 		}
25790 
25791 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
25792 		return (B_FALSE);
25793 	}
25794 
25795 	return (B_TRUE);
25796 }
25797 
25798 /*
25799  * Process an IPSEC_OUT message and see what you can
25800  * do with it.
25801  * IPQoS Notes:
25802  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
25803  * IPSec.
25804  * XXX would like to nuke ire_t.
25805  * XXX ill_index better be "real"
25806  */
25807 void
25808 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
25809 {
25810 	ipsec_out_t *io;
25811 	ipsec_policy_t *pp;
25812 	ipsec_action_t *ap;
25813 	ipha_t *ipha;
25814 	ip6_t *ip6h;
25815 	mblk_t *mp;
25816 	ill_t *ill;
25817 	zoneid_t zoneid;
25818 	ipsec_status_t ipsec_rc;
25819 	boolean_t ill_need_rele = B_FALSE;
25820 
25821 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25822 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25823 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25824 	mp = ipsec_mp->b_cont;
25825 
25826 	/*
25827 	 * Initiate IPPF processing. We do it here to account for packets
25828 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
25829 	 * We can check for ipsec_out_proc_begin even for such packets, as
25830 	 * they will always be false (asserted below).
25831 	 */
25832 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
25833 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
25834 		    io->ipsec_out_ill_index : ill_index);
25835 		if (mp == NULL) {
25836 			ip2dbg(("ipsec_out_process: packet dropped "\
25837 			    "during IPPF processing\n"));
25838 			freeb(ipsec_mp);
25839 			BUMP_MIB(&ip_mib, ipOutDiscards);
25840 			return;
25841 		}
25842 	}
25843 
25844 	if (!io->ipsec_out_secure) {
25845 		/*
25846 		 * We came here by mistake.
25847 		 * Don't bother with ipsec processing
25848 		 * Should "discourage" this path in the future.
25849 		 */
25850 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25851 		goto done;
25852 	}
25853 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25854 	ASSERT((io->ipsec_out_policy != NULL) ||
25855 	    (io->ipsec_out_act != NULL));
25856 	ASSERT(io->ipsec_out_failed == B_FALSE);
25857 
25858 	if (!ipsec_loaded()) {
25859 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
25860 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25861 			BUMP_MIB(&ip_mib, ipOutDiscards);
25862 		} else {
25863 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
25864 		}
25865 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
25866 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
25867 		return;
25868 	}
25869 
25870 	/*
25871 	 * IPSEC processing has started.
25872 	 */
25873 	io->ipsec_out_proc_begin = B_TRUE;
25874 	ap = io->ipsec_out_act;
25875 	if (ap == NULL) {
25876 		pp = io->ipsec_out_policy;
25877 		ASSERT(pp != NULL);
25878 		ap = pp->ipsp_act;
25879 		ASSERT(ap != NULL);
25880 	}
25881 
25882 	/*
25883 	 * Save the outbound ill index. When the packet comes back
25884 	 * from IPsec, we make sure the ill hasn't changed or disappeared
25885 	 * before sending it the accelerated packet.
25886 	 */
25887 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
25888 		int ifindex;
25889 		ill = ire_to_ill(ire);
25890 		ifindex = ill->ill_phyint->phyint_ifindex;
25891 		io->ipsec_out_capab_ill_index = ifindex;
25892 	}
25893 
25894 	/*
25895 	 * The order of processing is first insert a IP header if needed.
25896 	 * Then insert the ESP header and then the AH header.
25897 	 */
25898 	if ((io->ipsec_out_se_done == B_FALSE) &&
25899 	    (ap->ipa_want_se)) {
25900 		/*
25901 		 * First get the outer IP header before sending
25902 		 * it to ESP.
25903 		 */
25904 		ipha_t *oipha, *iipha;
25905 		mblk_t *outer_mp, *inner_mp;
25906 
25907 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
25908 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
25909 			    "ipsec_out_process: "
25910 			    "Self-Encapsulation failed: Out of memory\n");
25911 			freemsg(ipsec_mp);
25912 			BUMP_MIB(&ip_mib, ipOutDiscards);
25913 			return;
25914 		}
25915 		inner_mp = ipsec_mp->b_cont;
25916 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
25917 		oipha = (ipha_t *)outer_mp->b_rptr;
25918 		iipha = (ipha_t *)inner_mp->b_rptr;
25919 		*oipha = *iipha;
25920 		outer_mp->b_wptr += sizeof (ipha_t);
25921 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
25922 		    sizeof (ipha_t));
25923 		oipha->ipha_protocol = IPPROTO_ENCAP;
25924 		oipha->ipha_version_and_hdr_length =
25925 		    IP_SIMPLE_HDR_VERSION;
25926 		oipha->ipha_hdr_checksum = 0;
25927 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
25928 		outer_mp->b_cont = inner_mp;
25929 		ipsec_mp->b_cont = outer_mp;
25930 
25931 		io->ipsec_out_se_done = B_TRUE;
25932 		io->ipsec_out_tunnel = B_TRUE;
25933 	}
25934 
25935 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
25936 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
25937 	    !ipsec_out_select_sa(ipsec_mp))
25938 		return;
25939 
25940 	/*
25941 	 * By now, we know what SA's to use.  Toss over to ESP & AH
25942 	 * to do the heavy lifting.
25943 	 */
25944 	zoneid = io->ipsec_out_zoneid;
25945 	ASSERT(zoneid != ALL_ZONES);
25946 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
25947 		ASSERT(io->ipsec_out_esp_sa != NULL);
25948 		io->ipsec_out_esp_done = B_TRUE;
25949 		/*
25950 		 * Note that since hw accel can only apply one transform,
25951 		 * not two, we skip hw accel for ESP if we also have AH
25952 		 * This is an design limitation of the interface
25953 		 * which should be revisited.
25954 		 */
25955 		ASSERT(ire != NULL);
25956 		if (io->ipsec_out_ah_sa == NULL) {
25957 			ill = (ill_t *)ire->ire_stq->q_ptr;
25958 			ipsec_out_is_accelerated(ipsec_mp,
25959 			    io->ipsec_out_esp_sa, ill, ire);
25960 		}
25961 
25962 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
25963 		switch (ipsec_rc) {
25964 		case IPSEC_STATUS_SUCCESS:
25965 			break;
25966 		case IPSEC_STATUS_FAILED:
25967 			BUMP_MIB(&ip_mib, ipOutDiscards);
25968 			/* FALLTHRU */
25969 		case IPSEC_STATUS_PENDING:
25970 			return;
25971 		}
25972 	}
25973 
25974 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
25975 		ASSERT(io->ipsec_out_ah_sa != NULL);
25976 		io->ipsec_out_ah_done = B_TRUE;
25977 		if (ire == NULL) {
25978 			int idx = io->ipsec_out_capab_ill_index;
25979 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
25980 			    NULL, NULL, NULL, NULL);
25981 			ill_need_rele = B_TRUE;
25982 		} else {
25983 			ill = (ill_t *)ire->ire_stq->q_ptr;
25984 		}
25985 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
25986 		    ire);
25987 
25988 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
25989 		switch (ipsec_rc) {
25990 		case IPSEC_STATUS_SUCCESS:
25991 			break;
25992 		case IPSEC_STATUS_FAILED:
25993 			BUMP_MIB(&ip_mib, ipOutDiscards);
25994 			/* FALLTHRU */
25995 		case IPSEC_STATUS_PENDING:
25996 			if (ill != NULL && ill_need_rele)
25997 				ill_refrele(ill);
25998 			return;
25999 		}
26000 	}
26001 	/*
26002 	 * We are done with IPSEC processing. Send it over
26003 	 * the wire.
26004 	 */
26005 done:
26006 	mp = ipsec_mp->b_cont;
26007 	ipha = (ipha_t *)mp->b_rptr;
26008 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26009 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26010 	} else {
26011 		ip6h = (ip6_t *)ipha;
26012 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26013 	}
26014 	if (ill != NULL && ill_need_rele)
26015 		ill_refrele(ill);
26016 }
26017 
26018 /* ARGSUSED */
26019 void
26020 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26021 {
26022 	opt_restart_t	*or;
26023 	int	err;
26024 	conn_t	*connp;
26025 
26026 	ASSERT(CONN_Q(q));
26027 	connp = Q_TO_CONN(q);
26028 
26029 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26030 	or = (opt_restart_t *)first_mp->b_rptr;
26031 	/*
26032 	 * We don't need to pass any credentials here since this is just
26033 	 * a restart. The credentials are passed in when svr4_optcom_req
26034 	 * is called the first time (from ip_wput_nondata).
26035 	 */
26036 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26037 		err = svr4_optcom_req(q, first_mp, NULL,
26038 		    &ip_opt_obj);
26039 	} else {
26040 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26041 		err = tpi_optcom_req(q, first_mp, NULL,
26042 		    &ip_opt_obj);
26043 	}
26044 	if (err != EINPROGRESS) {
26045 		/* operation is done */
26046 		CONN_OPER_PENDING_DONE(connp);
26047 	}
26048 }
26049 
26050 /*
26051  * ioctls that go through a down/up sequence may need to wait for the down
26052  * to complete. This involves waiting for the ire and ipif refcnts to go down
26053  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26054  */
26055 /* ARGSUSED */
26056 void
26057 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26058 {
26059 	struct iocblk *iocp;
26060 	mblk_t *mp1;
26061 	ipif_t	*ipif;
26062 	ip_ioctl_cmd_t *ipip;
26063 	int err;
26064 	sin_t	*sin;
26065 	struct lifreq *lifr;
26066 	struct ifreq *ifr;
26067 
26068 	iocp = (struct iocblk *)mp->b_rptr;
26069 	ASSERT(ipsq != NULL);
26070 	/* Existence of mp1 verified in ip_wput_nondata */
26071 	mp1 = mp->b_cont->b_cont;
26072 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26073 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26074 		ill_t *ill;
26075 		/*
26076 		 * Special case where ipsq_current_ipif may not be set.
26077 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26078 		 * ill could also have become part of a ipmp group in the
26079 		 * process, we are here as were not able to complete the
26080 		 * operation in ipif_set_values because we could not become
26081 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26082 		 * will not be set so we need to set it.
26083 		 */
26084 		ill = (ill_t *)q->q_ptr;
26085 		ipsq->ipsq_current_ipif = ill->ill_ipif;
26086 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26087 	}
26088 
26089 	ipif = ipsq->ipsq_current_ipif;
26090 	ASSERT(ipif != NULL);
26091 	if (ipip->ipi_cmd_type == IF_CMD) {
26092 		/* This a old style SIOC[GS]IF* command */
26093 		ifr = (struct ifreq *)mp1->b_rptr;
26094 		sin = (sin_t *)&ifr->ifr_addr;
26095 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26096 		/* This a new style SIOC[GS]LIF* command */
26097 		lifr = (struct lifreq *)mp1->b_rptr;
26098 		sin = (sin_t *)&lifr->lifr_addr;
26099 	} else {
26100 		sin = NULL;
26101 	}
26102 
26103 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
26104 	    (void *)mp1->b_rptr);
26105 
26106 	/* SIOCLIFREMOVEIF could have removed the ipif */
26107 	ip_ioctl_finish(q, mp, err,
26108 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26109 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
26110 }
26111 
26112 /*
26113  * ioctl processing
26114  *
26115  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
26116  * the ioctl command in the ioctl tables and determines the copyin data size
26117  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
26118  * size.
26119  *
26120  * ioctl processing then continues when the M_IOCDATA makes its way down.
26121  * Now the ioctl is looked up again in the ioctl table, and its properties are
26122  * extracted. The associated 'conn' is then refheld till the end of the ioctl
26123  * and the general ioctl processing function ip_process_ioctl is called.
26124  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26125  * so goes thru the serialization primitive ipsq_try_enter. Then the
26126  * appropriate function to handle the ioctl is called based on the entry in
26127  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26128  * which also refreleases the 'conn' that was refheld at the start of the
26129  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26130  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
26131  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
26132  *
26133  * Many exclusive ioctls go thru an internal down up sequence as part of
26134  * the operation. For example an attempt to change the IP address of an
26135  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26136  * does all the cleanup such as deleting all ires that use this address.
26137  * Then we need to wait till all references to the interface go away.
26138  */
26139 void
26140 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26141 {
26142 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26143 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
26144 	cmd_info_t ci;
26145 	int err;
26146 	boolean_t entered_ipsq = B_FALSE;
26147 
26148 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26149 
26150 	if (ipip == NULL)
26151 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26152 
26153 	/*
26154 	 * SIOCLIFADDIF needs to go thru a special path since the
26155 	 * ill may not exist yet. This happens in the case of lo0
26156 	 * which is created using this ioctl.
26157 	 */
26158 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26159 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26160 		ip_ioctl_finish(q, mp, err,
26161 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26162 		    NULL, NULL);
26163 		return;
26164 	}
26165 
26166 	ci.ci_ipif = NULL;
26167 	switch (ipip->ipi_cmd_type) {
26168 	case IF_CMD:
26169 	case LIF_CMD:
26170 		/*
26171 		 * ioctls that pass in a [l]ifreq appear here.
26172 		 * ip_extract_lifreq_cmn returns a refheld ipif in
26173 		 * ci.ci_ipif
26174 		 */
26175 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
26176 		    ipip->ipi_flags, &ci, ip_process_ioctl);
26177 		if (err != 0) {
26178 			ip_ioctl_finish(q, mp, err,
26179 			    ipip->ipi_flags & IPI_GET_CMD ?
26180 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26181 			return;
26182 		}
26183 		ASSERT(ci.ci_ipif != NULL);
26184 		break;
26185 
26186 	case TUN_CMD:
26187 		/*
26188 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
26189 		 * a refheld ipif in ci.ci_ipif
26190 		 */
26191 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
26192 		if (err != 0) {
26193 			ip_ioctl_finish(q, mp, err,
26194 			    ipip->ipi_flags & IPI_GET_CMD ?
26195 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26196 			return;
26197 		}
26198 		ASSERT(ci.ci_ipif != NULL);
26199 		break;
26200 
26201 	case MISC_CMD:
26202 		/*
26203 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
26204 		 * For eg. SIOCGLIFCONF will appear here.
26205 		 */
26206 		switch (ipip->ipi_cmd) {
26207 		case IF_UNITSEL:
26208 			/* ioctl comes down the ill */
26209 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26210 			ipif_refhold(ci.ci_ipif);
26211 			break;
26212 		case SIOCGMSFILTER:
26213 		case SIOCSMSFILTER:
26214 		case SIOCGIPMSFILTER:
26215 		case SIOCSIPMSFILTER:
26216 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
26217 			    ip_process_ioctl);
26218 			if (err != 0) {
26219 				ip_ioctl_finish(q, mp, err,
26220 				    ipip->ipi_flags & IPI_GET_CMD ?
26221 				    COPYOUT : NO_COPYOUT, NULL, NULL);
26222 				return;
26223 			}
26224 			break;
26225 		}
26226 		err = 0;
26227 		ci.ci_sin = NULL;
26228 		ci.ci_sin6 = NULL;
26229 		ci.ci_lifr = NULL;
26230 		break;
26231 	}
26232 
26233 	/*
26234 	 * If ipsq is non-null, we are already being called exclusively
26235 	 */
26236 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26237 	if (!(ipip->ipi_flags & IPI_WR)) {
26238 		/*
26239 		 * A return value of EINPROGRESS means the ioctl is
26240 		 * either queued and waiting for some reason or has
26241 		 * already completed.
26242 		 */
26243 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26244 		    ci.ci_lifr);
26245 		if (ci.ci_ipif != NULL)
26246 			ipif_refrele(ci.ci_ipif);
26247 		ip_ioctl_finish(q, mp, err,
26248 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26249 		    NULL, NULL);
26250 		return;
26251 	}
26252 
26253 	ASSERT(ci.ci_ipif != NULL);
26254 
26255 	if (ipsq == NULL) {
26256 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26257 		    ip_process_ioctl, NEW_OP, B_TRUE);
26258 		entered_ipsq = B_TRUE;
26259 	}
26260 	/*
26261 	 * Release the ipif so that ipif_down and friends that wait for
26262 	 * references to go away are not misled about the current ipif_refcnt
26263 	 * values. We are writer so we can access the ipif even after releasing
26264 	 * the ipif.
26265 	 */
26266 	ipif_refrele(ci.ci_ipif);
26267 	if (ipsq == NULL)
26268 		return;
26269 
26270 	mutex_enter(&ipsq->ipsq_lock);
26271 	ASSERT(ipsq->ipsq_current_ipif == NULL);
26272 	ipsq->ipsq_current_ipif = ci.ci_ipif;
26273 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26274 	mutex_exit(&ipsq->ipsq_lock);
26275 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26276 	/*
26277 	 * For most set ioctls that come here, this serves as a single point
26278 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26279 	 * be any new references to the ipif. This helps functions that go
26280 	 * through this path and end up trying to wait for the refcnts
26281 	 * associated with the ipif to go down to zero. Some exceptions are
26282 	 * Failover, Failback, and Groupname commands that operate on more than
26283 	 * just the ci.ci_ipif. These commands internally determine the
26284 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26285 	 * flags on that set. Another exception is the Removeif command that
26286 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26287 	 * ipif to operate on.
26288 	 */
26289 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26290 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26291 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26292 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26293 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26294 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26295 
26296 	/*
26297 	 * A return value of EINPROGRESS means the ioctl is
26298 	 * either queued and waiting for some reason or has
26299 	 * already completed.
26300 	 */
26301 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26302 	    ci.ci_lifr);
26303 
26304 	/* SIOCLIFREMOVEIF could have removed the ipif */
26305 	ip_ioctl_finish(q, mp, err,
26306 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26307 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
26308 
26309 	if (entered_ipsq)
26310 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26311 }
26312 
26313 /*
26314  * Complete the ioctl. Typically ioctls use the mi package and need to
26315  * do mi_copyout/mi_copy_done.
26316  */
26317 void
26318 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
26319     ipif_t *ipif, ipsq_t *ipsq)
26320 {
26321 	conn_t	*connp = NULL;
26322 	hook_nic_event_t *info;
26323 
26324 	if (err == EINPROGRESS)
26325 		return;
26326 
26327 	if (CONN_Q(q)) {
26328 		connp = Q_TO_CONN(q);
26329 		ASSERT(connp->conn_ref >= 2);
26330 	}
26331 
26332 	switch (mode) {
26333 	case COPYOUT:
26334 		if (err == 0)
26335 			mi_copyout(q, mp);
26336 		else
26337 			mi_copy_done(q, mp, err);
26338 		break;
26339 
26340 	case NO_COPYOUT:
26341 		mi_copy_done(q, mp, err);
26342 		break;
26343 
26344 	default:
26345 		/* An ioctl aborted through a conn close would take this path */
26346 		break;
26347 	}
26348 
26349 	/*
26350 	 * The refhold placed at the start of the ioctl is released here.
26351 	 */
26352 	if (connp != NULL)
26353 		CONN_OPER_PENDING_DONE(connp);
26354 
26355 	/*
26356 	 * If the ioctl were an exclusive ioctl it would have set
26357 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
26358 	 */
26359 	if (ipif != NULL) {
26360 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
26361 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
26362 
26363 		/*
26364 		 * Unhook the nic event message from the ill and enqueue it into
26365 		 * the nic event taskq.
26366 		 */
26367 		if ((info = ipif->ipif_ill->ill_nic_event_info) != NULL) {
26368 			if (ddi_taskq_dispatch(eventq_queue_nic,
26369 			    ip_ne_queue_func, (void *)info, DDI_SLEEP)
26370 			    == DDI_FAILURE) {
26371 				ip2dbg(("ip_ioctl_finish: ddi_taskq_dispatch"
26372 				    "failed\n"));
26373 				if (info->hne_data != NULL)
26374 					kmem_free(info->hne_data,
26375 					    info->hne_datalen);
26376 				kmem_free(info, sizeof (hook_nic_event_t));
26377 			}
26378 
26379 			ipif->ipif_ill->ill_nic_event_info = NULL;
26380 		}
26381 
26382 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
26383 	}
26384 
26385 	/*
26386 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
26387 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
26388 	 * entering the ipsq
26389 	 */
26390 	if (ipsq != NULL) {
26391 		mutex_enter(&ipsq->ipsq_lock);
26392 		ipsq->ipsq_current_ipif = NULL;
26393 		mutex_exit(&ipsq->ipsq_lock);
26394 	}
26395 }
26396 
26397 /*
26398  * This is called from ip_wput_nondata to resume a deferred TCP bind.
26399  */
26400 /* ARGSUSED */
26401 void
26402 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
26403 {
26404 	conn_t *connp = arg;
26405 	tcp_t	*tcp;
26406 
26407 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
26408 	tcp = connp->conn_tcp;
26409 
26410 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
26411 		freemsg(mp);
26412 	else
26413 		tcp_rput_other(tcp, mp);
26414 	CONN_OPER_PENDING_DONE(connp);
26415 }
26416 
26417 /* Called from ip_wput for all non data messages */
26418 /* ARGSUSED */
26419 void
26420 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26421 {
26422 	mblk_t		*mp1;
26423 	ire_t		*ire, *fake_ire;
26424 	ill_t		*ill;
26425 	struct iocblk	*iocp;
26426 	ip_ioctl_cmd_t	*ipip;
26427 	cred_t		*cr;
26428 	conn_t		*connp = NULL;
26429 	int		cmd, err;
26430 	nce_t		*nce;
26431 	ipif_t		*ipif;
26432 
26433 	if (CONN_Q(q))
26434 		connp = Q_TO_CONN(q);
26435 
26436 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26437 
26438 	/* Check if it is a queue to /dev/sctp. */
26439 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26440 	    connp->conn_rq == NULL) {
26441 		sctp_wput(q, mp);
26442 		return;
26443 	}
26444 
26445 	switch (DB_TYPE(mp)) {
26446 	case M_IOCTL:
26447 		/*
26448 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26449 		 * will arrange to copy in associated control structures.
26450 		 */
26451 		ip_sioctl_copyin_setup(q, mp);
26452 		return;
26453 	case M_IOCDATA:
26454 		/*
26455 		 * Ensure that this is associated with one of our trans-
26456 		 * parent ioctls.  If it's not ours, discard it if we're
26457 		 * running as a driver, or pass it on if we're a module.
26458 		 */
26459 		iocp = (struct iocblk *)mp->b_rptr;
26460 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26461 		if (ipip == NULL) {
26462 			if (q->q_next == NULL) {
26463 				goto nak;
26464 			} else {
26465 				putnext(q, mp);
26466 			}
26467 			return;
26468 		} else if ((q->q_next != NULL) &&
26469 		    !(ipip->ipi_flags & IPI_MODOK)) {
26470 			/*
26471 			 * the ioctl is one we recognise, but is not
26472 			 * consumed by IP as a module, pass M_IOCDATA
26473 			 * for processing downstream, but only for
26474 			 * common Streams ioctls.
26475 			 */
26476 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26477 				putnext(q, mp);
26478 				return;
26479 			} else {
26480 				goto nak;
26481 			}
26482 		}
26483 
26484 		/* IOCTL continuation following copyin or copyout. */
26485 		if (mi_copy_state(q, mp, NULL) == -1) {
26486 			/*
26487 			 * The copy operation failed.  mi_copy_state already
26488 			 * cleaned up, so we're out of here.
26489 			 */
26490 			return;
26491 		}
26492 		/*
26493 		 * If we just completed a copy in, we become writer and
26494 		 * continue processing in ip_sioctl_copyin_done.  If it
26495 		 * was a copy out, we call mi_copyout again.  If there is
26496 		 * nothing more to copy out, it will complete the IOCTL.
26497 		 */
26498 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
26499 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
26500 				mi_copy_done(q, mp, EPROTO);
26501 				return;
26502 			}
26503 			/*
26504 			 * Check for cases that need more copying.  A return
26505 			 * value of 0 means a second copyin has been started,
26506 			 * so we return; a return value of 1 means no more
26507 			 * copying is needed, so we continue.
26508 			 */
26509 			cmd = iocp->ioc_cmd;
26510 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
26511 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
26512 			    MI_COPY_COUNT(mp) == 1) {
26513 				if (ip_copyin_msfilter(q, mp) == 0)
26514 					return;
26515 			}
26516 			/*
26517 			 * Refhold the conn, till the ioctl completes. This is
26518 			 * needed in case the ioctl ends up in the pending mp
26519 			 * list. Every mp in the ill_pending_mp list and
26520 			 * the ipsq_pending_mp must have a refhold on the conn
26521 			 * to resume processing. The refhold is released when
26522 			 * the ioctl completes. (normally or abnormally)
26523 			 * In all cases ip_ioctl_finish is called to finish
26524 			 * the ioctl.
26525 			 */
26526 			if (connp != NULL) {
26527 				/* This is not a reentry */
26528 				ASSERT(ipsq == NULL);
26529 				CONN_INC_REF(connp);
26530 			} else {
26531 				if (!(ipip->ipi_flags & IPI_MODOK)) {
26532 					mi_copy_done(q, mp, EINVAL);
26533 					return;
26534 				}
26535 			}
26536 
26537 			ip_process_ioctl(ipsq, q, mp, ipip);
26538 
26539 		} else {
26540 			mi_copyout(q, mp);
26541 		}
26542 		return;
26543 nak:
26544 		iocp->ioc_error = EINVAL;
26545 		mp->b_datap->db_type = M_IOCNAK;
26546 		iocp->ioc_count = 0;
26547 		qreply(q, mp);
26548 		return;
26549 
26550 	case M_IOCNAK:
26551 		/*
26552 		 * The only way we could get here is if a resolver didn't like
26553 		 * an IOCTL we sent it.	 This shouldn't happen.
26554 		 */
26555 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
26556 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
26557 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
26558 		freemsg(mp);
26559 		return;
26560 	case M_IOCACK:
26561 		/* Finish socket ioctls passed through to ARP. */
26562 		ip_sioctl_iocack(q, mp);
26563 		return;
26564 	case M_FLUSH:
26565 		if (*mp->b_rptr & FLUSHW)
26566 			flushq(q, FLUSHALL);
26567 		if (q->q_next) {
26568 			/*
26569 			 * M_FLUSH is sent up to IP by some drivers during
26570 			 * unbind. ip_rput has already replied to it. We are
26571 			 * here for the M_FLUSH that we originated in IP
26572 			 * before sending the unbind request to the driver.
26573 			 * Just free it as we don't queue packets in IP
26574 			 * on the write side of the device instance.
26575 			 */
26576 			freemsg(mp);
26577 			return;
26578 		}
26579 		if (*mp->b_rptr & FLUSHR) {
26580 			*mp->b_rptr &= ~FLUSHW;
26581 			qreply(q, mp);
26582 			return;
26583 		}
26584 		freemsg(mp);
26585 		return;
26586 	case IRE_DB_REQ_TYPE:
26587 		/* An Upper Level Protocol wants a copy of an IRE. */
26588 		ip_ire_req(q, mp);
26589 		return;
26590 	case M_CTL:
26591 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
26592 			break;
26593 
26594 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
26595 		    TUN_HELLO) {
26596 			ASSERT(connp != NULL);
26597 			connp->conn_flags |= IPCL_IPTUN;
26598 			freeb(mp);
26599 			return;
26600 		}
26601 
26602 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
26603 		    IP_ULP_OUT_LABELED) {
26604 			out_labeled_t *olp;
26605 
26606 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
26607 				break;
26608 			olp = (out_labeled_t *)mp->b_rptr;
26609 			connp->conn_ulp_labeled = olp->out_qnext == q;
26610 			freemsg(mp);
26611 			return;
26612 		}
26613 
26614 		/* M_CTL messages are used by ARP to tell us things. */
26615 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
26616 			break;
26617 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
26618 		case AR_ENTRY_SQUERY:
26619 			ip_wput_ctl(q, mp);
26620 			return;
26621 		case AR_CLIENT_NOTIFY:
26622 			ip_arp_news(q, mp);
26623 			return;
26624 		case AR_DLPIOP_DONE:
26625 			ASSERT(q->q_next != NULL);
26626 			ill = (ill_t *)q->q_ptr;
26627 			/* qwriter_ip releases the refhold */
26628 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
26629 			ill_refhold(ill);
26630 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
26631 			    CUR_OP, B_FALSE);
26632 			return;
26633 		case AR_ARP_CLOSING:
26634 			/*
26635 			 * ARP (above us) is closing. If no ARP bringup is
26636 			 * currently pending, ack the message so that ARP
26637 			 * can complete its close. Also mark ill_arp_closing
26638 			 * so that new ARP bringups will fail. If any
26639 			 * ARP bringup is currently in progress, we will
26640 			 * ack this when the current ARP bringup completes.
26641 			 */
26642 			ASSERT(q->q_next != NULL);
26643 			ill = (ill_t *)q->q_ptr;
26644 			mutex_enter(&ill->ill_lock);
26645 			ill->ill_arp_closing = 1;
26646 			if (!ill->ill_arp_bringup_pending) {
26647 				mutex_exit(&ill->ill_lock);
26648 				qreply(q, mp);
26649 			} else {
26650 				mutex_exit(&ill->ill_lock);
26651 				freemsg(mp);
26652 			}
26653 			return;
26654 		case AR_ARP_EXTEND:
26655 			/*
26656 			 * The ARP module above us is capable of duplicate
26657 			 * address detection.  Old ATM drivers will not send
26658 			 * this message.
26659 			 */
26660 			ASSERT(q->q_next != NULL);
26661 			ill = (ill_t *)q->q_ptr;
26662 			ill->ill_arp_extend = B_TRUE;
26663 			freemsg(mp);
26664 			return;
26665 		default:
26666 			break;
26667 		}
26668 		break;
26669 	case M_PROTO:
26670 	case M_PCPROTO:
26671 		/*
26672 		 * The only PROTO messages we expect are ULP binds and
26673 		 * copies of option negotiation acknowledgements.
26674 		 */
26675 		switch (((union T_primitives *)mp->b_rptr)->type) {
26676 		case O_T_BIND_REQ:
26677 		case T_BIND_REQ: {
26678 			/* Request can get queued in bind */
26679 			ASSERT(connp != NULL);
26680 			/*
26681 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
26682 			 * instead of going through this path.  We only get
26683 			 * here in the following cases:
26684 			 *
26685 			 * a. Bind retries, where ipsq is non-NULL.
26686 			 * b. T_BIND_REQ is issued from non TCP/UDP
26687 			 *    transport, e.g. icmp for raw socket,
26688 			 *    in which case ipsq will be NULL.
26689 			 */
26690 			ASSERT(ipsq != NULL ||
26691 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
26692 
26693 			/* Don't increment refcnt if this is a re-entry */
26694 			if (ipsq == NULL)
26695 				CONN_INC_REF(connp);
26696 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
26697 			    connp, NULL) : ip_bind_v4(q, mp, connp);
26698 			if (mp == NULL)
26699 				return;
26700 			if (IPCL_IS_TCP(connp)) {
26701 				/*
26702 				 * In the case of TCP endpoint we
26703 				 * come here only for bind retries
26704 				 */
26705 				ASSERT(ipsq != NULL);
26706 				CONN_INC_REF(connp);
26707 				squeue_fill(connp->conn_sqp, mp,
26708 				    ip_resume_tcp_bind, connp,
26709 				    SQTAG_BIND_RETRY);
26710 				return;
26711 			} else if (IPCL_IS_UDP(connp)) {
26712 				/*
26713 				 * In the case of UDP endpoint we
26714 				 * come here only for bind retries
26715 				 */
26716 				ASSERT(ipsq != NULL);
26717 				udp_resume_bind(connp, mp);
26718 				return;
26719 			}
26720 			qreply(q, mp);
26721 			CONN_OPER_PENDING_DONE(connp);
26722 			return;
26723 		}
26724 		case T_SVR4_OPTMGMT_REQ:
26725 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
26726 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
26727 
26728 			ASSERT(connp != NULL);
26729 			if (!snmpcom_req(q, mp, ip_snmp_set,
26730 			    ip_snmp_get, cr)) {
26731 				/*
26732 				 * Call svr4_optcom_req so that it can
26733 				 * generate the ack. We don't come here
26734 				 * if this operation is being restarted.
26735 				 * ip_restart_optmgmt will drop the conn ref.
26736 				 * In the case of ipsec option after the ipsec
26737 				 * load is complete conn_restart_ipsec_waiter
26738 				 * drops the conn ref.
26739 				 */
26740 				ASSERT(ipsq == NULL);
26741 				CONN_INC_REF(connp);
26742 				if (ip_check_for_ipsec_opt(q, mp))
26743 					return;
26744 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
26745 				if (err != EINPROGRESS) {
26746 					/* Operation is done */
26747 					CONN_OPER_PENDING_DONE(connp);
26748 				}
26749 			}
26750 			return;
26751 		case T_OPTMGMT_REQ:
26752 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
26753 			/*
26754 			 * Note: No snmpcom_req support through new
26755 			 * T_OPTMGMT_REQ.
26756 			 * Call tpi_optcom_req so that it can
26757 			 * generate the ack.
26758 			 */
26759 			ASSERT(connp != NULL);
26760 			ASSERT(ipsq == NULL);
26761 			/*
26762 			 * We don't come here for restart. ip_restart_optmgmt
26763 			 * will drop the conn ref. In the case of ipsec option
26764 			 * after the ipsec load is complete
26765 			 * conn_restart_ipsec_waiter drops the conn ref.
26766 			 */
26767 			CONN_INC_REF(connp);
26768 			if (ip_check_for_ipsec_opt(q, mp))
26769 				return;
26770 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
26771 			if (err != EINPROGRESS) {
26772 				/* Operation is done */
26773 				CONN_OPER_PENDING_DONE(connp);
26774 			}
26775 			return;
26776 		case T_UNBIND_REQ:
26777 			mp = ip_unbind(q, mp);
26778 			qreply(q, mp);
26779 			return;
26780 		default:
26781 			/*
26782 			 * Have to drop any DLPI messages coming down from
26783 			 * arp (such as an info_req which would cause ip
26784 			 * to receive an extra info_ack if it was passed
26785 			 * through.
26786 			 */
26787 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
26788 			    (int)*(uint_t *)mp->b_rptr));
26789 			freemsg(mp);
26790 			return;
26791 		}
26792 		/* NOTREACHED */
26793 	case IRE_DB_TYPE: {
26794 		nce_t		*nce;
26795 		ill_t		*ill;
26796 		in6_addr_t	gw_addr_v6;
26797 
26798 
26799 		/*
26800 		 * This is a response back from a resolver.  It
26801 		 * consists of a message chain containing:
26802 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
26803 		 * The IRE_MBLK is the one we allocated in ip_newroute.
26804 		 * The LL_HDR_MBLK is the DLPI header to use to get
26805 		 * the attached packet, and subsequent ones for the
26806 		 * same destination, transmitted.
26807 		 */
26808 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
26809 			break;
26810 		/*
26811 		 * First, check to make sure the resolution succeeded.
26812 		 * If it failed, the second mblk will be empty.
26813 		 * If it is, free the chain, dropping the packet.
26814 		 * (We must ire_delete the ire; that frees the ire mblk)
26815 		 * We're doing this now to support PVCs for ATM; it's
26816 		 * a partial xresolv implementation. When we fully implement
26817 		 * xresolv interfaces, instead of freeing everything here
26818 		 * we'll initiate neighbor discovery.
26819 		 *
26820 		 * For v4 (ARP and other external resolvers) the resolver
26821 		 * frees the message, so no check is needed. This check
26822 		 * is required, though, for a full xresolve implementation.
26823 		 * Including this code here now both shows how external
26824 		 * resolvers can NACK a resolution request using an
26825 		 * existing design that has no specific provisions for NACKs,
26826 		 * and also takes into account that the current non-ARP
26827 		 * external resolver has been coded to use this method of
26828 		 * NACKing for all IPv6 (xresolv) cases,
26829 		 * whether our xresolv implementation is complete or not.
26830 		 *
26831 		 */
26832 		ire = (ire_t *)mp->b_rptr;
26833 		ill = ire_to_ill(ire);
26834 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26835 		if (mp1->b_rptr == mp1->b_wptr) {
26836 			if (ire->ire_ipversion == IPV6_VERSION) {
26837 				/*
26838 				 * XRESOLV interface.
26839 				 */
26840 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
26841 				mutex_enter(&ire->ire_lock);
26842 				gw_addr_v6 = ire->ire_gateway_addr_v6;
26843 				mutex_exit(&ire->ire_lock);
26844 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26845 					nce = ndp_lookup_v6(ill,
26846 					    &ire->ire_addr_v6, B_FALSE);
26847 				} else {
26848 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
26849 					    B_FALSE);
26850 				}
26851 				if (nce != NULL) {
26852 					nce_resolv_failed(nce);
26853 					ndp_delete(nce);
26854 					NCE_REFRELE(nce);
26855 				}
26856 			}
26857 			mp->b_cont = NULL;
26858 			freemsg(mp1);		/* frees the pkt as well */
26859 			ASSERT(ire->ire_nce == NULL);
26860 			ire_delete((ire_t *)mp->b_rptr);
26861 			return;
26862 		}
26863 
26864 		/*
26865 		 * Split them into IRE_MBLK and pkt and feed it into
26866 		 * ire_add_then_send. Then in ire_add_then_send
26867 		 * the IRE will be added, and then the packet will be
26868 		 * run back through ip_wput. This time it will make
26869 		 * it to the wire.
26870 		 */
26871 		mp->b_cont = NULL;
26872 		mp = mp1->b_cont;		/* now, mp points to pkt */
26873 		mp1->b_cont = NULL;
26874 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
26875 		if (ire->ire_ipversion == IPV6_VERSION) {
26876 			/*
26877 			 * XRESOLV interface. Find the nce and put a copy
26878 			 * of the dl_unitdata_req in nce_res_mp
26879 			 */
26880 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
26881 			mutex_enter(&ire->ire_lock);
26882 			gw_addr_v6 = ire->ire_gateway_addr_v6;
26883 			mutex_exit(&ire->ire_lock);
26884 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26885 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
26886 				    B_FALSE);
26887 			} else {
26888 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
26889 			}
26890 			if (nce != NULL) {
26891 				/*
26892 				 * We have to protect nce_res_mp here
26893 				 * from being accessed by other threads
26894 				 * while we change the mblk pointer.
26895 				 * Other functions will also lock the nce when
26896 				 * accessing nce_res_mp.
26897 				 *
26898 				 * The reason we change the mblk pointer
26899 				 * here rather than copying the resolved address
26900 				 * into the template is that, unlike with
26901 				 * ethernet, we have no guarantee that the
26902 				 * resolved address length will be
26903 				 * smaller than or equal to the lla length
26904 				 * with which the template was allocated,
26905 				 * (for ethernet, they're equal)
26906 				 * so we have to use the actual resolved
26907 				 * address mblk - which holds the real
26908 				 * dl_unitdata_req with the resolved address.
26909 				 *
26910 				 * Doing this is the same behavior as was
26911 				 * previously used in the v4 ARP case.
26912 				 */
26913 				mutex_enter(&nce->nce_lock);
26914 				if (nce->nce_res_mp != NULL)
26915 					freemsg(nce->nce_res_mp);
26916 				nce->nce_res_mp = mp1;
26917 				mutex_exit(&nce->nce_lock);
26918 				/*
26919 				 * We do a fastpath probe here because
26920 				 * we have resolved the address without
26921 				 * using Neighbor Discovery.
26922 				 * In the non-XRESOLV v6 case, the fastpath
26923 				 * probe is done right after neighbor
26924 				 * discovery completes.
26925 				 */
26926 				if (nce->nce_res_mp != NULL) {
26927 					int res;
26928 					nce_fastpath_list_add(nce);
26929 					res = ill_fastpath_probe(ill,
26930 					    nce->nce_res_mp);
26931 					if (res != 0 && res != EAGAIN)
26932 						nce_fastpath_list_delete(nce);
26933 				}
26934 
26935 				ire_add_then_send(q, ire, mp);
26936 				/*
26937 				 * Now we have to clean out any packets
26938 				 * that may have been queued on the nce
26939 				 * while it was waiting for address resolution
26940 				 * to complete.
26941 				 */
26942 				mutex_enter(&nce->nce_lock);
26943 				mp1 = nce->nce_qd_mp;
26944 				nce->nce_qd_mp = NULL;
26945 				mutex_exit(&nce->nce_lock);
26946 				while (mp1 != NULL) {
26947 					mblk_t *nxt_mp;
26948 					queue_t *fwdq = NULL;
26949 					ill_t   *inbound_ill;
26950 					uint_t ifindex;
26951 
26952 					nxt_mp = mp1->b_next;
26953 					mp1->b_next = NULL;
26954 					/*
26955 					 * Retrieve ifindex stored in
26956 					 * ip_rput_data_v6()
26957 					 */
26958 					ifindex =
26959 					    (uint_t)(uintptr_t)mp1->b_prev;
26960 					inbound_ill =
26961 						ill_lookup_on_ifindex(ifindex,
26962 						    B_TRUE, NULL, NULL, NULL,
26963 						    NULL);
26964 					mp1->b_prev = NULL;
26965 					if (inbound_ill != NULL)
26966 						fwdq = inbound_ill->ill_rq;
26967 
26968 					if (fwdq != NULL) {
26969 						put(fwdq, mp1);
26970 						ill_refrele(inbound_ill);
26971 					} else
26972 						put(WR(ill->ill_rq), mp1);
26973 					mp1 = nxt_mp;
26974 				}
26975 				NCE_REFRELE(nce);
26976 			} else {	/* nce is NULL; clean up */
26977 				ire_delete(ire);
26978 				freemsg(mp);
26979 				freemsg(mp1);
26980 				return;
26981 			}
26982 		} else {
26983 			nce_t *arpce;
26984 			/*
26985 			 * Link layer resolution succeeded. Recompute the
26986 			 * ire_nce.
26987 			 */
26988 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
26989 			if ((arpce = ndp_lookup_v4(ill,
26990 			    (ire->ire_gateway_addr != INADDR_ANY ?
26991 			    &ire->ire_gateway_addr : &ire->ire_addr),
26992 			    B_FALSE)) == NULL) {
26993 				freeb(ire->ire_mp);
26994 				freeb(mp1);
26995 				freemsg(mp);
26996 				return;
26997 			}
26998 			mutex_enter(&arpce->nce_lock);
26999 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27000 			if (arpce->nce_state == ND_REACHABLE) {
27001 				/*
27002 				 * Someone resolved this before us;
27003 				 * cleanup the res_mp. Since ire has
27004 				 * not been added yet, the call to ire_add_v4
27005 				 * from ire_add_then_send (when a dup is
27006 				 * detected) will clean up the ire.
27007 				 */
27008 				freeb(mp1);
27009 			} else {
27010 				if (arpce->nce_res_mp != NULL)
27011 					freemsg(arpce->nce_res_mp);
27012 				arpce->nce_res_mp = mp1;
27013 				arpce->nce_state = ND_REACHABLE;
27014 			}
27015 			mutex_exit(&arpce->nce_lock);
27016 			if (ire->ire_marks & IRE_MARK_NOADD) {
27017 				/*
27018 				 * this ire will not be added to the ire
27019 				 * cache table, so we can set the ire_nce
27020 				 * here, as there are no atomicity constraints.
27021 				 */
27022 				ire->ire_nce = arpce;
27023 				/*
27024 				 * We are associating this nce with the ire
27025 				 * so change the nce ref taken in
27026 				 * ndp_lookup_v4() from
27027 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27028 				 */
27029 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27030 			} else {
27031 				NCE_REFRELE(arpce);
27032 			}
27033 			ire_add_then_send(q, ire, mp);
27034 		}
27035 		return;	/* All is well, the packet has been sent. */
27036 	}
27037 	case IRE_ARPRESOLVE_TYPE: {
27038 
27039 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27040 			break;
27041 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27042 		mp->b_cont = NULL;
27043 		/*
27044 		 * First, check to make sure the resolution succeeded.
27045 		 * If it failed, the second mblk will be empty.
27046 		 */
27047 		if (mp1->b_rptr == mp1->b_wptr) {
27048 			/* cleanup  the incomplete ire, free queued packets */
27049 			freemsg(mp); /* fake ire */
27050 			freeb(mp1);  /* dl_unitdata response */
27051 			return;
27052 		}
27053 
27054 		/*
27055 		 * update any incomplete nce_t found. we lookup the ctable
27056 		 * and find the nce from the ire->ire_nce because we need
27057 		 * to pass the ire to ip_xmit_v4 later, and can find both
27058 		 * ire and nce in one lookup from the ctable.
27059 		 */
27060 		fake_ire = (ire_t *)mp->b_rptr;
27061 		/*
27062 		 * By the time we come back here from ARP
27063 		 * the logical outgoing interface  of the incomplete ire
27064 		 * we added in ire_forward could have disappeared,
27065 		 * causing the incomplete ire to also have
27066 		 * dissapeared. So we need to retreive the
27067 		 * proper ipif for the ire  before looking
27068 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27069 		 */
27070 		ill = q->q_ptr;
27071 
27072 		/* Get the outgoing ipif */
27073 		mutex_enter(&ill->ill_lock);
27074 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27075 			mutex_exit(&ill->ill_lock);
27076 			freemsg(mp); /* fake ire */
27077 			freeb(mp1);  /* dl_unitdata response */
27078 			return;
27079 		}
27080 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27081 
27082 		if (ipif == NULL) {
27083 			mutex_exit(&ill->ill_lock);
27084 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27085 			freemsg(mp);
27086 			freeb(mp1);
27087 			return;
27088 		}
27089 		ipif_refhold_locked(ipif);
27090 		mutex_exit(&ill->ill_lock);
27091 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27092 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27093 		    ipif, fake_ire->ire_zoneid, NULL,
27094 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
27095 		ipif_refrele(ipif);
27096 		if (ire == NULL) {
27097 			/*
27098 			 * no ire was found; check if there is an nce
27099 			 * for this lookup; if it has no ire's pointing at it
27100 			 * cleanup.
27101 			 */
27102 			if ((nce = ndp_lookup_v4(ill,
27103 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27104 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27105 			    B_FALSE)) != NULL) {
27106 				/*
27107 				 * cleanup: just reset nce.
27108 				 * We check for refcnt 2 (one for the nce
27109 				 * hash list + 1 for the ref taken by
27110 				 * ndp_lookup_v4) to ensure that there are
27111 				 * no ire's pointing at the nce.
27112 				 */
27113 				if (nce->nce_refcnt == 2) {
27114 					nce = nce_reinit(nce);
27115 				}
27116 				if (nce != NULL)
27117 					NCE_REFRELE(nce);
27118 			}
27119 			freeb(mp1);  /* dl_unitdata response */
27120 			freemsg(mp); /* fake ire */
27121 			return;
27122 		}
27123 		nce = ire->ire_nce;
27124 		DTRACE_PROBE2(ire__arpresolve__type,
27125 		    ire_t *, ire, nce_t *, nce);
27126 		ASSERT(nce->nce_state != ND_INITIAL);
27127 		mutex_enter(&nce->nce_lock);
27128 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27129 		if (nce->nce_state == ND_REACHABLE) {
27130 			/*
27131 			 * Someone resolved this before us;
27132 			 * our response is not needed any more.
27133 			 */
27134 			mutex_exit(&nce->nce_lock);
27135 			freeb(mp1);  /* dl_unitdata response */
27136 		} else {
27137 			if (nce->nce_res_mp != NULL) {
27138 				freemsg(nce->nce_res_mp);
27139 				/* existing dl_unitdata template */
27140 			}
27141 			nce->nce_res_mp = mp1;
27142 			nce->nce_state = ND_REACHABLE;
27143 			mutex_exit(&nce->nce_lock);
27144 			ire_fastpath(ire);
27145 		}
27146 		/*
27147 		 * The cached nce_t has been updated to be reachable;
27148 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
27149 		 */
27150 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27151 		freemsg(mp);
27152 		/*
27153 		 * send out queued packets.
27154 		 */
27155 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27156 
27157 		IRE_REFRELE(ire);
27158 		return;
27159 	}
27160 	default:
27161 		break;
27162 	}
27163 	if (q->q_next) {
27164 		putnext(q, mp);
27165 	} else
27166 		freemsg(mp);
27167 }
27168 
27169 /*
27170  * Process IP options in an outbound packet.  Modify the destination if there
27171  * is a source route option.
27172  * Returns non-zero if something fails in which case an ICMP error has been
27173  * sent and mp freed.
27174  */
27175 static int
27176 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27177     boolean_t mctl_present, zoneid_t zoneid)
27178 {
27179 	ipoptp_t	opts;
27180 	uchar_t		*opt;
27181 	uint8_t		optval;
27182 	uint8_t		optlen;
27183 	ipaddr_t	dst;
27184 	intptr_t	code = 0;
27185 	mblk_t		*mp;
27186 	ire_t		*ire = NULL;
27187 
27188 	ip2dbg(("ip_wput_options\n"));
27189 	mp = ipsec_mp;
27190 	if (mctl_present) {
27191 		mp = ipsec_mp->b_cont;
27192 	}
27193 
27194 	dst = ipha->ipha_dst;
27195 	for (optval = ipoptp_first(&opts, ipha);
27196 	    optval != IPOPT_EOL;
27197 	    optval = ipoptp_next(&opts)) {
27198 		opt = opts.ipoptp_cur;
27199 		optlen = opts.ipoptp_len;
27200 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27201 		    optval, optlen));
27202 		switch (optval) {
27203 			uint32_t off;
27204 		case IPOPT_SSRR:
27205 		case IPOPT_LSRR:
27206 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27207 				ip1dbg((
27208 				    "ip_wput_options: bad option offset\n"));
27209 				code = (char *)&opt[IPOPT_OLEN] -
27210 				    (char *)ipha;
27211 				goto param_prob;
27212 			}
27213 			off = opt[IPOPT_OFFSET];
27214 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27215 			    ntohl(dst)));
27216 			/*
27217 			 * For strict: verify that dst is directly
27218 			 * reachable.
27219 			 */
27220 			if (optval == IPOPT_SSRR) {
27221 				ire = ire_ftable_lookup(dst, 0, 0,
27222 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27223 				    MBLK_GETLABEL(mp),
27224 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
27225 				if (ire == NULL) {
27226 					ip1dbg(("ip_wput_options: SSRR not"
27227 					    " directly reachable: 0x%x\n",
27228 					    ntohl(dst)));
27229 					goto bad_src_route;
27230 				}
27231 				ire_refrele(ire);
27232 			}
27233 			break;
27234 		case IPOPT_RR:
27235 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27236 				ip1dbg((
27237 				    "ip_wput_options: bad option offset\n"));
27238 				code = (char *)&opt[IPOPT_OLEN] -
27239 				    (char *)ipha;
27240 				goto param_prob;
27241 			}
27242 			break;
27243 		case IPOPT_TS:
27244 			/*
27245 			 * Verify that length >=5 and that there is either
27246 			 * room for another timestamp or that the overflow
27247 			 * counter is not maxed out.
27248 			 */
27249 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27250 			if (optlen < IPOPT_MINLEN_IT) {
27251 				goto param_prob;
27252 			}
27253 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27254 				ip1dbg((
27255 				    "ip_wput_options: bad option offset\n"));
27256 				code = (char *)&opt[IPOPT_OFFSET] -
27257 				    (char *)ipha;
27258 				goto param_prob;
27259 			}
27260 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27261 			case IPOPT_TS_TSONLY:
27262 				off = IPOPT_TS_TIMELEN;
27263 				break;
27264 			case IPOPT_TS_TSANDADDR:
27265 			case IPOPT_TS_PRESPEC:
27266 			case IPOPT_TS_PRESPEC_RFC791:
27267 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27268 				break;
27269 			default:
27270 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27271 				    (char *)ipha;
27272 				goto param_prob;
27273 			}
27274 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27275 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27276 				/*
27277 				 * No room and the overflow counter is 15
27278 				 * already.
27279 				 */
27280 				goto param_prob;
27281 			}
27282 			break;
27283 		}
27284 	}
27285 
27286 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27287 		return (0);
27288 
27289 	ip1dbg(("ip_wput_options: error processing IP options."));
27290 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27291 
27292 param_prob:
27293 	/*
27294 	 * Since ip_wput() isn't close to finished, we fill
27295 	 * in enough of the header for credible error reporting.
27296 	 */
27297 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27298 		/* Failed */
27299 		freemsg(ipsec_mp);
27300 		return (-1);
27301 	}
27302 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid);
27303 	return (-1);
27304 
27305 bad_src_route:
27306 	/*
27307 	 * Since ip_wput() isn't close to finished, we fill
27308 	 * in enough of the header for credible error reporting.
27309 	 */
27310 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27311 		/* Failed */
27312 		freemsg(ipsec_mp);
27313 		return (-1);
27314 	}
27315 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
27316 	return (-1);
27317 }
27318 
27319 /*
27320  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27321  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27322  * thru /etc/system.
27323  */
27324 #define	CONN_MAXDRAINCNT	64
27325 
27326 static void
27327 conn_drain_init(void)
27328 {
27329 	int i;
27330 
27331 	conn_drain_list_cnt = conn_drain_nthreads;
27332 
27333 	if ((conn_drain_list_cnt == 0) ||
27334 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27335 		/*
27336 		 * Default value of the number of drainers is the
27337 		 * number of cpus, subject to maximum of 8 drainers.
27338 		 */
27339 		if (boot_max_ncpus != -1)
27340 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27341 		else
27342 			conn_drain_list_cnt = MIN(max_ncpus, 8);
27343 	}
27344 
27345 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
27346 	    KM_SLEEP);
27347 
27348 	for (i = 0; i < conn_drain_list_cnt; i++) {
27349 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
27350 		    MUTEX_DEFAULT, NULL);
27351 	}
27352 }
27353 
27354 static void
27355 conn_drain_fini(void)
27356 {
27357 	int i;
27358 
27359 	for (i = 0; i < conn_drain_list_cnt; i++)
27360 		mutex_destroy(&conn_drain_list[i].idl_lock);
27361 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
27362 	conn_drain_list = NULL;
27363 }
27364 
27365 /*
27366  * Note: For an overview of how flowcontrol is handled in IP please see the
27367  * IP Flowcontrol notes at the top of this file.
27368  *
27369  * Flow control has blocked us from proceeding. Insert the given conn in one
27370  * of the conn drain lists. These conn wq's will be qenabled later on when
27371  * STREAMS flow control does a backenable. conn_walk_drain will enable
27372  * the first conn in each of these drain lists. Each of these qenabled conns
27373  * in turn enables the next in the list, after it runs, or when it closes,
27374  * thus sustaining the drain process.
27375  *
27376  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27377  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27378  * running at any time, on a given conn, since there can be only 1 service proc
27379  * running on a queue at any time.
27380  */
27381 void
27382 conn_drain_insert(conn_t *connp)
27383 {
27384 	idl_t	*idl;
27385 	uint_t	index;
27386 
27387 	mutex_enter(&connp->conn_lock);
27388 	if (connp->conn_state_flags & CONN_CLOSING) {
27389 		/*
27390 		 * The conn is closing as a result of which CONN_CLOSING
27391 		 * is set. Return.
27392 		 */
27393 		mutex_exit(&connp->conn_lock);
27394 		return;
27395 	} else if (connp->conn_idl == NULL) {
27396 		/*
27397 		 * Assign the next drain list round robin. We dont' use
27398 		 * a lock, and thus it may not be strictly round robin.
27399 		 * Atomicity of load/stores is enough to make sure that
27400 		 * conn_drain_list_index is always within bounds.
27401 		 */
27402 		index = conn_drain_list_index;
27403 		ASSERT(index < conn_drain_list_cnt);
27404 		connp->conn_idl = &conn_drain_list[index];
27405 		index++;
27406 		if (index == conn_drain_list_cnt)
27407 			index = 0;
27408 		conn_drain_list_index = index;
27409 	}
27410 	mutex_exit(&connp->conn_lock);
27411 
27412 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27413 	if ((connp->conn_drain_prev != NULL) ||
27414 	    (connp->conn_state_flags & CONN_CLOSING)) {
27415 		/*
27416 		 * The conn is already in the drain list, OR
27417 		 * the conn is closing. We need to check again for
27418 		 * the closing case again since close can happen
27419 		 * after we drop the conn_lock, and before we
27420 		 * acquire the CONN_DRAIN_LIST_LOCK.
27421 		 */
27422 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27423 		return;
27424 	} else {
27425 		idl = connp->conn_idl;
27426 	}
27427 
27428 	/*
27429 	 * The conn is not in the drain list. Insert it at the
27430 	 * tail of the drain list. The drain list is circular
27431 	 * and doubly linked. idl_conn points to the 1st element
27432 	 * in the list.
27433 	 */
27434 	if (idl->idl_conn == NULL) {
27435 		idl->idl_conn = connp;
27436 		connp->conn_drain_next = connp;
27437 		connp->conn_drain_prev = connp;
27438 	} else {
27439 		conn_t *head = idl->idl_conn;
27440 
27441 		connp->conn_drain_next = head;
27442 		connp->conn_drain_prev = head->conn_drain_prev;
27443 		head->conn_drain_prev->conn_drain_next = connp;
27444 		head->conn_drain_prev = connp;
27445 	}
27446 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27447 }
27448 
27449 /*
27450  * This conn is closing, and we are called from ip_close. OR
27451  * This conn has been serviced by ip_wsrv, and we need to do the tail
27452  * processing.
27453  * If this conn is part of the drain list, we may need to sustain the drain
27454  * process by qenabling the next conn in the drain list. We may also need to
27455  * remove this conn from the list, if it is done.
27456  */
27457 static void
27458 conn_drain_tail(conn_t *connp, boolean_t closing)
27459 {
27460 	idl_t *idl;
27461 
27462 	/*
27463 	 * connp->conn_idl is stable at this point, and no lock is needed
27464 	 * to check it. If we are called from ip_close, close has already
27465 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27466 	 * called us only because conn_idl is non-null. If we are called thru
27467 	 * service, conn_idl could be null, but it cannot change because
27468 	 * service is single-threaded per queue, and there cannot be another
27469 	 * instance of service trying to call conn_drain_insert on this conn
27470 	 * now.
27471 	 */
27472 	ASSERT(!closing || (connp->conn_idl != NULL));
27473 
27474 	/*
27475 	 * If connp->conn_idl is null, the conn has not been inserted into any
27476 	 * drain list even once since creation of the conn. Just return.
27477 	 */
27478 	if (connp->conn_idl == NULL)
27479 		return;
27480 
27481 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27482 
27483 	if (connp->conn_drain_prev == NULL) {
27484 		/* This conn is currently not in the drain list.  */
27485 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27486 		return;
27487 	}
27488 	idl = connp->conn_idl;
27489 	if (idl->idl_conn_draining == connp) {
27490 		/*
27491 		 * This conn is the current drainer. If this is the last conn
27492 		 * in the drain list, we need to do more checks, in the 'if'
27493 		 * below. Otherwwise we need to just qenable the next conn,
27494 		 * to sustain the draining, and is handled in the 'else'
27495 		 * below.
27496 		 */
27497 		if (connp->conn_drain_next == idl->idl_conn) {
27498 			/*
27499 			 * This conn is the last in this list. This round
27500 			 * of draining is complete. If idl_repeat is set,
27501 			 * it means another flow enabling has happened from
27502 			 * the driver/streams and we need to another round
27503 			 * of draining.
27504 			 * If there are more than 2 conns in the drain list,
27505 			 * do a left rotate by 1, so that all conns except the
27506 			 * conn at the head move towards the head by 1, and the
27507 			 * the conn at the head goes to the tail. This attempts
27508 			 * a more even share for all queues that are being
27509 			 * drained.
27510 			 */
27511 			if ((connp->conn_drain_next != connp) &&
27512 			    (idl->idl_conn->conn_drain_next != connp)) {
27513 				idl->idl_conn = idl->idl_conn->conn_drain_next;
27514 			}
27515 			if (idl->idl_repeat) {
27516 				qenable(idl->idl_conn->conn_wq);
27517 				idl->idl_conn_draining = idl->idl_conn;
27518 				idl->idl_repeat = 0;
27519 			} else {
27520 				idl->idl_conn_draining = NULL;
27521 			}
27522 		} else {
27523 			/*
27524 			 * If the next queue that we are now qenable'ing,
27525 			 * is closing, it will remove itself from this list
27526 			 * and qenable the subsequent queue in ip_close().
27527 			 * Serialization is acheived thru idl_lock.
27528 			 */
27529 			qenable(connp->conn_drain_next->conn_wq);
27530 			idl->idl_conn_draining = connp->conn_drain_next;
27531 		}
27532 	}
27533 	if (!connp->conn_did_putbq || closing) {
27534 		/*
27535 		 * Remove ourself from the drain list, if we did not do
27536 		 * a putbq, or if the conn is closing.
27537 		 * Note: It is possible that q->q_first is non-null. It means
27538 		 * that these messages landed after we did a enableok() in
27539 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
27540 		 * service them.
27541 		 */
27542 		if (connp->conn_drain_next == connp) {
27543 			/* Singleton in the list */
27544 			ASSERT(connp->conn_drain_prev == connp);
27545 			idl->idl_conn = NULL;
27546 			idl->idl_conn_draining = NULL;
27547 		} else {
27548 			connp->conn_drain_prev->conn_drain_next =
27549 			    connp->conn_drain_next;
27550 			connp->conn_drain_next->conn_drain_prev =
27551 			    connp->conn_drain_prev;
27552 			if (idl->idl_conn == connp)
27553 				idl->idl_conn = connp->conn_drain_next;
27554 			ASSERT(idl->idl_conn_draining != connp);
27555 
27556 		}
27557 		connp->conn_drain_next = NULL;
27558 		connp->conn_drain_prev = NULL;
27559 	}
27560 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27561 }
27562 
27563 /*
27564  * Write service routine. Shared perimeter entry point.
27565  * ip_wsrv can be called in any of the following ways.
27566  * 1. The device queue's messages has fallen below the low water mark
27567  *    and STREAMS has backenabled the ill_wq. We walk thru all the
27568  *    the drain lists and backenable the first conn in each list.
27569  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
27570  *    qenabled non-tcp upper layers. We start dequeing messages and call
27571  *    ip_wput for each message.
27572  */
27573 
27574 void
27575 ip_wsrv(queue_t *q)
27576 {
27577 	conn_t	*connp;
27578 	ill_t	*ill;
27579 	mblk_t	*mp;
27580 
27581 	if (q->q_next) {
27582 		ill = (ill_t *)q->q_ptr;
27583 		if (ill->ill_state_flags == 0) {
27584 			/*
27585 			 * The device flow control has opened up.
27586 			 * Walk through conn drain lists and qenable the
27587 			 * first conn in each list. This makes sense only
27588 			 * if the stream is fully plumbed and setup.
27589 			 * Hence the if check above.
27590 			 */
27591 			ip1dbg(("ip_wsrv: walking\n"));
27592 			conn_walk_drain();
27593 		}
27594 		return;
27595 	}
27596 
27597 	connp = Q_TO_CONN(q);
27598 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
27599 
27600 	/*
27601 	 * 1. Set conn_draining flag to signal that service is active.
27602 	 *
27603 	 * 2. ip_output determines whether it has been called from service,
27604 	 *    based on the last parameter. If it is IP_WSRV it concludes it
27605 	 *    has been called from service.
27606 	 *
27607 	 * 3. Message ordering is preserved by the following logic.
27608 	 *    i. A directly called ip_output (i.e. not thru service) will queue
27609 	 *    the message at the tail, if conn_draining is set (i.e. service
27610 	 *    is running) or if q->q_first is non-null.
27611 	 *
27612 	 *    ii. If ip_output is called from service, and if ip_output cannot
27613 	 *    putnext due to flow control, it does a putbq.
27614 	 *
27615 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
27616 	 *    (causing an infinite loop).
27617 	 */
27618 	ASSERT(!connp->conn_did_putbq);
27619 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
27620 		connp->conn_draining = 1;
27621 		noenable(q);
27622 		while ((mp = getq(q)) != NULL) {
27623 			ASSERT(CONN_Q(q));
27624 
27625 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
27626 			if (connp->conn_did_putbq) {
27627 				/* ip_wput did a putbq */
27628 				break;
27629 			}
27630 		}
27631 		/*
27632 		 * At this point, a thread coming down from top, calling
27633 		 * ip_wput, may end up queueing the message. We have not yet
27634 		 * enabled the queue, so ip_wsrv won't be called again.
27635 		 * To avoid this race, check q->q_first again (in the loop)
27636 		 * If the other thread queued the message before we call
27637 		 * enableok(), we will catch it in the q->q_first check.
27638 		 * If the other thread queues the message after we call
27639 		 * enableok(), ip_wsrv will be called again by STREAMS.
27640 		 */
27641 		connp->conn_draining = 0;
27642 		enableok(q);
27643 	}
27644 
27645 	/* Enable the next conn for draining */
27646 	conn_drain_tail(connp, B_FALSE);
27647 
27648 	connp->conn_did_putbq = 0;
27649 }
27650 
27651 /*
27652  * Walk the list of all conn's calling the function provided with the
27653  * specified argument for each.	 Note that this only walks conn's that
27654  * have been bound.
27655  * Applies to both IPv4 and IPv6.
27656  */
27657 static void
27658 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
27659 {
27660 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
27661 	    func, arg, zoneid);
27662 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
27663 	    func, arg, zoneid);
27664 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
27665 	    func, arg, zoneid);
27666 	conn_walk_fanout_table(ipcl_proto_fanout,
27667 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
27668 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
27669 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
27670 }
27671 
27672 /*
27673  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
27674  * of conns that need to be drained, check if drain is already in progress.
27675  * If so set the idl_repeat bit, indicating that the last conn in the list
27676  * needs to reinitiate the drain once again, for the list. If drain is not
27677  * in progress for the list, initiate the draining, by qenabling the 1st
27678  * conn in the list. The drain is self-sustaining, each qenabled conn will
27679  * in turn qenable the next conn, when it is done/blocked/closing.
27680  */
27681 static void
27682 conn_walk_drain(void)
27683 {
27684 	int i;
27685 	idl_t *idl;
27686 
27687 	IP_STAT(ip_conn_walk_drain);
27688 
27689 	for (i = 0; i < conn_drain_list_cnt; i++) {
27690 		idl = &conn_drain_list[i];
27691 		mutex_enter(&idl->idl_lock);
27692 		if (idl->idl_conn == NULL) {
27693 			mutex_exit(&idl->idl_lock);
27694 			continue;
27695 		}
27696 		/*
27697 		 * If this list is not being drained currently by
27698 		 * an ip_wsrv thread, start the process.
27699 		 */
27700 		if (idl->idl_conn_draining == NULL) {
27701 			ASSERT(idl->idl_repeat == 0);
27702 			qenable(idl->idl_conn->conn_wq);
27703 			idl->idl_conn_draining = idl->idl_conn;
27704 		} else {
27705 			idl->idl_repeat = 1;
27706 		}
27707 		mutex_exit(&idl->idl_lock);
27708 	}
27709 }
27710 
27711 /*
27712  * Walk an conn hash table of `count' buckets, calling func for each entry.
27713  */
27714 static void
27715 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
27716     zoneid_t zoneid)
27717 {
27718 	conn_t	*connp;
27719 
27720 	while (count-- > 0) {
27721 		mutex_enter(&connfp->connf_lock);
27722 		for (connp = connfp->connf_head; connp != NULL;
27723 		    connp = connp->conn_next) {
27724 			if (zoneid == GLOBAL_ZONEID ||
27725 			    zoneid == connp->conn_zoneid) {
27726 				CONN_INC_REF(connp);
27727 				mutex_exit(&connfp->connf_lock);
27728 				(*func)(connp, arg);
27729 				mutex_enter(&connfp->connf_lock);
27730 				CONN_DEC_REF(connp);
27731 			}
27732 		}
27733 		mutex_exit(&connfp->connf_lock);
27734 		connfp++;
27735 	}
27736 }
27737 
27738 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
27739 static void
27740 conn_report1(conn_t *connp, void *mp)
27741 {
27742 	char	buf1[INET6_ADDRSTRLEN];
27743 	char	buf2[INET6_ADDRSTRLEN];
27744 	uint_t	print_len, buf_len;
27745 
27746 	ASSERT(connp != NULL);
27747 
27748 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
27749 	if (buf_len <= 0)
27750 		return;
27751 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
27752 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
27753 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
27754 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
27755 	    "%5d %s/%05d %s/%05d\n",
27756 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
27757 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
27758 	    buf1, connp->conn_lport,
27759 	    buf2, connp->conn_fport);
27760 	if (print_len < buf_len) {
27761 		((mblk_t *)mp)->b_wptr += print_len;
27762 	} else {
27763 		((mblk_t *)mp)->b_wptr += buf_len;
27764 	}
27765 }
27766 
27767 /*
27768  * Named Dispatch routine to produce a formatted report on all conns
27769  * that are listed in one of the fanout tables.
27770  * This report is accessed by using the ndd utility to "get" ND variable
27771  * "ip_conn_status".
27772  */
27773 /* ARGSUSED */
27774 static int
27775 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
27776 {
27777 	(void) mi_mpprintf(mp,
27778 	    "CONN      " MI_COL_HDRPAD_STR
27779 	    "rfq      " MI_COL_HDRPAD_STR
27780 	    "stq      " MI_COL_HDRPAD_STR
27781 	    " zone local                 remote");
27782 
27783 	/*
27784 	 * Because of the ndd constraint, at most we can have 64K buffer
27785 	 * to put in all conn info.  So to be more efficient, just
27786 	 * allocate a 64K buffer here, assuming we need that large buffer.
27787 	 * This should be OK as only privileged processes can do ndd /dev/ip.
27788 	 */
27789 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
27790 		/* The following may work even if we cannot get a large buf. */
27791 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
27792 		return (0);
27793 	}
27794 
27795 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
27796 	return (0);
27797 }
27798 
27799 /*
27800  * Determine if the ill and multicast aspects of that packets
27801  * "matches" the conn.
27802  */
27803 boolean_t
27804 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
27805     zoneid_t zoneid)
27806 {
27807 	ill_t *in_ill;
27808 	boolean_t found;
27809 	ipif_t *ipif;
27810 	ire_t *ire;
27811 	ipaddr_t dst, src;
27812 
27813 	dst = ipha->ipha_dst;
27814 	src = ipha->ipha_src;
27815 
27816 	/*
27817 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
27818 	 * unicast, broadcast and multicast reception to
27819 	 * conn_incoming_ill. conn_wantpacket itself is called
27820 	 * only for BROADCAST and multicast.
27821 	 *
27822 	 * 1) ip_rput supresses duplicate broadcasts if the ill
27823 	 *    is part of a group. Hence, we should be receiving
27824 	 *    just one copy of broadcast for the whole group.
27825 	 *    Thus, if it is part of the group the packet could
27826 	 *    come on any ill of the group and hence we need a
27827 	 *    match on the group. Otherwise, match on ill should
27828 	 *    be sufficient.
27829 	 *
27830 	 * 2) ip_rput does not suppress duplicate multicast packets.
27831 	 *    If there are two interfaces in a ill group and we have
27832 	 *    2 applications (conns) joined a multicast group G on
27833 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
27834 	 *    will give us two packets because we join G on both the
27835 	 *    interfaces rather than nominating just one interface
27836 	 *    for receiving multicast like broadcast above. So,
27837 	 *    we have to call ilg_lookup_ill to filter out duplicate
27838 	 *    copies, if ill is part of a group.
27839 	 */
27840 	in_ill = connp->conn_incoming_ill;
27841 	if (in_ill != NULL) {
27842 		if (in_ill->ill_group == NULL) {
27843 			if (in_ill != ill)
27844 				return (B_FALSE);
27845 		} else if (in_ill->ill_group != ill->ill_group) {
27846 			return (B_FALSE);
27847 		}
27848 	}
27849 
27850 	if (!CLASSD(dst)) {
27851 		if (IPCL_ZONE_MATCH(connp, zoneid))
27852 			return (B_TRUE);
27853 		/*
27854 		 * The conn is in a different zone; we need to check that this
27855 		 * broadcast address is configured in the application's zone and
27856 		 * on one ill in the group.
27857 		 */
27858 		ipif = ipif_get_next_ipif(NULL, ill);
27859 		if (ipif == NULL)
27860 			return (B_FALSE);
27861 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
27862 		    connp->conn_zoneid, NULL,
27863 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
27864 		ipif_refrele(ipif);
27865 		if (ire != NULL) {
27866 			ire_refrele(ire);
27867 			return (B_TRUE);
27868 		} else {
27869 			return (B_FALSE);
27870 		}
27871 	}
27872 
27873 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
27874 	    connp->conn_zoneid == zoneid) {
27875 		/*
27876 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
27877 		 * disabled, therefore we don't dispatch the multicast packet to
27878 		 * the sending zone.
27879 		 */
27880 		return (B_FALSE);
27881 	}
27882 
27883 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
27884 	    connp->conn_zoneid != zoneid) {
27885 		/*
27886 		 * Multicast packet on the loopback interface: we only match
27887 		 * conns who joined the group in the specified zone.
27888 		 */
27889 		return (B_FALSE);
27890 	}
27891 
27892 	if (connp->conn_multi_router) {
27893 		/* multicast packet and multicast router socket: send up */
27894 		return (B_TRUE);
27895 	}
27896 
27897 	mutex_enter(&connp->conn_lock);
27898 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
27899 	mutex_exit(&connp->conn_lock);
27900 	return (found);
27901 }
27902 
27903 /*
27904  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
27905  */
27906 /* ARGSUSED */
27907 static void
27908 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
27909 {
27910 	ill_t *ill = (ill_t *)q->q_ptr;
27911 	mblk_t	*mp1, *mp2;
27912 	ipif_t  *ipif;
27913 	int err = 0;
27914 	conn_t *connp = NULL;
27915 	ipsq_t	*ipsq;
27916 	arc_t	*arc;
27917 
27918 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
27919 
27920 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
27921 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
27922 
27923 	ASSERT(IAM_WRITER_ILL(ill));
27924 	mp2 = mp->b_cont;
27925 	mp->b_cont = NULL;
27926 
27927 	/*
27928 	 * We have now received the arp bringup completion message
27929 	 * from ARP. Mark the arp bringup as done. Also if the arp
27930 	 * stream has already started closing, send up the AR_ARP_CLOSING
27931 	 * ack now since ARP is waiting in close for this ack.
27932 	 */
27933 	mutex_enter(&ill->ill_lock);
27934 	ill->ill_arp_bringup_pending = 0;
27935 	if (ill->ill_arp_closing) {
27936 		mutex_exit(&ill->ill_lock);
27937 		/* Let's reuse the mp for sending the ack */
27938 		arc = (arc_t *)mp->b_rptr;
27939 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
27940 		arc->arc_cmd = AR_ARP_CLOSING;
27941 		qreply(q, mp);
27942 	} else {
27943 		mutex_exit(&ill->ill_lock);
27944 		freeb(mp);
27945 	}
27946 
27947 	/* We should have an IOCTL waiting on this. */
27948 	ipsq = ill->ill_phyint->phyint_ipsq;
27949 	ipif = ipsq->ipsq_pending_ipif;
27950 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
27951 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
27952 	if (mp1 == NULL) {
27953 		/* bringup was aborted by the user */
27954 		freemsg(mp2);
27955 		return;
27956 	}
27957 	ASSERT(connp != NULL);
27958 	q = CONNP_TO_WQ(connp);
27959 	/*
27960 	 * If the DL_BIND_REQ fails, it is noted
27961 	 * in arc_name_offset.
27962 	 */
27963 	err = *((int *)mp2->b_rptr);
27964 	if (err == 0) {
27965 		if (ipif->ipif_isv6) {
27966 			if ((err = ipif_up_done_v6(ipif)) != 0)
27967 				ip0dbg(("ip_arp_done: init failed\n"));
27968 		} else {
27969 			if ((err = ipif_up_done(ipif)) != 0)
27970 				ip0dbg(("ip_arp_done: init failed\n"));
27971 		}
27972 	} else {
27973 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
27974 	}
27975 
27976 	freemsg(mp2);
27977 
27978 	if ((err == 0) && (ill->ill_up_ipifs)) {
27979 		err = ill_up_ipifs(ill, q, mp1);
27980 		if (err == EINPROGRESS)
27981 			return;
27982 	}
27983 
27984 	if (ill->ill_up_ipifs) {
27985 		ill_group_cleanup(ill);
27986 	}
27987 
27988 	/*
27989 	 * The ioctl must complete now without EINPROGRESS
27990 	 * since ipsq_pending_mp_get has removed the ioctl mblk
27991 	 * from ipsq_pending_mp. Otherwise the ioctl will be
27992 	 * stuck for ever in the ipsq.
27993 	 */
27994 	ASSERT(err != EINPROGRESS);
27995 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
27996 }
27997 
27998 /* Allocate the private structure */
27999 static int
28000 ip_priv_alloc(void **bufp)
28001 {
28002 	void	*buf;
28003 
28004 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28005 		return (ENOMEM);
28006 
28007 	*bufp = buf;
28008 	return (0);
28009 }
28010 
28011 /* Function to delete the private structure */
28012 void
28013 ip_priv_free(void *buf)
28014 {
28015 	ASSERT(buf != NULL);
28016 	kmem_free(buf, sizeof (ip_priv_t));
28017 }
28018 
28019 /*
28020  * The entry point for IPPF processing.
28021  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28022  * routine just returns.
28023  *
28024  * When called, ip_process generates an ipp_packet_t structure
28025  * which holds the state information for this packet and invokes the
28026  * the classifier (via ipp_packet_process). The classification, depending on
28027  * configured filters, results in a list of actions for this packet. Invoking
28028  * an action may cause the packet to be dropped, in which case the resulting
28029  * mblk (*mpp) is NULL. proc indicates the callout position for
28030  * this packet and ill_index is the interface this packet on or will leave
28031  * on (inbound and outbound resp.).
28032  */
28033 void
28034 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28035 {
28036 	mblk_t		*mp;
28037 	ip_priv_t	*priv;
28038 	ipp_action_id_t	aid;
28039 	int		rc = 0;
28040 	ipp_packet_t	*pp;
28041 #define	IP_CLASS	"ip"
28042 
28043 	/* If the classifier is not loaded, return  */
28044 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28045 		return;
28046 	}
28047 
28048 	mp = *mpp;
28049 	ASSERT(mp != NULL);
28050 
28051 	/* Allocate the packet structure */
28052 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28053 	if (rc != 0) {
28054 		*mpp = NULL;
28055 		freemsg(mp);
28056 		return;
28057 	}
28058 
28059 	/* Allocate the private structure */
28060 	rc = ip_priv_alloc((void **)&priv);
28061 	if (rc != 0) {
28062 		*mpp = NULL;
28063 		freemsg(mp);
28064 		ipp_packet_free(pp);
28065 		return;
28066 	}
28067 	priv->proc = proc;
28068 	priv->ill_index = ill_index;
28069 	ipp_packet_set_private(pp, priv, ip_priv_free);
28070 	ipp_packet_set_data(pp, mp);
28071 
28072 	/* Invoke the classifier */
28073 	rc = ipp_packet_process(&pp);
28074 	if (pp != NULL) {
28075 		mp = ipp_packet_get_data(pp);
28076 		ipp_packet_free(pp);
28077 		if (rc != 0) {
28078 			freemsg(mp);
28079 			*mpp = NULL;
28080 		}
28081 	} else {
28082 		*mpp = NULL;
28083 	}
28084 #undef	IP_CLASS
28085 }
28086 
28087 /*
28088  * Propagate a multicast group membership operation (add/drop) on
28089  * all the interfaces crossed by the related multirt routes.
28090  * The call is considered successful if the operation succeeds
28091  * on at least one interface.
28092  */
28093 static int
28094 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28095     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28096     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28097     mblk_t *first_mp)
28098 {
28099 	ire_t		*ire_gw;
28100 	irb_t		*irb;
28101 	int		error = 0;
28102 	opt_restart_t	*or;
28103 
28104 	irb = ire->ire_bucket;
28105 	ASSERT(irb != NULL);
28106 
28107 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28108 
28109 	or = (opt_restart_t *)first_mp->b_rptr;
28110 	IRB_REFHOLD(irb);
28111 	for (; ire != NULL; ire = ire->ire_next) {
28112 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28113 			continue;
28114 		if (ire->ire_addr != group)
28115 			continue;
28116 
28117 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28118 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28119 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
28120 		/* No resolver exists for the gateway; skip this ire. */
28121 		if (ire_gw == NULL)
28122 			continue;
28123 
28124 		/*
28125 		 * This function can return EINPROGRESS. If so the operation
28126 		 * will be restarted from ip_restart_optmgmt which will
28127 		 * call ip_opt_set and option processing will restart for
28128 		 * this option. So we may end up calling 'fn' more than once.
28129 		 * This requires that 'fn' is idempotent except for the
28130 		 * return value. The operation is considered a success if
28131 		 * it succeeds at least once on any one interface.
28132 		 */
28133 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28134 		    NULL, fmode, src, first_mp);
28135 		if (error == 0)
28136 			or->or_private = CGTP_MCAST_SUCCESS;
28137 
28138 		if (ip_debug > 0) {
28139 			ulong_t	off;
28140 			char	*ksym;
28141 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28142 			ip2dbg(("ip_multirt_apply_membership: "
28143 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28144 			    "error %d [success %u]\n",
28145 			    ksym ? ksym : "?",
28146 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28147 			    error, or->or_private));
28148 		}
28149 
28150 		ire_refrele(ire_gw);
28151 		if (error == EINPROGRESS) {
28152 			IRB_REFRELE(irb);
28153 			return (error);
28154 		}
28155 	}
28156 	IRB_REFRELE(irb);
28157 	/*
28158 	 * Consider the call as successful if we succeeded on at least
28159 	 * one interface. Otherwise, return the last encountered error.
28160 	 */
28161 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28162 }
28163 
28164 
28165 /*
28166  * Issue a warning regarding a route crossing an interface with an
28167  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28168  * amount of time is logged.
28169  */
28170 static void
28171 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28172 {
28173 	hrtime_t	current = gethrtime();
28174 	char		buf[INET_ADDRSTRLEN];
28175 
28176 	/* Convert interval in ms to hrtime in ns */
28177 	if (multirt_bad_mtu_last_time +
28178 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
28179 	    current) {
28180 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28181 		    "to %s, incorrect MTU %u (expected %u)\n",
28182 		    ip_dot_addr(ire->ire_addr, buf),
28183 		    ire->ire_max_frag, max_frag);
28184 
28185 		multirt_bad_mtu_last_time = current;
28186 	}
28187 }
28188 
28189 
28190 /*
28191  * Get the CGTP (multirouting) filtering status.
28192  * If 0, the CGTP hooks are transparent.
28193  */
28194 /* ARGSUSED */
28195 static int
28196 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28197 {
28198 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28199 
28200 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28201 	return (0);
28202 }
28203 
28204 
28205 /*
28206  * Set the CGTP (multirouting) filtering status.
28207  * If the status is changed from active to transparent
28208  * or from transparent to active, forward the new status
28209  * to the filtering module (if loaded).
28210  */
28211 /* ARGSUSED */
28212 static int
28213 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28214     cred_t *ioc_cr)
28215 {
28216 	long		new_value;
28217 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28218 
28219 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28220 	    new_value < 0 || new_value > 1) {
28221 		return (EINVAL);
28222 	}
28223 
28224 	/*
28225 	 * Do not enable CGTP filtering - thus preventing the hooks
28226 	 * from being invoked - if the version number of the
28227 	 * filtering module hooks does not match.
28228 	 */
28229 	if ((ip_cgtp_filter_ops != NULL) &&
28230 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
28231 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
28232 		    "(module hooks version %d, expecting %d)\n",
28233 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
28234 		return (ENOTSUP);
28235 	}
28236 
28237 	if ((!*ip_cgtp_filter_value) && new_value) {
28238 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28239 		    ip_cgtp_filter_ops == NULL ?
28240 		    " (module not loaded)" : "");
28241 	}
28242 	if (*ip_cgtp_filter_value && (!new_value)) {
28243 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28244 		    ip_cgtp_filter_ops == NULL ?
28245 		    " (module not loaded)" : "");
28246 	}
28247 
28248 	if (ip_cgtp_filter_ops != NULL) {
28249 		int	res;
28250 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
28251 			return (res);
28252 		}
28253 	}
28254 
28255 	*ip_cgtp_filter_value = (boolean_t)new_value;
28256 
28257 	return (0);
28258 }
28259 
28260 
28261 /*
28262  * Return the expected CGTP hooks version number.
28263  */
28264 int
28265 ip_cgtp_filter_supported(void)
28266 {
28267 	return (ip_cgtp_filter_rev);
28268 }
28269 
28270 
28271 /*
28272  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
28273  * or by invoking this function. In the first case, the version number
28274  * of the registered structure is checked at hooks activation time
28275  * in ip_cgtp_filter_set().
28276  */
28277 int
28278 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
28279 {
28280 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28281 		return (ENOTSUP);
28282 
28283 	ip_cgtp_filter_ops = ops;
28284 	return (0);
28285 }
28286 
28287 static squeue_func_t
28288 ip_squeue_switch(int val)
28289 {
28290 	squeue_func_t rval = squeue_fill;
28291 
28292 	switch (val) {
28293 	case IP_SQUEUE_ENTER_NODRAIN:
28294 		rval = squeue_enter_nodrain;
28295 		break;
28296 	case IP_SQUEUE_ENTER:
28297 		rval = squeue_enter;
28298 		break;
28299 	default:
28300 		break;
28301 	}
28302 	return (rval);
28303 }
28304 
28305 /* ARGSUSED */
28306 static int
28307 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28308     caddr_t addr, cred_t *cr)
28309 {
28310 	int *v = (int *)addr;
28311 	long new_value;
28312 
28313 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28314 		return (EINVAL);
28315 
28316 	ip_input_proc = ip_squeue_switch(new_value);
28317 	*v = new_value;
28318 	return (0);
28319 }
28320 
28321 /* ARGSUSED */
28322 static int
28323 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28324     caddr_t addr, cred_t *cr)
28325 {
28326 	int *v = (int *)addr;
28327 	long new_value;
28328 
28329 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28330 		return (EINVAL);
28331 
28332 	*v = new_value;
28333 	return (0);
28334 }
28335 
28336 static void
28337 ip_kstat_init(void)
28338 {
28339 	ip_named_kstat_t template = {
28340 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
28341 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
28342 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
28343 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
28344 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
28345 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
28346 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
28347 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
28348 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
28349 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
28350 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
28351 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
28352 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
28353 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
28354 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
28355 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
28356 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
28357 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
28358 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
28359 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
28360 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
28361 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
28362 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
28363 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
28364 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
28365 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
28366 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
28367 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
28368 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
28369 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
28370 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
28371 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
28372 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
28373 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
28374 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
28375 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
28376 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
28377 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
28378 	};
28379 
28380 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
28381 					NUM_OF_FIELDS(ip_named_kstat_t),
28382 					0);
28383 	if (!ip_mibkp)
28384 		return;
28385 
28386 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
28387 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
28388 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
28389 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
28390 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
28391 
28392 	template.netToMediaEntrySize.value.i32 =
28393 		sizeof (mib2_ipNetToMediaEntry_t);
28394 
28395 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
28396 
28397 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
28398 
28399 	ip_mibkp->ks_update = ip_kstat_update;
28400 
28401 	kstat_install(ip_mibkp);
28402 }
28403 
28404 static void
28405 ip_kstat_fini(void)
28406 {
28407 
28408 	if (ip_mibkp != NULL) {
28409 		kstat_delete(ip_mibkp);
28410 		ip_mibkp = NULL;
28411 	}
28412 }
28413 
28414 static int
28415 ip_kstat_update(kstat_t *kp, int rw)
28416 {
28417 	ip_named_kstat_t *ipkp;
28418 
28419 	if (!kp || !kp->ks_data)
28420 		return (EIO);
28421 
28422 	if (rw == KSTAT_WRITE)
28423 		return (EACCES);
28424 
28425 	ipkp = (ip_named_kstat_t *)kp->ks_data;
28426 
28427 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
28428 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
28429 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
28430 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
28431 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
28432 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
28433 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
28434 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
28435 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
28436 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
28437 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
28438 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
28439 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
28440 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
28441 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
28442 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
28443 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
28444 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
28445 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
28446 
28447 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
28448 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
28449 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
28450 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
28451 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
28452 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
28453 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
28454 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
28455 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
28456 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
28457 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
28458 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
28459 
28460 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
28461 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
28462 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
28463 
28464 	return (0);
28465 }
28466 
28467 static void
28468 icmp_kstat_init(void)
28469 {
28470 	icmp_named_kstat_t template = {
28471 		{ "inMsgs",		KSTAT_DATA_UINT32 },
28472 		{ "inErrors",		KSTAT_DATA_UINT32 },
28473 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
28474 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
28475 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
28476 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
28477 		{ "inRedirects",	KSTAT_DATA_UINT32 },
28478 		{ "inEchos",		KSTAT_DATA_UINT32 },
28479 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
28480 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
28481 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
28482 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
28483 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
28484 		{ "outMsgs",		KSTAT_DATA_UINT32 },
28485 		{ "outErrors",		KSTAT_DATA_UINT32 },
28486 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
28487 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
28488 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
28489 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
28490 		{ "outRedirects",	KSTAT_DATA_UINT32 },
28491 		{ "outEchos",		KSTAT_DATA_UINT32 },
28492 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
28493 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
28494 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
28495 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
28496 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
28497 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
28498 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
28499 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
28500 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
28501 		{ "outDrops",		KSTAT_DATA_UINT32 },
28502 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
28503 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
28504 	};
28505 
28506 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
28507 					NUM_OF_FIELDS(icmp_named_kstat_t),
28508 					0);
28509 	if (icmp_mibkp == NULL)
28510 		return;
28511 
28512 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
28513 
28514 	icmp_mibkp->ks_update = icmp_kstat_update;
28515 
28516 	kstat_install(icmp_mibkp);
28517 }
28518 
28519 static void
28520 icmp_kstat_fini(void)
28521 {
28522 
28523 	if (icmp_mibkp != NULL) {
28524 		kstat_delete(icmp_mibkp);
28525 		icmp_mibkp = NULL;
28526 	}
28527 }
28528 
28529 static int
28530 icmp_kstat_update(kstat_t *kp, int rw)
28531 {
28532 	icmp_named_kstat_t *icmpkp;
28533 
28534 	if ((kp == NULL) || (kp->ks_data == NULL))
28535 		return (EIO);
28536 
28537 	if (rw == KSTAT_WRITE)
28538 		return (EACCES);
28539 
28540 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
28541 
28542 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
28543 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
28544 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
28545 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
28546 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
28547 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
28548 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
28549 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
28550 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
28551 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
28552 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
28553 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
28554 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
28555 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
28556 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
28557 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
28558 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
28559 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
28560 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
28561 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
28562 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
28563 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
28564 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
28565 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
28566 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
28567 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
28568 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
28569 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
28570 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
28571 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
28572 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
28573 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
28574 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
28575 
28576 	return (0);
28577 }
28578 
28579 /*
28580  * This is the fanout function for raw socket opened for SCTP.  Note
28581  * that it is called after SCTP checks that there is no socket which
28582  * wants a packet.  Then before SCTP handles this out of the blue packet,
28583  * this function is called to see if there is any raw socket for SCTP.
28584  * If there is and it is bound to the correct address, the packet will
28585  * be sent to that socket.  Note that only one raw socket can be bound to
28586  * a port.  This is assured in ipcl_sctp_hash_insert();
28587  */
28588 void
28589 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
28590     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
28591     uint_t ipif_seqid, zoneid_t zoneid)
28592 {
28593 	conn_t		*connp;
28594 	queue_t		*rq;
28595 	mblk_t		*first_mp;
28596 	boolean_t	secure;
28597 	ip6_t		*ip6h;
28598 
28599 	first_mp = mp;
28600 	if (mctl_present) {
28601 		mp = first_mp->b_cont;
28602 		secure = ipsec_in_is_secure(first_mp);
28603 		ASSERT(mp != NULL);
28604 	} else {
28605 		secure = B_FALSE;
28606 	}
28607 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
28608 
28609 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
28610 	if (connp == NULL) {
28611 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
28612 		    mctl_present);
28613 		return;
28614 	}
28615 	rq = connp->conn_rq;
28616 	if (!canputnext(rq)) {
28617 		CONN_DEC_REF(connp);
28618 		BUMP_MIB(&ip_mib, rawipInOverflows);
28619 		freemsg(first_mp);
28620 		return;
28621 	}
28622 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
28623 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
28624 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
28625 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
28626 		if (first_mp == NULL) {
28627 			CONN_DEC_REF(connp);
28628 			return;
28629 		}
28630 	}
28631 	/*
28632 	 * We probably should not send M_CTL message up to
28633 	 * raw socket.
28634 	 */
28635 	if (mctl_present)
28636 		freeb(first_mp);
28637 
28638 	/* Initiate IPPF processing here if needed. */
28639 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
28640 	    (!isv4 && IP6_IN_IPP(flags))) {
28641 		ip_process(IPP_LOCAL_IN, &mp,
28642 		    recv_ill->ill_phyint->phyint_ifindex);
28643 		if (mp == NULL) {
28644 			CONN_DEC_REF(connp);
28645 			return;
28646 		}
28647 	}
28648 
28649 	if (connp->conn_recvif || connp->conn_recvslla ||
28650 	    ((connp->conn_ipv6_recvpktinfo ||
28651 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
28652 	    (flags & IP_FF_IP6INFO))) {
28653 		int in_flags = 0;
28654 
28655 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
28656 			in_flags = IPF_RECVIF;
28657 		}
28658 		if (connp->conn_recvslla) {
28659 			in_flags |= IPF_RECVSLLA;
28660 		}
28661 		if (isv4) {
28662 			mp = ip_add_info(mp, recv_ill, in_flags);
28663 		} else {
28664 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
28665 			if (mp == NULL) {
28666 				CONN_DEC_REF(connp);
28667 				return;
28668 			}
28669 		}
28670 	}
28671 
28672 	BUMP_MIB(&ip_mib, ipInDelivers);
28673 	/*
28674 	 * We are sending the IPSEC_IN message also up. Refer
28675 	 * to comments above this function.
28676 	 */
28677 	putnext(rq, mp);
28678 	CONN_DEC_REF(connp);
28679 }
28680 
28681 /*
28682  * This function should be called only if all packet processing
28683  * including fragmentation is complete. Callers of this function
28684  * must set mp->b_prev to one of these values:
28685  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
28686  * prior to handing over the mp as first argument to this function.
28687  *
28688  * If the ire passed by caller is incomplete, this function
28689  * queues the packet and if necessary, sends ARP request and bails.
28690  * If the ire passed is fully resolved, we simply prepend
28691  * the link-layer header to the packet, do ipsec hw acceleration
28692  * work if necessary, and send the packet out on the wire.
28693  *
28694  * NOTE: IPSEC will only call this function with fully resolved
28695  * ires if hw acceleration is involved.
28696  * TODO list :
28697  * 	a Handle M_MULTIDATA so that
28698  *	  tcp_multisend->tcp_multisend_data can
28699  *	  call ip_xmit_v4 directly
28700  *	b Handle post-ARP work for fragments so that
28701  *	  ip_wput_frag can call this function.
28702  */
28703 ipxmit_state_t
28704 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
28705 {
28706 	nce_t		*arpce;
28707 	queue_t		*q;
28708 	int		ill_index;
28709 	mblk_t		*nxt_mp, *first_mp;
28710 	boolean_t	xmit_drop = B_FALSE;
28711 	ip_proc_t	proc;
28712 	ill_t		*out_ill;
28713 
28714 	arpce = ire->ire_nce;
28715 	ASSERT(arpce != NULL);
28716 
28717 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
28718 
28719 	mutex_enter(&arpce->nce_lock);
28720 	switch (arpce->nce_state) {
28721 	case ND_REACHABLE:
28722 		/* If there are other queued packets, queue this packet */
28723 		if (arpce->nce_qd_mp != NULL) {
28724 			if (mp != NULL)
28725 				nce_queue_mp_common(arpce, mp, B_FALSE);
28726 			mp = arpce->nce_qd_mp;
28727 		}
28728 		arpce->nce_qd_mp = NULL;
28729 		mutex_exit(&arpce->nce_lock);
28730 
28731 		/*
28732 		 * Flush the queue.  In the common case, where the
28733 		 * ARP is already resolved,  it will go through the
28734 		 * while loop only once.
28735 		 */
28736 		while (mp != NULL) {
28737 
28738 			nxt_mp = mp->b_next;
28739 			mp->b_next = NULL;
28740 			/*
28741 			 * This info is needed for IPQOS to do COS marking
28742 			 * in ip_wput_attach_llhdr->ip_process.
28743 			 */
28744 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
28745 			mp->b_prev = NULL;
28746 
28747 			/* set up ill index for outbound qos processing */
28748 			out_ill = ire->ire_ipif->ipif_ill;
28749 			ill_index = out_ill->ill_phyint->phyint_ifindex;
28750 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
28751 			    ill_index);
28752 			if (first_mp == NULL) {
28753 				xmit_drop = B_TRUE;
28754 				if (proc == IPP_FWD_OUT) {
28755 					BUMP_MIB(&ip_mib, ipInDiscards);
28756 				} else {
28757 					BUMP_MIB(&ip_mib, ipOutDiscards);
28758 				}
28759 				goto next_mp;
28760 			}
28761 			/* non-ipsec hw accel case */
28762 			if (io == NULL || !io->ipsec_out_accelerated) {
28763 				/* send it */
28764 				q = ire->ire_stq;
28765 				if (proc == IPP_FWD_OUT) {
28766 					UPDATE_IB_PKT_COUNT(ire);
28767 				} else {
28768 					UPDATE_OB_PKT_COUNT(ire);
28769 				}
28770 				ire->ire_last_used_time = lbolt;
28771 
28772 				if (flow_ctl_enabled || canputnext(q))  {
28773 					if (proc == IPP_FWD_OUT) {
28774 						BUMP_MIB(&ip_mib,
28775 						    ipForwDatagrams);
28776 					}
28777 
28778 					if (mp == NULL)
28779 						goto next_mp;
28780 					putnext(q, first_mp);
28781 				} else {
28782 					BUMP_MIB(&ip_mib,
28783 					    ipOutDiscards);
28784 					xmit_drop = B_TRUE;
28785 					freemsg(first_mp);
28786 				}
28787 			} else {
28788 				/*
28789 				 * Safety Pup says: make sure this
28790 				 *  is going to the right interface!
28791 				 */
28792 				ill_t *ill1 =
28793 				    (ill_t *)ire->ire_stq->q_ptr;
28794 				int ifindex =
28795 				    ill1->ill_phyint->phyint_ifindex;
28796 				if (ifindex !=
28797 				    io->ipsec_out_capab_ill_index) {
28798 					xmit_drop = B_TRUE;
28799 					freemsg(mp);
28800 				} else {
28801 					ipsec_hw_putnext(ire->ire_stq,
28802 					    mp);
28803 				}
28804 			}
28805 next_mp:
28806 			mp = nxt_mp;
28807 		} /* while (mp != NULL) */
28808 		if (xmit_drop)
28809 			return (SEND_FAILED);
28810 		else
28811 			return (SEND_PASSED);
28812 
28813 	case ND_INITIAL:
28814 	case ND_INCOMPLETE:
28815 
28816 		/*
28817 		 * While we do send off packets to dests that
28818 		 * use fully-resolved CGTP routes, we do not
28819 		 * handle unresolved CGTP routes.
28820 		 */
28821 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
28822 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
28823 
28824 		if (mp != NULL) {
28825 			/* queue the packet */
28826 			nce_queue_mp_common(arpce, mp, B_FALSE);
28827 		}
28828 
28829 		if (arpce->nce_state == ND_INCOMPLETE) {
28830 			mutex_exit(&arpce->nce_lock);
28831 			DTRACE_PROBE3(ip__xmit__incomplete,
28832 			    (ire_t *), ire, (mblk_t *), mp,
28833 			    (ipsec_out_t *), io);
28834 			return (LOOKUP_IN_PROGRESS);
28835 		}
28836 
28837 		arpce->nce_state = ND_INCOMPLETE;
28838 		mutex_exit(&arpce->nce_lock);
28839 		/*
28840 		 * Note that ire_add() (called from ire_forward())
28841 		 * holds a ref on the ire until ARP is completed.
28842 		 */
28843 
28844 		ire_arpresolve(ire, ire_to_ill(ire));
28845 		return (LOOKUP_IN_PROGRESS);
28846 	default:
28847 		ASSERT(0);
28848 		mutex_exit(&arpce->nce_lock);
28849 		return (LLHDR_RESLV_FAILED);
28850 	}
28851 }
28852 
28853 /*
28854  * Return B_TRUE if the buffers differ in length or content.
28855  * This is used for comparing extension header buffers.
28856  * Note that an extension header would be declared different
28857  * even if all that changed was the next header value in that header i.e.
28858  * what really changed is the next extension header.
28859  */
28860 boolean_t
28861 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
28862     uint_t blen)
28863 {
28864 	if (!b_valid)
28865 		blen = 0;
28866 
28867 	if (alen != blen)
28868 		return (B_TRUE);
28869 	if (alen == 0)
28870 		return (B_FALSE);	/* Both zero length */
28871 	return (bcmp(abuf, bbuf, alen));
28872 }
28873 
28874 /*
28875  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
28876  * Return B_FALSE if memory allocation fails - don't change any state!
28877  */
28878 boolean_t
28879 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28880     const void *src, uint_t srclen)
28881 {
28882 	void *dst;
28883 
28884 	if (!src_valid)
28885 		srclen = 0;
28886 
28887 	ASSERT(*dstlenp == 0);
28888 	if (src != NULL && srclen != 0) {
28889 		dst = mi_alloc(srclen, BPRI_MED);
28890 		if (dst == NULL)
28891 			return (B_FALSE);
28892 	} else {
28893 		dst = NULL;
28894 	}
28895 	if (*dstp != NULL)
28896 		mi_free(*dstp);
28897 	*dstp = dst;
28898 	*dstlenp = dst == NULL ? 0 : srclen;
28899 	return (B_TRUE);
28900 }
28901 
28902 /*
28903  * Replace what is in *dst, *dstlen with the source.
28904  * Assumes ip_allocbuf has already been called.
28905  */
28906 void
28907 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28908     const void *src, uint_t srclen)
28909 {
28910 	if (!src_valid)
28911 		srclen = 0;
28912 
28913 	ASSERT(*dstlenp == srclen);
28914 	if (src != NULL && srclen != 0)
28915 		bcopy(src, *dstp, srclen);
28916 }
28917 
28918 /*
28919  * Free the storage pointed to by the members of an ip6_pkt_t.
28920  */
28921 void
28922 ip6_pkt_free(ip6_pkt_t *ipp)
28923 {
28924 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
28925 
28926 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
28927 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
28928 		ipp->ipp_hopopts = NULL;
28929 		ipp->ipp_hopoptslen = 0;
28930 	}
28931 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
28932 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
28933 		ipp->ipp_rtdstopts = NULL;
28934 		ipp->ipp_rtdstoptslen = 0;
28935 	}
28936 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
28937 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
28938 		ipp->ipp_dstopts = NULL;
28939 		ipp->ipp_dstoptslen = 0;
28940 	}
28941 	if (ipp->ipp_fields & IPPF_RTHDR) {
28942 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
28943 		ipp->ipp_rthdr = NULL;
28944 		ipp->ipp_rthdrlen = 0;
28945 	}
28946 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
28947 	    IPPF_RTHDR);
28948 }
28949