xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision dd97b1d649428a0da2553d75f71a56bd2a00a06c)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /* Copyright (c) 1990 Mentat Inc. */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/stream.h>
31 #include <sys/dlpi.h>
32 #include <sys/stropts.h>
33 #include <sys/sysmacros.h>
34 #include <sys/strsubr.h>
35 #include <sys/strlog.h>
36 #include <sys/strsun.h>
37 #include <sys/zone.h>
38 #define	_SUN_TPI_VERSION 2
39 #include <sys/tihdr.h>
40 #include <sys/xti_inet.h>
41 #include <sys/ddi.h>
42 #include <sys/sunddi.h>
43 #include <sys/cmn_err.h>
44 #include <sys/debug.h>
45 #include <sys/kobj.h>
46 #include <sys/modctl.h>
47 #include <sys/atomic.h>
48 #include <sys/policy.h>
49 #include <sys/priv.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/sdt.h>
55 #include <sys/socket.h>
56 #include <sys/vtrace.h>
57 #include <sys/isa_defs.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/kstatcom.h>
72 
73 #include <netinet/igmp_var.h>
74 #include <netinet/ip6.h>
75 #include <netinet/icmp6.h>
76 #include <netinet/sctp.h>
77 
78 #include <inet/ip.h>
79 #include <inet/ip_impl.h>
80 #include <inet/ip6.h>
81 #include <inet/ip6_asp.h>
82 #include <inet/tcp.h>
83 #include <inet/tcp_impl.h>
84 #include <inet/ip_multi.h>
85 #include <inet/ip_if.h>
86 #include <inet/ip_ire.h>
87 #include <inet/ip_ftable.h>
88 #include <inet/ip_rts.h>
89 #include <inet/optcom.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <sys/sunddi.h>
121 
122 #include <sys/tsol/label.h>
123 #include <sys/tsol/tnet.h>
124 
125 #include <rpc/pmap_prot.h>
126 
127 /*
128  * Values for squeue switch:
129  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
130  * IP_SQUEUE_ENTER: squeue_enter
131  * IP_SQUEUE_FILL: squeue_fill
132  */
133 int ip_squeue_enter = 2;
134 squeue_func_t ip_input_proc;
135 /*
136  * IP statistics.
137  */
138 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
139 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
140 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
141 
142 typedef struct ip_stat {
143 	kstat_named_t	ipsec_fanout_proto;
144 	kstat_named_t	ip_udp_fannorm;
145 	kstat_named_t	ip_udp_fanmb;
146 	kstat_named_t	ip_udp_fanothers;
147 	kstat_named_t	ip_udp_fast_path;
148 	kstat_named_t	ip_udp_slow_path;
149 	kstat_named_t	ip_udp_input_err;
150 	kstat_named_t	ip_tcppullup;
151 	kstat_named_t	ip_tcpoptions;
152 	kstat_named_t	ip_multipkttcp;
153 	kstat_named_t	ip_tcp_fast_path;
154 	kstat_named_t	ip_tcp_slow_path;
155 	kstat_named_t	ip_tcp_input_error;
156 	kstat_named_t	ip_db_ref;
157 	kstat_named_t	ip_notaligned1;
158 	kstat_named_t	ip_notaligned2;
159 	kstat_named_t	ip_multimblk3;
160 	kstat_named_t	ip_multimblk4;
161 	kstat_named_t	ip_ipoptions;
162 	kstat_named_t	ip_classify_fail;
163 	kstat_named_t	ip_opt;
164 	kstat_named_t	ip_udp_rput_local;
165 	kstat_named_t	ipsec_proto_ahesp;
166 	kstat_named_t	ip_conn_flputbq;
167 	kstat_named_t	ip_conn_walk_drain;
168 	kstat_named_t   ip_out_sw_cksum;
169 	kstat_named_t   ip_in_sw_cksum;
170 	kstat_named_t   ip_trash_ire_reclaim_calls;
171 	kstat_named_t   ip_trash_ire_reclaim_success;
172 	kstat_named_t   ip_ire_arp_timer_expired;
173 	kstat_named_t   ip_ire_redirect_timer_expired;
174 	kstat_named_t	ip_ire_pmtu_timer_expired;
175 	kstat_named_t	ip_input_multi_squeue;
176 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
177 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
178 	kstat_named_t	ip_tcp_in_sw_cksum_err;
179 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
180 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
181 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
182 	kstat_named_t	ip_udp_in_sw_cksum_err;
183 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
184 	kstat_named_t	ip_frag_mdt_pkt_out;
185 	kstat_named_t	ip_frag_mdt_discarded;
186 	kstat_named_t	ip_frag_mdt_allocfail;
187 	kstat_named_t	ip_frag_mdt_addpdescfail;
188 	kstat_named_t	ip_frag_mdt_allocd;
189 } ip_stat_t;
190 
191 static ip_stat_t ip_statistics = {
192 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
193 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
194 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
195 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
196 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
197 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
198 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
199 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
200 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
201 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
202 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
203 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
204 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
205 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
206 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
207 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
208 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
209 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
210 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
211 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
212 	{ "ip_opt",				KSTAT_DATA_UINT64 },
213 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
214 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
215 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
216 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
217 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
218 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
219 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
220 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
221 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
222 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
223 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
224 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
225 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
226 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
227 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
228 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
229 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
230 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
231 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
232 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
233 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
234 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
235 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
236 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
237 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
238 };
239 
240 static kstat_t *ip_kstat;
241 
242 #define	TCP6 "tcp6"
243 #define	TCP "tcp"
244 #define	SCTP "sctp"
245 #define	SCTP6 "sctp6"
246 
247 major_t TCP6_MAJ;
248 major_t TCP_MAJ;
249 major_t SCTP_MAJ;
250 major_t SCTP6_MAJ;
251 
252 int ip_poll_normal_ms = 100;
253 int ip_poll_normal_ticks = 0;
254 
255 /*
256  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
257  */
258 
259 struct listptr_s {
260 	mblk_t	*lp_head;	/* pointer to the head of the list */
261 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
262 };
263 
264 typedef struct listptr_s listptr_t;
265 
266 /*
267  * This is used by ip_snmp_get_mib2_ip_route_media and
268  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
269  */
270 typedef struct iproutedata_s {
271 	uint_t		ird_idx;
272 	listptr_t	ird_route;	/* ipRouteEntryTable */
273 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
274 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
275 } iproutedata_t;
276 
277 /*
278  * Cluster specific hooks. These should be NULL when booted as a non-cluster
279  */
280 
281 /*
282  * Hook functions to enable cluster networking
283  * On non-clustered systems these vectors must always be NULL.
284  *
285  * Hook function to Check ip specified ip address is a shared ip address
286  * in the cluster
287  *
288  */
289 int (*cl_inet_isclusterwide)(uint8_t protocol,
290     sa_family_t addr_family, uint8_t *laddrp) = NULL;
291 
292 /*
293  * Hook function to generate cluster wide ip fragment identifier
294  */
295 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
296     uint8_t *laddrp, uint8_t *faddrp) = NULL;
297 
298 /*
299  * Synchronization notes:
300  *
301  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
302  * MT level protection given by STREAMS. IP uses a combination of its own
303  * internal serialization mechanism and standard Solaris locking techniques.
304  * The internal serialization is per phyint (no IPMP) or per IPMP group.
305  * This is used to serialize plumbing operations, IPMP operations, certain
306  * multicast operations, most set ioctls, igmp/mld timers etc.
307  *
308  * Plumbing is a long sequence of operations involving message
309  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
310  * involved in plumbing operations. A natural model is to serialize these
311  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
312  * parallel without any interference. But various set ioctls on hme0 are best
313  * serialized. However if the system uses IPMP, the operations are easier if
314  * they are serialized on a per IPMP group basis since IPMP operations
315  * happen across ill's of a group. Thus the lowest common denominator is to
316  * serialize most set ioctls, multicast join/leave operations, IPMP operations
317  * igmp/mld timer operations, and processing of DLPI control messages received
318  * from drivers on a per IPMP group basis. If the system does not employ
319  * IPMP the serialization is on a per phyint basis. This serialization is
320  * provided by the ipsq_t and primitives operating on this. Details can
321  * be found in ip_if.c above the core primitives operating on ipsq_t.
322  *
323  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
324  * Simiarly lookup of an ire by a thread also returns a refheld ire.
325  * In addition ipif's and ill's referenced by the ire are also indirectly
326  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
327  * the ipif's address or netmask change as long as an ipif is refheld
328  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
329  * address of an ipif has to go through the ipsq_t. This ensures that only
330  * 1 such exclusive operation proceeds at any time on the ipif. It then
331  * deletes all ires associated with this ipif, and waits for all refcnts
332  * associated with this ipif to come down to zero. The address is changed
333  * only after the ipif has been quiesced. Then the ipif is brought up again.
334  * More details are described above the comment in ip_sioctl_flags.
335  *
336  * Packet processing is based mostly on IREs and are fully multi-threaded
337  * using standard Solaris MT techniques.
338  *
339  * There are explicit locks in IP to handle:
340  * - The ip_g_head list maintained by mi_open_link() and friends.
341  *
342  * - The reassembly data structures (one lock per hash bucket)
343  *
344  * - conn_lock is meant to protect conn_t fields. The fields actually
345  *   protected by conn_lock are documented in the conn_t definition.
346  *
347  * - ire_lock to protect some of the fields of the ire, IRE tables
348  *   (one lock per hash bucket). Refer to ip_ire.c for details.
349  *
350  * - ndp_g_lock and nce_lock for protecting NCEs.
351  *
352  * - ill_lock protects fields of the ill and ipif. Details in ip.h
353  *
354  * - ill_g_lock: This is a global reader/writer lock. Protects the following
355  *	* The AVL tree based global multi list of all ills.
356  *	* The linked list of all ipifs of an ill
357  *	* The <ill-ipsq> mapping
358  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
359  *	* The illgroup list threaded by ill_group_next.
360  *	* <ill-phyint> association
361  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
362  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
363  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
364  *   will all have to hold the ill_g_lock as writer for the actual duration
365  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
366  *   may be found in the IPMP section.
367  *
368  * - ill_lock:  This is a per ill mutex.
369  *   It protects some members of the ill and is documented below.
370  *   It also protects the <ill-ipsq> mapping
371  *   It also protects the illgroup list threaded by ill_group_next.
372  *   It also protects the <ill-phyint> assoc.
373  *   It also protects the list of ipifs hanging off the ill.
374  *
375  * - ipsq_lock: This is a per ipsq_t mutex lock.
376  *   This protects all the other members of the ipsq struct except
377  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
378  *
379  * - illgrp_lock: This is a per ill_group mutex lock.
380  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
381  *   which dictates which is the next ill in an ill_group that is to be chosen
382  *   for sending outgoing packets, through creation of an IRE_CACHE that
383  *   references this ill.
384  *
385  * - phyint_lock: This is a per phyint mutex lock. Protects just the
386  *   phyint_flags
387  *
388  * - ip_g_nd_lock: This is a global reader/writer lock.
389  *   Any call to nd_load to load a new parameter to the ND table must hold the
390  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
391  *   as reader.
392  *
393  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
394  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
395  *   uniqueness check also done atomically.
396  *
397  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
398  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
399  *   as a writer when adding or deleting elements from these lists, and
400  *   as a reader when walking these lists to send a SADB update to the
401  *   IPsec capable ills.
402  *
403  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
404  *   group list linked by ill_usesrc_grp_next. It also protects the
405  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
406  *   group is being added or deleted.  This lock is taken as a reader when
407  *   walking the list/group(eg: to get the number of members in a usesrc group).
408  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
409  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
410  *   example, it is not necessary to take this lock in the initial portion
411  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
412  *   ip_sioctl_flags since the these operations are executed exclusively and
413  *   that ensures that the "usesrc group state" cannot change. The "usesrc
414  *   group state" change can happen only in the latter part of
415  *   ip_sioctl_slifusesrc and in ill_delete.
416  *
417  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
418  *
419  * To change the <ill-phyint> association, the ill_g_lock must be held
420  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
421  * must be held.
422  *
423  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
424  * and the ill_lock of the ill in question must be held.
425  *
426  * To change the <ill-illgroup> association the ill_g_lock must be held as
427  * writer and the ill_lock of the ill in question must be held.
428  *
429  * To add or delete an ipif from the list of ipifs hanging off the ill,
430  * ill_g_lock (writer) and ill_lock must be held and the thread must be
431  * a writer on the associated ipsq,.
432  *
433  * To add or delete an ill to the system, the ill_g_lock must be held as
434  * writer and the thread must be a writer on the associated ipsq.
435  *
436  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
437  * must be a writer on the associated ipsq.
438  *
439  * Lock hierarchy
440  *
441  * Some lock hierarchy scenarios are listed below.
442  *
443  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
444  * ill_g_lock -> illgrp_lock -> ill_lock
445  * ill_g_lock -> ill_lock(s) -> phyint_lock
446  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
447  * ill_g_lock -> ip_addr_avail_lock
448  * conn_lock -> irb_lock -> ill_lock -> ire_lock
449  * ill_g_lock -> ip_g_nd_lock
450  *
451  * When more than 1 ill lock is needed to be held, all ill lock addresses
452  * are sorted on address and locked starting from highest addressed lock
453  * downward.
454  *
455  * Mobile-IP scenarios
456  *
457  * irb_lock -> ill_lock -> ire_mrtun_lock
458  * irb_lock -> ill_lock -> ire_srcif_table_lock
459  *
460  * IPsec scenarios
461  *
462  * ipsa_lock -> ill_g_lock -> ill_lock
463  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
464  * ipsec_capab_ills_lock -> ipsa_lock
465  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
466  *
467  * Trusted Solaris scenarios
468  *
469  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
470  * igsa_lock -> gcdb_lock
471  * gcgrp_rwlock -> ire_lock
472  * gcgrp_rwlock -> gcdb_lock
473  *
474  *
475  * Routing/forwarding table locking notes:
476  *
477  * Lock acquisition order: Radix tree lock, irb_lock.
478  * Requirements:
479  * i.  Walker must not hold any locks during the walker callback.
480  * ii  Walker must not see a truncated tree during the walk because of any node
481  *     deletion.
482  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
483  *     in many places in the code to walk the irb list. Thus even if all the
484  *     ires in a bucket have been deleted, we still can't free the radix node
485  *     until the ires have actually been inactive'd (freed).
486  *
487  * Tree traversal - Need to hold the global tree lock in read mode.
488  * Before dropping the global tree lock, need to either increment the ire_refcnt
489  * to ensure that the radix node can't be deleted.
490  *
491  * Tree add - Need to hold the global tree lock in write mode to add a
492  * radix node. To prevent the node from being deleted, increment the
493  * irb_refcnt, after the node is added to the tree. The ire itself is
494  * added later while holding the irb_lock, but not the tree lock.
495  *
496  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
497  * All associated ires must be inactive (i.e. freed), and irb_refcnt
498  * must be zero.
499  *
500  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
501  * global tree lock (read mode) for traversal.
502  *
503  * IPSEC notes :
504  *
505  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
506  * in front of the actual packet. For outbound datagrams, the M_CTL
507  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
508  * information used by the IPSEC code for applying the right level of
509  * protection. The information initialized by IP in the ipsec_out_t
510  * is determined by the per-socket policy or global policy in the system.
511  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
512  * ipsec_info.h) which starts out with nothing in it. It gets filled
513  * with the right information if it goes through the AH/ESP code, which
514  * happens if the incoming packet is secure. The information initialized
515  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
516  * the policy requirements needed by per-socket policy or global policy
517  * is met or not.
518  *
519  * If there is both per-socket policy (set using setsockopt) and there
520  * is also global policy match for the 5 tuples of the socket,
521  * ipsec_override_policy() makes the decision of which one to use.
522  *
523  * For fully connected sockets i.e dst, src [addr, port] is known,
524  * conn_policy_cached is set indicating that policy has been cached.
525  * conn_in_enforce_policy may or may not be set depending on whether
526  * there is a global policy match or per-socket policy match.
527  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
528  * Once the right policy is set on the conn_t, policy cannot change for
529  * this socket. This makes life simpler for TCP (UDP ?) where
530  * re-transmissions go out with the same policy. For symmetry, policy
531  * is cached for fully connected UDP sockets also. Thus if policy is cached,
532  * it also implies that policy is latched i.e policy cannot change
533  * on these sockets. As we have the right policy on the conn, we don't
534  * have to lookup global policy for every outbound and inbound datagram
535  * and thus serving as an optimization. Note that a global policy change
536  * does not affect fully connected sockets if they have policy. If fully
537  * connected sockets did not have any policy associated with it, global
538  * policy change may affect them.
539  *
540  * IP Flow control notes:
541  *
542  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
543  * cannot be sent down to the driver by IP, because of a canput failure, IP
544  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
545  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
546  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
547  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
548  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
549  * the queued messages, and removes the conn from the drain list, if all
550  * messages were drained. It also qenables the next conn in the drain list to
551  * continue the drain process.
552  *
553  * In reality the drain list is not a single list, but a configurable number
554  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
555  * list. If the ip_wsrv of the next qenabled conn does not run, because the
556  * stream closes, ip_close takes responsibility to qenable the next conn in
557  * the drain list. The directly called ip_wput path always does a putq, if
558  * it cannot putnext. Thus synchronization problems are handled between
559  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
560  * functions that manipulate this drain list. Furthermore conn_drain_insert
561  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
562  * running on a queue at any time. conn_drain_tail can be simultaneously called
563  * from both ip_wsrv and ip_close.
564  *
565  * IPQOS notes:
566  *
567  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
568  * and IPQoS modules. IPPF includes hooks in IP at different control points
569  * (callout positions) which direct packets to IPQoS modules for policy
570  * processing. Policies, if present, are global.
571  *
572  * The callout positions are located in the following paths:
573  *		o local_in (packets destined for this host)
574  *		o local_out (packets orginating from this host )
575  *		o fwd_in  (packets forwarded by this m/c - inbound)
576  *		o fwd_out (packets forwarded by this m/c - outbound)
577  * Hooks at these callout points can be enabled/disabled using the ndd variable
578  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
579  * By default all the callout positions are enabled.
580  *
581  * Outbound (local_out)
582  * Hooks are placed in ip_wput_ire and ipsec_out_process.
583  *
584  * Inbound (local_in)
585  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
586  * TCP and UDP fanout routines.
587  *
588  * Forwarding (in and out)
589  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
590  *
591  * IP Policy Framework processing (IPPF processing)
592  * Policy processing for a packet is initiated by ip_process, which ascertains
593  * that the classifier (ipgpc) is loaded and configured, failing which the
594  * packet resumes normal processing in IP. If the clasifier is present, the
595  * packet is acted upon by one or more IPQoS modules (action instances), per
596  * filters configured in ipgpc and resumes normal IP processing thereafter.
597  * An action instance can drop a packet in course of its processing.
598  *
599  * A boolean variable, ip_policy, is used in all the fanout routines that can
600  * invoke ip_process for a packet. This variable indicates if the packet should
601  * to be sent for policy processing. The variable is set to B_TRUE by default,
602  * i.e. when the routines are invoked in the normal ip procesing path for a
603  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
604  * ip_policy is set to B_FALSE for all the routines called in these two
605  * functions because, in the former case,  we don't process loopback traffic
606  * currently while in the latter, the packets have already been processed in
607  * icmp_inbound.
608  *
609  * Zones notes:
610  *
611  * The partitioning rules for networking are as follows:
612  * 1) Packets coming from a zone must have a source address belonging to that
613  * zone.
614  * 2) Packets coming from a zone can only be sent on a physical interface on
615  * which the zone has an IP address.
616  * 3) Between two zones on the same machine, packet delivery is only allowed if
617  * there's a matching route for the destination and zone in the forwarding
618  * table.
619  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
620  * different zones can bind to the same port with the wildcard address
621  * (INADDR_ANY).
622  *
623  * The granularity of interface partitioning is at the logical interface level.
624  * Therefore, every zone has its own IP addresses, and incoming packets can be
625  * attributed to a zone unambiguously. A logical interface is placed into a zone
626  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
627  * structure. Rule (1) is implemented by modifying the source address selection
628  * algorithm so that the list of eligible addresses is filtered based on the
629  * sending process zone.
630  *
631  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
632  * across all zones, depending on their type. Here is the break-up:
633  *
634  * IRE type				Shared/exclusive
635  * --------				----------------
636  * IRE_BROADCAST			Exclusive
637  * IRE_DEFAULT (default routes)		Shared (*)
638  * IRE_LOCAL				Exclusive (x)
639  * IRE_LOOPBACK				Exclusive
640  * IRE_PREFIX (net routes)		Shared (*)
641  * IRE_CACHE				Exclusive
642  * IRE_IF_NORESOLVER (interface routes)	Exclusive
643  * IRE_IF_RESOLVER (interface routes)	Exclusive
644  * IRE_HOST (host routes)		Shared (*)
645  *
646  * (*) A zone can only use a default or off-subnet route if the gateway is
647  * directly reachable from the zone, that is, if the gateway's address matches
648  * one of the zone's logical interfaces.
649  *
650  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
651  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
652  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
653  * address of the zone itself (the destination). Since IRE_LOCAL is used
654  * for communication between zones, ip_wput_ire has special logic to set
655  * the right source address when sending using an IRE_LOCAL.
656  *
657  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
658  * ire_cache_lookup restricts loopback using an IRE_LOCAL
659  * between zone to the case when L2 would have conceptually looped the packet
660  * back, i.e. the loopback which is required since neither Ethernet drivers
661  * nor Ethernet hardware loops them back. This is the case when the normal
662  * routes (ignoring IREs with different zoneids) would send out the packet on
663  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
664  * associated.
665  *
666  * Multiple zones can share a common broadcast address; typically all zones
667  * share the 255.255.255.255 address. Incoming as well as locally originated
668  * broadcast packets must be dispatched to all the zones on the broadcast
669  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
670  * since some zones may not be on the 10.16.72/24 network. To handle this, each
671  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
672  * sent to every zone that has an IRE_BROADCAST entry for the destination
673  * address on the input ill, see conn_wantpacket().
674  *
675  * Applications in different zones can join the same multicast group address.
676  * For IPv4, group memberships are per-logical interface, so they're already
677  * inherently part of a zone. For IPv6, group memberships are per-physical
678  * interface, so we distinguish IPv6 group memberships based on group address,
679  * interface and zoneid. In both cases, received multicast packets are sent to
680  * every zone for which a group membership entry exists. On IPv6 we need to
681  * check that the target zone still has an address on the receiving physical
682  * interface; it could have been removed since the application issued the
683  * IPV6_JOIN_GROUP.
684  */
685 
686 /*
687  * Squeue Fanout flags:
688  *	0: No fanout.
689  *	1: Fanout across all squeues
690  */
691 boolean_t	ip_squeue_fanout = 0;
692 
693 /*
694  * Maximum dups allowed per packet.
695  */
696 uint_t ip_max_frag_dups = 10;
697 
698 #define	IS_SIMPLE_IPH(ipha)						\
699 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
700 
701 /* RFC1122 Conformance */
702 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
703 
704 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
705 
706 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
707 
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
709 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t);
712 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
713     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
714 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
715 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
716 		    mblk_t *, int);
717 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
718 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
719 		    ill_t *, zoneid_t);
720 static void	icmp_options_update(ipha_t *);
721 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t);
722 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
723 		    zoneid_t zoneid);
724 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
725 static void	icmp_redirect(mblk_t *);
726 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
727 
728 static void	ip_arp_news(queue_t *, mblk_t *);
729 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
730 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
731 char		*ip_dot_addr(ipaddr_t, char *);
732 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
733 int		ip_close(queue_t *, int);
734 static char	*ip_dot_saddr(uchar_t *, char *);
735 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
736 		    boolean_t, boolean_t, ill_t *, zoneid_t);
737 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
738 		    boolean_t, boolean_t, zoneid_t);
739 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
740 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
741 static void	ip_lrput(queue_t *, mblk_t *);
742 ipaddr_t	ip_massage_options(ipha_t *);
743 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
744 ipaddr_t	ip_net_mask(ipaddr_t);
745 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
746 		    zoneid_t);
747 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
748 		    conn_t *, uint32_t, zoneid_t);
749 char		*ip_nv_lookup(nv_t *, int);
750 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
751 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
752 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
754 			    size_t);
755 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
756 void	ip_rput(queue_t *, mblk_t *);
757 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
758 		    void *dummy_arg);
759 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
760 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
761 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
762 			    ire_t *);
763 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
764 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
765 		    uint16_t *);
766 int		ip_snmp_get(queue_t *, mblk_t *);
767 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
768 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
769 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
770 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
771 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
772 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
773 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
775 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
777 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
778 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
779 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
780 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
781 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
782 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
783 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
784 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
785 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
786 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
787 static boolean_t	ip_source_routed(ipha_t *);
788 static boolean_t	ip_source_route_included(ipha_t *);
789 
790 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
791 		    zoneid_t);
792 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
793 static void	ip_wput_local_options(ipha_t *);
794 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
795 		    zoneid_t);
796 
797 static void	conn_drain_init(void);
798 static void	conn_drain_fini(void);
799 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
800 
801 static void	conn_walk_drain(void);
802 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
803     zoneid_t);
804 
805 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
806     zoneid_t);
807 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
808     void *dummy_arg);
809 
810 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
811 
812 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
813     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
814     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
815 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
816 
817 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
818 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
819     caddr_t, cred_t *);
820 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
821     caddr_t cp, cred_t *cr);
822 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
823     cred_t *);
824 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
825     caddr_t cp, cred_t *cr);
826 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
827     cred_t *);
828 static squeue_func_t ip_squeue_switch(int);
829 
830 static void	ip_kstat_init(void);
831 static void	ip_kstat_fini(void);
832 static int	ip_kstat_update(kstat_t *kp, int rw);
833 static void	icmp_kstat_init(void);
834 static void	icmp_kstat_fini(void);
835 static int	icmp_kstat_update(kstat_t *kp, int rw);
836 
837 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
838 
839 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
840     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
841 
842 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
843     ipha_t *, ill_t *, boolean_t);
844 
845 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
846 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
847 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
848 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
849 
850 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
851 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
852 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
853 
854 /* How long, in seconds, we allow frags to hang around. */
855 #define	IP_FRAG_TIMEOUT	60
856 
857 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
858 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
859 
860 /*
861  * Threshold which determines whether MDT should be used when
862  * generating IP fragments; payload size must be greater than
863  * this threshold for MDT to take place.
864  */
865 #define	IP_WPUT_FRAG_MDT_MIN	32768
866 
867 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
868 
869 /* Protected by ip_mi_lock */
870 static void	*ip_g_head;		/* Instance Data List Head */
871 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
872 
873 /* Only modified during _init and _fini thus no locking is needed. */
874 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
875 
876 
877 static long ip_rput_pullups;
878 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
879 
880 vmem_t *ip_minor_arena;
881 
882 /*
883  * MIB-2 stuff for SNMP (both IP and ICMP)
884  */
885 mib2_ip_t	ip_mib;
886 mib2_icmp_t	icmp_mib;
887 
888 #ifdef DEBUG
889 uint32_t ipsechw_debug = 0;
890 #endif
891 
892 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
893 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
894 
895 uint_t	loopback_packets = 0;
896 
897 /*
898  * Multirouting/CGTP stuff
899  */
900 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
901 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
902 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
903 /* Interval (in ms) between consecutive 'bad MTU' warnings */
904 hrtime_t ip_multirt_log_interval = 1000;
905 /* Time since last warning issued. */
906 static hrtime_t	multirt_bad_mtu_last_time = 0;
907 
908 kmutex_t ip_trash_timer_lock;
909 krwlock_t ip_g_nd_lock;
910 
911 /*
912  * XXX following really should only be in a header. Would need more
913  * header and .c clean up first.
914  */
915 extern optdb_obj_t	ip_opt_obj;
916 
917 ulong_t ip_squeue_enter_unbound = 0;
918 
919 /*
920  * Named Dispatch Parameter Table.
921  * All of these are alterable, within the min/max values given, at run time.
922  */
923 static ipparam_t	lcl_param_arr[] = {
924 	/* min	max	value	name */
925 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
926 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
927 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
928 	{  0,	1,	0,	"ip_respond_to_timestamp"},
929 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
930 	{  0,	1,	1,	"ip_send_redirects"},
931 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
932 	{  0,	10,	0,	"ip_debug"},
933 	{  0,	10,	0,	"ip_mrtdebug"},
934 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
935 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
936 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
937 	{  1,	255,	255,	"ip_def_ttl" },
938 	{  0,	1,	0,	"ip_forward_src_routed"},
939 	{  0,	256,	32,	"ip_wroff_extra" },
940 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
941 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
942 	{  0,	1,	1,	"ip_path_mtu_discovery" },
943 	{  0,	240,	30,	"ip_ignore_delete_time" },
944 	{  0,	1,	0,	"ip_ignore_redirect" },
945 	{  0,	1,	1,	"ip_output_queue" },
946 	{  1,	254,	1,	"ip_broadcast_ttl" },
947 	{  0,	99999,	100,	"ip_icmp_err_interval" },
948 	{  1,	99999,	10,	"ip_icmp_err_burst" },
949 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
950 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
951 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
952 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
953 	{  0,	1,	1,	"icmp_accept_clear_messages" },
954 	{  0,	1,	1,	"igmp_accept_clear_messages" },
955 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
956 				"ip_ndp_delay_first_probe_time"},
957 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
958 				"ip_ndp_max_unicast_solicit"},
959 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
960 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
961 	{  0,	1,	0,	"ip6_forward_src_routed"},
962 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
963 	{  0,	1,	1,	"ip6_send_redirects"},
964 	{  0,	1,	0,	"ip6_ignore_redirect" },
965 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
966 
967 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
968 
969 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
970 
971 	{  0,	1,	1,	"pim_accept_clear_messages" },
972 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
973 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
974 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
975 	{  0,	15,	0,	"ip_policy_mask" },
976 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
977 	{  0,	255,	1,	"ip_multirt_ttl" },
978 	{  0,	1,	1,	"ip_multidata_outbound" },
979 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
980 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
981 	{  0,	1000,	1,	"ip_max_temp_defend" },
982 	{  0,	1000,	3,	"ip_max_defend" },
983 	{  0,	999999,	30,	"ip_defend_interval" },
984 	{  0,	3600000, 300000, "ip_dup_recovery" },
985 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
986 #ifdef DEBUG
987 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
988 #endif
989 };
990 
991 ipparam_t	*ip_param_arr = lcl_param_arr;
992 
993 /* Extended NDP table */
994 static ipndp_t	lcl_ndp_arr[] = {
995 	/* getf			setf		data			name */
996 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
997 	    "ip_forwarding" },
998 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
999 	    "ip6_forwarding" },
1000 	{  ip_ill_report,	NULL,		NULL,
1001 	    "ip_ill_status" },
1002 	{  ip_ipif_report,	NULL,		NULL,
1003 	    "ip_ipif_status" },
1004 	{  ip_ire_report,	NULL,		NULL,
1005 	    "ipv4_ire_status" },
1006 	{  ip_ire_report_mrtun,	NULL,		NULL,
1007 	    "ipv4_mrtun_ire_status" },
1008 	{  ip_ire_report_srcif,	NULL,		NULL,
1009 	    "ipv4_srcif_ire_status" },
1010 	{  ip_ire_report_v6,	NULL,		NULL,
1011 	    "ipv6_ire_status" },
1012 	{  ip_conn_report,	NULL,		NULL,
1013 	    "ip_conn_status" },
1014 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1015 	    "ip_rput_pullups" },
1016 	{  ndp_report,		NULL,		NULL,
1017 	    "ip_ndp_cache_report" },
1018 	{  ip_srcid_report,	NULL,		NULL,
1019 	    "ip_srcid_status" },
1020 	{ ip_param_generic_get, ip_squeue_profile_set,
1021 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
1022 	{ ip_param_generic_get, ip_squeue_bind_set,
1023 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
1024 	{ ip_param_generic_get, ip_input_proc_set,
1025 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1026 	{ ip_param_generic_get, ip_int_set,
1027 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1028 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
1029 	    "ip_cgtp_filter" },
1030 	{ ip_param_generic_get, ip_int_set,
1031 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
1032 };
1033 
1034 /*
1035  * ip_g_forward controls IP forwarding.  It takes two values:
1036  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
1037  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
1038  *
1039  * RFC1122 says there must be a configuration switch to control forwarding,
1040  * but that the default MUST be to not forward packets ever.  Implicit
1041  * control based on configuration of multiple interfaces MUST NOT be
1042  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
1043  * and, in fact, it was the default.  That capability is now provided in the
1044  * /etc/rc2.d/S69inet script.
1045  */
1046 int ip_g_forward = IP_FORWARD_DEFAULT;
1047 
1048 /* It also has an IPv6 counterpart. */
1049 
1050 int ipv6_forward = IP_FORWARD_DEFAULT;
1051 
1052 /*
1053  * Table of IP ioctls encoding the various properties of the ioctl and
1054  * indexed based on the last byte of the ioctl command. Occasionally there
1055  * is a clash, and there is more than 1 ioctl with the same last byte.
1056  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1057  * ioctls are encoded in the misc table. An entry in the ndx table is
1058  * retrieved by indexing on the last byte of the ioctl command and comparing
1059  * the ioctl command with the value in the ndx table. In the event of a
1060  * mismatch the misc table is then searched sequentially for the desired
1061  * ioctl command.
1062  *
1063  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1064  */
1065 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1066 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 
1077 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1078 			MISC_CMD, ip_siocaddrt, NULL },
1079 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1080 			MISC_CMD, ip_siocdelrt, NULL },
1081 
1082 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1083 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1084 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1085 			IF_CMD, ip_sioctl_get_addr, NULL },
1086 
1087 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1088 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1089 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1090 			IPI_GET_CMD | IPI_REPL,
1091 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1092 
1093 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1094 			IPI_PRIV | IPI_WR | IPI_REPL,
1095 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1096 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1097 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1098 			IF_CMD, ip_sioctl_get_flags, NULL },
1099 
1100 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 
1103 	/* copyin size cannot be coded for SIOCGIFCONF */
1104 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1105 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1106 
1107 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1108 			IF_CMD, ip_sioctl_mtu, NULL },
1109 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1110 			IF_CMD, ip_sioctl_get_mtu, NULL },
1111 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1112 			IPI_GET_CMD | IPI_REPL,
1113 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1114 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1115 			IF_CMD, ip_sioctl_brdaddr, NULL },
1116 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1117 			IPI_GET_CMD | IPI_REPL,
1118 			IF_CMD, ip_sioctl_get_netmask, NULL },
1119 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1120 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1121 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1122 			IPI_GET_CMD | IPI_REPL,
1123 			IF_CMD, ip_sioctl_get_metric, NULL },
1124 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1125 			IF_CMD, ip_sioctl_metric, NULL },
1126 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 
1128 	/* See 166-168 below for extended SIOC*XARP ioctls */
1129 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1130 			MISC_CMD, ip_sioctl_arp, NULL },
1131 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1132 			MISC_CMD, ip_sioctl_arp, NULL },
1133 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1134 			MISC_CMD, ip_sioctl_arp, NULL },
1135 
1136 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 
1158 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1159 			MISC_CMD, if_unitsel, if_unitsel_restart },
1160 
1161 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 
1180 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1181 			IPI_PRIV | IPI_WR | IPI_MODOK,
1182 			IF_CMD, ip_sioctl_sifname, NULL },
1183 
1184 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1190 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 
1198 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1199 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1200 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1201 			IF_CMD, ip_sioctl_get_muxid, NULL },
1202 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1203 			IPI_PRIV | IPI_WR | IPI_REPL,
1204 			IF_CMD, ip_sioctl_muxid, NULL },
1205 
1206 	/* Both if and lif variants share same func */
1207 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1208 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1209 	/* Both if and lif variants share same func */
1210 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1211 			IPI_PRIV | IPI_WR | IPI_REPL,
1212 			IF_CMD, ip_sioctl_slifindex, NULL },
1213 
1214 	/* copyin size cannot be coded for SIOCGIFCONF */
1215 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1216 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1217 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1218 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1219 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1220 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1221 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1222 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1223 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1226 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1227 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1228 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1229 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1230 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1231 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1232 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1233 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1234 
1235 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1236 			IPI_PRIV | IPI_WR | IPI_REPL,
1237 			LIF_CMD, ip_sioctl_removeif,
1238 			ip_sioctl_removeif_restart },
1239 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1240 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1241 			LIF_CMD, ip_sioctl_addif, NULL },
1242 #define	SIOCLIFADDR_NDX 112
1243 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1244 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1245 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1246 			IPI_GET_CMD | IPI_REPL,
1247 			LIF_CMD, ip_sioctl_get_addr, NULL },
1248 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1249 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1250 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1251 			IPI_GET_CMD | IPI_REPL,
1252 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1253 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1254 			IPI_PRIV | IPI_WR | IPI_REPL,
1255 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1256 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1257 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1258 			LIF_CMD, ip_sioctl_get_flags, NULL },
1259 
1260 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1261 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1262 
1263 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1264 			ip_sioctl_get_lifconf, NULL },
1265 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1266 			LIF_CMD, ip_sioctl_mtu, NULL },
1267 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1268 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1269 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1270 			IPI_GET_CMD | IPI_REPL,
1271 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1272 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1273 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1274 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1275 			IPI_GET_CMD | IPI_REPL,
1276 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1277 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1278 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1279 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1280 			IPI_GET_CMD | IPI_REPL,
1281 			LIF_CMD, ip_sioctl_get_metric, NULL },
1282 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1283 			LIF_CMD, ip_sioctl_metric, NULL },
1284 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1285 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1286 			LIF_CMD, ip_sioctl_slifname,
1287 			ip_sioctl_slifname_restart },
1288 
1289 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1290 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1291 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1292 			IPI_GET_CMD | IPI_REPL,
1293 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1294 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1295 			IPI_PRIV | IPI_WR | IPI_REPL,
1296 			LIF_CMD, ip_sioctl_muxid, NULL },
1297 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1298 			IPI_GET_CMD | IPI_REPL,
1299 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1300 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1301 			IPI_PRIV | IPI_WR | IPI_REPL,
1302 			LIF_CMD, ip_sioctl_slifindex, 0 },
1303 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1304 			LIF_CMD, ip_sioctl_token, NULL },
1305 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1306 			IPI_GET_CMD | IPI_REPL,
1307 			LIF_CMD, ip_sioctl_get_token, NULL },
1308 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1309 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1310 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1311 			IPI_GET_CMD | IPI_REPL,
1312 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1313 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1314 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1315 
1316 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1317 			IPI_GET_CMD | IPI_REPL,
1318 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1319 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1320 			LIF_CMD, ip_siocdelndp_v6, NULL },
1321 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1322 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1323 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1324 			LIF_CMD, ip_siocsetndp_v6, NULL },
1325 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1326 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1327 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1328 			MISC_CMD, ip_sioctl_tonlink, NULL },
1329 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1330 			MISC_CMD, ip_sioctl_tmysite, NULL },
1331 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1332 			TUN_CMD, ip_sioctl_tunparam, NULL },
1333 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1334 			IPI_PRIV | IPI_WR,
1335 			TUN_CMD, ip_sioctl_tunparam, NULL },
1336 
1337 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1338 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1339 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1340 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1341 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1342 
1343 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1344 			IPI_PRIV | IPI_WR | IPI_REPL,
1345 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1346 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1347 			IPI_PRIV | IPI_WR | IPI_REPL,
1348 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1349 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1350 			IPI_PRIV | IPI_WR,
1351 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1352 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1353 			IPI_GET_CMD | IPI_REPL,
1354 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1355 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1356 			IPI_GET_CMD | IPI_REPL,
1357 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1358 
1359 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1360 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1361 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1362 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1363 
1364 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1365 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1366 
1367 	/* These are handled in ip_sioctl_copyin_setup itself */
1368 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1369 			MISC_CMD, NULL, NULL },
1370 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1371 			MISC_CMD, NULL, NULL },
1372 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1373 
1374 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1375 			ip_sioctl_get_lifconf, NULL },
1376 
1377 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1378 			MISC_CMD, ip_sioctl_xarp, NULL },
1379 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1380 			MISC_CMD, ip_sioctl_xarp, NULL },
1381 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1382 			MISC_CMD, ip_sioctl_xarp, NULL },
1383 
1384 	/* SIOCPOPSOCKFS is not handled by IP */
1385 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1386 
1387 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1388 			IPI_GET_CMD | IPI_REPL,
1389 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1390 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1391 			IPI_PRIV | IPI_WR | IPI_REPL,
1392 			LIF_CMD, ip_sioctl_slifzone,
1393 			ip_sioctl_slifzone_restart },
1394 	/* 172-174 are SCTP ioctls and not handled by IP */
1395 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1396 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1397 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1398 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1399 			IPI_GET_CMD, LIF_CMD,
1400 			ip_sioctl_get_lifusesrc, 0 },
1401 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1402 			IPI_PRIV | IPI_WR,
1403 			LIF_CMD, ip_sioctl_slifusesrc,
1404 			NULL },
1405 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1406 			ip_sioctl_get_lifsrcof, NULL },
1407 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1408 			MISC_CMD, ip_sioctl_msfilter, NULL },
1409 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1410 			MISC_CMD, ip_sioctl_msfilter, NULL },
1411 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1412 			MISC_CMD, ip_sioctl_msfilter, NULL },
1413 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1414 			MISC_CMD, ip_sioctl_msfilter, NULL },
1415 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1416 			ip_sioctl_set_ipmpfailback, NULL }
1417 };
1418 
1419 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1420 
1421 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1422 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1423 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1424 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1425 		TUN_CMD, ip_sioctl_tunparam, NULL },
1426 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1427 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1428 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1429 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1430 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1431 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1432 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1433 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1434 		MISC_CMD, mrt_ioctl},
1435 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1436 		MISC_CMD, mrt_ioctl},
1437 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1438 		MISC_CMD, mrt_ioctl}
1439 };
1440 
1441 int ip_misc_ioctl_count =
1442     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1443 
1444 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1445 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1446 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1447 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1448 					/* Settable in /etc/system */
1449 uint_t	ip_redirect_cnt;		/* Num of redirect routes in ftable */
1450 
1451 /* Defined in ip_ire.c */
1452 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1453 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1454 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1455 
1456 static nv_t	ire_nv_arr[] = {
1457 	{ IRE_BROADCAST, "BROADCAST" },
1458 	{ IRE_LOCAL, "LOCAL" },
1459 	{ IRE_LOOPBACK, "LOOPBACK" },
1460 	{ IRE_CACHE, "CACHE" },
1461 	{ IRE_DEFAULT, "DEFAULT" },
1462 	{ IRE_PREFIX, "PREFIX" },
1463 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1464 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1465 	{ IRE_HOST, "HOST" },
1466 	{ 0 }
1467 };
1468 
1469 nv_t	*ire_nv_tbl = ire_nv_arr;
1470 
1471 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1472 extern krwlock_t ipsec_capab_ills_lock;
1473 
1474 /* Defined in ip_netinfo.c */
1475 extern ddi_taskq_t	*eventq_queue_nic;
1476 
1477 /* Packet dropper for IP IPsec processing failures */
1478 ipdropper_t ip_dropper;
1479 
1480 /* Simple ICMP IP Header Template */
1481 static ipha_t icmp_ipha = {
1482 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1483 };
1484 
1485 struct module_info ip_mod_info = {
1486 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1487 };
1488 
1489 /*
1490  * Duplicate static symbols within a module confuses mdb; so we avoid the
1491  * problem by making the symbols here distinct from those in udp.c.
1492  */
1493 
1494 static struct qinit iprinit = {
1495 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1496 	&ip_mod_info
1497 };
1498 
1499 static struct qinit ipwinit = {
1500 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1501 	&ip_mod_info
1502 };
1503 
1504 static struct qinit iplrinit = {
1505 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1506 	&ip_mod_info
1507 };
1508 
1509 static struct qinit iplwinit = {
1510 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1511 	&ip_mod_info
1512 };
1513 
1514 struct streamtab ipinfo = {
1515 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1516 };
1517 
1518 #ifdef	DEBUG
1519 static boolean_t skip_sctp_cksum = B_FALSE;
1520 #endif
1521 
1522 /*
1523  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1524  * ip_rput_v6(), ip_output(), etc.  If the message
1525  * block already has a M_CTL at the front of it, then simply set the zoneid
1526  * appropriately.
1527  */
1528 mblk_t *
1529 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid)
1530 {
1531 	mblk_t		*first_mp;
1532 	ipsec_out_t	*io;
1533 
1534 	ASSERT(zoneid != ALL_ZONES);
1535 	if (mp->b_datap->db_type == M_CTL) {
1536 		io = (ipsec_out_t *)mp->b_rptr;
1537 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1538 		io->ipsec_out_zoneid = zoneid;
1539 		return (mp);
1540 	}
1541 
1542 	first_mp = ipsec_alloc_ipsec_out();
1543 	if (first_mp == NULL)
1544 		return (NULL);
1545 	io = (ipsec_out_t *)first_mp->b_rptr;
1546 	/* This is not a secure packet */
1547 	io->ipsec_out_secure = B_FALSE;
1548 	io->ipsec_out_zoneid = zoneid;
1549 	first_mp->b_cont = mp;
1550 	return (first_mp);
1551 }
1552 
1553 /*
1554  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1555  */
1556 mblk_t *
1557 ip_copymsg(mblk_t *mp)
1558 {
1559 	mblk_t *nmp;
1560 	ipsec_info_t *in;
1561 
1562 	if (mp->b_datap->db_type != M_CTL)
1563 		return (copymsg(mp));
1564 
1565 	in = (ipsec_info_t *)mp->b_rptr;
1566 
1567 	/*
1568 	 * Note that M_CTL is also used for delivering ICMP error messages
1569 	 * upstream to transport layers.
1570 	 */
1571 	if (in->ipsec_info_type != IPSEC_OUT &&
1572 	    in->ipsec_info_type != IPSEC_IN)
1573 		return (copymsg(mp));
1574 
1575 	nmp = copymsg(mp->b_cont);
1576 
1577 	if (in->ipsec_info_type == IPSEC_OUT)
1578 		return (ipsec_out_tag(mp, nmp));
1579 	else
1580 		return (ipsec_in_tag(mp, nmp));
1581 }
1582 
1583 /* Generate an ICMP fragmentation needed message. */
1584 static void
1585 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid)
1586 {
1587 	icmph_t	icmph;
1588 	mblk_t *first_mp;
1589 	boolean_t mctl_present;
1590 
1591 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1592 
1593 	if (!(mp = icmp_pkt_err_ok(mp))) {
1594 		if (mctl_present)
1595 			freeb(first_mp);
1596 		return;
1597 	}
1598 
1599 	bzero(&icmph, sizeof (icmph_t));
1600 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1601 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1602 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1603 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1604 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1605 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
1606 }
1607 
1608 /*
1609  * icmp_inbound deals with ICMP messages in the following ways.
1610  *
1611  * 1) It needs to send a reply back and possibly delivering it
1612  *    to the "interested" upper clients.
1613  * 2) It needs to send it to the upper clients only.
1614  * 3) It needs to change some values in IP only.
1615  * 4) It needs to change some values in IP and upper layers e.g TCP.
1616  *
1617  * We need to accomodate icmp messages coming in clear until we get
1618  * everything secure from the wire. If icmp_accept_clear_messages
1619  * is zero we check with the global policy and act accordingly. If
1620  * it is non-zero, we accept the message without any checks. But
1621  * *this does not mean* that this will be delivered to the upper
1622  * clients. By accepting we might send replies back, change our MTU
1623  * value etc. but delivery to the ULP/clients depends on their policy
1624  * dispositions.
1625  *
1626  * We handle the above 4 cases in the context of IPSEC in the
1627  * following way :
1628  *
1629  * 1) Send the reply back in the same way as the request came in.
1630  *    If it came in encrypted, it goes out encrypted. If it came in
1631  *    clear, it goes out in clear. Thus, this will prevent chosen
1632  *    plain text attack.
1633  * 2) The client may or may not expect things to come in secure.
1634  *    If it comes in secure, the policy constraints are checked
1635  *    before delivering it to the upper layers. If it comes in
1636  *    clear, ipsec_inbound_accept_clear will decide whether to
1637  *    accept this in clear or not. In both the cases, if the returned
1638  *    message (IP header + 8 bytes) that caused the icmp message has
1639  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1640  *    sending up. If there are only 8 bytes of returned message, then
1641  *    upper client will not be notified.
1642  * 3) Check with global policy to see whether it matches the constaints.
1643  *    But this will be done only if icmp_accept_messages_in_clear is
1644  *    zero.
1645  * 4) If we need to change both in IP and ULP, then the decision taken
1646  *    while affecting the values in IP and while delivering up to TCP
1647  *    should be the same.
1648  *
1649  * 	There are two cases.
1650  *
1651  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1652  *	   failed), we will not deliver it to the ULP, even though they
1653  *	   are *willing* to accept in *clear*. This is fine as our global
1654  *	   disposition to icmp messages asks us reject the datagram.
1655  *
1656  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1657  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1658  *	   to deliver it to ULP (policy failed), it can lead to
1659  *	   consistency problems. The cases known at this time are
1660  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1661  *	   values :
1662  *
1663  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1664  *	     and Upper layer rejects. Then the communication will
1665  *	     come to a stop. This is solved by making similar decisions
1666  *	     at both levels. Currently, when we are unable to deliver
1667  *	     to the Upper Layer (due to policy failures) while IP has
1668  *	     adjusted ire_max_frag, the next outbound datagram would
1669  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1670  *	     will be with the right level of protection. Thus the right
1671  *	     value will be communicated even if we are not able to
1672  *	     communicate when we get from the wire initially. But this
1673  *	     assumes there would be at least one outbound datagram after
1674  *	     IP has adjusted its ire_max_frag value. To make things
1675  *	     simpler, we accept in clear after the validation of
1676  *	     AH/ESP headers.
1677  *
1678  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1679  *	     upper layer depending on the level of protection the upper
1680  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1681  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1682  *	     should be accepted in clear when the Upper layer expects secure.
1683  *	     Thus the communication may get aborted by some bad ICMP
1684  *	     packets.
1685  *
1686  * IPQoS Notes:
1687  * The only instance when a packet is sent for processing is when there
1688  * isn't an ICMP client and if we are interested in it.
1689  * If there is a client, IPPF processing will take place in the
1690  * ip_fanout_proto routine.
1691  *
1692  * Zones notes:
1693  * The packet is only processed in the context of the specified zone: typically
1694  * only this zone will reply to an echo request, and only interested clients in
1695  * this zone will receive a copy of the packet. This means that the caller must
1696  * call icmp_inbound() for each relevant zone.
1697  */
1698 static void
1699 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1700     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1701     ill_t *recv_ill, zoneid_t zoneid)
1702 {
1703 	icmph_t	*icmph;
1704 	ipha_t	*ipha;
1705 	int	iph_hdr_length;
1706 	int	hdr_length;
1707 	boolean_t	interested;
1708 	uint32_t	ts;
1709 	uchar_t	*wptr;
1710 	ipif_t	*ipif;
1711 	mblk_t *first_mp;
1712 	ipsec_in_t *ii;
1713 	ire_t *src_ire;
1714 	boolean_t onlink;
1715 	timestruc_t now;
1716 	uint32_t ill_index;
1717 
1718 	ASSERT(ill != NULL);
1719 
1720 	first_mp = mp;
1721 	if (mctl_present) {
1722 		mp = first_mp->b_cont;
1723 		ASSERT(mp != NULL);
1724 	}
1725 
1726 	ipha = (ipha_t *)mp->b_rptr;
1727 	if (icmp_accept_clear_messages == 0) {
1728 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1729 		    ipha, NULL, mctl_present);
1730 		if (first_mp == NULL)
1731 			return;
1732 	}
1733 
1734 	/*
1735 	 * On a labeled system, we have to check whether the zone itself is
1736 	 * permitted to receive raw traffic.
1737 	 */
1738 	if (is_system_labeled()) {
1739 		if (zoneid == ALL_ZONES)
1740 			zoneid = tsol_packet_to_zoneid(mp);
1741 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1742 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1743 			    zoneid));
1744 			BUMP_MIB(&icmp_mib, icmpInErrors);
1745 			freemsg(first_mp);
1746 			return;
1747 		}
1748 	}
1749 
1750 	/*
1751 	 * We have accepted the ICMP message. It means that we will
1752 	 * respond to the packet if needed. It may not be delivered
1753 	 * to the upper client depending on the policy constraints
1754 	 * and the disposition in ipsec_inbound_accept_clear.
1755 	 */
1756 
1757 	ASSERT(ill != NULL);
1758 
1759 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1760 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1761 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1762 		/* Last chance to get real. */
1763 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1764 			BUMP_MIB(&icmp_mib, icmpInErrors);
1765 			freemsg(first_mp);
1766 			return;
1767 		}
1768 		/* Refresh iph following the pullup. */
1769 		ipha = (ipha_t *)mp->b_rptr;
1770 	}
1771 	/* ICMP header checksum, including checksum field, should be zero. */
1772 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1773 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1774 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1775 		freemsg(first_mp);
1776 		return;
1777 	}
1778 	/* The IP header will always be a multiple of four bytes */
1779 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1780 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1781 	    icmph->icmph_code));
1782 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1783 	/* We will set "interested" to "true" if we want a copy */
1784 	interested = B_FALSE;
1785 	switch (icmph->icmph_type) {
1786 	case ICMP_ECHO_REPLY:
1787 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1788 		break;
1789 	case ICMP_DEST_UNREACHABLE:
1790 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1791 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1792 		interested = B_TRUE;	/* Pass up to transport */
1793 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1794 		break;
1795 	case ICMP_SOURCE_QUENCH:
1796 		interested = B_TRUE;	/* Pass up to transport */
1797 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1798 		break;
1799 	case ICMP_REDIRECT:
1800 		if (!ip_ignore_redirect)
1801 			interested = B_TRUE;
1802 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1803 		break;
1804 	case ICMP_ECHO_REQUEST:
1805 		/*
1806 		 * Whether to respond to echo requests that come in as IP
1807 		 * broadcasts or as IP multicast is subject to debate
1808 		 * (what isn't?).  We aim to please, you pick it.
1809 		 * Default is do it.
1810 		 */
1811 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1812 			/* unicast: always respond */
1813 			interested = B_TRUE;
1814 		} else if (CLASSD(ipha->ipha_dst)) {
1815 			/* multicast: respond based on tunable */
1816 			interested = ip_g_resp_to_echo_mcast;
1817 		} else if (broadcast) {
1818 			/* broadcast: respond based on tunable */
1819 			interested = ip_g_resp_to_echo_bcast;
1820 		}
1821 		BUMP_MIB(&icmp_mib, icmpInEchos);
1822 		break;
1823 	case ICMP_ROUTER_ADVERTISEMENT:
1824 	case ICMP_ROUTER_SOLICITATION:
1825 		break;
1826 	case ICMP_TIME_EXCEEDED:
1827 		interested = B_TRUE;	/* Pass up to transport */
1828 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1829 		break;
1830 	case ICMP_PARAM_PROBLEM:
1831 		interested = B_TRUE;	/* Pass up to transport */
1832 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1833 		break;
1834 	case ICMP_TIME_STAMP_REQUEST:
1835 		/* Response to Time Stamp Requests is local policy. */
1836 		if (ip_g_resp_to_timestamp &&
1837 		    /* So is whether to respond if it was an IP broadcast. */
1838 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1839 			int tstamp_len = 3 * sizeof (uint32_t);
1840 
1841 			if (wptr +  tstamp_len > mp->b_wptr) {
1842 				if (!pullupmsg(mp, wptr + tstamp_len -
1843 				    mp->b_rptr)) {
1844 					BUMP_MIB(&ip_mib, ipInDiscards);
1845 					freemsg(first_mp);
1846 					return;
1847 				}
1848 				/* Refresh ipha following the pullup. */
1849 				ipha = (ipha_t *)mp->b_rptr;
1850 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1851 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1852 			}
1853 			interested = B_TRUE;
1854 		}
1855 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1856 		break;
1857 	case ICMP_TIME_STAMP_REPLY:
1858 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1859 		break;
1860 	case ICMP_INFO_REQUEST:
1861 		/* Per RFC 1122 3.2.2.7, ignore this. */
1862 	case ICMP_INFO_REPLY:
1863 		break;
1864 	case ICMP_ADDRESS_MASK_REQUEST:
1865 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1866 		    /* TODO m_pullup of complete header? */
1867 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1868 			interested = B_TRUE;
1869 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1870 		break;
1871 	case ICMP_ADDRESS_MASK_REPLY:
1872 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1873 		break;
1874 	default:
1875 		interested = B_TRUE;	/* Pass up to transport */
1876 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1877 		break;
1878 	}
1879 	/* See if there is an ICMP client. */
1880 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1881 		/* If there is an ICMP client and we want one too, copy it. */
1882 		mblk_t *first_mp1;
1883 
1884 		if (!interested) {
1885 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1886 			    ip_policy, recv_ill, zoneid);
1887 			return;
1888 		}
1889 		first_mp1 = ip_copymsg(first_mp);
1890 		if (first_mp1 != NULL) {
1891 			ip_fanout_proto(q, first_mp1, ill, ipha,
1892 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1893 		}
1894 	} else if (!interested) {
1895 		freemsg(first_mp);
1896 		return;
1897 	} else {
1898 		/*
1899 		 * Initiate policy processing for this packet if ip_policy
1900 		 * is true.
1901 		 */
1902 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1903 			ill_index = ill->ill_phyint->phyint_ifindex;
1904 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1905 			if (mp == NULL) {
1906 				if (mctl_present) {
1907 					freeb(first_mp);
1908 				}
1909 				BUMP_MIB(&icmp_mib, icmpInErrors);
1910 				return;
1911 			}
1912 		}
1913 	}
1914 	/* We want to do something with it. */
1915 	/* Check db_ref to make sure we can modify the packet. */
1916 	if (mp->b_datap->db_ref > 1) {
1917 		mblk_t	*first_mp1;
1918 
1919 		first_mp1 = ip_copymsg(first_mp);
1920 		freemsg(first_mp);
1921 		if (!first_mp1) {
1922 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1923 			return;
1924 		}
1925 		first_mp = first_mp1;
1926 		if (mctl_present) {
1927 			mp = first_mp->b_cont;
1928 			ASSERT(mp != NULL);
1929 		} else {
1930 			mp = first_mp;
1931 		}
1932 		ipha = (ipha_t *)mp->b_rptr;
1933 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1934 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1935 	}
1936 	switch (icmph->icmph_type) {
1937 	case ICMP_ADDRESS_MASK_REQUEST:
1938 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1939 		if (ipif == NULL) {
1940 			freemsg(first_mp);
1941 			return;
1942 		}
1943 		/*
1944 		 * outging interface must be IPv4
1945 		 */
1946 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1947 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1948 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1949 		ipif_refrele(ipif);
1950 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1951 		break;
1952 	case ICMP_ECHO_REQUEST:
1953 		icmph->icmph_type = ICMP_ECHO_REPLY;
1954 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1955 		break;
1956 	case ICMP_TIME_STAMP_REQUEST: {
1957 		uint32_t *tsp;
1958 
1959 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1960 		tsp = (uint32_t *)wptr;
1961 		tsp++;		/* Skip past 'originate time' */
1962 		/* Compute # of milliseconds since midnight */
1963 		gethrestime(&now);
1964 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1965 		    now.tv_nsec / (NANOSEC / MILLISEC);
1966 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1967 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1968 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1969 		break;
1970 	}
1971 	default:
1972 		ipha = (ipha_t *)&icmph[1];
1973 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1974 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1975 				BUMP_MIB(&ip_mib, ipInDiscards);
1976 				freemsg(first_mp);
1977 				return;
1978 			}
1979 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1980 			ipha = (ipha_t *)&icmph[1];
1981 		}
1982 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1983 			BUMP_MIB(&ip_mib, ipInDiscards);
1984 			freemsg(first_mp);
1985 			return;
1986 		}
1987 		hdr_length = IPH_HDR_LENGTH(ipha);
1988 		if (hdr_length < sizeof (ipha_t)) {
1989 			BUMP_MIB(&ip_mib, ipInDiscards);
1990 			freemsg(first_mp);
1991 			return;
1992 		}
1993 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1994 			if (!pullupmsg(mp,
1995 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1996 				BUMP_MIB(&ip_mib, ipInDiscards);
1997 				freemsg(first_mp);
1998 				return;
1999 			}
2000 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2001 			ipha = (ipha_t *)&icmph[1];
2002 		}
2003 		switch (icmph->icmph_type) {
2004 		case ICMP_REDIRECT:
2005 			/*
2006 			 * As there is no upper client to deliver, we don't
2007 			 * need the first_mp any more.
2008 			 */
2009 			if (mctl_present) {
2010 				freeb(first_mp);
2011 			}
2012 			icmp_redirect(mp);
2013 			return;
2014 		case ICMP_DEST_UNREACHABLE:
2015 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
2016 				if (!icmp_inbound_too_big(icmph, ipha, ill,
2017 				    zoneid, mp, iph_hdr_length)) {
2018 					freemsg(first_mp);
2019 					return;
2020 				}
2021 				/*
2022 				 * icmp_inbound_too_big() may alter mp.
2023 				 * Resynch ipha and icmph accordingly.
2024 				 */
2025 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2026 				ipha = (ipha_t *)&icmph[1];
2027 			}
2028 			/* FALLTHRU */
2029 		default :
2030 			/*
2031 			 * IPQoS notes: Since we have already done IPQoS
2032 			 * processing we don't want to do it again in
2033 			 * the fanout routines called by
2034 			 * icmp_inbound_error_fanout, hence the last
2035 			 * argument, ip_policy, is B_FALSE.
2036 			 */
2037 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2038 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2039 			    B_FALSE, recv_ill, zoneid);
2040 		}
2041 		return;
2042 	}
2043 	/* Send out an ICMP packet */
2044 	icmph->icmph_checksum = 0;
2045 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2046 	if (icmph->icmph_checksum == 0)
2047 		icmph->icmph_checksum = 0xFFFF;
2048 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2049 		ipif_t	*ipif_chosen;
2050 		/*
2051 		 * Make it look like it was directed to us, so we don't look
2052 		 * like a fool with a broadcast or multicast source address.
2053 		 */
2054 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2055 		/*
2056 		 * Make sure that we haven't grabbed an interface that's DOWN.
2057 		 */
2058 		if (ipif != NULL) {
2059 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2060 			    ipha->ipha_src, zoneid);
2061 			if (ipif_chosen != NULL) {
2062 				ipif_refrele(ipif);
2063 				ipif = ipif_chosen;
2064 			}
2065 		}
2066 		if (ipif == NULL) {
2067 			ip0dbg(("icmp_inbound: "
2068 			    "No source for broadcast/multicast:\n"
2069 			    "\tsrc 0x%x dst 0x%x ill %p "
2070 			    "ipif_lcl_addr 0x%x\n",
2071 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2072 			    (void *)ill,
2073 			    ill->ill_ipif->ipif_lcl_addr));
2074 			freemsg(first_mp);
2075 			return;
2076 		}
2077 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2078 		ipha->ipha_dst = ipif->ipif_src_addr;
2079 		ipif_refrele(ipif);
2080 	}
2081 	/* Reset time to live. */
2082 	ipha->ipha_ttl = ip_def_ttl;
2083 	{
2084 		/* Swap source and destination addresses */
2085 		ipaddr_t tmp;
2086 
2087 		tmp = ipha->ipha_src;
2088 		ipha->ipha_src = ipha->ipha_dst;
2089 		ipha->ipha_dst = tmp;
2090 	}
2091 	ipha->ipha_ident = 0;
2092 	if (!IS_SIMPLE_IPH(ipha))
2093 		icmp_options_update(ipha);
2094 
2095 	/*
2096 	 * ICMP echo replies should go out on the same interface
2097 	 * the request came on as probes used by in.mpathd for detecting
2098 	 * NIC failures are ECHO packets. We turn-off load spreading
2099 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2100 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2101 	 * function. This is in turn handled by ip_wput and ip_newroute
2102 	 * to make sure that the packet goes out on the interface it came
2103 	 * in on. If we don't turnoff load spreading, the packets might get
2104 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2105 	 * to go out and in.mpathd would wrongly detect a failure or
2106 	 * mis-detect a NIC failure for link failure. As load spreading
2107 	 * can happen only if ill_group is not NULL, we do only for
2108 	 * that case and this does not affect the normal case.
2109 	 *
2110 	 * We turn off load spreading only on echo packets that came from
2111 	 * on-link hosts. If the interface route has been deleted, this will
2112 	 * not be enforced as we can't do much. For off-link hosts, as the
2113 	 * default routes in IPv4 does not typically have an ire_ipif
2114 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2115 	 * Moreover, expecting a default route through this interface may
2116 	 * not be correct. We use ipha_dst because of the swap above.
2117 	 */
2118 	onlink = B_FALSE;
2119 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2120 		/*
2121 		 * First, we need to make sure that it is not one of our
2122 		 * local addresses. If we set onlink when it is one of
2123 		 * our local addresses, we will end up creating IRE_CACHES
2124 		 * for one of our local addresses. Then, we will never
2125 		 * accept packets for them afterwards.
2126 		 */
2127 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2128 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2129 		if (src_ire == NULL) {
2130 			ipif = ipif_get_next_ipif(NULL, ill);
2131 			if (ipif == NULL) {
2132 				BUMP_MIB(&ip_mib, ipInDiscards);
2133 				freemsg(mp);
2134 				return;
2135 			}
2136 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2137 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2138 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2139 			ipif_refrele(ipif);
2140 			if (src_ire != NULL) {
2141 				onlink = B_TRUE;
2142 				ire_refrele(src_ire);
2143 			}
2144 		} else {
2145 			ire_refrele(src_ire);
2146 		}
2147 	}
2148 	if (!mctl_present) {
2149 		/*
2150 		 * This packet should go out the same way as it
2151 		 * came in i.e in clear. To make sure that global
2152 		 * policy will not be applied to this in ip_wput_ire,
2153 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2154 		 */
2155 		ASSERT(first_mp == mp);
2156 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2157 			BUMP_MIB(&ip_mib, ipInDiscards);
2158 			freemsg(mp);
2159 			return;
2160 		}
2161 		ii = (ipsec_in_t *)first_mp->b_rptr;
2162 
2163 		/* This is not a secure packet */
2164 		ii->ipsec_in_secure = B_FALSE;
2165 		if (onlink) {
2166 			ii->ipsec_in_attach_if = B_TRUE;
2167 			ii->ipsec_in_ill_index =
2168 			    ill->ill_phyint->phyint_ifindex;
2169 			ii->ipsec_in_rill_index =
2170 			    recv_ill->ill_phyint->phyint_ifindex;
2171 		}
2172 		first_mp->b_cont = mp;
2173 	} else if (onlink) {
2174 		ii = (ipsec_in_t *)first_mp->b_rptr;
2175 		ii->ipsec_in_attach_if = B_TRUE;
2176 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2177 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2178 	} else {
2179 		ii = (ipsec_in_t *)first_mp->b_rptr;
2180 	}
2181 	ii->ipsec_in_zoneid = zoneid;
2182 	ASSERT(zoneid != ALL_ZONES);
2183 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2184 		BUMP_MIB(&ip_mib, ipInDiscards);
2185 		return;
2186 	}
2187 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2188 	put(WR(q), first_mp);
2189 }
2190 
2191 static ipaddr_t
2192 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2193 {
2194 	conn_t *connp;
2195 	connf_t *connfp;
2196 	ipaddr_t nexthop_addr = INADDR_ANY;
2197 	int hdr_length = IPH_HDR_LENGTH(ipha);
2198 	uint16_t *up;
2199 	uint32_t ports;
2200 
2201 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2202 	switch (ipha->ipha_protocol) {
2203 		case IPPROTO_TCP:
2204 		{
2205 			tcph_t *tcph;
2206 
2207 			/* do a reverse lookup */
2208 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2209 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2210 			    TCPS_LISTEN);
2211 			break;
2212 		}
2213 		case IPPROTO_UDP:
2214 		{
2215 			uint32_t dstport, srcport;
2216 
2217 			((uint16_t *)&ports)[0] = up[1];
2218 			((uint16_t *)&ports)[1] = up[0];
2219 
2220 			/* Extract ports in net byte order */
2221 			dstport = htons(ntohl(ports) & 0xFFFF);
2222 			srcport = htons(ntohl(ports) >> 16);
2223 
2224 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2225 			mutex_enter(&connfp->connf_lock);
2226 			connp = connfp->connf_head;
2227 
2228 			/* do a reverse lookup */
2229 			while ((connp != NULL) &&
2230 			    (!IPCL_UDP_MATCH(connp, dstport,
2231 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2232 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2233 				connp = connp->conn_next;
2234 			}
2235 			if (connp != NULL)
2236 				CONN_INC_REF(connp);
2237 			mutex_exit(&connfp->connf_lock);
2238 			break;
2239 		}
2240 		case IPPROTO_SCTP:
2241 		{
2242 			in6_addr_t map_src, map_dst;
2243 
2244 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2245 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2246 			((uint16_t *)&ports)[0] = up[1];
2247 			((uint16_t *)&ports)[1] = up[0];
2248 
2249 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2250 			    0, zoneid)) == NULL) {
2251 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2252 				    zoneid, ports, ipha);
2253 			} else {
2254 				CONN_INC_REF(connp);
2255 				SCTP_REFRELE(CONN2SCTP(connp));
2256 			}
2257 			break;
2258 		}
2259 		default:
2260 		{
2261 			ipha_t ripha;
2262 
2263 			ripha.ipha_src = ipha->ipha_dst;
2264 			ripha.ipha_dst = ipha->ipha_src;
2265 			ripha.ipha_protocol = ipha->ipha_protocol;
2266 
2267 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2268 			mutex_enter(&connfp->connf_lock);
2269 			connp = connfp->connf_head;
2270 			for (connp = connfp->connf_head; connp != NULL;
2271 			    connp = connp->conn_next) {
2272 				if (IPCL_PROTO_MATCH(connp,
2273 				    ipha->ipha_protocol, &ripha, ill,
2274 				    0, zoneid)) {
2275 					CONN_INC_REF(connp);
2276 					break;
2277 				}
2278 			}
2279 			mutex_exit(&connfp->connf_lock);
2280 		}
2281 	}
2282 	if (connp != NULL) {
2283 		if (connp->conn_nexthop_set)
2284 			nexthop_addr = connp->conn_nexthop_v4;
2285 		CONN_DEC_REF(connp);
2286 	}
2287 	return (nexthop_addr);
2288 }
2289 
2290 /* Table from RFC 1191 */
2291 static int icmp_frag_size_table[] =
2292 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2293 
2294 /*
2295  * Process received ICMP Packet too big.
2296  * After updating any IRE it does the fanout to any matching transport streams.
2297  * Assumes the message has been pulled up till the IP header that caused
2298  * the error.
2299  *
2300  * Returns B_FALSE on failure and B_TRUE on success.
2301  */
2302 static boolean_t
2303 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2304     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2305 {
2306 	ire_t	*ire, *first_ire;
2307 	int	mtu;
2308 	int	hdr_length;
2309 	ipaddr_t nexthop_addr;
2310 
2311 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2312 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2313 
2314 	hdr_length = IPH_HDR_LENGTH(ipha);
2315 
2316 	/* Drop if the original packet contained a source route */
2317 	if (ip_source_route_included(ipha)) {
2318 		return (B_FALSE);
2319 	}
2320 	/*
2321 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2322 	 * header.
2323 	 */
2324 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2325 	    mp->b_wptr) {
2326 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2327 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2328 			BUMP_MIB(&ip_mib, ipInDiscards);
2329 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2330 			return (B_FALSE);
2331 		}
2332 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2333 		ipha = (ipha_t *)&icmph[1];
2334 	}
2335 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2336 	if (nexthop_addr != INADDR_ANY) {
2337 		/* nexthop set */
2338 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2339 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2340 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2341 	} else {
2342 		/* nexthop not set */
2343 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2344 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2345 	}
2346 
2347 	if (!first_ire) {
2348 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2349 		    ntohl(ipha->ipha_dst)));
2350 		return (B_FALSE);
2351 	}
2352 	/* Check for MTU discovery advice as described in RFC 1191 */
2353 	mtu = ntohs(icmph->icmph_du_mtu);
2354 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2355 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2356 	    ire = ire->ire_next) {
2357 		/*
2358 		 * Look for the connection to which this ICMP message is
2359 		 * directed. If it has the IP_NEXTHOP option set, then the
2360 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2361 		 * option. Else the search is limited to regular IREs.
2362 		 */
2363 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2364 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2365 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2366 		    (nexthop_addr != INADDR_ANY)))
2367 			continue;
2368 
2369 		mutex_enter(&ire->ire_lock);
2370 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2371 			/* Reduce the IRE max frag value as advised. */
2372 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2373 			    mtu, ire->ire_max_frag));
2374 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2375 		} else {
2376 			uint32_t length;
2377 			int	i;
2378 
2379 			/*
2380 			 * Use the table from RFC 1191 to figure out
2381 			 * the next "plateau" based on the length in
2382 			 * the original IP packet.
2383 			 */
2384 			length = ntohs(ipha->ipha_length);
2385 			if (ire->ire_max_frag <= length &&
2386 			    ire->ire_max_frag >= length - hdr_length) {
2387 				/*
2388 				 * Handle broken BSD 4.2 systems that
2389 				 * return the wrong iph_length in ICMP
2390 				 * errors.
2391 				 */
2392 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2393 				    length, ire->ire_max_frag));
2394 				length -= hdr_length;
2395 			}
2396 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2397 				if (length > icmp_frag_size_table[i])
2398 					break;
2399 			}
2400 			if (i == A_CNT(icmp_frag_size_table)) {
2401 				/* Smaller than 68! */
2402 				ip1dbg(("Too big for packet size %d\n",
2403 				    length));
2404 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2405 				ire->ire_frag_flag = 0;
2406 			} else {
2407 				mtu = icmp_frag_size_table[i];
2408 				ip1dbg(("Calculated mtu %d, packet size %d, "
2409 				    "before %d", mtu, length,
2410 				    ire->ire_max_frag));
2411 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2412 				ip1dbg((", after %d\n", ire->ire_max_frag));
2413 			}
2414 			/* Record the new max frag size for the ULP. */
2415 			icmph->icmph_du_zero = 0;
2416 			icmph->icmph_du_mtu =
2417 			    htons((uint16_t)ire->ire_max_frag);
2418 		}
2419 		mutex_exit(&ire->ire_lock);
2420 	}
2421 	rw_exit(&first_ire->ire_bucket->irb_lock);
2422 	ire_refrele(first_ire);
2423 	return (B_TRUE);
2424 }
2425 
2426 /*
2427  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2428  * calls this function.
2429  */
2430 static mblk_t *
2431 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2432 {
2433 	ipha_t *ipha;
2434 	icmph_t *icmph;
2435 	ipha_t *in_ipha;
2436 	int length;
2437 
2438 	ASSERT(mp->b_datap->db_type == M_DATA);
2439 
2440 	/*
2441 	 * For Self-encapsulated packets, we added an extra IP header
2442 	 * without the options. Inner IP header is the one from which
2443 	 * the outer IP header was formed. Thus, we need to remove the
2444 	 * outer IP header. To do this, we pullup the whole message
2445 	 * and overlay whatever follows the outer IP header over the
2446 	 * outer IP header.
2447 	 */
2448 
2449 	if (!pullupmsg(mp, -1)) {
2450 		BUMP_MIB(&ip_mib, ipInDiscards);
2451 		return (NULL);
2452 	}
2453 
2454 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2455 	ipha = (ipha_t *)&icmph[1];
2456 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2457 
2458 	/*
2459 	 * The length that we want to overlay is following the inner
2460 	 * IP header. Subtracting the IP header + icmp header + outer
2461 	 * IP header's length should give us the length that we want to
2462 	 * overlay.
2463 	 */
2464 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2465 	    hdr_length;
2466 	/*
2467 	 * Overlay whatever follows the inner header over the
2468 	 * outer header.
2469 	 */
2470 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2471 
2472 	/* Set the wptr to account for the outer header */
2473 	mp->b_wptr -= hdr_length;
2474 	return (mp);
2475 }
2476 
2477 /*
2478  * Try to pass the ICMP message upstream in case the ULP cares.
2479  *
2480  * If the packet that caused the ICMP error is secure, we send
2481  * it to AH/ESP to make sure that the attached packet has a
2482  * valid association. ipha in the code below points to the
2483  * IP header of the packet that caused the error.
2484  *
2485  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2486  * in the context of IPSEC. Normally we tell the upper layer
2487  * whenever we send the ire (including ip_bind), the IPSEC header
2488  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2489  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2490  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2491  * same thing. As TCP has the IPSEC options size that needs to be
2492  * adjusted, we just pass the MTU unchanged.
2493  *
2494  * IFN could have been generated locally or by some router.
2495  *
2496  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2497  *	    This happens because IP adjusted its value of MTU on an
2498  *	    earlier IFN message and could not tell the upper layer,
2499  *	    the new adjusted value of MTU e.g. Packet was encrypted
2500  *	    or there was not enough information to fanout to upper
2501  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2502  *	    generates the IFN, where IPSEC processing has *not* been
2503  *	    done.
2504  *
2505  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2506  *	    could have generated this. This happens because ire_max_frag
2507  *	    value in IP was set to a new value, while the IPSEC processing
2508  *	    was being done and after we made the fragmentation check in
2509  *	    ip_wput_ire. Thus on return from IPSEC processing,
2510  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2511  *	    and generates the IFN. As IPSEC processing is over, we fanout
2512  *	    to AH/ESP to remove the header.
2513  *
2514  *	    In both these cases, ipsec_in_loopback will be set indicating
2515  *	    that IFN was generated locally.
2516  *
2517  * ROUTER : IFN could be secure or non-secure.
2518  *
2519  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2520  *	      packet in error has AH/ESP headers to validate the AH/ESP
2521  *	      headers. AH/ESP will verify whether there is a valid SA or
2522  *	      not and send it back. We will fanout again if we have more
2523  *	      data in the packet.
2524  *
2525  *	      If the packet in error does not have AH/ESP, we handle it
2526  *	      like any other case.
2527  *
2528  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2529  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2530  *	      for validation. AH/ESP will verify whether there is a
2531  *	      valid SA or not and send it back. We will fanout again if
2532  *	      we have more data in the packet.
2533  *
2534  *	      If the packet in error does not have AH/ESP, we handle it
2535  *	      like any other case.
2536  */
2537 static void
2538 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2539     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2540     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2541     zoneid_t zoneid)
2542 {
2543 	uint16_t *up;	/* Pointer to ports in ULP header */
2544 	uint32_t ports;	/* reversed ports for fanout */
2545 	ipha_t ripha;	/* With reversed addresses */
2546 	mblk_t *first_mp;
2547 	ipsec_in_t *ii;
2548 	tcph_t	*tcph;
2549 	conn_t	*connp;
2550 
2551 	first_mp = mp;
2552 	if (mctl_present) {
2553 		mp = first_mp->b_cont;
2554 		ASSERT(mp != NULL);
2555 
2556 		ii = (ipsec_in_t *)first_mp->b_rptr;
2557 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2558 	} else {
2559 		ii = NULL;
2560 	}
2561 
2562 	switch (ipha->ipha_protocol) {
2563 	case IPPROTO_UDP:
2564 		/*
2565 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2566 		 * transport header.
2567 		 */
2568 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2569 		    mp->b_wptr) {
2570 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2571 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2572 				BUMP_MIB(&ip_mib, ipInDiscards);
2573 				goto drop_pkt;
2574 			}
2575 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2576 			ipha = (ipha_t *)&icmph[1];
2577 		}
2578 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2579 
2580 		/*
2581 		 * Attempt to find a client stream based on port.
2582 		 * Note that we do a reverse lookup since the header is
2583 		 * in the form we sent it out.
2584 		 * The ripha header is only used for the IP_UDP_MATCH and we
2585 		 * only set the src and dst addresses and protocol.
2586 		 */
2587 		ripha.ipha_src = ipha->ipha_dst;
2588 		ripha.ipha_dst = ipha->ipha_src;
2589 		ripha.ipha_protocol = ipha->ipha_protocol;
2590 		((uint16_t *)&ports)[0] = up[1];
2591 		((uint16_t *)&ports)[1] = up[0];
2592 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2593 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2594 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2595 		    icmph->icmph_type, icmph->icmph_code));
2596 
2597 		/* Have to change db_type after any pullupmsg */
2598 		DB_TYPE(mp) = M_CTL;
2599 
2600 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2601 		    mctl_present, ip_policy, recv_ill, zoneid);
2602 		return;
2603 
2604 	case IPPROTO_TCP:
2605 		/*
2606 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2607 		 * transport header.
2608 		 */
2609 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2610 		    mp->b_wptr) {
2611 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2612 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2613 				BUMP_MIB(&ip_mib, ipInDiscards);
2614 				goto drop_pkt;
2615 			}
2616 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2617 			ipha = (ipha_t *)&icmph[1];
2618 		}
2619 		/*
2620 		 * Find a TCP client stream for this packet.
2621 		 * Note that we do a reverse lookup since the header is
2622 		 * in the form we sent it out.
2623 		 */
2624 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2625 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2626 		if (connp == NULL) {
2627 			BUMP_MIB(&ip_mib, ipInDiscards);
2628 			goto drop_pkt;
2629 		}
2630 
2631 		/* Have to change db_type after any pullupmsg */
2632 		DB_TYPE(mp) = M_CTL;
2633 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2634 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2635 		return;
2636 
2637 	case IPPROTO_SCTP:
2638 		/*
2639 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2640 		 * transport header.
2641 		 */
2642 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2643 		    mp->b_wptr) {
2644 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2645 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2646 				BUMP_MIB(&ip_mib, ipInDiscards);
2647 				goto drop_pkt;
2648 			}
2649 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2650 			ipha = (ipha_t *)&icmph[1];
2651 		}
2652 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2653 		/*
2654 		 * Find a SCTP client stream for this packet.
2655 		 * Note that we do a reverse lookup since the header is
2656 		 * in the form we sent it out.
2657 		 * The ripha header is only used for the matching and we
2658 		 * only set the src and dst addresses, protocol, and version.
2659 		 */
2660 		ripha.ipha_src = ipha->ipha_dst;
2661 		ripha.ipha_dst = ipha->ipha_src;
2662 		ripha.ipha_protocol = ipha->ipha_protocol;
2663 		ripha.ipha_version_and_hdr_length =
2664 		    ipha->ipha_version_and_hdr_length;
2665 		((uint16_t *)&ports)[0] = up[1];
2666 		((uint16_t *)&ports)[1] = up[0];
2667 
2668 		/* Have to change db_type after any pullupmsg */
2669 		DB_TYPE(mp) = M_CTL;
2670 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2671 		    mctl_present, ip_policy, 0, zoneid);
2672 		return;
2673 
2674 	case IPPROTO_ESP:
2675 	case IPPROTO_AH: {
2676 		int ipsec_rc;
2677 
2678 		/*
2679 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2680 		 * We will re-use the IPSEC_IN if it is already present as
2681 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2682 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2683 		 * one and attach it in the front.
2684 		 */
2685 		if (ii != NULL) {
2686 			/*
2687 			 * ip_fanout_proto_again converts the ICMP errors
2688 			 * that come back from AH/ESP to M_DATA so that
2689 			 * if it is non-AH/ESP and we do a pullupmsg in
2690 			 * this function, it would work. Convert it back
2691 			 * to M_CTL before we send up as this is a ICMP
2692 			 * error. This could have been generated locally or
2693 			 * by some router. Validate the inner IPSEC
2694 			 * headers.
2695 			 *
2696 			 * NOTE : ill_index is used by ip_fanout_proto_again
2697 			 * to locate the ill.
2698 			 */
2699 			ASSERT(ill != NULL);
2700 			ii->ipsec_in_ill_index =
2701 			    ill->ill_phyint->phyint_ifindex;
2702 			ii->ipsec_in_rill_index =
2703 			    recv_ill->ill_phyint->phyint_ifindex;
2704 			DB_TYPE(first_mp->b_cont) = M_CTL;
2705 		} else {
2706 			/*
2707 			 * IPSEC_IN is not present. We attach a ipsec_in
2708 			 * message and send up to IPSEC for validating
2709 			 * and removing the IPSEC headers. Clear
2710 			 * ipsec_in_secure so that when we return
2711 			 * from IPSEC, we don't mistakenly think that this
2712 			 * is a secure packet came from the network.
2713 			 *
2714 			 * NOTE : ill_index is used by ip_fanout_proto_again
2715 			 * to locate the ill.
2716 			 */
2717 			ASSERT(first_mp == mp);
2718 			first_mp = ipsec_in_alloc(B_TRUE);
2719 			if (first_mp == NULL) {
2720 				freemsg(mp);
2721 				BUMP_MIB(&ip_mib, ipInDiscards);
2722 				return;
2723 			}
2724 			ii = (ipsec_in_t *)first_mp->b_rptr;
2725 
2726 			/* This is not a secure packet */
2727 			ii->ipsec_in_secure = B_FALSE;
2728 			first_mp->b_cont = mp;
2729 			DB_TYPE(mp) = M_CTL;
2730 			ASSERT(ill != NULL);
2731 			ii->ipsec_in_ill_index =
2732 			    ill->ill_phyint->phyint_ifindex;
2733 			ii->ipsec_in_rill_index =
2734 			    recv_ill->ill_phyint->phyint_ifindex;
2735 		}
2736 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2737 
2738 		if (!ipsec_loaded()) {
2739 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2740 			return;
2741 		}
2742 
2743 		if (ipha->ipha_protocol == IPPROTO_ESP)
2744 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2745 		else
2746 			ipsec_rc = ipsecah_icmp_error(first_mp);
2747 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2748 			return;
2749 
2750 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2751 		return;
2752 	}
2753 	default:
2754 		/*
2755 		 * The ripha header is only used for the lookup and we
2756 		 * only set the src and dst addresses and protocol.
2757 		 */
2758 		ripha.ipha_src = ipha->ipha_dst;
2759 		ripha.ipha_dst = ipha->ipha_src;
2760 		ripha.ipha_protocol = ipha->ipha_protocol;
2761 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2762 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2763 		    ntohl(ipha->ipha_dst),
2764 		    icmph->icmph_type, icmph->icmph_code));
2765 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2766 			ipha_t *in_ipha;
2767 
2768 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2769 			    mp->b_wptr) {
2770 				if (!pullupmsg(mp, (uchar_t *)ipha +
2771 				    hdr_length + sizeof (ipha_t) -
2772 				    mp->b_rptr)) {
2773 
2774 					BUMP_MIB(&ip_mib, ipInDiscards);
2775 					goto drop_pkt;
2776 				}
2777 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2778 				ipha = (ipha_t *)&icmph[1];
2779 			}
2780 			/*
2781 			 * Caller has verified that length has to be
2782 			 * at least the size of IP header.
2783 			 */
2784 			ASSERT(hdr_length >= sizeof (ipha_t));
2785 			/*
2786 			 * Check the sanity of the inner IP header like
2787 			 * we did for the outer header.
2788 			 */
2789 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2790 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2791 				BUMP_MIB(&ip_mib, ipInDiscards);
2792 				goto drop_pkt;
2793 			}
2794 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2795 				BUMP_MIB(&ip_mib, ipInDiscards);
2796 				goto drop_pkt;
2797 			}
2798 			/* Check for Self-encapsulated tunnels */
2799 			if (in_ipha->ipha_src == ipha->ipha_src &&
2800 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2801 
2802 				mp = icmp_inbound_self_encap_error(mp,
2803 				    iph_hdr_length, hdr_length);
2804 				if (mp == NULL)
2805 					goto drop_pkt;
2806 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2807 				ipha = (ipha_t *)&icmph[1];
2808 				hdr_length = IPH_HDR_LENGTH(ipha);
2809 				/*
2810 				 * The packet in error is self-encapsualted.
2811 				 * And we are finding it further encapsulated
2812 				 * which we could not have possibly generated.
2813 				 */
2814 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2815 					BUMP_MIB(&ip_mib, ipInDiscards);
2816 					goto drop_pkt;
2817 				}
2818 				icmp_inbound_error_fanout(q, ill, first_mp,
2819 				    icmph, ipha, iph_hdr_length, hdr_length,
2820 				    mctl_present, ip_policy, recv_ill, zoneid);
2821 				return;
2822 			}
2823 		}
2824 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2825 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2826 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2827 		    ii != NULL &&
2828 		    ii->ipsec_in_loopback &&
2829 		    ii->ipsec_in_secure) {
2830 			/*
2831 			 * For IP tunnels that get a looped-back
2832 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2833 			 * reported new MTU to take into account the IPsec
2834 			 * headers protecting this configured tunnel.
2835 			 *
2836 			 * This allows the tunnel module (tun.c) to blindly
2837 			 * accept the MTU reported in an ICMP "too big"
2838 			 * message.
2839 			 *
2840 			 * Non-looped back ICMP messages will just be
2841 			 * handled by the security protocols (if needed),
2842 			 * and the first subsequent packet will hit this
2843 			 * path.
2844 			 */
2845 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2846 			    ipsec_in_extra_length(first_mp));
2847 		}
2848 		/* Have to change db_type after any pullupmsg */
2849 		DB_TYPE(mp) = M_CTL;
2850 
2851 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2852 		    ip_policy, recv_ill, zoneid);
2853 		return;
2854 	}
2855 	/* NOTREACHED */
2856 drop_pkt:;
2857 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2858 	freemsg(first_mp);
2859 }
2860 
2861 /*
2862  * Common IP options parser.
2863  *
2864  * Setup routine: fill in *optp with options-parsing state, then
2865  * tail-call ipoptp_next to return the first option.
2866  */
2867 uint8_t
2868 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2869 {
2870 	uint32_t totallen; /* total length of all options */
2871 
2872 	totallen = ipha->ipha_version_and_hdr_length -
2873 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2874 	totallen <<= 2;
2875 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2876 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2877 	optp->ipoptp_flags = 0;
2878 	return (ipoptp_next(optp));
2879 }
2880 
2881 /*
2882  * Common IP options parser: extract next option.
2883  */
2884 uint8_t
2885 ipoptp_next(ipoptp_t *optp)
2886 {
2887 	uint8_t *end = optp->ipoptp_end;
2888 	uint8_t *cur = optp->ipoptp_next;
2889 	uint8_t opt, len, pointer;
2890 
2891 	/*
2892 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2893 	 * has been corrupted.
2894 	 */
2895 	ASSERT(cur <= end);
2896 
2897 	if (cur == end)
2898 		return (IPOPT_EOL);
2899 
2900 	opt = cur[IPOPT_OPTVAL];
2901 
2902 	/*
2903 	 * Skip any NOP options.
2904 	 */
2905 	while (opt == IPOPT_NOP) {
2906 		cur++;
2907 		if (cur == end)
2908 			return (IPOPT_EOL);
2909 		opt = cur[IPOPT_OPTVAL];
2910 	}
2911 
2912 	if (opt == IPOPT_EOL)
2913 		return (IPOPT_EOL);
2914 
2915 	/*
2916 	 * Option requiring a length.
2917 	 */
2918 	if ((cur + 1) >= end) {
2919 		optp->ipoptp_flags |= IPOPTP_ERROR;
2920 		return (IPOPT_EOL);
2921 	}
2922 	len = cur[IPOPT_OLEN];
2923 	if (len < 2) {
2924 		optp->ipoptp_flags |= IPOPTP_ERROR;
2925 		return (IPOPT_EOL);
2926 	}
2927 	optp->ipoptp_cur = cur;
2928 	optp->ipoptp_len = len;
2929 	optp->ipoptp_next = cur + len;
2930 	if (cur + len > end) {
2931 		optp->ipoptp_flags |= IPOPTP_ERROR;
2932 		return (IPOPT_EOL);
2933 	}
2934 
2935 	/*
2936 	 * For the options which require a pointer field, make sure
2937 	 * its there, and make sure it points to either something
2938 	 * inside this option, or the end of the option.
2939 	 */
2940 	switch (opt) {
2941 	case IPOPT_RR:
2942 	case IPOPT_TS:
2943 	case IPOPT_LSRR:
2944 	case IPOPT_SSRR:
2945 		if (len <= IPOPT_OFFSET) {
2946 			optp->ipoptp_flags |= IPOPTP_ERROR;
2947 			return (opt);
2948 		}
2949 		pointer = cur[IPOPT_OFFSET];
2950 		if (pointer - 1 > len) {
2951 			optp->ipoptp_flags |= IPOPTP_ERROR;
2952 			return (opt);
2953 		}
2954 		break;
2955 	}
2956 
2957 	/*
2958 	 * Sanity check the pointer field based on the type of the
2959 	 * option.
2960 	 */
2961 	switch (opt) {
2962 	case IPOPT_RR:
2963 	case IPOPT_SSRR:
2964 	case IPOPT_LSRR:
2965 		if (pointer < IPOPT_MINOFF_SR)
2966 			optp->ipoptp_flags |= IPOPTP_ERROR;
2967 		break;
2968 	case IPOPT_TS:
2969 		if (pointer < IPOPT_MINOFF_IT)
2970 			optp->ipoptp_flags |= IPOPTP_ERROR;
2971 		/*
2972 		 * Note that the Internet Timestamp option also
2973 		 * contains two four bit fields (the Overflow field,
2974 		 * and the Flag field), which follow the pointer
2975 		 * field.  We don't need to check that these fields
2976 		 * fall within the length of the option because this
2977 		 * was implicitely done above.  We've checked that the
2978 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2979 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2980 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2981 		 */
2982 		ASSERT(len > IPOPT_POS_OV_FLG);
2983 		break;
2984 	}
2985 
2986 	return (opt);
2987 }
2988 
2989 /*
2990  * Use the outgoing IP header to create an IP_OPTIONS option the way
2991  * it was passed down from the application.
2992  */
2993 int
2994 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2995 {
2996 	ipoptp_t	opts;
2997 	const uchar_t	*opt;
2998 	uint8_t		optval;
2999 	uint8_t		optlen;
3000 	uint32_t	len = 0;
3001 	uchar_t	*buf1 = buf;
3002 
3003 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
3004 	len += IP_ADDR_LEN;
3005 	bzero(buf1, IP_ADDR_LEN);
3006 
3007 	/*
3008 	 * OK to cast away const here, as we don't store through the returned
3009 	 * opts.ipoptp_cur pointer.
3010 	 */
3011 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
3012 	    optval != IPOPT_EOL;
3013 	    optval = ipoptp_next(&opts)) {
3014 		int	off;
3015 
3016 		opt = opts.ipoptp_cur;
3017 		optlen = opts.ipoptp_len;
3018 		switch (optval) {
3019 		case IPOPT_SSRR:
3020 		case IPOPT_LSRR:
3021 
3022 			/*
3023 			 * Insert ipha_dst as the first entry in the source
3024 			 * route and move down the entries on step.
3025 			 * The last entry gets placed at buf1.
3026 			 */
3027 			buf[IPOPT_OPTVAL] = optval;
3028 			buf[IPOPT_OLEN] = optlen;
3029 			buf[IPOPT_OFFSET] = optlen;
3030 
3031 			off = optlen - IP_ADDR_LEN;
3032 			if (off < 0) {
3033 				/* No entries in source route */
3034 				break;
3035 			}
3036 			/* Last entry in source route */
3037 			bcopy(opt + off, buf1, IP_ADDR_LEN);
3038 			off -= IP_ADDR_LEN;
3039 
3040 			while (off > 0) {
3041 				bcopy(opt + off,
3042 				    buf + off + IP_ADDR_LEN,
3043 				    IP_ADDR_LEN);
3044 				off -= IP_ADDR_LEN;
3045 			}
3046 			/* ipha_dst into first slot */
3047 			bcopy(&ipha->ipha_dst,
3048 			    buf + off + IP_ADDR_LEN,
3049 			    IP_ADDR_LEN);
3050 			buf += optlen;
3051 			len += optlen;
3052 			break;
3053 
3054 		case IPOPT_COMSEC:
3055 		case IPOPT_SECURITY:
3056 			/* if passing up a label is not ok, then remove */
3057 			if (is_system_labeled())
3058 				break;
3059 			/* FALLTHROUGH */
3060 		default:
3061 			bcopy(opt, buf, optlen);
3062 			buf += optlen;
3063 			len += optlen;
3064 			break;
3065 		}
3066 	}
3067 done:
3068 	/* Pad the resulting options */
3069 	while (len & 0x3) {
3070 		*buf++ = IPOPT_EOL;
3071 		len++;
3072 	}
3073 	return (len);
3074 }
3075 
3076 /*
3077  * Update any record route or timestamp options to include this host.
3078  * Reverse any source route option.
3079  * This routine assumes that the options are well formed i.e. that they
3080  * have already been checked.
3081  */
3082 static void
3083 icmp_options_update(ipha_t *ipha)
3084 {
3085 	ipoptp_t	opts;
3086 	uchar_t		*opt;
3087 	uint8_t		optval;
3088 	ipaddr_t	src;		/* Our local address */
3089 	ipaddr_t	dst;
3090 
3091 	ip2dbg(("icmp_options_update\n"));
3092 	src = ipha->ipha_src;
3093 	dst = ipha->ipha_dst;
3094 
3095 	for (optval = ipoptp_first(&opts, ipha);
3096 	    optval != IPOPT_EOL;
3097 	    optval = ipoptp_next(&opts)) {
3098 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3099 		opt = opts.ipoptp_cur;
3100 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3101 		    optval, opts.ipoptp_len));
3102 		switch (optval) {
3103 			int off1, off2;
3104 		case IPOPT_SSRR:
3105 		case IPOPT_LSRR:
3106 			/*
3107 			 * Reverse the source route.  The first entry
3108 			 * should be the next to last one in the current
3109 			 * source route (the last entry is our address).
3110 			 * The last entry should be the final destination.
3111 			 */
3112 			off1 = IPOPT_MINOFF_SR - 1;
3113 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3114 			if (off2 < 0) {
3115 				/* No entries in source route */
3116 				ip1dbg((
3117 				    "icmp_options_update: bad src route\n"));
3118 				break;
3119 			}
3120 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3121 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3122 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3123 			off2 -= IP_ADDR_LEN;
3124 
3125 			while (off1 < off2) {
3126 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3127 				bcopy((char *)opt + off2, (char *)opt + off1,
3128 				    IP_ADDR_LEN);
3129 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3130 				off1 += IP_ADDR_LEN;
3131 				off2 -= IP_ADDR_LEN;
3132 			}
3133 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3134 			break;
3135 		}
3136 	}
3137 }
3138 
3139 /*
3140  * Process received ICMP Redirect messages.
3141  */
3142 /* ARGSUSED */
3143 static void
3144 icmp_redirect(mblk_t *mp)
3145 {
3146 	ipha_t	*ipha;
3147 	int	iph_hdr_length;
3148 	icmph_t	*icmph;
3149 	ipha_t	*ipha_err;
3150 	ire_t	*ire;
3151 	ire_t	*prev_ire;
3152 	ire_t	*save_ire;
3153 	ipaddr_t  src, dst, gateway;
3154 	iulp_t	ulp_info = { 0 };
3155 	int	error;
3156 
3157 	ipha = (ipha_t *)mp->b_rptr;
3158 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3159 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3160 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3161 		BUMP_MIB(&icmp_mib, icmpInErrors);
3162 		freemsg(mp);
3163 		return;
3164 	}
3165 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3166 	ipha_err = (ipha_t *)&icmph[1];
3167 	src = ipha->ipha_src;
3168 	dst = ipha_err->ipha_dst;
3169 	gateway = icmph->icmph_rd_gateway;
3170 	/* Make sure the new gateway is reachable somehow. */
3171 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3172 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3173 	/*
3174 	 * Make sure we had a route for the dest in question and that
3175 	 * that route was pointing to the old gateway (the source of the
3176 	 * redirect packet.)
3177 	 */
3178 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3179 	    NULL, MATCH_IRE_GW);
3180 	/*
3181 	 * Check that
3182 	 *	the redirect was not from ourselves
3183 	 *	the new gateway and the old gateway are directly reachable
3184 	 */
3185 	if (!prev_ire ||
3186 	    !ire ||
3187 	    ire->ire_type == IRE_LOCAL) {
3188 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3189 		freemsg(mp);
3190 		if (ire != NULL)
3191 			ire_refrele(ire);
3192 		if (prev_ire != NULL)
3193 			ire_refrele(prev_ire);
3194 		return;
3195 	}
3196 
3197 	/*
3198 	 * Should we use the old ULP info to create the new gateway?  From
3199 	 * a user's perspective, we should inherit the info so that it
3200 	 * is a "smooth" transition.  If we do not do that, then new
3201 	 * connections going thru the new gateway will have no route metrics,
3202 	 * which is counter-intuitive to user.  From a network point of
3203 	 * view, this may or may not make sense even though the new gateway
3204 	 * is still directly connected to us so the route metrics should not
3205 	 * change much.
3206 	 *
3207 	 * But if the old ire_uinfo is not initialized, we do another
3208 	 * recursive lookup on the dest using the new gateway.  There may
3209 	 * be a route to that.  If so, use it to initialize the redirect
3210 	 * route.
3211 	 */
3212 	if (prev_ire->ire_uinfo.iulp_set) {
3213 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3214 	} else {
3215 		ire_t *tmp_ire;
3216 		ire_t *sire;
3217 
3218 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3219 		    ALL_ZONES, 0, NULL,
3220 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3221 		if (sire != NULL) {
3222 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3223 			/*
3224 			 * If sire != NULL, ire_ftable_lookup() should not
3225 			 * return a NULL value.
3226 			 */
3227 			ASSERT(tmp_ire != NULL);
3228 			ire_refrele(tmp_ire);
3229 			ire_refrele(sire);
3230 		} else if (tmp_ire != NULL) {
3231 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3232 			    sizeof (iulp_t));
3233 			ire_refrele(tmp_ire);
3234 		}
3235 	}
3236 	if (prev_ire->ire_type == IRE_CACHE)
3237 		ire_delete(prev_ire);
3238 	ire_refrele(prev_ire);
3239 	/*
3240 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3241 	 * require TOS routing
3242 	 */
3243 	switch (icmph->icmph_code) {
3244 	case 0:
3245 	case 1:
3246 		/* TODO: TOS specificity for cases 2 and 3 */
3247 	case 2:
3248 	case 3:
3249 		break;
3250 	default:
3251 		freemsg(mp);
3252 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3253 		ire_refrele(ire);
3254 		return;
3255 	}
3256 	/*
3257 	 * Create a Route Association.  This will allow us to remember that
3258 	 * someone we believe told us to use the particular gateway.
3259 	 */
3260 	save_ire = ire;
3261 	ire = ire_create(
3262 		(uchar_t *)&dst,			/* dest addr */
3263 		(uchar_t *)&ip_g_all_ones,		/* mask */
3264 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3265 		(uchar_t *)&gateway,			/* gateway addr */
3266 		NULL,					/* no in_srcaddr */
3267 		&save_ire->ire_max_frag,		/* max frag */
3268 		NULL,					/* Fast Path header */
3269 		NULL,					/* no rfq */
3270 		NULL,					/* no stq */
3271 		IRE_HOST,
3272 		NULL,
3273 		NULL,
3274 		NULL,
3275 		0,
3276 		0,
3277 		0,
3278 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3279 		&ulp_info,
3280 		NULL,
3281 		NULL);
3282 
3283 	if (ire == NULL) {
3284 		freemsg(mp);
3285 		ire_refrele(save_ire);
3286 		return;
3287 	}
3288 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3289 	ire_refrele(save_ire);
3290 	atomic_inc_32(&ip_redirect_cnt);
3291 
3292 	if (error == 0) {
3293 		ire_refrele(ire);		/* Held in ire_add_v4 */
3294 		/* tell routing sockets that we received a redirect */
3295 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3296 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3297 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3298 	}
3299 
3300 	/*
3301 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3302 	 * This together with the added IRE has the effect of
3303 	 * modifying an existing redirect.
3304 	 */
3305 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3306 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3307 	if (prev_ire != NULL) {
3308 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3309 			ire_delete(prev_ire);
3310 		ire_refrele(prev_ire);
3311 	}
3312 
3313 	freemsg(mp);
3314 }
3315 
3316 /*
3317  * Generate an ICMP parameter problem message.
3318  */
3319 static void
3320 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid)
3321 {
3322 	icmph_t	icmph;
3323 	boolean_t mctl_present;
3324 	mblk_t *first_mp;
3325 
3326 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3327 
3328 	if (!(mp = icmp_pkt_err_ok(mp))) {
3329 		if (mctl_present)
3330 			freeb(first_mp);
3331 		return;
3332 	}
3333 
3334 	bzero(&icmph, sizeof (icmph_t));
3335 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3336 	icmph.icmph_pp_ptr = ptr;
3337 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3338 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3339 }
3340 
3341 /*
3342  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3343  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3344  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3345  * an icmp error packet can be sent.
3346  * Assigns an appropriate source address to the packet. If ipha_dst is
3347  * one of our addresses use it for source. Otherwise pick a source based
3348  * on a route lookup back to ipha_src.
3349  * Note that ipha_src must be set here since the
3350  * packet is likely to arrive on an ill queue in ip_wput() which will
3351  * not set a source address.
3352  */
3353 static void
3354 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3355     boolean_t mctl_present, zoneid_t zoneid)
3356 {
3357 	ipaddr_t dst;
3358 	icmph_t	*icmph;
3359 	ipha_t	*ipha;
3360 	uint_t	len_needed;
3361 	size_t	msg_len;
3362 	mblk_t	*mp1;
3363 	ipaddr_t src;
3364 	ire_t	*ire;
3365 	mblk_t *ipsec_mp;
3366 	ipsec_out_t	*io = NULL;
3367 	boolean_t xmit_if_on = B_FALSE;
3368 
3369 	if (mctl_present) {
3370 		/*
3371 		 * If it is :
3372 		 *
3373 		 * 1) a IPSEC_OUT, then this is caused by outbound
3374 		 *    datagram originating on this host. IPSEC processing
3375 		 *    may or may not have been done. Refer to comments above
3376 		 *    icmp_inbound_error_fanout for details.
3377 		 *
3378 		 * 2) a IPSEC_IN if we are generating a icmp_message
3379 		 *    for an incoming datagram destined for us i.e called
3380 		 *    from ip_fanout_send_icmp.
3381 		 */
3382 		ipsec_info_t *in;
3383 		ipsec_mp = mp;
3384 		mp = ipsec_mp->b_cont;
3385 
3386 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3387 		ipha = (ipha_t *)mp->b_rptr;
3388 
3389 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3390 		    in->ipsec_info_type == IPSEC_IN);
3391 
3392 		if (in->ipsec_info_type == IPSEC_IN) {
3393 			/*
3394 			 * Convert the IPSEC_IN to IPSEC_OUT.
3395 			 */
3396 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3397 				BUMP_MIB(&ip_mib, ipOutDiscards);
3398 				return;
3399 			}
3400 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3401 		} else {
3402 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3403 			io = (ipsec_out_t *)in;
3404 			if (io->ipsec_out_xmit_if)
3405 				xmit_if_on = B_TRUE;
3406 			/*
3407 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3408 			 * ire lookup.
3409 			 */
3410 			io->ipsec_out_proc_begin = B_FALSE;
3411 		}
3412 		ASSERT(zoneid == io->ipsec_out_zoneid);
3413 		ASSERT(zoneid != ALL_ZONES);
3414 	} else {
3415 		/*
3416 		 * This is in clear. The icmp message we are building
3417 		 * here should go out in clear.
3418 		 *
3419 		 * Pardon the convolution of it all, but it's easier to
3420 		 * allocate a "use cleartext" IPSEC_IN message and convert
3421 		 * it than it is to allocate a new one.
3422 		 */
3423 		ipsec_in_t *ii;
3424 		ASSERT(DB_TYPE(mp) == M_DATA);
3425 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3426 			freemsg(mp);
3427 			BUMP_MIB(&ip_mib, ipOutDiscards);
3428 			return;
3429 		}
3430 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3431 
3432 		/* This is not a secure packet */
3433 		ii->ipsec_in_secure = B_FALSE;
3434 		/*
3435 		 * For trusted extensions using a shared IP address we can
3436 		 * send using any zoneid.
3437 		 */
3438 		if (zoneid == ALL_ZONES)
3439 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3440 		else
3441 			ii->ipsec_in_zoneid = zoneid;
3442 		ipsec_mp->b_cont = mp;
3443 		ipha = (ipha_t *)mp->b_rptr;
3444 		/*
3445 		 * Convert the IPSEC_IN to IPSEC_OUT.
3446 		 */
3447 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3448 			BUMP_MIB(&ip_mib, ipOutDiscards);
3449 			return;
3450 		}
3451 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3452 	}
3453 
3454 	/* Remember our eventual destination */
3455 	dst = ipha->ipha_src;
3456 
3457 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3458 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3459 	if (ire != NULL &&
3460 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3461 		src = ipha->ipha_dst;
3462 	} else if (!xmit_if_on) {
3463 		if (ire != NULL)
3464 			ire_refrele(ire);
3465 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3466 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3467 		if (ire == NULL) {
3468 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3469 			freemsg(ipsec_mp);
3470 			return;
3471 		}
3472 		src = ire->ire_src_addr;
3473 	} else {
3474 		ipif_t	*ipif = NULL;
3475 		ill_t	*ill;
3476 		/*
3477 		 * This must be an ICMP error coming from
3478 		 * ip_mrtun_forward(). The src addr should
3479 		 * be equal to the IP-addr of the outgoing
3480 		 * interface.
3481 		 */
3482 		if (io == NULL) {
3483 			/* This is not a IPSEC_OUT type control msg */
3484 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3485 			freemsg(ipsec_mp);
3486 			return;
3487 		}
3488 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3489 		    NULL, NULL, NULL, NULL);
3490 		if (ill != NULL) {
3491 			ipif = ipif_get_next_ipif(NULL, ill);
3492 			ill_refrele(ill);
3493 		}
3494 		if (ipif == NULL) {
3495 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3496 			freemsg(ipsec_mp);
3497 			return;
3498 		}
3499 		src = ipif->ipif_src_addr;
3500 		ipif_refrele(ipif);
3501 	}
3502 
3503 	if (ire != NULL)
3504 		ire_refrele(ire);
3505 
3506 	/*
3507 	 * Check if we can send back more then 8 bytes in addition
3508 	 * to the IP header. We will include as much as 64 bytes.
3509 	 */
3510 	len_needed = IPH_HDR_LENGTH(ipha);
3511 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3512 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3513 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3514 	}
3515 	len_needed += ip_icmp_return;
3516 	msg_len = msgdsize(mp);
3517 	if (msg_len > len_needed) {
3518 		(void) adjmsg(mp, len_needed - msg_len);
3519 		msg_len = len_needed;
3520 	}
3521 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3522 	if (mp1 == NULL) {
3523 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3524 		freemsg(ipsec_mp);
3525 		return;
3526 	}
3527 	/*
3528 	 * On an unlabeled system, dblks don't necessarily have creds.
3529 	 */
3530 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3531 	if (DB_CRED(mp) != NULL)
3532 		mblk_setcred(mp1, DB_CRED(mp));
3533 	mp1->b_cont = mp;
3534 	mp = mp1;
3535 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3536 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3537 	    io->ipsec_out_type == IPSEC_OUT);
3538 	ipsec_mp->b_cont = mp;
3539 
3540 	/*
3541 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3542 	 * node generates be accepted in peace by all on-host destinations.
3543 	 * If we do NOT assume that all on-host destinations trust
3544 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3545 	 * (Look for ipsec_out_icmp_loopback).
3546 	 */
3547 	io->ipsec_out_icmp_loopback = B_TRUE;
3548 
3549 	ipha = (ipha_t *)mp->b_rptr;
3550 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3551 	*ipha = icmp_ipha;
3552 	ipha->ipha_src = src;
3553 	ipha->ipha_dst = dst;
3554 	ipha->ipha_ttl = ip_def_ttl;
3555 	msg_len += sizeof (icmp_ipha) + len;
3556 	if (msg_len > IP_MAXPACKET) {
3557 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3558 		msg_len = IP_MAXPACKET;
3559 	}
3560 	ipha->ipha_length = htons((uint16_t)msg_len);
3561 	icmph = (icmph_t *)&ipha[1];
3562 	bcopy(stuff, icmph, len);
3563 	icmph->icmph_checksum = 0;
3564 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3565 	if (icmph->icmph_checksum == 0)
3566 		icmph->icmph_checksum = 0xFFFF;
3567 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3568 	put(q, ipsec_mp);
3569 }
3570 
3571 /*
3572  * Determine if an ICMP error packet can be sent given the rate limit.
3573  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3574  * in milliseconds) and a burst size. Burst size number of packets can
3575  * be sent arbitrarely closely spaced.
3576  * The state is tracked using two variables to implement an approximate
3577  * token bucket filter:
3578  *	icmp_pkt_err_last - lbolt value when the last burst started
3579  *	icmp_pkt_err_sent - number of packets sent in current burst
3580  */
3581 boolean_t
3582 icmp_err_rate_limit(void)
3583 {
3584 	clock_t now = TICK_TO_MSEC(lbolt);
3585 	uint_t refilled; /* Number of packets refilled in tbf since last */
3586 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3587 
3588 	if (err_interval == 0)
3589 		return (B_FALSE);
3590 
3591 	if (icmp_pkt_err_last > now) {
3592 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3593 		icmp_pkt_err_last = 0;
3594 		icmp_pkt_err_sent = 0;
3595 	}
3596 	/*
3597 	 * If we are in a burst update the token bucket filter.
3598 	 * Update the "last" time to be close to "now" but make sure
3599 	 * we don't loose precision.
3600 	 */
3601 	if (icmp_pkt_err_sent != 0) {
3602 		refilled = (now - icmp_pkt_err_last)/err_interval;
3603 		if (refilled > icmp_pkt_err_sent) {
3604 			icmp_pkt_err_sent = 0;
3605 		} else {
3606 			icmp_pkt_err_sent -= refilled;
3607 			icmp_pkt_err_last += refilled * err_interval;
3608 		}
3609 	}
3610 	if (icmp_pkt_err_sent == 0) {
3611 		/* Start of new burst */
3612 		icmp_pkt_err_last = now;
3613 	}
3614 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3615 		icmp_pkt_err_sent++;
3616 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3617 		    icmp_pkt_err_sent));
3618 		return (B_FALSE);
3619 	}
3620 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3621 	return (B_TRUE);
3622 }
3623 
3624 /*
3625  * Check if it is ok to send an IPv4 ICMP error packet in
3626  * response to the IPv4 packet in mp.
3627  * Free the message and return null if no
3628  * ICMP error packet should be sent.
3629  */
3630 static mblk_t *
3631 icmp_pkt_err_ok(mblk_t *mp)
3632 {
3633 	icmph_t	*icmph;
3634 	ipha_t	*ipha;
3635 	uint_t	len_needed;
3636 	ire_t	*src_ire;
3637 	ire_t	*dst_ire;
3638 
3639 	if (!mp)
3640 		return (NULL);
3641 	ipha = (ipha_t *)mp->b_rptr;
3642 	if (ip_csum_hdr(ipha)) {
3643 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3644 		freemsg(mp);
3645 		return (NULL);
3646 	}
3647 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3648 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3649 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3650 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3651 	if (src_ire != NULL || dst_ire != NULL ||
3652 	    CLASSD(ipha->ipha_dst) ||
3653 	    CLASSD(ipha->ipha_src) ||
3654 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3655 		/* Note: only errors to the fragment with offset 0 */
3656 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3657 		freemsg(mp);
3658 		if (src_ire != NULL)
3659 			ire_refrele(src_ire);
3660 		if (dst_ire != NULL)
3661 			ire_refrele(dst_ire);
3662 		return (NULL);
3663 	}
3664 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3665 		/*
3666 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3667 		 * errors in response to any ICMP errors.
3668 		 */
3669 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3670 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3671 			if (!pullupmsg(mp, len_needed)) {
3672 				BUMP_MIB(&icmp_mib, icmpInErrors);
3673 				freemsg(mp);
3674 				return (NULL);
3675 			}
3676 			ipha = (ipha_t *)mp->b_rptr;
3677 		}
3678 		icmph = (icmph_t *)
3679 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3680 		switch (icmph->icmph_type) {
3681 		case ICMP_DEST_UNREACHABLE:
3682 		case ICMP_SOURCE_QUENCH:
3683 		case ICMP_TIME_EXCEEDED:
3684 		case ICMP_PARAM_PROBLEM:
3685 		case ICMP_REDIRECT:
3686 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3687 			freemsg(mp);
3688 			return (NULL);
3689 		default:
3690 			break;
3691 		}
3692 	}
3693 	/*
3694 	 * If this is a labeled system, then check to see if we're allowed to
3695 	 * send a response to this particular sender.  If not, then just drop.
3696 	 */
3697 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3698 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3699 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3700 		freemsg(mp);
3701 		return (NULL);
3702 	}
3703 	if (icmp_err_rate_limit()) {
3704 		/*
3705 		 * Only send ICMP error packets every so often.
3706 		 * This should be done on a per port/source basis,
3707 		 * but for now this will suffice.
3708 		 */
3709 		freemsg(mp);
3710 		return (NULL);
3711 	}
3712 	return (mp);
3713 }
3714 
3715 /*
3716  * Generate an ICMP redirect message.
3717  */
3718 static void
3719 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3720 {
3721 	icmph_t	icmph;
3722 
3723 	/*
3724 	 * We are called from ip_rput where we could
3725 	 * not have attached an IPSEC_IN.
3726 	 */
3727 	ASSERT(mp->b_datap->db_type == M_DATA);
3728 
3729 	if (!(mp = icmp_pkt_err_ok(mp))) {
3730 		return;
3731 	}
3732 
3733 	bzero(&icmph, sizeof (icmph_t));
3734 	icmph.icmph_type = ICMP_REDIRECT;
3735 	icmph.icmph_code = 1;
3736 	icmph.icmph_rd_gateway = gateway;
3737 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3738 	/* Redirects sent by router, and router is global zone */
3739 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID);
3740 }
3741 
3742 /*
3743  * Generate an ICMP time exceeded message.
3744  */
3745 void
3746 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3747 {
3748 	icmph_t	icmph;
3749 	boolean_t mctl_present;
3750 	mblk_t *first_mp;
3751 
3752 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3753 
3754 	if (!(mp = icmp_pkt_err_ok(mp))) {
3755 		if (mctl_present)
3756 			freeb(first_mp);
3757 		return;
3758 	}
3759 
3760 	bzero(&icmph, sizeof (icmph_t));
3761 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3762 	icmph.icmph_code = code;
3763 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3764 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3765 }
3766 
3767 /*
3768  * Generate an ICMP unreachable message.
3769  */
3770 void
3771 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3772 {
3773 	icmph_t	icmph;
3774 	mblk_t *first_mp;
3775 	boolean_t mctl_present;
3776 
3777 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3778 
3779 	if (!(mp = icmp_pkt_err_ok(mp))) {
3780 		if (mctl_present)
3781 			freeb(first_mp);
3782 		return;
3783 	}
3784 
3785 	bzero(&icmph, sizeof (icmph_t));
3786 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3787 	icmph.icmph_code = code;
3788 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3789 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3790 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3791 	    zoneid);
3792 }
3793 
3794 /*
3795  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3796  * duplicate.  As long as someone else holds the address, the interface will
3797  * stay down.  When that conflict goes away, the interface is brought back up.
3798  * This is done so that accidental shutdowns of addresses aren't made
3799  * permanent.  Your server will recover from a failure.
3800  *
3801  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3802  * user space process (dhcpagent).
3803  *
3804  * Recovery completes if ARP reports that the address is now ours (via
3805  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3806  *
3807  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3808  */
3809 static void
3810 ipif_dup_recovery(void *arg)
3811 {
3812 	ipif_t *ipif = arg;
3813 	ill_t *ill = ipif->ipif_ill;
3814 	mblk_t *arp_add_mp;
3815 	mblk_t *arp_del_mp;
3816 	area_t *area;
3817 
3818 	ipif->ipif_recovery_id = 0;
3819 
3820 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3821 	    (ipif->ipif_flags & IPIF_POINTOPOINT)) {
3822 		/* No reason to try to bring this address back. */
3823 		return;
3824 	}
3825 
3826 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3827 		goto alloc_fail;
3828 
3829 	if (ipif->ipif_arp_del_mp == NULL) {
3830 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3831 			goto alloc_fail;
3832 		ipif->ipif_arp_del_mp = arp_del_mp;
3833 	}
3834 
3835 	/* Setting the 'unverified' flag restarts DAD */
3836 	area = (area_t *)arp_add_mp->b_rptr;
3837 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3838 	    ACE_F_UNVERIFIED;
3839 	putnext(ill->ill_rq, arp_add_mp);
3840 	return;
3841 
3842 alloc_fail:
3843 	/* On allocation failure, just restart the timer */
3844 	freemsg(arp_add_mp);
3845 	if (ip_dup_recovery > 0) {
3846 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3847 		    MSEC_TO_TICK(ip_dup_recovery));
3848 	}
3849 }
3850 
3851 /*
3852  * This is for exclusive changes due to ARP.  Either tear down an interface due
3853  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3854  */
3855 /* ARGSUSED */
3856 static void
3857 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3858 {
3859 	ill_t	*ill = rq->q_ptr;
3860 	arh_t *arh;
3861 	ipaddr_t src;
3862 	ipif_t	*ipif;
3863 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3864 	char hbuf[MAC_STR_LEN];
3865 	char sbuf[INET_ADDRSTRLEN];
3866 	const char *failtype;
3867 	boolean_t bring_up;
3868 
3869 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3870 	case AR_CN_READY:
3871 		failtype = NULL;
3872 		bring_up = B_TRUE;
3873 		break;
3874 	case AR_CN_FAILED:
3875 		failtype = "in use";
3876 		bring_up = B_FALSE;
3877 		break;
3878 	default:
3879 		failtype = "claimed";
3880 		bring_up = B_FALSE;
3881 		break;
3882 	}
3883 
3884 	arh = (arh_t *)mp->b_cont->b_rptr;
3885 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3886 
3887 	/* Handle failures due to probes */
3888 	if (src == 0) {
3889 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3890 		    IP_ADDR_LEN);
3891 	}
3892 
3893 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3894 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3895 	    sizeof (hbuf));
3896 	(void) ip_dot_addr(src, sbuf);
3897 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3898 
3899 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3900 		    ipif->ipif_lcl_addr != src) {
3901 			continue;
3902 		}
3903 
3904 		/*
3905 		 * If we failed on a recovery probe, then restart the timer to
3906 		 * try again later.
3907 		 */
3908 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3909 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3910 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3911 		    ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0) {
3912 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3913 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3914 			continue;
3915 		}
3916 
3917 		/*
3918 		 * If what we're trying to do has already been done, then do
3919 		 * nothing.
3920 		 */
3921 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3922 			continue;
3923 
3924 		if (ipif->ipif_id != 0) {
3925 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3926 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3927 			    ipif->ipif_id);
3928 		}
3929 		if (failtype == NULL) {
3930 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3931 			    ibuf);
3932 		} else {
3933 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3934 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3935 		}
3936 
3937 		if (bring_up) {
3938 			ASSERT(ill->ill_dl_up);
3939 			/*
3940 			 * Free up the ARP delete message so we can allocate
3941 			 * a fresh one through the normal path.
3942 			 */
3943 			freemsg(ipif->ipif_arp_del_mp);
3944 			ipif->ipif_arp_del_mp = NULL;
3945 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3946 			    EINPROGRESS) {
3947 				ipif->ipif_addr_ready = 1;
3948 				(void) ipif_up_done(ipif);
3949 			}
3950 			continue;
3951 		}
3952 
3953 		mutex_enter(&ill->ill_lock);
3954 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3955 		ipif->ipif_flags |= IPIF_DUPLICATE;
3956 		ill->ill_ipif_dup_count++;
3957 		mutex_exit(&ill->ill_lock);
3958 		/*
3959 		 * Already exclusive on the ill; no need to handle deferred
3960 		 * processing here.
3961 		 */
3962 		(void) ipif_down(ipif, NULL, NULL);
3963 		ipif_down_tail(ipif);
3964 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3965 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3966 		    ip_dup_recovery > 0) {
3967 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3968 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3969 		}
3970 	}
3971 	freemsg(mp);
3972 }
3973 
3974 /* ARGSUSED */
3975 static void
3976 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3977 {
3978 	ill_t	*ill = rq->q_ptr;
3979 	arh_t *arh;
3980 	ipaddr_t src;
3981 	ipif_t	*ipif;
3982 
3983 	arh = (arh_t *)mp->b_cont->b_rptr;
3984 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3985 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3986 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3987 			(void) ipif_resolver_up(ipif, Res_act_defend);
3988 	}
3989 	freemsg(mp);
3990 }
3991 
3992 /*
3993  * News from ARP.  ARP sends notification of interesting events down
3994  * to its clients using M_CTL messages with the interesting ARP packet
3995  * attached via b_cont.
3996  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3997  * queue as opposed to ARP sending the message to all the clients, i.e. all
3998  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3999  * table if a cache IRE is found to delete all the entries for the address in
4000  * the packet.
4001  */
4002 static void
4003 ip_arp_news(queue_t *q, mblk_t *mp)
4004 {
4005 	arcn_t		*arcn;
4006 	arh_t		*arh;
4007 	ire_t		*ire = NULL;
4008 	char		hbuf[MAC_STR_LEN];
4009 	char		sbuf[INET_ADDRSTRLEN];
4010 	ipaddr_t	src;
4011 	in6_addr_t	v6src;
4012 	boolean_t	isv6 = B_FALSE;
4013 	ipif_t		*ipif;
4014 	ill_t		*ill;
4015 
4016 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
4017 		if (q->q_next) {
4018 			putnext(q, mp);
4019 		} else
4020 			freemsg(mp);
4021 		return;
4022 	}
4023 	arh = (arh_t *)mp->b_cont->b_rptr;
4024 	/* Is it one we are interested in? */
4025 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
4026 		isv6 = B_TRUE;
4027 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
4028 		    IPV6_ADDR_LEN);
4029 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
4030 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
4031 		    IP_ADDR_LEN);
4032 	} else {
4033 		freemsg(mp);
4034 		return;
4035 	}
4036 
4037 	ill = q->q_ptr;
4038 
4039 	arcn = (arcn_t *)mp->b_rptr;
4040 	switch (arcn->arcn_code) {
4041 	case AR_CN_BOGON:
4042 		/*
4043 		 * Someone is sending ARP packets with a source protocol
4044 		 * address that we have published and for which we believe our
4045 		 * entry is authoritative and (when ill_arp_extend is set)
4046 		 * verified to be unique on the network.
4047 		 *
4048 		 * The ARP module internally handles the cases where the sender
4049 		 * is just probing (for DAD) and where the hardware address of
4050 		 * a non-authoritative entry has changed.  Thus, these are the
4051 		 * real conflicts, and we have to do resolution.
4052 		 *
4053 		 * We back away quickly from the address if it's from DHCP or
4054 		 * otherwise temporary and hasn't been used recently (or at
4055 		 * all).  We'd like to include "deprecated" addresses here as
4056 		 * well (as there's no real reason to defend something we're
4057 		 * discarding), but IPMP "reuses" this flag to mean something
4058 		 * other than the standard meaning.
4059 		 *
4060 		 * If the ARP module above is not extended (meaning that it
4061 		 * doesn't know how to defend the address), then we just log
4062 		 * the problem as we always did and continue on.  It's not
4063 		 * right, but there's little else we can do, and those old ATM
4064 		 * users are going away anyway.
4065 		 */
4066 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4067 		    hbuf, sizeof (hbuf));
4068 		(void) ip_dot_addr(src, sbuf);
4069 		if (isv6)
4070 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
4071 		else
4072 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
4073 
4074 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4075 			uint32_t now;
4076 			uint32_t maxage;
4077 			clock_t lused;
4078 			uint_t maxdefense;
4079 			uint_t defs;
4080 
4081 			/*
4082 			 * First, figure out if this address hasn't been used
4083 			 * in a while.  If it hasn't, then it's a better
4084 			 * candidate for abandoning.
4085 			 */
4086 			ipif = ire->ire_ipif;
4087 			ASSERT(ipif != NULL);
4088 			now = gethrestime_sec();
4089 			maxage = now - ire->ire_create_time;
4090 			if (maxage > ip_max_temp_idle)
4091 				maxage = ip_max_temp_idle;
4092 			lused = drv_hztousec(ddi_get_lbolt() -
4093 			    ire->ire_last_used_time) / MICROSEC + 1;
4094 			if (lused >= maxage && (ipif->ipif_flags &
4095 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4096 				maxdefense = ip_max_temp_defend;
4097 			else
4098 				maxdefense = ip_max_defend;
4099 
4100 			/*
4101 			 * Now figure out how many times we've defended
4102 			 * ourselves.  Ignore defenses that happened long in
4103 			 * the past.
4104 			 */
4105 			mutex_enter(&ire->ire_lock);
4106 			if ((defs = ire->ire_defense_count) > 0 &&
4107 			    now - ire->ire_defense_time > ip_defend_interval) {
4108 				ire->ire_defense_count = defs = 0;
4109 			}
4110 			ire->ire_defense_count++;
4111 			ire->ire_defense_time = now;
4112 			mutex_exit(&ire->ire_lock);
4113 			ill_refhold(ill);
4114 			ire_refrele(ire);
4115 
4116 			/*
4117 			 * If we've defended ourselves too many times already,
4118 			 * then give up and tear down the interface(s) using
4119 			 * this address.  Otherwise, defend by sending out a
4120 			 * gratuitous ARP.
4121 			 */
4122 			if (defs >= maxdefense && ill->ill_arp_extend) {
4123 				(void) qwriter_ip(NULL, ill, q, mp,
4124 				    ip_arp_excl, CUR_OP, B_FALSE);
4125 			} else {
4126 				cmn_err(CE_WARN,
4127 				    "node %s is using our IP address %s on %s",
4128 				    hbuf, sbuf, ill->ill_name);
4129 				/*
4130 				 * If this is an old (ATM) ARP module, then
4131 				 * don't try to defend the address.  Remain
4132 				 * compatible with the old behavior.  Defend
4133 				 * only with new ARP.
4134 				 */
4135 				if (ill->ill_arp_extend) {
4136 					(void) qwriter_ip(NULL, ill, q, mp,
4137 					    ip_arp_defend, CUR_OP, B_FALSE);
4138 				} else {
4139 					ill_refrele(ill);
4140 				}
4141 			}
4142 			return;
4143 		}
4144 		cmn_err(CE_WARN,
4145 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4146 		    hbuf, sbuf, ill->ill_name);
4147 		if (ire != NULL)
4148 			ire_refrele(ire);
4149 		break;
4150 	case AR_CN_ANNOUNCE:
4151 		if (isv6) {
4152 			/*
4153 			 * For XRESOLV interfaces.
4154 			 * Delete the IRE cache entry and NCE for this
4155 			 * v6 address
4156 			 */
4157 			ip_ire_clookup_and_delete_v6(&v6src);
4158 			/*
4159 			 * If v6src is a non-zero, it's a router address
4160 			 * as below. Do the same sort of thing to clean
4161 			 * out off-net IRE_CACHE entries that go through
4162 			 * the router.
4163 			 */
4164 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4165 				ire_walk_v6(ire_delete_cache_gw_v6,
4166 				    (char *)&v6src, ALL_ZONES);
4167 			}
4168 		} else {
4169 			nce_hw_map_t hwm;
4170 
4171 			/*
4172 			 * ARP gives us a copy of any packet where it thinks
4173 			 * the address has changed, so that we can update our
4174 			 * caches.  We're responsible for caching known answers
4175 			 * in the current design.  We check whether the
4176 			 * hardware address really has changed in all of our
4177 			 * entries that have cached this mapping, and if so, we
4178 			 * blow them away.  This way we will immediately pick
4179 			 * up the rare case of a host changing hardware
4180 			 * address.
4181 			 */
4182 			if (src == 0)
4183 				break;
4184 			hwm.hwm_addr = src;
4185 			hwm.hwm_hwlen = arh->arh_hlen;
4186 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4187 			ndp_walk_common(&ndp4, NULL,
4188 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4189 		}
4190 		break;
4191 	case AR_CN_READY:
4192 		/* No external v6 resolver has a contract to use this */
4193 		if (isv6)
4194 			break;
4195 		/* If the link is down, we'll retry this later */
4196 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4197 			break;
4198 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4199 		    NULL, NULL);
4200 		if (ipif != NULL) {
4201 			/*
4202 			 * If this is a duplicate recovery, then we now need to
4203 			 * go exclusive to bring this thing back up.
4204 			 */
4205 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4206 			    IPIF_DUPLICATE) {
4207 				ipif_refrele(ipif);
4208 				ill_refhold(ill);
4209 				(void) qwriter_ip(NULL, ill, q, mp,
4210 				    ip_arp_excl, CUR_OP, B_FALSE);
4211 				return;
4212 			}
4213 			/*
4214 			 * If this is the first notice that this address is
4215 			 * ready, then let the user know now.
4216 			 */
4217 			if ((ipif->ipif_flags & IPIF_UP) &&
4218 			    !ipif->ipif_addr_ready) {
4219 				ipif_mask_reply(ipif);
4220 				ip_rts_ifmsg(ipif);
4221 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4222 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4223 			}
4224 			ipif->ipif_addr_ready = 1;
4225 			ipif_refrele(ipif);
4226 		}
4227 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp));
4228 		if (ire != NULL) {
4229 			ire->ire_defense_count = 0;
4230 			ire_refrele(ire);
4231 		}
4232 		break;
4233 	case AR_CN_FAILED:
4234 		/* No external v6 resolver has a contract to use this */
4235 		if (isv6)
4236 			break;
4237 		ill_refhold(ill);
4238 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4239 		    B_FALSE);
4240 		return;
4241 	}
4242 	freemsg(mp);
4243 }
4244 
4245 /*
4246  * Create a mblk suitable for carrying the interface index and/or source link
4247  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4248  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4249  * application.
4250  */
4251 mblk_t *
4252 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
4253 {
4254 	mblk_t		*mp;
4255 	in_pktinfo_t	*pinfo;
4256 	ipha_t *ipha;
4257 	struct ether_header *pether;
4258 
4259 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
4260 	if (mp == NULL) {
4261 		ip1dbg(("ip_add_info: allocation failure.\n"));
4262 		return (data_mp);
4263 	}
4264 
4265 	ipha	= (ipha_t *)data_mp->b_rptr;
4266 	pinfo = (in_pktinfo_t *)mp->b_rptr;
4267 	bzero(pinfo, sizeof (in_pktinfo_t));
4268 	pinfo->in_pkt_flags = (uchar_t)flags;
4269 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4270 
4271 	if (flags & IPF_RECVIF)
4272 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4273 
4274 	pether = (struct ether_header *)((char *)ipha
4275 	    - sizeof (struct ether_header));
4276 	/*
4277 	 * Make sure the interface is an ethernet type, since this option
4278 	 * is currently supported only on this type of interface. Also make
4279 	 * sure we are pointing correctly above db_base.
4280 	 */
4281 
4282 	if ((flags & IPF_RECVSLLA) &&
4283 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4284 	    (ill->ill_type == IFT_ETHER) &&
4285 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4286 
4287 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
4288 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4289 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
4290 	} else {
4291 		/*
4292 		 * Clear the bit. Indicate to upper layer that IP is not
4293 		 * sending this ancillary info.
4294 		 */
4295 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
4296 	}
4297 
4298 	mp->b_datap->db_type = M_CTL;
4299 	mp->b_wptr += sizeof (in_pktinfo_t);
4300 	mp->b_cont = data_mp;
4301 
4302 	return (mp);
4303 }
4304 
4305 /*
4306  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4307  * part of the bind request.
4308  */
4309 
4310 boolean_t
4311 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4312 {
4313 	ipsec_in_t *ii;
4314 
4315 	ASSERT(policy_mp != NULL);
4316 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4317 
4318 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4319 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4320 
4321 	connp->conn_policy = ii->ipsec_in_policy;
4322 	ii->ipsec_in_policy = NULL;
4323 
4324 	if (ii->ipsec_in_action != NULL) {
4325 		if (connp->conn_latch == NULL) {
4326 			connp->conn_latch = iplatch_create();
4327 			if (connp->conn_latch == NULL)
4328 				return (B_FALSE);
4329 		}
4330 		ipsec_latch_inbound(connp->conn_latch, ii);
4331 	}
4332 	return (B_TRUE);
4333 }
4334 
4335 /*
4336  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4337  * and to arrange for power-fanout assist.  The ULP is identified by
4338  * adding a single byte at the end of the original bind message.
4339  * A ULP other than UDP or TCP that wishes to be recognized passes
4340  * down a bind with a zero length address.
4341  *
4342  * The binding works as follows:
4343  * - A zero byte address means just bind to the protocol.
4344  * - A four byte address is treated as a request to validate
4345  *   that the address is a valid local address, appropriate for
4346  *   an application to bind to. This does not affect any fanout
4347  *   information in IP.
4348  * - A sizeof sin_t byte address is used to bind to only the local address
4349  *   and port.
4350  * - A sizeof ipa_conn_t byte address contains complete fanout information
4351  *   consisting of local and remote addresses and ports.  In
4352  *   this case, the addresses are both validated as appropriate
4353  *   for this operation, and, if so, the information is retained
4354  *   for use in the inbound fanout.
4355  *
4356  * The ULP (except in the zero-length bind) can append an
4357  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4358  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4359  * a copy of the source or destination IRE (source for local bind;
4360  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4361  * policy information contained should be copied on to the conn.
4362  *
4363  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4364  */
4365 mblk_t *
4366 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4367 {
4368 	ssize_t		len;
4369 	struct T_bind_req	*tbr;
4370 	sin_t		*sin;
4371 	ipa_conn_t	*ac;
4372 	uchar_t		*ucp;
4373 	mblk_t		*mp1;
4374 	boolean_t	ire_requested;
4375 	boolean_t	ipsec_policy_set = B_FALSE;
4376 	int		error = 0;
4377 	int		protocol;
4378 	ipa_conn_x_t	*acx;
4379 
4380 	ASSERT(!connp->conn_af_isv6);
4381 	connp->conn_pkt_isv6 = B_FALSE;
4382 
4383 	len = MBLKL(mp);
4384 	if (len < (sizeof (*tbr) + 1)) {
4385 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4386 		    "ip_bind: bogus msg, len %ld", len);
4387 		/* XXX: Need to return something better */
4388 		goto bad_addr;
4389 	}
4390 	/* Back up and extract the protocol identifier. */
4391 	mp->b_wptr--;
4392 	protocol = *mp->b_wptr & 0xFF;
4393 	tbr = (struct T_bind_req *)mp->b_rptr;
4394 	/* Reset the message type in preparation for shipping it back. */
4395 	DB_TYPE(mp) = M_PCPROTO;
4396 
4397 	connp->conn_ulp = (uint8_t)protocol;
4398 
4399 	/*
4400 	 * Check for a zero length address.  This is from a protocol that
4401 	 * wants to register to receive all packets of its type.
4402 	 */
4403 	if (tbr->ADDR_length == 0) {
4404 		/*
4405 		 * These protocols are now intercepted in ip_bind_v6().
4406 		 * Reject protocol-level binds here for now.
4407 		 *
4408 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4409 		 * so that the protocol type cannot be SCTP.
4410 		 */
4411 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4412 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4413 			goto bad_addr;
4414 		}
4415 
4416 		/*
4417 		 *
4418 		 * The udp module never sends down a zero-length address,
4419 		 * and allowing this on a labeled system will break MLP
4420 		 * functionality.
4421 		 */
4422 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4423 			goto bad_addr;
4424 
4425 		if (connp->conn_mac_exempt)
4426 			goto bad_addr;
4427 
4428 		/* No hash here really.  The table is big enough. */
4429 		connp->conn_srcv6 = ipv6_all_zeros;
4430 
4431 		ipcl_proto_insert(connp, protocol);
4432 
4433 		tbr->PRIM_type = T_BIND_ACK;
4434 		return (mp);
4435 	}
4436 
4437 	/* Extract the address pointer from the message. */
4438 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4439 	    tbr->ADDR_length);
4440 	if (ucp == NULL) {
4441 		ip1dbg(("ip_bind: no address\n"));
4442 		goto bad_addr;
4443 	}
4444 	if (!OK_32PTR(ucp)) {
4445 		ip1dbg(("ip_bind: unaligned address\n"));
4446 		goto bad_addr;
4447 	}
4448 	/*
4449 	 * Check for trailing mps.
4450 	 */
4451 
4452 	mp1 = mp->b_cont;
4453 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4454 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4455 
4456 	switch (tbr->ADDR_length) {
4457 	default:
4458 		ip1dbg(("ip_bind: bad address length %d\n",
4459 		    (int)tbr->ADDR_length));
4460 		goto bad_addr;
4461 
4462 	case IP_ADDR_LEN:
4463 		/* Verification of local address only */
4464 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4465 		    ire_requested, ipsec_policy_set, B_FALSE);
4466 		break;
4467 
4468 	case sizeof (sin_t):
4469 		sin = (sin_t *)ucp;
4470 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4471 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4472 		if (protocol == IPPROTO_TCP)
4473 			connp->conn_recv = tcp_conn_request;
4474 		break;
4475 
4476 	case sizeof (ipa_conn_t):
4477 		ac = (ipa_conn_t *)ucp;
4478 		/* For raw socket, the local port is not set. */
4479 		if (ac->ac_lport == 0)
4480 			ac->ac_lport = connp->conn_lport;
4481 		/* Always verify destination reachability. */
4482 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4483 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4484 		    ipsec_policy_set, B_TRUE, B_TRUE);
4485 		if (protocol == IPPROTO_TCP)
4486 			connp->conn_recv = tcp_input;
4487 		break;
4488 
4489 	case sizeof (ipa_conn_x_t):
4490 		acx = (ipa_conn_x_t *)ucp;
4491 		/*
4492 		 * Whether or not to verify destination reachability depends
4493 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4494 		 */
4495 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4496 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4497 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4498 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4499 		if (protocol == IPPROTO_TCP)
4500 			connp->conn_recv = tcp_input;
4501 		break;
4502 	}
4503 	if (error == EINPROGRESS)
4504 		return (NULL);
4505 	else if (error != 0)
4506 		goto bad_addr;
4507 	/*
4508 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4509 	 * We can't do this in ip_bind_insert_ire because the policy
4510 	 * may not have been inherited at that point in time and hence
4511 	 * conn_out_enforce_policy may not be set.
4512 	 */
4513 	mp1 = mp->b_cont;
4514 	if (ire_requested && connp->conn_out_enforce_policy &&
4515 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4516 		ire_t *ire = (ire_t *)mp1->b_rptr;
4517 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4518 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4519 	}
4520 
4521 	/* Send it home. */
4522 	mp->b_datap->db_type = M_PCPROTO;
4523 	tbr->PRIM_type = T_BIND_ACK;
4524 	return (mp);
4525 
4526 bad_addr:
4527 	/*
4528 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4529 	 * a unix errno.
4530 	 */
4531 	if (error > 0)
4532 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4533 	else
4534 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4535 	return (mp);
4536 }
4537 
4538 /*
4539  * Here address is verified to be a valid local address.
4540  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4541  * address is also considered a valid local address.
4542  * In the case of a broadcast/multicast address, however, the
4543  * upper protocol is expected to reset the src address
4544  * to 0 if it sees a IRE_BROADCAST type returned so that
4545  * no packets are emitted with broadcast/multicast address as
4546  * source address (that violates hosts requirements RFC1122)
4547  * The addresses valid for bind are:
4548  *	(1) - INADDR_ANY (0)
4549  *	(2) - IP address of an UP interface
4550  *	(3) - IP address of a DOWN interface
4551  *	(4) - valid local IP broadcast addresses. In this case
4552  *	the conn will only receive packets destined to
4553  *	the specified broadcast address.
4554  *	(5) - a multicast address. In this case
4555  *	the conn will only receive packets destined to
4556  *	the specified multicast address. Note: the
4557  *	application still has to issue an
4558  *	IP_ADD_MEMBERSHIP socket option.
4559  *
4560  * On error, return -1 for TBADADDR otherwise pass the
4561  * errno with TSYSERR reply.
4562  *
4563  * In all the above cases, the bound address must be valid in the current zone.
4564  * When the address is loopback, multicast or broadcast, there might be many
4565  * matching IREs so bind has to look up based on the zone.
4566  *
4567  * Note: lport is in network byte order.
4568  */
4569 int
4570 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4571     boolean_t ire_requested, boolean_t ipsec_policy_set,
4572     boolean_t fanout_insert)
4573 {
4574 	int		error = 0;
4575 	ire_t		*src_ire;
4576 	mblk_t		*policy_mp;
4577 	ipif_t		*ipif;
4578 	zoneid_t	zoneid;
4579 
4580 	if (ipsec_policy_set) {
4581 		policy_mp = mp->b_cont;
4582 	}
4583 
4584 	/*
4585 	 * If it was previously connected, conn_fully_bound would have
4586 	 * been set.
4587 	 */
4588 	connp->conn_fully_bound = B_FALSE;
4589 
4590 	src_ire = NULL;
4591 	ipif = NULL;
4592 
4593 	zoneid = IPCL_ZONEID(connp);
4594 
4595 	if (src_addr) {
4596 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4597 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4598 		/*
4599 		 * If an address other than 0.0.0.0 is requested,
4600 		 * we verify that it is a valid address for bind
4601 		 * Note: Following code is in if-else-if form for
4602 		 * readability compared to a condition check.
4603 		 */
4604 		/* LINTED - statement has no consequent */
4605 		if (IRE_IS_LOCAL(src_ire)) {
4606 			/*
4607 			 * (2) Bind to address of local UP interface
4608 			 */
4609 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4610 			/*
4611 			 * (4) Bind to broadcast address
4612 			 * Note: permitted only from transports that
4613 			 * request IRE
4614 			 */
4615 			if (!ire_requested)
4616 				error = EADDRNOTAVAIL;
4617 		} else {
4618 			/*
4619 			 * (3) Bind to address of local DOWN interface
4620 			 * (ipif_lookup_addr() looks up all interfaces
4621 			 * but we do not get here for UP interfaces
4622 			 * - case (2) above)
4623 			 * We put the protocol byte back into the mblk
4624 			 * since we may come back via ip_wput_nondata()
4625 			 * later with this mblk if ipif_lookup_addr chooses
4626 			 * to defer processing.
4627 			 */
4628 			*mp->b_wptr++ = (char)connp->conn_ulp;
4629 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4630 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4631 			    &error)) != NULL) {
4632 				ipif_refrele(ipif);
4633 			} else if (error == EINPROGRESS) {
4634 				if (src_ire != NULL)
4635 					ire_refrele(src_ire);
4636 				return (EINPROGRESS);
4637 			} else if (CLASSD(src_addr)) {
4638 				error = 0;
4639 				if (src_ire != NULL)
4640 					ire_refrele(src_ire);
4641 				/*
4642 				 * (5) bind to multicast address.
4643 				 * Fake out the IRE returned to upper
4644 				 * layer to be a broadcast IRE.
4645 				 */
4646 				src_ire = ire_ctable_lookup(
4647 				    INADDR_BROADCAST, INADDR_ANY,
4648 				    IRE_BROADCAST, NULL, zoneid, NULL,
4649 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4650 				if (src_ire == NULL || !ire_requested)
4651 					error = EADDRNOTAVAIL;
4652 			} else {
4653 				/*
4654 				 * Not a valid address for bind
4655 				 */
4656 				error = EADDRNOTAVAIL;
4657 			}
4658 			/*
4659 			 * Just to keep it consistent with the processing in
4660 			 * ip_bind_v4()
4661 			 */
4662 			mp->b_wptr--;
4663 		}
4664 		if (error) {
4665 			/* Red Alert!  Attempting to be a bogon! */
4666 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4667 			    ntohl(src_addr)));
4668 			goto bad_addr;
4669 		}
4670 	}
4671 
4672 	/*
4673 	 * Allow setting new policies. For example, disconnects come
4674 	 * down as ipa_t bind. As we would have set conn_policy_cached
4675 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4676 	 * can change after the disconnect.
4677 	 */
4678 	connp->conn_policy_cached = B_FALSE;
4679 
4680 	/*
4681 	 * If not fanout_insert this was just an address verification
4682 	 */
4683 	if (fanout_insert) {
4684 		/*
4685 		 * The addresses have been verified. Time to insert in
4686 		 * the correct fanout list.
4687 		 */
4688 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4689 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4690 		connp->conn_lport = lport;
4691 		connp->conn_fport = 0;
4692 		/*
4693 		 * Do we need to add a check to reject Multicast packets
4694 		 */
4695 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4696 	}
4697 
4698 	if (error == 0) {
4699 		if (ire_requested) {
4700 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4701 				error = -1;
4702 				/* Falls through to bad_addr */
4703 			}
4704 		} else if (ipsec_policy_set) {
4705 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4706 				error = -1;
4707 				/* Falls through to bad_addr */
4708 			}
4709 		}
4710 	}
4711 bad_addr:
4712 	if (error != 0) {
4713 		if (connp->conn_anon_port) {
4714 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4715 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4716 			    B_FALSE);
4717 		}
4718 		connp->conn_mlp_type = mlptSingle;
4719 	}
4720 	if (src_ire != NULL)
4721 		IRE_REFRELE(src_ire);
4722 	if (ipsec_policy_set) {
4723 		ASSERT(policy_mp == mp->b_cont);
4724 		ASSERT(policy_mp != NULL);
4725 		freeb(policy_mp);
4726 		/*
4727 		 * As of now assume that nothing else accompanies
4728 		 * IPSEC_POLICY_SET.
4729 		 */
4730 		mp->b_cont = NULL;
4731 	}
4732 	return (error);
4733 }
4734 
4735 /*
4736  * Verify that both the source and destination addresses
4737  * are valid.  If verify_dst is false, then the destination address may be
4738  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4739  * destination reachability, while tunnels do not.
4740  * Note that we allow connect to broadcast and multicast
4741  * addresses when ire_requested is set. Thus the ULP
4742  * has to check for IRE_BROADCAST and multicast.
4743  *
4744  * Returns zero if ok.
4745  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4746  * (for use with TSYSERR reply).
4747  *
4748  * Note: lport and fport are in network byte order.
4749  */
4750 int
4751 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4752     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4753     boolean_t ire_requested, boolean_t ipsec_policy_set,
4754     boolean_t fanout_insert, boolean_t verify_dst)
4755 {
4756 	ire_t		*src_ire;
4757 	ire_t		*dst_ire;
4758 	int		error = 0;
4759 	int 		protocol;
4760 	mblk_t		*policy_mp;
4761 	ire_t		*sire = NULL;
4762 	ire_t		*md_dst_ire = NULL;
4763 	ill_t		*md_ill = NULL;
4764 	zoneid_t	zoneid;
4765 	ipaddr_t	src_addr = *src_addrp;
4766 
4767 	src_ire = dst_ire = NULL;
4768 	protocol = *mp->b_wptr & 0xFF;
4769 
4770 	/*
4771 	 * If we never got a disconnect before, clear it now.
4772 	 */
4773 	connp->conn_fully_bound = B_FALSE;
4774 
4775 	if (ipsec_policy_set) {
4776 		policy_mp = mp->b_cont;
4777 	}
4778 
4779 	zoneid = IPCL_ZONEID(connp);
4780 
4781 	if (CLASSD(dst_addr)) {
4782 		/* Pick up an IRE_BROADCAST */
4783 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4784 		    NULL, zoneid, MBLK_GETLABEL(mp),
4785 		    (MATCH_IRE_RECURSIVE |
4786 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4787 		    MATCH_IRE_SECATTR));
4788 	} else {
4789 		/*
4790 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4791 		 * and onlink ipif is not found set ENETUNREACH error.
4792 		 */
4793 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4794 			ipif_t *ipif;
4795 
4796 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4797 			    dst_addr : connp->conn_nexthop_v4,
4798 			    connp->conn_zoneid);
4799 			if (ipif == NULL) {
4800 				error = ENETUNREACH;
4801 				goto bad_addr;
4802 			}
4803 			ipif_refrele(ipif);
4804 		}
4805 
4806 		if (connp->conn_nexthop_set) {
4807 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4808 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4809 			    MATCH_IRE_SECATTR);
4810 		} else {
4811 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4812 			    &sire, zoneid, MBLK_GETLABEL(mp),
4813 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4814 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4815 			    MATCH_IRE_SECATTR));
4816 		}
4817 	}
4818 	/*
4819 	 * dst_ire can't be a broadcast when not ire_requested.
4820 	 * We also prevent ire's with src address INADDR_ANY to
4821 	 * be used, which are created temporarily for
4822 	 * sending out packets from endpoints that have
4823 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4824 	 * reachable.  If verify_dst is false, the destination needn't be
4825 	 * reachable.
4826 	 *
4827 	 * If we match on a reject or black hole, then we've got a
4828 	 * local failure.  May as well fail out the connect() attempt,
4829 	 * since it's never going to succeed.
4830 	 */
4831 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4832 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4833 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4834 		/*
4835 		 * If we're verifying destination reachability, we always want
4836 		 * to complain here.
4837 		 *
4838 		 * If we're not verifying destination reachability but the
4839 		 * destination has a route, we still want to fail on the
4840 		 * temporary address and broadcast address tests.
4841 		 */
4842 		if (verify_dst || (dst_ire != NULL)) {
4843 			if (ip_debug > 2) {
4844 				pr_addr_dbg("ip_bind_connected: bad connected "
4845 				    "dst %s\n", AF_INET, &dst_addr);
4846 			}
4847 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4848 				error = ENETUNREACH;
4849 			else
4850 				error = EHOSTUNREACH;
4851 			goto bad_addr;
4852 		}
4853 	}
4854 
4855 	/*
4856 	 * We now know that routing will allow us to reach the destination.
4857 	 * Check whether Trusted Solaris policy allows communication with this
4858 	 * host, and pretend that the destination is unreachable if not.
4859 	 *
4860 	 * This is never a problem for TCP, since that transport is known to
4861 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4862 	 * handling.  If the remote is unreachable, it will be detected at that
4863 	 * point, so there's no reason to check it here.
4864 	 *
4865 	 * Note that for sendto (and other datagram-oriented friends), this
4866 	 * check is done as part of the data path label computation instead.
4867 	 * The check here is just to make non-TCP connect() report the right
4868 	 * error.
4869 	 */
4870 	if (dst_ire != NULL && is_system_labeled() &&
4871 	    !IPCL_IS_TCP(connp) &&
4872 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4873 	    connp->conn_mac_exempt) != 0) {
4874 		error = EHOSTUNREACH;
4875 		if (ip_debug > 2) {
4876 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4877 			    AF_INET, &dst_addr);
4878 		}
4879 		goto bad_addr;
4880 	}
4881 
4882 	/*
4883 	 * If the app does a connect(), it means that it will most likely
4884 	 * send more than 1 packet to the destination.  It makes sense
4885 	 * to clear the temporary flag.
4886 	 */
4887 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4888 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4889 		irb_t *irb = dst_ire->ire_bucket;
4890 
4891 		rw_enter(&irb->irb_lock, RW_WRITER);
4892 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4893 		irb->irb_tmp_ire_cnt--;
4894 		rw_exit(&irb->irb_lock);
4895 	}
4896 
4897 	/*
4898 	 * See if we should notify ULP about MDT; we do this whether or not
4899 	 * ire_requested is TRUE, in order to handle active connects; MDT
4900 	 * eligibility tests for passive connects are handled separately
4901 	 * through tcp_adapt_ire().  We do this before the source address
4902 	 * selection, because dst_ire may change after a call to
4903 	 * ipif_select_source().  This is a best-effort check, as the
4904 	 * packet for this connection may not actually go through
4905 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4906 	 * calling ip_newroute().  This is why we further check on the
4907 	 * IRE during Multidata packet transmission in tcp_multisend().
4908 	 */
4909 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4910 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4911 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4912 	    ILL_MDT_CAPABLE(md_ill)) {
4913 		md_dst_ire = dst_ire;
4914 		IRE_REFHOLD(md_dst_ire);
4915 	}
4916 
4917 	if (dst_ire != NULL &&
4918 	    dst_ire->ire_type == IRE_LOCAL &&
4919 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4920 		/*
4921 		 * If the IRE belongs to a different zone, look for a matching
4922 		 * route in the forwarding table and use the source address from
4923 		 * that route.
4924 		 */
4925 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4926 		    zoneid, 0, NULL,
4927 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4928 		    MATCH_IRE_RJ_BHOLE);
4929 		if (src_ire == NULL) {
4930 			error = EHOSTUNREACH;
4931 			goto bad_addr;
4932 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4933 			if (!(src_ire->ire_type & IRE_HOST))
4934 				error = ENETUNREACH;
4935 			else
4936 				error = EHOSTUNREACH;
4937 			goto bad_addr;
4938 		}
4939 		if (src_addr == INADDR_ANY)
4940 			src_addr = src_ire->ire_src_addr;
4941 		ire_refrele(src_ire);
4942 		src_ire = NULL;
4943 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4944 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4945 			src_addr = sire->ire_src_addr;
4946 			ire_refrele(dst_ire);
4947 			dst_ire = sire;
4948 			sire = NULL;
4949 		} else {
4950 			/*
4951 			 * Pick a source address so that a proper inbound
4952 			 * load spreading would happen.
4953 			 */
4954 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4955 			ipif_t *src_ipif = NULL;
4956 			ire_t *ipif_ire;
4957 
4958 			/*
4959 			 * Supply a local source address such that inbound
4960 			 * load spreading happens.
4961 			 *
4962 			 * Determine the best source address on this ill for
4963 			 * the destination.
4964 			 *
4965 			 * 1) For broadcast, we should return a broadcast ire
4966 			 *    found above so that upper layers know that the
4967 			 *    destination address is a broadcast address.
4968 			 *
4969 			 * 2) If this is part of a group, select a better
4970 			 *    source address so that better inbound load
4971 			 *    balancing happens. Do the same if the ipif
4972 			 *    is DEPRECATED.
4973 			 *
4974 			 * 3) If the outgoing interface is part of a usesrc
4975 			 *    group, then try selecting a source address from
4976 			 *    the usesrc ILL.
4977 			 */
4978 			if ((dst_ire->ire_zoneid != zoneid &&
4979 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4980 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4981 			    ((dst_ill->ill_group != NULL) ||
4982 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4983 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4984 				/*
4985 				 * If the destination is reachable via a
4986 				 * given gateway, the selected source address
4987 				 * should be in the same subnet as the gateway.
4988 				 * Otherwise, the destination is not reachable.
4989 				 *
4990 				 * If there are no interfaces on the same subnet
4991 				 * as the destination, ipif_select_source gives
4992 				 * first non-deprecated interface which might be
4993 				 * on a different subnet than the gateway.
4994 				 * This is not desirable. Hence pass the dst_ire
4995 				 * source address to ipif_select_source.
4996 				 * It is sure that the destination is reachable
4997 				 * with the dst_ire source address subnet.
4998 				 * So passing dst_ire source address to
4999 				 * ipif_select_source will make sure that the
5000 				 * selected source will be on the same subnet
5001 				 * as dst_ire source address.
5002 				 */
5003 				ipaddr_t saddr =
5004 				    dst_ire->ire_ipif->ipif_src_addr;
5005 				src_ipif = ipif_select_source(dst_ill,
5006 				    saddr, zoneid);
5007 				if (src_ipif != NULL) {
5008 					if (IS_VNI(src_ipif->ipif_ill)) {
5009 						/*
5010 						 * For VNI there is no
5011 						 * interface route
5012 						 */
5013 						src_addr =
5014 						    src_ipif->ipif_src_addr;
5015 					} else {
5016 						ipif_ire =
5017 						    ipif_to_ire(src_ipif);
5018 						if (ipif_ire != NULL) {
5019 							IRE_REFRELE(dst_ire);
5020 							dst_ire = ipif_ire;
5021 						}
5022 						src_addr =
5023 						    dst_ire->ire_src_addr;
5024 					}
5025 					ipif_refrele(src_ipif);
5026 				} else {
5027 					src_addr = dst_ire->ire_src_addr;
5028 				}
5029 			} else {
5030 				src_addr = dst_ire->ire_src_addr;
5031 			}
5032 		}
5033 	}
5034 
5035 	/*
5036 	 * We do ire_route_lookup() here (and not
5037 	 * interface lookup as we assert that
5038 	 * src_addr should only come from an
5039 	 * UP interface for hard binding.
5040 	 */
5041 	ASSERT(src_ire == NULL);
5042 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5043 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
5044 	/* src_ire must be a local|loopback */
5045 	if (!IRE_IS_LOCAL(src_ire)) {
5046 		if (ip_debug > 2) {
5047 			pr_addr_dbg("ip_bind_connected: bad connected "
5048 			    "src %s\n", AF_INET, &src_addr);
5049 		}
5050 		error = EADDRNOTAVAIL;
5051 		goto bad_addr;
5052 	}
5053 
5054 	/*
5055 	 * If the source address is a loopback address, the
5056 	 * destination had best be local or multicast.
5057 	 * The transports that can't handle multicast will reject
5058 	 * those addresses.
5059 	 */
5060 	if (src_ire->ire_type == IRE_LOOPBACK &&
5061 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5062 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5063 		error = -1;
5064 		goto bad_addr;
5065 	}
5066 
5067 	/*
5068 	 * Allow setting new policies. For example, disconnects come
5069 	 * down as ipa_t bind. As we would have set conn_policy_cached
5070 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5071 	 * can change after the disconnect.
5072 	 */
5073 	connp->conn_policy_cached = B_FALSE;
5074 
5075 	/*
5076 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5077 	 * can handle their passed-in conn's.
5078 	 */
5079 
5080 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5081 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5082 	connp->conn_lport = lport;
5083 	connp->conn_fport = fport;
5084 	*src_addrp = src_addr;
5085 
5086 	ASSERT(!(ipsec_policy_set && ire_requested));
5087 	if (ire_requested) {
5088 		iulp_t *ulp_info = NULL;
5089 
5090 		/*
5091 		 * Note that sire will not be NULL if this is an off-link
5092 		 * connection and there is not cache for that dest yet.
5093 		 *
5094 		 * XXX Because of an existing bug, if there are multiple
5095 		 * default routes, the IRE returned now may not be the actual
5096 		 * default route used (default routes are chosen in a
5097 		 * round robin fashion).  So if the metrics for different
5098 		 * default routes are different, we may return the wrong
5099 		 * metrics.  This will not be a problem if the existing
5100 		 * bug is fixed.
5101 		 */
5102 		if (sire != NULL) {
5103 			ulp_info = &(sire->ire_uinfo);
5104 		}
5105 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5106 			error = -1;
5107 			goto bad_addr;
5108 		}
5109 	} else if (ipsec_policy_set) {
5110 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5111 			error = -1;
5112 			goto bad_addr;
5113 		}
5114 	}
5115 
5116 	/*
5117 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5118 	 * we'll cache that.  If we don't, we'll inherit global policy.
5119 	 *
5120 	 * We can't insert until the conn reflects the policy. Note that
5121 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5122 	 * connections where we don't have a policy. This is to prevent
5123 	 * global policy lookups in the inbound path.
5124 	 *
5125 	 * If we insert before we set conn_policy_cached,
5126 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5127 	 * because global policy cound be non-empty. We normally call
5128 	 * ipsec_check_policy() for conn_policy_cached connections only if
5129 	 * ipc_in_enforce_policy is set. But in this case,
5130 	 * conn_policy_cached can get set anytime since we made the
5131 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5132 	 * called, which will make the above assumption false.  Thus, we
5133 	 * need to insert after we set conn_policy_cached.
5134 	 */
5135 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5136 		goto bad_addr;
5137 
5138 	if (fanout_insert) {
5139 		/*
5140 		 * The addresses have been verified. Time to insert in
5141 		 * the correct fanout list.
5142 		 */
5143 		error = ipcl_conn_insert(connp, protocol, src_addr,
5144 		    dst_addr, connp->conn_ports);
5145 	}
5146 
5147 	if (error == 0) {
5148 		connp->conn_fully_bound = B_TRUE;
5149 		/*
5150 		 * Our initial checks for MDT have passed; the IRE is not
5151 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5152 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
5153 		 * ip_mdinfo_return(), which performs further checks
5154 		 * against them and upon success, returns the MDT info
5155 		 * mblk which we will attach to the bind acknowledgment.
5156 		 */
5157 		if (md_dst_ire != NULL) {
5158 			mblk_t *mdinfo_mp;
5159 
5160 			ASSERT(md_ill != NULL);
5161 			ASSERT(md_ill->ill_mdt_capab != NULL);
5162 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5163 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
5164 				linkb(mp, mdinfo_mp);
5165 		}
5166 	}
5167 bad_addr:
5168 	if (ipsec_policy_set) {
5169 		ASSERT(policy_mp == mp->b_cont);
5170 		ASSERT(policy_mp != NULL);
5171 		freeb(policy_mp);
5172 		/*
5173 		 * As of now assume that nothing else accompanies
5174 		 * IPSEC_POLICY_SET.
5175 		 */
5176 		mp->b_cont = NULL;
5177 	}
5178 	if (src_ire != NULL)
5179 		IRE_REFRELE(src_ire);
5180 	if (dst_ire != NULL)
5181 		IRE_REFRELE(dst_ire);
5182 	if (sire != NULL)
5183 		IRE_REFRELE(sire);
5184 	if (md_dst_ire != NULL)
5185 		IRE_REFRELE(md_dst_ire);
5186 	return (error);
5187 }
5188 
5189 /*
5190  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5191  * Prefers dst_ire over src_ire.
5192  */
5193 static boolean_t
5194 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5195 {
5196 	mblk_t	*mp1;
5197 	ire_t *ret_ire = NULL;
5198 
5199 	mp1 = mp->b_cont;
5200 	ASSERT(mp1 != NULL);
5201 
5202 	if (ire != NULL) {
5203 		/*
5204 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5205 		 * appended mblk. Its <upper protocol>'s
5206 		 * job to make sure there is room.
5207 		 */
5208 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5209 			return (0);
5210 
5211 		mp1->b_datap->db_type = IRE_DB_TYPE;
5212 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5213 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5214 		ret_ire = (ire_t *)mp1->b_rptr;
5215 		/*
5216 		 * Pass the latest setting of the ip_path_mtu_discovery and
5217 		 * copy the ulp info if any.
5218 		 */
5219 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5220 		    IPH_DF : 0;
5221 		if (ulp_info != NULL) {
5222 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5223 			    sizeof (iulp_t));
5224 		}
5225 		ret_ire->ire_mp = mp1;
5226 	} else {
5227 		/*
5228 		 * No IRE was found. Remove IRE mblk.
5229 		 */
5230 		mp->b_cont = mp1->b_cont;
5231 		freeb(mp1);
5232 	}
5233 
5234 	return (1);
5235 }
5236 
5237 /*
5238  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5239  * the final piece where we don't.  Return a pointer to the first mblk in the
5240  * result, and update the pointer to the next mblk to chew on.  If anything
5241  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5242  * NULL pointer.
5243  */
5244 mblk_t *
5245 ip_carve_mp(mblk_t **mpp, ssize_t len)
5246 {
5247 	mblk_t	*mp0;
5248 	mblk_t	*mp1;
5249 	mblk_t	*mp2;
5250 
5251 	if (!len || !mpp || !(mp0 = *mpp))
5252 		return (NULL);
5253 	/* If we aren't going to consume the first mblk, we need a dup. */
5254 	if (mp0->b_wptr - mp0->b_rptr > len) {
5255 		mp1 = dupb(mp0);
5256 		if (mp1) {
5257 			/* Partition the data between the two mblks. */
5258 			mp1->b_wptr = mp1->b_rptr + len;
5259 			mp0->b_rptr = mp1->b_wptr;
5260 			/*
5261 			 * after adjustments if mblk not consumed is now
5262 			 * unaligned, try to align it. If this fails free
5263 			 * all messages and let upper layer recover.
5264 			 */
5265 			if (!OK_32PTR(mp0->b_rptr)) {
5266 				if (!pullupmsg(mp0, -1)) {
5267 					freemsg(mp0);
5268 					freemsg(mp1);
5269 					*mpp = NULL;
5270 					return (NULL);
5271 				}
5272 			}
5273 		}
5274 		return (mp1);
5275 	}
5276 	/* Eat through as many mblks as we need to get len bytes. */
5277 	len -= mp0->b_wptr - mp0->b_rptr;
5278 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5279 		if (mp2->b_wptr - mp2->b_rptr > len) {
5280 			/*
5281 			 * We won't consume the entire last mblk.  Like
5282 			 * above, dup and partition it.
5283 			 */
5284 			mp1->b_cont = dupb(mp2);
5285 			mp1 = mp1->b_cont;
5286 			if (!mp1) {
5287 				/*
5288 				 * Trouble.  Rather than go to a lot of
5289 				 * trouble to clean up, we free the messages.
5290 				 * This won't be any worse than losing it on
5291 				 * the wire.
5292 				 */
5293 				freemsg(mp0);
5294 				freemsg(mp2);
5295 				*mpp = NULL;
5296 				return (NULL);
5297 			}
5298 			mp1->b_wptr = mp1->b_rptr + len;
5299 			mp2->b_rptr = mp1->b_wptr;
5300 			/*
5301 			 * after adjustments if mblk not consumed is now
5302 			 * unaligned, try to align it. If this fails free
5303 			 * all messages and let upper layer recover.
5304 			 */
5305 			if (!OK_32PTR(mp2->b_rptr)) {
5306 				if (!pullupmsg(mp2, -1)) {
5307 					freemsg(mp0);
5308 					freemsg(mp2);
5309 					*mpp = NULL;
5310 					return (NULL);
5311 				}
5312 			}
5313 			*mpp = mp2;
5314 			return (mp0);
5315 		}
5316 		/* Decrement len by the amount we just got. */
5317 		len -= mp2->b_wptr - mp2->b_rptr;
5318 	}
5319 	/*
5320 	 * len should be reduced to zero now.  If not our caller has
5321 	 * screwed up.
5322 	 */
5323 	if (len) {
5324 		/* Shouldn't happen! */
5325 		freemsg(mp0);
5326 		*mpp = NULL;
5327 		return (NULL);
5328 	}
5329 	/*
5330 	 * We consumed up to exactly the end of an mblk.  Detach the part
5331 	 * we are returning from the rest of the chain.
5332 	 */
5333 	mp1->b_cont = NULL;
5334 	*mpp = mp2;
5335 	return (mp0);
5336 }
5337 
5338 /* The ill stream is being unplumbed. Called from ip_close */
5339 int
5340 ip_modclose(ill_t *ill)
5341 {
5342 
5343 	boolean_t success;
5344 	ipsq_t	*ipsq;
5345 	ipif_t	*ipif;
5346 	queue_t	*q = ill->ill_rq;
5347 	hook_nic_event_t *info;
5348 
5349 	/*
5350 	 * Forcibly enter the ipsq after some delay. This is to take
5351 	 * care of the case when some ioctl does not complete because
5352 	 * we sent a control message to the driver and it did not
5353 	 * send us a reply. We want to be able to at least unplumb
5354 	 * and replumb rather than force the user to reboot the system.
5355 	 */
5356 	success = ipsq_enter(ill, B_FALSE);
5357 
5358 	/*
5359 	 * Open/close/push/pop is guaranteed to be single threaded
5360 	 * per stream by STREAMS. FS guarantees that all references
5361 	 * from top are gone before close is called. So there can't
5362 	 * be another close thread that has set CONDEMNED on this ill.
5363 	 * and cause ipsq_enter to return failure.
5364 	 */
5365 	ASSERT(success);
5366 	ipsq = ill->ill_phyint->phyint_ipsq;
5367 
5368 	/*
5369 	 * Mark it condemned. No new reference will be made to this ill.
5370 	 * Lookup functions will return an error. Threads that try to
5371 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5372 	 * that the refcnt will drop down to zero.
5373 	 */
5374 	mutex_enter(&ill->ill_lock);
5375 	ill->ill_state_flags |= ILL_CONDEMNED;
5376 	for (ipif = ill->ill_ipif; ipif != NULL;
5377 	    ipif = ipif->ipif_next) {
5378 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5379 	}
5380 	/*
5381 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5382 	 * returns  error if ILL_CONDEMNED is set
5383 	 */
5384 	cv_broadcast(&ill->ill_cv);
5385 	mutex_exit(&ill->ill_lock);
5386 
5387 	/*
5388 	 * Shut down fragmentation reassembly.
5389 	 * ill_frag_timer won't start a timer again.
5390 	 * Now cancel any existing timer
5391 	 */
5392 	(void) untimeout(ill->ill_frag_timer_id);
5393 	(void) ill_frag_timeout(ill, 0);
5394 
5395 	/*
5396 	 * If MOVE was in progress, clear the
5397 	 * move_in_progress fields also.
5398 	 */
5399 	if (ill->ill_move_in_progress) {
5400 		ILL_CLEAR_MOVE(ill);
5401 	}
5402 
5403 	/*
5404 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5405 	 * this ill. Then wait for the refcnts to drop to zero.
5406 	 * ill_is_quiescent checks whether the ill is really quiescent.
5407 	 * Then make sure that threads that are waiting to enter the
5408 	 * ipsq have seen the error returned by ipsq_enter and have
5409 	 * gone away. Then we call ill_delete_tail which does the
5410 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5411 	 */
5412 	ill_delete(ill);
5413 	mutex_enter(&ill->ill_lock);
5414 	while (!ill_is_quiescent(ill))
5415 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5416 	while (ill->ill_waiters)
5417 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5418 
5419 	mutex_exit(&ill->ill_lock);
5420 
5421 	/* qprocsoff is called in ill_delete_tail */
5422 	ill_delete_tail(ill);
5423 
5424 	/*
5425 	 * Walk through all upper (conn) streams and qenable
5426 	 * those that have queued data.
5427 	 * close synchronization needs this to
5428 	 * be done to ensure that all upper layers blocked
5429 	 * due to flow control to the closing device
5430 	 * get unblocked.
5431 	 */
5432 	ip1dbg(("ip_wsrv: walking\n"));
5433 	conn_walk_drain();
5434 
5435 	mutex_enter(&ip_mi_lock);
5436 	mi_close_unlink(&ip_g_head, (IDP)ill);
5437 	mutex_exit(&ip_mi_lock);
5438 
5439 	/*
5440 	 * credp could be null if the open didn't succeed and ip_modopen
5441 	 * itself calls ip_close.
5442 	 */
5443 	if (ill->ill_credp != NULL)
5444 		crfree(ill->ill_credp);
5445 
5446 	/*
5447 	 * Unhook the nic event message from the ill and enqueue it into the nic
5448 	 * event taskq.
5449 	 */
5450 	if ((info = ill->ill_nic_event_info) != NULL) {
5451 		if (ddi_taskq_dispatch(eventq_queue_nic, ip_ne_queue_func,
5452 		    (void *)info, DDI_SLEEP) == DDI_FAILURE) {
5453 			ip2dbg(("ip_ioctl_finish:ddi_taskq_dispatch failed\n"));
5454 			if (info->hne_data != NULL)
5455 				kmem_free(info->hne_data, info->hne_datalen);
5456 			kmem_free(info, sizeof (hook_nic_event_t));
5457 		}
5458 		ill->ill_nic_event_info = NULL;
5459 	}
5460 
5461 	mi_close_free((IDP)ill);
5462 	q->q_ptr = WR(q)->q_ptr = NULL;
5463 
5464 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5465 
5466 	return (0);
5467 }
5468 
5469 /*
5470  * This is called as part of close() for both IP and UDP
5471  * in order to quiesce the conn.
5472  */
5473 void
5474 ip_quiesce_conn(conn_t *connp)
5475 {
5476 	boolean_t	drain_cleanup_reqd = B_FALSE;
5477 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5478 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5479 
5480 	ASSERT(!IPCL_IS_TCP(connp));
5481 
5482 	/*
5483 	 * Mark the conn as closing, and this conn must not be
5484 	 * inserted in future into any list. Eg. conn_drain_insert(),
5485 	 * won't insert this conn into the conn_drain_list.
5486 	 * Similarly ill_pending_mp_add() will not add any mp to
5487 	 * the pending mp list, after this conn has started closing.
5488 	 *
5489 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5490 	 * cannot get set henceforth.
5491 	 */
5492 	mutex_enter(&connp->conn_lock);
5493 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5494 	connp->conn_state_flags |= CONN_CLOSING;
5495 	if (connp->conn_idl != NULL)
5496 		drain_cleanup_reqd = B_TRUE;
5497 	if (connp->conn_oper_pending_ill != NULL)
5498 		conn_ioctl_cleanup_reqd = B_TRUE;
5499 	if (connp->conn_ilg_inuse != 0)
5500 		ilg_cleanup_reqd = B_TRUE;
5501 	mutex_exit(&connp->conn_lock);
5502 
5503 	if (IPCL_IS_UDP(connp))
5504 		udp_quiesce_conn(connp);
5505 
5506 	if (conn_ioctl_cleanup_reqd)
5507 		conn_ioctl_cleanup(connp);
5508 
5509 	if (is_system_labeled() && connp->conn_anon_port) {
5510 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5511 		    connp->conn_mlp_type, connp->conn_ulp,
5512 		    ntohs(connp->conn_lport), B_FALSE);
5513 		connp->conn_anon_port = 0;
5514 	}
5515 	connp->conn_mlp_type = mlptSingle;
5516 
5517 	/*
5518 	 * Remove this conn from any fanout list it is on.
5519 	 * and then wait for any threads currently operating
5520 	 * on this endpoint to finish
5521 	 */
5522 	ipcl_hash_remove(connp);
5523 
5524 	/*
5525 	 * Remove this conn from the drain list, and do
5526 	 * any other cleanup that may be required.
5527 	 * (Only non-tcp streams may have a non-null conn_idl.
5528 	 * TCP streams are never flow controlled, and
5529 	 * conn_idl will be null)
5530 	 */
5531 	if (drain_cleanup_reqd)
5532 		conn_drain_tail(connp, B_TRUE);
5533 
5534 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5535 		(void) ip_mrouter_done(NULL);
5536 
5537 	if (ilg_cleanup_reqd)
5538 		ilg_delete_all(connp);
5539 
5540 	conn_delete_ire(connp, NULL);
5541 
5542 	/*
5543 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5544 	 * callers from write side can't be there now because close
5545 	 * is in progress. The only other caller is ipcl_walk
5546 	 * which checks for the condemned flag.
5547 	 */
5548 	mutex_enter(&connp->conn_lock);
5549 	connp->conn_state_flags |= CONN_CONDEMNED;
5550 	while (connp->conn_ref != 1)
5551 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5552 	connp->conn_state_flags |= CONN_QUIESCED;
5553 	mutex_exit(&connp->conn_lock);
5554 }
5555 
5556 /* ARGSUSED */
5557 int
5558 ip_close(queue_t *q, int flags)
5559 {
5560 	conn_t		*connp;
5561 
5562 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5563 
5564 	/*
5565 	 * Call the appropriate delete routine depending on whether this is
5566 	 * a module or device.
5567 	 */
5568 	if (WR(q)->q_next != NULL) {
5569 		/* This is a module close */
5570 		return (ip_modclose((ill_t *)q->q_ptr));
5571 	}
5572 
5573 	connp = q->q_ptr;
5574 	ip_quiesce_conn(connp);
5575 
5576 	qprocsoff(q);
5577 
5578 	/*
5579 	 * Now we are truly single threaded on this stream, and can
5580 	 * delete the things hanging off the connp, and finally the connp.
5581 	 * We removed this connp from the fanout list, it cannot be
5582 	 * accessed thru the fanouts, and we already waited for the
5583 	 * conn_ref to drop to 0. We are already in close, so
5584 	 * there cannot be any other thread from the top. qprocsoff
5585 	 * has completed, and service has completed or won't run in
5586 	 * future.
5587 	 */
5588 	ASSERT(connp->conn_ref == 1);
5589 
5590 	/*
5591 	 * A conn which was previously marked as IPCL_UDP cannot
5592 	 * retain the flag because it would have been cleared by
5593 	 * udp_close().
5594 	 */
5595 	ASSERT(!IPCL_IS_UDP(connp));
5596 
5597 	if (connp->conn_latch != NULL) {
5598 		IPLATCH_REFRELE(connp->conn_latch);
5599 		connp->conn_latch = NULL;
5600 	}
5601 	if (connp->conn_policy != NULL) {
5602 		IPPH_REFRELE(connp->conn_policy);
5603 		connp->conn_policy = NULL;
5604 	}
5605 	if (connp->conn_ipsec_opt_mp != NULL) {
5606 		freemsg(connp->conn_ipsec_opt_mp);
5607 		connp->conn_ipsec_opt_mp = NULL;
5608 	}
5609 
5610 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5611 
5612 	connp->conn_ref--;
5613 	ipcl_conn_destroy(connp);
5614 
5615 	q->q_ptr = WR(q)->q_ptr = NULL;
5616 	return (0);
5617 }
5618 
5619 int
5620 ip_snmpmod_close(queue_t *q)
5621 {
5622 	conn_t *connp = Q_TO_CONN(q);
5623 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5624 
5625 	qprocsoff(q);
5626 
5627 	if (connp->conn_flags & IPCL_UDPMOD)
5628 		udp_close_free(connp);
5629 
5630 	if (connp->conn_cred != NULL) {
5631 		crfree(connp->conn_cred);
5632 		connp->conn_cred = NULL;
5633 	}
5634 	CONN_DEC_REF(connp);
5635 	q->q_ptr = WR(q)->q_ptr = NULL;
5636 	return (0);
5637 }
5638 
5639 /*
5640  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5641  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5642  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5643  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5644  * queues as we never enqueue messages there and we don't handle any ioctls.
5645  * Everything else is freed.
5646  */
5647 void
5648 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5649 {
5650 	conn_t	*connp = q->q_ptr;
5651 	pfi_t	setfn;
5652 	pfi_t	getfn;
5653 
5654 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5655 
5656 	switch (DB_TYPE(mp)) {
5657 	case M_PROTO:
5658 	case M_PCPROTO:
5659 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5660 		    ((((union T_primitives *)mp->b_rptr)->type ==
5661 			T_SVR4_OPTMGMT_REQ) ||
5662 		    (((union T_primitives *)mp->b_rptr)->type ==
5663 			T_OPTMGMT_REQ))) {
5664 			/*
5665 			 * This is the only TPI primitive supported. Its
5666 			 * handling does not require tcp_t, but it does require
5667 			 * conn_t to check permissions.
5668 			 */
5669 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5670 
5671 			if (connp->conn_flags & IPCL_TCPMOD) {
5672 				setfn = tcp_snmp_set;
5673 				getfn = tcp_snmp_get;
5674 			} else {
5675 				setfn = udp_snmp_set;
5676 				getfn = udp_snmp_get;
5677 			}
5678 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5679 				freemsg(mp);
5680 				return;
5681 			}
5682 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5683 		    != NULL)
5684 			qreply(q, mp);
5685 		break;
5686 	case M_FLUSH:
5687 	case M_IOCTL:
5688 		putnext(q, mp);
5689 		break;
5690 	default:
5691 		freemsg(mp);
5692 		break;
5693 	}
5694 }
5695 
5696 /* Return the IP checksum for the IP header at "iph". */
5697 uint16_t
5698 ip_csum_hdr(ipha_t *ipha)
5699 {
5700 	uint16_t	*uph;
5701 	uint32_t	sum;
5702 	int		opt_len;
5703 
5704 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5705 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5706 	uph = (uint16_t *)ipha;
5707 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5708 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5709 	if (opt_len > 0) {
5710 		do {
5711 			sum += uph[10];
5712 			sum += uph[11];
5713 			uph += 2;
5714 		} while (--opt_len);
5715 	}
5716 	sum = (sum & 0xFFFF) + (sum >> 16);
5717 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5718 	if (sum == 0xffff)
5719 		sum = 0;
5720 	return ((uint16_t)sum);
5721 }
5722 
5723 void
5724 ip_ddi_destroy(void)
5725 {
5726 	ipv4_hook_destroy();
5727 	ipv6_hook_destroy();
5728 	ip_net_destroy();
5729 
5730 	tnet_fini();
5731 	tcp_ddi_destroy();
5732 	sctp_ddi_destroy();
5733 	ipsec_loader_destroy();
5734 	ipsec_policy_destroy();
5735 	ipsec_kstat_destroy();
5736 	nd_free(&ip_g_nd);
5737 	mutex_destroy(&igmp_timer_lock);
5738 	mutex_destroy(&mld_timer_lock);
5739 	mutex_destroy(&igmp_slowtimeout_lock);
5740 	mutex_destroy(&mld_slowtimeout_lock);
5741 	mutex_destroy(&ip_mi_lock);
5742 	mutex_destroy(&rts_clients.connf_lock);
5743 	ip_ire_fini();
5744 	ip6_asp_free();
5745 	conn_drain_fini();
5746 	ipcl_destroy();
5747 	inet_minor_destroy(ip_minor_arena);
5748 	icmp_kstat_fini();
5749 	ip_kstat_fini();
5750 	rw_destroy(&ipsec_capab_ills_lock);
5751 	rw_destroy(&ill_g_usesrc_lock);
5752 	ip_drop_unregister(&ip_dropper);
5753 }
5754 
5755 
5756 void
5757 ip_ddi_init(void)
5758 {
5759 	TCP6_MAJ = ddi_name_to_major(TCP6);
5760 	TCP_MAJ	= ddi_name_to_major(TCP);
5761 	SCTP_MAJ = ddi_name_to_major(SCTP);
5762 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5763 
5764 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5765 
5766 	/* IP's IPsec code calls the packet dropper */
5767 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5768 
5769 	if (!ip_g_nd) {
5770 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5771 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5772 			nd_free(&ip_g_nd);
5773 		}
5774 	}
5775 
5776 	ipsec_loader_init();
5777 	ipsec_policy_init();
5778 	ipsec_kstat_init();
5779 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5780 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5781 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5782 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5783 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5784 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5785 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5786 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5787 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5788 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5789 
5790 	/*
5791 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5792 	 * initial devices: ip, ip6, tcp, tcp6.
5793 	 */
5794 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5795 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5796 		cmn_err(CE_PANIC,
5797 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5798 	}
5799 
5800 	ipcl_init();
5801 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5802 	ip_ire_init();
5803 	ip6_asp_init();
5804 	ipif_init();
5805 	conn_drain_init();
5806 	tcp_ddi_init();
5807 	sctp_ddi_init();
5808 
5809 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5810 
5811 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5812 		"net", KSTAT_TYPE_NAMED,
5813 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5814 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5815 		ip_kstat->ks_data = &ip_statistics;
5816 		kstat_install(ip_kstat);
5817 	}
5818 	ip_kstat_init();
5819 	ip6_kstat_init();
5820 	icmp_kstat_init();
5821 	ipsec_loader_start();
5822 	tnet_init();
5823 
5824 	ip_net_init();
5825 	ipv4_hook_init();
5826 	ipv6_hook_init();
5827 }
5828 
5829 /*
5830  * Allocate and initialize a DLPI template of the specified length.  (May be
5831  * called as writer.)
5832  */
5833 mblk_t *
5834 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5835 {
5836 	mblk_t	*mp;
5837 
5838 	mp = allocb(len, BPRI_MED);
5839 	if (!mp)
5840 		return (NULL);
5841 
5842 	/*
5843 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5844 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5845 	 * that other DLPI are M_PROTO.
5846 	 */
5847 	if (prim == DL_INFO_REQ) {
5848 		mp->b_datap->db_type = M_PCPROTO;
5849 	} else {
5850 		mp->b_datap->db_type = M_PROTO;
5851 	}
5852 
5853 	mp->b_wptr = mp->b_rptr + len;
5854 	bzero(mp->b_rptr, len);
5855 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5856 	return (mp);
5857 }
5858 
5859 const char *
5860 dlpi_prim_str(int prim)
5861 {
5862 	switch (prim) {
5863 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5864 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5865 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5866 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5867 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5868 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5869 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5870 	case DL_OK_ACK:		return ("DL_OK_ACK");
5871 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5872 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5873 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5874 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5875 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5876 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5877 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5878 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5879 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5880 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5881 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5882 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5883 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5884 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5885 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5886 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5887 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5888 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5889 	default:		return ("<unknown primitive>");
5890 	}
5891 }
5892 
5893 const char *
5894 dlpi_err_str(int err)
5895 {
5896 	switch (err) {
5897 	case DL_ACCESS:		return ("DL_ACCESS");
5898 	case DL_BADADDR:	return ("DL_BADADDR");
5899 	case DL_BADCORR:	return ("DL_BADCORR");
5900 	case DL_BADDATA:	return ("DL_BADDATA");
5901 	case DL_BADPPA:		return ("DL_BADPPA");
5902 	case DL_BADPRIM:	return ("DL_BADPRIM");
5903 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5904 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5905 	case DL_BADSAP:		return ("DL_BADSAP");
5906 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5907 	case DL_BOUND:		return ("DL_BOUND");
5908 	case DL_INITFAILED:	return ("DL_INITFAILED");
5909 	case DL_NOADDR:		return ("DL_NOADDR");
5910 	case DL_NOTINIT:	return ("DL_NOTINIT");
5911 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5912 	case DL_SYSERR:		return ("DL_SYSERR");
5913 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5914 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5915 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5916 	case DL_TOOMANY:	return ("DL_TOOMANY");
5917 	case DL_NOTENAB:	return ("DL_NOTENAB");
5918 	case DL_BUSY:		return ("DL_BUSY");
5919 	case DL_NOAUTO:		return ("DL_NOAUTO");
5920 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5921 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5922 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5923 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5924 	case DL_PENDING:	return ("DL_PENDING");
5925 	default:		return ("<unknown error>");
5926 	}
5927 }
5928 
5929 /*
5930  * Debug formatting routine.  Returns a character string representation of the
5931  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5932  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5933  *
5934  * Once the ndd table-printing interfaces are removed, this can be changed to
5935  * standard dotted-decimal form.
5936  */
5937 char *
5938 ip_dot_addr(ipaddr_t addr, char *buf)
5939 {
5940 	uint8_t *ap = (uint8_t *)&addr;
5941 
5942 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5943 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
5944 	return (buf);
5945 }
5946 
5947 /*
5948  * Write the given MAC address as a printable string in the usual colon-
5949  * separated format.
5950  */
5951 const char *
5952 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
5953 {
5954 	char *bp;
5955 
5956 	if (alen == 0 || buflen < 4)
5957 		return ("?");
5958 	bp = buf;
5959 	for (;;) {
5960 		/*
5961 		 * If there are more MAC address bytes available, but we won't
5962 		 * have any room to print them, then add "..." to the string
5963 		 * instead.  See below for the 'magic number' explanation.
5964 		 */
5965 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
5966 			(void) strcpy(bp, "...");
5967 			break;
5968 		}
5969 		(void) sprintf(bp, "%02x", *addr++);
5970 		bp += 2;
5971 		if (--alen == 0)
5972 			break;
5973 		*bp++ = ':';
5974 		buflen -= 3;
5975 		/*
5976 		 * At this point, based on the first 'if' statement above,
5977 		 * either alen == 1 and buflen >= 3, or alen > 1 and
5978 		 * buflen >= 4.  The first case leaves room for the final "xx"
5979 		 * number and trailing NUL byte.  The second leaves room for at
5980 		 * least "...".  Thus the apparently 'magic' numbers chosen for
5981 		 * that statement.
5982 		 */
5983 	}
5984 	return (buf);
5985 }
5986 
5987 /*
5988  * Send an ICMP error after patching up the packet appropriately.  Returns
5989  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5990  */
5991 static boolean_t
5992 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5993     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5994 {
5995 	ipha_t *ipha;
5996 	mblk_t *first_mp;
5997 	boolean_t secure;
5998 	unsigned char db_type;
5999 
6000 	first_mp = mp;
6001 	if (mctl_present) {
6002 		mp = mp->b_cont;
6003 		secure = ipsec_in_is_secure(first_mp);
6004 		ASSERT(mp != NULL);
6005 	} else {
6006 		/*
6007 		 * If this is an ICMP error being reported - which goes
6008 		 * up as M_CTLs, we need to convert them to M_DATA till
6009 		 * we finish checking with global policy because
6010 		 * ipsec_check_global_policy() assumes M_DATA as clear
6011 		 * and M_CTL as secure.
6012 		 */
6013 		db_type = DB_TYPE(mp);
6014 		DB_TYPE(mp) = M_DATA;
6015 		secure = B_FALSE;
6016 	}
6017 	/*
6018 	 * We are generating an icmp error for some inbound packet.
6019 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6020 	 * Before we generate an error, check with global policy
6021 	 * to see whether this is allowed to enter the system. As
6022 	 * there is no "conn", we are checking with global policy.
6023 	 */
6024 	ipha = (ipha_t *)mp->b_rptr;
6025 	if (secure || ipsec_inbound_v4_policy_present) {
6026 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6027 		    ipha, NULL, mctl_present);
6028 		if (first_mp == NULL)
6029 			return (B_FALSE);
6030 	}
6031 
6032 	if (!mctl_present)
6033 		DB_TYPE(mp) = db_type;
6034 
6035 	if (flags & IP_FF_SEND_ICMP) {
6036 		if (flags & IP_FF_HDR_COMPLETE) {
6037 			if (ip_hdr_complete(ipha, zoneid)) {
6038 				freemsg(first_mp);
6039 				return (B_TRUE);
6040 			}
6041 		}
6042 		if (flags & IP_FF_CKSUM) {
6043 			/*
6044 			 * Have to correct checksum since
6045 			 * the packet might have been
6046 			 * fragmented and the reassembly code in ip_rput
6047 			 * does not restore the IP checksum.
6048 			 */
6049 			ipha->ipha_hdr_checksum = 0;
6050 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6051 		}
6052 		switch (icmp_type) {
6053 		case ICMP_DEST_UNREACHABLE:
6054 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid);
6055 			break;
6056 		default:
6057 			freemsg(first_mp);
6058 			break;
6059 		}
6060 	} else {
6061 		freemsg(first_mp);
6062 		return (B_FALSE);
6063 	}
6064 
6065 	return (B_TRUE);
6066 }
6067 
6068 /*
6069  * Used to send an ICMP error message when a packet is received for
6070  * a protocol that is not supported. The mblk passed as argument
6071  * is consumed by this function.
6072  */
6073 void
6074 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
6075 {
6076 	mblk_t *mp;
6077 	ipha_t *ipha;
6078 	ill_t *ill;
6079 	ipsec_in_t *ii;
6080 
6081 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6082 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6083 
6084 	mp = ipsec_mp->b_cont;
6085 	ipsec_mp->b_cont = NULL;
6086 	ipha = (ipha_t *)mp->b_rptr;
6087 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6088 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
6089 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6090 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
6091 		}
6092 	} else {
6093 		/* Get ill from index in ipsec_in_t. */
6094 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6095 		    B_TRUE, NULL, NULL, NULL, NULL);
6096 		if (ill != NULL) {
6097 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6098 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6099 			    0, B_FALSE, zoneid)) {
6100 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
6101 			}
6102 
6103 			ill_refrele(ill);
6104 		} else { /* re-link for the freemsg() below. */
6105 			ipsec_mp->b_cont = mp;
6106 		}
6107 	}
6108 
6109 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6110 	freemsg(ipsec_mp);
6111 }
6112 
6113 /*
6114  * See if the inbound datagram has had IPsec processing applied to it.
6115  */
6116 boolean_t
6117 ipsec_in_is_secure(mblk_t *ipsec_mp)
6118 {
6119 	ipsec_in_t *ii;
6120 
6121 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6122 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6123 
6124 	if (ii->ipsec_in_loopback) {
6125 		return (ii->ipsec_in_secure);
6126 	} else {
6127 		return (ii->ipsec_in_ah_sa != NULL ||
6128 		    ii->ipsec_in_esp_sa != NULL ||
6129 		    ii->ipsec_in_decaps);
6130 	}
6131 }
6132 
6133 /*
6134  * Handle protocols with which IP is less intimate.  There
6135  * can be more than one stream bound to a particular
6136  * protocol.  When this is the case, normally each one gets a copy
6137  * of any incoming packets.
6138  *
6139  * IPSEC NOTE :
6140  *
6141  * Don't allow a secure packet going up a non-secure connection.
6142  * We don't allow this because
6143  *
6144  * 1) Reply might go out in clear which will be dropped at
6145  *    the sending side.
6146  * 2) If the reply goes out in clear it will give the
6147  *    adversary enough information for getting the key in
6148  *    most of the cases.
6149  *
6150  * Moreover getting a secure packet when we expect clear
6151  * implies that SA's were added without checking for
6152  * policy on both ends. This should not happen once ISAKMP
6153  * is used to negotiate SAs as SAs will be added only after
6154  * verifying the policy.
6155  *
6156  * NOTE : If the packet was tunneled and not multicast we only send
6157  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6158  * back to delivering packets to AF_INET6 raw sockets.
6159  *
6160  * IPQoS Notes:
6161  * Once we have determined the client, invoke IPPF processing.
6162  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6163  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6164  * ip_policy will be false.
6165  *
6166  * Zones notes:
6167  * Currently only applications in the global zone can create raw sockets for
6168  * protocols other than ICMP. So unlike the broadcast / multicast case of
6169  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6170  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6171  */
6172 static void
6173 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6174     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6175     zoneid_t zoneid)
6176 {
6177 	queue_t	*rq;
6178 	mblk_t	*mp1, *first_mp1;
6179 	uint_t	protocol = ipha->ipha_protocol;
6180 	ipaddr_t dst;
6181 	boolean_t one_only;
6182 	mblk_t *first_mp = mp;
6183 	boolean_t secure;
6184 	uint32_t ill_index;
6185 	conn_t	*connp, *first_connp, *next_connp;
6186 	connf_t	*connfp;
6187 	boolean_t shared_addr;
6188 
6189 	if (mctl_present) {
6190 		mp = first_mp->b_cont;
6191 		secure = ipsec_in_is_secure(first_mp);
6192 		ASSERT(mp != NULL);
6193 	} else {
6194 		secure = B_FALSE;
6195 	}
6196 	dst = ipha->ipha_dst;
6197 	/*
6198 	 * If the packet was tunneled and not multicast we only send to it
6199 	 * the first match.
6200 	 */
6201 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6202 	    !CLASSD(dst));
6203 
6204 	shared_addr = (zoneid == ALL_ZONES);
6205 	if (shared_addr) {
6206 		/*
6207 		 * We don't allow multilevel ports for raw IP, so no need to
6208 		 * check for that here.
6209 		 */
6210 		zoneid = tsol_packet_to_zoneid(mp);
6211 	}
6212 
6213 	connfp = &ipcl_proto_fanout[protocol];
6214 	mutex_enter(&connfp->connf_lock);
6215 	connp = connfp->connf_head;
6216 	for (connp = connfp->connf_head; connp != NULL;
6217 		connp = connp->conn_next) {
6218 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6219 		    zoneid) &&
6220 		    (!is_system_labeled() ||
6221 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6222 		    connp)))
6223 			break;
6224 	}
6225 
6226 	if (connp == NULL || connp->conn_upq == NULL) {
6227 		/*
6228 		 * No one bound to these addresses.  Is
6229 		 * there a client that wants all
6230 		 * unclaimed datagrams?
6231 		 */
6232 		mutex_exit(&connfp->connf_lock);
6233 		/*
6234 		 * Check for IPPROTO_ENCAP...
6235 		 */
6236 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6237 			/*
6238 			 * XXX If an IPsec mblk is here on a multicast
6239 			 * tunnel (using ip_mroute stuff), what should
6240 			 * I do?
6241 			 *
6242 			 * For now, just free the IPsec mblk before
6243 			 * passing it up to the multicast routing
6244 			 * stuff.
6245 			 *
6246 			 * BTW,  If I match a configured IP-in-IP
6247 			 * tunnel, ip_mroute_decap will never be
6248 			 * called.
6249 			 */
6250 			if (mp != first_mp)
6251 				freeb(first_mp);
6252 			ip_mroute_decap(q, mp);
6253 		} else {
6254 			/*
6255 			 * Otherwise send an ICMP protocol unreachable.
6256 			 */
6257 			if (ip_fanout_send_icmp(q, first_mp, flags,
6258 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6259 			    mctl_present, zoneid)) {
6260 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
6261 			}
6262 		}
6263 		return;
6264 	}
6265 	CONN_INC_REF(connp);
6266 	first_connp = connp;
6267 
6268 	/*
6269 	 * Only send message to one tunnel driver by immediately
6270 	 * terminating the loop.
6271 	 */
6272 	connp = one_only ? NULL : connp->conn_next;
6273 
6274 	for (;;) {
6275 		while (connp != NULL) {
6276 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6277 			    flags, zoneid) &&
6278 			    (!is_system_labeled() ||
6279 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6280 			    shared_addr, connp)))
6281 				break;
6282 			connp = connp->conn_next;
6283 		}
6284 
6285 		/*
6286 		 * Copy the packet.
6287 		 */
6288 		if (connp == NULL || connp->conn_upq == NULL ||
6289 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6290 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6291 			/*
6292 			 * No more interested clients or memory
6293 			 * allocation failed
6294 			 */
6295 			connp = first_connp;
6296 			break;
6297 		}
6298 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6299 		CONN_INC_REF(connp);
6300 		mutex_exit(&connfp->connf_lock);
6301 		rq = connp->conn_rq;
6302 		if (!canputnext(rq)) {
6303 			if (flags & IP_FF_RAWIP) {
6304 				BUMP_MIB(&ip_mib, rawipInOverflows);
6305 			} else {
6306 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6307 			}
6308 
6309 			freemsg(first_mp1);
6310 		} else {
6311 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6312 				first_mp1 = ipsec_check_inbound_policy
6313 				    (first_mp1, connp, ipha, NULL,
6314 				    mctl_present);
6315 			}
6316 			if (first_mp1 != NULL) {
6317 				/*
6318 				 * ip_fanout_proto also gets called from
6319 				 * icmp_inbound_error_fanout, in which case
6320 				 * the msg type is M_CTL.  Don't add info
6321 				 * in this case for the time being. In future
6322 				 * when there is a need for knowing the
6323 				 * inbound iface index for ICMP error msgs,
6324 				 * then this can be changed.
6325 				 */
6326 				if ((connp->conn_recvif != 0) &&
6327 				    (mp->b_datap->db_type != M_CTL)) {
6328 					/*
6329 					 * the actual data will be
6330 					 * contained in b_cont upon
6331 					 * successful return of the
6332 					 * following call else
6333 					 * original mblk is returned
6334 					 */
6335 					ASSERT(recv_ill != NULL);
6336 					mp1 = ip_add_info(mp1, recv_ill,
6337 						IPF_RECVIF);
6338 				}
6339 				BUMP_MIB(&ip_mib, ipInDelivers);
6340 				if (mctl_present)
6341 					freeb(first_mp1);
6342 				putnext(rq, mp1);
6343 			}
6344 		}
6345 		mutex_enter(&connfp->connf_lock);
6346 		/* Follow the next pointer before releasing the conn. */
6347 		next_connp = connp->conn_next;
6348 		CONN_DEC_REF(connp);
6349 		connp = next_connp;
6350 	}
6351 
6352 	/* Last one.  Send it upstream. */
6353 	mutex_exit(&connfp->connf_lock);
6354 
6355 	/*
6356 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6357 	 * will be set to false.
6358 	 */
6359 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6360 		ill_index = ill->ill_phyint->phyint_ifindex;
6361 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6362 		if (mp == NULL) {
6363 			CONN_DEC_REF(connp);
6364 			if (mctl_present) {
6365 				freeb(first_mp);
6366 			}
6367 			return;
6368 		}
6369 	}
6370 
6371 	rq = connp->conn_rq;
6372 	if (!canputnext(rq)) {
6373 		if (flags & IP_FF_RAWIP) {
6374 			BUMP_MIB(&ip_mib, rawipInOverflows);
6375 		} else {
6376 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6377 		}
6378 
6379 		freemsg(first_mp);
6380 	} else {
6381 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6382 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6383 			    ipha, NULL, mctl_present);
6384 		}
6385 		if (first_mp != NULL) {
6386 			/*
6387 			 * ip_fanout_proto also gets called
6388 			 * from icmp_inbound_error_fanout, in
6389 			 * which case the msg type is M_CTL.
6390 			 * Don't add info in this case for time
6391 			 * being. In future when there is a
6392 			 * need for knowing the inbound iface
6393 			 * index for ICMP error msgs, then this
6394 			 * can be changed
6395 			 */
6396 			if ((connp->conn_recvif != 0) &&
6397 			    (mp->b_datap->db_type != M_CTL)) {
6398 				/*
6399 				 * the actual data will be contained in
6400 				 * b_cont upon successful return
6401 				 * of the following call else original
6402 				 * mblk is returned
6403 				 */
6404 				ASSERT(recv_ill != NULL);
6405 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6406 			}
6407 			BUMP_MIB(&ip_mib, ipInDelivers);
6408 			putnext(rq, mp);
6409 			if (mctl_present)
6410 				freeb(first_mp);
6411 		}
6412 	}
6413 	CONN_DEC_REF(connp);
6414 }
6415 
6416 /*
6417  * Fanout for TCP packets
6418  * The caller puts <fport, lport> in the ports parameter.
6419  *
6420  * IPQoS Notes
6421  * Before sending it to the client, invoke IPPF processing.
6422  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6423  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6424  * ip_policy is false.
6425  */
6426 static void
6427 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6428     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6429 {
6430 	mblk_t  *first_mp;
6431 	boolean_t secure;
6432 	uint32_t ill_index;
6433 	int	ip_hdr_len;
6434 	tcph_t	*tcph;
6435 	boolean_t syn_present = B_FALSE;
6436 	conn_t	*connp;
6437 
6438 	first_mp = mp;
6439 	if (mctl_present) {
6440 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6441 		mp = first_mp->b_cont;
6442 		secure = ipsec_in_is_secure(first_mp);
6443 		ASSERT(mp != NULL);
6444 	} else {
6445 		secure = B_FALSE;
6446 	}
6447 
6448 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6449 
6450 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6451 	    NULL) {
6452 		/*
6453 		 * No connected connection or listener. Send a
6454 		 * TH_RST via tcp_xmit_listeners_reset.
6455 		 */
6456 
6457 		/* Initiate IPPf processing, if needed. */
6458 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6459 			uint32_t ill_index;
6460 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6461 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6462 			if (first_mp == NULL)
6463 				return;
6464 		}
6465 		BUMP_MIB(&ip_mib, ipInDelivers);
6466 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6467 		    zoneid));
6468 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6469 		return;
6470 	}
6471 
6472 	/*
6473 	 * Allocate the SYN for the TCP connection here itself
6474 	 */
6475 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6476 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6477 		if (IPCL_IS_TCP(connp)) {
6478 			squeue_t *sqp;
6479 
6480 			/*
6481 			 * For fused tcp loopback, assign the eager's
6482 			 * squeue to be that of the active connect's.
6483 			 * Note that we don't check for IP_FF_LOOPBACK
6484 			 * here since this routine gets called only
6485 			 * for loopback (unlike the IPv6 counterpart).
6486 			 */
6487 			ASSERT(Q_TO_CONN(q) != NULL);
6488 			if (do_tcp_fusion &&
6489 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6490 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6491 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6492 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6493 				sqp = Q_TO_CONN(q)->conn_sqp;
6494 			} else {
6495 				sqp = IP_SQUEUE_GET(lbolt);
6496 			}
6497 
6498 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6499 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6500 			syn_present = B_TRUE;
6501 		}
6502 	}
6503 
6504 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6505 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6506 		if ((flags & TH_RST) || (flags & TH_URG)) {
6507 			CONN_DEC_REF(connp);
6508 			freemsg(first_mp);
6509 			return;
6510 		}
6511 		if (flags & TH_ACK) {
6512 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6513 			CONN_DEC_REF(connp);
6514 			return;
6515 		}
6516 
6517 		CONN_DEC_REF(connp);
6518 		freemsg(first_mp);
6519 		return;
6520 	}
6521 
6522 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6523 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6524 		    NULL, mctl_present);
6525 		if (first_mp == NULL) {
6526 			CONN_DEC_REF(connp);
6527 			return;
6528 		}
6529 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6530 			ASSERT(syn_present);
6531 			if (mctl_present) {
6532 				ASSERT(first_mp != mp);
6533 				first_mp->b_datap->db_struioflag |=
6534 				    STRUIO_POLICY;
6535 			} else {
6536 				ASSERT(first_mp == mp);
6537 				mp->b_datap->db_struioflag &=
6538 				    ~STRUIO_EAGER;
6539 				mp->b_datap->db_struioflag |=
6540 				    STRUIO_POLICY;
6541 			}
6542 		} else {
6543 			/*
6544 			 * Discard first_mp early since we're dealing with a
6545 			 * fully-connected conn_t and tcp doesn't do policy in
6546 			 * this case.
6547 			 */
6548 			if (mctl_present) {
6549 				freeb(first_mp);
6550 				mctl_present = B_FALSE;
6551 			}
6552 			first_mp = mp;
6553 		}
6554 	}
6555 
6556 	/*
6557 	 * Initiate policy processing here if needed. If we get here from
6558 	 * icmp_inbound_error_fanout, ip_policy is false.
6559 	 */
6560 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6561 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6562 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6563 		if (mp == NULL) {
6564 			CONN_DEC_REF(connp);
6565 			if (mctl_present)
6566 				freeb(first_mp);
6567 			return;
6568 		} else if (mctl_present) {
6569 			ASSERT(first_mp != mp);
6570 			first_mp->b_cont = mp;
6571 		} else {
6572 			first_mp = mp;
6573 		}
6574 	}
6575 
6576 
6577 
6578 	/* Handle IPv6 socket options. */
6579 	if (!syn_present &&
6580 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6581 		/* Add header */
6582 		ASSERT(recv_ill != NULL);
6583 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6584 		if (mp == NULL) {
6585 			CONN_DEC_REF(connp);
6586 			if (mctl_present)
6587 				freeb(first_mp);
6588 			return;
6589 		} else if (mctl_present) {
6590 			/*
6591 			 * ip_add_info might return a new mp.
6592 			 */
6593 			ASSERT(first_mp != mp);
6594 			first_mp->b_cont = mp;
6595 		} else {
6596 			first_mp = mp;
6597 		}
6598 	}
6599 
6600 	BUMP_MIB(&ip_mib, ipInDelivers);
6601 	if (IPCL_IS_TCP(connp)) {
6602 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6603 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6604 	} else {
6605 		putnext(connp->conn_rq, first_mp);
6606 		CONN_DEC_REF(connp);
6607 	}
6608 }
6609 
6610 /*
6611  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6612  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6613  * Caller is responsible for dropping references to the conn, and freeing
6614  * first_mp.
6615  *
6616  * IPQoS Notes
6617  * Before sending it to the client, invoke IPPF processing. Policy processing
6618  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6619  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6620  * ip_wput_local, ip_policy is false.
6621  */
6622 static void
6623 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6624     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6625     boolean_t ip_policy)
6626 {
6627 	boolean_t	mctl_present = (first_mp != NULL);
6628 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6629 	uint32_t	ill_index;
6630 
6631 	if (mctl_present)
6632 		first_mp->b_cont = mp;
6633 	else
6634 		first_mp = mp;
6635 
6636 	if (CONN_UDP_FLOWCTLD(connp)) {
6637 		BUMP_MIB(&ip_mib, udpInOverflows);
6638 		freemsg(first_mp);
6639 		return;
6640 	}
6641 
6642 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6643 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6644 		    NULL, mctl_present);
6645 		if (first_mp == NULL)
6646 			return;	/* Freed by ipsec_check_inbound_policy(). */
6647 	}
6648 	if (mctl_present)
6649 		freeb(first_mp);
6650 
6651 	if (connp->conn_recvif)
6652 		in_flags = IPF_RECVIF;
6653 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6654 		in_flags |= IPF_RECVSLLA;
6655 
6656 	/* Handle IPv6 options. */
6657 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6658 		in_flags |= IPF_RECVIF;
6659 
6660 	/*
6661 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6662 	 * freed if the packet is dropped. The caller will do so.
6663 	 */
6664 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6665 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6666 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6667 		if (mp == NULL) {
6668 			return;
6669 		}
6670 	}
6671 	if ((in_flags != 0) &&
6672 	    (mp->b_datap->db_type != M_CTL)) {
6673 		/*
6674 		 * The actual data will be contained in b_cont
6675 		 * upon successful return of the following call
6676 		 * else original mblk is returned
6677 		 */
6678 		ASSERT(recv_ill != NULL);
6679 		mp = ip_add_info(mp, recv_ill, in_flags);
6680 	}
6681 	BUMP_MIB(&ip_mib, ipInDelivers);
6682 
6683 	/* Send it upstream */
6684 	CONN_UDP_RECV(connp, mp);
6685 }
6686 
6687 /*
6688  * Fanout for UDP packets.
6689  * The caller puts <fport, lport> in the ports parameter.
6690  *
6691  * If SO_REUSEADDR is set all multicast and broadcast packets
6692  * will be delivered to all streams bound to the same port.
6693  *
6694  * Zones notes:
6695  * Multicast and broadcast packets will be distributed to streams in all zones.
6696  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6697  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6698  * packets. To maintain this behavior with multiple zones, the conns are grouped
6699  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6700  * each zone. If unset, all the following conns in the same zone are skipped.
6701  */
6702 static void
6703 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6704     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6705     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6706 {
6707 	uint32_t	dstport, srcport;
6708 	ipaddr_t	dst;
6709 	mblk_t		*first_mp;
6710 	boolean_t	secure;
6711 	in6_addr_t	v6src;
6712 	conn_t		*connp;
6713 	connf_t		*connfp;
6714 	conn_t		*first_connp;
6715 	conn_t		*next_connp;
6716 	mblk_t		*mp1, *first_mp1;
6717 	ipaddr_t	src;
6718 	zoneid_t	last_zoneid;
6719 	boolean_t	reuseaddr;
6720 	boolean_t	shared_addr;
6721 
6722 	first_mp = mp;
6723 	if (mctl_present) {
6724 		mp = first_mp->b_cont;
6725 		first_mp->b_cont = NULL;
6726 		secure = ipsec_in_is_secure(first_mp);
6727 		ASSERT(mp != NULL);
6728 	} else {
6729 		first_mp = NULL;
6730 		secure = B_FALSE;
6731 	}
6732 
6733 	/* Extract ports in net byte order */
6734 	dstport = htons(ntohl(ports) & 0xFFFF);
6735 	srcport = htons(ntohl(ports) >> 16);
6736 	dst = ipha->ipha_dst;
6737 	src = ipha->ipha_src;
6738 
6739 	shared_addr = (zoneid == ALL_ZONES);
6740 	if (shared_addr) {
6741 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6742 		if (zoneid == ALL_ZONES)
6743 			zoneid = tsol_packet_to_zoneid(mp);
6744 	}
6745 
6746 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6747 	mutex_enter(&connfp->connf_lock);
6748 	connp = connfp->connf_head;
6749 	if (!broadcast && !CLASSD(dst)) {
6750 		/*
6751 		 * Not broadcast or multicast. Send to the one (first)
6752 		 * client we find. No need to check conn_wantpacket()
6753 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6754 		 * IPv4 unicast packets.
6755 		 */
6756 		while ((connp != NULL) &&
6757 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
6758 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
6759 			connp = connp->conn_next;
6760 		}
6761 
6762 		if (connp == NULL || connp->conn_upq == NULL)
6763 			goto notfound;
6764 
6765 		if (is_system_labeled() &&
6766 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6767 		    connp))
6768 			goto notfound;
6769 
6770 		CONN_INC_REF(connp);
6771 		mutex_exit(&connfp->connf_lock);
6772 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6773 		    recv_ill, ip_policy);
6774 		IP_STAT(ip_udp_fannorm);
6775 		CONN_DEC_REF(connp);
6776 		return;
6777 	}
6778 
6779 	/*
6780 	 * Broadcast and multicast case
6781 	 *
6782 	 * Need to check conn_wantpacket().
6783 	 * If SO_REUSEADDR has been set on the first we send the
6784 	 * packet to all clients that have joined the group and
6785 	 * match the port.
6786 	 */
6787 
6788 	while (connp != NULL) {
6789 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6790 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6791 		    (!is_system_labeled() ||
6792 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6793 		    connp)))
6794 			break;
6795 		connp = connp->conn_next;
6796 	}
6797 
6798 	if (connp == NULL || connp->conn_upq == NULL)
6799 		goto notfound;
6800 
6801 	first_connp = connp;
6802 	/*
6803 	 * When SO_REUSEADDR is not set, send the packet only to the first
6804 	 * matching connection in its zone by keeping track of the zoneid.
6805 	 */
6806 	reuseaddr = first_connp->conn_reuseaddr;
6807 	last_zoneid = first_connp->conn_zoneid;
6808 
6809 	CONN_INC_REF(connp);
6810 	connp = connp->conn_next;
6811 	for (;;) {
6812 		while (connp != NULL) {
6813 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6814 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6815 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6816 			    (!is_system_labeled() ||
6817 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6818 			    shared_addr, connp)))
6819 				break;
6820 			connp = connp->conn_next;
6821 		}
6822 		/*
6823 		 * Just copy the data part alone. The mctl part is
6824 		 * needed just for verifying policy and it is never
6825 		 * sent up.
6826 		 */
6827 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6828 		    ((mp1 = copymsg(mp)) == NULL))) {
6829 			/*
6830 			 * No more interested clients or memory
6831 			 * allocation failed
6832 			 */
6833 			connp = first_connp;
6834 			break;
6835 		}
6836 		if (connp->conn_zoneid != last_zoneid) {
6837 			/*
6838 			 * Update the zoneid so that the packet isn't sent to
6839 			 * any more conns in the same zone unless SO_REUSEADDR
6840 			 * is set.
6841 			 */
6842 			reuseaddr = connp->conn_reuseaddr;
6843 			last_zoneid = connp->conn_zoneid;
6844 		}
6845 		if (first_mp != NULL) {
6846 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6847 			    ipsec_info_type == IPSEC_IN);
6848 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6849 			if (first_mp1 == NULL) {
6850 				freemsg(mp1);
6851 				connp = first_connp;
6852 				break;
6853 			}
6854 		} else {
6855 			first_mp1 = NULL;
6856 		}
6857 		CONN_INC_REF(connp);
6858 		mutex_exit(&connfp->connf_lock);
6859 		/*
6860 		 * IPQoS notes: We don't send the packet for policy
6861 		 * processing here, will do it for the last one (below).
6862 		 * i.e. we do it per-packet now, but if we do policy
6863 		 * processing per-conn, then we would need to do it
6864 		 * here too.
6865 		 */
6866 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6867 		    ipha, flags, recv_ill, B_FALSE);
6868 		mutex_enter(&connfp->connf_lock);
6869 		/* Follow the next pointer before releasing the conn. */
6870 		next_connp = connp->conn_next;
6871 		IP_STAT(ip_udp_fanmb);
6872 		CONN_DEC_REF(connp);
6873 		connp = next_connp;
6874 	}
6875 
6876 	/* Last one.  Send it upstream. */
6877 	mutex_exit(&connfp->connf_lock);
6878 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6879 	    ip_policy);
6880 	IP_STAT(ip_udp_fanmb);
6881 	CONN_DEC_REF(connp);
6882 	return;
6883 
6884 notfound:
6885 
6886 	mutex_exit(&connfp->connf_lock);
6887 	IP_STAT(ip_udp_fanothers);
6888 	/*
6889 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6890 	 * have already been matched above, since they live in the IPv4
6891 	 * fanout tables. This implies we only need to
6892 	 * check for IPv6 in6addr_any endpoints here.
6893 	 * Thus we compare using ipv6_all_zeros instead of the destination
6894 	 * address, except for the multicast group membership lookup which
6895 	 * uses the IPv4 destination.
6896 	 */
6897 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6898 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6899 	mutex_enter(&connfp->connf_lock);
6900 	connp = connfp->connf_head;
6901 	if (!broadcast && !CLASSD(dst)) {
6902 		while (connp != NULL) {
6903 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6904 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6905 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6906 			    !connp->conn_ipv6_v6only)
6907 				break;
6908 			connp = connp->conn_next;
6909 		}
6910 
6911 		if (connp != NULL && is_system_labeled() &&
6912 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6913 		    connp))
6914 			connp = NULL;
6915 
6916 		if (connp == NULL || connp->conn_upq == NULL) {
6917 			/*
6918 			 * No one bound to this port.  Is
6919 			 * there a client that wants all
6920 			 * unclaimed datagrams?
6921 			 */
6922 			mutex_exit(&connfp->connf_lock);
6923 
6924 			if (mctl_present)
6925 				first_mp->b_cont = mp;
6926 			else
6927 				first_mp = mp;
6928 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6929 				ip_fanout_proto(q, first_mp, ill, ipha,
6930 				    flags | IP_FF_RAWIP, mctl_present,
6931 				    ip_policy, recv_ill, zoneid);
6932 			} else {
6933 				if (ip_fanout_send_icmp(q, first_mp, flags,
6934 				    ICMP_DEST_UNREACHABLE,
6935 				    ICMP_PORT_UNREACHABLE,
6936 				    mctl_present, zoneid)) {
6937 					BUMP_MIB(&ip_mib, udpNoPorts);
6938 				}
6939 			}
6940 			return;
6941 		}
6942 
6943 		CONN_INC_REF(connp);
6944 		mutex_exit(&connfp->connf_lock);
6945 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6946 		    recv_ill, ip_policy);
6947 		CONN_DEC_REF(connp);
6948 		return;
6949 	}
6950 	/*
6951 	 * IPv4 multicast packet being delivered to an AF_INET6
6952 	 * in6addr_any endpoint.
6953 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6954 	 * and not conn_wantpacket_v6() since any multicast membership is
6955 	 * for an IPv4-mapped multicast address.
6956 	 * The packet is sent to all clients in all zones that have joined the
6957 	 * group and match the port.
6958 	 */
6959 	while (connp != NULL) {
6960 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6961 		    srcport, v6src) &&
6962 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6963 		    (!is_system_labeled() ||
6964 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6965 		    connp)))
6966 			break;
6967 		connp = connp->conn_next;
6968 	}
6969 
6970 	if (connp == NULL || connp->conn_upq == NULL) {
6971 		/*
6972 		 * No one bound to this port.  Is
6973 		 * there a client that wants all
6974 		 * unclaimed datagrams?
6975 		 */
6976 		mutex_exit(&connfp->connf_lock);
6977 
6978 		if (mctl_present)
6979 			first_mp->b_cont = mp;
6980 		else
6981 			first_mp = mp;
6982 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6983 			ip_fanout_proto(q, first_mp, ill, ipha,
6984 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6985 			    recv_ill, zoneid);
6986 		} else {
6987 			/*
6988 			 * We used to attempt to send an icmp error here, but
6989 			 * since this is known to be a multicast packet
6990 			 * and we don't send icmp errors in response to
6991 			 * multicast, just drop the packet and give up sooner.
6992 			 */
6993 			BUMP_MIB(&ip_mib, udpNoPorts);
6994 			freemsg(first_mp);
6995 		}
6996 		return;
6997 	}
6998 
6999 	first_connp = connp;
7000 
7001 	CONN_INC_REF(connp);
7002 	connp = connp->conn_next;
7003 	for (;;) {
7004 		while (connp != NULL) {
7005 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7006 			    ipv6_all_zeros, srcport, v6src) &&
7007 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7008 			    (!is_system_labeled() ||
7009 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7010 			    shared_addr, connp)))
7011 				break;
7012 			connp = connp->conn_next;
7013 		}
7014 		/*
7015 		 * Just copy the data part alone. The mctl part is
7016 		 * needed just for verifying policy and it is never
7017 		 * sent up.
7018 		 */
7019 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7020 		    ((mp1 = copymsg(mp)) == NULL))) {
7021 			/*
7022 			 * No more intested clients or memory
7023 			 * allocation failed
7024 			 */
7025 			connp = first_connp;
7026 			break;
7027 		}
7028 		if (first_mp != NULL) {
7029 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7030 			    ipsec_info_type == IPSEC_IN);
7031 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7032 			if (first_mp1 == NULL) {
7033 				freemsg(mp1);
7034 				connp = first_connp;
7035 				break;
7036 			}
7037 		} else {
7038 			first_mp1 = NULL;
7039 		}
7040 		CONN_INC_REF(connp);
7041 		mutex_exit(&connfp->connf_lock);
7042 		/*
7043 		 * IPQoS notes: We don't send the packet for policy
7044 		 * processing here, will do it for the last one (below).
7045 		 * i.e. we do it per-packet now, but if we do policy
7046 		 * processing per-conn, then we would need to do it
7047 		 * here too.
7048 		 */
7049 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
7050 		    ipha, flags, recv_ill, B_FALSE);
7051 		mutex_enter(&connfp->connf_lock);
7052 		/* Follow the next pointer before releasing the conn. */
7053 		next_connp = connp->conn_next;
7054 		CONN_DEC_REF(connp);
7055 		connp = next_connp;
7056 	}
7057 
7058 	/* Last one.  Send it upstream. */
7059 	mutex_exit(&connfp->connf_lock);
7060 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
7061 	    ip_policy);
7062 	CONN_DEC_REF(connp);
7063 }
7064 
7065 /*
7066  * Complete the ip_wput header so that it
7067  * is possible to generate ICMP
7068  * errors.
7069  */
7070 int
7071 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
7072 {
7073 	ire_t *ire;
7074 
7075 	if (ipha->ipha_src == INADDR_ANY) {
7076 		ire = ire_lookup_local(zoneid);
7077 		if (ire == NULL) {
7078 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7079 			return (1);
7080 		}
7081 		ipha->ipha_src = ire->ire_addr;
7082 		ire_refrele(ire);
7083 	}
7084 	ipha->ipha_ttl = ip_def_ttl;
7085 	ipha->ipha_hdr_checksum = 0;
7086 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7087 	return (0);
7088 }
7089 
7090 /*
7091  * Nobody should be sending
7092  * packets up this stream
7093  */
7094 static void
7095 ip_lrput(queue_t *q, mblk_t *mp)
7096 {
7097 	mblk_t *mp1;
7098 
7099 	switch (mp->b_datap->db_type) {
7100 	case M_FLUSH:
7101 		/* Turn around */
7102 		if (*mp->b_rptr & FLUSHW) {
7103 			*mp->b_rptr &= ~FLUSHR;
7104 			qreply(q, mp);
7105 			return;
7106 		}
7107 		break;
7108 	}
7109 	/* Could receive messages that passed through ar_rput */
7110 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7111 		mp1->b_prev = mp1->b_next = NULL;
7112 	freemsg(mp);
7113 }
7114 
7115 /* Nobody should be sending packets down this stream */
7116 /* ARGSUSED */
7117 void
7118 ip_lwput(queue_t *q, mblk_t *mp)
7119 {
7120 	freemsg(mp);
7121 }
7122 
7123 /*
7124  * Move the first hop in any source route to ipha_dst and remove that part of
7125  * the source route.  Called by other protocols.  Errors in option formatting
7126  * are ignored - will be handled by ip_wput_options Return the final
7127  * destination (either ipha_dst or the last entry in a source route.)
7128  */
7129 ipaddr_t
7130 ip_massage_options(ipha_t *ipha)
7131 {
7132 	ipoptp_t	opts;
7133 	uchar_t		*opt;
7134 	uint8_t		optval;
7135 	uint8_t		optlen;
7136 	ipaddr_t	dst;
7137 	int		i;
7138 	ire_t		*ire;
7139 
7140 	ip2dbg(("ip_massage_options\n"));
7141 	dst = ipha->ipha_dst;
7142 	for (optval = ipoptp_first(&opts, ipha);
7143 	    optval != IPOPT_EOL;
7144 	    optval = ipoptp_next(&opts)) {
7145 		opt = opts.ipoptp_cur;
7146 		switch (optval) {
7147 			uint8_t off;
7148 		case IPOPT_SSRR:
7149 		case IPOPT_LSRR:
7150 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7151 				ip1dbg(("ip_massage_options: bad src route\n"));
7152 				break;
7153 			}
7154 			optlen = opts.ipoptp_len;
7155 			off = opt[IPOPT_OFFSET];
7156 			off--;
7157 		redo_srr:
7158 			if (optlen < IP_ADDR_LEN ||
7159 			    off > optlen - IP_ADDR_LEN) {
7160 				/* End of source route */
7161 				ip1dbg(("ip_massage_options: end of SR\n"));
7162 				break;
7163 			}
7164 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7165 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7166 			    ntohl(dst)));
7167 			/*
7168 			 * Check if our address is present more than
7169 			 * once as consecutive hops in source route.
7170 			 * XXX verify per-interface ip_forwarding
7171 			 * for source route?
7172 			 */
7173 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7174 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
7175 			if (ire != NULL) {
7176 				ire_refrele(ire);
7177 				off += IP_ADDR_LEN;
7178 				goto redo_srr;
7179 			}
7180 			if (dst == htonl(INADDR_LOOPBACK)) {
7181 				ip1dbg(("ip_massage_options: loopback addr in "
7182 				    "source route!\n"));
7183 				break;
7184 			}
7185 			/*
7186 			 * Update ipha_dst to be the first hop and remove the
7187 			 * first hop from the source route (by overwriting
7188 			 * part of the option with NOP options).
7189 			 */
7190 			ipha->ipha_dst = dst;
7191 			/* Put the last entry in dst */
7192 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7193 			    3;
7194 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7195 
7196 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7197 			    ntohl(dst)));
7198 			/* Move down and overwrite */
7199 			opt[IP_ADDR_LEN] = opt[0];
7200 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7201 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7202 			for (i = 0; i < IP_ADDR_LEN; i++)
7203 				opt[i] = IPOPT_NOP;
7204 			break;
7205 		}
7206 	}
7207 	return (dst);
7208 }
7209 
7210 /*
7211  * This function's job is to forward data to the reverse tunnel (FA->HA)
7212  * after doing a few checks. It is assumed that the incoming interface
7213  * of the packet is always different than the outgoing interface and the
7214  * ire_type of the found ire has to be a non-resolver type.
7215  *
7216  * IPQoS notes
7217  * IP policy is invoked twice for a forwarded packet, once on the read side
7218  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7219  * enabled.
7220  */
7221 static void
7222 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7223 {
7224 	ipha_t		*ipha;
7225 	queue_t		*q;
7226 	uint32_t 	pkt_len;
7227 #define	rptr    ((uchar_t *)ipha)
7228 	uint32_t 	sum;
7229 	uint32_t 	max_frag;
7230 	mblk_t		*first_mp;
7231 	uint32_t	ill_index;
7232 	ipxmit_state_t	pktxmit_state;
7233 	ill_t		*out_ill;
7234 
7235 	ASSERT(ire != NULL);
7236 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7237 	ASSERT(ire->ire_stq != NULL);
7238 
7239 	/* Initiate read side IPPF processing */
7240 	if (IPP_ENABLED(IPP_FWD_IN)) {
7241 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7242 		ip_process(IPP_FWD_IN, &mp, ill_index);
7243 		if (mp == NULL) {
7244 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7245 			    "dropped during IPPF processing\n"));
7246 			return;
7247 		}
7248 	}
7249 
7250 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7251 		ILLF_ROUTER) == 0) ||
7252 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7253 		BUMP_MIB(&ip_mib, ipForwProhibits);
7254 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7255 		    "forwarding is not turned on\n"));
7256 		goto drop_pkt;
7257 	}
7258 
7259 	/*
7260 	 * Don't forward if the interface is down
7261 	 */
7262 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7263 		BUMP_MIB(&ip_mib, ipInDiscards);
7264 		goto drop_pkt;
7265 	}
7266 
7267 	ipha = (ipha_t *)mp->b_rptr;
7268 	pkt_len = ntohs(ipha->ipha_length);
7269 	/* Adjust the checksum to reflect the ttl decrement. */
7270 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7271 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7272 	if (ipha->ipha_ttl-- <= 1) {
7273 		if (ip_csum_hdr(ipha)) {
7274 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7275 			goto drop_pkt;
7276 		}
7277 		q = ire->ire_stq;
7278 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7279 		    BPRI_HI)) == NULL) {
7280 			goto drop_pkt;
7281 		}
7282 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7283 		/* Sent by forwarding path, and router is global zone */
7284 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7285 		    GLOBAL_ZONEID);
7286 		return;
7287 	}
7288 
7289 	/* Get the ill_index of the ILL */
7290 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7291 
7292 	/*
7293 	 * This location is chosen for the placement of the forwarding hook
7294 	 * because at this point we know that we have a path out for the
7295 	 * packet but haven't yet applied any logic (such as fragmenting)
7296 	 * that happen as part of transmitting the packet out.
7297 	 */
7298 	out_ill = ire->ire_ipif->ipif_ill;
7299 
7300 	DTRACE_PROBE4(ip4__forwarding__start,
7301 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7302 
7303 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
7304 	    MSG_FWCOOKED_FORWARD, in_ill, out_ill, ipha, mp, mp);
7305 
7306 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7307 
7308 	if (mp == NULL)
7309 		return;
7310 	pkt_len = ntohs(ipha->ipha_length);
7311 
7312 	/*
7313 	 * ip_mrtun_forward is only used by foreign agent to reverse
7314 	 * tunnel the incoming packet. So it does not do any option
7315 	 * processing for source routing.
7316 	 */
7317 	max_frag = ire->ire_max_frag;
7318 	if (pkt_len > max_frag) {
7319 		/*
7320 		 * It needs fragging on its way out.  We haven't
7321 		 * verified the header checksum yet.  Since we
7322 		 * are going to put a surely good checksum in the
7323 		 * outgoing header, we have to make sure that it
7324 		 * was good coming in.
7325 		 */
7326 		if (ip_csum_hdr(ipha)) {
7327 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7328 			goto drop_pkt;
7329 		}
7330 
7331 		/* Initiate write side IPPF processing */
7332 		if (IPP_ENABLED(IPP_FWD_OUT)) {
7333 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7334 			if (mp == NULL) {
7335 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7336 				    "dropped/deferred during ip policy "\
7337 				    "processing\n"));
7338 				return;
7339 			}
7340 		}
7341 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7342 		    BPRI_HI)) == NULL) {
7343 			goto drop_pkt;
7344 		}
7345 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7346 		mp = first_mp;
7347 
7348 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
7349 		return;
7350 	}
7351 
7352 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7353 
7354 	ASSERT(ire->ire_ipif != NULL);
7355 
7356 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7357 	    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha, mblk_t *, mp);
7358 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
7359 	    MSG_FWCOOKED_OUT, NULL, out_ill, ipha, mp, mp);
7360 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7361 	if (mp == NULL)
7362 		return;
7363 
7364 	/* Now send the packet to the tunnel interface */
7365 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7366 	q = ire->ire_stq;
7367 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7368 	if ((pktxmit_state == SEND_FAILED) ||
7369 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7370 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7371 		    q->q_ptr));
7372 	}
7373 
7374 	return;
7375 
7376 drop_pkt:;
7377 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7378 	freemsg(mp);
7379 #undef	rptr
7380 }
7381 
7382 /*
7383  * Fills the ipsec_out_t data structure with appropriate fields and
7384  * prepends it to mp which contains the IP hdr + data that was meant
7385  * to be forwarded. Please note that ipsec_out_info data structure
7386  * is used here to communicate the outgoing ill path at ip_wput()
7387  * for the ICMP error packet. This has nothing to do with ipsec IP
7388  * security. ipsec_out_t is really used to pass the info to the module
7389  * IP where this information cannot be extracted from conn.
7390  * This functions is called by ip_mrtun_forward().
7391  */
7392 void
7393 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7394 {
7395 	ipsec_out_t	*io;
7396 
7397 	ASSERT(xmit_ill != NULL);
7398 	first_mp->b_datap->db_type = M_CTL;
7399 	first_mp->b_wptr += sizeof (ipsec_info_t);
7400 	/*
7401 	 * This is to pass info to ip_wput in absence of conn.
7402 	 * ipsec_out_secure will be B_FALSE because of this.
7403 	 * Thus ipsec_out_secure being B_FALSE indicates that
7404 	 * this is not IPSEC security related information.
7405 	 */
7406 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7407 	io = (ipsec_out_t *)first_mp->b_rptr;
7408 	io->ipsec_out_type = IPSEC_OUT;
7409 	io->ipsec_out_len = sizeof (ipsec_out_t);
7410 	first_mp->b_cont = mp;
7411 	io->ipsec_out_ill_index =
7412 	    xmit_ill->ill_phyint->phyint_ifindex;
7413 	io->ipsec_out_xmit_if = B_TRUE;
7414 }
7415 
7416 /*
7417  * Return the network mask
7418  * associated with the specified address.
7419  */
7420 ipaddr_t
7421 ip_net_mask(ipaddr_t addr)
7422 {
7423 	uchar_t	*up = (uchar_t *)&addr;
7424 	ipaddr_t mask = 0;
7425 	uchar_t	*maskp = (uchar_t *)&mask;
7426 
7427 #if defined(__i386) || defined(__amd64)
7428 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7429 #endif
7430 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7431 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7432 #endif
7433 	if (CLASSD(addr)) {
7434 		maskp[0] = 0xF0;
7435 		return (mask);
7436 	}
7437 	if (addr == 0)
7438 		return (0);
7439 	maskp[0] = 0xFF;
7440 	if ((up[0] & 0x80) == 0)
7441 		return (mask);
7442 
7443 	maskp[1] = 0xFF;
7444 	if ((up[0] & 0xC0) == 0x80)
7445 		return (mask);
7446 
7447 	maskp[2] = 0xFF;
7448 	if ((up[0] & 0xE0) == 0xC0)
7449 		return (mask);
7450 
7451 	/* Must be experimental or multicast, indicate as much */
7452 	return ((ipaddr_t)0);
7453 }
7454 
7455 /*
7456  * Select an ill for the packet by considering load spreading across
7457  * a different ill in the group if dst_ill is part of some group.
7458  */
7459 ill_t *
7460 ip_newroute_get_dst_ill(ill_t *dst_ill)
7461 {
7462 	ill_t *ill;
7463 
7464 	/*
7465 	 * We schedule irrespective of whether the source address is
7466 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7467 	 */
7468 	ill = illgrp_scheduler(dst_ill);
7469 	if (ill == NULL)
7470 		return (NULL);
7471 
7472 	/*
7473 	 * For groups with names ip_sioctl_groupname ensures that all
7474 	 * ills are of same type. For groups without names, ifgrp_insert
7475 	 * ensures this.
7476 	 */
7477 	ASSERT(dst_ill->ill_type == ill->ill_type);
7478 
7479 	return (ill);
7480 }
7481 
7482 /*
7483  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7484  */
7485 ill_t *
7486 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7487 {
7488 	ill_t *ret_ill;
7489 
7490 	ASSERT(ifindex != 0);
7491 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7492 	if (ret_ill == NULL ||
7493 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7494 		if (isv6) {
7495 			if (ill != NULL) {
7496 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7497 			} else {
7498 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7499 			}
7500 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7501 			    "bad ifindex %d.\n", ifindex));
7502 		} else {
7503 			BUMP_MIB(&ip_mib, ipOutDiscards);
7504 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7505 			    "bad ifindex %d.\n", ifindex));
7506 		}
7507 		if (ret_ill != NULL)
7508 			ill_refrele(ret_ill);
7509 		freemsg(first_mp);
7510 		return (NULL);
7511 	}
7512 
7513 	return (ret_ill);
7514 }
7515 
7516 /*
7517  * IPv4 -
7518  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7519  * out a packet to a destination address for which we do not have specific
7520  * (or sufficient) routing information.
7521  *
7522  * NOTE : These are the scopes of some of the variables that point at IRE,
7523  *	  which needs to be followed while making any future modifications
7524  *	  to avoid memory leaks.
7525  *
7526  *	- ire and sire are the entries looked up initially by
7527  *	  ire_ftable_lookup.
7528  *	- ipif_ire is used to hold the interface ire associated with
7529  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7530  *	  it before branching out to error paths.
7531  *	- save_ire is initialized before ire_create, so that ire returned
7532  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7533  *	  before breaking out of the switch.
7534  *
7535  *	Thus on failures, we have to REFRELE only ire and sire, if they
7536  *	are not NULL.
7537  */
7538 void
7539 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7540     zoneid_t zoneid)
7541 {
7542 	areq_t	*areq;
7543 	ipaddr_t gw = 0;
7544 	ire_t	*ire = NULL;
7545 	mblk_t	*res_mp;
7546 	ipaddr_t *addrp;
7547 	ipaddr_t nexthop_addr;
7548 	ipif_t  *src_ipif = NULL;
7549 	ill_t	*dst_ill = NULL;
7550 	ipha_t  *ipha;
7551 	ire_t	*sire = NULL;
7552 	mblk_t	*first_mp;
7553 	ire_t	*save_ire;
7554 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7555 	ushort_t ire_marks = 0;
7556 	boolean_t mctl_present;
7557 	ipsec_out_t *io;
7558 	mblk_t	*saved_mp;
7559 	ire_t	*first_sire = NULL;
7560 	mblk_t	*copy_mp = NULL;
7561 	mblk_t	*xmit_mp = NULL;
7562 	ipaddr_t save_dst;
7563 	uint32_t multirt_flags =
7564 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7565 	boolean_t multirt_is_resolvable;
7566 	boolean_t multirt_resolve_next;
7567 	boolean_t do_attach_ill = B_FALSE;
7568 	boolean_t ip_nexthop = B_FALSE;
7569 	tsol_ire_gw_secattr_t *attrp = NULL;
7570 	tsol_gcgrp_t *gcgrp = NULL;
7571 	tsol_gcgrp_addr_t ga;
7572 
7573 	if (ip_debug > 2) {
7574 		/* ip1dbg */
7575 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7576 	}
7577 
7578 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7579 	if (mctl_present) {
7580 		io = (ipsec_out_t *)first_mp->b_rptr;
7581 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7582 		ASSERT(zoneid == io->ipsec_out_zoneid);
7583 		ASSERT(zoneid != ALL_ZONES);
7584 	}
7585 
7586 	ipha = (ipha_t *)mp->b_rptr;
7587 
7588 	/* All multicast lookups come through ip_newroute_ipif() */
7589 	if (CLASSD(dst)) {
7590 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7591 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7592 		freemsg(first_mp);
7593 		return;
7594 	}
7595 
7596 	if (mctl_present && io->ipsec_out_attach_if) {
7597 		/* ip_grab_attach_ill returns a held ill */
7598 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7599 		    io->ipsec_out_ill_index, B_FALSE);
7600 
7601 		/* Failure case frees things for us. */
7602 		if (attach_ill == NULL)
7603 			return;
7604 
7605 		/*
7606 		 * Check if we need an ire that will not be
7607 		 * looked up by anybody else i.e. HIDDEN.
7608 		 */
7609 		if (ill_is_probeonly(attach_ill))
7610 			ire_marks = IRE_MARK_HIDDEN;
7611 	}
7612 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7613 		ip_nexthop = B_TRUE;
7614 		nexthop_addr = io->ipsec_out_nexthop_addr;
7615 	}
7616 	/*
7617 	 * If this IRE is created for forwarding or it is not for
7618 	 * traffic for congestion controlled protocols, mark it as temporary.
7619 	 */
7620 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7621 		ire_marks |= IRE_MARK_TEMPORARY;
7622 
7623 	/*
7624 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7625 	 * chain until it gets the most specific information available.
7626 	 * For example, we know that there is no IRE_CACHE for this dest,
7627 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7628 	 * ire_ftable_lookup will look up the gateway, etc.
7629 	 * Check if in_ill != NULL. If it is true, the packet must be
7630 	 * from an incoming interface where RTA_SRCIFP is set.
7631 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7632 	 * to the destination, of equal netmask length in the forward table,
7633 	 * will be recursively explored. If no information is available
7634 	 * for the final gateway of that route, we force the returned ire
7635 	 * to be equal to sire using MATCH_IRE_PARENT.
7636 	 * At least, in this case we have a starting point (in the buckets)
7637 	 * to look for other routes to the destination in the forward table.
7638 	 * This is actually used only for multirouting, where a list
7639 	 * of routes has to be processed in sequence.
7640 	 *
7641 	 * In the process of coming up with the most specific information,
7642 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7643 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7644 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7645 	 * Two caveats when handling incomplete ire's in ip_newroute:
7646 	 * - we should be careful when accessing its ire_nce (specifically
7647 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7648 	 * - not all legacy code path callers are prepared to handle
7649 	 *   incomplete ire's, so we should not create/add incomplete
7650 	 *   ire_cache entries here. (See discussion about temporary solution
7651 	 *   further below).
7652 	 *
7653 	 * In order to minimize packet dropping, and to preserve existing
7654 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7655 	 * gateway, and instead use the IF_RESOLVER ire to send out
7656 	 * another request to ARP (this is achieved by passing the
7657 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7658 	 * arp response comes back in ip_wput_nondata, we will create
7659 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7660 	 *
7661 	 * Note that this is a temporary solution; the correct solution is
7662 	 * to create an incomplete  per-dst ire_cache entry, and send the
7663 	 * packet out when the gw's nce is resolved. In order to achieve this,
7664 	 * all packet processing must have been completed prior to calling
7665 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7666 	 * to be modified to accomodate this solution.
7667 	 */
7668 	if (in_ill != NULL) {
7669 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7670 		    in_ill, MATCH_IRE_TYPE);
7671 	} else if (ip_nexthop) {
7672 		/*
7673 		 * The first time we come here, we look for an IRE_INTERFACE
7674 		 * entry for the specified nexthop, set the dst to be the
7675 		 * nexthop address and create an IRE_CACHE entry for the
7676 		 * nexthop. The next time around, we are able to find an
7677 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7678 		 * nexthop address and create an IRE_CACHE entry for the
7679 		 * destination address via the specified nexthop.
7680 		 */
7681 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7682 		    MBLK_GETLABEL(mp));
7683 		if (ire != NULL) {
7684 			gw = nexthop_addr;
7685 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7686 		} else {
7687 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7688 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7689 			    MBLK_GETLABEL(mp),
7690 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7691 			if (ire != NULL) {
7692 				dst = nexthop_addr;
7693 			}
7694 		}
7695 	} else if (attach_ill == NULL) {
7696 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7697 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7698 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7699 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7700 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7701 	} else {
7702 		/*
7703 		 * attach_ill is set only for communicating with
7704 		 * on-link hosts. So, don't look for DEFAULT.
7705 		 */
7706 		ipif_t	*attach_ipif;
7707 
7708 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7709 		if (attach_ipif == NULL) {
7710 			ill_refrele(attach_ill);
7711 			goto icmp_err_ret;
7712 		}
7713 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7714 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7715 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7716 		    MATCH_IRE_SECATTR);
7717 		ipif_refrele(attach_ipif);
7718 	}
7719 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7720 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7721 
7722 	/*
7723 	 * This loop is run only once in most cases.
7724 	 * We loop to resolve further routes only when the destination
7725 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7726 	 */
7727 	do {
7728 		/* Clear the previous iteration's values */
7729 		if (src_ipif != NULL) {
7730 			ipif_refrele(src_ipif);
7731 			src_ipif = NULL;
7732 		}
7733 		if (dst_ill != NULL) {
7734 			ill_refrele(dst_ill);
7735 			dst_ill = NULL;
7736 		}
7737 
7738 		multirt_resolve_next = B_FALSE;
7739 		/*
7740 		 * We check if packets have to be multirouted.
7741 		 * In this case, given the current <ire, sire> couple,
7742 		 * we look for the next suitable <ire, sire>.
7743 		 * This check is done in ire_multirt_lookup(),
7744 		 * which applies various criteria to find the next route
7745 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7746 		 * unchanged if it detects it has not been tried yet.
7747 		 */
7748 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7749 			ip3dbg(("ip_newroute: starting next_resolution "
7750 			    "with first_mp %p, tag %d\n",
7751 			    (void *)first_mp,
7752 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7753 
7754 			ASSERT(sire != NULL);
7755 			multirt_is_resolvable =
7756 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7757 				MBLK_GETLABEL(mp));
7758 
7759 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7760 			    "ire %p, sire %p\n",
7761 			    multirt_is_resolvable,
7762 			    (void *)ire, (void *)sire));
7763 
7764 			if (!multirt_is_resolvable) {
7765 				/*
7766 				 * No more multirt route to resolve; give up
7767 				 * (all routes resolved or no more
7768 				 * resolvable routes).
7769 				 */
7770 				if (ire != NULL) {
7771 					ire_refrele(ire);
7772 					ire = NULL;
7773 				}
7774 			} else {
7775 				ASSERT(sire != NULL);
7776 				ASSERT(ire != NULL);
7777 				/*
7778 				 * We simply use first_sire as a flag that
7779 				 * indicates if a resolvable multirt route
7780 				 * has already been found.
7781 				 * If it is not the case, we may have to send
7782 				 * an ICMP error to report that the
7783 				 * destination is unreachable.
7784 				 * We do not IRE_REFHOLD first_sire.
7785 				 */
7786 				if (first_sire == NULL) {
7787 					first_sire = sire;
7788 				}
7789 			}
7790 		}
7791 		if (ire == NULL) {
7792 			if (ip_debug > 3) {
7793 				/* ip2dbg */
7794 				pr_addr_dbg("ip_newroute: "
7795 				    "can't resolve %s\n", AF_INET, &dst);
7796 			}
7797 			ip3dbg(("ip_newroute: "
7798 			    "ire %p, sire %p, first_sire %p\n",
7799 			    (void *)ire, (void *)sire, (void *)first_sire));
7800 
7801 			if (sire != NULL) {
7802 				ire_refrele(sire);
7803 				sire = NULL;
7804 			}
7805 
7806 			if (first_sire != NULL) {
7807 				/*
7808 				 * At least one multirt route has been found
7809 				 * in the same call to ip_newroute();
7810 				 * there is no need to report an ICMP error.
7811 				 * first_sire was not IRE_REFHOLDed.
7812 				 */
7813 				MULTIRT_DEBUG_UNTAG(first_mp);
7814 				freemsg(first_mp);
7815 				return;
7816 			}
7817 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7818 			    RTA_DST);
7819 			if (attach_ill != NULL)
7820 				ill_refrele(attach_ill);
7821 			goto icmp_err_ret;
7822 		}
7823 
7824 		/*
7825 		 * When RTA_SRCIFP is used to add a route, then an interface
7826 		 * route is added in the source interface's routing table.
7827 		 * If the outgoing interface of this route is of type
7828 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7829 		 * ire_nce->nce_res_mp is set to NULL.
7830 		 * Later, when this route is first used for forwarding
7831 		 * a packet, ip_newroute() is called
7832 		 * to resolve the hardware address of the outgoing ipif.
7833 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7834 		 * source interface based table. We only come here if the
7835 		 * outgoing interface is a resolver interface and we don't
7836 		 * have the ire_nce->nce_res_mp information yet.
7837 		 * If in_ill is not null that means it is called from
7838 		 * ip_rput.
7839 		 */
7840 
7841 		ASSERT(ire->ire_in_ill == NULL ||
7842 		    (ire->ire_type == IRE_IF_RESOLVER &&
7843 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
7844 
7845 		/*
7846 		 * Verify that the returned IRE does not have either
7847 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7848 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7849 		 */
7850 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7851 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7852 			if (attach_ill != NULL)
7853 				ill_refrele(attach_ill);
7854 			goto icmp_err_ret;
7855 		}
7856 		/*
7857 		 * Increment the ire_ob_pkt_count field for ire if it is an
7858 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7859 		 * increment the same for the parent IRE, sire, if it is some
7860 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7861 		 * and HOST_REDIRECT).
7862 		 */
7863 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7864 			UPDATE_OB_PKT_COUNT(ire);
7865 			ire->ire_last_used_time = lbolt;
7866 		}
7867 
7868 		if (sire != NULL) {
7869 			gw = sire->ire_gateway_addr;
7870 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7871 			    IRE_INTERFACE)) == 0);
7872 			UPDATE_OB_PKT_COUNT(sire);
7873 			sire->ire_last_used_time = lbolt;
7874 		}
7875 		/*
7876 		 * We have a route to reach the destination.
7877 		 *
7878 		 * 1) If the interface is part of ill group, try to get a new
7879 		 *    ill taking load spreading into account.
7880 		 *
7881 		 * 2) After selecting the ill, get a source address that
7882 		 *    might create good inbound load spreading.
7883 		 *    ipif_select_source does this for us.
7884 		 *
7885 		 * If the application specified the ill (ifindex), we still
7886 		 * load spread. Only if the packets needs to go out
7887 		 * specifically on a given ill e.g. binding to
7888 		 * IPIF_NOFAILOVER address, then we don't try to use a
7889 		 * different ill for load spreading.
7890 		 */
7891 		if (attach_ill == NULL) {
7892 			/*
7893 			 * Don't perform outbound load spreading in the
7894 			 * case of an RTF_MULTIRT route, as we actually
7895 			 * typically want to replicate outgoing packets
7896 			 * through particular interfaces.
7897 			 */
7898 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7899 				dst_ill = ire->ire_ipif->ipif_ill;
7900 				/* for uniformity */
7901 				ill_refhold(dst_ill);
7902 			} else {
7903 				/*
7904 				 * If we are here trying to create an IRE_CACHE
7905 				 * for an offlink destination and have the
7906 				 * IRE_CACHE for the next hop and the latter is
7907 				 * using virtual IP source address selection i.e
7908 				 * it's ire->ire_ipif is pointing to a virtual
7909 				 * network interface (vni) then
7910 				 * ip_newroute_get_dst_ll() will return the vni
7911 				 * interface as the dst_ill. Since the vni is
7912 				 * virtual i.e not associated with any physical
7913 				 * interface, it cannot be the dst_ill, hence
7914 				 * in such a case call ip_newroute_get_dst_ll()
7915 				 * with the stq_ill instead of the ire_ipif ILL.
7916 				 * The function returns a refheld ill.
7917 				 */
7918 				if ((ire->ire_type == IRE_CACHE) &&
7919 				    IS_VNI(ire->ire_ipif->ipif_ill))
7920 					dst_ill = ip_newroute_get_dst_ill(
7921 						ire->ire_stq->q_ptr);
7922 				else
7923 					dst_ill = ip_newroute_get_dst_ill(
7924 						ire->ire_ipif->ipif_ill);
7925 			}
7926 			if (dst_ill == NULL) {
7927 				if (ip_debug > 2) {
7928 					pr_addr_dbg("ip_newroute: "
7929 					    "no dst ill for dst"
7930 					    " %s\n", AF_INET, &dst);
7931 				}
7932 				goto icmp_err_ret;
7933 			}
7934 		} else {
7935 			dst_ill = ire->ire_ipif->ipif_ill;
7936 			/* for uniformity */
7937 			ill_refhold(dst_ill);
7938 			/*
7939 			 * We should have found a route matching ill as we
7940 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7941 			 * Rather than asserting, when there is a mismatch,
7942 			 * we just drop the packet.
7943 			 */
7944 			if (dst_ill != attach_ill) {
7945 				ip0dbg(("ip_newroute: Packet dropped as "
7946 				    "IPIF_NOFAILOVER ill is %s, "
7947 				    "ire->ire_ipif->ipif_ill is %s\n",
7948 				    attach_ill->ill_name,
7949 				    dst_ill->ill_name));
7950 				ill_refrele(attach_ill);
7951 				goto icmp_err_ret;
7952 			}
7953 		}
7954 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7955 		if (attach_ill != NULL) {
7956 			ill_refrele(attach_ill);
7957 			attach_ill = NULL;
7958 			do_attach_ill = B_TRUE;
7959 		}
7960 		ASSERT(dst_ill != NULL);
7961 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7962 
7963 		/*
7964 		 * Pick the best source address from dst_ill.
7965 		 *
7966 		 * 1) If it is part of a multipathing group, we would
7967 		 *    like to spread the inbound packets across different
7968 		 *    interfaces. ipif_select_source picks a random source
7969 		 *    across the different ills in the group.
7970 		 *
7971 		 * 2) If it is not part of a multipathing group, we try
7972 		 *    to pick the source address from the destination
7973 		 *    route. Clustering assumes that when we have multiple
7974 		 *    prefixes hosted on an interface, the prefix of the
7975 		 *    source address matches the prefix of the destination
7976 		 *    route. We do this only if the address is not
7977 		 *    DEPRECATED.
7978 		 *
7979 		 * 3) If the conn is in a different zone than the ire, we
7980 		 *    need to pick a source address from the right zone.
7981 		 *
7982 		 * NOTE : If we hit case (1) above, the prefix of the source
7983 		 *	  address picked may not match the prefix of the
7984 		 *	  destination routes prefix as ipif_select_source
7985 		 *	  does not look at "dst" while picking a source
7986 		 *	  address.
7987 		 *	  If we want the same behavior as (2), we will need
7988 		 *	  to change the behavior of ipif_select_source.
7989 		 */
7990 		ASSERT(src_ipif == NULL);
7991 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7992 			/*
7993 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7994 			 * Check that the ipif matching the requested source
7995 			 * address still exists.
7996 			 */
7997 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7998 			    zoneid, NULL, NULL, NULL, NULL);
7999 		}
8000 		if (src_ipif == NULL) {
8001 			ire_marks |= IRE_MARK_USESRC_CHECK;
8002 			if ((dst_ill->ill_group != NULL) ||
8003 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8004 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8005 			    ire->ire_zoneid != ALL_ZONES) ||
8006 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8007 				/*
8008 				 * If the destination is reachable via a
8009 				 * given gateway, the selected source address
8010 				 * should be in the same subnet as the gateway.
8011 				 * Otherwise, the destination is not reachable.
8012 				 *
8013 				 * If there are no interfaces on the same subnet
8014 				 * as the destination, ipif_select_source gives
8015 				 * first non-deprecated interface which might be
8016 				 * on a different subnet than the gateway.
8017 				 * This is not desirable. Hence pass the dst_ire
8018 				 * source address to ipif_select_source.
8019 				 * It is sure that the destination is reachable
8020 				 * with the dst_ire source address subnet.
8021 				 * So passing dst_ire source address to
8022 				 * ipif_select_source will make sure that the
8023 				 * selected source will be on the same subnet
8024 				 * as dst_ire source address.
8025 				 */
8026 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8027 				src_ipif = ipif_select_source(dst_ill, saddr,
8028 				    zoneid);
8029 				if (src_ipif == NULL) {
8030 					if (ip_debug > 2) {
8031 						pr_addr_dbg("ip_newroute: "
8032 						    "no src for dst %s ",
8033 						    AF_INET, &dst);
8034 						printf("through interface %s\n",
8035 						    dst_ill->ill_name);
8036 					}
8037 					goto icmp_err_ret;
8038 				}
8039 			} else {
8040 				src_ipif = ire->ire_ipif;
8041 				ASSERT(src_ipif != NULL);
8042 				/* hold src_ipif for uniformity */
8043 				ipif_refhold(src_ipif);
8044 			}
8045 		}
8046 
8047 		/*
8048 		 * Assign a source address while we have the conn.
8049 		 * We can't have ip_wput_ire pick a source address when the
8050 		 * packet returns from arp since we need to look at
8051 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8052 		 * going through arp.
8053 		 *
8054 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8055 		 *	  it uses ip6i to store this information.
8056 		 */
8057 		if (ipha->ipha_src == INADDR_ANY &&
8058 		    (connp == NULL || !connp->conn_unspec_src)) {
8059 			ipha->ipha_src = src_ipif->ipif_src_addr;
8060 		}
8061 		if (ip_debug > 3) {
8062 			/* ip2dbg */
8063 			pr_addr_dbg("ip_newroute: first hop %s\n",
8064 			    AF_INET, &gw);
8065 		}
8066 		ip2dbg(("\tire type %s (%d)\n",
8067 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8068 
8069 		/*
8070 		 * The TTL of multirouted packets is bounded by the
8071 		 * ip_multirt_ttl ndd variable.
8072 		 */
8073 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8074 			/* Force TTL of multirouted packets */
8075 			if ((ip_multirt_ttl > 0) &&
8076 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
8077 				ip2dbg(("ip_newroute: forcing multirt TTL "
8078 				    "to %d (was %d), dst 0x%08x\n",
8079 				    ip_multirt_ttl, ipha->ipha_ttl,
8080 				    ntohl(sire->ire_addr)));
8081 				ipha->ipha_ttl = ip_multirt_ttl;
8082 			}
8083 		}
8084 		/*
8085 		 * At this point in ip_newroute(), ire is either the
8086 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8087 		 * destination or an IRE_INTERFACE type that should be used
8088 		 * to resolve an on-subnet destination or an on-subnet
8089 		 * next-hop gateway.
8090 		 *
8091 		 * In the IRE_CACHE case, we have the following :
8092 		 *
8093 		 * 1) src_ipif - used for getting a source address.
8094 		 *
8095 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8096 		 *    means packets using this IRE_CACHE will go out on
8097 		 *    dst_ill.
8098 		 *
8099 		 * 3) The IRE sire will point to the prefix that is the
8100 		 *    longest  matching route for the destination. These
8101 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8102 		 *
8103 		 *    The newly created IRE_CACHE entry for the off-subnet
8104 		 *    destination is tied to both the prefix route and the
8105 		 *    interface route used to resolve the next-hop gateway
8106 		 *    via the ire_phandle and ire_ihandle fields,
8107 		 *    respectively.
8108 		 *
8109 		 * In the IRE_INTERFACE case, we have the following :
8110 		 *
8111 		 * 1) src_ipif - used for getting a source address.
8112 		 *
8113 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8114 		 *    means packets using the IRE_CACHE that we will build
8115 		 *    here will go out on dst_ill.
8116 		 *
8117 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8118 		 *    to be created will only be tied to the IRE_INTERFACE
8119 		 *    that was derived from the ire_ihandle field.
8120 		 *
8121 		 *    If sire is non-NULL, it means the destination is
8122 		 *    off-link and we will first create the IRE_CACHE for the
8123 		 *    gateway. Next time through ip_newroute, we will create
8124 		 *    the IRE_CACHE for the final destination as described
8125 		 *    above.
8126 		 *
8127 		 * In both cases, after the current resolution has been
8128 		 * completed (or possibly initialised, in the IRE_INTERFACE
8129 		 * case), the loop may be re-entered to attempt the resolution
8130 		 * of another RTF_MULTIRT route.
8131 		 *
8132 		 * When an IRE_CACHE entry for the off-subnet destination is
8133 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8134 		 * for further processing in emission loops.
8135 		 */
8136 		save_ire = ire;
8137 		switch (ire->ire_type) {
8138 		case IRE_CACHE: {
8139 			ire_t	*ipif_ire;
8140 			mblk_t	*ire_fp_mp;
8141 
8142 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8143 			if (gw == 0)
8144 				gw = ire->ire_gateway_addr;
8145 			/*
8146 			 * We need 3 ire's to create a new cache ire for an
8147 			 * off-link destination from the cache ire of the
8148 			 * gateway.
8149 			 *
8150 			 *	1. The prefix ire 'sire' (Note that this does
8151 			 *	   not apply to the conn_nexthop_set case)
8152 			 *	2. The cache ire of the gateway 'ire'
8153 			 *	3. The interface ire 'ipif_ire'
8154 			 *
8155 			 * We have (1) and (2). We lookup (3) below.
8156 			 *
8157 			 * If there is no interface route to the gateway,
8158 			 * it is a race condition, where we found the cache
8159 			 * but the interface route has been deleted.
8160 			 */
8161 			if (ip_nexthop) {
8162 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8163 			} else {
8164 				ipif_ire =
8165 				    ire_ihandle_lookup_offlink(ire, sire);
8166 			}
8167 			if (ipif_ire == NULL) {
8168 				ip1dbg(("ip_newroute: "
8169 				    "ire_ihandle_lookup_offlink failed\n"));
8170 				goto icmp_err_ret;
8171 			}
8172 			/*
8173 			 * XXX We are using the same res_mp
8174 			 * (DL_UNITDATA_REQ) though the save_ire is not
8175 			 * pointing at the same ill.
8176 			 * This is incorrect. We need to send it up to the
8177 			 * resolver to get the right res_mp. For ethernets
8178 			 * this may be okay (ill_type == DL_ETHER).
8179 			 */
8180 			res_mp = save_ire->ire_nce->nce_res_mp;
8181 			ire_fp_mp = NULL;
8182 			/*
8183 			 * save_ire's nce_fp_mp can't change since it is
8184 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8185 			 * LOCK_IRE_FP_MP does not do any useful work in
8186 			 * the case of IRE_CACHE. So we don't use it below.
8187 			 */
8188 			if (save_ire->ire_stq == dst_ill->ill_wq)
8189 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8190 
8191 			/*
8192 			 * Check cached gateway IRE for any security
8193 			 * attributes; if found, associate the gateway
8194 			 * credentials group to the destination IRE.
8195 			 */
8196 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8197 				mutex_enter(&attrp->igsa_lock);
8198 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8199 					GCGRP_REFHOLD(gcgrp);
8200 				mutex_exit(&attrp->igsa_lock);
8201 			}
8202 
8203 			ire = ire_create(
8204 			    (uchar_t *)&dst,		/* dest address */
8205 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8206 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8207 			    (uchar_t *)&gw,		/* gateway address */
8208 			    NULL,
8209 			    &save_ire->ire_max_frag,
8210 			    ire_fp_mp,			/* Fast Path header */
8211 			    dst_ill->ill_rq,		/* recv-from queue */
8212 			    dst_ill->ill_wq,		/* send-to queue */
8213 			    IRE_CACHE,			/* IRE type */
8214 			    res_mp,
8215 			    src_ipif,
8216 			    in_ill,			/* incoming ill */
8217 			    (sire != NULL) ?
8218 				sire->ire_mask : 0, 	/* Parent mask */
8219 			    (sire != NULL) ?
8220 				sire->ire_phandle : 0,  /* Parent handle */
8221 			    ipif_ire->ire_ihandle,	/* Interface handle */
8222 			    (sire != NULL) ? (sire->ire_flags &
8223 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8224 			    (sire != NULL) ?
8225 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8226 			    NULL,
8227 			    gcgrp);
8228 
8229 			if (ire == NULL) {
8230 				if (gcgrp != NULL) {
8231 					GCGRP_REFRELE(gcgrp);
8232 					gcgrp = NULL;
8233 				}
8234 				ire_refrele(ipif_ire);
8235 				ire_refrele(save_ire);
8236 				break;
8237 			}
8238 
8239 			/* reference now held by IRE */
8240 			gcgrp = NULL;
8241 
8242 			ire->ire_marks |= ire_marks;
8243 
8244 			/*
8245 			 * Prevent sire and ipif_ire from getting deleted.
8246 			 * The newly created ire is tied to both of them via
8247 			 * the phandle and ihandle respectively.
8248 			 */
8249 			if (sire != NULL) {
8250 				IRB_REFHOLD(sire->ire_bucket);
8251 				/* Has it been removed already ? */
8252 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8253 					IRB_REFRELE(sire->ire_bucket);
8254 					ire_refrele(ipif_ire);
8255 					ire_refrele(save_ire);
8256 					break;
8257 				}
8258 			}
8259 
8260 			IRB_REFHOLD(ipif_ire->ire_bucket);
8261 			/* Has it been removed already ? */
8262 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8263 				IRB_REFRELE(ipif_ire->ire_bucket);
8264 				if (sire != NULL)
8265 					IRB_REFRELE(sire->ire_bucket);
8266 				ire_refrele(ipif_ire);
8267 				ire_refrele(save_ire);
8268 				break;
8269 			}
8270 
8271 			xmit_mp = first_mp;
8272 			/*
8273 			 * In the case of multirouting, a copy
8274 			 * of the packet is done before its sending.
8275 			 * The copy is used to attempt another
8276 			 * route resolution, in a next loop.
8277 			 */
8278 			if (ire->ire_flags & RTF_MULTIRT) {
8279 				copy_mp = copymsg(first_mp);
8280 				if (copy_mp != NULL) {
8281 					xmit_mp = copy_mp;
8282 					MULTIRT_DEBUG_TAG(first_mp);
8283 				}
8284 			}
8285 			ire_add_then_send(q, ire, xmit_mp);
8286 			ire_refrele(save_ire);
8287 
8288 			/* Assert that sire is not deleted yet. */
8289 			if (sire != NULL) {
8290 				ASSERT(sire->ire_ptpn != NULL);
8291 				IRB_REFRELE(sire->ire_bucket);
8292 			}
8293 
8294 			/* Assert that ipif_ire is not deleted yet. */
8295 			ASSERT(ipif_ire->ire_ptpn != NULL);
8296 			IRB_REFRELE(ipif_ire->ire_bucket);
8297 			ire_refrele(ipif_ire);
8298 
8299 			/*
8300 			 * If copy_mp is not NULL, multirouting was
8301 			 * requested. We loop to initiate a next
8302 			 * route resolution attempt, starting from sire.
8303 			 */
8304 			if (copy_mp != NULL) {
8305 				/*
8306 				 * Search for the next unresolved
8307 				 * multirt route.
8308 				 */
8309 				copy_mp = NULL;
8310 				ipif_ire = NULL;
8311 				ire = NULL;
8312 				multirt_resolve_next = B_TRUE;
8313 				continue;
8314 			}
8315 			if (sire != NULL)
8316 				ire_refrele(sire);
8317 			ipif_refrele(src_ipif);
8318 			ill_refrele(dst_ill);
8319 			return;
8320 		}
8321 		case IRE_IF_NORESOLVER: {
8322 			/*
8323 			 * We have what we need to build an IRE_CACHE.
8324 			 *
8325 			 * Create a new res_mp with the IP gateway address
8326 			 * in destination address in the DLPI hdr if the
8327 			 * physical length is exactly 4 bytes.
8328 			 */
8329 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8330 				uchar_t *addr;
8331 
8332 				if (gw)
8333 					addr = (uchar_t *)&gw;
8334 				else
8335 					addr = (uchar_t *)&dst;
8336 
8337 				res_mp = ill_dlur_gen(addr,
8338 				    dst_ill->ill_phys_addr_length,
8339 				    dst_ill->ill_sap,
8340 				    dst_ill->ill_sap_length);
8341 
8342 				if (res_mp == NULL) {
8343 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8344 					break;
8345 				}
8346 			} else {
8347 				res_mp = NULL;
8348 			}
8349 
8350 			/*
8351 			 * TSol note: We are creating the ire cache for the
8352 			 * destination 'dst'. If 'dst' is offlink, going
8353 			 * through the first hop 'gw', the security attributes
8354 			 * of 'dst' must be set to point to the gateway
8355 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8356 			 * is possible that 'dst' is a potential gateway that is
8357 			 * referenced by some route that has some security
8358 			 * attributes. Thus in the former case, we need to do a
8359 			 * gcgrp_lookup of 'gw' while in the latter case we
8360 			 * need to do gcgrp_lookup of 'dst' itself.
8361 			 */
8362 			ga.ga_af = AF_INET;
8363 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8364 			    &ga.ga_addr);
8365 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8366 
8367 			ire = ire_create(
8368 			    (uchar_t *)&dst,		/* dest address */
8369 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8370 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8371 			    (uchar_t *)&gw,		/* gateway address */
8372 			    NULL,
8373 			    &save_ire->ire_max_frag,
8374 			    NULL,			/* Fast Path header */
8375 			    dst_ill->ill_rq,		/* recv-from queue */
8376 			    dst_ill->ill_wq,		/* send-to queue */
8377 			    IRE_CACHE,
8378 			    res_mp,
8379 			    src_ipif,
8380 			    in_ill,			/* Incoming ill */
8381 			    save_ire->ire_mask,		/* Parent mask */
8382 			    (sire != NULL) ?		/* Parent handle */
8383 				sire->ire_phandle : 0,
8384 			    save_ire->ire_ihandle,	/* Interface handle */
8385 			    (sire != NULL) ? sire->ire_flags &
8386 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8387 			    &(save_ire->ire_uinfo),
8388 			    NULL,
8389 			    gcgrp);
8390 
8391 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8392 				freeb(res_mp);
8393 
8394 			if (ire == NULL) {
8395 				if (gcgrp != NULL) {
8396 					GCGRP_REFRELE(gcgrp);
8397 					gcgrp = NULL;
8398 				}
8399 				ire_refrele(save_ire);
8400 				break;
8401 			}
8402 
8403 			/* reference now held by IRE */
8404 			gcgrp = NULL;
8405 
8406 			ire->ire_marks |= ire_marks;
8407 
8408 			/* Prevent save_ire from getting deleted */
8409 			IRB_REFHOLD(save_ire->ire_bucket);
8410 			/* Has it been removed already ? */
8411 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8412 				IRB_REFRELE(save_ire->ire_bucket);
8413 				ire_refrele(save_ire);
8414 				break;
8415 			}
8416 
8417 			/*
8418 			 * In the case of multirouting, a copy
8419 			 * of the packet is made before it is sent.
8420 			 * The copy is used in the next
8421 			 * loop to attempt another resolution.
8422 			 */
8423 			xmit_mp = first_mp;
8424 			if ((sire != NULL) &&
8425 			    (sire->ire_flags & RTF_MULTIRT)) {
8426 				copy_mp = copymsg(first_mp);
8427 				if (copy_mp != NULL) {
8428 					xmit_mp = copy_mp;
8429 					MULTIRT_DEBUG_TAG(first_mp);
8430 				}
8431 			}
8432 			ire_add_then_send(q, ire, xmit_mp);
8433 
8434 			/* Assert that it is not deleted yet. */
8435 			ASSERT(save_ire->ire_ptpn != NULL);
8436 			IRB_REFRELE(save_ire->ire_bucket);
8437 			ire_refrele(save_ire);
8438 
8439 			if (copy_mp != NULL) {
8440 				/*
8441 				 * If we found a (no)resolver, we ignore any
8442 				 * trailing top priority IRE_CACHE in further
8443 				 * loops. This ensures that we do not omit any
8444 				 * (no)resolver.
8445 				 * This IRE_CACHE, if any, will be processed
8446 				 * by another thread entering ip_newroute().
8447 				 * IRE_CACHE entries, if any, will be processed
8448 				 * by another thread entering ip_newroute(),
8449 				 * (upon resolver response, for instance).
8450 				 * This aims to force parallel multirt
8451 				 * resolutions as soon as a packet must be sent.
8452 				 * In the best case, after the tx of only one
8453 				 * packet, all reachable routes are resolved.
8454 				 * Otherwise, the resolution of all RTF_MULTIRT
8455 				 * routes would require several emissions.
8456 				 */
8457 				multirt_flags &= ~MULTIRT_CACHEGW;
8458 
8459 				/*
8460 				 * Search for the next unresolved multirt
8461 				 * route.
8462 				 */
8463 				copy_mp = NULL;
8464 				save_ire = NULL;
8465 				ire = NULL;
8466 				multirt_resolve_next = B_TRUE;
8467 				continue;
8468 			}
8469 
8470 			/*
8471 			 * Don't need sire anymore
8472 			 */
8473 			if (sire != NULL)
8474 				ire_refrele(sire);
8475 
8476 			ipif_refrele(src_ipif);
8477 			ill_refrele(dst_ill);
8478 			return;
8479 		}
8480 		case IRE_IF_RESOLVER:
8481 			/*
8482 			 * We can't build an IRE_CACHE yet, but at least we
8483 			 * found a resolver that can help.
8484 			 */
8485 			res_mp = dst_ill->ill_resolver_mp;
8486 			if (!OK_RESOLVER_MP(res_mp))
8487 				break;
8488 
8489 			/*
8490 			 * To be at this point in the code with a non-zero gw
8491 			 * means that dst is reachable through a gateway that
8492 			 * we have never resolved.  By changing dst to the gw
8493 			 * addr we resolve the gateway first.
8494 			 * When ire_add_then_send() tries to put the IP dg
8495 			 * to dst, it will reenter ip_newroute() at which
8496 			 * time we will find the IRE_CACHE for the gw and
8497 			 * create another IRE_CACHE in case IRE_CACHE above.
8498 			 */
8499 			if (gw != INADDR_ANY) {
8500 				/*
8501 				 * The source ipif that was determined above was
8502 				 * relative to the destination address, not the
8503 				 * gateway's. If src_ipif was not taken out of
8504 				 * the IRE_IF_RESOLVER entry, we'll need to call
8505 				 * ipif_select_source() again.
8506 				 */
8507 				if (src_ipif != ire->ire_ipif) {
8508 					ipif_refrele(src_ipif);
8509 					src_ipif = ipif_select_source(dst_ill,
8510 					    gw, zoneid);
8511 					if (src_ipif == NULL) {
8512 						if (ip_debug > 2) {
8513 							pr_addr_dbg(
8514 							    "ip_newroute: no "
8515 							    "src for gw %s ",
8516 							    AF_INET, &gw);
8517 							printf("through "
8518 							    "interface %s\n",
8519 							    dst_ill->ill_name);
8520 						}
8521 						goto icmp_err_ret;
8522 					}
8523 				}
8524 				save_dst = dst;
8525 				dst = gw;
8526 				gw = INADDR_ANY;
8527 			}
8528 
8529 			/*
8530 			 * We obtain a partial IRE_CACHE which we will pass
8531 			 * along with the resolver query.  When the response
8532 			 * comes back it will be there ready for us to add.
8533 			 * The ire_max_frag is atomically set under the
8534 			 * irebucket lock in ire_add_v[46].
8535 			 */
8536 
8537 			ire = ire_create_mp(
8538 			    (uchar_t *)&dst,		/* dest address */
8539 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8540 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8541 			    (uchar_t *)&gw,		/* gateway address */
8542 			    NULL,			/* no in_src_addr */
8543 			    NULL,			/* ire_max_frag */
8544 			    NULL,			/* Fast Path header */
8545 			    dst_ill->ill_rq,		/* recv-from queue */
8546 			    dst_ill->ill_wq,		/* send-to queue */
8547 			    IRE_CACHE,
8548 			    NULL,
8549 			    src_ipif,			/* Interface ipif */
8550 			    in_ill,			/* Incoming ILL */
8551 			    save_ire->ire_mask,		/* Parent mask */
8552 			    0,
8553 			    save_ire->ire_ihandle,	/* Interface handle */
8554 			    0,				/* flags if any */
8555 			    &(save_ire->ire_uinfo),
8556 			    NULL,
8557 			    NULL);
8558 
8559 			if (ire == NULL) {
8560 				ire_refrele(save_ire);
8561 				break;
8562 			}
8563 
8564 			if ((sire != NULL) &&
8565 			    (sire->ire_flags & RTF_MULTIRT)) {
8566 				copy_mp = copymsg(first_mp);
8567 				if (copy_mp != NULL)
8568 					MULTIRT_DEBUG_TAG(copy_mp);
8569 			}
8570 
8571 			ire->ire_marks |= ire_marks;
8572 
8573 			/*
8574 			 * Construct message chain for the resolver
8575 			 * of the form:
8576 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8577 			 * Packet could contain a IPSEC_OUT mp.
8578 			 *
8579 			 * NOTE : ire will be added later when the response
8580 			 * comes back from ARP. If the response does not
8581 			 * come back, ARP frees the packet. For this reason,
8582 			 * we can't REFHOLD the bucket of save_ire to prevent
8583 			 * deletions. We may not be able to REFRELE the bucket
8584 			 * if the response never comes back. Thus, before
8585 			 * adding the ire, ire_add_v4 will make sure that the
8586 			 * interface route does not get deleted. This is the
8587 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8588 			 * where we can always prevent deletions because of
8589 			 * the synchronous nature of adding IRES i.e
8590 			 * ire_add_then_send is called after creating the IRE.
8591 			 */
8592 			ASSERT(ire->ire_mp != NULL);
8593 			ire->ire_mp->b_cont = first_mp;
8594 			/* Have saved_mp handy, for cleanup if canput fails */
8595 			saved_mp = mp;
8596 			mp = copyb(res_mp);
8597 			if (mp == NULL) {
8598 				/* Prepare for cleanup */
8599 				mp = saved_mp; /* pkt */
8600 				ire_delete(ire); /* ire_mp */
8601 				ire = NULL;
8602 				ire_refrele(save_ire);
8603 				if (copy_mp != NULL) {
8604 					MULTIRT_DEBUG_UNTAG(copy_mp);
8605 					freemsg(copy_mp);
8606 					copy_mp = NULL;
8607 				}
8608 				break;
8609 			}
8610 			linkb(mp, ire->ire_mp);
8611 
8612 			/*
8613 			 * Fill in the source and dest addrs for the resolver.
8614 			 * NOTE: this depends on memory layouts imposed by
8615 			 * ill_init().
8616 			 */
8617 			areq = (areq_t *)mp->b_rptr;
8618 			addrp = (ipaddr_t *)((char *)areq +
8619 			    areq->areq_sender_addr_offset);
8620 			if (do_attach_ill) {
8621 				/*
8622 				 * This is bind to no failover case.
8623 				 * arp packet also must go out on attach_ill.
8624 				 */
8625 				ASSERT(ipha->ipha_src != NULL);
8626 				*addrp = ipha->ipha_src;
8627 			} else {
8628 				*addrp = save_ire->ire_src_addr;
8629 			}
8630 
8631 			ire_refrele(save_ire);
8632 			addrp = (ipaddr_t *)((char *)areq +
8633 			    areq->areq_target_addr_offset);
8634 			*addrp = dst;
8635 			/* Up to the resolver. */
8636 			if (canputnext(dst_ill->ill_rq) &&
8637 			    !(dst_ill->ill_arp_closing)) {
8638 				putnext(dst_ill->ill_rq, mp);
8639 				ire = NULL;
8640 				if (copy_mp != NULL) {
8641 					/*
8642 					 * If we found a resolver, we ignore
8643 					 * any trailing top priority IRE_CACHE
8644 					 * in the further loops. This ensures
8645 					 * that we do not omit any resolver.
8646 					 * IRE_CACHE entries, if any, will be
8647 					 * processed next time we enter
8648 					 * ip_newroute().
8649 					 */
8650 					multirt_flags &= ~MULTIRT_CACHEGW;
8651 					/*
8652 					 * Search for the next unresolved
8653 					 * multirt route.
8654 					 */
8655 					first_mp = copy_mp;
8656 					copy_mp = NULL;
8657 					/* Prepare the next resolution loop. */
8658 					mp = first_mp;
8659 					EXTRACT_PKT_MP(mp, first_mp,
8660 					    mctl_present);
8661 					if (mctl_present)
8662 						io = (ipsec_out_t *)
8663 						    first_mp->b_rptr;
8664 					ipha = (ipha_t *)mp->b_rptr;
8665 
8666 					ASSERT(sire != NULL);
8667 
8668 					dst = save_dst;
8669 					multirt_resolve_next = B_TRUE;
8670 					continue;
8671 				}
8672 
8673 				if (sire != NULL)
8674 					ire_refrele(sire);
8675 
8676 				/*
8677 				 * The response will come back in ip_wput
8678 				 * with db_type IRE_DB_TYPE.
8679 				 */
8680 				ipif_refrele(src_ipif);
8681 				ill_refrele(dst_ill);
8682 				return;
8683 			} else {
8684 				/* Prepare for cleanup */
8685 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8686 				    mp);
8687 				mp->b_cont = NULL;
8688 				freeb(mp); /* areq */
8689 				/*
8690 				 * this is an ire that is not added to the
8691 				 * cache. ire_freemblk will handle the release
8692 				 * of any resources associated with the ire.
8693 				 */
8694 				ire_delete(ire); /* ire_mp */
8695 				mp = saved_mp; /* pkt */
8696 				ire = NULL;
8697 				if (copy_mp != NULL) {
8698 					MULTIRT_DEBUG_UNTAG(copy_mp);
8699 					freemsg(copy_mp);
8700 					copy_mp = NULL;
8701 				}
8702 				break;
8703 			}
8704 		default:
8705 			break;
8706 		}
8707 	} while (multirt_resolve_next);
8708 
8709 	ip1dbg(("ip_newroute: dropped\n"));
8710 	/* Did this packet originate externally? */
8711 	if (mp->b_prev) {
8712 		mp->b_next = NULL;
8713 		mp->b_prev = NULL;
8714 		BUMP_MIB(&ip_mib, ipInDiscards);
8715 	} else {
8716 		BUMP_MIB(&ip_mib, ipOutDiscards);
8717 	}
8718 	ASSERT(copy_mp == NULL);
8719 	MULTIRT_DEBUG_UNTAG(first_mp);
8720 	freemsg(first_mp);
8721 	if (ire != NULL)
8722 		ire_refrele(ire);
8723 	if (sire != NULL)
8724 		ire_refrele(sire);
8725 	if (src_ipif != NULL)
8726 		ipif_refrele(src_ipif);
8727 	if (dst_ill != NULL)
8728 		ill_refrele(dst_ill);
8729 	return;
8730 
8731 icmp_err_ret:
8732 	ip1dbg(("ip_newroute: no route\n"));
8733 	if (src_ipif != NULL)
8734 		ipif_refrele(src_ipif);
8735 	if (dst_ill != NULL)
8736 		ill_refrele(dst_ill);
8737 	if (sire != NULL)
8738 		ire_refrele(sire);
8739 	/* Did this packet originate externally? */
8740 	if (mp->b_prev) {
8741 		mp->b_next = NULL;
8742 		mp->b_prev = NULL;
8743 		/* XXX ipInNoRoutes */
8744 		q = WR(q);
8745 	} else {
8746 		/*
8747 		 * Since ip_wput() isn't close to finished, we fill
8748 		 * in enough of the header for credible error reporting.
8749 		 */
8750 		if (ip_hdr_complete(ipha, zoneid)) {
8751 			/* Failed */
8752 			MULTIRT_DEBUG_UNTAG(first_mp);
8753 			freemsg(first_mp);
8754 			if (ire != NULL)
8755 				ire_refrele(ire);
8756 			return;
8757 		}
8758 	}
8759 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8760 
8761 	/*
8762 	 * At this point we will have ire only if RTF_BLACKHOLE
8763 	 * or RTF_REJECT flags are set on the IRE. It will not
8764 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8765 	 */
8766 	if (ire != NULL) {
8767 		if (ire->ire_flags & RTF_BLACKHOLE) {
8768 			ire_refrele(ire);
8769 			MULTIRT_DEBUG_UNTAG(first_mp);
8770 			freemsg(first_mp);
8771 			return;
8772 		}
8773 		ire_refrele(ire);
8774 	}
8775 	if (ip_source_routed(ipha)) {
8776 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8777 		    zoneid);
8778 		return;
8779 	}
8780 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
8781 }
8782 
8783 /*
8784  * IPv4 -
8785  * ip_newroute_ipif is called by ip_wput_multicast and
8786  * ip_rput_forward_multicast whenever we need to send
8787  * out a packet to a destination address for which we do not have specific
8788  * routing information. It is used when the packet will be sent out
8789  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8790  * socket option is set or icmp error message wants to go out on a particular
8791  * interface for a unicast packet.
8792  *
8793  * In most cases, the destination address is resolved thanks to the ipif
8794  * intrinsic resolver. However, there are some cases where the call to
8795  * ip_newroute_ipif must take into account the potential presence of
8796  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8797  * that uses the interface. This is specified through flags,
8798  * which can be a combination of:
8799  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8800  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8801  *   and flags. Additionally, the packet source address has to be set to
8802  *   the specified address. The caller is thus expected to set this flag
8803  *   if the packet has no specific source address yet.
8804  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8805  *   flag, the resulting ire will inherit the flag. All unresolved routes
8806  *   to the destination must be explored in the same call to
8807  *   ip_newroute_ipif().
8808  */
8809 static void
8810 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8811     conn_t *connp, uint32_t flags, zoneid_t zoneid)
8812 {
8813 	areq_t	*areq;
8814 	ire_t	*ire = NULL;
8815 	mblk_t	*res_mp;
8816 	ipaddr_t *addrp;
8817 	mblk_t *first_mp;
8818 	ire_t	*save_ire = NULL;
8819 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8820 	ipif_t	*src_ipif = NULL;
8821 	ushort_t ire_marks = 0;
8822 	ill_t	*dst_ill = NULL;
8823 	boolean_t mctl_present;
8824 	ipsec_out_t *io;
8825 	ipha_t *ipha;
8826 	int	ihandle = 0;
8827 	mblk_t	*saved_mp;
8828 	ire_t   *fire = NULL;
8829 	mblk_t  *copy_mp = NULL;
8830 	boolean_t multirt_resolve_next;
8831 	ipaddr_t ipha_dst;
8832 
8833 	/*
8834 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8835 	 * here for uniformity
8836 	 */
8837 	ipif_refhold(ipif);
8838 
8839 	/*
8840 	 * This loop is run only once in most cases.
8841 	 * We loop to resolve further routes only when the destination
8842 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8843 	 */
8844 	do {
8845 		if (dst_ill != NULL) {
8846 			ill_refrele(dst_ill);
8847 			dst_ill = NULL;
8848 		}
8849 		if (src_ipif != NULL) {
8850 			ipif_refrele(src_ipif);
8851 			src_ipif = NULL;
8852 		}
8853 		multirt_resolve_next = B_FALSE;
8854 
8855 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8856 		    ipif->ipif_ill->ill_name));
8857 
8858 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8859 		if (mctl_present)
8860 			io = (ipsec_out_t *)first_mp->b_rptr;
8861 
8862 		ipha = (ipha_t *)mp->b_rptr;
8863 
8864 		/*
8865 		 * Save the packet destination address, we may need it after
8866 		 * the packet has been consumed.
8867 		 */
8868 		ipha_dst = ipha->ipha_dst;
8869 
8870 		/*
8871 		 * If the interface is a pt-pt interface we look for an
8872 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8873 		 * local_address and the pt-pt destination address. Otherwise
8874 		 * we just match the local address.
8875 		 * NOTE: dst could be different than ipha->ipha_dst in case
8876 		 * of sending igmp multicast packets over a point-to-point
8877 		 * connection.
8878 		 * Thus we must be careful enough to check ipha_dst to be a
8879 		 * multicast address, otherwise it will take xmit_if path for
8880 		 * multicast packets resulting into kernel stack overflow by
8881 		 * repeated calls to ip_newroute_ipif from ire_send().
8882 		 */
8883 		if (CLASSD(ipha_dst) &&
8884 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8885 			goto err_ret;
8886 		}
8887 
8888 		/*
8889 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8890 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8891 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8892 		 * propagate its flags to the new ire.
8893 		 */
8894 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8895 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8896 			ip2dbg(("ip_newroute_ipif: "
8897 			    "ipif_lookup_multi_ire("
8898 			    "ipif %p, dst %08x) = fire %p\n",
8899 			    (void *)ipif, ntohl(dst), (void *)fire));
8900 		}
8901 
8902 		if (mctl_present && io->ipsec_out_attach_if) {
8903 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8904 			    io->ipsec_out_ill_index, B_FALSE);
8905 
8906 			/* Failure case frees things for us. */
8907 			if (attach_ill == NULL) {
8908 				ipif_refrele(ipif);
8909 				if (fire != NULL)
8910 					ire_refrele(fire);
8911 				return;
8912 			}
8913 
8914 			/*
8915 			 * Check if we need an ire that will not be
8916 			 * looked up by anybody else i.e. HIDDEN.
8917 			 */
8918 			if (ill_is_probeonly(attach_ill)) {
8919 				ire_marks = IRE_MARK_HIDDEN;
8920 			}
8921 			/*
8922 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8923 			 * case.
8924 			 */
8925 			dst_ill = ipif->ipif_ill;
8926 			/* attach_ill has been refheld by ip_grab_attach_ill */
8927 			ASSERT(dst_ill == attach_ill);
8928 		} else {
8929 			/*
8930 			 * If this is set by IP_XMIT_IF, then make sure that
8931 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8932 			 * specified ill.
8933 			 */
8934 			ASSERT((connp == NULL) ||
8935 			    (connp->conn_xmit_if_ill == NULL) ||
8936 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8937 			/*
8938 			 * If the interface belongs to an interface group,
8939 			 * make sure the next possible interface in the group
8940 			 * is used.  This encourages load spreading among
8941 			 * peers in an interface group.
8942 			 * Note: load spreading is disabled for RTF_MULTIRT
8943 			 * routes.
8944 			 */
8945 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8946 			    (fire->ire_flags & RTF_MULTIRT)) {
8947 				/*
8948 				 * Don't perform outbound load spreading
8949 				 * in the case of an RTF_MULTIRT issued route,
8950 				 * we actually typically want to replicate
8951 				 * outgoing packets through particular
8952 				 * interfaces.
8953 				 */
8954 				dst_ill = ipif->ipif_ill;
8955 				ill_refhold(dst_ill);
8956 			} else {
8957 				dst_ill = ip_newroute_get_dst_ill(
8958 				    ipif->ipif_ill);
8959 			}
8960 			if (dst_ill == NULL) {
8961 				if (ip_debug > 2) {
8962 					pr_addr_dbg("ip_newroute_ipif: "
8963 					    "no dst ill for dst %s\n",
8964 					    AF_INET, &dst);
8965 				}
8966 				goto err_ret;
8967 			}
8968 		}
8969 
8970 		/*
8971 		 * Pick a source address preferring non-deprecated ones.
8972 		 * Unlike ip_newroute, we don't do any source address
8973 		 * selection here since for multicast it really does not help
8974 		 * in inbound load spreading as in the unicast case.
8975 		 */
8976 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8977 		    (fire->ire_flags & RTF_SETSRC)) {
8978 			/*
8979 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8980 			 * on that interface. This ire has RTF_SETSRC flag, so
8981 			 * the source address of the packet must be changed.
8982 			 * Check that the ipif matching the requested source
8983 			 * address still exists.
8984 			 */
8985 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8986 			    zoneid, NULL, NULL, NULL, NULL);
8987 		}
8988 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8989 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
8990 		    ipif->ipif_zoneid != ALL_ZONES)) &&
8991 		    (src_ipif == NULL)) {
8992 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8993 			if (src_ipif == NULL) {
8994 				if (ip_debug > 2) {
8995 					/* ip1dbg */
8996 					pr_addr_dbg("ip_newroute_ipif: "
8997 					    "no src for dst %s",
8998 					    AF_INET, &dst);
8999 				}
9000 				ip1dbg((" through interface %s\n",
9001 				    dst_ill->ill_name));
9002 				goto err_ret;
9003 			}
9004 			ipif_refrele(ipif);
9005 			ipif = src_ipif;
9006 			ipif_refhold(ipif);
9007 		}
9008 		if (src_ipif == NULL) {
9009 			src_ipif = ipif;
9010 			ipif_refhold(src_ipif);
9011 		}
9012 
9013 		/*
9014 		 * Assign a source address while we have the conn.
9015 		 * We can't have ip_wput_ire pick a source address when the
9016 		 * packet returns from arp since conn_unspec_src might be set
9017 		 * and we loose the conn when going through arp.
9018 		 */
9019 		if (ipha->ipha_src == INADDR_ANY &&
9020 		    (connp == NULL || !connp->conn_unspec_src)) {
9021 			ipha->ipha_src = src_ipif->ipif_src_addr;
9022 		}
9023 
9024 		/*
9025 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9026 		 * interface does not have an interface ire.
9027 		 * Example: Thousands of mobileip PPP interfaces to mobile
9028 		 * nodes. We don't want to create interface ires because
9029 		 * packets from other mobile nodes must not take the route
9030 		 * via interface ires to the visiting mobile node without
9031 		 * going through the home agent, in absence of mobileip
9032 		 * route optimization.
9033 		 */
9034 		if (CLASSD(ipha_dst) && (connp == NULL ||
9035 		    connp->conn_xmit_if_ill == NULL)) {
9036 			/* ipif_to_ire returns an held ire */
9037 			ire = ipif_to_ire(ipif);
9038 			if (ire == NULL)
9039 				goto err_ret;
9040 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9041 				goto err_ret;
9042 			/*
9043 			 * ihandle is needed when the ire is added to
9044 			 * cache table.
9045 			 */
9046 			save_ire = ire;
9047 			ihandle = save_ire->ire_ihandle;
9048 
9049 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9050 			    "flags %04x\n",
9051 			    (void *)ire, (void *)ipif, flags));
9052 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9053 			    (fire->ire_flags & RTF_MULTIRT)) {
9054 				/*
9055 				 * As requested by flags, an IRE_OFFSUBNET was
9056 				 * looked up on that interface. This ire has
9057 				 * RTF_MULTIRT flag, so the resolution loop will
9058 				 * be re-entered to resolve additional routes on
9059 				 * other interfaces. For that purpose, a copy of
9060 				 * the packet is performed at this point.
9061 				 */
9062 				fire->ire_last_used_time = lbolt;
9063 				copy_mp = copymsg(first_mp);
9064 				if (copy_mp) {
9065 					MULTIRT_DEBUG_TAG(copy_mp);
9066 				}
9067 			}
9068 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9069 			    (fire->ire_flags & RTF_SETSRC)) {
9070 				/*
9071 				 * As requested by flags, an IRE_OFFSUBET was
9072 				 * looked up on that interface. This ire has
9073 				 * RTF_SETSRC flag, so the source address of the
9074 				 * packet must be changed.
9075 				 */
9076 				ipha->ipha_src = fire->ire_src_addr;
9077 			}
9078 		} else {
9079 			ASSERT((connp == NULL) ||
9080 			    (connp->conn_xmit_if_ill != NULL) ||
9081 			    (connp->conn_dontroute));
9082 			/*
9083 			 * The only ways we can come here are:
9084 			 * 1) IP_XMIT_IF socket option is set
9085 			 * 2) ICMP error message generated from
9086 			 *    ip_mrtun_forward() routine and it needs
9087 			 *    to go through the specified ill.
9088 			 * 3) SO_DONTROUTE socket option is set
9089 			 * In all cases, the new ire will not be added
9090 			 * into cache table.
9091 			 */
9092 			ire_marks |= IRE_MARK_NOADD;
9093 		}
9094 
9095 		switch (ipif->ipif_net_type) {
9096 		case IRE_IF_NORESOLVER: {
9097 			/* We have what we need to build an IRE_CACHE. */
9098 			mblk_t	*res_mp;
9099 
9100 			/*
9101 			 * Create a new res_mp with the
9102 			 * IP gateway address as destination address in the
9103 			 * DLPI hdr if the physical length is exactly 4 bytes.
9104 			 */
9105 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9106 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9107 				    dst_ill->ill_phys_addr_length,
9108 				    dst_ill->ill_sap,
9109 				    dst_ill->ill_sap_length);
9110 			} else {
9111 				/* use the value set in ip_ll_subnet_defaults */
9112 				res_mp = ill_dlur_gen(NULL,
9113 				    dst_ill->ill_phys_addr_length,
9114 				    dst_ill->ill_sap,
9115 				    dst_ill->ill_sap_length);
9116 			}
9117 
9118 			if (res_mp == NULL)
9119 				break;
9120 			/*
9121 			 * The new ire inherits the IRE_OFFSUBNET flags
9122 			 * and source address, if this was requested.
9123 			 */
9124 			ire = ire_create(
9125 			    (uchar_t *)&dst,		/* dest address */
9126 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9127 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9128 			    NULL,			/* gateway address */
9129 			    NULL,
9130 			    &ipif->ipif_mtu,
9131 			    NULL,			/* Fast Path header */
9132 			    dst_ill->ill_rq,		/* recv-from queue */
9133 			    dst_ill->ill_wq,		/* send-to queue */
9134 			    IRE_CACHE,
9135 			    res_mp,
9136 			    src_ipif,
9137 			    NULL,
9138 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9139 			    (fire != NULL) ?		/* Parent handle */
9140 				fire->ire_phandle : 0,
9141 			    ihandle,			/* Interface handle */
9142 			    (fire != NULL) ?
9143 				(fire->ire_flags &
9144 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9145 			    (save_ire == NULL ? &ire_uinfo_null :
9146 				&save_ire->ire_uinfo),
9147 			    NULL,
9148 			    NULL);
9149 
9150 			freeb(res_mp);
9151 
9152 			if (ire == NULL) {
9153 				if (save_ire != NULL)
9154 					ire_refrele(save_ire);
9155 				break;
9156 			}
9157 
9158 			ire->ire_marks |= ire_marks;
9159 
9160 			/*
9161 			 * If IRE_MARK_NOADD is set then we need to convert
9162 			 * the max_fragp to a useable value now. This is
9163 			 * normally done in ire_add_v[46]. We also need to
9164 			 * associate the ire with an nce (normally would be
9165 			 * done in ip_wput_nondata()).
9166 			 *
9167 			 * Note that IRE_MARK_NOADD packets created here
9168 			 * do not have a non-null ire_mp pointer. The null
9169 			 * value of ire_bucket indicates that they were
9170 			 * never added.
9171 			 */
9172 			if (ire->ire_marks & IRE_MARK_NOADD) {
9173 				uint_t  max_frag;
9174 
9175 				max_frag = *ire->ire_max_fragp;
9176 				ire->ire_max_fragp = NULL;
9177 				ire->ire_max_frag = max_frag;
9178 
9179 				if ((ire->ire_nce = ndp_lookup_v4(
9180 				    ire_to_ill(ire),
9181 				    (ire->ire_gateway_addr != INADDR_ANY ?
9182 				    &ire->ire_gateway_addr : &ire->ire_addr),
9183 				    B_FALSE)) == NULL) {
9184 					if (save_ire != NULL)
9185 						ire_refrele(save_ire);
9186 					break;
9187 				}
9188 				ASSERT(ire->ire_nce->nce_state ==
9189 				    ND_REACHABLE);
9190 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9191 			}
9192 
9193 			/* Prevent save_ire from getting deleted */
9194 			if (save_ire != NULL) {
9195 				IRB_REFHOLD(save_ire->ire_bucket);
9196 				/* Has it been removed already ? */
9197 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9198 					IRB_REFRELE(save_ire->ire_bucket);
9199 					ire_refrele(save_ire);
9200 					break;
9201 				}
9202 			}
9203 
9204 			ire_add_then_send(q, ire, first_mp);
9205 
9206 			/* Assert that save_ire is not deleted yet. */
9207 			if (save_ire != NULL) {
9208 				ASSERT(save_ire->ire_ptpn != NULL);
9209 				IRB_REFRELE(save_ire->ire_bucket);
9210 				ire_refrele(save_ire);
9211 				save_ire = NULL;
9212 			}
9213 			if (fire != NULL) {
9214 				ire_refrele(fire);
9215 				fire = NULL;
9216 			}
9217 
9218 			/*
9219 			 * the resolution loop is re-entered if this
9220 			 * was requested through flags and if we
9221 			 * actually are in a multirouting case.
9222 			 */
9223 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9224 				boolean_t need_resolve =
9225 				    ire_multirt_need_resolve(ipha_dst,
9226 					MBLK_GETLABEL(copy_mp));
9227 				if (!need_resolve) {
9228 					MULTIRT_DEBUG_UNTAG(copy_mp);
9229 					freemsg(copy_mp);
9230 					copy_mp = NULL;
9231 				} else {
9232 					/*
9233 					 * ipif_lookup_group() calls
9234 					 * ire_lookup_multi() that uses
9235 					 * ire_ftable_lookup() to find
9236 					 * an IRE_INTERFACE for the group.
9237 					 * In the multirt case,
9238 					 * ire_lookup_multi() then invokes
9239 					 * ire_multirt_lookup() to find
9240 					 * the next resolvable ire.
9241 					 * As a result, we obtain an new
9242 					 * interface, derived from the
9243 					 * next ire.
9244 					 */
9245 					ipif_refrele(ipif);
9246 					ipif = ipif_lookup_group(ipha_dst,
9247 					    zoneid);
9248 					ip2dbg(("ip_newroute_ipif: "
9249 					    "multirt dst %08x, ipif %p\n",
9250 					    htonl(dst), (void *)ipif));
9251 					if (ipif != NULL) {
9252 						mp = copy_mp;
9253 						copy_mp = NULL;
9254 						multirt_resolve_next = B_TRUE;
9255 						continue;
9256 					} else {
9257 						freemsg(copy_mp);
9258 					}
9259 				}
9260 			}
9261 			if (ipif != NULL)
9262 				ipif_refrele(ipif);
9263 			ill_refrele(dst_ill);
9264 			ipif_refrele(src_ipif);
9265 			return;
9266 		}
9267 		case IRE_IF_RESOLVER:
9268 			/*
9269 			 * We can't build an IRE_CACHE yet, but at least
9270 			 * we found a resolver that can help.
9271 			 */
9272 			res_mp = dst_ill->ill_resolver_mp;
9273 			if (!OK_RESOLVER_MP(res_mp))
9274 				break;
9275 
9276 			/*
9277 			 * We obtain a partial IRE_CACHE which we will pass
9278 			 * along with the resolver query.  When the response
9279 			 * comes back it will be there ready for us to add.
9280 			 * The new ire inherits the IRE_OFFSUBNET flags
9281 			 * and source address, if this was requested.
9282 			 * The ire_max_frag is atomically set under the
9283 			 * irebucket lock in ire_add_v[46]. Only in the
9284 			 * case of IRE_MARK_NOADD, we set it here itself.
9285 			 */
9286 			ire = ire_create_mp(
9287 			    (uchar_t *)&dst,		/* dest address */
9288 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9289 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9290 			    NULL,			/* gateway address */
9291 			    NULL,			/* no in_src_addr */
9292 			    (ire_marks & IRE_MARK_NOADD) ?
9293 				ipif->ipif_mtu : 0,	/* max_frag */
9294 			    NULL,			/* Fast path header */
9295 			    dst_ill->ill_rq,		/* recv-from queue */
9296 			    dst_ill->ill_wq,		/* send-to queue */
9297 			    IRE_CACHE,
9298 			    NULL,	/* let ire_nce_init figure res_mp out */
9299 			    src_ipif,
9300 			    NULL,
9301 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9302 			    (fire != NULL) ?		/* Parent handle */
9303 				fire->ire_phandle : 0,
9304 			    ihandle,			/* Interface handle */
9305 			    (fire != NULL) ?		/* flags if any */
9306 				(fire->ire_flags &
9307 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9308 			    (save_ire == NULL ? &ire_uinfo_null :
9309 				&save_ire->ire_uinfo),
9310 			    NULL,
9311 			    NULL);
9312 
9313 			if (save_ire != NULL) {
9314 				ire_refrele(save_ire);
9315 				save_ire = NULL;
9316 			}
9317 			if (ire == NULL)
9318 				break;
9319 
9320 			ire->ire_marks |= ire_marks;
9321 			/*
9322 			 * Construct message chain for the resolver of the
9323 			 * form:
9324 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9325 			 *
9326 			 * NOTE : ire will be added later when the response
9327 			 * comes back from ARP. If the response does not
9328 			 * come back, ARP frees the packet. For this reason,
9329 			 * we can't REFHOLD the bucket of save_ire to prevent
9330 			 * deletions. We may not be able to REFRELE the
9331 			 * bucket if the response never comes back.
9332 			 * Thus, before adding the ire, ire_add_v4 will make
9333 			 * sure that the interface route does not get deleted.
9334 			 * This is the only case unlike ip_newroute_v6,
9335 			 * ip_newroute_ipif_v6 where we can always prevent
9336 			 * deletions because ire_add_then_send is called after
9337 			 * creating the IRE.
9338 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9339 			 * does not add this IRE into the IRE CACHE.
9340 			 */
9341 			ASSERT(ire->ire_mp != NULL);
9342 			ire->ire_mp->b_cont = first_mp;
9343 			/* Have saved_mp handy, for cleanup if canput fails */
9344 			saved_mp = mp;
9345 			mp = copyb(res_mp);
9346 			if (mp == NULL) {
9347 				/* Prepare for cleanup */
9348 				mp = saved_mp; /* pkt */
9349 				ire_delete(ire); /* ire_mp */
9350 				ire = NULL;
9351 				if (copy_mp != NULL) {
9352 					MULTIRT_DEBUG_UNTAG(copy_mp);
9353 					freemsg(copy_mp);
9354 					copy_mp = NULL;
9355 				}
9356 				break;
9357 			}
9358 			linkb(mp, ire->ire_mp);
9359 
9360 			/*
9361 			 * Fill in the source and dest addrs for the resolver.
9362 			 * NOTE: this depends on memory layouts imposed by
9363 			 * ill_init().
9364 			 */
9365 			areq = (areq_t *)mp->b_rptr;
9366 			addrp = (ipaddr_t *)((char *)areq +
9367 			    areq->areq_sender_addr_offset);
9368 			*addrp = ire->ire_src_addr;
9369 			addrp = (ipaddr_t *)((char *)areq +
9370 			    areq->areq_target_addr_offset);
9371 			*addrp = dst;
9372 			/* Up to the resolver. */
9373 			if (canputnext(dst_ill->ill_rq) &&
9374 			    !(dst_ill->ill_arp_closing)) {
9375 				putnext(dst_ill->ill_rq, mp);
9376 				/*
9377 				 * The response will come back in ip_wput
9378 				 * with db_type IRE_DB_TYPE.
9379 				 */
9380 			} else {
9381 				mp->b_cont = NULL;
9382 				freeb(mp); /* areq */
9383 				ire_delete(ire); /* ire_mp */
9384 				saved_mp->b_next = NULL;
9385 				saved_mp->b_prev = NULL;
9386 				freemsg(first_mp); /* pkt */
9387 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9388 			}
9389 
9390 			if (fire != NULL) {
9391 				ire_refrele(fire);
9392 				fire = NULL;
9393 			}
9394 
9395 
9396 			/*
9397 			 * The resolution loop is re-entered if this was
9398 			 * requested through flags and we actually are
9399 			 * in a multirouting case.
9400 			 */
9401 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9402 				boolean_t need_resolve =
9403 				    ire_multirt_need_resolve(ipha_dst,
9404 					MBLK_GETLABEL(copy_mp));
9405 				if (!need_resolve) {
9406 					MULTIRT_DEBUG_UNTAG(copy_mp);
9407 					freemsg(copy_mp);
9408 					copy_mp = NULL;
9409 				} else {
9410 					/*
9411 					 * ipif_lookup_group() calls
9412 					 * ire_lookup_multi() that uses
9413 					 * ire_ftable_lookup() to find
9414 					 * an IRE_INTERFACE for the group.
9415 					 * In the multirt case,
9416 					 * ire_lookup_multi() then invokes
9417 					 * ire_multirt_lookup() to find
9418 					 * the next resolvable ire.
9419 					 * As a result, we obtain an new
9420 					 * interface, derived from the
9421 					 * next ire.
9422 					 */
9423 					ipif_refrele(ipif);
9424 					ipif = ipif_lookup_group(ipha_dst,
9425 					    zoneid);
9426 					if (ipif != NULL) {
9427 						mp = copy_mp;
9428 						copy_mp = NULL;
9429 						multirt_resolve_next = B_TRUE;
9430 						continue;
9431 					} else {
9432 						freemsg(copy_mp);
9433 					}
9434 				}
9435 			}
9436 			if (ipif != NULL)
9437 				ipif_refrele(ipif);
9438 			ill_refrele(dst_ill);
9439 			ipif_refrele(src_ipif);
9440 			return;
9441 		default:
9442 			break;
9443 		}
9444 	} while (multirt_resolve_next);
9445 
9446 err_ret:
9447 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9448 	if (fire != NULL)
9449 		ire_refrele(fire);
9450 	ipif_refrele(ipif);
9451 	/* Did this packet originate externally? */
9452 	if (dst_ill != NULL)
9453 		ill_refrele(dst_ill);
9454 	if (src_ipif != NULL)
9455 		ipif_refrele(src_ipif);
9456 	if (mp->b_prev || mp->b_next) {
9457 		mp->b_next = NULL;
9458 		mp->b_prev = NULL;
9459 	} else {
9460 		/*
9461 		 * Since ip_wput() isn't close to finished, we fill
9462 		 * in enough of the header for credible error reporting.
9463 		 */
9464 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9465 			/* Failed */
9466 			freemsg(first_mp);
9467 			if (ire != NULL)
9468 				ire_refrele(ire);
9469 			return;
9470 		}
9471 	}
9472 	/*
9473 	 * At this point we will have ire only if RTF_BLACKHOLE
9474 	 * or RTF_REJECT flags are set on the IRE. It will not
9475 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9476 	 */
9477 	if (ire != NULL) {
9478 		if (ire->ire_flags & RTF_BLACKHOLE) {
9479 			ire_refrele(ire);
9480 			freemsg(first_mp);
9481 			return;
9482 		}
9483 		ire_refrele(ire);
9484 	}
9485 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9486 }
9487 
9488 /* Name/Value Table Lookup Routine */
9489 char *
9490 ip_nv_lookup(nv_t *nv, int value)
9491 {
9492 	if (!nv)
9493 		return (NULL);
9494 	for (; nv->nv_name; nv++) {
9495 		if (nv->nv_value == value)
9496 			return (nv->nv_name);
9497 	}
9498 	return ("unknown");
9499 }
9500 
9501 /*
9502  * one day it can be patched to 1 from /etc/system for machines that have few
9503  * fast network interfaces feeding multiple cpus.
9504  */
9505 int ill_stream_putlocks = 0;
9506 
9507 /*
9508  * This is a module open, i.e. this is a control stream for access
9509  * to a DLPI device.  We allocate an ill_t as the instance data in
9510  * this case.
9511  */
9512 int
9513 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9514 {
9515 	uint32_t mem_cnt;
9516 	uint32_t cpu_cnt;
9517 	uint32_t min_cnt;
9518 	pgcnt_t mem_avail;
9519 	ill_t	*ill;
9520 	int	err;
9521 
9522 	/*
9523 	 * Prevent unprivileged processes from pushing IP so that
9524 	 * they can't send raw IP.
9525 	 */
9526 	if (secpolicy_net_rawaccess(credp) != 0)
9527 		return (EPERM);
9528 
9529 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9530 	q->q_ptr = WR(q)->q_ptr = ill;
9531 
9532 	/*
9533 	 * ill_init initializes the ill fields and then sends down
9534 	 * down a DL_INFO_REQ after calling qprocson.
9535 	 */
9536 	err = ill_init(q, ill);
9537 	if (err != 0) {
9538 		mi_free(ill);
9539 		q->q_ptr = NULL;
9540 		WR(q)->q_ptr = NULL;
9541 		return (err);
9542 	}
9543 
9544 	/* ill_init initializes the ipsq marking this thread as writer */
9545 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9546 	/* Wait for the DL_INFO_ACK */
9547 	mutex_enter(&ill->ill_lock);
9548 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9549 		/*
9550 		 * Return value of 0 indicates a pending signal.
9551 		 */
9552 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9553 		if (err == 0) {
9554 			mutex_exit(&ill->ill_lock);
9555 			(void) ip_close(q, 0);
9556 			return (EINTR);
9557 		}
9558 	}
9559 	mutex_exit(&ill->ill_lock);
9560 
9561 	/*
9562 	 * ip_rput_other could have set an error  in ill_error on
9563 	 * receipt of M_ERROR.
9564 	 */
9565 
9566 	err = ill->ill_error;
9567 	if (err != 0) {
9568 		(void) ip_close(q, 0);
9569 		return (err);
9570 	}
9571 
9572 	/*
9573 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9574 	 * size and the cpu speed of the machine. This is upper
9575 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9576 	 * and is lower bounded by the compile time value of
9577 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9578 	 * ip6_ire_max_bucket_cnt.
9579 	 */
9580 	mem_avail = kmem_avail();
9581 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9582 	    ip_cache_table_size / sizeof (ire_t);
9583 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9584 
9585 	min_cnt = MIN(cpu_cnt, mem_cnt);
9586 	if (min_cnt < ip_ire_min_bucket_cnt)
9587 		min_cnt = ip_ire_min_bucket_cnt;
9588 	if (ip_ire_max_bucket_cnt > min_cnt) {
9589 		ip_ire_max_bucket_cnt = min_cnt;
9590 	}
9591 
9592 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9593 	    ip6_cache_table_size / sizeof (ire_t);
9594 	min_cnt = MIN(cpu_cnt, mem_cnt);
9595 	if (min_cnt < ip6_ire_min_bucket_cnt)
9596 		min_cnt = ip6_ire_min_bucket_cnt;
9597 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9598 		ip6_ire_max_bucket_cnt = min_cnt;
9599 	}
9600 
9601 	ill->ill_credp = credp;
9602 	crhold(credp);
9603 
9604 	mutex_enter(&ip_mi_lock);
9605 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9606 	mutex_exit(&ip_mi_lock);
9607 	if (err) {
9608 		(void) ip_close(q, 0);
9609 		return (err);
9610 	}
9611 	return (0);
9612 }
9613 
9614 /* IP open routine. */
9615 int
9616 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9617 {
9618 	conn_t 		*connp;
9619 	major_t		maj;
9620 
9621 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9622 
9623 	/* Allow reopen. */
9624 	if (q->q_ptr != NULL)
9625 		return (0);
9626 
9627 	if (sflag & MODOPEN) {
9628 		/* This is a module open */
9629 		return (ip_modopen(q, devp, flag, sflag, credp));
9630 	}
9631 
9632 	/*
9633 	 * We are opening as a device. This is an IP client stream, and we
9634 	 * allocate an conn_t as the instance data.
9635 	 */
9636 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9637 	connp->conn_upq = q;
9638 	q->q_ptr = WR(q)->q_ptr = connp;
9639 
9640 	if (flag & SO_SOCKSTR)
9641 		connp->conn_flags |= IPCL_SOCKET;
9642 
9643 	/* Minor tells us which /dev entry was opened */
9644 	if (geteminor(*devp) == IPV6_MINOR) {
9645 		connp->conn_flags |= IPCL_ISV6;
9646 		connp->conn_af_isv6 = B_TRUE;
9647 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9648 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9649 	} else {
9650 		connp->conn_af_isv6 = B_FALSE;
9651 		connp->conn_pkt_isv6 = B_FALSE;
9652 	}
9653 
9654 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9655 		q->q_ptr = WR(q)->q_ptr = NULL;
9656 		CONN_DEC_REF(connp);
9657 		return (EBUSY);
9658 	}
9659 
9660 	maj = getemajor(*devp);
9661 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9662 
9663 	/*
9664 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9665 	 */
9666 	connp->conn_cred = credp;
9667 	crhold(connp->conn_cred);
9668 
9669 	/*
9670 	 * If the caller has the process-wide flag set, then default to MAC
9671 	 * exempt mode.  This allows read-down to unlabeled hosts.
9672 	 */
9673 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9674 		connp->conn_mac_exempt = B_TRUE;
9675 
9676 	connp->conn_zoneid = getzoneid();
9677 
9678 	/*
9679 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9680 	 * administrative ops.  In these cases, we just need a normal conn_t
9681 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9682 	 * an error will be returned.
9683 	 */
9684 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9685 		connp->conn_rq = q;
9686 		connp->conn_wq = WR(q);
9687 	} else {
9688 		connp->conn_ulp = IPPROTO_SCTP;
9689 		connp->conn_rq = connp->conn_wq = NULL;
9690 	}
9691 	/* Non-zero default values */
9692 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9693 
9694 	/*
9695 	 * Make the conn globally visible to walkers
9696 	 */
9697 	mutex_enter(&connp->conn_lock);
9698 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9699 	mutex_exit(&connp->conn_lock);
9700 	ASSERT(connp->conn_ref == 1);
9701 
9702 	qprocson(q);
9703 
9704 	return (0);
9705 }
9706 
9707 /*
9708  * Change q_qinfo based on the value of isv6.
9709  * This can not called on an ill queue.
9710  * Note that there is no race since either q_qinfo works for conn queues - it
9711  * is just an optimization to enter the best wput routine directly.
9712  */
9713 void
9714 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9715 {
9716 	ASSERT(q->q_flag & QREADR);
9717 	ASSERT(WR(q)->q_next == NULL);
9718 	ASSERT(q->q_ptr != NULL);
9719 
9720 	if (minor == IPV6_MINOR)  {
9721 		if (bump_mib)
9722 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9723 		q->q_qinfo = &rinit_ipv6;
9724 		WR(q)->q_qinfo = &winit_ipv6;
9725 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9726 	} else {
9727 		if (bump_mib)
9728 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9729 		q->q_qinfo = &iprinit;
9730 		WR(q)->q_qinfo = &ipwinit;
9731 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9732 	}
9733 
9734 }
9735 
9736 /*
9737  * See if IPsec needs loading because of the options in mp.
9738  */
9739 static boolean_t
9740 ipsec_opt_present(mblk_t *mp)
9741 {
9742 	uint8_t *optcp, *next_optcp, *opt_endcp;
9743 	struct opthdr *opt;
9744 	struct T_opthdr *topt;
9745 	int opthdr_len;
9746 	t_uscalar_t optname, optlevel;
9747 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9748 	ipsec_req_t *ipsr;
9749 
9750 	/*
9751 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9752 	 * return TRUE.
9753 	 */
9754 
9755 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9756 	opt_endcp = optcp + tor->OPT_length;
9757 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9758 		opthdr_len = sizeof (struct T_opthdr);
9759 	} else {		/* O_OPTMGMT_REQ */
9760 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9761 		opthdr_len = sizeof (struct opthdr);
9762 	}
9763 	for (; optcp < opt_endcp; optcp = next_optcp) {
9764 		if (optcp + opthdr_len > opt_endcp)
9765 			return (B_FALSE);	/* Not enough option header. */
9766 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9767 			topt = (struct T_opthdr *)optcp;
9768 			optlevel = topt->level;
9769 			optname = topt->name;
9770 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9771 		} else {
9772 			opt = (struct opthdr *)optcp;
9773 			optlevel = opt->level;
9774 			optname = opt->name;
9775 			next_optcp = optcp + opthdr_len +
9776 			    _TPI_ALIGN_OPT(opt->len);
9777 		}
9778 		if ((next_optcp < optcp) || /* wraparound pointer space */
9779 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9780 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9781 			return (B_FALSE); /* bad option buffer */
9782 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9783 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9784 			/*
9785 			 * Check to see if it's an all-bypass or all-zeroes
9786 			 * IPsec request.  Don't bother loading IPsec if
9787 			 * the socket doesn't want to use it.  (A good example
9788 			 * is a bypass request.)
9789 			 *
9790 			 * Basically, if any of the non-NEVER bits are set,
9791 			 * load IPsec.
9792 			 */
9793 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9794 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9795 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9796 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9797 			    != 0)
9798 				return (B_TRUE);
9799 		}
9800 	}
9801 	return (B_FALSE);
9802 }
9803 
9804 /*
9805  * If conn is is waiting for ipsec to finish loading, kick it.
9806  */
9807 /* ARGSUSED */
9808 static void
9809 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9810 {
9811 	t_scalar_t	optreq_prim;
9812 	mblk_t		*mp;
9813 	cred_t		*cr;
9814 	int		err = 0;
9815 
9816 	/*
9817 	 * This function is called, after ipsec loading is complete.
9818 	 * Since IP checks exclusively and atomically (i.e it prevents
9819 	 * ipsec load from completing until ip_optcom_req completes)
9820 	 * whether ipsec load is complete, there cannot be a race with IP
9821 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9822 	 */
9823 	mutex_enter(&connp->conn_lock);
9824 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9825 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9826 		mp = connp->conn_ipsec_opt_mp;
9827 		connp->conn_ipsec_opt_mp = NULL;
9828 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9829 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9830 		mutex_exit(&connp->conn_lock);
9831 
9832 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9833 
9834 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9835 		if (optreq_prim == T_OPTMGMT_REQ) {
9836 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9837 			    &ip_opt_obj);
9838 		} else {
9839 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9840 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9841 			    &ip_opt_obj);
9842 		}
9843 		if (err != EINPROGRESS)
9844 			CONN_OPER_PENDING_DONE(connp);
9845 		return;
9846 	}
9847 	mutex_exit(&connp->conn_lock);
9848 }
9849 
9850 /*
9851  * Called from the ipsec_loader thread, outside any perimeter, to tell
9852  * ip qenable any of the queues waiting for the ipsec loader to
9853  * complete.
9854  *
9855  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9856  * are done with this lock held, so it's guaranteed that none of the
9857  * links will change along the way.
9858  */
9859 void
9860 ip_ipsec_load_complete()
9861 {
9862 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9863 }
9864 
9865 /*
9866  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9867  * determines the grp on which it has to become exclusive, queues the mp
9868  * and sq draining restarts the optmgmt
9869  */
9870 static boolean_t
9871 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9872 {
9873 	conn_t *connp;
9874 
9875 	/*
9876 	 * Take IPsec requests and treat them special.
9877 	 */
9878 	if (ipsec_opt_present(mp)) {
9879 		/* First check if IPsec is loaded. */
9880 		mutex_enter(&ipsec_loader_lock);
9881 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9882 			mutex_exit(&ipsec_loader_lock);
9883 			return (B_FALSE);
9884 		}
9885 		connp = Q_TO_CONN(q);
9886 		mutex_enter(&connp->conn_lock);
9887 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9888 
9889 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9890 		connp->conn_ipsec_opt_mp = mp;
9891 		mutex_exit(&connp->conn_lock);
9892 		mutex_exit(&ipsec_loader_lock);
9893 
9894 		ipsec_loader_loadnow();
9895 		return (B_TRUE);
9896 	}
9897 	return (B_FALSE);
9898 }
9899 
9900 /*
9901  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9902  * all of them are copied to the conn_t. If the req is "zero", the policy is
9903  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9904  * fields.
9905  * We keep only the latest setting of the policy and thus policy setting
9906  * is not incremental/cumulative.
9907  *
9908  * Requests to set policies with multiple alternative actions will
9909  * go through a different API.
9910  */
9911 int
9912 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9913 {
9914 	uint_t ah_req = 0;
9915 	uint_t esp_req = 0;
9916 	uint_t se_req = 0;
9917 	ipsec_selkey_t sel;
9918 	ipsec_act_t *actp = NULL;
9919 	uint_t nact;
9920 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9921 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9922 	ipsec_policy_root_t *pr;
9923 	ipsec_policy_head_t *ph;
9924 	int fam;
9925 	boolean_t is_pol_reset;
9926 	int error = 0;
9927 
9928 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9929 
9930 	/*
9931 	 * The IP_SEC_OPT option does not allow variable length parameters,
9932 	 * hence a request cannot be NULL.
9933 	 */
9934 	if (req == NULL)
9935 		return (EINVAL);
9936 
9937 	ah_req = req->ipsr_ah_req;
9938 	esp_req = req->ipsr_esp_req;
9939 	se_req = req->ipsr_self_encap_req;
9940 
9941 	/*
9942 	 * Are we dealing with a request to reset the policy (i.e.
9943 	 * zero requests).
9944 	 */
9945 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9946 	    (esp_req & REQ_MASK) == 0 &&
9947 	    (se_req & REQ_MASK) == 0);
9948 
9949 	if (!is_pol_reset) {
9950 		/*
9951 		 * If we couldn't load IPsec, fail with "protocol
9952 		 * not supported".
9953 		 * IPsec may not have been loaded for a request with zero
9954 		 * policies, so we don't fail in this case.
9955 		 */
9956 		mutex_enter(&ipsec_loader_lock);
9957 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9958 			mutex_exit(&ipsec_loader_lock);
9959 			return (EPROTONOSUPPORT);
9960 		}
9961 		mutex_exit(&ipsec_loader_lock);
9962 
9963 		/*
9964 		 * Test for valid requests. Invalid algorithms
9965 		 * need to be tested by IPSEC code because new
9966 		 * algorithms can be added dynamically.
9967 		 */
9968 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9969 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9970 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9971 			return (EINVAL);
9972 		}
9973 
9974 		/*
9975 		 * Only privileged users can issue these
9976 		 * requests.
9977 		 */
9978 		if (((ah_req & IPSEC_PREF_NEVER) ||
9979 		    (esp_req & IPSEC_PREF_NEVER) ||
9980 		    (se_req & IPSEC_PREF_NEVER)) &&
9981 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9982 			return (EPERM);
9983 		}
9984 
9985 		/*
9986 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9987 		 * are mutually exclusive.
9988 		 */
9989 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9990 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9991 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9992 			/* Both of them are set */
9993 			return (EINVAL);
9994 		}
9995 	}
9996 
9997 	mutex_enter(&connp->conn_lock);
9998 
9999 	/*
10000 	 * If we have already cached policies in ip_bind_connected*(), don't
10001 	 * let them change now. We cache policies for connections
10002 	 * whose src,dst [addr, port] is known.  The exception to this is
10003 	 * tunnels.  Tunnels are allowed to change policies after having
10004 	 * become fully bound.
10005 	 */
10006 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
10007 		mutex_exit(&connp->conn_lock);
10008 		return (EINVAL);
10009 	}
10010 
10011 	/*
10012 	 * We have a zero policies, reset the connection policy if already
10013 	 * set. This will cause the connection to inherit the
10014 	 * global policy, if any.
10015 	 */
10016 	if (is_pol_reset) {
10017 		if (connp->conn_policy != NULL) {
10018 			IPPH_REFRELE(connp->conn_policy);
10019 			connp->conn_policy = NULL;
10020 		}
10021 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10022 		connp->conn_in_enforce_policy = B_FALSE;
10023 		connp->conn_out_enforce_policy = B_FALSE;
10024 		mutex_exit(&connp->conn_lock);
10025 		return (0);
10026 	}
10027 
10028 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
10029 	if (ph == NULL)
10030 		goto enomem;
10031 
10032 	ipsec_actvec_from_req(req, &actp, &nact);
10033 	if (actp == NULL)
10034 		goto enomem;
10035 
10036 	/*
10037 	 * Always allocate IPv4 policy entries, since they can also
10038 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10039 	 */
10040 	bzero(&sel, sizeof (sel));
10041 	sel.ipsl_valid = IPSL_IPV4;
10042 
10043 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
10044 	if (pin4 == NULL)
10045 		goto enomem;
10046 
10047 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
10048 	if (pout4 == NULL)
10049 		goto enomem;
10050 
10051 	if (connp->conn_pkt_isv6) {
10052 		/*
10053 		 * We're looking at a v6 socket, also allocate the
10054 		 * v6-specific entries...
10055 		 */
10056 		sel.ipsl_valid = IPSL_IPV6;
10057 		pin6 = ipsec_policy_create(&sel, actp, nact,
10058 		    IPSEC_PRIO_SOCKET);
10059 		if (pin6 == NULL)
10060 			goto enomem;
10061 
10062 		pout6 = ipsec_policy_create(&sel, actp, nact,
10063 		    IPSEC_PRIO_SOCKET);
10064 		if (pout6 == NULL)
10065 			goto enomem;
10066 
10067 		/*
10068 		 * .. and file them away in the right place.
10069 		 */
10070 		fam = IPSEC_AF_V6;
10071 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10072 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10073 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10074 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10075 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10076 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10077 	}
10078 
10079 	ipsec_actvec_free(actp, nact);
10080 
10081 	/*
10082 	 * File the v4 policies.
10083 	 */
10084 	fam = IPSEC_AF_V4;
10085 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10086 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10087 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10088 
10089 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10090 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10091 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10092 
10093 	/*
10094 	 * If the requests need security, set enforce_policy.
10095 	 * If the requests are IPSEC_PREF_NEVER, one should
10096 	 * still set conn_out_enforce_policy so that an ipsec_out
10097 	 * gets attached in ip_wput. This is needed so that
10098 	 * for connections that we don't cache policy in ip_bind,
10099 	 * if global policy matches in ip_wput_attach_policy, we
10100 	 * don't wrongly inherit global policy. Similarly, we need
10101 	 * to set conn_in_enforce_policy also so that we don't verify
10102 	 * policy wrongly.
10103 	 */
10104 	if ((ah_req & REQ_MASK) != 0 ||
10105 	    (esp_req & REQ_MASK) != 0 ||
10106 	    (se_req & REQ_MASK) != 0) {
10107 		connp->conn_in_enforce_policy = B_TRUE;
10108 		connp->conn_out_enforce_policy = B_TRUE;
10109 		connp->conn_flags |= IPCL_CHECK_POLICY;
10110 	}
10111 
10112 	/*
10113 	 * Tunnels are allowed to set policy after having been fully bound.
10114 	 * If that's the case, cache policy here.
10115 	 */
10116 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
10117 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
10118 
10119 	mutex_exit(&connp->conn_lock);
10120 	return (error);
10121 #undef REQ_MASK
10122 
10123 	/*
10124 	 * Common memory-allocation-failure exit path.
10125 	 */
10126 enomem:
10127 	mutex_exit(&connp->conn_lock);
10128 	if (actp != NULL)
10129 		ipsec_actvec_free(actp, nact);
10130 	if (pin4 != NULL)
10131 		IPPOL_REFRELE(pin4);
10132 	if (pout4 != NULL)
10133 		IPPOL_REFRELE(pout4);
10134 	if (pin6 != NULL)
10135 		IPPOL_REFRELE(pin6);
10136 	if (pout6 != NULL)
10137 		IPPOL_REFRELE(pout6);
10138 	return (ENOMEM);
10139 }
10140 
10141 /*
10142  * Only for options that pass in an IP addr. Currently only V4 options
10143  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10144  * So this function assumes level is IPPROTO_IP
10145  */
10146 int
10147 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10148     mblk_t *first_mp)
10149 {
10150 	ipif_t *ipif = NULL;
10151 	int error;
10152 	ill_t *ill;
10153 	int zoneid;
10154 
10155 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10156 
10157 	if (addr != INADDR_ANY || checkonly) {
10158 		ASSERT(connp != NULL);
10159 		zoneid = IPCL_ZONEID(connp);
10160 		if (option == IP_NEXTHOP) {
10161 			ipif = ipif_lookup_onlink_addr(addr,
10162 			    connp->conn_zoneid);
10163 		} else {
10164 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10165 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10166 			    &error);
10167 		}
10168 		if (ipif == NULL) {
10169 			if (error == EINPROGRESS)
10170 				return (error);
10171 			else if ((option == IP_MULTICAST_IF) ||
10172 			    (option == IP_NEXTHOP))
10173 				return (EHOSTUNREACH);
10174 			else
10175 				return (EINVAL);
10176 		} else if (checkonly) {
10177 			if (option == IP_MULTICAST_IF) {
10178 				ill = ipif->ipif_ill;
10179 				/* not supported by the virtual network iface */
10180 				if (IS_VNI(ill)) {
10181 					ipif_refrele(ipif);
10182 					return (EINVAL);
10183 				}
10184 			}
10185 			ipif_refrele(ipif);
10186 			return (0);
10187 		}
10188 		ill = ipif->ipif_ill;
10189 		mutex_enter(&connp->conn_lock);
10190 		mutex_enter(&ill->ill_lock);
10191 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10192 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10193 			mutex_exit(&ill->ill_lock);
10194 			mutex_exit(&connp->conn_lock);
10195 			ipif_refrele(ipif);
10196 			return (option == IP_MULTICAST_IF ?
10197 			    EHOSTUNREACH : EINVAL);
10198 		}
10199 	} else {
10200 		mutex_enter(&connp->conn_lock);
10201 	}
10202 
10203 	/* None of the options below are supported on the VNI */
10204 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10205 		mutex_exit(&ill->ill_lock);
10206 		mutex_exit(&connp->conn_lock);
10207 		ipif_refrele(ipif);
10208 		return (EINVAL);
10209 	}
10210 
10211 	switch (option) {
10212 	case IP_DONTFAILOVER_IF:
10213 		/*
10214 		 * This option is used by in.mpathd to ensure
10215 		 * that IPMP probe packets only go out on the
10216 		 * test interfaces. in.mpathd sets this option
10217 		 * on the non-failover interfaces.
10218 		 * For backward compatibility, this option
10219 		 * implicitly sets IP_MULTICAST_IF, as used
10220 		 * be done in bind(), so that ip_wput gets
10221 		 * this ipif to send mcast packets.
10222 		 */
10223 		if (ipif != NULL) {
10224 			ASSERT(addr != INADDR_ANY);
10225 			connp->conn_nofailover_ill = ipif->ipif_ill;
10226 			connp->conn_multicast_ipif = ipif;
10227 		} else {
10228 			ASSERT(addr == INADDR_ANY);
10229 			connp->conn_nofailover_ill = NULL;
10230 			connp->conn_multicast_ipif = NULL;
10231 		}
10232 		break;
10233 
10234 	case IP_MULTICAST_IF:
10235 		connp->conn_multicast_ipif = ipif;
10236 		break;
10237 	case IP_NEXTHOP:
10238 		connp->conn_nexthop_v4 = addr;
10239 		connp->conn_nexthop_set = B_TRUE;
10240 		break;
10241 	}
10242 
10243 	if (ipif != NULL) {
10244 		mutex_exit(&ill->ill_lock);
10245 		mutex_exit(&connp->conn_lock);
10246 		ipif_refrele(ipif);
10247 		return (0);
10248 	}
10249 	mutex_exit(&connp->conn_lock);
10250 	/* We succeded in cleared the option */
10251 	return (0);
10252 }
10253 
10254 /*
10255  * For options that pass in an ifindex specifying the ill. V6 options always
10256  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10257  */
10258 int
10259 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10260     int level, int option, mblk_t *first_mp)
10261 {
10262 	ill_t *ill = NULL;
10263 	int error = 0;
10264 
10265 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10266 	if (ifindex != 0) {
10267 		ASSERT(connp != NULL);
10268 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10269 		    first_mp, ip_restart_optmgmt, &error);
10270 		if (ill != NULL) {
10271 			if (checkonly) {
10272 				/* not supported by the virtual network iface */
10273 				if (IS_VNI(ill)) {
10274 					ill_refrele(ill);
10275 					return (EINVAL);
10276 				}
10277 				ill_refrele(ill);
10278 				return (0);
10279 			}
10280 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10281 			    0, NULL)) {
10282 				ill_refrele(ill);
10283 				ill = NULL;
10284 				mutex_enter(&connp->conn_lock);
10285 				goto setit;
10286 			}
10287 			mutex_enter(&connp->conn_lock);
10288 			mutex_enter(&ill->ill_lock);
10289 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10290 				mutex_exit(&ill->ill_lock);
10291 				mutex_exit(&connp->conn_lock);
10292 				ill_refrele(ill);
10293 				ill = NULL;
10294 				mutex_enter(&connp->conn_lock);
10295 			}
10296 			goto setit;
10297 		} else if (error == EINPROGRESS) {
10298 			return (error);
10299 		} else {
10300 			error = 0;
10301 		}
10302 	}
10303 	mutex_enter(&connp->conn_lock);
10304 setit:
10305 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10306 
10307 	/*
10308 	 * The options below assume that the ILL (if any) transmits and/or
10309 	 * receives traffic. Neither of which is true for the virtual network
10310 	 * interface, so fail setting these on a VNI.
10311 	 */
10312 	if (IS_VNI(ill)) {
10313 		ASSERT(ill != NULL);
10314 		mutex_exit(&ill->ill_lock);
10315 		mutex_exit(&connp->conn_lock);
10316 		ill_refrele(ill);
10317 		return (EINVAL);
10318 	}
10319 
10320 	if (level == IPPROTO_IP) {
10321 		switch (option) {
10322 		case IP_BOUND_IF:
10323 			connp->conn_incoming_ill = ill;
10324 			connp->conn_outgoing_ill = ill;
10325 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10326 			    0 : ifindex;
10327 			break;
10328 
10329 		case IP_XMIT_IF:
10330 			/*
10331 			 * Similar to IP_BOUND_IF, but this only
10332 			 * determines the outgoing interface for
10333 			 * unicast packets. Also no IRE_CACHE entry
10334 			 * is added for the destination of the
10335 			 * outgoing packets. This feature is needed
10336 			 * for mobile IP.
10337 			 */
10338 			connp->conn_xmit_if_ill = ill;
10339 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10340 			    0 : ifindex;
10341 			break;
10342 
10343 		case IP_MULTICAST_IF:
10344 			/*
10345 			 * This option is an internal special. The socket
10346 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10347 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10348 			 * specifies an ifindex and we try first on V6 ill's.
10349 			 * If we don't find one, we they try using on v4 ill's
10350 			 * intenally and we come here.
10351 			 */
10352 			if (!checkonly && ill != NULL) {
10353 				ipif_t	*ipif;
10354 				ipif = ill->ill_ipif;
10355 
10356 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10357 					mutex_exit(&ill->ill_lock);
10358 					mutex_exit(&connp->conn_lock);
10359 					ill_refrele(ill);
10360 					ill = NULL;
10361 					mutex_enter(&connp->conn_lock);
10362 				} else {
10363 					connp->conn_multicast_ipif = ipif;
10364 				}
10365 			}
10366 			break;
10367 		}
10368 	} else {
10369 		switch (option) {
10370 		case IPV6_BOUND_IF:
10371 			connp->conn_incoming_ill = ill;
10372 			connp->conn_outgoing_ill = ill;
10373 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10374 			    0 : ifindex;
10375 			break;
10376 
10377 		case IPV6_BOUND_PIF:
10378 			/*
10379 			 * Limit all transmit to this ill.
10380 			 * Unlike IPV6_BOUND_IF, using this option
10381 			 * prevents load spreading and failover from
10382 			 * happening when the interface is part of the
10383 			 * group. That's why we don't need to remember
10384 			 * the ifindex in orig_bound_ifindex as in
10385 			 * IPV6_BOUND_IF.
10386 			 */
10387 			connp->conn_outgoing_pill = ill;
10388 			break;
10389 
10390 		case IPV6_DONTFAILOVER_IF:
10391 			/*
10392 			 * This option is used by in.mpathd to ensure
10393 			 * that IPMP probe packets only go out on the
10394 			 * test interfaces. in.mpathd sets this option
10395 			 * on the non-failover interfaces.
10396 			 */
10397 			connp->conn_nofailover_ill = ill;
10398 			/*
10399 			 * For backward compatibility, this option
10400 			 * implicitly sets ip_multicast_ill as used in
10401 			 * IP_MULTICAST_IF so that ip_wput gets
10402 			 * this ipif to send mcast packets.
10403 			 */
10404 			connp->conn_multicast_ill = ill;
10405 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10406 			    0 : ifindex;
10407 			break;
10408 
10409 		case IPV6_MULTICAST_IF:
10410 			/*
10411 			 * Set conn_multicast_ill to be the IPv6 ill.
10412 			 * Set conn_multicast_ipif to be an IPv4 ipif
10413 			 * for ifindex to make IPv4 mapped addresses
10414 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10415 			 * Even if no IPv6 ill exists for the ifindex
10416 			 * we need to check for an IPv4 ifindex in order
10417 			 * for this to work with mapped addresses. In that
10418 			 * case only set conn_multicast_ipif.
10419 			 */
10420 			if (!checkonly) {
10421 				if (ifindex == 0) {
10422 					connp->conn_multicast_ill = NULL;
10423 					connp->conn_orig_multicast_ifindex = 0;
10424 					connp->conn_multicast_ipif = NULL;
10425 				} else if (ill != NULL) {
10426 					connp->conn_multicast_ill = ill;
10427 					connp->conn_orig_multicast_ifindex =
10428 					    ifindex;
10429 				}
10430 			}
10431 			break;
10432 		}
10433 	}
10434 
10435 	if (ill != NULL) {
10436 		mutex_exit(&ill->ill_lock);
10437 		mutex_exit(&connp->conn_lock);
10438 		ill_refrele(ill);
10439 		return (0);
10440 	}
10441 	mutex_exit(&connp->conn_lock);
10442 	/*
10443 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10444 	 * locate the ill and could not set the option (ifindex != 0)
10445 	 */
10446 	return (ifindex == 0 ? 0 : EINVAL);
10447 }
10448 
10449 /* This routine sets socket options. */
10450 /* ARGSUSED */
10451 int
10452 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10453     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10454     void *dummy, cred_t *cr, mblk_t *first_mp)
10455 {
10456 	int		*i1 = (int *)invalp;
10457 	conn_t		*connp = Q_TO_CONN(q);
10458 	int		error = 0;
10459 	boolean_t	checkonly;
10460 	ire_t		*ire;
10461 	boolean_t	found;
10462 
10463 	switch (optset_context) {
10464 
10465 	case SETFN_OPTCOM_CHECKONLY:
10466 		checkonly = B_TRUE;
10467 		/*
10468 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10469 		 * inlen != 0 implies value supplied and
10470 		 * 	we have to "pretend" to set it.
10471 		 * inlen == 0 implies that there is no
10472 		 * 	value part in T_CHECK request and just validation
10473 		 * done elsewhere should be enough, we just return here.
10474 		 */
10475 		if (inlen == 0) {
10476 			*outlenp = 0;
10477 			return (0);
10478 		}
10479 		break;
10480 	case SETFN_OPTCOM_NEGOTIATE:
10481 	case SETFN_UD_NEGOTIATE:
10482 	case SETFN_CONN_NEGOTIATE:
10483 		checkonly = B_FALSE;
10484 		break;
10485 	default:
10486 		/*
10487 		 * We should never get here
10488 		 */
10489 		*outlenp = 0;
10490 		return (EINVAL);
10491 	}
10492 
10493 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10494 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10495 
10496 	/*
10497 	 * For fixed length options, no sanity check
10498 	 * of passed in length is done. It is assumed *_optcom_req()
10499 	 * routines do the right thing.
10500 	 */
10501 
10502 	switch (level) {
10503 	case SOL_SOCKET:
10504 		/*
10505 		 * conn_lock protects the bitfields, and is used to
10506 		 * set the fields atomically.
10507 		 */
10508 		switch (name) {
10509 		case SO_BROADCAST:
10510 			if (!checkonly) {
10511 				/* TODO: use value someplace? */
10512 				mutex_enter(&connp->conn_lock);
10513 				connp->conn_broadcast = *i1 ? 1 : 0;
10514 				mutex_exit(&connp->conn_lock);
10515 			}
10516 			break;	/* goto sizeof (int) option return */
10517 		case SO_USELOOPBACK:
10518 			if (!checkonly) {
10519 				/* TODO: use value someplace? */
10520 				mutex_enter(&connp->conn_lock);
10521 				connp->conn_loopback = *i1 ? 1 : 0;
10522 				mutex_exit(&connp->conn_lock);
10523 			}
10524 			break;	/* goto sizeof (int) option return */
10525 		case SO_DONTROUTE:
10526 			if (!checkonly) {
10527 				mutex_enter(&connp->conn_lock);
10528 				connp->conn_dontroute = *i1 ? 1 : 0;
10529 				mutex_exit(&connp->conn_lock);
10530 			}
10531 			break;	/* goto sizeof (int) option return */
10532 		case SO_REUSEADDR:
10533 			if (!checkonly) {
10534 				mutex_enter(&connp->conn_lock);
10535 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10536 				mutex_exit(&connp->conn_lock);
10537 			}
10538 			break;	/* goto sizeof (int) option return */
10539 		case SO_PROTOTYPE:
10540 			if (!checkonly) {
10541 				mutex_enter(&connp->conn_lock);
10542 				connp->conn_proto = *i1;
10543 				mutex_exit(&connp->conn_lock);
10544 			}
10545 			break;	/* goto sizeof (int) option return */
10546 		case SO_ALLZONES:
10547 			if (!checkonly) {
10548 				mutex_enter(&connp->conn_lock);
10549 				if (IPCL_IS_BOUND(connp)) {
10550 					mutex_exit(&connp->conn_lock);
10551 					return (EINVAL);
10552 				}
10553 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10554 				mutex_exit(&connp->conn_lock);
10555 			}
10556 			break;	/* goto sizeof (int) option return */
10557 		case SO_ANON_MLP:
10558 			if (!checkonly) {
10559 				mutex_enter(&connp->conn_lock);
10560 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10561 				mutex_exit(&connp->conn_lock);
10562 			}
10563 			break;	/* goto sizeof (int) option return */
10564 		case SO_MAC_EXEMPT:
10565 			if (secpolicy_net_mac_aware(cr) != 0 ||
10566 			    IPCL_IS_BOUND(connp))
10567 				return (EACCES);
10568 			if (!checkonly) {
10569 				mutex_enter(&connp->conn_lock);
10570 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10571 				mutex_exit(&connp->conn_lock);
10572 			}
10573 			break;	/* goto sizeof (int) option return */
10574 		default:
10575 			/*
10576 			 * "soft" error (negative)
10577 			 * option not handled at this level
10578 			 * Note: Do not modify *outlenp
10579 			 */
10580 			return (-EINVAL);
10581 		}
10582 		break;
10583 	case IPPROTO_IP:
10584 		switch (name) {
10585 		case IP_NEXTHOP:
10586 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10587 				return (EPERM);
10588 			/* FALLTHRU */
10589 		case IP_MULTICAST_IF:
10590 		case IP_DONTFAILOVER_IF: {
10591 			ipaddr_t addr = *i1;
10592 
10593 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10594 			    first_mp);
10595 			if (error != 0)
10596 				return (error);
10597 			break;	/* goto sizeof (int) option return */
10598 		}
10599 
10600 		case IP_MULTICAST_TTL:
10601 			/* Recorded in transport above IP */
10602 			*outvalp = *invalp;
10603 			*outlenp = sizeof (uchar_t);
10604 			return (0);
10605 		case IP_MULTICAST_LOOP:
10606 			if (!checkonly) {
10607 				mutex_enter(&connp->conn_lock);
10608 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10609 				mutex_exit(&connp->conn_lock);
10610 			}
10611 			*outvalp = *invalp;
10612 			*outlenp = sizeof (uchar_t);
10613 			return (0);
10614 		case IP_ADD_MEMBERSHIP:
10615 		case MCAST_JOIN_GROUP:
10616 		case IP_DROP_MEMBERSHIP:
10617 		case MCAST_LEAVE_GROUP: {
10618 			struct ip_mreq *mreqp;
10619 			struct group_req *greqp;
10620 			ire_t *ire;
10621 			boolean_t done = B_FALSE;
10622 			ipaddr_t group, ifaddr;
10623 			struct sockaddr_in *sin;
10624 			uint32_t *ifindexp;
10625 			boolean_t mcast_opt = B_TRUE;
10626 			mcast_record_t fmode;
10627 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10628 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10629 
10630 			switch (name) {
10631 			case IP_ADD_MEMBERSHIP:
10632 				mcast_opt = B_FALSE;
10633 				/* FALLTHRU */
10634 			case MCAST_JOIN_GROUP:
10635 				fmode = MODE_IS_EXCLUDE;
10636 				optfn = ip_opt_add_group;
10637 				break;
10638 
10639 			case IP_DROP_MEMBERSHIP:
10640 				mcast_opt = B_FALSE;
10641 				/* FALLTHRU */
10642 			case MCAST_LEAVE_GROUP:
10643 				fmode = MODE_IS_INCLUDE;
10644 				optfn = ip_opt_delete_group;
10645 				break;
10646 			}
10647 
10648 			if (mcast_opt) {
10649 				greqp = (struct group_req *)i1;
10650 				sin = (struct sockaddr_in *)&greqp->gr_group;
10651 				if (sin->sin_family != AF_INET) {
10652 					*outlenp = 0;
10653 					return (ENOPROTOOPT);
10654 				}
10655 				group = (ipaddr_t)sin->sin_addr.s_addr;
10656 				ifaddr = INADDR_ANY;
10657 				ifindexp = &greqp->gr_interface;
10658 			} else {
10659 				mreqp = (struct ip_mreq *)i1;
10660 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10661 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10662 				ifindexp = NULL;
10663 			}
10664 
10665 			/*
10666 			 * In the multirouting case, we need to replicate
10667 			 * the request on all interfaces that will take part
10668 			 * in replication.  We do so because multirouting is
10669 			 * reflective, thus we will probably receive multi-
10670 			 * casts on those interfaces.
10671 			 * The ip_multirt_apply_membership() succeeds if the
10672 			 * operation succeeds on at least one interface.
10673 			 */
10674 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10675 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10676 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10677 			if (ire != NULL) {
10678 				if (ire->ire_flags & RTF_MULTIRT) {
10679 					error = ip_multirt_apply_membership(
10680 					    optfn, ire, connp, checkonly, group,
10681 					    fmode, INADDR_ANY, first_mp);
10682 					done = B_TRUE;
10683 				}
10684 				ire_refrele(ire);
10685 			}
10686 			if (!done) {
10687 				error = optfn(connp, checkonly, group, ifaddr,
10688 				    ifindexp, fmode, INADDR_ANY, first_mp);
10689 			}
10690 			if (error) {
10691 				/*
10692 				 * EINPROGRESS is a soft error, needs retry
10693 				 * so don't make *outlenp zero.
10694 				 */
10695 				if (error != EINPROGRESS)
10696 					*outlenp = 0;
10697 				return (error);
10698 			}
10699 			/* OK return - copy input buffer into output buffer */
10700 			if (invalp != outvalp) {
10701 				/* don't trust bcopy for identical src/dst */
10702 				bcopy(invalp, outvalp, inlen);
10703 			}
10704 			*outlenp = inlen;
10705 			return (0);
10706 		}
10707 		case IP_BLOCK_SOURCE:
10708 		case IP_UNBLOCK_SOURCE:
10709 		case IP_ADD_SOURCE_MEMBERSHIP:
10710 		case IP_DROP_SOURCE_MEMBERSHIP:
10711 		case MCAST_BLOCK_SOURCE:
10712 		case MCAST_UNBLOCK_SOURCE:
10713 		case MCAST_JOIN_SOURCE_GROUP:
10714 		case MCAST_LEAVE_SOURCE_GROUP: {
10715 			struct ip_mreq_source *imreqp;
10716 			struct group_source_req *gsreqp;
10717 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10718 			uint32_t ifindex = 0;
10719 			mcast_record_t fmode;
10720 			struct sockaddr_in *sin;
10721 			ire_t *ire;
10722 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10723 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10724 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10725 
10726 			switch (name) {
10727 			case IP_BLOCK_SOURCE:
10728 				mcast_opt = B_FALSE;
10729 				/* FALLTHRU */
10730 			case MCAST_BLOCK_SOURCE:
10731 				fmode = MODE_IS_EXCLUDE;
10732 				optfn = ip_opt_add_group;
10733 				break;
10734 
10735 			case IP_UNBLOCK_SOURCE:
10736 				mcast_opt = B_FALSE;
10737 				/* FALLTHRU */
10738 			case MCAST_UNBLOCK_SOURCE:
10739 				fmode = MODE_IS_EXCLUDE;
10740 				optfn = ip_opt_delete_group;
10741 				break;
10742 
10743 			case IP_ADD_SOURCE_MEMBERSHIP:
10744 				mcast_opt = B_FALSE;
10745 				/* FALLTHRU */
10746 			case MCAST_JOIN_SOURCE_GROUP:
10747 				fmode = MODE_IS_INCLUDE;
10748 				optfn = ip_opt_add_group;
10749 				break;
10750 
10751 			case IP_DROP_SOURCE_MEMBERSHIP:
10752 				mcast_opt = B_FALSE;
10753 				/* FALLTHRU */
10754 			case MCAST_LEAVE_SOURCE_GROUP:
10755 				fmode = MODE_IS_INCLUDE;
10756 				optfn = ip_opt_delete_group;
10757 				break;
10758 			}
10759 
10760 			if (mcast_opt) {
10761 				gsreqp = (struct group_source_req *)i1;
10762 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10763 					*outlenp = 0;
10764 					return (ENOPROTOOPT);
10765 				}
10766 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10767 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10768 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10769 				src = (ipaddr_t)sin->sin_addr.s_addr;
10770 				ifindex = gsreqp->gsr_interface;
10771 			} else {
10772 				imreqp = (struct ip_mreq_source *)i1;
10773 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10774 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10775 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10776 			}
10777 
10778 			/*
10779 			 * In the multirouting case, we need to replicate
10780 			 * the request as noted in the mcast cases above.
10781 			 */
10782 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10783 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10784 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10785 			if (ire != NULL) {
10786 				if (ire->ire_flags & RTF_MULTIRT) {
10787 					error = ip_multirt_apply_membership(
10788 					    optfn, ire, connp, checkonly, grp,
10789 					    fmode, src, first_mp);
10790 					done = B_TRUE;
10791 				}
10792 				ire_refrele(ire);
10793 			}
10794 			if (!done) {
10795 				error = optfn(connp, checkonly, grp, ifaddr,
10796 				    &ifindex, fmode, src, first_mp);
10797 			}
10798 			if (error != 0) {
10799 				/*
10800 				 * EINPROGRESS is a soft error, needs retry
10801 				 * so don't make *outlenp zero.
10802 				 */
10803 				if (error != EINPROGRESS)
10804 					*outlenp = 0;
10805 				return (error);
10806 			}
10807 			/* OK return - copy input buffer into output buffer */
10808 			if (invalp != outvalp) {
10809 				bcopy(invalp, outvalp, inlen);
10810 			}
10811 			*outlenp = inlen;
10812 			return (0);
10813 		}
10814 		case IP_SEC_OPT:
10815 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10816 			if (error != 0) {
10817 				*outlenp = 0;
10818 				return (error);
10819 			}
10820 			break;
10821 		case IP_HDRINCL:
10822 		case IP_OPTIONS:
10823 		case T_IP_OPTIONS:
10824 		case IP_TOS:
10825 		case T_IP_TOS:
10826 		case IP_TTL:
10827 		case IP_RECVDSTADDR:
10828 		case IP_RECVOPTS:
10829 			/* OK return - copy input buffer into output buffer */
10830 			if (invalp != outvalp) {
10831 				/* don't trust bcopy for identical src/dst */
10832 				bcopy(invalp, outvalp, inlen);
10833 			}
10834 			*outlenp = inlen;
10835 			return (0);
10836 		case IP_RECVIF:
10837 			/* Retrieve the inbound interface index */
10838 			if (!checkonly) {
10839 				mutex_enter(&connp->conn_lock);
10840 				connp->conn_recvif = *i1 ? 1 : 0;
10841 				mutex_exit(&connp->conn_lock);
10842 			}
10843 			break;	/* goto sizeof (int) option return */
10844 		case IP_RECVSLLA:
10845 			/* Retrieve the source link layer address */
10846 			if (!checkonly) {
10847 				mutex_enter(&connp->conn_lock);
10848 				connp->conn_recvslla = *i1 ? 1 : 0;
10849 				mutex_exit(&connp->conn_lock);
10850 			}
10851 			break;	/* goto sizeof (int) option return */
10852 		case MRT_INIT:
10853 		case MRT_DONE:
10854 		case MRT_ADD_VIF:
10855 		case MRT_DEL_VIF:
10856 		case MRT_ADD_MFC:
10857 		case MRT_DEL_MFC:
10858 		case MRT_ASSERT:
10859 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10860 				*outlenp = 0;
10861 				return (error);
10862 			}
10863 			error = ip_mrouter_set((int)name, q, checkonly,
10864 			    (uchar_t *)invalp, inlen, first_mp);
10865 			if (error) {
10866 				*outlenp = 0;
10867 				return (error);
10868 			}
10869 			/* OK return - copy input buffer into output buffer */
10870 			if (invalp != outvalp) {
10871 				/* don't trust bcopy for identical src/dst */
10872 				bcopy(invalp, outvalp, inlen);
10873 			}
10874 			*outlenp = inlen;
10875 			return (0);
10876 		case IP_BOUND_IF:
10877 		case IP_XMIT_IF:
10878 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10879 			    level, name, first_mp);
10880 			if (error != 0)
10881 				return (error);
10882 			break; 		/* goto sizeof (int) option return */
10883 
10884 		case IP_UNSPEC_SRC:
10885 			/* Allow sending with a zero source address */
10886 			if (!checkonly) {
10887 				mutex_enter(&connp->conn_lock);
10888 				connp->conn_unspec_src = *i1 ? 1 : 0;
10889 				mutex_exit(&connp->conn_lock);
10890 			}
10891 			break;	/* goto sizeof (int) option return */
10892 		default:
10893 			/*
10894 			 * "soft" error (negative)
10895 			 * option not handled at this level
10896 			 * Note: Do not modify *outlenp
10897 			 */
10898 			return (-EINVAL);
10899 		}
10900 		break;
10901 	case IPPROTO_IPV6:
10902 		switch (name) {
10903 		case IPV6_BOUND_IF:
10904 		case IPV6_BOUND_PIF:
10905 		case IPV6_DONTFAILOVER_IF:
10906 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10907 			    level, name, first_mp);
10908 			if (error != 0)
10909 				return (error);
10910 			break; 		/* goto sizeof (int) option return */
10911 
10912 		case IPV6_MULTICAST_IF:
10913 			/*
10914 			 * The only possible errors are EINPROGRESS and
10915 			 * EINVAL. EINPROGRESS will be restarted and is not
10916 			 * a hard error. We call this option on both V4 and V6
10917 			 * If both return EINVAL, then this call returns
10918 			 * EINVAL. If at least one of them succeeds we
10919 			 * return success.
10920 			 */
10921 			found = B_FALSE;
10922 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10923 			    level, name, first_mp);
10924 			if (error == EINPROGRESS)
10925 				return (error);
10926 			if (error == 0)
10927 				found = B_TRUE;
10928 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10929 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10930 			if (error == 0)
10931 				found = B_TRUE;
10932 			if (!found)
10933 				return (error);
10934 			break; 		/* goto sizeof (int) option return */
10935 
10936 		case IPV6_MULTICAST_HOPS:
10937 			/* Recorded in transport above IP */
10938 			break;	/* goto sizeof (int) option return */
10939 		case IPV6_MULTICAST_LOOP:
10940 			if (!checkonly) {
10941 				mutex_enter(&connp->conn_lock);
10942 				connp->conn_multicast_loop = *i1;
10943 				mutex_exit(&connp->conn_lock);
10944 			}
10945 			break;	/* goto sizeof (int) option return */
10946 		case IPV6_JOIN_GROUP:
10947 		case MCAST_JOIN_GROUP:
10948 		case IPV6_LEAVE_GROUP:
10949 		case MCAST_LEAVE_GROUP: {
10950 			struct ipv6_mreq *ip_mreqp;
10951 			struct group_req *greqp;
10952 			ire_t *ire;
10953 			boolean_t done = B_FALSE;
10954 			in6_addr_t groupv6;
10955 			uint32_t ifindex;
10956 			boolean_t mcast_opt = B_TRUE;
10957 			mcast_record_t fmode;
10958 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10959 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10960 
10961 			switch (name) {
10962 			case IPV6_JOIN_GROUP:
10963 				mcast_opt = B_FALSE;
10964 				/* FALLTHRU */
10965 			case MCAST_JOIN_GROUP:
10966 				fmode = MODE_IS_EXCLUDE;
10967 				optfn = ip_opt_add_group_v6;
10968 				break;
10969 
10970 			case IPV6_LEAVE_GROUP:
10971 				mcast_opt = B_FALSE;
10972 				/* FALLTHRU */
10973 			case MCAST_LEAVE_GROUP:
10974 				fmode = MODE_IS_INCLUDE;
10975 				optfn = ip_opt_delete_group_v6;
10976 				break;
10977 			}
10978 
10979 			if (mcast_opt) {
10980 				struct sockaddr_in *sin;
10981 				struct sockaddr_in6 *sin6;
10982 				greqp = (struct group_req *)i1;
10983 				if (greqp->gr_group.ss_family == AF_INET) {
10984 					sin = (struct sockaddr_in *)
10985 					    &(greqp->gr_group);
10986 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10987 					    &groupv6);
10988 				} else {
10989 					sin6 = (struct sockaddr_in6 *)
10990 					    &(greqp->gr_group);
10991 					groupv6 = sin6->sin6_addr;
10992 				}
10993 				ifindex = greqp->gr_interface;
10994 			} else {
10995 				ip_mreqp = (struct ipv6_mreq *)i1;
10996 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10997 				ifindex = ip_mreqp->ipv6mr_interface;
10998 			}
10999 			/*
11000 			 * In the multirouting case, we need to replicate
11001 			 * the request on all interfaces that will take part
11002 			 * in replication.  We do so because multirouting is
11003 			 * reflective, thus we will probably receive multi-
11004 			 * casts on those interfaces.
11005 			 * The ip_multirt_apply_membership_v6() succeeds if
11006 			 * the operation succeeds on at least one interface.
11007 			 */
11008 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11009 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11010 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11011 			if (ire != NULL) {
11012 				if (ire->ire_flags & RTF_MULTIRT) {
11013 					error = ip_multirt_apply_membership_v6(
11014 					    optfn, ire, connp, checkonly,
11015 					    &groupv6, fmode, &ipv6_all_zeros,
11016 					    first_mp);
11017 					done = B_TRUE;
11018 				}
11019 				ire_refrele(ire);
11020 			}
11021 			if (!done) {
11022 				error = optfn(connp, checkonly, &groupv6,
11023 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11024 			}
11025 			if (error) {
11026 				/*
11027 				 * EINPROGRESS is a soft error, needs retry
11028 				 * so don't make *outlenp zero.
11029 				 */
11030 				if (error != EINPROGRESS)
11031 					*outlenp = 0;
11032 				return (error);
11033 			}
11034 			/* OK return - copy input buffer into output buffer */
11035 			if (invalp != outvalp) {
11036 				/* don't trust bcopy for identical src/dst */
11037 				bcopy(invalp, outvalp, inlen);
11038 			}
11039 			*outlenp = inlen;
11040 			return (0);
11041 		}
11042 		case MCAST_BLOCK_SOURCE:
11043 		case MCAST_UNBLOCK_SOURCE:
11044 		case MCAST_JOIN_SOURCE_GROUP:
11045 		case MCAST_LEAVE_SOURCE_GROUP: {
11046 			struct group_source_req *gsreqp;
11047 			in6_addr_t v6grp, v6src;
11048 			uint32_t ifindex;
11049 			mcast_record_t fmode;
11050 			ire_t *ire;
11051 			boolean_t done = B_FALSE;
11052 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11053 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11054 
11055 			switch (name) {
11056 			case MCAST_BLOCK_SOURCE:
11057 				fmode = MODE_IS_EXCLUDE;
11058 				optfn = ip_opt_add_group_v6;
11059 				break;
11060 			case MCAST_UNBLOCK_SOURCE:
11061 				fmode = MODE_IS_EXCLUDE;
11062 				optfn = ip_opt_delete_group_v6;
11063 				break;
11064 			case MCAST_JOIN_SOURCE_GROUP:
11065 				fmode = MODE_IS_INCLUDE;
11066 				optfn = ip_opt_add_group_v6;
11067 				break;
11068 			case MCAST_LEAVE_SOURCE_GROUP:
11069 				fmode = MODE_IS_INCLUDE;
11070 				optfn = ip_opt_delete_group_v6;
11071 				break;
11072 			}
11073 
11074 			gsreqp = (struct group_source_req *)i1;
11075 			ifindex = gsreqp->gsr_interface;
11076 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11077 				struct sockaddr_in *s;
11078 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11079 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11080 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11081 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11082 			} else {
11083 				struct sockaddr_in6 *s6;
11084 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11085 				v6grp = s6->sin6_addr;
11086 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11087 				v6src = s6->sin6_addr;
11088 			}
11089 
11090 			/*
11091 			 * In the multirouting case, we need to replicate
11092 			 * the request as noted in the mcast cases above.
11093 			 */
11094 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11095 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11096 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11097 			if (ire != NULL) {
11098 				if (ire->ire_flags & RTF_MULTIRT) {
11099 					error = ip_multirt_apply_membership_v6(
11100 					    optfn, ire, connp, checkonly,
11101 					    &v6grp, fmode, &v6src, first_mp);
11102 					done = B_TRUE;
11103 				}
11104 				ire_refrele(ire);
11105 			}
11106 			if (!done) {
11107 				error = optfn(connp, checkonly, &v6grp,
11108 				    ifindex, fmode, &v6src, first_mp);
11109 			}
11110 			if (error != 0) {
11111 				/*
11112 				 * EINPROGRESS is a soft error, needs retry
11113 				 * so don't make *outlenp zero.
11114 				 */
11115 				if (error != EINPROGRESS)
11116 					*outlenp = 0;
11117 				return (error);
11118 			}
11119 			/* OK return - copy input buffer into output buffer */
11120 			if (invalp != outvalp) {
11121 				bcopy(invalp, outvalp, inlen);
11122 			}
11123 			*outlenp = inlen;
11124 			return (0);
11125 		}
11126 		case IPV6_UNICAST_HOPS:
11127 			/* Recorded in transport above IP */
11128 			break;	/* goto sizeof (int) option return */
11129 		case IPV6_UNSPEC_SRC:
11130 			/* Allow sending with a zero source address */
11131 			if (!checkonly) {
11132 				mutex_enter(&connp->conn_lock);
11133 				connp->conn_unspec_src = *i1 ? 1 : 0;
11134 				mutex_exit(&connp->conn_lock);
11135 			}
11136 			break;	/* goto sizeof (int) option return */
11137 		case IPV6_RECVPKTINFO:
11138 			if (!checkonly) {
11139 				mutex_enter(&connp->conn_lock);
11140 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
11141 				mutex_exit(&connp->conn_lock);
11142 			}
11143 			break;	/* goto sizeof (int) option return */
11144 		case IPV6_RECVTCLASS:
11145 			if (!checkonly) {
11146 				if (*i1 < 0 || *i1 > 1) {
11147 					return (EINVAL);
11148 				}
11149 				mutex_enter(&connp->conn_lock);
11150 				connp->conn_ipv6_recvtclass = *i1;
11151 				mutex_exit(&connp->conn_lock);
11152 			}
11153 			break;
11154 		case IPV6_RECVPATHMTU:
11155 			if (!checkonly) {
11156 				if (*i1 < 0 || *i1 > 1) {
11157 					return (EINVAL);
11158 				}
11159 				mutex_enter(&connp->conn_lock);
11160 				connp->conn_ipv6_recvpathmtu = *i1;
11161 				mutex_exit(&connp->conn_lock);
11162 			}
11163 			break;
11164 		case IPV6_RECVHOPLIMIT:
11165 			if (!checkonly) {
11166 				mutex_enter(&connp->conn_lock);
11167 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11168 				mutex_exit(&connp->conn_lock);
11169 			}
11170 			break;	/* goto sizeof (int) option return */
11171 		case IPV6_RECVHOPOPTS:
11172 			if (!checkonly) {
11173 				mutex_enter(&connp->conn_lock);
11174 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11175 				mutex_exit(&connp->conn_lock);
11176 			}
11177 			break;	/* goto sizeof (int) option return */
11178 		case IPV6_RECVDSTOPTS:
11179 			if (!checkonly) {
11180 				mutex_enter(&connp->conn_lock);
11181 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11182 				mutex_exit(&connp->conn_lock);
11183 			}
11184 			break;	/* goto sizeof (int) option return */
11185 		case IPV6_RECVRTHDR:
11186 			if (!checkonly) {
11187 				mutex_enter(&connp->conn_lock);
11188 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11189 				mutex_exit(&connp->conn_lock);
11190 			}
11191 			break;	/* goto sizeof (int) option return */
11192 		case IPV6_RECVRTHDRDSTOPTS:
11193 			if (!checkonly) {
11194 				mutex_enter(&connp->conn_lock);
11195 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11196 				mutex_exit(&connp->conn_lock);
11197 			}
11198 			break;	/* goto sizeof (int) option return */
11199 		case IPV6_PKTINFO:
11200 			if (inlen == 0)
11201 				return (-EINVAL);	/* clearing option */
11202 			error = ip6_set_pktinfo(cr, connp,
11203 			    (struct in6_pktinfo *)invalp, first_mp);
11204 			if (error != 0)
11205 				*outlenp = 0;
11206 			else
11207 				*outlenp = inlen;
11208 			return (error);
11209 		case IPV6_NEXTHOP: {
11210 			struct sockaddr_in6 *sin6;
11211 
11212 			/* Verify that the nexthop is reachable */
11213 			if (inlen == 0)
11214 				return (-EINVAL);	/* clearing option */
11215 
11216 			sin6 = (struct sockaddr_in6 *)invalp;
11217 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11218 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11219 			    NULL, MATCH_IRE_DEFAULT);
11220 
11221 			if (ire == NULL) {
11222 				*outlenp = 0;
11223 				return (EHOSTUNREACH);
11224 			}
11225 			ire_refrele(ire);
11226 			return (-EINVAL);
11227 		}
11228 		case IPV6_SEC_OPT:
11229 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11230 			if (error != 0) {
11231 				*outlenp = 0;
11232 				return (error);
11233 			}
11234 			break;
11235 		case IPV6_SRC_PREFERENCES: {
11236 			/*
11237 			 * This is implemented strictly in the ip module
11238 			 * (here and in tcp_opt_*() to accomodate tcp
11239 			 * sockets).  Modules above ip pass this option
11240 			 * down here since ip is the only one that needs to
11241 			 * be aware of source address preferences.
11242 			 *
11243 			 * This socket option only affects connected
11244 			 * sockets that haven't already bound to a specific
11245 			 * IPv6 address.  In other words, sockets that
11246 			 * don't call bind() with an address other than the
11247 			 * unspecified address and that call connect().
11248 			 * ip_bind_connected_v6() passes these preferences
11249 			 * to the ipif_select_source_v6() function.
11250 			 */
11251 			if (inlen != sizeof (uint32_t))
11252 				return (EINVAL);
11253 			error = ip6_set_src_preferences(connp,
11254 			    *(uint32_t *)invalp);
11255 			if (error != 0) {
11256 				*outlenp = 0;
11257 				return (error);
11258 			} else {
11259 				*outlenp = sizeof (uint32_t);
11260 			}
11261 			break;
11262 		}
11263 		case IPV6_V6ONLY:
11264 			if (*i1 < 0 || *i1 > 1) {
11265 				return (EINVAL);
11266 			}
11267 			mutex_enter(&connp->conn_lock);
11268 			connp->conn_ipv6_v6only = *i1;
11269 			mutex_exit(&connp->conn_lock);
11270 			break;
11271 		default:
11272 			return (-EINVAL);
11273 		}
11274 		break;
11275 	default:
11276 		/*
11277 		 * "soft" error (negative)
11278 		 * option not handled at this level
11279 		 * Note: Do not modify *outlenp
11280 		 */
11281 		return (-EINVAL);
11282 	}
11283 	/*
11284 	 * Common case of return from an option that is sizeof (int)
11285 	 */
11286 	*(int *)outvalp = *i1;
11287 	*outlenp = sizeof (int);
11288 	return (0);
11289 }
11290 
11291 /*
11292  * This routine gets default values of certain options whose default
11293  * values are maintained by protocol specific code
11294  */
11295 /* ARGSUSED */
11296 int
11297 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11298 {
11299 	int *i1 = (int *)ptr;
11300 
11301 	switch (level) {
11302 	case IPPROTO_IP:
11303 		switch (name) {
11304 		case IP_MULTICAST_TTL:
11305 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11306 			return (sizeof (uchar_t));
11307 		case IP_MULTICAST_LOOP:
11308 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11309 			return (sizeof (uchar_t));
11310 		default:
11311 			return (-1);
11312 		}
11313 	case IPPROTO_IPV6:
11314 		switch (name) {
11315 		case IPV6_UNICAST_HOPS:
11316 			*i1 = ipv6_def_hops;
11317 			return (sizeof (int));
11318 		case IPV6_MULTICAST_HOPS:
11319 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11320 			return (sizeof (int));
11321 		case IPV6_MULTICAST_LOOP:
11322 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11323 			return (sizeof (int));
11324 		case IPV6_V6ONLY:
11325 			*i1 = 1;
11326 			return (sizeof (int));
11327 		default:
11328 			return (-1);
11329 		}
11330 	default:
11331 		return (-1);
11332 	}
11333 	/* NOTREACHED */
11334 }
11335 
11336 /*
11337  * Given a destination address and a pointer to where to put the information
11338  * this routine fills in the mtuinfo.
11339  */
11340 int
11341 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11342     struct ip6_mtuinfo *mtuinfo)
11343 {
11344 	ire_t *ire;
11345 
11346 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11347 		return (-1);
11348 
11349 	bzero(mtuinfo, sizeof (*mtuinfo));
11350 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11351 	mtuinfo->ip6m_addr.sin6_port = port;
11352 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11353 
11354 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11355 	if (ire != NULL) {
11356 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11357 		ire_refrele(ire);
11358 	} else {
11359 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11360 	}
11361 	return (sizeof (struct ip6_mtuinfo));
11362 }
11363 
11364 /*
11365  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11366  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11367  * isn't.  This doesn't matter as the error checking is done properly for the
11368  * other MRT options coming in through ip_opt_set.
11369  */
11370 int
11371 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11372 {
11373 	conn_t		*connp = Q_TO_CONN(q);
11374 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11375 
11376 	switch (level) {
11377 	case IPPROTO_IP:
11378 		switch (name) {
11379 		case MRT_VERSION:
11380 		case MRT_ASSERT:
11381 			(void) ip_mrouter_get(name, q, ptr);
11382 			return (sizeof (int));
11383 		case IP_SEC_OPT:
11384 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11385 		case IP_NEXTHOP:
11386 			if (connp->conn_nexthop_set) {
11387 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11388 				return (sizeof (ipaddr_t));
11389 			} else
11390 				return (0);
11391 		default:
11392 			break;
11393 		}
11394 		break;
11395 	case IPPROTO_IPV6:
11396 		switch (name) {
11397 		case IPV6_SEC_OPT:
11398 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11399 		case IPV6_SRC_PREFERENCES: {
11400 			return (ip6_get_src_preferences(connp,
11401 			    (uint32_t *)ptr));
11402 		}
11403 		case IPV6_V6ONLY:
11404 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11405 			return (sizeof (int));
11406 		case IPV6_PATHMTU:
11407 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11408 				(struct ip6_mtuinfo *)ptr));
11409 		default:
11410 			break;
11411 		}
11412 		break;
11413 	default:
11414 		break;
11415 	}
11416 	return (-1);
11417 }
11418 
11419 /* Named Dispatch routine to get a current value out of our parameter table. */
11420 /* ARGSUSED */
11421 static int
11422 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11423 {
11424 	ipparam_t *ippa = (ipparam_t *)cp;
11425 
11426 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11427 	return (0);
11428 }
11429 
11430 /* ARGSUSED */
11431 static int
11432 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11433 {
11434 
11435 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11436 	return (0);
11437 }
11438 
11439 /*
11440  * Set ip{,6}_forwarding values.  This means walking through all of the
11441  * ill's and toggling their forwarding values.
11442  */
11443 /* ARGSUSED */
11444 static int
11445 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11446 {
11447 	long new_value;
11448 	int *forwarding_value = (int *)cp;
11449 	ill_t *walker;
11450 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11451 	ill_walk_context_t ctx;
11452 
11453 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11454 	    new_value < 0 || new_value > 1) {
11455 		return (EINVAL);
11456 	}
11457 
11458 	*forwarding_value = new_value;
11459 
11460 	/*
11461 	 * Regardless of the current value of ip_forwarding, set all per-ill
11462 	 * values of ip_forwarding to the value being set.
11463 	 *
11464 	 * Bring all the ill's up to date with the new global value.
11465 	 */
11466 	rw_enter(&ill_g_lock, RW_READER);
11467 
11468 	if (isv6)
11469 		walker = ILL_START_WALK_V6(&ctx);
11470 	else
11471 		walker = ILL_START_WALK_V4(&ctx);
11472 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11473 		(void) ill_forward_set(q, mp, (new_value != 0),
11474 		    (caddr_t)walker);
11475 	}
11476 	rw_exit(&ill_g_lock);
11477 
11478 	return (0);
11479 }
11480 
11481 /*
11482  * Walk through the param array specified registering each element with the
11483  * Named Dispatch handler. This is called only during init. So it is ok
11484  * not to acquire any locks
11485  */
11486 static boolean_t
11487 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11488     ipndp_t *ipnd, size_t ipnd_cnt)
11489 {
11490 	for (; ippa_cnt-- > 0; ippa++) {
11491 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11492 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11493 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11494 				nd_free(&ip_g_nd);
11495 				return (B_FALSE);
11496 			}
11497 		}
11498 	}
11499 
11500 	for (; ipnd_cnt-- > 0; ipnd++) {
11501 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11502 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11503 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11504 			    ipnd->ip_ndp_data)) {
11505 				nd_free(&ip_g_nd);
11506 				return (B_FALSE);
11507 			}
11508 		}
11509 	}
11510 
11511 	return (B_TRUE);
11512 }
11513 
11514 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11515 /* ARGSUSED */
11516 static int
11517 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11518 {
11519 	long		new_value;
11520 	ipparam_t	*ippa = (ipparam_t *)cp;
11521 
11522 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11523 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11524 		return (EINVAL);
11525 	}
11526 	ippa->ip_param_value = new_value;
11527 	return (0);
11528 }
11529 
11530 /*
11531  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11532  * When an ipf is passed here for the first time, if
11533  * we already have in-order fragments on the queue, we convert from the fast-
11534  * path reassembly scheme to the hard-case scheme.  From then on, additional
11535  * fragments are reassembled here.  We keep track of the start and end offsets
11536  * of each piece, and the number of holes in the chain.  When the hole count
11537  * goes to zero, we are done!
11538  *
11539  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11540  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11541  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11542  * after the call to ip_reassemble().
11543  */
11544 int
11545 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11546     size_t msg_len)
11547 {
11548 	uint_t	end;
11549 	mblk_t	*next_mp;
11550 	mblk_t	*mp1;
11551 	uint_t	offset;
11552 	boolean_t incr_dups = B_TRUE;
11553 	boolean_t offset_zero_seen = B_FALSE;
11554 	boolean_t pkt_boundary_checked = B_FALSE;
11555 
11556 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11557 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11558 
11559 	/* Add in byte count */
11560 	ipf->ipf_count += msg_len;
11561 	if (ipf->ipf_end) {
11562 		/*
11563 		 * We were part way through in-order reassembly, but now there
11564 		 * is a hole.  We walk through messages already queued, and
11565 		 * mark them for hard case reassembly.  We know that up till
11566 		 * now they were in order starting from offset zero.
11567 		 */
11568 		offset = 0;
11569 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11570 			IP_REASS_SET_START(mp1, offset);
11571 			if (offset == 0) {
11572 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11573 				offset = -ipf->ipf_nf_hdr_len;
11574 			}
11575 			offset += mp1->b_wptr - mp1->b_rptr;
11576 			IP_REASS_SET_END(mp1, offset);
11577 		}
11578 		/* One hole at the end. */
11579 		ipf->ipf_hole_cnt = 1;
11580 		/* Brand it as a hard case, forever. */
11581 		ipf->ipf_end = 0;
11582 	}
11583 	/* Walk through all the new pieces. */
11584 	do {
11585 		end = start + (mp->b_wptr - mp->b_rptr);
11586 		/*
11587 		 * If start is 0, decrease 'end' only for the first mblk of
11588 		 * the fragment. Otherwise 'end' can get wrong value in the
11589 		 * second pass of the loop if first mblk is exactly the
11590 		 * size of ipf_nf_hdr_len.
11591 		 */
11592 		if (start == 0 && !offset_zero_seen) {
11593 			/* First segment */
11594 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11595 			end -= ipf->ipf_nf_hdr_len;
11596 			offset_zero_seen = B_TRUE;
11597 		}
11598 		next_mp = mp->b_cont;
11599 		/*
11600 		 * We are checking to see if there is any interesing data
11601 		 * to process.  If there isn't and the mblk isn't the
11602 		 * one which carries the unfragmentable header then we
11603 		 * drop it.  It's possible to have just the unfragmentable
11604 		 * header come through without any data.  That needs to be
11605 		 * saved.
11606 		 *
11607 		 * If the assert at the top of this function holds then the
11608 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11609 		 * is infrequently traveled enough that the test is left in
11610 		 * to protect against future code changes which break that
11611 		 * invariant.
11612 		 */
11613 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11614 			/* Empty.  Blast it. */
11615 			IP_REASS_SET_START(mp, 0);
11616 			IP_REASS_SET_END(mp, 0);
11617 			/*
11618 			 * If the ipf points to the mblk we are about to free,
11619 			 * update ipf to point to the next mblk (or NULL
11620 			 * if none).
11621 			 */
11622 			if (ipf->ipf_mp->b_cont == mp)
11623 				ipf->ipf_mp->b_cont = next_mp;
11624 			freeb(mp);
11625 			continue;
11626 		}
11627 		mp->b_cont = NULL;
11628 		IP_REASS_SET_START(mp, start);
11629 		IP_REASS_SET_END(mp, end);
11630 		if (!ipf->ipf_tail_mp) {
11631 			ipf->ipf_tail_mp = mp;
11632 			ipf->ipf_mp->b_cont = mp;
11633 			if (start == 0 || !more) {
11634 				ipf->ipf_hole_cnt = 1;
11635 				/*
11636 				 * if the first fragment comes in more than one
11637 				 * mblk, this loop will be executed for each
11638 				 * mblk. Need to adjust hole count so exiting
11639 				 * this routine will leave hole count at 1.
11640 				 */
11641 				if (next_mp)
11642 					ipf->ipf_hole_cnt++;
11643 			} else
11644 				ipf->ipf_hole_cnt = 2;
11645 			continue;
11646 		} else if (ipf->ipf_last_frag_seen && !more &&
11647 			    !pkt_boundary_checked) {
11648 			/*
11649 			 * We check datagram boundary only if this fragment
11650 			 * claims to be the last fragment and we have seen a
11651 			 * last fragment in the past too. We do this only
11652 			 * once for a given fragment.
11653 			 *
11654 			 * start cannot be 0 here as fragments with start=0
11655 			 * and MF=0 gets handled as a complete packet. These
11656 			 * fragments should not reach here.
11657 			 */
11658 
11659 			if (start + msgdsize(mp) !=
11660 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11661 				/*
11662 				 * We have two fragments both of which claim
11663 				 * to be the last fragment but gives conflicting
11664 				 * information about the whole datagram size.
11665 				 * Something fishy is going on. Drop the
11666 				 * fragment and free up the reassembly list.
11667 				 */
11668 				return (IP_REASS_FAILED);
11669 			}
11670 
11671 			/*
11672 			 * We shouldn't come to this code block again for this
11673 			 * particular fragment.
11674 			 */
11675 			pkt_boundary_checked = B_TRUE;
11676 		}
11677 
11678 		/* New stuff at or beyond tail? */
11679 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11680 		if (start >= offset) {
11681 			if (ipf->ipf_last_frag_seen) {
11682 				/* current fragment is beyond last fragment */
11683 				return (IP_REASS_FAILED);
11684 			}
11685 			/* Link it on end. */
11686 			ipf->ipf_tail_mp->b_cont = mp;
11687 			ipf->ipf_tail_mp = mp;
11688 			if (more) {
11689 				if (start != offset)
11690 					ipf->ipf_hole_cnt++;
11691 			} else if (start == offset && next_mp == NULL)
11692 					ipf->ipf_hole_cnt--;
11693 			continue;
11694 		}
11695 		mp1 = ipf->ipf_mp->b_cont;
11696 		offset = IP_REASS_START(mp1);
11697 		/* New stuff at the front? */
11698 		if (start < offset) {
11699 			if (start == 0) {
11700 				if (end >= offset) {
11701 					/* Nailed the hole at the begining. */
11702 					ipf->ipf_hole_cnt--;
11703 				}
11704 			} else if (end < offset) {
11705 				/*
11706 				 * A hole, stuff, and a hole where there used
11707 				 * to be just a hole.
11708 				 */
11709 				ipf->ipf_hole_cnt++;
11710 			}
11711 			mp->b_cont = mp1;
11712 			/* Check for overlap. */
11713 			while (end > offset) {
11714 				if (end < IP_REASS_END(mp1)) {
11715 					mp->b_wptr -= end - offset;
11716 					IP_REASS_SET_END(mp, offset);
11717 					if (ill->ill_isv6) {
11718 						BUMP_MIB(ill->ill_ip6_mib,
11719 						    ipv6ReasmPartDups);
11720 					} else {
11721 						BUMP_MIB(&ip_mib,
11722 						    ipReasmPartDups);
11723 					}
11724 					break;
11725 				}
11726 				/* Did we cover another hole? */
11727 				if ((mp1->b_cont &&
11728 				    IP_REASS_END(mp1) !=
11729 				    IP_REASS_START(mp1->b_cont) &&
11730 				    end >= IP_REASS_START(mp1->b_cont)) ||
11731 				    (!ipf->ipf_last_frag_seen && !more)) {
11732 					ipf->ipf_hole_cnt--;
11733 				}
11734 				/* Clip out mp1. */
11735 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11736 					/*
11737 					 * After clipping out mp1, this guy
11738 					 * is now hanging off the end.
11739 					 */
11740 					ipf->ipf_tail_mp = mp;
11741 				}
11742 				IP_REASS_SET_START(mp1, 0);
11743 				IP_REASS_SET_END(mp1, 0);
11744 				/* Subtract byte count */
11745 				ipf->ipf_count -= mp1->b_datap->db_lim -
11746 				    mp1->b_datap->db_base;
11747 				freeb(mp1);
11748 				if (ill->ill_isv6) {
11749 					BUMP_MIB(ill->ill_ip6_mib,
11750 					    ipv6ReasmPartDups);
11751 				} else {
11752 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11753 				}
11754 				mp1 = mp->b_cont;
11755 				if (!mp1)
11756 					break;
11757 				offset = IP_REASS_START(mp1);
11758 			}
11759 			ipf->ipf_mp->b_cont = mp;
11760 			continue;
11761 		}
11762 		/*
11763 		 * The new piece starts somewhere between the start of the head
11764 		 * and before the end of the tail.
11765 		 */
11766 		for (; mp1; mp1 = mp1->b_cont) {
11767 			offset = IP_REASS_END(mp1);
11768 			if (start < offset) {
11769 				if (end <= offset) {
11770 					/* Nothing new. */
11771 					IP_REASS_SET_START(mp, 0);
11772 					IP_REASS_SET_END(mp, 0);
11773 					/* Subtract byte count */
11774 					ipf->ipf_count -= mp->b_datap->db_lim -
11775 					    mp->b_datap->db_base;
11776 					if (incr_dups) {
11777 						ipf->ipf_num_dups++;
11778 						incr_dups = B_FALSE;
11779 					}
11780 					freeb(mp);
11781 					if (ill->ill_isv6) {
11782 						BUMP_MIB(ill->ill_ip6_mib,
11783 						    ipv6ReasmDuplicates);
11784 					} else {
11785 						BUMP_MIB(&ip_mib,
11786 						    ipReasmDuplicates);
11787 					}
11788 					break;
11789 				}
11790 				/*
11791 				 * Trim redundant stuff off beginning of new
11792 				 * piece.
11793 				 */
11794 				IP_REASS_SET_START(mp, offset);
11795 				mp->b_rptr += offset - start;
11796 				if (ill->ill_isv6) {
11797 					BUMP_MIB(ill->ill_ip6_mib,
11798 					    ipv6ReasmPartDups);
11799 				} else {
11800 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11801 				}
11802 				start = offset;
11803 				if (!mp1->b_cont) {
11804 					/*
11805 					 * After trimming, this guy is now
11806 					 * hanging off the end.
11807 					 */
11808 					mp1->b_cont = mp;
11809 					ipf->ipf_tail_mp = mp;
11810 					if (!more) {
11811 						ipf->ipf_hole_cnt--;
11812 					}
11813 					break;
11814 				}
11815 			}
11816 			if (start >= IP_REASS_START(mp1->b_cont))
11817 				continue;
11818 			/* Fill a hole */
11819 			if (start > offset)
11820 				ipf->ipf_hole_cnt++;
11821 			mp->b_cont = mp1->b_cont;
11822 			mp1->b_cont = mp;
11823 			mp1 = mp->b_cont;
11824 			offset = IP_REASS_START(mp1);
11825 			if (end >= offset) {
11826 				ipf->ipf_hole_cnt--;
11827 				/* Check for overlap. */
11828 				while (end > offset) {
11829 					if (end < IP_REASS_END(mp1)) {
11830 						mp->b_wptr -= end - offset;
11831 						IP_REASS_SET_END(mp, offset);
11832 						/*
11833 						 * TODO we might bump
11834 						 * this up twice if there is
11835 						 * overlap at both ends.
11836 						 */
11837 						if (ill->ill_isv6) {
11838 							BUMP_MIB(
11839 							    ill->ill_ip6_mib,
11840 							    ipv6ReasmPartDups);
11841 						} else {
11842 							BUMP_MIB(&ip_mib,
11843 							    ipReasmPartDups);
11844 						}
11845 						break;
11846 					}
11847 					/* Did we cover another hole? */
11848 					if ((mp1->b_cont &&
11849 					    IP_REASS_END(mp1)
11850 					    != IP_REASS_START(mp1->b_cont) &&
11851 					    end >=
11852 					    IP_REASS_START(mp1->b_cont)) ||
11853 					    (!ipf->ipf_last_frag_seen &&
11854 					    !more)) {
11855 						ipf->ipf_hole_cnt--;
11856 					}
11857 					/* Clip out mp1. */
11858 					if ((mp->b_cont = mp1->b_cont) ==
11859 					    NULL) {
11860 						/*
11861 						 * After clipping out mp1,
11862 						 * this guy is now hanging
11863 						 * off the end.
11864 						 */
11865 						ipf->ipf_tail_mp = mp;
11866 					}
11867 					IP_REASS_SET_START(mp1, 0);
11868 					IP_REASS_SET_END(mp1, 0);
11869 					/* Subtract byte count */
11870 					ipf->ipf_count -=
11871 					    mp1->b_datap->db_lim -
11872 					    mp1->b_datap->db_base;
11873 					freeb(mp1);
11874 					if (ill->ill_isv6) {
11875 						BUMP_MIB(ill->ill_ip6_mib,
11876 						    ipv6ReasmPartDups);
11877 					} else {
11878 						BUMP_MIB(&ip_mib,
11879 						    ipReasmPartDups);
11880 					}
11881 					mp1 = mp->b_cont;
11882 					if (!mp1)
11883 						break;
11884 					offset = IP_REASS_START(mp1);
11885 				}
11886 			}
11887 			break;
11888 		}
11889 	} while (start = end, mp = next_mp);
11890 
11891 	/* Fragment just processed could be the last one. Remember this fact */
11892 	if (!more)
11893 		ipf->ipf_last_frag_seen = B_TRUE;
11894 
11895 	/* Still got holes? */
11896 	if (ipf->ipf_hole_cnt)
11897 		return (IP_REASS_PARTIAL);
11898 	/* Clean up overloaded fields to avoid upstream disasters. */
11899 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11900 		IP_REASS_SET_START(mp1, 0);
11901 		IP_REASS_SET_END(mp1, 0);
11902 	}
11903 	return (IP_REASS_COMPLETE);
11904 }
11905 
11906 /*
11907  * ipsec processing for the fast path, used for input UDP Packets
11908  */
11909 static boolean_t
11910 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11911     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11912 {
11913 	uint32_t	ill_index;
11914 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11915 
11916 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11917 	/* The ill_index of the incoming ILL */
11918 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11919 
11920 	/* pass packet up to the transport */
11921 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11922 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11923 		    NULL, mctl_present);
11924 		if (*first_mpp == NULL) {
11925 			return (B_FALSE);
11926 		}
11927 	}
11928 
11929 	/* Initiate IPPF processing for fastpath UDP */
11930 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11931 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11932 		if (*mpp == NULL) {
11933 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11934 			    "deferred/dropped during IPPF processing\n"));
11935 			return (B_FALSE);
11936 		}
11937 	}
11938 	/*
11939 	 * We make the checks as below since we are in the fast path
11940 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11941 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11942 	 */
11943 	if (connp->conn_recvif || connp->conn_recvslla ||
11944 	    connp->conn_ipv6_recvpktinfo) {
11945 		if (connp->conn_recvif ||
11946 		    connp->conn_ipv6_recvpktinfo) {
11947 			in_flags = IPF_RECVIF;
11948 		}
11949 		if (connp->conn_recvslla) {
11950 			in_flags |= IPF_RECVSLLA;
11951 		}
11952 		/*
11953 		 * since in_flags are being set ill will be
11954 		 * referenced in ip_add_info, so it better not
11955 		 * be NULL.
11956 		 */
11957 		/*
11958 		 * the actual data will be contained in b_cont
11959 		 * upon successful return of the following call.
11960 		 * If the call fails then the original mblk is
11961 		 * returned.
11962 		 */
11963 		*mpp = ip_add_info(*mpp, ill, in_flags);
11964 	}
11965 
11966 	return (B_TRUE);
11967 }
11968 
11969 /*
11970  * Fragmentation reassembly.  Each ILL has a hash table for
11971  * queuing packets undergoing reassembly for all IPIFs
11972  * associated with the ILL.  The hash is based on the packet
11973  * IP ident field.  The ILL frag hash table was allocated
11974  * as a timer block at the time the ILL was created.  Whenever
11975  * there is anything on the reassembly queue, the timer will
11976  * be running.  Returns B_TRUE if successful else B_FALSE;
11977  * frees mp on failure.
11978  */
11979 static boolean_t
11980 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11981     uint32_t *cksum_val, uint16_t *cksum_flags)
11982 {
11983 	uint32_t	frag_offset_flags;
11984 	ill_t		*ill = (ill_t *)q->q_ptr;
11985 	mblk_t		*mp = *mpp;
11986 	mblk_t		*t_mp;
11987 	ipaddr_t	dst;
11988 	uint8_t		proto = ipha->ipha_protocol;
11989 	uint32_t	sum_val;
11990 	uint16_t	sum_flags;
11991 	ipf_t		*ipf;
11992 	ipf_t		**ipfp;
11993 	ipfb_t		*ipfb;
11994 	uint16_t	ident;
11995 	uint32_t	offset;
11996 	ipaddr_t	src;
11997 	uint_t		hdr_length;
11998 	uint32_t	end;
11999 	mblk_t		*mp1;
12000 	mblk_t		*tail_mp;
12001 	size_t		count;
12002 	size_t		msg_len;
12003 	uint8_t		ecn_info = 0;
12004 	uint32_t	packet_size;
12005 	boolean_t	pruned = B_FALSE;
12006 
12007 	if (cksum_val != NULL)
12008 		*cksum_val = 0;
12009 	if (cksum_flags != NULL)
12010 		*cksum_flags = 0;
12011 
12012 	/*
12013 	 * Drop the fragmented as early as possible, if
12014 	 * we don't have resource(s) to re-assemble.
12015 	 */
12016 	if (ip_reass_queue_bytes == 0) {
12017 		freemsg(mp);
12018 		return (B_FALSE);
12019 	}
12020 
12021 	/* Check for fragmentation offset; return if there's none */
12022 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12023 	    (IPH_MF | IPH_OFFSET)) == 0)
12024 		return (B_TRUE);
12025 
12026 	/*
12027 	 * We utilize hardware computed checksum info only for UDP since
12028 	 * IP fragmentation is a normal occurence for the protocol.  In
12029 	 * addition, checksum offload support for IP fragments carrying
12030 	 * UDP payload is commonly implemented across network adapters.
12031 	 */
12032 	ASSERT(ill != NULL);
12033 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12034 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12035 		mblk_t *mp1 = mp->b_cont;
12036 		int32_t len;
12037 
12038 		/* Record checksum information from the packet */
12039 		sum_val = (uint32_t)DB_CKSUM16(mp);
12040 		sum_flags = DB_CKSUMFLAGS(mp);
12041 
12042 		/* IP payload offset from beginning of mblk */
12043 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12044 
12045 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12046 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12047 		    offset >= DB_CKSUMSTART(mp) &&
12048 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12049 			uint32_t adj;
12050 			/*
12051 			 * Partial checksum has been calculated by hardware
12052 			 * and attached to the packet; in addition, any
12053 			 * prepended extraneous data is even byte aligned.
12054 			 * If any such data exists, we adjust the checksum;
12055 			 * this would also handle any postpended data.
12056 			 */
12057 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12058 			    mp, mp1, len, adj);
12059 
12060 			/* One's complement subtract extraneous checksum */
12061 			if (adj >= sum_val)
12062 				sum_val = ~(adj - sum_val) & 0xFFFF;
12063 			else
12064 				sum_val -= adj;
12065 		}
12066 	} else {
12067 		sum_val = 0;
12068 		sum_flags = 0;
12069 	}
12070 
12071 	/* Clear hardware checksumming flag */
12072 	DB_CKSUMFLAGS(mp) = 0;
12073 
12074 	ident = ipha->ipha_ident;
12075 	offset = (frag_offset_flags << 3) & 0xFFFF;
12076 	src = ipha->ipha_src;
12077 	dst = ipha->ipha_dst;
12078 	hdr_length = IPH_HDR_LENGTH(ipha);
12079 	end = ntohs(ipha->ipha_length) - hdr_length;
12080 
12081 	/* If end == 0 then we have a packet with no data, so just free it */
12082 	if (end == 0) {
12083 		freemsg(mp);
12084 		return (B_FALSE);
12085 	}
12086 
12087 	/* Record the ECN field info. */
12088 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12089 	if (offset != 0) {
12090 		/*
12091 		 * If this isn't the first piece, strip the header, and
12092 		 * add the offset to the end value.
12093 		 */
12094 		mp->b_rptr += hdr_length;
12095 		end += offset;
12096 	}
12097 
12098 	msg_len = MBLKSIZE(mp);
12099 	tail_mp = mp;
12100 	while (tail_mp->b_cont != NULL) {
12101 		tail_mp = tail_mp->b_cont;
12102 		msg_len += MBLKSIZE(tail_mp);
12103 	}
12104 
12105 	/* If the reassembly list for this ILL will get too big, prune it */
12106 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12107 	    ip_reass_queue_bytes) {
12108 		ill_frag_prune(ill,
12109 		    (ip_reass_queue_bytes < msg_len) ? 0 :
12110 		    (ip_reass_queue_bytes - msg_len));
12111 		pruned = B_TRUE;
12112 	}
12113 
12114 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12115 	mutex_enter(&ipfb->ipfb_lock);
12116 
12117 	ipfp = &ipfb->ipfb_ipf;
12118 	/* Try to find an existing fragment queue for this packet. */
12119 	for (;;) {
12120 		ipf = ipfp[0];
12121 		if (ipf != NULL) {
12122 			/*
12123 			 * It has to match on ident and src/dst address.
12124 			 */
12125 			if (ipf->ipf_ident == ident &&
12126 			    ipf->ipf_src == src &&
12127 			    ipf->ipf_dst == dst &&
12128 			    ipf->ipf_protocol == proto) {
12129 				/*
12130 				 * If we have received too many
12131 				 * duplicate fragments for this packet
12132 				 * free it.
12133 				 */
12134 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12135 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12136 					freemsg(mp);
12137 					mutex_exit(&ipfb->ipfb_lock);
12138 					return (B_FALSE);
12139 				}
12140 				/* Found it. */
12141 				break;
12142 			}
12143 			ipfp = &ipf->ipf_hash_next;
12144 			continue;
12145 		}
12146 
12147 		/*
12148 		 * If we pruned the list, do we want to store this new
12149 		 * fragment?. We apply an optimization here based on the
12150 		 * fact that most fragments will be received in order.
12151 		 * So if the offset of this incoming fragment is zero,
12152 		 * it is the first fragment of a new packet. We will
12153 		 * keep it.  Otherwise drop the fragment, as we have
12154 		 * probably pruned the packet already (since the
12155 		 * packet cannot be found).
12156 		 */
12157 		if (pruned && offset != 0) {
12158 			mutex_exit(&ipfb->ipfb_lock);
12159 			freemsg(mp);
12160 			return (B_FALSE);
12161 		}
12162 
12163 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12164 			/*
12165 			 * Too many fragmented packets in this hash
12166 			 * bucket. Free the oldest.
12167 			 */
12168 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12169 		}
12170 
12171 		/* New guy.  Allocate a frag message. */
12172 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12173 		if (mp1 == NULL) {
12174 			BUMP_MIB(&ip_mib, ipInDiscards);
12175 			freemsg(mp);
12176 reass_done:
12177 			mutex_exit(&ipfb->ipfb_lock);
12178 			return (B_FALSE);
12179 		}
12180 
12181 
12182 		BUMP_MIB(&ip_mib, ipReasmReqds);
12183 		mp1->b_cont = mp;
12184 
12185 		/* Initialize the fragment header. */
12186 		ipf = (ipf_t *)mp1->b_rptr;
12187 		ipf->ipf_mp = mp1;
12188 		ipf->ipf_ptphn = ipfp;
12189 		ipfp[0] = ipf;
12190 		ipf->ipf_hash_next = NULL;
12191 		ipf->ipf_ident = ident;
12192 		ipf->ipf_protocol = proto;
12193 		ipf->ipf_src = src;
12194 		ipf->ipf_dst = dst;
12195 		ipf->ipf_nf_hdr_len = 0;
12196 		/* Record reassembly start time. */
12197 		ipf->ipf_timestamp = gethrestime_sec();
12198 		/* Record ipf generation and account for frag header */
12199 		ipf->ipf_gen = ill->ill_ipf_gen++;
12200 		ipf->ipf_count = MBLKSIZE(mp1);
12201 		ipf->ipf_last_frag_seen = B_FALSE;
12202 		ipf->ipf_ecn = ecn_info;
12203 		ipf->ipf_num_dups = 0;
12204 		ipfb->ipfb_frag_pkts++;
12205 		ipf->ipf_checksum = 0;
12206 		ipf->ipf_checksum_flags = 0;
12207 
12208 		/* Store checksum value in fragment header */
12209 		if (sum_flags != 0) {
12210 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12211 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12212 			ipf->ipf_checksum = sum_val;
12213 			ipf->ipf_checksum_flags = sum_flags;
12214 		}
12215 
12216 		/*
12217 		 * We handle reassembly two ways.  In the easy case,
12218 		 * where all the fragments show up in order, we do
12219 		 * minimal bookkeeping, and just clip new pieces on
12220 		 * the end.  If we ever see a hole, then we go off
12221 		 * to ip_reassemble which has to mark the pieces and
12222 		 * keep track of the number of holes, etc.  Obviously,
12223 		 * the point of having both mechanisms is so we can
12224 		 * handle the easy case as efficiently as possible.
12225 		 */
12226 		if (offset == 0) {
12227 			/* Easy case, in-order reassembly so far. */
12228 			ipf->ipf_count += msg_len;
12229 			ipf->ipf_tail_mp = tail_mp;
12230 			/*
12231 			 * Keep track of next expected offset in
12232 			 * ipf_end.
12233 			 */
12234 			ipf->ipf_end = end;
12235 			ipf->ipf_nf_hdr_len = hdr_length;
12236 		} else {
12237 			/* Hard case, hole at the beginning. */
12238 			ipf->ipf_tail_mp = NULL;
12239 			/*
12240 			 * ipf_end == 0 means that we have given up
12241 			 * on easy reassembly.
12242 			 */
12243 			ipf->ipf_end = 0;
12244 
12245 			/* Forget checksum offload from now on */
12246 			ipf->ipf_checksum_flags = 0;
12247 
12248 			/*
12249 			 * ipf_hole_cnt is set by ip_reassemble.
12250 			 * ipf_count is updated by ip_reassemble.
12251 			 * No need to check for return value here
12252 			 * as we don't expect reassembly to complete
12253 			 * or fail for the first fragment itself.
12254 			 */
12255 			(void) ip_reassemble(mp, ipf,
12256 			    (frag_offset_flags & IPH_OFFSET) << 3,
12257 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12258 		}
12259 		/* Update per ipfb and ill byte counts */
12260 		ipfb->ipfb_count += ipf->ipf_count;
12261 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12262 		ill->ill_frag_count += ipf->ipf_count;
12263 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12264 		/* If the frag timer wasn't already going, start it. */
12265 		mutex_enter(&ill->ill_lock);
12266 		ill_frag_timer_start(ill);
12267 		mutex_exit(&ill->ill_lock);
12268 		goto reass_done;
12269 	}
12270 
12271 	/*
12272 	 * If the packet's flag has changed (it could be coming up
12273 	 * from an interface different than the previous, therefore
12274 	 * possibly different checksum capability), then forget about
12275 	 * any stored checksum states.  Otherwise add the value to
12276 	 * the existing one stored in the fragment header.
12277 	 */
12278 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12279 		sum_val += ipf->ipf_checksum;
12280 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12281 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12282 		ipf->ipf_checksum = sum_val;
12283 	} else if (ipf->ipf_checksum_flags != 0) {
12284 		/* Forget checksum offload from now on */
12285 		ipf->ipf_checksum_flags = 0;
12286 	}
12287 
12288 	/*
12289 	 * We have a new piece of a datagram which is already being
12290 	 * reassembled.  Update the ECN info if all IP fragments
12291 	 * are ECN capable.  If there is one which is not, clear
12292 	 * all the info.  If there is at least one which has CE
12293 	 * code point, IP needs to report that up to transport.
12294 	 */
12295 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12296 		if (ecn_info == IPH_ECN_CE)
12297 			ipf->ipf_ecn = IPH_ECN_CE;
12298 	} else {
12299 		ipf->ipf_ecn = IPH_ECN_NECT;
12300 	}
12301 	if (offset && ipf->ipf_end == offset) {
12302 		/* The new fragment fits at the end */
12303 		ipf->ipf_tail_mp->b_cont = mp;
12304 		/* Update the byte count */
12305 		ipf->ipf_count += msg_len;
12306 		/* Update per ipfb and ill byte counts */
12307 		ipfb->ipfb_count += msg_len;
12308 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12309 		ill->ill_frag_count += msg_len;
12310 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12311 		if (frag_offset_flags & IPH_MF) {
12312 			/* More to come. */
12313 			ipf->ipf_end = end;
12314 			ipf->ipf_tail_mp = tail_mp;
12315 			goto reass_done;
12316 		}
12317 	} else {
12318 		/* Go do the hard cases. */
12319 		int ret;
12320 
12321 		if (offset == 0)
12322 			ipf->ipf_nf_hdr_len = hdr_length;
12323 
12324 		/* Save current byte count */
12325 		count = ipf->ipf_count;
12326 		ret = ip_reassemble(mp, ipf,
12327 		    (frag_offset_flags & IPH_OFFSET) << 3,
12328 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12329 		/* Count of bytes added and subtracted (freeb()ed) */
12330 		count = ipf->ipf_count - count;
12331 		if (count) {
12332 			/* Update per ipfb and ill byte counts */
12333 			ipfb->ipfb_count += count;
12334 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12335 			ill->ill_frag_count += count;
12336 			ASSERT(ill->ill_frag_count > 0);
12337 		}
12338 		if (ret == IP_REASS_PARTIAL) {
12339 			goto reass_done;
12340 		} else if (ret == IP_REASS_FAILED) {
12341 			/* Reassembly failed. Free up all resources */
12342 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12343 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12344 				IP_REASS_SET_START(t_mp, 0);
12345 				IP_REASS_SET_END(t_mp, 0);
12346 			}
12347 			freemsg(mp);
12348 			goto reass_done;
12349 		}
12350 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12351 	}
12352 	/*
12353 	 * We have completed reassembly.  Unhook the frag header from
12354 	 * the reassembly list.
12355 	 *
12356 	 * Before we free the frag header, record the ECN info
12357 	 * to report back to the transport.
12358 	 */
12359 	ecn_info = ipf->ipf_ecn;
12360 	BUMP_MIB(&ip_mib, ipReasmOKs);
12361 	ipfp = ipf->ipf_ptphn;
12362 
12363 	/* We need to supply these to caller */
12364 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12365 		sum_val = ipf->ipf_checksum;
12366 	else
12367 		sum_val = 0;
12368 
12369 	mp1 = ipf->ipf_mp;
12370 	count = ipf->ipf_count;
12371 	ipf = ipf->ipf_hash_next;
12372 	if (ipf != NULL)
12373 		ipf->ipf_ptphn = ipfp;
12374 	ipfp[0] = ipf;
12375 	ill->ill_frag_count -= count;
12376 	ASSERT(ipfb->ipfb_count >= count);
12377 	ipfb->ipfb_count -= count;
12378 	ipfb->ipfb_frag_pkts--;
12379 	mutex_exit(&ipfb->ipfb_lock);
12380 	/* Ditch the frag header. */
12381 	mp = mp1->b_cont;
12382 
12383 	freeb(mp1);
12384 
12385 	/* Restore original IP length in header. */
12386 	packet_size = (uint32_t)msgdsize(mp);
12387 	if (packet_size > IP_MAXPACKET) {
12388 		freemsg(mp);
12389 		BUMP_MIB(&ip_mib, ipInHdrErrors);
12390 		return (B_FALSE);
12391 	}
12392 
12393 	if (DB_REF(mp) > 1) {
12394 		mblk_t *mp2 = copymsg(mp);
12395 
12396 		freemsg(mp);
12397 		if (mp2 == NULL) {
12398 			BUMP_MIB(&ip_mib, ipInDiscards);
12399 			return (B_FALSE);
12400 		}
12401 		mp = mp2;
12402 	}
12403 	ipha = (ipha_t *)mp->b_rptr;
12404 
12405 	ipha->ipha_length = htons((uint16_t)packet_size);
12406 	/* We're now complete, zip the frag state */
12407 	ipha->ipha_fragment_offset_and_flags = 0;
12408 	/* Record the ECN info. */
12409 	ipha->ipha_type_of_service &= 0xFC;
12410 	ipha->ipha_type_of_service |= ecn_info;
12411 	*mpp = mp;
12412 
12413 	/* Reassembly is successful; return checksum information if needed */
12414 	if (cksum_val != NULL)
12415 		*cksum_val = sum_val;
12416 	if (cksum_flags != NULL)
12417 		*cksum_flags = sum_flags;
12418 
12419 	return (B_TRUE);
12420 }
12421 
12422 /*
12423  * Perform ip header check sum update local options.
12424  * return B_TRUE if all is well, else return B_FALSE and release
12425  * the mp. caller is responsible for decrementing ire ref cnt.
12426  */
12427 static boolean_t
12428 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12429 {
12430 	mblk_t		*first_mp;
12431 	boolean_t	mctl_present;
12432 	uint16_t	sum;
12433 
12434 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12435 	/*
12436 	 * Don't do the checksum if it has gone through AH/ESP
12437 	 * processing.
12438 	 */
12439 	if (!mctl_present) {
12440 		sum = ip_csum_hdr(ipha);
12441 		if (sum != 0) {
12442 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12443 			freemsg(first_mp);
12444 			return (B_FALSE);
12445 		}
12446 	}
12447 
12448 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12449 		if (mctl_present)
12450 			freeb(first_mp);
12451 		return (B_FALSE);
12452 	}
12453 
12454 	return (B_TRUE);
12455 }
12456 
12457 /*
12458  * All udp packet are delivered to the local host via this routine.
12459  */
12460 void
12461 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12462     ill_t *recv_ill)
12463 {
12464 	uint32_t	sum;
12465 	uint32_t	u1;
12466 	boolean_t	mctl_present;
12467 	conn_t		*connp;
12468 	mblk_t		*first_mp;
12469 	uint16_t	*up;
12470 	ill_t		*ill = (ill_t *)q->q_ptr;
12471 	uint16_t	reass_hck_flags = 0;
12472 
12473 #define	rptr    ((uchar_t *)ipha)
12474 
12475 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12476 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12477 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12478 
12479 	/*
12480 	 * FAST PATH for udp packets
12481 	 */
12482 
12483 	/* u1 is # words of IP options */
12484 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12485 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12486 
12487 	/* IP options present */
12488 	if (u1 != 0)
12489 		goto ipoptions;
12490 
12491 	/* Check the IP header checksum.  */
12492 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12493 		/* Clear the IP header h/w cksum flag */
12494 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12495 	} else {
12496 #define	uph	((uint16_t *)ipha)
12497 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12498 		    uph[6] + uph[7] + uph[8] + uph[9];
12499 #undef	uph
12500 		/* finish doing IP checksum */
12501 		sum = (sum & 0xFFFF) + (sum >> 16);
12502 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12503 		/*
12504 		 * Don't verify header checksum if this packet is coming
12505 		 * back from AH/ESP as we already did it.
12506 		 */
12507 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12508 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12509 			freemsg(first_mp);
12510 			return;
12511 		}
12512 	}
12513 
12514 	/*
12515 	 * Count for SNMP of inbound packets for ire.
12516 	 * if mctl is present this might be a secure packet and
12517 	 * has already been counted for in ip_proto_input().
12518 	 */
12519 	if (!mctl_present) {
12520 		UPDATE_IB_PKT_COUNT(ire);
12521 		ire->ire_last_used_time = lbolt;
12522 	}
12523 
12524 	/* packet part of fragmented IP packet? */
12525 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12526 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12527 		goto fragmented;
12528 	}
12529 
12530 	/* u1 = IP header length (20 bytes) */
12531 	u1 = IP_SIMPLE_HDR_LENGTH;
12532 
12533 	/* packet does not contain complete IP & UDP headers */
12534 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12535 		goto udppullup;
12536 
12537 	/* up points to UDP header */
12538 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12539 #define	iphs    ((uint16_t *)ipha)
12540 
12541 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12542 	if (up[3] != 0) {
12543 		mblk_t *mp1 = mp->b_cont;
12544 		boolean_t cksum_err;
12545 		uint16_t hck_flags = 0;
12546 
12547 		/* Pseudo-header checksum */
12548 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12549 		    iphs[9] + up[2];
12550 
12551 		/*
12552 		 * Revert to software checksum calculation if the interface
12553 		 * isn't capable of checksum offload or if IPsec is present.
12554 		 */
12555 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12556 			hck_flags = DB_CKSUMFLAGS(mp);
12557 
12558 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12559 			IP_STAT(ip_in_sw_cksum);
12560 
12561 		IP_CKSUM_RECV(hck_flags, u1,
12562 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12563 		    (int32_t)((uchar_t *)up - rptr),
12564 		    mp, mp1, cksum_err);
12565 
12566 		if (cksum_err) {
12567 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12568 
12569 			if (hck_flags & HCK_FULLCKSUM)
12570 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12571 			else if (hck_flags & HCK_PARTIALCKSUM)
12572 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12573 			else
12574 				IP_STAT(ip_udp_in_sw_cksum_err);
12575 
12576 			freemsg(first_mp);
12577 			return;
12578 		}
12579 	}
12580 
12581 	/* Non-fragmented broadcast or multicast packet? */
12582 	if (ire->ire_type == IRE_BROADCAST)
12583 		goto udpslowpath;
12584 
12585 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12586 	    ire->ire_zoneid)) != NULL) {
12587 		ASSERT(connp->conn_upq != NULL);
12588 		IP_STAT(ip_udp_fast_path);
12589 
12590 		if (CONN_UDP_FLOWCTLD(connp)) {
12591 			freemsg(mp);
12592 			BUMP_MIB(&ip_mib, udpInOverflows);
12593 		} else {
12594 			if (!mctl_present) {
12595 				BUMP_MIB(&ip_mib, ipInDelivers);
12596 			}
12597 			/*
12598 			 * mp and first_mp can change.
12599 			 */
12600 			if (ip_udp_check(q, connp, recv_ill,
12601 			    ipha, &mp, &first_mp, mctl_present)) {
12602 				/* Send it upstream */
12603 				CONN_UDP_RECV(connp, mp);
12604 			}
12605 		}
12606 		/*
12607 		 * freeb() cannot deal with null mblk being passed
12608 		 * in and first_mp can be set to null in the call
12609 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12610 		 */
12611 		if (mctl_present && first_mp != NULL) {
12612 			freeb(first_mp);
12613 		}
12614 		CONN_DEC_REF(connp);
12615 		return;
12616 	}
12617 
12618 	/*
12619 	 * if we got here we know the packet is not fragmented and
12620 	 * has no options. The classifier could not find a conn_t and
12621 	 * most likely its an icmp packet so send it through slow path.
12622 	 */
12623 
12624 	goto udpslowpath;
12625 
12626 ipoptions:
12627 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12628 		goto slow_done;
12629 	}
12630 
12631 	UPDATE_IB_PKT_COUNT(ire);
12632 	ire->ire_last_used_time = lbolt;
12633 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12634 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12635 fragmented:
12636 		/*
12637 		 * "sum" and "reass_hck_flags" are non-zero if the
12638 		 * reassembled packet has a valid hardware computed
12639 		 * checksum information associated with it.
12640 		 */
12641 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12642 			goto slow_done;
12643 		/*
12644 		 * Make sure that first_mp points back to mp as
12645 		 * the mp we came in with could have changed in
12646 		 * ip_rput_fragment().
12647 		 */
12648 		ASSERT(!mctl_present);
12649 		ipha = (ipha_t *)mp->b_rptr;
12650 		first_mp = mp;
12651 	}
12652 
12653 	/* Now we have a complete datagram, destined for this machine. */
12654 	u1 = IPH_HDR_LENGTH(ipha);
12655 	/* Pull up the UDP header, if necessary. */
12656 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12657 udppullup:
12658 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12659 			BUMP_MIB(&ip_mib, ipInDiscards);
12660 			freemsg(first_mp);
12661 			goto slow_done;
12662 		}
12663 		ipha = (ipha_t *)mp->b_rptr;
12664 	}
12665 
12666 	/*
12667 	 * Validate the checksum for the reassembled packet; for the
12668 	 * pullup case we calculate the payload checksum in software.
12669 	 */
12670 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12671 	if (up[3] != 0) {
12672 		boolean_t cksum_err;
12673 
12674 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12675 			IP_STAT(ip_in_sw_cksum);
12676 
12677 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12678 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12679 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12680 		    iphs[9] + up[2], sum, cksum_err);
12681 
12682 		if (cksum_err) {
12683 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12684 
12685 			if (reass_hck_flags & HCK_FULLCKSUM)
12686 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12687 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12688 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12689 			else
12690 				IP_STAT(ip_udp_in_sw_cksum_err);
12691 
12692 			freemsg(first_mp);
12693 			goto slow_done;
12694 		}
12695 	}
12696 udpslowpath:
12697 
12698 	/* Clear hardware checksum flag to be safe */
12699 	DB_CKSUMFLAGS(mp) = 0;
12700 
12701 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12702 	    (ire->ire_type == IRE_BROADCAST),
12703 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12704 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12705 
12706 slow_done:
12707 	IP_STAT(ip_udp_slow_path);
12708 	return;
12709 
12710 #undef  iphs
12711 #undef  rptr
12712 }
12713 
12714 /* ARGSUSED */
12715 static mblk_t *
12716 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12717     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12718     ill_rx_ring_t *ill_ring)
12719 {
12720 	conn_t		*connp;
12721 	uint32_t	sum;
12722 	uint32_t	u1;
12723 	uint16_t	*up;
12724 	int		offset;
12725 	ssize_t		len;
12726 	mblk_t		*mp1;
12727 	boolean_t	syn_present = B_FALSE;
12728 	tcph_t		*tcph;
12729 	uint_t		ip_hdr_len;
12730 	ill_t		*ill = (ill_t *)q->q_ptr;
12731 	zoneid_t	zoneid = ire->ire_zoneid;
12732 	boolean_t	cksum_err;
12733 	uint16_t	hck_flags = 0;
12734 
12735 #define	rptr	((uchar_t *)ipha)
12736 
12737 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12738 
12739 	/*
12740 	 * FAST PATH for tcp packets
12741 	 */
12742 
12743 	/* u1 is # words of IP options */
12744 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12745 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12746 
12747 	/* IP options present */
12748 	if (u1) {
12749 		goto ipoptions;
12750 	} else {
12751 		/* Check the IP header checksum.  */
12752 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12753 			/* Clear the IP header h/w cksum flag */
12754 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12755 		} else {
12756 #define	uph	((uint16_t *)ipha)
12757 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12758 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12759 #undef	uph
12760 			/* finish doing IP checksum */
12761 			sum = (sum & 0xFFFF) + (sum >> 16);
12762 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12763 			/*
12764 			 * Don't verify header checksum if this packet
12765 			 * is coming back from AH/ESP as we already did it.
12766 			 */
12767 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12768 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12769 				goto error;
12770 			}
12771 		}
12772 	}
12773 
12774 	if (!mctl_present) {
12775 		UPDATE_IB_PKT_COUNT(ire);
12776 		ire->ire_last_used_time = lbolt;
12777 	}
12778 
12779 	/* packet part of fragmented IP packet? */
12780 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12781 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12782 		goto fragmented;
12783 	}
12784 
12785 	/* u1 = IP header length (20 bytes) */
12786 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12787 
12788 	/* does packet contain IP+TCP headers? */
12789 	len = mp->b_wptr - rptr;
12790 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12791 		IP_STAT(ip_tcppullup);
12792 		goto tcppullup;
12793 	}
12794 
12795 	/* TCP options present? */
12796 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12797 
12798 	/*
12799 	 * If options need to be pulled up, then goto tcpoptions.
12800 	 * otherwise we are still in the fast path
12801 	 */
12802 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12803 		IP_STAT(ip_tcpoptions);
12804 		goto tcpoptions;
12805 	}
12806 
12807 	/* multiple mblks of tcp data? */
12808 	if ((mp1 = mp->b_cont) != NULL) {
12809 		/* more then two? */
12810 		if (mp1->b_cont != NULL) {
12811 			IP_STAT(ip_multipkttcp);
12812 			goto multipkttcp;
12813 		}
12814 		len += mp1->b_wptr - mp1->b_rptr;
12815 	}
12816 
12817 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12818 
12819 	/* part of pseudo checksum */
12820 
12821 	/* TCP datagram length */
12822 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12823 
12824 #define	iphs    ((uint16_t *)ipha)
12825 
12826 #ifdef	_BIG_ENDIAN
12827 	u1 += IPPROTO_TCP;
12828 #else
12829 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12830 #endif
12831 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12832 
12833 	/*
12834 	 * Revert to software checksum calculation if the interface
12835 	 * isn't capable of checksum offload or if IPsec is present.
12836 	 */
12837 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12838 		hck_flags = DB_CKSUMFLAGS(mp);
12839 
12840 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12841 		IP_STAT(ip_in_sw_cksum);
12842 
12843 	IP_CKSUM_RECV(hck_flags, u1,
12844 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12845 	    (int32_t)((uchar_t *)up - rptr),
12846 	    mp, mp1, cksum_err);
12847 
12848 	if (cksum_err) {
12849 		BUMP_MIB(&ip_mib, tcpInErrs);
12850 
12851 		if (hck_flags & HCK_FULLCKSUM)
12852 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12853 		else if (hck_flags & HCK_PARTIALCKSUM)
12854 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12855 		else
12856 			IP_STAT(ip_tcp_in_sw_cksum_err);
12857 
12858 		goto error;
12859 	}
12860 
12861 try_again:
12862 
12863 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12864 	    NULL) {
12865 		/* Send the TH_RST */
12866 		goto no_conn;
12867 	}
12868 
12869 	/*
12870 	 * TCP FAST PATH for AF_INET socket.
12871 	 *
12872 	 * TCP fast path to avoid extra work. An AF_INET socket type
12873 	 * does not have facility to receive extra information via
12874 	 * ip_process or ip_add_info. Also, when the connection was
12875 	 * established, we made a check if this connection is impacted
12876 	 * by any global IPSec policy or per connection policy (a
12877 	 * policy that comes in effect later will not apply to this
12878 	 * connection). Since all this can be determined at the
12879 	 * connection establishment time, a quick check of flags
12880 	 * can avoid extra work.
12881 	 */
12882 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12883 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12884 		ASSERT(first_mp == mp);
12885 		SET_SQUEUE(mp, tcp_rput_data, connp);
12886 		return (mp);
12887 	}
12888 
12889 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12890 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12891 		if (IPCL_IS_TCP(connp)) {
12892 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12893 			DB_CKSUMSTART(mp) =
12894 			    (intptr_t)ip_squeue_get(ill_ring);
12895 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12896 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12897 				SET_SQUEUE(mp, connp->conn_recv, connp);
12898 				return (mp);
12899 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12900 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12901 				ip_squeue_enter_unbound++;
12902 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12903 				    connp);
12904 				return (mp);
12905 			}
12906 			syn_present = B_TRUE;
12907 		}
12908 
12909 	}
12910 
12911 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12912 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12913 
12914 		/* No need to send this packet to TCP */
12915 		if ((flags & TH_RST) || (flags & TH_URG)) {
12916 			CONN_DEC_REF(connp);
12917 			freemsg(first_mp);
12918 			return (NULL);
12919 		}
12920 		if (flags & TH_ACK) {
12921 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
12922 			CONN_DEC_REF(connp);
12923 			return (NULL);
12924 		}
12925 
12926 		CONN_DEC_REF(connp);
12927 		freemsg(first_mp);
12928 		return (NULL);
12929 	}
12930 
12931 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12932 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12933 		    ipha, NULL, mctl_present);
12934 		if (first_mp == NULL) {
12935 			CONN_DEC_REF(connp);
12936 			return (NULL);
12937 		}
12938 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12939 			ASSERT(syn_present);
12940 			if (mctl_present) {
12941 				ASSERT(first_mp != mp);
12942 				first_mp->b_datap->db_struioflag |=
12943 				    STRUIO_POLICY;
12944 			} else {
12945 				ASSERT(first_mp == mp);
12946 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12947 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12948 			}
12949 		} else {
12950 			/*
12951 			 * Discard first_mp early since we're dealing with a
12952 			 * fully-connected conn_t and tcp doesn't do policy in
12953 			 * this case.
12954 			 */
12955 			if (mctl_present) {
12956 				freeb(first_mp);
12957 				mctl_present = B_FALSE;
12958 			}
12959 			first_mp = mp;
12960 		}
12961 	}
12962 
12963 	/* Initiate IPPF processing for fastpath */
12964 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12965 		uint32_t	ill_index;
12966 
12967 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12968 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12969 		if (mp == NULL) {
12970 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12971 			    "deferred/dropped during IPPF processing\n"));
12972 			CONN_DEC_REF(connp);
12973 			if (mctl_present)
12974 				freeb(first_mp);
12975 			return (NULL);
12976 		} else if (mctl_present) {
12977 			/*
12978 			 * ip_process might return a new mp.
12979 			 */
12980 			ASSERT(first_mp != mp);
12981 			first_mp->b_cont = mp;
12982 		} else {
12983 			first_mp = mp;
12984 		}
12985 
12986 	}
12987 
12988 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12989 		mp = ip_add_info(mp, recv_ill, flags);
12990 		if (mp == NULL) {
12991 			CONN_DEC_REF(connp);
12992 			if (mctl_present)
12993 				freeb(first_mp);
12994 			return (NULL);
12995 		} else if (mctl_present) {
12996 			/*
12997 			 * ip_add_info might return a new mp.
12998 			 */
12999 			ASSERT(first_mp != mp);
13000 			first_mp->b_cont = mp;
13001 		} else {
13002 			first_mp = mp;
13003 		}
13004 	}
13005 
13006 	if (IPCL_IS_TCP(connp)) {
13007 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13008 		return (first_mp);
13009 	} else {
13010 		putnext(connp->conn_rq, first_mp);
13011 		CONN_DEC_REF(connp);
13012 		return (NULL);
13013 	}
13014 
13015 no_conn:
13016 	/* Initiate IPPf processing, if needed. */
13017 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13018 		uint32_t ill_index;
13019 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13020 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13021 		if (first_mp == NULL) {
13022 			return (NULL);
13023 		}
13024 	}
13025 	BUMP_MIB(&ip_mib, ipInDelivers);
13026 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid);
13027 	return (NULL);
13028 ipoptions:
13029 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
13030 		goto slow_done;
13031 	}
13032 
13033 	UPDATE_IB_PKT_COUNT(ire);
13034 	ire->ire_last_used_time = lbolt;
13035 
13036 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13037 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13038 fragmented:
13039 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13040 			if (mctl_present)
13041 				freeb(first_mp);
13042 			goto slow_done;
13043 		}
13044 		/*
13045 		 * Make sure that first_mp points back to mp as
13046 		 * the mp we came in with could have changed in
13047 		 * ip_rput_fragment().
13048 		 */
13049 		ASSERT(!mctl_present);
13050 		ipha = (ipha_t *)mp->b_rptr;
13051 		first_mp = mp;
13052 	}
13053 
13054 	/* Now we have a complete datagram, destined for this machine. */
13055 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13056 
13057 	len = mp->b_wptr - mp->b_rptr;
13058 	/* Pull up a minimal TCP header, if necessary. */
13059 	if (len < (u1 + 20)) {
13060 tcppullup:
13061 		if (!pullupmsg(mp, u1 + 20)) {
13062 			BUMP_MIB(&ip_mib, ipInDiscards);
13063 			goto error;
13064 		}
13065 		ipha = (ipha_t *)mp->b_rptr;
13066 		len = mp->b_wptr - mp->b_rptr;
13067 	}
13068 
13069 	/*
13070 	 * Extract the offset field from the TCP header.  As usual, we
13071 	 * try to help the compiler more than the reader.
13072 	 */
13073 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13074 	if (offset != 5) {
13075 tcpoptions:
13076 		if (offset < 5) {
13077 			BUMP_MIB(&ip_mib, ipInDiscards);
13078 			goto error;
13079 		}
13080 		/*
13081 		 * There must be TCP options.
13082 		 * Make sure we can grab them.
13083 		 */
13084 		offset <<= 2;
13085 		offset += u1;
13086 		if (len < offset) {
13087 			if (!pullupmsg(mp, offset)) {
13088 				BUMP_MIB(&ip_mib, ipInDiscards);
13089 				goto error;
13090 			}
13091 			ipha = (ipha_t *)mp->b_rptr;
13092 			len = mp->b_wptr - rptr;
13093 		}
13094 	}
13095 
13096 	/* Get the total packet length in len, including headers. */
13097 	if (mp->b_cont) {
13098 multipkttcp:
13099 		len = msgdsize(mp);
13100 	}
13101 
13102 	/*
13103 	 * Check the TCP checksum by pulling together the pseudo-
13104 	 * header checksum, and passing it to ip_csum to be added in
13105 	 * with the TCP datagram.
13106 	 *
13107 	 * Since we are not using the hwcksum if available we must
13108 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13109 	 * If either of these fails along the way the mblk is freed.
13110 	 * If this logic ever changes and mblk is reused to say send
13111 	 * ICMP's back, then this flag may need to be cleared in
13112 	 * other places as well.
13113 	 */
13114 	DB_CKSUMFLAGS(mp) = 0;
13115 
13116 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13117 
13118 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13119 #ifdef	_BIG_ENDIAN
13120 	u1 += IPPROTO_TCP;
13121 #else
13122 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13123 #endif
13124 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13125 	/*
13126 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13127 	 */
13128 	IP_STAT(ip_in_sw_cksum);
13129 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13130 		BUMP_MIB(&ip_mib, tcpInErrs);
13131 		goto error;
13132 	}
13133 
13134 	IP_STAT(ip_tcp_slow_path);
13135 	goto try_again;
13136 #undef  iphs
13137 #undef  rptr
13138 
13139 error:
13140 	freemsg(first_mp);
13141 slow_done:
13142 	return (NULL);
13143 }
13144 
13145 /* ARGSUSED */
13146 static void
13147 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13148     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13149 {
13150 	conn_t		*connp;
13151 	uint32_t	sum;
13152 	uint32_t	u1;
13153 	ssize_t		len;
13154 	sctp_hdr_t	*sctph;
13155 	zoneid_t	zoneid = ire->ire_zoneid;
13156 	uint32_t	pktsum;
13157 	uint32_t	calcsum;
13158 	uint32_t	ports;
13159 	uint_t		ipif_seqid;
13160 	in6_addr_t	map_src, map_dst;
13161 	ill_t		*ill = (ill_t *)q->q_ptr;
13162 
13163 #define	rptr	((uchar_t *)ipha)
13164 
13165 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13166 
13167 	/* u1 is # words of IP options */
13168 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13169 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13170 
13171 	/* IP options present */
13172 	if (u1 > 0) {
13173 		goto ipoptions;
13174 	} else {
13175 		/* Check the IP header checksum.  */
13176 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13177 #define	uph	((uint16_t *)ipha)
13178 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13179 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13180 #undef	uph
13181 			/* finish doing IP checksum */
13182 			sum = (sum & 0xFFFF) + (sum >> 16);
13183 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13184 			/*
13185 			 * Don't verify header checksum if this packet
13186 			 * is coming back from AH/ESP as we already did it.
13187 			 */
13188 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13189 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13190 				goto error;
13191 			}
13192 		}
13193 		/*
13194 		 * Since there is no SCTP h/w cksum support yet, just
13195 		 * clear the flag.
13196 		 */
13197 		DB_CKSUMFLAGS(mp) = 0;
13198 	}
13199 
13200 	/*
13201 	 * Don't verify header checksum if this packet is coming
13202 	 * back from AH/ESP as we already did it.
13203 	 */
13204 	if (!mctl_present) {
13205 		UPDATE_IB_PKT_COUNT(ire);
13206 		ire->ire_last_used_time = lbolt;
13207 	}
13208 
13209 	/* packet part of fragmented IP packet? */
13210 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13211 	if (u1 & (IPH_MF | IPH_OFFSET))
13212 		goto fragmented;
13213 
13214 	/* u1 = IP header length (20 bytes) */
13215 	u1 = IP_SIMPLE_HDR_LENGTH;
13216 
13217 find_sctp_client:
13218 	/* Pullup if we don't have the sctp common header. */
13219 	len = MBLKL(mp);
13220 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13221 		if (mp->b_cont == NULL ||
13222 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13223 			BUMP_MIB(&ip_mib, ipInDiscards);
13224 			goto error;
13225 		}
13226 		ipha = (ipha_t *)mp->b_rptr;
13227 		len = MBLKL(mp);
13228 	}
13229 
13230 	sctph = (sctp_hdr_t *)(rptr + u1);
13231 #ifdef	DEBUG
13232 	if (!skip_sctp_cksum) {
13233 #endif
13234 		pktsum = sctph->sh_chksum;
13235 		sctph->sh_chksum = 0;
13236 		calcsum = sctp_cksum(mp, u1);
13237 		if (calcsum != pktsum) {
13238 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13239 			goto error;
13240 		}
13241 		sctph->sh_chksum = pktsum;
13242 #ifdef	DEBUG	/* skip_sctp_cksum */
13243 	}
13244 #endif
13245 	/* get the ports */
13246 	ports = *(uint32_t *)&sctph->sh_sport;
13247 
13248 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13249 	IRE_REFRELE(ire);
13250 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13251 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13252 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13253 	    mp)) == NULL) {
13254 		/* Check for raw socket or OOTB handling */
13255 		goto no_conn;
13256 	}
13257 
13258 	/* Found a client; up it goes */
13259 	BUMP_MIB(&ip_mib, ipInDelivers);
13260 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13261 	return;
13262 
13263 no_conn:
13264 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13265 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13266 	return;
13267 
13268 ipoptions:
13269 	DB_CKSUMFLAGS(mp) = 0;
13270 	if (!ip_options_cksum(q, first_mp, ipha, ire))
13271 		goto slow_done;
13272 
13273 	UPDATE_IB_PKT_COUNT(ire);
13274 	ire->ire_last_used_time = lbolt;
13275 
13276 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13277 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13278 fragmented:
13279 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13280 			goto slow_done;
13281 		/*
13282 		 * Make sure that first_mp points back to mp as
13283 		 * the mp we came in with could have changed in
13284 		 * ip_rput_fragment().
13285 		 */
13286 		ASSERT(!mctl_present);
13287 		ipha = (ipha_t *)mp->b_rptr;
13288 		first_mp = mp;
13289 	}
13290 
13291 	/* Now we have a complete datagram, destined for this machine. */
13292 	u1 = IPH_HDR_LENGTH(ipha);
13293 	goto find_sctp_client;
13294 #undef  iphs
13295 #undef  rptr
13296 
13297 error:
13298 	freemsg(first_mp);
13299 slow_done:
13300 	IRE_REFRELE(ire);
13301 }
13302 
13303 #define	VER_BITS	0xF0
13304 #define	VERSION_6	0x60
13305 
13306 static boolean_t
13307 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
13308     ipaddr_t *dstp)
13309 {
13310 	uint_t	opt_len;
13311 	ipha_t *ipha;
13312 	ssize_t len;
13313 	uint_t	pkt_len;
13314 
13315 	IP_STAT(ip_ipoptions);
13316 	ipha = *iphapp;
13317 
13318 #define	rptr    ((uchar_t *)ipha)
13319 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13320 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13321 		BUMP_MIB(&ip_mib, ipInIPv6);
13322 		freemsg(mp);
13323 		return (B_FALSE);
13324 	}
13325 
13326 	/* multiple mblk or too short */
13327 	pkt_len = ntohs(ipha->ipha_length);
13328 
13329 	/* Get the number of words of IP options in the IP header. */
13330 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13331 	if (opt_len) {
13332 		/* IP Options present!  Validate and process. */
13333 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13334 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13335 			goto done;
13336 		}
13337 		/*
13338 		 * Recompute complete header length and make sure we
13339 		 * have access to all of it.
13340 		 */
13341 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13342 		if (len > (mp->b_wptr - rptr)) {
13343 			if (len > pkt_len) {
13344 				BUMP_MIB(&ip_mib, ipInHdrErrors);
13345 				goto done;
13346 			}
13347 			if (!pullupmsg(mp, len)) {
13348 				BUMP_MIB(&ip_mib, ipInDiscards);
13349 				goto done;
13350 			}
13351 			ipha = (ipha_t *)mp->b_rptr;
13352 		}
13353 		/*
13354 		 * Go off to ip_rput_options which returns the next hop
13355 		 * destination address, which may have been affected
13356 		 * by source routing.
13357 		 */
13358 		IP_STAT(ip_opt);
13359 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13360 			return (B_FALSE);
13361 		}
13362 	}
13363 	*iphapp = ipha;
13364 	return (B_TRUE);
13365 done:
13366 	/* clear b_prev - used by ip_mroute_decap */
13367 	mp->b_prev = NULL;
13368 	freemsg(mp);
13369 	return (B_FALSE);
13370 #undef  rptr
13371 }
13372 
13373 /*
13374  * Deal with the fact that there is no ire for the destination.
13375  * The incoming ill (in_ill) is passed in to ip_newroute only
13376  * in the case of packets coming from mobile ip forward tunnel.
13377  * It must be null otherwise.
13378  */
13379 static ire_t *
13380 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13381     ipaddr_t dst)
13382 {
13383 	ipha_t	*ipha;
13384 	ill_t	*ill;
13385 	ire_t	*ire;
13386 	boolean_t	check_multirt = B_FALSE;
13387 
13388 	ipha = (ipha_t *)mp->b_rptr;
13389 	ill = (ill_t *)q->q_ptr;
13390 
13391 	ASSERT(ill != NULL);
13392 	/*
13393 	 * No IRE for this destination, so it can't be for us.
13394 	 * Unless we are forwarding, drop the packet.
13395 	 * We have to let source routed packets through
13396 	 * since we don't yet know if they are 'ping -l'
13397 	 * packets i.e. if they will go out over the
13398 	 * same interface as they came in on.
13399 	 */
13400 	if (ll_multicast) {
13401 		freemsg(mp);
13402 		return (NULL);
13403 	}
13404 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13405 		BUMP_MIB(&ip_mib, ipForwProhibits);
13406 		freemsg(mp);
13407 		return (NULL);
13408 	}
13409 
13410 	/*
13411 	 * Mark this packet as having originated externally.
13412 	 *
13413 	 * For non-forwarding code path, ire_send later double
13414 	 * checks this interface to see if it is still exists
13415 	 * post-ARP resolution.
13416 	 *
13417 	 * Also, IPQOS uses this to differentiate between
13418 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13419 	 * QOS packet processing in ip_wput_attach_llhdr().
13420 	 * The QoS module can mark the b_band for a fastpath message
13421 	 * or the dl_priority field in a unitdata_req header for
13422 	 * CoS marking. This info can only be found in
13423 	 * ip_wput_attach_llhdr().
13424 	 */
13425 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13426 	/*
13427 	 * Clear the indication that this may have a hardware checksum
13428 	 * as we are not using it
13429 	 */
13430 	DB_CKSUMFLAGS(mp) = 0;
13431 
13432 	if (in_ill != NULL) {
13433 		/*
13434 		 * Now hand the packet to ip_newroute.
13435 		 */
13436 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13437 		return (NULL);
13438 	}
13439 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13440 	    MBLK_GETLABEL(mp));
13441 
13442 	if (ire == NULL && check_multirt) {
13443 		/* Let ip_newroute handle CGTP  */
13444 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13445 		return (NULL);
13446 	}
13447 
13448 	if (ire != NULL)
13449 		return (ire);
13450 
13451 	mp->b_prev = mp->b_next = 0;
13452 	/* send icmp unreachable */
13453 	q = WR(q);
13454 	/* Sent by forwarding path, and router is global zone */
13455 	if (ip_source_routed(ipha)) {
13456 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13457 		    GLOBAL_ZONEID);
13458 	} else {
13459 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13460 	}
13461 
13462 	return (NULL);
13463 
13464 }
13465 
13466 /*
13467  * check ip header length and align it.
13468  */
13469 static boolean_t
13470 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13471 {
13472 	ssize_t len;
13473 	ill_t *ill;
13474 	ipha_t	*ipha;
13475 
13476 	len = MBLKL(mp);
13477 
13478 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13479 		if (!OK_32PTR(mp->b_rptr))
13480 			IP_STAT(ip_notaligned1);
13481 		else
13482 			IP_STAT(ip_notaligned2);
13483 		/* Guard against bogus device drivers */
13484 		if (len < 0) {
13485 			/* clear b_prev - used by ip_mroute_decap */
13486 			mp->b_prev = NULL;
13487 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13488 			freemsg(mp);
13489 			return (B_FALSE);
13490 		}
13491 
13492 		if (ip_rput_pullups++ == 0) {
13493 			ill = (ill_t *)q->q_ptr;
13494 			ipha = (ipha_t *)mp->b_rptr;
13495 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13496 			    "ip_check_and_align_header: %s forced us to "
13497 			    " pullup pkt, hdr len %ld, hdr addr %p",
13498 			    ill->ill_name, len, ipha);
13499 		}
13500 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13501 			/* clear b_prev - used by ip_mroute_decap */
13502 			mp->b_prev = NULL;
13503 			BUMP_MIB(&ip_mib, ipInDiscards);
13504 			freemsg(mp);
13505 			return (B_FALSE);
13506 		}
13507 	}
13508 	return (B_TRUE);
13509 }
13510 
13511 static boolean_t
13512 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13513 {
13514 	ill_group_t	*ill_group;
13515 	ill_group_t	*ire_group;
13516 	queue_t 	*q;
13517 	ill_t		*ire_ill;
13518 	uint_t		ill_ifindex;
13519 
13520 	q = *qp;
13521 	/*
13522 	 * We need to check to make sure the packet came in
13523 	 * on the queue associated with the destination IRE.
13524 	 * Note that for multicast packets and broadcast packets sent to
13525 	 * a broadcast address which is shared between multiple interfaces
13526 	 * we should not do this since we just got a random broadcast ire.
13527 	 */
13528 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13529 		boolean_t check_multi = B_TRUE;
13530 
13531 		/*
13532 		 * This packet came in on an interface other than the
13533 		 * one associated with the destination address.
13534 		 * "Gateway" it to the appropriate interface here.
13535 		 * As long as the ills belong to the same group,
13536 		 * we don't consider them to arriving on the wrong
13537 		 * interface. Thus, when the switch is doing inbound
13538 		 * load spreading, we won't drop packets when we
13539 		 * are doing strict multihoming checks. Note, the
13540 		 * same holds true for 'usesrc groups' where the
13541 		 * destination address may belong to another interface
13542 		 * to allow multipathing to happen
13543 		 */
13544 		ill_group = ill->ill_group;
13545 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13546 		ill_ifindex = ill->ill_usesrc_ifindex;
13547 		ire_group = ire_ill->ill_group;
13548 
13549 		/*
13550 		 * If it's part of the same IPMP group, or if it's a legal
13551 		 * address on the 'usesrc' interface, then bypass strict
13552 		 * checks.
13553 		 */
13554 		if (ill_group != NULL && ill_group == ire_group) {
13555 			check_multi = B_FALSE;
13556 		} else if (ill_ifindex != 0 &&
13557 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13558 			check_multi = B_FALSE;
13559 		}
13560 
13561 		if (check_multi &&
13562 		    ip_strict_dst_multihoming &&
13563 		    ((ill->ill_flags &
13564 		    ire->ire_ipif->ipif_ill->ill_flags &
13565 		    ILLF_ROUTER) == 0)) {
13566 			/* Drop packet */
13567 			BUMP_MIB(&ip_mib, ipForwProhibits);
13568 			freemsg(mp);
13569 			return (B_TRUE);
13570 		}
13571 
13572 		/*
13573 		 * Change the queue (for non-virtual destination network
13574 		 * interfaces) and ip_rput_local will be called with the right
13575 		 * queue
13576 		 */
13577 		q = ire->ire_rfq;
13578 	}
13579 	/* Must be broadcast.  We'll take it. */
13580 	*qp = q;
13581 	return (B_FALSE);
13582 }
13583 
13584 ire_t *
13585 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13586 {
13587 	ipha_t	*ipha;
13588 	ipaddr_t ip_dst, ip_src;
13589 	ire_t	*src_ire = NULL;
13590 	ill_t	*stq_ill;
13591 	uint_t	hlen;
13592 	uint32_t sum;
13593 	queue_t	*dev_q;
13594 	boolean_t check_multirt = B_FALSE;
13595 
13596 
13597 	ipha = (ipha_t *)mp->b_rptr;
13598 
13599 	/*
13600 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13601 	 * The loopback address check for both src and dst has already
13602 	 * been checked in ip_input
13603 	 */
13604 	ip_dst = ntohl(dst);
13605 	ip_src = ntohl(ipha->ipha_src);
13606 
13607 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13608 	    IN_CLASSD(ip_src)) {
13609 		BUMP_MIB(&ip_mib, ipForwProhibits);
13610 		goto drop;
13611 	}
13612 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13613 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13614 
13615 	if (src_ire != NULL) {
13616 		BUMP_MIB(&ip_mib, ipForwProhibits);
13617 		goto drop;
13618 	}
13619 
13620 	/* No ire cache of nexthop. So first create one  */
13621 	if (ire == NULL) {
13622 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13623 		/*
13624 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13625 		 * is not set. So upon return from ire_forward
13626 		 * check_multirt should remain as false.
13627 		 */
13628 		ASSERT(!check_multirt);
13629 		if (ire == NULL) {
13630 			BUMP_MIB(&ip_mib, ipInDiscards);
13631 			mp->b_prev = mp->b_next = 0;
13632 			/* send icmp unreachable */
13633 			/* Sent by forwarding path, and router is global zone */
13634 			if (ip_source_routed(ipha)) {
13635 				icmp_unreachable(ill->ill_wq, mp,
13636 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13637 			} else {
13638 				icmp_unreachable(ill->ill_wq, mp,
13639 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13640 			}
13641 			return (ire);
13642 		}
13643 	}
13644 
13645 	/*
13646 	 * Forwarding fastpath exception case:
13647 	 * If either of the follwoing case is true, we take
13648 	 * the slowpath
13649 	 *	o forwarding is not enabled
13650 	 *	o IPMP is enabled
13651 	 *	o corresponding ire is in incomplete state
13652 	 *	o packet needs fragmentation
13653 	 *
13654 	 * The codeflow from here on is thus:
13655 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13656 	 */
13657 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13658 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13659 	    !(ill->ill_flags & ILLF_ROUTER) || SAME_IPMP_GROUP(ill, stq_ill) ||
13660 	    (ire->ire_nce == NULL) ||
13661 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13662 	    (ntohs(ipha->ipha_length) > ire->ire_max_frag) ||
13663 	    ipha->ipha_ttl <= 1) {
13664 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13665 		    ipha, ill, B_FALSE);
13666 		return (ire);
13667 	}
13668 
13669 	DTRACE_PROBE4(ip4__forwarding__start,
13670 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13671 
13672 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
13673 	    MSG_FWCOOKED_FORWARD, ill, stq_ill, ipha, mp, mp);
13674 
13675 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13676 
13677 	if (mp == NULL)
13678 		goto drop;
13679 
13680 	mp->b_datap->db_struioun.cksum.flags = 0;
13681 	/* Adjust the checksum to reflect the ttl decrement. */
13682 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13683 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13684 	ipha->ipha_ttl--;
13685 
13686 	dev_q = ire->ire_stq->q_next;
13687 	if ((dev_q->q_next != NULL ||
13688 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13689 		goto indiscard;
13690 	}
13691 
13692 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13693 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13694 
13695 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13696 		mblk_t *mpip = mp;
13697 
13698 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13699 		if (mp != NULL) {
13700 			DTRACE_PROBE4(ip4__physical__out__start,
13701 			    ill_t *, NULL, ill_t *, stq_ill,
13702 			    ipha_t *, ipha, mblk_t *, mp);
13703 			FW_HOOKS(ip4_physical_out_event,
13704 			    ipv4firewall_physical_out, MSG_FWCOOKED_OUT, NULL,
13705 			    stq_ill, ipha, mp, mpip);
13706 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13707 			    mp);
13708 			if (mp == NULL)
13709 				goto drop;
13710 
13711 			UPDATE_IB_PKT_COUNT(ire);
13712 			ire->ire_last_used_time = lbolt;
13713 			BUMP_MIB(&ip_mib, ipForwDatagrams);
13714 			putnext(ire->ire_stq, mp);
13715 			return (ire);
13716 		}
13717 	}
13718 
13719 indiscard:
13720 	BUMP_MIB(&ip_mib, ipInDiscards);
13721 drop:
13722 	if (mp != NULL)
13723 		freemsg(mp);
13724 	if (src_ire != NULL)
13725 		ire_refrele(src_ire);
13726 	return (ire);
13727 
13728 }
13729 
13730 /*
13731  * This function is called in the forwarding slowpath, when
13732  * either the ire lacks the link-layer address, or the packet needs
13733  * further processing(eg. fragmentation), before transmission.
13734  */
13735 static void
13736 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13737     ill_t *ill, boolean_t ll_multicast)
13738 {
13739 	ill_group_t	*ill_group;
13740 	ill_group_t	*ire_group;
13741 	queue_t		*dev_q;
13742 	ire_t		*src_ire;
13743 
13744 	ASSERT(ire->ire_stq != NULL);
13745 
13746 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13747 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13748 
13749 	if (ll_multicast != 0)
13750 		goto drop_pkt;
13751 
13752 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13753 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13754 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13755 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13756 		if (src_ire != NULL)
13757 			ire_refrele(src_ire);
13758 		BUMP_MIB(&ip_mib, ipForwProhibits);
13759 		ip2dbg(("ip_rput_process_forward: Received packet with"
13760 		    " bad src/dst address on %s\n", ill->ill_name));
13761 	}
13762 
13763 	ill_group = ill->ill_group;
13764 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13765 	/*
13766 	 * Check if we want to forward this one at this time.
13767 	 * We allow source routed packets on a host provided that
13768 	 * they go out the same interface or same interface group
13769 	 * as they came in on.
13770 	 *
13771 	 * XXX To be quicker, we may wish to not chase pointers to
13772 	 * get the ILLF_ROUTER flag and instead store the
13773 	 * forwarding policy in the ire.  An unfortunate
13774 	 * side-effect of that would be requiring an ire flush
13775 	 * whenever the ILLF_ROUTER flag changes.
13776 	 */
13777 	if (((ill->ill_flags &
13778 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13779 	    ILLF_ROUTER) == 0) &&
13780 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13781 	    (ill_group != NULL && ill_group == ire_group)))) {
13782 		BUMP_MIB(&ip_mib, ipForwProhibits);
13783 		if (ip_source_routed(ipha)) {
13784 			q = WR(q);
13785 			/*
13786 			 * Clear the indication that this may have
13787 			 * hardware checksum as we are not using it.
13788 			 */
13789 			DB_CKSUMFLAGS(mp) = 0;
13790 			/* Sent by forwarding path, and router is global zone */
13791 			icmp_unreachable(q, mp,
13792 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13793 			return;
13794 		}
13795 		goto drop_pkt;
13796 	}
13797 
13798 	/* Packet is being forwarded. Turning off hwcksum flag. */
13799 	DB_CKSUMFLAGS(mp) = 0;
13800 	if (ip_g_send_redirects) {
13801 		/*
13802 		 * Check whether the incoming interface and outgoing
13803 		 * interface is part of the same group. If so,
13804 		 * send redirects.
13805 		 *
13806 		 * Check the source address to see if it originated
13807 		 * on the same logical subnet it is going back out on.
13808 		 * If so, we should be able to send it a redirect.
13809 		 * Avoid sending a redirect if the destination
13810 		 * is directly connected (gw_addr == 0),
13811 		 * or if the packet was source routed out this
13812 		 * interface.
13813 		 */
13814 		ipaddr_t src;
13815 		mblk_t	*mp1;
13816 		ire_t	*src_ire = NULL;
13817 
13818 		/*
13819 		 * Check whether ire_rfq and q are from the same ill
13820 		 * or if they are not same, they at least belong
13821 		 * to the same group. If so, send redirects.
13822 		 */
13823 		if ((ire->ire_rfq == q ||
13824 		    (ill_group != NULL && ill_group == ire_group)) &&
13825 		    (ire->ire_gateway_addr != 0) &&
13826 		    !ip_source_routed(ipha)) {
13827 
13828 			src = ipha->ipha_src;
13829 			src_ire = ire_ftable_lookup(src, 0, 0,
13830 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
13831 			    0, NULL, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
13832 
13833 			if (src_ire != NULL) {
13834 				/*
13835 				 * The source is directly connected.
13836 				 * Just copy the ip header (which is
13837 				 * in the first mblk)
13838 				 */
13839 				mp1 = copyb(mp);
13840 				if (mp1 != NULL) {
13841 					icmp_send_redirect(WR(q), mp1,
13842 					    ire->ire_gateway_addr);
13843 				}
13844 				ire_refrele(src_ire);
13845 			}
13846 		}
13847 	}
13848 
13849 	dev_q = ire->ire_stq->q_next;
13850 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13851 		BUMP_MIB(&ip_mib, ipInDiscards);
13852 		freemsg(mp);
13853 		return;
13854 	}
13855 
13856 	ip_rput_forward(ire, ipha, mp, ill);
13857 	return;
13858 
13859 drop_pkt:
13860 	ip2dbg(("ip_rput_forward: drop pkt\n"));
13861 	freemsg(mp);
13862 }
13863 
13864 ire_t *
13865 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13866     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13867 {
13868 	queue_t		*q;
13869 	uint16_t	hcksumflags;
13870 
13871 	q = *qp;
13872 
13873 	/*
13874 	 * Clear the indication that this may have hardware
13875 	 * checksum as we are not using it for forwarding.
13876 	 */
13877 	hcksumflags = DB_CKSUMFLAGS(mp);
13878 	DB_CKSUMFLAGS(mp) = 0;
13879 
13880 	/*
13881 	 * Directed broadcast forwarding: if the packet came in over a
13882 	 * different interface then it is routed out over we can forward it.
13883 	 */
13884 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13885 		ire_refrele(ire);
13886 		freemsg(mp);
13887 		BUMP_MIB(&ip_mib, ipInDiscards);
13888 		return (NULL);
13889 	}
13890 	/*
13891 	 * For multicast we have set dst to be INADDR_BROADCAST
13892 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13893 	 * only for broadcast packets.
13894 	 */
13895 	if (!CLASSD(ipha->ipha_dst)) {
13896 		ire_t *new_ire;
13897 		ipif_t *ipif;
13898 		/*
13899 		 * For ill groups, as the switch duplicates broadcasts
13900 		 * across all the ports, we need to filter out and
13901 		 * send up only one copy. There is one copy for every
13902 		 * broadcast address on each ill. Thus, we look for a
13903 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13904 		 * later to see whether this ill is eligible to receive
13905 		 * them or not. ill_nominate_bcast_rcv() nominates only
13906 		 * one set of IREs for receiving.
13907 		 */
13908 
13909 		ipif = ipif_get_next_ipif(NULL, ill);
13910 		if (ipif == NULL) {
13911 			ire_refrele(ire);
13912 			freemsg(mp);
13913 			BUMP_MIB(&ip_mib, ipInDiscards);
13914 			return (NULL);
13915 		}
13916 		new_ire = ire_ctable_lookup(dst, 0, 0,
13917 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13918 		ipif_refrele(ipif);
13919 
13920 		if (new_ire != NULL) {
13921 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13922 				ire_refrele(ire);
13923 				ire_refrele(new_ire);
13924 				freemsg(mp);
13925 				BUMP_MIB(&ip_mib, ipInDiscards);
13926 				return (NULL);
13927 			}
13928 			/*
13929 			 * In the special case of multirouted broadcast
13930 			 * packets, we unconditionally need to "gateway"
13931 			 * them to the appropriate interface here.
13932 			 * In the normal case, this cannot happen, because
13933 			 * there is no broadcast IRE tagged with the
13934 			 * RTF_MULTIRT flag.
13935 			 */
13936 			if (new_ire->ire_flags & RTF_MULTIRT) {
13937 				ire_refrele(new_ire);
13938 				if (ire->ire_rfq != NULL) {
13939 					q = ire->ire_rfq;
13940 					*qp = q;
13941 				}
13942 			} else {
13943 				ire_refrele(ire);
13944 				ire = new_ire;
13945 			}
13946 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
13947 			if (!ip_g_forward_directed_bcast) {
13948 				/*
13949 				 * Free the message if
13950 				 * ip_g_forward_directed_bcast is turned
13951 				 * off for non-local broadcast.
13952 				 */
13953 				ire_refrele(ire);
13954 				freemsg(mp);
13955 				BUMP_MIB(&ip_mib, ipInDiscards);
13956 				return (NULL);
13957 			}
13958 		} else {
13959 			/*
13960 			 * This CGTP packet successfully passed the
13961 			 * CGTP filter, but the related CGTP
13962 			 * broadcast IRE has not been found,
13963 			 * meaning that the redundant ipif is
13964 			 * probably down. However, if we discarded
13965 			 * this packet, its duplicate would be
13966 			 * filtered out by the CGTP filter so none
13967 			 * of them would get through. So we keep
13968 			 * going with this one.
13969 			 */
13970 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
13971 			if (ire->ire_rfq != NULL) {
13972 				q = ire->ire_rfq;
13973 				*qp = q;
13974 			}
13975 		}
13976 	}
13977 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
13978 		/*
13979 		 * Verify that there are not more then one
13980 		 * IRE_BROADCAST with this broadcast address which
13981 		 * has ire_stq set.
13982 		 * TODO: simplify, loop over all IRE's
13983 		 */
13984 		ire_t	*ire1;
13985 		int	num_stq = 0;
13986 		mblk_t	*mp1;
13987 
13988 		/* Find the first one with ire_stq set */
13989 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
13990 		for (ire1 = ire; ire1 &&
13991 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
13992 		    ire1 = ire1->ire_next)
13993 			;
13994 		if (ire1) {
13995 			ire_refrele(ire);
13996 			ire = ire1;
13997 			IRE_REFHOLD(ire);
13998 		}
13999 
14000 		/* Check if there are additional ones with stq set */
14001 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14002 			if (ire->ire_addr != ire1->ire_addr)
14003 				break;
14004 			if (ire1->ire_stq) {
14005 				num_stq++;
14006 				break;
14007 			}
14008 		}
14009 		rw_exit(&ire->ire_bucket->irb_lock);
14010 		if (num_stq == 1 && ire->ire_stq != NULL) {
14011 			ip1dbg(("ip_rput_process_broadcast: directed "
14012 			    "broadcast to 0x%x\n",
14013 			    ntohl(ire->ire_addr)));
14014 			mp1 = copymsg(mp);
14015 			if (mp1) {
14016 				switch (ipha->ipha_protocol) {
14017 				case IPPROTO_UDP:
14018 					ip_udp_input(q, mp1, ipha, ire, ill);
14019 					break;
14020 				default:
14021 					ip_proto_input(q, mp1, ipha, ire, ill);
14022 					break;
14023 				}
14024 			}
14025 			/*
14026 			 * Adjust ttl to 2 (1+1 - the forward engine
14027 			 * will decrement it by one.
14028 			 */
14029 			if (ip_csum_hdr(ipha)) {
14030 				BUMP_MIB(&ip_mib, ipInCksumErrs);
14031 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14032 				freemsg(mp);
14033 				ire_refrele(ire);
14034 				return (NULL);
14035 			}
14036 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
14037 			ipha->ipha_hdr_checksum = 0;
14038 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14039 			ip_rput_process_forward(q, mp, ire, ipha,
14040 			    ill, ll_multicast);
14041 			ire_refrele(ire);
14042 			return (NULL);
14043 		}
14044 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14045 		    ntohl(ire->ire_addr)));
14046 	}
14047 
14048 
14049 	/* Restore any hardware checksum flags */
14050 	DB_CKSUMFLAGS(mp) = hcksumflags;
14051 	return (ire);
14052 }
14053 
14054 /* ARGSUSED */
14055 static boolean_t
14056 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14057     int *ll_multicast, ipaddr_t *dstp)
14058 {
14059 	/*
14060 	 * Forward packets only if we have joined the allmulti
14061 	 * group on this interface.
14062 	 */
14063 	if (ip_g_mrouter && ill->ill_join_allmulti) {
14064 		int retval;
14065 
14066 		/*
14067 		 * Clear the indication that this may have hardware
14068 		 * checksum as we are not using it.
14069 		 */
14070 		DB_CKSUMFLAGS(mp) = 0;
14071 		retval = ip_mforward(ill, ipha, mp);
14072 		/* ip_mforward updates mib variables if needed */
14073 		/* clear b_prev - used by ip_mroute_decap */
14074 		mp->b_prev = NULL;
14075 
14076 		switch (retval) {
14077 		case 0:
14078 			/*
14079 			 * pkt is okay and arrived on phyint.
14080 			 *
14081 			 * If we are running as a multicast router
14082 			 * we need to see all IGMP and/or PIM packets.
14083 			 */
14084 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14085 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14086 				goto done;
14087 			}
14088 			break;
14089 		case -1:
14090 			/* pkt is mal-formed, toss it */
14091 			goto drop_pkt;
14092 		case 1:
14093 			/* pkt is okay and arrived on a tunnel */
14094 			/*
14095 			 * If we are running a multicast router
14096 			 *  we need to see all igmp packets.
14097 			 */
14098 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14099 				*dstp = INADDR_BROADCAST;
14100 				*ll_multicast = 1;
14101 				return (B_FALSE);
14102 			}
14103 
14104 			goto drop_pkt;
14105 		}
14106 	}
14107 
14108 	ILM_WALKER_HOLD(ill);
14109 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14110 		/*
14111 		 * This might just be caused by the fact that
14112 		 * multiple IP Multicast addresses map to the same
14113 		 * link layer multicast - no need to increment counter!
14114 		 */
14115 		ILM_WALKER_RELE(ill);
14116 		freemsg(mp);
14117 		return (B_TRUE);
14118 	}
14119 	ILM_WALKER_RELE(ill);
14120 done:
14121 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14122 	/*
14123 	 * This assumes the we deliver to all streams for multicast
14124 	 * and broadcast packets.
14125 	 */
14126 	*dstp = INADDR_BROADCAST;
14127 	*ll_multicast = 1;
14128 	return (B_FALSE);
14129 drop_pkt:
14130 	ip2dbg(("ip_rput: drop pkt\n"));
14131 	freemsg(mp);
14132 	return (B_TRUE);
14133 }
14134 
14135 static boolean_t
14136 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14137     int *ll_multicast, mblk_t **mpp)
14138 {
14139 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14140 	boolean_t must_copy = B_FALSE;
14141 	struct iocblk   *iocp;
14142 	ipha_t		*ipha;
14143 
14144 #define	rptr    ((uchar_t *)ipha)
14145 
14146 	first_mp = *first_mpp;
14147 	mp = *mpp;
14148 
14149 	ASSERT(first_mp == mp);
14150 
14151 	/*
14152 	 * if db_ref > 1 then copymsg and free original. Packet may be
14153 	 * changed and do not want other entity who has a reference to this
14154 	 * message to trip over the changes. This is a blind change because
14155 	 * trying to catch all places that might change packet is too
14156 	 * difficult (since it may be a module above this one)
14157 	 *
14158 	 * This corresponds to the non-fast path case. We walk down the full
14159 	 * chain in this case, and check the db_ref count of all the dblks,
14160 	 * and do a copymsg if required. It is possible that the db_ref counts
14161 	 * of the data blocks in the mblk chain can be different.
14162 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14163 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14164 	 * 'snoop' is running.
14165 	 */
14166 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14167 		if (mp1->b_datap->db_ref > 1) {
14168 			must_copy = B_TRUE;
14169 			break;
14170 		}
14171 	}
14172 
14173 	if (must_copy) {
14174 		mp1 = copymsg(mp);
14175 		if (mp1 == NULL) {
14176 			for (mp1 = mp; mp1 != NULL;
14177 			    mp1 = mp1->b_cont) {
14178 				mp1->b_next = NULL;
14179 				mp1->b_prev = NULL;
14180 			}
14181 			freemsg(mp);
14182 			BUMP_MIB(&ip_mib, ipInDiscards);
14183 			return (B_TRUE);
14184 		}
14185 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14186 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14187 			/* Copy b_prev - used by ip_mroute_decap */
14188 			to_mp->b_prev = from_mp->b_prev;
14189 			from_mp->b_prev = NULL;
14190 		}
14191 		*first_mpp = first_mp = mp1;
14192 		freemsg(mp);
14193 		mp = mp1;
14194 		*mpp = mp1;
14195 	}
14196 
14197 	ipha = (ipha_t *)mp->b_rptr;
14198 
14199 	/*
14200 	 * previous code has a case for M_DATA.
14201 	 * We want to check how that happens.
14202 	 */
14203 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14204 	switch (first_mp->b_datap->db_type) {
14205 	case M_PROTO:
14206 	case M_PCPROTO:
14207 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14208 		    DL_UNITDATA_IND) {
14209 			/* Go handle anything other than data elsewhere. */
14210 			ip_rput_dlpi(q, mp);
14211 			return (B_TRUE);
14212 		}
14213 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14214 		/* Ditch the DLPI header. */
14215 		mp1 = mp->b_cont;
14216 		ASSERT(first_mp == mp);
14217 		*first_mpp = mp1;
14218 		freeb(mp);
14219 		*mpp = mp1;
14220 		return (B_FALSE);
14221 	case M_IOCACK:
14222 		ip1dbg(("got iocack "));
14223 		iocp = (struct iocblk *)mp->b_rptr;
14224 		switch (iocp->ioc_cmd) {
14225 		case DL_IOC_HDR_INFO:
14226 			ill = (ill_t *)q->q_ptr;
14227 			ill_fastpath_ack(ill, mp);
14228 			return (B_TRUE);
14229 		case SIOCSTUNPARAM:
14230 		case OSIOCSTUNPARAM:
14231 			/* Go through qwriter_ip */
14232 			break;
14233 		case SIOCGTUNPARAM:
14234 		case OSIOCGTUNPARAM:
14235 			ip_rput_other(NULL, q, mp, NULL);
14236 			return (B_TRUE);
14237 		default:
14238 			putnext(q, mp);
14239 			return (B_TRUE);
14240 		}
14241 		/* FALLTHRU */
14242 	case M_ERROR:
14243 	case M_HANGUP:
14244 		/*
14245 		 * Since this is on the ill stream we unconditionally
14246 		 * bump up the refcount
14247 		 */
14248 		ill_refhold(ill);
14249 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14250 		    B_FALSE);
14251 		return (B_TRUE);
14252 	case M_CTL:
14253 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14254 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14255 			IPHADA_M_CTL)) {
14256 			/*
14257 			 * It's an IPsec accelerated packet.
14258 			 * Make sure that the ill from which we received the
14259 			 * packet has enabled IPsec hardware acceleration.
14260 			 */
14261 			if (!(ill->ill_capabilities &
14262 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14263 				/* IPsec kstats: bean counter */
14264 				freemsg(mp);
14265 				return (B_TRUE);
14266 			}
14267 
14268 			/*
14269 			 * Make mp point to the mblk following the M_CTL,
14270 			 * then process according to type of mp.
14271 			 * After this processing, first_mp will point to
14272 			 * the data-attributes and mp to the pkt following
14273 			 * the M_CTL.
14274 			 */
14275 			mp = first_mp->b_cont;
14276 			if (mp == NULL) {
14277 				freemsg(first_mp);
14278 				return (B_TRUE);
14279 			}
14280 			/*
14281 			 * A Hardware Accelerated packet can only be M_DATA
14282 			 * ESP or AH packet.
14283 			 */
14284 			if (mp->b_datap->db_type != M_DATA) {
14285 				/* non-M_DATA IPsec accelerated packet */
14286 				IPSECHW_DEBUG(IPSECHW_PKT,
14287 				    ("non-M_DATA IPsec accelerated pkt\n"));
14288 				freemsg(first_mp);
14289 				return (B_TRUE);
14290 			}
14291 			ipha = (ipha_t *)mp->b_rptr;
14292 			if (ipha->ipha_protocol != IPPROTO_AH &&
14293 			    ipha->ipha_protocol != IPPROTO_ESP) {
14294 				IPSECHW_DEBUG(IPSECHW_PKT,
14295 				    ("non-M_DATA IPsec accelerated pkt\n"));
14296 				freemsg(first_mp);
14297 				return (B_TRUE);
14298 			}
14299 			*mpp = mp;
14300 			return (B_FALSE);
14301 		}
14302 		putnext(q, mp);
14303 		return (B_TRUE);
14304 	case M_FLUSH:
14305 		if (*mp->b_rptr & FLUSHW) {
14306 			*mp->b_rptr &= ~FLUSHR;
14307 			qreply(q, mp);
14308 			return (B_TRUE);
14309 		}
14310 		freemsg(mp);
14311 		return (B_TRUE);
14312 	case M_IOCNAK:
14313 		ip1dbg(("got iocnak "));
14314 		iocp = (struct iocblk *)mp->b_rptr;
14315 		switch (iocp->ioc_cmd) {
14316 		case DL_IOC_HDR_INFO:
14317 		case SIOCSTUNPARAM:
14318 		case OSIOCSTUNPARAM:
14319 			/*
14320 			 * Since this is on the ill stream we unconditionally
14321 			 * bump up the refcount
14322 			 */
14323 			ill_refhold(ill);
14324 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14325 			    CUR_OP, B_FALSE);
14326 			return (B_TRUE);
14327 		case SIOCGTUNPARAM:
14328 		case OSIOCGTUNPARAM:
14329 			ip_rput_other(NULL, q, mp, NULL);
14330 			return (B_TRUE);
14331 		default:
14332 			break;
14333 		}
14334 		/* FALLTHRU */
14335 	default:
14336 		putnext(q, mp);
14337 		return (B_TRUE);
14338 	}
14339 }
14340 
14341 /* Read side put procedure.  Packets coming from the wire arrive here. */
14342 void
14343 ip_rput(queue_t *q, mblk_t *mp)
14344 {
14345 	ill_t	*ill;
14346 	mblk_t	 *dmp = NULL;
14347 
14348 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14349 
14350 	ill = (ill_t *)q->q_ptr;
14351 
14352 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14353 		union DL_primitives *dl;
14354 
14355 		/*
14356 		 * Things are opening or closing. Only accept DLPI control
14357 		 * messages. In the open case, the ill->ill_ipif has not yet
14358 		 * been created. In the close case, things hanging off the
14359 		 * ill could have been freed already. In either case it
14360 		 * may not be safe to proceed further.
14361 		 */
14362 
14363 		dl = (union DL_primitives *)mp->b_rptr;
14364 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14365 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14366 			/*
14367 			 * Also SIOC[GS]TUN* ioctls can come here.
14368 			 */
14369 			inet_freemsg(mp);
14370 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14371 			    "ip_input_end: q %p (%S)", q, "uninit");
14372 			return;
14373 		}
14374 	}
14375 
14376 	/*
14377 	 * if db_ref > 1 then copymsg and free original. Packet may be
14378 	 * changed and we do not want the other entity who has a reference to
14379 	 * this message to trip over the changes. This is a blind change because
14380 	 * trying to catch all places that might change the packet is too
14381 	 * difficult.
14382 	 *
14383 	 * This corresponds to the fast path case, where we have a chain of
14384 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14385 	 * in the mblk chain. There doesn't seem to be a reason why a device
14386 	 * driver would send up data with varying db_ref counts in the mblk
14387 	 * chain. In any case the Fast path is a private interface, and our
14388 	 * drivers don't do such a thing. Given the above assumption, there is
14389 	 * no need to walk down the entire mblk chain (which could have a
14390 	 * potential performance problem)
14391 	 */
14392 	if (mp->b_datap->db_ref > 1) {
14393 		mblk_t  *mp1;
14394 		boolean_t adjusted = B_FALSE;
14395 		IP_STAT(ip_db_ref);
14396 
14397 		/*
14398 		 * The IP_RECVSLLA option depends on having the link layer
14399 		 * header. First check that:
14400 		 * a> the underlying device is of type ether, since this
14401 		 * option is currently supported only over ethernet.
14402 		 * b> there is enough room to copy over the link layer header.
14403 		 *
14404 		 * Once the checks are done, adjust rptr so that the link layer
14405 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14406 		 * be returned by some non-ethernet drivers but in this case the
14407 		 * second check will fail.
14408 		 */
14409 		if (ill->ill_type == IFT_ETHER &&
14410 		    (mp->b_rptr - mp->b_datap->db_base) >=
14411 		    sizeof (struct ether_header)) {
14412 			mp->b_rptr -= sizeof (struct ether_header);
14413 			adjusted = B_TRUE;
14414 		}
14415 		mp1 = copymsg(mp);
14416 		if (mp1 == NULL) {
14417 			mp->b_next = NULL;
14418 			/* clear b_prev - used by ip_mroute_decap */
14419 			mp->b_prev = NULL;
14420 			freemsg(mp);
14421 			BUMP_MIB(&ip_mib, ipInDiscards);
14422 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14423 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14424 			return;
14425 		}
14426 		if (adjusted) {
14427 			/*
14428 			 * Copy is done. Restore the pointer in the _new_ mblk
14429 			 */
14430 			mp1->b_rptr += sizeof (struct ether_header);
14431 		}
14432 		/* Copy b_prev - used by ip_mroute_decap */
14433 		mp1->b_prev = mp->b_prev;
14434 		mp->b_prev = NULL;
14435 		freemsg(mp);
14436 		mp = mp1;
14437 	}
14438 	if (DB_TYPE(mp) == M_DATA) {
14439 		dmp = mp;
14440 	} else if (DB_TYPE(mp) == M_PROTO &&
14441 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14442 		dmp = mp->b_cont;
14443 	}
14444 	if (dmp != NULL) {
14445 		/*
14446 		 * IP header ptr not aligned?
14447 		 * OR IP header not complete in first mblk
14448 		 */
14449 		if (!OK_32PTR(dmp->b_rptr) ||
14450 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14451 			if (!ip_check_and_align_header(q, dmp))
14452 				return;
14453 		}
14454 	}
14455 
14456 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14457 	    "ip_rput_end: q %p (%S)", q, "end");
14458 
14459 	ip_input(ill, NULL, mp, NULL);
14460 }
14461 
14462 /*
14463  * Direct read side procedure capable of dealing with chains. GLDv3 based
14464  * drivers call this function directly with mblk chains while STREAMS
14465  * read side procedure ip_rput() calls this for single packet with ip_ring
14466  * set to NULL to process one packet at a time.
14467  *
14468  * The ill will always be valid if this function is called directly from
14469  * the driver.
14470  *
14471  * If ip_input() is called from GLDv3:
14472  *
14473  *   - This must be a non-VLAN IP stream.
14474  *   - 'mp' is either an untagged or a special priority-tagged packet.
14475  *   - Any VLAN tag that was in the MAC header has been stripped.
14476  *
14477  * Thus, there is no need to adjust b_rptr in this function.
14478  */
14479 /* ARGSUSED */
14480 void
14481 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14482     struct mac_header_info_s *mhip)
14483 {
14484 	ipaddr_t		dst = NULL;
14485 	ipaddr_t		prev_dst;
14486 	ire_t			*ire = NULL;
14487 	ipha_t			*ipha;
14488 	uint_t			pkt_len;
14489 	ssize_t			len;
14490 	uint_t			opt_len;
14491 	int			ll_multicast;
14492 	int			cgtp_flt_pkt;
14493 	queue_t			*q = ill->ill_rq;
14494 	squeue_t		*curr_sqp = NULL;
14495 	mblk_t 			*head = NULL;
14496 	mblk_t			*tail = NULL;
14497 	mblk_t			*first_mp;
14498 	mblk_t 			*mp;
14499 	int			cnt = 0;
14500 
14501 	ASSERT(mp_chain != NULL);
14502 	ASSERT(ill != NULL);
14503 
14504 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14505 
14506 #define	rptr	((uchar_t *)ipha)
14507 
14508 	while (mp_chain != NULL) {
14509 		first_mp = mp = mp_chain;
14510 		mp_chain = mp_chain->b_next;
14511 		mp->b_next = NULL;
14512 		ll_multicast = 0;
14513 
14514 		/*
14515 		 * We do ire caching from one iteration to
14516 		 * another. In the event the packet chain contains
14517 		 * all packets from the same dst, this caching saves
14518 		 * an ire_cache_lookup for each of the succeeding
14519 		 * packets in a packet chain.
14520 		 */
14521 		prev_dst = dst;
14522 
14523 		/*
14524 		 * ip_input fast path
14525 		 */
14526 
14527 		/* mblk type is not M_DATA */
14528 		if (mp->b_datap->db_type != M_DATA) {
14529 			if (ip_rput_process_notdata(q, &first_mp, ill,
14530 			    &ll_multicast, &mp))
14531 				continue;
14532 		}
14533 
14534 		/* Make sure its an M_DATA and that its aligned */
14535 		ASSERT(mp->b_datap->db_type == M_DATA);
14536 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14537 
14538 		ipha = (ipha_t *)mp->b_rptr;
14539 		len = mp->b_wptr - rptr;
14540 
14541 		BUMP_MIB(&ip_mib, ipInReceives);
14542 
14543 
14544 		/* multiple mblk or too short */
14545 		pkt_len = ntohs(ipha->ipha_length);
14546 		len -= pkt_len;
14547 		if (len != 0) {
14548 			/*
14549 			 * Make sure we have data length consistent
14550 			 * with the IP header.
14551 			 */
14552 			if (mp->b_cont == NULL) {
14553 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14554 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14555 					ip2dbg(("ip_input: drop pkt\n"));
14556 					freemsg(mp);
14557 					continue;
14558 				}
14559 				mp->b_wptr = rptr + pkt_len;
14560 			} else if (len += msgdsize(mp->b_cont)) {
14561 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14562 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14563 					ip2dbg(("ip_input: drop pkt\n"));
14564 					freemsg(mp);
14565 					continue;
14566 				}
14567 				(void) adjmsg(mp, -len);
14568 				IP_STAT(ip_multimblk3);
14569 			}
14570 		}
14571 
14572 		/*
14573 		 * The event for packets being received from a 'physical'
14574 		 * interface is placed before validation of the source and/or
14575 		 * destination address as being local so that packets such as
14576 		 * these that are found on the network can be observed via
14577 		 * this interface.  The checks prior to this have all been
14578 		 * to do with validating the sanity of the packet - length
14579 		 * fields vs data in the buffer, buffer size, etc, otherwise
14580 		 * uninteresting packet flaws that will always lead to them
14581 		 * being discarded.
14582 		 */
14583 		DTRACE_PROBE4(ip4__physical__in__start,
14584 		    ill_t *, ill, ill_t *, NULL,
14585 		    ipha_t *, ipha, mblk_t *, first_mp);
14586 
14587 		FW_HOOKS(ip4_physical_in_event, ipv4firewall_physical_in,
14588 		    MSG_FWCOOKED_IN, ill, NULL, ipha, first_mp, mp);
14589 
14590 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14591 
14592 		if (first_mp == NULL) {
14593 			continue;
14594 		}
14595 
14596 		/* Obtain the dst of the current packet */
14597 		dst = ipha->ipha_dst;
14598 
14599 		if (IP_LOOPBACK_ADDR(dst) ||
14600 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14601 			BUMP_MIB(&ip_mib, ipInAddrErrors);
14602 			cmn_err(CE_CONT, "dst %X src %X\n",
14603 			    dst, ipha->ipha_src);
14604 			freemsg(mp);
14605 			continue;
14606 		}
14607 
14608 		/*
14609 		 * The event for packets being received from a 'physical'
14610 		 * interface is placed after validation of the source and/or
14611 		 * destination address as being local so that packets can be
14612 		 * redirected to loopback addresses using ipnat.
14613 		 */
14614 		DTRACE_PROBE4(ip4__physical__in__start,
14615 		    ill_t *, ill, ill_t *, NULL,
14616 		    ipha_t *, ipha, mblk_t *, first_mp);
14617 
14618 		FW_HOOKS(ip4_physical_in_event, ipv4firewall_physical_in,
14619 		    MSG_FWCOOKED_IN, ill, NULL, ipha, first_mp, mp);
14620 
14621 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14622 
14623 		if (first_mp == NULL) {
14624 			continue;
14625 		}
14626 		dst = ipha->ipha_dst;
14627 
14628 		/*
14629 		 * Attach any necessary label information to
14630 		 * this packet
14631 		 */
14632 		if (is_system_labeled() &&
14633 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14634 			BUMP_MIB(&ip_mib, ipInDiscards);
14635 			freemsg(mp);
14636 			continue;
14637 		}
14638 
14639 		/*
14640 		 * Reuse the cached ire only if the ipha_dst of the previous
14641 		 * packet is the same as the current packet AND it is not
14642 		 * INADDR_ANY.
14643 		 */
14644 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14645 		    (ire != NULL)) {
14646 			ire_refrele(ire);
14647 			ire = NULL;
14648 		}
14649 		opt_len = ipha->ipha_version_and_hdr_length -
14650 		    IP_SIMPLE_HDR_VERSION;
14651 
14652 		/*
14653 		 * Check to see if we can take the fastpath.
14654 		 * That is possible if the following conditions are met
14655 		 *	o Tsol disabled
14656 		 *	o CGTP disabled
14657 		 *	o ipp_action_count is 0
14658 		 *	o Mobile IP not running
14659 		 *	o no options in the packet
14660 		 *	o not a RSVP packet
14661 		 * 	o not a multicast packet
14662 		 */
14663 		if (!is_system_labeled() &&
14664 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14665 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14666 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14667 		    !ll_multicast && !CLASSD(dst)) {
14668 			if (ire == NULL)
14669 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14670 
14671 			/* incoming packet is for forwarding */
14672 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14673 				ire = ip_fast_forward(ire, dst, ill, mp);
14674 				continue;
14675 			}
14676 			/* incoming packet is for local consumption */
14677 			if (ire->ire_type & IRE_LOCAL)
14678 				goto local;
14679 		}
14680 
14681 		/*
14682 		 * Disable ire caching for anything more complex
14683 		 * than the simple fast path case we checked for above.
14684 		 */
14685 		if (ire != NULL) {
14686 			ire_refrele(ire);
14687 			ire = NULL;
14688 		}
14689 
14690 		/* Full-blown slow path */
14691 		if (opt_len != 0) {
14692 			if (len != 0)
14693 				IP_STAT(ip_multimblk4);
14694 			else
14695 				IP_STAT(ip_ipoptions);
14696 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
14697 				continue;
14698 		}
14699 
14700 		/*
14701 		 * Invoke the CGTP (multirouting) filtering module to process
14702 		 * the incoming packet. Packets identified as duplicates
14703 		 * must be discarded. Filtering is active only if the
14704 		 * the ip_cgtp_filter ndd variable is non-zero.
14705 		 */
14706 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14707 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
14708 			cgtp_flt_pkt =
14709 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14710 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14711 				freemsg(first_mp);
14712 				continue;
14713 			}
14714 		}
14715 
14716 		/*
14717 		 * If rsvpd is running, let RSVP daemon handle its processing
14718 		 * and forwarding of RSVP multicast/unicast packets.
14719 		 * If rsvpd is not running but mrouted is running, RSVP
14720 		 * multicast packets are forwarded as multicast traffic
14721 		 * and RSVP unicast packets are forwarded by unicast router.
14722 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14723 		 * packets are not forwarded, but the unicast packets are
14724 		 * forwarded like unicast traffic.
14725 		 */
14726 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14727 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
14728 			/* RSVP packet and rsvpd running. Treat as ours */
14729 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14730 			/*
14731 			 * This assumes that we deliver to all streams for
14732 			 * multicast and broadcast packets.
14733 			 * We have to force ll_multicast to 1 to handle the
14734 			 * M_DATA messages passed in from ip_mroute_decap.
14735 			 */
14736 			dst = INADDR_BROADCAST;
14737 			ll_multicast = 1;
14738 		} else if (CLASSD(dst)) {
14739 			/* packet is multicast */
14740 			mp->b_next = NULL;
14741 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14742 			    &ll_multicast, &dst))
14743 				continue;
14744 		}
14745 
14746 
14747 		/*
14748 		 * Check if the packet is coming from the Mobile IP
14749 		 * forward tunnel interface
14750 		 */
14751 		if (ill->ill_srcif_refcnt > 0) {
14752 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
14753 			    NULL, ill, MATCH_IRE_TYPE);
14754 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
14755 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
14756 
14757 				/* We need to resolve the link layer info */
14758 				ire_refrele(ire);
14759 				ire = NULL;
14760 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
14761 				    ll_multicast, dst);
14762 				continue;
14763 			}
14764 		}
14765 
14766 		if (ire == NULL) {
14767 			ire = ire_cache_lookup(dst, ALL_ZONES,
14768 			    MBLK_GETLABEL(mp));
14769 		}
14770 
14771 		/*
14772 		 * If mipagent is running and reverse tunnel is created as per
14773 		 * mobile node request, then any packet coming through the
14774 		 * incoming interface from the mobile-node, should be reverse
14775 		 * tunneled to it's home agent except those that are destined
14776 		 * to foreign agent only.
14777 		 * This needs source address based ire lookup. The routing
14778 		 * entries for source address based lookup are only created by
14779 		 * mipagent program only when a reverse tunnel is created.
14780 		 * Reference : RFC2002, RFC2344
14781 		 */
14782 		if (ill->ill_mrtun_refcnt > 0) {
14783 			ipaddr_t	srcaddr;
14784 			ire_t		*tmp_ire;
14785 
14786 			tmp_ire = ire;	/* Save, we might need it later */
14787 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14788 			    ire->ire_type != IRE_BROADCAST)) {
14789 				srcaddr = ipha->ipha_src;
14790 				ire = ire_mrtun_lookup(srcaddr, ill);
14791 				if (ire != NULL) {
14792 					/*
14793 					 * Should not be getting iphada packet
14794 					 * here. we should only get those for
14795 					 * IRE_LOCAL traffic, excluded above.
14796 					 * Fail-safe (drop packet) in the event
14797 					 * hardware is misbehaving.
14798 					 */
14799 					if (first_mp != mp) {
14800 						/* IPsec KSTATS: beancount me */
14801 						freemsg(first_mp);
14802 					} else {
14803 						/*
14804 						 * This packet must be forwarded
14805 						 * to Reverse Tunnel
14806 						 */
14807 						ip_mrtun_forward(ire, ill, mp);
14808 					}
14809 					ire_refrele(ire);
14810 					ire = NULL;
14811 					if (tmp_ire != NULL) {
14812 						ire_refrele(tmp_ire);
14813 						tmp_ire = NULL;
14814 					}
14815 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14816 					    "ip_input_end: q %p (%S)",
14817 					    q, "uninit");
14818 					continue;
14819 				}
14820 			}
14821 			/*
14822 			 * If this packet is from a non-mobilenode  or a
14823 			 * mobile-node which does not request reverse
14824 			 * tunnel service
14825 			 */
14826 			ire = tmp_ire;
14827 		}
14828 
14829 
14830 		/*
14831 		 * If we reach here that means the incoming packet satisfies
14832 		 * one of the following conditions:
14833 		 *   - packet is from a mobile node which does not request
14834 		 *	reverse tunnel
14835 		 *   - packet is from a non-mobile node, which is the most
14836 		 *	common case
14837 		 *   - packet is from a reverse tunnel enabled mobile node
14838 		 *	and destined to foreign agent only
14839 		 */
14840 
14841 		if (ire == NULL) {
14842 			/*
14843 			 * No IRE for this destination, so it can't be for us.
14844 			 * Unless we are forwarding, drop the packet.
14845 			 * We have to let source routed packets through
14846 			 * since we don't yet know if they are 'ping -l'
14847 			 * packets i.e. if they will go out over the
14848 			 * same interface as they came in on.
14849 			 */
14850 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14851 			if (ire == NULL)
14852 				continue;
14853 		}
14854 
14855 		/*
14856 		 * Broadcast IRE may indicate either broadcast or
14857 		 * multicast packet
14858 		 */
14859 		if (ire->ire_type == IRE_BROADCAST) {
14860 			/*
14861 			 * Skip broadcast checks if packet is UDP multicast;
14862 			 * we'd rather not enter ip_rput_process_broadcast()
14863 			 * unless the packet is broadcast for real, since
14864 			 * that routine is a no-op for multicast.
14865 			 */
14866 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14867 			    !CLASSD(ipha->ipha_dst)) {
14868 				ire = ip_rput_process_broadcast(&q, mp,
14869 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14870 				    ll_multicast);
14871 				if (ire == NULL)
14872 					continue;
14873 			}
14874 		} else if (ire->ire_stq != NULL) {
14875 			/* fowarding? */
14876 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14877 			    ll_multicast);
14878 			/* ip_rput_process_forward consumed the packet */
14879 			continue;
14880 		}
14881 
14882 local:
14883 		/* packet not for us */
14884 		if (ire->ire_rfq != q) {
14885 			if (ip_rput_notforus(&q, mp, ire, ill))
14886 				continue;
14887 		}
14888 
14889 		switch (ipha->ipha_protocol) {
14890 		case IPPROTO_TCP:
14891 			ASSERT(first_mp == mp);
14892 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14893 				mp, 0, q, ip_ring)) != NULL) {
14894 				if (curr_sqp == NULL) {
14895 					curr_sqp = GET_SQUEUE(mp);
14896 					ASSERT(cnt == 0);
14897 					cnt++;
14898 					head = tail = mp;
14899 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14900 					ASSERT(tail != NULL);
14901 					cnt++;
14902 					tail->b_next = mp;
14903 					tail = mp;
14904 				} else {
14905 					/*
14906 					 * A different squeue. Send the
14907 					 * chain for the previous squeue on
14908 					 * its way. This shouldn't happen
14909 					 * often unless interrupt binding
14910 					 * changes.
14911 					 */
14912 					IP_STAT(ip_input_multi_squeue);
14913 					squeue_enter_chain(curr_sqp, head,
14914 					    tail, cnt, SQTAG_IP_INPUT);
14915 					curr_sqp = GET_SQUEUE(mp);
14916 					head = mp;
14917 					tail = mp;
14918 					cnt = 1;
14919 				}
14920 			}
14921 			continue;
14922 		case IPPROTO_UDP:
14923 			ASSERT(first_mp == mp);
14924 			ip_udp_input(q, mp, ipha, ire, ill);
14925 			continue;
14926 		case IPPROTO_SCTP:
14927 			ASSERT(first_mp == mp);
14928 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14929 			    q, dst);
14930 			/* ire has been released by ip_sctp_input */
14931 			ire = NULL;
14932 			continue;
14933 		default:
14934 			ip_proto_input(q, first_mp, ipha, ire, ill);
14935 			continue;
14936 		}
14937 	}
14938 
14939 	if (ire != NULL)
14940 		ire_refrele(ire);
14941 
14942 	if (head != NULL)
14943 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14944 
14945 	/*
14946 	 * This code is there just to make netperf/ttcp look good.
14947 	 *
14948 	 * Its possible that after being in polling mode (and having cleared
14949 	 * the backlog), squeues have turned the interrupt frequency higher
14950 	 * to improve latency at the expense of more CPU utilization (less
14951 	 * packets per interrupts or more number of interrupts). Workloads
14952 	 * like ttcp/netperf do manage to tickle polling once in a while
14953 	 * but for the remaining time, stay in higher interrupt mode since
14954 	 * their packet arrival rate is pretty uniform and this shows up
14955 	 * as higher CPU utilization. Since people care about CPU utilization
14956 	 * while running netperf/ttcp, turn the interrupt frequency back to
14957 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14958 	 */
14959 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14960 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14961 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14962 			ip_ring->rr_blank(ip_ring->rr_handle,
14963 			    ip_ring->rr_normal_blank_time,
14964 			    ip_ring->rr_normal_pkt_cnt);
14965 		}
14966 	}
14967 
14968 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14969 	    "ip_input_end: q %p (%S)", q, "end");
14970 #undef	rptr
14971 }
14972 
14973 static void
14974 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
14975     t_uscalar_t err)
14976 {
14977 	if (dl_err == DL_SYSERR) {
14978 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14979 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
14980 		    ill->ill_name, dlpi_prim_str(prim), err);
14981 		return;
14982 	}
14983 
14984 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14985 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
14986 	    dlpi_err_str(dl_err));
14987 }
14988 
14989 /*
14990  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
14991  * than DL_UNITDATA_IND messages. If we need to process this message
14992  * exclusively, we call qwriter_ip, in which case we also need to call
14993  * ill_refhold before that, since qwriter_ip does an ill_refrele.
14994  */
14995 void
14996 ip_rput_dlpi(queue_t *q, mblk_t *mp)
14997 {
14998 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14999 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15000 	ill_t		*ill;
15001 
15002 	ip1dbg(("ip_rput_dlpi"));
15003 	ill = (ill_t *)q->q_ptr;
15004 	switch (dloa->dl_primitive) {
15005 	case DL_ERROR_ACK:
15006 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15007 		    "%s (0x%x), unix %u\n", ill->ill_name,
15008 		    dlpi_prim_str(dlea->dl_error_primitive),
15009 		    dlea->dl_error_primitive,
15010 		    dlpi_err_str(dlea->dl_errno),
15011 		    dlea->dl_errno,
15012 		    dlea->dl_unix_errno));
15013 		switch (dlea->dl_error_primitive) {
15014 		case DL_UNBIND_REQ:
15015 			mutex_enter(&ill->ill_lock);
15016 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15017 			cv_signal(&ill->ill_cv);
15018 			mutex_exit(&ill->ill_lock);
15019 			/* FALLTHRU */
15020 		case DL_NOTIFY_REQ:
15021 		case DL_ATTACH_REQ:
15022 		case DL_DETACH_REQ:
15023 		case DL_INFO_REQ:
15024 		case DL_BIND_REQ:
15025 		case DL_ENABMULTI_REQ:
15026 		case DL_PHYS_ADDR_REQ:
15027 		case DL_CAPABILITY_REQ:
15028 		case DL_CONTROL_REQ:
15029 			/*
15030 			 * Refhold the ill to match qwriter_ip which does a
15031 			 * refrele. Since this is on the ill stream we
15032 			 * unconditionally bump up the refcount without
15033 			 * checking for ILL_CAN_LOOKUP
15034 			 */
15035 			ill_refhold(ill);
15036 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15037 			    CUR_OP, B_FALSE);
15038 			return;
15039 		case DL_DISABMULTI_REQ:
15040 			freemsg(mp);	/* Don't want to pass this up */
15041 			return;
15042 		default:
15043 			break;
15044 		}
15045 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15046 		    dlea->dl_errno, dlea->dl_unix_errno);
15047 		freemsg(mp);
15048 		return;
15049 	case DL_INFO_ACK:
15050 	case DL_BIND_ACK:
15051 	case DL_PHYS_ADDR_ACK:
15052 	case DL_NOTIFY_ACK:
15053 	case DL_CAPABILITY_ACK:
15054 	case DL_CONTROL_ACK:
15055 		/*
15056 		 * Refhold the ill to match qwriter_ip which does a refrele
15057 		 * Since this is on the ill stream we unconditionally
15058 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15059 		 */
15060 		ill_refhold(ill);
15061 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15062 		    CUR_OP, B_FALSE);
15063 		return;
15064 	case DL_NOTIFY_IND:
15065 		ill_refhold(ill);
15066 		/*
15067 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15068 		 * relation to the current ioctl in progress (if any). Hence we
15069 		 * pass in NEW_OP in this case.
15070 		 */
15071 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15072 		    NEW_OP, B_FALSE);
15073 		return;
15074 	case DL_OK_ACK:
15075 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15076 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15077 		switch (dloa->dl_correct_primitive) {
15078 		case DL_UNBIND_REQ:
15079 			mutex_enter(&ill->ill_lock);
15080 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15081 			cv_signal(&ill->ill_cv);
15082 			mutex_exit(&ill->ill_lock);
15083 			/* FALLTHRU */
15084 		case DL_ATTACH_REQ:
15085 		case DL_DETACH_REQ:
15086 			/*
15087 			 * Refhold the ill to match qwriter_ip which does a
15088 			 * refrele. Since this is on the ill stream we
15089 			 * unconditionally bump up the refcount
15090 			 */
15091 			ill_refhold(ill);
15092 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15093 			    CUR_OP, B_FALSE);
15094 			return;
15095 		case DL_ENABMULTI_REQ:
15096 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15097 				ill->ill_dlpi_multicast_state = IDS_OK;
15098 			break;
15099 
15100 		}
15101 		break;
15102 	default:
15103 		break;
15104 	}
15105 	freemsg(mp);
15106 }
15107 
15108 /*
15109  * Handling of DLPI messages that require exclusive access to the ipsq.
15110  *
15111  * Need to do ill_pending_mp_release on ioctl completion, which could
15112  * happen here. (along with mi_copy_done)
15113  */
15114 /* ARGSUSED */
15115 static void
15116 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15117 {
15118 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15119 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15120 	int		err = 0;
15121 	ill_t		*ill;
15122 	ipif_t		*ipif = NULL;
15123 	mblk_t		*mp1 = NULL;
15124 	conn_t		*connp = NULL;
15125 	t_uscalar_t	physaddr_req;
15126 	mblk_t		*mp_hw;
15127 	union DL_primitives *dlp;
15128 	boolean_t	success;
15129 	boolean_t	ioctl_aborted = B_FALSE;
15130 	boolean_t	log = B_TRUE;
15131 	hook_nic_event_t	*info;
15132 
15133 	ip1dbg(("ip_rput_dlpi_writer .."));
15134 	ill = (ill_t *)q->q_ptr;
15135 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15136 
15137 	ASSERT(IAM_WRITER_ILL(ill));
15138 
15139 	/*
15140 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15141 	 * both are null or non-null. However we can assert that only
15142 	 * after grabbing the ipsq_lock. So we don't make any assertion
15143 	 * here and in other places in the code.
15144 	 */
15145 	ipif = ipsq->ipsq_pending_ipif;
15146 	/*
15147 	 * The current ioctl could have been aborted by the user and a new
15148 	 * ioctl to bring up another ill could have started. We could still
15149 	 * get a response from the driver later.
15150 	 */
15151 	if (ipif != NULL && ipif->ipif_ill != ill)
15152 		ioctl_aborted = B_TRUE;
15153 
15154 	switch (dloa->dl_primitive) {
15155 	case DL_ERROR_ACK:
15156 		switch (dlea->dl_error_primitive) {
15157 		case DL_UNBIND_REQ:
15158 		case DL_ATTACH_REQ:
15159 		case DL_DETACH_REQ:
15160 		case DL_INFO_REQ:
15161 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15162 			break;
15163 		case DL_NOTIFY_REQ:
15164 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15165 			log = B_FALSE;
15166 			break;
15167 		case DL_PHYS_ADDR_REQ:
15168 			/*
15169 			 * For IPv6 only, there are two additional
15170 			 * phys_addr_req's sent to the driver to get the
15171 			 * IPv6 token and lla. This allows IP to acquire
15172 			 * the hardware address format for a given interface
15173 			 * without having built in knowledge of the hardware
15174 			 * address. ill_phys_addr_pend keeps track of the last
15175 			 * DL_PAR sent so we know which response we are
15176 			 * dealing with. ill_dlpi_done will update
15177 			 * ill_phys_addr_pend when it sends the next req.
15178 			 * We don't complete the IOCTL until all three DL_PARs
15179 			 * have been attempted, so set *_len to 0 and break.
15180 			 */
15181 			physaddr_req = ill->ill_phys_addr_pend;
15182 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15183 			if (physaddr_req == DL_IPV6_TOKEN) {
15184 				ill->ill_token_length = 0;
15185 				log = B_FALSE;
15186 				break;
15187 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15188 				ill->ill_nd_lla_len = 0;
15189 				log = B_FALSE;
15190 				break;
15191 			}
15192 			/*
15193 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15194 			 * We presumably have an IOCTL hanging out waiting
15195 			 * for completion. Find it and complete the IOCTL
15196 			 * with the error noted.
15197 			 * However, ill_dl_phys was called on an ill queue
15198 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15199 			 * set. But the ioctl is known to be pending on ill_wq.
15200 			 */
15201 			if (!ill->ill_ifname_pending)
15202 				break;
15203 			ill->ill_ifname_pending = 0;
15204 			if (!ioctl_aborted)
15205 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15206 			if (mp1 != NULL) {
15207 				/*
15208 				 * This operation (SIOCSLIFNAME) must have
15209 				 * happened on the ill. Assert there is no conn
15210 				 */
15211 				ASSERT(connp == NULL);
15212 				q = ill->ill_wq;
15213 			}
15214 			break;
15215 		case DL_BIND_REQ:
15216 			ill_dlpi_done(ill, DL_BIND_REQ);
15217 			if (ill->ill_ifname_pending)
15218 				break;
15219 			/*
15220 			 * Something went wrong with the bind.  We presumably
15221 			 * have an IOCTL hanging out waiting for completion.
15222 			 * Find it, take down the interface that was coming
15223 			 * up, and complete the IOCTL with the error noted.
15224 			 */
15225 			if (!ioctl_aborted)
15226 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15227 			if (mp1 != NULL) {
15228 				/*
15229 				 * This operation (SIOCSLIFFLAGS) must have
15230 				 * happened from a conn.
15231 				 */
15232 				ASSERT(connp != NULL);
15233 				q = CONNP_TO_WQ(connp);
15234 				if (ill->ill_move_in_progress) {
15235 					ILL_CLEAR_MOVE(ill);
15236 				}
15237 				(void) ipif_down(ipif, NULL, NULL);
15238 				/* error is set below the switch */
15239 			}
15240 			break;
15241 		case DL_ENABMULTI_REQ:
15242 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15243 
15244 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15245 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15246 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15247 				ipif_t *ipif;
15248 
15249 				log = B_FALSE;
15250 				printf("ip: joining multicasts failed (%d)"
15251 				    " on %s - will use link layer "
15252 				    "broadcasts for multicast\n",
15253 				    dlea->dl_errno, ill->ill_name);
15254 
15255 				/*
15256 				 * Set up the multicast mapping alone.
15257 				 * writer, so ok to access ill->ill_ipif
15258 				 * without any lock.
15259 				 */
15260 				ipif = ill->ill_ipif;
15261 				mutex_enter(&ill->ill_phyint->phyint_lock);
15262 				ill->ill_phyint->phyint_flags |=
15263 				    PHYI_MULTI_BCAST;
15264 				mutex_exit(&ill->ill_phyint->phyint_lock);
15265 
15266 				if (!ill->ill_isv6) {
15267 					(void) ipif_arp_setup_multicast(ipif,
15268 					    NULL);
15269 				} else {
15270 					(void) ipif_ndp_setup_multicast(ipif,
15271 					    NULL);
15272 				}
15273 			}
15274 			freemsg(mp);	/* Don't want to pass this up */
15275 			return;
15276 		case DL_CAPABILITY_REQ:
15277 		case DL_CONTROL_REQ:
15278 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15279 			    "DL_CAPABILITY/CONTROL REQ\n"));
15280 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15281 			ill->ill_dlpi_capab_state = IDS_FAILED;
15282 			freemsg(mp);
15283 			return;
15284 		}
15285 		/*
15286 		 * Note the error for IOCTL completion (mp1 is set when
15287 		 * ready to complete ioctl). If ill_ifname_pending_err is
15288 		 * set, an error occured during plumbing (ill_ifname_pending),
15289 		 * so we want to report that error.
15290 		 *
15291 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15292 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15293 		 * expected to get errack'd if the driver doesn't support
15294 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15295 		 * if these error conditions are encountered.
15296 		 */
15297 		if (mp1 != NULL) {
15298 			if (ill->ill_ifname_pending_err != 0)  {
15299 				err = ill->ill_ifname_pending_err;
15300 				ill->ill_ifname_pending_err = 0;
15301 			} else {
15302 				err = dlea->dl_unix_errno ?
15303 				    dlea->dl_unix_errno : ENXIO;
15304 			}
15305 		/*
15306 		 * If we're plumbing an interface and an error hasn't already
15307 		 * been saved, set ill_ifname_pending_err to the error passed
15308 		 * up. Ignore the error if log is B_FALSE (see comment above).
15309 		 */
15310 		} else if (log && ill->ill_ifname_pending &&
15311 		    ill->ill_ifname_pending_err == 0) {
15312 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15313 			dlea->dl_unix_errno : ENXIO;
15314 		}
15315 
15316 		if (log)
15317 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15318 			    dlea->dl_errno, dlea->dl_unix_errno);
15319 		break;
15320 	case DL_CAPABILITY_ACK: {
15321 		boolean_t reneg_flag = B_FALSE;
15322 		/* Call a routine to handle this one. */
15323 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15324 		/*
15325 		 * Check if the ACK is due to renegotiation case since we
15326 		 * will need to send a new CAPABILITY_REQ later.
15327 		 */
15328 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15329 			/* This is the ack for a renogiation case */
15330 			reneg_flag = B_TRUE;
15331 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15332 		}
15333 		ill_capability_ack(ill, mp);
15334 		if (reneg_flag)
15335 			ill_capability_probe(ill);
15336 		break;
15337 	}
15338 	case DL_CONTROL_ACK:
15339 		/* We treat all of these as "fire and forget" */
15340 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15341 		break;
15342 	case DL_INFO_ACK:
15343 		/* Call a routine to handle this one. */
15344 		ill_dlpi_done(ill, DL_INFO_REQ);
15345 		ip_ll_subnet_defaults(ill, mp);
15346 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15347 		return;
15348 	case DL_BIND_ACK:
15349 		/*
15350 		 * We should have an IOCTL waiting on this unless
15351 		 * sent by ill_dl_phys, in which case just return
15352 		 */
15353 		ill_dlpi_done(ill, DL_BIND_REQ);
15354 		if (ill->ill_ifname_pending)
15355 			break;
15356 
15357 		if (!ioctl_aborted)
15358 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15359 		if (mp1 == NULL)
15360 			break;
15361 		ASSERT(connp != NULL);
15362 		q = CONNP_TO_WQ(connp);
15363 
15364 		/*
15365 		 * We are exclusive. So nothing can change even after
15366 		 * we get the pending mp. If need be we can put it back
15367 		 * and restart, as in calling ipif_arp_up()  below.
15368 		 */
15369 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15370 
15371 		mutex_enter(&ill->ill_lock);
15372 
15373 		ill->ill_dl_up = 1;
15374 
15375 		if ((info = ill->ill_nic_event_info) != NULL) {
15376 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15377 			    "attached for %s\n", info->hne_event,
15378 			    ill->ill_name));
15379 			if (info->hne_data != NULL)
15380 				kmem_free(info->hne_data, info->hne_datalen);
15381 			kmem_free(info, sizeof (hook_nic_event_t));
15382 		}
15383 
15384 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15385 		if (info != NULL) {
15386 			info->hne_nic = ill->ill_phyint->phyint_ifindex;
15387 			info->hne_lif = 0;
15388 			info->hne_event = NE_UP;
15389 			info->hne_data = NULL;
15390 			info->hne_datalen = 0;
15391 			info->hne_family = ill->ill_isv6 ? ipv6 : ipv4;
15392 		} else
15393 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15394 			    "event information for %s (ENOMEM)\n",
15395 			    ill->ill_name));
15396 
15397 		ill->ill_nic_event_info = info;
15398 
15399 		mutex_exit(&ill->ill_lock);
15400 
15401 		/*
15402 		 * Now bring up the resolver; when that is complete, we'll
15403 		 * create IREs.  Note that we intentionally mirror what
15404 		 * ipif_up() would have done, because we got here by way of
15405 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15406 		 */
15407 		if (ill->ill_isv6) {
15408 			/*
15409 			 * v6 interfaces.
15410 			 * Unlike ARP which has to do another bind
15411 			 * and attach, once we get here we are
15412 			 * done with NDP. Except in the case of
15413 			 * ILLF_XRESOLV, in which case we send an
15414 			 * AR_INTERFACE_UP to the external resolver.
15415 			 * If all goes well, the ioctl will complete
15416 			 * in ip_rput(). If there's an error, we
15417 			 * complete it here.
15418 			 */
15419 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15420 			    B_FALSE);
15421 			if (err == 0) {
15422 				if (ill->ill_flags & ILLF_XRESOLV) {
15423 					mutex_enter(&connp->conn_lock);
15424 					mutex_enter(&ill->ill_lock);
15425 					success = ipsq_pending_mp_add(
15426 					    connp, ipif, q, mp1, 0);
15427 					mutex_exit(&ill->ill_lock);
15428 					mutex_exit(&connp->conn_lock);
15429 					if (success) {
15430 						err = ipif_resolver_up(ipif,
15431 						    Res_act_initial);
15432 						if (err == EINPROGRESS) {
15433 							freemsg(mp);
15434 							return;
15435 						}
15436 						ASSERT(err != 0);
15437 						mp1 = ipsq_pending_mp_get(ipsq,
15438 						    &connp);
15439 						ASSERT(mp1 != NULL);
15440 					} else {
15441 						/* conn has started closing */
15442 						err = EINTR;
15443 					}
15444 				} else { /* Non XRESOLV interface */
15445 					(void) ipif_resolver_up(ipif,
15446 					    Res_act_initial);
15447 					err = ipif_up_done_v6(ipif);
15448 				}
15449 			}
15450 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15451 			/*
15452 			 * ARP and other v4 external resolvers.
15453 			 * Leave the pending mblk intact so that
15454 			 * the ioctl completes in ip_rput().
15455 			 */
15456 			mutex_enter(&connp->conn_lock);
15457 			mutex_enter(&ill->ill_lock);
15458 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15459 			mutex_exit(&ill->ill_lock);
15460 			mutex_exit(&connp->conn_lock);
15461 			if (success) {
15462 				err = ipif_resolver_up(ipif, Res_act_initial);
15463 				if (err == EINPROGRESS) {
15464 					freemsg(mp);
15465 					return;
15466 				}
15467 				ASSERT(err != 0);
15468 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15469 			} else {
15470 				/* The conn has started closing */
15471 				err = EINTR;
15472 			}
15473 		} else {
15474 			/*
15475 			 * This one is complete. Reply to pending ioctl.
15476 			 */
15477 			(void) ipif_resolver_up(ipif, Res_act_initial);
15478 			err = ipif_up_done(ipif);
15479 		}
15480 
15481 		if ((err == 0) && (ill->ill_up_ipifs)) {
15482 			err = ill_up_ipifs(ill, q, mp1);
15483 			if (err == EINPROGRESS) {
15484 				freemsg(mp);
15485 				return;
15486 			}
15487 		}
15488 
15489 		if (ill->ill_up_ipifs) {
15490 			ill_group_cleanup(ill);
15491 		}
15492 
15493 		break;
15494 	case DL_NOTIFY_IND: {
15495 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15496 		ire_t *ire;
15497 		boolean_t need_ire_walk_v4 = B_FALSE;
15498 		boolean_t need_ire_walk_v6 = B_FALSE;
15499 
15500 		/*
15501 		 * Change the address everywhere we need to.
15502 		 * What we're getting here is a link-level addr or phys addr.
15503 		 * The new addr is at notify + notify->dl_addr_offset
15504 		 * The address length is notify->dl_addr_length;
15505 		 */
15506 		switch (notify->dl_notification) {
15507 		case DL_NOTE_PHYS_ADDR:
15508 			mp_hw = copyb(mp);
15509 			if (mp_hw == NULL) {
15510 				err = ENOMEM;
15511 				break;
15512 			}
15513 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15514 			/*
15515 			 * We currently don't support changing
15516 			 * the token via DL_NOTIFY_IND.
15517 			 * When we do support it, we have to consider
15518 			 * what the implications are with respect to
15519 			 * the token and the link local address.
15520 			 */
15521 			mutex_enter(&ill->ill_lock);
15522 			if (dlp->notify_ind.dl_data ==
15523 			    DL_IPV6_LINK_LAYER_ADDR) {
15524 				if (ill->ill_nd_lla_mp != NULL)
15525 					freemsg(ill->ill_nd_lla_mp);
15526 				ill->ill_nd_lla_mp = mp_hw;
15527 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15528 				    dlp->notify_ind.dl_addr_offset;
15529 				ill->ill_nd_lla_len =
15530 				    dlp->notify_ind.dl_addr_length -
15531 				    ABS(ill->ill_sap_length);
15532 				mutex_exit(&ill->ill_lock);
15533 				break;
15534 			} else if (dlp->notify_ind.dl_data ==
15535 			    DL_CURR_PHYS_ADDR) {
15536 				if (ill->ill_phys_addr_mp != NULL)
15537 					freemsg(ill->ill_phys_addr_mp);
15538 				ill->ill_phys_addr_mp = mp_hw;
15539 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15540 				    dlp->notify_ind.dl_addr_offset;
15541 				ill->ill_phys_addr_length =
15542 				    dlp->notify_ind.dl_addr_length -
15543 				    ABS(ill->ill_sap_length);
15544 				if (ill->ill_isv6 &&
15545 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15546 					if (ill->ill_nd_lla_mp != NULL)
15547 						freemsg(ill->ill_nd_lla_mp);
15548 					ill->ill_nd_lla_mp = copyb(mp_hw);
15549 					ill->ill_nd_lla = (uchar_t *)
15550 					    ill->ill_nd_lla_mp->b_rptr +
15551 					    dlp->notify_ind.dl_addr_offset;
15552 					ill->ill_nd_lla_len =
15553 					    ill->ill_phys_addr_length;
15554 				}
15555 			}
15556 			mutex_exit(&ill->ill_lock);
15557 			/*
15558 			 * Send out gratuitous arp request for our new
15559 			 * hardware address.
15560 			 */
15561 			for (ipif = ill->ill_ipif; ipif != NULL;
15562 			    ipif = ipif->ipif_next) {
15563 				if (!(ipif->ipif_flags & IPIF_UP))
15564 					continue;
15565 				if (ill->ill_isv6) {
15566 					ipif_ndp_down(ipif);
15567 					/*
15568 					 * Set B_TRUE to enable
15569 					 * ipif_ndp_up() to send out
15570 					 * unsolicited advertisements.
15571 					 */
15572 					err = ipif_ndp_up(ipif,
15573 					    &ipif->ipif_v6lcl_addr,
15574 					    B_TRUE);
15575 					if (err) {
15576 						ip1dbg((
15577 						    "ip_rput_dlpi_writer: "
15578 						    "Failed to update ndp "
15579 						    "err %d\n", err));
15580 					}
15581 				} else {
15582 					/*
15583 					 * IPv4 ARP case
15584 					 *
15585 					 * Set Res_act_move, as we only want
15586 					 * ipif_resolver_up to send an
15587 					 * AR_ENTRY_ADD request up to
15588 					 * ARP.
15589 					 */
15590 					err = ipif_resolver_up(ipif,
15591 					    Res_act_move);
15592 					if (err) {
15593 						ip1dbg((
15594 						    "ip_rput_dlpi_writer: "
15595 						    "Failed to update arp "
15596 						    "err %d\n", err));
15597 					}
15598 				}
15599 			}
15600 			/*
15601 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15602 			 * case so that all old fastpath information can be
15603 			 * purged from IRE caches.
15604 			 */
15605 		/* FALLTHRU */
15606 		case DL_NOTE_FASTPATH_FLUSH:
15607 			/*
15608 			 * Any fastpath probe sent henceforth will get the
15609 			 * new fp mp. So we first delete any ires that are
15610 			 * waiting for the fastpath. Then walk all ires and
15611 			 * delete the ire or delete the fp mp. In the case of
15612 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15613 			 * recreate the ire's without going through a complex
15614 			 * ipif up/down dance. So we don't delete the ire
15615 			 * itself, but just the nce_fp_mp for these 2 ire's
15616 			 * In the case of the other ire's we delete the ire's
15617 			 * themselves. Access to nce_fp_mp is completely
15618 			 * protected by ire_lock for IRE_MIPRTUN and
15619 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15620 			 * other cases for performance.
15621 			 */
15622 			if (ill->ill_isv6) {
15623 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15624 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15625 				    NULL);
15626 			} else {
15627 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15628 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15629 				    IRE_CACHE | IRE_BROADCAST,
15630 				    ire_fastpath_flush, NULL, ill);
15631 				mutex_enter(&ire_mrtun_lock);
15632 				if (ire_mrtun_count != 0) {
15633 					mutex_exit(&ire_mrtun_lock);
15634 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15635 					    IRE_MIPRTUN, ire_fastpath_flush,
15636 					    NULL, ill);
15637 				} else {
15638 					mutex_exit(&ire_mrtun_lock);
15639 				}
15640 			}
15641 			break;
15642 		case DL_NOTE_SDU_SIZE:
15643 			/*
15644 			 * Change the MTU size of the interface, of all
15645 			 * attached ipif's, and of all relevant ire's.  The
15646 			 * new value's a uint32_t at notify->dl_data.
15647 			 * Mtu change Vs. new ire creation - protocol below.
15648 			 *
15649 			 * a Mark the ipif as IPIF_CHANGING.
15650 			 * b Set the new mtu in the ipif.
15651 			 * c Change the ire_max_frag on all affected ires
15652 			 * d Unmark the IPIF_CHANGING
15653 			 *
15654 			 * To see how the protocol works, assume an interface
15655 			 * route is also being added simultaneously by
15656 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15657 			 * the ire. If the ire is created before step a,
15658 			 * it will be cleaned up by step c. If the ire is
15659 			 * created after step d, it will see the new value of
15660 			 * ipif_mtu. Any attempt to create the ire between
15661 			 * steps a to d will fail because of the IPIF_CHANGING
15662 			 * flag. Note that ire_create() is passed a pointer to
15663 			 * the ipif_mtu, and not the value. During ire_add
15664 			 * under the bucket lock, the ire_max_frag of the
15665 			 * new ire being created is set from the ipif/ire from
15666 			 * which it is being derived.
15667 			 */
15668 			mutex_enter(&ill->ill_lock);
15669 			ill->ill_max_frag = (uint_t)notify->dl_data;
15670 
15671 			/*
15672 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15673 			 * leave it alone
15674 			 */
15675 			if (ill->ill_mtu_userspecified) {
15676 				mutex_exit(&ill->ill_lock);
15677 				break;
15678 			}
15679 			ill->ill_max_mtu = ill->ill_max_frag;
15680 			if (ill->ill_isv6) {
15681 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15682 					ill->ill_max_mtu = IPV6_MIN_MTU;
15683 			} else {
15684 				if (ill->ill_max_mtu < IP_MIN_MTU)
15685 					ill->ill_max_mtu = IP_MIN_MTU;
15686 			}
15687 			for (ipif = ill->ill_ipif; ipif != NULL;
15688 			    ipif = ipif->ipif_next) {
15689 				/*
15690 				 * Don't override the mtu if the user
15691 				 * has explicitly set it.
15692 				 */
15693 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15694 					continue;
15695 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15696 				if (ipif->ipif_isv6)
15697 					ire = ipif_to_ire_v6(ipif);
15698 				else
15699 					ire = ipif_to_ire(ipif);
15700 				if (ire != NULL) {
15701 					ire->ire_max_frag = ipif->ipif_mtu;
15702 					ire_refrele(ire);
15703 				}
15704 				if (ipif->ipif_flags & IPIF_UP) {
15705 					if (ill->ill_isv6)
15706 						need_ire_walk_v6 = B_TRUE;
15707 					else
15708 						need_ire_walk_v4 = B_TRUE;
15709 				}
15710 			}
15711 			mutex_exit(&ill->ill_lock);
15712 			if (need_ire_walk_v4)
15713 				ire_walk_v4(ill_mtu_change, (char *)ill,
15714 				    ALL_ZONES);
15715 			if (need_ire_walk_v6)
15716 				ire_walk_v6(ill_mtu_change, (char *)ill,
15717 				    ALL_ZONES);
15718 			break;
15719 		case DL_NOTE_LINK_UP:
15720 		case DL_NOTE_LINK_DOWN: {
15721 			/*
15722 			 * We are writer. ill / phyint / ipsq assocs stable.
15723 			 * The RUNNING flag reflects the state of the link.
15724 			 */
15725 			phyint_t *phyint = ill->ill_phyint;
15726 			uint64_t new_phyint_flags;
15727 			boolean_t changed = B_FALSE;
15728 			boolean_t went_up;
15729 
15730 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15731 			mutex_enter(&phyint->phyint_lock);
15732 			new_phyint_flags = went_up ?
15733 			    phyint->phyint_flags | PHYI_RUNNING :
15734 			    phyint->phyint_flags & ~PHYI_RUNNING;
15735 			if (new_phyint_flags != phyint->phyint_flags) {
15736 				phyint->phyint_flags = new_phyint_flags;
15737 				changed = B_TRUE;
15738 			}
15739 			mutex_exit(&phyint->phyint_lock);
15740 			/*
15741 			 * ill_restart_dad handles the DAD restart and routing
15742 			 * socket notification logic.
15743 			 */
15744 			if (changed) {
15745 				ill_restart_dad(phyint->phyint_illv4, went_up);
15746 				ill_restart_dad(phyint->phyint_illv6, went_up);
15747 			}
15748 			break;
15749 		}
15750 		case DL_NOTE_PROMISC_ON_PHYS:
15751 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15752 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15753 			mutex_enter(&ill->ill_lock);
15754 			ill->ill_promisc_on_phys = B_TRUE;
15755 			mutex_exit(&ill->ill_lock);
15756 			break;
15757 		case DL_NOTE_PROMISC_OFF_PHYS:
15758 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15759 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15760 			mutex_enter(&ill->ill_lock);
15761 			ill->ill_promisc_on_phys = B_FALSE;
15762 			mutex_exit(&ill->ill_lock);
15763 			break;
15764 		case DL_NOTE_CAPAB_RENEG:
15765 			/*
15766 			 * Something changed on the driver side.
15767 			 * It wants us to renegotiate the capabilities
15768 			 * on this ill. The most likely cause is the
15769 			 * aggregation interface under us where a
15770 			 * port got added or went away.
15771 			 *
15772 			 * We reset the capabilities and set the
15773 			 * state to IDS_RENG so that when the ack
15774 			 * comes back, we can start the
15775 			 * renegotiation process.
15776 			 */
15777 			ill_capability_reset(ill);
15778 			ill->ill_dlpi_capab_state = IDS_RENEG;
15779 			break;
15780 		default:
15781 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15782 			    "type 0x%x for DL_NOTIFY_IND\n",
15783 			    notify->dl_notification));
15784 			break;
15785 		}
15786 
15787 		/*
15788 		 * As this is an asynchronous operation, we
15789 		 * should not call ill_dlpi_done
15790 		 */
15791 		break;
15792 	}
15793 	case DL_NOTIFY_ACK: {
15794 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15795 
15796 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15797 			ill->ill_note_link = 1;
15798 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15799 		break;
15800 	}
15801 	case DL_PHYS_ADDR_ACK: {
15802 		/*
15803 		 * We should have an IOCTL waiting on this when request
15804 		 * sent by ill_dl_phys.
15805 		 * However, ill_dl_phys was called on an ill queue (from
15806 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15807 		 * ioctl is known to be pending on ill_wq.
15808 		 * There are two additional phys_addr_req's sent to the
15809 		 * driver to get the token and lla. ill_phys_addr_pend
15810 		 * keeps track of the last one sent so we know which
15811 		 * response we are dealing with. ill_dlpi_done will
15812 		 * update ill_phys_addr_pend when it sends the next req.
15813 		 * We don't complete the IOCTL until all three DL_PARs
15814 		 * have been attempted.
15815 		 *
15816 		 * We don't need any lock to update ill_nd_lla* fields,
15817 		 * since the ill is not yet up, We grab the lock just
15818 		 * for uniformity with other code that accesses ill_nd_lla.
15819 		 */
15820 		physaddr_req = ill->ill_phys_addr_pend;
15821 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15822 		if (physaddr_req == DL_IPV6_TOKEN ||
15823 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15824 			if (physaddr_req == DL_IPV6_TOKEN) {
15825 				/*
15826 				 * bcopy to low-order bits of ill_token
15827 				 *
15828 				 * XXX Temporary hack - currently,
15829 				 * all known tokens are 64 bits,
15830 				 * so I'll cheat for the moment.
15831 				 */
15832 				dlp = (union DL_primitives *)mp->b_rptr;
15833 
15834 				mutex_enter(&ill->ill_lock);
15835 				bcopy((uchar_t *)(mp->b_rptr +
15836 				dlp->physaddr_ack.dl_addr_offset),
15837 				(void *)&ill->ill_token.s6_addr32[2],
15838 				dlp->physaddr_ack.dl_addr_length);
15839 				ill->ill_token_length =
15840 					dlp->physaddr_ack.dl_addr_length;
15841 				mutex_exit(&ill->ill_lock);
15842 			} else {
15843 				ASSERT(ill->ill_nd_lla_mp == NULL);
15844 				mp_hw = copyb(mp);
15845 				if (mp_hw == NULL) {
15846 					err = ENOMEM;
15847 					break;
15848 				}
15849 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15850 				mutex_enter(&ill->ill_lock);
15851 				ill->ill_nd_lla_mp = mp_hw;
15852 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15853 				dlp->physaddr_ack.dl_addr_offset;
15854 				ill->ill_nd_lla_len =
15855 					dlp->physaddr_ack.dl_addr_length;
15856 				mutex_exit(&ill->ill_lock);
15857 			}
15858 			break;
15859 		}
15860 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15861 		ASSERT(ill->ill_phys_addr_mp == NULL);
15862 		if (!ill->ill_ifname_pending)
15863 			break;
15864 		ill->ill_ifname_pending = 0;
15865 		if (!ioctl_aborted)
15866 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15867 		if (mp1 != NULL) {
15868 			ASSERT(connp == NULL);
15869 			q = ill->ill_wq;
15870 		}
15871 		/*
15872 		 * If any error acks received during the plumbing sequence,
15873 		 * ill_ifname_pending_err will be set. Break out and send up
15874 		 * the error to the pending ioctl.
15875 		 */
15876 		if (ill->ill_ifname_pending_err != 0) {
15877 			err = ill->ill_ifname_pending_err;
15878 			ill->ill_ifname_pending_err = 0;
15879 			break;
15880 		}
15881 		/*
15882 		 * Get the interface token.  If the zeroth interface
15883 		 * address is zero then set the address to the link local
15884 		 * address
15885 		 */
15886 		mp_hw = copyb(mp);
15887 		if (mp_hw == NULL) {
15888 			err = ENOMEM;
15889 			break;
15890 		}
15891 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15892 		ill->ill_phys_addr_mp = mp_hw;
15893 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15894 				dlp->physaddr_ack.dl_addr_offset;
15895 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15896 		    ill->ill_phys_addr_length == 0 ||
15897 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15898 			/*
15899 			 * Compatibility: atun driver returns a length of 0.
15900 			 * ipdptp has an ill_phys_addr_length of zero(from
15901 			 * DL_BIND_ACK) but a non-zero length here.
15902 			 * ipd has an ill_phys_addr_length of 4(from
15903 			 * DL_BIND_ACK) but a non-zero length here.
15904 			 */
15905 			ill->ill_phys_addr = NULL;
15906 		} else if (dlp->physaddr_ack.dl_addr_length !=
15907 		    ill->ill_phys_addr_length) {
15908 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15909 			    "Address length mismatch %d %d\n",
15910 			    dlp->physaddr_ack.dl_addr_length,
15911 			    ill->ill_phys_addr_length));
15912 			err = EINVAL;
15913 			break;
15914 		}
15915 		mutex_enter(&ill->ill_lock);
15916 		if (ill->ill_nd_lla_mp == NULL) {
15917 			ill->ill_nd_lla_mp = copyb(mp_hw);
15918 			if (ill->ill_nd_lla_mp == NULL) {
15919 				err = ENOMEM;
15920 				mutex_exit(&ill->ill_lock);
15921 				break;
15922 			}
15923 			ill->ill_nd_lla =
15924 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15925 			    dlp->physaddr_ack.dl_addr_offset;
15926 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15927 		}
15928 		mutex_exit(&ill->ill_lock);
15929 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15930 			(void) ill_setdefaulttoken(ill);
15931 
15932 		/*
15933 		 * If the ill zero interface has a zero address assign
15934 		 * it the proper link local address.
15935 		 */
15936 		ASSERT(ill->ill_ipif->ipif_id == 0);
15937 		if (ipif != NULL &&
15938 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15939 			(void) ipif_setlinklocal(ipif);
15940 		break;
15941 	}
15942 	case DL_OK_ACK:
15943 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15944 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15945 		    dloa->dl_correct_primitive));
15946 		switch (dloa->dl_correct_primitive) {
15947 		case DL_UNBIND_REQ:
15948 		case DL_ATTACH_REQ:
15949 		case DL_DETACH_REQ:
15950 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15951 			break;
15952 		}
15953 		break;
15954 	default:
15955 		break;
15956 	}
15957 
15958 	freemsg(mp);
15959 	if (mp1) {
15960 		struct iocblk *iocp;
15961 		int mode;
15962 
15963 		/*
15964 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15965 		 * SIOCSLIFNAME do a copyout.
15966 		 */
15967 		iocp = (struct iocblk *)mp1->b_rptr;
15968 
15969 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
15970 		    iocp->ioc_cmd == SIOCSLIFNAME)
15971 			mode = COPYOUT;
15972 		else
15973 			mode = NO_COPYOUT;
15974 		/*
15975 		 * The ioctl must complete now without EINPROGRESS
15976 		 * since ipsq_pending_mp_get has removed the ioctl mblk
15977 		 * from ipsq_pending_mp. Otherwise the ioctl will be
15978 		 * stuck for ever in the ipsq.
15979 		 */
15980 		ASSERT(err != EINPROGRESS);
15981 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
15982 
15983 	}
15984 }
15985 
15986 /*
15987  * ip_rput_other is called by ip_rput to handle messages modifying the global
15988  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15989  */
15990 /* ARGSUSED */
15991 void
15992 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15993 {
15994 	ill_t		*ill;
15995 	struct iocblk	*iocp;
15996 	mblk_t		*mp1;
15997 	conn_t		*connp = NULL;
15998 
15999 	ip1dbg(("ip_rput_other "));
16000 	ill = (ill_t *)q->q_ptr;
16001 	/*
16002 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16003 	 * in which case ipsq is NULL.
16004 	 */
16005 	if (ipsq != NULL) {
16006 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16007 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16008 	}
16009 
16010 	switch (mp->b_datap->db_type) {
16011 	case M_ERROR:
16012 	case M_HANGUP:
16013 		/*
16014 		 * The device has a problem.  We force the ILL down.  It can
16015 		 * be brought up again manually using SIOCSIFFLAGS (via
16016 		 * ifconfig or equivalent).
16017 		 */
16018 		ASSERT(ipsq != NULL);
16019 		if (mp->b_rptr < mp->b_wptr)
16020 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16021 		if (ill->ill_error == 0)
16022 			ill->ill_error = ENXIO;
16023 		if (!ill_down_start(q, mp))
16024 			return;
16025 		ipif_all_down_tail(ipsq, q, mp, NULL);
16026 		break;
16027 	case M_IOCACK:
16028 		iocp = (struct iocblk *)mp->b_rptr;
16029 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16030 		switch (iocp->ioc_cmd) {
16031 		case SIOCSTUNPARAM:
16032 		case OSIOCSTUNPARAM:
16033 			ASSERT(ipsq != NULL);
16034 			/*
16035 			 * Finish socket ioctl passed through to tun.
16036 			 * We should have an IOCTL waiting on this.
16037 			 */
16038 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16039 			if (ill->ill_isv6) {
16040 				struct iftun_req *ta;
16041 
16042 				/*
16043 				 * if a source or destination is
16044 				 * being set, try and set the link
16045 				 * local address for the tunnel
16046 				 */
16047 				ta = (struct iftun_req *)mp->b_cont->
16048 				    b_cont->b_rptr;
16049 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16050 					ipif_set_tun_llink(ill, ta);
16051 				}
16052 
16053 			}
16054 			if (mp1 != NULL) {
16055 				/*
16056 				 * Now copy back the b_next/b_prev used by
16057 				 * mi code for the mi_copy* functions.
16058 				 * See ip_sioctl_tunparam() for the reason.
16059 				 * Also protect against missing b_cont.
16060 				 */
16061 				if (mp->b_cont != NULL) {
16062 					mp->b_cont->b_next =
16063 					    mp1->b_cont->b_next;
16064 					mp->b_cont->b_prev =
16065 					    mp1->b_cont->b_prev;
16066 				}
16067 				inet_freemsg(mp1);
16068 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16069 				ASSERT(connp != NULL);
16070 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16071 				    iocp->ioc_error, NO_COPYOUT,
16072 				    ipsq->ipsq_current_ipif, ipsq);
16073 			} else {
16074 				ASSERT(connp == NULL);
16075 				putnext(q, mp);
16076 			}
16077 			break;
16078 		case SIOCGTUNPARAM:
16079 		case OSIOCGTUNPARAM:
16080 			/*
16081 			 * This is really M_IOCDATA from the tunnel driver.
16082 			 * convert back and complete the ioctl.
16083 			 * We should have an IOCTL waiting on this.
16084 			 */
16085 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16086 			if (mp1) {
16087 				/*
16088 				 * Now copy back the b_next/b_prev used by
16089 				 * mi code for the mi_copy* functions.
16090 				 * See ip_sioctl_tunparam() for the reason.
16091 				 * Also protect against missing b_cont.
16092 				 */
16093 				if (mp->b_cont != NULL) {
16094 					mp->b_cont->b_next =
16095 					    mp1->b_cont->b_next;
16096 					mp->b_cont->b_prev =
16097 					    mp1->b_cont->b_prev;
16098 				}
16099 				inet_freemsg(mp1);
16100 				if (iocp->ioc_error == 0)
16101 					mp->b_datap->db_type = M_IOCDATA;
16102 				ASSERT(connp != NULL);
16103 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16104 				    iocp->ioc_error, COPYOUT, NULL, NULL);
16105 			} else {
16106 				ASSERT(connp == NULL);
16107 				putnext(q, mp);
16108 			}
16109 			break;
16110 		default:
16111 			break;
16112 		}
16113 		break;
16114 	case M_IOCNAK:
16115 		iocp = (struct iocblk *)mp->b_rptr;
16116 
16117 		switch (iocp->ioc_cmd) {
16118 		int mode;
16119 		ipif_t	*ipif;
16120 
16121 		case DL_IOC_HDR_INFO:
16122 			/*
16123 			 * If this was the first attempt turn of the
16124 			 * fastpath probing.
16125 			 */
16126 			mutex_enter(&ill->ill_lock);
16127 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16128 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16129 				mutex_exit(&ill->ill_lock);
16130 				ill_fastpath_nack(ill);
16131 				ip1dbg(("ip_rput: DLPI fastpath off on "
16132 				    "interface %s\n",
16133 				    ill->ill_name));
16134 			} else {
16135 				mutex_exit(&ill->ill_lock);
16136 			}
16137 			freemsg(mp);
16138 			break;
16139 		case SIOCSTUNPARAM:
16140 		case OSIOCSTUNPARAM:
16141 			ASSERT(ipsq != NULL);
16142 			/*
16143 			 * Finish socket ioctl passed through to tun
16144 			 * We should have an IOCTL waiting on this.
16145 			 */
16146 			/* FALLTHRU */
16147 		case SIOCGTUNPARAM:
16148 		case OSIOCGTUNPARAM:
16149 			/*
16150 			 * This is really M_IOCDATA from the tunnel driver.
16151 			 * convert back and complete the ioctl.
16152 			 * We should have an IOCTL waiting on this.
16153 			 */
16154 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16155 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16156 				mp1 = ill_pending_mp_get(ill, &connp,
16157 				    iocp->ioc_id);
16158 				mode = COPYOUT;
16159 				ipsq = NULL;
16160 				ipif = NULL;
16161 			} else {
16162 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16163 				mode = NO_COPYOUT;
16164 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16165 				ipif = ipsq->ipsq_current_ipif;
16166 			}
16167 			if (mp1 != NULL) {
16168 				/*
16169 				 * Now copy back the b_next/b_prev used by
16170 				 * mi code for the mi_copy* functions.
16171 				 * See ip_sioctl_tunparam() for the reason.
16172 				 * Also protect against missing b_cont.
16173 				 */
16174 				if (mp->b_cont != NULL) {
16175 					mp->b_cont->b_next =
16176 					    mp1->b_cont->b_next;
16177 					mp->b_cont->b_prev =
16178 					    mp1->b_cont->b_prev;
16179 				}
16180 				inet_freemsg(mp1);
16181 				if (iocp->ioc_error == 0)
16182 					iocp->ioc_error = EINVAL;
16183 				ASSERT(connp != NULL);
16184 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16185 				    iocp->ioc_error, mode, ipif, ipsq);
16186 			} else {
16187 				ASSERT(connp == NULL);
16188 				putnext(q, mp);
16189 			}
16190 			break;
16191 		default:
16192 			break;
16193 		}
16194 	default:
16195 		break;
16196 	}
16197 }
16198 
16199 /*
16200  * NOTE : This function does not ire_refrele the ire argument passed in.
16201  *
16202  * IPQoS notes
16203  * IP policy is invoked twice for a forwarded packet, once on the read side
16204  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16205  * enabled. An additional parameter, in_ill, has been added for this purpose.
16206  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16207  * because ip_mroute drops this information.
16208  *
16209  */
16210 void
16211 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16212 {
16213 	uint32_t	pkt_len;
16214 	queue_t	*q;
16215 	uint32_t	sum;
16216 #define	rptr	((uchar_t *)ipha)
16217 	uint32_t	max_frag;
16218 	uint32_t	ill_index;
16219 	ill_t		*out_ill;
16220 
16221 	/* Get the ill_index of the incoming ILL */
16222 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16223 
16224 	/* Initiate Read side IPPF processing */
16225 	if (IPP_ENABLED(IPP_FWD_IN)) {
16226 		ip_process(IPP_FWD_IN, &mp, ill_index);
16227 		if (mp == NULL) {
16228 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16229 			    "during IPPF processing\n"));
16230 			return;
16231 		}
16232 	}
16233 
16234 	pkt_len = ntohs(ipha->ipha_length);
16235 
16236 	/* Adjust the checksum to reflect the ttl decrement. */
16237 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16238 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16239 
16240 	if (ipha->ipha_ttl-- <= 1) {
16241 		if (ip_csum_hdr(ipha)) {
16242 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16243 			goto drop_pkt;
16244 		}
16245 		/*
16246 		 * Note: ire_stq this will be NULL for multicast
16247 		 * datagrams using the long path through arp (the IRE
16248 		 * is not an IRE_CACHE). This should not cause
16249 		 * problems since we don't generate ICMP errors for
16250 		 * multicast packets.
16251 		 */
16252 		q = ire->ire_stq;
16253 		if (q != NULL) {
16254 			/* Sent by forwarding path, and router is global zone */
16255 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16256 			    GLOBAL_ZONEID);
16257 		} else
16258 			freemsg(mp);
16259 		return;
16260 	}
16261 
16262 	/*
16263 	 * Don't forward if the interface is down
16264 	 */
16265 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16266 		BUMP_MIB(&ip_mib, ipInDiscards);
16267 		ip2dbg(("ip_rput_forward:interface is down\n"));
16268 		goto drop_pkt;
16269 	}
16270 
16271 	/* Get the ill_index of the outgoing ILL */
16272 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16273 
16274 	out_ill = ire->ire_ipif->ipif_ill;
16275 
16276 	DTRACE_PROBE4(ip4__forwarding__start,
16277 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16278 
16279 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
16280 	    MSG_FWCOOKED_FORWARD, in_ill, out_ill, ipha, mp, mp);
16281 
16282 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16283 
16284 	if (mp == NULL)
16285 		return;
16286 	pkt_len = ntohs(ipha->ipha_length);
16287 
16288 	if (is_system_labeled()) {
16289 		mblk_t *mp1;
16290 
16291 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16292 			BUMP_MIB(&ip_mib, ipForwProhibits);
16293 			goto drop_pkt;
16294 		}
16295 		/* Size may have changed */
16296 		mp = mp1;
16297 		ipha = (ipha_t *)mp->b_rptr;
16298 		pkt_len = ntohs(ipha->ipha_length);
16299 	}
16300 
16301 	/* Check if there are options to update */
16302 	if (!IS_SIMPLE_IPH(ipha)) {
16303 		if (ip_csum_hdr(ipha)) {
16304 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16305 			goto drop_pkt;
16306 		}
16307 		if (ip_rput_forward_options(mp, ipha, ire)) {
16308 			return;
16309 		}
16310 
16311 		ipha->ipha_hdr_checksum = 0;
16312 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16313 	}
16314 	max_frag = ire->ire_max_frag;
16315 	if (pkt_len > max_frag) {
16316 		/*
16317 		 * It needs fragging on its way out.  We haven't
16318 		 * verified the header checksum yet.  Since we
16319 		 * are going to put a surely good checksum in the
16320 		 * outgoing header, we have to make sure that it
16321 		 * was good coming in.
16322 		 */
16323 		if (ip_csum_hdr(ipha)) {
16324 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16325 			goto drop_pkt;
16326 		}
16327 		/* Initiate Write side IPPF processing */
16328 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16329 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16330 			if (mp == NULL) {
16331 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16332 				    " during IPPF processing\n"));
16333 				return;
16334 			}
16335 		}
16336 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
16337 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16338 		return;
16339 	}
16340 
16341 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16342 	    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha, mblk_t *, mp);
16343 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
16344 	    MSG_FWCOOKED_OUT, NULL, out_ill, ipha, mp, mp);
16345 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16346 	if (mp == NULL)
16347 		return;
16348 
16349 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16350 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16351 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16352 	/* ip_xmit_v4 always consumes the packet */
16353 	return;
16354 
16355 drop_pkt:;
16356 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16357 	freemsg(mp);
16358 #undef	rptr
16359 }
16360 
16361 void
16362 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16363 {
16364 	ire_t	*ire;
16365 
16366 	ASSERT(!ipif->ipif_isv6);
16367 	/*
16368 	 * Find an IRE which matches the destination and the outgoing
16369 	 * queue in the cache table. All we need is an IRE_CACHE which
16370 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16371 	 * then it is enough to have some IRE_CACHE in the group.
16372 	 */
16373 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16374 		dst = ipif->ipif_pp_dst_addr;
16375 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16376 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16377 	if (ire == NULL) {
16378 		/*
16379 		 * Mark this packet to make it be delivered to
16380 		 * ip_rput_forward after the new ire has been
16381 		 * created.
16382 		 */
16383 		mp->b_prev = NULL;
16384 		mp->b_next = mp;
16385 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16386 		    NULL, 0, GLOBAL_ZONEID);
16387 	} else {
16388 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16389 		IRE_REFRELE(ire);
16390 	}
16391 }
16392 
16393 /* Update any source route, record route or timestamp options */
16394 static int
16395 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16396 {
16397 	ipoptp_t	opts;
16398 	uchar_t		*opt;
16399 	uint8_t		optval;
16400 	uint8_t		optlen;
16401 	ipaddr_t	dst;
16402 	uint32_t	ts;
16403 	ire_t		*dst_ire = NULL;
16404 	ire_t		*tmp_ire = NULL;
16405 	timestruc_t	now;
16406 
16407 	ip2dbg(("ip_rput_forward_options\n"));
16408 	dst = ipha->ipha_dst;
16409 	for (optval = ipoptp_first(&opts, ipha);
16410 	    optval != IPOPT_EOL;
16411 	    optval = ipoptp_next(&opts)) {
16412 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16413 		opt = opts.ipoptp_cur;
16414 		optlen = opts.ipoptp_len;
16415 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16416 		    optval, opts.ipoptp_len));
16417 		switch (optval) {
16418 			uint32_t off;
16419 		case IPOPT_SSRR:
16420 		case IPOPT_LSRR:
16421 			/* Check if adminstratively disabled */
16422 			if (!ip_forward_src_routed) {
16423 				BUMP_MIB(&ip_mib, ipForwProhibits);
16424 				if (ire->ire_stq != NULL) {
16425 					/*
16426 					 * Sent by forwarding path, and router
16427 					 * is global zone
16428 					 */
16429 					icmp_unreachable(ire->ire_stq, mp,
16430 					    ICMP_SOURCE_ROUTE_FAILED,
16431 					    GLOBAL_ZONEID);
16432 				} else {
16433 					ip0dbg(("ip_rput_forward_options: "
16434 					    "unable to send unreach\n"));
16435 					freemsg(mp);
16436 				}
16437 				return (-1);
16438 			}
16439 
16440 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16441 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16442 			if (dst_ire == NULL) {
16443 				/*
16444 				 * Must be partial since ip_rput_options
16445 				 * checked for strict.
16446 				 */
16447 				break;
16448 			}
16449 			off = opt[IPOPT_OFFSET];
16450 			off--;
16451 		redo_srr:
16452 			if (optlen < IP_ADDR_LEN ||
16453 			    off > optlen - IP_ADDR_LEN) {
16454 				/* End of source route */
16455 				ip1dbg((
16456 				    "ip_rput_forward_options: end of SR\n"));
16457 				ire_refrele(dst_ire);
16458 				break;
16459 			}
16460 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16461 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16462 			    IP_ADDR_LEN);
16463 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16464 			    ntohl(dst)));
16465 
16466 			/*
16467 			 * Check if our address is present more than
16468 			 * once as consecutive hops in source route.
16469 			 */
16470 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16471 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16472 			if (tmp_ire != NULL) {
16473 				ire_refrele(tmp_ire);
16474 				off += IP_ADDR_LEN;
16475 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16476 				goto redo_srr;
16477 			}
16478 			ipha->ipha_dst = dst;
16479 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16480 			ire_refrele(dst_ire);
16481 			break;
16482 		case IPOPT_RR:
16483 			off = opt[IPOPT_OFFSET];
16484 			off--;
16485 			if (optlen < IP_ADDR_LEN ||
16486 			    off > optlen - IP_ADDR_LEN) {
16487 				/* No more room - ignore */
16488 				ip1dbg((
16489 				    "ip_rput_forward_options: end of RR\n"));
16490 				break;
16491 			}
16492 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16493 			    IP_ADDR_LEN);
16494 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16495 			break;
16496 		case IPOPT_TS:
16497 			/* Insert timestamp if there is room */
16498 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16499 			case IPOPT_TS_TSONLY:
16500 				off = IPOPT_TS_TIMELEN;
16501 				break;
16502 			case IPOPT_TS_PRESPEC:
16503 			case IPOPT_TS_PRESPEC_RFC791:
16504 				/* Verify that the address matched */
16505 				off = opt[IPOPT_OFFSET] - 1;
16506 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16507 				dst_ire = ire_ctable_lookup(dst, 0,
16508 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16509 				    MATCH_IRE_TYPE);
16510 
16511 				if (dst_ire == NULL) {
16512 					/* Not for us */
16513 					break;
16514 				}
16515 				ire_refrele(dst_ire);
16516 				/* FALLTHRU */
16517 			case IPOPT_TS_TSANDADDR:
16518 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16519 				break;
16520 			default:
16521 				/*
16522 				 * ip_*put_options should have already
16523 				 * dropped this packet.
16524 				 */
16525 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16526 				    "unknown IT - bug in ip_rput_options?\n");
16527 				return (0);	/* Keep "lint" happy */
16528 			}
16529 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16530 				/* Increase overflow counter */
16531 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16532 				opt[IPOPT_POS_OV_FLG] =
16533 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16534 				    (off << 4));
16535 				break;
16536 			}
16537 			off = opt[IPOPT_OFFSET] - 1;
16538 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16539 			case IPOPT_TS_PRESPEC:
16540 			case IPOPT_TS_PRESPEC_RFC791:
16541 			case IPOPT_TS_TSANDADDR:
16542 				bcopy(&ire->ire_src_addr,
16543 				    (char *)opt + off, IP_ADDR_LEN);
16544 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16545 				/* FALLTHRU */
16546 			case IPOPT_TS_TSONLY:
16547 				off = opt[IPOPT_OFFSET] - 1;
16548 				/* Compute # of milliseconds since midnight */
16549 				gethrestime(&now);
16550 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16551 				    now.tv_nsec / (NANOSEC / MILLISEC);
16552 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16553 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16554 				break;
16555 			}
16556 			break;
16557 		}
16558 	}
16559 	return (0);
16560 }
16561 
16562 /*
16563  * This is called after processing at least one of AH/ESP headers.
16564  *
16565  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16566  * the actual, physical interface on which the packet was received,
16567  * but, when ip_strict_dst_multihoming is set to 1, could be the
16568  * interface which had the ipha_dst configured when the packet went
16569  * through ip_rput. The ill_index corresponding to the recv_ill
16570  * is saved in ipsec_in_rill_index
16571  */
16572 void
16573 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16574 {
16575 	mblk_t *mp;
16576 	ipaddr_t dst;
16577 	in6_addr_t *v6dstp;
16578 	ipha_t *ipha;
16579 	ip6_t *ip6h;
16580 	ipsec_in_t *ii;
16581 	boolean_t ill_need_rele = B_FALSE;
16582 	boolean_t rill_need_rele = B_FALSE;
16583 	boolean_t ire_need_rele = B_FALSE;
16584 
16585 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16586 	ASSERT(ii->ipsec_in_ill_index != 0);
16587 
16588 	mp = ipsec_mp->b_cont;
16589 	ASSERT(mp != NULL);
16590 
16591 
16592 	if (ill == NULL) {
16593 		ASSERT(recv_ill == NULL);
16594 		/*
16595 		 * We need to get the original queue on which ip_rput_local
16596 		 * or ip_rput_data_v6 was called.
16597 		 */
16598 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16599 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16600 		ill_need_rele = B_TRUE;
16601 
16602 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16603 			recv_ill = ill_lookup_on_ifindex(
16604 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16605 			    NULL, NULL, NULL, NULL);
16606 			rill_need_rele = B_TRUE;
16607 		} else {
16608 			recv_ill = ill;
16609 		}
16610 
16611 		if ((ill == NULL) || (recv_ill == NULL)) {
16612 			ip0dbg(("ip_fanout_proto_again: interface "
16613 			    "disappeared\n"));
16614 			if (ill != NULL)
16615 				ill_refrele(ill);
16616 			if (recv_ill != NULL)
16617 				ill_refrele(recv_ill);
16618 			freemsg(ipsec_mp);
16619 			return;
16620 		}
16621 	}
16622 
16623 	ASSERT(ill != NULL && recv_ill != NULL);
16624 
16625 	if (mp->b_datap->db_type == M_CTL) {
16626 		/*
16627 		 * AH/ESP is returning the ICMP message after
16628 		 * removing their headers. Fanout again till
16629 		 * it gets to the right protocol.
16630 		 */
16631 		if (ii->ipsec_in_v4) {
16632 			icmph_t *icmph;
16633 			int iph_hdr_length;
16634 			int hdr_length;
16635 
16636 			ipha = (ipha_t *)mp->b_rptr;
16637 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16638 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16639 			ipha = (ipha_t *)&icmph[1];
16640 			hdr_length = IPH_HDR_LENGTH(ipha);
16641 			/*
16642 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16643 			 * Reset the type to M_DATA.
16644 			 */
16645 			mp->b_datap->db_type = M_DATA;
16646 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16647 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16648 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16649 		} else {
16650 			icmp6_t *icmp6;
16651 			int hdr_length;
16652 
16653 			ip6h = (ip6_t *)mp->b_rptr;
16654 			/* Don't call hdr_length_v6() unless you have to. */
16655 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16656 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16657 			else
16658 				hdr_length = IPV6_HDR_LEN;
16659 
16660 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16661 			/*
16662 			 * icmp_inbound_error_fanout_v6 may need to do
16663 			 * pullupmsg.  Reset the type to M_DATA.
16664 			 */
16665 			mp->b_datap->db_type = M_DATA;
16666 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16667 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16668 		}
16669 		if (ill_need_rele)
16670 			ill_refrele(ill);
16671 		if (rill_need_rele)
16672 			ill_refrele(recv_ill);
16673 		return;
16674 	}
16675 
16676 	if (ii->ipsec_in_v4) {
16677 		ipha = (ipha_t *)mp->b_rptr;
16678 		dst = ipha->ipha_dst;
16679 		if (CLASSD(dst)) {
16680 			/*
16681 			 * Multicast has to be delivered to all streams.
16682 			 */
16683 			dst = INADDR_BROADCAST;
16684 		}
16685 
16686 		if (ire == NULL) {
16687 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16688 			    MBLK_GETLABEL(mp));
16689 			if (ire == NULL) {
16690 				if (ill_need_rele)
16691 					ill_refrele(ill);
16692 				if (rill_need_rele)
16693 					ill_refrele(recv_ill);
16694 				ip1dbg(("ip_fanout_proto_again: "
16695 				    "IRE not found"));
16696 				freemsg(ipsec_mp);
16697 				return;
16698 			}
16699 			ire_need_rele = B_TRUE;
16700 		}
16701 
16702 		switch (ipha->ipha_protocol) {
16703 			case IPPROTO_UDP:
16704 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16705 				    recv_ill);
16706 				if (ire_need_rele)
16707 					ire_refrele(ire);
16708 				break;
16709 			case IPPROTO_TCP:
16710 				if (!ire_need_rele)
16711 					IRE_REFHOLD(ire);
16712 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16713 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16714 				IRE_REFRELE(ire);
16715 				if (mp != NULL)
16716 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16717 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16718 				break;
16719 			case IPPROTO_SCTP:
16720 				if (!ire_need_rele)
16721 					IRE_REFHOLD(ire);
16722 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16723 				    ipsec_mp, 0, ill->ill_rq, dst);
16724 				break;
16725 			default:
16726 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16727 				    recv_ill);
16728 				if (ire_need_rele)
16729 					ire_refrele(ire);
16730 				break;
16731 		}
16732 	} else {
16733 		uint32_t rput_flags = 0;
16734 
16735 		ip6h = (ip6_t *)mp->b_rptr;
16736 		v6dstp = &ip6h->ip6_dst;
16737 		/*
16738 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16739 		 * address.
16740 		 *
16741 		 * Currently, we don't store that state in the IPSEC_IN
16742 		 * message, and we may need to.
16743 		 */
16744 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16745 		    IP6_IN_LLMCAST : 0);
16746 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16747 		    NULL, NULL);
16748 	}
16749 	if (ill_need_rele)
16750 		ill_refrele(ill);
16751 	if (rill_need_rele)
16752 		ill_refrele(recv_ill);
16753 }
16754 
16755 /*
16756  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16757  * returns 'true' if there are still fragments left on the queue, in
16758  * which case we restart the timer.
16759  */
16760 void
16761 ill_frag_timer(void *arg)
16762 {
16763 	ill_t	*ill = (ill_t *)arg;
16764 	boolean_t frag_pending;
16765 
16766 	mutex_enter(&ill->ill_lock);
16767 	ASSERT(!ill->ill_fragtimer_executing);
16768 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16769 		ill->ill_frag_timer_id = 0;
16770 		mutex_exit(&ill->ill_lock);
16771 		return;
16772 	}
16773 	ill->ill_fragtimer_executing = 1;
16774 	mutex_exit(&ill->ill_lock);
16775 
16776 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16777 
16778 	/*
16779 	 * Restart the timer, if we have fragments pending or if someone
16780 	 * wanted us to be scheduled again.
16781 	 */
16782 	mutex_enter(&ill->ill_lock);
16783 	ill->ill_fragtimer_executing = 0;
16784 	ill->ill_frag_timer_id = 0;
16785 	if (frag_pending || ill->ill_fragtimer_needrestart)
16786 		ill_frag_timer_start(ill);
16787 	mutex_exit(&ill->ill_lock);
16788 }
16789 
16790 void
16791 ill_frag_timer_start(ill_t *ill)
16792 {
16793 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16794 
16795 	/* If the ill is closing or opening don't proceed */
16796 	if (ill->ill_state_flags & ILL_CONDEMNED)
16797 		return;
16798 
16799 	if (ill->ill_fragtimer_executing) {
16800 		/*
16801 		 * ill_frag_timer is currently executing. Just record the
16802 		 * the fact that we want the timer to be restarted.
16803 		 * ill_frag_timer will post a timeout before it returns,
16804 		 * ensuring it will be called again.
16805 		 */
16806 		ill->ill_fragtimer_needrestart = 1;
16807 		return;
16808 	}
16809 
16810 	if (ill->ill_frag_timer_id == 0) {
16811 		/*
16812 		 * The timer is neither running nor is the timeout handler
16813 		 * executing. Post a timeout so that ill_frag_timer will be
16814 		 * called
16815 		 */
16816 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16817 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16818 		ill->ill_fragtimer_needrestart = 0;
16819 	}
16820 }
16821 
16822 /*
16823  * This routine is needed for loopback when forwarding multicasts.
16824  *
16825  * IPQoS Notes:
16826  * IPPF processing is done in fanout routines.
16827  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16828  * processing for IPSec packets is done when it comes back in clear.
16829  * NOTE : The callers of this function need to do the ire_refrele for the
16830  *	  ire that is being passed in.
16831  */
16832 void
16833 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16834     ill_t *recv_ill)
16835 {
16836 	ill_t	*ill = (ill_t *)q->q_ptr;
16837 	uint32_t	sum;
16838 	uint32_t	u1;
16839 	uint32_t	u2;
16840 	int		hdr_length;
16841 	boolean_t	mctl_present;
16842 	mblk_t		*first_mp = mp;
16843 	mblk_t		*hada_mp = NULL;
16844 	ipha_t		*inner_ipha;
16845 
16846 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16847 	    "ip_rput_locl_start: q %p", q);
16848 
16849 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16850 
16851 
16852 #define	rptr	((uchar_t *)ipha)
16853 #define	iphs	((uint16_t *)ipha)
16854 
16855 	/*
16856 	 * no UDP or TCP packet should come here anymore.
16857 	 */
16858 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16859 	    (ipha->ipha_protocol != IPPROTO_UDP));
16860 
16861 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16862 	if (mctl_present &&
16863 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16864 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16865 
16866 		/*
16867 		 * It's an IPsec accelerated packet.
16868 		 * Keep a pointer to the data attributes around until
16869 		 * we allocate the ipsec_info_t.
16870 		 */
16871 		IPSECHW_DEBUG(IPSECHW_PKT,
16872 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16873 		hada_mp = first_mp;
16874 		hada_mp->b_cont = NULL;
16875 		/*
16876 		 * Since it is accelerated, it comes directly from
16877 		 * the ill and the data attributes is followed by
16878 		 * the packet data.
16879 		 */
16880 		ASSERT(mp->b_datap->db_type != M_CTL);
16881 		first_mp = mp;
16882 		mctl_present = B_FALSE;
16883 	}
16884 
16885 	/*
16886 	 * IF M_CTL is not present, then ipsec_in_is_secure
16887 	 * should return B_TRUE. There is a case where loopback
16888 	 * packets has an M_CTL in the front with all the
16889 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16890 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16891 	 * packets never comes here, it is safe to ASSERT the
16892 	 * following.
16893 	 */
16894 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16895 
16896 
16897 	/* u1 is # words of IP options */
16898 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16899 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16900 
16901 	if (u1) {
16902 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16903 			if (hada_mp != NULL)
16904 				freemsg(hada_mp);
16905 			return;
16906 		}
16907 	} else {
16908 		/* Check the IP header checksum.  */
16909 #define	uph	((uint16_t *)ipha)
16910 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16911 		    uph[6] + uph[7] + uph[8] + uph[9];
16912 #undef  uph
16913 		/* finish doing IP checksum */
16914 		sum = (sum & 0xFFFF) + (sum >> 16);
16915 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16916 		/*
16917 		 * Don't verify header checksum if this packet is coming
16918 		 * back from AH/ESP as we already did it.
16919 		 */
16920 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16921 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16922 			goto drop_pkt;
16923 		}
16924 	}
16925 
16926 	/*
16927 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16928 	 * might be called more than once for secure packets, count only
16929 	 * the first time.
16930 	 */
16931 	if (!mctl_present) {
16932 		UPDATE_IB_PKT_COUNT(ire);
16933 		ire->ire_last_used_time = lbolt;
16934 	}
16935 
16936 	/* Check for fragmentation offset. */
16937 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16938 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16939 	if (u1) {
16940 		/*
16941 		 * We re-assemble fragments before we do the AH/ESP
16942 		 * processing. Thus, M_CTL should not be present
16943 		 * while we are re-assembling.
16944 		 */
16945 		ASSERT(!mctl_present);
16946 		ASSERT(first_mp == mp);
16947 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16948 			return;
16949 		}
16950 		/*
16951 		 * Make sure that first_mp points back to mp as
16952 		 * the mp we came in with could have changed in
16953 		 * ip_rput_fragment().
16954 		 */
16955 		ipha = (ipha_t *)mp->b_rptr;
16956 		first_mp = mp;
16957 	}
16958 
16959 	/*
16960 	 * Clear hardware checksumming flag as it is currently only
16961 	 * used by TCP and UDP.
16962 	 */
16963 	DB_CKSUMFLAGS(mp) = 0;
16964 
16965 	/* Now we have a complete datagram, destined for this machine. */
16966 	u1 = IPH_HDR_LENGTH(ipha);
16967 	switch (ipha->ipha_protocol) {
16968 	case IPPROTO_ICMP: {
16969 		ire_t		*ire_zone;
16970 		ilm_t		*ilm;
16971 		mblk_t		*mp1;
16972 		zoneid_t	last_zoneid;
16973 
16974 		if (CLASSD(ipha->ipha_dst) &&
16975 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
16976 			ASSERT(ire->ire_type == IRE_BROADCAST);
16977 			/*
16978 			 * In the multicast case, applications may have joined
16979 			 * the group from different zones, so we need to deliver
16980 			 * the packet to each of them. Loop through the
16981 			 * multicast memberships structures (ilm) on the receive
16982 			 * ill and send a copy of the packet up each matching
16983 			 * one. However, we don't do this for multicasts sent on
16984 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16985 			 * they must stay in the sender's zone.
16986 			 *
16987 			 * ilm_add_v6() ensures that ilms in the same zone are
16988 			 * contiguous in the ill_ilm list. We use this property
16989 			 * to avoid sending duplicates needed when two
16990 			 * applications in the same zone join the same group on
16991 			 * different logical interfaces: we ignore the ilm if
16992 			 * its zoneid is the same as the last matching one.
16993 			 * In addition, the sending of the packet for
16994 			 * ire_zoneid is delayed until all of the other ilms
16995 			 * have been exhausted.
16996 			 */
16997 			last_zoneid = -1;
16998 			ILM_WALKER_HOLD(recv_ill);
16999 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17000 			    ilm = ilm->ilm_next) {
17001 				if ((ilm->ilm_flags & ILM_DELETED) ||
17002 				    ipha->ipha_dst != ilm->ilm_addr ||
17003 				    ilm->ilm_zoneid == last_zoneid ||
17004 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17005 				    ilm->ilm_zoneid == ALL_ZONES ||
17006 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17007 					continue;
17008 				mp1 = ip_copymsg(first_mp);
17009 				if (mp1 == NULL)
17010 					continue;
17011 				icmp_inbound(q, mp1, B_TRUE, ill,
17012 				    0, sum, mctl_present, B_TRUE,
17013 				    recv_ill, ilm->ilm_zoneid);
17014 				last_zoneid = ilm->ilm_zoneid;
17015 			}
17016 			ILM_WALKER_RELE(recv_ill);
17017 		} else if (ire->ire_type == IRE_BROADCAST) {
17018 			/*
17019 			 * In the broadcast case, there may be many zones
17020 			 * which need a copy of the packet delivered to them.
17021 			 * There is one IRE_BROADCAST per broadcast address
17022 			 * and per zone; we walk those using a helper function.
17023 			 * In addition, the sending of the packet for ire is
17024 			 * delayed until all of the other ires have been
17025 			 * processed.
17026 			 */
17027 			IRB_REFHOLD(ire->ire_bucket);
17028 			ire_zone = NULL;
17029 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17030 			    ire)) != NULL) {
17031 				mp1 = ip_copymsg(first_mp);
17032 				if (mp1 == NULL)
17033 					continue;
17034 
17035 				UPDATE_IB_PKT_COUNT(ire_zone);
17036 				ire_zone->ire_last_used_time = lbolt;
17037 				icmp_inbound(q, mp1, B_TRUE, ill,
17038 				    0, sum, mctl_present, B_TRUE,
17039 				    recv_ill, ire_zone->ire_zoneid);
17040 			}
17041 			IRB_REFRELE(ire->ire_bucket);
17042 		}
17043 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17044 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17045 		    ire->ire_zoneid);
17046 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17047 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17048 		return;
17049 	}
17050 	case IPPROTO_IGMP:
17051 		/*
17052 		 * If we are not willing to accept IGMP packets in clear,
17053 		 * then check with global policy.
17054 		 */
17055 		if (igmp_accept_clear_messages == 0) {
17056 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17057 			    ipha, NULL, mctl_present);
17058 			if (first_mp == NULL)
17059 				return;
17060 		}
17061 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17062 			freemsg(first_mp);
17063 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17064 			BUMP_MIB(&ip_mib, ipInDiscards);
17065 			return;
17066 		}
17067 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17068 			/* Bad packet - discarded by igmp_input */
17069 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17070 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17071 			if (mctl_present)
17072 				freeb(first_mp);
17073 			return;
17074 		}
17075 		/*
17076 		 * igmp_input() may have returned the pulled up message.
17077 		 * So first_mp and ipha need to be reinitialized.
17078 		 */
17079 		ipha = (ipha_t *)mp->b_rptr;
17080 		if (mctl_present)
17081 			first_mp->b_cont = mp;
17082 		else
17083 			first_mp = mp;
17084 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17085 			/* No user-level listener for IGMP packets */
17086 			goto drop_pkt;
17087 		}
17088 		/* deliver to local raw users */
17089 		break;
17090 	case IPPROTO_PIM:
17091 		/*
17092 		 * If we are not willing to accept PIM packets in clear,
17093 		 * then check with global policy.
17094 		 */
17095 		if (pim_accept_clear_messages == 0) {
17096 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17097 			    ipha, NULL, mctl_present);
17098 			if (first_mp == NULL)
17099 				return;
17100 		}
17101 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17102 			freemsg(first_mp);
17103 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17104 			BUMP_MIB(&ip_mib, ipInDiscards);
17105 			return;
17106 		}
17107 		if (pim_input(q, mp) != 0) {
17108 			/* Bad packet - discarded by pim_input */
17109 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17110 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17111 			if (mctl_present)
17112 				freeb(first_mp);
17113 			return;
17114 		}
17115 
17116 		/*
17117 		 * pim_input() may have pulled up the message so ipha needs to
17118 		 * be reinitialized.
17119 		 */
17120 		ipha = (ipha_t *)mp->b_rptr;
17121 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17122 			/* No user-level listener for PIM packets */
17123 			goto drop_pkt;
17124 		}
17125 		/* deliver to local raw users */
17126 		break;
17127 	case IPPROTO_ENCAP:
17128 		/*
17129 		 * Handle self-encapsulated packets (IP-in-IP where
17130 		 * the inner addresses == the outer addresses).
17131 		 */
17132 		hdr_length = IPH_HDR_LENGTH(ipha);
17133 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17134 		    mp->b_wptr) {
17135 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17136 			    sizeof (ipha_t) - mp->b_rptr)) {
17137 				BUMP_MIB(&ip_mib, ipInDiscards);
17138 				freemsg(first_mp);
17139 				return;
17140 			}
17141 			ipha = (ipha_t *)mp->b_rptr;
17142 		}
17143 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17144 		/*
17145 		 * Check the sanity of the inner IP header.
17146 		 */
17147 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17148 			BUMP_MIB(&ip_mib, ipInDiscards);
17149 			freemsg(first_mp);
17150 			return;
17151 		}
17152 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17153 			BUMP_MIB(&ip_mib, ipInDiscards);
17154 			freemsg(first_mp);
17155 			return;
17156 		}
17157 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17158 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17159 			ipsec_in_t *ii;
17160 
17161 			/*
17162 			 * Self-encapsulated tunnel packet. Remove
17163 			 * the outer IP header and fanout again.
17164 			 * We also need to make sure that the inner
17165 			 * header is pulled up until options.
17166 			 */
17167 			mp->b_rptr = (uchar_t *)inner_ipha;
17168 			ipha = inner_ipha;
17169 			hdr_length = IPH_HDR_LENGTH(ipha);
17170 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17171 				if (!pullupmsg(mp, (uchar_t *)ipha +
17172 				    + hdr_length - mp->b_rptr)) {
17173 					freemsg(first_mp);
17174 					return;
17175 				}
17176 				ipha = (ipha_t *)mp->b_rptr;
17177 			}
17178 			if (!mctl_present) {
17179 				ASSERT(first_mp == mp);
17180 				/*
17181 				 * This means that somebody is sending
17182 				 * Self-encapsualted packets without AH/ESP.
17183 				 * If AH/ESP was present, we would have already
17184 				 * allocated the first_mp.
17185 				 */
17186 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
17187 				    NULL) {
17188 					ip1dbg(("ip_proto_input: IPSEC_IN "
17189 					    "allocation failure.\n"));
17190 					BUMP_MIB(&ip_mib, ipInDiscards);
17191 					freemsg(mp);
17192 					return;
17193 				}
17194 				first_mp->b_cont = mp;
17195 			}
17196 			/*
17197 			 * We generally store the ill_index if we need to
17198 			 * do IPSEC processing as we lose the ill queue when
17199 			 * we come back. But in this case, we never should
17200 			 * have to store the ill_index here as it should have
17201 			 * been stored previously when we processed the
17202 			 * AH/ESP header in this routine or for non-ipsec
17203 			 * cases, we still have the queue. But for some bad
17204 			 * packets from the wire, we can get to IPSEC after
17205 			 * this and we better store the index for that case.
17206 			 */
17207 			ill = (ill_t *)q->q_ptr;
17208 			ii = (ipsec_in_t *)first_mp->b_rptr;
17209 			ii->ipsec_in_ill_index =
17210 			    ill->ill_phyint->phyint_ifindex;
17211 			ii->ipsec_in_rill_index =
17212 			    recv_ill->ill_phyint->phyint_ifindex;
17213 			if (ii->ipsec_in_decaps) {
17214 				/*
17215 				 * This packet is self-encapsulated multiple
17216 				 * times. We don't want to recurse infinitely.
17217 				 * To keep it simple, drop the packet.
17218 				 */
17219 				BUMP_MIB(&ip_mib, ipInDiscards);
17220 				freemsg(first_mp);
17221 				return;
17222 			}
17223 			ii->ipsec_in_decaps = B_TRUE;
17224 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
17225 			return;
17226 		}
17227 		break;
17228 	case IPPROTO_AH:
17229 	case IPPROTO_ESP: {
17230 		/*
17231 		 * Fast path for AH/ESP. If this is the first time
17232 		 * we are sending a datagram to AH/ESP, allocate
17233 		 * a IPSEC_IN message and prepend it. Otherwise,
17234 		 * just fanout.
17235 		 */
17236 
17237 		int ipsec_rc;
17238 		ipsec_in_t *ii;
17239 
17240 		IP_STAT(ipsec_proto_ahesp);
17241 		if (!mctl_present) {
17242 			ASSERT(first_mp == mp);
17243 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
17244 				ip1dbg(("ip_proto_input: IPSEC_IN "
17245 				    "allocation failure.\n"));
17246 				freemsg(hada_mp); /* okay ifnull */
17247 				BUMP_MIB(&ip_mib, ipInDiscards);
17248 				freemsg(mp);
17249 				return;
17250 			}
17251 			/*
17252 			 * Store the ill_index so that when we come back
17253 			 * from IPSEC we ride on the same queue.
17254 			 */
17255 			ill = (ill_t *)q->q_ptr;
17256 			ii = (ipsec_in_t *)first_mp->b_rptr;
17257 			ii->ipsec_in_ill_index =
17258 			    ill->ill_phyint->phyint_ifindex;
17259 			ii->ipsec_in_rill_index =
17260 			    recv_ill->ill_phyint->phyint_ifindex;
17261 			first_mp->b_cont = mp;
17262 			/*
17263 			 * Cache hardware acceleration info.
17264 			 */
17265 			if (hada_mp != NULL) {
17266 				IPSECHW_DEBUG(IPSECHW_PKT,
17267 				    ("ip_rput_local: caching data attr.\n"));
17268 				ii->ipsec_in_accelerated = B_TRUE;
17269 				ii->ipsec_in_da = hada_mp;
17270 				hada_mp = NULL;
17271 			}
17272 		} else {
17273 			ii = (ipsec_in_t *)first_mp->b_rptr;
17274 		}
17275 
17276 		if (!ipsec_loaded()) {
17277 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17278 			    ire->ire_zoneid);
17279 			return;
17280 		}
17281 
17282 		/* select inbound SA and have IPsec process the pkt */
17283 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17284 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17285 			if (esph == NULL)
17286 				return;
17287 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17288 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17289 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17290 			    first_mp, esph);
17291 		} else {
17292 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17293 			if (ah == NULL)
17294 				return;
17295 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17296 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17297 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17298 			    first_mp, ah);
17299 		}
17300 
17301 		switch (ipsec_rc) {
17302 		case IPSEC_STATUS_SUCCESS:
17303 			break;
17304 		case IPSEC_STATUS_FAILED:
17305 			BUMP_MIB(&ip_mib, ipInDiscards);
17306 			/* FALLTHRU */
17307 		case IPSEC_STATUS_PENDING:
17308 			return;
17309 		}
17310 		/* we're done with IPsec processing, send it up */
17311 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17312 		return;
17313 	}
17314 	default:
17315 		break;
17316 	}
17317 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17318 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17319 		    ire->ire_zoneid));
17320 		goto drop_pkt;
17321 	}
17322 	/*
17323 	 * Handle protocols with which IP is less intimate.  There
17324 	 * can be more than one stream bound to a particular
17325 	 * protocol.  When this is the case, each one gets a copy
17326 	 * of any incoming packets.
17327 	 */
17328 	ip_fanout_proto(q, first_mp, ill, ipha,
17329 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17330 	    B_TRUE, recv_ill, ire->ire_zoneid);
17331 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17332 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17333 	return;
17334 
17335 drop_pkt:
17336 	freemsg(first_mp);
17337 	if (hada_mp != NULL)
17338 		freeb(hada_mp);
17339 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17340 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17341 #undef	rptr
17342 #undef  iphs
17343 
17344 }
17345 
17346 /*
17347  * Update any source route, record route or timestamp options.
17348  * Check that we are at end of strict source route.
17349  * The options have already been checked for sanity in ip_rput_options().
17350  */
17351 static boolean_t
17352 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17353 {
17354 	ipoptp_t	opts;
17355 	uchar_t		*opt;
17356 	uint8_t		optval;
17357 	uint8_t		optlen;
17358 	ipaddr_t	dst;
17359 	uint32_t	ts;
17360 	ire_t		*dst_ire;
17361 	timestruc_t	now;
17362 	zoneid_t	zoneid;
17363 	ill_t		*ill;
17364 
17365 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17366 
17367 	ip2dbg(("ip_rput_local_options\n"));
17368 
17369 	for (optval = ipoptp_first(&opts, ipha);
17370 	    optval != IPOPT_EOL;
17371 	    optval = ipoptp_next(&opts)) {
17372 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17373 		opt = opts.ipoptp_cur;
17374 		optlen = opts.ipoptp_len;
17375 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17376 		    optval, optlen));
17377 		switch (optval) {
17378 			uint32_t off;
17379 		case IPOPT_SSRR:
17380 		case IPOPT_LSRR:
17381 			off = opt[IPOPT_OFFSET];
17382 			off--;
17383 			if (optlen < IP_ADDR_LEN ||
17384 			    off > optlen - IP_ADDR_LEN) {
17385 				/* End of source route */
17386 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17387 				break;
17388 			}
17389 			/*
17390 			 * This will only happen if two consecutive entries
17391 			 * in the source route contains our address or if
17392 			 * it is a packet with a loose source route which
17393 			 * reaches us before consuming the whole source route
17394 			 */
17395 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17396 			if (optval == IPOPT_SSRR) {
17397 				goto bad_src_route;
17398 			}
17399 			/*
17400 			 * Hack: instead of dropping the packet truncate the
17401 			 * source route to what has been used by filling the
17402 			 * rest with IPOPT_NOP.
17403 			 */
17404 			opt[IPOPT_OLEN] = (uint8_t)off;
17405 			while (off < optlen) {
17406 				opt[off++] = IPOPT_NOP;
17407 			}
17408 			break;
17409 		case IPOPT_RR:
17410 			off = opt[IPOPT_OFFSET];
17411 			off--;
17412 			if (optlen < IP_ADDR_LEN ||
17413 			    off > optlen - IP_ADDR_LEN) {
17414 				/* No more room - ignore */
17415 				ip1dbg((
17416 				    "ip_rput_local_options: end of RR\n"));
17417 				break;
17418 			}
17419 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17420 			    IP_ADDR_LEN);
17421 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17422 			break;
17423 		case IPOPT_TS:
17424 			/* Insert timestamp if there is romm */
17425 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17426 			case IPOPT_TS_TSONLY:
17427 				off = IPOPT_TS_TIMELEN;
17428 				break;
17429 			case IPOPT_TS_PRESPEC:
17430 			case IPOPT_TS_PRESPEC_RFC791:
17431 				/* Verify that the address matched */
17432 				off = opt[IPOPT_OFFSET] - 1;
17433 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17434 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17435 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17436 				if (dst_ire == NULL) {
17437 					/* Not for us */
17438 					break;
17439 				}
17440 				ire_refrele(dst_ire);
17441 				/* FALLTHRU */
17442 			case IPOPT_TS_TSANDADDR:
17443 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17444 				break;
17445 			default:
17446 				/*
17447 				 * ip_*put_options should have already
17448 				 * dropped this packet.
17449 				 */
17450 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17451 				    "unknown IT - bug in ip_rput_options?\n");
17452 				return (B_TRUE);	/* Keep "lint" happy */
17453 			}
17454 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17455 				/* Increase overflow counter */
17456 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17457 				opt[IPOPT_POS_OV_FLG] =
17458 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17459 				    (off << 4));
17460 				break;
17461 			}
17462 			off = opt[IPOPT_OFFSET] - 1;
17463 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17464 			case IPOPT_TS_PRESPEC:
17465 			case IPOPT_TS_PRESPEC_RFC791:
17466 			case IPOPT_TS_TSANDADDR:
17467 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17468 				    IP_ADDR_LEN);
17469 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17470 				/* FALLTHRU */
17471 			case IPOPT_TS_TSONLY:
17472 				off = opt[IPOPT_OFFSET] - 1;
17473 				/* Compute # of milliseconds since midnight */
17474 				gethrestime(&now);
17475 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17476 				    now.tv_nsec / (NANOSEC / MILLISEC);
17477 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17478 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17479 				break;
17480 			}
17481 			break;
17482 		}
17483 	}
17484 	return (B_TRUE);
17485 
17486 bad_src_route:
17487 	q = WR(q);
17488 	if (q->q_next != NULL)
17489 		ill = q->q_ptr;
17490 	else
17491 		ill = NULL;
17492 
17493 	/* make sure we clear any indication of a hardware checksum */
17494 	DB_CKSUMFLAGS(mp) = 0;
17495 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill);
17496 	if (zoneid == ALL_ZONES)
17497 		freemsg(mp);
17498 	else
17499 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17500 	return (B_FALSE);
17501 
17502 }
17503 
17504 /*
17505  * Process IP options in an inbound packet.  If an option affects the
17506  * effective destination address, return the next hop address via dstp.
17507  * Returns -1 if something fails in which case an ICMP error has been sent
17508  * and mp freed.
17509  */
17510 static int
17511 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17512 {
17513 	ipoptp_t	opts;
17514 	uchar_t		*opt;
17515 	uint8_t		optval;
17516 	uint8_t		optlen;
17517 	ipaddr_t	dst;
17518 	intptr_t	code = 0;
17519 	ire_t		*ire = NULL;
17520 	zoneid_t	zoneid;
17521 	ill_t		*ill;
17522 
17523 	ip2dbg(("ip_rput_options\n"));
17524 	dst = ipha->ipha_dst;
17525 	for (optval = ipoptp_first(&opts, ipha);
17526 	    optval != IPOPT_EOL;
17527 	    optval = ipoptp_next(&opts)) {
17528 		opt = opts.ipoptp_cur;
17529 		optlen = opts.ipoptp_len;
17530 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17531 		    optval, optlen));
17532 		/*
17533 		 * Note: we need to verify the checksum before we
17534 		 * modify anything thus this routine only extracts the next
17535 		 * hop dst from any source route.
17536 		 */
17537 		switch (optval) {
17538 			uint32_t off;
17539 		case IPOPT_SSRR:
17540 		case IPOPT_LSRR:
17541 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17542 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17543 			if (ire == NULL) {
17544 				if (optval == IPOPT_SSRR) {
17545 					ip1dbg(("ip_rput_options: not next"
17546 					    " strict source route 0x%x\n",
17547 					    ntohl(dst)));
17548 					code = (char *)&ipha->ipha_dst -
17549 					    (char *)ipha;
17550 					goto param_prob; /* RouterReq's */
17551 				}
17552 				ip2dbg(("ip_rput_options: "
17553 				    "not next source route 0x%x\n",
17554 				    ntohl(dst)));
17555 				break;
17556 			}
17557 			ire_refrele(ire);
17558 
17559 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17560 				ip1dbg((
17561 				    "ip_rput_options: bad option offset\n"));
17562 				code = (char *)&opt[IPOPT_OLEN] -
17563 				    (char *)ipha;
17564 				goto param_prob;
17565 			}
17566 			off = opt[IPOPT_OFFSET];
17567 			off--;
17568 		redo_srr:
17569 			if (optlen < IP_ADDR_LEN ||
17570 			    off > optlen - IP_ADDR_LEN) {
17571 				/* End of source route */
17572 				ip1dbg(("ip_rput_options: end of SR\n"));
17573 				break;
17574 			}
17575 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17576 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17577 			    ntohl(dst)));
17578 
17579 			/*
17580 			 * Check if our address is present more than
17581 			 * once as consecutive hops in source route.
17582 			 * XXX verify per-interface ip_forwarding
17583 			 * for source route?
17584 			 */
17585 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17586 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17587 
17588 			if (ire != NULL) {
17589 				ire_refrele(ire);
17590 				off += IP_ADDR_LEN;
17591 				goto redo_srr;
17592 			}
17593 
17594 			if (dst == htonl(INADDR_LOOPBACK)) {
17595 				ip1dbg(("ip_rput_options: loopback addr in "
17596 				    "source route!\n"));
17597 				goto bad_src_route;
17598 			}
17599 			/*
17600 			 * For strict: verify that dst is directly
17601 			 * reachable.
17602 			 */
17603 			if (optval == IPOPT_SSRR) {
17604 				ire = ire_ftable_lookup(dst, 0, 0,
17605 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17606 				    MBLK_GETLABEL(mp),
17607 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17608 				if (ire == NULL) {
17609 					ip1dbg(("ip_rput_options: SSRR not "
17610 					    "directly reachable: 0x%x\n",
17611 					    ntohl(dst)));
17612 					goto bad_src_route;
17613 				}
17614 				ire_refrele(ire);
17615 			}
17616 			/*
17617 			 * Defer update of the offset and the record route
17618 			 * until the packet is forwarded.
17619 			 */
17620 			break;
17621 		case IPOPT_RR:
17622 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17623 				ip1dbg((
17624 				    "ip_rput_options: bad option offset\n"));
17625 				code = (char *)&opt[IPOPT_OLEN] -
17626 				    (char *)ipha;
17627 				goto param_prob;
17628 			}
17629 			break;
17630 		case IPOPT_TS:
17631 			/*
17632 			 * Verify that length >= 5 and that there is either
17633 			 * room for another timestamp or that the overflow
17634 			 * counter is not maxed out.
17635 			 */
17636 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17637 			if (optlen < IPOPT_MINLEN_IT) {
17638 				goto param_prob;
17639 			}
17640 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17641 				ip1dbg((
17642 				    "ip_rput_options: bad option offset\n"));
17643 				code = (char *)&opt[IPOPT_OFFSET] -
17644 				    (char *)ipha;
17645 				goto param_prob;
17646 			}
17647 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17648 			case IPOPT_TS_TSONLY:
17649 				off = IPOPT_TS_TIMELEN;
17650 				break;
17651 			case IPOPT_TS_TSANDADDR:
17652 			case IPOPT_TS_PRESPEC:
17653 			case IPOPT_TS_PRESPEC_RFC791:
17654 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17655 				break;
17656 			default:
17657 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17658 				    (char *)ipha;
17659 				goto param_prob;
17660 			}
17661 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17662 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17663 				/*
17664 				 * No room and the overflow counter is 15
17665 				 * already.
17666 				 */
17667 				goto param_prob;
17668 			}
17669 			break;
17670 		}
17671 	}
17672 
17673 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17674 		*dstp = dst;
17675 		return (0);
17676 	}
17677 
17678 	ip1dbg(("ip_rput_options: error processing IP options."));
17679 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17680 
17681 param_prob:
17682 	q = WR(q);
17683 	if (q->q_next != NULL)
17684 		ill = q->q_ptr;
17685 	else
17686 		ill = NULL;
17687 
17688 	/* make sure we clear any indication of a hardware checksum */
17689 	DB_CKSUMFLAGS(mp) = 0;
17690 	/* Don't know whether this is for non-global or global/forwarding */
17691 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17692 	if (zoneid == ALL_ZONES)
17693 		freemsg(mp);
17694 	else
17695 		icmp_param_problem(q, mp, (uint8_t)code, zoneid);
17696 	return (-1);
17697 
17698 bad_src_route:
17699 	q = WR(q);
17700 	if (q->q_next != NULL)
17701 		ill = q->q_ptr;
17702 	else
17703 		ill = NULL;
17704 
17705 	/* make sure we clear any indication of a hardware checksum */
17706 	DB_CKSUMFLAGS(mp) = 0;
17707 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17708 	if (zoneid == ALL_ZONES)
17709 		freemsg(mp);
17710 	else
17711 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17712 	return (-1);
17713 }
17714 
17715 /*
17716  * IP & ICMP info in >=14 msg's ...
17717  *  - ip fixed part (mib2_ip_t)
17718  *  - icmp fixed part (mib2_icmp_t)
17719  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17720  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17721  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
17722  *  - ipRouteAttributeTable (ip 102)	labeled routes
17723  *  - ip multicast membership (ip_member_t)
17724  *  - ip multicast source filtering (ip_grpsrc_t)
17725  *  - igmp fixed part (struct igmpstat)
17726  *  - multicast routing stats (struct mrtstat)
17727  *  - multicast routing vifs (array of struct vifctl)
17728  *  - multicast routing routes (array of struct mfcctl)
17729  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17730  *					One per ill plus one generic
17731  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17732  *					One per ill plus one generic
17733  *  - ipv6RouteEntry			all IPv6 IREs
17734  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17735  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17736  *  - ipv6AddrEntry			all IPv6 ipifs
17737  *  - ipv6 multicast membership (ipv6_member_t)
17738  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17739  *
17740  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
17741  * already present.
17742  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17743  * already filled in by the caller.
17744  * Return value of 0 indicates that no messages were sent and caller
17745  * should free mpctl.
17746  */
17747 int
17748 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17749 {
17750 
17751 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17752 		return (0);
17753 	}
17754 
17755 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
17756 		return (1);
17757 	}
17758 
17759 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17760 		return (1);
17761 	}
17762 
17763 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17764 		return (1);
17765 	}
17766 
17767 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17768 		return (1);
17769 	}
17770 
17771 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17772 		return (1);
17773 	}
17774 
17775 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17776 		return (1);
17777 	}
17778 
17779 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17780 		return (1);
17781 	}
17782 
17783 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17784 		return (1);
17785 	}
17786 
17787 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17788 		return (1);
17789 	}
17790 
17791 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17792 		return (1);
17793 	}
17794 
17795 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17796 		return (1);
17797 	}
17798 
17799 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17800 		return (1);
17801 	}
17802 
17803 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17804 		return (1);
17805 	}
17806 
17807 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17808 		return (1);
17809 	}
17810 
17811 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17812 		return (1);
17813 	}
17814 
17815 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17816 		return (1);
17817 	}
17818 
17819 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17820 		return (1);
17821 	}
17822 	freemsg(mpctl);
17823 	return (1);
17824 }
17825 
17826 
17827 /* Get global IPv4 statistics */
17828 static mblk_t *
17829 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
17830 {
17831 	struct opthdr		*optp;
17832 	mblk_t			*mp2ctl;
17833 
17834 	/*
17835 	 * make a copy of the original message
17836 	 */
17837 	mp2ctl = copymsg(mpctl);
17838 
17839 	/* fixed length IP structure... */
17840 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17841 	optp->level = MIB2_IP;
17842 	optp->name = 0;
17843 	SET_MIB(ip_mib.ipForwarding,
17844 	    (WE_ARE_FORWARDING ? 1 : 2));
17845 	SET_MIB(ip_mib.ipDefaultTTL,
17846 	    (uint32_t)ip_def_ttl);
17847 	SET_MIB(ip_mib.ipReasmTimeout,
17848 	    ip_g_frag_timeout);
17849 	SET_MIB(ip_mib.ipAddrEntrySize,
17850 	    sizeof (mib2_ipAddrEntry_t));
17851 	SET_MIB(ip_mib.ipRouteEntrySize,
17852 	    sizeof (mib2_ipRouteEntry_t));
17853 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
17854 	    sizeof (mib2_ipNetToMediaEntry_t));
17855 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17856 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17857 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
17858 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17859 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
17860 	    (int)sizeof (ip_mib))) {
17861 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17862 		    (uint_t)sizeof (ip_mib)));
17863 	}
17864 
17865 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17866 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17867 	    (int)optp->level, (int)optp->name, (int)optp->len));
17868 	qreply(q, mpctl);
17869 	return (mp2ctl);
17870 }
17871 
17872 /* Global IPv4 ICMP statistics */
17873 static mblk_t *
17874 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
17875 {
17876 	struct opthdr		*optp;
17877 	mblk_t			*mp2ctl;
17878 
17879 	/*
17880 	 * Make a copy of the original message
17881 	 */
17882 	mp2ctl = copymsg(mpctl);
17883 
17884 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17885 	optp->level = MIB2_ICMP;
17886 	optp->name = 0;
17887 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17888 	    (int)sizeof (icmp_mib))) {
17889 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17890 		    (uint_t)sizeof (icmp_mib)));
17891 	}
17892 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17893 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17894 	    (int)optp->level, (int)optp->name, (int)optp->len));
17895 	qreply(q, mpctl);
17896 	return (mp2ctl);
17897 }
17898 
17899 /* Global IPv4 IGMP statistics */
17900 static mblk_t *
17901 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17902 {
17903 	struct opthdr		*optp;
17904 	mblk_t			*mp2ctl;
17905 
17906 	/*
17907 	 * make a copy of the original message
17908 	 */
17909 	mp2ctl = copymsg(mpctl);
17910 
17911 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17912 	optp->level = EXPER_IGMP;
17913 	optp->name = 0;
17914 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17915 	    (int)sizeof (igmpstat))) {
17916 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17917 		    (uint_t)sizeof (igmpstat)));
17918 	}
17919 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17920 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17921 	    (int)optp->level, (int)optp->name, (int)optp->len));
17922 	qreply(q, mpctl);
17923 	return (mp2ctl);
17924 }
17925 
17926 /* Global IPv4 Multicast Routing statistics */
17927 static mblk_t *
17928 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17929 {
17930 	struct opthdr		*optp;
17931 	mblk_t			*mp2ctl;
17932 
17933 	/*
17934 	 * make a copy of the original message
17935 	 */
17936 	mp2ctl = copymsg(mpctl);
17937 
17938 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17939 	optp->level = EXPER_DVMRP;
17940 	optp->name = 0;
17941 	if (!ip_mroute_stats(mpctl->b_cont)) {
17942 		ip0dbg(("ip_mroute_stats: failed\n"));
17943 	}
17944 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17945 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17946 	    (int)optp->level, (int)optp->name, (int)optp->len));
17947 	qreply(q, mpctl);
17948 	return (mp2ctl);
17949 }
17950 
17951 /* IPv4 address information */
17952 static mblk_t *
17953 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17954 {
17955 	struct opthdr		*optp;
17956 	mblk_t			*mp2ctl;
17957 	mblk_t			*mp_tail = NULL;
17958 	ill_t			*ill;
17959 	ipif_t			*ipif;
17960 	uint_t			bitval;
17961 	mib2_ipAddrEntry_t	mae;
17962 	zoneid_t		zoneid;
17963 	ill_walk_context_t ctx;
17964 
17965 	/*
17966 	 * make a copy of the original message
17967 	 */
17968 	mp2ctl = copymsg(mpctl);
17969 
17970 	/* ipAddrEntryTable */
17971 
17972 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17973 	optp->level = MIB2_IP;
17974 	optp->name = MIB2_IP_ADDR;
17975 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17976 
17977 	rw_enter(&ill_g_lock, RW_READER);
17978 	ill = ILL_START_WALK_V4(&ctx);
17979 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17980 		for (ipif = ill->ill_ipif; ipif != NULL;
17981 		    ipif = ipif->ipif_next) {
17982 			if (ipif->ipif_zoneid != zoneid &&
17983 			    ipif->ipif_zoneid != ALL_ZONES)
17984 				continue;
17985 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17986 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17987 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17988 
17989 			(void) ipif_get_name(ipif,
17990 			    mae.ipAdEntIfIndex.o_bytes,
17991 			    OCTET_LENGTH);
17992 			mae.ipAdEntIfIndex.o_length =
17993 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
17994 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
17995 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
17996 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
17997 			mae.ipAdEntInfo.ae_subnet_len =
17998 			    ip_mask_to_plen(ipif->ipif_net_mask);
17999 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18000 			for (bitval = 1;
18001 			    bitval &&
18002 			    !(bitval & ipif->ipif_brd_addr);
18003 			    bitval <<= 1)
18004 				noop;
18005 			mae.ipAdEntBcastAddr = bitval;
18006 			mae.ipAdEntReasmMaxSize = 65535;
18007 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18008 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18009 			mae.ipAdEntInfo.ae_broadcast_addr =
18010 			    ipif->ipif_brd_addr;
18011 			mae.ipAdEntInfo.ae_pp_dst_addr =
18012 			    ipif->ipif_pp_dst_addr;
18013 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18014 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18015 
18016 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18017 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18018 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18019 				    "allocate %u bytes\n",
18020 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18021 			}
18022 		}
18023 	}
18024 	rw_exit(&ill_g_lock);
18025 
18026 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18027 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18028 	    (int)optp->level, (int)optp->name, (int)optp->len));
18029 	qreply(q, mpctl);
18030 	return (mp2ctl);
18031 }
18032 
18033 /* IPv6 address information */
18034 static mblk_t *
18035 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
18036 {
18037 	struct opthdr		*optp;
18038 	mblk_t			*mp2ctl;
18039 	mblk_t			*mp_tail = NULL;
18040 	ill_t			*ill;
18041 	ipif_t			*ipif;
18042 	mib2_ipv6AddrEntry_t	mae6;
18043 	zoneid_t		zoneid;
18044 	ill_walk_context_t	ctx;
18045 
18046 	/*
18047 	 * make a copy of the original message
18048 	 */
18049 	mp2ctl = copymsg(mpctl);
18050 
18051 	/* ipv6AddrEntryTable */
18052 
18053 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18054 	optp->level = MIB2_IP6;
18055 	optp->name = MIB2_IP6_ADDR;
18056 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18057 
18058 	rw_enter(&ill_g_lock, RW_READER);
18059 	ill = ILL_START_WALK_V6(&ctx);
18060 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18061 		for (ipif = ill->ill_ipif; ipif != NULL;
18062 		    ipif = ipif->ipif_next) {
18063 			if (ipif->ipif_zoneid != zoneid &&
18064 			    ipif->ipif_zoneid != ALL_ZONES)
18065 				continue;
18066 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18067 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18068 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18069 
18070 			(void) ipif_get_name(ipif,
18071 			    mae6.ipv6AddrIfIndex.o_bytes,
18072 			    OCTET_LENGTH);
18073 			mae6.ipv6AddrIfIndex.o_length =
18074 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18075 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18076 			mae6.ipv6AddrPfxLength =
18077 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18078 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18079 			mae6.ipv6AddrInfo.ae_subnet_len =
18080 			    mae6.ipv6AddrPfxLength;
18081 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18082 
18083 			/* Type: stateless(1), stateful(2), unknown(3) */
18084 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18085 				mae6.ipv6AddrType = 1;
18086 			else
18087 				mae6.ipv6AddrType = 2;
18088 			/* Anycast: true(1), false(2) */
18089 			if (ipif->ipif_flags & IPIF_ANYCAST)
18090 				mae6.ipv6AddrAnycastFlag = 1;
18091 			else
18092 				mae6.ipv6AddrAnycastFlag = 2;
18093 
18094 			/*
18095 			 * Address status: preferred(1), deprecated(2),
18096 			 * invalid(3), inaccessible(4), unknown(5)
18097 			 */
18098 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18099 				mae6.ipv6AddrStatus = 3;
18100 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18101 				mae6.ipv6AddrStatus = 2;
18102 			else
18103 				mae6.ipv6AddrStatus = 1;
18104 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18105 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18106 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18107 						ipif->ipif_v6pp_dst_addr;
18108 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18109 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18110 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18111 				(char *)&mae6,
18112 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18113 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18114 				    "allocate %u bytes\n",
18115 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18116 			}
18117 		}
18118 	}
18119 	rw_exit(&ill_g_lock);
18120 
18121 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18122 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18123 	    (int)optp->level, (int)optp->name, (int)optp->len));
18124 	qreply(q, mpctl);
18125 	return (mp2ctl);
18126 }
18127 
18128 /* IPv4 multicast group membership. */
18129 static mblk_t *
18130 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
18131 {
18132 	struct opthdr		*optp;
18133 	mblk_t			*mp2ctl;
18134 	ill_t			*ill;
18135 	ipif_t			*ipif;
18136 	ilm_t			*ilm;
18137 	ip_member_t		ipm;
18138 	mblk_t			*mp_tail = NULL;
18139 	ill_walk_context_t	ctx;
18140 	zoneid_t		zoneid;
18141 
18142 	/*
18143 	 * make a copy of the original message
18144 	 */
18145 	mp2ctl = copymsg(mpctl);
18146 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18147 
18148 	/* ipGroupMember table */
18149 	optp = (struct opthdr *)&mpctl->b_rptr[
18150 	    sizeof (struct T_optmgmt_ack)];
18151 	optp->level = MIB2_IP;
18152 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18153 
18154 	rw_enter(&ill_g_lock, RW_READER);
18155 	ill = ILL_START_WALK_V4(&ctx);
18156 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18157 		ILM_WALKER_HOLD(ill);
18158 		for (ipif = ill->ill_ipif; ipif != NULL;
18159 		    ipif = ipif->ipif_next) {
18160 			if (ipif->ipif_zoneid != zoneid &&
18161 			    ipif->ipif_zoneid != ALL_ZONES)
18162 				continue;	/* not this zone */
18163 			(void) ipif_get_name(ipif,
18164 			    ipm.ipGroupMemberIfIndex.o_bytes,
18165 			    OCTET_LENGTH);
18166 			ipm.ipGroupMemberIfIndex.o_length =
18167 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18168 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18169 				ASSERT(ilm->ilm_ipif != NULL);
18170 				ASSERT(ilm->ilm_ill == NULL);
18171 				if (ilm->ilm_ipif != ipif)
18172 					continue;
18173 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18174 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18175 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18176 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18177 				    (char *)&ipm, (int)sizeof (ipm))) {
18178 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18179 					    "failed to allocate %u bytes\n",
18180 						(uint_t)sizeof (ipm)));
18181 				}
18182 			}
18183 		}
18184 		ILM_WALKER_RELE(ill);
18185 	}
18186 	rw_exit(&ill_g_lock);
18187 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18188 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18189 	    (int)optp->level, (int)optp->name, (int)optp->len));
18190 	qreply(q, mpctl);
18191 	return (mp2ctl);
18192 }
18193 
18194 /* IPv6 multicast group membership. */
18195 static mblk_t *
18196 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
18197 {
18198 	struct opthdr		*optp;
18199 	mblk_t			*mp2ctl;
18200 	ill_t			*ill;
18201 	ilm_t			*ilm;
18202 	ipv6_member_t		ipm6;
18203 	mblk_t			*mp_tail = NULL;
18204 	ill_walk_context_t	ctx;
18205 	zoneid_t		zoneid;
18206 
18207 	/*
18208 	 * make a copy of the original message
18209 	 */
18210 	mp2ctl = copymsg(mpctl);
18211 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18212 
18213 	/* ip6GroupMember table */
18214 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18215 	optp->level = MIB2_IP6;
18216 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18217 
18218 	rw_enter(&ill_g_lock, RW_READER);
18219 	ill = ILL_START_WALK_V6(&ctx);
18220 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18221 		ILM_WALKER_HOLD(ill);
18222 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18223 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18224 			ASSERT(ilm->ilm_ipif == NULL);
18225 			ASSERT(ilm->ilm_ill != NULL);
18226 			if (ilm->ilm_zoneid != zoneid)
18227 				continue;	/* not this zone */
18228 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18229 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18230 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18231 			if (!snmp_append_data2(mpctl->b_cont,
18232 			    &mp_tail,
18233 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18234 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18235 				    "failed to allocate %u bytes\n",
18236 				    (uint_t)sizeof (ipm6)));
18237 			}
18238 		}
18239 		ILM_WALKER_RELE(ill);
18240 	}
18241 	rw_exit(&ill_g_lock);
18242 
18243 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18244 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18245 	    (int)optp->level, (int)optp->name, (int)optp->len));
18246 	qreply(q, mpctl);
18247 	return (mp2ctl);
18248 }
18249 
18250 /* IP multicast filtered sources */
18251 static mblk_t *
18252 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
18253 {
18254 	struct opthdr		*optp;
18255 	mblk_t			*mp2ctl;
18256 	ill_t			*ill;
18257 	ipif_t			*ipif;
18258 	ilm_t			*ilm;
18259 	ip_grpsrc_t		ips;
18260 	mblk_t			*mp_tail = NULL;
18261 	ill_walk_context_t	ctx;
18262 	zoneid_t		zoneid;
18263 	int			i;
18264 	slist_t			*sl;
18265 
18266 	/*
18267 	 * make a copy of the original message
18268 	 */
18269 	mp2ctl = copymsg(mpctl);
18270 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18271 
18272 	/* ipGroupSource table */
18273 	optp = (struct opthdr *)&mpctl->b_rptr[
18274 	    sizeof (struct T_optmgmt_ack)];
18275 	optp->level = MIB2_IP;
18276 	optp->name = EXPER_IP_GROUP_SOURCES;
18277 
18278 	rw_enter(&ill_g_lock, RW_READER);
18279 	ill = ILL_START_WALK_V4(&ctx);
18280 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18281 		ILM_WALKER_HOLD(ill);
18282 		for (ipif = ill->ill_ipif; ipif != NULL;
18283 		    ipif = ipif->ipif_next) {
18284 			if (ipif->ipif_zoneid != zoneid)
18285 				continue;	/* not this zone */
18286 			(void) ipif_get_name(ipif,
18287 			    ips.ipGroupSourceIfIndex.o_bytes,
18288 			    OCTET_LENGTH);
18289 			ips.ipGroupSourceIfIndex.o_length =
18290 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18291 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18292 				ASSERT(ilm->ilm_ipif != NULL);
18293 				ASSERT(ilm->ilm_ill == NULL);
18294 				sl = ilm->ilm_filter;
18295 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18296 					continue;
18297 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18298 				for (i = 0; i < sl->sl_numsrc; i++) {
18299 					if (!IN6_IS_ADDR_V4MAPPED(
18300 					    &sl->sl_addr[i]))
18301 						continue;
18302 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18303 					    ips.ipGroupSourceAddress);
18304 					if (snmp_append_data2(mpctl->b_cont,
18305 					    &mp_tail, (char *)&ips,
18306 					    (int)sizeof (ips)) == 0) {
18307 						ip1dbg(("ip_snmp_get_mib2_"
18308 						    "ip_group_src: failed to "
18309 						    "allocate %u bytes\n",
18310 						    (uint_t)sizeof (ips)));
18311 					}
18312 				}
18313 			}
18314 		}
18315 		ILM_WALKER_RELE(ill);
18316 	}
18317 	rw_exit(&ill_g_lock);
18318 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18319 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18320 	    (int)optp->level, (int)optp->name, (int)optp->len));
18321 	qreply(q, mpctl);
18322 	return (mp2ctl);
18323 }
18324 
18325 /* IPv6 multicast filtered sources. */
18326 static mblk_t *
18327 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18328 {
18329 	struct opthdr		*optp;
18330 	mblk_t			*mp2ctl;
18331 	ill_t			*ill;
18332 	ilm_t			*ilm;
18333 	ipv6_grpsrc_t		ips6;
18334 	mblk_t			*mp_tail = NULL;
18335 	ill_walk_context_t	ctx;
18336 	zoneid_t		zoneid;
18337 	int			i;
18338 	slist_t			*sl;
18339 
18340 	/*
18341 	 * make a copy of the original message
18342 	 */
18343 	mp2ctl = copymsg(mpctl);
18344 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18345 
18346 	/* ip6GroupMember table */
18347 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18348 	optp->level = MIB2_IP6;
18349 	optp->name = EXPER_IP6_GROUP_SOURCES;
18350 
18351 	rw_enter(&ill_g_lock, RW_READER);
18352 	ill = ILL_START_WALK_V6(&ctx);
18353 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18354 		ILM_WALKER_HOLD(ill);
18355 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18356 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18357 			ASSERT(ilm->ilm_ipif == NULL);
18358 			ASSERT(ilm->ilm_ill != NULL);
18359 			sl = ilm->ilm_filter;
18360 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18361 				continue;
18362 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18363 			for (i = 0; i < sl->sl_numsrc; i++) {
18364 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18365 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18366 				    (char *)&ips6, (int)sizeof (ips6))) {
18367 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18368 					    "group_src: failed to allocate "
18369 					    "%u bytes\n",
18370 					    (uint_t)sizeof (ips6)));
18371 				}
18372 			}
18373 		}
18374 		ILM_WALKER_RELE(ill);
18375 	}
18376 	rw_exit(&ill_g_lock);
18377 
18378 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18379 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18380 	    (int)optp->level, (int)optp->name, (int)optp->len));
18381 	qreply(q, mpctl);
18382 	return (mp2ctl);
18383 }
18384 
18385 /* Multicast routing virtual interface table. */
18386 static mblk_t *
18387 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18388 {
18389 	struct opthdr		*optp;
18390 	mblk_t			*mp2ctl;
18391 
18392 	/*
18393 	 * make a copy of the original message
18394 	 */
18395 	mp2ctl = copymsg(mpctl);
18396 
18397 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18398 	optp->level = EXPER_DVMRP;
18399 	optp->name = EXPER_DVMRP_VIF;
18400 	if (!ip_mroute_vif(mpctl->b_cont)) {
18401 		ip0dbg(("ip_mroute_vif: failed\n"));
18402 	}
18403 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18404 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18405 	    (int)optp->level, (int)optp->name, (int)optp->len));
18406 	qreply(q, mpctl);
18407 	return (mp2ctl);
18408 }
18409 
18410 /* Multicast routing table. */
18411 static mblk_t *
18412 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18413 {
18414 	struct opthdr		*optp;
18415 	mblk_t			*mp2ctl;
18416 
18417 	/*
18418 	 * make a copy of the original message
18419 	 */
18420 	mp2ctl = copymsg(mpctl);
18421 
18422 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18423 	optp->level = EXPER_DVMRP;
18424 	optp->name = EXPER_DVMRP_MRT;
18425 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18426 		ip0dbg(("ip_mroute_mrt: failed\n"));
18427 	}
18428 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18429 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18430 	    (int)optp->level, (int)optp->name, (int)optp->len));
18431 	qreply(q, mpctl);
18432 	return (mp2ctl);
18433 }
18434 
18435 /*
18436  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18437  * in one IRE walk.
18438  */
18439 static mblk_t *
18440 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18441 {
18442 	struct opthdr	*optp;
18443 	mblk_t		*mp2ctl;	/* Returned */
18444 	mblk_t		*mp3ctl;	/* nettomedia */
18445 	mblk_t		*mp4ctl;	/* routeattrs */
18446 	iproutedata_t	ird;
18447 	zoneid_t	zoneid;
18448 
18449 	/*
18450 	 * make copies of the original message
18451 	 *	- mp2ctl is returned unchanged to the caller for his use
18452 	 *	- mpctl is sent upstream as ipRouteEntryTable
18453 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18454 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18455 	 */
18456 	mp2ctl = copymsg(mpctl);
18457 	mp3ctl = copymsg(mpctl);
18458 	mp4ctl = copymsg(mpctl);
18459 	if (mp3ctl == NULL || mp4ctl == NULL) {
18460 		freemsg(mp4ctl);
18461 		freemsg(mp3ctl);
18462 		freemsg(mp2ctl);
18463 		freemsg(mpctl);
18464 		return (NULL);
18465 	}
18466 
18467 	bzero(&ird, sizeof (ird));
18468 
18469 	ird.ird_route.lp_head = mpctl->b_cont;
18470 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18471 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18472 
18473 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18474 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18475 	if (zoneid == GLOBAL_ZONEID) {
18476 		/*
18477 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18478 		 * the sys_net_config privilege, it can only run in the global
18479 		 * zone, so we don't display these IREs in the other zones.
18480 		 */
18481 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18482 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18483 	}
18484 
18485 	/* ipRouteEntryTable in mpctl */
18486 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18487 	optp->level = MIB2_IP;
18488 	optp->name = MIB2_IP_ROUTE;
18489 	optp->len = msgdsize(ird.ird_route.lp_head);
18490 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18491 	    (int)optp->level, (int)optp->name, (int)optp->len));
18492 	qreply(q, mpctl);
18493 
18494 	/* ipNetToMediaEntryTable in mp3ctl */
18495 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18496 	optp->level = MIB2_IP;
18497 	optp->name = MIB2_IP_MEDIA;
18498 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18499 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18500 	    (int)optp->level, (int)optp->name, (int)optp->len));
18501 	qreply(q, mp3ctl);
18502 
18503 	/* ipRouteAttributeTable in mp4ctl */
18504 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18505 	optp->level = MIB2_IP;
18506 	optp->name = EXPER_IP_RTATTR;
18507 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18508 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18509 	    (int)optp->level, (int)optp->name, (int)optp->len));
18510 	if (optp->len == 0)
18511 		freemsg(mp4ctl);
18512 	else
18513 		qreply(q, mp4ctl);
18514 
18515 	return (mp2ctl);
18516 }
18517 
18518 /*
18519  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18520  * ipv6NetToMediaEntryTable in an NDP walk.
18521  */
18522 static mblk_t *
18523 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18524 {
18525 	struct opthdr	*optp;
18526 	mblk_t		*mp2ctl;	/* Returned */
18527 	mblk_t		*mp3ctl;	/* nettomedia */
18528 	mblk_t		*mp4ctl;	/* routeattrs */
18529 	iproutedata_t	ird;
18530 	zoneid_t	zoneid;
18531 
18532 	/*
18533 	 * make copies of the original message
18534 	 *	- mp2ctl is returned unchanged to the caller for his use
18535 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18536 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18537 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18538 	 */
18539 	mp2ctl = copymsg(mpctl);
18540 	mp3ctl = copymsg(mpctl);
18541 	mp4ctl = copymsg(mpctl);
18542 	if (mp3ctl == NULL || mp4ctl == NULL) {
18543 		freemsg(mp4ctl);
18544 		freemsg(mp3ctl);
18545 		freemsg(mp2ctl);
18546 		freemsg(mpctl);
18547 		return (NULL);
18548 	}
18549 
18550 	bzero(&ird, sizeof (ird));
18551 
18552 	ird.ird_route.lp_head = mpctl->b_cont;
18553 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18554 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18555 
18556 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18557 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18558 
18559 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18560 	optp->level = MIB2_IP6;
18561 	optp->name = MIB2_IP6_ROUTE;
18562 	optp->len = msgdsize(ird.ird_route.lp_head);
18563 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18564 	    (int)optp->level, (int)optp->name, (int)optp->len));
18565 	qreply(q, mpctl);
18566 
18567 	/* ipv6NetToMediaEntryTable in mp3ctl */
18568 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18569 
18570 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18571 	optp->level = MIB2_IP6;
18572 	optp->name = MIB2_IP6_MEDIA;
18573 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18574 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18575 	    (int)optp->level, (int)optp->name, (int)optp->len));
18576 	qreply(q, mp3ctl);
18577 
18578 	/* ipv6RouteAttributeTable in mp4ctl */
18579 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18580 	optp->level = MIB2_IP6;
18581 	optp->name = EXPER_IP_RTATTR;
18582 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18583 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18584 	    (int)optp->level, (int)optp->name, (int)optp->len));
18585 	if (optp->len == 0)
18586 		freemsg(mp4ctl);
18587 	else
18588 		qreply(q, mp4ctl);
18589 
18590 	return (mp2ctl);
18591 }
18592 
18593 /*
18594  * ICMPv6 mib: One per ill
18595  */
18596 static mblk_t *
18597 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18598 {
18599 	struct opthdr		*optp;
18600 	mblk_t			*mp2ctl;
18601 	ill_t			*ill;
18602 	ill_walk_context_t	ctx;
18603 	mblk_t			*mp_tail = NULL;
18604 
18605 	/*
18606 	 * Make a copy of the original message
18607 	 */
18608 	mp2ctl = copymsg(mpctl);
18609 
18610 	/* fixed length IPv6 structure ... */
18611 
18612 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18613 	optp->level = MIB2_IP6;
18614 	optp->name = 0;
18615 	/* Include "unknown interface" ip6_mib */
18616 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
18617 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
18618 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
18619 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
18620 	    sizeof (mib2_ipv6IfStatsEntry_t));
18621 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18622 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
18623 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
18624 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18625 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
18626 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18627 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18628 	    (int)sizeof (ip6_mib))) {
18629 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18630 		    (uint_t)sizeof (ip6_mib)));
18631 	}
18632 
18633 	rw_enter(&ill_g_lock, RW_READER);
18634 	ill = ILL_START_WALK_V6(&ctx);
18635 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18636 		ill->ill_ip6_mib->ipv6IfIndex =
18637 		    ill->ill_phyint->phyint_ifindex;
18638 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
18639 		    ipv6_forward ? 1 : 2);
18640 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
18641 		    ill->ill_max_hops);
18642 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
18643 		    sizeof (mib2_ipv6IfStatsEntry_t));
18644 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
18645 		    sizeof (mib2_ipv6AddrEntry_t));
18646 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
18647 		    sizeof (mib2_ipv6RouteEntry_t));
18648 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
18649 		    sizeof (mib2_ipv6NetToMediaEntry_t));
18650 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
18651 		    sizeof (ipv6_member_t));
18652 
18653 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18654 		    (char *)ill->ill_ip6_mib,
18655 		    (int)sizeof (*ill->ill_ip6_mib))) {
18656 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18657 				"%u bytes\n",
18658 				(uint_t)sizeof (*ill->ill_ip6_mib)));
18659 		}
18660 	}
18661 	rw_exit(&ill_g_lock);
18662 
18663 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18664 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18665 	    (int)optp->level, (int)optp->name, (int)optp->len));
18666 	qreply(q, mpctl);
18667 	return (mp2ctl);
18668 }
18669 
18670 /*
18671  * ICMPv6 mib: One per ill
18672  */
18673 static mblk_t *
18674 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18675 {
18676 	struct opthdr		*optp;
18677 	mblk_t			*mp2ctl;
18678 	ill_t			*ill;
18679 	ill_walk_context_t	ctx;
18680 	mblk_t			*mp_tail = NULL;
18681 	/*
18682 	 * Make a copy of the original message
18683 	 */
18684 	mp2ctl = copymsg(mpctl);
18685 
18686 	/* fixed length ICMPv6 structure ... */
18687 
18688 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18689 	optp->level = MIB2_ICMP6;
18690 	optp->name = 0;
18691 	/* Include "unknown interface" icmp6_mib */
18692 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
18693 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18694 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18695 	    (int)sizeof (icmp6_mib))) {
18696 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18697 		    (uint_t)sizeof (icmp6_mib)));
18698 	}
18699 
18700 	rw_enter(&ill_g_lock, RW_READER);
18701 	ill = ILL_START_WALK_V6(&ctx);
18702 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18703 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18704 		    ill->ill_phyint->phyint_ifindex;
18705 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
18706 		    sizeof (mib2_ipv6IfIcmpEntry_t);
18707 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18708 		    (char *)ill->ill_icmp6_mib,
18709 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18710 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18711 			    "%u bytes\n",
18712 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18713 		}
18714 	}
18715 	rw_exit(&ill_g_lock);
18716 
18717 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18718 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18719 	    (int)optp->level, (int)optp->name, (int)optp->len));
18720 	qreply(q, mpctl);
18721 	return (mp2ctl);
18722 }
18723 
18724 /*
18725  * ire_walk routine to create both ipRouteEntryTable and
18726  * ipNetToMediaEntryTable in one IRE walk
18727  */
18728 static void
18729 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18730 {
18731 	ill_t				*ill;
18732 	ipif_t				*ipif;
18733 	mblk_t				*llmp;
18734 	dl_unitdata_req_t		*dlup;
18735 	mib2_ipRouteEntry_t		*re;
18736 	mib2_ipNetToMediaEntry_t	ntme;
18737 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18738 	ipaddr_t			gw_addr;
18739 	tsol_ire_gw_secattr_t		*attrp;
18740 	tsol_gc_t			*gc = NULL;
18741 	tsol_gcgrp_t			*gcgrp = NULL;
18742 	uint_t				sacnt = 0;
18743 	int				i;
18744 
18745 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18746 
18747 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18748 		return;
18749 
18750 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18751 		mutex_enter(&attrp->igsa_lock);
18752 		if ((gc = attrp->igsa_gc) != NULL) {
18753 			gcgrp = gc->gc_grp;
18754 			ASSERT(gcgrp != NULL);
18755 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18756 			sacnt = 1;
18757 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18758 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18759 			gc = gcgrp->gcgrp_head;
18760 			sacnt = gcgrp->gcgrp_count;
18761 		}
18762 		mutex_exit(&attrp->igsa_lock);
18763 
18764 		/* do nothing if there's no gc to report */
18765 		if (gc == NULL) {
18766 			ASSERT(sacnt == 0);
18767 			if (gcgrp != NULL) {
18768 				/* we might as well drop the lock now */
18769 				rw_exit(&gcgrp->gcgrp_rwlock);
18770 				gcgrp = NULL;
18771 			}
18772 			attrp = NULL;
18773 		}
18774 
18775 		ASSERT(gc == NULL || (gcgrp != NULL &&
18776 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18777 	}
18778 	ASSERT(sacnt == 0 || gc != NULL);
18779 
18780 	if (sacnt != 0 &&
18781 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18782 		kmem_free(re, sizeof (*re));
18783 		rw_exit(&gcgrp->gcgrp_rwlock);
18784 		return;
18785 	}
18786 
18787 	/*
18788 	 * Return all IRE types for route table... let caller pick and choose
18789 	 */
18790 	re->ipRouteDest = ire->ire_addr;
18791 	ipif = ire->ire_ipif;
18792 	re->ipRouteIfIndex.o_length = 0;
18793 	if (ire->ire_type == IRE_CACHE) {
18794 		ill = (ill_t *)ire->ire_stq->q_ptr;
18795 		re->ipRouteIfIndex.o_length =
18796 		    ill->ill_name_length == 0 ? 0 :
18797 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18798 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18799 		    re->ipRouteIfIndex.o_length);
18800 	} else if (ipif != NULL) {
18801 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18802 		    OCTET_LENGTH);
18803 		re->ipRouteIfIndex.o_length =
18804 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18805 	}
18806 	re->ipRouteMetric1 = -1;
18807 	re->ipRouteMetric2 = -1;
18808 	re->ipRouteMetric3 = -1;
18809 	re->ipRouteMetric4 = -1;
18810 
18811 	gw_addr = ire->ire_gateway_addr;
18812 
18813 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18814 		re->ipRouteNextHop = ire->ire_src_addr;
18815 	else
18816 		re->ipRouteNextHop = gw_addr;
18817 	/* indirect(4), direct(3), or invalid(2) */
18818 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18819 		re->ipRouteType = 2;
18820 	else
18821 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18822 	re->ipRouteProto = -1;
18823 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18824 	re->ipRouteMask = ire->ire_mask;
18825 	re->ipRouteMetric5 = -1;
18826 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
18827 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
18828 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
18829 	if (ire->ire_nce &&
18830 	    ire->ire_nce->nce_state == ND_REACHABLE)
18831 		llmp = ire->ire_nce->nce_res_mp;
18832 	else
18833 		llmp = NULL;
18834 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
18835 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
18836 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18837 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18838 	re->ipRouteInfo.re_flags	= ire->ire_flags;
18839 	re->ipRouteInfo.re_in_ill.o_length = 0;
18840 
18841 	if (ire->ire_flags & RTF_DYNAMIC) {
18842 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
18843 	} else {
18844 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
18845 	}
18846 
18847 	if (ire->ire_in_ill != NULL) {
18848 		re->ipRouteInfo.re_in_ill.o_length =
18849 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
18850 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
18851 		bcopy(ire->ire_in_ill->ill_name,
18852 		    re->ipRouteInfo.re_in_ill.o_bytes,
18853 		    re->ipRouteInfo.re_in_ill.o_length);
18854 	}
18855 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
18856 
18857 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18858 	    (char *)re, (int)sizeof (*re))) {
18859 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18860 		    (uint_t)sizeof (*re)));
18861 	}
18862 
18863 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18864 		iaeptr->iae_routeidx = ird->ird_idx;
18865 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18866 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18867 	}
18868 
18869 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18870 	    (char *)iae, sacnt * sizeof (*iae))) {
18871 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18872 		    (unsigned)(sacnt * sizeof (*iae))));
18873 	}
18874 
18875 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
18876 		goto done;
18877 	/*
18878 	 * only IRE_CACHE entries that are for a directly connected subnet
18879 	 * get appended to net -> phys addr table
18880 	 * (others in arp)
18881 	 */
18882 	ntme.ipNetToMediaIfIndex.o_length = 0;
18883 	ill = ire_to_ill(ire);
18884 	ASSERT(ill != NULL);
18885 	ntme.ipNetToMediaIfIndex.o_length =
18886 	    ill->ill_name_length == 0 ? 0 :
18887 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18888 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
18889 		    ntme.ipNetToMediaIfIndex.o_length);
18890 
18891 	ntme.ipNetToMediaPhysAddress.o_length = 0;
18892 	if (llmp) {
18893 		uchar_t *addr;
18894 
18895 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
18896 		/* Remove sap from  address */
18897 		if (ill->ill_sap_length < 0)
18898 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
18899 		else
18900 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
18901 			    ill->ill_sap_length;
18902 
18903 		ntme.ipNetToMediaPhysAddress.o_length =
18904 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18905 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18906 		    ntme.ipNetToMediaPhysAddress.o_length);
18907 	}
18908 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18909 	/* assume dynamic (may be changed in arp) */
18910 	ntme.ipNetToMediaType = 3;
18911 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18912 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18913 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18914 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18915 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18916 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18917 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18918 		    (uint_t)sizeof (ntme)));
18919 	}
18920 done:
18921 	/* bump route index for next pass */
18922 	ird->ird_idx++;
18923 
18924 	kmem_free(re, sizeof (*re));
18925 	if (sacnt != 0)
18926 		kmem_free(iae, sacnt * sizeof (*iae));
18927 
18928 	if (gcgrp != NULL)
18929 		rw_exit(&gcgrp->gcgrp_rwlock);
18930 }
18931 
18932 /*
18933  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18934  */
18935 static void
18936 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18937 {
18938 	ill_t				*ill;
18939 	ipif_t				*ipif;
18940 	mib2_ipv6RouteEntry_t		*re;
18941 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18942 	in6_addr_t			gw_addr_v6;
18943 	tsol_ire_gw_secattr_t		*attrp;
18944 	tsol_gc_t			*gc = NULL;
18945 	tsol_gcgrp_t			*gcgrp = NULL;
18946 	uint_t				sacnt = 0;
18947 	int				i;
18948 
18949 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18950 
18951 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18952 		return;
18953 
18954 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18955 		mutex_enter(&attrp->igsa_lock);
18956 		if ((gc = attrp->igsa_gc) != NULL) {
18957 			gcgrp = gc->gc_grp;
18958 			ASSERT(gcgrp != NULL);
18959 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18960 			sacnt = 1;
18961 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18962 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18963 			gc = gcgrp->gcgrp_head;
18964 			sacnt = gcgrp->gcgrp_count;
18965 		}
18966 		mutex_exit(&attrp->igsa_lock);
18967 
18968 		/* do nothing if there's no gc to report */
18969 		if (gc == NULL) {
18970 			ASSERT(sacnt == 0);
18971 			if (gcgrp != NULL) {
18972 				/* we might as well drop the lock now */
18973 				rw_exit(&gcgrp->gcgrp_rwlock);
18974 				gcgrp = NULL;
18975 			}
18976 			attrp = NULL;
18977 		}
18978 
18979 		ASSERT(gc == NULL || (gcgrp != NULL &&
18980 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18981 	}
18982 	ASSERT(sacnt == 0 || gc != NULL);
18983 
18984 	if (sacnt != 0 &&
18985 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18986 		kmem_free(re, sizeof (*re));
18987 		rw_exit(&gcgrp->gcgrp_rwlock);
18988 		return;
18989 	}
18990 
18991 	/*
18992 	 * Return all IRE types for route table... let caller pick and choose
18993 	 */
18994 	re->ipv6RouteDest = ire->ire_addr_v6;
18995 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18996 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18997 	re->ipv6RouteIfIndex.o_length = 0;
18998 	ipif = ire->ire_ipif;
18999 	if (ire->ire_type == IRE_CACHE) {
19000 		ill = (ill_t *)ire->ire_stq->q_ptr;
19001 		re->ipv6RouteIfIndex.o_length =
19002 		    ill->ill_name_length == 0 ? 0 :
19003 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19004 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19005 		    re->ipv6RouteIfIndex.o_length);
19006 	} else if (ipif != NULL) {
19007 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19008 		    OCTET_LENGTH);
19009 		re->ipv6RouteIfIndex.o_length =
19010 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19011 	}
19012 
19013 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19014 
19015 	mutex_enter(&ire->ire_lock);
19016 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19017 	mutex_exit(&ire->ire_lock);
19018 
19019 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19020 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19021 	else
19022 		re->ipv6RouteNextHop = gw_addr_v6;
19023 
19024 	/* remote(4), local(3), or discard(2) */
19025 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19026 		re->ipv6RouteType = 2;
19027 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19028 		re->ipv6RouteType = 3;
19029 	else
19030 		re->ipv6RouteType = 4;
19031 
19032 	re->ipv6RouteProtocol	= -1;
19033 	re->ipv6RoutePolicy	= 0;
19034 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19035 	re->ipv6RouteNextHopRDI	= 0;
19036 	re->ipv6RouteWeight	= 0;
19037 	re->ipv6RouteMetric	= 0;
19038 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19039 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19040 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19041 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19042 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19043 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19044 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19045 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19046 
19047 	if (ire->ire_flags & RTF_DYNAMIC) {
19048 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19049 	} else {
19050 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19051 	}
19052 
19053 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19054 	    (char *)re, (int)sizeof (*re))) {
19055 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19056 		    (uint_t)sizeof (*re)));
19057 	}
19058 
19059 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19060 		iaeptr->iae_routeidx = ird->ird_idx;
19061 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19062 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19063 	}
19064 
19065 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19066 	    (char *)iae, sacnt * sizeof (*iae))) {
19067 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19068 		    (unsigned)(sacnt * sizeof (*iae))));
19069 	}
19070 
19071 	/* bump route index for next pass */
19072 	ird->ird_idx++;
19073 
19074 	kmem_free(re, sizeof (*re));
19075 	if (sacnt != 0)
19076 		kmem_free(iae, sacnt * sizeof (*iae));
19077 
19078 	if (gcgrp != NULL)
19079 		rw_exit(&gcgrp->gcgrp_rwlock);
19080 }
19081 
19082 /*
19083  * ndp_walk routine to create ipv6NetToMediaEntryTable
19084  */
19085 static int
19086 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19087 {
19088 	ill_t				*ill;
19089 	mib2_ipv6NetToMediaEntry_t	ntme;
19090 	dl_unitdata_req_t		*dl;
19091 
19092 	ill = nce->nce_ill;
19093 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19094 		return (0);
19095 
19096 	/*
19097 	 * Neighbor cache entry attached to IRE with on-link
19098 	 * destination.
19099 	 */
19100 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19101 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19102 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19103 	    (nce->nce_res_mp != NULL)) {
19104 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19105 		ntme.ipv6NetToMediaPhysAddress.o_length =
19106 		    dl->dl_dest_addr_length;
19107 	} else {
19108 		ntme.ipv6NetToMediaPhysAddress.o_length =
19109 		    ill->ill_phys_addr_length;
19110 	}
19111 	if (nce->nce_res_mp != NULL) {
19112 		bcopy((char *)nce->nce_res_mp->b_rptr +
19113 		    NCE_LL_ADDR_OFFSET(ill),
19114 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19115 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19116 	} else {
19117 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19118 		    ill->ill_phys_addr_length);
19119 	}
19120 	/*
19121 	 * Note: Returns ND_* states. Should be:
19122 	 * reachable(1), stale(2), delay(3), probe(4),
19123 	 * invalid(5), unknown(6)
19124 	 */
19125 	ntme.ipv6NetToMediaState = nce->nce_state;
19126 	ntme.ipv6NetToMediaLastUpdated = 0;
19127 
19128 	/* other(1), dynamic(2), static(3), local(4) */
19129 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19130 		ntme.ipv6NetToMediaType = 4;
19131 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19132 		ntme.ipv6NetToMediaType = 1;
19133 	} else {
19134 		ntme.ipv6NetToMediaType = 2;
19135 	}
19136 
19137 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19138 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19139 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19140 		    (uint_t)sizeof (ntme)));
19141 	}
19142 	return (0);
19143 }
19144 
19145 /*
19146  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19147  */
19148 /* ARGSUSED */
19149 int
19150 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19151 {
19152 	switch (level) {
19153 	case MIB2_IP:
19154 	case MIB2_ICMP:
19155 		switch (name) {
19156 		default:
19157 			break;
19158 		}
19159 		return (1);
19160 	default:
19161 		return (1);
19162 	}
19163 }
19164 
19165 /*
19166  * Called before the options are updated to check if this packet will
19167  * be source routed from here.
19168  * This routine assumes that the options are well formed i.e. that they
19169  * have already been checked.
19170  */
19171 static boolean_t
19172 ip_source_routed(ipha_t *ipha)
19173 {
19174 	ipoptp_t	opts;
19175 	uchar_t		*opt;
19176 	uint8_t		optval;
19177 	uint8_t		optlen;
19178 	ipaddr_t	dst;
19179 	ire_t		*ire;
19180 
19181 	if (IS_SIMPLE_IPH(ipha)) {
19182 		ip2dbg(("not source routed\n"));
19183 		return (B_FALSE);
19184 	}
19185 	dst = ipha->ipha_dst;
19186 	for (optval = ipoptp_first(&opts, ipha);
19187 	    optval != IPOPT_EOL;
19188 	    optval = ipoptp_next(&opts)) {
19189 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19190 		opt = opts.ipoptp_cur;
19191 		optlen = opts.ipoptp_len;
19192 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19193 		    optval, optlen));
19194 		switch (optval) {
19195 			uint32_t off;
19196 		case IPOPT_SSRR:
19197 		case IPOPT_LSRR:
19198 			/*
19199 			 * If dst is one of our addresses and there are some
19200 			 * entries left in the source route return (true).
19201 			 */
19202 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19203 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
19204 			if (ire == NULL) {
19205 				ip2dbg(("ip_source_routed: not next"
19206 				    " source route 0x%x\n",
19207 				    ntohl(dst)));
19208 				return (B_FALSE);
19209 			}
19210 			ire_refrele(ire);
19211 			off = opt[IPOPT_OFFSET];
19212 			off--;
19213 			if (optlen < IP_ADDR_LEN ||
19214 			    off > optlen - IP_ADDR_LEN) {
19215 				/* End of source route */
19216 				ip1dbg(("ip_source_routed: end of SR\n"));
19217 				return (B_FALSE);
19218 			}
19219 			return (B_TRUE);
19220 		}
19221 	}
19222 	ip2dbg(("not source routed\n"));
19223 	return (B_FALSE);
19224 }
19225 
19226 /*
19227  * Check if the packet contains any source route.
19228  */
19229 static boolean_t
19230 ip_source_route_included(ipha_t *ipha)
19231 {
19232 	ipoptp_t	opts;
19233 	uint8_t		optval;
19234 
19235 	if (IS_SIMPLE_IPH(ipha))
19236 		return (B_FALSE);
19237 	for (optval = ipoptp_first(&opts, ipha);
19238 	    optval != IPOPT_EOL;
19239 	    optval = ipoptp_next(&opts)) {
19240 		switch (optval) {
19241 		case IPOPT_SSRR:
19242 		case IPOPT_LSRR:
19243 			return (B_TRUE);
19244 		}
19245 	}
19246 	return (B_FALSE);
19247 }
19248 
19249 /*
19250  * Called when the IRE expiration timer fires.
19251  */
19252 /* ARGSUSED */
19253 void
19254 ip_trash_timer_expire(void *args)
19255 {
19256 	int	flush_flag = 0;
19257 
19258 	/*
19259 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19260 	 * This lock makes sure that a new invocation of this function
19261 	 * that occurs due to an almost immediate timer firing will not
19262 	 * progress beyond this point until the current invocation is done
19263 	 */
19264 	mutex_enter(&ip_trash_timer_lock);
19265 	ip_ire_expire_id = 0;
19266 	mutex_exit(&ip_trash_timer_lock);
19267 
19268 	/* Periodic timer */
19269 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
19270 		/*
19271 		 * Remove all IRE_CACHE entries since they might
19272 		 * contain arp information.
19273 		 */
19274 		flush_flag |= FLUSH_ARP_TIME;
19275 		ip_ire_arp_time_elapsed = 0;
19276 		IP_STAT(ip_ire_arp_timer_expired);
19277 	}
19278 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
19279 		/* Remove all redirects */
19280 		flush_flag |= FLUSH_REDIRECT_TIME;
19281 		ip_ire_rd_time_elapsed = 0;
19282 		IP_STAT(ip_ire_redirect_timer_expired);
19283 	}
19284 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
19285 		/* Increase path mtu */
19286 		flush_flag |= FLUSH_MTU_TIME;
19287 		ip_ire_pmtu_time_elapsed = 0;
19288 		IP_STAT(ip_ire_pmtu_timer_expired);
19289 	}
19290 
19291 	/*
19292 	 * Optimize for the case when there are no redirects in the
19293 	 * ftable, that is, no need to walk the ftable in that case.
19294 	 */
19295 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19296 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19297 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
19298 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
19299 	}
19300 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
19301 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19302 		    ire_expire, (char *)(uintptr_t)flush_flag,
19303 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
19304 	}
19305 	if (flush_flag & FLUSH_MTU_TIME) {
19306 		/*
19307 		 * Walk all IPv6 IRE's and update them
19308 		 * Note that ARP and redirect timers are not
19309 		 * needed since NUD handles stale entries.
19310 		 */
19311 		flush_flag = FLUSH_MTU_TIME;
19312 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
19313 		    ALL_ZONES);
19314 	}
19315 
19316 	ip_ire_arp_time_elapsed += ip_timer_interval;
19317 	ip_ire_rd_time_elapsed += ip_timer_interval;
19318 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19319 
19320 	/*
19321 	 * Hold the lock to serialize timeout calls and prevent
19322 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19323 	 * for the timer to fire and a new invocation of this function
19324 	 * to start before the return value of timeout has been stored
19325 	 * in ip_ire_expire_id by the current invocation.
19326 	 */
19327 	mutex_enter(&ip_trash_timer_lock);
19328 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19329 	    MSEC_TO_TICK(ip_timer_interval));
19330 	mutex_exit(&ip_trash_timer_lock);
19331 }
19332 
19333 /*
19334  * Called by the memory allocator subsystem directly, when the system
19335  * is running low on memory.
19336  */
19337 /* ARGSUSED */
19338 void
19339 ip_trash_ire_reclaim(void *args)
19340 {
19341 	ire_cache_count_t icc;
19342 	ire_cache_reclaim_t icr;
19343 	ncc_cache_count_t ncc;
19344 	nce_cache_reclaim_t ncr;
19345 	uint_t delete_cnt;
19346 	/*
19347 	 * Memory reclaim call back.
19348 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19349 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19350 	 * entries, determine what fraction to free for
19351 	 * each category of IRE_CACHE entries giving absolute priority
19352 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19353 	 * entry will be freed unless all offlink entries are freed).
19354 	 */
19355 	icc.icc_total = 0;
19356 	icc.icc_unused = 0;
19357 	icc.icc_offlink = 0;
19358 	icc.icc_pmtu = 0;
19359 	icc.icc_onlink = 0;
19360 	ire_walk(ire_cache_count, (char *)&icc);
19361 
19362 	/*
19363 	 * Free NCEs for IPv6 like the onlink ires.
19364 	 */
19365 	ncc.ncc_total = 0;
19366 	ncc.ncc_host = 0;
19367 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19368 
19369 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19370 	    icc.icc_pmtu + icc.icc_onlink);
19371 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19372 	IP_STAT(ip_trash_ire_reclaim_calls);
19373 	if (delete_cnt == 0)
19374 		return;
19375 	IP_STAT(ip_trash_ire_reclaim_success);
19376 	/* Always delete all unused offlink entries */
19377 	icr.icr_unused = 1;
19378 	if (delete_cnt <= icc.icc_unused) {
19379 		/*
19380 		 * Only need to free unused entries.  In other words,
19381 		 * there are enough unused entries to free to meet our
19382 		 * target number of freed ire cache entries.
19383 		 */
19384 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19385 		ncr.ncr_host = 0;
19386 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19387 		/*
19388 		 * Only need to free unused entries, plus a fraction of offlink
19389 		 * entries.  It follows from the first if statement that
19390 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19391 		 */
19392 		delete_cnt -= icc.icc_unused;
19393 		/* Round up # deleted by truncating fraction */
19394 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19395 		icr.icr_pmtu = icr.icr_onlink = 0;
19396 		ncr.ncr_host = 0;
19397 	} else if (delete_cnt <=
19398 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19399 		/*
19400 		 * Free all unused and offlink entries, plus a fraction of
19401 		 * pmtu entries.  It follows from the previous if statement
19402 		 * that icc_pmtu is non-zero, and that
19403 		 * delete_cnt != icc_unused + icc_offlink.
19404 		 */
19405 		icr.icr_offlink = 1;
19406 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19407 		/* Round up # deleted by truncating fraction */
19408 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19409 		icr.icr_onlink = 0;
19410 		ncr.ncr_host = 0;
19411 	} else {
19412 		/*
19413 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19414 		 * of onlink entries.  If we're here, then we know that
19415 		 * icc_onlink is non-zero, and that
19416 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19417 		 */
19418 		icr.icr_offlink = icr.icr_pmtu = 1;
19419 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19420 		    icc.icc_pmtu;
19421 		/* Round up # deleted by truncating fraction */
19422 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19423 		/* Using the same delete fraction as for onlink IREs */
19424 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19425 	}
19426 #ifdef DEBUG
19427 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19428 	    "fractions %d/%d/%d/%d\n",
19429 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19430 	    icc.icc_unused, icc.icc_offlink,
19431 	    icc.icc_pmtu, icc.icc_onlink,
19432 	    icr.icr_unused, icr.icr_offlink,
19433 	    icr.icr_pmtu, icr.icr_onlink));
19434 #endif
19435 	ire_walk(ire_cache_reclaim, (char *)&icr);
19436 	if (ncr.ncr_host != 0)
19437 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19438 		    (uchar_t *)&ncr);
19439 #ifdef DEBUG
19440 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19441 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19442 	ire_walk(ire_cache_count, (char *)&icc);
19443 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19444 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19445 	    icc.icc_pmtu, icc.icc_onlink));
19446 #endif
19447 }
19448 
19449 /*
19450  * ip_unbind is called when a copy of an unbind request is received from the
19451  * upper level protocol.  We remove this conn from any fanout hash list it is
19452  * on, and zero out the bind information.  No reply is expected up above.
19453  */
19454 mblk_t *
19455 ip_unbind(queue_t *q, mblk_t *mp)
19456 {
19457 	conn_t	*connp = Q_TO_CONN(q);
19458 
19459 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19460 
19461 	if (is_system_labeled() && connp->conn_anon_port) {
19462 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19463 		    connp->conn_mlp_type, connp->conn_ulp,
19464 		    ntohs(connp->conn_lport), B_FALSE);
19465 		connp->conn_anon_port = 0;
19466 	}
19467 	connp->conn_mlp_type = mlptSingle;
19468 
19469 	ipcl_hash_remove(connp);
19470 
19471 	ASSERT(mp->b_cont == NULL);
19472 	/*
19473 	 * Convert mp into a T_OK_ACK
19474 	 */
19475 	mp = mi_tpi_ok_ack_alloc(mp);
19476 
19477 	/*
19478 	 * should not happen in practice... T_OK_ACK is smaller than the
19479 	 * original message.
19480 	 */
19481 	if (mp == NULL)
19482 		return (NULL);
19483 
19484 	/*
19485 	 * Don't bzero the ports if its TCP since TCP still needs the
19486 	 * lport to remove it from its own bind hash. TCP will do the
19487 	 * cleanup.
19488 	 */
19489 	if (!IPCL_IS_TCP(connp))
19490 		bzero(&connp->u_port, sizeof (connp->u_port));
19491 
19492 	return (mp);
19493 }
19494 
19495 /*
19496  * Write side put procedure.  Outbound data, IOCTLs, responses from
19497  * resolvers, etc, come down through here.
19498  *
19499  * arg2 is always a queue_t *.
19500  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19501  * the zoneid.
19502  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19503  */
19504 void
19505 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19506 {
19507 	conn_t		*connp = NULL;
19508 	queue_t		*q = (queue_t *)arg2;
19509 	ipha_t		*ipha;
19510 #define	rptr	((uchar_t *)ipha)
19511 	ire_t		*ire = NULL;
19512 	ire_t		*sctp_ire = NULL;
19513 	uint32_t	v_hlen_tos_len;
19514 	ipaddr_t	dst;
19515 	mblk_t		*first_mp = NULL;
19516 	boolean_t	mctl_present;
19517 	ipsec_out_t	*io;
19518 	int		match_flags;
19519 	ill_t		*attach_ill = NULL;
19520 					/* Bind to IPIF_NOFAILOVER ill etc. */
19521 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19522 	ipif_t		*dst_ipif;
19523 	boolean_t	multirt_need_resolve = B_FALSE;
19524 	mblk_t		*copy_mp = NULL;
19525 	int		err;
19526 	zoneid_t	zoneid;
19527 	int	adjust;
19528 	uint16_t iplen;
19529 	boolean_t	need_decref = B_FALSE;
19530 	boolean_t	ignore_dontroute = B_FALSE;
19531 	boolean_t	ignore_nexthop = B_FALSE;
19532 	boolean_t	ip_nexthop = B_FALSE;
19533 	ipaddr_t	nexthop_addr;
19534 
19535 #ifdef	_BIG_ENDIAN
19536 #define	V_HLEN	(v_hlen_tos_len >> 24)
19537 #else
19538 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19539 #endif
19540 
19541 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19542 	    "ip_wput_start: q %p", q);
19543 
19544 	/*
19545 	 * ip_wput fast path
19546 	 */
19547 
19548 	/* is packet from ARP ? */
19549 	if (q->q_next != NULL) {
19550 		zoneid = (zoneid_t)(uintptr_t)arg;
19551 		goto qnext;
19552 	}
19553 
19554 	connp = (conn_t *)arg;
19555 	ASSERT(connp != NULL);
19556 	zoneid = connp->conn_zoneid;
19557 
19558 	/* is queue flow controlled? */
19559 	if ((q->q_first != NULL || connp->conn_draining) &&
19560 	    (caller == IP_WPUT)) {
19561 		ASSERT(!need_decref);
19562 		(void) putq(q, mp);
19563 		return;
19564 	}
19565 
19566 	/* Multidata transmit? */
19567 	if (DB_TYPE(mp) == M_MULTIDATA) {
19568 		/*
19569 		 * We should never get here, since all Multidata messages
19570 		 * originating from tcp should have been directed over to
19571 		 * tcp_multisend() in the first place.
19572 		 */
19573 		BUMP_MIB(&ip_mib, ipOutDiscards);
19574 		freemsg(mp);
19575 		return;
19576 	} else if (DB_TYPE(mp) != M_DATA)
19577 		goto notdata;
19578 
19579 	if (mp->b_flag & MSGHASREF) {
19580 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19581 		mp->b_flag &= ~MSGHASREF;
19582 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19583 		need_decref = B_TRUE;
19584 	}
19585 	ipha = (ipha_t *)mp->b_rptr;
19586 
19587 	/* is IP header non-aligned or mblk smaller than basic IP header */
19588 #ifndef SAFETY_BEFORE_SPEED
19589 	if (!OK_32PTR(rptr) ||
19590 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19591 		goto hdrtoosmall;
19592 #endif
19593 
19594 	ASSERT(OK_32PTR(ipha));
19595 
19596 	/*
19597 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19598 	 * wrong version, we'll catch it again in ip_output_v6.
19599 	 *
19600 	 * Note that this is *only* locally-generated output here, and never
19601 	 * forwarded data, and that we need to deal only with transports that
19602 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19603 	 * label.)
19604 	 */
19605 	if (is_system_labeled() &&
19606 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19607 	    !connp->conn_ulp_labeled) {
19608 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19609 		    connp->conn_mac_exempt);
19610 		ipha = (ipha_t *)mp->b_rptr;
19611 		if (err != 0) {
19612 			first_mp = mp;
19613 			if (err == EINVAL)
19614 				goto icmp_parameter_problem;
19615 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19616 			goto drop_pkt;
19617 		}
19618 		iplen = ntohs(ipha->ipha_length) + adjust;
19619 		ipha->ipha_length = htons(iplen);
19620 	}
19621 
19622 	/*
19623 	 * If there is a policy, try to attach an ipsec_out in
19624 	 * the front. At the end, first_mp either points to a
19625 	 * M_DATA message or IPSEC_OUT message linked to a
19626 	 * M_DATA message. We have to do it now as we might
19627 	 * lose the "conn" if we go through ip_newroute.
19628 	 */
19629 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19630 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
19631 		    ipha->ipha_protocol)) == NULL)) {
19632 			if (need_decref)
19633 				CONN_DEC_REF(connp);
19634 			return;
19635 		} else {
19636 			ASSERT(mp->b_datap->db_type == M_CTL);
19637 			first_mp = mp;
19638 			mp = mp->b_cont;
19639 			mctl_present = B_TRUE;
19640 		}
19641 	} else {
19642 		first_mp = mp;
19643 		mctl_present = B_FALSE;
19644 	}
19645 
19646 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19647 
19648 	/* is wrong version or IP options present */
19649 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19650 		goto version_hdrlen_check;
19651 	dst = ipha->ipha_dst;
19652 
19653 	if (connp->conn_nofailover_ill != NULL) {
19654 		attach_ill = conn_get_held_ill(connp,
19655 		    &connp->conn_nofailover_ill, &err);
19656 		if (err == ILL_LOOKUP_FAILED) {
19657 			if (need_decref)
19658 				CONN_DEC_REF(connp);
19659 			freemsg(first_mp);
19660 			return;
19661 		}
19662 	}
19663 
19664 	/* is packet multicast? */
19665 	if (CLASSD(dst))
19666 		goto multicast;
19667 
19668 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19669 	    (connp->conn_nexthop_set)) {
19670 		/*
19671 		 * If the destination is a broadcast or a loopback
19672 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
19673 		 * through the standard path. But in the case of local
19674 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
19675 		 * the standard path not IP_XMIT_IF.
19676 		 */
19677 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19678 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
19679 		    (ire->ire_type != IRE_LOOPBACK))) {
19680 			if ((connp->conn_dontroute ||
19681 			    connp->conn_nexthop_set) && (ire != NULL) &&
19682 			    (ire->ire_type == IRE_LOCAL))
19683 				goto standard_path;
19684 
19685 			if (ire != NULL) {
19686 				ire_refrele(ire);
19687 				/* No more access to ire */
19688 				ire = NULL;
19689 			}
19690 			/*
19691 			 * bypass routing checks and go directly to
19692 			 * interface.
19693 			 */
19694 			if (connp->conn_dontroute) {
19695 				goto dontroute;
19696 			} else if (connp->conn_nexthop_set) {
19697 				ip_nexthop = B_TRUE;
19698 				nexthop_addr = connp->conn_nexthop_v4;
19699 				goto send_from_ill;
19700 			}
19701 
19702 			/*
19703 			 * If IP_XMIT_IF socket option is set,
19704 			 * then we allow unicast and multicast
19705 			 * packets to go through the ill. It is
19706 			 * quite possible that the destination
19707 			 * is not in the ire cache table and we
19708 			 * do not want to go to ip_newroute()
19709 			 * instead we call ip_newroute_ipif.
19710 			 */
19711 			xmit_ill = conn_get_held_ill(connp,
19712 			    &connp->conn_xmit_if_ill, &err);
19713 			if (err == ILL_LOOKUP_FAILED) {
19714 				if (attach_ill != NULL)
19715 					ill_refrele(attach_ill);
19716 				if (need_decref)
19717 					CONN_DEC_REF(connp);
19718 				freemsg(first_mp);
19719 				return;
19720 			}
19721 			goto send_from_ill;
19722 		}
19723 standard_path:
19724 		/* Must be a broadcast, a loopback or a local ire */
19725 		if (ire != NULL) {
19726 			ire_refrele(ire);
19727 			/* No more access to ire */
19728 			ire = NULL;
19729 		}
19730 	}
19731 
19732 	if (attach_ill != NULL)
19733 		goto send_from_ill;
19734 
19735 	/*
19736 	 * We cache IRE_CACHEs to avoid lookups. We don't do
19737 	 * this for the tcp global queue and listen end point
19738 	 * as it does not really have a real destination to
19739 	 * talk to.  This is also true for SCTP.
19740 	 */
19741 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
19742 	    !connp->conn_fully_bound) {
19743 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19744 		if (ire == NULL)
19745 			goto noirefound;
19746 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19747 		    "ip_wput_end: q %p (%S)", q, "end");
19748 
19749 		/*
19750 		 * Check if the ire has the RTF_MULTIRT flag, inherited
19751 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19752 		 */
19753 		if (ire->ire_flags & RTF_MULTIRT) {
19754 
19755 			/*
19756 			 * Force the TTL of multirouted packets if required.
19757 			 * The TTL of such packets is bounded by the
19758 			 * ip_multirt_ttl ndd variable.
19759 			 */
19760 			if ((ip_multirt_ttl > 0) &&
19761 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
19762 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
19763 				    "(was %d), dst 0x%08x\n",
19764 				    ip_multirt_ttl, ipha->ipha_ttl,
19765 				    ntohl(ire->ire_addr)));
19766 				ipha->ipha_ttl = ip_multirt_ttl;
19767 			}
19768 			/*
19769 			 * We look at this point if there are pending
19770 			 * unresolved routes. ire_multirt_resolvable()
19771 			 * checks in O(n) that all IRE_OFFSUBNET ire
19772 			 * entries for the packet's destination and
19773 			 * flagged RTF_MULTIRT are currently resolved.
19774 			 * If some remain unresolved, we make a copy
19775 			 * of the current message. It will be used
19776 			 * to initiate additional route resolutions.
19777 			 */
19778 			multirt_need_resolve =
19779 			    ire_multirt_need_resolve(ire->ire_addr,
19780 			    MBLK_GETLABEL(first_mp));
19781 			ip2dbg(("ip_wput[TCP]: ire %p, "
19782 			    "multirt_need_resolve %d, first_mp %p\n",
19783 			    (void *)ire, multirt_need_resolve,
19784 			    (void *)first_mp));
19785 			if (multirt_need_resolve) {
19786 				copy_mp = copymsg(first_mp);
19787 				if (copy_mp != NULL) {
19788 					MULTIRT_DEBUG_TAG(copy_mp);
19789 				}
19790 			}
19791 		}
19792 
19793 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19794 
19795 		/*
19796 		 * Try to resolve another multiroute if
19797 		 * ire_multirt_need_resolve() deemed it necessary.
19798 		 */
19799 		if (copy_mp != NULL) {
19800 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19801 		}
19802 		if (need_decref)
19803 			CONN_DEC_REF(connp);
19804 		return;
19805 	}
19806 
19807 	/*
19808 	 * Access to conn_ire_cache. (protected by conn_lock)
19809 	 *
19810 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
19811 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
19812 	 * send a packet or two with the IRE_CACHE that is going away.
19813 	 * Access to the ire requires an ire refhold on the ire prior to
19814 	 * its use since an interface unplumb thread may delete the cached
19815 	 * ire and release the refhold at any time.
19816 	 *
19817 	 * Caching an ire in the conn_ire_cache
19818 	 *
19819 	 * o Caching an ire pointer in the conn requires a strict check for
19820 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
19821 	 * ires  before cleaning up the conns. So the caching of an ire pointer
19822 	 * in the conn is done after making sure under the bucket lock that the
19823 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
19824 	 * caching an ire after the unplumb thread has cleaned up the conn.
19825 	 * If the conn does not send a packet subsequently the unplumb thread
19826 	 * will be hanging waiting for the ire count to drop to zero.
19827 	 *
19828 	 * o We also need to atomically test for a null conn_ire_cache and
19829 	 * set the conn_ire_cache under the the protection of the conn_lock
19830 	 * to avoid races among concurrent threads trying to simultaneously
19831 	 * cache an ire in the conn_ire_cache.
19832 	 */
19833 	mutex_enter(&connp->conn_lock);
19834 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
19835 
19836 	if (ire != NULL && ire->ire_addr == dst &&
19837 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19838 
19839 		IRE_REFHOLD(ire);
19840 		mutex_exit(&connp->conn_lock);
19841 
19842 	} else {
19843 		boolean_t cached = B_FALSE;
19844 		connp->conn_ire_cache = NULL;
19845 		mutex_exit(&connp->conn_lock);
19846 		/* Release the old ire */
19847 		if (ire != NULL && sctp_ire == NULL)
19848 			IRE_REFRELE_NOTR(ire);
19849 
19850 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19851 		if (ire == NULL)
19852 			goto noirefound;
19853 		IRE_REFHOLD_NOTR(ire);
19854 
19855 		mutex_enter(&connp->conn_lock);
19856 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
19857 		    connp->conn_ire_cache == NULL) {
19858 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19859 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19860 				connp->conn_ire_cache = ire;
19861 				cached = B_TRUE;
19862 			}
19863 			rw_exit(&ire->ire_bucket->irb_lock);
19864 		}
19865 		mutex_exit(&connp->conn_lock);
19866 
19867 		/*
19868 		 * We can continue to use the ire but since it was
19869 		 * not cached, we should drop the extra reference.
19870 		 */
19871 		if (!cached)
19872 			IRE_REFRELE_NOTR(ire);
19873 	}
19874 
19875 
19876 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19877 	    "ip_wput_end: q %p (%S)", q, "end");
19878 
19879 	/*
19880 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19881 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19882 	 */
19883 	if (ire->ire_flags & RTF_MULTIRT) {
19884 
19885 		/*
19886 		 * Force the TTL of multirouted packets if required.
19887 		 * The TTL of such packets is bounded by the
19888 		 * ip_multirt_ttl ndd variable.
19889 		 */
19890 		if ((ip_multirt_ttl > 0) &&
19891 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19892 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19893 			    "(was %d), dst 0x%08x\n",
19894 			    ip_multirt_ttl, ipha->ipha_ttl,
19895 			    ntohl(ire->ire_addr)));
19896 			ipha->ipha_ttl = ip_multirt_ttl;
19897 		}
19898 
19899 		/*
19900 		 * At this point, we check to see if there are any pending
19901 		 * unresolved routes. ire_multirt_resolvable()
19902 		 * checks in O(n) that all IRE_OFFSUBNET ire
19903 		 * entries for the packet's destination and
19904 		 * flagged RTF_MULTIRT are currently resolved.
19905 		 * If some remain unresolved, we make a copy
19906 		 * of the current message. It will be used
19907 		 * to initiate additional route resolutions.
19908 		 */
19909 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19910 		    MBLK_GETLABEL(first_mp));
19911 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19912 		    "multirt_need_resolve %d, first_mp %p\n",
19913 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19914 		if (multirt_need_resolve) {
19915 			copy_mp = copymsg(first_mp);
19916 			if (copy_mp != NULL) {
19917 				MULTIRT_DEBUG_TAG(copy_mp);
19918 			}
19919 		}
19920 	}
19921 
19922 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19923 
19924 	/*
19925 	 * Try to resolve another multiroute if
19926 	 * ire_multirt_resolvable() deemed it necessary
19927 	 */
19928 	if (copy_mp != NULL) {
19929 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19930 	}
19931 	if (need_decref)
19932 		CONN_DEC_REF(connp);
19933 	return;
19934 
19935 qnext:
19936 	/*
19937 	 * Upper Level Protocols pass down complete IP datagrams
19938 	 * as M_DATA messages.	Everything else is a sideshow.
19939 	 *
19940 	 * 1) We could be re-entering ip_wput because of ip_neworute
19941 	 *    in which case we could have a IPSEC_OUT message. We
19942 	 *    need to pass through ip_wput like other datagrams and
19943 	 *    hence cannot branch to ip_wput_nondata.
19944 	 *
19945 	 * 2) ARP, AH, ESP, and other clients who are on the module
19946 	 *    instance of IP stream, give us something to deal with.
19947 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19948 	 *
19949 	 * 3) ICMP replies also could come here.
19950 	 */
19951 	if (DB_TYPE(mp) != M_DATA) {
19952 	    notdata:
19953 		if (DB_TYPE(mp) == M_CTL) {
19954 			/*
19955 			 * M_CTL messages are used by ARP, AH and ESP to
19956 			 * communicate with IP. We deal with IPSEC_IN and
19957 			 * IPSEC_OUT here. ip_wput_nondata handles other
19958 			 * cases.
19959 			 */
19960 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19961 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19962 				first_mp = mp->b_cont;
19963 				first_mp->b_flag &= ~MSGHASREF;
19964 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19965 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19966 				CONN_DEC_REF(connp);
19967 				connp = NULL;
19968 			}
19969 			if (ii->ipsec_info_type == IPSEC_IN) {
19970 				/*
19971 				 * Either this message goes back to
19972 				 * IPSEC for further processing or to
19973 				 * ULP after policy checks.
19974 				 */
19975 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19976 				return;
19977 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19978 				io = (ipsec_out_t *)ii;
19979 				if (io->ipsec_out_proc_begin) {
19980 					/*
19981 					 * IPSEC processing has already started.
19982 					 * Complete it.
19983 					 * IPQoS notes: We don't care what is
19984 					 * in ipsec_out_ill_index since this
19985 					 * won't be processed for IPQoS policies
19986 					 * in ipsec_out_process.
19987 					 */
19988 					ipsec_out_process(q, mp, NULL,
19989 					    io->ipsec_out_ill_index);
19990 					return;
19991 				} else {
19992 					connp = (q->q_next != NULL) ?
19993 					    NULL : Q_TO_CONN(q);
19994 					first_mp = mp;
19995 					mp = mp->b_cont;
19996 					mctl_present = B_TRUE;
19997 				}
19998 				zoneid = io->ipsec_out_zoneid;
19999 				ASSERT(zoneid != ALL_ZONES);
20000 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20001 				/*
20002 				 * It's an IPsec control message requesting
20003 				 * an SADB update to be sent to the IPsec
20004 				 * hardware acceleration capable ills.
20005 				 */
20006 				ipsec_ctl_t *ipsec_ctl =
20007 				    (ipsec_ctl_t *)mp->b_rptr;
20008 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20009 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20010 				mblk_t *cmp = mp->b_cont;
20011 
20012 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20013 				ASSERT(cmp != NULL);
20014 
20015 				freeb(mp);
20016 				ill_ipsec_capab_send_all(satype, cmp, sa);
20017 				return;
20018 			} else {
20019 				/*
20020 				 * This must be ARP or special TSOL signaling.
20021 				 */
20022 				ip_wput_nondata(NULL, q, mp, NULL);
20023 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20024 				    "ip_wput_end: q %p (%S)", q, "nondata");
20025 				return;
20026 			}
20027 		} else {
20028 			/*
20029 			 * This must be non-(ARP/AH/ESP) messages.
20030 			 */
20031 			ASSERT(!need_decref);
20032 			ip_wput_nondata(NULL, q, mp, NULL);
20033 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20034 			    "ip_wput_end: q %p (%S)", q, "nondata");
20035 			return;
20036 		}
20037 	} else {
20038 		first_mp = mp;
20039 		mctl_present = B_FALSE;
20040 	}
20041 
20042 	ASSERT(first_mp != NULL);
20043 	/*
20044 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20045 	 * to make sure that this packet goes out on the same interface it
20046 	 * came in. We handle that here.
20047 	 */
20048 	if (mctl_present) {
20049 		uint_t ifindex;
20050 
20051 		io = (ipsec_out_t *)first_mp->b_rptr;
20052 		if (io->ipsec_out_attach_if ||
20053 		    io->ipsec_out_xmit_if ||
20054 		    io->ipsec_out_ip_nexthop) {
20055 			ill_t	*ill;
20056 
20057 			/*
20058 			 * We may have lost the conn context if we are
20059 			 * coming here from ip_newroute(). Copy the
20060 			 * nexthop information.
20061 			 */
20062 			if (io->ipsec_out_ip_nexthop) {
20063 				ip_nexthop = B_TRUE;
20064 				nexthop_addr = io->ipsec_out_nexthop_addr;
20065 
20066 				ipha = (ipha_t *)mp->b_rptr;
20067 				dst = ipha->ipha_dst;
20068 				goto send_from_ill;
20069 			} else {
20070 				ASSERT(io->ipsec_out_ill_index != 0);
20071 				ifindex = io->ipsec_out_ill_index;
20072 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20073 				    NULL, NULL, NULL, NULL);
20074 				/*
20075 				 * ipsec_out_xmit_if bit is used to tell
20076 				 * ip_wput to use the ill to send outgoing data
20077 				 * as we have no conn when data comes from ICMP
20078 				 * error msg routines. Currently this feature is
20079 				 * only used by ip_mrtun_forward routine.
20080 				 */
20081 				if (io->ipsec_out_xmit_if) {
20082 					xmit_ill = ill;
20083 					if (xmit_ill == NULL) {
20084 						ip1dbg(("ip_output:bad ifindex "
20085 						    "for xmit_ill %d\n",
20086 						    ifindex));
20087 						freemsg(first_mp);
20088 						BUMP_MIB(&ip_mib,
20089 						    ipOutDiscards);
20090 						ASSERT(!need_decref);
20091 						return;
20092 					}
20093 					/* Free up the ipsec_out_t mblk */
20094 					ASSERT(first_mp->b_cont == mp);
20095 					first_mp->b_cont = NULL;
20096 					freeb(first_mp);
20097 					/* Just send the IP header+ICMP+data */
20098 					first_mp = mp;
20099 					ipha = (ipha_t *)mp->b_rptr;
20100 					dst = ipha->ipha_dst;
20101 					goto send_from_ill;
20102 				} else {
20103 					attach_ill = ill;
20104 				}
20105 
20106 				if (attach_ill == NULL) {
20107 					ASSERT(xmit_ill == NULL);
20108 					ip1dbg(("ip_output: bad ifindex for "
20109 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20110 					    ifindex));
20111 					freemsg(first_mp);
20112 					BUMP_MIB(&ip_mib, ipOutDiscards);
20113 					ASSERT(!need_decref);
20114 					return;
20115 				}
20116 			}
20117 		}
20118 	}
20119 
20120 	ASSERT(xmit_ill == NULL);
20121 
20122 	/* We have a complete IP datagram heading outbound. */
20123 	ipha = (ipha_t *)mp->b_rptr;
20124 
20125 #ifndef SPEED_BEFORE_SAFETY
20126 	/*
20127 	 * Make sure we have a full-word aligned message and that at least
20128 	 * a simple IP header is accessible in the first message.  If not,
20129 	 * try a pullup.
20130 	 */
20131 	if (!OK_32PTR(rptr) ||
20132 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20133 	    hdrtoosmall:
20134 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20135 			BUMP_MIB(&ip_mib, ipOutDiscards);
20136 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20137 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20138 			if (first_mp == NULL)
20139 				first_mp = mp;
20140 			goto drop_pkt;
20141 		}
20142 
20143 		/* This function assumes that mp points to an IPv4 packet. */
20144 		if (is_system_labeled() && q->q_next == NULL &&
20145 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20146 		    !connp->conn_ulp_labeled) {
20147 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20148 			    &adjust, connp->conn_mac_exempt);
20149 			ipha = (ipha_t *)mp->b_rptr;
20150 			if (first_mp != NULL)
20151 				first_mp->b_cont = mp;
20152 			if (err != 0) {
20153 				if (first_mp == NULL)
20154 					first_mp = mp;
20155 				if (err == EINVAL)
20156 					goto icmp_parameter_problem;
20157 				ip2dbg(("ip_wput: label check failed (%d)\n",
20158 				    err));
20159 				goto drop_pkt;
20160 			}
20161 			iplen = ntohs(ipha->ipha_length) + adjust;
20162 			ipha->ipha_length = htons(iplen);
20163 		}
20164 
20165 		ipha = (ipha_t *)mp->b_rptr;
20166 		if (first_mp == NULL) {
20167 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20168 			/*
20169 			 * If we got here because of "goto hdrtoosmall"
20170 			 * We need to attach a IPSEC_OUT.
20171 			 */
20172 			if (connp->conn_out_enforce_policy) {
20173 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20174 				    NULL, ipha->ipha_protocol)) == NULL)) {
20175 					if (need_decref)
20176 						CONN_DEC_REF(connp);
20177 					return;
20178 				} else {
20179 					ASSERT(mp->b_datap->db_type == M_CTL);
20180 					first_mp = mp;
20181 					mp = mp->b_cont;
20182 					mctl_present = B_TRUE;
20183 				}
20184 			} else {
20185 				first_mp = mp;
20186 				mctl_present = B_FALSE;
20187 			}
20188 		}
20189 	}
20190 #endif
20191 
20192 	/* Most of the code below is written for speed, not readability */
20193 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20194 
20195 	/*
20196 	 * If ip_newroute() fails, we're going to need a full
20197 	 * header for the icmp wraparound.
20198 	 */
20199 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20200 		uint_t	v_hlen;
20201 	    version_hdrlen_check:
20202 		ASSERT(first_mp != NULL);
20203 		v_hlen = V_HLEN;
20204 		/*
20205 		 * siphon off IPv6 packets coming down from transport
20206 		 * layer modules here.
20207 		 * Note: high-order bit carries NUD reachability confirmation
20208 		 */
20209 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20210 			/*
20211 			 * XXX implement a IPv4 and IPv6 packet counter per
20212 			 * conn and switch when ratio exceeds e.g. 10:1
20213 			 */
20214 #ifdef notyet
20215 			if (q->q_next == NULL) /* Avoid ill queue */
20216 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
20217 #endif
20218 			BUMP_MIB(&ip_mib, ipOutIPv6);
20219 			ASSERT(xmit_ill == NULL);
20220 			if (attach_ill != NULL)
20221 				ill_refrele(attach_ill);
20222 			if (need_decref)
20223 				mp->b_flag |= MSGHASREF;
20224 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20225 			return;
20226 		}
20227 
20228 		if ((v_hlen >> 4) != IP_VERSION) {
20229 			BUMP_MIB(&ip_mib, ipOutDiscards);
20230 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20231 			    "ip_wput_end: q %p (%S)", q, "badvers");
20232 			goto drop_pkt;
20233 		}
20234 		/*
20235 		 * Is the header length at least 20 bytes?
20236 		 *
20237 		 * Are there enough bytes accessible in the header?  If
20238 		 * not, try a pullup.
20239 		 */
20240 		v_hlen &= 0xF;
20241 		v_hlen <<= 2;
20242 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20243 			BUMP_MIB(&ip_mib, ipOutDiscards);
20244 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20245 			    "ip_wput_end: q %p (%S)", q, "badlen");
20246 			goto drop_pkt;
20247 		}
20248 		if (v_hlen > (mp->b_wptr - rptr)) {
20249 			if (!pullupmsg(mp, v_hlen)) {
20250 				BUMP_MIB(&ip_mib, ipOutDiscards);
20251 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20252 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20253 				goto drop_pkt;
20254 			}
20255 			ipha = (ipha_t *)mp->b_rptr;
20256 		}
20257 		/*
20258 		 * Move first entry from any source route into ipha_dst and
20259 		 * verify the options
20260 		 */
20261 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
20262 			ASSERT(xmit_ill == NULL);
20263 			if (attach_ill != NULL)
20264 				ill_refrele(attach_ill);
20265 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20266 			    "ip_wput_end: q %p (%S)", q, "badopts");
20267 			if (need_decref)
20268 				CONN_DEC_REF(connp);
20269 			return;
20270 		}
20271 	}
20272 	dst = ipha->ipha_dst;
20273 
20274 	/*
20275 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20276 	 * we have to run the packet through ip_newroute which will take
20277 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20278 	 * a resolver, or assigning a default gateway, etc.
20279 	 */
20280 	if (CLASSD(dst)) {
20281 		ipif_t	*ipif;
20282 		uint32_t setsrc = 0;
20283 
20284 	    multicast:
20285 		ASSERT(first_mp != NULL);
20286 		ASSERT(xmit_ill == NULL);
20287 		ip2dbg(("ip_wput: CLASSD\n"));
20288 		if (connp == NULL) {
20289 			/*
20290 			 * Use the first good ipif on the ill.
20291 			 * XXX Should this ever happen? (Appears
20292 			 * to show up with just ppp and no ethernet due
20293 			 * to in.rdisc.)
20294 			 * However, ire_send should be able to
20295 			 * call ip_wput_ire directly.
20296 			 *
20297 			 * XXX Also, this can happen for ICMP and other packets
20298 			 * with multicast source addresses.  Perhaps we should
20299 			 * fix things so that we drop the packet in question,
20300 			 * but for now, just run with it.
20301 			 */
20302 			ill_t *ill = (ill_t *)q->q_ptr;
20303 
20304 			/*
20305 			 * Don't honor attach_if for this case. If ill
20306 			 * is part of the group, ipif could belong to
20307 			 * any ill and we cannot maintain attach_ill
20308 			 * and ipif_ill same anymore and the assert
20309 			 * below would fail.
20310 			 */
20311 			if (mctl_present && io->ipsec_out_attach_if) {
20312 				io->ipsec_out_ill_index = 0;
20313 				io->ipsec_out_attach_if = B_FALSE;
20314 				ASSERT(attach_ill != NULL);
20315 				ill_refrele(attach_ill);
20316 				attach_ill = NULL;
20317 			}
20318 
20319 			ASSERT(attach_ill == NULL);
20320 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20321 			if (ipif == NULL) {
20322 				if (need_decref)
20323 					CONN_DEC_REF(connp);
20324 				freemsg(first_mp);
20325 				return;
20326 			}
20327 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20328 			    ntohl(dst), ill->ill_name));
20329 		} else {
20330 			/*
20331 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
20332 			 * IP_XMIT_IF is honoured.
20333 			 * Block comment above this function explains the
20334 			 * locking mechanism used here
20335 			 */
20336 			xmit_ill = conn_get_held_ill(connp,
20337 			    &connp->conn_xmit_if_ill, &err);
20338 			if (err == ILL_LOOKUP_FAILED) {
20339 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
20340 				goto drop_pkt;
20341 			}
20342 			if (xmit_ill == NULL) {
20343 				ipif = conn_get_held_ipif(connp,
20344 				    &connp->conn_multicast_ipif, &err);
20345 				if (err == IPIF_LOOKUP_FAILED) {
20346 					ip1dbg(("ip_wput: No ipif for "
20347 					    "multicast\n"));
20348 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20349 					goto drop_pkt;
20350 				}
20351 			}
20352 			if (xmit_ill != NULL) {
20353 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20354 				if (ipif == NULL) {
20355 					ip1dbg(("ip_wput: No ipif for "
20356 					    "IP_XMIT_IF\n"));
20357 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20358 					goto drop_pkt;
20359 				}
20360 			} else if (ipif == NULL || ipif->ipif_isv6) {
20361 				/*
20362 				 * We must do this ipif determination here
20363 				 * else we could pass through ip_newroute
20364 				 * and come back here without the conn context.
20365 				 *
20366 				 * Note: we do late binding i.e. we bind to
20367 				 * the interface when the first packet is sent.
20368 				 * For performance reasons we do not rebind on
20369 				 * each packet but keep the binding until the
20370 				 * next IP_MULTICAST_IF option.
20371 				 *
20372 				 * conn_multicast_{ipif,ill} are shared between
20373 				 * IPv4 and IPv6 and AF_INET6 sockets can
20374 				 * send both IPv4 and IPv6 packets. Hence
20375 				 * we have to check that "isv6" matches above.
20376 				 */
20377 				if (ipif != NULL)
20378 					ipif_refrele(ipif);
20379 				ipif = ipif_lookup_group(dst, zoneid);
20380 				if (ipif == NULL) {
20381 					ip1dbg(("ip_wput: No ipif for "
20382 					    "multicast\n"));
20383 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20384 					goto drop_pkt;
20385 				}
20386 				err = conn_set_held_ipif(connp,
20387 				    &connp->conn_multicast_ipif, ipif);
20388 				if (err == IPIF_LOOKUP_FAILED) {
20389 					ipif_refrele(ipif);
20390 					ip1dbg(("ip_wput: No ipif for "
20391 					    "multicast\n"));
20392 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20393 					goto drop_pkt;
20394 				}
20395 			}
20396 		}
20397 		ASSERT(!ipif->ipif_isv6);
20398 		/*
20399 		 * As we may lose the conn by the time we reach ip_wput_ire,
20400 		 * we copy conn_multicast_loop and conn_dontroute on to an
20401 		 * ipsec_out. In case if this datagram goes out secure,
20402 		 * we need the ill_index also. Copy that also into the
20403 		 * ipsec_out.
20404 		 */
20405 		if (mctl_present) {
20406 			io = (ipsec_out_t *)first_mp->b_rptr;
20407 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20408 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20409 		} else {
20410 			ASSERT(mp == first_mp);
20411 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20412 			    BPRI_HI)) == NULL) {
20413 				ipif_refrele(ipif);
20414 				first_mp = mp;
20415 				goto drop_pkt;
20416 			}
20417 			first_mp->b_datap->db_type = M_CTL;
20418 			first_mp->b_wptr += sizeof (ipsec_info_t);
20419 			/* ipsec_out_secure is B_FALSE now */
20420 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20421 			io = (ipsec_out_t *)first_mp->b_rptr;
20422 			io->ipsec_out_type = IPSEC_OUT;
20423 			io->ipsec_out_len = sizeof (ipsec_out_t);
20424 			io->ipsec_out_use_global_policy = B_TRUE;
20425 			first_mp->b_cont = mp;
20426 			mctl_present = B_TRUE;
20427 		}
20428 		if (attach_ill != NULL) {
20429 			ASSERT(attach_ill == ipif->ipif_ill);
20430 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20431 
20432 			/*
20433 			 * Check if we need an ire that will not be
20434 			 * looked up by anybody else i.e. HIDDEN.
20435 			 */
20436 			if (ill_is_probeonly(attach_ill)) {
20437 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20438 			}
20439 			io->ipsec_out_ill_index =
20440 			    attach_ill->ill_phyint->phyint_ifindex;
20441 			io->ipsec_out_attach_if = B_TRUE;
20442 		} else {
20443 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20444 			io->ipsec_out_ill_index =
20445 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20446 		}
20447 		if (connp != NULL) {
20448 			io->ipsec_out_multicast_loop =
20449 			    connp->conn_multicast_loop;
20450 			io->ipsec_out_dontroute = connp->conn_dontroute;
20451 			io->ipsec_out_zoneid = connp->conn_zoneid;
20452 		}
20453 		/*
20454 		 * If the application uses IP_MULTICAST_IF with
20455 		 * different logical addresses of the same ILL, we
20456 		 * need to make sure that the soruce address of
20457 		 * the packet matches the logical IP address used
20458 		 * in the option. We do it by initializing ipha_src
20459 		 * here. This should keep IPSEC also happy as
20460 		 * when we return from IPSEC processing, we don't
20461 		 * have to worry about getting the right address on
20462 		 * the packet. Thus it is sufficient to look for
20463 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20464 		 * MATCH_IRE_IPIF.
20465 		 *
20466 		 * NOTE : We need to do it for non-secure case also as
20467 		 * this might go out secure if there is a global policy
20468 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20469 		 * address, the source should be initialized already and
20470 		 * hence we won't be initializing here.
20471 		 *
20472 		 * As we do not have the ire yet, it is possible that
20473 		 * we set the source address here and then later discover
20474 		 * that the ire implies the source address to be assigned
20475 		 * through the RTF_SETSRC flag.
20476 		 * In that case, the setsrc variable will remind us
20477 		 * that overwritting the source address by the one
20478 		 * of the RTF_SETSRC-flagged ire is allowed.
20479 		 */
20480 		if (ipha->ipha_src == INADDR_ANY &&
20481 		    (connp == NULL || !connp->conn_unspec_src)) {
20482 			ipha->ipha_src = ipif->ipif_src_addr;
20483 			setsrc = RTF_SETSRC;
20484 		}
20485 		/*
20486 		 * Find an IRE which matches the destination and the outgoing
20487 		 * queue (i.e. the outgoing interface.)
20488 		 * For loopback use a unicast IP address for
20489 		 * the ire lookup.
20490 		 */
20491 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20492 		    PHYI_LOOPBACK) {
20493 			dst = ipif->ipif_lcl_addr;
20494 		}
20495 		/*
20496 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20497 		 * We don't need to lookup ire in ctable as the packet
20498 		 * needs to be sent to the destination through the specified
20499 		 * ill irrespective of ires in the cache table.
20500 		 */
20501 		ire = NULL;
20502 		if (xmit_ill == NULL) {
20503 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20504 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20505 		}
20506 
20507 		/*
20508 		 * refrele attach_ill as its not needed anymore.
20509 		 */
20510 		if (attach_ill != NULL) {
20511 			ill_refrele(attach_ill);
20512 			attach_ill = NULL;
20513 		}
20514 
20515 		if (ire == NULL) {
20516 			/*
20517 			 * Multicast loopback and multicast forwarding is
20518 			 * done in ip_wput_ire.
20519 			 *
20520 			 * Mark this packet to make it be delivered to
20521 			 * ip_wput_ire after the new ire has been
20522 			 * created.
20523 			 *
20524 			 * The call to ip_newroute_ipif takes into account
20525 			 * the setsrc reminder. In any case, we take care
20526 			 * of the RTF_MULTIRT flag.
20527 			 */
20528 			mp->b_prev = mp->b_next = NULL;
20529 			if (xmit_ill == NULL ||
20530 			    xmit_ill->ill_ipif_up_count > 0) {
20531 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20532 				    setsrc | RTF_MULTIRT, zoneid);
20533 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20534 				    "ip_wput_end: q %p (%S)", q, "noire");
20535 			} else {
20536 				freemsg(first_mp);
20537 			}
20538 			ipif_refrele(ipif);
20539 			if (xmit_ill != NULL)
20540 				ill_refrele(xmit_ill);
20541 			if (need_decref)
20542 				CONN_DEC_REF(connp);
20543 			return;
20544 		}
20545 
20546 		ipif_refrele(ipif);
20547 		ipif = NULL;
20548 		ASSERT(xmit_ill == NULL);
20549 
20550 		/*
20551 		 * Honor the RTF_SETSRC flag for multicast packets,
20552 		 * if allowed by the setsrc reminder.
20553 		 */
20554 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20555 			ipha->ipha_src = ire->ire_src_addr;
20556 		}
20557 
20558 		/*
20559 		 * Unconditionally force the TTL to 1 for
20560 		 * multirouted multicast packets:
20561 		 * multirouted multicast should not cross
20562 		 * multicast routers.
20563 		 */
20564 		if (ire->ire_flags & RTF_MULTIRT) {
20565 			if (ipha->ipha_ttl > 1) {
20566 				ip2dbg(("ip_wput: forcing multicast "
20567 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20568 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20569 				ipha->ipha_ttl = 1;
20570 			}
20571 		}
20572 	} else {
20573 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20574 		if ((ire != NULL) && (ire->ire_type &
20575 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20576 			ignore_dontroute = B_TRUE;
20577 			ignore_nexthop = B_TRUE;
20578 		}
20579 		if (ire != NULL) {
20580 			ire_refrele(ire);
20581 			ire = NULL;
20582 		}
20583 		/*
20584 		 * Guard against coming in from arp in which case conn is NULL.
20585 		 * Also guard against non M_DATA with dontroute set but
20586 		 * destined to local, loopback or broadcast addresses.
20587 		 */
20588 		if (connp != NULL && connp->conn_dontroute &&
20589 		    !ignore_dontroute) {
20590 dontroute:
20591 			/*
20592 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20593 			 * routing protocols from seeing false direct
20594 			 * connectivity.
20595 			 */
20596 			ipha->ipha_ttl = 1;
20597 			/*
20598 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20599 			 * along with SO_DONTROUTE, higher precedence is
20600 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20601 			 */
20602 			if (connp->conn_xmit_if_ill == NULL) {
20603 				/* If suitable ipif not found, drop packet */
20604 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20605 				if (dst_ipif == NULL) {
20606 					ip1dbg(("ip_wput: no route for "
20607 					    "dst using SO_DONTROUTE\n"));
20608 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20609 					mp->b_prev = mp->b_next = NULL;
20610 					if (first_mp == NULL)
20611 						first_mp = mp;
20612 					goto drop_pkt;
20613 				} else {
20614 					/*
20615 					 * If suitable ipif has been found, set
20616 					 * xmit_ill to the corresponding
20617 					 * ipif_ill because we'll be following
20618 					 * the IP_XMIT_IF logic.
20619 					 */
20620 					ASSERT(xmit_ill == NULL);
20621 					xmit_ill = dst_ipif->ipif_ill;
20622 					mutex_enter(&xmit_ill->ill_lock);
20623 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20624 						mutex_exit(&xmit_ill->ill_lock);
20625 						xmit_ill = NULL;
20626 						ipif_refrele(dst_ipif);
20627 						ip1dbg(("ip_wput: no route for"
20628 						    " dst using"
20629 						    " SO_DONTROUTE\n"));
20630 						BUMP_MIB(&ip_mib,
20631 						    ipOutNoRoutes);
20632 						mp->b_prev = mp->b_next = NULL;
20633 						if (first_mp == NULL)
20634 							first_mp = mp;
20635 						goto drop_pkt;
20636 					}
20637 					ill_refhold_locked(xmit_ill);
20638 					mutex_exit(&xmit_ill->ill_lock);
20639 					ipif_refrele(dst_ipif);
20640 				}
20641 			}
20642 
20643 		}
20644 		/*
20645 		 * If we are bound to IPIF_NOFAILOVER address, look for
20646 		 * an IRE_CACHE matching the ill.
20647 		 */
20648 send_from_ill:
20649 		if (attach_ill != NULL) {
20650 			ipif_t	*attach_ipif;
20651 
20652 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20653 
20654 			/*
20655 			 * Check if we need an ire that will not be
20656 			 * looked up by anybody else i.e. HIDDEN.
20657 			 */
20658 			if (ill_is_probeonly(attach_ill)) {
20659 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20660 			}
20661 
20662 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20663 			if (attach_ipif == NULL) {
20664 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20665 				goto drop_pkt;
20666 			}
20667 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20668 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20669 			ipif_refrele(attach_ipif);
20670 		} else if (xmit_ill != NULL || (connp != NULL &&
20671 			    connp->conn_xmit_if_ill != NULL)) {
20672 			/*
20673 			 * Mark this packet as originated locally
20674 			 */
20675 			mp->b_prev = mp->b_next = NULL;
20676 			/*
20677 			 * xmit_ill could be NULL if SO_DONTROUTE
20678 			 * is also set.
20679 			 */
20680 			if (xmit_ill == NULL) {
20681 				xmit_ill = conn_get_held_ill(connp,
20682 				    &connp->conn_xmit_if_ill, &err);
20683 				if (err == ILL_LOOKUP_FAILED) {
20684 					if (need_decref)
20685 						CONN_DEC_REF(connp);
20686 					freemsg(first_mp);
20687 					return;
20688 				}
20689 				if (xmit_ill == NULL) {
20690 					if (connp->conn_dontroute)
20691 						goto dontroute;
20692 					goto send_from_ill;
20693 				}
20694 			}
20695 			/*
20696 			 * could be SO_DONTROUTE case also.
20697 			 * check at least one interface is UP as
20698 			 * spcified by this ILL, and then call
20699 			 * ip_newroute_ipif()
20700 			 */
20701 			if (xmit_ill->ill_ipif_up_count > 0) {
20702 				ipif_t *ipif;
20703 
20704 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20705 				if (ipif != NULL) {
20706 					ip_newroute_ipif(q, first_mp, ipif,
20707 					    dst, connp, 0, zoneid);
20708 					ipif_refrele(ipif);
20709 					ip1dbg(("ip_wput: ip_unicast_if\n"));
20710 				}
20711 			} else {
20712 				freemsg(first_mp);
20713 			}
20714 			ill_refrele(xmit_ill);
20715 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20716 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
20717 			if (need_decref)
20718 				CONN_DEC_REF(connp);
20719 			return;
20720 		} else if (ip_nexthop || (connp != NULL &&
20721 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
20722 			if (!ip_nexthop) {
20723 				ip_nexthop = B_TRUE;
20724 				nexthop_addr = connp->conn_nexthop_v4;
20725 			}
20726 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
20727 			    MATCH_IRE_GW;
20728 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
20729 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
20730 		} else {
20731 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20732 		}
20733 		if (!ire) {
20734 			/*
20735 			 * Make sure we don't load spread if this
20736 			 * is IPIF_NOFAILOVER case.
20737 			 */
20738 			if ((attach_ill != NULL) ||
20739 			    (ip_nexthop && !ignore_nexthop)) {
20740 				if (mctl_present) {
20741 					io = (ipsec_out_t *)first_mp->b_rptr;
20742 					ASSERT(first_mp->b_datap->db_type ==
20743 					    M_CTL);
20744 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
20745 				} else {
20746 					ASSERT(mp == first_mp);
20747 					first_mp = allocb(
20748 					    sizeof (ipsec_info_t), BPRI_HI);
20749 					if (first_mp == NULL) {
20750 						first_mp = mp;
20751 						goto drop_pkt;
20752 					}
20753 					first_mp->b_datap->db_type = M_CTL;
20754 					first_mp->b_wptr +=
20755 					    sizeof (ipsec_info_t);
20756 					/* ipsec_out_secure is B_FALSE now */
20757 					bzero(first_mp->b_rptr,
20758 					    sizeof (ipsec_info_t));
20759 					io = (ipsec_out_t *)first_mp->b_rptr;
20760 					io->ipsec_out_type = IPSEC_OUT;
20761 					io->ipsec_out_len =
20762 					    sizeof (ipsec_out_t);
20763 					io->ipsec_out_use_global_policy =
20764 					    B_TRUE;
20765 					first_mp->b_cont = mp;
20766 					mctl_present = B_TRUE;
20767 				}
20768 				if (attach_ill != NULL) {
20769 					io->ipsec_out_ill_index = attach_ill->
20770 					    ill_phyint->phyint_ifindex;
20771 					io->ipsec_out_attach_if = B_TRUE;
20772 				} else {
20773 					io->ipsec_out_ip_nexthop = ip_nexthop;
20774 					io->ipsec_out_nexthop_addr =
20775 					    nexthop_addr;
20776 				}
20777 			}
20778 noirefound:
20779 			/*
20780 			 * Mark this packet as having originated on
20781 			 * this machine.  This will be noted in
20782 			 * ire_add_then_send, which needs to know
20783 			 * whether to run it back through ip_wput or
20784 			 * ip_rput following successful resolution.
20785 			 */
20786 			mp->b_prev = NULL;
20787 			mp->b_next = NULL;
20788 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid);
20789 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20790 			    "ip_wput_end: q %p (%S)", q, "newroute");
20791 			if (attach_ill != NULL)
20792 				ill_refrele(attach_ill);
20793 			if (xmit_ill != NULL)
20794 				ill_refrele(xmit_ill);
20795 			if (need_decref)
20796 				CONN_DEC_REF(connp);
20797 			return;
20798 		}
20799 	}
20800 
20801 	/* We now know where we are going with it. */
20802 
20803 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20804 	    "ip_wput_end: q %p (%S)", q, "end");
20805 
20806 	/*
20807 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20808 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
20809 	 */
20810 	if (ire->ire_flags & RTF_MULTIRT) {
20811 		/*
20812 		 * Force the TTL of multirouted packets if required.
20813 		 * The TTL of such packets is bounded by the
20814 		 * ip_multirt_ttl ndd variable.
20815 		 */
20816 		if ((ip_multirt_ttl > 0) &&
20817 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20818 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20819 			    "(was %d), dst 0x%08x\n",
20820 			    ip_multirt_ttl, ipha->ipha_ttl,
20821 			    ntohl(ire->ire_addr)));
20822 			ipha->ipha_ttl = ip_multirt_ttl;
20823 		}
20824 		/*
20825 		 * At this point, we check to see if there are any pending
20826 		 * unresolved routes. ire_multirt_resolvable()
20827 		 * checks in O(n) that all IRE_OFFSUBNET ire
20828 		 * entries for the packet's destination and
20829 		 * flagged RTF_MULTIRT are currently resolved.
20830 		 * If some remain unresolved, we make a copy
20831 		 * of the current message. It will be used
20832 		 * to initiate additional route resolutions.
20833 		 */
20834 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20835 		    MBLK_GETLABEL(first_mp));
20836 		ip2dbg(("ip_wput[noirefound]: ire %p, "
20837 		    "multirt_need_resolve %d, first_mp %p\n",
20838 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20839 		if (multirt_need_resolve) {
20840 			copy_mp = copymsg(first_mp);
20841 			if (copy_mp != NULL) {
20842 				MULTIRT_DEBUG_TAG(copy_mp);
20843 			}
20844 		}
20845 	}
20846 
20847 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20848 	/*
20849 	 * Try to resolve another multiroute if
20850 	 * ire_multirt_resolvable() deemed it necessary.
20851 	 * At this point, we need to distinguish
20852 	 * multicasts from other packets. For multicasts,
20853 	 * we call ip_newroute_ipif() and request that both
20854 	 * multirouting and setsrc flags are checked.
20855 	 */
20856 	if (copy_mp != NULL) {
20857 		if (CLASSD(dst)) {
20858 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
20859 			if (ipif) {
20860 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
20861 				    RTF_SETSRC | RTF_MULTIRT, zoneid);
20862 				ipif_refrele(ipif);
20863 			} else {
20864 				MULTIRT_DEBUG_UNTAG(copy_mp);
20865 				freemsg(copy_mp);
20866 				copy_mp = NULL;
20867 			}
20868 		} else {
20869 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20870 		}
20871 	}
20872 	if (attach_ill != NULL)
20873 		ill_refrele(attach_ill);
20874 	if (xmit_ill != NULL)
20875 		ill_refrele(xmit_ill);
20876 	if (need_decref)
20877 		CONN_DEC_REF(connp);
20878 	return;
20879 
20880 icmp_parameter_problem:
20881 	/* could not have originated externally */
20882 	ASSERT(mp->b_prev == NULL);
20883 	if (ip_hdr_complete(ipha, zoneid) == 0) {
20884 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
20885 		/* it's the IP header length that's in trouble */
20886 		icmp_param_problem(q, first_mp, 0, zoneid);
20887 		first_mp = NULL;
20888 	}
20889 
20890 drop_pkt:
20891 	ip1dbg(("ip_wput: dropped packet\n"));
20892 	if (ire != NULL)
20893 		ire_refrele(ire);
20894 	if (need_decref)
20895 		CONN_DEC_REF(connp);
20896 	freemsg(first_mp);
20897 	if (attach_ill != NULL)
20898 		ill_refrele(attach_ill);
20899 	if (xmit_ill != NULL)
20900 		ill_refrele(xmit_ill);
20901 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20902 	    "ip_wput_end: q %p (%S)", q, "droppkt");
20903 }
20904 
20905 /*
20906  * If this is a conn_t queue, then we pass in the conn. This includes the
20907  * zoneid.
20908  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
20909  * in which case we use the global zoneid since those are all part of
20910  * the global zone.
20911  */
20912 void
20913 ip_wput(queue_t *q, mblk_t *mp)
20914 {
20915 	if (CONN_Q(q))
20916 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20917 	else
20918 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
20919 }
20920 
20921 /*
20922  *
20923  * The following rules must be observed when accessing any ipif or ill
20924  * that has been cached in the conn. Typically conn_nofailover_ill,
20925  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20926  *
20927  * Access: The ipif or ill pointed to from the conn can be accessed under
20928  * the protection of the conn_lock or after it has been refheld under the
20929  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20930  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20931  * The reason for this is that a concurrent unplumb could actually be
20932  * cleaning up these cached pointers by walking the conns and might have
20933  * finished cleaning up the conn in question. The macros check that an
20934  * unplumb has not yet started on the ipif or ill.
20935  *
20936  * Caching: An ipif or ill pointer may be cached in the conn only after
20937  * making sure that an unplumb has not started. So the caching is done
20938  * while holding both the conn_lock and the ill_lock and after using the
20939  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20940  * flag before starting the cleanup of conns.
20941  *
20942  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20943  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20944  * or a reference to the ipif or a reference to an ire that references the
20945  * ipif. An ipif does not change its ill except for failover/failback. Since
20946  * failover/failback happens only after bringing down the ipif and making sure
20947  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20948  * the above holds.
20949  */
20950 ipif_t *
20951 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20952 {
20953 	ipif_t	*ipif;
20954 	ill_t	*ill;
20955 
20956 	*err = 0;
20957 	rw_enter(&ill_g_lock, RW_READER);
20958 	mutex_enter(&connp->conn_lock);
20959 	ipif = *ipifp;
20960 	if (ipif != NULL) {
20961 		ill = ipif->ipif_ill;
20962 		mutex_enter(&ill->ill_lock);
20963 		if (IPIF_CAN_LOOKUP(ipif)) {
20964 			ipif_refhold_locked(ipif);
20965 			mutex_exit(&ill->ill_lock);
20966 			mutex_exit(&connp->conn_lock);
20967 			rw_exit(&ill_g_lock);
20968 			return (ipif);
20969 		} else {
20970 			*err = IPIF_LOOKUP_FAILED;
20971 		}
20972 		mutex_exit(&ill->ill_lock);
20973 	}
20974 	mutex_exit(&connp->conn_lock);
20975 	rw_exit(&ill_g_lock);
20976 	return (NULL);
20977 }
20978 
20979 ill_t *
20980 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20981 {
20982 	ill_t	*ill;
20983 
20984 	*err = 0;
20985 	mutex_enter(&connp->conn_lock);
20986 	ill = *illp;
20987 	if (ill != NULL) {
20988 		mutex_enter(&ill->ill_lock);
20989 		if (ILL_CAN_LOOKUP(ill)) {
20990 			ill_refhold_locked(ill);
20991 			mutex_exit(&ill->ill_lock);
20992 			mutex_exit(&connp->conn_lock);
20993 			return (ill);
20994 		} else {
20995 			*err = ILL_LOOKUP_FAILED;
20996 		}
20997 		mutex_exit(&ill->ill_lock);
20998 	}
20999 	mutex_exit(&connp->conn_lock);
21000 	return (NULL);
21001 }
21002 
21003 static int
21004 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21005 {
21006 	ill_t	*ill;
21007 
21008 	ill = ipif->ipif_ill;
21009 	mutex_enter(&connp->conn_lock);
21010 	mutex_enter(&ill->ill_lock);
21011 	if (IPIF_CAN_LOOKUP(ipif)) {
21012 		*ipifp = ipif;
21013 		mutex_exit(&ill->ill_lock);
21014 		mutex_exit(&connp->conn_lock);
21015 		return (0);
21016 	}
21017 	mutex_exit(&ill->ill_lock);
21018 	mutex_exit(&connp->conn_lock);
21019 	return (IPIF_LOOKUP_FAILED);
21020 }
21021 
21022 /*
21023  * This is called if the outbound datagram needs fragmentation.
21024  *
21025  * NOTE : This function does not ire_refrele the ire argument passed in.
21026  */
21027 static void
21028 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid)
21029 {
21030 	ipha_t		*ipha;
21031 	mblk_t		*mp;
21032 	uint32_t	v_hlen_tos_len;
21033 	uint32_t	max_frag;
21034 	uint32_t	frag_flag;
21035 	boolean_t	dont_use;
21036 
21037 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21038 		mp = ipsec_mp->b_cont;
21039 	} else {
21040 		mp = ipsec_mp;
21041 	}
21042 
21043 	ipha = (ipha_t *)mp->b_rptr;
21044 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21045 
21046 #ifdef	_BIG_ENDIAN
21047 #define	V_HLEN	(v_hlen_tos_len >> 24)
21048 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21049 #else
21050 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21051 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21052 #endif
21053 
21054 #ifndef SPEED_BEFORE_SAFETY
21055 	/*
21056 	 * Check that ipha_length is consistent with
21057 	 * the mblk length
21058 	 */
21059 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21060 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21061 		    LENGTH, msgdsize(mp)));
21062 		freemsg(ipsec_mp);
21063 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21064 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21065 		    "packet length mismatch");
21066 		return;
21067 	}
21068 #endif
21069 	/*
21070 	 * Don't use frag_flag if pre-built packet or source
21071 	 * routed or if multicast (since multicast packets do not solicit
21072 	 * ICMP "packet too big" messages). Get the values of
21073 	 * max_frag and frag_flag atomically by acquiring the
21074 	 * ire_lock.
21075 	 */
21076 	mutex_enter(&ire->ire_lock);
21077 	max_frag = ire->ire_max_frag;
21078 	frag_flag = ire->ire_frag_flag;
21079 	mutex_exit(&ire->ire_lock);
21080 
21081 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21082 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21083 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21084 
21085 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21086 	    (dont_use ? 0 : frag_flag), zoneid);
21087 }
21088 
21089 /*
21090  * Used for deciding the MSS size for the upper layer. Thus
21091  * we need to check the outbound policy values in the conn.
21092  */
21093 int
21094 conn_ipsec_length(conn_t *connp)
21095 {
21096 	ipsec_latch_t *ipl;
21097 
21098 	ipl = connp->conn_latch;
21099 	if (ipl == NULL)
21100 		return (0);
21101 
21102 	if (ipl->ipl_out_policy == NULL)
21103 		return (0);
21104 
21105 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21106 }
21107 
21108 /*
21109  * Returns an estimate of the IPSEC headers size. This is used if
21110  * we don't want to call into IPSEC to get the exact size.
21111  */
21112 int
21113 ipsec_out_extra_length(mblk_t *ipsec_mp)
21114 {
21115 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21116 	ipsec_action_t *a;
21117 
21118 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21119 	if (!io->ipsec_out_secure)
21120 		return (0);
21121 
21122 	a = io->ipsec_out_act;
21123 
21124 	if (a == NULL) {
21125 		ASSERT(io->ipsec_out_policy != NULL);
21126 		a = io->ipsec_out_policy->ipsp_act;
21127 	}
21128 	ASSERT(a != NULL);
21129 
21130 	return (a->ipa_ovhd);
21131 }
21132 
21133 /*
21134  * Returns an estimate of the IPSEC headers size. This is used if
21135  * we don't want to call into IPSEC to get the exact size.
21136  */
21137 int
21138 ipsec_in_extra_length(mblk_t *ipsec_mp)
21139 {
21140 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21141 	ipsec_action_t *a;
21142 
21143 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21144 
21145 	a = ii->ipsec_in_action;
21146 	return (a == NULL ? 0 : a->ipa_ovhd);
21147 }
21148 
21149 /*
21150  * If there are any source route options, return the true final
21151  * destination. Otherwise, return the destination.
21152  */
21153 ipaddr_t
21154 ip_get_dst(ipha_t *ipha)
21155 {
21156 	ipoptp_t	opts;
21157 	uchar_t		*opt;
21158 	uint8_t		optval;
21159 	uint8_t		optlen;
21160 	ipaddr_t	dst;
21161 	uint32_t off;
21162 
21163 	dst = ipha->ipha_dst;
21164 
21165 	if (IS_SIMPLE_IPH(ipha))
21166 		return (dst);
21167 
21168 	for (optval = ipoptp_first(&opts, ipha);
21169 	    optval != IPOPT_EOL;
21170 	    optval = ipoptp_next(&opts)) {
21171 		opt = opts.ipoptp_cur;
21172 		optlen = opts.ipoptp_len;
21173 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21174 		switch (optval) {
21175 		case IPOPT_SSRR:
21176 		case IPOPT_LSRR:
21177 			off = opt[IPOPT_OFFSET];
21178 			/*
21179 			 * If one of the conditions is true, it means
21180 			 * end of options and dst already has the right
21181 			 * value.
21182 			 */
21183 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21184 				off = optlen - IP_ADDR_LEN;
21185 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21186 			}
21187 			return (dst);
21188 		default:
21189 			break;
21190 		}
21191 	}
21192 
21193 	return (dst);
21194 }
21195 
21196 mblk_t *
21197 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21198     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21199 {
21200 	ipsec_out_t	*io;
21201 	mblk_t		*first_mp;
21202 	boolean_t policy_present;
21203 
21204 	first_mp = mp;
21205 	if (mp->b_datap->db_type == M_CTL) {
21206 		io = (ipsec_out_t *)first_mp->b_rptr;
21207 		/*
21208 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21209 		 *
21210 		 * 1) There is per-socket policy (including cached global
21211 		 *    policy).
21212 		 * 2) There is no per-socket policy, but it is
21213 		 *    a multicast packet that needs to go out
21214 		 *    on a specific interface. This is the case
21215 		 *    where (ip_wput and ip_wput_multicast) attaches
21216 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21217 		 *
21218 		 * In case (2) we check with global policy to
21219 		 * see if there is a match and set the ill_index
21220 		 * appropriately so that we can lookup the ire
21221 		 * properly in ip_wput_ipsec_out.
21222 		 */
21223 
21224 		/*
21225 		 * ipsec_out_use_global_policy is set to B_FALSE
21226 		 * in ipsec_in_to_out(). Refer to that function for
21227 		 * details.
21228 		 */
21229 		if ((io->ipsec_out_latch == NULL) &&
21230 		    (io->ipsec_out_use_global_policy)) {
21231 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21232 				    ire, connp, unspec_src, zoneid));
21233 		}
21234 		if (!io->ipsec_out_secure) {
21235 			/*
21236 			 * If this is not a secure packet, drop
21237 			 * the IPSEC_OUT mp and treat it as a clear
21238 			 * packet. This happens when we are sending
21239 			 * a ICMP reply back to a clear packet. See
21240 			 * ipsec_in_to_out() for details.
21241 			 */
21242 			mp = first_mp->b_cont;
21243 			freeb(first_mp);
21244 		}
21245 		return (mp);
21246 	}
21247 	/*
21248 	 * See whether we need to attach a global policy here. We
21249 	 * don't depend on the conn (as it could be null) for deciding
21250 	 * what policy this datagram should go through because it
21251 	 * should have happened in ip_wput if there was some
21252 	 * policy. This normally happens for connections which are not
21253 	 * fully bound preventing us from caching policies in
21254 	 * ip_bind. Packets coming from the TCP listener/global queue
21255 	 * - which are non-hard_bound - could also be affected by
21256 	 * applying policy here.
21257 	 *
21258 	 * If this packet is coming from tcp global queue or listener,
21259 	 * we will be applying policy here.  This may not be *right*
21260 	 * if these packets are coming from the detached connection as
21261 	 * it could have gone in clear before. This happens only if a
21262 	 * TCP connection started when there is no policy and somebody
21263 	 * added policy before it became detached. Thus packets of the
21264 	 * detached connection could go out secure and the other end
21265 	 * would drop it because it will be expecting in clear. The
21266 	 * converse is not true i.e if somebody starts a TCP
21267 	 * connection and deletes the policy, all the packets will
21268 	 * still go out with the policy that existed before deleting
21269 	 * because ip_unbind sends up policy information which is used
21270 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21271 	 * TCP to attach a dummy IPSEC_OUT and set
21272 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21273 	 * affect performance for normal cases, we are not doing it.
21274 	 * Thus, set policy before starting any TCP connections.
21275 	 *
21276 	 * NOTE - We might apply policy even for a hard bound connection
21277 	 * - for which we cached policy in ip_bind - if somebody added
21278 	 * global policy after we inherited the policy in ip_bind.
21279 	 * This means that the packets that were going out in clear
21280 	 * previously would start going secure and hence get dropped
21281 	 * on the other side. To fix this, TCP attaches a dummy
21282 	 * ipsec_out and make sure that we don't apply global policy.
21283 	 */
21284 	if (ipha != NULL)
21285 		policy_present = ipsec_outbound_v4_policy_present;
21286 	else
21287 		policy_present = ipsec_outbound_v6_policy_present;
21288 	if (!policy_present)
21289 		return (mp);
21290 
21291 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21292 		    zoneid));
21293 }
21294 
21295 ire_t *
21296 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21297 {
21298 	ipaddr_t addr;
21299 	ire_t *save_ire;
21300 	irb_t *irb;
21301 	ill_group_t *illgrp;
21302 	int	err;
21303 
21304 	save_ire = ire;
21305 	addr = ire->ire_addr;
21306 
21307 	ASSERT(ire->ire_type == IRE_BROADCAST);
21308 
21309 	illgrp = connp->conn_outgoing_ill->ill_group;
21310 	if (illgrp == NULL) {
21311 		*conn_outgoing_ill = conn_get_held_ill(connp,
21312 		    &connp->conn_outgoing_ill, &err);
21313 		if (err == ILL_LOOKUP_FAILED) {
21314 			ire_refrele(save_ire);
21315 			return (NULL);
21316 		}
21317 		return (save_ire);
21318 	}
21319 	/*
21320 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21321 	 * If it is part of the group, we need to send on the ire
21322 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21323 	 * to this group. This is okay as IP_BOUND_IF really means
21324 	 * any ill in the group. We depend on the fact that the
21325 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21326 	 * if such an ire exists. This is possible only if you have
21327 	 * at least one ill in the group that has not failed.
21328 	 *
21329 	 * First get to the ire that matches the address and group.
21330 	 *
21331 	 * We don't look for an ire with a matching zoneid because a given zone
21332 	 * won't always have broadcast ires on all ills in the group.
21333 	 */
21334 	irb = ire->ire_bucket;
21335 	rw_enter(&irb->irb_lock, RW_READER);
21336 	if (ire->ire_marks & IRE_MARK_NORECV) {
21337 		/*
21338 		 * If the current zone only has an ire broadcast for this
21339 		 * address marked NORECV, the ire we want is ahead in the
21340 		 * bucket, so we look it up deliberately ignoring the zoneid.
21341 		 */
21342 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21343 			if (ire->ire_addr != addr)
21344 				continue;
21345 			/* skip over deleted ires */
21346 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21347 				continue;
21348 		}
21349 	}
21350 	while (ire != NULL) {
21351 		/*
21352 		 * If a new interface is coming up, we could end up
21353 		 * seeing the loopback ire and the non-loopback ire
21354 		 * may not have been added yet. So check for ire_stq
21355 		 */
21356 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21357 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21358 			break;
21359 		}
21360 		ire = ire->ire_next;
21361 	}
21362 	if (ire != NULL && ire->ire_addr == addr &&
21363 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21364 		IRE_REFHOLD(ire);
21365 		rw_exit(&irb->irb_lock);
21366 		ire_refrele(save_ire);
21367 		*conn_outgoing_ill = ire_to_ill(ire);
21368 		/*
21369 		 * Refhold the ill to make the conn_outgoing_ill
21370 		 * independent of the ire. ip_wput_ire goes in a loop
21371 		 * and may refrele the ire. Since we have an ire at this
21372 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21373 		 */
21374 		ill_refhold(*conn_outgoing_ill);
21375 		return (ire);
21376 	}
21377 	rw_exit(&irb->irb_lock);
21378 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21379 	/*
21380 	 * If we can't find a suitable ire, return the original ire.
21381 	 */
21382 	return (save_ire);
21383 }
21384 
21385 /*
21386  * This function does the ire_refrele of the ire passed in as the
21387  * argument. As this function looks up more ires i.e broadcast ires,
21388  * it needs to REFRELE them. Currently, for simplicity we don't
21389  * differentiate the one passed in and looked up here. We always
21390  * REFRELE.
21391  * IPQoS Notes:
21392  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21393  * IPSec packets are done in ipsec_out_process.
21394  *
21395  */
21396 void
21397 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21398     zoneid_t zoneid)
21399 {
21400 	ipha_t		*ipha;
21401 #define	rptr	((uchar_t *)ipha)
21402 	queue_t		*stq;
21403 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21404 	uint32_t	v_hlen_tos_len;
21405 	uint32_t	ttl_protocol;
21406 	ipaddr_t	src;
21407 	ipaddr_t	dst;
21408 	uint32_t	cksum;
21409 	ipaddr_t	orig_src;
21410 	ire_t		*ire1;
21411 	mblk_t		*next_mp;
21412 	uint_t		hlen;
21413 	uint16_t	*up;
21414 	uint32_t	max_frag = ire->ire_max_frag;
21415 	ill_t		*ill = ire_to_ill(ire);
21416 	int		clusterwide;
21417 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21418 	int		ipsec_len;
21419 	mblk_t		*first_mp;
21420 	ipsec_out_t	*io;
21421 	boolean_t	conn_dontroute;		/* conn value for multicast */
21422 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21423 	boolean_t	multicast_forward;	/* Should we forward ? */
21424 	boolean_t	unspec_src;
21425 	ill_t		*conn_outgoing_ill = NULL;
21426 	ill_t		*ire_ill;
21427 	ill_t		*ire1_ill;
21428 	ill_t		*out_ill;
21429 	uint32_t 	ill_index = 0;
21430 	boolean_t	multirt_send = B_FALSE;
21431 	int		err;
21432 	ipxmit_state_t	pktxmit_state;
21433 
21434 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21435 	    "ip_wput_ire_start: q %p", q);
21436 
21437 	multicast_forward = B_FALSE;
21438 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21439 
21440 	if (ire->ire_flags & RTF_MULTIRT) {
21441 		/*
21442 		 * Multirouting case. The bucket where ire is stored
21443 		 * probably holds other RTF_MULTIRT flagged ire
21444 		 * to the destination. In this call to ip_wput_ire,
21445 		 * we attempt to send the packet through all
21446 		 * those ires. Thus, we first ensure that ire is the
21447 		 * first RTF_MULTIRT ire in the bucket,
21448 		 * before walking the ire list.
21449 		 */
21450 		ire_t *first_ire;
21451 		irb_t *irb = ire->ire_bucket;
21452 		ASSERT(irb != NULL);
21453 
21454 		/* Make sure we do not omit any multiroute ire. */
21455 		IRB_REFHOLD(irb);
21456 		for (first_ire = irb->irb_ire;
21457 		    first_ire != NULL;
21458 		    first_ire = first_ire->ire_next) {
21459 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21460 			    (first_ire->ire_addr == ire->ire_addr) &&
21461 			    !(first_ire->ire_marks &
21462 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21463 				break;
21464 		}
21465 
21466 		if ((first_ire != NULL) && (first_ire != ire)) {
21467 			IRE_REFHOLD(first_ire);
21468 			ire_refrele(ire);
21469 			ire = first_ire;
21470 			ill = ire_to_ill(ire);
21471 		}
21472 		IRB_REFRELE(irb);
21473 	}
21474 
21475 	/*
21476 	 * conn_outgoing_ill is used only in the broadcast loop.
21477 	 * for performance we don't grab the mutexs in the fastpath
21478 	 */
21479 	if ((connp != NULL) &&
21480 	    (connp->conn_xmit_if_ill == NULL) &&
21481 	    (ire->ire_type == IRE_BROADCAST) &&
21482 	    ((connp->conn_nofailover_ill != NULL) ||
21483 	    (connp->conn_outgoing_ill != NULL))) {
21484 		/*
21485 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21486 		 * option. So, see if this endpoint is bound to a
21487 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21488 		 * that if the interface is failed, we will still send
21489 		 * the packet on the same ill which is what we want.
21490 		 */
21491 		conn_outgoing_ill = conn_get_held_ill(connp,
21492 		    &connp->conn_nofailover_ill, &err);
21493 		if (err == ILL_LOOKUP_FAILED) {
21494 			ire_refrele(ire);
21495 			freemsg(mp);
21496 			return;
21497 		}
21498 		if (conn_outgoing_ill == NULL) {
21499 			/*
21500 			 * Choose a good ill in the group to send the
21501 			 * packets on.
21502 			 */
21503 			ire = conn_set_outgoing_ill(connp, ire,
21504 			    &conn_outgoing_ill);
21505 			if (ire == NULL) {
21506 				freemsg(mp);
21507 				return;
21508 			}
21509 		}
21510 	}
21511 
21512 	if (mp->b_datap->db_type != M_CTL) {
21513 		ipha = (ipha_t *)mp->b_rptr;
21514 	} else {
21515 		io = (ipsec_out_t *)mp->b_rptr;
21516 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21517 		ASSERT(zoneid == io->ipsec_out_zoneid);
21518 		ASSERT(zoneid != ALL_ZONES);
21519 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21520 		dst = ipha->ipha_dst;
21521 		/*
21522 		 * For the multicast case, ipsec_out carries conn_dontroute and
21523 		 * conn_multicast_loop as conn may not be available here. We
21524 		 * need this for multicast loopback and forwarding which is done
21525 		 * later in the code.
21526 		 */
21527 		if (CLASSD(dst)) {
21528 			conn_dontroute = io->ipsec_out_dontroute;
21529 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21530 			/*
21531 			 * If conn_dontroute is not set or conn_multicast_loop
21532 			 * is set, we need to do forwarding/loopback. For
21533 			 * datagrams from ip_wput_multicast, conn_dontroute is
21534 			 * set to B_TRUE and conn_multicast_loop is set to
21535 			 * B_FALSE so that we neither do forwarding nor
21536 			 * loopback.
21537 			 */
21538 			if (!conn_dontroute || conn_multicast_loop)
21539 				multicast_forward = B_TRUE;
21540 		}
21541 	}
21542 
21543 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21544 	    ire->ire_zoneid != ALL_ZONES) {
21545 		/*
21546 		 * When a zone sends a packet to another zone, we try to deliver
21547 		 * the packet under the same conditions as if the destination
21548 		 * was a real node on the network. To do so, we look for a
21549 		 * matching route in the forwarding table.
21550 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21551 		 * ip_newroute() does.
21552 		 * Note that IRE_LOCAL are special, since they are used
21553 		 * when the zoneid doesn't match in some cases. This means that
21554 		 * we need to handle ipha_src differently since ire_src_addr
21555 		 * belongs to the receiving zone instead of the sending zone.
21556 		 * When ip_restrict_interzone_loopback is set, then
21557 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
21558 		 * for loopback between zones when the logical "Ethernet" would
21559 		 * have looped them back.
21560 		 */
21561 		ire_t *src_ire;
21562 
21563 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21564 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21565 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
21566 		if (src_ire != NULL &&
21567 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
21568 		    (!ip_restrict_interzone_loopback ||
21569 		    ire_local_same_ill_group(ire, src_ire))) {
21570 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21571 				ipha->ipha_src = src_ire->ire_src_addr;
21572 			ire_refrele(src_ire);
21573 		} else {
21574 			ire_refrele(ire);
21575 			if (conn_outgoing_ill != NULL)
21576 				ill_refrele(conn_outgoing_ill);
21577 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
21578 			if (src_ire != NULL) {
21579 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21580 					ire_refrele(src_ire);
21581 					freemsg(mp);
21582 					return;
21583 				}
21584 				ire_refrele(src_ire);
21585 			}
21586 			if (ip_hdr_complete(ipha, zoneid)) {
21587 				/* Failed */
21588 				freemsg(mp);
21589 				return;
21590 			}
21591 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid);
21592 			return;
21593 		}
21594 	}
21595 
21596 	if (mp->b_datap->db_type == M_CTL ||
21597 	    ipsec_outbound_v4_policy_present) {
21598 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21599 		    unspec_src, zoneid);
21600 		if (mp == NULL) {
21601 			ire_refrele(ire);
21602 			if (conn_outgoing_ill != NULL)
21603 				ill_refrele(conn_outgoing_ill);
21604 			return;
21605 		}
21606 	}
21607 
21608 	first_mp = mp;
21609 	ipsec_len = 0;
21610 
21611 	if (first_mp->b_datap->db_type == M_CTL) {
21612 		io = (ipsec_out_t *)first_mp->b_rptr;
21613 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21614 		mp = first_mp->b_cont;
21615 		ipsec_len = ipsec_out_extra_length(first_mp);
21616 		ASSERT(ipsec_len >= 0);
21617 		/* We already picked up the zoneid from the M_CTL above */
21618 		ASSERT(zoneid == io->ipsec_out_zoneid);
21619 		ASSERT(zoneid != ALL_ZONES);
21620 
21621 		/*
21622 		 * Drop M_CTL here if IPsec processing is not needed.
21623 		 * (Non-IPsec use of M_CTL extracted any information it
21624 		 * needed above).
21625 		 */
21626 		if (ipsec_len == 0) {
21627 			freeb(first_mp);
21628 			first_mp = mp;
21629 		}
21630 	}
21631 
21632 	/*
21633 	 * Fast path for ip_wput_ire
21634 	 */
21635 
21636 	ipha = (ipha_t *)mp->b_rptr;
21637 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21638 	dst = ipha->ipha_dst;
21639 
21640 	/*
21641 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21642 	 * if the socket is a SOCK_RAW type. The transport checksum should
21643 	 * be provided in the pre-built packet, so we don't need to compute it.
21644 	 * Also, other application set flags, like DF, should not be altered.
21645 	 * Other transport MUST pass down zero.
21646 	 */
21647 	ip_hdr_included = ipha->ipha_ident;
21648 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21649 
21650 	if (CLASSD(dst)) {
21651 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
21652 		    ntohl(dst),
21653 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
21654 		    ntohl(ire->ire_addr)));
21655 	}
21656 
21657 /* Macros to extract header fields from data already in registers */
21658 #ifdef	_BIG_ENDIAN
21659 #define	V_HLEN	(v_hlen_tos_len >> 24)
21660 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21661 #define	PROTO	(ttl_protocol & 0xFF)
21662 #else
21663 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21664 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21665 #define	PROTO	(ttl_protocol >> 8)
21666 #endif
21667 
21668 
21669 	orig_src = src = ipha->ipha_src;
21670 	/* (The loop back to "another" is explained down below.) */
21671 another:;
21672 	/*
21673 	 * Assign an ident value for this packet.  We assign idents on
21674 	 * a per destination basis out of the IRE.  There could be
21675 	 * other threads targeting the same destination, so we have to
21676 	 * arrange for a atomic increment.  Note that we use a 32-bit
21677 	 * atomic add because it has better performance than its
21678 	 * 16-bit sibling.
21679 	 *
21680 	 * If running in cluster mode and if the source address
21681 	 * belongs to a replicated service then vector through
21682 	 * cl_inet_ipident vector to allocate ip identifier
21683 	 * NOTE: This is a contract private interface with the
21684 	 * clustering group.
21685 	 */
21686 	clusterwide = 0;
21687 	if (cl_inet_ipident) {
21688 		ASSERT(cl_inet_isclusterwide);
21689 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21690 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
21691 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
21692 			    AF_INET, (uint8_t *)(uintptr_t)src,
21693 			    (uint8_t *)(uintptr_t)dst);
21694 			clusterwide = 1;
21695 		}
21696 	}
21697 	if (!clusterwide) {
21698 		ipha->ipha_ident =
21699 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
21700 	}
21701 
21702 #ifndef _BIG_ENDIAN
21703 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21704 #endif
21705 
21706 	/*
21707 	 * Set source address unless sent on an ill or conn_unspec_src is set.
21708 	 * This is needed to obey conn_unspec_src when packets go through
21709 	 * ip_newroute + arp.
21710 	 * Assumes ip_newroute{,_multi} sets the source address as well.
21711 	 */
21712 	if (src == INADDR_ANY && !unspec_src) {
21713 		/*
21714 		 * Assign the appropriate source address from the IRE if none
21715 		 * was specified.
21716 		 */
21717 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
21718 
21719 		/*
21720 		 * With IP multipathing, broadcast packets are sent on the ire
21721 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
21722 		 * the group. However, this ire might not be in the same zone so
21723 		 * we can't always use its source address. We look for a
21724 		 * broadcast ire in the same group and in the right zone.
21725 		 */
21726 		if (ire->ire_type == IRE_BROADCAST &&
21727 		    ire->ire_zoneid != zoneid) {
21728 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
21729 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
21730 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
21731 			if (src_ire != NULL) {
21732 				src = src_ire->ire_src_addr;
21733 				ire_refrele(src_ire);
21734 			} else {
21735 				ire_refrele(ire);
21736 				if (conn_outgoing_ill != NULL)
21737 					ill_refrele(conn_outgoing_ill);
21738 				freemsg(first_mp);
21739 				BUMP_MIB(&ip_mib, ipOutDiscards);
21740 				return;
21741 			}
21742 		} else {
21743 			src = ire->ire_src_addr;
21744 		}
21745 
21746 		if (connp == NULL) {
21747 			ip1dbg(("ip_wput_ire: no connp and no src "
21748 			    "address for dst 0x%x, using src 0x%x\n",
21749 			    ntohl(dst),
21750 			    ntohl(src)));
21751 		}
21752 		ipha->ipha_src = src;
21753 	}
21754 	stq = ire->ire_stq;
21755 
21756 	/*
21757 	 * We only allow ire chains for broadcasts since there will
21758 	 * be multiple IRE_CACHE entries for the same multicast
21759 	 * address (one per ipif).
21760 	 */
21761 	next_mp = NULL;
21762 
21763 	/* broadcast packet */
21764 	if (ire->ire_type == IRE_BROADCAST)
21765 		goto broadcast;
21766 
21767 	/* loopback ? */
21768 	if (stq == NULL)
21769 		goto nullstq;
21770 
21771 	/* The ill_index for outbound ILL */
21772 	ill_index = Q_TO_INDEX(stq);
21773 
21774 	BUMP_MIB(&ip_mib, ipOutRequests);
21775 	ttl_protocol = ((uint16_t *)ipha)[4];
21776 
21777 	/* pseudo checksum (do it in parts for IP header checksum) */
21778 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21779 
21780 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
21781 		queue_t *dev_q = stq->q_next;
21782 
21783 		/* flow controlled */
21784 		if ((dev_q->q_next || dev_q->q_first) &&
21785 		    !canput(dev_q))
21786 			goto blocked;
21787 		if ((PROTO == IPPROTO_UDP) &&
21788 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21789 			hlen = (V_HLEN & 0xF) << 2;
21790 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21791 			if (*up != 0) {
21792 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
21793 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
21794 				/* Software checksum? */
21795 				if (DB_CKSUMFLAGS(mp) == 0) {
21796 					IP_STAT(ip_out_sw_cksum);
21797 					IP_STAT_UPDATE(
21798 					    ip_udp_out_sw_cksum_bytes,
21799 					    LENGTH - hlen);
21800 				}
21801 			}
21802 		}
21803 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
21804 		hlen = (V_HLEN & 0xF) << 2;
21805 		if (PROTO == IPPROTO_TCP) {
21806 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21807 			/*
21808 			 * The packet header is processed once and for all, even
21809 			 * in the multirouting case. We disable hardware
21810 			 * checksum if the packet is multirouted, as it will be
21811 			 * replicated via several interfaces, and not all of
21812 			 * them may have this capability.
21813 			 */
21814 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
21815 			    LENGTH, max_frag, ipsec_len, cksum);
21816 			/* Software checksum? */
21817 			if (DB_CKSUMFLAGS(mp) == 0) {
21818 				IP_STAT(ip_out_sw_cksum);
21819 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21820 				    LENGTH - hlen);
21821 			}
21822 		} else {
21823 			sctp_hdr_t	*sctph;
21824 
21825 			ASSERT(PROTO == IPPROTO_SCTP);
21826 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21827 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21828 			/*
21829 			 * Zero out the checksum field to ensure proper
21830 			 * checksum calculation.
21831 			 */
21832 			sctph->sh_chksum = 0;
21833 #ifdef	DEBUG
21834 			if (!skip_sctp_cksum)
21835 #endif
21836 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21837 		}
21838 	}
21839 
21840 	/*
21841 	 * If this is a multicast packet and originated from ip_wput
21842 	 * we need to do loopback and forwarding checks. If it comes
21843 	 * from ip_wput_multicast, we SHOULD not do this.
21844 	 */
21845 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
21846 
21847 	/* checksum */
21848 	cksum += ttl_protocol;
21849 
21850 	/* fragment the packet */
21851 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
21852 		goto fragmentit;
21853 	/*
21854 	 * Don't use frag_flag if packet is pre-built or source
21855 	 * routed or if multicast (since multicast packets do
21856 	 * not solicit ICMP "packet too big" messages).
21857 	 */
21858 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21859 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21860 	    !ip_source_route_included(ipha)) &&
21861 	    !CLASSD(ipha->ipha_dst))
21862 		ipha->ipha_fragment_offset_and_flags |=
21863 		    htons(ire->ire_frag_flag);
21864 
21865 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21866 		/* calculate IP header checksum */
21867 		cksum += ipha->ipha_ident;
21868 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
21869 		cksum += ipha->ipha_fragment_offset_and_flags;
21870 
21871 		/* IP options present */
21872 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21873 		if (hlen)
21874 			goto checksumoptions;
21875 
21876 		/* calculate hdr checksum */
21877 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21878 		cksum = ~(cksum + (cksum >> 16));
21879 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
21880 	}
21881 	if (ipsec_len != 0) {
21882 		/*
21883 		 * We will do the rest of the processing after
21884 		 * we come back from IPSEC in ip_wput_ipsec_out().
21885 		 */
21886 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
21887 
21888 		io = (ipsec_out_t *)first_mp->b_rptr;
21889 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
21890 				ill_phyint->phyint_ifindex;
21891 
21892 		ipsec_out_process(q, first_mp, ire, ill_index);
21893 		ire_refrele(ire);
21894 		if (conn_outgoing_ill != NULL)
21895 			ill_refrele(conn_outgoing_ill);
21896 		return;
21897 	}
21898 
21899 	/*
21900 	 * In most cases, the emission loop below is entered only
21901 	 * once. Only in the case where the ire holds the
21902 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
21903 	 * flagged ires in the bucket, and send the packet
21904 	 * through all crossed RTF_MULTIRT routes.
21905 	 */
21906 	if (ire->ire_flags & RTF_MULTIRT) {
21907 		multirt_send = B_TRUE;
21908 	}
21909 	do {
21910 		if (multirt_send) {
21911 			irb_t *irb;
21912 			/*
21913 			 * We are in a multiple send case, need to get
21914 			 * the next ire and make a duplicate of the packet.
21915 			 * ire1 holds here the next ire to process in the
21916 			 * bucket. If multirouting is expected,
21917 			 * any non-RTF_MULTIRT ire that has the
21918 			 * right destination address is ignored.
21919 			 */
21920 			irb = ire->ire_bucket;
21921 			ASSERT(irb != NULL);
21922 
21923 			IRB_REFHOLD(irb);
21924 			for (ire1 = ire->ire_next;
21925 			    ire1 != NULL;
21926 			    ire1 = ire1->ire_next) {
21927 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21928 					continue;
21929 				if (ire1->ire_addr != ire->ire_addr)
21930 					continue;
21931 				if (ire1->ire_marks &
21932 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21933 					continue;
21934 
21935 				/* Got one */
21936 				IRE_REFHOLD(ire1);
21937 				break;
21938 			}
21939 			IRB_REFRELE(irb);
21940 
21941 			if (ire1 != NULL) {
21942 				next_mp = copyb(mp);
21943 				if ((next_mp == NULL) ||
21944 				    ((mp->b_cont != NULL) &&
21945 				    ((next_mp->b_cont =
21946 				    dupmsg(mp->b_cont)) == NULL))) {
21947 					freemsg(next_mp);
21948 					next_mp = NULL;
21949 					ire_refrele(ire1);
21950 					ire1 = NULL;
21951 				}
21952 			}
21953 
21954 			/* Last multiroute ire; don't loop anymore. */
21955 			if (ire1 == NULL) {
21956 				multirt_send = B_FALSE;
21957 			}
21958 		}
21959 
21960 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
21961 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
21962 		    mblk_t *, mp);
21963 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
21964 		    MSG_FWCOOKED_OUT, NULL, ire->ire_ipif->ipif_ill,
21965 		    ipha, mp, mp);
21966 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21967 		if (mp == NULL)
21968 			goto release_ire_and_ill;
21969 
21970 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
21971 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
21972 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
21973 		if ((pktxmit_state == SEND_FAILED) ||
21974 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
21975 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
21976 			    "- packet dropped\n"));
21977 release_ire_and_ill:
21978 			ire_refrele(ire);
21979 			if (next_mp != NULL) {
21980 				freemsg(next_mp);
21981 				ire_refrele(ire1);
21982 			}
21983 			if (conn_outgoing_ill != NULL)
21984 				ill_refrele(conn_outgoing_ill);
21985 			return;
21986 		}
21987 
21988 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21989 		    "ip_wput_ire_end: q %p (%S)",
21990 		    q, "last copy out");
21991 		IRE_REFRELE(ire);
21992 
21993 		if (multirt_send) {
21994 			ASSERT(ire1);
21995 			/*
21996 			 * Proceed with the next RTF_MULTIRT ire,
21997 			 * Also set up the send-to queue accordingly.
21998 			 */
21999 			ire = ire1;
22000 			ire1 = NULL;
22001 			stq = ire->ire_stq;
22002 			mp = next_mp;
22003 			next_mp = NULL;
22004 			ipha = (ipha_t *)mp->b_rptr;
22005 			ill_index = Q_TO_INDEX(stq);
22006 		}
22007 	} while (multirt_send);
22008 	if (conn_outgoing_ill != NULL)
22009 		ill_refrele(conn_outgoing_ill);
22010 	return;
22011 
22012 	/*
22013 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22014 	 */
22015 broadcast:
22016 	{
22017 		/*
22018 		 * Avoid broadcast storms by setting the ttl to 1
22019 		 * for broadcasts. This parameter can be set
22020 		 * via ndd, so make sure that for the SO_DONTROUTE
22021 		 * case that ipha_ttl is always set to 1.
22022 		 * In the event that we are replying to incoming
22023 		 * ICMP packets, conn could be NULL.
22024 		 */
22025 		if ((connp != NULL) && connp->conn_dontroute)
22026 			ipha->ipha_ttl = 1;
22027 		else
22028 			ipha->ipha_ttl = ip_broadcast_ttl;
22029 
22030 		/*
22031 		 * Note that we are not doing a IRB_REFHOLD here.
22032 		 * Actually we don't care if the list changes i.e
22033 		 * if somebody deletes an IRE from the list while
22034 		 * we drop the lock, the next time we come around
22035 		 * ire_next will be NULL and hence we won't send
22036 		 * out multiple copies which is fine.
22037 		 */
22038 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22039 		ire1 = ire->ire_next;
22040 		if (conn_outgoing_ill != NULL) {
22041 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22042 				ASSERT(ire1 == ire->ire_next);
22043 				if (ire1 != NULL && ire1->ire_addr == dst) {
22044 					ire_refrele(ire);
22045 					ire = ire1;
22046 					IRE_REFHOLD(ire);
22047 					ire1 = ire->ire_next;
22048 					continue;
22049 				}
22050 				rw_exit(&ire->ire_bucket->irb_lock);
22051 				/* Did not find a matching ill */
22052 				ip1dbg(("ip_wput_ire: broadcast with no "
22053 				    "matching IP_BOUND_IF ill %s\n",
22054 				    conn_outgoing_ill->ill_name));
22055 				freemsg(first_mp);
22056 				if (ire != NULL)
22057 					ire_refrele(ire);
22058 				ill_refrele(conn_outgoing_ill);
22059 				return;
22060 			}
22061 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22062 			/*
22063 			 * If the next IRE has the same address and is not one
22064 			 * of the two copies that we need to send, try to see
22065 			 * whether this copy should be sent at all. This
22066 			 * assumes that we insert loopbacks first and then
22067 			 * non-loopbacks. This is acheived by inserting the
22068 			 * loopback always before non-loopback.
22069 			 * This is used to send a single copy of a broadcast
22070 			 * packet out all physical interfaces that have an
22071 			 * matching IRE_BROADCAST while also looping
22072 			 * back one copy (to ip_wput_local) for each
22073 			 * matching physical interface. However, we avoid
22074 			 * sending packets out different logical that match by
22075 			 * having ipif_up/ipif_down supress duplicate
22076 			 * IRE_BROADCASTS.
22077 			 *
22078 			 * This feature is currently used to get broadcasts
22079 			 * sent to multiple interfaces, when the broadcast
22080 			 * address being used applies to multiple interfaces.
22081 			 * For example, a whole net broadcast will be
22082 			 * replicated on every connected subnet of
22083 			 * the target net.
22084 			 *
22085 			 * Each zone has its own set of IRE_BROADCASTs, so that
22086 			 * we're able to distribute inbound packets to multiple
22087 			 * zones who share a broadcast address. We avoid looping
22088 			 * back outbound packets in different zones but on the
22089 			 * same ill, as the application would see duplicates.
22090 			 *
22091 			 * If the interfaces are part of the same group,
22092 			 * we would want to send only one copy out for
22093 			 * whole group.
22094 			 *
22095 			 * This logic assumes that ire_add_v4() groups the
22096 			 * IRE_BROADCAST entries so that those with the same
22097 			 * ire_addr and ill_group are kept together.
22098 			 */
22099 			ire_ill = ire->ire_ipif->ipif_ill;
22100 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22101 				if (ire_ill->ill_group != NULL &&
22102 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22103 					/*
22104 					 * If the current zone only has an ire
22105 					 * broadcast for this address marked
22106 					 * NORECV, the ire we want is ahead in
22107 					 * the bucket, so we look it up
22108 					 * deliberately ignoring the zoneid.
22109 					 */
22110 					for (ire1 = ire->ire_bucket->irb_ire;
22111 					    ire1 != NULL;
22112 					    ire1 = ire1->ire_next) {
22113 						ire1_ill =
22114 						    ire1->ire_ipif->ipif_ill;
22115 						if (ire1->ire_addr != dst)
22116 							continue;
22117 						/* skip over the current ire */
22118 						if (ire1 == ire)
22119 							continue;
22120 						/* skip over deleted ires */
22121 						if (ire1->ire_marks &
22122 						    IRE_MARK_CONDEMNED)
22123 							continue;
22124 						/*
22125 						 * non-loopback ire in our
22126 						 * group: use it for the next
22127 						 * pass in the loop
22128 						 */
22129 						if (ire1->ire_stq != NULL &&
22130 						    ire1_ill->ill_group ==
22131 						    ire_ill->ill_group)
22132 							break;
22133 					}
22134 				}
22135 			} else {
22136 				while (ire1 != NULL && ire1->ire_addr == dst) {
22137 					ire1_ill = ire1->ire_ipif->ipif_ill;
22138 					/*
22139 					 * We can have two broadcast ires on the
22140 					 * same ill in different zones; here
22141 					 * we'll send a copy of the packet on
22142 					 * each ill and the fanout code will
22143 					 * call conn_wantpacket() to check that
22144 					 * the zone has the broadcast address
22145 					 * configured on the ill. If the two
22146 					 * ires are in the same group we only
22147 					 * send one copy up.
22148 					 */
22149 					if (ire1_ill != ire_ill &&
22150 					    (ire1_ill->ill_group == NULL ||
22151 					    ire_ill->ill_group == NULL ||
22152 					    ire1_ill->ill_group !=
22153 					    ire_ill->ill_group)) {
22154 						break;
22155 					}
22156 					ire1 = ire1->ire_next;
22157 				}
22158 			}
22159 		}
22160 		ASSERT(multirt_send == B_FALSE);
22161 		if (ire1 != NULL && ire1->ire_addr == dst) {
22162 			if ((ire->ire_flags & RTF_MULTIRT) &&
22163 			    (ire1->ire_flags & RTF_MULTIRT)) {
22164 				/*
22165 				 * We are in the multirouting case.
22166 				 * The message must be sent at least
22167 				 * on both ires. These ires have been
22168 				 * inserted AFTER the standard ones
22169 				 * in ip_rt_add(). There are thus no
22170 				 * other ire entries for the destination
22171 				 * address in the rest of the bucket
22172 				 * that do not have the RTF_MULTIRT
22173 				 * flag. We don't process a copy
22174 				 * of the message here. This will be
22175 				 * done in the final sending loop.
22176 				 */
22177 				multirt_send = B_TRUE;
22178 			} else {
22179 				next_mp = ip_copymsg(first_mp);
22180 				if (next_mp != NULL)
22181 					IRE_REFHOLD(ire1);
22182 			}
22183 		}
22184 		rw_exit(&ire->ire_bucket->irb_lock);
22185 	}
22186 
22187 	if (stq) {
22188 		/*
22189 		 * A non-NULL send-to queue means this packet is going
22190 		 * out of this machine.
22191 		 */
22192 
22193 		BUMP_MIB(&ip_mib, ipOutRequests);
22194 		ttl_protocol = ((uint16_t *)ipha)[4];
22195 		/*
22196 		 * We accumulate the pseudo header checksum in cksum.
22197 		 * This is pretty hairy code, so watch close.  One
22198 		 * thing to keep in mind is that UDP and TCP have
22199 		 * stored their respective datagram lengths in their
22200 		 * checksum fields.  This lines things up real nice.
22201 		 */
22202 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22203 		    (src >> 16) + (src & 0xFFFF);
22204 		/*
22205 		 * We assume the udp checksum field contains the
22206 		 * length, so to compute the pseudo header checksum,
22207 		 * all we need is the protocol number and src/dst.
22208 		 */
22209 		/* Provide the checksums for UDP and TCP. */
22210 		if ((PROTO == IPPROTO_TCP) &&
22211 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22212 			/* hlen gets the number of uchar_ts in the IP header */
22213 			hlen = (V_HLEN & 0xF) << 2;
22214 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22215 			IP_STAT(ip_out_sw_cksum);
22216 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22217 			    LENGTH - hlen);
22218 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22219 			if (*up == 0)
22220 				*up = 0xFFFF;
22221 		} else if (PROTO == IPPROTO_SCTP &&
22222 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22223 			sctp_hdr_t	*sctph;
22224 
22225 			hlen = (V_HLEN & 0xF) << 2;
22226 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22227 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22228 			sctph->sh_chksum = 0;
22229 #ifdef	DEBUG
22230 			if (!skip_sctp_cksum)
22231 #endif
22232 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22233 		} else {
22234 			queue_t *dev_q = stq->q_next;
22235 
22236 			if ((dev_q->q_next || dev_q->q_first) &&
22237 			    !canput(dev_q)) {
22238 			    blocked:
22239 				ipha->ipha_ident = ip_hdr_included;
22240 				/*
22241 				 * If we don't have a conn to apply
22242 				 * backpressure, free the message.
22243 				 * In the ire_send path, we don't know
22244 				 * the position to requeue the packet. Rather
22245 				 * than reorder packets, we just drop this
22246 				 * packet.
22247 				 */
22248 				if (ip_output_queue && connp != NULL &&
22249 				    caller != IRE_SEND) {
22250 					if (caller == IP_WSRV) {
22251 						connp->conn_did_putbq = 1;
22252 						(void) putbq(connp->conn_wq,
22253 						    first_mp);
22254 						conn_drain_insert(connp);
22255 						/*
22256 						 * This is the service thread,
22257 						 * and the queue is already
22258 						 * noenabled. The check for
22259 						 * canput and the putbq is not
22260 						 * atomic. So we need to check
22261 						 * again.
22262 						 */
22263 						if (canput(stq->q_next))
22264 							connp->conn_did_putbq
22265 							    = 0;
22266 						IP_STAT(ip_conn_flputbq);
22267 					} else {
22268 						/*
22269 						 * We are not the service proc.
22270 						 * ip_wsrv will be scheduled or
22271 						 * is already running.
22272 						 */
22273 						(void) putq(connp->conn_wq,
22274 						    first_mp);
22275 					}
22276 				} else {
22277 					BUMP_MIB(&ip_mib, ipOutDiscards);
22278 					freemsg(first_mp);
22279 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22280 					    "ip_wput_ire_end: q %p (%S)",
22281 					    q, "discard");
22282 				}
22283 				ire_refrele(ire);
22284 				if (next_mp) {
22285 					ire_refrele(ire1);
22286 					freemsg(next_mp);
22287 				}
22288 				if (conn_outgoing_ill != NULL)
22289 					ill_refrele(conn_outgoing_ill);
22290 				return;
22291 			}
22292 			if ((PROTO == IPPROTO_UDP) &&
22293 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22294 				/*
22295 				 * hlen gets the number of uchar_ts in the
22296 				 * IP header
22297 				 */
22298 				hlen = (V_HLEN & 0xF) << 2;
22299 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22300 				max_frag = ire->ire_max_frag;
22301 				if (*up != 0) {
22302 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22303 					    up, PROTO, hlen, LENGTH, max_frag,
22304 					    ipsec_len, cksum);
22305 					/* Software checksum? */
22306 					if (DB_CKSUMFLAGS(mp) == 0) {
22307 						IP_STAT(ip_out_sw_cksum);
22308 						IP_STAT_UPDATE(
22309 						    ip_udp_out_sw_cksum_bytes,
22310 						    LENGTH - hlen);
22311 					}
22312 				}
22313 			}
22314 		}
22315 		/*
22316 		 * Need to do this even when fragmenting. The local
22317 		 * loopback can be done without computing checksums
22318 		 * but forwarding out other interface must be done
22319 		 * after the IP checksum (and ULP checksums) have been
22320 		 * computed.
22321 		 *
22322 		 * NOTE : multicast_forward is set only if this packet
22323 		 * originated from ip_wput. For packets originating from
22324 		 * ip_wput_multicast, it is not set.
22325 		 */
22326 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22327 		    multi_loopback:
22328 			ip2dbg(("ip_wput: multicast, loop %d\n",
22329 			    conn_multicast_loop));
22330 
22331 			/*  Forget header checksum offload */
22332 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22333 
22334 			/*
22335 			 * Local loopback of multicasts?  Check the
22336 			 * ill.
22337 			 *
22338 			 * Note that the loopback function will not come
22339 			 * in through ip_rput - it will only do the
22340 			 * client fanout thus we need to do an mforward
22341 			 * as well.  The is different from the BSD
22342 			 * logic.
22343 			 */
22344 			if (ill != NULL) {
22345 				ilm_t	*ilm;
22346 
22347 				ILM_WALKER_HOLD(ill);
22348 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22349 				    ALL_ZONES);
22350 				ILM_WALKER_RELE(ill);
22351 				if (ilm != NULL) {
22352 					/*
22353 					 * Pass along the virtual output q.
22354 					 * ip_wput_local() will distribute the
22355 					 * packet to all the matching zones,
22356 					 * except the sending zone when
22357 					 * IP_MULTICAST_LOOP is false.
22358 					 */
22359 					ip_multicast_loopback(q, ill, first_mp,
22360 					    conn_multicast_loop ? 0 :
22361 					    IP_FF_NO_MCAST_LOOP, zoneid);
22362 				}
22363 			}
22364 			if (ipha->ipha_ttl == 0) {
22365 				/*
22366 				 * 0 => only to this host i.e. we are
22367 				 * done. We are also done if this was the
22368 				 * loopback interface since it is sufficient
22369 				 * to loopback one copy of a multicast packet.
22370 				 */
22371 				freemsg(first_mp);
22372 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22373 				    "ip_wput_ire_end: q %p (%S)",
22374 				    q, "loopback");
22375 				ire_refrele(ire);
22376 				if (conn_outgoing_ill != NULL)
22377 					ill_refrele(conn_outgoing_ill);
22378 				return;
22379 			}
22380 			/*
22381 			 * ILLF_MULTICAST is checked in ip_newroute
22382 			 * i.e. we don't need to check it here since
22383 			 * all IRE_CACHEs come from ip_newroute.
22384 			 * For multicast traffic, SO_DONTROUTE is interpreted
22385 			 * to mean only send the packet out the interface
22386 			 * (optionally specified with IP_MULTICAST_IF)
22387 			 * and do not forward it out additional interfaces.
22388 			 * RSVP and the rsvp daemon is an example of a
22389 			 * protocol and user level process that
22390 			 * handles it's own routing. Hence, it uses the
22391 			 * SO_DONTROUTE option to accomplish this.
22392 			 */
22393 
22394 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22395 				/* Unconditionally redo the checksum */
22396 				ipha->ipha_hdr_checksum = 0;
22397 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22398 
22399 				/*
22400 				 * If this needs to go out secure, we need
22401 				 * to wait till we finish the IPSEC
22402 				 * processing.
22403 				 */
22404 				if (ipsec_len == 0 &&
22405 				    ip_mforward(ill, ipha, mp)) {
22406 					freemsg(first_mp);
22407 					ip1dbg(("ip_wput: mforward failed\n"));
22408 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22409 					    "ip_wput_ire_end: q %p (%S)",
22410 					    q, "mforward failed");
22411 					ire_refrele(ire);
22412 					if (conn_outgoing_ill != NULL)
22413 						ill_refrele(conn_outgoing_ill);
22414 					return;
22415 				}
22416 			}
22417 		}
22418 		max_frag = ire->ire_max_frag;
22419 		cksum += ttl_protocol;
22420 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22421 			/* No fragmentation required for this one. */
22422 			/*
22423 			 * Don't use frag_flag if packet is pre-built or source
22424 			 * routed or if multicast (since multicast packets do
22425 			 * not solicit ICMP "packet too big" messages).
22426 			 */
22427 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22428 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22429 			    !ip_source_route_included(ipha)) &&
22430 			    !CLASSD(ipha->ipha_dst))
22431 				ipha->ipha_fragment_offset_and_flags |=
22432 				    htons(ire->ire_frag_flag);
22433 
22434 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22435 				/* Complete the IP header checksum. */
22436 				cksum += ipha->ipha_ident;
22437 				cksum += (v_hlen_tos_len >> 16)+
22438 				    (v_hlen_tos_len & 0xFFFF);
22439 				cksum += ipha->ipha_fragment_offset_and_flags;
22440 				hlen = (V_HLEN & 0xF) -
22441 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22442 				if (hlen) {
22443 				    checksumoptions:
22444 					/*
22445 					 * Account for the IP Options in the IP
22446 					 * header checksum.
22447 					 */
22448 					up = (uint16_t *)(rptr+
22449 					    IP_SIMPLE_HDR_LENGTH);
22450 					do {
22451 						cksum += up[0];
22452 						cksum += up[1];
22453 						up += 2;
22454 					} while (--hlen);
22455 				}
22456 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22457 				cksum = ~(cksum + (cksum >> 16));
22458 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22459 			}
22460 			if (ipsec_len != 0) {
22461 				ipsec_out_process(q, first_mp, ire, ill_index);
22462 				if (!next_mp) {
22463 					ire_refrele(ire);
22464 					if (conn_outgoing_ill != NULL)
22465 						ill_refrele(conn_outgoing_ill);
22466 					return;
22467 				}
22468 				goto next;
22469 			}
22470 
22471 			/*
22472 			 * multirt_send has already been handled
22473 			 * for broadcast, but not yet for multicast
22474 			 * or IP options.
22475 			 */
22476 			if (next_mp == NULL) {
22477 				if (ire->ire_flags & RTF_MULTIRT) {
22478 					multirt_send = B_TRUE;
22479 				}
22480 			}
22481 
22482 			/*
22483 			 * In most cases, the emission loop below is
22484 			 * entered only once. Only in the case where
22485 			 * the ire holds the RTF_MULTIRT flag, do we loop
22486 			 * to process all RTF_MULTIRT ires in the bucket,
22487 			 * and send the packet through all crossed
22488 			 * RTF_MULTIRT routes.
22489 			 */
22490 			do {
22491 				if (multirt_send) {
22492 					irb_t *irb;
22493 
22494 					irb = ire->ire_bucket;
22495 					ASSERT(irb != NULL);
22496 					/*
22497 					 * We are in a multiple send case,
22498 					 * need to get the next IRE and make
22499 					 * a duplicate of the packet.
22500 					 */
22501 					IRB_REFHOLD(irb);
22502 					for (ire1 = ire->ire_next;
22503 					    ire1 != NULL;
22504 					    ire1 = ire1->ire_next) {
22505 						if (!(ire1->ire_flags &
22506 						    RTF_MULTIRT))
22507 							continue;
22508 						if (ire1->ire_addr !=
22509 						    ire->ire_addr)
22510 							continue;
22511 						if (ire1->ire_marks &
22512 						    (IRE_MARK_CONDEMNED|
22513 							IRE_MARK_HIDDEN))
22514 							continue;
22515 
22516 						/* Got one */
22517 						IRE_REFHOLD(ire1);
22518 						break;
22519 					}
22520 					IRB_REFRELE(irb);
22521 
22522 					if (ire1 != NULL) {
22523 						next_mp = copyb(mp);
22524 						if ((next_mp == NULL) ||
22525 						    ((mp->b_cont != NULL) &&
22526 						    ((next_mp->b_cont =
22527 						    dupmsg(mp->b_cont))
22528 						    == NULL))) {
22529 							freemsg(next_mp);
22530 							next_mp = NULL;
22531 							ire_refrele(ire1);
22532 							ire1 = NULL;
22533 						}
22534 					}
22535 
22536 					/*
22537 					 * Last multiroute ire; don't loop
22538 					 * anymore. The emission is over
22539 					 * and next_mp is NULL.
22540 					 */
22541 					if (ire1 == NULL) {
22542 						multirt_send = B_FALSE;
22543 					}
22544 				}
22545 
22546 				out_ill = ire->ire_ipif->ipif_ill;
22547 				DTRACE_PROBE4(ip4__physical__out__start,
22548 				    ill_t *, NULL,
22549 				    ill_t *, out_ill,
22550 				    ipha_t *, ipha, mblk_t *, mp);
22551 				FW_HOOKS(ip4_physical_out_event,
22552 				    ipv4firewall_physical_out,
22553 				    MSG_FWCOOKED_OUT, NULL, out_ill,
22554 				    ipha, mp, mp);
22555 				DTRACE_PROBE1(ip4__physical__out__end,
22556 				    mblk_t *, mp);
22557 				if (mp == NULL)
22558 					goto release_ire_and_ill_2;
22559 
22560 				ASSERT(ipsec_len == 0);
22561 				mp->b_prev =
22562 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22563 				DTRACE_PROBE2(ip__xmit__2,
22564 				    mblk_t *, mp, ire_t *, ire);
22565 				pktxmit_state = ip_xmit_v4(mp, ire,
22566 				    NULL, B_TRUE);
22567 				if ((pktxmit_state == SEND_FAILED) ||
22568 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22569 release_ire_and_ill_2:
22570 					if (next_mp) {
22571 						freemsg(next_mp);
22572 						ire_refrele(ire1);
22573 					}
22574 					ire_refrele(ire);
22575 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22576 					    "ip_wput_ire_end: q %p (%S)",
22577 					    q, "discard MDATA");
22578 					if (conn_outgoing_ill != NULL)
22579 						ill_refrele(conn_outgoing_ill);
22580 					return;
22581 				}
22582 
22583 				if (multirt_send) {
22584 					/*
22585 					 * We are in a multiple send case,
22586 					 * need to re-enter the sending loop
22587 					 * using the next ire.
22588 					 */
22589 					ire_refrele(ire);
22590 					ire = ire1;
22591 					stq = ire->ire_stq;
22592 					mp = next_mp;
22593 					next_mp = NULL;
22594 					ipha = (ipha_t *)mp->b_rptr;
22595 					ill_index = Q_TO_INDEX(stq);
22596 				}
22597 			} while (multirt_send);
22598 
22599 			if (!next_mp) {
22600 				/*
22601 				 * Last copy going out (the ultra-common
22602 				 * case).  Note that we intentionally replicate
22603 				 * the putnext rather than calling it before
22604 				 * the next_mp check in hopes of a little
22605 				 * tail-call action out of the compiler.
22606 				 */
22607 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22608 				    "ip_wput_ire_end: q %p (%S)",
22609 				    q, "last copy out(1)");
22610 				ire_refrele(ire);
22611 				if (conn_outgoing_ill != NULL)
22612 					ill_refrele(conn_outgoing_ill);
22613 				return;
22614 			}
22615 			/* More copies going out below. */
22616 		} else {
22617 			int offset;
22618 		    fragmentit:
22619 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22620 			/*
22621 			 * If this would generate a icmp_frag_needed message,
22622 			 * we need to handle it before we do the IPSEC
22623 			 * processing. Otherwise, we need to strip the IPSEC
22624 			 * headers before we send up the message to the ULPs
22625 			 * which becomes messy and difficult.
22626 			 */
22627 			if (ipsec_len != 0) {
22628 				if ((max_frag < (unsigned int)(LENGTH +
22629 				    ipsec_len)) && (offset & IPH_DF)) {
22630 
22631 					BUMP_MIB(&ip_mib, ipFragFails);
22632 					ipha->ipha_hdr_checksum = 0;
22633 					ipha->ipha_hdr_checksum =
22634 					    (uint16_t)ip_csum_hdr(ipha);
22635 					icmp_frag_needed(ire->ire_stq, first_mp,
22636 					    max_frag, zoneid);
22637 					if (!next_mp) {
22638 						ire_refrele(ire);
22639 						if (conn_outgoing_ill != NULL) {
22640 							ill_refrele(
22641 							    conn_outgoing_ill);
22642 						}
22643 						return;
22644 					}
22645 				} else {
22646 					/*
22647 					 * This won't cause a icmp_frag_needed
22648 					 * message. to be gnerated. Send it on
22649 					 * the wire. Note that this could still
22650 					 * cause fragmentation and all we
22651 					 * do is the generation of the message
22652 					 * to the ULP if needed before IPSEC.
22653 					 */
22654 					if (!next_mp) {
22655 						ipsec_out_process(q, first_mp,
22656 						    ire, ill_index);
22657 						TRACE_2(TR_FAC_IP,
22658 						    TR_IP_WPUT_IRE_END,
22659 						    "ip_wput_ire_end: q %p "
22660 						    "(%S)", q,
22661 						    "last ipsec_out_process");
22662 						ire_refrele(ire);
22663 						if (conn_outgoing_ill != NULL) {
22664 							ill_refrele(
22665 							    conn_outgoing_ill);
22666 						}
22667 						return;
22668 					}
22669 					ipsec_out_process(q, first_mp,
22670 					    ire, ill_index);
22671 				}
22672 			} else {
22673 				/*
22674 				 * Initiate IPPF processing. For
22675 				 * fragmentable packets we finish
22676 				 * all QOS packet processing before
22677 				 * calling:
22678 				 * ip_wput_ire_fragmentit->ip_wput_frag
22679 				 */
22680 
22681 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22682 					ip_process(IPP_LOCAL_OUT, &mp,
22683 					    ill_index);
22684 					if (mp == NULL) {
22685 						BUMP_MIB(&ip_mib,
22686 						    ipOutDiscards);
22687 						if (next_mp != NULL) {
22688 							freemsg(next_mp);
22689 							ire_refrele(ire1);
22690 						}
22691 						ire_refrele(ire);
22692 						TRACE_2(TR_FAC_IP,
22693 						    TR_IP_WPUT_IRE_END,
22694 						    "ip_wput_ire: q %p (%S)",
22695 						    q, "discard MDATA");
22696 						if (conn_outgoing_ill != NULL) {
22697 							ill_refrele(
22698 							    conn_outgoing_ill);
22699 						}
22700 						return;
22701 					}
22702 				}
22703 				if (!next_mp) {
22704 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22705 					    "ip_wput_ire_end: q %p (%S)",
22706 					    q, "last fragmentation");
22707 					ip_wput_ire_fragmentit(mp, ire,
22708 					    zoneid);
22709 					ire_refrele(ire);
22710 					if (conn_outgoing_ill != NULL)
22711 						ill_refrele(conn_outgoing_ill);
22712 					return;
22713 				}
22714 				ip_wput_ire_fragmentit(mp, ire, zoneid);
22715 			}
22716 		}
22717 	} else {
22718 	    nullstq:
22719 		/* A NULL stq means the destination address is local. */
22720 		UPDATE_OB_PKT_COUNT(ire);
22721 		ire->ire_last_used_time = lbolt;
22722 		ASSERT(ire->ire_ipif != NULL);
22723 		if (!next_mp) {
22724 			/*
22725 			 * Is there an "in" and "out" for traffic local
22726 			 * to a host (loopback)?  The code in Solaris doesn't
22727 			 * explicitly draw a line in its code for in vs out,
22728 			 * so we've had to draw a line in the sand: ip_wput_ire
22729 			 * is considered to be the "output" side and
22730 			 * ip_wput_local to be the "input" side.
22731 			 */
22732 			out_ill = ire->ire_ipif->ipif_ill;
22733 
22734 			DTRACE_PROBE4(ip4__loopback__out__start,
22735 			    ill_t *, NULL, ill_t *, out_ill,
22736 			    ipha_t *, ipha, mblk_t *, first_mp);
22737 
22738 			FW_HOOKS(ip4_loopback_out_event,
22739 			    ipv4firewall_loopback_out, MSG_FWCOOKED_OUT,
22740 			    NULL, out_ill, ipha, first_mp, mp);
22741 
22742 			DTRACE_PROBE1(ip4__loopback__out_end,
22743 			    mblk_t *, first_mp);
22744 
22745 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22746 			    "ip_wput_ire_end: q %p (%S)",
22747 			    q, "local address");
22748 
22749 			if (first_mp != NULL)
22750 				ip_wput_local(q, out_ill, ipha,
22751 				    first_mp, ire, 0, ire->ire_zoneid);
22752 			ire_refrele(ire);
22753 			if (conn_outgoing_ill != NULL)
22754 				ill_refrele(conn_outgoing_ill);
22755 			return;
22756 		}
22757 
22758 		out_ill = ire->ire_ipif->ipif_ill;
22759 
22760 		DTRACE_PROBE4(ip4__loopback__out__start,
22761 		    ill_t *, NULL, ill_t *, out_ill,
22762 		    ipha_t *, ipha, mblk_t *, first_mp);
22763 
22764 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
22765 		    MSG_FWCOOKED_OUT, NULL, out_ill, ipha, first_mp, mp);
22766 
22767 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
22768 
22769 		if (first_mp != NULL)
22770 			ip_wput_local(q, out_ill, ipha,
22771 			    first_mp, ire, 0, ire->ire_zoneid);
22772 	}
22773 next:
22774 	/*
22775 	 * More copies going out to additional interfaces.
22776 	 * ire1 has already been held. We don't need the
22777 	 * "ire" anymore.
22778 	 */
22779 	ire_refrele(ire);
22780 	ire = ire1;
22781 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
22782 	mp = next_mp;
22783 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
22784 	ill = ire_to_ill(ire);
22785 	first_mp = mp;
22786 	if (ipsec_len != 0) {
22787 		ASSERT(first_mp->b_datap->db_type == M_CTL);
22788 		mp = mp->b_cont;
22789 	}
22790 	dst = ire->ire_addr;
22791 	ipha = (ipha_t *)mp->b_rptr;
22792 	/*
22793 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
22794 	 * Restore ipha_ident "no checksum" flag.
22795 	 */
22796 	src = orig_src;
22797 	ipha->ipha_ident = ip_hdr_included;
22798 	goto another;
22799 
22800 #undef	rptr
22801 #undef	Q_TO_INDEX
22802 }
22803 
22804 /*
22805  * Routine to allocate a message that is used to notify the ULP about MDT.
22806  * The caller may provide a pointer to the link-layer MDT capabilities,
22807  * or NULL if MDT is to be disabled on the stream.
22808  */
22809 mblk_t *
22810 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
22811 {
22812 	mblk_t *mp;
22813 	ip_mdt_info_t *mdti;
22814 	ill_mdt_capab_t *idst;
22815 
22816 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
22817 		DB_TYPE(mp) = M_CTL;
22818 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
22819 		mdti = (ip_mdt_info_t *)mp->b_rptr;
22820 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
22821 		idst = &(mdti->mdt_capab);
22822 
22823 		/*
22824 		 * If the caller provides us with the capability, copy
22825 		 * it over into our notification message; otherwise
22826 		 * we zero out the capability portion.
22827 		 */
22828 		if (isrc != NULL)
22829 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22830 		else
22831 			bzero((caddr_t)idst, sizeof (*idst));
22832 	}
22833 	return (mp);
22834 }
22835 
22836 /*
22837  * Routine which determines whether MDT can be enabled on the destination
22838  * IRE and IPC combination, and if so, allocates and returns the MDT
22839  * notification mblk that may be used by ULP.  We also check if we need to
22840  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
22841  * MDT usage in the past have been lifted.  This gets called during IP
22842  * and ULP binding.
22843  */
22844 mblk_t *
22845 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22846     ill_mdt_capab_t *mdt_cap)
22847 {
22848 	mblk_t *mp;
22849 	boolean_t rc = B_FALSE;
22850 
22851 	ASSERT(dst_ire != NULL);
22852 	ASSERT(connp != NULL);
22853 	ASSERT(mdt_cap != NULL);
22854 
22855 	/*
22856 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
22857 	 * Multidata, which is handled in tcp_multisend().  This
22858 	 * is the reason why we do all these checks here, to ensure
22859 	 * that we don't enable Multidata for the cases which we
22860 	 * can't handle at the moment.
22861 	 */
22862 	do {
22863 		/* Only do TCP at the moment */
22864 		if (connp->conn_ulp != IPPROTO_TCP)
22865 			break;
22866 
22867 		/*
22868 		 * IPSEC outbound policy present?  Note that we get here
22869 		 * after calling ipsec_conn_cache_policy() where the global
22870 		 * policy checking is performed.  conn_latch will be
22871 		 * non-NULL as long as there's a policy defined,
22872 		 * i.e. conn_out_enforce_policy may be NULL in such case
22873 		 * when the connection is non-secure, and hence we check
22874 		 * further if the latch refers to an outbound policy.
22875 		 */
22876 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
22877 			break;
22878 
22879 		/* CGTP (multiroute) is enabled? */
22880 		if (dst_ire->ire_flags & RTF_MULTIRT)
22881 			break;
22882 
22883 		/* Outbound IPQoS enabled? */
22884 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22885 			/*
22886 			 * In this case, we disable MDT for this and all
22887 			 * future connections going over the interface.
22888 			 */
22889 			mdt_cap->ill_mdt_on = 0;
22890 			break;
22891 		}
22892 
22893 		/* socket option(s) present? */
22894 		if (!CONN_IS_MD_FASTPATH(connp))
22895 			break;
22896 
22897 		rc = B_TRUE;
22898 	/* CONSTCOND */
22899 	} while (0);
22900 
22901 	/* Remember the result */
22902 	connp->conn_mdt_ok = rc;
22903 
22904 	if (!rc)
22905 		return (NULL);
22906 	else if (!mdt_cap->ill_mdt_on) {
22907 		/*
22908 		 * If MDT has been previously turned off in the past, and we
22909 		 * currently can do MDT (due to IPQoS policy removal, etc.)
22910 		 * then enable it for this interface.
22911 		 */
22912 		mdt_cap->ill_mdt_on = 1;
22913 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
22914 		    "interface %s\n", ill_name));
22915 	}
22916 
22917 	/* Allocate the MDT info mblk */
22918 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
22919 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
22920 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
22921 		return (NULL);
22922 	}
22923 	return (mp);
22924 }
22925 
22926 /*
22927  * Create destination address attribute, and fill it with the physical
22928  * destination address and SAP taken from the template DL_UNITDATA_REQ
22929  * message block.
22930  */
22931 boolean_t
22932 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
22933 {
22934 	dl_unitdata_req_t *dlurp;
22935 	pattr_t *pa;
22936 	pattrinfo_t pa_info;
22937 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
22938 	uint_t das_len, das_off;
22939 
22940 	ASSERT(dlmp != NULL);
22941 
22942 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
22943 	das_len = dlurp->dl_dest_addr_length;
22944 	das_off = dlurp->dl_dest_addr_offset;
22945 
22946 	pa_info.type = PATTR_DSTADDRSAP;
22947 	pa_info.len = sizeof (**das) + das_len - 1;
22948 
22949 	/* create and associate the attribute */
22950 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22951 	if (pa != NULL) {
22952 		ASSERT(*das != NULL);
22953 		(*das)->addr_is_group = 0;
22954 		(*das)->addr_len = (uint8_t)das_len;
22955 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
22956 	}
22957 
22958 	return (pa != NULL);
22959 }
22960 
22961 /*
22962  * Create hardware checksum attribute and fill it with the values passed.
22963  */
22964 boolean_t
22965 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
22966     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
22967 {
22968 	pattr_t *pa;
22969 	pattrinfo_t pa_info;
22970 
22971 	ASSERT(mmd != NULL);
22972 
22973 	pa_info.type = PATTR_HCKSUM;
22974 	pa_info.len = sizeof (pattr_hcksum_t);
22975 
22976 	/* create and associate the attribute */
22977 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22978 	if (pa != NULL) {
22979 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
22980 
22981 		hck->hcksum_start_offset = start_offset;
22982 		hck->hcksum_stuff_offset = stuff_offset;
22983 		hck->hcksum_end_offset = end_offset;
22984 		hck->hcksum_flags = flags;
22985 	}
22986 	return (pa != NULL);
22987 }
22988 
22989 /*
22990  * Create zerocopy attribute and fill it with the specified flags
22991  */
22992 boolean_t
22993 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
22994 {
22995 	pattr_t *pa;
22996 	pattrinfo_t pa_info;
22997 
22998 	ASSERT(mmd != NULL);
22999 	pa_info.type = PATTR_ZCOPY;
23000 	pa_info.len = sizeof (pattr_zcopy_t);
23001 
23002 	/* create and associate the attribute */
23003 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23004 	if (pa != NULL) {
23005 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23006 
23007 		zcopy->zcopy_flags = flags;
23008 	}
23009 	return (pa != NULL);
23010 }
23011 
23012 /*
23013  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23014  * block chain. We could rewrite to handle arbitrary message block chains but
23015  * that would make the code complicated and slow. Right now there three
23016  * restrictions:
23017  *
23018  *   1. The first message block must contain the complete IP header and
23019  *	at least 1 byte of payload data.
23020  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23021  *	so that we can use a single Multidata message.
23022  *   3. No frag must be distributed over two or more message blocks so
23023  *	that we don't need more than two packet descriptors per frag.
23024  *
23025  * The above restrictions allow us to support userland applications (which
23026  * will send down a single message block) and NFS over UDP (which will
23027  * send down a chain of at most three message blocks).
23028  *
23029  * We also don't use MDT for payloads with less than or equal to
23030  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23031  */
23032 boolean_t
23033 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23034 {
23035 	int	blocks;
23036 	ssize_t	total, missing, size;
23037 
23038 	ASSERT(mp != NULL);
23039 	ASSERT(hdr_len > 0);
23040 
23041 	size = MBLKL(mp) - hdr_len;
23042 	if (size <= 0)
23043 		return (B_FALSE);
23044 
23045 	/* The first mblk contains the header and some payload. */
23046 	blocks = 1;
23047 	total = size;
23048 	size %= len;
23049 	missing = (size == 0) ? 0 : (len - size);
23050 	mp = mp->b_cont;
23051 
23052 	while (mp != NULL) {
23053 		/*
23054 		 * Give up if we encounter a zero length message block.
23055 		 * In practice, this should rarely happen and therefore
23056 		 * not worth the trouble of freeing and re-linking the
23057 		 * mblk from the chain to handle such case.
23058 		 */
23059 		if ((size = MBLKL(mp)) == 0)
23060 			return (B_FALSE);
23061 
23062 		/* Too many payload buffers for a single Multidata message? */
23063 		if (++blocks > MULTIDATA_MAX_PBUFS)
23064 			return (B_FALSE);
23065 
23066 		total += size;
23067 		/* Is a frag distributed over two or more message blocks? */
23068 		if (missing > size)
23069 			return (B_FALSE);
23070 		size -= missing;
23071 
23072 		size %= len;
23073 		missing = (size == 0) ? 0 : (len - size);
23074 
23075 		mp = mp->b_cont;
23076 	}
23077 
23078 	return (total > ip_wput_frag_mdt_min);
23079 }
23080 
23081 /*
23082  * Outbound IPv4 fragmentation routine using MDT.
23083  */
23084 static void
23085 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23086     uint32_t frag_flag, int offset)
23087 {
23088 	ipha_t		*ipha_orig;
23089 	int		i1, ip_data_end;
23090 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23091 	mblk_t		*hdr_mp, *md_mp = NULL;
23092 	unsigned char	*hdr_ptr, *pld_ptr;
23093 	multidata_t	*mmd;
23094 	ip_pdescinfo_t	pdi;
23095 
23096 	ASSERT(DB_TYPE(mp) == M_DATA);
23097 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23098 
23099 	ipha_orig = (ipha_t *)mp->b_rptr;
23100 	mp->b_rptr += sizeof (ipha_t);
23101 
23102 	/* Calculate how many packets we will send out */
23103 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23104 	pkts = (i1 + len - 1) / len;
23105 	ASSERT(pkts > 1);
23106 
23107 	/* Allocate a message block which will hold all the IP Headers. */
23108 	wroff = ip_wroff_extra;
23109 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23110 
23111 	i1 = pkts * hdr_chunk_len;
23112 	/*
23113 	 * Create the header buffer, Multidata and destination address
23114 	 * and SAP attribute that should be associated with it.
23115 	 */
23116 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23117 	    ((hdr_mp->b_wptr += i1),
23118 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23119 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23120 		freemsg(mp);
23121 		if (md_mp == NULL) {
23122 			freemsg(hdr_mp);
23123 		} else {
23124 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
23125 			freemsg(md_mp);
23126 		}
23127 		IP_STAT(ip_frag_mdt_allocfail);
23128 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
23129 		return;
23130 	}
23131 	IP_STAT(ip_frag_mdt_allocd);
23132 
23133 	/*
23134 	 * Add a payload buffer to the Multidata; this operation must not
23135 	 * fail, or otherwise our logic in this routine is broken.  There
23136 	 * is no memory allocation done by the routine, so any returned
23137 	 * failure simply tells us that we've done something wrong.
23138 	 *
23139 	 * A failure tells us that either we're adding the same payload
23140 	 * buffer more than once, or we're trying to add more buffers than
23141 	 * allowed.  None of the above cases should happen, and we panic
23142 	 * because either there's horrible heap corruption, and/or
23143 	 * programming mistake.
23144 	 */
23145 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23146 		goto pbuf_panic;
23147 
23148 	hdr_ptr = hdr_mp->b_rptr;
23149 	pld_ptr = mp->b_rptr;
23150 
23151 	/* Establish the ending byte offset, based on the starting offset. */
23152 	offset <<= 3;
23153 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23154 	    IP_SIMPLE_HDR_LENGTH;
23155 
23156 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23157 
23158 	while (pld_ptr < mp->b_wptr) {
23159 		ipha_t		*ipha;
23160 		uint16_t	offset_and_flags;
23161 		uint16_t	ip_len;
23162 		int		error;
23163 
23164 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23165 		ipha = (ipha_t *)(hdr_ptr + wroff);
23166 		ASSERT(OK_32PTR(ipha));
23167 		*ipha = *ipha_orig;
23168 
23169 		if (ip_data_end - offset > len) {
23170 			offset_and_flags = IPH_MF;
23171 		} else {
23172 			/*
23173 			 * Last frag. Set len to the length of this last piece.
23174 			 */
23175 			len = ip_data_end - offset;
23176 			/* A frag of a frag might have IPH_MF non-zero */
23177 			offset_and_flags =
23178 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23179 			    IPH_MF;
23180 		}
23181 		offset_and_flags |= (uint16_t)(offset >> 3);
23182 		offset_and_flags |= (uint16_t)frag_flag;
23183 		/* Store the offset and flags in the IP header. */
23184 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23185 
23186 		/* Store the length in the IP header. */
23187 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23188 		ipha->ipha_length = htons(ip_len);
23189 
23190 		/*
23191 		 * Set the IP header checksum.  Note that mp is just
23192 		 * the header, so this is easy to pass to ip_csum.
23193 		 */
23194 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23195 
23196 		/*
23197 		 * Record offset and size of header and data of the next packet
23198 		 * in the multidata message.
23199 		 */
23200 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23201 		PDESC_PLD_INIT(&pdi);
23202 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23203 		ASSERT(i1 > 0);
23204 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23205 		if (i1 == len) {
23206 			pld_ptr += len;
23207 		} else {
23208 			i1 = len - i1;
23209 			mp = mp->b_cont;
23210 			ASSERT(mp != NULL);
23211 			ASSERT(MBLKL(mp) >= i1);
23212 			/*
23213 			 * Attach the next payload message block to the
23214 			 * multidata message.
23215 			 */
23216 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23217 				goto pbuf_panic;
23218 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23219 			pld_ptr = mp->b_rptr + i1;
23220 		}
23221 
23222 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23223 		    KM_NOSLEEP)) == NULL) {
23224 			/*
23225 			 * Any failure other than ENOMEM indicates that we
23226 			 * have passed in invalid pdesc info or parameters
23227 			 * to mmd_addpdesc, which must not happen.
23228 			 *
23229 			 * EINVAL is a result of failure on boundary checks
23230 			 * against the pdesc info contents.  It should not
23231 			 * happen, and we panic because either there's
23232 			 * horrible heap corruption, and/or programming
23233 			 * mistake.
23234 			 */
23235 			if (error != ENOMEM) {
23236 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23237 				    "pdesc logic error detected for "
23238 				    "mmd %p pinfo %p (%d)\n",
23239 				    (void *)mmd, (void *)&pdi, error);
23240 				/* NOTREACHED */
23241 			}
23242 			IP_STAT(ip_frag_mdt_addpdescfail);
23243 			/* Free unattached payload message blocks as well */
23244 			md_mp->b_cont = mp->b_cont;
23245 			goto free_mmd;
23246 		}
23247 
23248 		/* Advance fragment offset. */
23249 		offset += len;
23250 
23251 		/* Advance to location for next header in the buffer. */
23252 		hdr_ptr += hdr_chunk_len;
23253 
23254 		/* Did we reach the next payload message block? */
23255 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23256 			mp = mp->b_cont;
23257 			/*
23258 			 * Attach the next message block with payload
23259 			 * data to the multidata message.
23260 			 */
23261 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23262 				goto pbuf_panic;
23263 			pld_ptr = mp->b_rptr;
23264 		}
23265 	}
23266 
23267 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23268 	ASSERT(mp->b_wptr == pld_ptr);
23269 
23270 	/* Update IP statistics */
23271 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
23272 	BUMP_MIB(&ip_mib, ipFragOKs);
23273 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
23274 
23275 	if (pkt_type == OB_PKT) {
23276 		ire->ire_ob_pkt_count += pkts;
23277 		if (ire->ire_ipif != NULL)
23278 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23279 	} else {
23280 		/*
23281 		 * The type is IB_PKT in the forwarding path and in
23282 		 * the mobile IP case when the packet is being reverse-
23283 		 * tunneled to the home agent.
23284 		 */
23285 		ire->ire_ib_pkt_count += pkts;
23286 		ASSERT(!IRE_IS_LOCAL(ire));
23287 		if (ire->ire_type & IRE_BROADCAST)
23288 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23289 		else
23290 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23291 	}
23292 	ire->ire_last_used_time = lbolt;
23293 	/* Send it down */
23294 	putnext(ire->ire_stq, md_mp);
23295 	return;
23296 
23297 pbuf_panic:
23298 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23299 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23300 	    pbuf_idx);
23301 	/* NOTREACHED */
23302 }
23303 
23304 /*
23305  * Outbound IP fragmentation routine.
23306  *
23307  * NOTE : This routine does not ire_refrele the ire that is passed in
23308  * as the argument.
23309  */
23310 static void
23311 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23312     uint32_t frag_flag, zoneid_t zoneid)
23313 {
23314 	int		i1;
23315 	mblk_t		*ll_hdr_mp;
23316 	int 		ll_hdr_len;
23317 	int		hdr_len;
23318 	mblk_t		*hdr_mp;
23319 	ipha_t		*ipha;
23320 	int		ip_data_end;
23321 	int		len;
23322 	mblk_t		*mp = mp_orig, *mp1;
23323 	int		offset;
23324 	queue_t		*q;
23325 	uint32_t	v_hlen_tos_len;
23326 	mblk_t		*first_mp;
23327 	boolean_t	mctl_present;
23328 	ill_t		*ill;
23329 	ill_t		*out_ill;
23330 	mblk_t		*xmit_mp;
23331 	mblk_t		*carve_mp;
23332 	ire_t		*ire1 = NULL;
23333 	ire_t		*save_ire = NULL;
23334 	mblk_t  	*next_mp = NULL;
23335 	boolean_t	last_frag = B_FALSE;
23336 	boolean_t	multirt_send = B_FALSE;
23337 	ire_t		*first_ire = NULL;
23338 	irb_t		*irb = NULL;
23339 
23340 	/*
23341 	 * IPSEC does not allow hw accelerated packets to be fragmented
23342 	 * This check is made in ip_wput_ipsec_out prior to coming here
23343 	 * via ip_wput_ire_fragmentit.
23344 	 *
23345 	 * If at this point we have an ire whose ARP request has not
23346 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23347 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23348 	 * This packet and all fragmentable packets for this ire will
23349 	 * continue to get dropped while ire_nce->nce_state remains in
23350 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23351 	 * ND_REACHABLE, all subsquent large packets for this ire will
23352 	 * get fragemented and sent out by this function.
23353 	 */
23354 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23355 		/* If nce_state is ND_INITIAL, trigger ARP query */
23356 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23357 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23358 		    " -  dropping packet\n"));
23359 		BUMP_MIB(&ip_mib, ipFragFails);
23360 		freemsg(mp);
23361 		return;
23362 	}
23363 
23364 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23365 	    "ip_wput_frag_start:");
23366 
23367 	if (mp->b_datap->db_type == M_CTL) {
23368 		first_mp = mp;
23369 		mp_orig = mp = mp->b_cont;
23370 		mctl_present = B_TRUE;
23371 	} else {
23372 		first_mp = mp;
23373 		mctl_present = B_FALSE;
23374 	}
23375 
23376 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23377 	ipha = (ipha_t *)mp->b_rptr;
23378 
23379 	/*
23380 	 * If the Don't Fragment flag is on, generate an ICMP destination
23381 	 * unreachable, fragmentation needed.
23382 	 */
23383 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23384 	if (offset & IPH_DF) {
23385 		BUMP_MIB(&ip_mib, ipFragFails);
23386 		/*
23387 		 * Need to compute hdr checksum if called from ip_wput_ire.
23388 		 * Note that ip_rput_forward verifies the checksum before
23389 		 * calling this routine so in that case this is a noop.
23390 		 */
23391 		ipha->ipha_hdr_checksum = 0;
23392 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23393 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid);
23394 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23395 		    "ip_wput_frag_end:(%S)",
23396 		    "don't fragment");
23397 		return;
23398 	}
23399 	if (mctl_present)
23400 		freeb(first_mp);
23401 	/*
23402 	 * Establish the starting offset.  May not be zero if we are fragging
23403 	 * a fragment that is being forwarded.
23404 	 */
23405 	offset = offset & IPH_OFFSET;
23406 
23407 	/* TODO why is this test needed? */
23408 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23409 	if (((max_frag - LENGTH) & ~7) < 8) {
23410 		/* TODO: notify ulp somehow */
23411 		BUMP_MIB(&ip_mib, ipFragFails);
23412 		freemsg(mp);
23413 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23414 		    "ip_wput_frag_end:(%S)",
23415 		    "len < 8");
23416 		return;
23417 	}
23418 
23419 	hdr_len = (V_HLEN & 0xF) << 2;
23420 
23421 	ipha->ipha_hdr_checksum = 0;
23422 
23423 	/*
23424 	 * Establish the number of bytes maximum per frag, after putting
23425 	 * in the header.
23426 	 */
23427 	len = (max_frag - hdr_len) & ~7;
23428 
23429 	/* Check if we can use MDT to send out the frags. */
23430 	ASSERT(!IRE_IS_LOCAL(ire));
23431 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
23432 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
23433 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
23434 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23435 		ASSERT(ill->ill_mdt_capab != NULL);
23436 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23437 			/*
23438 			 * If MDT has been previously turned off in the past,
23439 			 * and we currently can do MDT (due to IPQoS policy
23440 			 * removal, etc.) then enable it for this interface.
23441 			 */
23442 			ill->ill_mdt_capab->ill_mdt_on = 1;
23443 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23444 			    ill->ill_name));
23445 		}
23446 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23447 		    offset);
23448 		return;
23449 	}
23450 
23451 	/* Get a copy of the header for the trailing frags */
23452 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
23453 	if (!hdr_mp) {
23454 		BUMP_MIB(&ip_mib, ipOutDiscards);
23455 		freemsg(mp);
23456 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23457 		    "ip_wput_frag_end:(%S)",
23458 		    "couldn't copy hdr");
23459 		return;
23460 	}
23461 	if (DB_CRED(mp) != NULL)
23462 		mblk_setcred(hdr_mp, DB_CRED(mp));
23463 
23464 	/* Store the starting offset, with the MoreFrags flag. */
23465 	i1 = offset | IPH_MF | frag_flag;
23466 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23467 
23468 	/* Establish the ending byte offset, based on the starting offset. */
23469 	offset <<= 3;
23470 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23471 
23472 	/* Store the length of the first fragment in the IP header. */
23473 	i1 = len + hdr_len;
23474 	ASSERT(i1 <= IP_MAXPACKET);
23475 	ipha->ipha_length = htons((uint16_t)i1);
23476 
23477 	/*
23478 	 * Compute the IP header checksum for the first frag.  We have to
23479 	 * watch out that we stop at the end of the header.
23480 	 */
23481 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23482 
23483 	/*
23484 	 * Now carve off the first frag.  Note that this will include the
23485 	 * original IP header.
23486 	 */
23487 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
23488 		BUMP_MIB(&ip_mib, ipOutDiscards);
23489 		freeb(hdr_mp);
23490 		freemsg(mp_orig);
23491 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23492 		    "ip_wput_frag_end:(%S)",
23493 		    "couldn't carve first");
23494 		return;
23495 	}
23496 
23497 	/*
23498 	 * Multirouting case. Each fragment is replicated
23499 	 * via all non-condemned RTF_MULTIRT routes
23500 	 * currently resolved.
23501 	 * We ensure that first_ire is the first RTF_MULTIRT
23502 	 * ire in the bucket.
23503 	 */
23504 	if (ire->ire_flags & RTF_MULTIRT) {
23505 		irb = ire->ire_bucket;
23506 		ASSERT(irb != NULL);
23507 
23508 		multirt_send = B_TRUE;
23509 
23510 		/* Make sure we do not omit any multiroute ire. */
23511 		IRB_REFHOLD(irb);
23512 		for (first_ire = irb->irb_ire;
23513 		    first_ire != NULL;
23514 		    first_ire = first_ire->ire_next) {
23515 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23516 			    (first_ire->ire_addr == ire->ire_addr) &&
23517 			    !(first_ire->ire_marks &
23518 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23519 				break;
23520 		}
23521 
23522 		if (first_ire != NULL) {
23523 			if (first_ire != ire) {
23524 				IRE_REFHOLD(first_ire);
23525 				/*
23526 				 * Do not release the ire passed in
23527 				 * as the argument.
23528 				 */
23529 				ire = first_ire;
23530 			} else {
23531 				first_ire = NULL;
23532 			}
23533 		}
23534 		IRB_REFRELE(irb);
23535 
23536 		/*
23537 		 * Save the first ire; we will need to restore it
23538 		 * for the trailing frags.
23539 		 * We REFHOLD save_ire, as each iterated ire will be
23540 		 * REFRELEd.
23541 		 */
23542 		save_ire = ire;
23543 		IRE_REFHOLD(save_ire);
23544 	}
23545 
23546 	/*
23547 	 * First fragment emission loop.
23548 	 * In most cases, the emission loop below is entered only
23549 	 * once. Only in the case where the ire holds the RTF_MULTIRT
23550 	 * flag, do we loop to process all RTF_MULTIRT ires in the
23551 	 * bucket, and send the fragment through all crossed
23552 	 * RTF_MULTIRT routes.
23553 	 */
23554 	do {
23555 		if (ire->ire_flags & RTF_MULTIRT) {
23556 			/*
23557 			 * We are in a multiple send case, need to get
23558 			 * the next ire and make a copy of the packet.
23559 			 * ire1 holds here the next ire to process in the
23560 			 * bucket. If multirouting is expected,
23561 			 * any non-RTF_MULTIRT ire that has the
23562 			 * right destination address is ignored.
23563 			 *
23564 			 * We have to take into account the MTU of
23565 			 * each walked ire. max_frag is set by the
23566 			 * the caller and generally refers to
23567 			 * the primary ire entry. Here we ensure that
23568 			 * no route with a lower MTU will be used, as
23569 			 * fragments are carved once for all ires,
23570 			 * then replicated.
23571 			 */
23572 			ASSERT(irb != NULL);
23573 			IRB_REFHOLD(irb);
23574 			for (ire1 = ire->ire_next;
23575 			    ire1 != NULL;
23576 			    ire1 = ire1->ire_next) {
23577 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23578 					continue;
23579 				if (ire1->ire_addr != ire->ire_addr)
23580 					continue;
23581 				if (ire1->ire_marks &
23582 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23583 					continue;
23584 				/*
23585 				 * Ensure we do not exceed the MTU
23586 				 * of the next route.
23587 				 */
23588 				if (ire1->ire_max_frag < max_frag) {
23589 					ip_multirt_bad_mtu(ire1, max_frag);
23590 					continue;
23591 				}
23592 
23593 				/* Got one. */
23594 				IRE_REFHOLD(ire1);
23595 				break;
23596 			}
23597 			IRB_REFRELE(irb);
23598 
23599 			if (ire1 != NULL) {
23600 				next_mp = copyb(mp);
23601 				if ((next_mp == NULL) ||
23602 				    ((mp->b_cont != NULL) &&
23603 				    ((next_mp->b_cont =
23604 				    dupmsg(mp->b_cont)) == NULL))) {
23605 					freemsg(next_mp);
23606 					next_mp = NULL;
23607 					ire_refrele(ire1);
23608 					ire1 = NULL;
23609 				}
23610 			}
23611 
23612 			/* Last multiroute ire; don't loop anymore. */
23613 			if (ire1 == NULL) {
23614 				multirt_send = B_FALSE;
23615 			}
23616 		}
23617 
23618 		ll_hdr_len = 0;
23619 		LOCK_IRE_FP_MP(ire);
23620 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23621 		if (ll_hdr_mp != NULL) {
23622 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23623 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
23624 		} else {
23625 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
23626 		}
23627 
23628 		/* If there is a transmit header, get a copy for this frag. */
23629 		/*
23630 		 * TODO: should check db_ref before calling ip_carve_mp since
23631 		 * it might give us a dup.
23632 		 */
23633 		if (!ll_hdr_mp) {
23634 			/* No xmit header. */
23635 			xmit_mp = mp;
23636 
23637 		/* We have a link-layer header that can fit in our mblk. */
23638 		} else if (mp->b_datap->db_ref == 1 &&
23639 		    ll_hdr_len != 0 &&
23640 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23641 			/* M_DATA fastpath */
23642 			mp->b_rptr -= ll_hdr_len;
23643 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
23644 			xmit_mp = mp;
23645 
23646 		/* Corner case if copyb has failed */
23647 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
23648 			UNLOCK_IRE_FP_MP(ire);
23649 			BUMP_MIB(&ip_mib, ipOutDiscards);
23650 			freeb(hdr_mp);
23651 			freemsg(mp);
23652 			freemsg(mp_orig);
23653 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23654 			    "ip_wput_frag_end:(%S)",
23655 			    "discard");
23656 
23657 			if (multirt_send) {
23658 				ASSERT(ire1);
23659 				ASSERT(next_mp);
23660 
23661 				freemsg(next_mp);
23662 				ire_refrele(ire1);
23663 			}
23664 			if (save_ire != NULL)
23665 				IRE_REFRELE(save_ire);
23666 
23667 			if (first_ire != NULL)
23668 				ire_refrele(first_ire);
23669 			return;
23670 
23671 		/*
23672 		 * Case of res_mp OR the fastpath mp can't fit
23673 		 * in the mblk
23674 		 */
23675 		} else {
23676 			xmit_mp->b_cont = mp;
23677 			if (DB_CRED(mp) != NULL)
23678 				mblk_setcred(xmit_mp, DB_CRED(mp));
23679 			/*
23680 			 * Get priority marking, if any.
23681 			 * We propagate the CoS marking from the
23682 			 * original packet that went to QoS processing
23683 			 * in ip_wput_ire to the newly carved mp.
23684 			 */
23685 			if (DB_TYPE(xmit_mp) == M_DATA)
23686 				xmit_mp->b_band = mp->b_band;
23687 		}
23688 		UNLOCK_IRE_FP_MP(ire);
23689 		q = ire->ire_stq;
23690 		BUMP_MIB(&ip_mib, ipFragCreates);
23691 
23692 		out_ill = (ill_t *)q->q_ptr;
23693 
23694 		DTRACE_PROBE4(ip4__physical__out__start,
23695 		    ill_t *, NULL, ill_t *, out_ill,
23696 		    ipha_t *, ipha, mblk_t *, xmit_mp);
23697 
23698 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
23699 		    MSG_FWCOOKED_OUT, NULL, out_ill, ipha, xmit_mp, mp);
23700 
23701 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
23702 
23703 		if (xmit_mp != NULL) {
23704 			putnext(q, xmit_mp);
23705 			if (pkt_type != OB_PKT) {
23706 				/*
23707 				 * Update the packet count of trailing
23708 				 * RTF_MULTIRT ires.
23709 				 */
23710 				UPDATE_OB_PKT_COUNT(ire);
23711 			}
23712 		}
23713 
23714 		if (multirt_send) {
23715 			/*
23716 			 * We are in a multiple send case; look for
23717 			 * the next ire and re-enter the loop.
23718 			 */
23719 			ASSERT(ire1);
23720 			ASSERT(next_mp);
23721 			/* REFRELE the current ire before looping */
23722 			ire_refrele(ire);
23723 			ire = ire1;
23724 			ire1 = NULL;
23725 			mp = next_mp;
23726 			next_mp = NULL;
23727 		}
23728 	} while (multirt_send);
23729 
23730 	ASSERT(ire1 == NULL);
23731 
23732 	/* Restore the original ire; we need it for the trailing frags */
23733 	if (save_ire != NULL) {
23734 		/* REFRELE the last iterated ire */
23735 		ire_refrele(ire);
23736 		/* save_ire has been REFHOLDed */
23737 		ire = save_ire;
23738 		save_ire = NULL;
23739 		q = ire->ire_stq;
23740 	}
23741 
23742 	if (pkt_type == OB_PKT) {
23743 		UPDATE_OB_PKT_COUNT(ire);
23744 	} else {
23745 		UPDATE_IB_PKT_COUNT(ire);
23746 	}
23747 
23748 	/* Advance the offset to the second frag starting point. */
23749 	offset += len;
23750 	/*
23751 	 * Update hdr_len from the copied header - there might be less options
23752 	 * in the later fragments.
23753 	 */
23754 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
23755 	/* Loop until done. */
23756 	for (;;) {
23757 		uint16_t	offset_and_flags;
23758 		uint16_t	ip_len;
23759 
23760 		if (ip_data_end - offset > len) {
23761 			/*
23762 			 * Carve off the appropriate amount from the original
23763 			 * datagram.
23764 			 */
23765 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23766 				mp = NULL;
23767 				break;
23768 			}
23769 			/*
23770 			 * More frags after this one.  Get another copy
23771 			 * of the header.
23772 			 */
23773 			if (carve_mp->b_datap->db_ref == 1 &&
23774 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23775 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23776 				/* Inline IP header */
23777 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23778 				    hdr_mp->b_rptr;
23779 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23780 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23781 				mp = carve_mp;
23782 			} else {
23783 				if (!(mp = copyb(hdr_mp))) {
23784 					freemsg(carve_mp);
23785 					break;
23786 				}
23787 				/* Get priority marking, if any. */
23788 				mp->b_band = carve_mp->b_band;
23789 				mp->b_cont = carve_mp;
23790 			}
23791 			ipha = (ipha_t *)mp->b_rptr;
23792 			offset_and_flags = IPH_MF;
23793 		} else {
23794 			/*
23795 			 * Last frag.  Consume the header. Set len to
23796 			 * the length of this last piece.
23797 			 */
23798 			len = ip_data_end - offset;
23799 
23800 			/*
23801 			 * Carve off the appropriate amount from the original
23802 			 * datagram.
23803 			 */
23804 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23805 				mp = NULL;
23806 				break;
23807 			}
23808 			if (carve_mp->b_datap->db_ref == 1 &&
23809 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23810 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23811 				/* Inline IP header */
23812 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23813 				    hdr_mp->b_rptr;
23814 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23815 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23816 				mp = carve_mp;
23817 				freeb(hdr_mp);
23818 				hdr_mp = mp;
23819 			} else {
23820 				mp = hdr_mp;
23821 				/* Get priority marking, if any. */
23822 				mp->b_band = carve_mp->b_band;
23823 				mp->b_cont = carve_mp;
23824 			}
23825 			ipha = (ipha_t *)mp->b_rptr;
23826 			/* A frag of a frag might have IPH_MF non-zero */
23827 			offset_and_flags =
23828 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23829 			    IPH_MF;
23830 		}
23831 		offset_and_flags |= (uint16_t)(offset >> 3);
23832 		offset_and_flags |= (uint16_t)frag_flag;
23833 		/* Store the offset and flags in the IP header. */
23834 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23835 
23836 		/* Store the length in the IP header. */
23837 		ip_len = (uint16_t)(len + hdr_len);
23838 		ipha->ipha_length = htons(ip_len);
23839 
23840 		/*
23841 		 * Set the IP header checksum.	Note that mp is just
23842 		 * the header, so this is easy to pass to ip_csum.
23843 		 */
23844 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23845 
23846 		/* Attach a transmit header, if any, and ship it. */
23847 		if (pkt_type == OB_PKT) {
23848 			UPDATE_OB_PKT_COUNT(ire);
23849 		} else {
23850 			UPDATE_IB_PKT_COUNT(ire);
23851 		}
23852 
23853 		if (ire->ire_flags & RTF_MULTIRT) {
23854 			irb = ire->ire_bucket;
23855 			ASSERT(irb != NULL);
23856 
23857 			multirt_send = B_TRUE;
23858 
23859 			/*
23860 			 * Save the original ire; we will need to restore it
23861 			 * for the tailing frags.
23862 			 */
23863 			save_ire = ire;
23864 			IRE_REFHOLD(save_ire);
23865 		}
23866 		/*
23867 		 * Emission loop for this fragment, similar
23868 		 * to what is done for the first fragment.
23869 		 */
23870 		do {
23871 			if (multirt_send) {
23872 				/*
23873 				 * We are in a multiple send case, need to get
23874 				 * the next ire and make a copy of the packet.
23875 				 */
23876 				ASSERT(irb != NULL);
23877 				IRB_REFHOLD(irb);
23878 				for (ire1 = ire->ire_next;
23879 				    ire1 != NULL;
23880 				    ire1 = ire1->ire_next) {
23881 					if (!(ire1->ire_flags & RTF_MULTIRT))
23882 						continue;
23883 					if (ire1->ire_addr != ire->ire_addr)
23884 						continue;
23885 					if (ire1->ire_marks &
23886 					    (IRE_MARK_CONDEMNED|
23887 						IRE_MARK_HIDDEN))
23888 						continue;
23889 					/*
23890 					 * Ensure we do not exceed the MTU
23891 					 * of the next route.
23892 					 */
23893 					if (ire1->ire_max_frag < max_frag) {
23894 						ip_multirt_bad_mtu(ire1,
23895 						    max_frag);
23896 						continue;
23897 					}
23898 
23899 					/* Got one. */
23900 					IRE_REFHOLD(ire1);
23901 					break;
23902 				}
23903 				IRB_REFRELE(irb);
23904 
23905 				if (ire1 != NULL) {
23906 					next_mp = copyb(mp);
23907 					if ((next_mp == NULL) ||
23908 					    ((mp->b_cont != NULL) &&
23909 					    ((next_mp->b_cont =
23910 					    dupmsg(mp->b_cont)) == NULL))) {
23911 						freemsg(next_mp);
23912 						next_mp = NULL;
23913 						ire_refrele(ire1);
23914 						ire1 = NULL;
23915 					}
23916 				}
23917 
23918 				/* Last multiroute ire; don't loop anymore. */
23919 				if (ire1 == NULL) {
23920 					multirt_send = B_FALSE;
23921 				}
23922 			}
23923 
23924 			/* Update transmit header */
23925 			ll_hdr_len = 0;
23926 			LOCK_IRE_FP_MP(ire);
23927 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23928 			if (ll_hdr_mp != NULL) {
23929 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23930 				ll_hdr_len = MBLKL(ll_hdr_mp);
23931 			} else {
23932 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
23933 			}
23934 
23935 			if (!ll_hdr_mp) {
23936 				xmit_mp = mp;
23937 
23938 			/*
23939 			 * We have link-layer header that can fit in
23940 			 * our mblk.
23941 			 */
23942 			} else if (mp->b_datap->db_ref == 1 &&
23943 			    ll_hdr_len != 0 &&
23944 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23945 				/* M_DATA fastpath */
23946 				mp->b_rptr -= ll_hdr_len;
23947 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
23948 				    ll_hdr_len);
23949 				xmit_mp = mp;
23950 
23951 			/*
23952 			 * Case of res_mp OR the fastpath mp can't fit
23953 			 * in the mblk
23954 			 */
23955 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
23956 				xmit_mp->b_cont = mp;
23957 				if (DB_CRED(mp) != NULL)
23958 					mblk_setcred(xmit_mp, DB_CRED(mp));
23959 				/* Get priority marking, if any. */
23960 				if (DB_TYPE(xmit_mp) == M_DATA)
23961 					xmit_mp->b_band = mp->b_band;
23962 
23963 			/* Corner case if copyb failed */
23964 			} else {
23965 				/*
23966 				 * Exit both the replication and
23967 				 * fragmentation loops.
23968 				 */
23969 				UNLOCK_IRE_FP_MP(ire);
23970 				goto drop_pkt;
23971 			}
23972 			UNLOCK_IRE_FP_MP(ire);
23973 			BUMP_MIB(&ip_mib, ipFragCreates);
23974 
23975 			mp1 = mp;
23976 			out_ill = (ill_t *)q->q_ptr;
23977 
23978 			DTRACE_PROBE4(ip4__physical__out__start,
23979 			    ill_t *, NULL, ill_t *, out_ill,
23980 			    ipha_t *, ipha, mblk_t *, xmit_mp);
23981 
23982 			FW_HOOKS(ip4_physical_out_event,
23983 			    ipv4firewall_physical_out, MSG_FWCOOKED_OUT,
23984 			    NULL, out_ill, ipha, xmit_mp, mp);
23985 
23986 			DTRACE_PROBE1(ip4__physical__out__end,
23987 			    mblk_t *, xmit_mp);
23988 
23989 			if (mp != mp1 && hdr_mp == mp1)
23990 				hdr_mp = mp;
23991 			if (mp != mp1 && mp_orig == mp1)
23992 				mp_orig = mp;
23993 
23994 			if (xmit_mp != NULL) {
23995 				putnext(q, xmit_mp);
23996 
23997 				if (pkt_type != OB_PKT) {
23998 					/*
23999 					 * Update the packet count of trailing
24000 					 * RTF_MULTIRT ires.
24001 					 */
24002 					UPDATE_OB_PKT_COUNT(ire);
24003 				}
24004 			}
24005 
24006 			/* All done if we just consumed the hdr_mp. */
24007 			if (mp == hdr_mp) {
24008 				last_frag = B_TRUE;
24009 			}
24010 
24011 			if (multirt_send) {
24012 				/*
24013 				 * We are in a multiple send case; look for
24014 				 * the next ire and re-enter the loop.
24015 				 */
24016 				ASSERT(ire1);
24017 				ASSERT(next_mp);
24018 				/* REFRELE the current ire before looping */
24019 				ire_refrele(ire);
24020 				ire = ire1;
24021 				ire1 = NULL;
24022 				q = ire->ire_stq;
24023 				mp = next_mp;
24024 				next_mp = NULL;
24025 			}
24026 		} while (multirt_send);
24027 		/*
24028 		 * Restore the original ire; we need it for the
24029 		 * trailing frags
24030 		 */
24031 		if (save_ire != NULL) {
24032 			ASSERT(ire1 == NULL);
24033 			/* REFRELE the last iterated ire */
24034 			ire_refrele(ire);
24035 			/* save_ire has been REFHOLDed */
24036 			ire = save_ire;
24037 			q = ire->ire_stq;
24038 			save_ire = NULL;
24039 		}
24040 
24041 		if (last_frag) {
24042 			BUMP_MIB(&ip_mib, ipFragOKs);
24043 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24044 			    "ip_wput_frag_end:(%S)",
24045 			    "consumed hdr_mp");
24046 
24047 			if (first_ire != NULL)
24048 				ire_refrele(first_ire);
24049 			return;
24050 		}
24051 		/* Otherwise, advance and loop. */
24052 		offset += len;
24053 	}
24054 
24055 drop_pkt:
24056 	/* Clean up following allocation failure. */
24057 	BUMP_MIB(&ip_mib, ipOutDiscards);
24058 	freemsg(mp);
24059 	if (mp != hdr_mp)
24060 		freeb(hdr_mp);
24061 	if (mp != mp_orig)
24062 		freemsg(mp_orig);
24063 
24064 	if (save_ire != NULL)
24065 		IRE_REFRELE(save_ire);
24066 	if (first_ire != NULL)
24067 		ire_refrele(first_ire);
24068 
24069 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24070 	    "ip_wput_frag_end:(%S)",
24071 	    "end--alloc failure");
24072 }
24073 
24074 /*
24075  * Copy the header plus those options which have the copy bit set
24076  */
24077 static mblk_t *
24078 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
24079 {
24080 	mblk_t	*mp;
24081 	uchar_t	*up;
24082 
24083 	/*
24084 	 * Quick check if we need to look for options without the copy bit
24085 	 * set
24086 	 */
24087 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
24088 	if (!mp)
24089 		return (mp);
24090 	mp->b_rptr += ip_wroff_extra;
24091 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24092 		bcopy(rptr, mp->b_rptr, hdr_len);
24093 		mp->b_wptr += hdr_len + ip_wroff_extra;
24094 		return (mp);
24095 	}
24096 	up  = mp->b_rptr;
24097 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24098 	up += IP_SIMPLE_HDR_LENGTH;
24099 	rptr += IP_SIMPLE_HDR_LENGTH;
24100 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24101 	while (hdr_len > 0) {
24102 		uint32_t optval;
24103 		uint32_t optlen;
24104 
24105 		optval = *rptr;
24106 		if (optval == IPOPT_EOL)
24107 			break;
24108 		if (optval == IPOPT_NOP)
24109 			optlen = 1;
24110 		else
24111 			optlen = rptr[1];
24112 		if (optval & IPOPT_COPY) {
24113 			bcopy(rptr, up, optlen);
24114 			up += optlen;
24115 		}
24116 		rptr += optlen;
24117 		hdr_len -= optlen;
24118 	}
24119 	/*
24120 	 * Make sure that we drop an even number of words by filling
24121 	 * with EOL to the next word boundary.
24122 	 */
24123 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24124 	    hdr_len & 0x3; hdr_len++)
24125 		*up++ = IPOPT_EOL;
24126 	mp->b_wptr = up;
24127 	/* Update header length */
24128 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24129 	return (mp);
24130 }
24131 
24132 /*
24133  * Delivery to local recipients including fanout to multiple recipients.
24134  * Does not do checksumming of UDP/TCP.
24135  * Note: q should be the read side queue for either the ill or conn.
24136  * Note: rq should be the read side q for the lower (ill) stream.
24137  * We don't send packets to IPPF processing, thus the last argument
24138  * to all the fanout calls are B_FALSE.
24139  */
24140 void
24141 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24142     int fanout_flags, zoneid_t zoneid)
24143 {
24144 	uint32_t	protocol;
24145 	mblk_t		*first_mp;
24146 	boolean_t	mctl_present;
24147 	int		ire_type;
24148 #define	rptr	((uchar_t *)ipha)
24149 
24150 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24151 	    "ip_wput_local_start: q %p", q);
24152 
24153 	if (ire != NULL) {
24154 		ire_type = ire->ire_type;
24155 	} else {
24156 		/*
24157 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24158 		 * packet is not multicast, we can't tell the ire type.
24159 		 */
24160 		ASSERT(CLASSD(ipha->ipha_dst));
24161 		ire_type = IRE_BROADCAST;
24162 	}
24163 
24164 	first_mp = mp;
24165 	if (first_mp->b_datap->db_type == M_CTL) {
24166 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24167 		if (!io->ipsec_out_secure) {
24168 			/*
24169 			 * This ipsec_out_t was allocated in ip_wput
24170 			 * for multicast packets to store the ill_index.
24171 			 * As this is being delivered locally, we don't
24172 			 * need this anymore.
24173 			 */
24174 			mp = first_mp->b_cont;
24175 			freeb(first_mp);
24176 			first_mp = mp;
24177 			mctl_present = B_FALSE;
24178 		} else {
24179 			mctl_present = B_TRUE;
24180 			mp = first_mp->b_cont;
24181 			ASSERT(mp != NULL);
24182 			ipsec_out_to_in(first_mp);
24183 		}
24184 	} else {
24185 		mctl_present = B_FALSE;
24186 	}
24187 
24188 	DTRACE_PROBE4(ip4__loopback__in__start,
24189 	    ill_t *, ill, ill_t *, NULL,
24190 	    ipha_t *, ipha, mblk_t *, first_mp);
24191 
24192 	FW_HOOKS(ip4_loopback_in_event, ipv4firewall_loopback_in,
24193 	    MSG_FWCOOKED_IN, ill, NULL, ipha, first_mp, mp);
24194 
24195 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24196 
24197 	if (first_mp == NULL)
24198 		return;
24199 
24200 	loopback_packets++;
24201 
24202 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24203 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24204 	if (!IS_SIMPLE_IPH(ipha)) {
24205 		ip_wput_local_options(ipha);
24206 	}
24207 
24208 	protocol = ipha->ipha_protocol;
24209 	switch (protocol) {
24210 	case IPPROTO_ICMP: {
24211 		ire_t		*ire_zone;
24212 		ilm_t		*ilm;
24213 		mblk_t		*mp1;
24214 		zoneid_t	last_zoneid;
24215 
24216 		if (CLASSD(ipha->ipha_dst) &&
24217 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
24218 			ASSERT(ire_type == IRE_BROADCAST);
24219 			/*
24220 			 * In the multicast case, applications may have joined
24221 			 * the group from different zones, so we need to deliver
24222 			 * the packet to each of them. Loop through the
24223 			 * multicast memberships structures (ilm) on the receive
24224 			 * ill and send a copy of the packet up each matching
24225 			 * one. However, we don't do this for multicasts sent on
24226 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24227 			 * they must stay in the sender's zone.
24228 			 *
24229 			 * ilm_add_v6() ensures that ilms in the same zone are
24230 			 * contiguous in the ill_ilm list. We use this property
24231 			 * to avoid sending duplicates needed when two
24232 			 * applications in the same zone join the same group on
24233 			 * different logical interfaces: we ignore the ilm if
24234 			 * it's zoneid is the same as the last matching one.
24235 			 * In addition, the sending of the packet for
24236 			 * ire_zoneid is delayed until all of the other ilms
24237 			 * have been exhausted.
24238 			 */
24239 			last_zoneid = -1;
24240 			ILM_WALKER_HOLD(ill);
24241 			for (ilm = ill->ill_ilm; ilm != NULL;
24242 			    ilm = ilm->ilm_next) {
24243 				if ((ilm->ilm_flags & ILM_DELETED) ||
24244 				    ipha->ipha_dst != ilm->ilm_addr ||
24245 				    ilm->ilm_zoneid == last_zoneid ||
24246 				    ilm->ilm_zoneid == zoneid ||
24247 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24248 					continue;
24249 				mp1 = ip_copymsg(first_mp);
24250 				if (mp1 == NULL)
24251 					continue;
24252 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24253 				    mctl_present, B_FALSE, ill,
24254 				    ilm->ilm_zoneid);
24255 				last_zoneid = ilm->ilm_zoneid;
24256 			}
24257 			ILM_WALKER_RELE(ill);
24258 			/*
24259 			 * Loopback case: the sending endpoint has
24260 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24261 			 * dispatch the multicast packet to the sending zone.
24262 			 */
24263 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24264 				freemsg(first_mp);
24265 				return;
24266 			}
24267 		} else if (ire_type == IRE_BROADCAST) {
24268 			/*
24269 			 * In the broadcast case, there may be many zones
24270 			 * which need a copy of the packet delivered to them.
24271 			 * There is one IRE_BROADCAST per broadcast address
24272 			 * and per zone; we walk those using a helper function.
24273 			 * In addition, the sending of the packet for zoneid is
24274 			 * delayed until all of the other ires have been
24275 			 * processed.
24276 			 */
24277 			IRB_REFHOLD(ire->ire_bucket);
24278 			ire_zone = NULL;
24279 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24280 			    ire)) != NULL) {
24281 				mp1 = ip_copymsg(first_mp);
24282 				if (mp1 == NULL)
24283 					continue;
24284 
24285 				UPDATE_IB_PKT_COUNT(ire_zone);
24286 				ire_zone->ire_last_used_time = lbolt;
24287 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24288 				    mctl_present, B_FALSE, ill,
24289 				    ire_zone->ire_zoneid);
24290 			}
24291 			IRB_REFRELE(ire->ire_bucket);
24292 		}
24293 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
24294 		    0, mctl_present, B_FALSE, ill, zoneid);
24295 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24296 		    "ip_wput_local_end: q %p (%S)",
24297 		    q, "icmp");
24298 		return;
24299 	}
24300 	case IPPROTO_IGMP:
24301 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
24302 			/* Bad packet - discarded by igmp_input */
24303 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24304 			    "ip_wput_local_end: q %p (%S)",
24305 			    q, "igmp_input--bad packet");
24306 			if (mctl_present)
24307 				freeb(first_mp);
24308 			return;
24309 		}
24310 		/*
24311 		 * igmp_input() may have returned the pulled up message.
24312 		 * So first_mp and ipha need to be reinitialized.
24313 		 */
24314 		ipha = (ipha_t *)mp->b_rptr;
24315 		if (mctl_present)
24316 			first_mp->b_cont = mp;
24317 		else
24318 			first_mp = mp;
24319 		/* deliver to local raw users */
24320 		break;
24321 	case IPPROTO_ENCAP:
24322 		/*
24323 		 * This case is covered by either ip_fanout_proto, or by
24324 		 * the above security processing for self-tunneled packets.
24325 		 */
24326 		break;
24327 	case IPPROTO_UDP: {
24328 		uint16_t	*up;
24329 		uint32_t	ports;
24330 
24331 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
24332 		    UDP_PORTS_OFFSET);
24333 		/* Force a 'valid' checksum. */
24334 		up[3] = 0;
24335 
24336 		ports = *(uint32_t *)up;
24337 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24338 		    (ire_type == IRE_BROADCAST),
24339 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24340 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
24341 		    ill, zoneid);
24342 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24343 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24344 		return;
24345 	}
24346 	case IPPROTO_TCP: {
24347 
24348 		/*
24349 		 * For TCP, discard broadcast packets.
24350 		 */
24351 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24352 			freemsg(first_mp);
24353 			BUMP_MIB(&ip_mib, ipInDiscards);
24354 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24355 			return;
24356 		}
24357 
24358 		if (mp->b_datap->db_type == M_DATA) {
24359 			/*
24360 			 * M_DATA mblk, so init mblk (chain) for no struio().
24361 			 */
24362 			mblk_t	*mp1 = mp;
24363 
24364 			do
24365 				mp1->b_datap->db_struioflag = 0;
24366 			while ((mp1 = mp1->b_cont) != NULL);
24367 		}
24368 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24369 		    <= mp->b_wptr);
24370 		ip_fanout_tcp(q, first_mp, ill, ipha,
24371 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24372 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
24373 		    mctl_present, B_FALSE, zoneid);
24374 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24375 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24376 		return;
24377 	}
24378 	case IPPROTO_SCTP:
24379 	{
24380 		uint32_t	ports;
24381 
24382 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24383 		ip_fanout_sctp(first_mp, ill, ipha, ports,
24384 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24385 		    IP_FF_IP6INFO,
24386 		    mctl_present, B_FALSE, 0, zoneid);
24387 		return;
24388 	}
24389 
24390 	default:
24391 		break;
24392 	}
24393 	/*
24394 	 * Find a client for some other protocol.  We give
24395 	 * copies to multiple clients, if more than one is
24396 	 * bound.
24397 	 */
24398 	ip_fanout_proto(q, first_mp, ill, ipha,
24399 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
24400 	    mctl_present, B_FALSE, ill, zoneid);
24401 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24402 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
24403 #undef	rptr
24404 }
24405 
24406 /*
24407  * Update any source route, record route, or timestamp options.
24408  * Check that we are at end of strict source route.
24409  * The options have been sanity checked by ip_wput_options().
24410  */
24411 static void
24412 ip_wput_local_options(ipha_t *ipha)
24413 {
24414 	ipoptp_t	opts;
24415 	uchar_t		*opt;
24416 	uint8_t		optval;
24417 	uint8_t		optlen;
24418 	ipaddr_t	dst;
24419 	uint32_t	ts;
24420 	ire_t		*ire;
24421 	timestruc_t	now;
24422 
24423 	ip2dbg(("ip_wput_local_options\n"));
24424 	for (optval = ipoptp_first(&opts, ipha);
24425 	    optval != IPOPT_EOL;
24426 	    optval = ipoptp_next(&opts)) {
24427 		opt = opts.ipoptp_cur;
24428 		optlen = opts.ipoptp_len;
24429 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
24430 		switch (optval) {
24431 			uint32_t off;
24432 		case IPOPT_SSRR:
24433 		case IPOPT_LSRR:
24434 			off = opt[IPOPT_OFFSET];
24435 			off--;
24436 			if (optlen < IP_ADDR_LEN ||
24437 			    off > optlen - IP_ADDR_LEN) {
24438 				/* End of source route */
24439 				break;
24440 			}
24441 			/*
24442 			 * This will only happen if two consecutive entries
24443 			 * in the source route contains our address or if
24444 			 * it is a packet with a loose source route which
24445 			 * reaches us before consuming the whole source route
24446 			 */
24447 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
24448 			if (optval == IPOPT_SSRR) {
24449 				return;
24450 			}
24451 			/*
24452 			 * Hack: instead of dropping the packet truncate the
24453 			 * source route to what has been used by filling the
24454 			 * rest with IPOPT_NOP.
24455 			 */
24456 			opt[IPOPT_OLEN] = (uint8_t)off;
24457 			while (off < optlen) {
24458 				opt[off++] = IPOPT_NOP;
24459 			}
24460 			break;
24461 		case IPOPT_RR:
24462 			off = opt[IPOPT_OFFSET];
24463 			off--;
24464 			if (optlen < IP_ADDR_LEN ||
24465 			    off > optlen - IP_ADDR_LEN) {
24466 				/* No more room - ignore */
24467 				ip1dbg((
24468 				    "ip_wput_forward_options: end of RR\n"));
24469 				break;
24470 			}
24471 			dst = htonl(INADDR_LOOPBACK);
24472 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24473 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24474 			break;
24475 		case IPOPT_TS:
24476 			/* Insert timestamp if there is romm */
24477 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24478 			case IPOPT_TS_TSONLY:
24479 				off = IPOPT_TS_TIMELEN;
24480 				break;
24481 			case IPOPT_TS_PRESPEC:
24482 			case IPOPT_TS_PRESPEC_RFC791:
24483 				/* Verify that the address matched */
24484 				off = opt[IPOPT_OFFSET] - 1;
24485 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
24486 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
24487 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
24488 				if (ire == NULL) {
24489 					/* Not for us */
24490 					break;
24491 				}
24492 				ire_refrele(ire);
24493 				/* FALLTHRU */
24494 			case IPOPT_TS_TSANDADDR:
24495 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24496 				break;
24497 			default:
24498 				/*
24499 				 * ip_*put_options should have already
24500 				 * dropped this packet.
24501 				 */
24502 				cmn_err(CE_PANIC, "ip_wput_local_options: "
24503 				    "unknown IT - bug in ip_wput_options?\n");
24504 				return;	/* Keep "lint" happy */
24505 			}
24506 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
24507 				/* Increase overflow counter */
24508 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
24509 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
24510 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
24511 				    (off << 4);
24512 				break;
24513 			}
24514 			off = opt[IPOPT_OFFSET] - 1;
24515 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24516 			case IPOPT_TS_PRESPEC:
24517 			case IPOPT_TS_PRESPEC_RFC791:
24518 			case IPOPT_TS_TSANDADDR:
24519 				dst = htonl(INADDR_LOOPBACK);
24520 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24521 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24522 				/* FALLTHRU */
24523 			case IPOPT_TS_TSONLY:
24524 				off = opt[IPOPT_OFFSET] - 1;
24525 				/* Compute # of milliseconds since midnight */
24526 				gethrestime(&now);
24527 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
24528 				    now.tv_nsec / (NANOSEC / MILLISEC);
24529 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
24530 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
24531 				break;
24532 			}
24533 			break;
24534 		}
24535 	}
24536 }
24537 
24538 /*
24539  * Send out a multicast packet on interface ipif.
24540  * The sender does not have an conn.
24541  * Caller verifies that this isn't a PHYI_LOOPBACK.
24542  */
24543 void
24544 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
24545 {
24546 	ipha_t	*ipha;
24547 	ire_t	*ire;
24548 	ipaddr_t	dst;
24549 	mblk_t		*first_mp;
24550 
24551 	/* igmp_sendpkt always allocates a ipsec_out_t */
24552 	ASSERT(mp->b_datap->db_type == M_CTL);
24553 	ASSERT(!ipif->ipif_isv6);
24554 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
24555 
24556 	first_mp = mp;
24557 	mp = first_mp->b_cont;
24558 	ASSERT(mp->b_datap->db_type == M_DATA);
24559 	ipha = (ipha_t *)mp->b_rptr;
24560 
24561 	/*
24562 	 * Find an IRE which matches the destination and the outgoing
24563 	 * queue (i.e. the outgoing interface.)
24564 	 */
24565 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
24566 		dst = ipif->ipif_pp_dst_addr;
24567 	else
24568 		dst = ipha->ipha_dst;
24569 	/*
24570 	 * The source address has already been initialized by the
24571 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
24572 	 * be sufficient rather than MATCH_IRE_IPIF.
24573 	 *
24574 	 * This function is used for sending IGMP packets. We need
24575 	 * to make sure that we send the packet out of the interface
24576 	 * (ipif->ipif_ill) where we joined the group. This is to
24577 	 * prevent from switches doing IGMP snooping to send us multicast
24578 	 * packets for a given group on the interface we have joined.
24579 	 * If we can't find an ire, igmp_sendpkt has already initialized
24580 	 * ipsec_out_attach_if so that this will not be load spread in
24581 	 * ip_newroute_ipif.
24582 	 */
24583 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
24584 	    MATCH_IRE_ILL);
24585 	if (!ire) {
24586 		/*
24587 		 * Mark this packet to make it be delivered to
24588 		 * ip_wput_ire after the new ire has been
24589 		 * created.
24590 		 */
24591 		mp->b_prev = NULL;
24592 		mp->b_next = NULL;
24593 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
24594 		    zoneid);
24595 		return;
24596 	}
24597 
24598 	/*
24599 	 * Honor the RTF_SETSRC flag; this is the only case
24600 	 * where we force this addr whatever the current src addr is,
24601 	 * because this address is set by igmp_sendpkt(), and
24602 	 * cannot be specified by any user.
24603 	 */
24604 	if (ire->ire_flags & RTF_SETSRC) {
24605 		ipha->ipha_src = ire->ire_src_addr;
24606 	}
24607 
24608 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
24609 }
24610 
24611 /*
24612  * NOTE : This function does not ire_refrele the ire argument passed in.
24613  *
24614  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
24615  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
24616  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
24617  * the ire_lock to access the nce_fp_mp in this case.
24618  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
24619  * prepending a fastpath message IPQoS processing must precede it, we also set
24620  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
24621  * (IPQoS might have set the b_band for CoS marking).
24622  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
24623  * must follow it so that IPQoS can mark the dl_priority field for CoS
24624  * marking, if needed.
24625  */
24626 static mblk_t *
24627 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
24628 {
24629 	uint_t	hlen;
24630 	ipha_t *ipha;
24631 	mblk_t *mp1;
24632 	boolean_t qos_done = B_FALSE;
24633 	uchar_t	*ll_hdr;
24634 
24635 #define	rptr	((uchar_t *)ipha)
24636 
24637 	ipha = (ipha_t *)mp->b_rptr;
24638 	hlen = 0;
24639 	LOCK_IRE_FP_MP(ire);
24640 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
24641 		ASSERT(DB_TYPE(mp1) == M_DATA);
24642 		/* Initiate IPPF processing */
24643 		if ((proc != 0) && IPP_ENABLED(proc)) {
24644 			UNLOCK_IRE_FP_MP(ire);
24645 			ip_process(proc, &mp, ill_index);
24646 			if (mp == NULL)
24647 				return (NULL);
24648 
24649 			ipha = (ipha_t *)mp->b_rptr;
24650 			LOCK_IRE_FP_MP(ire);
24651 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
24652 				qos_done = B_TRUE;
24653 				goto no_fp_mp;
24654 			}
24655 			ASSERT(DB_TYPE(mp1) == M_DATA);
24656 		}
24657 		hlen = MBLKL(mp1);
24658 		/*
24659 		 * Check if we have enough room to prepend fastpath
24660 		 * header
24661 		 */
24662 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
24663 			ll_hdr = rptr - hlen;
24664 			bcopy(mp1->b_rptr, ll_hdr, hlen);
24665 			/*
24666 			 * Set the b_rptr to the start of the link layer
24667 			 * header
24668 			 */
24669 			mp->b_rptr = ll_hdr;
24670 			mp1 = mp;
24671 		} else {
24672 			mp1 = copyb(mp1);
24673 			if (mp1 == NULL)
24674 				goto unlock_err;
24675 			mp1->b_band = mp->b_band;
24676 			mp1->b_cont = mp;
24677 			/*
24678 			 * certain system generated traffic may not
24679 			 * have cred/label in ip header block. This
24680 			 * is true even for a labeled system. But for
24681 			 * labeled traffic, inherit the label in the
24682 			 * new header.
24683 			 */
24684 			if (DB_CRED(mp) != NULL)
24685 				mblk_setcred(mp1, DB_CRED(mp));
24686 			/*
24687 			 * XXX disable ICK_VALID and compute checksum
24688 			 * here; can happen if nce_fp_mp changes and
24689 			 * it can't be copied now due to insufficient
24690 			 * space. (unlikely, fp mp can change, but it
24691 			 * does not increase in length)
24692 			 */
24693 		}
24694 		UNLOCK_IRE_FP_MP(ire);
24695 	} else {
24696 no_fp_mp:
24697 		mp1 = copyb(ire->ire_nce->nce_res_mp);
24698 		if (mp1 == NULL) {
24699 unlock_err:
24700 			UNLOCK_IRE_FP_MP(ire);
24701 			freemsg(mp);
24702 			return (NULL);
24703 		}
24704 		UNLOCK_IRE_FP_MP(ire);
24705 		mp1->b_cont = mp;
24706 		/*
24707 		 * certain system generated traffic may not
24708 		 * have cred/label in ip header block. This
24709 		 * is true even for a labeled system. But for
24710 		 * labeled traffic, inherit the label in the
24711 		 * new header.
24712 		 */
24713 		if (DB_CRED(mp) != NULL)
24714 			mblk_setcred(mp1, DB_CRED(mp));
24715 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
24716 			ip_process(proc, &mp1, ill_index);
24717 			if (mp1 == NULL)
24718 				return (NULL);
24719 		}
24720 	}
24721 	return (mp1);
24722 #undef rptr
24723 }
24724 
24725 /*
24726  * Finish the outbound IPsec processing for an IPv6 packet. This function
24727  * is called from ipsec_out_process() if the IPsec packet was processed
24728  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24729  * asynchronously.
24730  */
24731 void
24732 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
24733     ire_t *ire_arg)
24734 {
24735 	in6_addr_t *v6dstp;
24736 	ire_t *ire;
24737 	mblk_t *mp;
24738 	uint_t	ill_index;
24739 	ipsec_out_t *io;
24740 	boolean_t attach_if, hwaccel;
24741 	uint32_t flags = IP6_NO_IPPOLICY;
24742 	int match_flags;
24743 	zoneid_t zoneid;
24744 	boolean_t ill_need_rele = B_FALSE;
24745 	boolean_t ire_need_rele = B_FALSE;
24746 	ill_t *out_ill;
24747 
24748 	mp = ipsec_mp->b_cont;
24749 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24750 	ill_index = io->ipsec_out_ill_index;
24751 	if (io->ipsec_out_reachable) {
24752 		flags |= IPV6_REACHABILITY_CONFIRMATION;
24753 	}
24754 	attach_if = io->ipsec_out_attach_if;
24755 	hwaccel = io->ipsec_out_accelerated;
24756 	zoneid = io->ipsec_out_zoneid;
24757 	ASSERT(zoneid != ALL_ZONES);
24758 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24759 	/* Multicast addresses should have non-zero ill_index. */
24760 	v6dstp = &ip6h->ip6_dst;
24761 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
24762 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
24763 	ASSERT(!attach_if || ill_index != 0);
24764 	if (ill_index != 0) {
24765 		if (ill == NULL) {
24766 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
24767 			    B_TRUE);
24768 
24769 			/* Failure case frees things for us. */
24770 			if (ill == NULL)
24771 				return;
24772 
24773 			ill_need_rele = B_TRUE;
24774 		}
24775 		/*
24776 		 * If this packet needs to go out on a particular interface
24777 		 * honor it.
24778 		 */
24779 		if (attach_if) {
24780 			match_flags = MATCH_IRE_ILL;
24781 
24782 			/*
24783 			 * Check if we need an ire that will not be
24784 			 * looked up by anybody else i.e. HIDDEN.
24785 			 */
24786 			if (ill_is_probeonly(ill)) {
24787 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24788 			}
24789 		}
24790 	}
24791 	ASSERT(mp != NULL);
24792 
24793 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
24794 		boolean_t unspec_src;
24795 		ipif_t	*ipif;
24796 
24797 		/*
24798 		 * Use the ill_index to get the right ill.
24799 		 */
24800 		unspec_src = io->ipsec_out_unspec_src;
24801 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24802 		if (ipif == NULL) {
24803 			if (ill_need_rele)
24804 				ill_refrele(ill);
24805 			freemsg(ipsec_mp);
24806 			return;
24807 		}
24808 
24809 		if (ire_arg != NULL) {
24810 			ire = ire_arg;
24811 		} else {
24812 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24813 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24814 			ire_need_rele = B_TRUE;
24815 		}
24816 		if (ire != NULL) {
24817 			ipif_refrele(ipif);
24818 			/*
24819 			 * XXX Do the multicast forwarding now, as the IPSEC
24820 			 * processing has been done.
24821 			 */
24822 			goto send;
24823 		}
24824 
24825 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
24826 		mp->b_prev = NULL;
24827 		mp->b_next = NULL;
24828 
24829 		/*
24830 		 * If the IPsec packet was processed asynchronously,
24831 		 * drop it now.
24832 		 */
24833 		if (q == NULL) {
24834 			if (ill_need_rele)
24835 				ill_refrele(ill);
24836 			freemsg(ipsec_mp);
24837 			return;
24838 		}
24839 
24840 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
24841 		    unspec_src, zoneid);
24842 		ipif_refrele(ipif);
24843 	} else {
24844 		if (attach_if) {
24845 			ipif_t	*ipif;
24846 
24847 			ipif = ipif_get_next_ipif(NULL, ill);
24848 			if (ipif == NULL) {
24849 				if (ill_need_rele)
24850 					ill_refrele(ill);
24851 				freemsg(ipsec_mp);
24852 				return;
24853 			}
24854 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24855 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24856 			ire_need_rele = B_TRUE;
24857 			ipif_refrele(ipif);
24858 		} else {
24859 			if (ire_arg != NULL) {
24860 				ire = ire_arg;
24861 			} else {
24862 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
24863 				ire_need_rele = B_TRUE;
24864 			}
24865 		}
24866 		if (ire != NULL)
24867 			goto send;
24868 		/*
24869 		 * ire disappeared underneath.
24870 		 *
24871 		 * What we need to do here is the ip_newroute
24872 		 * logic to get the ire without doing the IPSEC
24873 		 * processing. Follow the same old path. But this
24874 		 * time, ip_wput or ire_add_then_send will call us
24875 		 * directly as all the IPSEC operations are done.
24876 		 */
24877 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
24878 		mp->b_prev = NULL;
24879 		mp->b_next = NULL;
24880 
24881 		/*
24882 		 * If the IPsec packet was processed asynchronously,
24883 		 * drop it now.
24884 		 */
24885 		if (q == NULL) {
24886 			if (ill_need_rele)
24887 				ill_refrele(ill);
24888 			freemsg(ipsec_mp);
24889 			return;
24890 		}
24891 
24892 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
24893 		    zoneid);
24894 	}
24895 	if (ill != NULL && ill_need_rele)
24896 		ill_refrele(ill);
24897 	return;
24898 send:
24899 	if (ill != NULL && ill_need_rele)
24900 		ill_refrele(ill);
24901 
24902 	/* Local delivery */
24903 	if (ire->ire_stq == NULL) {
24904 		ASSERT(q != NULL);
24905 
24906 		/* PFHooks: LOOPBACK_OUT */
24907 		out_ill = ire->ire_ipif->ipif_ill;
24908 
24909 		DTRACE_PROBE4(ip6__loopback__out__start,
24910 		    ill_t *, NULL, ill_t *, out_ill,
24911 		    ip6_t *, ip6h, mblk_t *, ipsec_mp);
24912 
24913 		FW_HOOKS6(ip6_loopback_out_event, ipv6firewall_loopback_out,
24914 		    MSG_FWCOOKED_OUT, NULL, out_ill, ip6h,
24915 		    ipsec_mp, mp);
24916 
24917 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
24918 
24919 		if (ipsec_mp != NULL)
24920 			ip_wput_local_v6(RD(q), out_ill,
24921 			    ip6h, ipsec_mp, ire, 0);
24922 		if (ire_need_rele)
24923 			ire_refrele(ire);
24924 		return;
24925 	}
24926 	/*
24927 	 * Everything is done. Send it out on the wire.
24928 	 * We force the insertion of a fragment header using the
24929 	 * IPH_FRAG_HDR flag in two cases:
24930 	 * - after reception of an ICMPv6 "packet too big" message
24931 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
24932 	 * - for multirouted IPv6 packets, so that the receiver can
24933 	 *   discard duplicates according to their fragment identifier
24934 	 */
24935 	/* XXX fix flow control problems. */
24936 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
24937 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
24938 		if (hwaccel) {
24939 			/*
24940 			 * hardware acceleration does not handle these
24941 			 * "slow path" cases.
24942 			 */
24943 			/* IPsec KSTATS: should bump bean counter here. */
24944 			if (ire_need_rele)
24945 				ire_refrele(ire);
24946 			freemsg(ipsec_mp);
24947 			return;
24948 		}
24949 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
24950 		    (mp->b_cont ? msgdsize(mp) :
24951 		    mp->b_wptr - (uchar_t *)ip6h)) {
24952 			/* IPsec KSTATS: should bump bean counter here. */
24953 			ip0dbg(("Packet length mismatch: %d, %ld\n",
24954 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
24955 			    msgdsize(mp)));
24956 			if (ire_need_rele)
24957 				ire_refrele(ire);
24958 			freemsg(ipsec_mp);
24959 			return;
24960 		}
24961 		ASSERT(mp->b_prev == NULL);
24962 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
24963 		    ntohs(ip6h->ip6_plen) +
24964 		    IPV6_HDR_LEN, ire->ire_max_frag));
24965 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
24966 		    ire->ire_max_frag);
24967 	} else {
24968 		UPDATE_OB_PKT_COUNT(ire);
24969 		ire->ire_last_used_time = lbolt;
24970 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
24971 	}
24972 	if (ire_need_rele)
24973 		ire_refrele(ire);
24974 	freeb(ipsec_mp);
24975 }
24976 
24977 void
24978 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
24979 {
24980 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
24981 	da_ipsec_t *hada;	/* data attributes */
24982 	ill_t *ill = (ill_t *)q->q_ptr;
24983 
24984 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
24985 
24986 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
24987 		/* IPsec KSTATS: Bump lose counter here! */
24988 		freemsg(mp);
24989 		return;
24990 	}
24991 
24992 	/*
24993 	 * It's an IPsec packet that must be
24994 	 * accelerated by the Provider, and the
24995 	 * outbound ill is IPsec acceleration capable.
24996 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
24997 	 * to the ill.
24998 	 * IPsec KSTATS: should bump packet counter here.
24999 	 */
25000 
25001 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25002 	if (hada_mp == NULL) {
25003 		/* IPsec KSTATS: should bump packet counter here. */
25004 		freemsg(mp);
25005 		return;
25006 	}
25007 
25008 	hada_mp->b_datap->db_type = M_CTL;
25009 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25010 	hada_mp->b_cont = mp;
25011 
25012 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25013 	bzero(hada, sizeof (da_ipsec_t));
25014 	hada->da_type = IPHADA_M_CTL;
25015 
25016 	putnext(q, hada_mp);
25017 }
25018 
25019 /*
25020  * Finish the outbound IPsec processing. This function is called from
25021  * ipsec_out_process() if the IPsec packet was processed
25022  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25023  * asynchronously.
25024  */
25025 void
25026 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25027     ire_t *ire_arg)
25028 {
25029 	uint32_t v_hlen_tos_len;
25030 	ipaddr_t	dst;
25031 	ipif_t	*ipif = NULL;
25032 	ire_t *ire;
25033 	ire_t *ire1 = NULL;
25034 	mblk_t *next_mp = NULL;
25035 	uint32_t max_frag;
25036 	boolean_t multirt_send = B_FALSE;
25037 	mblk_t *mp;
25038 	mblk_t *mp1;
25039 	uint_t	ill_index;
25040 	ipsec_out_t *io;
25041 	boolean_t attach_if;
25042 	int match_flags, offset;
25043 	irb_t *irb = NULL;
25044 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25045 	zoneid_t zoneid;
25046 	uint32_t cksum;
25047 	uint16_t *up;
25048 	ipxmit_state_t	pktxmit_state;
25049 	ill_t	*out_ill;
25050 #ifdef	_BIG_ENDIAN
25051 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25052 #else
25053 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25054 #endif
25055 
25056 	mp = ipsec_mp->b_cont;
25057 	ASSERT(mp != NULL);
25058 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25059 	dst = ipha->ipha_dst;
25060 
25061 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25062 	ill_index = io->ipsec_out_ill_index;
25063 	attach_if = io->ipsec_out_attach_if;
25064 	zoneid = io->ipsec_out_zoneid;
25065 	ASSERT(zoneid != ALL_ZONES);
25066 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25067 	if (ill_index != 0) {
25068 		if (ill == NULL) {
25069 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25070 			    ill_index, B_FALSE);
25071 
25072 			/* Failure case frees things for us. */
25073 			if (ill == NULL)
25074 				return;
25075 
25076 			ill_need_rele = B_TRUE;
25077 		}
25078 		/*
25079 		 * If this packet needs to go out on a particular interface
25080 		 * honor it.
25081 		 */
25082 		if (attach_if) {
25083 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25084 
25085 			/*
25086 			 * Check if we need an ire that will not be
25087 			 * looked up by anybody else i.e. HIDDEN.
25088 			 */
25089 			if (ill_is_probeonly(ill)) {
25090 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25091 			}
25092 		}
25093 	}
25094 
25095 	if (CLASSD(dst)) {
25096 		boolean_t conn_dontroute;
25097 		/*
25098 		 * Use the ill_index to get the right ipif.
25099 		 */
25100 		conn_dontroute = io->ipsec_out_dontroute;
25101 		if (ill_index == 0)
25102 			ipif = ipif_lookup_group(dst, zoneid);
25103 		else
25104 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25105 		if (ipif == NULL) {
25106 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25107 			    " multicast\n"));
25108 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
25109 			freemsg(ipsec_mp);
25110 			goto done;
25111 		}
25112 		/*
25113 		 * ipha_src has already been intialized with the
25114 		 * value of the ipif in ip_wput. All we need now is
25115 		 * an ire to send this downstream.
25116 		 */
25117 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25118 		    MBLK_GETLABEL(mp), match_flags);
25119 		if (ire != NULL) {
25120 			ill_t *ill1;
25121 			/*
25122 			 * Do the multicast forwarding now, as the IPSEC
25123 			 * processing has been done.
25124 			 */
25125 			if (ip_g_mrouter && !conn_dontroute &&
25126 			    (ill1 = ire_to_ill(ire))) {
25127 				if (ip_mforward(ill1, ipha, mp)) {
25128 					freemsg(ipsec_mp);
25129 					ip1dbg(("ip_wput_ipsec_out: mforward "
25130 					    "failed\n"));
25131 					ire_refrele(ire);
25132 					goto done;
25133 				}
25134 			}
25135 			goto send;
25136 		}
25137 
25138 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25139 		mp->b_prev = NULL;
25140 		mp->b_next = NULL;
25141 
25142 		/*
25143 		 * If the IPsec packet was processed asynchronously,
25144 		 * drop it now.
25145 		 */
25146 		if (q == NULL) {
25147 			freemsg(ipsec_mp);
25148 			goto done;
25149 		}
25150 
25151 		/*
25152 		 * We may be using a wrong ipif to create the ire.
25153 		 * But it is okay as the source address is assigned
25154 		 * for the packet already. Next outbound packet would
25155 		 * create the IRE with the right IPIF in ip_wput.
25156 		 *
25157 		 * Also handle RTF_MULTIRT routes.
25158 		 */
25159 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25160 		    zoneid);
25161 	} else {
25162 		if (attach_if) {
25163 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25164 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25165 		} else {
25166 			if (ire_arg != NULL) {
25167 				ire = ire_arg;
25168 				ire_need_rele = B_FALSE;
25169 			} else {
25170 				ire = ire_cache_lookup(dst, zoneid,
25171 				    MBLK_GETLABEL(mp));
25172 			}
25173 		}
25174 		if (ire != NULL) {
25175 			goto send;
25176 		}
25177 
25178 		/*
25179 		 * ire disappeared underneath.
25180 		 *
25181 		 * What we need to do here is the ip_newroute
25182 		 * logic to get the ire without doing the IPSEC
25183 		 * processing. Follow the same old path. But this
25184 		 * time, ip_wput or ire_add_then_put will call us
25185 		 * directly as all the IPSEC operations are done.
25186 		 */
25187 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25188 		mp->b_prev = NULL;
25189 		mp->b_next = NULL;
25190 
25191 		/*
25192 		 * If the IPsec packet was processed asynchronously,
25193 		 * drop it now.
25194 		 */
25195 		if (q == NULL) {
25196 			freemsg(ipsec_mp);
25197 			goto done;
25198 		}
25199 
25200 		/*
25201 		 * Since we're going through ip_newroute() again, we
25202 		 * need to make sure we don't:
25203 		 *
25204 		 *	1.) Trigger the ASSERT() with the ipha_ident
25205 		 *	    overloading.
25206 		 *	2.) Redo transport-layer checksumming, since we've
25207 		 *	    already done all that to get this far.
25208 		 *
25209 		 * The easiest way not do either of the above is to set
25210 		 * the ipha_ident field to IP_HDR_INCLUDED.
25211 		 */
25212 		ipha->ipha_ident = IP_HDR_INCLUDED;
25213 		ip_newroute(q, ipsec_mp, dst, NULL,
25214 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid);
25215 	}
25216 	goto done;
25217 send:
25218 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
25219 		/*
25220 		 * ESP NAT-Traversal packet.
25221 		 *
25222 		 * Just do software checksum for now.
25223 		 */
25224 
25225 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
25226 		IP_STAT(ip_out_sw_cksum);
25227 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
25228 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
25229 #define	iphs	((uint16_t *)ipha)
25230 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
25231 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
25232 		    IP_SIMPLE_HDR_LENGTH);
25233 #undef iphs
25234 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
25235 			cksum = 0xFFFF;
25236 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
25237 			if (mp1->b_wptr - mp1->b_rptr >=
25238 			    offset + sizeof (uint16_t)) {
25239 				up = (uint16_t *)(mp1->b_rptr + offset);
25240 				*up = cksum;
25241 				break;	/* out of for loop */
25242 			} else {
25243 				offset -= (mp->b_wptr - mp->b_rptr);
25244 			}
25245 	} /* Otherwise, just keep the all-zero checksum. */
25246 
25247 	if (ire->ire_stq == NULL) {
25248 		/*
25249 		 * Loopbacks go through ip_wput_local except for one case.
25250 		 * We come here if we generate a icmp_frag_needed message
25251 		 * after IPSEC processing is over. When this function calls
25252 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25253 		 * icmp_frag_needed. The message generated comes back here
25254 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25255 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25256 		 * source address as it is usually set in ip_wput_ire. As
25257 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25258 		 * and we end up here. We can't enter ip_wput_ire once the
25259 		 * IPSEC processing is over and hence we need to do it here.
25260 		 */
25261 		ASSERT(q != NULL);
25262 		UPDATE_OB_PKT_COUNT(ire);
25263 		ire->ire_last_used_time = lbolt;
25264 		if (ipha->ipha_src == 0)
25265 			ipha->ipha_src = ire->ire_src_addr;
25266 
25267 		/* PFHooks: LOOPBACK_OUT */
25268 		out_ill = ire->ire_ipif->ipif_ill;
25269 
25270 		DTRACE_PROBE4(ip4__loopback__out__start,
25271 		    ill_t *, NULL, ill_t *, out_ill,
25272 		    ipha_t *, ipha, mblk_t *, ipsec_mp);
25273 
25274 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
25275 		    MSG_FWCOOKED_OUT, NULL, out_ill, ipha, ipsec_mp, mp);
25276 
25277 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25278 
25279 		if (ipsec_mp != NULL)
25280 			ip_wput_local(RD(q), out_ill,
25281 			    ipha, ipsec_mp, ire, 0, zoneid);
25282 		if (ire_need_rele)
25283 			ire_refrele(ire);
25284 		goto done;
25285 	}
25286 
25287 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25288 		/*
25289 		 * We are through with IPSEC processing.
25290 		 * Fragment this and send it on the wire.
25291 		 */
25292 		if (io->ipsec_out_accelerated) {
25293 			/*
25294 			 * The packet has been accelerated but must
25295 			 * be fragmented. This should not happen
25296 			 * since AH and ESP must not accelerate
25297 			 * packets that need fragmentation, however
25298 			 * the configuration could have changed
25299 			 * since the AH or ESP processing.
25300 			 * Drop packet.
25301 			 * IPsec KSTATS: bump bean counter here.
25302 			 */
25303 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25304 			    "fragmented accelerated packet!\n"));
25305 			freemsg(ipsec_mp);
25306 		} else {
25307 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid);
25308 		}
25309 		if (ire_need_rele)
25310 			ire_refrele(ire);
25311 		goto done;
25312 	}
25313 
25314 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25315 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25316 	    (void *)ire->ire_ipif, (void *)ipif));
25317 
25318 	/*
25319 	 * Multiroute the secured packet, unless IPsec really
25320 	 * requires the packet to go out only through a particular
25321 	 * interface.
25322 	 */
25323 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
25324 		ire_t *first_ire;
25325 		irb = ire->ire_bucket;
25326 		ASSERT(irb != NULL);
25327 		/*
25328 		 * This ire has been looked up as the one that
25329 		 * goes through the given ipif;
25330 		 * make sure we do not omit any other multiroute ire
25331 		 * that may be present in the bucket before this one.
25332 		 */
25333 		IRB_REFHOLD(irb);
25334 		for (first_ire = irb->irb_ire;
25335 		    first_ire != NULL;
25336 		    first_ire = first_ire->ire_next) {
25337 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25338 			    (first_ire->ire_addr == ire->ire_addr) &&
25339 			    !(first_ire->ire_marks &
25340 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
25341 				break;
25342 		}
25343 
25344 		if ((first_ire != NULL) && (first_ire != ire)) {
25345 			/*
25346 			 * Don't change the ire if the packet must
25347 			 * be fragmented if sent via this new one.
25348 			 */
25349 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25350 				IRE_REFHOLD(first_ire);
25351 				if (ire_need_rele)
25352 					ire_refrele(ire);
25353 				else
25354 					ire_need_rele = B_TRUE;
25355 				ire = first_ire;
25356 			}
25357 		}
25358 		IRB_REFRELE(irb);
25359 
25360 		multirt_send = B_TRUE;
25361 		max_frag = ire->ire_max_frag;
25362 	} else {
25363 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
25364 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25365 			    "flag, attach_if %d\n", attach_if));
25366 		}
25367 	}
25368 
25369 	/*
25370 	 * In most cases, the emission loop below is entered only once.
25371 	 * Only in the case where the ire holds the RTF_MULTIRT
25372 	 * flag, we loop to process all RTF_MULTIRT ires in the
25373 	 * bucket, and send the packet through all crossed
25374 	 * RTF_MULTIRT routes.
25375 	 */
25376 	do {
25377 		if (multirt_send) {
25378 			/*
25379 			 * ire1 holds here the next ire to process in the
25380 			 * bucket. If multirouting is expected,
25381 			 * any non-RTF_MULTIRT ire that has the
25382 			 * right destination address is ignored.
25383 			 */
25384 			ASSERT(irb != NULL);
25385 			IRB_REFHOLD(irb);
25386 			for (ire1 = ire->ire_next;
25387 			    ire1 != NULL;
25388 			    ire1 = ire1->ire_next) {
25389 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
25390 					continue;
25391 				if (ire1->ire_addr != ire->ire_addr)
25392 					continue;
25393 				if (ire1->ire_marks &
25394 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
25395 					continue;
25396 				/* No loopback here */
25397 				if (ire1->ire_stq == NULL)
25398 					continue;
25399 				/*
25400 				 * Ensure we do not exceed the MTU
25401 				 * of the next route.
25402 				 */
25403 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
25404 					ip_multirt_bad_mtu(ire1, max_frag);
25405 					continue;
25406 				}
25407 
25408 				IRE_REFHOLD(ire1);
25409 				break;
25410 			}
25411 			IRB_REFRELE(irb);
25412 			if (ire1 != NULL) {
25413 				/*
25414 				 * We are in a multiple send case, need to
25415 				 * make a copy of the packet.
25416 				 */
25417 				next_mp = copymsg(ipsec_mp);
25418 				if (next_mp == NULL) {
25419 					ire_refrele(ire1);
25420 					ire1 = NULL;
25421 				}
25422 			}
25423 		}
25424 		/*
25425 		 * Everything is done. Send it out on the wire
25426 		 *
25427 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
25428 		 * either send it on the wire or, in the case of
25429 		 * HW acceleration, call ipsec_hw_putnext.
25430 		 */
25431 		if (ire->ire_nce &&
25432 		    ire->ire_nce->nce_state != ND_REACHABLE) {
25433 			DTRACE_PROBE2(ip__wput__ipsec__bail,
25434 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
25435 			/*
25436 			 * If ire's link-layer is unresolved (this
25437 			 * would only happen if the incomplete ire
25438 			 * was added to cachetable via forwarding path)
25439 			 * don't bother going to ip_xmit_v4. Just drop the
25440 			 * packet.
25441 			 * There is a slight risk here, in that, if we
25442 			 * have the forwarding path create an incomplete
25443 			 * IRE, then until the IRE is completed, any
25444 			 * transmitted IPSEC packets will be dropped
25445 			 * instead of being queued waiting for resolution.
25446 			 *
25447 			 * But the likelihood of a forwarding packet and a wput
25448 			 * packet sending to the same dst at the same time
25449 			 * and there not yet be an ARP entry for it is small.
25450 			 * Furthermore, if this actually happens, it might
25451 			 * be likely that wput would generate multiple
25452 			 * packets (and forwarding would also have a train
25453 			 * of packets) for that destination. If this is
25454 			 * the case, some of them would have been dropped
25455 			 * anyway, since ARP only queues a few packets while
25456 			 * waiting for resolution
25457 			 *
25458 			 * NOTE: We should really call ip_xmit_v4,
25459 			 * and let it queue the packet and send the
25460 			 * ARP query and have ARP come back thus:
25461 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
25462 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
25463 			 * hw accel work. But it's too complex to get
25464 			 * the IPsec hw  acceleration approach to fit
25465 			 * well with ip_xmit_v4 doing ARP without
25466 			 * doing IPSEC simplification. For now, we just
25467 			 * poke ip_xmit_v4 to trigger the arp resolve, so
25468 			 * that we can continue with the send on the next
25469 			 * attempt.
25470 			 *
25471 			 * XXX THis should be revisited, when
25472 			 * the IPsec/IP interaction is cleaned up
25473 			 */
25474 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
25475 			    " - dropping packet\n"));
25476 			freemsg(ipsec_mp);
25477 			/*
25478 			 * Call ip_xmit_v4() to trigger ARP query
25479 			 * in case the nce_state is ND_INITIAL
25480 			 */
25481 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
25482 			goto drop_pkt;
25483 		}
25484 
25485 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
25486 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
25487 		    mblk_t *, mp);
25488 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
25489 		    MSG_FWCOOKED_OUT, NULL, out_ill, ipha, mp, mp);
25490 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
25491 		if (mp == NULL)
25492 			goto drop_pkt;
25493 
25494 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
25495 		pktxmit_state = ip_xmit_v4(mp, ire,
25496 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
25497 
25498 		if ((pktxmit_state ==  SEND_FAILED) ||
25499 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
25500 
25501 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
25502 drop_pkt:
25503 			BUMP_MIB(&ip_mib, ipOutDiscards);
25504 			if (ire_need_rele)
25505 				ire_refrele(ire);
25506 			if (ire1 != NULL) {
25507 				ire_refrele(ire1);
25508 				freemsg(next_mp);
25509 			}
25510 			goto done;
25511 		}
25512 
25513 		freeb(ipsec_mp);
25514 		if (ire_need_rele)
25515 			ire_refrele(ire);
25516 
25517 		if (ire1 != NULL) {
25518 			ire = ire1;
25519 			ire_need_rele = B_TRUE;
25520 			ASSERT(next_mp);
25521 			ipsec_mp = next_mp;
25522 			mp = ipsec_mp->b_cont;
25523 			ire1 = NULL;
25524 			next_mp = NULL;
25525 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
25526 		} else {
25527 			multirt_send = B_FALSE;
25528 		}
25529 	} while (multirt_send);
25530 done:
25531 	if (ill != NULL && ill_need_rele)
25532 		ill_refrele(ill);
25533 	if (ipif != NULL)
25534 		ipif_refrele(ipif);
25535 }
25536 
25537 /*
25538  * Get the ill corresponding to the specified ire, and compare its
25539  * capabilities with the protocol and algorithms specified by the
25540  * the SA obtained from ipsec_out. If they match, annotate the
25541  * ipsec_out structure to indicate that the packet needs acceleration.
25542  *
25543  *
25544  * A packet is eligible for outbound hardware acceleration if the
25545  * following conditions are satisfied:
25546  *
25547  * 1. the packet will not be fragmented
25548  * 2. the provider supports the algorithm
25549  * 3. there is no pending control message being exchanged
25550  * 4. snoop is not attached
25551  * 5. the destination address is not a broadcast or multicast address.
25552  *
25553  * Rationale:
25554  *	- Hardware drivers do not support fragmentation with
25555  *	  the current interface.
25556  *	- snoop, multicast, and broadcast may result in exposure of
25557  *	  a cleartext datagram.
25558  * We check all five of these conditions here.
25559  *
25560  * XXX would like to nuke "ire_t *" parameter here; problem is that
25561  * IRE is only way to figure out if a v4 address is a broadcast and
25562  * thus ineligible for acceleration...
25563  */
25564 static void
25565 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
25566 {
25567 	ipsec_out_t *io;
25568 	mblk_t *data_mp;
25569 	uint_t plen, overhead;
25570 
25571 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
25572 		return;
25573 
25574 	if (ill == NULL)
25575 		return;
25576 
25577 	/*
25578 	 * Destination address is a broadcast or multicast.  Punt.
25579 	 */
25580 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
25581 	    IRE_LOCAL)))
25582 		return;
25583 
25584 	data_mp = ipsec_mp->b_cont;
25585 
25586 	if (ill->ill_isv6) {
25587 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
25588 
25589 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
25590 			return;
25591 
25592 		plen = ip6h->ip6_plen;
25593 	} else {
25594 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
25595 
25596 		if (CLASSD(ipha->ipha_dst))
25597 			return;
25598 
25599 		plen = ipha->ipha_length;
25600 	}
25601 	/*
25602 	 * Is there a pending DLPI control message being exchanged
25603 	 * between IP/IPsec and the DLS Provider? If there is, it
25604 	 * could be a SADB update, and the state of the DLS Provider
25605 	 * SADB might not be in sync with the SADB maintained by
25606 	 * IPsec. To avoid dropping packets or using the wrong keying
25607 	 * material, we do not accelerate this packet.
25608 	 */
25609 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
25610 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25611 		    "ill_dlpi_pending! don't accelerate packet\n"));
25612 		return;
25613 	}
25614 
25615 	/*
25616 	 * Is the Provider in promiscous mode? If it does, we don't
25617 	 * accelerate the packet since it will bounce back up to the
25618 	 * listeners in the clear.
25619 	 */
25620 	if (ill->ill_promisc_on_phys) {
25621 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25622 		    "ill in promiscous mode, don't accelerate packet\n"));
25623 		return;
25624 	}
25625 
25626 	/*
25627 	 * Will the packet require fragmentation?
25628 	 */
25629 
25630 	/*
25631 	 * IPsec ESP note: this is a pessimistic estimate, but the same
25632 	 * as is used elsewhere.
25633 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
25634 	 *	+ 2-byte trailer
25635 	 */
25636 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
25637 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
25638 
25639 	if ((plen + overhead) > ill->ill_max_mtu)
25640 		return;
25641 
25642 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25643 
25644 	/*
25645 	 * Can the ill accelerate this IPsec protocol and algorithm
25646 	 * specified by the SA?
25647 	 */
25648 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
25649 	    ill->ill_isv6, sa)) {
25650 		return;
25651 	}
25652 
25653 	/*
25654 	 * Tell AH or ESP that the outbound ill is capable of
25655 	 * accelerating this packet.
25656 	 */
25657 	io->ipsec_out_is_capab_ill = B_TRUE;
25658 }
25659 
25660 /*
25661  * Select which AH & ESP SA's to use (if any) for the outbound packet.
25662  *
25663  * If this function returns B_TRUE, the requested SA's have been filled
25664  * into the ipsec_out_*_sa pointers.
25665  *
25666  * If the function returns B_FALSE, the packet has been "consumed", most
25667  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
25668  *
25669  * The SA references created by the protocol-specific "select"
25670  * function will be released when the ipsec_mp is freed, thanks to the
25671  * ipsec_out_free destructor -- see spd.c.
25672  */
25673 static boolean_t
25674 ipsec_out_select_sa(mblk_t *ipsec_mp)
25675 {
25676 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
25677 	ipsec_out_t *io;
25678 	ipsec_policy_t *pp;
25679 	ipsec_action_t *ap;
25680 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25681 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25682 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25683 
25684 	if (!io->ipsec_out_secure) {
25685 		/*
25686 		 * We came here by mistake.
25687 		 * Don't bother with ipsec processing
25688 		 * We should "discourage" this path in the future.
25689 		 */
25690 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25691 		return (B_FALSE);
25692 	}
25693 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25694 	ASSERT((io->ipsec_out_policy != NULL) ||
25695 	    (io->ipsec_out_act != NULL));
25696 
25697 	ASSERT(io->ipsec_out_failed == B_FALSE);
25698 
25699 	/*
25700 	 * IPSEC processing has started.
25701 	 */
25702 	io->ipsec_out_proc_begin = B_TRUE;
25703 	ap = io->ipsec_out_act;
25704 	if (ap == NULL) {
25705 		pp = io->ipsec_out_policy;
25706 		ASSERT(pp != NULL);
25707 		ap = pp->ipsp_act;
25708 		ASSERT(ap != NULL);
25709 	}
25710 
25711 	/*
25712 	 * We have an action.  now, let's select SA's.
25713 	 * (In the future, we can cache this in the conn_t..)
25714 	 */
25715 	if (ap->ipa_want_esp) {
25716 		if (io->ipsec_out_esp_sa == NULL) {
25717 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
25718 			    IPPROTO_ESP);
25719 		}
25720 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
25721 	}
25722 
25723 	if (ap->ipa_want_ah) {
25724 		if (io->ipsec_out_ah_sa == NULL) {
25725 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
25726 			    IPPROTO_AH);
25727 		}
25728 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
25729 		/*
25730 		 * The ESP and AH processing order needs to be preserved
25731 		 * when both protocols are required (ESP should be applied
25732 		 * before AH for an outbound packet). Force an ESP ACQUIRE
25733 		 * when both ESP and AH are required, and an AH ACQUIRE
25734 		 * is needed.
25735 		 */
25736 		if (ap->ipa_want_esp && need_ah_acquire)
25737 			need_esp_acquire = B_TRUE;
25738 	}
25739 
25740 	/*
25741 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
25742 	 * Release SAs that got referenced, but will not be used until we
25743 	 * acquire _all_ of the SAs we need.
25744 	 */
25745 	if (need_ah_acquire || need_esp_acquire) {
25746 		if (io->ipsec_out_ah_sa != NULL) {
25747 			IPSA_REFRELE(io->ipsec_out_ah_sa);
25748 			io->ipsec_out_ah_sa = NULL;
25749 		}
25750 		if (io->ipsec_out_esp_sa != NULL) {
25751 			IPSA_REFRELE(io->ipsec_out_esp_sa);
25752 			io->ipsec_out_esp_sa = NULL;
25753 		}
25754 
25755 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
25756 		return (B_FALSE);
25757 	}
25758 
25759 	return (B_TRUE);
25760 }
25761 
25762 /*
25763  * Process an IPSEC_OUT message and see what you can
25764  * do with it.
25765  * IPQoS Notes:
25766  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
25767  * IPSec.
25768  * XXX would like to nuke ire_t.
25769  * XXX ill_index better be "real"
25770  */
25771 void
25772 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
25773 {
25774 	ipsec_out_t *io;
25775 	ipsec_policy_t *pp;
25776 	ipsec_action_t *ap;
25777 	ipha_t *ipha;
25778 	ip6_t *ip6h;
25779 	mblk_t *mp;
25780 	ill_t *ill;
25781 	zoneid_t zoneid;
25782 	ipsec_status_t ipsec_rc;
25783 	boolean_t ill_need_rele = B_FALSE;
25784 
25785 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25786 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25787 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25788 	mp = ipsec_mp->b_cont;
25789 
25790 	/*
25791 	 * Initiate IPPF processing. We do it here to account for packets
25792 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
25793 	 * We can check for ipsec_out_proc_begin even for such packets, as
25794 	 * they will always be false (asserted below).
25795 	 */
25796 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
25797 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
25798 		    io->ipsec_out_ill_index : ill_index);
25799 		if (mp == NULL) {
25800 			ip2dbg(("ipsec_out_process: packet dropped "\
25801 			    "during IPPF processing\n"));
25802 			freeb(ipsec_mp);
25803 			BUMP_MIB(&ip_mib, ipOutDiscards);
25804 			return;
25805 		}
25806 	}
25807 
25808 	if (!io->ipsec_out_secure) {
25809 		/*
25810 		 * We came here by mistake.
25811 		 * Don't bother with ipsec processing
25812 		 * Should "discourage" this path in the future.
25813 		 */
25814 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25815 		goto done;
25816 	}
25817 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25818 	ASSERT((io->ipsec_out_policy != NULL) ||
25819 	    (io->ipsec_out_act != NULL));
25820 	ASSERT(io->ipsec_out_failed == B_FALSE);
25821 
25822 	if (!ipsec_loaded()) {
25823 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
25824 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25825 			BUMP_MIB(&ip_mib, ipOutDiscards);
25826 		} else {
25827 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
25828 		}
25829 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
25830 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
25831 		return;
25832 	}
25833 
25834 	/*
25835 	 * IPSEC processing has started.
25836 	 */
25837 	io->ipsec_out_proc_begin = B_TRUE;
25838 	ap = io->ipsec_out_act;
25839 	if (ap == NULL) {
25840 		pp = io->ipsec_out_policy;
25841 		ASSERT(pp != NULL);
25842 		ap = pp->ipsp_act;
25843 		ASSERT(ap != NULL);
25844 	}
25845 
25846 	/*
25847 	 * Save the outbound ill index. When the packet comes back
25848 	 * from IPsec, we make sure the ill hasn't changed or disappeared
25849 	 * before sending it the accelerated packet.
25850 	 */
25851 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
25852 		int ifindex;
25853 		ill = ire_to_ill(ire);
25854 		ifindex = ill->ill_phyint->phyint_ifindex;
25855 		io->ipsec_out_capab_ill_index = ifindex;
25856 	}
25857 
25858 	/*
25859 	 * The order of processing is first insert a IP header if needed.
25860 	 * Then insert the ESP header and then the AH header.
25861 	 */
25862 	if ((io->ipsec_out_se_done == B_FALSE) &&
25863 	    (ap->ipa_want_se)) {
25864 		/*
25865 		 * First get the outer IP header before sending
25866 		 * it to ESP.
25867 		 */
25868 		ipha_t *oipha, *iipha;
25869 		mblk_t *outer_mp, *inner_mp;
25870 
25871 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
25872 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
25873 			    "ipsec_out_process: "
25874 			    "Self-Encapsulation failed: Out of memory\n");
25875 			freemsg(ipsec_mp);
25876 			BUMP_MIB(&ip_mib, ipOutDiscards);
25877 			return;
25878 		}
25879 		inner_mp = ipsec_mp->b_cont;
25880 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
25881 		oipha = (ipha_t *)outer_mp->b_rptr;
25882 		iipha = (ipha_t *)inner_mp->b_rptr;
25883 		*oipha = *iipha;
25884 		outer_mp->b_wptr += sizeof (ipha_t);
25885 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
25886 		    sizeof (ipha_t));
25887 		oipha->ipha_protocol = IPPROTO_ENCAP;
25888 		oipha->ipha_version_and_hdr_length =
25889 		    IP_SIMPLE_HDR_VERSION;
25890 		oipha->ipha_hdr_checksum = 0;
25891 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
25892 		outer_mp->b_cont = inner_mp;
25893 		ipsec_mp->b_cont = outer_mp;
25894 
25895 		io->ipsec_out_se_done = B_TRUE;
25896 		io->ipsec_out_encaps = B_TRUE;
25897 	}
25898 
25899 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
25900 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
25901 	    !ipsec_out_select_sa(ipsec_mp))
25902 		return;
25903 
25904 	/*
25905 	 * By now, we know what SA's to use.  Toss over to ESP & AH
25906 	 * to do the heavy lifting.
25907 	 */
25908 	zoneid = io->ipsec_out_zoneid;
25909 	ASSERT(zoneid != ALL_ZONES);
25910 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
25911 		ASSERT(io->ipsec_out_esp_sa != NULL);
25912 		io->ipsec_out_esp_done = B_TRUE;
25913 		/*
25914 		 * Note that since hw accel can only apply one transform,
25915 		 * not two, we skip hw accel for ESP if we also have AH
25916 		 * This is an design limitation of the interface
25917 		 * which should be revisited.
25918 		 */
25919 		ASSERT(ire != NULL);
25920 		if (io->ipsec_out_ah_sa == NULL) {
25921 			ill = (ill_t *)ire->ire_stq->q_ptr;
25922 			ipsec_out_is_accelerated(ipsec_mp,
25923 			    io->ipsec_out_esp_sa, ill, ire);
25924 		}
25925 
25926 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
25927 		switch (ipsec_rc) {
25928 		case IPSEC_STATUS_SUCCESS:
25929 			break;
25930 		case IPSEC_STATUS_FAILED:
25931 			BUMP_MIB(&ip_mib, ipOutDiscards);
25932 			/* FALLTHRU */
25933 		case IPSEC_STATUS_PENDING:
25934 			return;
25935 		}
25936 	}
25937 
25938 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
25939 		ASSERT(io->ipsec_out_ah_sa != NULL);
25940 		io->ipsec_out_ah_done = B_TRUE;
25941 		if (ire == NULL) {
25942 			int idx = io->ipsec_out_capab_ill_index;
25943 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
25944 			    NULL, NULL, NULL, NULL);
25945 			ill_need_rele = B_TRUE;
25946 		} else {
25947 			ill = (ill_t *)ire->ire_stq->q_ptr;
25948 		}
25949 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
25950 		    ire);
25951 
25952 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
25953 		switch (ipsec_rc) {
25954 		case IPSEC_STATUS_SUCCESS:
25955 			break;
25956 		case IPSEC_STATUS_FAILED:
25957 			BUMP_MIB(&ip_mib, ipOutDiscards);
25958 			/* FALLTHRU */
25959 		case IPSEC_STATUS_PENDING:
25960 			if (ill != NULL && ill_need_rele)
25961 				ill_refrele(ill);
25962 			return;
25963 		}
25964 	}
25965 	/*
25966 	 * We are done with IPSEC processing. Send it over
25967 	 * the wire.
25968 	 */
25969 done:
25970 	mp = ipsec_mp->b_cont;
25971 	ipha = (ipha_t *)mp->b_rptr;
25972 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25973 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
25974 	} else {
25975 		ip6h = (ip6_t *)ipha;
25976 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
25977 	}
25978 	if (ill != NULL && ill_need_rele)
25979 		ill_refrele(ill);
25980 }
25981 
25982 /* ARGSUSED */
25983 void
25984 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
25985 {
25986 	opt_restart_t	*or;
25987 	int	err;
25988 	conn_t	*connp;
25989 
25990 	ASSERT(CONN_Q(q));
25991 	connp = Q_TO_CONN(q);
25992 
25993 	ASSERT(first_mp->b_datap->db_type == M_CTL);
25994 	or = (opt_restart_t *)first_mp->b_rptr;
25995 	/*
25996 	 * We don't need to pass any credentials here since this is just
25997 	 * a restart. The credentials are passed in when svr4_optcom_req
25998 	 * is called the first time (from ip_wput_nondata).
25999 	 */
26000 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26001 		err = svr4_optcom_req(q, first_mp, NULL,
26002 		    &ip_opt_obj);
26003 	} else {
26004 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26005 		err = tpi_optcom_req(q, first_mp, NULL,
26006 		    &ip_opt_obj);
26007 	}
26008 	if (err != EINPROGRESS) {
26009 		/* operation is done */
26010 		CONN_OPER_PENDING_DONE(connp);
26011 	}
26012 }
26013 
26014 /*
26015  * ioctls that go through a down/up sequence may need to wait for the down
26016  * to complete. This involves waiting for the ire and ipif refcnts to go down
26017  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26018  */
26019 /* ARGSUSED */
26020 void
26021 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26022 {
26023 	struct iocblk *iocp;
26024 	mblk_t *mp1;
26025 	ipif_t	*ipif;
26026 	ip_ioctl_cmd_t *ipip;
26027 	int err;
26028 	sin_t	*sin;
26029 	struct lifreq *lifr;
26030 	struct ifreq *ifr;
26031 
26032 	iocp = (struct iocblk *)mp->b_rptr;
26033 	ASSERT(ipsq != NULL);
26034 	/* Existence of mp1 verified in ip_wput_nondata */
26035 	mp1 = mp->b_cont->b_cont;
26036 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26037 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26038 		ill_t *ill;
26039 		/*
26040 		 * Special case where ipsq_current_ipif may not be set.
26041 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26042 		 * ill could also have become part of a ipmp group in the
26043 		 * process, we are here as were not able to complete the
26044 		 * operation in ipif_set_values because we could not become
26045 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26046 		 * will not be set so we need to set it.
26047 		 */
26048 		ill = (ill_t *)q->q_ptr;
26049 		ipsq->ipsq_current_ipif = ill->ill_ipif;
26050 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26051 	}
26052 
26053 	ipif = ipsq->ipsq_current_ipif;
26054 	ASSERT(ipif != NULL);
26055 	if (ipip->ipi_cmd_type == IF_CMD) {
26056 		/* This a old style SIOC[GS]IF* command */
26057 		ifr = (struct ifreq *)mp1->b_rptr;
26058 		sin = (sin_t *)&ifr->ifr_addr;
26059 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26060 		/* This a new style SIOC[GS]LIF* command */
26061 		lifr = (struct lifreq *)mp1->b_rptr;
26062 		sin = (sin_t *)&lifr->lifr_addr;
26063 	} else {
26064 		sin = NULL;
26065 	}
26066 
26067 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
26068 	    (void *)mp1->b_rptr);
26069 
26070 	/* SIOCLIFREMOVEIF could have removed the ipif */
26071 	ip_ioctl_finish(q, mp, err,
26072 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26073 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
26074 }
26075 
26076 /*
26077  * ioctl processing
26078  *
26079  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
26080  * the ioctl command in the ioctl tables and determines the copyin data size
26081  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
26082  * size.
26083  *
26084  * ioctl processing then continues when the M_IOCDATA makes its way down.
26085  * Now the ioctl is looked up again in the ioctl table, and its properties are
26086  * extracted. The associated 'conn' is then refheld till the end of the ioctl
26087  * and the general ioctl processing function ip_process_ioctl is called.
26088  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26089  * so goes thru the serialization primitive ipsq_try_enter. Then the
26090  * appropriate function to handle the ioctl is called based on the entry in
26091  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26092  * which also refreleases the 'conn' that was refheld at the start of the
26093  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26094  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
26095  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
26096  *
26097  * Many exclusive ioctls go thru an internal down up sequence as part of
26098  * the operation. For example an attempt to change the IP address of an
26099  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26100  * does all the cleanup such as deleting all ires that use this address.
26101  * Then we need to wait till all references to the interface go away.
26102  */
26103 void
26104 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26105 {
26106 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26107 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
26108 	cmd_info_t ci;
26109 	int err;
26110 	boolean_t entered_ipsq = B_FALSE;
26111 
26112 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26113 
26114 	if (ipip == NULL)
26115 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26116 
26117 	/*
26118 	 * SIOCLIFADDIF needs to go thru a special path since the
26119 	 * ill may not exist yet. This happens in the case of lo0
26120 	 * which is created using this ioctl.
26121 	 */
26122 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26123 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26124 		ip_ioctl_finish(q, mp, err,
26125 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26126 		    NULL, NULL);
26127 		return;
26128 	}
26129 
26130 	ci.ci_ipif = NULL;
26131 	switch (ipip->ipi_cmd_type) {
26132 	case IF_CMD:
26133 	case LIF_CMD:
26134 		/*
26135 		 * ioctls that pass in a [l]ifreq appear here.
26136 		 * ip_extract_lifreq_cmn returns a refheld ipif in
26137 		 * ci.ci_ipif
26138 		 */
26139 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
26140 		    ipip->ipi_flags, &ci, ip_process_ioctl);
26141 		if (err != 0) {
26142 			ip_ioctl_finish(q, mp, err,
26143 			    ipip->ipi_flags & IPI_GET_CMD ?
26144 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26145 			return;
26146 		}
26147 		ASSERT(ci.ci_ipif != NULL);
26148 		break;
26149 
26150 	case TUN_CMD:
26151 		/*
26152 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
26153 		 * a refheld ipif in ci.ci_ipif
26154 		 */
26155 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
26156 		if (err != 0) {
26157 			ip_ioctl_finish(q, mp, err,
26158 			    ipip->ipi_flags & IPI_GET_CMD ?
26159 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26160 			return;
26161 		}
26162 		ASSERT(ci.ci_ipif != NULL);
26163 		break;
26164 
26165 	case MISC_CMD:
26166 		/*
26167 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
26168 		 * For eg. SIOCGLIFCONF will appear here.
26169 		 */
26170 		switch (ipip->ipi_cmd) {
26171 		case IF_UNITSEL:
26172 			/* ioctl comes down the ill */
26173 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26174 			ipif_refhold(ci.ci_ipif);
26175 			break;
26176 		case SIOCGMSFILTER:
26177 		case SIOCSMSFILTER:
26178 		case SIOCGIPMSFILTER:
26179 		case SIOCSIPMSFILTER:
26180 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
26181 			    ip_process_ioctl);
26182 			if (err != 0) {
26183 				ip_ioctl_finish(q, mp, err,
26184 				    ipip->ipi_flags & IPI_GET_CMD ?
26185 				    COPYOUT : NO_COPYOUT, NULL, NULL);
26186 				return;
26187 			}
26188 			break;
26189 		}
26190 		err = 0;
26191 		ci.ci_sin = NULL;
26192 		ci.ci_sin6 = NULL;
26193 		ci.ci_lifr = NULL;
26194 		break;
26195 	}
26196 
26197 	/*
26198 	 * If ipsq is non-null, we are already being called exclusively
26199 	 */
26200 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26201 	if (!(ipip->ipi_flags & IPI_WR)) {
26202 		/*
26203 		 * A return value of EINPROGRESS means the ioctl is
26204 		 * either queued and waiting for some reason or has
26205 		 * already completed.
26206 		 */
26207 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26208 		    ci.ci_lifr);
26209 		if (ci.ci_ipif != NULL)
26210 			ipif_refrele(ci.ci_ipif);
26211 		ip_ioctl_finish(q, mp, err,
26212 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26213 		    NULL, NULL);
26214 		return;
26215 	}
26216 
26217 	ASSERT(ci.ci_ipif != NULL);
26218 
26219 	if (ipsq == NULL) {
26220 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26221 		    ip_process_ioctl, NEW_OP, B_TRUE);
26222 		entered_ipsq = B_TRUE;
26223 	}
26224 	/*
26225 	 * Release the ipif so that ipif_down and friends that wait for
26226 	 * references to go away are not misled about the current ipif_refcnt
26227 	 * values. We are writer so we can access the ipif even after releasing
26228 	 * the ipif.
26229 	 */
26230 	ipif_refrele(ci.ci_ipif);
26231 	if (ipsq == NULL)
26232 		return;
26233 
26234 	mutex_enter(&ipsq->ipsq_lock);
26235 	ASSERT(ipsq->ipsq_current_ipif == NULL);
26236 	ipsq->ipsq_current_ipif = ci.ci_ipif;
26237 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26238 	mutex_exit(&ipsq->ipsq_lock);
26239 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26240 	/*
26241 	 * For most set ioctls that come here, this serves as a single point
26242 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26243 	 * be any new references to the ipif. This helps functions that go
26244 	 * through this path and end up trying to wait for the refcnts
26245 	 * associated with the ipif to go down to zero. Some exceptions are
26246 	 * Failover, Failback, and Groupname commands that operate on more than
26247 	 * just the ci.ci_ipif. These commands internally determine the
26248 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26249 	 * flags on that set. Another exception is the Removeif command that
26250 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26251 	 * ipif to operate on.
26252 	 */
26253 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26254 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26255 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26256 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26257 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26258 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26259 
26260 	/*
26261 	 * A return value of EINPROGRESS means the ioctl is
26262 	 * either queued and waiting for some reason or has
26263 	 * already completed.
26264 	 */
26265 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26266 	    ci.ci_lifr);
26267 
26268 	/* SIOCLIFREMOVEIF could have removed the ipif */
26269 	ip_ioctl_finish(q, mp, err,
26270 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26271 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
26272 
26273 	if (entered_ipsq)
26274 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26275 }
26276 
26277 /*
26278  * Complete the ioctl. Typically ioctls use the mi package and need to
26279  * do mi_copyout/mi_copy_done.
26280  */
26281 void
26282 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
26283     ipif_t *ipif, ipsq_t *ipsq)
26284 {
26285 	conn_t	*connp = NULL;
26286 	hook_nic_event_t *info;
26287 
26288 	if (err == EINPROGRESS)
26289 		return;
26290 
26291 	if (CONN_Q(q)) {
26292 		connp = Q_TO_CONN(q);
26293 		ASSERT(connp->conn_ref >= 2);
26294 	}
26295 
26296 	switch (mode) {
26297 	case COPYOUT:
26298 		if (err == 0)
26299 			mi_copyout(q, mp);
26300 		else
26301 			mi_copy_done(q, mp, err);
26302 		break;
26303 
26304 	case NO_COPYOUT:
26305 		mi_copy_done(q, mp, err);
26306 		break;
26307 
26308 	default:
26309 		/* An ioctl aborted through a conn close would take this path */
26310 		break;
26311 	}
26312 
26313 	/*
26314 	 * The refhold placed at the start of the ioctl is released here.
26315 	 */
26316 	if (connp != NULL)
26317 		CONN_OPER_PENDING_DONE(connp);
26318 
26319 	/*
26320 	 * If the ioctl were an exclusive ioctl it would have set
26321 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
26322 	 */
26323 	if (ipif != NULL) {
26324 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
26325 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
26326 
26327 		/*
26328 		 * Unhook the nic event message from the ill and enqueue it into
26329 		 * the nic event taskq.
26330 		 */
26331 		if ((info = ipif->ipif_ill->ill_nic_event_info) != NULL) {
26332 			if (ddi_taskq_dispatch(eventq_queue_nic,
26333 			    ip_ne_queue_func, (void *)info, DDI_SLEEP)
26334 			    == DDI_FAILURE) {
26335 				ip2dbg(("ip_ioctl_finish: ddi_taskq_dispatch"
26336 				    "failed\n"));
26337 				if (info->hne_data != NULL)
26338 					kmem_free(info->hne_data,
26339 					    info->hne_datalen);
26340 				kmem_free(info, sizeof (hook_nic_event_t));
26341 			}
26342 
26343 			ipif->ipif_ill->ill_nic_event_info = NULL;
26344 		}
26345 
26346 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
26347 	}
26348 
26349 	/*
26350 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
26351 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
26352 	 * entering the ipsq
26353 	 */
26354 	if (ipsq != NULL) {
26355 		mutex_enter(&ipsq->ipsq_lock);
26356 		ipsq->ipsq_current_ipif = NULL;
26357 		mutex_exit(&ipsq->ipsq_lock);
26358 	}
26359 }
26360 
26361 /*
26362  * This is called from ip_wput_nondata to resume a deferred TCP bind.
26363  */
26364 /* ARGSUSED */
26365 void
26366 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
26367 {
26368 	conn_t *connp = arg;
26369 	tcp_t	*tcp;
26370 
26371 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
26372 	tcp = connp->conn_tcp;
26373 
26374 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
26375 		freemsg(mp);
26376 	else
26377 		tcp_rput_other(tcp, mp);
26378 	CONN_OPER_PENDING_DONE(connp);
26379 }
26380 
26381 /* Called from ip_wput for all non data messages */
26382 /* ARGSUSED */
26383 void
26384 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26385 {
26386 	mblk_t		*mp1;
26387 	ire_t		*ire, *fake_ire;
26388 	ill_t		*ill;
26389 	struct iocblk	*iocp;
26390 	ip_ioctl_cmd_t	*ipip;
26391 	cred_t		*cr;
26392 	conn_t		*connp = NULL;
26393 	int		cmd, err;
26394 	nce_t		*nce;
26395 	ipif_t		*ipif;
26396 
26397 	if (CONN_Q(q))
26398 		connp = Q_TO_CONN(q);
26399 
26400 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26401 
26402 	/* Check if it is a queue to /dev/sctp. */
26403 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26404 	    connp->conn_rq == NULL) {
26405 		sctp_wput(q, mp);
26406 		return;
26407 	}
26408 
26409 	switch (DB_TYPE(mp)) {
26410 	case M_IOCTL:
26411 		/*
26412 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26413 		 * will arrange to copy in associated control structures.
26414 		 */
26415 		ip_sioctl_copyin_setup(q, mp);
26416 		return;
26417 	case M_IOCDATA:
26418 		/*
26419 		 * Ensure that this is associated with one of our trans-
26420 		 * parent ioctls.  If it's not ours, discard it if we're
26421 		 * running as a driver, or pass it on if we're a module.
26422 		 */
26423 		iocp = (struct iocblk *)mp->b_rptr;
26424 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26425 		if (ipip == NULL) {
26426 			if (q->q_next == NULL) {
26427 				goto nak;
26428 			} else {
26429 				putnext(q, mp);
26430 			}
26431 			return;
26432 		} else if ((q->q_next != NULL) &&
26433 		    !(ipip->ipi_flags & IPI_MODOK)) {
26434 			/*
26435 			 * the ioctl is one we recognise, but is not
26436 			 * consumed by IP as a module, pass M_IOCDATA
26437 			 * for processing downstream, but only for
26438 			 * common Streams ioctls.
26439 			 */
26440 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26441 				putnext(q, mp);
26442 				return;
26443 			} else {
26444 				goto nak;
26445 			}
26446 		}
26447 
26448 		/* IOCTL continuation following copyin or copyout. */
26449 		if (mi_copy_state(q, mp, NULL) == -1) {
26450 			/*
26451 			 * The copy operation failed.  mi_copy_state already
26452 			 * cleaned up, so we're out of here.
26453 			 */
26454 			return;
26455 		}
26456 		/*
26457 		 * If we just completed a copy in, we become writer and
26458 		 * continue processing in ip_sioctl_copyin_done.  If it
26459 		 * was a copy out, we call mi_copyout again.  If there is
26460 		 * nothing more to copy out, it will complete the IOCTL.
26461 		 */
26462 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
26463 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
26464 				mi_copy_done(q, mp, EPROTO);
26465 				return;
26466 			}
26467 			/*
26468 			 * Check for cases that need more copying.  A return
26469 			 * value of 0 means a second copyin has been started,
26470 			 * so we return; a return value of 1 means no more
26471 			 * copying is needed, so we continue.
26472 			 */
26473 			cmd = iocp->ioc_cmd;
26474 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
26475 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
26476 			    MI_COPY_COUNT(mp) == 1) {
26477 				if (ip_copyin_msfilter(q, mp) == 0)
26478 					return;
26479 			}
26480 			/*
26481 			 * Refhold the conn, till the ioctl completes. This is
26482 			 * needed in case the ioctl ends up in the pending mp
26483 			 * list. Every mp in the ill_pending_mp list and
26484 			 * the ipsq_pending_mp must have a refhold on the conn
26485 			 * to resume processing. The refhold is released when
26486 			 * the ioctl completes. (normally or abnormally)
26487 			 * In all cases ip_ioctl_finish is called to finish
26488 			 * the ioctl.
26489 			 */
26490 			if (connp != NULL) {
26491 				/* This is not a reentry */
26492 				ASSERT(ipsq == NULL);
26493 				CONN_INC_REF(connp);
26494 			} else {
26495 				if (!(ipip->ipi_flags & IPI_MODOK)) {
26496 					mi_copy_done(q, mp, EINVAL);
26497 					return;
26498 				}
26499 			}
26500 
26501 			ip_process_ioctl(ipsq, q, mp, ipip);
26502 
26503 		} else {
26504 			mi_copyout(q, mp);
26505 		}
26506 		return;
26507 nak:
26508 		iocp->ioc_error = EINVAL;
26509 		mp->b_datap->db_type = M_IOCNAK;
26510 		iocp->ioc_count = 0;
26511 		qreply(q, mp);
26512 		return;
26513 
26514 	case M_IOCNAK:
26515 		/*
26516 		 * The only way we could get here is if a resolver didn't like
26517 		 * an IOCTL we sent it.	 This shouldn't happen.
26518 		 */
26519 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
26520 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
26521 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
26522 		freemsg(mp);
26523 		return;
26524 	case M_IOCACK:
26525 		/* Finish socket ioctls passed through to ARP. */
26526 		ip_sioctl_iocack(q, mp);
26527 		return;
26528 	case M_FLUSH:
26529 		if (*mp->b_rptr & FLUSHW)
26530 			flushq(q, FLUSHALL);
26531 		if (q->q_next) {
26532 			/*
26533 			 * M_FLUSH is sent up to IP by some drivers during
26534 			 * unbind. ip_rput has already replied to it. We are
26535 			 * here for the M_FLUSH that we originated in IP
26536 			 * before sending the unbind request to the driver.
26537 			 * Just free it as we don't queue packets in IP
26538 			 * on the write side of the device instance.
26539 			 */
26540 			freemsg(mp);
26541 			return;
26542 		}
26543 		if (*mp->b_rptr & FLUSHR) {
26544 			*mp->b_rptr &= ~FLUSHW;
26545 			qreply(q, mp);
26546 			return;
26547 		}
26548 		freemsg(mp);
26549 		return;
26550 	case IRE_DB_REQ_TYPE:
26551 		/* An Upper Level Protocol wants a copy of an IRE. */
26552 		ip_ire_req(q, mp);
26553 		return;
26554 	case M_CTL:
26555 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
26556 			break;
26557 
26558 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
26559 		    IP_ULP_OUT_LABELED) {
26560 			out_labeled_t *olp;
26561 
26562 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
26563 				break;
26564 			olp = (out_labeled_t *)mp->b_rptr;
26565 			connp->conn_ulp_labeled = olp->out_qnext == q;
26566 			freemsg(mp);
26567 			return;
26568 		}
26569 
26570 		/* M_CTL messages are used by ARP to tell us things. */
26571 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
26572 			break;
26573 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
26574 		case AR_ENTRY_SQUERY:
26575 			ip_wput_ctl(q, mp);
26576 			return;
26577 		case AR_CLIENT_NOTIFY:
26578 			ip_arp_news(q, mp);
26579 			return;
26580 		case AR_DLPIOP_DONE:
26581 			ASSERT(q->q_next != NULL);
26582 			ill = (ill_t *)q->q_ptr;
26583 			/* qwriter_ip releases the refhold */
26584 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
26585 			ill_refhold(ill);
26586 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
26587 			    CUR_OP, B_FALSE);
26588 			return;
26589 		case AR_ARP_CLOSING:
26590 			/*
26591 			 * ARP (above us) is closing. If no ARP bringup is
26592 			 * currently pending, ack the message so that ARP
26593 			 * can complete its close. Also mark ill_arp_closing
26594 			 * so that new ARP bringups will fail. If any
26595 			 * ARP bringup is currently in progress, we will
26596 			 * ack this when the current ARP bringup completes.
26597 			 */
26598 			ASSERT(q->q_next != NULL);
26599 			ill = (ill_t *)q->q_ptr;
26600 			mutex_enter(&ill->ill_lock);
26601 			ill->ill_arp_closing = 1;
26602 			if (!ill->ill_arp_bringup_pending) {
26603 				mutex_exit(&ill->ill_lock);
26604 				qreply(q, mp);
26605 			} else {
26606 				mutex_exit(&ill->ill_lock);
26607 				freemsg(mp);
26608 			}
26609 			return;
26610 		case AR_ARP_EXTEND:
26611 			/*
26612 			 * The ARP module above us is capable of duplicate
26613 			 * address detection.  Old ATM drivers will not send
26614 			 * this message.
26615 			 */
26616 			ASSERT(q->q_next != NULL);
26617 			ill = (ill_t *)q->q_ptr;
26618 			ill->ill_arp_extend = B_TRUE;
26619 			freemsg(mp);
26620 			return;
26621 		default:
26622 			break;
26623 		}
26624 		break;
26625 	case M_PROTO:
26626 	case M_PCPROTO:
26627 		/*
26628 		 * The only PROTO messages we expect are ULP binds and
26629 		 * copies of option negotiation acknowledgements.
26630 		 */
26631 		switch (((union T_primitives *)mp->b_rptr)->type) {
26632 		case O_T_BIND_REQ:
26633 		case T_BIND_REQ: {
26634 			/* Request can get queued in bind */
26635 			ASSERT(connp != NULL);
26636 			/*
26637 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
26638 			 * instead of going through this path.  We only get
26639 			 * here in the following cases:
26640 			 *
26641 			 * a. Bind retries, where ipsq is non-NULL.
26642 			 * b. T_BIND_REQ is issued from non TCP/UDP
26643 			 *    transport, e.g. icmp for raw socket,
26644 			 *    in which case ipsq will be NULL.
26645 			 */
26646 			ASSERT(ipsq != NULL ||
26647 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
26648 
26649 			/* Don't increment refcnt if this is a re-entry */
26650 			if (ipsq == NULL)
26651 				CONN_INC_REF(connp);
26652 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
26653 			    connp, NULL) : ip_bind_v4(q, mp, connp);
26654 			if (mp == NULL)
26655 				return;
26656 			if (IPCL_IS_TCP(connp)) {
26657 				/*
26658 				 * In the case of TCP endpoint we
26659 				 * come here only for bind retries
26660 				 */
26661 				ASSERT(ipsq != NULL);
26662 				CONN_INC_REF(connp);
26663 				squeue_fill(connp->conn_sqp, mp,
26664 				    ip_resume_tcp_bind, connp,
26665 				    SQTAG_BIND_RETRY);
26666 				return;
26667 			} else if (IPCL_IS_UDP(connp)) {
26668 				/*
26669 				 * In the case of UDP endpoint we
26670 				 * come here only for bind retries
26671 				 */
26672 				ASSERT(ipsq != NULL);
26673 				udp_resume_bind(connp, mp);
26674 				return;
26675 			}
26676 			qreply(q, mp);
26677 			CONN_OPER_PENDING_DONE(connp);
26678 			return;
26679 		}
26680 		case T_SVR4_OPTMGMT_REQ:
26681 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
26682 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
26683 
26684 			ASSERT(connp != NULL);
26685 			if (!snmpcom_req(q, mp, ip_snmp_set,
26686 			    ip_snmp_get, cr)) {
26687 				/*
26688 				 * Call svr4_optcom_req so that it can
26689 				 * generate the ack. We don't come here
26690 				 * if this operation is being restarted.
26691 				 * ip_restart_optmgmt will drop the conn ref.
26692 				 * In the case of ipsec option after the ipsec
26693 				 * load is complete conn_restart_ipsec_waiter
26694 				 * drops the conn ref.
26695 				 */
26696 				ASSERT(ipsq == NULL);
26697 				CONN_INC_REF(connp);
26698 				if (ip_check_for_ipsec_opt(q, mp))
26699 					return;
26700 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
26701 				if (err != EINPROGRESS) {
26702 					/* Operation is done */
26703 					CONN_OPER_PENDING_DONE(connp);
26704 				}
26705 			}
26706 			return;
26707 		case T_OPTMGMT_REQ:
26708 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
26709 			/*
26710 			 * Note: No snmpcom_req support through new
26711 			 * T_OPTMGMT_REQ.
26712 			 * Call tpi_optcom_req so that it can
26713 			 * generate the ack.
26714 			 */
26715 			ASSERT(connp != NULL);
26716 			ASSERT(ipsq == NULL);
26717 			/*
26718 			 * We don't come here for restart. ip_restart_optmgmt
26719 			 * will drop the conn ref. In the case of ipsec option
26720 			 * after the ipsec load is complete
26721 			 * conn_restart_ipsec_waiter drops the conn ref.
26722 			 */
26723 			CONN_INC_REF(connp);
26724 			if (ip_check_for_ipsec_opt(q, mp))
26725 				return;
26726 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
26727 			if (err != EINPROGRESS) {
26728 				/* Operation is done */
26729 				CONN_OPER_PENDING_DONE(connp);
26730 			}
26731 			return;
26732 		case T_UNBIND_REQ:
26733 			mp = ip_unbind(q, mp);
26734 			qreply(q, mp);
26735 			return;
26736 		default:
26737 			/*
26738 			 * Have to drop any DLPI messages coming down from
26739 			 * arp (such as an info_req which would cause ip
26740 			 * to receive an extra info_ack if it was passed
26741 			 * through.
26742 			 */
26743 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
26744 			    (int)*(uint_t *)mp->b_rptr));
26745 			freemsg(mp);
26746 			return;
26747 		}
26748 		/* NOTREACHED */
26749 	case IRE_DB_TYPE: {
26750 		nce_t		*nce;
26751 		ill_t		*ill;
26752 		in6_addr_t	gw_addr_v6;
26753 
26754 
26755 		/*
26756 		 * This is a response back from a resolver.  It
26757 		 * consists of a message chain containing:
26758 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
26759 		 * The IRE_MBLK is the one we allocated in ip_newroute.
26760 		 * The LL_HDR_MBLK is the DLPI header to use to get
26761 		 * the attached packet, and subsequent ones for the
26762 		 * same destination, transmitted.
26763 		 */
26764 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
26765 			break;
26766 		/*
26767 		 * First, check to make sure the resolution succeeded.
26768 		 * If it failed, the second mblk will be empty.
26769 		 * If it is, free the chain, dropping the packet.
26770 		 * (We must ire_delete the ire; that frees the ire mblk)
26771 		 * We're doing this now to support PVCs for ATM; it's
26772 		 * a partial xresolv implementation. When we fully implement
26773 		 * xresolv interfaces, instead of freeing everything here
26774 		 * we'll initiate neighbor discovery.
26775 		 *
26776 		 * For v4 (ARP and other external resolvers) the resolver
26777 		 * frees the message, so no check is needed. This check
26778 		 * is required, though, for a full xresolve implementation.
26779 		 * Including this code here now both shows how external
26780 		 * resolvers can NACK a resolution request using an
26781 		 * existing design that has no specific provisions for NACKs,
26782 		 * and also takes into account that the current non-ARP
26783 		 * external resolver has been coded to use this method of
26784 		 * NACKing for all IPv6 (xresolv) cases,
26785 		 * whether our xresolv implementation is complete or not.
26786 		 *
26787 		 */
26788 		ire = (ire_t *)mp->b_rptr;
26789 		ill = ire_to_ill(ire);
26790 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26791 		if (mp1->b_rptr == mp1->b_wptr) {
26792 			if (ire->ire_ipversion == IPV6_VERSION) {
26793 				/*
26794 				 * XRESOLV interface.
26795 				 */
26796 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
26797 				mutex_enter(&ire->ire_lock);
26798 				gw_addr_v6 = ire->ire_gateway_addr_v6;
26799 				mutex_exit(&ire->ire_lock);
26800 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26801 					nce = ndp_lookup_v6(ill,
26802 					    &ire->ire_addr_v6, B_FALSE);
26803 				} else {
26804 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
26805 					    B_FALSE);
26806 				}
26807 				if (nce != NULL) {
26808 					nce_resolv_failed(nce);
26809 					ndp_delete(nce);
26810 					NCE_REFRELE(nce);
26811 				}
26812 			}
26813 			mp->b_cont = NULL;
26814 			freemsg(mp1);		/* frees the pkt as well */
26815 			ASSERT(ire->ire_nce == NULL);
26816 			ire_delete((ire_t *)mp->b_rptr);
26817 			return;
26818 		}
26819 
26820 		/*
26821 		 * Split them into IRE_MBLK and pkt and feed it into
26822 		 * ire_add_then_send. Then in ire_add_then_send
26823 		 * the IRE will be added, and then the packet will be
26824 		 * run back through ip_wput. This time it will make
26825 		 * it to the wire.
26826 		 */
26827 		mp->b_cont = NULL;
26828 		mp = mp1->b_cont;		/* now, mp points to pkt */
26829 		mp1->b_cont = NULL;
26830 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
26831 		if (ire->ire_ipversion == IPV6_VERSION) {
26832 			/*
26833 			 * XRESOLV interface. Find the nce and put a copy
26834 			 * of the dl_unitdata_req in nce_res_mp
26835 			 */
26836 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
26837 			mutex_enter(&ire->ire_lock);
26838 			gw_addr_v6 = ire->ire_gateway_addr_v6;
26839 			mutex_exit(&ire->ire_lock);
26840 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26841 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
26842 				    B_FALSE);
26843 			} else {
26844 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
26845 			}
26846 			if (nce != NULL) {
26847 				/*
26848 				 * We have to protect nce_res_mp here
26849 				 * from being accessed by other threads
26850 				 * while we change the mblk pointer.
26851 				 * Other functions will also lock the nce when
26852 				 * accessing nce_res_mp.
26853 				 *
26854 				 * The reason we change the mblk pointer
26855 				 * here rather than copying the resolved address
26856 				 * into the template is that, unlike with
26857 				 * ethernet, we have no guarantee that the
26858 				 * resolved address length will be
26859 				 * smaller than or equal to the lla length
26860 				 * with which the template was allocated,
26861 				 * (for ethernet, they're equal)
26862 				 * so we have to use the actual resolved
26863 				 * address mblk - which holds the real
26864 				 * dl_unitdata_req with the resolved address.
26865 				 *
26866 				 * Doing this is the same behavior as was
26867 				 * previously used in the v4 ARP case.
26868 				 */
26869 				mutex_enter(&nce->nce_lock);
26870 				if (nce->nce_res_mp != NULL)
26871 					freemsg(nce->nce_res_mp);
26872 				nce->nce_res_mp = mp1;
26873 				mutex_exit(&nce->nce_lock);
26874 				/*
26875 				 * We do a fastpath probe here because
26876 				 * we have resolved the address without
26877 				 * using Neighbor Discovery.
26878 				 * In the non-XRESOLV v6 case, the fastpath
26879 				 * probe is done right after neighbor
26880 				 * discovery completes.
26881 				 */
26882 				if (nce->nce_res_mp != NULL) {
26883 					int res;
26884 					nce_fastpath_list_add(nce);
26885 					res = ill_fastpath_probe(ill,
26886 					    nce->nce_res_mp);
26887 					if (res != 0 && res != EAGAIN)
26888 						nce_fastpath_list_delete(nce);
26889 				}
26890 
26891 				ire_add_then_send(q, ire, mp);
26892 				/*
26893 				 * Now we have to clean out any packets
26894 				 * that may have been queued on the nce
26895 				 * while it was waiting for address resolution
26896 				 * to complete.
26897 				 */
26898 				mutex_enter(&nce->nce_lock);
26899 				mp1 = nce->nce_qd_mp;
26900 				nce->nce_qd_mp = NULL;
26901 				mutex_exit(&nce->nce_lock);
26902 				while (mp1 != NULL) {
26903 					mblk_t *nxt_mp;
26904 					queue_t *fwdq = NULL;
26905 					ill_t   *inbound_ill;
26906 					uint_t ifindex;
26907 
26908 					nxt_mp = mp1->b_next;
26909 					mp1->b_next = NULL;
26910 					/*
26911 					 * Retrieve ifindex stored in
26912 					 * ip_rput_data_v6()
26913 					 */
26914 					ifindex =
26915 					    (uint_t)(uintptr_t)mp1->b_prev;
26916 					inbound_ill =
26917 						ill_lookup_on_ifindex(ifindex,
26918 						    B_TRUE, NULL, NULL, NULL,
26919 						    NULL);
26920 					mp1->b_prev = NULL;
26921 					if (inbound_ill != NULL)
26922 						fwdq = inbound_ill->ill_rq;
26923 
26924 					if (fwdq != NULL) {
26925 						put(fwdq, mp1);
26926 						ill_refrele(inbound_ill);
26927 					} else
26928 						put(WR(ill->ill_rq), mp1);
26929 					mp1 = nxt_mp;
26930 				}
26931 				NCE_REFRELE(nce);
26932 			} else {	/* nce is NULL; clean up */
26933 				ire_delete(ire);
26934 				freemsg(mp);
26935 				freemsg(mp1);
26936 				return;
26937 			}
26938 		} else {
26939 			nce_t *arpce;
26940 			/*
26941 			 * Link layer resolution succeeded. Recompute the
26942 			 * ire_nce.
26943 			 */
26944 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
26945 			if ((arpce = ndp_lookup_v4(ill,
26946 			    (ire->ire_gateway_addr != INADDR_ANY ?
26947 			    &ire->ire_gateway_addr : &ire->ire_addr),
26948 			    B_FALSE)) == NULL) {
26949 				freeb(ire->ire_mp);
26950 				freeb(mp1);
26951 				freemsg(mp);
26952 				return;
26953 			}
26954 			mutex_enter(&arpce->nce_lock);
26955 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
26956 			if (arpce->nce_state == ND_REACHABLE) {
26957 				/*
26958 				 * Someone resolved this before us;
26959 				 * cleanup the res_mp. Since ire has
26960 				 * not been added yet, the call to ire_add_v4
26961 				 * from ire_add_then_send (when a dup is
26962 				 * detected) will clean up the ire.
26963 				 */
26964 				freeb(mp1);
26965 			} else {
26966 				if (arpce->nce_res_mp != NULL)
26967 					freemsg(arpce->nce_res_mp);
26968 				arpce->nce_res_mp = mp1;
26969 				arpce->nce_state = ND_REACHABLE;
26970 			}
26971 			mutex_exit(&arpce->nce_lock);
26972 			if (ire->ire_marks & IRE_MARK_NOADD) {
26973 				/*
26974 				 * this ire will not be added to the ire
26975 				 * cache table, so we can set the ire_nce
26976 				 * here, as there are no atomicity constraints.
26977 				 */
26978 				ire->ire_nce = arpce;
26979 				/*
26980 				 * We are associating this nce with the ire
26981 				 * so change the nce ref taken in
26982 				 * ndp_lookup_v4() from
26983 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
26984 				 */
26985 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
26986 			} else {
26987 				NCE_REFRELE(arpce);
26988 			}
26989 			ire_add_then_send(q, ire, mp);
26990 		}
26991 		return;	/* All is well, the packet has been sent. */
26992 	}
26993 	case IRE_ARPRESOLVE_TYPE: {
26994 
26995 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
26996 			break;
26997 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26998 		mp->b_cont = NULL;
26999 		/*
27000 		 * First, check to make sure the resolution succeeded.
27001 		 * If it failed, the second mblk will be empty.
27002 		 */
27003 		if (mp1->b_rptr == mp1->b_wptr) {
27004 			/* cleanup  the incomplete ire, free queued packets */
27005 			freemsg(mp); /* fake ire */
27006 			freeb(mp1);  /* dl_unitdata response */
27007 			return;
27008 		}
27009 
27010 		/*
27011 		 * update any incomplete nce_t found. we lookup the ctable
27012 		 * and find the nce from the ire->ire_nce because we need
27013 		 * to pass the ire to ip_xmit_v4 later, and can find both
27014 		 * ire and nce in one lookup from the ctable.
27015 		 */
27016 		fake_ire = (ire_t *)mp->b_rptr;
27017 		/*
27018 		 * By the time we come back here from ARP
27019 		 * the logical outgoing interface  of the incomplete ire
27020 		 * we added in ire_forward could have disappeared,
27021 		 * causing the incomplete ire to also have
27022 		 * dissapeared. So we need to retreive the
27023 		 * proper ipif for the ire  before looking
27024 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27025 		 */
27026 		ill = q->q_ptr;
27027 
27028 		/* Get the outgoing ipif */
27029 		mutex_enter(&ill->ill_lock);
27030 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27031 			mutex_exit(&ill->ill_lock);
27032 			freemsg(mp); /* fake ire */
27033 			freeb(mp1);  /* dl_unitdata response */
27034 			return;
27035 		}
27036 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27037 
27038 		if (ipif == NULL) {
27039 			mutex_exit(&ill->ill_lock);
27040 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27041 			freemsg(mp);
27042 			freeb(mp1);
27043 			return;
27044 		}
27045 		ipif_refhold_locked(ipif);
27046 		mutex_exit(&ill->ill_lock);
27047 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27048 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27049 		    ipif, fake_ire->ire_zoneid, NULL,
27050 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
27051 		ipif_refrele(ipif);
27052 		if (ire == NULL) {
27053 			/*
27054 			 * no ire was found; check if there is an nce
27055 			 * for this lookup; if it has no ire's pointing at it
27056 			 * cleanup.
27057 			 */
27058 			if ((nce = ndp_lookup_v4(ill,
27059 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27060 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27061 			    B_FALSE)) != NULL) {
27062 				/*
27063 				 * cleanup: just reset nce.
27064 				 * We check for refcnt 2 (one for the nce
27065 				 * hash list + 1 for the ref taken by
27066 				 * ndp_lookup_v4) to ensure that there are
27067 				 * no ire's pointing at the nce.
27068 				 */
27069 				if (nce->nce_refcnt == 2) {
27070 					nce = nce_reinit(nce);
27071 				}
27072 				if (nce != NULL)
27073 					NCE_REFRELE(nce);
27074 			}
27075 			freeb(mp1);  /* dl_unitdata response */
27076 			freemsg(mp); /* fake ire */
27077 			return;
27078 		}
27079 		nce = ire->ire_nce;
27080 		DTRACE_PROBE2(ire__arpresolve__type,
27081 		    ire_t *, ire, nce_t *, nce);
27082 		ASSERT(nce->nce_state != ND_INITIAL);
27083 		mutex_enter(&nce->nce_lock);
27084 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27085 		if (nce->nce_state == ND_REACHABLE) {
27086 			/*
27087 			 * Someone resolved this before us;
27088 			 * our response is not needed any more.
27089 			 */
27090 			mutex_exit(&nce->nce_lock);
27091 			freeb(mp1);  /* dl_unitdata response */
27092 		} else {
27093 			if (nce->nce_res_mp != NULL) {
27094 				freemsg(nce->nce_res_mp);
27095 				/* existing dl_unitdata template */
27096 			}
27097 			nce->nce_res_mp = mp1;
27098 			nce->nce_state = ND_REACHABLE;
27099 			mutex_exit(&nce->nce_lock);
27100 			ire_fastpath(ire);
27101 		}
27102 		/*
27103 		 * The cached nce_t has been updated to be reachable;
27104 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
27105 		 */
27106 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27107 		freemsg(mp);
27108 		/*
27109 		 * send out queued packets.
27110 		 */
27111 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27112 
27113 		IRE_REFRELE(ire);
27114 		return;
27115 	}
27116 	default:
27117 		break;
27118 	}
27119 	if (q->q_next) {
27120 		putnext(q, mp);
27121 	} else
27122 		freemsg(mp);
27123 }
27124 
27125 /*
27126  * Process IP options in an outbound packet.  Modify the destination if there
27127  * is a source route option.
27128  * Returns non-zero if something fails in which case an ICMP error has been
27129  * sent and mp freed.
27130  */
27131 static int
27132 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27133     boolean_t mctl_present, zoneid_t zoneid)
27134 {
27135 	ipoptp_t	opts;
27136 	uchar_t		*opt;
27137 	uint8_t		optval;
27138 	uint8_t		optlen;
27139 	ipaddr_t	dst;
27140 	intptr_t	code = 0;
27141 	mblk_t		*mp;
27142 	ire_t		*ire = NULL;
27143 
27144 	ip2dbg(("ip_wput_options\n"));
27145 	mp = ipsec_mp;
27146 	if (mctl_present) {
27147 		mp = ipsec_mp->b_cont;
27148 	}
27149 
27150 	dst = ipha->ipha_dst;
27151 	for (optval = ipoptp_first(&opts, ipha);
27152 	    optval != IPOPT_EOL;
27153 	    optval = ipoptp_next(&opts)) {
27154 		opt = opts.ipoptp_cur;
27155 		optlen = opts.ipoptp_len;
27156 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27157 		    optval, optlen));
27158 		switch (optval) {
27159 			uint32_t off;
27160 		case IPOPT_SSRR:
27161 		case IPOPT_LSRR:
27162 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27163 				ip1dbg((
27164 				    "ip_wput_options: bad option offset\n"));
27165 				code = (char *)&opt[IPOPT_OLEN] -
27166 				    (char *)ipha;
27167 				goto param_prob;
27168 			}
27169 			off = opt[IPOPT_OFFSET];
27170 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27171 			    ntohl(dst)));
27172 			/*
27173 			 * For strict: verify that dst is directly
27174 			 * reachable.
27175 			 */
27176 			if (optval == IPOPT_SSRR) {
27177 				ire = ire_ftable_lookup(dst, 0, 0,
27178 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27179 				    MBLK_GETLABEL(mp),
27180 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
27181 				if (ire == NULL) {
27182 					ip1dbg(("ip_wput_options: SSRR not"
27183 					    " directly reachable: 0x%x\n",
27184 					    ntohl(dst)));
27185 					goto bad_src_route;
27186 				}
27187 				ire_refrele(ire);
27188 			}
27189 			break;
27190 		case IPOPT_RR:
27191 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27192 				ip1dbg((
27193 				    "ip_wput_options: bad option offset\n"));
27194 				code = (char *)&opt[IPOPT_OLEN] -
27195 				    (char *)ipha;
27196 				goto param_prob;
27197 			}
27198 			break;
27199 		case IPOPT_TS:
27200 			/*
27201 			 * Verify that length >=5 and that there is either
27202 			 * room for another timestamp or that the overflow
27203 			 * counter is not maxed out.
27204 			 */
27205 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27206 			if (optlen < IPOPT_MINLEN_IT) {
27207 				goto param_prob;
27208 			}
27209 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27210 				ip1dbg((
27211 				    "ip_wput_options: bad option offset\n"));
27212 				code = (char *)&opt[IPOPT_OFFSET] -
27213 				    (char *)ipha;
27214 				goto param_prob;
27215 			}
27216 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27217 			case IPOPT_TS_TSONLY:
27218 				off = IPOPT_TS_TIMELEN;
27219 				break;
27220 			case IPOPT_TS_TSANDADDR:
27221 			case IPOPT_TS_PRESPEC:
27222 			case IPOPT_TS_PRESPEC_RFC791:
27223 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27224 				break;
27225 			default:
27226 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27227 				    (char *)ipha;
27228 				goto param_prob;
27229 			}
27230 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27231 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27232 				/*
27233 				 * No room and the overflow counter is 15
27234 				 * already.
27235 				 */
27236 				goto param_prob;
27237 			}
27238 			break;
27239 		}
27240 	}
27241 
27242 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27243 		return (0);
27244 
27245 	ip1dbg(("ip_wput_options: error processing IP options."));
27246 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27247 
27248 param_prob:
27249 	/*
27250 	 * Since ip_wput() isn't close to finished, we fill
27251 	 * in enough of the header for credible error reporting.
27252 	 */
27253 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27254 		/* Failed */
27255 		freemsg(ipsec_mp);
27256 		return (-1);
27257 	}
27258 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid);
27259 	return (-1);
27260 
27261 bad_src_route:
27262 	/*
27263 	 * Since ip_wput() isn't close to finished, we fill
27264 	 * in enough of the header for credible error reporting.
27265 	 */
27266 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27267 		/* Failed */
27268 		freemsg(ipsec_mp);
27269 		return (-1);
27270 	}
27271 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
27272 	return (-1);
27273 }
27274 
27275 /*
27276  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27277  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27278  * thru /etc/system.
27279  */
27280 #define	CONN_MAXDRAINCNT	64
27281 
27282 static void
27283 conn_drain_init(void)
27284 {
27285 	int i;
27286 
27287 	conn_drain_list_cnt = conn_drain_nthreads;
27288 
27289 	if ((conn_drain_list_cnt == 0) ||
27290 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27291 		/*
27292 		 * Default value of the number of drainers is the
27293 		 * number of cpus, subject to maximum of 8 drainers.
27294 		 */
27295 		if (boot_max_ncpus != -1)
27296 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27297 		else
27298 			conn_drain_list_cnt = MIN(max_ncpus, 8);
27299 	}
27300 
27301 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
27302 	    KM_SLEEP);
27303 
27304 	for (i = 0; i < conn_drain_list_cnt; i++) {
27305 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
27306 		    MUTEX_DEFAULT, NULL);
27307 	}
27308 }
27309 
27310 static void
27311 conn_drain_fini(void)
27312 {
27313 	int i;
27314 
27315 	for (i = 0; i < conn_drain_list_cnt; i++)
27316 		mutex_destroy(&conn_drain_list[i].idl_lock);
27317 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
27318 	conn_drain_list = NULL;
27319 }
27320 
27321 /*
27322  * Note: For an overview of how flowcontrol is handled in IP please see the
27323  * IP Flowcontrol notes at the top of this file.
27324  *
27325  * Flow control has blocked us from proceeding. Insert the given conn in one
27326  * of the conn drain lists. These conn wq's will be qenabled later on when
27327  * STREAMS flow control does a backenable. conn_walk_drain will enable
27328  * the first conn in each of these drain lists. Each of these qenabled conns
27329  * in turn enables the next in the list, after it runs, or when it closes,
27330  * thus sustaining the drain process.
27331  *
27332  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27333  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27334  * running at any time, on a given conn, since there can be only 1 service proc
27335  * running on a queue at any time.
27336  */
27337 void
27338 conn_drain_insert(conn_t *connp)
27339 {
27340 	idl_t	*idl;
27341 	uint_t	index;
27342 
27343 	mutex_enter(&connp->conn_lock);
27344 	if (connp->conn_state_flags & CONN_CLOSING) {
27345 		/*
27346 		 * The conn is closing as a result of which CONN_CLOSING
27347 		 * is set. Return.
27348 		 */
27349 		mutex_exit(&connp->conn_lock);
27350 		return;
27351 	} else if (connp->conn_idl == NULL) {
27352 		/*
27353 		 * Assign the next drain list round robin. We dont' use
27354 		 * a lock, and thus it may not be strictly round robin.
27355 		 * Atomicity of load/stores is enough to make sure that
27356 		 * conn_drain_list_index is always within bounds.
27357 		 */
27358 		index = conn_drain_list_index;
27359 		ASSERT(index < conn_drain_list_cnt);
27360 		connp->conn_idl = &conn_drain_list[index];
27361 		index++;
27362 		if (index == conn_drain_list_cnt)
27363 			index = 0;
27364 		conn_drain_list_index = index;
27365 	}
27366 	mutex_exit(&connp->conn_lock);
27367 
27368 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27369 	if ((connp->conn_drain_prev != NULL) ||
27370 	    (connp->conn_state_flags & CONN_CLOSING)) {
27371 		/*
27372 		 * The conn is already in the drain list, OR
27373 		 * the conn is closing. We need to check again for
27374 		 * the closing case again since close can happen
27375 		 * after we drop the conn_lock, and before we
27376 		 * acquire the CONN_DRAIN_LIST_LOCK.
27377 		 */
27378 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27379 		return;
27380 	} else {
27381 		idl = connp->conn_idl;
27382 	}
27383 
27384 	/*
27385 	 * The conn is not in the drain list. Insert it at the
27386 	 * tail of the drain list. The drain list is circular
27387 	 * and doubly linked. idl_conn points to the 1st element
27388 	 * in the list.
27389 	 */
27390 	if (idl->idl_conn == NULL) {
27391 		idl->idl_conn = connp;
27392 		connp->conn_drain_next = connp;
27393 		connp->conn_drain_prev = connp;
27394 	} else {
27395 		conn_t *head = idl->idl_conn;
27396 
27397 		connp->conn_drain_next = head;
27398 		connp->conn_drain_prev = head->conn_drain_prev;
27399 		head->conn_drain_prev->conn_drain_next = connp;
27400 		head->conn_drain_prev = connp;
27401 	}
27402 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27403 }
27404 
27405 /*
27406  * This conn is closing, and we are called from ip_close. OR
27407  * This conn has been serviced by ip_wsrv, and we need to do the tail
27408  * processing.
27409  * If this conn is part of the drain list, we may need to sustain the drain
27410  * process by qenabling the next conn in the drain list. We may also need to
27411  * remove this conn from the list, if it is done.
27412  */
27413 static void
27414 conn_drain_tail(conn_t *connp, boolean_t closing)
27415 {
27416 	idl_t *idl;
27417 
27418 	/*
27419 	 * connp->conn_idl is stable at this point, and no lock is needed
27420 	 * to check it. If we are called from ip_close, close has already
27421 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27422 	 * called us only because conn_idl is non-null. If we are called thru
27423 	 * service, conn_idl could be null, but it cannot change because
27424 	 * service is single-threaded per queue, and there cannot be another
27425 	 * instance of service trying to call conn_drain_insert on this conn
27426 	 * now.
27427 	 */
27428 	ASSERT(!closing || (connp->conn_idl != NULL));
27429 
27430 	/*
27431 	 * If connp->conn_idl is null, the conn has not been inserted into any
27432 	 * drain list even once since creation of the conn. Just return.
27433 	 */
27434 	if (connp->conn_idl == NULL)
27435 		return;
27436 
27437 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27438 
27439 	if (connp->conn_drain_prev == NULL) {
27440 		/* This conn is currently not in the drain list.  */
27441 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27442 		return;
27443 	}
27444 	idl = connp->conn_idl;
27445 	if (idl->idl_conn_draining == connp) {
27446 		/*
27447 		 * This conn is the current drainer. If this is the last conn
27448 		 * in the drain list, we need to do more checks, in the 'if'
27449 		 * below. Otherwwise we need to just qenable the next conn,
27450 		 * to sustain the draining, and is handled in the 'else'
27451 		 * below.
27452 		 */
27453 		if (connp->conn_drain_next == idl->idl_conn) {
27454 			/*
27455 			 * This conn is the last in this list. This round
27456 			 * of draining is complete. If idl_repeat is set,
27457 			 * it means another flow enabling has happened from
27458 			 * the driver/streams and we need to another round
27459 			 * of draining.
27460 			 * If there are more than 2 conns in the drain list,
27461 			 * do a left rotate by 1, so that all conns except the
27462 			 * conn at the head move towards the head by 1, and the
27463 			 * the conn at the head goes to the tail. This attempts
27464 			 * a more even share for all queues that are being
27465 			 * drained.
27466 			 */
27467 			if ((connp->conn_drain_next != connp) &&
27468 			    (idl->idl_conn->conn_drain_next != connp)) {
27469 				idl->idl_conn = idl->idl_conn->conn_drain_next;
27470 			}
27471 			if (idl->idl_repeat) {
27472 				qenable(idl->idl_conn->conn_wq);
27473 				idl->idl_conn_draining = idl->idl_conn;
27474 				idl->idl_repeat = 0;
27475 			} else {
27476 				idl->idl_conn_draining = NULL;
27477 			}
27478 		} else {
27479 			/*
27480 			 * If the next queue that we are now qenable'ing,
27481 			 * is closing, it will remove itself from this list
27482 			 * and qenable the subsequent queue in ip_close().
27483 			 * Serialization is acheived thru idl_lock.
27484 			 */
27485 			qenable(connp->conn_drain_next->conn_wq);
27486 			idl->idl_conn_draining = connp->conn_drain_next;
27487 		}
27488 	}
27489 	if (!connp->conn_did_putbq || closing) {
27490 		/*
27491 		 * Remove ourself from the drain list, if we did not do
27492 		 * a putbq, or if the conn is closing.
27493 		 * Note: It is possible that q->q_first is non-null. It means
27494 		 * that these messages landed after we did a enableok() in
27495 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
27496 		 * service them.
27497 		 */
27498 		if (connp->conn_drain_next == connp) {
27499 			/* Singleton in the list */
27500 			ASSERT(connp->conn_drain_prev == connp);
27501 			idl->idl_conn = NULL;
27502 			idl->idl_conn_draining = NULL;
27503 		} else {
27504 			connp->conn_drain_prev->conn_drain_next =
27505 			    connp->conn_drain_next;
27506 			connp->conn_drain_next->conn_drain_prev =
27507 			    connp->conn_drain_prev;
27508 			if (idl->idl_conn == connp)
27509 				idl->idl_conn = connp->conn_drain_next;
27510 			ASSERT(idl->idl_conn_draining != connp);
27511 
27512 		}
27513 		connp->conn_drain_next = NULL;
27514 		connp->conn_drain_prev = NULL;
27515 	}
27516 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27517 }
27518 
27519 /*
27520  * Write service routine. Shared perimeter entry point.
27521  * ip_wsrv can be called in any of the following ways.
27522  * 1. The device queue's messages has fallen below the low water mark
27523  *    and STREAMS has backenabled the ill_wq. We walk thru all the
27524  *    the drain lists and backenable the first conn in each list.
27525  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
27526  *    qenabled non-tcp upper layers. We start dequeing messages and call
27527  *    ip_wput for each message.
27528  */
27529 
27530 void
27531 ip_wsrv(queue_t *q)
27532 {
27533 	conn_t	*connp;
27534 	ill_t	*ill;
27535 	mblk_t	*mp;
27536 
27537 	if (q->q_next) {
27538 		ill = (ill_t *)q->q_ptr;
27539 		if (ill->ill_state_flags == 0) {
27540 			/*
27541 			 * The device flow control has opened up.
27542 			 * Walk through conn drain lists and qenable the
27543 			 * first conn in each list. This makes sense only
27544 			 * if the stream is fully plumbed and setup.
27545 			 * Hence the if check above.
27546 			 */
27547 			ip1dbg(("ip_wsrv: walking\n"));
27548 			conn_walk_drain();
27549 		}
27550 		return;
27551 	}
27552 
27553 	connp = Q_TO_CONN(q);
27554 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
27555 
27556 	/*
27557 	 * 1. Set conn_draining flag to signal that service is active.
27558 	 *
27559 	 * 2. ip_output determines whether it has been called from service,
27560 	 *    based on the last parameter. If it is IP_WSRV it concludes it
27561 	 *    has been called from service.
27562 	 *
27563 	 * 3. Message ordering is preserved by the following logic.
27564 	 *    i. A directly called ip_output (i.e. not thru service) will queue
27565 	 *    the message at the tail, if conn_draining is set (i.e. service
27566 	 *    is running) or if q->q_first is non-null.
27567 	 *
27568 	 *    ii. If ip_output is called from service, and if ip_output cannot
27569 	 *    putnext due to flow control, it does a putbq.
27570 	 *
27571 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
27572 	 *    (causing an infinite loop).
27573 	 */
27574 	ASSERT(!connp->conn_did_putbq);
27575 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
27576 		connp->conn_draining = 1;
27577 		noenable(q);
27578 		while ((mp = getq(q)) != NULL) {
27579 			ASSERT(CONN_Q(q));
27580 
27581 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
27582 			if (connp->conn_did_putbq) {
27583 				/* ip_wput did a putbq */
27584 				break;
27585 			}
27586 		}
27587 		/*
27588 		 * At this point, a thread coming down from top, calling
27589 		 * ip_wput, may end up queueing the message. We have not yet
27590 		 * enabled the queue, so ip_wsrv won't be called again.
27591 		 * To avoid this race, check q->q_first again (in the loop)
27592 		 * If the other thread queued the message before we call
27593 		 * enableok(), we will catch it in the q->q_first check.
27594 		 * If the other thread queues the message after we call
27595 		 * enableok(), ip_wsrv will be called again by STREAMS.
27596 		 */
27597 		connp->conn_draining = 0;
27598 		enableok(q);
27599 	}
27600 
27601 	/* Enable the next conn for draining */
27602 	conn_drain_tail(connp, B_FALSE);
27603 
27604 	connp->conn_did_putbq = 0;
27605 }
27606 
27607 /*
27608  * Walk the list of all conn's calling the function provided with the
27609  * specified argument for each.	 Note that this only walks conn's that
27610  * have been bound.
27611  * Applies to both IPv4 and IPv6.
27612  */
27613 static void
27614 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
27615 {
27616 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
27617 	    func, arg, zoneid);
27618 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
27619 	    func, arg, zoneid);
27620 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
27621 	    func, arg, zoneid);
27622 	conn_walk_fanout_table(ipcl_proto_fanout,
27623 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
27624 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
27625 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
27626 }
27627 
27628 /*
27629  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
27630  * of conns that need to be drained, check if drain is already in progress.
27631  * If so set the idl_repeat bit, indicating that the last conn in the list
27632  * needs to reinitiate the drain once again, for the list. If drain is not
27633  * in progress for the list, initiate the draining, by qenabling the 1st
27634  * conn in the list. The drain is self-sustaining, each qenabled conn will
27635  * in turn qenable the next conn, when it is done/blocked/closing.
27636  */
27637 static void
27638 conn_walk_drain(void)
27639 {
27640 	int i;
27641 	idl_t *idl;
27642 
27643 	IP_STAT(ip_conn_walk_drain);
27644 
27645 	for (i = 0; i < conn_drain_list_cnt; i++) {
27646 		idl = &conn_drain_list[i];
27647 		mutex_enter(&idl->idl_lock);
27648 		if (idl->idl_conn == NULL) {
27649 			mutex_exit(&idl->idl_lock);
27650 			continue;
27651 		}
27652 		/*
27653 		 * If this list is not being drained currently by
27654 		 * an ip_wsrv thread, start the process.
27655 		 */
27656 		if (idl->idl_conn_draining == NULL) {
27657 			ASSERT(idl->idl_repeat == 0);
27658 			qenable(idl->idl_conn->conn_wq);
27659 			idl->idl_conn_draining = idl->idl_conn;
27660 		} else {
27661 			idl->idl_repeat = 1;
27662 		}
27663 		mutex_exit(&idl->idl_lock);
27664 	}
27665 }
27666 
27667 /*
27668  * Walk an conn hash table of `count' buckets, calling func for each entry.
27669  */
27670 static void
27671 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
27672     zoneid_t zoneid)
27673 {
27674 	conn_t	*connp;
27675 
27676 	while (count-- > 0) {
27677 		mutex_enter(&connfp->connf_lock);
27678 		for (connp = connfp->connf_head; connp != NULL;
27679 		    connp = connp->conn_next) {
27680 			if (zoneid == GLOBAL_ZONEID ||
27681 			    zoneid == connp->conn_zoneid) {
27682 				CONN_INC_REF(connp);
27683 				mutex_exit(&connfp->connf_lock);
27684 				(*func)(connp, arg);
27685 				mutex_enter(&connfp->connf_lock);
27686 				CONN_DEC_REF(connp);
27687 			}
27688 		}
27689 		mutex_exit(&connfp->connf_lock);
27690 		connfp++;
27691 	}
27692 }
27693 
27694 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
27695 static void
27696 conn_report1(conn_t *connp, void *mp)
27697 {
27698 	char	buf1[INET6_ADDRSTRLEN];
27699 	char	buf2[INET6_ADDRSTRLEN];
27700 	uint_t	print_len, buf_len;
27701 
27702 	ASSERT(connp != NULL);
27703 
27704 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
27705 	if (buf_len <= 0)
27706 		return;
27707 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
27708 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
27709 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
27710 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
27711 	    "%5d %s/%05d %s/%05d\n",
27712 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
27713 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
27714 	    buf1, connp->conn_lport,
27715 	    buf2, connp->conn_fport);
27716 	if (print_len < buf_len) {
27717 		((mblk_t *)mp)->b_wptr += print_len;
27718 	} else {
27719 		((mblk_t *)mp)->b_wptr += buf_len;
27720 	}
27721 }
27722 
27723 /*
27724  * Named Dispatch routine to produce a formatted report on all conns
27725  * that are listed in one of the fanout tables.
27726  * This report is accessed by using the ndd utility to "get" ND variable
27727  * "ip_conn_status".
27728  */
27729 /* ARGSUSED */
27730 static int
27731 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
27732 {
27733 	(void) mi_mpprintf(mp,
27734 	    "CONN      " MI_COL_HDRPAD_STR
27735 	    "rfq      " MI_COL_HDRPAD_STR
27736 	    "stq      " MI_COL_HDRPAD_STR
27737 	    " zone local                 remote");
27738 
27739 	/*
27740 	 * Because of the ndd constraint, at most we can have 64K buffer
27741 	 * to put in all conn info.  So to be more efficient, just
27742 	 * allocate a 64K buffer here, assuming we need that large buffer.
27743 	 * This should be OK as only privileged processes can do ndd /dev/ip.
27744 	 */
27745 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
27746 		/* The following may work even if we cannot get a large buf. */
27747 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
27748 		return (0);
27749 	}
27750 
27751 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
27752 	return (0);
27753 }
27754 
27755 /*
27756  * Determine if the ill and multicast aspects of that packets
27757  * "matches" the conn.
27758  */
27759 boolean_t
27760 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
27761     zoneid_t zoneid)
27762 {
27763 	ill_t *in_ill;
27764 	boolean_t found;
27765 	ipif_t *ipif;
27766 	ire_t *ire;
27767 	ipaddr_t dst, src;
27768 
27769 	dst = ipha->ipha_dst;
27770 	src = ipha->ipha_src;
27771 
27772 	/*
27773 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
27774 	 * unicast, broadcast and multicast reception to
27775 	 * conn_incoming_ill. conn_wantpacket itself is called
27776 	 * only for BROADCAST and multicast.
27777 	 *
27778 	 * 1) ip_rput supresses duplicate broadcasts if the ill
27779 	 *    is part of a group. Hence, we should be receiving
27780 	 *    just one copy of broadcast for the whole group.
27781 	 *    Thus, if it is part of the group the packet could
27782 	 *    come on any ill of the group and hence we need a
27783 	 *    match on the group. Otherwise, match on ill should
27784 	 *    be sufficient.
27785 	 *
27786 	 * 2) ip_rput does not suppress duplicate multicast packets.
27787 	 *    If there are two interfaces in a ill group and we have
27788 	 *    2 applications (conns) joined a multicast group G on
27789 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
27790 	 *    will give us two packets because we join G on both the
27791 	 *    interfaces rather than nominating just one interface
27792 	 *    for receiving multicast like broadcast above. So,
27793 	 *    we have to call ilg_lookup_ill to filter out duplicate
27794 	 *    copies, if ill is part of a group.
27795 	 */
27796 	in_ill = connp->conn_incoming_ill;
27797 	if (in_ill != NULL) {
27798 		if (in_ill->ill_group == NULL) {
27799 			if (in_ill != ill)
27800 				return (B_FALSE);
27801 		} else if (in_ill->ill_group != ill->ill_group) {
27802 			return (B_FALSE);
27803 		}
27804 	}
27805 
27806 	if (!CLASSD(dst)) {
27807 		if (IPCL_ZONE_MATCH(connp, zoneid))
27808 			return (B_TRUE);
27809 		/*
27810 		 * The conn is in a different zone; we need to check that this
27811 		 * broadcast address is configured in the application's zone and
27812 		 * on one ill in the group.
27813 		 */
27814 		ipif = ipif_get_next_ipif(NULL, ill);
27815 		if (ipif == NULL)
27816 			return (B_FALSE);
27817 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
27818 		    connp->conn_zoneid, NULL,
27819 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
27820 		ipif_refrele(ipif);
27821 		if (ire != NULL) {
27822 			ire_refrele(ire);
27823 			return (B_TRUE);
27824 		} else {
27825 			return (B_FALSE);
27826 		}
27827 	}
27828 
27829 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
27830 	    connp->conn_zoneid == zoneid) {
27831 		/*
27832 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
27833 		 * disabled, therefore we don't dispatch the multicast packet to
27834 		 * the sending zone.
27835 		 */
27836 		return (B_FALSE);
27837 	}
27838 
27839 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
27840 	    connp->conn_zoneid != zoneid) {
27841 		/*
27842 		 * Multicast packet on the loopback interface: we only match
27843 		 * conns who joined the group in the specified zone.
27844 		 */
27845 		return (B_FALSE);
27846 	}
27847 
27848 	if (connp->conn_multi_router) {
27849 		/* multicast packet and multicast router socket: send up */
27850 		return (B_TRUE);
27851 	}
27852 
27853 	mutex_enter(&connp->conn_lock);
27854 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
27855 	mutex_exit(&connp->conn_lock);
27856 	return (found);
27857 }
27858 
27859 /*
27860  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
27861  */
27862 /* ARGSUSED */
27863 static void
27864 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
27865 {
27866 	ill_t *ill = (ill_t *)q->q_ptr;
27867 	mblk_t	*mp1, *mp2;
27868 	ipif_t  *ipif;
27869 	int err = 0;
27870 	conn_t *connp = NULL;
27871 	ipsq_t	*ipsq;
27872 	arc_t	*arc;
27873 
27874 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
27875 
27876 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
27877 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
27878 
27879 	ASSERT(IAM_WRITER_ILL(ill));
27880 	mp2 = mp->b_cont;
27881 	mp->b_cont = NULL;
27882 
27883 	/*
27884 	 * We have now received the arp bringup completion message
27885 	 * from ARP. Mark the arp bringup as done. Also if the arp
27886 	 * stream has already started closing, send up the AR_ARP_CLOSING
27887 	 * ack now since ARP is waiting in close for this ack.
27888 	 */
27889 	mutex_enter(&ill->ill_lock);
27890 	ill->ill_arp_bringup_pending = 0;
27891 	if (ill->ill_arp_closing) {
27892 		mutex_exit(&ill->ill_lock);
27893 		/* Let's reuse the mp for sending the ack */
27894 		arc = (arc_t *)mp->b_rptr;
27895 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
27896 		arc->arc_cmd = AR_ARP_CLOSING;
27897 		qreply(q, mp);
27898 	} else {
27899 		mutex_exit(&ill->ill_lock);
27900 		freeb(mp);
27901 	}
27902 
27903 	/* We should have an IOCTL waiting on this. */
27904 	ipsq = ill->ill_phyint->phyint_ipsq;
27905 	ipif = ipsq->ipsq_pending_ipif;
27906 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
27907 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
27908 	if (mp1 == NULL) {
27909 		/* bringup was aborted by the user */
27910 		freemsg(mp2);
27911 		return;
27912 	}
27913 	ASSERT(connp != NULL);
27914 	q = CONNP_TO_WQ(connp);
27915 	/*
27916 	 * If the DL_BIND_REQ fails, it is noted
27917 	 * in arc_name_offset.
27918 	 */
27919 	err = *((int *)mp2->b_rptr);
27920 	if (err == 0) {
27921 		if (ipif->ipif_isv6) {
27922 			if ((err = ipif_up_done_v6(ipif)) != 0)
27923 				ip0dbg(("ip_arp_done: init failed\n"));
27924 		} else {
27925 			if ((err = ipif_up_done(ipif)) != 0)
27926 				ip0dbg(("ip_arp_done: init failed\n"));
27927 		}
27928 	} else {
27929 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
27930 	}
27931 
27932 	freemsg(mp2);
27933 
27934 	if ((err == 0) && (ill->ill_up_ipifs)) {
27935 		err = ill_up_ipifs(ill, q, mp1);
27936 		if (err == EINPROGRESS)
27937 			return;
27938 	}
27939 
27940 	if (ill->ill_up_ipifs) {
27941 		ill_group_cleanup(ill);
27942 	}
27943 
27944 	/*
27945 	 * The ioctl must complete now without EINPROGRESS
27946 	 * since ipsq_pending_mp_get has removed the ioctl mblk
27947 	 * from ipsq_pending_mp. Otherwise the ioctl will be
27948 	 * stuck for ever in the ipsq.
27949 	 */
27950 	ASSERT(err != EINPROGRESS);
27951 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
27952 }
27953 
27954 /* Allocate the private structure */
27955 static int
27956 ip_priv_alloc(void **bufp)
27957 {
27958 	void	*buf;
27959 
27960 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
27961 		return (ENOMEM);
27962 
27963 	*bufp = buf;
27964 	return (0);
27965 }
27966 
27967 /* Function to delete the private structure */
27968 void
27969 ip_priv_free(void *buf)
27970 {
27971 	ASSERT(buf != NULL);
27972 	kmem_free(buf, sizeof (ip_priv_t));
27973 }
27974 
27975 /*
27976  * The entry point for IPPF processing.
27977  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
27978  * routine just returns.
27979  *
27980  * When called, ip_process generates an ipp_packet_t structure
27981  * which holds the state information for this packet and invokes the
27982  * the classifier (via ipp_packet_process). The classification, depending on
27983  * configured filters, results in a list of actions for this packet. Invoking
27984  * an action may cause the packet to be dropped, in which case the resulting
27985  * mblk (*mpp) is NULL. proc indicates the callout position for
27986  * this packet and ill_index is the interface this packet on or will leave
27987  * on (inbound and outbound resp.).
27988  */
27989 void
27990 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
27991 {
27992 	mblk_t		*mp;
27993 	ip_priv_t	*priv;
27994 	ipp_action_id_t	aid;
27995 	int		rc = 0;
27996 	ipp_packet_t	*pp;
27997 #define	IP_CLASS	"ip"
27998 
27999 	/* If the classifier is not loaded, return  */
28000 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28001 		return;
28002 	}
28003 
28004 	mp = *mpp;
28005 	ASSERT(mp != NULL);
28006 
28007 	/* Allocate the packet structure */
28008 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28009 	if (rc != 0) {
28010 		*mpp = NULL;
28011 		freemsg(mp);
28012 		return;
28013 	}
28014 
28015 	/* Allocate the private structure */
28016 	rc = ip_priv_alloc((void **)&priv);
28017 	if (rc != 0) {
28018 		*mpp = NULL;
28019 		freemsg(mp);
28020 		ipp_packet_free(pp);
28021 		return;
28022 	}
28023 	priv->proc = proc;
28024 	priv->ill_index = ill_index;
28025 	ipp_packet_set_private(pp, priv, ip_priv_free);
28026 	ipp_packet_set_data(pp, mp);
28027 
28028 	/* Invoke the classifier */
28029 	rc = ipp_packet_process(&pp);
28030 	if (pp != NULL) {
28031 		mp = ipp_packet_get_data(pp);
28032 		ipp_packet_free(pp);
28033 		if (rc != 0) {
28034 			freemsg(mp);
28035 			*mpp = NULL;
28036 		}
28037 	} else {
28038 		*mpp = NULL;
28039 	}
28040 #undef	IP_CLASS
28041 }
28042 
28043 /*
28044  * Propagate a multicast group membership operation (add/drop) on
28045  * all the interfaces crossed by the related multirt routes.
28046  * The call is considered successful if the operation succeeds
28047  * on at least one interface.
28048  */
28049 static int
28050 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28051     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28052     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28053     mblk_t *first_mp)
28054 {
28055 	ire_t		*ire_gw;
28056 	irb_t		*irb;
28057 	int		error = 0;
28058 	opt_restart_t	*or;
28059 
28060 	irb = ire->ire_bucket;
28061 	ASSERT(irb != NULL);
28062 
28063 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28064 
28065 	or = (opt_restart_t *)first_mp->b_rptr;
28066 	IRB_REFHOLD(irb);
28067 	for (; ire != NULL; ire = ire->ire_next) {
28068 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28069 			continue;
28070 		if (ire->ire_addr != group)
28071 			continue;
28072 
28073 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28074 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28075 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
28076 		/* No resolver exists for the gateway; skip this ire. */
28077 		if (ire_gw == NULL)
28078 			continue;
28079 
28080 		/*
28081 		 * This function can return EINPROGRESS. If so the operation
28082 		 * will be restarted from ip_restart_optmgmt which will
28083 		 * call ip_opt_set and option processing will restart for
28084 		 * this option. So we may end up calling 'fn' more than once.
28085 		 * This requires that 'fn' is idempotent except for the
28086 		 * return value. The operation is considered a success if
28087 		 * it succeeds at least once on any one interface.
28088 		 */
28089 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28090 		    NULL, fmode, src, first_mp);
28091 		if (error == 0)
28092 			or->or_private = CGTP_MCAST_SUCCESS;
28093 
28094 		if (ip_debug > 0) {
28095 			ulong_t	off;
28096 			char	*ksym;
28097 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28098 			ip2dbg(("ip_multirt_apply_membership: "
28099 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28100 			    "error %d [success %u]\n",
28101 			    ksym ? ksym : "?",
28102 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28103 			    error, or->or_private));
28104 		}
28105 
28106 		ire_refrele(ire_gw);
28107 		if (error == EINPROGRESS) {
28108 			IRB_REFRELE(irb);
28109 			return (error);
28110 		}
28111 	}
28112 	IRB_REFRELE(irb);
28113 	/*
28114 	 * Consider the call as successful if we succeeded on at least
28115 	 * one interface. Otherwise, return the last encountered error.
28116 	 */
28117 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28118 }
28119 
28120 
28121 /*
28122  * Issue a warning regarding a route crossing an interface with an
28123  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28124  * amount of time is logged.
28125  */
28126 static void
28127 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28128 {
28129 	hrtime_t	current = gethrtime();
28130 	char		buf[INET_ADDRSTRLEN];
28131 
28132 	/* Convert interval in ms to hrtime in ns */
28133 	if (multirt_bad_mtu_last_time +
28134 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
28135 	    current) {
28136 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28137 		    "to %s, incorrect MTU %u (expected %u)\n",
28138 		    ip_dot_addr(ire->ire_addr, buf),
28139 		    ire->ire_max_frag, max_frag);
28140 
28141 		multirt_bad_mtu_last_time = current;
28142 	}
28143 }
28144 
28145 
28146 /*
28147  * Get the CGTP (multirouting) filtering status.
28148  * If 0, the CGTP hooks are transparent.
28149  */
28150 /* ARGSUSED */
28151 static int
28152 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28153 {
28154 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28155 
28156 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28157 	return (0);
28158 }
28159 
28160 
28161 /*
28162  * Set the CGTP (multirouting) filtering status.
28163  * If the status is changed from active to transparent
28164  * or from transparent to active, forward the new status
28165  * to the filtering module (if loaded).
28166  */
28167 /* ARGSUSED */
28168 static int
28169 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28170     cred_t *ioc_cr)
28171 {
28172 	long		new_value;
28173 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28174 
28175 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28176 	    new_value < 0 || new_value > 1) {
28177 		return (EINVAL);
28178 	}
28179 
28180 	/*
28181 	 * Do not enable CGTP filtering - thus preventing the hooks
28182 	 * from being invoked - if the version number of the
28183 	 * filtering module hooks does not match.
28184 	 */
28185 	if ((ip_cgtp_filter_ops != NULL) &&
28186 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
28187 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
28188 		    "(module hooks version %d, expecting %d)\n",
28189 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
28190 		return (ENOTSUP);
28191 	}
28192 
28193 	if ((!*ip_cgtp_filter_value) && new_value) {
28194 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28195 		    ip_cgtp_filter_ops == NULL ?
28196 		    " (module not loaded)" : "");
28197 	}
28198 	if (*ip_cgtp_filter_value && (!new_value)) {
28199 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28200 		    ip_cgtp_filter_ops == NULL ?
28201 		    " (module not loaded)" : "");
28202 	}
28203 
28204 	if (ip_cgtp_filter_ops != NULL) {
28205 		int	res;
28206 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
28207 			return (res);
28208 		}
28209 	}
28210 
28211 	*ip_cgtp_filter_value = (boolean_t)new_value;
28212 
28213 	return (0);
28214 }
28215 
28216 
28217 /*
28218  * Return the expected CGTP hooks version number.
28219  */
28220 int
28221 ip_cgtp_filter_supported(void)
28222 {
28223 	return (ip_cgtp_filter_rev);
28224 }
28225 
28226 
28227 /*
28228  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
28229  * or by invoking this function. In the first case, the version number
28230  * of the registered structure is checked at hooks activation time
28231  * in ip_cgtp_filter_set().
28232  */
28233 int
28234 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
28235 {
28236 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28237 		return (ENOTSUP);
28238 
28239 	ip_cgtp_filter_ops = ops;
28240 	return (0);
28241 }
28242 
28243 static squeue_func_t
28244 ip_squeue_switch(int val)
28245 {
28246 	squeue_func_t rval = squeue_fill;
28247 
28248 	switch (val) {
28249 	case IP_SQUEUE_ENTER_NODRAIN:
28250 		rval = squeue_enter_nodrain;
28251 		break;
28252 	case IP_SQUEUE_ENTER:
28253 		rval = squeue_enter;
28254 		break;
28255 	default:
28256 		break;
28257 	}
28258 	return (rval);
28259 }
28260 
28261 /* ARGSUSED */
28262 static int
28263 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28264     caddr_t addr, cred_t *cr)
28265 {
28266 	int *v = (int *)addr;
28267 	long new_value;
28268 
28269 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28270 		return (EINVAL);
28271 
28272 	ip_input_proc = ip_squeue_switch(new_value);
28273 	*v = new_value;
28274 	return (0);
28275 }
28276 
28277 /* ARGSUSED */
28278 static int
28279 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28280     caddr_t addr, cred_t *cr)
28281 {
28282 	int *v = (int *)addr;
28283 	long new_value;
28284 
28285 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28286 		return (EINVAL);
28287 
28288 	*v = new_value;
28289 	return (0);
28290 }
28291 
28292 static void
28293 ip_kstat_init(void)
28294 {
28295 	ip_named_kstat_t template = {
28296 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
28297 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
28298 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
28299 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
28300 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
28301 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
28302 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
28303 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
28304 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
28305 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
28306 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
28307 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
28308 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
28309 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
28310 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
28311 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
28312 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
28313 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
28314 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
28315 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
28316 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
28317 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
28318 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
28319 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
28320 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
28321 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
28322 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
28323 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
28324 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
28325 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
28326 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
28327 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
28328 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
28329 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
28330 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
28331 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
28332 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
28333 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
28334 	};
28335 
28336 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
28337 					NUM_OF_FIELDS(ip_named_kstat_t),
28338 					0);
28339 	if (!ip_mibkp)
28340 		return;
28341 
28342 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
28343 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
28344 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
28345 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
28346 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
28347 
28348 	template.netToMediaEntrySize.value.i32 =
28349 		sizeof (mib2_ipNetToMediaEntry_t);
28350 
28351 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
28352 
28353 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
28354 
28355 	ip_mibkp->ks_update = ip_kstat_update;
28356 
28357 	kstat_install(ip_mibkp);
28358 }
28359 
28360 static void
28361 ip_kstat_fini(void)
28362 {
28363 
28364 	if (ip_mibkp != NULL) {
28365 		kstat_delete(ip_mibkp);
28366 		ip_mibkp = NULL;
28367 	}
28368 }
28369 
28370 static int
28371 ip_kstat_update(kstat_t *kp, int rw)
28372 {
28373 	ip_named_kstat_t *ipkp;
28374 
28375 	if (!kp || !kp->ks_data)
28376 		return (EIO);
28377 
28378 	if (rw == KSTAT_WRITE)
28379 		return (EACCES);
28380 
28381 	ipkp = (ip_named_kstat_t *)kp->ks_data;
28382 
28383 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
28384 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
28385 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
28386 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
28387 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
28388 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
28389 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
28390 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
28391 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
28392 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
28393 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
28394 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
28395 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
28396 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
28397 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
28398 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
28399 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
28400 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
28401 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
28402 
28403 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
28404 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
28405 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
28406 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
28407 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
28408 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
28409 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
28410 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
28411 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
28412 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
28413 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
28414 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
28415 
28416 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
28417 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
28418 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
28419 
28420 	return (0);
28421 }
28422 
28423 static void
28424 icmp_kstat_init(void)
28425 {
28426 	icmp_named_kstat_t template = {
28427 		{ "inMsgs",		KSTAT_DATA_UINT32 },
28428 		{ "inErrors",		KSTAT_DATA_UINT32 },
28429 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
28430 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
28431 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
28432 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
28433 		{ "inRedirects",	KSTAT_DATA_UINT32 },
28434 		{ "inEchos",		KSTAT_DATA_UINT32 },
28435 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
28436 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
28437 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
28438 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
28439 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
28440 		{ "outMsgs",		KSTAT_DATA_UINT32 },
28441 		{ "outErrors",		KSTAT_DATA_UINT32 },
28442 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
28443 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
28444 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
28445 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
28446 		{ "outRedirects",	KSTAT_DATA_UINT32 },
28447 		{ "outEchos",		KSTAT_DATA_UINT32 },
28448 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
28449 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
28450 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
28451 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
28452 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
28453 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
28454 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
28455 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
28456 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
28457 		{ "outDrops",		KSTAT_DATA_UINT32 },
28458 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
28459 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
28460 	};
28461 
28462 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
28463 					NUM_OF_FIELDS(icmp_named_kstat_t),
28464 					0);
28465 	if (icmp_mibkp == NULL)
28466 		return;
28467 
28468 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
28469 
28470 	icmp_mibkp->ks_update = icmp_kstat_update;
28471 
28472 	kstat_install(icmp_mibkp);
28473 }
28474 
28475 static void
28476 icmp_kstat_fini(void)
28477 {
28478 
28479 	if (icmp_mibkp != NULL) {
28480 		kstat_delete(icmp_mibkp);
28481 		icmp_mibkp = NULL;
28482 	}
28483 }
28484 
28485 static int
28486 icmp_kstat_update(kstat_t *kp, int rw)
28487 {
28488 	icmp_named_kstat_t *icmpkp;
28489 
28490 	if ((kp == NULL) || (kp->ks_data == NULL))
28491 		return (EIO);
28492 
28493 	if (rw == KSTAT_WRITE)
28494 		return (EACCES);
28495 
28496 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
28497 
28498 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
28499 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
28500 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
28501 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
28502 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
28503 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
28504 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
28505 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
28506 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
28507 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
28508 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
28509 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
28510 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
28511 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
28512 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
28513 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
28514 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
28515 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
28516 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
28517 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
28518 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
28519 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
28520 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
28521 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
28522 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
28523 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
28524 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
28525 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
28526 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
28527 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
28528 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
28529 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
28530 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
28531 
28532 	return (0);
28533 }
28534 
28535 /*
28536  * This is the fanout function for raw socket opened for SCTP.  Note
28537  * that it is called after SCTP checks that there is no socket which
28538  * wants a packet.  Then before SCTP handles this out of the blue packet,
28539  * this function is called to see if there is any raw socket for SCTP.
28540  * If there is and it is bound to the correct address, the packet will
28541  * be sent to that socket.  Note that only one raw socket can be bound to
28542  * a port.  This is assured in ipcl_sctp_hash_insert();
28543  */
28544 void
28545 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
28546     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
28547     uint_t ipif_seqid, zoneid_t zoneid)
28548 {
28549 	conn_t		*connp;
28550 	queue_t		*rq;
28551 	mblk_t		*first_mp;
28552 	boolean_t	secure;
28553 	ip6_t		*ip6h;
28554 
28555 	first_mp = mp;
28556 	if (mctl_present) {
28557 		mp = first_mp->b_cont;
28558 		secure = ipsec_in_is_secure(first_mp);
28559 		ASSERT(mp != NULL);
28560 	} else {
28561 		secure = B_FALSE;
28562 	}
28563 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
28564 
28565 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
28566 	if (connp == NULL) {
28567 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
28568 		    mctl_present);
28569 		return;
28570 	}
28571 	rq = connp->conn_rq;
28572 	if (!canputnext(rq)) {
28573 		CONN_DEC_REF(connp);
28574 		BUMP_MIB(&ip_mib, rawipInOverflows);
28575 		freemsg(first_mp);
28576 		return;
28577 	}
28578 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
28579 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
28580 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
28581 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
28582 		if (first_mp == NULL) {
28583 			CONN_DEC_REF(connp);
28584 			return;
28585 		}
28586 	}
28587 	/*
28588 	 * We probably should not send M_CTL message up to
28589 	 * raw socket.
28590 	 */
28591 	if (mctl_present)
28592 		freeb(first_mp);
28593 
28594 	/* Initiate IPPF processing here if needed. */
28595 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
28596 	    (!isv4 && IP6_IN_IPP(flags))) {
28597 		ip_process(IPP_LOCAL_IN, &mp,
28598 		    recv_ill->ill_phyint->phyint_ifindex);
28599 		if (mp == NULL) {
28600 			CONN_DEC_REF(connp);
28601 			return;
28602 		}
28603 	}
28604 
28605 	if (connp->conn_recvif || connp->conn_recvslla ||
28606 	    ((connp->conn_ipv6_recvpktinfo ||
28607 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
28608 	    (flags & IP_FF_IP6INFO))) {
28609 		int in_flags = 0;
28610 
28611 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
28612 			in_flags = IPF_RECVIF;
28613 		}
28614 		if (connp->conn_recvslla) {
28615 			in_flags |= IPF_RECVSLLA;
28616 		}
28617 		if (isv4) {
28618 			mp = ip_add_info(mp, recv_ill, in_flags);
28619 		} else {
28620 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
28621 			if (mp == NULL) {
28622 				CONN_DEC_REF(connp);
28623 				return;
28624 			}
28625 		}
28626 	}
28627 
28628 	BUMP_MIB(&ip_mib, ipInDelivers);
28629 	/*
28630 	 * We are sending the IPSEC_IN message also up. Refer
28631 	 * to comments above this function.
28632 	 */
28633 	putnext(rq, mp);
28634 	CONN_DEC_REF(connp);
28635 }
28636 
28637 /*
28638  * This function should be called only if all packet processing
28639  * including fragmentation is complete. Callers of this function
28640  * must set mp->b_prev to one of these values:
28641  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
28642  * prior to handing over the mp as first argument to this function.
28643  *
28644  * If the ire passed by caller is incomplete, this function
28645  * queues the packet and if necessary, sends ARP request and bails.
28646  * If the ire passed is fully resolved, we simply prepend
28647  * the link-layer header to the packet, do ipsec hw acceleration
28648  * work if necessary, and send the packet out on the wire.
28649  *
28650  * NOTE: IPSEC will only call this function with fully resolved
28651  * ires if hw acceleration is involved.
28652  * TODO list :
28653  * 	a Handle M_MULTIDATA so that
28654  *	  tcp_multisend->tcp_multisend_data can
28655  *	  call ip_xmit_v4 directly
28656  *	b Handle post-ARP work for fragments so that
28657  *	  ip_wput_frag can call this function.
28658  */
28659 ipxmit_state_t
28660 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
28661 {
28662 	nce_t		*arpce;
28663 	queue_t		*q;
28664 	int		ill_index;
28665 	mblk_t		*nxt_mp, *first_mp;
28666 	boolean_t	xmit_drop = B_FALSE;
28667 	ip_proc_t	proc;
28668 	ill_t		*out_ill;
28669 
28670 	arpce = ire->ire_nce;
28671 	ASSERT(arpce != NULL);
28672 
28673 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
28674 
28675 	mutex_enter(&arpce->nce_lock);
28676 	switch (arpce->nce_state) {
28677 	case ND_REACHABLE:
28678 		/* If there are other queued packets, queue this packet */
28679 		if (arpce->nce_qd_mp != NULL) {
28680 			if (mp != NULL)
28681 				nce_queue_mp_common(arpce, mp, B_FALSE);
28682 			mp = arpce->nce_qd_mp;
28683 		}
28684 		arpce->nce_qd_mp = NULL;
28685 		mutex_exit(&arpce->nce_lock);
28686 
28687 		/*
28688 		 * Flush the queue.  In the common case, where the
28689 		 * ARP is already resolved,  it will go through the
28690 		 * while loop only once.
28691 		 */
28692 		while (mp != NULL) {
28693 
28694 			nxt_mp = mp->b_next;
28695 			mp->b_next = NULL;
28696 			/*
28697 			 * This info is needed for IPQOS to do COS marking
28698 			 * in ip_wput_attach_llhdr->ip_process.
28699 			 */
28700 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
28701 			mp->b_prev = NULL;
28702 
28703 			/* set up ill index for outbound qos processing */
28704 			out_ill = ire->ire_ipif->ipif_ill;
28705 			ill_index = out_ill->ill_phyint->phyint_ifindex;
28706 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
28707 			    ill_index);
28708 			if (first_mp == NULL) {
28709 				xmit_drop = B_TRUE;
28710 				if (proc == IPP_FWD_OUT) {
28711 					BUMP_MIB(&ip_mib, ipInDiscards);
28712 				} else {
28713 					BUMP_MIB(&ip_mib, ipOutDiscards);
28714 				}
28715 				goto next_mp;
28716 			}
28717 			/* non-ipsec hw accel case */
28718 			if (io == NULL || !io->ipsec_out_accelerated) {
28719 				/* send it */
28720 				q = ire->ire_stq;
28721 				if (proc == IPP_FWD_OUT) {
28722 					UPDATE_IB_PKT_COUNT(ire);
28723 				} else {
28724 					UPDATE_OB_PKT_COUNT(ire);
28725 				}
28726 				ire->ire_last_used_time = lbolt;
28727 
28728 				if (flow_ctl_enabled || canputnext(q))  {
28729 					if (proc == IPP_FWD_OUT) {
28730 						BUMP_MIB(&ip_mib,
28731 						    ipForwDatagrams);
28732 					}
28733 
28734 					if (mp == NULL)
28735 						goto next_mp;
28736 					putnext(q, first_mp);
28737 				} else {
28738 					BUMP_MIB(&ip_mib,
28739 					    ipOutDiscards);
28740 					xmit_drop = B_TRUE;
28741 					freemsg(first_mp);
28742 				}
28743 			} else {
28744 				/*
28745 				 * Safety Pup says: make sure this
28746 				 *  is going to the right interface!
28747 				 */
28748 				ill_t *ill1 =
28749 				    (ill_t *)ire->ire_stq->q_ptr;
28750 				int ifindex =
28751 				    ill1->ill_phyint->phyint_ifindex;
28752 				if (ifindex !=
28753 				    io->ipsec_out_capab_ill_index) {
28754 					xmit_drop = B_TRUE;
28755 					freemsg(mp);
28756 				} else {
28757 					ipsec_hw_putnext(ire->ire_stq,
28758 					    mp);
28759 				}
28760 			}
28761 next_mp:
28762 			mp = nxt_mp;
28763 		} /* while (mp != NULL) */
28764 		if (xmit_drop)
28765 			return (SEND_FAILED);
28766 		else
28767 			return (SEND_PASSED);
28768 
28769 	case ND_INITIAL:
28770 	case ND_INCOMPLETE:
28771 
28772 		/*
28773 		 * While we do send off packets to dests that
28774 		 * use fully-resolved CGTP routes, we do not
28775 		 * handle unresolved CGTP routes.
28776 		 */
28777 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
28778 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
28779 
28780 		if (mp != NULL) {
28781 			/* queue the packet */
28782 			nce_queue_mp_common(arpce, mp, B_FALSE);
28783 		}
28784 
28785 		if (arpce->nce_state == ND_INCOMPLETE) {
28786 			mutex_exit(&arpce->nce_lock);
28787 			DTRACE_PROBE3(ip__xmit__incomplete,
28788 			    (ire_t *), ire, (mblk_t *), mp,
28789 			    (ipsec_out_t *), io);
28790 			return (LOOKUP_IN_PROGRESS);
28791 		}
28792 
28793 		arpce->nce_state = ND_INCOMPLETE;
28794 		mutex_exit(&arpce->nce_lock);
28795 		/*
28796 		 * Note that ire_add() (called from ire_forward())
28797 		 * holds a ref on the ire until ARP is completed.
28798 		 */
28799 
28800 		ire_arpresolve(ire, ire_to_ill(ire));
28801 		return (LOOKUP_IN_PROGRESS);
28802 	default:
28803 		ASSERT(0);
28804 		mutex_exit(&arpce->nce_lock);
28805 		return (LLHDR_RESLV_FAILED);
28806 	}
28807 }
28808 
28809 /*
28810  * Return B_TRUE if the buffers differ in length or content.
28811  * This is used for comparing extension header buffers.
28812  * Note that an extension header would be declared different
28813  * even if all that changed was the next header value in that header i.e.
28814  * what really changed is the next extension header.
28815  */
28816 boolean_t
28817 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
28818     uint_t blen)
28819 {
28820 	if (!b_valid)
28821 		blen = 0;
28822 
28823 	if (alen != blen)
28824 		return (B_TRUE);
28825 	if (alen == 0)
28826 		return (B_FALSE);	/* Both zero length */
28827 	return (bcmp(abuf, bbuf, alen));
28828 }
28829 
28830 /*
28831  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
28832  * Return B_FALSE if memory allocation fails - don't change any state!
28833  */
28834 boolean_t
28835 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28836     const void *src, uint_t srclen)
28837 {
28838 	void *dst;
28839 
28840 	if (!src_valid)
28841 		srclen = 0;
28842 
28843 	ASSERT(*dstlenp == 0);
28844 	if (src != NULL && srclen != 0) {
28845 		dst = mi_alloc(srclen, BPRI_MED);
28846 		if (dst == NULL)
28847 			return (B_FALSE);
28848 	} else {
28849 		dst = NULL;
28850 	}
28851 	if (*dstp != NULL)
28852 		mi_free(*dstp);
28853 	*dstp = dst;
28854 	*dstlenp = dst == NULL ? 0 : srclen;
28855 	return (B_TRUE);
28856 }
28857 
28858 /*
28859  * Replace what is in *dst, *dstlen with the source.
28860  * Assumes ip_allocbuf has already been called.
28861  */
28862 void
28863 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28864     const void *src, uint_t srclen)
28865 {
28866 	if (!src_valid)
28867 		srclen = 0;
28868 
28869 	ASSERT(*dstlenp == srclen);
28870 	if (src != NULL && srclen != 0)
28871 		bcopy(src, *dstp, srclen);
28872 }
28873 
28874 /*
28875  * Free the storage pointed to by the members of an ip6_pkt_t.
28876  */
28877 void
28878 ip6_pkt_free(ip6_pkt_t *ipp)
28879 {
28880 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
28881 
28882 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
28883 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
28884 		ipp->ipp_hopopts = NULL;
28885 		ipp->ipp_hopoptslen = 0;
28886 	}
28887 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
28888 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
28889 		ipp->ipp_rtdstopts = NULL;
28890 		ipp->ipp_rtdstoptslen = 0;
28891 	}
28892 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
28893 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
28894 		ipp->ipp_dstopts = NULL;
28895 		ipp->ipp_dstoptslen = 0;
28896 	}
28897 	if (ipp->ipp_fields & IPPF_RTHDR) {
28898 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
28899 		ipp->ipp_rthdr = NULL;
28900 		ipp->ipp_rthdrlen = 0;
28901 	}
28902 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
28903 	    IPPF_RTHDR);
28904 }
28905