xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision 4496171313bed39e96f21bc2f9faf2868e267ae3)
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 	{  0,	1,	1,	"ip_lso_outbound" },
987 #ifdef DEBUG
988 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
989 #endif
990 };
991 
992 ipparam_t	*ip_param_arr = lcl_param_arr;
993 
994 /* Extended NDP table */
995 static ipndp_t	lcl_ndp_arr[] = {
996 	/* getf			setf		data			name */
997 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
998 	    "ip_forwarding" },
999 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
1000 	    "ip6_forwarding" },
1001 	{  ip_ill_report,	NULL,		NULL,
1002 	    "ip_ill_status" },
1003 	{  ip_ipif_report,	NULL,		NULL,
1004 	    "ip_ipif_status" },
1005 	{  ip_ire_report,	NULL,		NULL,
1006 	    "ipv4_ire_status" },
1007 	{  ip_ire_report_mrtun,	NULL,		NULL,
1008 	    "ipv4_mrtun_ire_status" },
1009 	{  ip_ire_report_srcif,	NULL,		NULL,
1010 	    "ipv4_srcif_ire_status" },
1011 	{  ip_ire_report_v6,	NULL,		NULL,
1012 	    "ipv6_ire_status" },
1013 	{  ip_conn_report,	NULL,		NULL,
1014 	    "ip_conn_status" },
1015 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1016 	    "ip_rput_pullups" },
1017 	{  ndp_report,		NULL,		NULL,
1018 	    "ip_ndp_cache_report" },
1019 	{  ip_srcid_report,	NULL,		NULL,
1020 	    "ip_srcid_status" },
1021 	{ ip_param_generic_get, ip_squeue_profile_set,
1022 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
1023 	{ ip_param_generic_get, ip_squeue_bind_set,
1024 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
1025 	{ ip_param_generic_get, ip_input_proc_set,
1026 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1027 	{ ip_param_generic_get, ip_int_set,
1028 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1029 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
1030 	    "ip_cgtp_filter" },
1031 	{ ip_param_generic_get, ip_int_set,
1032 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
1033 };
1034 
1035 /*
1036  * ip_g_forward controls IP forwarding.  It takes two values:
1037  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
1038  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
1039  *
1040  * RFC1122 says there must be a configuration switch to control forwarding,
1041  * but that the default MUST be to not forward packets ever.  Implicit
1042  * control based on configuration of multiple interfaces MUST NOT be
1043  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
1044  * and, in fact, it was the default.  That capability is now provided in the
1045  * /etc/rc2.d/S69inet script.
1046  */
1047 int ip_g_forward = IP_FORWARD_DEFAULT;
1048 
1049 /* It also has an IPv6 counterpart. */
1050 
1051 int ipv6_forward = IP_FORWARD_DEFAULT;
1052 
1053 /*
1054  * Table of IP ioctls encoding the various properties of the ioctl and
1055  * indexed based on the last byte of the ioctl command. Occasionally there
1056  * is a clash, and there is more than 1 ioctl with the same last byte.
1057  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1058  * ioctls are encoded in the misc table. An entry in the ndx table is
1059  * retrieved by indexing on the last byte of the ioctl command and comparing
1060  * the ioctl command with the value in the ndx table. In the event of a
1061  * mismatch the misc table is then searched sequentially for the desired
1062  * ioctl command.
1063  *
1064  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1065  */
1066 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1067 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 
1078 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1079 			MISC_CMD, ip_siocaddrt, NULL },
1080 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1081 			MISC_CMD, ip_siocdelrt, NULL },
1082 
1083 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1084 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1085 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1086 			IF_CMD, ip_sioctl_get_addr, NULL },
1087 
1088 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1089 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1090 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1091 			IPI_GET_CMD | IPI_REPL,
1092 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1093 
1094 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1095 			IPI_PRIV | IPI_WR | IPI_REPL,
1096 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1097 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1098 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1099 			IF_CMD, ip_sioctl_get_flags, NULL },
1100 
1101 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 
1104 	/* copyin size cannot be coded for SIOCGIFCONF */
1105 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1106 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1107 
1108 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1109 			IF_CMD, ip_sioctl_mtu, NULL },
1110 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1111 			IF_CMD, ip_sioctl_get_mtu, NULL },
1112 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1113 			IPI_GET_CMD | IPI_REPL,
1114 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1115 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1116 			IF_CMD, ip_sioctl_brdaddr, NULL },
1117 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1118 			IPI_GET_CMD | IPI_REPL,
1119 			IF_CMD, ip_sioctl_get_netmask, NULL },
1120 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1121 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1122 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1123 			IPI_GET_CMD | IPI_REPL,
1124 			IF_CMD, ip_sioctl_get_metric, NULL },
1125 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1126 			IF_CMD, ip_sioctl_metric, NULL },
1127 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 
1129 	/* See 166-168 below for extended SIOC*XARP ioctls */
1130 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1131 			MISC_CMD, ip_sioctl_arp, NULL },
1132 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1133 			MISC_CMD, ip_sioctl_arp, NULL },
1134 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1135 			MISC_CMD, ip_sioctl_arp, NULL },
1136 
1137 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1158 
1159 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1160 			MISC_CMD, if_unitsel, if_unitsel_restart },
1161 
1162 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 
1181 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1182 			IPI_PRIV | IPI_WR | IPI_MODOK,
1183 			IF_CMD, ip_sioctl_sifname, NULL },
1184 
1185 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1190 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 
1199 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1200 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1201 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1202 			IF_CMD, ip_sioctl_get_muxid, NULL },
1203 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1204 			IPI_PRIV | IPI_WR | IPI_REPL,
1205 			IF_CMD, ip_sioctl_muxid, NULL },
1206 
1207 	/* Both if and lif variants share same func */
1208 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1209 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1210 	/* Both if and lif variants share same func */
1211 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1212 			IPI_PRIV | IPI_WR | IPI_REPL,
1213 			IF_CMD, ip_sioctl_slifindex, NULL },
1214 
1215 	/* copyin size cannot be coded for SIOCGIFCONF */
1216 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1217 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1218 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1219 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1220 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1221 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1222 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1223 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1226 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1227 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1228 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1229 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1230 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1231 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1232 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1233 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1234 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1235 
1236 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1237 			IPI_PRIV | IPI_WR | IPI_REPL,
1238 			LIF_CMD, ip_sioctl_removeif,
1239 			ip_sioctl_removeif_restart },
1240 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1241 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1242 			LIF_CMD, ip_sioctl_addif, NULL },
1243 #define	SIOCLIFADDR_NDX 112
1244 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1245 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1246 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1247 			IPI_GET_CMD | IPI_REPL,
1248 			LIF_CMD, ip_sioctl_get_addr, NULL },
1249 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1250 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1251 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1252 			IPI_GET_CMD | IPI_REPL,
1253 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1254 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1255 			IPI_PRIV | IPI_WR | IPI_REPL,
1256 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1257 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1258 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1259 			LIF_CMD, ip_sioctl_get_flags, NULL },
1260 
1261 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1262 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1263 
1264 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1265 			ip_sioctl_get_lifconf, NULL },
1266 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1267 			LIF_CMD, ip_sioctl_mtu, NULL },
1268 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1269 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1270 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1271 			IPI_GET_CMD | IPI_REPL,
1272 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1273 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1274 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1275 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1276 			IPI_GET_CMD | IPI_REPL,
1277 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1278 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1279 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1280 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1281 			IPI_GET_CMD | IPI_REPL,
1282 			LIF_CMD, ip_sioctl_get_metric, NULL },
1283 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1284 			LIF_CMD, ip_sioctl_metric, NULL },
1285 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1286 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1287 			LIF_CMD, ip_sioctl_slifname,
1288 			ip_sioctl_slifname_restart },
1289 
1290 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1291 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1292 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1293 			IPI_GET_CMD | IPI_REPL,
1294 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1295 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1296 			IPI_PRIV | IPI_WR | IPI_REPL,
1297 			LIF_CMD, ip_sioctl_muxid, NULL },
1298 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1299 			IPI_GET_CMD | IPI_REPL,
1300 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1301 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1302 			IPI_PRIV | IPI_WR | IPI_REPL,
1303 			LIF_CMD, ip_sioctl_slifindex, 0 },
1304 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1305 			LIF_CMD, ip_sioctl_token, NULL },
1306 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1307 			IPI_GET_CMD | IPI_REPL,
1308 			LIF_CMD, ip_sioctl_get_token, NULL },
1309 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1310 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1311 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1312 			IPI_GET_CMD | IPI_REPL,
1313 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1314 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1315 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1316 
1317 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1318 			IPI_GET_CMD | IPI_REPL,
1319 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1320 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1321 			LIF_CMD, ip_siocdelndp_v6, NULL },
1322 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1323 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1324 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1325 			LIF_CMD, ip_siocsetndp_v6, NULL },
1326 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1327 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1328 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1329 			MISC_CMD, ip_sioctl_tonlink, NULL },
1330 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1331 			MISC_CMD, ip_sioctl_tmysite, NULL },
1332 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1333 			TUN_CMD, ip_sioctl_tunparam, NULL },
1334 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1335 			IPI_PRIV | IPI_WR,
1336 			TUN_CMD, ip_sioctl_tunparam, NULL },
1337 
1338 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1339 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1340 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1341 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1342 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1343 
1344 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1345 			IPI_PRIV | IPI_WR | IPI_REPL,
1346 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1347 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1348 			IPI_PRIV | IPI_WR | IPI_REPL,
1349 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1350 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1351 			IPI_PRIV | IPI_WR,
1352 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1353 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1354 			IPI_GET_CMD | IPI_REPL,
1355 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1356 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1357 			IPI_GET_CMD | IPI_REPL,
1358 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1359 
1360 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1361 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1362 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1363 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1364 
1365 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1366 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1367 
1368 	/* These are handled in ip_sioctl_copyin_setup itself */
1369 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1370 			MISC_CMD, NULL, NULL },
1371 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1372 			MISC_CMD, NULL, NULL },
1373 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1374 
1375 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1376 			ip_sioctl_get_lifconf, NULL },
1377 
1378 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1379 			MISC_CMD, ip_sioctl_xarp, NULL },
1380 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1381 			MISC_CMD, ip_sioctl_xarp, NULL },
1382 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1383 			MISC_CMD, ip_sioctl_xarp, NULL },
1384 
1385 	/* SIOCPOPSOCKFS is not handled by IP */
1386 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1387 
1388 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1389 			IPI_GET_CMD | IPI_REPL,
1390 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1391 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1392 			IPI_PRIV | IPI_WR | IPI_REPL,
1393 			LIF_CMD, ip_sioctl_slifzone,
1394 			ip_sioctl_slifzone_restart },
1395 	/* 172-174 are SCTP ioctls and not handled by IP */
1396 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1397 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1398 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1399 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1400 			IPI_GET_CMD, LIF_CMD,
1401 			ip_sioctl_get_lifusesrc, 0 },
1402 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1403 			IPI_PRIV | IPI_WR,
1404 			LIF_CMD, ip_sioctl_slifusesrc,
1405 			NULL },
1406 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1407 			ip_sioctl_get_lifsrcof, NULL },
1408 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1409 			MISC_CMD, ip_sioctl_msfilter, NULL },
1410 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1411 			MISC_CMD, ip_sioctl_msfilter, NULL },
1412 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1413 			MISC_CMD, ip_sioctl_msfilter, NULL },
1414 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1415 			MISC_CMD, ip_sioctl_msfilter, NULL },
1416 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1417 			ip_sioctl_set_ipmpfailback, NULL }
1418 };
1419 
1420 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1421 
1422 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1423 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1424 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1425 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1426 		TUN_CMD, ip_sioctl_tunparam, NULL },
1427 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1428 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1429 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1430 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1431 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1432 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1433 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1434 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1435 		MISC_CMD, mrt_ioctl},
1436 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1437 		MISC_CMD, mrt_ioctl},
1438 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1439 		MISC_CMD, mrt_ioctl}
1440 };
1441 
1442 int ip_misc_ioctl_count =
1443     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1444 
1445 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1446 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1447 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1448 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1449 					/* Settable in /etc/system */
1450 uint_t	ip_redirect_cnt;		/* Num of redirect routes in ftable */
1451 
1452 /* Defined in ip_ire.c */
1453 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1454 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1455 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1456 
1457 static nv_t	ire_nv_arr[] = {
1458 	{ IRE_BROADCAST, "BROADCAST" },
1459 	{ IRE_LOCAL, "LOCAL" },
1460 	{ IRE_LOOPBACK, "LOOPBACK" },
1461 	{ IRE_CACHE, "CACHE" },
1462 	{ IRE_DEFAULT, "DEFAULT" },
1463 	{ IRE_PREFIX, "PREFIX" },
1464 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1465 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1466 	{ IRE_HOST, "HOST" },
1467 	{ 0 }
1468 };
1469 
1470 nv_t	*ire_nv_tbl = ire_nv_arr;
1471 
1472 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1473 extern krwlock_t ipsec_capab_ills_lock;
1474 
1475 /* Defined in ip_netinfo.c */
1476 extern ddi_taskq_t	*eventq_queue_nic;
1477 
1478 /* Packet dropper for IP IPsec processing failures */
1479 ipdropper_t ip_dropper;
1480 
1481 /* Simple ICMP IP Header Template */
1482 static ipha_t icmp_ipha = {
1483 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1484 };
1485 
1486 struct module_info ip_mod_info = {
1487 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1488 };
1489 
1490 /*
1491  * Duplicate static symbols within a module confuses mdb; so we avoid the
1492  * problem by making the symbols here distinct from those in udp.c.
1493  */
1494 
1495 static struct qinit iprinit = {
1496 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1497 	&ip_mod_info
1498 };
1499 
1500 static struct qinit ipwinit = {
1501 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1502 	&ip_mod_info
1503 };
1504 
1505 static struct qinit iplrinit = {
1506 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1507 	&ip_mod_info
1508 };
1509 
1510 static struct qinit iplwinit = {
1511 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1512 	&ip_mod_info
1513 };
1514 
1515 struct streamtab ipinfo = {
1516 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1517 };
1518 
1519 #ifdef	DEBUG
1520 static boolean_t skip_sctp_cksum = B_FALSE;
1521 #endif
1522 
1523 /*
1524  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1525  * ip_rput_v6(), ip_output(), etc.  If the message
1526  * block already has a M_CTL at the front of it, then simply set the zoneid
1527  * appropriately.
1528  */
1529 mblk_t *
1530 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid)
1531 {
1532 	mblk_t		*first_mp;
1533 	ipsec_out_t	*io;
1534 
1535 	ASSERT(zoneid != ALL_ZONES);
1536 	if (mp->b_datap->db_type == M_CTL) {
1537 		io = (ipsec_out_t *)mp->b_rptr;
1538 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1539 		io->ipsec_out_zoneid = zoneid;
1540 		return (mp);
1541 	}
1542 
1543 	first_mp = ipsec_alloc_ipsec_out();
1544 	if (first_mp == NULL)
1545 		return (NULL);
1546 	io = (ipsec_out_t *)first_mp->b_rptr;
1547 	/* This is not a secure packet */
1548 	io->ipsec_out_secure = B_FALSE;
1549 	io->ipsec_out_zoneid = zoneid;
1550 	first_mp->b_cont = mp;
1551 	return (first_mp);
1552 }
1553 
1554 /*
1555  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1556  */
1557 mblk_t *
1558 ip_copymsg(mblk_t *mp)
1559 {
1560 	mblk_t *nmp;
1561 	ipsec_info_t *in;
1562 
1563 	if (mp->b_datap->db_type != M_CTL)
1564 		return (copymsg(mp));
1565 
1566 	in = (ipsec_info_t *)mp->b_rptr;
1567 
1568 	/*
1569 	 * Note that M_CTL is also used for delivering ICMP error messages
1570 	 * upstream to transport layers.
1571 	 */
1572 	if (in->ipsec_info_type != IPSEC_OUT &&
1573 	    in->ipsec_info_type != IPSEC_IN)
1574 		return (copymsg(mp));
1575 
1576 	nmp = copymsg(mp->b_cont);
1577 
1578 	if (in->ipsec_info_type == IPSEC_OUT)
1579 		return (ipsec_out_tag(mp, nmp));
1580 	else
1581 		return (ipsec_in_tag(mp, nmp));
1582 }
1583 
1584 /* Generate an ICMP fragmentation needed message. */
1585 static void
1586 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid)
1587 {
1588 	icmph_t	icmph;
1589 	mblk_t *first_mp;
1590 	boolean_t mctl_present;
1591 
1592 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1593 
1594 	if (!(mp = icmp_pkt_err_ok(mp))) {
1595 		if (mctl_present)
1596 			freeb(first_mp);
1597 		return;
1598 	}
1599 
1600 	bzero(&icmph, sizeof (icmph_t));
1601 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1602 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1603 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1604 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1605 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1606 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
1607 }
1608 
1609 /*
1610  * icmp_inbound deals with ICMP messages in the following ways.
1611  *
1612  * 1) It needs to send a reply back and possibly delivering it
1613  *    to the "interested" upper clients.
1614  * 2) It needs to send it to the upper clients only.
1615  * 3) It needs to change some values in IP only.
1616  * 4) It needs to change some values in IP and upper layers e.g TCP.
1617  *
1618  * We need to accomodate icmp messages coming in clear until we get
1619  * everything secure from the wire. If icmp_accept_clear_messages
1620  * is zero we check with the global policy and act accordingly. If
1621  * it is non-zero, we accept the message without any checks. But
1622  * *this does not mean* that this will be delivered to the upper
1623  * clients. By accepting we might send replies back, change our MTU
1624  * value etc. but delivery to the ULP/clients depends on their policy
1625  * dispositions.
1626  *
1627  * We handle the above 4 cases in the context of IPSEC in the
1628  * following way :
1629  *
1630  * 1) Send the reply back in the same way as the request came in.
1631  *    If it came in encrypted, it goes out encrypted. If it came in
1632  *    clear, it goes out in clear. Thus, this will prevent chosen
1633  *    plain text attack.
1634  * 2) The client may or may not expect things to come in secure.
1635  *    If it comes in secure, the policy constraints are checked
1636  *    before delivering it to the upper layers. If it comes in
1637  *    clear, ipsec_inbound_accept_clear will decide whether to
1638  *    accept this in clear or not. In both the cases, if the returned
1639  *    message (IP header + 8 bytes) that caused the icmp message has
1640  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1641  *    sending up. If there are only 8 bytes of returned message, then
1642  *    upper client will not be notified.
1643  * 3) Check with global policy to see whether it matches the constaints.
1644  *    But this will be done only if icmp_accept_messages_in_clear is
1645  *    zero.
1646  * 4) If we need to change both in IP and ULP, then the decision taken
1647  *    while affecting the values in IP and while delivering up to TCP
1648  *    should be the same.
1649  *
1650  * 	There are two cases.
1651  *
1652  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1653  *	   failed), we will not deliver it to the ULP, even though they
1654  *	   are *willing* to accept in *clear*. This is fine as our global
1655  *	   disposition to icmp messages asks us reject the datagram.
1656  *
1657  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1658  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1659  *	   to deliver it to ULP (policy failed), it can lead to
1660  *	   consistency problems. The cases known at this time are
1661  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1662  *	   values :
1663  *
1664  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1665  *	     and Upper layer rejects. Then the communication will
1666  *	     come to a stop. This is solved by making similar decisions
1667  *	     at both levels. Currently, when we are unable to deliver
1668  *	     to the Upper Layer (due to policy failures) while IP has
1669  *	     adjusted ire_max_frag, the next outbound datagram would
1670  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1671  *	     will be with the right level of protection. Thus the right
1672  *	     value will be communicated even if we are not able to
1673  *	     communicate when we get from the wire initially. But this
1674  *	     assumes there would be at least one outbound datagram after
1675  *	     IP has adjusted its ire_max_frag value. To make things
1676  *	     simpler, we accept in clear after the validation of
1677  *	     AH/ESP headers.
1678  *
1679  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1680  *	     upper layer depending on the level of protection the upper
1681  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1682  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1683  *	     should be accepted in clear when the Upper layer expects secure.
1684  *	     Thus the communication may get aborted by some bad ICMP
1685  *	     packets.
1686  *
1687  * IPQoS Notes:
1688  * The only instance when a packet is sent for processing is when there
1689  * isn't an ICMP client and if we are interested in it.
1690  * If there is a client, IPPF processing will take place in the
1691  * ip_fanout_proto routine.
1692  *
1693  * Zones notes:
1694  * The packet is only processed in the context of the specified zone: typically
1695  * only this zone will reply to an echo request, and only interested clients in
1696  * this zone will receive a copy of the packet. This means that the caller must
1697  * call icmp_inbound() for each relevant zone.
1698  */
1699 static void
1700 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1701     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1702     ill_t *recv_ill, zoneid_t zoneid)
1703 {
1704 	icmph_t	*icmph;
1705 	ipha_t	*ipha;
1706 	int	iph_hdr_length;
1707 	int	hdr_length;
1708 	boolean_t	interested;
1709 	uint32_t	ts;
1710 	uchar_t	*wptr;
1711 	ipif_t	*ipif;
1712 	mblk_t *first_mp;
1713 	ipsec_in_t *ii;
1714 	ire_t *src_ire;
1715 	boolean_t onlink;
1716 	timestruc_t now;
1717 	uint32_t ill_index;
1718 
1719 	ASSERT(ill != NULL);
1720 
1721 	first_mp = mp;
1722 	if (mctl_present) {
1723 		mp = first_mp->b_cont;
1724 		ASSERT(mp != NULL);
1725 	}
1726 
1727 	ipha = (ipha_t *)mp->b_rptr;
1728 	if (icmp_accept_clear_messages == 0) {
1729 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1730 		    ipha, NULL, mctl_present);
1731 		if (first_mp == NULL)
1732 			return;
1733 	}
1734 
1735 	/*
1736 	 * On a labeled system, we have to check whether the zone itself is
1737 	 * permitted to receive raw traffic.
1738 	 */
1739 	if (is_system_labeled()) {
1740 		if (zoneid == ALL_ZONES)
1741 			zoneid = tsol_packet_to_zoneid(mp);
1742 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1743 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1744 			    zoneid));
1745 			BUMP_MIB(&icmp_mib, icmpInErrors);
1746 			freemsg(first_mp);
1747 			return;
1748 		}
1749 	}
1750 
1751 	/*
1752 	 * We have accepted the ICMP message. It means that we will
1753 	 * respond to the packet if needed. It may not be delivered
1754 	 * to the upper client depending on the policy constraints
1755 	 * and the disposition in ipsec_inbound_accept_clear.
1756 	 */
1757 
1758 	ASSERT(ill != NULL);
1759 
1760 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1761 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1762 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1763 		/* Last chance to get real. */
1764 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1765 			BUMP_MIB(&icmp_mib, icmpInErrors);
1766 			freemsg(first_mp);
1767 			return;
1768 		}
1769 		/* Refresh iph following the pullup. */
1770 		ipha = (ipha_t *)mp->b_rptr;
1771 	}
1772 	/* ICMP header checksum, including checksum field, should be zero. */
1773 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1774 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1775 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1776 		freemsg(first_mp);
1777 		return;
1778 	}
1779 	/* The IP header will always be a multiple of four bytes */
1780 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1781 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1782 	    icmph->icmph_code));
1783 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1784 	/* We will set "interested" to "true" if we want a copy */
1785 	interested = B_FALSE;
1786 	switch (icmph->icmph_type) {
1787 	case ICMP_ECHO_REPLY:
1788 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1789 		break;
1790 	case ICMP_DEST_UNREACHABLE:
1791 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1792 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1793 		interested = B_TRUE;	/* Pass up to transport */
1794 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1795 		break;
1796 	case ICMP_SOURCE_QUENCH:
1797 		interested = B_TRUE;	/* Pass up to transport */
1798 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1799 		break;
1800 	case ICMP_REDIRECT:
1801 		if (!ip_ignore_redirect)
1802 			interested = B_TRUE;
1803 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1804 		break;
1805 	case ICMP_ECHO_REQUEST:
1806 		/*
1807 		 * Whether to respond to echo requests that come in as IP
1808 		 * broadcasts or as IP multicast is subject to debate
1809 		 * (what isn't?).  We aim to please, you pick it.
1810 		 * Default is do it.
1811 		 */
1812 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1813 			/* unicast: always respond */
1814 			interested = B_TRUE;
1815 		} else if (CLASSD(ipha->ipha_dst)) {
1816 			/* multicast: respond based on tunable */
1817 			interested = ip_g_resp_to_echo_mcast;
1818 		} else if (broadcast) {
1819 			/* broadcast: respond based on tunable */
1820 			interested = ip_g_resp_to_echo_bcast;
1821 		}
1822 		BUMP_MIB(&icmp_mib, icmpInEchos);
1823 		break;
1824 	case ICMP_ROUTER_ADVERTISEMENT:
1825 	case ICMP_ROUTER_SOLICITATION:
1826 		break;
1827 	case ICMP_TIME_EXCEEDED:
1828 		interested = B_TRUE;	/* Pass up to transport */
1829 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1830 		break;
1831 	case ICMP_PARAM_PROBLEM:
1832 		interested = B_TRUE;	/* Pass up to transport */
1833 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1834 		break;
1835 	case ICMP_TIME_STAMP_REQUEST:
1836 		/* Response to Time Stamp Requests is local policy. */
1837 		if (ip_g_resp_to_timestamp &&
1838 		    /* So is whether to respond if it was an IP broadcast. */
1839 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1840 			int tstamp_len = 3 * sizeof (uint32_t);
1841 
1842 			if (wptr +  tstamp_len > mp->b_wptr) {
1843 				if (!pullupmsg(mp, wptr + tstamp_len -
1844 				    mp->b_rptr)) {
1845 					BUMP_MIB(&ip_mib, ipInDiscards);
1846 					freemsg(first_mp);
1847 					return;
1848 				}
1849 				/* Refresh ipha following the pullup. */
1850 				ipha = (ipha_t *)mp->b_rptr;
1851 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1852 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1853 			}
1854 			interested = B_TRUE;
1855 		}
1856 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1857 		break;
1858 	case ICMP_TIME_STAMP_REPLY:
1859 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1860 		break;
1861 	case ICMP_INFO_REQUEST:
1862 		/* Per RFC 1122 3.2.2.7, ignore this. */
1863 	case ICMP_INFO_REPLY:
1864 		break;
1865 	case ICMP_ADDRESS_MASK_REQUEST:
1866 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1867 		    /* TODO m_pullup of complete header? */
1868 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1869 			interested = B_TRUE;
1870 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1871 		break;
1872 	case ICMP_ADDRESS_MASK_REPLY:
1873 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1874 		break;
1875 	default:
1876 		interested = B_TRUE;	/* Pass up to transport */
1877 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1878 		break;
1879 	}
1880 	/* See if there is an ICMP client. */
1881 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1882 		/* If there is an ICMP client and we want one too, copy it. */
1883 		mblk_t *first_mp1;
1884 
1885 		if (!interested) {
1886 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1887 			    ip_policy, recv_ill, zoneid);
1888 			return;
1889 		}
1890 		first_mp1 = ip_copymsg(first_mp);
1891 		if (first_mp1 != NULL) {
1892 			ip_fanout_proto(q, first_mp1, ill, ipha,
1893 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1894 		}
1895 	} else if (!interested) {
1896 		freemsg(first_mp);
1897 		return;
1898 	} else {
1899 		/*
1900 		 * Initiate policy processing for this packet if ip_policy
1901 		 * is true.
1902 		 */
1903 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1904 			ill_index = ill->ill_phyint->phyint_ifindex;
1905 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1906 			if (mp == NULL) {
1907 				if (mctl_present) {
1908 					freeb(first_mp);
1909 				}
1910 				BUMP_MIB(&icmp_mib, icmpInErrors);
1911 				return;
1912 			}
1913 		}
1914 	}
1915 	/* We want to do something with it. */
1916 	/* Check db_ref to make sure we can modify the packet. */
1917 	if (mp->b_datap->db_ref > 1) {
1918 		mblk_t	*first_mp1;
1919 
1920 		first_mp1 = ip_copymsg(first_mp);
1921 		freemsg(first_mp);
1922 		if (!first_mp1) {
1923 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1924 			return;
1925 		}
1926 		first_mp = first_mp1;
1927 		if (mctl_present) {
1928 			mp = first_mp->b_cont;
1929 			ASSERT(mp != NULL);
1930 		} else {
1931 			mp = first_mp;
1932 		}
1933 		ipha = (ipha_t *)mp->b_rptr;
1934 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1935 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1936 	}
1937 	switch (icmph->icmph_type) {
1938 	case ICMP_ADDRESS_MASK_REQUEST:
1939 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1940 		if (ipif == NULL) {
1941 			freemsg(first_mp);
1942 			return;
1943 		}
1944 		/*
1945 		 * outging interface must be IPv4
1946 		 */
1947 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1948 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1949 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1950 		ipif_refrele(ipif);
1951 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1952 		break;
1953 	case ICMP_ECHO_REQUEST:
1954 		icmph->icmph_type = ICMP_ECHO_REPLY;
1955 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1956 		break;
1957 	case ICMP_TIME_STAMP_REQUEST: {
1958 		uint32_t *tsp;
1959 
1960 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1961 		tsp = (uint32_t *)wptr;
1962 		tsp++;		/* Skip past 'originate time' */
1963 		/* Compute # of milliseconds since midnight */
1964 		gethrestime(&now);
1965 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1966 		    now.tv_nsec / (NANOSEC / MILLISEC);
1967 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1968 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1969 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1970 		break;
1971 	}
1972 	default:
1973 		ipha = (ipha_t *)&icmph[1];
1974 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1975 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1976 				BUMP_MIB(&ip_mib, ipInDiscards);
1977 				freemsg(first_mp);
1978 				return;
1979 			}
1980 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1981 			ipha = (ipha_t *)&icmph[1];
1982 		}
1983 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1984 			BUMP_MIB(&ip_mib, ipInDiscards);
1985 			freemsg(first_mp);
1986 			return;
1987 		}
1988 		hdr_length = IPH_HDR_LENGTH(ipha);
1989 		if (hdr_length < sizeof (ipha_t)) {
1990 			BUMP_MIB(&ip_mib, ipInDiscards);
1991 			freemsg(first_mp);
1992 			return;
1993 		}
1994 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1995 			if (!pullupmsg(mp,
1996 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1997 				BUMP_MIB(&ip_mib, ipInDiscards);
1998 				freemsg(first_mp);
1999 				return;
2000 			}
2001 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2002 			ipha = (ipha_t *)&icmph[1];
2003 		}
2004 		switch (icmph->icmph_type) {
2005 		case ICMP_REDIRECT:
2006 			/*
2007 			 * As there is no upper client to deliver, we don't
2008 			 * need the first_mp any more.
2009 			 */
2010 			if (mctl_present) {
2011 				freeb(first_mp);
2012 			}
2013 			icmp_redirect(mp);
2014 			return;
2015 		case ICMP_DEST_UNREACHABLE:
2016 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
2017 				if (!icmp_inbound_too_big(icmph, ipha, ill,
2018 				    zoneid, mp, iph_hdr_length)) {
2019 					freemsg(first_mp);
2020 					return;
2021 				}
2022 				/*
2023 				 * icmp_inbound_too_big() may alter mp.
2024 				 * Resynch ipha and icmph accordingly.
2025 				 */
2026 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2027 				ipha = (ipha_t *)&icmph[1];
2028 			}
2029 			/* FALLTHRU */
2030 		default :
2031 			/*
2032 			 * IPQoS notes: Since we have already done IPQoS
2033 			 * processing we don't want to do it again in
2034 			 * the fanout routines called by
2035 			 * icmp_inbound_error_fanout, hence the last
2036 			 * argument, ip_policy, is B_FALSE.
2037 			 */
2038 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2039 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2040 			    B_FALSE, recv_ill, zoneid);
2041 		}
2042 		return;
2043 	}
2044 	/* Send out an ICMP packet */
2045 	icmph->icmph_checksum = 0;
2046 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2047 	if (icmph->icmph_checksum == 0)
2048 		icmph->icmph_checksum = 0xFFFF;
2049 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2050 		ipif_t	*ipif_chosen;
2051 		/*
2052 		 * Make it look like it was directed to us, so we don't look
2053 		 * like a fool with a broadcast or multicast source address.
2054 		 */
2055 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2056 		/*
2057 		 * Make sure that we haven't grabbed an interface that's DOWN.
2058 		 */
2059 		if (ipif != NULL) {
2060 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2061 			    ipha->ipha_src, zoneid);
2062 			if (ipif_chosen != NULL) {
2063 				ipif_refrele(ipif);
2064 				ipif = ipif_chosen;
2065 			}
2066 		}
2067 		if (ipif == NULL) {
2068 			ip0dbg(("icmp_inbound: "
2069 			    "No source for broadcast/multicast:\n"
2070 			    "\tsrc 0x%x dst 0x%x ill %p "
2071 			    "ipif_lcl_addr 0x%x\n",
2072 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2073 			    (void *)ill,
2074 			    ill->ill_ipif->ipif_lcl_addr));
2075 			freemsg(first_mp);
2076 			return;
2077 		}
2078 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2079 		ipha->ipha_dst = ipif->ipif_src_addr;
2080 		ipif_refrele(ipif);
2081 	}
2082 	/* Reset time to live. */
2083 	ipha->ipha_ttl = ip_def_ttl;
2084 	{
2085 		/* Swap source and destination addresses */
2086 		ipaddr_t tmp;
2087 
2088 		tmp = ipha->ipha_src;
2089 		ipha->ipha_src = ipha->ipha_dst;
2090 		ipha->ipha_dst = tmp;
2091 	}
2092 	ipha->ipha_ident = 0;
2093 	if (!IS_SIMPLE_IPH(ipha))
2094 		icmp_options_update(ipha);
2095 
2096 	/*
2097 	 * ICMP echo replies should go out on the same interface
2098 	 * the request came on as probes used by in.mpathd for detecting
2099 	 * NIC failures are ECHO packets. We turn-off load spreading
2100 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2101 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2102 	 * function. This is in turn handled by ip_wput and ip_newroute
2103 	 * to make sure that the packet goes out on the interface it came
2104 	 * in on. If we don't turnoff load spreading, the packets might get
2105 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2106 	 * to go out and in.mpathd would wrongly detect a failure or
2107 	 * mis-detect a NIC failure for link failure. As load spreading
2108 	 * can happen only if ill_group is not NULL, we do only for
2109 	 * that case and this does not affect the normal case.
2110 	 *
2111 	 * We turn off load spreading only on echo packets that came from
2112 	 * on-link hosts. If the interface route has been deleted, this will
2113 	 * not be enforced as we can't do much. For off-link hosts, as the
2114 	 * default routes in IPv4 does not typically have an ire_ipif
2115 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2116 	 * Moreover, expecting a default route through this interface may
2117 	 * not be correct. We use ipha_dst because of the swap above.
2118 	 */
2119 	onlink = B_FALSE;
2120 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2121 		/*
2122 		 * First, we need to make sure that it is not one of our
2123 		 * local addresses. If we set onlink when it is one of
2124 		 * our local addresses, we will end up creating IRE_CACHES
2125 		 * for one of our local addresses. Then, we will never
2126 		 * accept packets for them afterwards.
2127 		 */
2128 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2129 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2130 		if (src_ire == NULL) {
2131 			ipif = ipif_get_next_ipif(NULL, ill);
2132 			if (ipif == NULL) {
2133 				BUMP_MIB(&ip_mib, ipInDiscards);
2134 				freemsg(mp);
2135 				return;
2136 			}
2137 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2138 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2139 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2140 			ipif_refrele(ipif);
2141 			if (src_ire != NULL) {
2142 				onlink = B_TRUE;
2143 				ire_refrele(src_ire);
2144 			}
2145 		} else {
2146 			ire_refrele(src_ire);
2147 		}
2148 	}
2149 	if (!mctl_present) {
2150 		/*
2151 		 * This packet should go out the same way as it
2152 		 * came in i.e in clear. To make sure that global
2153 		 * policy will not be applied to this in ip_wput_ire,
2154 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2155 		 */
2156 		ASSERT(first_mp == mp);
2157 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2158 			BUMP_MIB(&ip_mib, ipInDiscards);
2159 			freemsg(mp);
2160 			return;
2161 		}
2162 		ii = (ipsec_in_t *)first_mp->b_rptr;
2163 
2164 		/* This is not a secure packet */
2165 		ii->ipsec_in_secure = B_FALSE;
2166 		if (onlink) {
2167 			ii->ipsec_in_attach_if = B_TRUE;
2168 			ii->ipsec_in_ill_index =
2169 			    ill->ill_phyint->phyint_ifindex;
2170 			ii->ipsec_in_rill_index =
2171 			    recv_ill->ill_phyint->phyint_ifindex;
2172 		}
2173 		first_mp->b_cont = mp;
2174 	} else if (onlink) {
2175 		ii = (ipsec_in_t *)first_mp->b_rptr;
2176 		ii->ipsec_in_attach_if = B_TRUE;
2177 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2178 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2179 	} else {
2180 		ii = (ipsec_in_t *)first_mp->b_rptr;
2181 	}
2182 	ii->ipsec_in_zoneid = zoneid;
2183 	ASSERT(zoneid != ALL_ZONES);
2184 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2185 		BUMP_MIB(&ip_mib, ipInDiscards);
2186 		return;
2187 	}
2188 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2189 	put(WR(q), first_mp);
2190 }
2191 
2192 static ipaddr_t
2193 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2194 {
2195 	conn_t *connp;
2196 	connf_t *connfp;
2197 	ipaddr_t nexthop_addr = INADDR_ANY;
2198 	int hdr_length = IPH_HDR_LENGTH(ipha);
2199 	uint16_t *up;
2200 	uint32_t ports;
2201 
2202 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2203 	switch (ipha->ipha_protocol) {
2204 		case IPPROTO_TCP:
2205 		{
2206 			tcph_t *tcph;
2207 
2208 			/* do a reverse lookup */
2209 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2210 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2211 			    TCPS_LISTEN);
2212 			break;
2213 		}
2214 		case IPPROTO_UDP:
2215 		{
2216 			uint32_t dstport, srcport;
2217 
2218 			((uint16_t *)&ports)[0] = up[1];
2219 			((uint16_t *)&ports)[1] = up[0];
2220 
2221 			/* Extract ports in net byte order */
2222 			dstport = htons(ntohl(ports) & 0xFFFF);
2223 			srcport = htons(ntohl(ports) >> 16);
2224 
2225 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2226 			mutex_enter(&connfp->connf_lock);
2227 			connp = connfp->connf_head;
2228 
2229 			/* do a reverse lookup */
2230 			while ((connp != NULL) &&
2231 			    (!IPCL_UDP_MATCH(connp, dstport,
2232 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2233 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2234 				connp = connp->conn_next;
2235 			}
2236 			if (connp != NULL)
2237 				CONN_INC_REF(connp);
2238 			mutex_exit(&connfp->connf_lock);
2239 			break;
2240 		}
2241 		case IPPROTO_SCTP:
2242 		{
2243 			in6_addr_t map_src, map_dst;
2244 
2245 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2246 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2247 			((uint16_t *)&ports)[0] = up[1];
2248 			((uint16_t *)&ports)[1] = up[0];
2249 
2250 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2251 			    0, zoneid)) == NULL) {
2252 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2253 				    zoneid, ports, ipha);
2254 			} else {
2255 				CONN_INC_REF(connp);
2256 				SCTP_REFRELE(CONN2SCTP(connp));
2257 			}
2258 			break;
2259 		}
2260 		default:
2261 		{
2262 			ipha_t ripha;
2263 
2264 			ripha.ipha_src = ipha->ipha_dst;
2265 			ripha.ipha_dst = ipha->ipha_src;
2266 			ripha.ipha_protocol = ipha->ipha_protocol;
2267 
2268 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2269 			mutex_enter(&connfp->connf_lock);
2270 			connp = connfp->connf_head;
2271 			for (connp = connfp->connf_head; connp != NULL;
2272 			    connp = connp->conn_next) {
2273 				if (IPCL_PROTO_MATCH(connp,
2274 				    ipha->ipha_protocol, &ripha, ill,
2275 				    0, zoneid)) {
2276 					CONN_INC_REF(connp);
2277 					break;
2278 				}
2279 			}
2280 			mutex_exit(&connfp->connf_lock);
2281 		}
2282 	}
2283 	if (connp != NULL) {
2284 		if (connp->conn_nexthop_set)
2285 			nexthop_addr = connp->conn_nexthop_v4;
2286 		CONN_DEC_REF(connp);
2287 	}
2288 	return (nexthop_addr);
2289 }
2290 
2291 /* Table from RFC 1191 */
2292 static int icmp_frag_size_table[] =
2293 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2294 
2295 /*
2296  * Process received ICMP Packet too big.
2297  * After updating any IRE it does the fanout to any matching transport streams.
2298  * Assumes the message has been pulled up till the IP header that caused
2299  * the error.
2300  *
2301  * Returns B_FALSE on failure and B_TRUE on success.
2302  */
2303 static boolean_t
2304 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2305     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2306 {
2307 	ire_t	*ire, *first_ire;
2308 	int	mtu;
2309 	int	hdr_length;
2310 	ipaddr_t nexthop_addr;
2311 
2312 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2313 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2314 
2315 	hdr_length = IPH_HDR_LENGTH(ipha);
2316 
2317 	/* Drop if the original packet contained a source route */
2318 	if (ip_source_route_included(ipha)) {
2319 		return (B_FALSE);
2320 	}
2321 	/*
2322 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2323 	 * header.
2324 	 */
2325 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2326 	    mp->b_wptr) {
2327 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2328 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2329 			BUMP_MIB(&ip_mib, ipInDiscards);
2330 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2331 			return (B_FALSE);
2332 		}
2333 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2334 		ipha = (ipha_t *)&icmph[1];
2335 	}
2336 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2337 	if (nexthop_addr != INADDR_ANY) {
2338 		/* nexthop set */
2339 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2340 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2341 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2342 	} else {
2343 		/* nexthop not set */
2344 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2345 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2346 	}
2347 
2348 	if (!first_ire) {
2349 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2350 		    ntohl(ipha->ipha_dst)));
2351 		return (B_FALSE);
2352 	}
2353 	/* Check for MTU discovery advice as described in RFC 1191 */
2354 	mtu = ntohs(icmph->icmph_du_mtu);
2355 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2356 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2357 	    ire = ire->ire_next) {
2358 		/*
2359 		 * Look for the connection to which this ICMP message is
2360 		 * directed. If it has the IP_NEXTHOP option set, then the
2361 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2362 		 * option. Else the search is limited to regular IREs.
2363 		 */
2364 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2365 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2366 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2367 		    (nexthop_addr != INADDR_ANY)))
2368 			continue;
2369 
2370 		mutex_enter(&ire->ire_lock);
2371 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2372 			/* Reduce the IRE max frag value as advised. */
2373 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2374 			    mtu, ire->ire_max_frag));
2375 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2376 		} else {
2377 			uint32_t length;
2378 			int	i;
2379 
2380 			/*
2381 			 * Use the table from RFC 1191 to figure out
2382 			 * the next "plateau" based on the length in
2383 			 * the original IP packet.
2384 			 */
2385 			length = ntohs(ipha->ipha_length);
2386 			if (ire->ire_max_frag <= length &&
2387 			    ire->ire_max_frag >= length - hdr_length) {
2388 				/*
2389 				 * Handle broken BSD 4.2 systems that
2390 				 * return the wrong iph_length in ICMP
2391 				 * errors.
2392 				 */
2393 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2394 				    length, ire->ire_max_frag));
2395 				length -= hdr_length;
2396 			}
2397 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2398 				if (length > icmp_frag_size_table[i])
2399 					break;
2400 			}
2401 			if (i == A_CNT(icmp_frag_size_table)) {
2402 				/* Smaller than 68! */
2403 				ip1dbg(("Too big for packet size %d\n",
2404 				    length));
2405 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2406 				ire->ire_frag_flag = 0;
2407 			} else {
2408 				mtu = icmp_frag_size_table[i];
2409 				ip1dbg(("Calculated mtu %d, packet size %d, "
2410 				    "before %d", mtu, length,
2411 				    ire->ire_max_frag));
2412 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2413 				ip1dbg((", after %d\n", ire->ire_max_frag));
2414 			}
2415 			/* Record the new max frag size for the ULP. */
2416 			icmph->icmph_du_zero = 0;
2417 			icmph->icmph_du_mtu =
2418 			    htons((uint16_t)ire->ire_max_frag);
2419 		}
2420 		mutex_exit(&ire->ire_lock);
2421 	}
2422 	rw_exit(&first_ire->ire_bucket->irb_lock);
2423 	ire_refrele(first_ire);
2424 	return (B_TRUE);
2425 }
2426 
2427 /*
2428  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2429  * calls this function.
2430  */
2431 static mblk_t *
2432 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2433 {
2434 	ipha_t *ipha;
2435 	icmph_t *icmph;
2436 	ipha_t *in_ipha;
2437 	int length;
2438 
2439 	ASSERT(mp->b_datap->db_type == M_DATA);
2440 
2441 	/*
2442 	 * For Self-encapsulated packets, we added an extra IP header
2443 	 * without the options. Inner IP header is the one from which
2444 	 * the outer IP header was formed. Thus, we need to remove the
2445 	 * outer IP header. To do this, we pullup the whole message
2446 	 * and overlay whatever follows the outer IP header over the
2447 	 * outer IP header.
2448 	 */
2449 
2450 	if (!pullupmsg(mp, -1)) {
2451 		BUMP_MIB(&ip_mib, ipInDiscards);
2452 		return (NULL);
2453 	}
2454 
2455 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2456 	ipha = (ipha_t *)&icmph[1];
2457 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2458 
2459 	/*
2460 	 * The length that we want to overlay is following the inner
2461 	 * IP header. Subtracting the IP header + icmp header + outer
2462 	 * IP header's length should give us the length that we want to
2463 	 * overlay.
2464 	 */
2465 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2466 	    hdr_length;
2467 	/*
2468 	 * Overlay whatever follows the inner header over the
2469 	 * outer header.
2470 	 */
2471 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2472 
2473 	/* Set the wptr to account for the outer header */
2474 	mp->b_wptr -= hdr_length;
2475 	return (mp);
2476 }
2477 
2478 /*
2479  * Try to pass the ICMP message upstream in case the ULP cares.
2480  *
2481  * If the packet that caused the ICMP error is secure, we send
2482  * it to AH/ESP to make sure that the attached packet has a
2483  * valid association. ipha in the code below points to the
2484  * IP header of the packet that caused the error.
2485  *
2486  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2487  * in the context of IPSEC. Normally we tell the upper layer
2488  * whenever we send the ire (including ip_bind), the IPSEC header
2489  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2490  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2491  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2492  * same thing. As TCP has the IPSEC options size that needs to be
2493  * adjusted, we just pass the MTU unchanged.
2494  *
2495  * IFN could have been generated locally or by some router.
2496  *
2497  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2498  *	    This happens because IP adjusted its value of MTU on an
2499  *	    earlier IFN message and could not tell the upper layer,
2500  *	    the new adjusted value of MTU e.g. Packet was encrypted
2501  *	    or there was not enough information to fanout to upper
2502  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2503  *	    generates the IFN, where IPSEC processing has *not* been
2504  *	    done.
2505  *
2506  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2507  *	    could have generated this. This happens because ire_max_frag
2508  *	    value in IP was set to a new value, while the IPSEC processing
2509  *	    was being done and after we made the fragmentation check in
2510  *	    ip_wput_ire. Thus on return from IPSEC processing,
2511  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2512  *	    and generates the IFN. As IPSEC processing is over, we fanout
2513  *	    to AH/ESP to remove the header.
2514  *
2515  *	    In both these cases, ipsec_in_loopback will be set indicating
2516  *	    that IFN was generated locally.
2517  *
2518  * ROUTER : IFN could be secure or non-secure.
2519  *
2520  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2521  *	      packet in error has AH/ESP headers to validate the AH/ESP
2522  *	      headers. AH/ESP will verify whether there is a valid SA or
2523  *	      not and send it back. We will fanout again if we have more
2524  *	      data in the packet.
2525  *
2526  *	      If the packet in error does not have AH/ESP, we handle it
2527  *	      like any other case.
2528  *
2529  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2530  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2531  *	      for validation. AH/ESP will verify whether there is a
2532  *	      valid SA or not and send it back. We will fanout again if
2533  *	      we have more data in the packet.
2534  *
2535  *	      If the packet in error does not have AH/ESP, we handle it
2536  *	      like any other case.
2537  */
2538 static void
2539 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2540     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2541     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2542     zoneid_t zoneid)
2543 {
2544 	uint16_t *up;	/* Pointer to ports in ULP header */
2545 	uint32_t ports;	/* reversed ports for fanout */
2546 	ipha_t ripha;	/* With reversed addresses */
2547 	mblk_t *first_mp;
2548 	ipsec_in_t *ii;
2549 	tcph_t	*tcph;
2550 	conn_t	*connp;
2551 
2552 	first_mp = mp;
2553 	if (mctl_present) {
2554 		mp = first_mp->b_cont;
2555 		ASSERT(mp != NULL);
2556 
2557 		ii = (ipsec_in_t *)first_mp->b_rptr;
2558 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2559 	} else {
2560 		ii = NULL;
2561 	}
2562 
2563 	switch (ipha->ipha_protocol) {
2564 	case IPPROTO_UDP:
2565 		/*
2566 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2567 		 * transport header.
2568 		 */
2569 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2570 		    mp->b_wptr) {
2571 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2572 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2573 				BUMP_MIB(&ip_mib, ipInDiscards);
2574 				goto drop_pkt;
2575 			}
2576 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2577 			ipha = (ipha_t *)&icmph[1];
2578 		}
2579 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2580 
2581 		/*
2582 		 * Attempt to find a client stream based on port.
2583 		 * Note that we do a reverse lookup since the header is
2584 		 * in the form we sent it out.
2585 		 * The ripha header is only used for the IP_UDP_MATCH and we
2586 		 * only set the src and dst addresses and protocol.
2587 		 */
2588 		ripha.ipha_src = ipha->ipha_dst;
2589 		ripha.ipha_dst = ipha->ipha_src;
2590 		ripha.ipha_protocol = ipha->ipha_protocol;
2591 		((uint16_t *)&ports)[0] = up[1];
2592 		((uint16_t *)&ports)[1] = up[0];
2593 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2594 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2595 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2596 		    icmph->icmph_type, icmph->icmph_code));
2597 
2598 		/* Have to change db_type after any pullupmsg */
2599 		DB_TYPE(mp) = M_CTL;
2600 
2601 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2602 		    mctl_present, ip_policy, recv_ill, zoneid);
2603 		return;
2604 
2605 	case IPPROTO_TCP:
2606 		/*
2607 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2608 		 * transport header.
2609 		 */
2610 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2611 		    mp->b_wptr) {
2612 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2613 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2614 				BUMP_MIB(&ip_mib, ipInDiscards);
2615 				goto drop_pkt;
2616 			}
2617 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2618 			ipha = (ipha_t *)&icmph[1];
2619 		}
2620 		/*
2621 		 * Find a TCP client stream for this packet.
2622 		 * Note that we do a reverse lookup since the header is
2623 		 * in the form we sent it out.
2624 		 */
2625 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2626 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2627 		if (connp == NULL) {
2628 			BUMP_MIB(&ip_mib, ipInDiscards);
2629 			goto drop_pkt;
2630 		}
2631 
2632 		/* Have to change db_type after any pullupmsg */
2633 		DB_TYPE(mp) = M_CTL;
2634 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2635 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2636 		return;
2637 
2638 	case IPPROTO_SCTP:
2639 		/*
2640 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2641 		 * transport header.
2642 		 */
2643 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2644 		    mp->b_wptr) {
2645 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2646 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2647 				BUMP_MIB(&ip_mib, ipInDiscards);
2648 				goto drop_pkt;
2649 			}
2650 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2651 			ipha = (ipha_t *)&icmph[1];
2652 		}
2653 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2654 		/*
2655 		 * Find a SCTP client stream for this packet.
2656 		 * Note that we do a reverse lookup since the header is
2657 		 * in the form we sent it out.
2658 		 * The ripha header is only used for the matching and we
2659 		 * only set the src and dst addresses, protocol, and version.
2660 		 */
2661 		ripha.ipha_src = ipha->ipha_dst;
2662 		ripha.ipha_dst = ipha->ipha_src;
2663 		ripha.ipha_protocol = ipha->ipha_protocol;
2664 		ripha.ipha_version_and_hdr_length =
2665 		    ipha->ipha_version_and_hdr_length;
2666 		((uint16_t *)&ports)[0] = up[1];
2667 		((uint16_t *)&ports)[1] = up[0];
2668 
2669 		/* Have to change db_type after any pullupmsg */
2670 		DB_TYPE(mp) = M_CTL;
2671 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2672 		    mctl_present, ip_policy, 0, zoneid);
2673 		return;
2674 
2675 	case IPPROTO_ESP:
2676 	case IPPROTO_AH: {
2677 		int ipsec_rc;
2678 
2679 		/*
2680 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2681 		 * We will re-use the IPSEC_IN if it is already present as
2682 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2683 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2684 		 * one and attach it in the front.
2685 		 */
2686 		if (ii != NULL) {
2687 			/*
2688 			 * ip_fanout_proto_again converts the ICMP errors
2689 			 * that come back from AH/ESP to M_DATA so that
2690 			 * if it is non-AH/ESP and we do a pullupmsg in
2691 			 * this function, it would work. Convert it back
2692 			 * to M_CTL before we send up as this is a ICMP
2693 			 * error. This could have been generated locally or
2694 			 * by some router. Validate the inner IPSEC
2695 			 * headers.
2696 			 *
2697 			 * NOTE : ill_index is used by ip_fanout_proto_again
2698 			 * to locate the ill.
2699 			 */
2700 			ASSERT(ill != NULL);
2701 			ii->ipsec_in_ill_index =
2702 			    ill->ill_phyint->phyint_ifindex;
2703 			ii->ipsec_in_rill_index =
2704 			    recv_ill->ill_phyint->phyint_ifindex;
2705 			DB_TYPE(first_mp->b_cont) = M_CTL;
2706 		} else {
2707 			/*
2708 			 * IPSEC_IN is not present. We attach a ipsec_in
2709 			 * message and send up to IPSEC for validating
2710 			 * and removing the IPSEC headers. Clear
2711 			 * ipsec_in_secure so that when we return
2712 			 * from IPSEC, we don't mistakenly think that this
2713 			 * is a secure packet came from the network.
2714 			 *
2715 			 * NOTE : ill_index is used by ip_fanout_proto_again
2716 			 * to locate the ill.
2717 			 */
2718 			ASSERT(first_mp == mp);
2719 			first_mp = ipsec_in_alloc(B_TRUE);
2720 			if (first_mp == NULL) {
2721 				freemsg(mp);
2722 				BUMP_MIB(&ip_mib, ipInDiscards);
2723 				return;
2724 			}
2725 			ii = (ipsec_in_t *)first_mp->b_rptr;
2726 
2727 			/* This is not a secure packet */
2728 			ii->ipsec_in_secure = B_FALSE;
2729 			first_mp->b_cont = mp;
2730 			DB_TYPE(mp) = M_CTL;
2731 			ASSERT(ill != NULL);
2732 			ii->ipsec_in_ill_index =
2733 			    ill->ill_phyint->phyint_ifindex;
2734 			ii->ipsec_in_rill_index =
2735 			    recv_ill->ill_phyint->phyint_ifindex;
2736 		}
2737 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2738 
2739 		if (!ipsec_loaded()) {
2740 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2741 			return;
2742 		}
2743 
2744 		if (ipha->ipha_protocol == IPPROTO_ESP)
2745 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2746 		else
2747 			ipsec_rc = ipsecah_icmp_error(first_mp);
2748 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2749 			return;
2750 
2751 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2752 		return;
2753 	}
2754 	default:
2755 		/*
2756 		 * The ripha header is only used for the lookup and we
2757 		 * only set the src and dst addresses and protocol.
2758 		 */
2759 		ripha.ipha_src = ipha->ipha_dst;
2760 		ripha.ipha_dst = ipha->ipha_src;
2761 		ripha.ipha_protocol = ipha->ipha_protocol;
2762 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2763 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2764 		    ntohl(ipha->ipha_dst),
2765 		    icmph->icmph_type, icmph->icmph_code));
2766 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2767 			ipha_t *in_ipha;
2768 
2769 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2770 			    mp->b_wptr) {
2771 				if (!pullupmsg(mp, (uchar_t *)ipha +
2772 				    hdr_length + sizeof (ipha_t) -
2773 				    mp->b_rptr)) {
2774 
2775 					BUMP_MIB(&ip_mib, ipInDiscards);
2776 					goto drop_pkt;
2777 				}
2778 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2779 				ipha = (ipha_t *)&icmph[1];
2780 			}
2781 			/*
2782 			 * Caller has verified that length has to be
2783 			 * at least the size of IP header.
2784 			 */
2785 			ASSERT(hdr_length >= sizeof (ipha_t));
2786 			/*
2787 			 * Check the sanity of the inner IP header like
2788 			 * we did for the outer header.
2789 			 */
2790 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2791 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2792 				BUMP_MIB(&ip_mib, ipInDiscards);
2793 				goto drop_pkt;
2794 			}
2795 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2796 				BUMP_MIB(&ip_mib, ipInDiscards);
2797 				goto drop_pkt;
2798 			}
2799 			/* Check for Self-encapsulated tunnels */
2800 			if (in_ipha->ipha_src == ipha->ipha_src &&
2801 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2802 
2803 				mp = icmp_inbound_self_encap_error(mp,
2804 				    iph_hdr_length, hdr_length);
2805 				if (mp == NULL)
2806 					goto drop_pkt;
2807 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2808 				ipha = (ipha_t *)&icmph[1];
2809 				hdr_length = IPH_HDR_LENGTH(ipha);
2810 				/*
2811 				 * The packet in error is self-encapsualted.
2812 				 * And we are finding it further encapsulated
2813 				 * which we could not have possibly generated.
2814 				 */
2815 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2816 					BUMP_MIB(&ip_mib, ipInDiscards);
2817 					goto drop_pkt;
2818 				}
2819 				icmp_inbound_error_fanout(q, ill, first_mp,
2820 				    icmph, ipha, iph_hdr_length, hdr_length,
2821 				    mctl_present, ip_policy, recv_ill, zoneid);
2822 				return;
2823 			}
2824 		}
2825 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2826 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2827 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2828 		    ii != NULL &&
2829 		    ii->ipsec_in_loopback &&
2830 		    ii->ipsec_in_secure) {
2831 			/*
2832 			 * For IP tunnels that get a looped-back
2833 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2834 			 * reported new MTU to take into account the IPsec
2835 			 * headers protecting this configured tunnel.
2836 			 *
2837 			 * This allows the tunnel module (tun.c) to blindly
2838 			 * accept the MTU reported in an ICMP "too big"
2839 			 * message.
2840 			 *
2841 			 * Non-looped back ICMP messages will just be
2842 			 * handled by the security protocols (if needed),
2843 			 * and the first subsequent packet will hit this
2844 			 * path.
2845 			 */
2846 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2847 			    ipsec_in_extra_length(first_mp));
2848 		}
2849 		/* Have to change db_type after any pullupmsg */
2850 		DB_TYPE(mp) = M_CTL;
2851 
2852 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2853 		    ip_policy, recv_ill, zoneid);
2854 		return;
2855 	}
2856 	/* NOTREACHED */
2857 drop_pkt:;
2858 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2859 	freemsg(first_mp);
2860 }
2861 
2862 /*
2863  * Common IP options parser.
2864  *
2865  * Setup routine: fill in *optp with options-parsing state, then
2866  * tail-call ipoptp_next to return the first option.
2867  */
2868 uint8_t
2869 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2870 {
2871 	uint32_t totallen; /* total length of all options */
2872 
2873 	totallen = ipha->ipha_version_and_hdr_length -
2874 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2875 	totallen <<= 2;
2876 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2877 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2878 	optp->ipoptp_flags = 0;
2879 	return (ipoptp_next(optp));
2880 }
2881 
2882 /*
2883  * Common IP options parser: extract next option.
2884  */
2885 uint8_t
2886 ipoptp_next(ipoptp_t *optp)
2887 {
2888 	uint8_t *end = optp->ipoptp_end;
2889 	uint8_t *cur = optp->ipoptp_next;
2890 	uint8_t opt, len, pointer;
2891 
2892 	/*
2893 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2894 	 * has been corrupted.
2895 	 */
2896 	ASSERT(cur <= end);
2897 
2898 	if (cur == end)
2899 		return (IPOPT_EOL);
2900 
2901 	opt = cur[IPOPT_OPTVAL];
2902 
2903 	/*
2904 	 * Skip any NOP options.
2905 	 */
2906 	while (opt == IPOPT_NOP) {
2907 		cur++;
2908 		if (cur == end)
2909 			return (IPOPT_EOL);
2910 		opt = cur[IPOPT_OPTVAL];
2911 	}
2912 
2913 	if (opt == IPOPT_EOL)
2914 		return (IPOPT_EOL);
2915 
2916 	/*
2917 	 * Option requiring a length.
2918 	 */
2919 	if ((cur + 1) >= end) {
2920 		optp->ipoptp_flags |= IPOPTP_ERROR;
2921 		return (IPOPT_EOL);
2922 	}
2923 	len = cur[IPOPT_OLEN];
2924 	if (len < 2) {
2925 		optp->ipoptp_flags |= IPOPTP_ERROR;
2926 		return (IPOPT_EOL);
2927 	}
2928 	optp->ipoptp_cur = cur;
2929 	optp->ipoptp_len = len;
2930 	optp->ipoptp_next = cur + len;
2931 	if (cur + len > end) {
2932 		optp->ipoptp_flags |= IPOPTP_ERROR;
2933 		return (IPOPT_EOL);
2934 	}
2935 
2936 	/*
2937 	 * For the options which require a pointer field, make sure
2938 	 * its there, and make sure it points to either something
2939 	 * inside this option, or the end of the option.
2940 	 */
2941 	switch (opt) {
2942 	case IPOPT_RR:
2943 	case IPOPT_TS:
2944 	case IPOPT_LSRR:
2945 	case IPOPT_SSRR:
2946 		if (len <= IPOPT_OFFSET) {
2947 			optp->ipoptp_flags |= IPOPTP_ERROR;
2948 			return (opt);
2949 		}
2950 		pointer = cur[IPOPT_OFFSET];
2951 		if (pointer - 1 > len) {
2952 			optp->ipoptp_flags |= IPOPTP_ERROR;
2953 			return (opt);
2954 		}
2955 		break;
2956 	}
2957 
2958 	/*
2959 	 * Sanity check the pointer field based on the type of the
2960 	 * option.
2961 	 */
2962 	switch (opt) {
2963 	case IPOPT_RR:
2964 	case IPOPT_SSRR:
2965 	case IPOPT_LSRR:
2966 		if (pointer < IPOPT_MINOFF_SR)
2967 			optp->ipoptp_flags |= IPOPTP_ERROR;
2968 		break;
2969 	case IPOPT_TS:
2970 		if (pointer < IPOPT_MINOFF_IT)
2971 			optp->ipoptp_flags |= IPOPTP_ERROR;
2972 		/*
2973 		 * Note that the Internet Timestamp option also
2974 		 * contains two four bit fields (the Overflow field,
2975 		 * and the Flag field), which follow the pointer
2976 		 * field.  We don't need to check that these fields
2977 		 * fall within the length of the option because this
2978 		 * was implicitely done above.  We've checked that the
2979 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2980 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2981 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2982 		 */
2983 		ASSERT(len > IPOPT_POS_OV_FLG);
2984 		break;
2985 	}
2986 
2987 	return (opt);
2988 }
2989 
2990 /*
2991  * Use the outgoing IP header to create an IP_OPTIONS option the way
2992  * it was passed down from the application.
2993  */
2994 int
2995 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2996 {
2997 	ipoptp_t	opts;
2998 	const uchar_t	*opt;
2999 	uint8_t		optval;
3000 	uint8_t		optlen;
3001 	uint32_t	len = 0;
3002 	uchar_t	*buf1 = buf;
3003 
3004 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
3005 	len += IP_ADDR_LEN;
3006 	bzero(buf1, IP_ADDR_LEN);
3007 
3008 	/*
3009 	 * OK to cast away const here, as we don't store through the returned
3010 	 * opts.ipoptp_cur pointer.
3011 	 */
3012 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
3013 	    optval != IPOPT_EOL;
3014 	    optval = ipoptp_next(&opts)) {
3015 		int	off;
3016 
3017 		opt = opts.ipoptp_cur;
3018 		optlen = opts.ipoptp_len;
3019 		switch (optval) {
3020 		case IPOPT_SSRR:
3021 		case IPOPT_LSRR:
3022 
3023 			/*
3024 			 * Insert ipha_dst as the first entry in the source
3025 			 * route and move down the entries on step.
3026 			 * The last entry gets placed at buf1.
3027 			 */
3028 			buf[IPOPT_OPTVAL] = optval;
3029 			buf[IPOPT_OLEN] = optlen;
3030 			buf[IPOPT_OFFSET] = optlen;
3031 
3032 			off = optlen - IP_ADDR_LEN;
3033 			if (off < 0) {
3034 				/* No entries in source route */
3035 				break;
3036 			}
3037 			/* Last entry in source route */
3038 			bcopy(opt + off, buf1, IP_ADDR_LEN);
3039 			off -= IP_ADDR_LEN;
3040 
3041 			while (off > 0) {
3042 				bcopy(opt + off,
3043 				    buf + off + IP_ADDR_LEN,
3044 				    IP_ADDR_LEN);
3045 				off -= IP_ADDR_LEN;
3046 			}
3047 			/* ipha_dst into first slot */
3048 			bcopy(&ipha->ipha_dst,
3049 			    buf + off + IP_ADDR_LEN,
3050 			    IP_ADDR_LEN);
3051 			buf += optlen;
3052 			len += optlen;
3053 			break;
3054 
3055 		case IPOPT_COMSEC:
3056 		case IPOPT_SECURITY:
3057 			/* if passing up a label is not ok, then remove */
3058 			if (is_system_labeled())
3059 				break;
3060 			/* FALLTHROUGH */
3061 		default:
3062 			bcopy(opt, buf, optlen);
3063 			buf += optlen;
3064 			len += optlen;
3065 			break;
3066 		}
3067 	}
3068 done:
3069 	/* Pad the resulting options */
3070 	while (len & 0x3) {
3071 		*buf++ = IPOPT_EOL;
3072 		len++;
3073 	}
3074 	return (len);
3075 }
3076 
3077 /*
3078  * Update any record route or timestamp options to include this host.
3079  * Reverse any source route option.
3080  * This routine assumes that the options are well formed i.e. that they
3081  * have already been checked.
3082  */
3083 static void
3084 icmp_options_update(ipha_t *ipha)
3085 {
3086 	ipoptp_t	opts;
3087 	uchar_t		*opt;
3088 	uint8_t		optval;
3089 	ipaddr_t	src;		/* Our local address */
3090 	ipaddr_t	dst;
3091 
3092 	ip2dbg(("icmp_options_update\n"));
3093 	src = ipha->ipha_src;
3094 	dst = ipha->ipha_dst;
3095 
3096 	for (optval = ipoptp_first(&opts, ipha);
3097 	    optval != IPOPT_EOL;
3098 	    optval = ipoptp_next(&opts)) {
3099 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3100 		opt = opts.ipoptp_cur;
3101 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3102 		    optval, opts.ipoptp_len));
3103 		switch (optval) {
3104 			int off1, off2;
3105 		case IPOPT_SSRR:
3106 		case IPOPT_LSRR:
3107 			/*
3108 			 * Reverse the source route.  The first entry
3109 			 * should be the next to last one in the current
3110 			 * source route (the last entry is our address).
3111 			 * The last entry should be the final destination.
3112 			 */
3113 			off1 = IPOPT_MINOFF_SR - 1;
3114 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3115 			if (off2 < 0) {
3116 				/* No entries in source route */
3117 				ip1dbg((
3118 				    "icmp_options_update: bad src route\n"));
3119 				break;
3120 			}
3121 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3122 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3123 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3124 			off2 -= IP_ADDR_LEN;
3125 
3126 			while (off1 < off2) {
3127 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3128 				bcopy((char *)opt + off2, (char *)opt + off1,
3129 				    IP_ADDR_LEN);
3130 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3131 				off1 += IP_ADDR_LEN;
3132 				off2 -= IP_ADDR_LEN;
3133 			}
3134 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3135 			break;
3136 		}
3137 	}
3138 }
3139 
3140 /*
3141  * Process received ICMP Redirect messages.
3142  */
3143 /* ARGSUSED */
3144 static void
3145 icmp_redirect(mblk_t *mp)
3146 {
3147 	ipha_t	*ipha;
3148 	int	iph_hdr_length;
3149 	icmph_t	*icmph;
3150 	ipha_t	*ipha_err;
3151 	ire_t	*ire;
3152 	ire_t	*prev_ire;
3153 	ire_t	*save_ire;
3154 	ipaddr_t  src, dst, gateway;
3155 	iulp_t	ulp_info = { 0 };
3156 	int	error;
3157 
3158 	ipha = (ipha_t *)mp->b_rptr;
3159 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3160 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3161 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3162 		BUMP_MIB(&icmp_mib, icmpInErrors);
3163 		freemsg(mp);
3164 		return;
3165 	}
3166 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3167 	ipha_err = (ipha_t *)&icmph[1];
3168 	src = ipha->ipha_src;
3169 	dst = ipha_err->ipha_dst;
3170 	gateway = icmph->icmph_rd_gateway;
3171 	/* Make sure the new gateway is reachable somehow. */
3172 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3173 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3174 	/*
3175 	 * Make sure we had a route for the dest in question and that
3176 	 * that route was pointing to the old gateway (the source of the
3177 	 * redirect packet.)
3178 	 */
3179 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3180 	    NULL, MATCH_IRE_GW);
3181 	/*
3182 	 * Check that
3183 	 *	the redirect was not from ourselves
3184 	 *	the new gateway and the old gateway are directly reachable
3185 	 */
3186 	if (!prev_ire ||
3187 	    !ire ||
3188 	    ire->ire_type == IRE_LOCAL) {
3189 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3190 		freemsg(mp);
3191 		if (ire != NULL)
3192 			ire_refrele(ire);
3193 		if (prev_ire != NULL)
3194 			ire_refrele(prev_ire);
3195 		return;
3196 	}
3197 
3198 	/*
3199 	 * Should we use the old ULP info to create the new gateway?  From
3200 	 * a user's perspective, we should inherit the info so that it
3201 	 * is a "smooth" transition.  If we do not do that, then new
3202 	 * connections going thru the new gateway will have no route metrics,
3203 	 * which is counter-intuitive to user.  From a network point of
3204 	 * view, this may or may not make sense even though the new gateway
3205 	 * is still directly connected to us so the route metrics should not
3206 	 * change much.
3207 	 *
3208 	 * But if the old ire_uinfo is not initialized, we do another
3209 	 * recursive lookup on the dest using the new gateway.  There may
3210 	 * be a route to that.  If so, use it to initialize the redirect
3211 	 * route.
3212 	 */
3213 	if (prev_ire->ire_uinfo.iulp_set) {
3214 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3215 	} else {
3216 		ire_t *tmp_ire;
3217 		ire_t *sire;
3218 
3219 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3220 		    ALL_ZONES, 0, NULL,
3221 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3222 		if (sire != NULL) {
3223 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3224 			/*
3225 			 * If sire != NULL, ire_ftable_lookup() should not
3226 			 * return a NULL value.
3227 			 */
3228 			ASSERT(tmp_ire != NULL);
3229 			ire_refrele(tmp_ire);
3230 			ire_refrele(sire);
3231 		} else if (tmp_ire != NULL) {
3232 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3233 			    sizeof (iulp_t));
3234 			ire_refrele(tmp_ire);
3235 		}
3236 	}
3237 	if (prev_ire->ire_type == IRE_CACHE)
3238 		ire_delete(prev_ire);
3239 	ire_refrele(prev_ire);
3240 	/*
3241 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3242 	 * require TOS routing
3243 	 */
3244 	switch (icmph->icmph_code) {
3245 	case 0:
3246 	case 1:
3247 		/* TODO: TOS specificity for cases 2 and 3 */
3248 	case 2:
3249 	case 3:
3250 		break;
3251 	default:
3252 		freemsg(mp);
3253 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3254 		ire_refrele(ire);
3255 		return;
3256 	}
3257 	/*
3258 	 * Create a Route Association.  This will allow us to remember that
3259 	 * someone we believe told us to use the particular gateway.
3260 	 */
3261 	save_ire = ire;
3262 	ire = ire_create(
3263 		(uchar_t *)&dst,			/* dest addr */
3264 		(uchar_t *)&ip_g_all_ones,		/* mask */
3265 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3266 		(uchar_t *)&gateway,			/* gateway addr */
3267 		NULL,					/* no in_srcaddr */
3268 		&save_ire->ire_max_frag,		/* max frag */
3269 		NULL,					/* Fast Path header */
3270 		NULL,					/* no rfq */
3271 		NULL,					/* no stq */
3272 		IRE_HOST,
3273 		NULL,
3274 		NULL,
3275 		NULL,
3276 		0,
3277 		0,
3278 		0,
3279 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3280 		&ulp_info,
3281 		NULL,
3282 		NULL);
3283 
3284 	if (ire == NULL) {
3285 		freemsg(mp);
3286 		ire_refrele(save_ire);
3287 		return;
3288 	}
3289 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3290 	ire_refrele(save_ire);
3291 	atomic_inc_32(&ip_redirect_cnt);
3292 
3293 	if (error == 0) {
3294 		ire_refrele(ire);		/* Held in ire_add_v4 */
3295 		/* tell routing sockets that we received a redirect */
3296 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3297 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3298 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3299 	}
3300 
3301 	/*
3302 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3303 	 * This together with the added IRE has the effect of
3304 	 * modifying an existing redirect.
3305 	 */
3306 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3307 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3308 	if (prev_ire != NULL) {
3309 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3310 			ire_delete(prev_ire);
3311 		ire_refrele(prev_ire);
3312 	}
3313 
3314 	freemsg(mp);
3315 }
3316 
3317 /*
3318  * Generate an ICMP parameter problem message.
3319  */
3320 static void
3321 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid)
3322 {
3323 	icmph_t	icmph;
3324 	boolean_t mctl_present;
3325 	mblk_t *first_mp;
3326 
3327 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3328 
3329 	if (!(mp = icmp_pkt_err_ok(mp))) {
3330 		if (mctl_present)
3331 			freeb(first_mp);
3332 		return;
3333 	}
3334 
3335 	bzero(&icmph, sizeof (icmph_t));
3336 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3337 	icmph.icmph_pp_ptr = ptr;
3338 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3339 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3340 }
3341 
3342 /*
3343  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3344  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3345  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3346  * an icmp error packet can be sent.
3347  * Assigns an appropriate source address to the packet. If ipha_dst is
3348  * one of our addresses use it for source. Otherwise pick a source based
3349  * on a route lookup back to ipha_src.
3350  * Note that ipha_src must be set here since the
3351  * packet is likely to arrive on an ill queue in ip_wput() which will
3352  * not set a source address.
3353  */
3354 static void
3355 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3356     boolean_t mctl_present, zoneid_t zoneid)
3357 {
3358 	ipaddr_t dst;
3359 	icmph_t	*icmph;
3360 	ipha_t	*ipha;
3361 	uint_t	len_needed;
3362 	size_t	msg_len;
3363 	mblk_t	*mp1;
3364 	ipaddr_t src;
3365 	ire_t	*ire;
3366 	mblk_t *ipsec_mp;
3367 	ipsec_out_t	*io = NULL;
3368 	boolean_t xmit_if_on = B_FALSE;
3369 
3370 	if (mctl_present) {
3371 		/*
3372 		 * If it is :
3373 		 *
3374 		 * 1) a IPSEC_OUT, then this is caused by outbound
3375 		 *    datagram originating on this host. IPSEC processing
3376 		 *    may or may not have been done. Refer to comments above
3377 		 *    icmp_inbound_error_fanout for details.
3378 		 *
3379 		 * 2) a IPSEC_IN if we are generating a icmp_message
3380 		 *    for an incoming datagram destined for us i.e called
3381 		 *    from ip_fanout_send_icmp.
3382 		 */
3383 		ipsec_info_t *in;
3384 		ipsec_mp = mp;
3385 		mp = ipsec_mp->b_cont;
3386 
3387 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3388 		ipha = (ipha_t *)mp->b_rptr;
3389 
3390 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3391 		    in->ipsec_info_type == IPSEC_IN);
3392 
3393 		if (in->ipsec_info_type == IPSEC_IN) {
3394 			/*
3395 			 * Convert the IPSEC_IN to IPSEC_OUT.
3396 			 */
3397 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3398 				BUMP_MIB(&ip_mib, ipOutDiscards);
3399 				return;
3400 			}
3401 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3402 		} else {
3403 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3404 			io = (ipsec_out_t *)in;
3405 			if (io->ipsec_out_xmit_if)
3406 				xmit_if_on = B_TRUE;
3407 			/*
3408 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3409 			 * ire lookup.
3410 			 */
3411 			io->ipsec_out_proc_begin = B_FALSE;
3412 		}
3413 		ASSERT(zoneid == io->ipsec_out_zoneid);
3414 		ASSERT(zoneid != ALL_ZONES);
3415 	} else {
3416 		/*
3417 		 * This is in clear. The icmp message we are building
3418 		 * here should go out in clear.
3419 		 *
3420 		 * Pardon the convolution of it all, but it's easier to
3421 		 * allocate a "use cleartext" IPSEC_IN message and convert
3422 		 * it than it is to allocate a new one.
3423 		 */
3424 		ipsec_in_t *ii;
3425 		ASSERT(DB_TYPE(mp) == M_DATA);
3426 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3427 			freemsg(mp);
3428 			BUMP_MIB(&ip_mib, ipOutDiscards);
3429 			return;
3430 		}
3431 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3432 
3433 		/* This is not a secure packet */
3434 		ii->ipsec_in_secure = B_FALSE;
3435 		/*
3436 		 * For trusted extensions using a shared IP address we can
3437 		 * send using any zoneid.
3438 		 */
3439 		if (zoneid == ALL_ZONES)
3440 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3441 		else
3442 			ii->ipsec_in_zoneid = zoneid;
3443 		ipsec_mp->b_cont = mp;
3444 		ipha = (ipha_t *)mp->b_rptr;
3445 		/*
3446 		 * Convert the IPSEC_IN to IPSEC_OUT.
3447 		 */
3448 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3449 			BUMP_MIB(&ip_mib, ipOutDiscards);
3450 			return;
3451 		}
3452 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3453 	}
3454 
3455 	/* Remember our eventual destination */
3456 	dst = ipha->ipha_src;
3457 
3458 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3459 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3460 	if (ire != NULL &&
3461 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3462 		src = ipha->ipha_dst;
3463 	} else if (!xmit_if_on) {
3464 		if (ire != NULL)
3465 			ire_refrele(ire);
3466 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3467 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3468 		if (ire == NULL) {
3469 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3470 			freemsg(ipsec_mp);
3471 			return;
3472 		}
3473 		src = ire->ire_src_addr;
3474 	} else {
3475 		ipif_t	*ipif = NULL;
3476 		ill_t	*ill;
3477 		/*
3478 		 * This must be an ICMP error coming from
3479 		 * ip_mrtun_forward(). The src addr should
3480 		 * be equal to the IP-addr of the outgoing
3481 		 * interface.
3482 		 */
3483 		if (io == NULL) {
3484 			/* This is not a IPSEC_OUT type control msg */
3485 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3486 			freemsg(ipsec_mp);
3487 			return;
3488 		}
3489 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3490 		    NULL, NULL, NULL, NULL);
3491 		if (ill != NULL) {
3492 			ipif = ipif_get_next_ipif(NULL, ill);
3493 			ill_refrele(ill);
3494 		}
3495 		if (ipif == NULL) {
3496 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3497 			freemsg(ipsec_mp);
3498 			return;
3499 		}
3500 		src = ipif->ipif_src_addr;
3501 		ipif_refrele(ipif);
3502 	}
3503 
3504 	if (ire != NULL)
3505 		ire_refrele(ire);
3506 
3507 	/*
3508 	 * Check if we can send back more then 8 bytes in addition
3509 	 * to the IP header. We will include as much as 64 bytes.
3510 	 */
3511 	len_needed = IPH_HDR_LENGTH(ipha);
3512 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3513 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3514 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3515 	}
3516 	len_needed += ip_icmp_return;
3517 	msg_len = msgdsize(mp);
3518 	if (msg_len > len_needed) {
3519 		(void) adjmsg(mp, len_needed - msg_len);
3520 		msg_len = len_needed;
3521 	}
3522 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3523 	if (mp1 == NULL) {
3524 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3525 		freemsg(ipsec_mp);
3526 		return;
3527 	}
3528 	/*
3529 	 * On an unlabeled system, dblks don't necessarily have creds.
3530 	 */
3531 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3532 	if (DB_CRED(mp) != NULL)
3533 		mblk_setcred(mp1, DB_CRED(mp));
3534 	mp1->b_cont = mp;
3535 	mp = mp1;
3536 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3537 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3538 	    io->ipsec_out_type == IPSEC_OUT);
3539 	ipsec_mp->b_cont = mp;
3540 
3541 	/*
3542 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3543 	 * node generates be accepted in peace by all on-host destinations.
3544 	 * If we do NOT assume that all on-host destinations trust
3545 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3546 	 * (Look for ipsec_out_icmp_loopback).
3547 	 */
3548 	io->ipsec_out_icmp_loopback = B_TRUE;
3549 
3550 	ipha = (ipha_t *)mp->b_rptr;
3551 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3552 	*ipha = icmp_ipha;
3553 	ipha->ipha_src = src;
3554 	ipha->ipha_dst = dst;
3555 	ipha->ipha_ttl = ip_def_ttl;
3556 	msg_len += sizeof (icmp_ipha) + len;
3557 	if (msg_len > IP_MAXPACKET) {
3558 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3559 		msg_len = IP_MAXPACKET;
3560 	}
3561 	ipha->ipha_length = htons((uint16_t)msg_len);
3562 	icmph = (icmph_t *)&ipha[1];
3563 	bcopy(stuff, icmph, len);
3564 	icmph->icmph_checksum = 0;
3565 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3566 	if (icmph->icmph_checksum == 0)
3567 		icmph->icmph_checksum = 0xFFFF;
3568 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3569 	put(q, ipsec_mp);
3570 }
3571 
3572 /*
3573  * Determine if an ICMP error packet can be sent given the rate limit.
3574  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3575  * in milliseconds) and a burst size. Burst size number of packets can
3576  * be sent arbitrarely closely spaced.
3577  * The state is tracked using two variables to implement an approximate
3578  * token bucket filter:
3579  *	icmp_pkt_err_last - lbolt value when the last burst started
3580  *	icmp_pkt_err_sent - number of packets sent in current burst
3581  */
3582 boolean_t
3583 icmp_err_rate_limit(void)
3584 {
3585 	clock_t now = TICK_TO_MSEC(lbolt);
3586 	uint_t refilled; /* Number of packets refilled in tbf since last */
3587 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3588 
3589 	if (err_interval == 0)
3590 		return (B_FALSE);
3591 
3592 	if (icmp_pkt_err_last > now) {
3593 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3594 		icmp_pkt_err_last = 0;
3595 		icmp_pkt_err_sent = 0;
3596 	}
3597 	/*
3598 	 * If we are in a burst update the token bucket filter.
3599 	 * Update the "last" time to be close to "now" but make sure
3600 	 * we don't loose precision.
3601 	 */
3602 	if (icmp_pkt_err_sent != 0) {
3603 		refilled = (now - icmp_pkt_err_last)/err_interval;
3604 		if (refilled > icmp_pkt_err_sent) {
3605 			icmp_pkt_err_sent = 0;
3606 		} else {
3607 			icmp_pkt_err_sent -= refilled;
3608 			icmp_pkt_err_last += refilled * err_interval;
3609 		}
3610 	}
3611 	if (icmp_pkt_err_sent == 0) {
3612 		/* Start of new burst */
3613 		icmp_pkt_err_last = now;
3614 	}
3615 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3616 		icmp_pkt_err_sent++;
3617 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3618 		    icmp_pkt_err_sent));
3619 		return (B_FALSE);
3620 	}
3621 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3622 	return (B_TRUE);
3623 }
3624 
3625 /*
3626  * Check if it is ok to send an IPv4 ICMP error packet in
3627  * response to the IPv4 packet in mp.
3628  * Free the message and return null if no
3629  * ICMP error packet should be sent.
3630  */
3631 static mblk_t *
3632 icmp_pkt_err_ok(mblk_t *mp)
3633 {
3634 	icmph_t	*icmph;
3635 	ipha_t	*ipha;
3636 	uint_t	len_needed;
3637 	ire_t	*src_ire;
3638 	ire_t	*dst_ire;
3639 
3640 	if (!mp)
3641 		return (NULL);
3642 	ipha = (ipha_t *)mp->b_rptr;
3643 	if (ip_csum_hdr(ipha)) {
3644 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3645 		freemsg(mp);
3646 		return (NULL);
3647 	}
3648 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3649 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3650 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3651 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3652 	if (src_ire != NULL || dst_ire != NULL ||
3653 	    CLASSD(ipha->ipha_dst) ||
3654 	    CLASSD(ipha->ipha_src) ||
3655 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3656 		/* Note: only errors to the fragment with offset 0 */
3657 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3658 		freemsg(mp);
3659 		if (src_ire != NULL)
3660 			ire_refrele(src_ire);
3661 		if (dst_ire != NULL)
3662 			ire_refrele(dst_ire);
3663 		return (NULL);
3664 	}
3665 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3666 		/*
3667 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3668 		 * errors in response to any ICMP errors.
3669 		 */
3670 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3671 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3672 			if (!pullupmsg(mp, len_needed)) {
3673 				BUMP_MIB(&icmp_mib, icmpInErrors);
3674 				freemsg(mp);
3675 				return (NULL);
3676 			}
3677 			ipha = (ipha_t *)mp->b_rptr;
3678 		}
3679 		icmph = (icmph_t *)
3680 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3681 		switch (icmph->icmph_type) {
3682 		case ICMP_DEST_UNREACHABLE:
3683 		case ICMP_SOURCE_QUENCH:
3684 		case ICMP_TIME_EXCEEDED:
3685 		case ICMP_PARAM_PROBLEM:
3686 		case ICMP_REDIRECT:
3687 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3688 			freemsg(mp);
3689 			return (NULL);
3690 		default:
3691 			break;
3692 		}
3693 	}
3694 	/*
3695 	 * If this is a labeled system, then check to see if we're allowed to
3696 	 * send a response to this particular sender.  If not, then just drop.
3697 	 */
3698 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3699 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3700 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3701 		freemsg(mp);
3702 		return (NULL);
3703 	}
3704 	if (icmp_err_rate_limit()) {
3705 		/*
3706 		 * Only send ICMP error packets every so often.
3707 		 * This should be done on a per port/source basis,
3708 		 * but for now this will suffice.
3709 		 */
3710 		freemsg(mp);
3711 		return (NULL);
3712 	}
3713 	return (mp);
3714 }
3715 
3716 /*
3717  * Generate an ICMP redirect message.
3718  */
3719 static void
3720 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3721 {
3722 	icmph_t	icmph;
3723 
3724 	/*
3725 	 * We are called from ip_rput where we could
3726 	 * not have attached an IPSEC_IN.
3727 	 */
3728 	ASSERT(mp->b_datap->db_type == M_DATA);
3729 
3730 	if (!(mp = icmp_pkt_err_ok(mp))) {
3731 		return;
3732 	}
3733 
3734 	bzero(&icmph, sizeof (icmph_t));
3735 	icmph.icmph_type = ICMP_REDIRECT;
3736 	icmph.icmph_code = 1;
3737 	icmph.icmph_rd_gateway = gateway;
3738 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3739 	/* Redirects sent by router, and router is global zone */
3740 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID);
3741 }
3742 
3743 /*
3744  * Generate an ICMP time exceeded message.
3745  */
3746 void
3747 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3748 {
3749 	icmph_t	icmph;
3750 	boolean_t mctl_present;
3751 	mblk_t *first_mp;
3752 
3753 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3754 
3755 	if (!(mp = icmp_pkt_err_ok(mp))) {
3756 		if (mctl_present)
3757 			freeb(first_mp);
3758 		return;
3759 	}
3760 
3761 	bzero(&icmph, sizeof (icmph_t));
3762 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3763 	icmph.icmph_code = code;
3764 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3765 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3766 }
3767 
3768 /*
3769  * Generate an ICMP unreachable message.
3770  */
3771 void
3772 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3773 {
3774 	icmph_t	icmph;
3775 	mblk_t *first_mp;
3776 	boolean_t mctl_present;
3777 
3778 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3779 
3780 	if (!(mp = icmp_pkt_err_ok(mp))) {
3781 		if (mctl_present)
3782 			freeb(first_mp);
3783 		return;
3784 	}
3785 
3786 	bzero(&icmph, sizeof (icmph_t));
3787 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3788 	icmph.icmph_code = code;
3789 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3790 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3791 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3792 	    zoneid);
3793 }
3794 
3795 /*
3796  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3797  * duplicate.  As long as someone else holds the address, the interface will
3798  * stay down.  When that conflict goes away, the interface is brought back up.
3799  * This is done so that accidental shutdowns of addresses aren't made
3800  * permanent.  Your server will recover from a failure.
3801  *
3802  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3803  * user space process (dhcpagent).
3804  *
3805  * Recovery completes if ARP reports that the address is now ours (via
3806  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3807  *
3808  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3809  */
3810 static void
3811 ipif_dup_recovery(void *arg)
3812 {
3813 	ipif_t *ipif = arg;
3814 	ill_t *ill = ipif->ipif_ill;
3815 	mblk_t *arp_add_mp;
3816 	mblk_t *arp_del_mp;
3817 	area_t *area;
3818 
3819 	ipif->ipif_recovery_id = 0;
3820 
3821 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3822 	    (ipif->ipif_flags & IPIF_POINTOPOINT)) {
3823 		/* No reason to try to bring this address back. */
3824 		return;
3825 	}
3826 
3827 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3828 		goto alloc_fail;
3829 
3830 	if (ipif->ipif_arp_del_mp == NULL) {
3831 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3832 			goto alloc_fail;
3833 		ipif->ipif_arp_del_mp = arp_del_mp;
3834 	}
3835 
3836 	/* Setting the 'unverified' flag restarts DAD */
3837 	area = (area_t *)arp_add_mp->b_rptr;
3838 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3839 	    ACE_F_UNVERIFIED;
3840 	putnext(ill->ill_rq, arp_add_mp);
3841 	return;
3842 
3843 alloc_fail:
3844 	/* On allocation failure, just restart the timer */
3845 	freemsg(arp_add_mp);
3846 	if (ip_dup_recovery > 0) {
3847 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3848 		    MSEC_TO_TICK(ip_dup_recovery));
3849 	}
3850 }
3851 
3852 /*
3853  * This is for exclusive changes due to ARP.  Either tear down an interface due
3854  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3855  */
3856 /* ARGSUSED */
3857 static void
3858 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3859 {
3860 	ill_t	*ill = rq->q_ptr;
3861 	arh_t *arh;
3862 	ipaddr_t src;
3863 	ipif_t	*ipif;
3864 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3865 	char hbuf[MAC_STR_LEN];
3866 	char sbuf[INET_ADDRSTRLEN];
3867 	const char *failtype;
3868 	boolean_t bring_up;
3869 
3870 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3871 	case AR_CN_READY:
3872 		failtype = NULL;
3873 		bring_up = B_TRUE;
3874 		break;
3875 	case AR_CN_FAILED:
3876 		failtype = "in use";
3877 		bring_up = B_FALSE;
3878 		break;
3879 	default:
3880 		failtype = "claimed";
3881 		bring_up = B_FALSE;
3882 		break;
3883 	}
3884 
3885 	arh = (arh_t *)mp->b_cont->b_rptr;
3886 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3887 
3888 	/* Handle failures due to probes */
3889 	if (src == 0) {
3890 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3891 		    IP_ADDR_LEN);
3892 	}
3893 
3894 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3895 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3896 	    sizeof (hbuf));
3897 	(void) ip_dot_addr(src, sbuf);
3898 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3899 
3900 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3901 		    ipif->ipif_lcl_addr != src) {
3902 			continue;
3903 		}
3904 
3905 		/*
3906 		 * If we failed on a recovery probe, then restart the timer to
3907 		 * try again later.
3908 		 */
3909 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3910 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3911 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3912 		    ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0) {
3913 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3914 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3915 			continue;
3916 		}
3917 
3918 		/*
3919 		 * If what we're trying to do has already been done, then do
3920 		 * nothing.
3921 		 */
3922 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3923 			continue;
3924 
3925 		if (ipif->ipif_id != 0) {
3926 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3927 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3928 			    ipif->ipif_id);
3929 		}
3930 		if (failtype == NULL) {
3931 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3932 			    ibuf);
3933 		} else {
3934 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3935 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3936 		}
3937 
3938 		if (bring_up) {
3939 			ASSERT(ill->ill_dl_up);
3940 			/*
3941 			 * Free up the ARP delete message so we can allocate
3942 			 * a fresh one through the normal path.
3943 			 */
3944 			freemsg(ipif->ipif_arp_del_mp);
3945 			ipif->ipif_arp_del_mp = NULL;
3946 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3947 			    EINPROGRESS) {
3948 				ipif->ipif_addr_ready = 1;
3949 				(void) ipif_up_done(ipif);
3950 			}
3951 			continue;
3952 		}
3953 
3954 		mutex_enter(&ill->ill_lock);
3955 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3956 		ipif->ipif_flags |= IPIF_DUPLICATE;
3957 		ill->ill_ipif_dup_count++;
3958 		mutex_exit(&ill->ill_lock);
3959 		/*
3960 		 * Already exclusive on the ill; no need to handle deferred
3961 		 * processing here.
3962 		 */
3963 		(void) ipif_down(ipif, NULL, NULL);
3964 		ipif_down_tail(ipif);
3965 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3966 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3967 		    ip_dup_recovery > 0) {
3968 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3969 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3970 		}
3971 	}
3972 	freemsg(mp);
3973 }
3974 
3975 /* ARGSUSED */
3976 static void
3977 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3978 {
3979 	ill_t	*ill = rq->q_ptr;
3980 	arh_t *arh;
3981 	ipaddr_t src;
3982 	ipif_t	*ipif;
3983 
3984 	arh = (arh_t *)mp->b_cont->b_rptr;
3985 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3986 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3987 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3988 			(void) ipif_resolver_up(ipif, Res_act_defend);
3989 	}
3990 	freemsg(mp);
3991 }
3992 
3993 /*
3994  * News from ARP.  ARP sends notification of interesting events down
3995  * to its clients using M_CTL messages with the interesting ARP packet
3996  * attached via b_cont.
3997  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3998  * queue as opposed to ARP sending the message to all the clients, i.e. all
3999  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
4000  * table if a cache IRE is found to delete all the entries for the address in
4001  * the packet.
4002  */
4003 static void
4004 ip_arp_news(queue_t *q, mblk_t *mp)
4005 {
4006 	arcn_t		*arcn;
4007 	arh_t		*arh;
4008 	ire_t		*ire = NULL;
4009 	char		hbuf[MAC_STR_LEN];
4010 	char		sbuf[INET_ADDRSTRLEN];
4011 	ipaddr_t	src;
4012 	in6_addr_t	v6src;
4013 	boolean_t	isv6 = B_FALSE;
4014 	ipif_t		*ipif;
4015 	ill_t		*ill;
4016 
4017 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
4018 		if (q->q_next) {
4019 			putnext(q, mp);
4020 		} else
4021 			freemsg(mp);
4022 		return;
4023 	}
4024 	arh = (arh_t *)mp->b_cont->b_rptr;
4025 	/* Is it one we are interested in? */
4026 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
4027 		isv6 = B_TRUE;
4028 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
4029 		    IPV6_ADDR_LEN);
4030 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
4031 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
4032 		    IP_ADDR_LEN);
4033 	} else {
4034 		freemsg(mp);
4035 		return;
4036 	}
4037 
4038 	ill = q->q_ptr;
4039 
4040 	arcn = (arcn_t *)mp->b_rptr;
4041 	switch (arcn->arcn_code) {
4042 	case AR_CN_BOGON:
4043 		/*
4044 		 * Someone is sending ARP packets with a source protocol
4045 		 * address that we have published and for which we believe our
4046 		 * entry is authoritative and (when ill_arp_extend is set)
4047 		 * verified to be unique on the network.
4048 		 *
4049 		 * The ARP module internally handles the cases where the sender
4050 		 * is just probing (for DAD) and where the hardware address of
4051 		 * a non-authoritative entry has changed.  Thus, these are the
4052 		 * real conflicts, and we have to do resolution.
4053 		 *
4054 		 * We back away quickly from the address if it's from DHCP or
4055 		 * otherwise temporary and hasn't been used recently (or at
4056 		 * all).  We'd like to include "deprecated" addresses here as
4057 		 * well (as there's no real reason to defend something we're
4058 		 * discarding), but IPMP "reuses" this flag to mean something
4059 		 * other than the standard meaning.
4060 		 *
4061 		 * If the ARP module above is not extended (meaning that it
4062 		 * doesn't know how to defend the address), then we just log
4063 		 * the problem as we always did and continue on.  It's not
4064 		 * right, but there's little else we can do, and those old ATM
4065 		 * users are going away anyway.
4066 		 */
4067 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4068 		    hbuf, sizeof (hbuf));
4069 		(void) ip_dot_addr(src, sbuf);
4070 		if (isv6)
4071 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
4072 		else
4073 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
4074 
4075 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4076 			uint32_t now;
4077 			uint32_t maxage;
4078 			clock_t lused;
4079 			uint_t maxdefense;
4080 			uint_t defs;
4081 
4082 			/*
4083 			 * First, figure out if this address hasn't been used
4084 			 * in a while.  If it hasn't, then it's a better
4085 			 * candidate for abandoning.
4086 			 */
4087 			ipif = ire->ire_ipif;
4088 			ASSERT(ipif != NULL);
4089 			now = gethrestime_sec();
4090 			maxage = now - ire->ire_create_time;
4091 			if (maxage > ip_max_temp_idle)
4092 				maxage = ip_max_temp_idle;
4093 			lused = drv_hztousec(ddi_get_lbolt() -
4094 			    ire->ire_last_used_time) / MICROSEC + 1;
4095 			if (lused >= maxage && (ipif->ipif_flags &
4096 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4097 				maxdefense = ip_max_temp_defend;
4098 			else
4099 				maxdefense = ip_max_defend;
4100 
4101 			/*
4102 			 * Now figure out how many times we've defended
4103 			 * ourselves.  Ignore defenses that happened long in
4104 			 * the past.
4105 			 */
4106 			mutex_enter(&ire->ire_lock);
4107 			if ((defs = ire->ire_defense_count) > 0 &&
4108 			    now - ire->ire_defense_time > ip_defend_interval) {
4109 				ire->ire_defense_count = defs = 0;
4110 			}
4111 			ire->ire_defense_count++;
4112 			ire->ire_defense_time = now;
4113 			mutex_exit(&ire->ire_lock);
4114 			ill_refhold(ill);
4115 			ire_refrele(ire);
4116 
4117 			/*
4118 			 * If we've defended ourselves too many times already,
4119 			 * then give up and tear down the interface(s) using
4120 			 * this address.  Otherwise, defend by sending out a
4121 			 * gratuitous ARP.
4122 			 */
4123 			if (defs >= maxdefense && ill->ill_arp_extend) {
4124 				(void) qwriter_ip(NULL, ill, q, mp,
4125 				    ip_arp_excl, CUR_OP, B_FALSE);
4126 			} else {
4127 				cmn_err(CE_WARN,
4128 				    "node %s is using our IP address %s on %s",
4129 				    hbuf, sbuf, ill->ill_name);
4130 				/*
4131 				 * If this is an old (ATM) ARP module, then
4132 				 * don't try to defend the address.  Remain
4133 				 * compatible with the old behavior.  Defend
4134 				 * only with new ARP.
4135 				 */
4136 				if (ill->ill_arp_extend) {
4137 					(void) qwriter_ip(NULL, ill, q, mp,
4138 					    ip_arp_defend, CUR_OP, B_FALSE);
4139 				} else {
4140 					ill_refrele(ill);
4141 				}
4142 			}
4143 			return;
4144 		}
4145 		cmn_err(CE_WARN,
4146 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4147 		    hbuf, sbuf, ill->ill_name);
4148 		if (ire != NULL)
4149 			ire_refrele(ire);
4150 		break;
4151 	case AR_CN_ANNOUNCE:
4152 		if (isv6) {
4153 			/*
4154 			 * For XRESOLV interfaces.
4155 			 * Delete the IRE cache entry and NCE for this
4156 			 * v6 address
4157 			 */
4158 			ip_ire_clookup_and_delete_v6(&v6src);
4159 			/*
4160 			 * If v6src is a non-zero, it's a router address
4161 			 * as below. Do the same sort of thing to clean
4162 			 * out off-net IRE_CACHE entries that go through
4163 			 * the router.
4164 			 */
4165 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4166 				ire_walk_v6(ire_delete_cache_gw_v6,
4167 				    (char *)&v6src, ALL_ZONES);
4168 			}
4169 		} else {
4170 			nce_hw_map_t hwm;
4171 
4172 			/*
4173 			 * ARP gives us a copy of any packet where it thinks
4174 			 * the address has changed, so that we can update our
4175 			 * caches.  We're responsible for caching known answers
4176 			 * in the current design.  We check whether the
4177 			 * hardware address really has changed in all of our
4178 			 * entries that have cached this mapping, and if so, we
4179 			 * blow them away.  This way we will immediately pick
4180 			 * up the rare case of a host changing hardware
4181 			 * address.
4182 			 */
4183 			if (src == 0)
4184 				break;
4185 			hwm.hwm_addr = src;
4186 			hwm.hwm_hwlen = arh->arh_hlen;
4187 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4188 			ndp_walk_common(&ndp4, NULL,
4189 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4190 		}
4191 		break;
4192 	case AR_CN_READY:
4193 		/* No external v6 resolver has a contract to use this */
4194 		if (isv6)
4195 			break;
4196 		/* If the link is down, we'll retry this later */
4197 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4198 			break;
4199 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4200 		    NULL, NULL);
4201 		if (ipif != NULL) {
4202 			/*
4203 			 * If this is a duplicate recovery, then we now need to
4204 			 * go exclusive to bring this thing back up.
4205 			 */
4206 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4207 			    IPIF_DUPLICATE) {
4208 				ipif_refrele(ipif);
4209 				ill_refhold(ill);
4210 				(void) qwriter_ip(NULL, ill, q, mp,
4211 				    ip_arp_excl, CUR_OP, B_FALSE);
4212 				return;
4213 			}
4214 			/*
4215 			 * If this is the first notice that this address is
4216 			 * ready, then let the user know now.
4217 			 */
4218 			if ((ipif->ipif_flags & IPIF_UP) &&
4219 			    !ipif->ipif_addr_ready) {
4220 				ipif_mask_reply(ipif);
4221 				ip_rts_ifmsg(ipif);
4222 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4223 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4224 			}
4225 			ipif->ipif_addr_ready = 1;
4226 			ipif_refrele(ipif);
4227 		}
4228 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp));
4229 		if (ire != NULL) {
4230 			ire->ire_defense_count = 0;
4231 			ire_refrele(ire);
4232 		}
4233 		break;
4234 	case AR_CN_FAILED:
4235 		/* No external v6 resolver has a contract to use this */
4236 		if (isv6)
4237 			break;
4238 		ill_refhold(ill);
4239 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4240 		    B_FALSE);
4241 		return;
4242 	}
4243 	freemsg(mp);
4244 }
4245 
4246 /*
4247  * Create a mblk suitable for carrying the interface index and/or source link
4248  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4249  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4250  * application.
4251  */
4252 mblk_t *
4253 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
4254 {
4255 	mblk_t		*mp;
4256 	in_pktinfo_t	*pinfo;
4257 	ipha_t *ipha;
4258 	struct ether_header *pether;
4259 
4260 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
4261 	if (mp == NULL) {
4262 		ip1dbg(("ip_add_info: allocation failure.\n"));
4263 		return (data_mp);
4264 	}
4265 
4266 	ipha	= (ipha_t *)data_mp->b_rptr;
4267 	pinfo = (in_pktinfo_t *)mp->b_rptr;
4268 	bzero(pinfo, sizeof (in_pktinfo_t));
4269 	pinfo->in_pkt_flags = (uchar_t)flags;
4270 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4271 
4272 	if (flags & IPF_RECVIF)
4273 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4274 
4275 	pether = (struct ether_header *)((char *)ipha
4276 	    - sizeof (struct ether_header));
4277 	/*
4278 	 * Make sure the interface is an ethernet type, since this option
4279 	 * is currently supported only on this type of interface. Also make
4280 	 * sure we are pointing correctly above db_base.
4281 	 */
4282 
4283 	if ((flags & IPF_RECVSLLA) &&
4284 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4285 	    (ill->ill_type == IFT_ETHER) &&
4286 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4287 
4288 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
4289 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4290 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
4291 	} else {
4292 		/*
4293 		 * Clear the bit. Indicate to upper layer that IP is not
4294 		 * sending this ancillary info.
4295 		 */
4296 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
4297 	}
4298 
4299 	mp->b_datap->db_type = M_CTL;
4300 	mp->b_wptr += sizeof (in_pktinfo_t);
4301 	mp->b_cont = data_mp;
4302 
4303 	return (mp);
4304 }
4305 
4306 /*
4307  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4308  * part of the bind request.
4309  */
4310 
4311 boolean_t
4312 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4313 {
4314 	ipsec_in_t *ii;
4315 
4316 	ASSERT(policy_mp != NULL);
4317 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4318 
4319 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4320 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4321 
4322 	connp->conn_policy = ii->ipsec_in_policy;
4323 	ii->ipsec_in_policy = NULL;
4324 
4325 	if (ii->ipsec_in_action != NULL) {
4326 		if (connp->conn_latch == NULL) {
4327 			connp->conn_latch = iplatch_create();
4328 			if (connp->conn_latch == NULL)
4329 				return (B_FALSE);
4330 		}
4331 		ipsec_latch_inbound(connp->conn_latch, ii);
4332 	}
4333 	return (B_TRUE);
4334 }
4335 
4336 /*
4337  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4338  * and to arrange for power-fanout assist.  The ULP is identified by
4339  * adding a single byte at the end of the original bind message.
4340  * A ULP other than UDP or TCP that wishes to be recognized passes
4341  * down a bind with a zero length address.
4342  *
4343  * The binding works as follows:
4344  * - A zero byte address means just bind to the protocol.
4345  * - A four byte address is treated as a request to validate
4346  *   that the address is a valid local address, appropriate for
4347  *   an application to bind to. This does not affect any fanout
4348  *   information in IP.
4349  * - A sizeof sin_t byte address is used to bind to only the local address
4350  *   and port.
4351  * - A sizeof ipa_conn_t byte address contains complete fanout information
4352  *   consisting of local and remote addresses and ports.  In
4353  *   this case, the addresses are both validated as appropriate
4354  *   for this operation, and, if so, the information is retained
4355  *   for use in the inbound fanout.
4356  *
4357  * The ULP (except in the zero-length bind) can append an
4358  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4359  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4360  * a copy of the source or destination IRE (source for local bind;
4361  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4362  * policy information contained should be copied on to the conn.
4363  *
4364  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4365  */
4366 mblk_t *
4367 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4368 {
4369 	ssize_t		len;
4370 	struct T_bind_req	*tbr;
4371 	sin_t		*sin;
4372 	ipa_conn_t	*ac;
4373 	uchar_t		*ucp;
4374 	mblk_t		*mp1;
4375 	boolean_t	ire_requested;
4376 	boolean_t	ipsec_policy_set = B_FALSE;
4377 	int		error = 0;
4378 	int		protocol;
4379 	ipa_conn_x_t	*acx;
4380 
4381 	ASSERT(!connp->conn_af_isv6);
4382 	connp->conn_pkt_isv6 = B_FALSE;
4383 
4384 	len = MBLKL(mp);
4385 	if (len < (sizeof (*tbr) + 1)) {
4386 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4387 		    "ip_bind: bogus msg, len %ld", len);
4388 		/* XXX: Need to return something better */
4389 		goto bad_addr;
4390 	}
4391 	/* Back up and extract the protocol identifier. */
4392 	mp->b_wptr--;
4393 	protocol = *mp->b_wptr & 0xFF;
4394 	tbr = (struct T_bind_req *)mp->b_rptr;
4395 	/* Reset the message type in preparation for shipping it back. */
4396 	DB_TYPE(mp) = M_PCPROTO;
4397 
4398 	connp->conn_ulp = (uint8_t)protocol;
4399 
4400 	/*
4401 	 * Check for a zero length address.  This is from a protocol that
4402 	 * wants to register to receive all packets of its type.
4403 	 */
4404 	if (tbr->ADDR_length == 0) {
4405 		/*
4406 		 * These protocols are now intercepted in ip_bind_v6().
4407 		 * Reject protocol-level binds here for now.
4408 		 *
4409 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4410 		 * so that the protocol type cannot be SCTP.
4411 		 */
4412 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4413 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4414 			goto bad_addr;
4415 		}
4416 
4417 		/*
4418 		 *
4419 		 * The udp module never sends down a zero-length address,
4420 		 * and allowing this on a labeled system will break MLP
4421 		 * functionality.
4422 		 */
4423 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4424 			goto bad_addr;
4425 
4426 		if (connp->conn_mac_exempt)
4427 			goto bad_addr;
4428 
4429 		/* No hash here really.  The table is big enough. */
4430 		connp->conn_srcv6 = ipv6_all_zeros;
4431 
4432 		ipcl_proto_insert(connp, protocol);
4433 
4434 		tbr->PRIM_type = T_BIND_ACK;
4435 		return (mp);
4436 	}
4437 
4438 	/* Extract the address pointer from the message. */
4439 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4440 	    tbr->ADDR_length);
4441 	if (ucp == NULL) {
4442 		ip1dbg(("ip_bind: no address\n"));
4443 		goto bad_addr;
4444 	}
4445 	if (!OK_32PTR(ucp)) {
4446 		ip1dbg(("ip_bind: unaligned address\n"));
4447 		goto bad_addr;
4448 	}
4449 	/*
4450 	 * Check for trailing mps.
4451 	 */
4452 
4453 	mp1 = mp->b_cont;
4454 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4455 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4456 
4457 	switch (tbr->ADDR_length) {
4458 	default:
4459 		ip1dbg(("ip_bind: bad address length %d\n",
4460 		    (int)tbr->ADDR_length));
4461 		goto bad_addr;
4462 
4463 	case IP_ADDR_LEN:
4464 		/* Verification of local address only */
4465 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4466 		    ire_requested, ipsec_policy_set, B_FALSE);
4467 		break;
4468 
4469 	case sizeof (sin_t):
4470 		sin = (sin_t *)ucp;
4471 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4472 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4473 		break;
4474 
4475 	case sizeof (ipa_conn_t):
4476 		ac = (ipa_conn_t *)ucp;
4477 		/* For raw socket, the local port is not set. */
4478 		if (ac->ac_lport == 0)
4479 			ac->ac_lport = connp->conn_lport;
4480 		/* Always verify destination reachability. */
4481 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4482 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4483 		    ipsec_policy_set, B_TRUE, B_TRUE);
4484 		break;
4485 
4486 	case sizeof (ipa_conn_x_t):
4487 		acx = (ipa_conn_x_t *)ucp;
4488 		/*
4489 		 * Whether or not to verify destination reachability depends
4490 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4491 		 */
4492 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4493 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4494 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4495 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4496 		break;
4497 	}
4498 	if (error == EINPROGRESS)
4499 		return (NULL);
4500 	else if (error != 0)
4501 		goto bad_addr;
4502 	/*
4503 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4504 	 * We can't do this in ip_bind_insert_ire because the policy
4505 	 * may not have been inherited at that point in time and hence
4506 	 * conn_out_enforce_policy may not be set.
4507 	 */
4508 	mp1 = mp->b_cont;
4509 	if (ire_requested && connp->conn_out_enforce_policy &&
4510 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4511 		ire_t *ire = (ire_t *)mp1->b_rptr;
4512 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4513 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4514 	}
4515 
4516 	/* Send it home. */
4517 	mp->b_datap->db_type = M_PCPROTO;
4518 	tbr->PRIM_type = T_BIND_ACK;
4519 	return (mp);
4520 
4521 bad_addr:
4522 	/*
4523 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4524 	 * a unix errno.
4525 	 */
4526 	if (error > 0)
4527 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4528 	else
4529 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4530 	return (mp);
4531 }
4532 
4533 /*
4534  * Here address is verified to be a valid local address.
4535  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4536  * address is also considered a valid local address.
4537  * In the case of a broadcast/multicast address, however, the
4538  * upper protocol is expected to reset the src address
4539  * to 0 if it sees a IRE_BROADCAST type returned so that
4540  * no packets are emitted with broadcast/multicast address as
4541  * source address (that violates hosts requirements RFC1122)
4542  * The addresses valid for bind are:
4543  *	(1) - INADDR_ANY (0)
4544  *	(2) - IP address of an UP interface
4545  *	(3) - IP address of a DOWN interface
4546  *	(4) - valid local IP broadcast addresses. In this case
4547  *	the conn will only receive packets destined to
4548  *	the specified broadcast address.
4549  *	(5) - a multicast address. In this case
4550  *	the conn will only receive packets destined to
4551  *	the specified multicast address. Note: the
4552  *	application still has to issue an
4553  *	IP_ADD_MEMBERSHIP socket option.
4554  *
4555  * On error, return -1 for TBADADDR otherwise pass the
4556  * errno with TSYSERR reply.
4557  *
4558  * In all the above cases, the bound address must be valid in the current zone.
4559  * When the address is loopback, multicast or broadcast, there might be many
4560  * matching IREs so bind has to look up based on the zone.
4561  *
4562  * Note: lport is in network byte order.
4563  */
4564 int
4565 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4566     boolean_t ire_requested, boolean_t ipsec_policy_set,
4567     boolean_t fanout_insert)
4568 {
4569 	int		error = 0;
4570 	ire_t		*src_ire;
4571 	mblk_t		*policy_mp;
4572 	ipif_t		*ipif;
4573 	zoneid_t	zoneid;
4574 
4575 	if (ipsec_policy_set) {
4576 		policy_mp = mp->b_cont;
4577 	}
4578 
4579 	/*
4580 	 * If it was previously connected, conn_fully_bound would have
4581 	 * been set.
4582 	 */
4583 	connp->conn_fully_bound = B_FALSE;
4584 
4585 	src_ire = NULL;
4586 	ipif = NULL;
4587 
4588 	zoneid = IPCL_ZONEID(connp);
4589 
4590 	if (src_addr) {
4591 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4592 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4593 		/*
4594 		 * If an address other than 0.0.0.0 is requested,
4595 		 * we verify that it is a valid address for bind
4596 		 * Note: Following code is in if-else-if form for
4597 		 * readability compared to a condition check.
4598 		 */
4599 		/* LINTED - statement has no consequent */
4600 		if (IRE_IS_LOCAL(src_ire)) {
4601 			/*
4602 			 * (2) Bind to address of local UP interface
4603 			 */
4604 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4605 			/*
4606 			 * (4) Bind to broadcast address
4607 			 * Note: permitted only from transports that
4608 			 * request IRE
4609 			 */
4610 			if (!ire_requested)
4611 				error = EADDRNOTAVAIL;
4612 		} else {
4613 			/*
4614 			 * (3) Bind to address of local DOWN interface
4615 			 * (ipif_lookup_addr() looks up all interfaces
4616 			 * but we do not get here for UP interfaces
4617 			 * - case (2) above)
4618 			 * We put the protocol byte back into the mblk
4619 			 * since we may come back via ip_wput_nondata()
4620 			 * later with this mblk if ipif_lookup_addr chooses
4621 			 * to defer processing.
4622 			 */
4623 			*mp->b_wptr++ = (char)connp->conn_ulp;
4624 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4625 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4626 			    &error)) != NULL) {
4627 				ipif_refrele(ipif);
4628 			} else if (error == EINPROGRESS) {
4629 				if (src_ire != NULL)
4630 					ire_refrele(src_ire);
4631 				return (EINPROGRESS);
4632 			} else if (CLASSD(src_addr)) {
4633 				error = 0;
4634 				if (src_ire != NULL)
4635 					ire_refrele(src_ire);
4636 				/*
4637 				 * (5) bind to multicast address.
4638 				 * Fake out the IRE returned to upper
4639 				 * layer to be a broadcast IRE.
4640 				 */
4641 				src_ire = ire_ctable_lookup(
4642 				    INADDR_BROADCAST, INADDR_ANY,
4643 				    IRE_BROADCAST, NULL, zoneid, NULL,
4644 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4645 				if (src_ire == NULL || !ire_requested)
4646 					error = EADDRNOTAVAIL;
4647 			} else {
4648 				/*
4649 				 * Not a valid address for bind
4650 				 */
4651 				error = EADDRNOTAVAIL;
4652 			}
4653 			/*
4654 			 * Just to keep it consistent with the processing in
4655 			 * ip_bind_v4()
4656 			 */
4657 			mp->b_wptr--;
4658 		}
4659 		if (error) {
4660 			/* Red Alert!  Attempting to be a bogon! */
4661 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4662 			    ntohl(src_addr)));
4663 			goto bad_addr;
4664 		}
4665 	}
4666 
4667 	/*
4668 	 * Allow setting new policies. For example, disconnects come
4669 	 * down as ipa_t bind. As we would have set conn_policy_cached
4670 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4671 	 * can change after the disconnect.
4672 	 */
4673 	connp->conn_policy_cached = B_FALSE;
4674 
4675 	/*
4676 	 * If not fanout_insert this was just an address verification
4677 	 */
4678 	if (fanout_insert) {
4679 		/*
4680 		 * The addresses have been verified. Time to insert in
4681 		 * the correct fanout list.
4682 		 */
4683 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4684 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4685 		connp->conn_lport = lport;
4686 		connp->conn_fport = 0;
4687 		/*
4688 		 * Do we need to add a check to reject Multicast packets
4689 		 *
4690 		 * We need to make sure that the conn_recv is set to a non-null
4691 		 * value before we insert the conn into the classifier table.
4692 		 * This is to avoid a race with an incoming packet which does an
4693 		 * ipcl_classify().
4694 		 */
4695 		if (*mp->b_wptr == IPPROTO_TCP)
4696 			connp->conn_recv = tcp_conn_request;
4697 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4698 	}
4699 
4700 	if (error == 0) {
4701 		if (ire_requested) {
4702 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4703 				error = -1;
4704 				/* Falls through to bad_addr */
4705 			}
4706 		} else if (ipsec_policy_set) {
4707 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4708 				error = -1;
4709 				/* Falls through to bad_addr */
4710 			}
4711 		}
4712 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4713 		connp->conn_recv = tcp_input;
4714 	}
4715 bad_addr:
4716 	if (error != 0) {
4717 		if (connp->conn_anon_port) {
4718 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4719 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4720 			    B_FALSE);
4721 		}
4722 		connp->conn_mlp_type = mlptSingle;
4723 	}
4724 	if (src_ire != NULL)
4725 		IRE_REFRELE(src_ire);
4726 	if (ipsec_policy_set) {
4727 		ASSERT(policy_mp == mp->b_cont);
4728 		ASSERT(policy_mp != NULL);
4729 		freeb(policy_mp);
4730 		/*
4731 		 * As of now assume that nothing else accompanies
4732 		 * IPSEC_POLICY_SET.
4733 		 */
4734 		mp->b_cont = NULL;
4735 	}
4736 	return (error);
4737 }
4738 
4739 /*
4740  * Verify that both the source and destination addresses
4741  * are valid.  If verify_dst is false, then the destination address may be
4742  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4743  * destination reachability, while tunnels do not.
4744  * Note that we allow connect to broadcast and multicast
4745  * addresses when ire_requested is set. Thus the ULP
4746  * has to check for IRE_BROADCAST and multicast.
4747  *
4748  * Returns zero if ok.
4749  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4750  * (for use with TSYSERR reply).
4751  *
4752  * Note: lport and fport are in network byte order.
4753  */
4754 int
4755 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4756     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4757     boolean_t ire_requested, boolean_t ipsec_policy_set,
4758     boolean_t fanout_insert, boolean_t verify_dst)
4759 {
4760 	ire_t		*src_ire;
4761 	ire_t		*dst_ire;
4762 	int		error = 0;
4763 	int 		protocol;
4764 	mblk_t		*policy_mp;
4765 	ire_t		*sire = NULL;
4766 	ire_t		*md_dst_ire = NULL;
4767 	ire_t		*lso_dst_ire = NULL;
4768 	ill_t		*ill = NULL;
4769 	zoneid_t	zoneid;
4770 	ipaddr_t	src_addr = *src_addrp;
4771 
4772 	src_ire = dst_ire = NULL;
4773 	protocol = *mp->b_wptr & 0xFF;
4774 
4775 	/*
4776 	 * If we never got a disconnect before, clear it now.
4777 	 */
4778 	connp->conn_fully_bound = B_FALSE;
4779 
4780 	if (ipsec_policy_set) {
4781 		policy_mp = mp->b_cont;
4782 	}
4783 
4784 	zoneid = IPCL_ZONEID(connp);
4785 
4786 	if (CLASSD(dst_addr)) {
4787 		/* Pick up an IRE_BROADCAST */
4788 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4789 		    NULL, zoneid, MBLK_GETLABEL(mp),
4790 		    (MATCH_IRE_RECURSIVE |
4791 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4792 		    MATCH_IRE_SECATTR));
4793 	} else {
4794 		/*
4795 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4796 		 * and onlink ipif is not found set ENETUNREACH error.
4797 		 */
4798 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4799 			ipif_t *ipif;
4800 
4801 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4802 			    dst_addr : connp->conn_nexthop_v4,
4803 			    connp->conn_zoneid);
4804 			if (ipif == NULL) {
4805 				error = ENETUNREACH;
4806 				goto bad_addr;
4807 			}
4808 			ipif_refrele(ipif);
4809 		}
4810 
4811 		if (connp->conn_nexthop_set) {
4812 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4813 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4814 			    MATCH_IRE_SECATTR);
4815 		} else {
4816 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4817 			    &sire, zoneid, MBLK_GETLABEL(mp),
4818 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4819 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4820 			    MATCH_IRE_SECATTR));
4821 		}
4822 	}
4823 	/*
4824 	 * dst_ire can't be a broadcast when not ire_requested.
4825 	 * We also prevent ire's with src address INADDR_ANY to
4826 	 * be used, which are created temporarily for
4827 	 * sending out packets from endpoints that have
4828 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4829 	 * reachable.  If verify_dst is false, the destination needn't be
4830 	 * reachable.
4831 	 *
4832 	 * If we match on a reject or black hole, then we've got a
4833 	 * local failure.  May as well fail out the connect() attempt,
4834 	 * since it's never going to succeed.
4835 	 */
4836 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4837 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4838 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4839 		/*
4840 		 * If we're verifying destination reachability, we always want
4841 		 * to complain here.
4842 		 *
4843 		 * If we're not verifying destination reachability but the
4844 		 * destination has a route, we still want to fail on the
4845 		 * temporary address and broadcast address tests.
4846 		 */
4847 		if (verify_dst || (dst_ire != NULL)) {
4848 			if (ip_debug > 2) {
4849 				pr_addr_dbg("ip_bind_connected: bad connected "
4850 				    "dst %s\n", AF_INET, &dst_addr);
4851 			}
4852 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4853 				error = ENETUNREACH;
4854 			else
4855 				error = EHOSTUNREACH;
4856 			goto bad_addr;
4857 		}
4858 	}
4859 
4860 	/*
4861 	 * We now know that routing will allow us to reach the destination.
4862 	 * Check whether Trusted Solaris policy allows communication with this
4863 	 * host, and pretend that the destination is unreachable if not.
4864 	 *
4865 	 * This is never a problem for TCP, since that transport is known to
4866 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4867 	 * handling.  If the remote is unreachable, it will be detected at that
4868 	 * point, so there's no reason to check it here.
4869 	 *
4870 	 * Note that for sendto (and other datagram-oriented friends), this
4871 	 * check is done as part of the data path label computation instead.
4872 	 * The check here is just to make non-TCP connect() report the right
4873 	 * error.
4874 	 */
4875 	if (dst_ire != NULL && is_system_labeled() &&
4876 	    !IPCL_IS_TCP(connp) &&
4877 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4878 	    connp->conn_mac_exempt) != 0) {
4879 		error = EHOSTUNREACH;
4880 		if (ip_debug > 2) {
4881 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4882 			    AF_INET, &dst_addr);
4883 		}
4884 		goto bad_addr;
4885 	}
4886 
4887 	/*
4888 	 * If the app does a connect(), it means that it will most likely
4889 	 * send more than 1 packet to the destination.  It makes sense
4890 	 * to clear the temporary flag.
4891 	 */
4892 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4893 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4894 		irb_t *irb = dst_ire->ire_bucket;
4895 
4896 		rw_enter(&irb->irb_lock, RW_WRITER);
4897 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4898 		irb->irb_tmp_ire_cnt--;
4899 		rw_exit(&irb->irb_lock);
4900 	}
4901 
4902 	/*
4903 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4904 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4905 	 * eligibility tests for passive connects are handled separately
4906 	 * through tcp_adapt_ire().  We do this before the source address
4907 	 * selection, because dst_ire may change after a call to
4908 	 * ipif_select_source().  This is a best-effort check, as the
4909 	 * packet for this connection may not actually go through
4910 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4911 	 * calling ip_newroute().  This is why we further check on the
4912 	 * IRE during LSO/Multidata packet transmission in
4913 	 * tcp_lsosend()/tcp_multisend().
4914 	 */
4915 	if (!ipsec_policy_set && dst_ire != NULL &&
4916 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4917 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4918 		if (ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4919 			lso_dst_ire = dst_ire;
4920 			IRE_REFHOLD(lso_dst_ire);
4921 		} else if (ip_multidata_outbound && ILL_MDT_CAPABLE(ill)) {
4922 			md_dst_ire = dst_ire;
4923 			IRE_REFHOLD(md_dst_ire);
4924 		}
4925 	}
4926 
4927 	if (dst_ire != NULL &&
4928 	    dst_ire->ire_type == IRE_LOCAL &&
4929 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4930 		/*
4931 		 * If the IRE belongs to a different zone, look for a matching
4932 		 * route in the forwarding table and use the source address from
4933 		 * that route.
4934 		 */
4935 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4936 		    zoneid, 0, NULL,
4937 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4938 		    MATCH_IRE_RJ_BHOLE);
4939 		if (src_ire == NULL) {
4940 			error = EHOSTUNREACH;
4941 			goto bad_addr;
4942 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4943 			if (!(src_ire->ire_type & IRE_HOST))
4944 				error = ENETUNREACH;
4945 			else
4946 				error = EHOSTUNREACH;
4947 			goto bad_addr;
4948 		}
4949 		if (src_addr == INADDR_ANY)
4950 			src_addr = src_ire->ire_src_addr;
4951 		ire_refrele(src_ire);
4952 		src_ire = NULL;
4953 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4954 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4955 			src_addr = sire->ire_src_addr;
4956 			ire_refrele(dst_ire);
4957 			dst_ire = sire;
4958 			sire = NULL;
4959 		} else {
4960 			/*
4961 			 * Pick a source address so that a proper inbound
4962 			 * load spreading would happen.
4963 			 */
4964 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4965 			ipif_t *src_ipif = NULL;
4966 			ire_t *ipif_ire;
4967 
4968 			/*
4969 			 * Supply a local source address such that inbound
4970 			 * load spreading happens.
4971 			 *
4972 			 * Determine the best source address on this ill for
4973 			 * the destination.
4974 			 *
4975 			 * 1) For broadcast, we should return a broadcast ire
4976 			 *    found above so that upper layers know that the
4977 			 *    destination address is a broadcast address.
4978 			 *
4979 			 * 2) If this is part of a group, select a better
4980 			 *    source address so that better inbound load
4981 			 *    balancing happens. Do the same if the ipif
4982 			 *    is DEPRECATED.
4983 			 *
4984 			 * 3) If the outgoing interface is part of a usesrc
4985 			 *    group, then try selecting a source address from
4986 			 *    the usesrc ILL.
4987 			 */
4988 			if ((dst_ire->ire_zoneid != zoneid &&
4989 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4990 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4991 			    ((dst_ill->ill_group != NULL) ||
4992 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4993 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4994 				/*
4995 				 * If the destination is reachable via a
4996 				 * given gateway, the selected source address
4997 				 * should be in the same subnet as the gateway.
4998 				 * Otherwise, the destination is not reachable.
4999 				 *
5000 				 * If there are no interfaces on the same subnet
5001 				 * as the destination, ipif_select_source gives
5002 				 * first non-deprecated interface which might be
5003 				 * on a different subnet than the gateway.
5004 				 * This is not desirable. Hence pass the dst_ire
5005 				 * source address to ipif_select_source.
5006 				 * It is sure that the destination is reachable
5007 				 * with the dst_ire source address subnet.
5008 				 * So passing dst_ire source address to
5009 				 * ipif_select_source will make sure that the
5010 				 * selected source will be on the same subnet
5011 				 * as dst_ire source address.
5012 				 */
5013 				ipaddr_t saddr =
5014 				    dst_ire->ire_ipif->ipif_src_addr;
5015 				src_ipif = ipif_select_source(dst_ill,
5016 				    saddr, zoneid);
5017 				if (src_ipif != NULL) {
5018 					if (IS_VNI(src_ipif->ipif_ill)) {
5019 						/*
5020 						 * For VNI there is no
5021 						 * interface route
5022 						 */
5023 						src_addr =
5024 						    src_ipif->ipif_src_addr;
5025 					} else {
5026 						ipif_ire =
5027 						    ipif_to_ire(src_ipif);
5028 						if (ipif_ire != NULL) {
5029 							IRE_REFRELE(dst_ire);
5030 							dst_ire = ipif_ire;
5031 						}
5032 						src_addr =
5033 						    dst_ire->ire_src_addr;
5034 					}
5035 					ipif_refrele(src_ipif);
5036 				} else {
5037 					src_addr = dst_ire->ire_src_addr;
5038 				}
5039 			} else {
5040 				src_addr = dst_ire->ire_src_addr;
5041 			}
5042 		}
5043 	}
5044 
5045 	/*
5046 	 * We do ire_route_lookup() here (and not
5047 	 * interface lookup as we assert that
5048 	 * src_addr should only come from an
5049 	 * UP interface for hard binding.
5050 	 */
5051 	ASSERT(src_ire == NULL);
5052 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5053 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
5054 	/* src_ire must be a local|loopback */
5055 	if (!IRE_IS_LOCAL(src_ire)) {
5056 		if (ip_debug > 2) {
5057 			pr_addr_dbg("ip_bind_connected: bad connected "
5058 			    "src %s\n", AF_INET, &src_addr);
5059 		}
5060 		error = EADDRNOTAVAIL;
5061 		goto bad_addr;
5062 	}
5063 
5064 	/*
5065 	 * If the source address is a loopback address, the
5066 	 * destination had best be local or multicast.
5067 	 * The transports that can't handle multicast will reject
5068 	 * those addresses.
5069 	 */
5070 	if (src_ire->ire_type == IRE_LOOPBACK &&
5071 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5072 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5073 		error = -1;
5074 		goto bad_addr;
5075 	}
5076 
5077 	/*
5078 	 * Allow setting new policies. For example, disconnects come
5079 	 * down as ipa_t bind. As we would have set conn_policy_cached
5080 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5081 	 * can change after the disconnect.
5082 	 */
5083 	connp->conn_policy_cached = B_FALSE;
5084 
5085 	/*
5086 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5087 	 * can handle their passed-in conn's.
5088 	 */
5089 
5090 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5091 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5092 	connp->conn_lport = lport;
5093 	connp->conn_fport = fport;
5094 	*src_addrp = src_addr;
5095 
5096 	ASSERT(!(ipsec_policy_set && ire_requested));
5097 	if (ire_requested) {
5098 		iulp_t *ulp_info = NULL;
5099 
5100 		/*
5101 		 * Note that sire will not be NULL if this is an off-link
5102 		 * connection and there is not cache for that dest yet.
5103 		 *
5104 		 * XXX Because of an existing bug, if there are multiple
5105 		 * default routes, the IRE returned now may not be the actual
5106 		 * default route used (default routes are chosen in a
5107 		 * round robin fashion).  So if the metrics for different
5108 		 * default routes are different, we may return the wrong
5109 		 * metrics.  This will not be a problem if the existing
5110 		 * bug is fixed.
5111 		 */
5112 		if (sire != NULL) {
5113 			ulp_info = &(sire->ire_uinfo);
5114 		}
5115 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5116 			error = -1;
5117 			goto bad_addr;
5118 		}
5119 	} else if (ipsec_policy_set) {
5120 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5121 			error = -1;
5122 			goto bad_addr;
5123 		}
5124 	}
5125 
5126 	/*
5127 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5128 	 * we'll cache that.  If we don't, we'll inherit global policy.
5129 	 *
5130 	 * We can't insert until the conn reflects the policy. Note that
5131 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5132 	 * connections where we don't have a policy. This is to prevent
5133 	 * global policy lookups in the inbound path.
5134 	 *
5135 	 * If we insert before we set conn_policy_cached,
5136 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5137 	 * because global policy cound be non-empty. We normally call
5138 	 * ipsec_check_policy() for conn_policy_cached connections only if
5139 	 * ipc_in_enforce_policy is set. But in this case,
5140 	 * conn_policy_cached can get set anytime since we made the
5141 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5142 	 * called, which will make the above assumption false.  Thus, we
5143 	 * need to insert after we set conn_policy_cached.
5144 	 */
5145 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5146 		goto bad_addr;
5147 
5148 	if (fanout_insert) {
5149 		/*
5150 		 * The addresses have been verified. Time to insert in
5151 		 * the correct fanout list.
5152 		 * We need to make sure that the conn_recv is set to a non-null
5153 		 * value before we insert into the classifier table to avoid a
5154 		 * race with an incoming packet which does an ipcl_classify().
5155 		 */
5156 		if (protocol == IPPROTO_TCP)
5157 			connp->conn_recv = tcp_input;
5158 		error = ipcl_conn_insert(connp, protocol, src_addr,
5159 		    dst_addr, connp->conn_ports);
5160 	}
5161 
5162 	if (error == 0) {
5163 		connp->conn_fully_bound = B_TRUE;
5164 		/*
5165 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5166 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5167 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5168 		 * ip_xxinfo_return(), which performs further checks
5169 		 * against them and upon success, returns the LSO/MDT info
5170 		 * mblk which we will attach to the bind acknowledgment.
5171 		 */
5172 		if (lso_dst_ire != NULL) {
5173 			mblk_t *lsoinfo_mp;
5174 
5175 			ASSERT(ill->ill_lso_capab != NULL);
5176 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5177 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5178 				linkb(mp, lsoinfo_mp);
5179 		} else if (md_dst_ire != NULL) {
5180 			mblk_t *mdinfo_mp;
5181 
5182 			ASSERT(ill->ill_mdt_capab != NULL);
5183 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5184 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5185 				linkb(mp, mdinfo_mp);
5186 		}
5187 	}
5188 bad_addr:
5189 	if (ipsec_policy_set) {
5190 		ASSERT(policy_mp == mp->b_cont);
5191 		ASSERT(policy_mp != NULL);
5192 		freeb(policy_mp);
5193 		/*
5194 		 * As of now assume that nothing else accompanies
5195 		 * IPSEC_POLICY_SET.
5196 		 */
5197 		mp->b_cont = NULL;
5198 	}
5199 	if (src_ire != NULL)
5200 		IRE_REFRELE(src_ire);
5201 	if (dst_ire != NULL)
5202 		IRE_REFRELE(dst_ire);
5203 	if (sire != NULL)
5204 		IRE_REFRELE(sire);
5205 	if (md_dst_ire != NULL)
5206 		IRE_REFRELE(md_dst_ire);
5207 	if (lso_dst_ire != NULL)
5208 		IRE_REFRELE(lso_dst_ire);
5209 	return (error);
5210 }
5211 
5212 /*
5213  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5214  * Prefers dst_ire over src_ire.
5215  */
5216 static boolean_t
5217 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5218 {
5219 	mblk_t	*mp1;
5220 	ire_t *ret_ire = NULL;
5221 
5222 	mp1 = mp->b_cont;
5223 	ASSERT(mp1 != NULL);
5224 
5225 	if (ire != NULL) {
5226 		/*
5227 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5228 		 * appended mblk. Its <upper protocol>'s
5229 		 * job to make sure there is room.
5230 		 */
5231 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5232 			return (0);
5233 
5234 		mp1->b_datap->db_type = IRE_DB_TYPE;
5235 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5236 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5237 		ret_ire = (ire_t *)mp1->b_rptr;
5238 		/*
5239 		 * Pass the latest setting of the ip_path_mtu_discovery and
5240 		 * copy the ulp info if any.
5241 		 */
5242 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5243 		    IPH_DF : 0;
5244 		if (ulp_info != NULL) {
5245 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5246 			    sizeof (iulp_t));
5247 		}
5248 		ret_ire->ire_mp = mp1;
5249 	} else {
5250 		/*
5251 		 * No IRE was found. Remove IRE mblk.
5252 		 */
5253 		mp->b_cont = mp1->b_cont;
5254 		freeb(mp1);
5255 	}
5256 
5257 	return (1);
5258 }
5259 
5260 /*
5261  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5262  * the final piece where we don't.  Return a pointer to the first mblk in the
5263  * result, and update the pointer to the next mblk to chew on.  If anything
5264  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5265  * NULL pointer.
5266  */
5267 mblk_t *
5268 ip_carve_mp(mblk_t **mpp, ssize_t len)
5269 {
5270 	mblk_t	*mp0;
5271 	mblk_t	*mp1;
5272 	mblk_t	*mp2;
5273 
5274 	if (!len || !mpp || !(mp0 = *mpp))
5275 		return (NULL);
5276 	/* If we aren't going to consume the first mblk, we need a dup. */
5277 	if (mp0->b_wptr - mp0->b_rptr > len) {
5278 		mp1 = dupb(mp0);
5279 		if (mp1) {
5280 			/* Partition the data between the two mblks. */
5281 			mp1->b_wptr = mp1->b_rptr + len;
5282 			mp0->b_rptr = mp1->b_wptr;
5283 			/*
5284 			 * after adjustments if mblk not consumed is now
5285 			 * unaligned, try to align it. If this fails free
5286 			 * all messages and let upper layer recover.
5287 			 */
5288 			if (!OK_32PTR(mp0->b_rptr)) {
5289 				if (!pullupmsg(mp0, -1)) {
5290 					freemsg(mp0);
5291 					freemsg(mp1);
5292 					*mpp = NULL;
5293 					return (NULL);
5294 				}
5295 			}
5296 		}
5297 		return (mp1);
5298 	}
5299 	/* Eat through as many mblks as we need to get len bytes. */
5300 	len -= mp0->b_wptr - mp0->b_rptr;
5301 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5302 		if (mp2->b_wptr - mp2->b_rptr > len) {
5303 			/*
5304 			 * We won't consume the entire last mblk.  Like
5305 			 * above, dup and partition it.
5306 			 */
5307 			mp1->b_cont = dupb(mp2);
5308 			mp1 = mp1->b_cont;
5309 			if (!mp1) {
5310 				/*
5311 				 * Trouble.  Rather than go to a lot of
5312 				 * trouble to clean up, we free the messages.
5313 				 * This won't be any worse than losing it on
5314 				 * the wire.
5315 				 */
5316 				freemsg(mp0);
5317 				freemsg(mp2);
5318 				*mpp = NULL;
5319 				return (NULL);
5320 			}
5321 			mp1->b_wptr = mp1->b_rptr + len;
5322 			mp2->b_rptr = mp1->b_wptr;
5323 			/*
5324 			 * after adjustments if mblk not consumed is now
5325 			 * unaligned, try to align it. If this fails free
5326 			 * all messages and let upper layer recover.
5327 			 */
5328 			if (!OK_32PTR(mp2->b_rptr)) {
5329 				if (!pullupmsg(mp2, -1)) {
5330 					freemsg(mp0);
5331 					freemsg(mp2);
5332 					*mpp = NULL;
5333 					return (NULL);
5334 				}
5335 			}
5336 			*mpp = mp2;
5337 			return (mp0);
5338 		}
5339 		/* Decrement len by the amount we just got. */
5340 		len -= mp2->b_wptr - mp2->b_rptr;
5341 	}
5342 	/*
5343 	 * len should be reduced to zero now.  If not our caller has
5344 	 * screwed up.
5345 	 */
5346 	if (len) {
5347 		/* Shouldn't happen! */
5348 		freemsg(mp0);
5349 		*mpp = NULL;
5350 		return (NULL);
5351 	}
5352 	/*
5353 	 * We consumed up to exactly the end of an mblk.  Detach the part
5354 	 * we are returning from the rest of the chain.
5355 	 */
5356 	mp1->b_cont = NULL;
5357 	*mpp = mp2;
5358 	return (mp0);
5359 }
5360 
5361 /* The ill stream is being unplumbed. Called from ip_close */
5362 int
5363 ip_modclose(ill_t *ill)
5364 {
5365 
5366 	boolean_t success;
5367 	ipsq_t	*ipsq;
5368 	ipif_t	*ipif;
5369 	queue_t	*q = ill->ill_rq;
5370 	hook_nic_event_t *info;
5371 
5372 	/*
5373 	 * Forcibly enter the ipsq after some delay. This is to take
5374 	 * care of the case when some ioctl does not complete because
5375 	 * we sent a control message to the driver and it did not
5376 	 * send us a reply. We want to be able to at least unplumb
5377 	 * and replumb rather than force the user to reboot the system.
5378 	 */
5379 	success = ipsq_enter(ill, B_FALSE);
5380 
5381 	/*
5382 	 * Open/close/push/pop is guaranteed to be single threaded
5383 	 * per stream by STREAMS. FS guarantees that all references
5384 	 * from top are gone before close is called. So there can't
5385 	 * be another close thread that has set CONDEMNED on this ill.
5386 	 * and cause ipsq_enter to return failure.
5387 	 */
5388 	ASSERT(success);
5389 	ipsq = ill->ill_phyint->phyint_ipsq;
5390 
5391 	/*
5392 	 * Mark it condemned. No new reference will be made to this ill.
5393 	 * Lookup functions will return an error. Threads that try to
5394 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5395 	 * that the refcnt will drop down to zero.
5396 	 */
5397 	mutex_enter(&ill->ill_lock);
5398 	ill->ill_state_flags |= ILL_CONDEMNED;
5399 	for (ipif = ill->ill_ipif; ipif != NULL;
5400 	    ipif = ipif->ipif_next) {
5401 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5402 	}
5403 	/*
5404 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5405 	 * returns  error if ILL_CONDEMNED is set
5406 	 */
5407 	cv_broadcast(&ill->ill_cv);
5408 	mutex_exit(&ill->ill_lock);
5409 
5410 	/*
5411 	 * Shut down fragmentation reassembly.
5412 	 * ill_frag_timer won't start a timer again.
5413 	 * Now cancel any existing timer
5414 	 */
5415 	(void) untimeout(ill->ill_frag_timer_id);
5416 	(void) ill_frag_timeout(ill, 0);
5417 
5418 	/*
5419 	 * If MOVE was in progress, clear the
5420 	 * move_in_progress fields also.
5421 	 */
5422 	if (ill->ill_move_in_progress) {
5423 		ILL_CLEAR_MOVE(ill);
5424 	}
5425 
5426 	/*
5427 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5428 	 * this ill. Then wait for the refcnts to drop to zero.
5429 	 * ill_is_quiescent checks whether the ill is really quiescent.
5430 	 * Then make sure that threads that are waiting to enter the
5431 	 * ipsq have seen the error returned by ipsq_enter and have
5432 	 * gone away. Then we call ill_delete_tail which does the
5433 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5434 	 */
5435 	ill_delete(ill);
5436 	mutex_enter(&ill->ill_lock);
5437 	while (!ill_is_quiescent(ill))
5438 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5439 	while (ill->ill_waiters)
5440 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5441 
5442 	mutex_exit(&ill->ill_lock);
5443 
5444 	/* qprocsoff is called in ill_delete_tail */
5445 	ill_delete_tail(ill);
5446 
5447 	/*
5448 	 * Walk through all upper (conn) streams and qenable
5449 	 * those that have queued data.
5450 	 * close synchronization needs this to
5451 	 * be done to ensure that all upper layers blocked
5452 	 * due to flow control to the closing device
5453 	 * get unblocked.
5454 	 */
5455 	ip1dbg(("ip_wsrv: walking\n"));
5456 	conn_walk_drain();
5457 
5458 	mutex_enter(&ip_mi_lock);
5459 	mi_close_unlink(&ip_g_head, (IDP)ill);
5460 	mutex_exit(&ip_mi_lock);
5461 
5462 	/*
5463 	 * credp could be null if the open didn't succeed and ip_modopen
5464 	 * itself calls ip_close.
5465 	 */
5466 	if (ill->ill_credp != NULL)
5467 		crfree(ill->ill_credp);
5468 
5469 	/*
5470 	 * Unhook the nic event message from the ill and enqueue it into the nic
5471 	 * event taskq.
5472 	 */
5473 	if ((info = ill->ill_nic_event_info) != NULL) {
5474 		if (ddi_taskq_dispatch(eventq_queue_nic, ip_ne_queue_func,
5475 		    (void *)info, DDI_SLEEP) == DDI_FAILURE) {
5476 			ip2dbg(("ip_ioctl_finish:ddi_taskq_dispatch failed\n"));
5477 			if (info->hne_data != NULL)
5478 				kmem_free(info->hne_data, info->hne_datalen);
5479 			kmem_free(info, sizeof (hook_nic_event_t));
5480 		}
5481 		ill->ill_nic_event_info = NULL;
5482 	}
5483 
5484 	mi_close_free((IDP)ill);
5485 	q->q_ptr = WR(q)->q_ptr = NULL;
5486 
5487 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5488 
5489 	return (0);
5490 }
5491 
5492 /*
5493  * This is called as part of close() for both IP and UDP
5494  * in order to quiesce the conn.
5495  */
5496 void
5497 ip_quiesce_conn(conn_t *connp)
5498 {
5499 	boolean_t	drain_cleanup_reqd = B_FALSE;
5500 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5501 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5502 
5503 	ASSERT(!IPCL_IS_TCP(connp));
5504 
5505 	/*
5506 	 * Mark the conn as closing, and this conn must not be
5507 	 * inserted in future into any list. Eg. conn_drain_insert(),
5508 	 * won't insert this conn into the conn_drain_list.
5509 	 * Similarly ill_pending_mp_add() will not add any mp to
5510 	 * the pending mp list, after this conn has started closing.
5511 	 *
5512 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5513 	 * cannot get set henceforth.
5514 	 */
5515 	mutex_enter(&connp->conn_lock);
5516 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5517 	connp->conn_state_flags |= CONN_CLOSING;
5518 	if (connp->conn_idl != NULL)
5519 		drain_cleanup_reqd = B_TRUE;
5520 	if (connp->conn_oper_pending_ill != NULL)
5521 		conn_ioctl_cleanup_reqd = B_TRUE;
5522 	if (connp->conn_ilg_inuse != 0)
5523 		ilg_cleanup_reqd = B_TRUE;
5524 	mutex_exit(&connp->conn_lock);
5525 
5526 	if (IPCL_IS_UDP(connp))
5527 		udp_quiesce_conn(connp);
5528 
5529 	if (conn_ioctl_cleanup_reqd)
5530 		conn_ioctl_cleanup(connp);
5531 
5532 	if (is_system_labeled() && connp->conn_anon_port) {
5533 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5534 		    connp->conn_mlp_type, connp->conn_ulp,
5535 		    ntohs(connp->conn_lport), B_FALSE);
5536 		connp->conn_anon_port = 0;
5537 	}
5538 	connp->conn_mlp_type = mlptSingle;
5539 
5540 	/*
5541 	 * Remove this conn from any fanout list it is on.
5542 	 * and then wait for any threads currently operating
5543 	 * on this endpoint to finish
5544 	 */
5545 	ipcl_hash_remove(connp);
5546 
5547 	/*
5548 	 * Remove this conn from the drain list, and do
5549 	 * any other cleanup that may be required.
5550 	 * (Only non-tcp streams may have a non-null conn_idl.
5551 	 * TCP streams are never flow controlled, and
5552 	 * conn_idl will be null)
5553 	 */
5554 	if (drain_cleanup_reqd)
5555 		conn_drain_tail(connp, B_TRUE);
5556 
5557 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5558 		(void) ip_mrouter_done(NULL);
5559 
5560 	if (ilg_cleanup_reqd)
5561 		ilg_delete_all(connp);
5562 
5563 	conn_delete_ire(connp, NULL);
5564 
5565 	/*
5566 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5567 	 * callers from write side can't be there now because close
5568 	 * is in progress. The only other caller is ipcl_walk
5569 	 * which checks for the condemned flag.
5570 	 */
5571 	mutex_enter(&connp->conn_lock);
5572 	connp->conn_state_flags |= CONN_CONDEMNED;
5573 	while (connp->conn_ref != 1)
5574 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5575 	connp->conn_state_flags |= CONN_QUIESCED;
5576 	mutex_exit(&connp->conn_lock);
5577 }
5578 
5579 /* ARGSUSED */
5580 int
5581 ip_close(queue_t *q, int flags)
5582 {
5583 	conn_t		*connp;
5584 
5585 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5586 
5587 	/*
5588 	 * Call the appropriate delete routine depending on whether this is
5589 	 * a module or device.
5590 	 */
5591 	if (WR(q)->q_next != NULL) {
5592 		/* This is a module close */
5593 		return (ip_modclose((ill_t *)q->q_ptr));
5594 	}
5595 
5596 	connp = q->q_ptr;
5597 	ip_quiesce_conn(connp);
5598 
5599 	qprocsoff(q);
5600 
5601 	/*
5602 	 * Now we are truly single threaded on this stream, and can
5603 	 * delete the things hanging off the connp, and finally the connp.
5604 	 * We removed this connp from the fanout list, it cannot be
5605 	 * accessed thru the fanouts, and we already waited for the
5606 	 * conn_ref to drop to 0. We are already in close, so
5607 	 * there cannot be any other thread from the top. qprocsoff
5608 	 * has completed, and service has completed or won't run in
5609 	 * future.
5610 	 */
5611 	ASSERT(connp->conn_ref == 1);
5612 
5613 	/*
5614 	 * A conn which was previously marked as IPCL_UDP cannot
5615 	 * retain the flag because it would have been cleared by
5616 	 * udp_close().
5617 	 */
5618 	ASSERT(!IPCL_IS_UDP(connp));
5619 
5620 	if (connp->conn_latch != NULL) {
5621 		IPLATCH_REFRELE(connp->conn_latch);
5622 		connp->conn_latch = NULL;
5623 	}
5624 	if (connp->conn_policy != NULL) {
5625 		IPPH_REFRELE(connp->conn_policy);
5626 		connp->conn_policy = NULL;
5627 	}
5628 	if (connp->conn_ipsec_opt_mp != NULL) {
5629 		freemsg(connp->conn_ipsec_opt_mp);
5630 		connp->conn_ipsec_opt_mp = NULL;
5631 	}
5632 
5633 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5634 
5635 	connp->conn_ref--;
5636 	ipcl_conn_destroy(connp);
5637 
5638 	q->q_ptr = WR(q)->q_ptr = NULL;
5639 	return (0);
5640 }
5641 
5642 int
5643 ip_snmpmod_close(queue_t *q)
5644 {
5645 	conn_t *connp = Q_TO_CONN(q);
5646 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5647 
5648 	qprocsoff(q);
5649 
5650 	if (connp->conn_flags & IPCL_UDPMOD)
5651 		udp_close_free(connp);
5652 
5653 	if (connp->conn_cred != NULL) {
5654 		crfree(connp->conn_cred);
5655 		connp->conn_cred = NULL;
5656 	}
5657 	CONN_DEC_REF(connp);
5658 	q->q_ptr = WR(q)->q_ptr = NULL;
5659 	return (0);
5660 }
5661 
5662 /*
5663  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5664  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5665  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5666  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5667  * queues as we never enqueue messages there and we don't handle any ioctls.
5668  * Everything else is freed.
5669  */
5670 void
5671 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5672 {
5673 	conn_t	*connp = q->q_ptr;
5674 	pfi_t	setfn;
5675 	pfi_t	getfn;
5676 
5677 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5678 
5679 	switch (DB_TYPE(mp)) {
5680 	case M_PROTO:
5681 	case M_PCPROTO:
5682 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5683 		    ((((union T_primitives *)mp->b_rptr)->type ==
5684 			T_SVR4_OPTMGMT_REQ) ||
5685 		    (((union T_primitives *)mp->b_rptr)->type ==
5686 			T_OPTMGMT_REQ))) {
5687 			/*
5688 			 * This is the only TPI primitive supported. Its
5689 			 * handling does not require tcp_t, but it does require
5690 			 * conn_t to check permissions.
5691 			 */
5692 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5693 
5694 			if (connp->conn_flags & IPCL_TCPMOD) {
5695 				setfn = tcp_snmp_set;
5696 				getfn = tcp_snmp_get;
5697 			} else {
5698 				setfn = udp_snmp_set;
5699 				getfn = udp_snmp_get;
5700 			}
5701 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5702 				freemsg(mp);
5703 				return;
5704 			}
5705 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5706 		    != NULL)
5707 			qreply(q, mp);
5708 		break;
5709 	case M_FLUSH:
5710 	case M_IOCTL:
5711 		putnext(q, mp);
5712 		break;
5713 	default:
5714 		freemsg(mp);
5715 		break;
5716 	}
5717 }
5718 
5719 /* Return the IP checksum for the IP header at "iph". */
5720 uint16_t
5721 ip_csum_hdr(ipha_t *ipha)
5722 {
5723 	uint16_t	*uph;
5724 	uint32_t	sum;
5725 	int		opt_len;
5726 
5727 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5728 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5729 	uph = (uint16_t *)ipha;
5730 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5731 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5732 	if (opt_len > 0) {
5733 		do {
5734 			sum += uph[10];
5735 			sum += uph[11];
5736 			uph += 2;
5737 		} while (--opt_len);
5738 	}
5739 	sum = (sum & 0xFFFF) + (sum >> 16);
5740 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5741 	if (sum == 0xffff)
5742 		sum = 0;
5743 	return ((uint16_t)sum);
5744 }
5745 
5746 void
5747 ip_ddi_destroy(void)
5748 {
5749 	ipv4_hook_destroy();
5750 	ipv6_hook_destroy();
5751 	ip_net_destroy();
5752 
5753 	tnet_fini();
5754 	tcp_ddi_destroy();
5755 	sctp_ddi_destroy();
5756 	ipsec_loader_destroy();
5757 	ipsec_policy_destroy();
5758 	ipsec_kstat_destroy();
5759 	nd_free(&ip_g_nd);
5760 	mutex_destroy(&igmp_timer_lock);
5761 	mutex_destroy(&mld_timer_lock);
5762 	mutex_destroy(&igmp_slowtimeout_lock);
5763 	mutex_destroy(&mld_slowtimeout_lock);
5764 	mutex_destroy(&ip_mi_lock);
5765 	mutex_destroy(&rts_clients.connf_lock);
5766 	ip_ire_fini();
5767 	ip6_asp_free();
5768 	conn_drain_fini();
5769 	ipcl_destroy();
5770 	inet_minor_destroy(ip_minor_arena);
5771 	icmp_kstat_fini();
5772 	ip_kstat_fini();
5773 	rw_destroy(&ipsec_capab_ills_lock);
5774 	rw_destroy(&ill_g_usesrc_lock);
5775 	ip_drop_unregister(&ip_dropper);
5776 }
5777 
5778 
5779 void
5780 ip_ddi_init(void)
5781 {
5782 	TCP6_MAJ = ddi_name_to_major(TCP6);
5783 	TCP_MAJ	= ddi_name_to_major(TCP);
5784 	SCTP_MAJ = ddi_name_to_major(SCTP);
5785 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5786 
5787 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5788 
5789 	/* IP's IPsec code calls the packet dropper */
5790 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5791 
5792 	if (!ip_g_nd) {
5793 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5794 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5795 			nd_free(&ip_g_nd);
5796 		}
5797 	}
5798 
5799 	ipsec_loader_init();
5800 	ipsec_policy_init();
5801 	ipsec_kstat_init();
5802 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5803 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5804 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5805 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5806 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5807 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5808 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5809 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5810 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5811 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5812 
5813 	/*
5814 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5815 	 * initial devices: ip, ip6, tcp, tcp6.
5816 	 */
5817 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5818 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5819 		cmn_err(CE_PANIC,
5820 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5821 	}
5822 
5823 	ipcl_init();
5824 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5825 	ip_ire_init();
5826 	ip6_asp_init();
5827 	ipif_init();
5828 	conn_drain_init();
5829 	tcp_ddi_init();
5830 	sctp_ddi_init();
5831 
5832 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5833 
5834 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5835 		"net", KSTAT_TYPE_NAMED,
5836 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5837 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5838 		ip_kstat->ks_data = &ip_statistics;
5839 		kstat_install(ip_kstat);
5840 	}
5841 	ip_kstat_init();
5842 	ip6_kstat_init();
5843 	icmp_kstat_init();
5844 	ipsec_loader_start();
5845 	tnet_init();
5846 
5847 	ip_net_init();
5848 	ipv4_hook_init();
5849 	ipv6_hook_init();
5850 }
5851 
5852 /*
5853  * Allocate and initialize a DLPI template of the specified length.  (May be
5854  * called as writer.)
5855  */
5856 mblk_t *
5857 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5858 {
5859 	mblk_t	*mp;
5860 
5861 	mp = allocb(len, BPRI_MED);
5862 	if (!mp)
5863 		return (NULL);
5864 
5865 	/*
5866 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5867 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5868 	 * that other DLPI are M_PROTO.
5869 	 */
5870 	if (prim == DL_INFO_REQ) {
5871 		mp->b_datap->db_type = M_PCPROTO;
5872 	} else {
5873 		mp->b_datap->db_type = M_PROTO;
5874 	}
5875 
5876 	mp->b_wptr = mp->b_rptr + len;
5877 	bzero(mp->b_rptr, len);
5878 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5879 	return (mp);
5880 }
5881 
5882 const char *
5883 dlpi_prim_str(int prim)
5884 {
5885 	switch (prim) {
5886 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5887 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5888 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5889 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5890 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5891 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5892 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5893 	case DL_OK_ACK:		return ("DL_OK_ACK");
5894 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5895 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5896 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5897 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5898 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5899 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5900 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5901 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5902 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5903 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5904 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5905 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5906 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5907 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5908 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5909 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5910 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5911 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5912 	default:		return ("<unknown primitive>");
5913 	}
5914 }
5915 
5916 const char *
5917 dlpi_err_str(int err)
5918 {
5919 	switch (err) {
5920 	case DL_ACCESS:		return ("DL_ACCESS");
5921 	case DL_BADADDR:	return ("DL_BADADDR");
5922 	case DL_BADCORR:	return ("DL_BADCORR");
5923 	case DL_BADDATA:	return ("DL_BADDATA");
5924 	case DL_BADPPA:		return ("DL_BADPPA");
5925 	case DL_BADPRIM:	return ("DL_BADPRIM");
5926 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5927 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5928 	case DL_BADSAP:		return ("DL_BADSAP");
5929 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5930 	case DL_BOUND:		return ("DL_BOUND");
5931 	case DL_INITFAILED:	return ("DL_INITFAILED");
5932 	case DL_NOADDR:		return ("DL_NOADDR");
5933 	case DL_NOTINIT:	return ("DL_NOTINIT");
5934 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5935 	case DL_SYSERR:		return ("DL_SYSERR");
5936 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5937 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5938 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5939 	case DL_TOOMANY:	return ("DL_TOOMANY");
5940 	case DL_NOTENAB:	return ("DL_NOTENAB");
5941 	case DL_BUSY:		return ("DL_BUSY");
5942 	case DL_NOAUTO:		return ("DL_NOAUTO");
5943 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5944 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5945 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5946 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5947 	case DL_PENDING:	return ("DL_PENDING");
5948 	default:		return ("<unknown error>");
5949 	}
5950 }
5951 
5952 /*
5953  * Debug formatting routine.  Returns a character string representation of the
5954  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5955  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5956  *
5957  * Once the ndd table-printing interfaces are removed, this can be changed to
5958  * standard dotted-decimal form.
5959  */
5960 char *
5961 ip_dot_addr(ipaddr_t addr, char *buf)
5962 {
5963 	uint8_t *ap = (uint8_t *)&addr;
5964 
5965 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5966 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
5967 	return (buf);
5968 }
5969 
5970 /*
5971  * Write the given MAC address as a printable string in the usual colon-
5972  * separated format.
5973  */
5974 const char *
5975 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
5976 {
5977 	char *bp;
5978 
5979 	if (alen == 0 || buflen < 4)
5980 		return ("?");
5981 	bp = buf;
5982 	for (;;) {
5983 		/*
5984 		 * If there are more MAC address bytes available, but we won't
5985 		 * have any room to print them, then add "..." to the string
5986 		 * instead.  See below for the 'magic number' explanation.
5987 		 */
5988 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
5989 			(void) strcpy(bp, "...");
5990 			break;
5991 		}
5992 		(void) sprintf(bp, "%02x", *addr++);
5993 		bp += 2;
5994 		if (--alen == 0)
5995 			break;
5996 		*bp++ = ':';
5997 		buflen -= 3;
5998 		/*
5999 		 * At this point, based on the first 'if' statement above,
6000 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6001 		 * buflen >= 4.  The first case leaves room for the final "xx"
6002 		 * number and trailing NUL byte.  The second leaves room for at
6003 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6004 		 * that statement.
6005 		 */
6006 	}
6007 	return (buf);
6008 }
6009 
6010 /*
6011  * Send an ICMP error after patching up the packet appropriately.  Returns
6012  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6013  */
6014 static boolean_t
6015 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6016     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
6017 {
6018 	ipha_t *ipha;
6019 	mblk_t *first_mp;
6020 	boolean_t secure;
6021 	unsigned char db_type;
6022 
6023 	first_mp = mp;
6024 	if (mctl_present) {
6025 		mp = mp->b_cont;
6026 		secure = ipsec_in_is_secure(first_mp);
6027 		ASSERT(mp != NULL);
6028 	} else {
6029 		/*
6030 		 * If this is an ICMP error being reported - which goes
6031 		 * up as M_CTLs, we need to convert them to M_DATA till
6032 		 * we finish checking with global policy because
6033 		 * ipsec_check_global_policy() assumes M_DATA as clear
6034 		 * and M_CTL as secure.
6035 		 */
6036 		db_type = DB_TYPE(mp);
6037 		DB_TYPE(mp) = M_DATA;
6038 		secure = B_FALSE;
6039 	}
6040 	/*
6041 	 * We are generating an icmp error for some inbound packet.
6042 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6043 	 * Before we generate an error, check with global policy
6044 	 * to see whether this is allowed to enter the system. As
6045 	 * there is no "conn", we are checking with global policy.
6046 	 */
6047 	ipha = (ipha_t *)mp->b_rptr;
6048 	if (secure || ipsec_inbound_v4_policy_present) {
6049 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6050 		    ipha, NULL, mctl_present);
6051 		if (first_mp == NULL)
6052 			return (B_FALSE);
6053 	}
6054 
6055 	if (!mctl_present)
6056 		DB_TYPE(mp) = db_type;
6057 
6058 	if (flags & IP_FF_SEND_ICMP) {
6059 		if (flags & IP_FF_HDR_COMPLETE) {
6060 			if (ip_hdr_complete(ipha, zoneid)) {
6061 				freemsg(first_mp);
6062 				return (B_TRUE);
6063 			}
6064 		}
6065 		if (flags & IP_FF_CKSUM) {
6066 			/*
6067 			 * Have to correct checksum since
6068 			 * the packet might have been
6069 			 * fragmented and the reassembly code in ip_rput
6070 			 * does not restore the IP checksum.
6071 			 */
6072 			ipha->ipha_hdr_checksum = 0;
6073 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6074 		}
6075 		switch (icmp_type) {
6076 		case ICMP_DEST_UNREACHABLE:
6077 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid);
6078 			break;
6079 		default:
6080 			freemsg(first_mp);
6081 			break;
6082 		}
6083 	} else {
6084 		freemsg(first_mp);
6085 		return (B_FALSE);
6086 	}
6087 
6088 	return (B_TRUE);
6089 }
6090 
6091 /*
6092  * Used to send an ICMP error message when a packet is received for
6093  * a protocol that is not supported. The mblk passed as argument
6094  * is consumed by this function.
6095  */
6096 void
6097 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
6098 {
6099 	mblk_t *mp;
6100 	ipha_t *ipha;
6101 	ill_t *ill;
6102 	ipsec_in_t *ii;
6103 
6104 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6105 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6106 
6107 	mp = ipsec_mp->b_cont;
6108 	ipsec_mp->b_cont = NULL;
6109 	ipha = (ipha_t *)mp->b_rptr;
6110 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6111 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
6112 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6113 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
6114 		}
6115 	} else {
6116 		/* Get ill from index in ipsec_in_t. */
6117 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6118 		    B_TRUE, NULL, NULL, NULL, NULL);
6119 		if (ill != NULL) {
6120 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6121 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6122 			    0, B_FALSE, zoneid)) {
6123 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
6124 			}
6125 
6126 			ill_refrele(ill);
6127 		} else { /* re-link for the freemsg() below. */
6128 			ipsec_mp->b_cont = mp;
6129 		}
6130 	}
6131 
6132 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6133 	freemsg(ipsec_mp);
6134 }
6135 
6136 /*
6137  * See if the inbound datagram has had IPsec processing applied to it.
6138  */
6139 boolean_t
6140 ipsec_in_is_secure(mblk_t *ipsec_mp)
6141 {
6142 	ipsec_in_t *ii;
6143 
6144 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6145 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6146 
6147 	if (ii->ipsec_in_loopback) {
6148 		return (ii->ipsec_in_secure);
6149 	} else {
6150 		return (ii->ipsec_in_ah_sa != NULL ||
6151 		    ii->ipsec_in_esp_sa != NULL ||
6152 		    ii->ipsec_in_decaps);
6153 	}
6154 }
6155 
6156 /*
6157  * Handle protocols with which IP is less intimate.  There
6158  * can be more than one stream bound to a particular
6159  * protocol.  When this is the case, normally each one gets a copy
6160  * of any incoming packets.
6161  *
6162  * IPSEC NOTE :
6163  *
6164  * Don't allow a secure packet going up a non-secure connection.
6165  * We don't allow this because
6166  *
6167  * 1) Reply might go out in clear which will be dropped at
6168  *    the sending side.
6169  * 2) If the reply goes out in clear it will give the
6170  *    adversary enough information for getting the key in
6171  *    most of the cases.
6172  *
6173  * Moreover getting a secure packet when we expect clear
6174  * implies that SA's were added without checking for
6175  * policy on both ends. This should not happen once ISAKMP
6176  * is used to negotiate SAs as SAs will be added only after
6177  * verifying the policy.
6178  *
6179  * NOTE : If the packet was tunneled and not multicast we only send
6180  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6181  * back to delivering packets to AF_INET6 raw sockets.
6182  *
6183  * IPQoS Notes:
6184  * Once we have determined the client, invoke IPPF processing.
6185  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6186  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6187  * ip_policy will be false.
6188  *
6189  * Zones notes:
6190  * Currently only applications in the global zone can create raw sockets for
6191  * protocols other than ICMP. So unlike the broadcast / multicast case of
6192  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6193  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6194  */
6195 static void
6196 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6197     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6198     zoneid_t zoneid)
6199 {
6200 	queue_t	*rq;
6201 	mblk_t	*mp1, *first_mp1;
6202 	uint_t	protocol = ipha->ipha_protocol;
6203 	ipaddr_t dst;
6204 	boolean_t one_only;
6205 	mblk_t *first_mp = mp;
6206 	boolean_t secure;
6207 	uint32_t ill_index;
6208 	conn_t	*connp, *first_connp, *next_connp;
6209 	connf_t	*connfp;
6210 	boolean_t shared_addr;
6211 
6212 	if (mctl_present) {
6213 		mp = first_mp->b_cont;
6214 		secure = ipsec_in_is_secure(first_mp);
6215 		ASSERT(mp != NULL);
6216 	} else {
6217 		secure = B_FALSE;
6218 	}
6219 	dst = ipha->ipha_dst;
6220 	/*
6221 	 * If the packet was tunneled and not multicast we only send to it
6222 	 * the first match.
6223 	 */
6224 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6225 	    !CLASSD(dst));
6226 
6227 	shared_addr = (zoneid == ALL_ZONES);
6228 	if (shared_addr) {
6229 		/*
6230 		 * We don't allow multilevel ports for raw IP, so no need to
6231 		 * check for that here.
6232 		 */
6233 		zoneid = tsol_packet_to_zoneid(mp);
6234 	}
6235 
6236 	connfp = &ipcl_proto_fanout[protocol];
6237 	mutex_enter(&connfp->connf_lock);
6238 	connp = connfp->connf_head;
6239 	for (connp = connfp->connf_head; connp != NULL;
6240 		connp = connp->conn_next) {
6241 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6242 		    zoneid) &&
6243 		    (!is_system_labeled() ||
6244 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6245 		    connp)))
6246 			break;
6247 	}
6248 
6249 	if (connp == NULL || connp->conn_upq == NULL) {
6250 		/*
6251 		 * No one bound to these addresses.  Is
6252 		 * there a client that wants all
6253 		 * unclaimed datagrams?
6254 		 */
6255 		mutex_exit(&connfp->connf_lock);
6256 		/*
6257 		 * Check for IPPROTO_ENCAP...
6258 		 */
6259 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6260 			/*
6261 			 * If an IPsec mblk is here on a multicast
6262 			 * tunnel (using ip_mroute stuff), check policy here,
6263 			 * THEN ship off to ip_mroute_decap().
6264 			 *
6265 			 * BTW,  If I match a configured IP-in-IP
6266 			 * tunnel, this path will not be reached, and
6267 			 * ip_mroute_decap will never be called.
6268 			 */
6269 			first_mp = ipsec_check_global_policy(first_mp, connp,
6270 			    ipha, NULL, mctl_present);
6271 			if (first_mp != NULL) {
6272 				if (mctl_present)
6273 					freeb(first_mp);
6274 				ip_mroute_decap(q, mp);
6275 			} /* Else we already freed everything! */
6276 		} else {
6277 			/*
6278 			 * Otherwise send an ICMP protocol unreachable.
6279 			 */
6280 			if (ip_fanout_send_icmp(q, first_mp, flags,
6281 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6282 			    mctl_present, zoneid)) {
6283 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
6284 			}
6285 		}
6286 		return;
6287 	}
6288 	CONN_INC_REF(connp);
6289 	first_connp = connp;
6290 
6291 	/*
6292 	 * Only send message to one tunnel driver by immediately
6293 	 * terminating the loop.
6294 	 */
6295 	connp = one_only ? NULL : connp->conn_next;
6296 
6297 	for (;;) {
6298 		while (connp != NULL) {
6299 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6300 			    flags, zoneid) &&
6301 			    (!is_system_labeled() ||
6302 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6303 			    shared_addr, connp)))
6304 				break;
6305 			connp = connp->conn_next;
6306 		}
6307 
6308 		/*
6309 		 * Copy the packet.
6310 		 */
6311 		if (connp == NULL || connp->conn_upq == NULL ||
6312 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6313 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6314 			/*
6315 			 * No more interested clients or memory
6316 			 * allocation failed
6317 			 */
6318 			connp = first_connp;
6319 			break;
6320 		}
6321 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6322 		CONN_INC_REF(connp);
6323 		mutex_exit(&connfp->connf_lock);
6324 		rq = connp->conn_rq;
6325 		if (!canputnext(rq)) {
6326 			if (flags & IP_FF_RAWIP) {
6327 				BUMP_MIB(&ip_mib, rawipInOverflows);
6328 			} else {
6329 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6330 			}
6331 
6332 			freemsg(first_mp1);
6333 		} else {
6334 			/*
6335 			 * Don't enforce here if we're an actual tunnel -
6336 			 * let "tun" do it instead.
6337 			 */
6338 			if (!IPCL_IS_IPTUN(connp) &&
6339 			    (CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6340 				first_mp1 = ipsec_check_inbound_policy
6341 				    (first_mp1, connp, ipha, NULL,
6342 				    mctl_present);
6343 			}
6344 			if (first_mp1 != NULL) {
6345 				/*
6346 				 * ip_fanout_proto also gets called from
6347 				 * icmp_inbound_error_fanout, in which case
6348 				 * the msg type is M_CTL.  Don't add info
6349 				 * in this case for the time being. In future
6350 				 * when there is a need for knowing the
6351 				 * inbound iface index for ICMP error msgs,
6352 				 * then this can be changed.
6353 				 */
6354 				if ((connp->conn_recvif != 0) &&
6355 				    (mp->b_datap->db_type != M_CTL)) {
6356 					/*
6357 					 * the actual data will be
6358 					 * contained in b_cont upon
6359 					 * successful return of the
6360 					 * following call else
6361 					 * original mblk is returned
6362 					 */
6363 					ASSERT(recv_ill != NULL);
6364 					mp1 = ip_add_info(mp1, recv_ill,
6365 						IPF_RECVIF);
6366 				}
6367 				BUMP_MIB(&ip_mib, ipInDelivers);
6368 				if (mctl_present)
6369 					freeb(first_mp1);
6370 				putnext(rq, mp1);
6371 			}
6372 		}
6373 		mutex_enter(&connfp->connf_lock);
6374 		/* Follow the next pointer before releasing the conn. */
6375 		next_connp = connp->conn_next;
6376 		CONN_DEC_REF(connp);
6377 		connp = next_connp;
6378 	}
6379 
6380 	/* Last one.  Send it upstream. */
6381 	mutex_exit(&connfp->connf_lock);
6382 
6383 	/*
6384 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6385 	 * will be set to false.
6386 	 */
6387 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6388 		ill_index = ill->ill_phyint->phyint_ifindex;
6389 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6390 		if (mp == NULL) {
6391 			CONN_DEC_REF(connp);
6392 			if (mctl_present) {
6393 				freeb(first_mp);
6394 			}
6395 			return;
6396 		}
6397 	}
6398 
6399 	rq = connp->conn_rq;
6400 	if (!canputnext(rq)) {
6401 		if (flags & IP_FF_RAWIP) {
6402 			BUMP_MIB(&ip_mib, rawipInOverflows);
6403 		} else {
6404 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6405 		}
6406 
6407 		freemsg(first_mp);
6408 	} else {
6409 		if (IPCL_IS_IPTUN(connp)) {
6410 			/*
6411 			 * Tunneled packet.  We enforce policy in the tunnel
6412 			 * module itself.
6413 			 *
6414 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6415 			 * a policy check.
6416 			 */
6417 			putnext(rq, first_mp);
6418 			CONN_DEC_REF(connp);
6419 			return;
6420 		}
6421 
6422 		if ((CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6423 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6424 			    ipha, NULL, mctl_present);
6425 		}
6426 
6427 		if (first_mp != NULL) {
6428 			/*
6429 			 * ip_fanout_proto also gets called
6430 			 * from icmp_inbound_error_fanout, in
6431 			 * which case the msg type is M_CTL.
6432 			 * Don't add info in this case for time
6433 			 * being. In future when there is a
6434 			 * need for knowing the inbound iface
6435 			 * index for ICMP error msgs, then this
6436 			 * can be changed
6437 			 */
6438 			if ((connp->conn_recvif != 0) &&
6439 			    (mp->b_datap->db_type != M_CTL)) {
6440 				/*
6441 				 * the actual data will be contained in
6442 				 * b_cont upon successful return
6443 				 * of the following call else original
6444 				 * mblk is returned
6445 				 */
6446 				ASSERT(recv_ill != NULL);
6447 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6448 			}
6449 			BUMP_MIB(&ip_mib, ipInDelivers);
6450 			putnext(rq, mp);
6451 			if (mctl_present)
6452 				freeb(first_mp);
6453 		}
6454 	}
6455 	CONN_DEC_REF(connp);
6456 }
6457 
6458 /*
6459  * Fanout for TCP packets
6460  * The caller puts <fport, lport> in the ports parameter.
6461  *
6462  * IPQoS Notes
6463  * Before sending it to the client, invoke IPPF processing.
6464  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6465  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6466  * ip_policy is false.
6467  */
6468 static void
6469 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6470     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6471 {
6472 	mblk_t  *first_mp;
6473 	boolean_t secure;
6474 	uint32_t ill_index;
6475 	int	ip_hdr_len;
6476 	tcph_t	*tcph;
6477 	boolean_t syn_present = B_FALSE;
6478 	conn_t	*connp;
6479 
6480 	first_mp = mp;
6481 	if (mctl_present) {
6482 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6483 		mp = first_mp->b_cont;
6484 		secure = ipsec_in_is_secure(first_mp);
6485 		ASSERT(mp != NULL);
6486 	} else {
6487 		secure = B_FALSE;
6488 	}
6489 
6490 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6491 
6492 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6493 	    NULL) {
6494 		/*
6495 		 * No connected connection or listener. Send a
6496 		 * TH_RST via tcp_xmit_listeners_reset.
6497 		 */
6498 
6499 		/* Initiate IPPf processing, if needed. */
6500 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6501 			uint32_t ill_index;
6502 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6503 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6504 			if (first_mp == NULL)
6505 				return;
6506 		}
6507 		BUMP_MIB(&ip_mib, ipInDelivers);
6508 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6509 		    zoneid));
6510 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6511 		return;
6512 	}
6513 
6514 	/*
6515 	 * Allocate the SYN for the TCP connection here itself
6516 	 */
6517 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6518 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6519 		if (IPCL_IS_TCP(connp)) {
6520 			squeue_t *sqp;
6521 
6522 			/*
6523 			 * For fused tcp loopback, assign the eager's
6524 			 * squeue to be that of the active connect's.
6525 			 * Note that we don't check for IP_FF_LOOPBACK
6526 			 * here since this routine gets called only
6527 			 * for loopback (unlike the IPv6 counterpart).
6528 			 */
6529 			ASSERT(Q_TO_CONN(q) != NULL);
6530 			if (do_tcp_fusion &&
6531 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6532 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6533 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6534 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6535 				sqp = Q_TO_CONN(q)->conn_sqp;
6536 			} else {
6537 				sqp = IP_SQUEUE_GET(lbolt);
6538 			}
6539 
6540 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6541 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6542 			syn_present = B_TRUE;
6543 		}
6544 	}
6545 
6546 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6547 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6548 		if ((flags & TH_RST) || (flags & TH_URG)) {
6549 			CONN_DEC_REF(connp);
6550 			freemsg(first_mp);
6551 			return;
6552 		}
6553 		if (flags & TH_ACK) {
6554 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6555 			CONN_DEC_REF(connp);
6556 			return;
6557 		}
6558 
6559 		CONN_DEC_REF(connp);
6560 		freemsg(first_mp);
6561 		return;
6562 	}
6563 
6564 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6565 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6566 		    NULL, mctl_present);
6567 		if (first_mp == NULL) {
6568 			CONN_DEC_REF(connp);
6569 			return;
6570 		}
6571 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6572 			ASSERT(syn_present);
6573 			if (mctl_present) {
6574 				ASSERT(first_mp != mp);
6575 				first_mp->b_datap->db_struioflag |=
6576 				    STRUIO_POLICY;
6577 			} else {
6578 				ASSERT(first_mp == mp);
6579 				mp->b_datap->db_struioflag &=
6580 				    ~STRUIO_EAGER;
6581 				mp->b_datap->db_struioflag |=
6582 				    STRUIO_POLICY;
6583 			}
6584 		} else {
6585 			/*
6586 			 * Discard first_mp early since we're dealing with a
6587 			 * fully-connected conn_t and tcp doesn't do policy in
6588 			 * this case.
6589 			 */
6590 			if (mctl_present) {
6591 				freeb(first_mp);
6592 				mctl_present = B_FALSE;
6593 			}
6594 			first_mp = mp;
6595 		}
6596 	}
6597 
6598 	/*
6599 	 * Initiate policy processing here if needed. If we get here from
6600 	 * icmp_inbound_error_fanout, ip_policy is false.
6601 	 */
6602 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6603 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6604 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6605 		if (mp == NULL) {
6606 			CONN_DEC_REF(connp);
6607 			if (mctl_present)
6608 				freeb(first_mp);
6609 			return;
6610 		} else if (mctl_present) {
6611 			ASSERT(first_mp != mp);
6612 			first_mp->b_cont = mp;
6613 		} else {
6614 			first_mp = mp;
6615 		}
6616 	}
6617 
6618 
6619 
6620 	/* Handle IPv6 socket options. */
6621 	if (!syn_present &&
6622 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6623 		/* Add header */
6624 		ASSERT(recv_ill != NULL);
6625 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6626 		if (mp == NULL) {
6627 			CONN_DEC_REF(connp);
6628 			if (mctl_present)
6629 				freeb(first_mp);
6630 			return;
6631 		} else if (mctl_present) {
6632 			/*
6633 			 * ip_add_info might return a new mp.
6634 			 */
6635 			ASSERT(first_mp != mp);
6636 			first_mp->b_cont = mp;
6637 		} else {
6638 			first_mp = mp;
6639 		}
6640 	}
6641 
6642 	BUMP_MIB(&ip_mib, ipInDelivers);
6643 	if (IPCL_IS_TCP(connp)) {
6644 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6645 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6646 	} else {
6647 		putnext(connp->conn_rq, first_mp);
6648 		CONN_DEC_REF(connp);
6649 	}
6650 }
6651 
6652 /*
6653  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6654  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6655  * Caller is responsible for dropping references to the conn, and freeing
6656  * first_mp.
6657  *
6658  * IPQoS Notes
6659  * Before sending it to the client, invoke IPPF processing. Policy processing
6660  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6661  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6662  * ip_wput_local, ip_policy is false.
6663  */
6664 static void
6665 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6666     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6667     boolean_t ip_policy)
6668 {
6669 	boolean_t	mctl_present = (first_mp != NULL);
6670 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6671 	uint32_t	ill_index;
6672 
6673 	if (mctl_present)
6674 		first_mp->b_cont = mp;
6675 	else
6676 		first_mp = mp;
6677 
6678 	if (CONN_UDP_FLOWCTLD(connp)) {
6679 		BUMP_MIB(&ip_mib, udpInOverflows);
6680 		freemsg(first_mp);
6681 		return;
6682 	}
6683 
6684 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6685 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6686 		    NULL, mctl_present);
6687 		if (first_mp == NULL)
6688 			return;	/* Freed by ipsec_check_inbound_policy(). */
6689 	}
6690 	if (mctl_present)
6691 		freeb(first_mp);
6692 
6693 	if (connp->conn_recvif)
6694 		in_flags = IPF_RECVIF;
6695 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6696 		in_flags |= IPF_RECVSLLA;
6697 
6698 	/* Handle IPv6 options. */
6699 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6700 		in_flags |= IPF_RECVIF;
6701 
6702 	/*
6703 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6704 	 * freed if the packet is dropped. The caller will do so.
6705 	 */
6706 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6707 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6708 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6709 		if (mp == NULL) {
6710 			return;
6711 		}
6712 	}
6713 	if ((in_flags != 0) &&
6714 	    (mp->b_datap->db_type != M_CTL)) {
6715 		/*
6716 		 * The actual data will be contained in b_cont
6717 		 * upon successful return of the following call
6718 		 * else original mblk is returned
6719 		 */
6720 		ASSERT(recv_ill != NULL);
6721 		mp = ip_add_info(mp, recv_ill, in_flags);
6722 	}
6723 	BUMP_MIB(&ip_mib, ipInDelivers);
6724 
6725 	/* Send it upstream */
6726 	CONN_UDP_RECV(connp, mp);
6727 }
6728 
6729 /*
6730  * Fanout for UDP packets.
6731  * The caller puts <fport, lport> in the ports parameter.
6732  *
6733  * If SO_REUSEADDR is set all multicast and broadcast packets
6734  * will be delivered to all streams bound to the same port.
6735  *
6736  * Zones notes:
6737  * Multicast and broadcast packets will be distributed to streams in all zones.
6738  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6739  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6740  * packets. To maintain this behavior with multiple zones, the conns are grouped
6741  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6742  * each zone. If unset, all the following conns in the same zone are skipped.
6743  */
6744 static void
6745 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6746     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6747     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6748 {
6749 	uint32_t	dstport, srcport;
6750 	ipaddr_t	dst;
6751 	mblk_t		*first_mp;
6752 	boolean_t	secure;
6753 	in6_addr_t	v6src;
6754 	conn_t		*connp;
6755 	connf_t		*connfp;
6756 	conn_t		*first_connp;
6757 	conn_t		*next_connp;
6758 	mblk_t		*mp1, *first_mp1;
6759 	ipaddr_t	src;
6760 	zoneid_t	last_zoneid;
6761 	boolean_t	reuseaddr;
6762 	boolean_t	shared_addr;
6763 
6764 	first_mp = mp;
6765 	if (mctl_present) {
6766 		mp = first_mp->b_cont;
6767 		first_mp->b_cont = NULL;
6768 		secure = ipsec_in_is_secure(first_mp);
6769 		ASSERT(mp != NULL);
6770 	} else {
6771 		first_mp = NULL;
6772 		secure = B_FALSE;
6773 	}
6774 
6775 	/* Extract ports in net byte order */
6776 	dstport = htons(ntohl(ports) & 0xFFFF);
6777 	srcport = htons(ntohl(ports) >> 16);
6778 	dst = ipha->ipha_dst;
6779 	src = ipha->ipha_src;
6780 
6781 	shared_addr = (zoneid == ALL_ZONES);
6782 	if (shared_addr) {
6783 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6784 		if (zoneid == ALL_ZONES)
6785 			zoneid = tsol_packet_to_zoneid(mp);
6786 	}
6787 
6788 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6789 	mutex_enter(&connfp->connf_lock);
6790 	connp = connfp->connf_head;
6791 	if (!broadcast && !CLASSD(dst)) {
6792 		/*
6793 		 * Not broadcast or multicast. Send to the one (first)
6794 		 * client we find. No need to check conn_wantpacket()
6795 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6796 		 * IPv4 unicast packets.
6797 		 */
6798 		while ((connp != NULL) &&
6799 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
6800 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
6801 			connp = connp->conn_next;
6802 		}
6803 
6804 		if (connp == NULL || connp->conn_upq == NULL)
6805 			goto notfound;
6806 
6807 		if (is_system_labeled() &&
6808 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6809 		    connp))
6810 			goto notfound;
6811 
6812 		CONN_INC_REF(connp);
6813 		mutex_exit(&connfp->connf_lock);
6814 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6815 		    recv_ill, ip_policy);
6816 		IP_STAT(ip_udp_fannorm);
6817 		CONN_DEC_REF(connp);
6818 		return;
6819 	}
6820 
6821 	/*
6822 	 * Broadcast and multicast case
6823 	 *
6824 	 * Need to check conn_wantpacket().
6825 	 * If SO_REUSEADDR has been set on the first we send the
6826 	 * packet to all clients that have joined the group and
6827 	 * match the port.
6828 	 */
6829 
6830 	while (connp != NULL) {
6831 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6832 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6833 		    (!is_system_labeled() ||
6834 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6835 		    connp)))
6836 			break;
6837 		connp = connp->conn_next;
6838 	}
6839 
6840 	if (connp == NULL || connp->conn_upq == NULL)
6841 		goto notfound;
6842 
6843 	first_connp = connp;
6844 	/*
6845 	 * When SO_REUSEADDR is not set, send the packet only to the first
6846 	 * matching connection in its zone by keeping track of the zoneid.
6847 	 */
6848 	reuseaddr = first_connp->conn_reuseaddr;
6849 	last_zoneid = first_connp->conn_zoneid;
6850 
6851 	CONN_INC_REF(connp);
6852 	connp = connp->conn_next;
6853 	for (;;) {
6854 		while (connp != NULL) {
6855 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6856 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6857 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6858 			    (!is_system_labeled() ||
6859 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6860 			    shared_addr, connp)))
6861 				break;
6862 			connp = connp->conn_next;
6863 		}
6864 		/*
6865 		 * Just copy the data part alone. The mctl part is
6866 		 * needed just for verifying policy and it is never
6867 		 * sent up.
6868 		 */
6869 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6870 		    ((mp1 = copymsg(mp)) == NULL))) {
6871 			/*
6872 			 * No more interested clients or memory
6873 			 * allocation failed
6874 			 */
6875 			connp = first_connp;
6876 			break;
6877 		}
6878 		if (connp->conn_zoneid != last_zoneid) {
6879 			/*
6880 			 * Update the zoneid so that the packet isn't sent to
6881 			 * any more conns in the same zone unless SO_REUSEADDR
6882 			 * is set.
6883 			 */
6884 			reuseaddr = connp->conn_reuseaddr;
6885 			last_zoneid = connp->conn_zoneid;
6886 		}
6887 		if (first_mp != NULL) {
6888 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6889 			    ipsec_info_type == IPSEC_IN);
6890 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6891 			if (first_mp1 == NULL) {
6892 				freemsg(mp1);
6893 				connp = first_connp;
6894 				break;
6895 			}
6896 		} else {
6897 			first_mp1 = NULL;
6898 		}
6899 		CONN_INC_REF(connp);
6900 		mutex_exit(&connfp->connf_lock);
6901 		/*
6902 		 * IPQoS notes: We don't send the packet for policy
6903 		 * processing here, will do it for the last one (below).
6904 		 * i.e. we do it per-packet now, but if we do policy
6905 		 * processing per-conn, then we would need to do it
6906 		 * here too.
6907 		 */
6908 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6909 		    ipha, flags, recv_ill, B_FALSE);
6910 		mutex_enter(&connfp->connf_lock);
6911 		/* Follow the next pointer before releasing the conn. */
6912 		next_connp = connp->conn_next;
6913 		IP_STAT(ip_udp_fanmb);
6914 		CONN_DEC_REF(connp);
6915 		connp = next_connp;
6916 	}
6917 
6918 	/* Last one.  Send it upstream. */
6919 	mutex_exit(&connfp->connf_lock);
6920 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6921 	    ip_policy);
6922 	IP_STAT(ip_udp_fanmb);
6923 	CONN_DEC_REF(connp);
6924 	return;
6925 
6926 notfound:
6927 
6928 	mutex_exit(&connfp->connf_lock);
6929 	IP_STAT(ip_udp_fanothers);
6930 	/*
6931 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6932 	 * have already been matched above, since they live in the IPv4
6933 	 * fanout tables. This implies we only need to
6934 	 * check for IPv6 in6addr_any endpoints here.
6935 	 * Thus we compare using ipv6_all_zeros instead of the destination
6936 	 * address, except for the multicast group membership lookup which
6937 	 * uses the IPv4 destination.
6938 	 */
6939 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6940 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6941 	mutex_enter(&connfp->connf_lock);
6942 	connp = connfp->connf_head;
6943 	if (!broadcast && !CLASSD(dst)) {
6944 		while (connp != NULL) {
6945 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6946 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6947 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6948 			    !connp->conn_ipv6_v6only)
6949 				break;
6950 			connp = connp->conn_next;
6951 		}
6952 
6953 		if (connp != NULL && is_system_labeled() &&
6954 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6955 		    connp))
6956 			connp = NULL;
6957 
6958 		if (connp == NULL || connp->conn_upq == NULL) {
6959 			/*
6960 			 * No one bound to this port.  Is
6961 			 * there a client that wants all
6962 			 * unclaimed datagrams?
6963 			 */
6964 			mutex_exit(&connfp->connf_lock);
6965 
6966 			if (mctl_present)
6967 				first_mp->b_cont = mp;
6968 			else
6969 				first_mp = mp;
6970 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6971 				ip_fanout_proto(q, first_mp, ill, ipha,
6972 				    flags | IP_FF_RAWIP, mctl_present,
6973 				    ip_policy, recv_ill, zoneid);
6974 			} else {
6975 				if (ip_fanout_send_icmp(q, first_mp, flags,
6976 				    ICMP_DEST_UNREACHABLE,
6977 				    ICMP_PORT_UNREACHABLE,
6978 				    mctl_present, zoneid)) {
6979 					BUMP_MIB(&ip_mib, udpNoPorts);
6980 				}
6981 			}
6982 			return;
6983 		}
6984 
6985 		CONN_INC_REF(connp);
6986 		mutex_exit(&connfp->connf_lock);
6987 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6988 		    recv_ill, ip_policy);
6989 		CONN_DEC_REF(connp);
6990 		return;
6991 	}
6992 	/*
6993 	 * IPv4 multicast packet being delivered to an AF_INET6
6994 	 * in6addr_any endpoint.
6995 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6996 	 * and not conn_wantpacket_v6() since any multicast membership is
6997 	 * for an IPv4-mapped multicast address.
6998 	 * The packet is sent to all clients in all zones that have joined the
6999 	 * group and match the port.
7000 	 */
7001 	while (connp != NULL) {
7002 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7003 		    srcport, v6src) &&
7004 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7005 		    (!is_system_labeled() ||
7006 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7007 		    connp)))
7008 			break;
7009 		connp = connp->conn_next;
7010 	}
7011 
7012 	if (connp == NULL || connp->conn_upq == NULL) {
7013 		/*
7014 		 * No one bound to this port.  Is
7015 		 * there a client that wants all
7016 		 * unclaimed datagrams?
7017 		 */
7018 		mutex_exit(&connfp->connf_lock);
7019 
7020 		if (mctl_present)
7021 			first_mp->b_cont = mp;
7022 		else
7023 			first_mp = mp;
7024 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
7025 			ip_fanout_proto(q, first_mp, ill, ipha,
7026 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7027 			    recv_ill, zoneid);
7028 		} else {
7029 			/*
7030 			 * We used to attempt to send an icmp error here, but
7031 			 * since this is known to be a multicast packet
7032 			 * and we don't send icmp errors in response to
7033 			 * multicast, just drop the packet and give up sooner.
7034 			 */
7035 			BUMP_MIB(&ip_mib, udpNoPorts);
7036 			freemsg(first_mp);
7037 		}
7038 		return;
7039 	}
7040 
7041 	first_connp = connp;
7042 
7043 	CONN_INC_REF(connp);
7044 	connp = connp->conn_next;
7045 	for (;;) {
7046 		while (connp != NULL) {
7047 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7048 			    ipv6_all_zeros, srcport, v6src) &&
7049 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7050 			    (!is_system_labeled() ||
7051 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7052 			    shared_addr, connp)))
7053 				break;
7054 			connp = connp->conn_next;
7055 		}
7056 		/*
7057 		 * Just copy the data part alone. The mctl part is
7058 		 * needed just for verifying policy and it is never
7059 		 * sent up.
7060 		 */
7061 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7062 		    ((mp1 = copymsg(mp)) == NULL))) {
7063 			/*
7064 			 * No more intested clients or memory
7065 			 * allocation failed
7066 			 */
7067 			connp = first_connp;
7068 			break;
7069 		}
7070 		if (first_mp != NULL) {
7071 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7072 			    ipsec_info_type == IPSEC_IN);
7073 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7074 			if (first_mp1 == NULL) {
7075 				freemsg(mp1);
7076 				connp = first_connp;
7077 				break;
7078 			}
7079 		} else {
7080 			first_mp1 = NULL;
7081 		}
7082 		CONN_INC_REF(connp);
7083 		mutex_exit(&connfp->connf_lock);
7084 		/*
7085 		 * IPQoS notes: We don't send the packet for policy
7086 		 * processing here, will do it for the last one (below).
7087 		 * i.e. we do it per-packet now, but if we do policy
7088 		 * processing per-conn, then we would need to do it
7089 		 * here too.
7090 		 */
7091 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
7092 		    ipha, flags, recv_ill, B_FALSE);
7093 		mutex_enter(&connfp->connf_lock);
7094 		/* Follow the next pointer before releasing the conn. */
7095 		next_connp = connp->conn_next;
7096 		CONN_DEC_REF(connp);
7097 		connp = next_connp;
7098 	}
7099 
7100 	/* Last one.  Send it upstream. */
7101 	mutex_exit(&connfp->connf_lock);
7102 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
7103 	    ip_policy);
7104 	CONN_DEC_REF(connp);
7105 }
7106 
7107 /*
7108  * Complete the ip_wput header so that it
7109  * is possible to generate ICMP
7110  * errors.
7111  */
7112 int
7113 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
7114 {
7115 	ire_t *ire;
7116 
7117 	if (ipha->ipha_src == INADDR_ANY) {
7118 		ire = ire_lookup_local(zoneid);
7119 		if (ire == NULL) {
7120 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7121 			return (1);
7122 		}
7123 		ipha->ipha_src = ire->ire_addr;
7124 		ire_refrele(ire);
7125 	}
7126 	ipha->ipha_ttl = ip_def_ttl;
7127 	ipha->ipha_hdr_checksum = 0;
7128 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7129 	return (0);
7130 }
7131 
7132 /*
7133  * Nobody should be sending
7134  * packets up this stream
7135  */
7136 static void
7137 ip_lrput(queue_t *q, mblk_t *mp)
7138 {
7139 	mblk_t *mp1;
7140 
7141 	switch (mp->b_datap->db_type) {
7142 	case M_FLUSH:
7143 		/* Turn around */
7144 		if (*mp->b_rptr & FLUSHW) {
7145 			*mp->b_rptr &= ~FLUSHR;
7146 			qreply(q, mp);
7147 			return;
7148 		}
7149 		break;
7150 	}
7151 	/* Could receive messages that passed through ar_rput */
7152 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7153 		mp1->b_prev = mp1->b_next = NULL;
7154 	freemsg(mp);
7155 }
7156 
7157 /* Nobody should be sending packets down this stream */
7158 /* ARGSUSED */
7159 void
7160 ip_lwput(queue_t *q, mblk_t *mp)
7161 {
7162 	freemsg(mp);
7163 }
7164 
7165 /*
7166  * Move the first hop in any source route to ipha_dst and remove that part of
7167  * the source route.  Called by other protocols.  Errors in option formatting
7168  * are ignored - will be handled by ip_wput_options Return the final
7169  * destination (either ipha_dst or the last entry in a source route.)
7170  */
7171 ipaddr_t
7172 ip_massage_options(ipha_t *ipha)
7173 {
7174 	ipoptp_t	opts;
7175 	uchar_t		*opt;
7176 	uint8_t		optval;
7177 	uint8_t		optlen;
7178 	ipaddr_t	dst;
7179 	int		i;
7180 	ire_t		*ire;
7181 
7182 	ip2dbg(("ip_massage_options\n"));
7183 	dst = ipha->ipha_dst;
7184 	for (optval = ipoptp_first(&opts, ipha);
7185 	    optval != IPOPT_EOL;
7186 	    optval = ipoptp_next(&opts)) {
7187 		opt = opts.ipoptp_cur;
7188 		switch (optval) {
7189 			uint8_t off;
7190 		case IPOPT_SSRR:
7191 		case IPOPT_LSRR:
7192 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7193 				ip1dbg(("ip_massage_options: bad src route\n"));
7194 				break;
7195 			}
7196 			optlen = opts.ipoptp_len;
7197 			off = opt[IPOPT_OFFSET];
7198 			off--;
7199 		redo_srr:
7200 			if (optlen < IP_ADDR_LEN ||
7201 			    off > optlen - IP_ADDR_LEN) {
7202 				/* End of source route */
7203 				ip1dbg(("ip_massage_options: end of SR\n"));
7204 				break;
7205 			}
7206 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7207 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7208 			    ntohl(dst)));
7209 			/*
7210 			 * Check if our address is present more than
7211 			 * once as consecutive hops in source route.
7212 			 * XXX verify per-interface ip_forwarding
7213 			 * for source route?
7214 			 */
7215 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7216 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
7217 			if (ire != NULL) {
7218 				ire_refrele(ire);
7219 				off += IP_ADDR_LEN;
7220 				goto redo_srr;
7221 			}
7222 			if (dst == htonl(INADDR_LOOPBACK)) {
7223 				ip1dbg(("ip_massage_options: loopback addr in "
7224 				    "source route!\n"));
7225 				break;
7226 			}
7227 			/*
7228 			 * Update ipha_dst to be the first hop and remove the
7229 			 * first hop from the source route (by overwriting
7230 			 * part of the option with NOP options).
7231 			 */
7232 			ipha->ipha_dst = dst;
7233 			/* Put the last entry in dst */
7234 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7235 			    3;
7236 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7237 
7238 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7239 			    ntohl(dst)));
7240 			/* Move down and overwrite */
7241 			opt[IP_ADDR_LEN] = opt[0];
7242 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7243 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7244 			for (i = 0; i < IP_ADDR_LEN; i++)
7245 				opt[i] = IPOPT_NOP;
7246 			break;
7247 		}
7248 	}
7249 	return (dst);
7250 }
7251 
7252 /*
7253  * This function's job is to forward data to the reverse tunnel (FA->HA)
7254  * after doing a few checks. It is assumed that the incoming interface
7255  * of the packet is always different than the outgoing interface and the
7256  * ire_type of the found ire has to be a non-resolver type.
7257  *
7258  * IPQoS notes
7259  * IP policy is invoked twice for a forwarded packet, once on the read side
7260  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7261  * enabled.
7262  */
7263 static void
7264 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7265 {
7266 	ipha_t		*ipha;
7267 	queue_t		*q;
7268 	uint32_t 	pkt_len;
7269 #define	rptr    ((uchar_t *)ipha)
7270 	uint32_t 	sum;
7271 	uint32_t 	max_frag;
7272 	mblk_t		*first_mp;
7273 	uint32_t	ill_index;
7274 	ipxmit_state_t	pktxmit_state;
7275 	ill_t		*out_ill;
7276 
7277 	ASSERT(ire != NULL);
7278 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7279 	ASSERT(ire->ire_stq != NULL);
7280 
7281 	/* Initiate read side IPPF processing */
7282 	if (IPP_ENABLED(IPP_FWD_IN)) {
7283 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7284 		ip_process(IPP_FWD_IN, &mp, ill_index);
7285 		if (mp == NULL) {
7286 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7287 			    "dropped during IPPF processing\n"));
7288 			return;
7289 		}
7290 	}
7291 
7292 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7293 		ILLF_ROUTER) == 0) ||
7294 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7295 		BUMP_MIB(&ip_mib, ipForwProhibits);
7296 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7297 		    "forwarding is not turned on\n"));
7298 		goto drop_pkt;
7299 	}
7300 
7301 	/*
7302 	 * Don't forward if the interface is down
7303 	 */
7304 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7305 		BUMP_MIB(&ip_mib, ipInDiscards);
7306 		goto drop_pkt;
7307 	}
7308 
7309 	ipha = (ipha_t *)mp->b_rptr;
7310 	pkt_len = ntohs(ipha->ipha_length);
7311 	/* Adjust the checksum to reflect the ttl decrement. */
7312 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7313 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7314 	if (ipha->ipha_ttl-- <= 1) {
7315 		if (ip_csum_hdr(ipha)) {
7316 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7317 			goto drop_pkt;
7318 		}
7319 		q = ire->ire_stq;
7320 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7321 		    BPRI_HI)) == NULL) {
7322 			goto drop_pkt;
7323 		}
7324 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7325 		/* Sent by forwarding path, and router is global zone */
7326 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7327 		    GLOBAL_ZONEID);
7328 		return;
7329 	}
7330 
7331 	/* Get the ill_index of the ILL */
7332 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7333 
7334 	/*
7335 	 * This location is chosen for the placement of the forwarding hook
7336 	 * because at this point we know that we have a path out for the
7337 	 * packet but haven't yet applied any logic (such as fragmenting)
7338 	 * that happen as part of transmitting the packet out.
7339 	 */
7340 	out_ill = ire->ire_ipif->ipif_ill;
7341 
7342 	DTRACE_PROBE4(ip4__forwarding__start,
7343 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7344 
7345 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
7346 	    in_ill, out_ill, ipha, mp, mp);
7347 
7348 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7349 
7350 	if (mp == NULL)
7351 		return;
7352 	pkt_len = ntohs(ipha->ipha_length);
7353 
7354 	/*
7355 	 * ip_mrtun_forward is only used by foreign agent to reverse
7356 	 * tunnel the incoming packet. So it does not do any option
7357 	 * processing for source routing.
7358 	 */
7359 	max_frag = ire->ire_max_frag;
7360 	if (pkt_len > max_frag) {
7361 		/*
7362 		 * It needs fragging on its way out.  We haven't
7363 		 * verified the header checksum yet.  Since we
7364 		 * are going to put a surely good checksum in the
7365 		 * outgoing header, we have to make sure that it
7366 		 * was good coming in.
7367 		 */
7368 		if (ip_csum_hdr(ipha)) {
7369 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7370 			goto drop_pkt;
7371 		}
7372 
7373 		/* Initiate write side IPPF processing */
7374 		if (IPP_ENABLED(IPP_FWD_OUT)) {
7375 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7376 			if (mp == NULL) {
7377 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7378 				    "dropped/deferred during ip policy "\
7379 				    "processing\n"));
7380 				return;
7381 			}
7382 		}
7383 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7384 		    BPRI_HI)) == NULL) {
7385 			goto drop_pkt;
7386 		}
7387 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7388 		mp = first_mp;
7389 
7390 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
7391 		return;
7392 	}
7393 
7394 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7395 
7396 	ASSERT(ire->ire_ipif != NULL);
7397 
7398 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7399 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7400 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
7401 	    NULL, out_ill, ipha, mp, mp);
7402 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7403 	if (mp == NULL)
7404 		return;
7405 
7406 	/* Now send the packet to the tunnel interface */
7407 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7408 	q = ire->ire_stq;
7409 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7410 	if ((pktxmit_state == SEND_FAILED) ||
7411 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7412 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7413 		    q->q_ptr));
7414 	}
7415 
7416 	return;
7417 
7418 drop_pkt:;
7419 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7420 	freemsg(mp);
7421 #undef	rptr
7422 }
7423 
7424 /*
7425  * Fills the ipsec_out_t data structure with appropriate fields and
7426  * prepends it to mp which contains the IP hdr + data that was meant
7427  * to be forwarded. Please note that ipsec_out_info data structure
7428  * is used here to communicate the outgoing ill path at ip_wput()
7429  * for the ICMP error packet. This has nothing to do with ipsec IP
7430  * security. ipsec_out_t is really used to pass the info to the module
7431  * IP where this information cannot be extracted from conn.
7432  * This functions is called by ip_mrtun_forward().
7433  */
7434 void
7435 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7436 {
7437 	ipsec_out_t	*io;
7438 
7439 	ASSERT(xmit_ill != NULL);
7440 	first_mp->b_datap->db_type = M_CTL;
7441 	first_mp->b_wptr += sizeof (ipsec_info_t);
7442 	/*
7443 	 * This is to pass info to ip_wput in absence of conn.
7444 	 * ipsec_out_secure will be B_FALSE because of this.
7445 	 * Thus ipsec_out_secure being B_FALSE indicates that
7446 	 * this is not IPSEC security related information.
7447 	 */
7448 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7449 	io = (ipsec_out_t *)first_mp->b_rptr;
7450 	io->ipsec_out_type = IPSEC_OUT;
7451 	io->ipsec_out_len = sizeof (ipsec_out_t);
7452 	first_mp->b_cont = mp;
7453 	io->ipsec_out_ill_index =
7454 	    xmit_ill->ill_phyint->phyint_ifindex;
7455 	io->ipsec_out_xmit_if = B_TRUE;
7456 }
7457 
7458 /*
7459  * Return the network mask
7460  * associated with the specified address.
7461  */
7462 ipaddr_t
7463 ip_net_mask(ipaddr_t addr)
7464 {
7465 	uchar_t	*up = (uchar_t *)&addr;
7466 	ipaddr_t mask = 0;
7467 	uchar_t	*maskp = (uchar_t *)&mask;
7468 
7469 #if defined(__i386) || defined(__amd64)
7470 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7471 #endif
7472 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7473 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7474 #endif
7475 	if (CLASSD(addr)) {
7476 		maskp[0] = 0xF0;
7477 		return (mask);
7478 	}
7479 	if (addr == 0)
7480 		return (0);
7481 	maskp[0] = 0xFF;
7482 	if ((up[0] & 0x80) == 0)
7483 		return (mask);
7484 
7485 	maskp[1] = 0xFF;
7486 	if ((up[0] & 0xC0) == 0x80)
7487 		return (mask);
7488 
7489 	maskp[2] = 0xFF;
7490 	if ((up[0] & 0xE0) == 0xC0)
7491 		return (mask);
7492 
7493 	/* Must be experimental or multicast, indicate as much */
7494 	return ((ipaddr_t)0);
7495 }
7496 
7497 /*
7498  * Select an ill for the packet by considering load spreading across
7499  * a different ill in the group if dst_ill is part of some group.
7500  */
7501 ill_t *
7502 ip_newroute_get_dst_ill(ill_t *dst_ill)
7503 {
7504 	ill_t *ill;
7505 
7506 	/*
7507 	 * We schedule irrespective of whether the source address is
7508 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7509 	 */
7510 	ill = illgrp_scheduler(dst_ill);
7511 	if (ill == NULL)
7512 		return (NULL);
7513 
7514 	/*
7515 	 * For groups with names ip_sioctl_groupname ensures that all
7516 	 * ills are of same type. For groups without names, ifgrp_insert
7517 	 * ensures this.
7518 	 */
7519 	ASSERT(dst_ill->ill_type == ill->ill_type);
7520 
7521 	return (ill);
7522 }
7523 
7524 /*
7525  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7526  */
7527 ill_t *
7528 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7529 {
7530 	ill_t *ret_ill;
7531 
7532 	ASSERT(ifindex != 0);
7533 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7534 	if (ret_ill == NULL ||
7535 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7536 		if (isv6) {
7537 			if (ill != NULL) {
7538 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7539 			} else {
7540 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7541 			}
7542 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7543 			    "bad ifindex %d.\n", ifindex));
7544 		} else {
7545 			BUMP_MIB(&ip_mib, ipOutDiscards);
7546 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7547 			    "bad ifindex %d.\n", ifindex));
7548 		}
7549 		if (ret_ill != NULL)
7550 			ill_refrele(ret_ill);
7551 		freemsg(first_mp);
7552 		return (NULL);
7553 	}
7554 
7555 	return (ret_ill);
7556 }
7557 
7558 /*
7559  * IPv4 -
7560  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7561  * out a packet to a destination address for which we do not have specific
7562  * (or sufficient) routing information.
7563  *
7564  * NOTE : These are the scopes of some of the variables that point at IRE,
7565  *	  which needs to be followed while making any future modifications
7566  *	  to avoid memory leaks.
7567  *
7568  *	- ire and sire are the entries looked up initially by
7569  *	  ire_ftable_lookup.
7570  *	- ipif_ire is used to hold the interface ire associated with
7571  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7572  *	  it before branching out to error paths.
7573  *	- save_ire is initialized before ire_create, so that ire returned
7574  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7575  *	  before breaking out of the switch.
7576  *
7577  *	Thus on failures, we have to REFRELE only ire and sire, if they
7578  *	are not NULL.
7579  */
7580 void
7581 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7582     zoneid_t zoneid)
7583 {
7584 	areq_t	*areq;
7585 	ipaddr_t gw = 0;
7586 	ire_t	*ire = NULL;
7587 	mblk_t	*res_mp;
7588 	ipaddr_t *addrp;
7589 	ipaddr_t nexthop_addr;
7590 	ipif_t  *src_ipif = NULL;
7591 	ill_t	*dst_ill = NULL;
7592 	ipha_t  *ipha;
7593 	ire_t	*sire = NULL;
7594 	mblk_t	*first_mp;
7595 	ire_t	*save_ire;
7596 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7597 	ushort_t ire_marks = 0;
7598 	boolean_t mctl_present;
7599 	ipsec_out_t *io;
7600 	mblk_t	*saved_mp;
7601 	ire_t	*first_sire = NULL;
7602 	mblk_t	*copy_mp = NULL;
7603 	mblk_t	*xmit_mp = NULL;
7604 	ipaddr_t save_dst;
7605 	uint32_t multirt_flags =
7606 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7607 	boolean_t multirt_is_resolvable;
7608 	boolean_t multirt_resolve_next;
7609 	boolean_t do_attach_ill = B_FALSE;
7610 	boolean_t ip_nexthop = B_FALSE;
7611 	tsol_ire_gw_secattr_t *attrp = NULL;
7612 	tsol_gcgrp_t *gcgrp = NULL;
7613 	tsol_gcgrp_addr_t ga;
7614 
7615 	if (ip_debug > 2) {
7616 		/* ip1dbg */
7617 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7618 	}
7619 
7620 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7621 	if (mctl_present) {
7622 		io = (ipsec_out_t *)first_mp->b_rptr;
7623 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7624 		ASSERT(zoneid == io->ipsec_out_zoneid);
7625 		ASSERT(zoneid != ALL_ZONES);
7626 	}
7627 
7628 	ipha = (ipha_t *)mp->b_rptr;
7629 
7630 	/* All multicast lookups come through ip_newroute_ipif() */
7631 	if (CLASSD(dst)) {
7632 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7633 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7634 		freemsg(first_mp);
7635 		return;
7636 	}
7637 
7638 	if (mctl_present && io->ipsec_out_attach_if) {
7639 		/* ip_grab_attach_ill returns a held ill */
7640 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7641 		    io->ipsec_out_ill_index, B_FALSE);
7642 
7643 		/* Failure case frees things for us. */
7644 		if (attach_ill == NULL)
7645 			return;
7646 
7647 		/*
7648 		 * Check if we need an ire that will not be
7649 		 * looked up by anybody else i.e. HIDDEN.
7650 		 */
7651 		if (ill_is_probeonly(attach_ill))
7652 			ire_marks = IRE_MARK_HIDDEN;
7653 	}
7654 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7655 		ip_nexthop = B_TRUE;
7656 		nexthop_addr = io->ipsec_out_nexthop_addr;
7657 	}
7658 	/*
7659 	 * If this IRE is created for forwarding or it is not for
7660 	 * traffic for congestion controlled protocols, mark it as temporary.
7661 	 */
7662 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7663 		ire_marks |= IRE_MARK_TEMPORARY;
7664 
7665 	/*
7666 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7667 	 * chain until it gets the most specific information available.
7668 	 * For example, we know that there is no IRE_CACHE for this dest,
7669 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7670 	 * ire_ftable_lookup will look up the gateway, etc.
7671 	 * Check if in_ill != NULL. If it is true, the packet must be
7672 	 * from an incoming interface where RTA_SRCIFP is set.
7673 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7674 	 * to the destination, of equal netmask length in the forward table,
7675 	 * will be recursively explored. If no information is available
7676 	 * for the final gateway of that route, we force the returned ire
7677 	 * to be equal to sire using MATCH_IRE_PARENT.
7678 	 * At least, in this case we have a starting point (in the buckets)
7679 	 * to look for other routes to the destination in the forward table.
7680 	 * This is actually used only for multirouting, where a list
7681 	 * of routes has to be processed in sequence.
7682 	 *
7683 	 * In the process of coming up with the most specific information,
7684 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7685 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7686 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7687 	 * Two caveats when handling incomplete ire's in ip_newroute:
7688 	 * - we should be careful when accessing its ire_nce (specifically
7689 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7690 	 * - not all legacy code path callers are prepared to handle
7691 	 *   incomplete ire's, so we should not create/add incomplete
7692 	 *   ire_cache entries here. (See discussion about temporary solution
7693 	 *   further below).
7694 	 *
7695 	 * In order to minimize packet dropping, and to preserve existing
7696 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7697 	 * gateway, and instead use the IF_RESOLVER ire to send out
7698 	 * another request to ARP (this is achieved by passing the
7699 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7700 	 * arp response comes back in ip_wput_nondata, we will create
7701 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7702 	 *
7703 	 * Note that this is a temporary solution; the correct solution is
7704 	 * to create an incomplete  per-dst ire_cache entry, and send the
7705 	 * packet out when the gw's nce is resolved. In order to achieve this,
7706 	 * all packet processing must have been completed prior to calling
7707 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7708 	 * to be modified to accomodate this solution.
7709 	 */
7710 	if (in_ill != NULL) {
7711 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7712 		    in_ill, MATCH_IRE_TYPE);
7713 	} else if (ip_nexthop) {
7714 		/*
7715 		 * The first time we come here, we look for an IRE_INTERFACE
7716 		 * entry for the specified nexthop, set the dst to be the
7717 		 * nexthop address and create an IRE_CACHE entry for the
7718 		 * nexthop. The next time around, we are able to find an
7719 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7720 		 * nexthop address and create an IRE_CACHE entry for the
7721 		 * destination address via the specified nexthop.
7722 		 */
7723 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7724 		    MBLK_GETLABEL(mp));
7725 		if (ire != NULL) {
7726 			gw = nexthop_addr;
7727 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7728 		} else {
7729 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7730 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7731 			    MBLK_GETLABEL(mp),
7732 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7733 			if (ire != NULL) {
7734 				dst = nexthop_addr;
7735 			}
7736 		}
7737 	} else if (attach_ill == NULL) {
7738 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7739 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7740 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7741 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7742 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7743 	} else {
7744 		/*
7745 		 * attach_ill is set only for communicating with
7746 		 * on-link hosts. So, don't look for DEFAULT.
7747 		 */
7748 		ipif_t	*attach_ipif;
7749 
7750 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7751 		if (attach_ipif == NULL) {
7752 			ill_refrele(attach_ill);
7753 			goto icmp_err_ret;
7754 		}
7755 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7756 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7757 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7758 		    MATCH_IRE_SECATTR);
7759 		ipif_refrele(attach_ipif);
7760 	}
7761 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7762 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7763 
7764 	/*
7765 	 * This loop is run only once in most cases.
7766 	 * We loop to resolve further routes only when the destination
7767 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7768 	 */
7769 	do {
7770 		/* Clear the previous iteration's values */
7771 		if (src_ipif != NULL) {
7772 			ipif_refrele(src_ipif);
7773 			src_ipif = NULL;
7774 		}
7775 		if (dst_ill != NULL) {
7776 			ill_refrele(dst_ill);
7777 			dst_ill = NULL;
7778 		}
7779 
7780 		multirt_resolve_next = B_FALSE;
7781 		/*
7782 		 * We check if packets have to be multirouted.
7783 		 * In this case, given the current <ire, sire> couple,
7784 		 * we look for the next suitable <ire, sire>.
7785 		 * This check is done in ire_multirt_lookup(),
7786 		 * which applies various criteria to find the next route
7787 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7788 		 * unchanged if it detects it has not been tried yet.
7789 		 */
7790 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7791 			ip3dbg(("ip_newroute: starting next_resolution "
7792 			    "with first_mp %p, tag %d\n",
7793 			    (void *)first_mp,
7794 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7795 
7796 			ASSERT(sire != NULL);
7797 			multirt_is_resolvable =
7798 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7799 				MBLK_GETLABEL(mp));
7800 
7801 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7802 			    "ire %p, sire %p\n",
7803 			    multirt_is_resolvable,
7804 			    (void *)ire, (void *)sire));
7805 
7806 			if (!multirt_is_resolvable) {
7807 				/*
7808 				 * No more multirt route to resolve; give up
7809 				 * (all routes resolved or no more
7810 				 * resolvable routes).
7811 				 */
7812 				if (ire != NULL) {
7813 					ire_refrele(ire);
7814 					ire = NULL;
7815 				}
7816 			} else {
7817 				ASSERT(sire != NULL);
7818 				ASSERT(ire != NULL);
7819 				/*
7820 				 * We simply use first_sire as a flag that
7821 				 * indicates if a resolvable multirt route
7822 				 * has already been found.
7823 				 * If it is not the case, we may have to send
7824 				 * an ICMP error to report that the
7825 				 * destination is unreachable.
7826 				 * We do not IRE_REFHOLD first_sire.
7827 				 */
7828 				if (first_sire == NULL) {
7829 					first_sire = sire;
7830 				}
7831 			}
7832 		}
7833 		if (ire == NULL) {
7834 			if (ip_debug > 3) {
7835 				/* ip2dbg */
7836 				pr_addr_dbg("ip_newroute: "
7837 				    "can't resolve %s\n", AF_INET, &dst);
7838 			}
7839 			ip3dbg(("ip_newroute: "
7840 			    "ire %p, sire %p, first_sire %p\n",
7841 			    (void *)ire, (void *)sire, (void *)first_sire));
7842 
7843 			if (sire != NULL) {
7844 				ire_refrele(sire);
7845 				sire = NULL;
7846 			}
7847 
7848 			if (first_sire != NULL) {
7849 				/*
7850 				 * At least one multirt route has been found
7851 				 * in the same call to ip_newroute();
7852 				 * there is no need to report an ICMP error.
7853 				 * first_sire was not IRE_REFHOLDed.
7854 				 */
7855 				MULTIRT_DEBUG_UNTAG(first_mp);
7856 				freemsg(first_mp);
7857 				return;
7858 			}
7859 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7860 			    RTA_DST);
7861 			if (attach_ill != NULL)
7862 				ill_refrele(attach_ill);
7863 			goto icmp_err_ret;
7864 		}
7865 
7866 		/*
7867 		 * When RTA_SRCIFP is used to add a route, then an interface
7868 		 * route is added in the source interface's routing table.
7869 		 * If the outgoing interface of this route is of type
7870 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7871 		 * ire_nce->nce_res_mp is set to NULL.
7872 		 * Later, when this route is first used for forwarding
7873 		 * a packet, ip_newroute() is called
7874 		 * to resolve the hardware address of the outgoing ipif.
7875 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7876 		 * source interface based table. We only come here if the
7877 		 * outgoing interface is a resolver interface and we don't
7878 		 * have the ire_nce->nce_res_mp information yet.
7879 		 * If in_ill is not null that means it is called from
7880 		 * ip_rput.
7881 		 */
7882 
7883 		ASSERT(ire->ire_in_ill == NULL ||
7884 		    (ire->ire_type == IRE_IF_RESOLVER &&
7885 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
7886 
7887 		/*
7888 		 * Verify that the returned IRE does not have either
7889 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7890 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7891 		 */
7892 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7893 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7894 			if (attach_ill != NULL)
7895 				ill_refrele(attach_ill);
7896 			goto icmp_err_ret;
7897 		}
7898 		/*
7899 		 * Increment the ire_ob_pkt_count field for ire if it is an
7900 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7901 		 * increment the same for the parent IRE, sire, if it is some
7902 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7903 		 * and HOST_REDIRECT).
7904 		 */
7905 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7906 			UPDATE_OB_PKT_COUNT(ire);
7907 			ire->ire_last_used_time = lbolt;
7908 		}
7909 
7910 		if (sire != NULL) {
7911 			gw = sire->ire_gateway_addr;
7912 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7913 			    IRE_INTERFACE)) == 0);
7914 			UPDATE_OB_PKT_COUNT(sire);
7915 			sire->ire_last_used_time = lbolt;
7916 		}
7917 		/*
7918 		 * We have a route to reach the destination.
7919 		 *
7920 		 * 1) If the interface is part of ill group, try to get a new
7921 		 *    ill taking load spreading into account.
7922 		 *
7923 		 * 2) After selecting the ill, get a source address that
7924 		 *    might create good inbound load spreading.
7925 		 *    ipif_select_source does this for us.
7926 		 *
7927 		 * If the application specified the ill (ifindex), we still
7928 		 * load spread. Only if the packets needs to go out
7929 		 * specifically on a given ill e.g. binding to
7930 		 * IPIF_NOFAILOVER address, then we don't try to use a
7931 		 * different ill for load spreading.
7932 		 */
7933 		if (attach_ill == NULL) {
7934 			/*
7935 			 * Don't perform outbound load spreading in the
7936 			 * case of an RTF_MULTIRT route, as we actually
7937 			 * typically want to replicate outgoing packets
7938 			 * through particular interfaces.
7939 			 */
7940 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7941 				dst_ill = ire->ire_ipif->ipif_ill;
7942 				/* for uniformity */
7943 				ill_refhold(dst_ill);
7944 			} else {
7945 				/*
7946 				 * If we are here trying to create an IRE_CACHE
7947 				 * for an offlink destination and have the
7948 				 * IRE_CACHE for the next hop and the latter is
7949 				 * using virtual IP source address selection i.e
7950 				 * it's ire->ire_ipif is pointing to a virtual
7951 				 * network interface (vni) then
7952 				 * ip_newroute_get_dst_ll() will return the vni
7953 				 * interface as the dst_ill. Since the vni is
7954 				 * virtual i.e not associated with any physical
7955 				 * interface, it cannot be the dst_ill, hence
7956 				 * in such a case call ip_newroute_get_dst_ll()
7957 				 * with the stq_ill instead of the ire_ipif ILL.
7958 				 * The function returns a refheld ill.
7959 				 */
7960 				if ((ire->ire_type == IRE_CACHE) &&
7961 				    IS_VNI(ire->ire_ipif->ipif_ill))
7962 					dst_ill = ip_newroute_get_dst_ill(
7963 						ire->ire_stq->q_ptr);
7964 				else
7965 					dst_ill = ip_newroute_get_dst_ill(
7966 						ire->ire_ipif->ipif_ill);
7967 			}
7968 			if (dst_ill == NULL) {
7969 				if (ip_debug > 2) {
7970 					pr_addr_dbg("ip_newroute: "
7971 					    "no dst ill for dst"
7972 					    " %s\n", AF_INET, &dst);
7973 				}
7974 				goto icmp_err_ret;
7975 			}
7976 		} else {
7977 			dst_ill = ire->ire_ipif->ipif_ill;
7978 			/* for uniformity */
7979 			ill_refhold(dst_ill);
7980 			/*
7981 			 * We should have found a route matching ill as we
7982 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7983 			 * Rather than asserting, when there is a mismatch,
7984 			 * we just drop the packet.
7985 			 */
7986 			if (dst_ill != attach_ill) {
7987 				ip0dbg(("ip_newroute: Packet dropped as "
7988 				    "IPIF_NOFAILOVER ill is %s, "
7989 				    "ire->ire_ipif->ipif_ill is %s\n",
7990 				    attach_ill->ill_name,
7991 				    dst_ill->ill_name));
7992 				ill_refrele(attach_ill);
7993 				goto icmp_err_ret;
7994 			}
7995 		}
7996 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7997 		if (attach_ill != NULL) {
7998 			ill_refrele(attach_ill);
7999 			attach_ill = NULL;
8000 			do_attach_ill = B_TRUE;
8001 		}
8002 		ASSERT(dst_ill != NULL);
8003 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8004 
8005 		/*
8006 		 * Pick the best source address from dst_ill.
8007 		 *
8008 		 * 1) If it is part of a multipathing group, we would
8009 		 *    like to spread the inbound packets across different
8010 		 *    interfaces. ipif_select_source picks a random source
8011 		 *    across the different ills in the group.
8012 		 *
8013 		 * 2) If it is not part of a multipathing group, we try
8014 		 *    to pick the source address from the destination
8015 		 *    route. Clustering assumes that when we have multiple
8016 		 *    prefixes hosted on an interface, the prefix of the
8017 		 *    source address matches the prefix of the destination
8018 		 *    route. We do this only if the address is not
8019 		 *    DEPRECATED.
8020 		 *
8021 		 * 3) If the conn is in a different zone than the ire, we
8022 		 *    need to pick a source address from the right zone.
8023 		 *
8024 		 * NOTE : If we hit case (1) above, the prefix of the source
8025 		 *	  address picked may not match the prefix of the
8026 		 *	  destination routes prefix as ipif_select_source
8027 		 *	  does not look at "dst" while picking a source
8028 		 *	  address.
8029 		 *	  If we want the same behavior as (2), we will need
8030 		 *	  to change the behavior of ipif_select_source.
8031 		 */
8032 		ASSERT(src_ipif == NULL);
8033 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8034 			/*
8035 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8036 			 * Check that the ipif matching the requested source
8037 			 * address still exists.
8038 			 */
8039 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8040 			    zoneid, NULL, NULL, NULL, NULL);
8041 		}
8042 		if (src_ipif == NULL) {
8043 			ire_marks |= IRE_MARK_USESRC_CHECK;
8044 			if ((dst_ill->ill_group != NULL) ||
8045 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8046 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8047 			    ire->ire_zoneid != ALL_ZONES) ||
8048 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8049 				/*
8050 				 * If the destination is reachable via a
8051 				 * given gateway, the selected source address
8052 				 * should be in the same subnet as the gateway.
8053 				 * Otherwise, the destination is not reachable.
8054 				 *
8055 				 * If there are no interfaces on the same subnet
8056 				 * as the destination, ipif_select_source gives
8057 				 * first non-deprecated interface which might be
8058 				 * on a different subnet than the gateway.
8059 				 * This is not desirable. Hence pass the dst_ire
8060 				 * source address to ipif_select_source.
8061 				 * It is sure that the destination is reachable
8062 				 * with the dst_ire source address subnet.
8063 				 * So passing dst_ire source address to
8064 				 * ipif_select_source will make sure that the
8065 				 * selected source will be on the same subnet
8066 				 * as dst_ire source address.
8067 				 */
8068 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8069 				src_ipif = ipif_select_source(dst_ill, saddr,
8070 				    zoneid);
8071 				if (src_ipif == NULL) {
8072 					if (ip_debug > 2) {
8073 						pr_addr_dbg("ip_newroute: "
8074 						    "no src for dst %s ",
8075 						    AF_INET, &dst);
8076 						printf("through interface %s\n",
8077 						    dst_ill->ill_name);
8078 					}
8079 					goto icmp_err_ret;
8080 				}
8081 			} else {
8082 				src_ipif = ire->ire_ipif;
8083 				ASSERT(src_ipif != NULL);
8084 				/* hold src_ipif for uniformity */
8085 				ipif_refhold(src_ipif);
8086 			}
8087 		}
8088 
8089 		/*
8090 		 * Assign a source address while we have the conn.
8091 		 * We can't have ip_wput_ire pick a source address when the
8092 		 * packet returns from arp since we need to look at
8093 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8094 		 * going through arp.
8095 		 *
8096 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8097 		 *	  it uses ip6i to store this information.
8098 		 */
8099 		if (ipha->ipha_src == INADDR_ANY &&
8100 		    (connp == NULL || !connp->conn_unspec_src)) {
8101 			ipha->ipha_src = src_ipif->ipif_src_addr;
8102 		}
8103 		if (ip_debug > 3) {
8104 			/* ip2dbg */
8105 			pr_addr_dbg("ip_newroute: first hop %s\n",
8106 			    AF_INET, &gw);
8107 		}
8108 		ip2dbg(("\tire type %s (%d)\n",
8109 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8110 
8111 		/*
8112 		 * The TTL of multirouted packets is bounded by the
8113 		 * ip_multirt_ttl ndd variable.
8114 		 */
8115 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8116 			/* Force TTL of multirouted packets */
8117 			if ((ip_multirt_ttl > 0) &&
8118 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
8119 				ip2dbg(("ip_newroute: forcing multirt TTL "
8120 				    "to %d (was %d), dst 0x%08x\n",
8121 				    ip_multirt_ttl, ipha->ipha_ttl,
8122 				    ntohl(sire->ire_addr)));
8123 				ipha->ipha_ttl = ip_multirt_ttl;
8124 			}
8125 		}
8126 		/*
8127 		 * At this point in ip_newroute(), ire is either the
8128 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8129 		 * destination or an IRE_INTERFACE type that should be used
8130 		 * to resolve an on-subnet destination or an on-subnet
8131 		 * next-hop gateway.
8132 		 *
8133 		 * In the IRE_CACHE case, we have the following :
8134 		 *
8135 		 * 1) src_ipif - used for getting a source address.
8136 		 *
8137 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8138 		 *    means packets using this IRE_CACHE will go out on
8139 		 *    dst_ill.
8140 		 *
8141 		 * 3) The IRE sire will point to the prefix that is the
8142 		 *    longest  matching route for the destination. These
8143 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8144 		 *
8145 		 *    The newly created IRE_CACHE entry for the off-subnet
8146 		 *    destination is tied to both the prefix route and the
8147 		 *    interface route used to resolve the next-hop gateway
8148 		 *    via the ire_phandle and ire_ihandle fields,
8149 		 *    respectively.
8150 		 *
8151 		 * In the IRE_INTERFACE case, we have the following :
8152 		 *
8153 		 * 1) src_ipif - used for getting a source address.
8154 		 *
8155 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8156 		 *    means packets using the IRE_CACHE that we will build
8157 		 *    here will go out on dst_ill.
8158 		 *
8159 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8160 		 *    to be created will only be tied to the IRE_INTERFACE
8161 		 *    that was derived from the ire_ihandle field.
8162 		 *
8163 		 *    If sire is non-NULL, it means the destination is
8164 		 *    off-link and we will first create the IRE_CACHE for the
8165 		 *    gateway. Next time through ip_newroute, we will create
8166 		 *    the IRE_CACHE for the final destination as described
8167 		 *    above.
8168 		 *
8169 		 * In both cases, after the current resolution has been
8170 		 * completed (or possibly initialised, in the IRE_INTERFACE
8171 		 * case), the loop may be re-entered to attempt the resolution
8172 		 * of another RTF_MULTIRT route.
8173 		 *
8174 		 * When an IRE_CACHE entry for the off-subnet destination is
8175 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8176 		 * for further processing in emission loops.
8177 		 */
8178 		save_ire = ire;
8179 		switch (ire->ire_type) {
8180 		case IRE_CACHE: {
8181 			ire_t	*ipif_ire;
8182 			mblk_t	*ire_fp_mp;
8183 
8184 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8185 			if (gw == 0)
8186 				gw = ire->ire_gateway_addr;
8187 			/*
8188 			 * We need 3 ire's to create a new cache ire for an
8189 			 * off-link destination from the cache ire of the
8190 			 * gateway.
8191 			 *
8192 			 *	1. The prefix ire 'sire' (Note that this does
8193 			 *	   not apply to the conn_nexthop_set case)
8194 			 *	2. The cache ire of the gateway 'ire'
8195 			 *	3. The interface ire 'ipif_ire'
8196 			 *
8197 			 * We have (1) and (2). We lookup (3) below.
8198 			 *
8199 			 * If there is no interface route to the gateway,
8200 			 * it is a race condition, where we found the cache
8201 			 * but the interface route has been deleted.
8202 			 */
8203 			if (ip_nexthop) {
8204 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8205 			} else {
8206 				ipif_ire =
8207 				    ire_ihandle_lookup_offlink(ire, sire);
8208 			}
8209 			if (ipif_ire == NULL) {
8210 				ip1dbg(("ip_newroute: "
8211 				    "ire_ihandle_lookup_offlink failed\n"));
8212 				goto icmp_err_ret;
8213 			}
8214 			/*
8215 			 * XXX We are using the same res_mp
8216 			 * (DL_UNITDATA_REQ) though the save_ire is not
8217 			 * pointing at the same ill.
8218 			 * This is incorrect. We need to send it up to the
8219 			 * resolver to get the right res_mp. For ethernets
8220 			 * this may be okay (ill_type == DL_ETHER).
8221 			 */
8222 			res_mp = save_ire->ire_nce->nce_res_mp;
8223 			ire_fp_mp = NULL;
8224 			/*
8225 			 * save_ire's nce_fp_mp can't change since it is
8226 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8227 			 * LOCK_IRE_FP_MP does not do any useful work in
8228 			 * the case of IRE_CACHE. So we don't use it below.
8229 			 */
8230 			if (save_ire->ire_stq == dst_ill->ill_wq)
8231 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8232 
8233 			/*
8234 			 * Check cached gateway IRE for any security
8235 			 * attributes; if found, associate the gateway
8236 			 * credentials group to the destination IRE.
8237 			 */
8238 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8239 				mutex_enter(&attrp->igsa_lock);
8240 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8241 					GCGRP_REFHOLD(gcgrp);
8242 				mutex_exit(&attrp->igsa_lock);
8243 			}
8244 
8245 			ire = ire_create(
8246 			    (uchar_t *)&dst,		/* dest address */
8247 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8248 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8249 			    (uchar_t *)&gw,		/* gateway address */
8250 			    NULL,
8251 			    &save_ire->ire_max_frag,
8252 			    ire_fp_mp,			/* Fast Path header */
8253 			    dst_ill->ill_rq,		/* recv-from queue */
8254 			    dst_ill->ill_wq,		/* send-to queue */
8255 			    IRE_CACHE,			/* IRE type */
8256 			    res_mp,
8257 			    src_ipif,
8258 			    in_ill,			/* incoming ill */
8259 			    (sire != NULL) ?
8260 				sire->ire_mask : 0, 	/* Parent mask */
8261 			    (sire != NULL) ?
8262 				sire->ire_phandle : 0,  /* Parent handle */
8263 			    ipif_ire->ire_ihandle,	/* Interface handle */
8264 			    (sire != NULL) ? (sire->ire_flags &
8265 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8266 			    (sire != NULL) ?
8267 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8268 			    NULL,
8269 			    gcgrp);
8270 
8271 			if (ire == NULL) {
8272 				if (gcgrp != NULL) {
8273 					GCGRP_REFRELE(gcgrp);
8274 					gcgrp = NULL;
8275 				}
8276 				ire_refrele(ipif_ire);
8277 				ire_refrele(save_ire);
8278 				break;
8279 			}
8280 
8281 			/* reference now held by IRE */
8282 			gcgrp = NULL;
8283 
8284 			ire->ire_marks |= ire_marks;
8285 
8286 			/*
8287 			 * Prevent sire and ipif_ire from getting deleted.
8288 			 * The newly created ire is tied to both of them via
8289 			 * the phandle and ihandle respectively.
8290 			 */
8291 			if (sire != NULL) {
8292 				IRB_REFHOLD(sire->ire_bucket);
8293 				/* Has it been removed already ? */
8294 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8295 					IRB_REFRELE(sire->ire_bucket);
8296 					ire_refrele(ipif_ire);
8297 					ire_refrele(save_ire);
8298 					break;
8299 				}
8300 			}
8301 
8302 			IRB_REFHOLD(ipif_ire->ire_bucket);
8303 			/* Has it been removed already ? */
8304 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8305 				IRB_REFRELE(ipif_ire->ire_bucket);
8306 				if (sire != NULL)
8307 					IRB_REFRELE(sire->ire_bucket);
8308 				ire_refrele(ipif_ire);
8309 				ire_refrele(save_ire);
8310 				break;
8311 			}
8312 
8313 			xmit_mp = first_mp;
8314 			/*
8315 			 * In the case of multirouting, a copy
8316 			 * of the packet is done before its sending.
8317 			 * The copy is used to attempt another
8318 			 * route resolution, in a next loop.
8319 			 */
8320 			if (ire->ire_flags & RTF_MULTIRT) {
8321 				copy_mp = copymsg(first_mp);
8322 				if (copy_mp != NULL) {
8323 					xmit_mp = copy_mp;
8324 					MULTIRT_DEBUG_TAG(first_mp);
8325 				}
8326 			}
8327 			ire_add_then_send(q, ire, xmit_mp);
8328 			ire_refrele(save_ire);
8329 
8330 			/* Assert that sire is not deleted yet. */
8331 			if (sire != NULL) {
8332 				ASSERT(sire->ire_ptpn != NULL);
8333 				IRB_REFRELE(sire->ire_bucket);
8334 			}
8335 
8336 			/* Assert that ipif_ire is not deleted yet. */
8337 			ASSERT(ipif_ire->ire_ptpn != NULL);
8338 			IRB_REFRELE(ipif_ire->ire_bucket);
8339 			ire_refrele(ipif_ire);
8340 
8341 			/*
8342 			 * If copy_mp is not NULL, multirouting was
8343 			 * requested. We loop to initiate a next
8344 			 * route resolution attempt, starting from sire.
8345 			 */
8346 			if (copy_mp != NULL) {
8347 				/*
8348 				 * Search for the next unresolved
8349 				 * multirt route.
8350 				 */
8351 				copy_mp = NULL;
8352 				ipif_ire = NULL;
8353 				ire = NULL;
8354 				multirt_resolve_next = B_TRUE;
8355 				continue;
8356 			}
8357 			if (sire != NULL)
8358 				ire_refrele(sire);
8359 			ipif_refrele(src_ipif);
8360 			ill_refrele(dst_ill);
8361 			return;
8362 		}
8363 		case IRE_IF_NORESOLVER: {
8364 			/*
8365 			 * We have what we need to build an IRE_CACHE.
8366 			 *
8367 			 * Create a new res_mp with the IP gateway address
8368 			 * in destination address in the DLPI hdr if the
8369 			 * physical length is exactly 4 bytes.
8370 			 */
8371 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8372 				uchar_t *addr;
8373 
8374 				if (gw)
8375 					addr = (uchar_t *)&gw;
8376 				else
8377 					addr = (uchar_t *)&dst;
8378 
8379 				res_mp = ill_dlur_gen(addr,
8380 				    dst_ill->ill_phys_addr_length,
8381 				    dst_ill->ill_sap,
8382 				    dst_ill->ill_sap_length);
8383 
8384 				if (res_mp == NULL) {
8385 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8386 					break;
8387 				}
8388 			} else if (dst_ill->ill_resolver_mp == NULL) {
8389 				ip1dbg(("ip_newroute: dst_ill %p "
8390 				    "for IF_NORESOLV ire %p has "
8391 				    "no ill_resolver_mp\n",
8392 				    (void *)dst_ill, (void *)ire));
8393 				break;
8394 			} else {
8395 				res_mp = NULL;
8396 			}
8397 
8398 			/*
8399 			 * TSol note: We are creating the ire cache for the
8400 			 * destination 'dst'. If 'dst' is offlink, going
8401 			 * through the first hop 'gw', the security attributes
8402 			 * of 'dst' must be set to point to the gateway
8403 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8404 			 * is possible that 'dst' is a potential gateway that is
8405 			 * referenced by some route that has some security
8406 			 * attributes. Thus in the former case, we need to do a
8407 			 * gcgrp_lookup of 'gw' while in the latter case we
8408 			 * need to do gcgrp_lookup of 'dst' itself.
8409 			 */
8410 			ga.ga_af = AF_INET;
8411 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8412 			    &ga.ga_addr);
8413 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8414 
8415 			ire = ire_create(
8416 			    (uchar_t *)&dst,		/* dest address */
8417 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8418 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8419 			    (uchar_t *)&gw,		/* gateway address */
8420 			    NULL,
8421 			    &save_ire->ire_max_frag,
8422 			    NULL,			/* Fast Path header */
8423 			    dst_ill->ill_rq,		/* recv-from queue */
8424 			    dst_ill->ill_wq,		/* send-to queue */
8425 			    IRE_CACHE,
8426 			    res_mp,
8427 			    src_ipif,
8428 			    in_ill,			/* Incoming ill */
8429 			    save_ire->ire_mask,		/* Parent mask */
8430 			    (sire != NULL) ?		/* Parent handle */
8431 				sire->ire_phandle : 0,
8432 			    save_ire->ire_ihandle,	/* Interface handle */
8433 			    (sire != NULL) ? sire->ire_flags &
8434 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8435 			    &(save_ire->ire_uinfo),
8436 			    NULL,
8437 			    gcgrp);
8438 
8439 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8440 				freeb(res_mp);
8441 
8442 			if (ire == NULL) {
8443 				if (gcgrp != NULL) {
8444 					GCGRP_REFRELE(gcgrp);
8445 					gcgrp = NULL;
8446 				}
8447 				ire_refrele(save_ire);
8448 				break;
8449 			}
8450 
8451 			/* reference now held by IRE */
8452 			gcgrp = NULL;
8453 
8454 			ire->ire_marks |= ire_marks;
8455 
8456 			/* Prevent save_ire from getting deleted */
8457 			IRB_REFHOLD(save_ire->ire_bucket);
8458 			/* Has it been removed already ? */
8459 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8460 				IRB_REFRELE(save_ire->ire_bucket);
8461 				ire_refrele(save_ire);
8462 				break;
8463 			}
8464 
8465 			/*
8466 			 * In the case of multirouting, a copy
8467 			 * of the packet is made before it is sent.
8468 			 * The copy is used in the next
8469 			 * loop to attempt another resolution.
8470 			 */
8471 			xmit_mp = first_mp;
8472 			if ((sire != NULL) &&
8473 			    (sire->ire_flags & RTF_MULTIRT)) {
8474 				copy_mp = copymsg(first_mp);
8475 				if (copy_mp != NULL) {
8476 					xmit_mp = copy_mp;
8477 					MULTIRT_DEBUG_TAG(first_mp);
8478 				}
8479 			}
8480 			ire_add_then_send(q, ire, xmit_mp);
8481 
8482 			/* Assert that it is not deleted yet. */
8483 			ASSERT(save_ire->ire_ptpn != NULL);
8484 			IRB_REFRELE(save_ire->ire_bucket);
8485 			ire_refrele(save_ire);
8486 
8487 			if (copy_mp != NULL) {
8488 				/*
8489 				 * If we found a (no)resolver, we ignore any
8490 				 * trailing top priority IRE_CACHE in further
8491 				 * loops. This ensures that we do not omit any
8492 				 * (no)resolver.
8493 				 * This IRE_CACHE, if any, will be processed
8494 				 * by another thread entering ip_newroute().
8495 				 * IRE_CACHE entries, if any, will be processed
8496 				 * by another thread entering ip_newroute(),
8497 				 * (upon resolver response, for instance).
8498 				 * This aims to force parallel multirt
8499 				 * resolutions as soon as a packet must be sent.
8500 				 * In the best case, after the tx of only one
8501 				 * packet, all reachable routes are resolved.
8502 				 * Otherwise, the resolution of all RTF_MULTIRT
8503 				 * routes would require several emissions.
8504 				 */
8505 				multirt_flags &= ~MULTIRT_CACHEGW;
8506 
8507 				/*
8508 				 * Search for the next unresolved multirt
8509 				 * route.
8510 				 */
8511 				copy_mp = NULL;
8512 				save_ire = NULL;
8513 				ire = NULL;
8514 				multirt_resolve_next = B_TRUE;
8515 				continue;
8516 			}
8517 
8518 			/*
8519 			 * Don't need sire anymore
8520 			 */
8521 			if (sire != NULL)
8522 				ire_refrele(sire);
8523 
8524 			ipif_refrele(src_ipif);
8525 			ill_refrele(dst_ill);
8526 			return;
8527 		}
8528 		case IRE_IF_RESOLVER:
8529 			/*
8530 			 * We can't build an IRE_CACHE yet, but at least we
8531 			 * found a resolver that can help.
8532 			 */
8533 			res_mp = dst_ill->ill_resolver_mp;
8534 			if (!OK_RESOLVER_MP(res_mp))
8535 				break;
8536 
8537 			/*
8538 			 * To be at this point in the code with a non-zero gw
8539 			 * means that dst is reachable through a gateway that
8540 			 * we have never resolved.  By changing dst to the gw
8541 			 * addr we resolve the gateway first.
8542 			 * When ire_add_then_send() tries to put the IP dg
8543 			 * to dst, it will reenter ip_newroute() at which
8544 			 * time we will find the IRE_CACHE for the gw and
8545 			 * create another IRE_CACHE in case IRE_CACHE above.
8546 			 */
8547 			if (gw != INADDR_ANY) {
8548 				/*
8549 				 * The source ipif that was determined above was
8550 				 * relative to the destination address, not the
8551 				 * gateway's. If src_ipif was not taken out of
8552 				 * the IRE_IF_RESOLVER entry, we'll need to call
8553 				 * ipif_select_source() again.
8554 				 */
8555 				if (src_ipif != ire->ire_ipif) {
8556 					ipif_refrele(src_ipif);
8557 					src_ipif = ipif_select_source(dst_ill,
8558 					    gw, zoneid);
8559 					if (src_ipif == NULL) {
8560 						if (ip_debug > 2) {
8561 							pr_addr_dbg(
8562 							    "ip_newroute: no "
8563 							    "src for gw %s ",
8564 							    AF_INET, &gw);
8565 							printf("through "
8566 							    "interface %s\n",
8567 							    dst_ill->ill_name);
8568 						}
8569 						goto icmp_err_ret;
8570 					}
8571 				}
8572 				save_dst = dst;
8573 				dst = gw;
8574 				gw = INADDR_ANY;
8575 			}
8576 
8577 			/*
8578 			 * We obtain a partial IRE_CACHE which we will pass
8579 			 * along with the resolver query.  When the response
8580 			 * comes back it will be there ready for us to add.
8581 			 * The ire_max_frag is atomically set under the
8582 			 * irebucket lock in ire_add_v[46].
8583 			 */
8584 
8585 			ire = ire_create_mp(
8586 			    (uchar_t *)&dst,		/* dest address */
8587 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8588 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8589 			    (uchar_t *)&gw,		/* gateway address */
8590 			    NULL,			/* no in_src_addr */
8591 			    NULL,			/* ire_max_frag */
8592 			    NULL,			/* Fast Path header */
8593 			    dst_ill->ill_rq,		/* recv-from queue */
8594 			    dst_ill->ill_wq,		/* send-to queue */
8595 			    IRE_CACHE,
8596 			    NULL,
8597 			    src_ipif,			/* Interface ipif */
8598 			    in_ill,			/* Incoming ILL */
8599 			    save_ire->ire_mask,		/* Parent mask */
8600 			    0,
8601 			    save_ire->ire_ihandle,	/* Interface handle */
8602 			    0,				/* flags if any */
8603 			    &(save_ire->ire_uinfo),
8604 			    NULL,
8605 			    NULL);
8606 
8607 			if (ire == NULL) {
8608 				ire_refrele(save_ire);
8609 				break;
8610 			}
8611 
8612 			if ((sire != NULL) &&
8613 			    (sire->ire_flags & RTF_MULTIRT)) {
8614 				copy_mp = copymsg(first_mp);
8615 				if (copy_mp != NULL)
8616 					MULTIRT_DEBUG_TAG(copy_mp);
8617 			}
8618 
8619 			ire->ire_marks |= ire_marks;
8620 
8621 			/*
8622 			 * Construct message chain for the resolver
8623 			 * of the form:
8624 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8625 			 * Packet could contain a IPSEC_OUT mp.
8626 			 *
8627 			 * NOTE : ire will be added later when the response
8628 			 * comes back from ARP. If the response does not
8629 			 * come back, ARP frees the packet. For this reason,
8630 			 * we can't REFHOLD the bucket of save_ire to prevent
8631 			 * deletions. We may not be able to REFRELE the bucket
8632 			 * if the response never comes back. Thus, before
8633 			 * adding the ire, ire_add_v4 will make sure that the
8634 			 * interface route does not get deleted. This is the
8635 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8636 			 * where we can always prevent deletions because of
8637 			 * the synchronous nature of adding IRES i.e
8638 			 * ire_add_then_send is called after creating the IRE.
8639 			 */
8640 			ASSERT(ire->ire_mp != NULL);
8641 			ire->ire_mp->b_cont = first_mp;
8642 			/* Have saved_mp handy, for cleanup if canput fails */
8643 			saved_mp = mp;
8644 			mp = copyb(res_mp);
8645 			if (mp == NULL) {
8646 				/* Prepare for cleanup */
8647 				mp = saved_mp; /* pkt */
8648 				ire_delete(ire); /* ire_mp */
8649 				ire = NULL;
8650 				ire_refrele(save_ire);
8651 				if (copy_mp != NULL) {
8652 					MULTIRT_DEBUG_UNTAG(copy_mp);
8653 					freemsg(copy_mp);
8654 					copy_mp = NULL;
8655 				}
8656 				break;
8657 			}
8658 			linkb(mp, ire->ire_mp);
8659 
8660 			/*
8661 			 * Fill in the source and dest addrs for the resolver.
8662 			 * NOTE: this depends on memory layouts imposed by
8663 			 * ill_init().
8664 			 */
8665 			areq = (areq_t *)mp->b_rptr;
8666 			addrp = (ipaddr_t *)((char *)areq +
8667 			    areq->areq_sender_addr_offset);
8668 			if (do_attach_ill) {
8669 				/*
8670 				 * This is bind to no failover case.
8671 				 * arp packet also must go out on attach_ill.
8672 				 */
8673 				ASSERT(ipha->ipha_src != NULL);
8674 				*addrp = ipha->ipha_src;
8675 			} else {
8676 				*addrp = save_ire->ire_src_addr;
8677 			}
8678 
8679 			ire_refrele(save_ire);
8680 			addrp = (ipaddr_t *)((char *)areq +
8681 			    areq->areq_target_addr_offset);
8682 			*addrp = dst;
8683 			/* Up to the resolver. */
8684 			if (canputnext(dst_ill->ill_rq) &&
8685 			    !(dst_ill->ill_arp_closing)) {
8686 				putnext(dst_ill->ill_rq, mp);
8687 				ire = NULL;
8688 				if (copy_mp != NULL) {
8689 					/*
8690 					 * If we found a resolver, we ignore
8691 					 * any trailing top priority IRE_CACHE
8692 					 * in the further loops. This ensures
8693 					 * that we do not omit any resolver.
8694 					 * IRE_CACHE entries, if any, will be
8695 					 * processed next time we enter
8696 					 * ip_newroute().
8697 					 */
8698 					multirt_flags &= ~MULTIRT_CACHEGW;
8699 					/*
8700 					 * Search for the next unresolved
8701 					 * multirt route.
8702 					 */
8703 					first_mp = copy_mp;
8704 					copy_mp = NULL;
8705 					/* Prepare the next resolution loop. */
8706 					mp = first_mp;
8707 					EXTRACT_PKT_MP(mp, first_mp,
8708 					    mctl_present);
8709 					if (mctl_present)
8710 						io = (ipsec_out_t *)
8711 						    first_mp->b_rptr;
8712 					ipha = (ipha_t *)mp->b_rptr;
8713 
8714 					ASSERT(sire != NULL);
8715 
8716 					dst = save_dst;
8717 					multirt_resolve_next = B_TRUE;
8718 					continue;
8719 				}
8720 
8721 				if (sire != NULL)
8722 					ire_refrele(sire);
8723 
8724 				/*
8725 				 * The response will come back in ip_wput
8726 				 * with db_type IRE_DB_TYPE.
8727 				 */
8728 				ipif_refrele(src_ipif);
8729 				ill_refrele(dst_ill);
8730 				return;
8731 			} else {
8732 				/* Prepare for cleanup */
8733 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8734 				    mp);
8735 				mp->b_cont = NULL;
8736 				freeb(mp); /* areq */
8737 				/*
8738 				 * this is an ire that is not added to the
8739 				 * cache. ire_freemblk will handle the release
8740 				 * of any resources associated with the ire.
8741 				 */
8742 				ire_delete(ire); /* ire_mp */
8743 				mp = saved_mp; /* pkt */
8744 				ire = NULL;
8745 				if (copy_mp != NULL) {
8746 					MULTIRT_DEBUG_UNTAG(copy_mp);
8747 					freemsg(copy_mp);
8748 					copy_mp = NULL;
8749 				}
8750 				break;
8751 			}
8752 		default:
8753 			break;
8754 		}
8755 	} while (multirt_resolve_next);
8756 
8757 	ip1dbg(("ip_newroute: dropped\n"));
8758 	/* Did this packet originate externally? */
8759 	if (mp->b_prev) {
8760 		mp->b_next = NULL;
8761 		mp->b_prev = NULL;
8762 		BUMP_MIB(&ip_mib, ipInDiscards);
8763 	} else {
8764 		BUMP_MIB(&ip_mib, ipOutDiscards);
8765 	}
8766 	ASSERT(copy_mp == NULL);
8767 	MULTIRT_DEBUG_UNTAG(first_mp);
8768 	freemsg(first_mp);
8769 	if (ire != NULL)
8770 		ire_refrele(ire);
8771 	if (sire != NULL)
8772 		ire_refrele(sire);
8773 	if (src_ipif != NULL)
8774 		ipif_refrele(src_ipif);
8775 	if (dst_ill != NULL)
8776 		ill_refrele(dst_ill);
8777 	return;
8778 
8779 icmp_err_ret:
8780 	ip1dbg(("ip_newroute: no route\n"));
8781 	if (src_ipif != NULL)
8782 		ipif_refrele(src_ipif);
8783 	if (dst_ill != NULL)
8784 		ill_refrele(dst_ill);
8785 	if (sire != NULL)
8786 		ire_refrele(sire);
8787 	/* Did this packet originate externally? */
8788 	if (mp->b_prev) {
8789 		mp->b_next = NULL;
8790 		mp->b_prev = NULL;
8791 		/* XXX ipInNoRoutes */
8792 		q = WR(q);
8793 	} else {
8794 		/*
8795 		 * Since ip_wput() isn't close to finished, we fill
8796 		 * in enough of the header for credible error reporting.
8797 		 */
8798 		if (ip_hdr_complete(ipha, zoneid)) {
8799 			/* Failed */
8800 			MULTIRT_DEBUG_UNTAG(first_mp);
8801 			freemsg(first_mp);
8802 			if (ire != NULL)
8803 				ire_refrele(ire);
8804 			return;
8805 		}
8806 	}
8807 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8808 
8809 	/*
8810 	 * At this point we will have ire only if RTF_BLACKHOLE
8811 	 * or RTF_REJECT flags are set on the IRE. It will not
8812 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8813 	 */
8814 	if (ire != NULL) {
8815 		if (ire->ire_flags & RTF_BLACKHOLE) {
8816 			ire_refrele(ire);
8817 			MULTIRT_DEBUG_UNTAG(first_mp);
8818 			freemsg(first_mp);
8819 			return;
8820 		}
8821 		ire_refrele(ire);
8822 	}
8823 	if (ip_source_routed(ipha)) {
8824 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8825 		    zoneid);
8826 		return;
8827 	}
8828 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
8829 }
8830 
8831 /*
8832  * IPv4 -
8833  * ip_newroute_ipif is called by ip_wput_multicast and
8834  * ip_rput_forward_multicast whenever we need to send
8835  * out a packet to a destination address for which we do not have specific
8836  * routing information. It is used when the packet will be sent out
8837  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8838  * socket option is set or icmp error message wants to go out on a particular
8839  * interface for a unicast packet.
8840  *
8841  * In most cases, the destination address is resolved thanks to the ipif
8842  * intrinsic resolver. However, there are some cases where the call to
8843  * ip_newroute_ipif must take into account the potential presence of
8844  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8845  * that uses the interface. This is specified through flags,
8846  * which can be a combination of:
8847  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8848  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8849  *   and flags. Additionally, the packet source address has to be set to
8850  *   the specified address. The caller is thus expected to set this flag
8851  *   if the packet has no specific source address yet.
8852  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8853  *   flag, the resulting ire will inherit the flag. All unresolved routes
8854  *   to the destination must be explored in the same call to
8855  *   ip_newroute_ipif().
8856  */
8857 static void
8858 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8859     conn_t *connp, uint32_t flags, zoneid_t zoneid)
8860 {
8861 	areq_t	*areq;
8862 	ire_t	*ire = NULL;
8863 	mblk_t	*res_mp;
8864 	ipaddr_t *addrp;
8865 	mblk_t *first_mp;
8866 	ire_t	*save_ire = NULL;
8867 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8868 	ipif_t	*src_ipif = NULL;
8869 	ushort_t ire_marks = 0;
8870 	ill_t	*dst_ill = NULL;
8871 	boolean_t mctl_present;
8872 	ipsec_out_t *io;
8873 	ipha_t *ipha;
8874 	int	ihandle = 0;
8875 	mblk_t	*saved_mp;
8876 	ire_t   *fire = NULL;
8877 	mblk_t  *copy_mp = NULL;
8878 	boolean_t multirt_resolve_next;
8879 	ipaddr_t ipha_dst;
8880 
8881 	/*
8882 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8883 	 * here for uniformity
8884 	 */
8885 	ipif_refhold(ipif);
8886 
8887 	/*
8888 	 * This loop is run only once in most cases.
8889 	 * We loop to resolve further routes only when the destination
8890 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8891 	 */
8892 	do {
8893 		if (dst_ill != NULL) {
8894 			ill_refrele(dst_ill);
8895 			dst_ill = NULL;
8896 		}
8897 		if (src_ipif != NULL) {
8898 			ipif_refrele(src_ipif);
8899 			src_ipif = NULL;
8900 		}
8901 		multirt_resolve_next = B_FALSE;
8902 
8903 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8904 		    ipif->ipif_ill->ill_name));
8905 
8906 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8907 		if (mctl_present)
8908 			io = (ipsec_out_t *)first_mp->b_rptr;
8909 
8910 		ipha = (ipha_t *)mp->b_rptr;
8911 
8912 		/*
8913 		 * Save the packet destination address, we may need it after
8914 		 * the packet has been consumed.
8915 		 */
8916 		ipha_dst = ipha->ipha_dst;
8917 
8918 		/*
8919 		 * If the interface is a pt-pt interface we look for an
8920 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8921 		 * local_address and the pt-pt destination address. Otherwise
8922 		 * we just match the local address.
8923 		 * NOTE: dst could be different than ipha->ipha_dst in case
8924 		 * of sending igmp multicast packets over a point-to-point
8925 		 * connection.
8926 		 * Thus we must be careful enough to check ipha_dst to be a
8927 		 * multicast address, otherwise it will take xmit_if path for
8928 		 * multicast packets resulting into kernel stack overflow by
8929 		 * repeated calls to ip_newroute_ipif from ire_send().
8930 		 */
8931 		if (CLASSD(ipha_dst) &&
8932 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8933 			goto err_ret;
8934 		}
8935 
8936 		/*
8937 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8938 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8939 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8940 		 * propagate its flags to the new ire.
8941 		 */
8942 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8943 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8944 			ip2dbg(("ip_newroute_ipif: "
8945 			    "ipif_lookup_multi_ire("
8946 			    "ipif %p, dst %08x) = fire %p\n",
8947 			    (void *)ipif, ntohl(dst), (void *)fire));
8948 		}
8949 
8950 		if (mctl_present && io->ipsec_out_attach_if) {
8951 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8952 			    io->ipsec_out_ill_index, B_FALSE);
8953 
8954 			/* Failure case frees things for us. */
8955 			if (attach_ill == NULL) {
8956 				ipif_refrele(ipif);
8957 				if (fire != NULL)
8958 					ire_refrele(fire);
8959 				return;
8960 			}
8961 
8962 			/*
8963 			 * Check if we need an ire that will not be
8964 			 * looked up by anybody else i.e. HIDDEN.
8965 			 */
8966 			if (ill_is_probeonly(attach_ill)) {
8967 				ire_marks = IRE_MARK_HIDDEN;
8968 			}
8969 			/*
8970 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8971 			 * case.
8972 			 */
8973 			dst_ill = ipif->ipif_ill;
8974 			/* attach_ill has been refheld by ip_grab_attach_ill */
8975 			ASSERT(dst_ill == attach_ill);
8976 		} else {
8977 			/*
8978 			 * If this is set by IP_XMIT_IF, then make sure that
8979 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8980 			 * specified ill.
8981 			 */
8982 			ASSERT((connp == NULL) ||
8983 			    (connp->conn_xmit_if_ill == NULL) ||
8984 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8985 			/*
8986 			 * If the interface belongs to an interface group,
8987 			 * make sure the next possible interface in the group
8988 			 * is used.  This encourages load spreading among
8989 			 * peers in an interface group.
8990 			 * Note: load spreading is disabled for RTF_MULTIRT
8991 			 * routes.
8992 			 */
8993 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8994 			    (fire->ire_flags & RTF_MULTIRT)) {
8995 				/*
8996 				 * Don't perform outbound load spreading
8997 				 * in the case of an RTF_MULTIRT issued route,
8998 				 * we actually typically want to replicate
8999 				 * outgoing packets through particular
9000 				 * interfaces.
9001 				 */
9002 				dst_ill = ipif->ipif_ill;
9003 				ill_refhold(dst_ill);
9004 			} else {
9005 				dst_ill = ip_newroute_get_dst_ill(
9006 				    ipif->ipif_ill);
9007 			}
9008 			if (dst_ill == NULL) {
9009 				if (ip_debug > 2) {
9010 					pr_addr_dbg("ip_newroute_ipif: "
9011 					    "no dst ill for dst %s\n",
9012 					    AF_INET, &dst);
9013 				}
9014 				goto err_ret;
9015 			}
9016 		}
9017 
9018 		/*
9019 		 * Pick a source address preferring non-deprecated ones.
9020 		 * Unlike ip_newroute, we don't do any source address
9021 		 * selection here since for multicast it really does not help
9022 		 * in inbound load spreading as in the unicast case.
9023 		 */
9024 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9025 		    (fire->ire_flags & RTF_SETSRC)) {
9026 			/*
9027 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9028 			 * on that interface. This ire has RTF_SETSRC flag, so
9029 			 * the source address of the packet must be changed.
9030 			 * Check that the ipif matching the requested source
9031 			 * address still exists.
9032 			 */
9033 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9034 			    zoneid, NULL, NULL, NULL, NULL);
9035 		}
9036 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9037 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9038 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9039 		    (src_ipif == NULL)) {
9040 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9041 			if (src_ipif == NULL) {
9042 				if (ip_debug > 2) {
9043 					/* ip1dbg */
9044 					pr_addr_dbg("ip_newroute_ipif: "
9045 					    "no src for dst %s",
9046 					    AF_INET, &dst);
9047 				}
9048 				ip1dbg((" through interface %s\n",
9049 				    dst_ill->ill_name));
9050 				goto err_ret;
9051 			}
9052 			ipif_refrele(ipif);
9053 			ipif = src_ipif;
9054 			ipif_refhold(ipif);
9055 		}
9056 		if (src_ipif == NULL) {
9057 			src_ipif = ipif;
9058 			ipif_refhold(src_ipif);
9059 		}
9060 
9061 		/*
9062 		 * Assign a source address while we have the conn.
9063 		 * We can't have ip_wput_ire pick a source address when the
9064 		 * packet returns from arp since conn_unspec_src might be set
9065 		 * and we loose the conn when going through arp.
9066 		 */
9067 		if (ipha->ipha_src == INADDR_ANY &&
9068 		    (connp == NULL || !connp->conn_unspec_src)) {
9069 			ipha->ipha_src = src_ipif->ipif_src_addr;
9070 		}
9071 
9072 		/*
9073 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9074 		 * interface does not have an interface ire.
9075 		 * Example: Thousands of mobileip PPP interfaces to mobile
9076 		 * nodes. We don't want to create interface ires because
9077 		 * packets from other mobile nodes must not take the route
9078 		 * via interface ires to the visiting mobile node without
9079 		 * going through the home agent, in absence of mobileip
9080 		 * route optimization.
9081 		 */
9082 		if (CLASSD(ipha_dst) && (connp == NULL ||
9083 		    connp->conn_xmit_if_ill == NULL)) {
9084 			/* ipif_to_ire returns an held ire */
9085 			ire = ipif_to_ire(ipif);
9086 			if (ire == NULL)
9087 				goto err_ret;
9088 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9089 				goto err_ret;
9090 			/*
9091 			 * ihandle is needed when the ire is added to
9092 			 * cache table.
9093 			 */
9094 			save_ire = ire;
9095 			ihandle = save_ire->ire_ihandle;
9096 
9097 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9098 			    "flags %04x\n",
9099 			    (void *)ire, (void *)ipif, flags));
9100 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9101 			    (fire->ire_flags & RTF_MULTIRT)) {
9102 				/*
9103 				 * As requested by flags, an IRE_OFFSUBNET was
9104 				 * looked up on that interface. This ire has
9105 				 * RTF_MULTIRT flag, so the resolution loop will
9106 				 * be re-entered to resolve additional routes on
9107 				 * other interfaces. For that purpose, a copy of
9108 				 * the packet is performed at this point.
9109 				 */
9110 				fire->ire_last_used_time = lbolt;
9111 				copy_mp = copymsg(first_mp);
9112 				if (copy_mp) {
9113 					MULTIRT_DEBUG_TAG(copy_mp);
9114 				}
9115 			}
9116 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9117 			    (fire->ire_flags & RTF_SETSRC)) {
9118 				/*
9119 				 * As requested by flags, an IRE_OFFSUBET was
9120 				 * looked up on that interface. This ire has
9121 				 * RTF_SETSRC flag, so the source address of the
9122 				 * packet must be changed.
9123 				 */
9124 				ipha->ipha_src = fire->ire_src_addr;
9125 			}
9126 		} else {
9127 			ASSERT((connp == NULL) ||
9128 			    (connp->conn_xmit_if_ill != NULL) ||
9129 			    (connp->conn_dontroute));
9130 			/*
9131 			 * The only ways we can come here are:
9132 			 * 1) IP_XMIT_IF socket option is set
9133 			 * 2) ICMP error message generated from
9134 			 *    ip_mrtun_forward() routine and it needs
9135 			 *    to go through the specified ill.
9136 			 * 3) SO_DONTROUTE socket option is set
9137 			 * In all cases, the new ire will not be added
9138 			 * into cache table.
9139 			 */
9140 			ire_marks |= IRE_MARK_NOADD;
9141 		}
9142 
9143 		switch (ipif->ipif_net_type) {
9144 		case IRE_IF_NORESOLVER: {
9145 			/* We have what we need to build an IRE_CACHE. */
9146 			mblk_t	*res_mp;
9147 
9148 			/*
9149 			 * Create a new res_mp with the
9150 			 * IP gateway address as destination address in the
9151 			 * DLPI hdr if the physical length is exactly 4 bytes.
9152 			 */
9153 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9154 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9155 				    dst_ill->ill_phys_addr_length,
9156 				    dst_ill->ill_sap,
9157 				    dst_ill->ill_sap_length);
9158 			} else if (dst_ill->ill_resolver_mp == NULL) {
9159 				ip1dbg(("ip_newroute: dst_ill %p "
9160 				    "for IF_NORESOLV ire %p has "
9161 				    "no ill_resolver_mp\n",
9162 				    (void *)dst_ill, (void *)ire));
9163 				break;
9164 			} else {
9165 				/* use the value set in ip_ll_subnet_defaults */
9166 				res_mp = ill_dlur_gen(NULL,
9167 				    dst_ill->ill_phys_addr_length,
9168 				    dst_ill->ill_sap,
9169 				    dst_ill->ill_sap_length);
9170 			}
9171 
9172 			if (res_mp == NULL)
9173 				break;
9174 			/*
9175 			 * The new ire inherits the IRE_OFFSUBNET flags
9176 			 * and source address, if this was requested.
9177 			 */
9178 			ire = ire_create(
9179 			    (uchar_t *)&dst,		/* dest address */
9180 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9181 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9182 			    NULL,			/* gateway address */
9183 			    NULL,
9184 			    &ipif->ipif_mtu,
9185 			    NULL,			/* Fast Path header */
9186 			    dst_ill->ill_rq,		/* recv-from queue */
9187 			    dst_ill->ill_wq,		/* send-to queue */
9188 			    IRE_CACHE,
9189 			    res_mp,
9190 			    src_ipif,
9191 			    NULL,
9192 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9193 			    (fire != NULL) ?		/* Parent handle */
9194 				fire->ire_phandle : 0,
9195 			    ihandle,			/* Interface handle */
9196 			    (fire != NULL) ?
9197 				(fire->ire_flags &
9198 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9199 			    (save_ire == NULL ? &ire_uinfo_null :
9200 				&save_ire->ire_uinfo),
9201 			    NULL,
9202 			    NULL);
9203 
9204 			freeb(res_mp);
9205 
9206 			if (ire == NULL) {
9207 				if (save_ire != NULL)
9208 					ire_refrele(save_ire);
9209 				break;
9210 			}
9211 
9212 			ire->ire_marks |= ire_marks;
9213 
9214 			/*
9215 			 * If IRE_MARK_NOADD is set then we need to convert
9216 			 * the max_fragp to a useable value now. This is
9217 			 * normally done in ire_add_v[46]. We also need to
9218 			 * associate the ire with an nce (normally would be
9219 			 * done in ip_wput_nondata()).
9220 			 *
9221 			 * Note that IRE_MARK_NOADD packets created here
9222 			 * do not have a non-null ire_mp pointer. The null
9223 			 * value of ire_bucket indicates that they were
9224 			 * never added.
9225 			 */
9226 			if (ire->ire_marks & IRE_MARK_NOADD) {
9227 				uint_t  max_frag;
9228 
9229 				max_frag = *ire->ire_max_fragp;
9230 				ire->ire_max_fragp = NULL;
9231 				ire->ire_max_frag = max_frag;
9232 
9233 				if ((ire->ire_nce = ndp_lookup_v4(
9234 				    ire_to_ill(ire),
9235 				    (ire->ire_gateway_addr != INADDR_ANY ?
9236 				    &ire->ire_gateway_addr : &ire->ire_addr),
9237 				    B_FALSE)) == NULL) {
9238 					if (save_ire != NULL)
9239 						ire_refrele(save_ire);
9240 					break;
9241 				}
9242 				ASSERT(ire->ire_nce->nce_state ==
9243 				    ND_REACHABLE);
9244 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9245 			}
9246 
9247 			/* Prevent save_ire from getting deleted */
9248 			if (save_ire != NULL) {
9249 				IRB_REFHOLD(save_ire->ire_bucket);
9250 				/* Has it been removed already ? */
9251 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9252 					IRB_REFRELE(save_ire->ire_bucket);
9253 					ire_refrele(save_ire);
9254 					break;
9255 				}
9256 			}
9257 
9258 			ire_add_then_send(q, ire, first_mp);
9259 
9260 			/* Assert that save_ire is not deleted yet. */
9261 			if (save_ire != NULL) {
9262 				ASSERT(save_ire->ire_ptpn != NULL);
9263 				IRB_REFRELE(save_ire->ire_bucket);
9264 				ire_refrele(save_ire);
9265 				save_ire = NULL;
9266 			}
9267 			if (fire != NULL) {
9268 				ire_refrele(fire);
9269 				fire = NULL;
9270 			}
9271 
9272 			/*
9273 			 * the resolution loop is re-entered if this
9274 			 * was requested through flags and if we
9275 			 * actually are in a multirouting case.
9276 			 */
9277 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9278 				boolean_t need_resolve =
9279 				    ire_multirt_need_resolve(ipha_dst,
9280 					MBLK_GETLABEL(copy_mp));
9281 				if (!need_resolve) {
9282 					MULTIRT_DEBUG_UNTAG(copy_mp);
9283 					freemsg(copy_mp);
9284 					copy_mp = NULL;
9285 				} else {
9286 					/*
9287 					 * ipif_lookup_group() calls
9288 					 * ire_lookup_multi() that uses
9289 					 * ire_ftable_lookup() to find
9290 					 * an IRE_INTERFACE for the group.
9291 					 * In the multirt case,
9292 					 * ire_lookup_multi() then invokes
9293 					 * ire_multirt_lookup() to find
9294 					 * the next resolvable ire.
9295 					 * As a result, we obtain an new
9296 					 * interface, derived from the
9297 					 * next ire.
9298 					 */
9299 					ipif_refrele(ipif);
9300 					ipif = ipif_lookup_group(ipha_dst,
9301 					    zoneid);
9302 					ip2dbg(("ip_newroute_ipif: "
9303 					    "multirt dst %08x, ipif %p\n",
9304 					    htonl(dst), (void *)ipif));
9305 					if (ipif != NULL) {
9306 						mp = copy_mp;
9307 						copy_mp = NULL;
9308 						multirt_resolve_next = B_TRUE;
9309 						continue;
9310 					} else {
9311 						freemsg(copy_mp);
9312 					}
9313 				}
9314 			}
9315 			if (ipif != NULL)
9316 				ipif_refrele(ipif);
9317 			ill_refrele(dst_ill);
9318 			ipif_refrele(src_ipif);
9319 			return;
9320 		}
9321 		case IRE_IF_RESOLVER:
9322 			/*
9323 			 * We can't build an IRE_CACHE yet, but at least
9324 			 * we found a resolver that can help.
9325 			 */
9326 			res_mp = dst_ill->ill_resolver_mp;
9327 			if (!OK_RESOLVER_MP(res_mp))
9328 				break;
9329 
9330 			/*
9331 			 * We obtain a partial IRE_CACHE which we will pass
9332 			 * along with the resolver query.  When the response
9333 			 * comes back it will be there ready for us to add.
9334 			 * The new ire inherits the IRE_OFFSUBNET flags
9335 			 * and source address, if this was requested.
9336 			 * The ire_max_frag is atomically set under the
9337 			 * irebucket lock in ire_add_v[46]. Only in the
9338 			 * case of IRE_MARK_NOADD, we set it here itself.
9339 			 */
9340 			ire = ire_create_mp(
9341 			    (uchar_t *)&dst,		/* dest address */
9342 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9343 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9344 			    NULL,			/* gateway address */
9345 			    NULL,			/* no in_src_addr */
9346 			    (ire_marks & IRE_MARK_NOADD) ?
9347 				ipif->ipif_mtu : 0,	/* max_frag */
9348 			    NULL,			/* Fast path header */
9349 			    dst_ill->ill_rq,		/* recv-from queue */
9350 			    dst_ill->ill_wq,		/* send-to queue */
9351 			    IRE_CACHE,
9352 			    NULL,	/* let ire_nce_init figure res_mp out */
9353 			    src_ipif,
9354 			    NULL,
9355 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9356 			    (fire != NULL) ?		/* Parent handle */
9357 				fire->ire_phandle : 0,
9358 			    ihandle,			/* Interface handle */
9359 			    (fire != NULL) ?		/* flags if any */
9360 				(fire->ire_flags &
9361 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9362 			    (save_ire == NULL ? &ire_uinfo_null :
9363 				&save_ire->ire_uinfo),
9364 			    NULL,
9365 			    NULL);
9366 
9367 			if (save_ire != NULL) {
9368 				ire_refrele(save_ire);
9369 				save_ire = NULL;
9370 			}
9371 			if (ire == NULL)
9372 				break;
9373 
9374 			ire->ire_marks |= ire_marks;
9375 			/*
9376 			 * Construct message chain for the resolver of the
9377 			 * form:
9378 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9379 			 *
9380 			 * NOTE : ire will be added later when the response
9381 			 * comes back from ARP. If the response does not
9382 			 * come back, ARP frees the packet. For this reason,
9383 			 * we can't REFHOLD the bucket of save_ire to prevent
9384 			 * deletions. We may not be able to REFRELE the
9385 			 * bucket if the response never comes back.
9386 			 * Thus, before adding the ire, ire_add_v4 will make
9387 			 * sure that the interface route does not get deleted.
9388 			 * This is the only case unlike ip_newroute_v6,
9389 			 * ip_newroute_ipif_v6 where we can always prevent
9390 			 * deletions because ire_add_then_send is called after
9391 			 * creating the IRE.
9392 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9393 			 * does not add this IRE into the IRE CACHE.
9394 			 */
9395 			ASSERT(ire->ire_mp != NULL);
9396 			ire->ire_mp->b_cont = first_mp;
9397 			/* Have saved_mp handy, for cleanup if canput fails */
9398 			saved_mp = mp;
9399 			mp = copyb(res_mp);
9400 			if (mp == NULL) {
9401 				/* Prepare for cleanup */
9402 				mp = saved_mp; /* pkt */
9403 				ire_delete(ire); /* ire_mp */
9404 				ire = NULL;
9405 				if (copy_mp != NULL) {
9406 					MULTIRT_DEBUG_UNTAG(copy_mp);
9407 					freemsg(copy_mp);
9408 					copy_mp = NULL;
9409 				}
9410 				break;
9411 			}
9412 			linkb(mp, ire->ire_mp);
9413 
9414 			/*
9415 			 * Fill in the source and dest addrs for the resolver.
9416 			 * NOTE: this depends on memory layouts imposed by
9417 			 * ill_init().
9418 			 */
9419 			areq = (areq_t *)mp->b_rptr;
9420 			addrp = (ipaddr_t *)((char *)areq +
9421 			    areq->areq_sender_addr_offset);
9422 			*addrp = ire->ire_src_addr;
9423 			addrp = (ipaddr_t *)((char *)areq +
9424 			    areq->areq_target_addr_offset);
9425 			*addrp = dst;
9426 			/* Up to the resolver. */
9427 			if (canputnext(dst_ill->ill_rq) &&
9428 			    !(dst_ill->ill_arp_closing)) {
9429 				putnext(dst_ill->ill_rq, mp);
9430 				/*
9431 				 * The response will come back in ip_wput
9432 				 * with db_type IRE_DB_TYPE.
9433 				 */
9434 			} else {
9435 				mp->b_cont = NULL;
9436 				freeb(mp); /* areq */
9437 				ire_delete(ire); /* ire_mp */
9438 				saved_mp->b_next = NULL;
9439 				saved_mp->b_prev = NULL;
9440 				freemsg(first_mp); /* pkt */
9441 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9442 			}
9443 
9444 			if (fire != NULL) {
9445 				ire_refrele(fire);
9446 				fire = NULL;
9447 			}
9448 
9449 
9450 			/*
9451 			 * The resolution loop is re-entered if this was
9452 			 * requested through flags and we actually are
9453 			 * in a multirouting case.
9454 			 */
9455 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9456 				boolean_t need_resolve =
9457 				    ire_multirt_need_resolve(ipha_dst,
9458 					MBLK_GETLABEL(copy_mp));
9459 				if (!need_resolve) {
9460 					MULTIRT_DEBUG_UNTAG(copy_mp);
9461 					freemsg(copy_mp);
9462 					copy_mp = NULL;
9463 				} else {
9464 					/*
9465 					 * ipif_lookup_group() calls
9466 					 * ire_lookup_multi() that uses
9467 					 * ire_ftable_lookup() to find
9468 					 * an IRE_INTERFACE for the group.
9469 					 * In the multirt case,
9470 					 * ire_lookup_multi() then invokes
9471 					 * ire_multirt_lookup() to find
9472 					 * the next resolvable ire.
9473 					 * As a result, we obtain an new
9474 					 * interface, derived from the
9475 					 * next ire.
9476 					 */
9477 					ipif_refrele(ipif);
9478 					ipif = ipif_lookup_group(ipha_dst,
9479 					    zoneid);
9480 					if (ipif != NULL) {
9481 						mp = copy_mp;
9482 						copy_mp = NULL;
9483 						multirt_resolve_next = B_TRUE;
9484 						continue;
9485 					} else {
9486 						freemsg(copy_mp);
9487 					}
9488 				}
9489 			}
9490 			if (ipif != NULL)
9491 				ipif_refrele(ipif);
9492 			ill_refrele(dst_ill);
9493 			ipif_refrele(src_ipif);
9494 			return;
9495 		default:
9496 			break;
9497 		}
9498 	} while (multirt_resolve_next);
9499 
9500 err_ret:
9501 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9502 	if (fire != NULL)
9503 		ire_refrele(fire);
9504 	ipif_refrele(ipif);
9505 	/* Did this packet originate externally? */
9506 	if (dst_ill != NULL)
9507 		ill_refrele(dst_ill);
9508 	if (src_ipif != NULL)
9509 		ipif_refrele(src_ipif);
9510 	if (mp->b_prev || mp->b_next) {
9511 		mp->b_next = NULL;
9512 		mp->b_prev = NULL;
9513 	} else {
9514 		/*
9515 		 * Since ip_wput() isn't close to finished, we fill
9516 		 * in enough of the header for credible error reporting.
9517 		 */
9518 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9519 			/* Failed */
9520 			freemsg(first_mp);
9521 			if (ire != NULL)
9522 				ire_refrele(ire);
9523 			return;
9524 		}
9525 	}
9526 	/*
9527 	 * At this point we will have ire only if RTF_BLACKHOLE
9528 	 * or RTF_REJECT flags are set on the IRE. It will not
9529 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9530 	 */
9531 	if (ire != NULL) {
9532 		if (ire->ire_flags & RTF_BLACKHOLE) {
9533 			ire_refrele(ire);
9534 			freemsg(first_mp);
9535 			return;
9536 		}
9537 		ire_refrele(ire);
9538 	}
9539 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9540 }
9541 
9542 /* Name/Value Table Lookup Routine */
9543 char *
9544 ip_nv_lookup(nv_t *nv, int value)
9545 {
9546 	if (!nv)
9547 		return (NULL);
9548 	for (; nv->nv_name; nv++) {
9549 		if (nv->nv_value == value)
9550 			return (nv->nv_name);
9551 	}
9552 	return ("unknown");
9553 }
9554 
9555 /*
9556  * one day it can be patched to 1 from /etc/system for machines that have few
9557  * fast network interfaces feeding multiple cpus.
9558  */
9559 int ill_stream_putlocks = 0;
9560 
9561 /*
9562  * This is a module open, i.e. this is a control stream for access
9563  * to a DLPI device.  We allocate an ill_t as the instance data in
9564  * this case.
9565  */
9566 int
9567 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9568 {
9569 	uint32_t mem_cnt;
9570 	uint32_t cpu_cnt;
9571 	uint32_t min_cnt;
9572 	pgcnt_t mem_avail;
9573 	ill_t	*ill;
9574 	int	err;
9575 
9576 	/*
9577 	 * Prevent unprivileged processes from pushing IP so that
9578 	 * they can't send raw IP.
9579 	 */
9580 	if (secpolicy_net_rawaccess(credp) != 0)
9581 		return (EPERM);
9582 
9583 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9584 	q->q_ptr = WR(q)->q_ptr = ill;
9585 
9586 	/*
9587 	 * ill_init initializes the ill fields and then sends down
9588 	 * down a DL_INFO_REQ after calling qprocson.
9589 	 */
9590 	err = ill_init(q, ill);
9591 	if (err != 0) {
9592 		mi_free(ill);
9593 		q->q_ptr = NULL;
9594 		WR(q)->q_ptr = NULL;
9595 		return (err);
9596 	}
9597 
9598 	/* ill_init initializes the ipsq marking this thread as writer */
9599 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9600 	/* Wait for the DL_INFO_ACK */
9601 	mutex_enter(&ill->ill_lock);
9602 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9603 		/*
9604 		 * Return value of 0 indicates a pending signal.
9605 		 */
9606 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9607 		if (err == 0) {
9608 			mutex_exit(&ill->ill_lock);
9609 			(void) ip_close(q, 0);
9610 			return (EINTR);
9611 		}
9612 	}
9613 	mutex_exit(&ill->ill_lock);
9614 
9615 	/*
9616 	 * ip_rput_other could have set an error  in ill_error on
9617 	 * receipt of M_ERROR.
9618 	 */
9619 
9620 	err = ill->ill_error;
9621 	if (err != 0) {
9622 		(void) ip_close(q, 0);
9623 		return (err);
9624 	}
9625 
9626 	/*
9627 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9628 	 * size and the cpu speed of the machine. This is upper
9629 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9630 	 * and is lower bounded by the compile time value of
9631 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9632 	 * ip6_ire_max_bucket_cnt.
9633 	 */
9634 	mem_avail = kmem_avail();
9635 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9636 	    ip_cache_table_size / sizeof (ire_t);
9637 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9638 
9639 	min_cnt = MIN(cpu_cnt, mem_cnt);
9640 	if (min_cnt < ip_ire_min_bucket_cnt)
9641 		min_cnt = ip_ire_min_bucket_cnt;
9642 	if (ip_ire_max_bucket_cnt > min_cnt) {
9643 		ip_ire_max_bucket_cnt = min_cnt;
9644 	}
9645 
9646 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9647 	    ip6_cache_table_size / sizeof (ire_t);
9648 	min_cnt = MIN(cpu_cnt, mem_cnt);
9649 	if (min_cnt < ip6_ire_min_bucket_cnt)
9650 		min_cnt = ip6_ire_min_bucket_cnt;
9651 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9652 		ip6_ire_max_bucket_cnt = min_cnt;
9653 	}
9654 
9655 	ill->ill_credp = credp;
9656 	crhold(credp);
9657 
9658 	mutex_enter(&ip_mi_lock);
9659 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9660 	mutex_exit(&ip_mi_lock);
9661 	if (err) {
9662 		(void) ip_close(q, 0);
9663 		return (err);
9664 	}
9665 	return (0);
9666 }
9667 
9668 /* IP open routine. */
9669 int
9670 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9671 {
9672 	conn_t 		*connp;
9673 	major_t		maj;
9674 
9675 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9676 
9677 	/* Allow reopen. */
9678 	if (q->q_ptr != NULL)
9679 		return (0);
9680 
9681 	if (sflag & MODOPEN) {
9682 		/* This is a module open */
9683 		return (ip_modopen(q, devp, flag, sflag, credp));
9684 	}
9685 
9686 	/*
9687 	 * We are opening as a device. This is an IP client stream, and we
9688 	 * allocate an conn_t as the instance data.
9689 	 */
9690 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9691 	connp->conn_upq = q;
9692 	q->q_ptr = WR(q)->q_ptr = connp;
9693 
9694 	if (flag & SO_SOCKSTR)
9695 		connp->conn_flags |= IPCL_SOCKET;
9696 
9697 	/* Minor tells us which /dev entry was opened */
9698 	if (geteminor(*devp) == IPV6_MINOR) {
9699 		connp->conn_flags |= IPCL_ISV6;
9700 		connp->conn_af_isv6 = B_TRUE;
9701 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9702 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9703 	} else {
9704 		connp->conn_af_isv6 = B_FALSE;
9705 		connp->conn_pkt_isv6 = B_FALSE;
9706 	}
9707 
9708 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9709 		q->q_ptr = WR(q)->q_ptr = NULL;
9710 		CONN_DEC_REF(connp);
9711 		return (EBUSY);
9712 	}
9713 
9714 	maj = getemajor(*devp);
9715 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9716 
9717 	/*
9718 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9719 	 */
9720 	connp->conn_cred = credp;
9721 	crhold(connp->conn_cred);
9722 
9723 	/*
9724 	 * If the caller has the process-wide flag set, then default to MAC
9725 	 * exempt mode.  This allows read-down to unlabeled hosts.
9726 	 */
9727 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9728 		connp->conn_mac_exempt = B_TRUE;
9729 
9730 	connp->conn_zoneid = getzoneid();
9731 
9732 	/*
9733 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9734 	 * administrative ops.  In these cases, we just need a normal conn_t
9735 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9736 	 * an error will be returned.
9737 	 */
9738 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9739 		connp->conn_rq = q;
9740 		connp->conn_wq = WR(q);
9741 	} else {
9742 		connp->conn_ulp = IPPROTO_SCTP;
9743 		connp->conn_rq = connp->conn_wq = NULL;
9744 	}
9745 	/* Non-zero default values */
9746 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9747 
9748 	/*
9749 	 * Make the conn globally visible to walkers
9750 	 */
9751 	mutex_enter(&connp->conn_lock);
9752 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9753 	mutex_exit(&connp->conn_lock);
9754 	ASSERT(connp->conn_ref == 1);
9755 
9756 	qprocson(q);
9757 
9758 	return (0);
9759 }
9760 
9761 /*
9762  * Change q_qinfo based on the value of isv6.
9763  * This can not called on an ill queue.
9764  * Note that there is no race since either q_qinfo works for conn queues - it
9765  * is just an optimization to enter the best wput routine directly.
9766  */
9767 void
9768 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9769 {
9770 	ASSERT(q->q_flag & QREADR);
9771 	ASSERT(WR(q)->q_next == NULL);
9772 	ASSERT(q->q_ptr != NULL);
9773 
9774 	if (minor == IPV6_MINOR)  {
9775 		if (bump_mib)
9776 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9777 		q->q_qinfo = &rinit_ipv6;
9778 		WR(q)->q_qinfo = &winit_ipv6;
9779 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9780 	} else {
9781 		if (bump_mib)
9782 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9783 		q->q_qinfo = &iprinit;
9784 		WR(q)->q_qinfo = &ipwinit;
9785 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9786 	}
9787 
9788 }
9789 
9790 /*
9791  * See if IPsec needs loading because of the options in mp.
9792  */
9793 static boolean_t
9794 ipsec_opt_present(mblk_t *mp)
9795 {
9796 	uint8_t *optcp, *next_optcp, *opt_endcp;
9797 	struct opthdr *opt;
9798 	struct T_opthdr *topt;
9799 	int opthdr_len;
9800 	t_uscalar_t optname, optlevel;
9801 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9802 	ipsec_req_t *ipsr;
9803 
9804 	/*
9805 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9806 	 * return TRUE.
9807 	 */
9808 
9809 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9810 	opt_endcp = optcp + tor->OPT_length;
9811 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9812 		opthdr_len = sizeof (struct T_opthdr);
9813 	} else {		/* O_OPTMGMT_REQ */
9814 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9815 		opthdr_len = sizeof (struct opthdr);
9816 	}
9817 	for (; optcp < opt_endcp; optcp = next_optcp) {
9818 		if (optcp + opthdr_len > opt_endcp)
9819 			return (B_FALSE);	/* Not enough option header. */
9820 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9821 			topt = (struct T_opthdr *)optcp;
9822 			optlevel = topt->level;
9823 			optname = topt->name;
9824 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9825 		} else {
9826 			opt = (struct opthdr *)optcp;
9827 			optlevel = opt->level;
9828 			optname = opt->name;
9829 			next_optcp = optcp + opthdr_len +
9830 			    _TPI_ALIGN_OPT(opt->len);
9831 		}
9832 		if ((next_optcp < optcp) || /* wraparound pointer space */
9833 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9834 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9835 			return (B_FALSE); /* bad option buffer */
9836 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9837 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9838 			/*
9839 			 * Check to see if it's an all-bypass or all-zeroes
9840 			 * IPsec request.  Don't bother loading IPsec if
9841 			 * the socket doesn't want to use it.  (A good example
9842 			 * is a bypass request.)
9843 			 *
9844 			 * Basically, if any of the non-NEVER bits are set,
9845 			 * load IPsec.
9846 			 */
9847 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9848 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9849 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9850 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9851 			    != 0)
9852 				return (B_TRUE);
9853 		}
9854 	}
9855 	return (B_FALSE);
9856 }
9857 
9858 /*
9859  * If conn is is waiting for ipsec to finish loading, kick it.
9860  */
9861 /* ARGSUSED */
9862 static void
9863 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9864 {
9865 	t_scalar_t	optreq_prim;
9866 	mblk_t		*mp;
9867 	cred_t		*cr;
9868 	int		err = 0;
9869 
9870 	/*
9871 	 * This function is called, after ipsec loading is complete.
9872 	 * Since IP checks exclusively and atomically (i.e it prevents
9873 	 * ipsec load from completing until ip_optcom_req completes)
9874 	 * whether ipsec load is complete, there cannot be a race with IP
9875 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9876 	 */
9877 	mutex_enter(&connp->conn_lock);
9878 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9879 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9880 		mp = connp->conn_ipsec_opt_mp;
9881 		connp->conn_ipsec_opt_mp = NULL;
9882 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9883 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9884 		mutex_exit(&connp->conn_lock);
9885 
9886 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9887 
9888 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9889 		if (optreq_prim == T_OPTMGMT_REQ) {
9890 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9891 			    &ip_opt_obj);
9892 		} else {
9893 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9894 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9895 			    &ip_opt_obj);
9896 		}
9897 		if (err != EINPROGRESS)
9898 			CONN_OPER_PENDING_DONE(connp);
9899 		return;
9900 	}
9901 	mutex_exit(&connp->conn_lock);
9902 }
9903 
9904 /*
9905  * Called from the ipsec_loader thread, outside any perimeter, to tell
9906  * ip qenable any of the queues waiting for the ipsec loader to
9907  * complete.
9908  *
9909  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9910  * are done with this lock held, so it's guaranteed that none of the
9911  * links will change along the way.
9912  */
9913 void
9914 ip_ipsec_load_complete()
9915 {
9916 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9917 }
9918 
9919 /*
9920  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9921  * determines the grp on which it has to become exclusive, queues the mp
9922  * and sq draining restarts the optmgmt
9923  */
9924 static boolean_t
9925 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9926 {
9927 	conn_t *connp;
9928 
9929 	/*
9930 	 * Take IPsec requests and treat them special.
9931 	 */
9932 	if (ipsec_opt_present(mp)) {
9933 		/* First check if IPsec is loaded. */
9934 		mutex_enter(&ipsec_loader_lock);
9935 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9936 			mutex_exit(&ipsec_loader_lock);
9937 			return (B_FALSE);
9938 		}
9939 		connp = Q_TO_CONN(q);
9940 		mutex_enter(&connp->conn_lock);
9941 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9942 
9943 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9944 		connp->conn_ipsec_opt_mp = mp;
9945 		mutex_exit(&connp->conn_lock);
9946 		mutex_exit(&ipsec_loader_lock);
9947 
9948 		ipsec_loader_loadnow();
9949 		return (B_TRUE);
9950 	}
9951 	return (B_FALSE);
9952 }
9953 
9954 /*
9955  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9956  * all of them are copied to the conn_t. If the req is "zero", the policy is
9957  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9958  * fields.
9959  * We keep only the latest setting of the policy and thus policy setting
9960  * is not incremental/cumulative.
9961  *
9962  * Requests to set policies with multiple alternative actions will
9963  * go through a different API.
9964  */
9965 int
9966 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9967 {
9968 	uint_t ah_req = 0;
9969 	uint_t esp_req = 0;
9970 	uint_t se_req = 0;
9971 	ipsec_selkey_t sel;
9972 	ipsec_act_t *actp = NULL;
9973 	uint_t nact;
9974 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9975 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9976 	ipsec_policy_root_t *pr;
9977 	ipsec_policy_head_t *ph;
9978 	int fam;
9979 	boolean_t is_pol_reset;
9980 	int error = 0;
9981 
9982 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9983 
9984 	/*
9985 	 * The IP_SEC_OPT option does not allow variable length parameters,
9986 	 * hence a request cannot be NULL.
9987 	 */
9988 	if (req == NULL)
9989 		return (EINVAL);
9990 
9991 	ah_req = req->ipsr_ah_req;
9992 	esp_req = req->ipsr_esp_req;
9993 	se_req = req->ipsr_self_encap_req;
9994 
9995 	/*
9996 	 * Are we dealing with a request to reset the policy (i.e.
9997 	 * zero requests).
9998 	 */
9999 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10000 	    (esp_req & REQ_MASK) == 0 &&
10001 	    (se_req & REQ_MASK) == 0);
10002 
10003 	if (!is_pol_reset) {
10004 		/*
10005 		 * If we couldn't load IPsec, fail with "protocol
10006 		 * not supported".
10007 		 * IPsec may not have been loaded for a request with zero
10008 		 * policies, so we don't fail in this case.
10009 		 */
10010 		mutex_enter(&ipsec_loader_lock);
10011 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10012 			mutex_exit(&ipsec_loader_lock);
10013 			return (EPROTONOSUPPORT);
10014 		}
10015 		mutex_exit(&ipsec_loader_lock);
10016 
10017 		/*
10018 		 * Test for valid requests. Invalid algorithms
10019 		 * need to be tested by IPSEC code because new
10020 		 * algorithms can be added dynamically.
10021 		 */
10022 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10023 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10024 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10025 			return (EINVAL);
10026 		}
10027 
10028 		/*
10029 		 * Only privileged users can issue these
10030 		 * requests.
10031 		 */
10032 		if (((ah_req & IPSEC_PREF_NEVER) ||
10033 		    (esp_req & IPSEC_PREF_NEVER) ||
10034 		    (se_req & IPSEC_PREF_NEVER)) &&
10035 		    secpolicy_net_config(cr, B_FALSE) != 0) {
10036 			return (EPERM);
10037 		}
10038 
10039 		/*
10040 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10041 		 * are mutually exclusive.
10042 		 */
10043 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10044 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10045 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10046 			/* Both of them are set */
10047 			return (EINVAL);
10048 		}
10049 	}
10050 
10051 	mutex_enter(&connp->conn_lock);
10052 
10053 	/*
10054 	 * If we have already cached policies in ip_bind_connected*(), don't
10055 	 * let them change now. We cache policies for connections
10056 	 * whose src,dst [addr, port] is known.
10057 	 */
10058 	if (connp->conn_policy_cached) {
10059 		mutex_exit(&connp->conn_lock);
10060 		return (EINVAL);
10061 	}
10062 
10063 	/*
10064 	 * We have a zero policies, reset the connection policy if already
10065 	 * set. This will cause the connection to inherit the
10066 	 * global policy, if any.
10067 	 */
10068 	if (is_pol_reset) {
10069 		if (connp->conn_policy != NULL) {
10070 			IPPH_REFRELE(connp->conn_policy);
10071 			connp->conn_policy = NULL;
10072 		}
10073 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10074 		connp->conn_in_enforce_policy = B_FALSE;
10075 		connp->conn_out_enforce_policy = B_FALSE;
10076 		mutex_exit(&connp->conn_lock);
10077 		return (0);
10078 	}
10079 
10080 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
10081 	if (ph == NULL)
10082 		goto enomem;
10083 
10084 	ipsec_actvec_from_req(req, &actp, &nact);
10085 	if (actp == NULL)
10086 		goto enomem;
10087 
10088 	/*
10089 	 * Always allocate IPv4 policy entries, since they can also
10090 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10091 	 */
10092 	bzero(&sel, sizeof (sel));
10093 	sel.ipsl_valid = IPSL_IPV4;
10094 
10095 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10096 	if (pin4 == NULL)
10097 		goto enomem;
10098 
10099 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10100 	if (pout4 == NULL)
10101 		goto enomem;
10102 
10103 	if (connp->conn_pkt_isv6) {
10104 		/*
10105 		 * We're looking at a v6 socket, also allocate the
10106 		 * v6-specific entries...
10107 		 */
10108 		sel.ipsl_valid = IPSL_IPV6;
10109 		pin6 = ipsec_policy_create(&sel, actp, nact,
10110 		    IPSEC_PRIO_SOCKET, NULL);
10111 		if (pin6 == NULL)
10112 			goto enomem;
10113 
10114 		pout6 = ipsec_policy_create(&sel, actp, nact,
10115 		    IPSEC_PRIO_SOCKET, NULL);
10116 		if (pout6 == NULL)
10117 			goto enomem;
10118 
10119 		/*
10120 		 * .. and file them away in the right place.
10121 		 */
10122 		fam = IPSEC_AF_V6;
10123 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10124 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10125 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10126 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10127 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10128 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10129 	}
10130 
10131 	ipsec_actvec_free(actp, nact);
10132 
10133 	/*
10134 	 * File the v4 policies.
10135 	 */
10136 	fam = IPSEC_AF_V4;
10137 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10138 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10139 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10140 
10141 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10142 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10143 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10144 
10145 	/*
10146 	 * If the requests need security, set enforce_policy.
10147 	 * If the requests are IPSEC_PREF_NEVER, one should
10148 	 * still set conn_out_enforce_policy so that an ipsec_out
10149 	 * gets attached in ip_wput. This is needed so that
10150 	 * for connections that we don't cache policy in ip_bind,
10151 	 * if global policy matches in ip_wput_attach_policy, we
10152 	 * don't wrongly inherit global policy. Similarly, we need
10153 	 * to set conn_in_enforce_policy also so that we don't verify
10154 	 * policy wrongly.
10155 	 */
10156 	if ((ah_req & REQ_MASK) != 0 ||
10157 	    (esp_req & REQ_MASK) != 0 ||
10158 	    (se_req & REQ_MASK) != 0) {
10159 		connp->conn_in_enforce_policy = B_TRUE;
10160 		connp->conn_out_enforce_policy = B_TRUE;
10161 		connp->conn_flags |= IPCL_CHECK_POLICY;
10162 	}
10163 
10164 	mutex_exit(&connp->conn_lock);
10165 	return (error);
10166 #undef REQ_MASK
10167 
10168 	/*
10169 	 * Common memory-allocation-failure exit path.
10170 	 */
10171 enomem:
10172 	mutex_exit(&connp->conn_lock);
10173 	if (actp != NULL)
10174 		ipsec_actvec_free(actp, nact);
10175 	if (pin4 != NULL)
10176 		IPPOL_REFRELE(pin4);
10177 	if (pout4 != NULL)
10178 		IPPOL_REFRELE(pout4);
10179 	if (pin6 != NULL)
10180 		IPPOL_REFRELE(pin6);
10181 	if (pout6 != NULL)
10182 		IPPOL_REFRELE(pout6);
10183 	return (ENOMEM);
10184 }
10185 
10186 /*
10187  * Only for options that pass in an IP addr. Currently only V4 options
10188  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10189  * So this function assumes level is IPPROTO_IP
10190  */
10191 int
10192 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10193     mblk_t *first_mp)
10194 {
10195 	ipif_t *ipif = NULL;
10196 	int error;
10197 	ill_t *ill;
10198 	int zoneid;
10199 
10200 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10201 
10202 	if (addr != INADDR_ANY || checkonly) {
10203 		ASSERT(connp != NULL);
10204 		zoneid = IPCL_ZONEID(connp);
10205 		if (option == IP_NEXTHOP) {
10206 			ipif = ipif_lookup_onlink_addr(addr,
10207 			    connp->conn_zoneid);
10208 		} else {
10209 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10210 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10211 			    &error);
10212 		}
10213 		if (ipif == NULL) {
10214 			if (error == EINPROGRESS)
10215 				return (error);
10216 			else if ((option == IP_MULTICAST_IF) ||
10217 			    (option == IP_NEXTHOP))
10218 				return (EHOSTUNREACH);
10219 			else
10220 				return (EINVAL);
10221 		} else if (checkonly) {
10222 			if (option == IP_MULTICAST_IF) {
10223 				ill = ipif->ipif_ill;
10224 				/* not supported by the virtual network iface */
10225 				if (IS_VNI(ill)) {
10226 					ipif_refrele(ipif);
10227 					return (EINVAL);
10228 				}
10229 			}
10230 			ipif_refrele(ipif);
10231 			return (0);
10232 		}
10233 		ill = ipif->ipif_ill;
10234 		mutex_enter(&connp->conn_lock);
10235 		mutex_enter(&ill->ill_lock);
10236 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10237 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10238 			mutex_exit(&ill->ill_lock);
10239 			mutex_exit(&connp->conn_lock);
10240 			ipif_refrele(ipif);
10241 			return (option == IP_MULTICAST_IF ?
10242 			    EHOSTUNREACH : EINVAL);
10243 		}
10244 	} else {
10245 		mutex_enter(&connp->conn_lock);
10246 	}
10247 
10248 	/* None of the options below are supported on the VNI */
10249 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10250 		mutex_exit(&ill->ill_lock);
10251 		mutex_exit(&connp->conn_lock);
10252 		ipif_refrele(ipif);
10253 		return (EINVAL);
10254 	}
10255 
10256 	switch (option) {
10257 	case IP_DONTFAILOVER_IF:
10258 		/*
10259 		 * This option is used by in.mpathd to ensure
10260 		 * that IPMP probe packets only go out on the
10261 		 * test interfaces. in.mpathd sets this option
10262 		 * on the non-failover interfaces.
10263 		 * For backward compatibility, this option
10264 		 * implicitly sets IP_MULTICAST_IF, as used
10265 		 * be done in bind(), so that ip_wput gets
10266 		 * this ipif to send mcast packets.
10267 		 */
10268 		if (ipif != NULL) {
10269 			ASSERT(addr != INADDR_ANY);
10270 			connp->conn_nofailover_ill = ipif->ipif_ill;
10271 			connp->conn_multicast_ipif = ipif;
10272 		} else {
10273 			ASSERT(addr == INADDR_ANY);
10274 			connp->conn_nofailover_ill = NULL;
10275 			connp->conn_multicast_ipif = NULL;
10276 		}
10277 		break;
10278 
10279 	case IP_MULTICAST_IF:
10280 		connp->conn_multicast_ipif = ipif;
10281 		break;
10282 	case IP_NEXTHOP:
10283 		connp->conn_nexthop_v4 = addr;
10284 		connp->conn_nexthop_set = B_TRUE;
10285 		break;
10286 	}
10287 
10288 	if (ipif != NULL) {
10289 		mutex_exit(&ill->ill_lock);
10290 		mutex_exit(&connp->conn_lock);
10291 		ipif_refrele(ipif);
10292 		return (0);
10293 	}
10294 	mutex_exit(&connp->conn_lock);
10295 	/* We succeded in cleared the option */
10296 	return (0);
10297 }
10298 
10299 /*
10300  * For options that pass in an ifindex specifying the ill. V6 options always
10301  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10302  */
10303 int
10304 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10305     int level, int option, mblk_t *first_mp)
10306 {
10307 	ill_t *ill = NULL;
10308 	int error = 0;
10309 
10310 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10311 	if (ifindex != 0) {
10312 		ASSERT(connp != NULL);
10313 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10314 		    first_mp, ip_restart_optmgmt, &error);
10315 		if (ill != NULL) {
10316 			if (checkonly) {
10317 				/* not supported by the virtual network iface */
10318 				if (IS_VNI(ill)) {
10319 					ill_refrele(ill);
10320 					return (EINVAL);
10321 				}
10322 				ill_refrele(ill);
10323 				return (0);
10324 			}
10325 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10326 			    0, NULL)) {
10327 				ill_refrele(ill);
10328 				ill = NULL;
10329 				mutex_enter(&connp->conn_lock);
10330 				goto setit;
10331 			}
10332 			mutex_enter(&connp->conn_lock);
10333 			mutex_enter(&ill->ill_lock);
10334 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10335 				mutex_exit(&ill->ill_lock);
10336 				mutex_exit(&connp->conn_lock);
10337 				ill_refrele(ill);
10338 				ill = NULL;
10339 				mutex_enter(&connp->conn_lock);
10340 			}
10341 			goto setit;
10342 		} else if (error == EINPROGRESS) {
10343 			return (error);
10344 		} else {
10345 			error = 0;
10346 		}
10347 	}
10348 	mutex_enter(&connp->conn_lock);
10349 setit:
10350 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10351 
10352 	/*
10353 	 * The options below assume that the ILL (if any) transmits and/or
10354 	 * receives traffic. Neither of which is true for the virtual network
10355 	 * interface, so fail setting these on a VNI.
10356 	 */
10357 	if (IS_VNI(ill)) {
10358 		ASSERT(ill != NULL);
10359 		mutex_exit(&ill->ill_lock);
10360 		mutex_exit(&connp->conn_lock);
10361 		ill_refrele(ill);
10362 		return (EINVAL);
10363 	}
10364 
10365 	if (level == IPPROTO_IP) {
10366 		switch (option) {
10367 		case IP_BOUND_IF:
10368 			connp->conn_incoming_ill = ill;
10369 			connp->conn_outgoing_ill = ill;
10370 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10371 			    0 : ifindex;
10372 			break;
10373 
10374 		case IP_XMIT_IF:
10375 			/*
10376 			 * Similar to IP_BOUND_IF, but this only
10377 			 * determines the outgoing interface for
10378 			 * unicast packets. Also no IRE_CACHE entry
10379 			 * is added for the destination of the
10380 			 * outgoing packets. This feature is needed
10381 			 * for mobile IP.
10382 			 */
10383 			connp->conn_xmit_if_ill = ill;
10384 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10385 			    0 : ifindex;
10386 			break;
10387 
10388 		case IP_MULTICAST_IF:
10389 			/*
10390 			 * This option is an internal special. The socket
10391 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10392 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10393 			 * specifies an ifindex and we try first on V6 ill's.
10394 			 * If we don't find one, we they try using on v4 ill's
10395 			 * intenally and we come here.
10396 			 */
10397 			if (!checkonly && ill != NULL) {
10398 				ipif_t	*ipif;
10399 				ipif = ill->ill_ipif;
10400 
10401 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10402 					mutex_exit(&ill->ill_lock);
10403 					mutex_exit(&connp->conn_lock);
10404 					ill_refrele(ill);
10405 					ill = NULL;
10406 					mutex_enter(&connp->conn_lock);
10407 				} else {
10408 					connp->conn_multicast_ipif = ipif;
10409 				}
10410 			}
10411 			break;
10412 		}
10413 	} else {
10414 		switch (option) {
10415 		case IPV6_BOUND_IF:
10416 			connp->conn_incoming_ill = ill;
10417 			connp->conn_outgoing_ill = ill;
10418 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10419 			    0 : ifindex;
10420 			break;
10421 
10422 		case IPV6_BOUND_PIF:
10423 			/*
10424 			 * Limit all transmit to this ill.
10425 			 * Unlike IPV6_BOUND_IF, using this option
10426 			 * prevents load spreading and failover from
10427 			 * happening when the interface is part of the
10428 			 * group. That's why we don't need to remember
10429 			 * the ifindex in orig_bound_ifindex as in
10430 			 * IPV6_BOUND_IF.
10431 			 */
10432 			connp->conn_outgoing_pill = ill;
10433 			break;
10434 
10435 		case IPV6_DONTFAILOVER_IF:
10436 			/*
10437 			 * This option is used by in.mpathd to ensure
10438 			 * that IPMP probe packets only go out on the
10439 			 * test interfaces. in.mpathd sets this option
10440 			 * on the non-failover interfaces.
10441 			 */
10442 			connp->conn_nofailover_ill = ill;
10443 			/*
10444 			 * For backward compatibility, this option
10445 			 * implicitly sets ip_multicast_ill as used in
10446 			 * IP_MULTICAST_IF so that ip_wput gets
10447 			 * this ipif to send mcast packets.
10448 			 */
10449 			connp->conn_multicast_ill = ill;
10450 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10451 			    0 : ifindex;
10452 			break;
10453 
10454 		case IPV6_MULTICAST_IF:
10455 			/*
10456 			 * Set conn_multicast_ill to be the IPv6 ill.
10457 			 * Set conn_multicast_ipif to be an IPv4 ipif
10458 			 * for ifindex to make IPv4 mapped addresses
10459 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10460 			 * Even if no IPv6 ill exists for the ifindex
10461 			 * we need to check for an IPv4 ifindex in order
10462 			 * for this to work with mapped addresses. In that
10463 			 * case only set conn_multicast_ipif.
10464 			 */
10465 			if (!checkonly) {
10466 				if (ifindex == 0) {
10467 					connp->conn_multicast_ill = NULL;
10468 					connp->conn_orig_multicast_ifindex = 0;
10469 					connp->conn_multicast_ipif = NULL;
10470 				} else if (ill != NULL) {
10471 					connp->conn_multicast_ill = ill;
10472 					connp->conn_orig_multicast_ifindex =
10473 					    ifindex;
10474 				}
10475 			}
10476 			break;
10477 		}
10478 	}
10479 
10480 	if (ill != NULL) {
10481 		mutex_exit(&ill->ill_lock);
10482 		mutex_exit(&connp->conn_lock);
10483 		ill_refrele(ill);
10484 		return (0);
10485 	}
10486 	mutex_exit(&connp->conn_lock);
10487 	/*
10488 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10489 	 * locate the ill and could not set the option (ifindex != 0)
10490 	 */
10491 	return (ifindex == 0 ? 0 : EINVAL);
10492 }
10493 
10494 /* This routine sets socket options. */
10495 /* ARGSUSED */
10496 int
10497 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10498     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10499     void *dummy, cred_t *cr, mblk_t *first_mp)
10500 {
10501 	int		*i1 = (int *)invalp;
10502 	conn_t		*connp = Q_TO_CONN(q);
10503 	int		error = 0;
10504 	boolean_t	checkonly;
10505 	ire_t		*ire;
10506 	boolean_t	found;
10507 
10508 	switch (optset_context) {
10509 
10510 	case SETFN_OPTCOM_CHECKONLY:
10511 		checkonly = B_TRUE;
10512 		/*
10513 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10514 		 * inlen != 0 implies value supplied and
10515 		 * 	we have to "pretend" to set it.
10516 		 * inlen == 0 implies that there is no
10517 		 * 	value part in T_CHECK request and just validation
10518 		 * done elsewhere should be enough, we just return here.
10519 		 */
10520 		if (inlen == 0) {
10521 			*outlenp = 0;
10522 			return (0);
10523 		}
10524 		break;
10525 	case SETFN_OPTCOM_NEGOTIATE:
10526 	case SETFN_UD_NEGOTIATE:
10527 	case SETFN_CONN_NEGOTIATE:
10528 		checkonly = B_FALSE;
10529 		break;
10530 	default:
10531 		/*
10532 		 * We should never get here
10533 		 */
10534 		*outlenp = 0;
10535 		return (EINVAL);
10536 	}
10537 
10538 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10539 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10540 
10541 	/*
10542 	 * For fixed length options, no sanity check
10543 	 * of passed in length is done. It is assumed *_optcom_req()
10544 	 * routines do the right thing.
10545 	 */
10546 
10547 	switch (level) {
10548 	case SOL_SOCKET:
10549 		/*
10550 		 * conn_lock protects the bitfields, and is used to
10551 		 * set the fields atomically.
10552 		 */
10553 		switch (name) {
10554 		case SO_BROADCAST:
10555 			if (!checkonly) {
10556 				/* TODO: use value someplace? */
10557 				mutex_enter(&connp->conn_lock);
10558 				connp->conn_broadcast = *i1 ? 1 : 0;
10559 				mutex_exit(&connp->conn_lock);
10560 			}
10561 			break;	/* goto sizeof (int) option return */
10562 		case SO_USELOOPBACK:
10563 			if (!checkonly) {
10564 				/* TODO: use value someplace? */
10565 				mutex_enter(&connp->conn_lock);
10566 				connp->conn_loopback = *i1 ? 1 : 0;
10567 				mutex_exit(&connp->conn_lock);
10568 			}
10569 			break;	/* goto sizeof (int) option return */
10570 		case SO_DONTROUTE:
10571 			if (!checkonly) {
10572 				mutex_enter(&connp->conn_lock);
10573 				connp->conn_dontroute = *i1 ? 1 : 0;
10574 				mutex_exit(&connp->conn_lock);
10575 			}
10576 			break;	/* goto sizeof (int) option return */
10577 		case SO_REUSEADDR:
10578 			if (!checkonly) {
10579 				mutex_enter(&connp->conn_lock);
10580 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10581 				mutex_exit(&connp->conn_lock);
10582 			}
10583 			break;	/* goto sizeof (int) option return */
10584 		case SO_PROTOTYPE:
10585 			if (!checkonly) {
10586 				mutex_enter(&connp->conn_lock);
10587 				connp->conn_proto = *i1;
10588 				mutex_exit(&connp->conn_lock);
10589 			}
10590 			break;	/* goto sizeof (int) option return */
10591 		case SO_ALLZONES:
10592 			if (!checkonly) {
10593 				mutex_enter(&connp->conn_lock);
10594 				if (IPCL_IS_BOUND(connp)) {
10595 					mutex_exit(&connp->conn_lock);
10596 					return (EINVAL);
10597 				}
10598 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10599 				mutex_exit(&connp->conn_lock);
10600 			}
10601 			break;	/* goto sizeof (int) option return */
10602 		case SO_ANON_MLP:
10603 			if (!checkonly) {
10604 				mutex_enter(&connp->conn_lock);
10605 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10606 				mutex_exit(&connp->conn_lock);
10607 			}
10608 			break;	/* goto sizeof (int) option return */
10609 		case SO_MAC_EXEMPT:
10610 			if (secpolicy_net_mac_aware(cr) != 0 ||
10611 			    IPCL_IS_BOUND(connp))
10612 				return (EACCES);
10613 			if (!checkonly) {
10614 				mutex_enter(&connp->conn_lock);
10615 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10616 				mutex_exit(&connp->conn_lock);
10617 			}
10618 			break;	/* goto sizeof (int) option return */
10619 		default:
10620 			/*
10621 			 * "soft" error (negative)
10622 			 * option not handled at this level
10623 			 * Note: Do not modify *outlenp
10624 			 */
10625 			return (-EINVAL);
10626 		}
10627 		break;
10628 	case IPPROTO_IP:
10629 		switch (name) {
10630 		case IP_NEXTHOP:
10631 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10632 				return (EPERM);
10633 			/* FALLTHRU */
10634 		case IP_MULTICAST_IF:
10635 		case IP_DONTFAILOVER_IF: {
10636 			ipaddr_t addr = *i1;
10637 
10638 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10639 			    first_mp);
10640 			if (error != 0)
10641 				return (error);
10642 			break;	/* goto sizeof (int) option return */
10643 		}
10644 
10645 		case IP_MULTICAST_TTL:
10646 			/* Recorded in transport above IP */
10647 			*outvalp = *invalp;
10648 			*outlenp = sizeof (uchar_t);
10649 			return (0);
10650 		case IP_MULTICAST_LOOP:
10651 			if (!checkonly) {
10652 				mutex_enter(&connp->conn_lock);
10653 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10654 				mutex_exit(&connp->conn_lock);
10655 			}
10656 			*outvalp = *invalp;
10657 			*outlenp = sizeof (uchar_t);
10658 			return (0);
10659 		case IP_ADD_MEMBERSHIP:
10660 		case MCAST_JOIN_GROUP:
10661 		case IP_DROP_MEMBERSHIP:
10662 		case MCAST_LEAVE_GROUP: {
10663 			struct ip_mreq *mreqp;
10664 			struct group_req *greqp;
10665 			ire_t *ire;
10666 			boolean_t done = B_FALSE;
10667 			ipaddr_t group, ifaddr;
10668 			struct sockaddr_in *sin;
10669 			uint32_t *ifindexp;
10670 			boolean_t mcast_opt = B_TRUE;
10671 			mcast_record_t fmode;
10672 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10673 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10674 
10675 			switch (name) {
10676 			case IP_ADD_MEMBERSHIP:
10677 				mcast_opt = B_FALSE;
10678 				/* FALLTHRU */
10679 			case MCAST_JOIN_GROUP:
10680 				fmode = MODE_IS_EXCLUDE;
10681 				optfn = ip_opt_add_group;
10682 				break;
10683 
10684 			case IP_DROP_MEMBERSHIP:
10685 				mcast_opt = B_FALSE;
10686 				/* FALLTHRU */
10687 			case MCAST_LEAVE_GROUP:
10688 				fmode = MODE_IS_INCLUDE;
10689 				optfn = ip_opt_delete_group;
10690 				break;
10691 			}
10692 
10693 			if (mcast_opt) {
10694 				greqp = (struct group_req *)i1;
10695 				sin = (struct sockaddr_in *)&greqp->gr_group;
10696 				if (sin->sin_family != AF_INET) {
10697 					*outlenp = 0;
10698 					return (ENOPROTOOPT);
10699 				}
10700 				group = (ipaddr_t)sin->sin_addr.s_addr;
10701 				ifaddr = INADDR_ANY;
10702 				ifindexp = &greqp->gr_interface;
10703 			} else {
10704 				mreqp = (struct ip_mreq *)i1;
10705 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10706 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10707 				ifindexp = NULL;
10708 			}
10709 
10710 			/*
10711 			 * In the multirouting case, we need to replicate
10712 			 * the request on all interfaces that will take part
10713 			 * in replication.  We do so because multirouting is
10714 			 * reflective, thus we will probably receive multi-
10715 			 * casts on those interfaces.
10716 			 * The ip_multirt_apply_membership() succeeds if the
10717 			 * operation succeeds on at least one interface.
10718 			 */
10719 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10720 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10721 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10722 			if (ire != NULL) {
10723 				if (ire->ire_flags & RTF_MULTIRT) {
10724 					error = ip_multirt_apply_membership(
10725 					    optfn, ire, connp, checkonly, group,
10726 					    fmode, INADDR_ANY, first_mp);
10727 					done = B_TRUE;
10728 				}
10729 				ire_refrele(ire);
10730 			}
10731 			if (!done) {
10732 				error = optfn(connp, checkonly, group, ifaddr,
10733 				    ifindexp, fmode, INADDR_ANY, first_mp);
10734 			}
10735 			if (error) {
10736 				/*
10737 				 * EINPROGRESS is a soft error, needs retry
10738 				 * so don't make *outlenp zero.
10739 				 */
10740 				if (error != EINPROGRESS)
10741 					*outlenp = 0;
10742 				return (error);
10743 			}
10744 			/* OK return - copy input buffer into output buffer */
10745 			if (invalp != outvalp) {
10746 				/* don't trust bcopy for identical src/dst */
10747 				bcopy(invalp, outvalp, inlen);
10748 			}
10749 			*outlenp = inlen;
10750 			return (0);
10751 		}
10752 		case IP_BLOCK_SOURCE:
10753 		case IP_UNBLOCK_SOURCE:
10754 		case IP_ADD_SOURCE_MEMBERSHIP:
10755 		case IP_DROP_SOURCE_MEMBERSHIP:
10756 		case MCAST_BLOCK_SOURCE:
10757 		case MCAST_UNBLOCK_SOURCE:
10758 		case MCAST_JOIN_SOURCE_GROUP:
10759 		case MCAST_LEAVE_SOURCE_GROUP: {
10760 			struct ip_mreq_source *imreqp;
10761 			struct group_source_req *gsreqp;
10762 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10763 			uint32_t ifindex = 0;
10764 			mcast_record_t fmode;
10765 			struct sockaddr_in *sin;
10766 			ire_t *ire;
10767 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10768 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10769 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10770 
10771 			switch (name) {
10772 			case IP_BLOCK_SOURCE:
10773 				mcast_opt = B_FALSE;
10774 				/* FALLTHRU */
10775 			case MCAST_BLOCK_SOURCE:
10776 				fmode = MODE_IS_EXCLUDE;
10777 				optfn = ip_opt_add_group;
10778 				break;
10779 
10780 			case IP_UNBLOCK_SOURCE:
10781 				mcast_opt = B_FALSE;
10782 				/* FALLTHRU */
10783 			case MCAST_UNBLOCK_SOURCE:
10784 				fmode = MODE_IS_EXCLUDE;
10785 				optfn = ip_opt_delete_group;
10786 				break;
10787 
10788 			case IP_ADD_SOURCE_MEMBERSHIP:
10789 				mcast_opt = B_FALSE;
10790 				/* FALLTHRU */
10791 			case MCAST_JOIN_SOURCE_GROUP:
10792 				fmode = MODE_IS_INCLUDE;
10793 				optfn = ip_opt_add_group;
10794 				break;
10795 
10796 			case IP_DROP_SOURCE_MEMBERSHIP:
10797 				mcast_opt = B_FALSE;
10798 				/* FALLTHRU */
10799 			case MCAST_LEAVE_SOURCE_GROUP:
10800 				fmode = MODE_IS_INCLUDE;
10801 				optfn = ip_opt_delete_group;
10802 				break;
10803 			}
10804 
10805 			if (mcast_opt) {
10806 				gsreqp = (struct group_source_req *)i1;
10807 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10808 					*outlenp = 0;
10809 					return (ENOPROTOOPT);
10810 				}
10811 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10812 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10813 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10814 				src = (ipaddr_t)sin->sin_addr.s_addr;
10815 				ifindex = gsreqp->gsr_interface;
10816 			} else {
10817 				imreqp = (struct ip_mreq_source *)i1;
10818 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10819 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10820 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10821 			}
10822 
10823 			/*
10824 			 * In the multirouting case, we need to replicate
10825 			 * the request as noted in the mcast cases above.
10826 			 */
10827 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10828 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10829 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10830 			if (ire != NULL) {
10831 				if (ire->ire_flags & RTF_MULTIRT) {
10832 					error = ip_multirt_apply_membership(
10833 					    optfn, ire, connp, checkonly, grp,
10834 					    fmode, src, first_mp);
10835 					done = B_TRUE;
10836 				}
10837 				ire_refrele(ire);
10838 			}
10839 			if (!done) {
10840 				error = optfn(connp, checkonly, grp, ifaddr,
10841 				    &ifindex, fmode, src, first_mp);
10842 			}
10843 			if (error != 0) {
10844 				/*
10845 				 * EINPROGRESS is a soft error, needs retry
10846 				 * so don't make *outlenp zero.
10847 				 */
10848 				if (error != EINPROGRESS)
10849 					*outlenp = 0;
10850 				return (error);
10851 			}
10852 			/* OK return - copy input buffer into output buffer */
10853 			if (invalp != outvalp) {
10854 				bcopy(invalp, outvalp, inlen);
10855 			}
10856 			*outlenp = inlen;
10857 			return (0);
10858 		}
10859 		case IP_SEC_OPT:
10860 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10861 			if (error != 0) {
10862 				*outlenp = 0;
10863 				return (error);
10864 			}
10865 			break;
10866 		case IP_HDRINCL:
10867 		case IP_OPTIONS:
10868 		case T_IP_OPTIONS:
10869 		case IP_TOS:
10870 		case T_IP_TOS:
10871 		case IP_TTL:
10872 		case IP_RECVDSTADDR:
10873 		case IP_RECVOPTS:
10874 			/* OK return - copy input buffer into output buffer */
10875 			if (invalp != outvalp) {
10876 				/* don't trust bcopy for identical src/dst */
10877 				bcopy(invalp, outvalp, inlen);
10878 			}
10879 			*outlenp = inlen;
10880 			return (0);
10881 		case IP_RECVIF:
10882 			/* Retrieve the inbound interface index */
10883 			if (!checkonly) {
10884 				mutex_enter(&connp->conn_lock);
10885 				connp->conn_recvif = *i1 ? 1 : 0;
10886 				mutex_exit(&connp->conn_lock);
10887 			}
10888 			break;	/* goto sizeof (int) option return */
10889 		case IP_RECVSLLA:
10890 			/* Retrieve the source link layer address */
10891 			if (!checkonly) {
10892 				mutex_enter(&connp->conn_lock);
10893 				connp->conn_recvslla = *i1 ? 1 : 0;
10894 				mutex_exit(&connp->conn_lock);
10895 			}
10896 			break;	/* goto sizeof (int) option return */
10897 		case MRT_INIT:
10898 		case MRT_DONE:
10899 		case MRT_ADD_VIF:
10900 		case MRT_DEL_VIF:
10901 		case MRT_ADD_MFC:
10902 		case MRT_DEL_MFC:
10903 		case MRT_ASSERT:
10904 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10905 				*outlenp = 0;
10906 				return (error);
10907 			}
10908 			error = ip_mrouter_set((int)name, q, checkonly,
10909 			    (uchar_t *)invalp, inlen, first_mp);
10910 			if (error) {
10911 				*outlenp = 0;
10912 				return (error);
10913 			}
10914 			/* OK return - copy input buffer into output buffer */
10915 			if (invalp != outvalp) {
10916 				/* don't trust bcopy for identical src/dst */
10917 				bcopy(invalp, outvalp, inlen);
10918 			}
10919 			*outlenp = inlen;
10920 			return (0);
10921 		case IP_BOUND_IF:
10922 		case IP_XMIT_IF:
10923 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10924 			    level, name, first_mp);
10925 			if (error != 0)
10926 				return (error);
10927 			break; 		/* goto sizeof (int) option return */
10928 
10929 		case IP_UNSPEC_SRC:
10930 			/* Allow sending with a zero source address */
10931 			if (!checkonly) {
10932 				mutex_enter(&connp->conn_lock);
10933 				connp->conn_unspec_src = *i1 ? 1 : 0;
10934 				mutex_exit(&connp->conn_lock);
10935 			}
10936 			break;	/* goto sizeof (int) option return */
10937 		default:
10938 			/*
10939 			 * "soft" error (negative)
10940 			 * option not handled at this level
10941 			 * Note: Do not modify *outlenp
10942 			 */
10943 			return (-EINVAL);
10944 		}
10945 		break;
10946 	case IPPROTO_IPV6:
10947 		switch (name) {
10948 		case IPV6_BOUND_IF:
10949 		case IPV6_BOUND_PIF:
10950 		case IPV6_DONTFAILOVER_IF:
10951 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10952 			    level, name, first_mp);
10953 			if (error != 0)
10954 				return (error);
10955 			break; 		/* goto sizeof (int) option return */
10956 
10957 		case IPV6_MULTICAST_IF:
10958 			/*
10959 			 * The only possible errors are EINPROGRESS and
10960 			 * EINVAL. EINPROGRESS will be restarted and is not
10961 			 * a hard error. We call this option on both V4 and V6
10962 			 * If both return EINVAL, then this call returns
10963 			 * EINVAL. If at least one of them succeeds we
10964 			 * return success.
10965 			 */
10966 			found = B_FALSE;
10967 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10968 			    level, name, first_mp);
10969 			if (error == EINPROGRESS)
10970 				return (error);
10971 			if (error == 0)
10972 				found = B_TRUE;
10973 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10974 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10975 			if (error == 0)
10976 				found = B_TRUE;
10977 			if (!found)
10978 				return (error);
10979 			break; 		/* goto sizeof (int) option return */
10980 
10981 		case IPV6_MULTICAST_HOPS:
10982 			/* Recorded in transport above IP */
10983 			break;	/* goto sizeof (int) option return */
10984 		case IPV6_MULTICAST_LOOP:
10985 			if (!checkonly) {
10986 				mutex_enter(&connp->conn_lock);
10987 				connp->conn_multicast_loop = *i1;
10988 				mutex_exit(&connp->conn_lock);
10989 			}
10990 			break;	/* goto sizeof (int) option return */
10991 		case IPV6_JOIN_GROUP:
10992 		case MCAST_JOIN_GROUP:
10993 		case IPV6_LEAVE_GROUP:
10994 		case MCAST_LEAVE_GROUP: {
10995 			struct ipv6_mreq *ip_mreqp;
10996 			struct group_req *greqp;
10997 			ire_t *ire;
10998 			boolean_t done = B_FALSE;
10999 			in6_addr_t groupv6;
11000 			uint32_t ifindex;
11001 			boolean_t mcast_opt = B_TRUE;
11002 			mcast_record_t fmode;
11003 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11004 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11005 
11006 			switch (name) {
11007 			case IPV6_JOIN_GROUP:
11008 				mcast_opt = B_FALSE;
11009 				/* FALLTHRU */
11010 			case MCAST_JOIN_GROUP:
11011 				fmode = MODE_IS_EXCLUDE;
11012 				optfn = ip_opt_add_group_v6;
11013 				break;
11014 
11015 			case IPV6_LEAVE_GROUP:
11016 				mcast_opt = B_FALSE;
11017 				/* FALLTHRU */
11018 			case MCAST_LEAVE_GROUP:
11019 				fmode = MODE_IS_INCLUDE;
11020 				optfn = ip_opt_delete_group_v6;
11021 				break;
11022 			}
11023 
11024 			if (mcast_opt) {
11025 				struct sockaddr_in *sin;
11026 				struct sockaddr_in6 *sin6;
11027 				greqp = (struct group_req *)i1;
11028 				if (greqp->gr_group.ss_family == AF_INET) {
11029 					sin = (struct sockaddr_in *)
11030 					    &(greqp->gr_group);
11031 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11032 					    &groupv6);
11033 				} else {
11034 					sin6 = (struct sockaddr_in6 *)
11035 					    &(greqp->gr_group);
11036 					groupv6 = sin6->sin6_addr;
11037 				}
11038 				ifindex = greqp->gr_interface;
11039 			} else {
11040 				ip_mreqp = (struct ipv6_mreq *)i1;
11041 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11042 				ifindex = ip_mreqp->ipv6mr_interface;
11043 			}
11044 			/*
11045 			 * In the multirouting case, we need to replicate
11046 			 * the request on all interfaces that will take part
11047 			 * in replication.  We do so because multirouting is
11048 			 * reflective, thus we will probably receive multi-
11049 			 * casts on those interfaces.
11050 			 * The ip_multirt_apply_membership_v6() succeeds if
11051 			 * the operation succeeds on at least one interface.
11052 			 */
11053 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11054 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11055 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11056 			if (ire != NULL) {
11057 				if (ire->ire_flags & RTF_MULTIRT) {
11058 					error = ip_multirt_apply_membership_v6(
11059 					    optfn, ire, connp, checkonly,
11060 					    &groupv6, fmode, &ipv6_all_zeros,
11061 					    first_mp);
11062 					done = B_TRUE;
11063 				}
11064 				ire_refrele(ire);
11065 			}
11066 			if (!done) {
11067 				error = optfn(connp, checkonly, &groupv6,
11068 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11069 			}
11070 			if (error) {
11071 				/*
11072 				 * EINPROGRESS is a soft error, needs retry
11073 				 * so don't make *outlenp zero.
11074 				 */
11075 				if (error != EINPROGRESS)
11076 					*outlenp = 0;
11077 				return (error);
11078 			}
11079 			/* OK return - copy input buffer into output buffer */
11080 			if (invalp != outvalp) {
11081 				/* don't trust bcopy for identical src/dst */
11082 				bcopy(invalp, outvalp, inlen);
11083 			}
11084 			*outlenp = inlen;
11085 			return (0);
11086 		}
11087 		case MCAST_BLOCK_SOURCE:
11088 		case MCAST_UNBLOCK_SOURCE:
11089 		case MCAST_JOIN_SOURCE_GROUP:
11090 		case MCAST_LEAVE_SOURCE_GROUP: {
11091 			struct group_source_req *gsreqp;
11092 			in6_addr_t v6grp, v6src;
11093 			uint32_t ifindex;
11094 			mcast_record_t fmode;
11095 			ire_t *ire;
11096 			boolean_t done = B_FALSE;
11097 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11098 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11099 
11100 			switch (name) {
11101 			case MCAST_BLOCK_SOURCE:
11102 				fmode = MODE_IS_EXCLUDE;
11103 				optfn = ip_opt_add_group_v6;
11104 				break;
11105 			case MCAST_UNBLOCK_SOURCE:
11106 				fmode = MODE_IS_EXCLUDE;
11107 				optfn = ip_opt_delete_group_v6;
11108 				break;
11109 			case MCAST_JOIN_SOURCE_GROUP:
11110 				fmode = MODE_IS_INCLUDE;
11111 				optfn = ip_opt_add_group_v6;
11112 				break;
11113 			case MCAST_LEAVE_SOURCE_GROUP:
11114 				fmode = MODE_IS_INCLUDE;
11115 				optfn = ip_opt_delete_group_v6;
11116 				break;
11117 			}
11118 
11119 			gsreqp = (struct group_source_req *)i1;
11120 			ifindex = gsreqp->gsr_interface;
11121 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11122 				struct sockaddr_in *s;
11123 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11124 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11125 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11126 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11127 			} else {
11128 				struct sockaddr_in6 *s6;
11129 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11130 				v6grp = s6->sin6_addr;
11131 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11132 				v6src = s6->sin6_addr;
11133 			}
11134 
11135 			/*
11136 			 * In the multirouting case, we need to replicate
11137 			 * the request as noted in the mcast cases above.
11138 			 */
11139 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11140 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11141 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11142 			if (ire != NULL) {
11143 				if (ire->ire_flags & RTF_MULTIRT) {
11144 					error = ip_multirt_apply_membership_v6(
11145 					    optfn, ire, connp, checkonly,
11146 					    &v6grp, fmode, &v6src, first_mp);
11147 					done = B_TRUE;
11148 				}
11149 				ire_refrele(ire);
11150 			}
11151 			if (!done) {
11152 				error = optfn(connp, checkonly, &v6grp,
11153 				    ifindex, fmode, &v6src, first_mp);
11154 			}
11155 			if (error != 0) {
11156 				/*
11157 				 * EINPROGRESS is a soft error, needs retry
11158 				 * so don't make *outlenp zero.
11159 				 */
11160 				if (error != EINPROGRESS)
11161 					*outlenp = 0;
11162 				return (error);
11163 			}
11164 			/* OK return - copy input buffer into output buffer */
11165 			if (invalp != outvalp) {
11166 				bcopy(invalp, outvalp, inlen);
11167 			}
11168 			*outlenp = inlen;
11169 			return (0);
11170 		}
11171 		case IPV6_UNICAST_HOPS:
11172 			/* Recorded in transport above IP */
11173 			break;	/* goto sizeof (int) option return */
11174 		case IPV6_UNSPEC_SRC:
11175 			/* Allow sending with a zero source address */
11176 			if (!checkonly) {
11177 				mutex_enter(&connp->conn_lock);
11178 				connp->conn_unspec_src = *i1 ? 1 : 0;
11179 				mutex_exit(&connp->conn_lock);
11180 			}
11181 			break;	/* goto sizeof (int) option return */
11182 		case IPV6_RECVPKTINFO:
11183 			if (!checkonly) {
11184 				mutex_enter(&connp->conn_lock);
11185 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
11186 				mutex_exit(&connp->conn_lock);
11187 			}
11188 			break;	/* goto sizeof (int) option return */
11189 		case IPV6_RECVTCLASS:
11190 			if (!checkonly) {
11191 				if (*i1 < 0 || *i1 > 1) {
11192 					return (EINVAL);
11193 				}
11194 				mutex_enter(&connp->conn_lock);
11195 				connp->conn_ipv6_recvtclass = *i1;
11196 				mutex_exit(&connp->conn_lock);
11197 			}
11198 			break;
11199 		case IPV6_RECVPATHMTU:
11200 			if (!checkonly) {
11201 				if (*i1 < 0 || *i1 > 1) {
11202 					return (EINVAL);
11203 				}
11204 				mutex_enter(&connp->conn_lock);
11205 				connp->conn_ipv6_recvpathmtu = *i1;
11206 				mutex_exit(&connp->conn_lock);
11207 			}
11208 			break;
11209 		case IPV6_RECVHOPLIMIT:
11210 			if (!checkonly) {
11211 				mutex_enter(&connp->conn_lock);
11212 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11213 				mutex_exit(&connp->conn_lock);
11214 			}
11215 			break;	/* goto sizeof (int) option return */
11216 		case IPV6_RECVHOPOPTS:
11217 			if (!checkonly) {
11218 				mutex_enter(&connp->conn_lock);
11219 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11220 				mutex_exit(&connp->conn_lock);
11221 			}
11222 			break;	/* goto sizeof (int) option return */
11223 		case IPV6_RECVDSTOPTS:
11224 			if (!checkonly) {
11225 				mutex_enter(&connp->conn_lock);
11226 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11227 				mutex_exit(&connp->conn_lock);
11228 			}
11229 			break;	/* goto sizeof (int) option return */
11230 		case IPV6_RECVRTHDR:
11231 			if (!checkonly) {
11232 				mutex_enter(&connp->conn_lock);
11233 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11234 				mutex_exit(&connp->conn_lock);
11235 			}
11236 			break;	/* goto sizeof (int) option return */
11237 		case IPV6_RECVRTHDRDSTOPTS:
11238 			if (!checkonly) {
11239 				mutex_enter(&connp->conn_lock);
11240 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11241 				mutex_exit(&connp->conn_lock);
11242 			}
11243 			break;	/* goto sizeof (int) option return */
11244 		case IPV6_PKTINFO:
11245 			if (inlen == 0)
11246 				return (-EINVAL);	/* clearing option */
11247 			error = ip6_set_pktinfo(cr, connp,
11248 			    (struct in6_pktinfo *)invalp, first_mp);
11249 			if (error != 0)
11250 				*outlenp = 0;
11251 			else
11252 				*outlenp = inlen;
11253 			return (error);
11254 		case IPV6_NEXTHOP: {
11255 			struct sockaddr_in6 *sin6;
11256 
11257 			/* Verify that the nexthop is reachable */
11258 			if (inlen == 0)
11259 				return (-EINVAL);	/* clearing option */
11260 
11261 			sin6 = (struct sockaddr_in6 *)invalp;
11262 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11263 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11264 			    NULL, MATCH_IRE_DEFAULT);
11265 
11266 			if (ire == NULL) {
11267 				*outlenp = 0;
11268 				return (EHOSTUNREACH);
11269 			}
11270 			ire_refrele(ire);
11271 			return (-EINVAL);
11272 		}
11273 		case IPV6_SEC_OPT:
11274 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11275 			if (error != 0) {
11276 				*outlenp = 0;
11277 				return (error);
11278 			}
11279 			break;
11280 		case IPV6_SRC_PREFERENCES: {
11281 			/*
11282 			 * This is implemented strictly in the ip module
11283 			 * (here and in tcp_opt_*() to accomodate tcp
11284 			 * sockets).  Modules above ip pass this option
11285 			 * down here since ip is the only one that needs to
11286 			 * be aware of source address preferences.
11287 			 *
11288 			 * This socket option only affects connected
11289 			 * sockets that haven't already bound to a specific
11290 			 * IPv6 address.  In other words, sockets that
11291 			 * don't call bind() with an address other than the
11292 			 * unspecified address and that call connect().
11293 			 * ip_bind_connected_v6() passes these preferences
11294 			 * to the ipif_select_source_v6() function.
11295 			 */
11296 			if (inlen != sizeof (uint32_t))
11297 				return (EINVAL);
11298 			error = ip6_set_src_preferences(connp,
11299 			    *(uint32_t *)invalp);
11300 			if (error != 0) {
11301 				*outlenp = 0;
11302 				return (error);
11303 			} else {
11304 				*outlenp = sizeof (uint32_t);
11305 			}
11306 			break;
11307 		}
11308 		case IPV6_V6ONLY:
11309 			if (*i1 < 0 || *i1 > 1) {
11310 				return (EINVAL);
11311 			}
11312 			mutex_enter(&connp->conn_lock);
11313 			connp->conn_ipv6_v6only = *i1;
11314 			mutex_exit(&connp->conn_lock);
11315 			break;
11316 		default:
11317 			return (-EINVAL);
11318 		}
11319 		break;
11320 	default:
11321 		/*
11322 		 * "soft" error (negative)
11323 		 * option not handled at this level
11324 		 * Note: Do not modify *outlenp
11325 		 */
11326 		return (-EINVAL);
11327 	}
11328 	/*
11329 	 * Common case of return from an option that is sizeof (int)
11330 	 */
11331 	*(int *)outvalp = *i1;
11332 	*outlenp = sizeof (int);
11333 	return (0);
11334 }
11335 
11336 /*
11337  * This routine gets default values of certain options whose default
11338  * values are maintained by protocol specific code
11339  */
11340 /* ARGSUSED */
11341 int
11342 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11343 {
11344 	int *i1 = (int *)ptr;
11345 
11346 	switch (level) {
11347 	case IPPROTO_IP:
11348 		switch (name) {
11349 		case IP_MULTICAST_TTL:
11350 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11351 			return (sizeof (uchar_t));
11352 		case IP_MULTICAST_LOOP:
11353 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11354 			return (sizeof (uchar_t));
11355 		default:
11356 			return (-1);
11357 		}
11358 	case IPPROTO_IPV6:
11359 		switch (name) {
11360 		case IPV6_UNICAST_HOPS:
11361 			*i1 = ipv6_def_hops;
11362 			return (sizeof (int));
11363 		case IPV6_MULTICAST_HOPS:
11364 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11365 			return (sizeof (int));
11366 		case IPV6_MULTICAST_LOOP:
11367 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11368 			return (sizeof (int));
11369 		case IPV6_V6ONLY:
11370 			*i1 = 1;
11371 			return (sizeof (int));
11372 		default:
11373 			return (-1);
11374 		}
11375 	default:
11376 		return (-1);
11377 	}
11378 	/* NOTREACHED */
11379 }
11380 
11381 /*
11382  * Given a destination address and a pointer to where to put the information
11383  * this routine fills in the mtuinfo.
11384  */
11385 int
11386 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11387     struct ip6_mtuinfo *mtuinfo)
11388 {
11389 	ire_t *ire;
11390 
11391 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11392 		return (-1);
11393 
11394 	bzero(mtuinfo, sizeof (*mtuinfo));
11395 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11396 	mtuinfo->ip6m_addr.sin6_port = port;
11397 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11398 
11399 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11400 	if (ire != NULL) {
11401 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11402 		ire_refrele(ire);
11403 	} else {
11404 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11405 	}
11406 	return (sizeof (struct ip6_mtuinfo));
11407 }
11408 
11409 /*
11410  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11411  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11412  * isn't.  This doesn't matter as the error checking is done properly for the
11413  * other MRT options coming in through ip_opt_set.
11414  */
11415 int
11416 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11417 {
11418 	conn_t		*connp = Q_TO_CONN(q);
11419 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11420 
11421 	switch (level) {
11422 	case IPPROTO_IP:
11423 		switch (name) {
11424 		case MRT_VERSION:
11425 		case MRT_ASSERT:
11426 			(void) ip_mrouter_get(name, q, ptr);
11427 			return (sizeof (int));
11428 		case IP_SEC_OPT:
11429 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11430 		case IP_NEXTHOP:
11431 			if (connp->conn_nexthop_set) {
11432 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11433 				return (sizeof (ipaddr_t));
11434 			} else
11435 				return (0);
11436 		default:
11437 			break;
11438 		}
11439 		break;
11440 	case IPPROTO_IPV6:
11441 		switch (name) {
11442 		case IPV6_SEC_OPT:
11443 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11444 		case IPV6_SRC_PREFERENCES: {
11445 			return (ip6_get_src_preferences(connp,
11446 			    (uint32_t *)ptr));
11447 		}
11448 		case IPV6_V6ONLY:
11449 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11450 			return (sizeof (int));
11451 		case IPV6_PATHMTU:
11452 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11453 				(struct ip6_mtuinfo *)ptr));
11454 		default:
11455 			break;
11456 		}
11457 		break;
11458 	default:
11459 		break;
11460 	}
11461 	return (-1);
11462 }
11463 
11464 /* Named Dispatch routine to get a current value out of our parameter table. */
11465 /* ARGSUSED */
11466 static int
11467 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11468 {
11469 	ipparam_t *ippa = (ipparam_t *)cp;
11470 
11471 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11472 	return (0);
11473 }
11474 
11475 /* ARGSUSED */
11476 static int
11477 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11478 {
11479 
11480 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11481 	return (0);
11482 }
11483 
11484 /*
11485  * Set ip{,6}_forwarding values.  This means walking through all of the
11486  * ill's and toggling their forwarding values.
11487  */
11488 /* ARGSUSED */
11489 static int
11490 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11491 {
11492 	long new_value;
11493 	int *forwarding_value = (int *)cp;
11494 	ill_t *walker;
11495 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11496 	ill_walk_context_t ctx;
11497 
11498 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11499 	    new_value < 0 || new_value > 1) {
11500 		return (EINVAL);
11501 	}
11502 
11503 	*forwarding_value = new_value;
11504 
11505 	/*
11506 	 * Regardless of the current value of ip_forwarding, set all per-ill
11507 	 * values of ip_forwarding to the value being set.
11508 	 *
11509 	 * Bring all the ill's up to date with the new global value.
11510 	 */
11511 	rw_enter(&ill_g_lock, RW_READER);
11512 
11513 	if (isv6)
11514 		walker = ILL_START_WALK_V6(&ctx);
11515 	else
11516 		walker = ILL_START_WALK_V4(&ctx);
11517 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11518 		(void) ill_forward_set(q, mp, (new_value != 0),
11519 		    (caddr_t)walker);
11520 	}
11521 	rw_exit(&ill_g_lock);
11522 
11523 	return (0);
11524 }
11525 
11526 /*
11527  * Walk through the param array specified registering each element with the
11528  * Named Dispatch handler. This is called only during init. So it is ok
11529  * not to acquire any locks
11530  */
11531 static boolean_t
11532 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11533     ipndp_t *ipnd, size_t ipnd_cnt)
11534 {
11535 	for (; ippa_cnt-- > 0; ippa++) {
11536 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11537 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11538 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11539 				nd_free(&ip_g_nd);
11540 				return (B_FALSE);
11541 			}
11542 		}
11543 	}
11544 
11545 	for (; ipnd_cnt-- > 0; ipnd++) {
11546 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11547 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11548 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11549 			    ipnd->ip_ndp_data)) {
11550 				nd_free(&ip_g_nd);
11551 				return (B_FALSE);
11552 			}
11553 		}
11554 	}
11555 
11556 	return (B_TRUE);
11557 }
11558 
11559 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11560 /* ARGSUSED */
11561 static int
11562 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11563 {
11564 	long		new_value;
11565 	ipparam_t	*ippa = (ipparam_t *)cp;
11566 
11567 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11568 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11569 		return (EINVAL);
11570 	}
11571 	ippa->ip_param_value = new_value;
11572 	return (0);
11573 }
11574 
11575 /*
11576  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11577  * When an ipf is passed here for the first time, if
11578  * we already have in-order fragments on the queue, we convert from the fast-
11579  * path reassembly scheme to the hard-case scheme.  From then on, additional
11580  * fragments are reassembled here.  We keep track of the start and end offsets
11581  * of each piece, and the number of holes in the chain.  When the hole count
11582  * goes to zero, we are done!
11583  *
11584  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11585  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11586  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11587  * after the call to ip_reassemble().
11588  */
11589 int
11590 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11591     size_t msg_len)
11592 {
11593 	uint_t	end;
11594 	mblk_t	*next_mp;
11595 	mblk_t	*mp1;
11596 	uint_t	offset;
11597 	boolean_t incr_dups = B_TRUE;
11598 	boolean_t offset_zero_seen = B_FALSE;
11599 	boolean_t pkt_boundary_checked = B_FALSE;
11600 
11601 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11602 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11603 
11604 	/* Add in byte count */
11605 	ipf->ipf_count += msg_len;
11606 	if (ipf->ipf_end) {
11607 		/*
11608 		 * We were part way through in-order reassembly, but now there
11609 		 * is a hole.  We walk through messages already queued, and
11610 		 * mark them for hard case reassembly.  We know that up till
11611 		 * now they were in order starting from offset zero.
11612 		 */
11613 		offset = 0;
11614 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11615 			IP_REASS_SET_START(mp1, offset);
11616 			if (offset == 0) {
11617 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11618 				offset = -ipf->ipf_nf_hdr_len;
11619 			}
11620 			offset += mp1->b_wptr - mp1->b_rptr;
11621 			IP_REASS_SET_END(mp1, offset);
11622 		}
11623 		/* One hole at the end. */
11624 		ipf->ipf_hole_cnt = 1;
11625 		/* Brand it as a hard case, forever. */
11626 		ipf->ipf_end = 0;
11627 	}
11628 	/* Walk through all the new pieces. */
11629 	do {
11630 		end = start + (mp->b_wptr - mp->b_rptr);
11631 		/*
11632 		 * If start is 0, decrease 'end' only for the first mblk of
11633 		 * the fragment. Otherwise 'end' can get wrong value in the
11634 		 * second pass of the loop if first mblk is exactly the
11635 		 * size of ipf_nf_hdr_len.
11636 		 */
11637 		if (start == 0 && !offset_zero_seen) {
11638 			/* First segment */
11639 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11640 			end -= ipf->ipf_nf_hdr_len;
11641 			offset_zero_seen = B_TRUE;
11642 		}
11643 		next_mp = mp->b_cont;
11644 		/*
11645 		 * We are checking to see if there is any interesing data
11646 		 * to process.  If there isn't and the mblk isn't the
11647 		 * one which carries the unfragmentable header then we
11648 		 * drop it.  It's possible to have just the unfragmentable
11649 		 * header come through without any data.  That needs to be
11650 		 * saved.
11651 		 *
11652 		 * If the assert at the top of this function holds then the
11653 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11654 		 * is infrequently traveled enough that the test is left in
11655 		 * to protect against future code changes which break that
11656 		 * invariant.
11657 		 */
11658 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11659 			/* Empty.  Blast it. */
11660 			IP_REASS_SET_START(mp, 0);
11661 			IP_REASS_SET_END(mp, 0);
11662 			/*
11663 			 * If the ipf points to the mblk we are about to free,
11664 			 * update ipf to point to the next mblk (or NULL
11665 			 * if none).
11666 			 */
11667 			if (ipf->ipf_mp->b_cont == mp)
11668 				ipf->ipf_mp->b_cont = next_mp;
11669 			freeb(mp);
11670 			continue;
11671 		}
11672 		mp->b_cont = NULL;
11673 		IP_REASS_SET_START(mp, start);
11674 		IP_REASS_SET_END(mp, end);
11675 		if (!ipf->ipf_tail_mp) {
11676 			ipf->ipf_tail_mp = mp;
11677 			ipf->ipf_mp->b_cont = mp;
11678 			if (start == 0 || !more) {
11679 				ipf->ipf_hole_cnt = 1;
11680 				/*
11681 				 * if the first fragment comes in more than one
11682 				 * mblk, this loop will be executed for each
11683 				 * mblk. Need to adjust hole count so exiting
11684 				 * this routine will leave hole count at 1.
11685 				 */
11686 				if (next_mp)
11687 					ipf->ipf_hole_cnt++;
11688 			} else
11689 				ipf->ipf_hole_cnt = 2;
11690 			continue;
11691 		} else if (ipf->ipf_last_frag_seen && !more &&
11692 			    !pkt_boundary_checked) {
11693 			/*
11694 			 * We check datagram boundary only if this fragment
11695 			 * claims to be the last fragment and we have seen a
11696 			 * last fragment in the past too. We do this only
11697 			 * once for a given fragment.
11698 			 *
11699 			 * start cannot be 0 here as fragments with start=0
11700 			 * and MF=0 gets handled as a complete packet. These
11701 			 * fragments should not reach here.
11702 			 */
11703 
11704 			if (start + msgdsize(mp) !=
11705 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11706 				/*
11707 				 * We have two fragments both of which claim
11708 				 * to be the last fragment but gives conflicting
11709 				 * information about the whole datagram size.
11710 				 * Something fishy is going on. Drop the
11711 				 * fragment and free up the reassembly list.
11712 				 */
11713 				return (IP_REASS_FAILED);
11714 			}
11715 
11716 			/*
11717 			 * We shouldn't come to this code block again for this
11718 			 * particular fragment.
11719 			 */
11720 			pkt_boundary_checked = B_TRUE;
11721 		}
11722 
11723 		/* New stuff at or beyond tail? */
11724 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11725 		if (start >= offset) {
11726 			if (ipf->ipf_last_frag_seen) {
11727 				/* current fragment is beyond last fragment */
11728 				return (IP_REASS_FAILED);
11729 			}
11730 			/* Link it on end. */
11731 			ipf->ipf_tail_mp->b_cont = mp;
11732 			ipf->ipf_tail_mp = mp;
11733 			if (more) {
11734 				if (start != offset)
11735 					ipf->ipf_hole_cnt++;
11736 			} else if (start == offset && next_mp == NULL)
11737 					ipf->ipf_hole_cnt--;
11738 			continue;
11739 		}
11740 		mp1 = ipf->ipf_mp->b_cont;
11741 		offset = IP_REASS_START(mp1);
11742 		/* New stuff at the front? */
11743 		if (start < offset) {
11744 			if (start == 0) {
11745 				if (end >= offset) {
11746 					/* Nailed the hole at the begining. */
11747 					ipf->ipf_hole_cnt--;
11748 				}
11749 			} else if (end < offset) {
11750 				/*
11751 				 * A hole, stuff, and a hole where there used
11752 				 * to be just a hole.
11753 				 */
11754 				ipf->ipf_hole_cnt++;
11755 			}
11756 			mp->b_cont = mp1;
11757 			/* Check for overlap. */
11758 			while (end > offset) {
11759 				if (end < IP_REASS_END(mp1)) {
11760 					mp->b_wptr -= end - offset;
11761 					IP_REASS_SET_END(mp, offset);
11762 					if (ill->ill_isv6) {
11763 						BUMP_MIB(ill->ill_ip6_mib,
11764 						    ipv6ReasmPartDups);
11765 					} else {
11766 						BUMP_MIB(&ip_mib,
11767 						    ipReasmPartDups);
11768 					}
11769 					break;
11770 				}
11771 				/* Did we cover another hole? */
11772 				if ((mp1->b_cont &&
11773 				    IP_REASS_END(mp1) !=
11774 				    IP_REASS_START(mp1->b_cont) &&
11775 				    end >= IP_REASS_START(mp1->b_cont)) ||
11776 				    (!ipf->ipf_last_frag_seen && !more)) {
11777 					ipf->ipf_hole_cnt--;
11778 				}
11779 				/* Clip out mp1. */
11780 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11781 					/*
11782 					 * After clipping out mp1, this guy
11783 					 * is now hanging off the end.
11784 					 */
11785 					ipf->ipf_tail_mp = mp;
11786 				}
11787 				IP_REASS_SET_START(mp1, 0);
11788 				IP_REASS_SET_END(mp1, 0);
11789 				/* Subtract byte count */
11790 				ipf->ipf_count -= mp1->b_datap->db_lim -
11791 				    mp1->b_datap->db_base;
11792 				freeb(mp1);
11793 				if (ill->ill_isv6) {
11794 					BUMP_MIB(ill->ill_ip6_mib,
11795 					    ipv6ReasmPartDups);
11796 				} else {
11797 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11798 				}
11799 				mp1 = mp->b_cont;
11800 				if (!mp1)
11801 					break;
11802 				offset = IP_REASS_START(mp1);
11803 			}
11804 			ipf->ipf_mp->b_cont = mp;
11805 			continue;
11806 		}
11807 		/*
11808 		 * The new piece starts somewhere between the start of the head
11809 		 * and before the end of the tail.
11810 		 */
11811 		for (; mp1; mp1 = mp1->b_cont) {
11812 			offset = IP_REASS_END(mp1);
11813 			if (start < offset) {
11814 				if (end <= offset) {
11815 					/* Nothing new. */
11816 					IP_REASS_SET_START(mp, 0);
11817 					IP_REASS_SET_END(mp, 0);
11818 					/* Subtract byte count */
11819 					ipf->ipf_count -= mp->b_datap->db_lim -
11820 					    mp->b_datap->db_base;
11821 					if (incr_dups) {
11822 						ipf->ipf_num_dups++;
11823 						incr_dups = B_FALSE;
11824 					}
11825 					freeb(mp);
11826 					if (ill->ill_isv6) {
11827 						BUMP_MIB(ill->ill_ip6_mib,
11828 						    ipv6ReasmDuplicates);
11829 					} else {
11830 						BUMP_MIB(&ip_mib,
11831 						    ipReasmDuplicates);
11832 					}
11833 					break;
11834 				}
11835 				/*
11836 				 * Trim redundant stuff off beginning of new
11837 				 * piece.
11838 				 */
11839 				IP_REASS_SET_START(mp, offset);
11840 				mp->b_rptr += offset - start;
11841 				if (ill->ill_isv6) {
11842 					BUMP_MIB(ill->ill_ip6_mib,
11843 					    ipv6ReasmPartDups);
11844 				} else {
11845 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11846 				}
11847 				start = offset;
11848 				if (!mp1->b_cont) {
11849 					/*
11850 					 * After trimming, this guy is now
11851 					 * hanging off the end.
11852 					 */
11853 					mp1->b_cont = mp;
11854 					ipf->ipf_tail_mp = mp;
11855 					if (!more) {
11856 						ipf->ipf_hole_cnt--;
11857 					}
11858 					break;
11859 				}
11860 			}
11861 			if (start >= IP_REASS_START(mp1->b_cont))
11862 				continue;
11863 			/* Fill a hole */
11864 			if (start > offset)
11865 				ipf->ipf_hole_cnt++;
11866 			mp->b_cont = mp1->b_cont;
11867 			mp1->b_cont = mp;
11868 			mp1 = mp->b_cont;
11869 			offset = IP_REASS_START(mp1);
11870 			if (end >= offset) {
11871 				ipf->ipf_hole_cnt--;
11872 				/* Check for overlap. */
11873 				while (end > offset) {
11874 					if (end < IP_REASS_END(mp1)) {
11875 						mp->b_wptr -= end - offset;
11876 						IP_REASS_SET_END(mp, offset);
11877 						/*
11878 						 * TODO we might bump
11879 						 * this up twice if there is
11880 						 * overlap at both ends.
11881 						 */
11882 						if (ill->ill_isv6) {
11883 							BUMP_MIB(
11884 							    ill->ill_ip6_mib,
11885 							    ipv6ReasmPartDups);
11886 						} else {
11887 							BUMP_MIB(&ip_mib,
11888 							    ipReasmPartDups);
11889 						}
11890 						break;
11891 					}
11892 					/* Did we cover another hole? */
11893 					if ((mp1->b_cont &&
11894 					    IP_REASS_END(mp1)
11895 					    != IP_REASS_START(mp1->b_cont) &&
11896 					    end >=
11897 					    IP_REASS_START(mp1->b_cont)) ||
11898 					    (!ipf->ipf_last_frag_seen &&
11899 					    !more)) {
11900 						ipf->ipf_hole_cnt--;
11901 					}
11902 					/* Clip out mp1. */
11903 					if ((mp->b_cont = mp1->b_cont) ==
11904 					    NULL) {
11905 						/*
11906 						 * After clipping out mp1,
11907 						 * this guy is now hanging
11908 						 * off the end.
11909 						 */
11910 						ipf->ipf_tail_mp = mp;
11911 					}
11912 					IP_REASS_SET_START(mp1, 0);
11913 					IP_REASS_SET_END(mp1, 0);
11914 					/* Subtract byte count */
11915 					ipf->ipf_count -=
11916 					    mp1->b_datap->db_lim -
11917 					    mp1->b_datap->db_base;
11918 					freeb(mp1);
11919 					if (ill->ill_isv6) {
11920 						BUMP_MIB(ill->ill_ip6_mib,
11921 						    ipv6ReasmPartDups);
11922 					} else {
11923 						BUMP_MIB(&ip_mib,
11924 						    ipReasmPartDups);
11925 					}
11926 					mp1 = mp->b_cont;
11927 					if (!mp1)
11928 						break;
11929 					offset = IP_REASS_START(mp1);
11930 				}
11931 			}
11932 			break;
11933 		}
11934 	} while (start = end, mp = next_mp);
11935 
11936 	/* Fragment just processed could be the last one. Remember this fact */
11937 	if (!more)
11938 		ipf->ipf_last_frag_seen = B_TRUE;
11939 
11940 	/* Still got holes? */
11941 	if (ipf->ipf_hole_cnt)
11942 		return (IP_REASS_PARTIAL);
11943 	/* Clean up overloaded fields to avoid upstream disasters. */
11944 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11945 		IP_REASS_SET_START(mp1, 0);
11946 		IP_REASS_SET_END(mp1, 0);
11947 	}
11948 	return (IP_REASS_COMPLETE);
11949 }
11950 
11951 /*
11952  * ipsec processing for the fast path, used for input UDP Packets
11953  */
11954 static boolean_t
11955 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11956     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11957 {
11958 	uint32_t	ill_index;
11959 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11960 
11961 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11962 	/* The ill_index of the incoming ILL */
11963 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11964 
11965 	/* pass packet up to the transport */
11966 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11967 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11968 		    NULL, mctl_present);
11969 		if (*first_mpp == NULL) {
11970 			return (B_FALSE);
11971 		}
11972 	}
11973 
11974 	/* Initiate IPPF processing for fastpath UDP */
11975 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11976 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11977 		if (*mpp == NULL) {
11978 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11979 			    "deferred/dropped during IPPF processing\n"));
11980 			return (B_FALSE);
11981 		}
11982 	}
11983 	/*
11984 	 * We make the checks as below since we are in the fast path
11985 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11986 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11987 	 */
11988 	if (connp->conn_recvif || connp->conn_recvslla ||
11989 	    connp->conn_ipv6_recvpktinfo) {
11990 		if (connp->conn_recvif ||
11991 		    connp->conn_ipv6_recvpktinfo) {
11992 			in_flags = IPF_RECVIF;
11993 		}
11994 		if (connp->conn_recvslla) {
11995 			in_flags |= IPF_RECVSLLA;
11996 		}
11997 		/*
11998 		 * since in_flags are being set ill will be
11999 		 * referenced in ip_add_info, so it better not
12000 		 * be NULL.
12001 		 */
12002 		/*
12003 		 * the actual data will be contained in b_cont
12004 		 * upon successful return of the following call.
12005 		 * If the call fails then the original mblk is
12006 		 * returned.
12007 		 */
12008 		*mpp = ip_add_info(*mpp, ill, in_flags);
12009 	}
12010 
12011 	return (B_TRUE);
12012 }
12013 
12014 /*
12015  * Fragmentation reassembly.  Each ILL has a hash table for
12016  * queuing packets undergoing reassembly for all IPIFs
12017  * associated with the ILL.  The hash is based on the packet
12018  * IP ident field.  The ILL frag hash table was allocated
12019  * as a timer block at the time the ILL was created.  Whenever
12020  * there is anything on the reassembly queue, the timer will
12021  * be running.  Returns B_TRUE if successful else B_FALSE;
12022  * frees mp on failure.
12023  */
12024 static boolean_t
12025 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12026     uint32_t *cksum_val, uint16_t *cksum_flags)
12027 {
12028 	uint32_t	frag_offset_flags;
12029 	ill_t		*ill = (ill_t *)q->q_ptr;
12030 	mblk_t		*mp = *mpp;
12031 	mblk_t		*t_mp;
12032 	ipaddr_t	dst;
12033 	uint8_t		proto = ipha->ipha_protocol;
12034 	uint32_t	sum_val;
12035 	uint16_t	sum_flags;
12036 	ipf_t		*ipf;
12037 	ipf_t		**ipfp;
12038 	ipfb_t		*ipfb;
12039 	uint16_t	ident;
12040 	uint32_t	offset;
12041 	ipaddr_t	src;
12042 	uint_t		hdr_length;
12043 	uint32_t	end;
12044 	mblk_t		*mp1;
12045 	mblk_t		*tail_mp;
12046 	size_t		count;
12047 	size_t		msg_len;
12048 	uint8_t		ecn_info = 0;
12049 	uint32_t	packet_size;
12050 	boolean_t	pruned = B_FALSE;
12051 
12052 	if (cksum_val != NULL)
12053 		*cksum_val = 0;
12054 	if (cksum_flags != NULL)
12055 		*cksum_flags = 0;
12056 
12057 	/*
12058 	 * Drop the fragmented as early as possible, if
12059 	 * we don't have resource(s) to re-assemble.
12060 	 */
12061 	if (ip_reass_queue_bytes == 0) {
12062 		freemsg(mp);
12063 		return (B_FALSE);
12064 	}
12065 
12066 	/* Check for fragmentation offset; return if there's none */
12067 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12068 	    (IPH_MF | IPH_OFFSET)) == 0)
12069 		return (B_TRUE);
12070 
12071 	/*
12072 	 * We utilize hardware computed checksum info only for UDP since
12073 	 * IP fragmentation is a normal occurence for the protocol.  In
12074 	 * addition, checksum offload support for IP fragments carrying
12075 	 * UDP payload is commonly implemented across network adapters.
12076 	 */
12077 	ASSERT(ill != NULL);
12078 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12079 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12080 		mblk_t *mp1 = mp->b_cont;
12081 		int32_t len;
12082 
12083 		/* Record checksum information from the packet */
12084 		sum_val = (uint32_t)DB_CKSUM16(mp);
12085 		sum_flags = DB_CKSUMFLAGS(mp);
12086 
12087 		/* IP payload offset from beginning of mblk */
12088 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12089 
12090 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12091 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12092 		    offset >= DB_CKSUMSTART(mp) &&
12093 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12094 			uint32_t adj;
12095 			/*
12096 			 * Partial checksum has been calculated by hardware
12097 			 * and attached to the packet; in addition, any
12098 			 * prepended extraneous data is even byte aligned.
12099 			 * If any such data exists, we adjust the checksum;
12100 			 * this would also handle any postpended data.
12101 			 */
12102 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12103 			    mp, mp1, len, adj);
12104 
12105 			/* One's complement subtract extraneous checksum */
12106 			if (adj >= sum_val)
12107 				sum_val = ~(adj - sum_val) & 0xFFFF;
12108 			else
12109 				sum_val -= adj;
12110 		}
12111 	} else {
12112 		sum_val = 0;
12113 		sum_flags = 0;
12114 	}
12115 
12116 	/* Clear hardware checksumming flag */
12117 	DB_CKSUMFLAGS(mp) = 0;
12118 
12119 	ident = ipha->ipha_ident;
12120 	offset = (frag_offset_flags << 3) & 0xFFFF;
12121 	src = ipha->ipha_src;
12122 	dst = ipha->ipha_dst;
12123 	hdr_length = IPH_HDR_LENGTH(ipha);
12124 	end = ntohs(ipha->ipha_length) - hdr_length;
12125 
12126 	/* If end == 0 then we have a packet with no data, so just free it */
12127 	if (end == 0) {
12128 		freemsg(mp);
12129 		return (B_FALSE);
12130 	}
12131 
12132 	/* Record the ECN field info. */
12133 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12134 	if (offset != 0) {
12135 		/*
12136 		 * If this isn't the first piece, strip the header, and
12137 		 * add the offset to the end value.
12138 		 */
12139 		mp->b_rptr += hdr_length;
12140 		end += offset;
12141 	}
12142 
12143 	msg_len = MBLKSIZE(mp);
12144 	tail_mp = mp;
12145 	while (tail_mp->b_cont != NULL) {
12146 		tail_mp = tail_mp->b_cont;
12147 		msg_len += MBLKSIZE(tail_mp);
12148 	}
12149 
12150 	/* If the reassembly list for this ILL will get too big, prune it */
12151 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12152 	    ip_reass_queue_bytes) {
12153 		ill_frag_prune(ill,
12154 		    (ip_reass_queue_bytes < msg_len) ? 0 :
12155 		    (ip_reass_queue_bytes - msg_len));
12156 		pruned = B_TRUE;
12157 	}
12158 
12159 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12160 	mutex_enter(&ipfb->ipfb_lock);
12161 
12162 	ipfp = &ipfb->ipfb_ipf;
12163 	/* Try to find an existing fragment queue for this packet. */
12164 	for (;;) {
12165 		ipf = ipfp[0];
12166 		if (ipf != NULL) {
12167 			/*
12168 			 * It has to match on ident and src/dst address.
12169 			 */
12170 			if (ipf->ipf_ident == ident &&
12171 			    ipf->ipf_src == src &&
12172 			    ipf->ipf_dst == dst &&
12173 			    ipf->ipf_protocol == proto) {
12174 				/*
12175 				 * If we have received too many
12176 				 * duplicate fragments for this packet
12177 				 * free it.
12178 				 */
12179 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12180 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12181 					freemsg(mp);
12182 					mutex_exit(&ipfb->ipfb_lock);
12183 					return (B_FALSE);
12184 				}
12185 				/* Found it. */
12186 				break;
12187 			}
12188 			ipfp = &ipf->ipf_hash_next;
12189 			continue;
12190 		}
12191 
12192 		/*
12193 		 * If we pruned the list, do we want to store this new
12194 		 * fragment?. We apply an optimization here based on the
12195 		 * fact that most fragments will be received in order.
12196 		 * So if the offset of this incoming fragment is zero,
12197 		 * it is the first fragment of a new packet. We will
12198 		 * keep it.  Otherwise drop the fragment, as we have
12199 		 * probably pruned the packet already (since the
12200 		 * packet cannot be found).
12201 		 */
12202 		if (pruned && offset != 0) {
12203 			mutex_exit(&ipfb->ipfb_lock);
12204 			freemsg(mp);
12205 			return (B_FALSE);
12206 		}
12207 
12208 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12209 			/*
12210 			 * Too many fragmented packets in this hash
12211 			 * bucket. Free the oldest.
12212 			 */
12213 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12214 		}
12215 
12216 		/* New guy.  Allocate a frag message. */
12217 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12218 		if (mp1 == NULL) {
12219 			BUMP_MIB(&ip_mib, ipInDiscards);
12220 			freemsg(mp);
12221 reass_done:
12222 			mutex_exit(&ipfb->ipfb_lock);
12223 			return (B_FALSE);
12224 		}
12225 
12226 
12227 		BUMP_MIB(&ip_mib, ipReasmReqds);
12228 		mp1->b_cont = mp;
12229 
12230 		/* Initialize the fragment header. */
12231 		ipf = (ipf_t *)mp1->b_rptr;
12232 		ipf->ipf_mp = mp1;
12233 		ipf->ipf_ptphn = ipfp;
12234 		ipfp[0] = ipf;
12235 		ipf->ipf_hash_next = NULL;
12236 		ipf->ipf_ident = ident;
12237 		ipf->ipf_protocol = proto;
12238 		ipf->ipf_src = src;
12239 		ipf->ipf_dst = dst;
12240 		ipf->ipf_nf_hdr_len = 0;
12241 		/* Record reassembly start time. */
12242 		ipf->ipf_timestamp = gethrestime_sec();
12243 		/* Record ipf generation and account for frag header */
12244 		ipf->ipf_gen = ill->ill_ipf_gen++;
12245 		ipf->ipf_count = MBLKSIZE(mp1);
12246 		ipf->ipf_last_frag_seen = B_FALSE;
12247 		ipf->ipf_ecn = ecn_info;
12248 		ipf->ipf_num_dups = 0;
12249 		ipfb->ipfb_frag_pkts++;
12250 		ipf->ipf_checksum = 0;
12251 		ipf->ipf_checksum_flags = 0;
12252 
12253 		/* Store checksum value in fragment header */
12254 		if (sum_flags != 0) {
12255 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12256 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12257 			ipf->ipf_checksum = sum_val;
12258 			ipf->ipf_checksum_flags = sum_flags;
12259 		}
12260 
12261 		/*
12262 		 * We handle reassembly two ways.  In the easy case,
12263 		 * where all the fragments show up in order, we do
12264 		 * minimal bookkeeping, and just clip new pieces on
12265 		 * the end.  If we ever see a hole, then we go off
12266 		 * to ip_reassemble which has to mark the pieces and
12267 		 * keep track of the number of holes, etc.  Obviously,
12268 		 * the point of having both mechanisms is so we can
12269 		 * handle the easy case as efficiently as possible.
12270 		 */
12271 		if (offset == 0) {
12272 			/* Easy case, in-order reassembly so far. */
12273 			ipf->ipf_count += msg_len;
12274 			ipf->ipf_tail_mp = tail_mp;
12275 			/*
12276 			 * Keep track of next expected offset in
12277 			 * ipf_end.
12278 			 */
12279 			ipf->ipf_end = end;
12280 			ipf->ipf_nf_hdr_len = hdr_length;
12281 		} else {
12282 			/* Hard case, hole at the beginning. */
12283 			ipf->ipf_tail_mp = NULL;
12284 			/*
12285 			 * ipf_end == 0 means that we have given up
12286 			 * on easy reassembly.
12287 			 */
12288 			ipf->ipf_end = 0;
12289 
12290 			/* Forget checksum offload from now on */
12291 			ipf->ipf_checksum_flags = 0;
12292 
12293 			/*
12294 			 * ipf_hole_cnt is set by ip_reassemble.
12295 			 * ipf_count is updated by ip_reassemble.
12296 			 * No need to check for return value here
12297 			 * as we don't expect reassembly to complete
12298 			 * or fail for the first fragment itself.
12299 			 */
12300 			(void) ip_reassemble(mp, ipf,
12301 			    (frag_offset_flags & IPH_OFFSET) << 3,
12302 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12303 		}
12304 		/* Update per ipfb and ill byte counts */
12305 		ipfb->ipfb_count += ipf->ipf_count;
12306 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12307 		ill->ill_frag_count += ipf->ipf_count;
12308 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12309 		/* If the frag timer wasn't already going, start it. */
12310 		mutex_enter(&ill->ill_lock);
12311 		ill_frag_timer_start(ill);
12312 		mutex_exit(&ill->ill_lock);
12313 		goto reass_done;
12314 	}
12315 
12316 	/*
12317 	 * If the packet's flag has changed (it could be coming up
12318 	 * from an interface different than the previous, therefore
12319 	 * possibly different checksum capability), then forget about
12320 	 * any stored checksum states.  Otherwise add the value to
12321 	 * the existing one stored in the fragment header.
12322 	 */
12323 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12324 		sum_val += ipf->ipf_checksum;
12325 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12326 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12327 		ipf->ipf_checksum = sum_val;
12328 	} else if (ipf->ipf_checksum_flags != 0) {
12329 		/* Forget checksum offload from now on */
12330 		ipf->ipf_checksum_flags = 0;
12331 	}
12332 
12333 	/*
12334 	 * We have a new piece of a datagram which is already being
12335 	 * reassembled.  Update the ECN info if all IP fragments
12336 	 * are ECN capable.  If there is one which is not, clear
12337 	 * all the info.  If there is at least one which has CE
12338 	 * code point, IP needs to report that up to transport.
12339 	 */
12340 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12341 		if (ecn_info == IPH_ECN_CE)
12342 			ipf->ipf_ecn = IPH_ECN_CE;
12343 	} else {
12344 		ipf->ipf_ecn = IPH_ECN_NECT;
12345 	}
12346 	if (offset && ipf->ipf_end == offset) {
12347 		/* The new fragment fits at the end */
12348 		ipf->ipf_tail_mp->b_cont = mp;
12349 		/* Update the byte count */
12350 		ipf->ipf_count += msg_len;
12351 		/* Update per ipfb and ill byte counts */
12352 		ipfb->ipfb_count += msg_len;
12353 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12354 		ill->ill_frag_count += msg_len;
12355 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12356 		if (frag_offset_flags & IPH_MF) {
12357 			/* More to come. */
12358 			ipf->ipf_end = end;
12359 			ipf->ipf_tail_mp = tail_mp;
12360 			goto reass_done;
12361 		}
12362 	} else {
12363 		/* Go do the hard cases. */
12364 		int ret;
12365 
12366 		if (offset == 0)
12367 			ipf->ipf_nf_hdr_len = hdr_length;
12368 
12369 		/* Save current byte count */
12370 		count = ipf->ipf_count;
12371 		ret = ip_reassemble(mp, ipf,
12372 		    (frag_offset_flags & IPH_OFFSET) << 3,
12373 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12374 		/* Count of bytes added and subtracted (freeb()ed) */
12375 		count = ipf->ipf_count - count;
12376 		if (count) {
12377 			/* Update per ipfb and ill byte counts */
12378 			ipfb->ipfb_count += count;
12379 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12380 			ill->ill_frag_count += count;
12381 			ASSERT(ill->ill_frag_count > 0);
12382 		}
12383 		if (ret == IP_REASS_PARTIAL) {
12384 			goto reass_done;
12385 		} else if (ret == IP_REASS_FAILED) {
12386 			/* Reassembly failed. Free up all resources */
12387 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12388 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12389 				IP_REASS_SET_START(t_mp, 0);
12390 				IP_REASS_SET_END(t_mp, 0);
12391 			}
12392 			freemsg(mp);
12393 			goto reass_done;
12394 		}
12395 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12396 	}
12397 	/*
12398 	 * We have completed reassembly.  Unhook the frag header from
12399 	 * the reassembly list.
12400 	 *
12401 	 * Before we free the frag header, record the ECN info
12402 	 * to report back to the transport.
12403 	 */
12404 	ecn_info = ipf->ipf_ecn;
12405 	BUMP_MIB(&ip_mib, ipReasmOKs);
12406 	ipfp = ipf->ipf_ptphn;
12407 
12408 	/* We need to supply these to caller */
12409 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12410 		sum_val = ipf->ipf_checksum;
12411 	else
12412 		sum_val = 0;
12413 
12414 	mp1 = ipf->ipf_mp;
12415 	count = ipf->ipf_count;
12416 	ipf = ipf->ipf_hash_next;
12417 	if (ipf != NULL)
12418 		ipf->ipf_ptphn = ipfp;
12419 	ipfp[0] = ipf;
12420 	ill->ill_frag_count -= count;
12421 	ASSERT(ipfb->ipfb_count >= count);
12422 	ipfb->ipfb_count -= count;
12423 	ipfb->ipfb_frag_pkts--;
12424 	mutex_exit(&ipfb->ipfb_lock);
12425 	/* Ditch the frag header. */
12426 	mp = mp1->b_cont;
12427 
12428 	freeb(mp1);
12429 
12430 	/* Restore original IP length in header. */
12431 	packet_size = (uint32_t)msgdsize(mp);
12432 	if (packet_size > IP_MAXPACKET) {
12433 		freemsg(mp);
12434 		BUMP_MIB(&ip_mib, ipInHdrErrors);
12435 		return (B_FALSE);
12436 	}
12437 
12438 	if (DB_REF(mp) > 1) {
12439 		mblk_t *mp2 = copymsg(mp);
12440 
12441 		freemsg(mp);
12442 		if (mp2 == NULL) {
12443 			BUMP_MIB(&ip_mib, ipInDiscards);
12444 			return (B_FALSE);
12445 		}
12446 		mp = mp2;
12447 	}
12448 	ipha = (ipha_t *)mp->b_rptr;
12449 
12450 	ipha->ipha_length = htons((uint16_t)packet_size);
12451 	/* We're now complete, zip the frag state */
12452 	ipha->ipha_fragment_offset_and_flags = 0;
12453 	/* Record the ECN info. */
12454 	ipha->ipha_type_of_service &= 0xFC;
12455 	ipha->ipha_type_of_service |= ecn_info;
12456 	*mpp = mp;
12457 
12458 	/* Reassembly is successful; return checksum information if needed */
12459 	if (cksum_val != NULL)
12460 		*cksum_val = sum_val;
12461 	if (cksum_flags != NULL)
12462 		*cksum_flags = sum_flags;
12463 
12464 	return (B_TRUE);
12465 }
12466 
12467 /*
12468  * Perform ip header check sum update local options.
12469  * return B_TRUE if all is well, else return B_FALSE and release
12470  * the mp. caller is responsible for decrementing ire ref cnt.
12471  */
12472 static boolean_t
12473 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12474 {
12475 	mblk_t		*first_mp;
12476 	boolean_t	mctl_present;
12477 	uint16_t	sum;
12478 
12479 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12480 	/*
12481 	 * Don't do the checksum if it has gone through AH/ESP
12482 	 * processing.
12483 	 */
12484 	if (!mctl_present) {
12485 		sum = ip_csum_hdr(ipha);
12486 		if (sum != 0) {
12487 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12488 			freemsg(first_mp);
12489 			return (B_FALSE);
12490 		}
12491 	}
12492 
12493 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12494 		if (mctl_present)
12495 			freeb(first_mp);
12496 		return (B_FALSE);
12497 	}
12498 
12499 	return (B_TRUE);
12500 }
12501 
12502 /*
12503  * All udp packet are delivered to the local host via this routine.
12504  */
12505 void
12506 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12507     ill_t *recv_ill)
12508 {
12509 	uint32_t	sum;
12510 	uint32_t	u1;
12511 	boolean_t	mctl_present;
12512 	conn_t		*connp;
12513 	mblk_t		*first_mp;
12514 	uint16_t	*up;
12515 	ill_t		*ill = (ill_t *)q->q_ptr;
12516 	uint16_t	reass_hck_flags = 0;
12517 
12518 #define	rptr    ((uchar_t *)ipha)
12519 
12520 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12521 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12522 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12523 
12524 	/*
12525 	 * FAST PATH for udp packets
12526 	 */
12527 
12528 	/* u1 is # words of IP options */
12529 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12530 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12531 
12532 	/* IP options present */
12533 	if (u1 != 0)
12534 		goto ipoptions;
12535 
12536 	/* Check the IP header checksum.  */
12537 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12538 		/* Clear the IP header h/w cksum flag */
12539 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12540 	} else {
12541 #define	uph	((uint16_t *)ipha)
12542 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12543 		    uph[6] + uph[7] + uph[8] + uph[9];
12544 #undef	uph
12545 		/* finish doing IP checksum */
12546 		sum = (sum & 0xFFFF) + (sum >> 16);
12547 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12548 		/*
12549 		 * Don't verify header checksum if this packet is coming
12550 		 * back from AH/ESP as we already did it.
12551 		 */
12552 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12553 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12554 			freemsg(first_mp);
12555 			return;
12556 		}
12557 	}
12558 
12559 	/*
12560 	 * Count for SNMP of inbound packets for ire.
12561 	 * if mctl is present this might be a secure packet and
12562 	 * has already been counted for in ip_proto_input().
12563 	 */
12564 	if (!mctl_present) {
12565 		UPDATE_IB_PKT_COUNT(ire);
12566 		ire->ire_last_used_time = lbolt;
12567 	}
12568 
12569 	/* packet part of fragmented IP packet? */
12570 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12571 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12572 		goto fragmented;
12573 	}
12574 
12575 	/* u1 = IP header length (20 bytes) */
12576 	u1 = IP_SIMPLE_HDR_LENGTH;
12577 
12578 	/* packet does not contain complete IP & UDP headers */
12579 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12580 		goto udppullup;
12581 
12582 	/* up points to UDP header */
12583 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12584 #define	iphs    ((uint16_t *)ipha)
12585 
12586 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12587 	if (up[3] != 0) {
12588 		mblk_t *mp1 = mp->b_cont;
12589 		boolean_t cksum_err;
12590 		uint16_t hck_flags = 0;
12591 
12592 		/* Pseudo-header checksum */
12593 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12594 		    iphs[9] + up[2];
12595 
12596 		/*
12597 		 * Revert to software checksum calculation if the interface
12598 		 * isn't capable of checksum offload or if IPsec is present.
12599 		 */
12600 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12601 			hck_flags = DB_CKSUMFLAGS(mp);
12602 
12603 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12604 			IP_STAT(ip_in_sw_cksum);
12605 
12606 		IP_CKSUM_RECV(hck_flags, u1,
12607 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12608 		    (int32_t)((uchar_t *)up - rptr),
12609 		    mp, mp1, cksum_err);
12610 
12611 		if (cksum_err) {
12612 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12613 
12614 			if (hck_flags & HCK_FULLCKSUM)
12615 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12616 			else if (hck_flags & HCK_PARTIALCKSUM)
12617 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12618 			else
12619 				IP_STAT(ip_udp_in_sw_cksum_err);
12620 
12621 			freemsg(first_mp);
12622 			return;
12623 		}
12624 	}
12625 
12626 	/* Non-fragmented broadcast or multicast packet? */
12627 	if (ire->ire_type == IRE_BROADCAST)
12628 		goto udpslowpath;
12629 
12630 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12631 	    ire->ire_zoneid)) != NULL) {
12632 		ASSERT(connp->conn_upq != NULL);
12633 		IP_STAT(ip_udp_fast_path);
12634 
12635 		if (CONN_UDP_FLOWCTLD(connp)) {
12636 			freemsg(mp);
12637 			BUMP_MIB(&ip_mib, udpInOverflows);
12638 		} else {
12639 			if (!mctl_present) {
12640 				BUMP_MIB(&ip_mib, ipInDelivers);
12641 			}
12642 			/*
12643 			 * mp and first_mp can change.
12644 			 */
12645 			if (ip_udp_check(q, connp, recv_ill,
12646 			    ipha, &mp, &first_mp, mctl_present)) {
12647 				/* Send it upstream */
12648 				CONN_UDP_RECV(connp, mp);
12649 			}
12650 		}
12651 		/*
12652 		 * freeb() cannot deal with null mblk being passed
12653 		 * in and first_mp can be set to null in the call
12654 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12655 		 */
12656 		if (mctl_present && first_mp != NULL) {
12657 			freeb(first_mp);
12658 		}
12659 		CONN_DEC_REF(connp);
12660 		return;
12661 	}
12662 
12663 	/*
12664 	 * if we got here we know the packet is not fragmented and
12665 	 * has no options. The classifier could not find a conn_t and
12666 	 * most likely its an icmp packet so send it through slow path.
12667 	 */
12668 
12669 	goto udpslowpath;
12670 
12671 ipoptions:
12672 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12673 		goto slow_done;
12674 	}
12675 
12676 	UPDATE_IB_PKT_COUNT(ire);
12677 	ire->ire_last_used_time = lbolt;
12678 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12679 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12680 fragmented:
12681 		/*
12682 		 * "sum" and "reass_hck_flags" are non-zero if the
12683 		 * reassembled packet has a valid hardware computed
12684 		 * checksum information associated with it.
12685 		 */
12686 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12687 			goto slow_done;
12688 		/*
12689 		 * Make sure that first_mp points back to mp as
12690 		 * the mp we came in with could have changed in
12691 		 * ip_rput_fragment().
12692 		 */
12693 		ASSERT(!mctl_present);
12694 		ipha = (ipha_t *)mp->b_rptr;
12695 		first_mp = mp;
12696 	}
12697 
12698 	/* Now we have a complete datagram, destined for this machine. */
12699 	u1 = IPH_HDR_LENGTH(ipha);
12700 	/* Pull up the UDP header, if necessary. */
12701 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12702 udppullup:
12703 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12704 			BUMP_MIB(&ip_mib, ipInDiscards);
12705 			freemsg(first_mp);
12706 			goto slow_done;
12707 		}
12708 		ipha = (ipha_t *)mp->b_rptr;
12709 	}
12710 
12711 	/*
12712 	 * Validate the checksum for the reassembled packet; for the
12713 	 * pullup case we calculate the payload checksum in software.
12714 	 */
12715 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12716 	if (up[3] != 0) {
12717 		boolean_t cksum_err;
12718 
12719 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12720 			IP_STAT(ip_in_sw_cksum);
12721 
12722 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12723 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12724 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12725 		    iphs[9] + up[2], sum, cksum_err);
12726 
12727 		if (cksum_err) {
12728 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12729 
12730 			if (reass_hck_flags & HCK_FULLCKSUM)
12731 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12732 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12733 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12734 			else
12735 				IP_STAT(ip_udp_in_sw_cksum_err);
12736 
12737 			freemsg(first_mp);
12738 			goto slow_done;
12739 		}
12740 	}
12741 udpslowpath:
12742 
12743 	/* Clear hardware checksum flag to be safe */
12744 	DB_CKSUMFLAGS(mp) = 0;
12745 
12746 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12747 	    (ire->ire_type == IRE_BROADCAST),
12748 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12749 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12750 
12751 slow_done:
12752 	IP_STAT(ip_udp_slow_path);
12753 	return;
12754 
12755 #undef  iphs
12756 #undef  rptr
12757 }
12758 
12759 /* ARGSUSED */
12760 static mblk_t *
12761 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12762     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12763     ill_rx_ring_t *ill_ring)
12764 {
12765 	conn_t		*connp;
12766 	uint32_t	sum;
12767 	uint32_t	u1;
12768 	uint16_t	*up;
12769 	int		offset;
12770 	ssize_t		len;
12771 	mblk_t		*mp1;
12772 	boolean_t	syn_present = B_FALSE;
12773 	tcph_t		*tcph;
12774 	uint_t		ip_hdr_len;
12775 	ill_t		*ill = (ill_t *)q->q_ptr;
12776 	zoneid_t	zoneid = ire->ire_zoneid;
12777 	boolean_t	cksum_err;
12778 	uint16_t	hck_flags = 0;
12779 
12780 #define	rptr	((uchar_t *)ipha)
12781 
12782 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12783 
12784 	/*
12785 	 * FAST PATH for tcp packets
12786 	 */
12787 
12788 	/* u1 is # words of IP options */
12789 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12790 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12791 
12792 	/* IP options present */
12793 	if (u1) {
12794 		goto ipoptions;
12795 	} else {
12796 		/* Check the IP header checksum.  */
12797 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12798 			/* Clear the IP header h/w cksum flag */
12799 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12800 		} else {
12801 #define	uph	((uint16_t *)ipha)
12802 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12803 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12804 #undef	uph
12805 			/* finish doing IP checksum */
12806 			sum = (sum & 0xFFFF) + (sum >> 16);
12807 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12808 			/*
12809 			 * Don't verify header checksum if this packet
12810 			 * is coming back from AH/ESP as we already did it.
12811 			 */
12812 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12813 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12814 				goto error;
12815 			}
12816 		}
12817 	}
12818 
12819 	if (!mctl_present) {
12820 		UPDATE_IB_PKT_COUNT(ire);
12821 		ire->ire_last_used_time = lbolt;
12822 	}
12823 
12824 	/* packet part of fragmented IP packet? */
12825 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12826 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12827 		goto fragmented;
12828 	}
12829 
12830 	/* u1 = IP header length (20 bytes) */
12831 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12832 
12833 	/* does packet contain IP+TCP headers? */
12834 	len = mp->b_wptr - rptr;
12835 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12836 		IP_STAT(ip_tcppullup);
12837 		goto tcppullup;
12838 	}
12839 
12840 	/* TCP options present? */
12841 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12842 
12843 	/*
12844 	 * If options need to be pulled up, then goto tcpoptions.
12845 	 * otherwise we are still in the fast path
12846 	 */
12847 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12848 		IP_STAT(ip_tcpoptions);
12849 		goto tcpoptions;
12850 	}
12851 
12852 	/* multiple mblks of tcp data? */
12853 	if ((mp1 = mp->b_cont) != NULL) {
12854 		/* more then two? */
12855 		if (mp1->b_cont != NULL) {
12856 			IP_STAT(ip_multipkttcp);
12857 			goto multipkttcp;
12858 		}
12859 		len += mp1->b_wptr - mp1->b_rptr;
12860 	}
12861 
12862 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12863 
12864 	/* part of pseudo checksum */
12865 
12866 	/* TCP datagram length */
12867 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12868 
12869 #define	iphs    ((uint16_t *)ipha)
12870 
12871 #ifdef	_BIG_ENDIAN
12872 	u1 += IPPROTO_TCP;
12873 #else
12874 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12875 #endif
12876 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12877 
12878 	/*
12879 	 * Revert to software checksum calculation if the interface
12880 	 * isn't capable of checksum offload or if IPsec is present.
12881 	 */
12882 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12883 		hck_flags = DB_CKSUMFLAGS(mp);
12884 
12885 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12886 		IP_STAT(ip_in_sw_cksum);
12887 
12888 	IP_CKSUM_RECV(hck_flags, u1,
12889 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12890 	    (int32_t)((uchar_t *)up - rptr),
12891 	    mp, mp1, cksum_err);
12892 
12893 	if (cksum_err) {
12894 		BUMP_MIB(&ip_mib, tcpInErrs);
12895 
12896 		if (hck_flags & HCK_FULLCKSUM)
12897 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12898 		else if (hck_flags & HCK_PARTIALCKSUM)
12899 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12900 		else
12901 			IP_STAT(ip_tcp_in_sw_cksum_err);
12902 
12903 		goto error;
12904 	}
12905 
12906 try_again:
12907 
12908 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12909 	    NULL) {
12910 		/* Send the TH_RST */
12911 		goto no_conn;
12912 	}
12913 
12914 	/*
12915 	 * TCP FAST PATH for AF_INET socket.
12916 	 *
12917 	 * TCP fast path to avoid extra work. An AF_INET socket type
12918 	 * does not have facility to receive extra information via
12919 	 * ip_process or ip_add_info. Also, when the connection was
12920 	 * established, we made a check if this connection is impacted
12921 	 * by any global IPSec policy or per connection policy (a
12922 	 * policy that comes in effect later will not apply to this
12923 	 * connection). Since all this can be determined at the
12924 	 * connection establishment time, a quick check of flags
12925 	 * can avoid extra work.
12926 	 */
12927 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12928 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12929 		ASSERT(first_mp == mp);
12930 		SET_SQUEUE(mp, tcp_rput_data, connp);
12931 		return (mp);
12932 	}
12933 
12934 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12935 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12936 		if (IPCL_IS_TCP(connp)) {
12937 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12938 			DB_CKSUMSTART(mp) =
12939 			    (intptr_t)ip_squeue_get(ill_ring);
12940 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12941 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12942 				SET_SQUEUE(mp, connp->conn_recv, connp);
12943 				return (mp);
12944 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12945 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12946 				ip_squeue_enter_unbound++;
12947 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12948 				    connp);
12949 				return (mp);
12950 			}
12951 			syn_present = B_TRUE;
12952 		}
12953 
12954 	}
12955 
12956 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12957 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12958 
12959 		/* No need to send this packet to TCP */
12960 		if ((flags & TH_RST) || (flags & TH_URG)) {
12961 			CONN_DEC_REF(connp);
12962 			freemsg(first_mp);
12963 			return (NULL);
12964 		}
12965 		if (flags & TH_ACK) {
12966 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
12967 			CONN_DEC_REF(connp);
12968 			return (NULL);
12969 		}
12970 
12971 		CONN_DEC_REF(connp);
12972 		freemsg(first_mp);
12973 		return (NULL);
12974 	}
12975 
12976 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12977 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12978 		    ipha, NULL, mctl_present);
12979 		if (first_mp == NULL) {
12980 			CONN_DEC_REF(connp);
12981 			return (NULL);
12982 		}
12983 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12984 			ASSERT(syn_present);
12985 			if (mctl_present) {
12986 				ASSERT(first_mp != mp);
12987 				first_mp->b_datap->db_struioflag |=
12988 				    STRUIO_POLICY;
12989 			} else {
12990 				ASSERT(first_mp == mp);
12991 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12992 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12993 			}
12994 		} else {
12995 			/*
12996 			 * Discard first_mp early since we're dealing with a
12997 			 * fully-connected conn_t and tcp doesn't do policy in
12998 			 * this case.
12999 			 */
13000 			if (mctl_present) {
13001 				freeb(first_mp);
13002 				mctl_present = B_FALSE;
13003 			}
13004 			first_mp = mp;
13005 		}
13006 	}
13007 
13008 	/* Initiate IPPF processing for fastpath */
13009 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13010 		uint32_t	ill_index;
13011 
13012 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13013 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13014 		if (mp == NULL) {
13015 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13016 			    "deferred/dropped during IPPF processing\n"));
13017 			CONN_DEC_REF(connp);
13018 			if (mctl_present)
13019 				freeb(first_mp);
13020 			return (NULL);
13021 		} else if (mctl_present) {
13022 			/*
13023 			 * ip_process might return a new mp.
13024 			 */
13025 			ASSERT(first_mp != mp);
13026 			first_mp->b_cont = mp;
13027 		} else {
13028 			first_mp = mp;
13029 		}
13030 
13031 	}
13032 
13033 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
13034 		mp = ip_add_info(mp, recv_ill, flags);
13035 		if (mp == NULL) {
13036 			CONN_DEC_REF(connp);
13037 			if (mctl_present)
13038 				freeb(first_mp);
13039 			return (NULL);
13040 		} else if (mctl_present) {
13041 			/*
13042 			 * ip_add_info might return a new mp.
13043 			 */
13044 			ASSERT(first_mp != mp);
13045 			first_mp->b_cont = mp;
13046 		} else {
13047 			first_mp = mp;
13048 		}
13049 	}
13050 
13051 	if (IPCL_IS_TCP(connp)) {
13052 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13053 		return (first_mp);
13054 	} else {
13055 		putnext(connp->conn_rq, first_mp);
13056 		CONN_DEC_REF(connp);
13057 		return (NULL);
13058 	}
13059 
13060 no_conn:
13061 	/* Initiate IPPf processing, if needed. */
13062 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13063 		uint32_t ill_index;
13064 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13065 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13066 		if (first_mp == NULL) {
13067 			return (NULL);
13068 		}
13069 	}
13070 	BUMP_MIB(&ip_mib, ipInDelivers);
13071 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid);
13072 	return (NULL);
13073 ipoptions:
13074 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
13075 		goto slow_done;
13076 	}
13077 
13078 	UPDATE_IB_PKT_COUNT(ire);
13079 	ire->ire_last_used_time = lbolt;
13080 
13081 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13082 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13083 fragmented:
13084 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13085 			if (mctl_present)
13086 				freeb(first_mp);
13087 			goto slow_done;
13088 		}
13089 		/*
13090 		 * Make sure that first_mp points back to mp as
13091 		 * the mp we came in with could have changed in
13092 		 * ip_rput_fragment().
13093 		 */
13094 		ASSERT(!mctl_present);
13095 		ipha = (ipha_t *)mp->b_rptr;
13096 		first_mp = mp;
13097 	}
13098 
13099 	/* Now we have a complete datagram, destined for this machine. */
13100 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13101 
13102 	len = mp->b_wptr - mp->b_rptr;
13103 	/* Pull up a minimal TCP header, if necessary. */
13104 	if (len < (u1 + 20)) {
13105 tcppullup:
13106 		if (!pullupmsg(mp, u1 + 20)) {
13107 			BUMP_MIB(&ip_mib, ipInDiscards);
13108 			goto error;
13109 		}
13110 		ipha = (ipha_t *)mp->b_rptr;
13111 		len = mp->b_wptr - mp->b_rptr;
13112 	}
13113 
13114 	/*
13115 	 * Extract the offset field from the TCP header.  As usual, we
13116 	 * try to help the compiler more than the reader.
13117 	 */
13118 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13119 	if (offset != 5) {
13120 tcpoptions:
13121 		if (offset < 5) {
13122 			BUMP_MIB(&ip_mib, ipInDiscards);
13123 			goto error;
13124 		}
13125 		/*
13126 		 * There must be TCP options.
13127 		 * Make sure we can grab them.
13128 		 */
13129 		offset <<= 2;
13130 		offset += u1;
13131 		if (len < offset) {
13132 			if (!pullupmsg(mp, offset)) {
13133 				BUMP_MIB(&ip_mib, ipInDiscards);
13134 				goto error;
13135 			}
13136 			ipha = (ipha_t *)mp->b_rptr;
13137 			len = mp->b_wptr - rptr;
13138 		}
13139 	}
13140 
13141 	/* Get the total packet length in len, including headers. */
13142 	if (mp->b_cont) {
13143 multipkttcp:
13144 		len = msgdsize(mp);
13145 	}
13146 
13147 	/*
13148 	 * Check the TCP checksum by pulling together the pseudo-
13149 	 * header checksum, and passing it to ip_csum to be added in
13150 	 * with the TCP datagram.
13151 	 *
13152 	 * Since we are not using the hwcksum if available we must
13153 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13154 	 * If either of these fails along the way the mblk is freed.
13155 	 * If this logic ever changes and mblk is reused to say send
13156 	 * ICMP's back, then this flag may need to be cleared in
13157 	 * other places as well.
13158 	 */
13159 	DB_CKSUMFLAGS(mp) = 0;
13160 
13161 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13162 
13163 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13164 #ifdef	_BIG_ENDIAN
13165 	u1 += IPPROTO_TCP;
13166 #else
13167 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13168 #endif
13169 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13170 	/*
13171 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13172 	 */
13173 	IP_STAT(ip_in_sw_cksum);
13174 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13175 		BUMP_MIB(&ip_mib, tcpInErrs);
13176 		goto error;
13177 	}
13178 
13179 	IP_STAT(ip_tcp_slow_path);
13180 	goto try_again;
13181 #undef  iphs
13182 #undef  rptr
13183 
13184 error:
13185 	freemsg(first_mp);
13186 slow_done:
13187 	return (NULL);
13188 }
13189 
13190 /* ARGSUSED */
13191 static void
13192 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13193     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13194 {
13195 	conn_t		*connp;
13196 	uint32_t	sum;
13197 	uint32_t	u1;
13198 	ssize_t		len;
13199 	sctp_hdr_t	*sctph;
13200 	zoneid_t	zoneid = ire->ire_zoneid;
13201 	uint32_t	pktsum;
13202 	uint32_t	calcsum;
13203 	uint32_t	ports;
13204 	uint_t		ipif_seqid;
13205 	in6_addr_t	map_src, map_dst;
13206 	ill_t		*ill = (ill_t *)q->q_ptr;
13207 
13208 #define	rptr	((uchar_t *)ipha)
13209 
13210 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13211 
13212 	/* u1 is # words of IP options */
13213 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13214 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13215 
13216 	/* IP options present */
13217 	if (u1 > 0) {
13218 		goto ipoptions;
13219 	} else {
13220 		/* Check the IP header checksum.  */
13221 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13222 #define	uph	((uint16_t *)ipha)
13223 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13224 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13225 #undef	uph
13226 			/* finish doing IP checksum */
13227 			sum = (sum & 0xFFFF) + (sum >> 16);
13228 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13229 			/*
13230 			 * Don't verify header checksum if this packet
13231 			 * is coming back from AH/ESP as we already did it.
13232 			 */
13233 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13234 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13235 				goto error;
13236 			}
13237 		}
13238 		/*
13239 		 * Since there is no SCTP h/w cksum support yet, just
13240 		 * clear the flag.
13241 		 */
13242 		DB_CKSUMFLAGS(mp) = 0;
13243 	}
13244 
13245 	/*
13246 	 * Don't verify header checksum if this packet is coming
13247 	 * back from AH/ESP as we already did it.
13248 	 */
13249 	if (!mctl_present) {
13250 		UPDATE_IB_PKT_COUNT(ire);
13251 		ire->ire_last_used_time = lbolt;
13252 	}
13253 
13254 	/* packet part of fragmented IP packet? */
13255 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13256 	if (u1 & (IPH_MF | IPH_OFFSET))
13257 		goto fragmented;
13258 
13259 	/* u1 = IP header length (20 bytes) */
13260 	u1 = IP_SIMPLE_HDR_LENGTH;
13261 
13262 find_sctp_client:
13263 	/* Pullup if we don't have the sctp common header. */
13264 	len = MBLKL(mp);
13265 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13266 		if (mp->b_cont == NULL ||
13267 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13268 			BUMP_MIB(&ip_mib, ipInDiscards);
13269 			goto error;
13270 		}
13271 		ipha = (ipha_t *)mp->b_rptr;
13272 		len = MBLKL(mp);
13273 	}
13274 
13275 	sctph = (sctp_hdr_t *)(rptr + u1);
13276 #ifdef	DEBUG
13277 	if (!skip_sctp_cksum) {
13278 #endif
13279 		pktsum = sctph->sh_chksum;
13280 		sctph->sh_chksum = 0;
13281 		calcsum = sctp_cksum(mp, u1);
13282 		if (calcsum != pktsum) {
13283 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13284 			goto error;
13285 		}
13286 		sctph->sh_chksum = pktsum;
13287 #ifdef	DEBUG	/* skip_sctp_cksum */
13288 	}
13289 #endif
13290 	/* get the ports */
13291 	ports = *(uint32_t *)&sctph->sh_sport;
13292 
13293 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13294 	IRE_REFRELE(ire);
13295 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13296 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13297 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13298 	    mp)) == NULL) {
13299 		/* Check for raw socket or OOTB handling */
13300 		goto no_conn;
13301 	}
13302 
13303 	/* Found a client; up it goes */
13304 	BUMP_MIB(&ip_mib, ipInDelivers);
13305 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13306 	return;
13307 
13308 no_conn:
13309 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13310 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13311 	return;
13312 
13313 ipoptions:
13314 	DB_CKSUMFLAGS(mp) = 0;
13315 	if (!ip_options_cksum(q, first_mp, ipha, ire))
13316 		goto slow_done;
13317 
13318 	UPDATE_IB_PKT_COUNT(ire);
13319 	ire->ire_last_used_time = lbolt;
13320 
13321 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13322 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13323 fragmented:
13324 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13325 			goto slow_done;
13326 		/*
13327 		 * Make sure that first_mp points back to mp as
13328 		 * the mp we came in with could have changed in
13329 		 * ip_rput_fragment().
13330 		 */
13331 		ASSERT(!mctl_present);
13332 		ipha = (ipha_t *)mp->b_rptr;
13333 		first_mp = mp;
13334 	}
13335 
13336 	/* Now we have a complete datagram, destined for this machine. */
13337 	u1 = IPH_HDR_LENGTH(ipha);
13338 	goto find_sctp_client;
13339 #undef  iphs
13340 #undef  rptr
13341 
13342 error:
13343 	freemsg(first_mp);
13344 slow_done:
13345 	IRE_REFRELE(ire);
13346 }
13347 
13348 #define	VER_BITS	0xF0
13349 #define	VERSION_6	0x60
13350 
13351 static boolean_t
13352 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
13353     ipaddr_t *dstp)
13354 {
13355 	uint_t	opt_len;
13356 	ipha_t *ipha;
13357 	ssize_t len;
13358 	uint_t	pkt_len;
13359 
13360 	IP_STAT(ip_ipoptions);
13361 	ipha = *iphapp;
13362 
13363 #define	rptr    ((uchar_t *)ipha)
13364 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13365 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13366 		BUMP_MIB(&ip_mib, ipInIPv6);
13367 		freemsg(mp);
13368 		return (B_FALSE);
13369 	}
13370 
13371 	/* multiple mblk or too short */
13372 	pkt_len = ntohs(ipha->ipha_length);
13373 
13374 	/* Get the number of words of IP options in the IP header. */
13375 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13376 	if (opt_len) {
13377 		/* IP Options present!  Validate and process. */
13378 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13379 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13380 			goto done;
13381 		}
13382 		/*
13383 		 * Recompute complete header length and make sure we
13384 		 * have access to all of it.
13385 		 */
13386 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13387 		if (len > (mp->b_wptr - rptr)) {
13388 			if (len > pkt_len) {
13389 				BUMP_MIB(&ip_mib, ipInHdrErrors);
13390 				goto done;
13391 			}
13392 			if (!pullupmsg(mp, len)) {
13393 				BUMP_MIB(&ip_mib, ipInDiscards);
13394 				goto done;
13395 			}
13396 			ipha = (ipha_t *)mp->b_rptr;
13397 		}
13398 		/*
13399 		 * Go off to ip_rput_options which returns the next hop
13400 		 * destination address, which may have been affected
13401 		 * by source routing.
13402 		 */
13403 		IP_STAT(ip_opt);
13404 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13405 			return (B_FALSE);
13406 		}
13407 	}
13408 	*iphapp = ipha;
13409 	return (B_TRUE);
13410 done:
13411 	/* clear b_prev - used by ip_mroute_decap */
13412 	mp->b_prev = NULL;
13413 	freemsg(mp);
13414 	return (B_FALSE);
13415 #undef  rptr
13416 }
13417 
13418 /*
13419  * Deal with the fact that there is no ire for the destination.
13420  * The incoming ill (in_ill) is passed in to ip_newroute only
13421  * in the case of packets coming from mobile ip forward tunnel.
13422  * It must be null otherwise.
13423  */
13424 static ire_t *
13425 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13426     ipaddr_t dst)
13427 {
13428 	ipha_t	*ipha;
13429 	ill_t	*ill;
13430 	ire_t	*ire;
13431 	boolean_t	check_multirt = B_FALSE;
13432 
13433 	ipha = (ipha_t *)mp->b_rptr;
13434 	ill = (ill_t *)q->q_ptr;
13435 
13436 	ASSERT(ill != NULL);
13437 	/*
13438 	 * No IRE for this destination, so it can't be for us.
13439 	 * Unless we are forwarding, drop the packet.
13440 	 * We have to let source routed packets through
13441 	 * since we don't yet know if they are 'ping -l'
13442 	 * packets i.e. if they will go out over the
13443 	 * same interface as they came in on.
13444 	 */
13445 	if (ll_multicast) {
13446 		freemsg(mp);
13447 		return (NULL);
13448 	}
13449 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13450 		BUMP_MIB(&ip_mib, ipForwProhibits);
13451 		freemsg(mp);
13452 		return (NULL);
13453 	}
13454 
13455 	/*
13456 	 * Mark this packet as having originated externally.
13457 	 *
13458 	 * For non-forwarding code path, ire_send later double
13459 	 * checks this interface to see if it is still exists
13460 	 * post-ARP resolution.
13461 	 *
13462 	 * Also, IPQOS uses this to differentiate between
13463 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13464 	 * QOS packet processing in ip_wput_attach_llhdr().
13465 	 * The QoS module can mark the b_band for a fastpath message
13466 	 * or the dl_priority field in a unitdata_req header for
13467 	 * CoS marking. This info can only be found in
13468 	 * ip_wput_attach_llhdr().
13469 	 */
13470 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13471 	/*
13472 	 * Clear the indication that this may have a hardware checksum
13473 	 * as we are not using it
13474 	 */
13475 	DB_CKSUMFLAGS(mp) = 0;
13476 
13477 	if (in_ill != NULL) {
13478 		/*
13479 		 * Now hand the packet to ip_newroute.
13480 		 */
13481 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13482 		return (NULL);
13483 	}
13484 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13485 	    MBLK_GETLABEL(mp));
13486 
13487 	if (ire == NULL && check_multirt) {
13488 		/* Let ip_newroute handle CGTP  */
13489 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13490 		return (NULL);
13491 	}
13492 
13493 	if (ire != NULL)
13494 		return (ire);
13495 
13496 	mp->b_prev = mp->b_next = 0;
13497 	/* send icmp unreachable */
13498 	q = WR(q);
13499 	/* Sent by forwarding path, and router is global zone */
13500 	if (ip_source_routed(ipha)) {
13501 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13502 		    GLOBAL_ZONEID);
13503 	} else {
13504 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13505 	}
13506 
13507 	return (NULL);
13508 
13509 }
13510 
13511 /*
13512  * check ip header length and align it.
13513  */
13514 static boolean_t
13515 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13516 {
13517 	ssize_t len;
13518 	ill_t *ill;
13519 	ipha_t	*ipha;
13520 
13521 	len = MBLKL(mp);
13522 
13523 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13524 		if (!OK_32PTR(mp->b_rptr))
13525 			IP_STAT(ip_notaligned1);
13526 		else
13527 			IP_STAT(ip_notaligned2);
13528 		/* Guard against bogus device drivers */
13529 		if (len < 0) {
13530 			/* clear b_prev - used by ip_mroute_decap */
13531 			mp->b_prev = NULL;
13532 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13533 			freemsg(mp);
13534 			return (B_FALSE);
13535 		}
13536 
13537 		if (ip_rput_pullups++ == 0) {
13538 			ill = (ill_t *)q->q_ptr;
13539 			ipha = (ipha_t *)mp->b_rptr;
13540 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13541 			    "ip_check_and_align_header: %s forced us to "
13542 			    " pullup pkt, hdr len %ld, hdr addr %p",
13543 			    ill->ill_name, len, ipha);
13544 		}
13545 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13546 			/* clear b_prev - used by ip_mroute_decap */
13547 			mp->b_prev = NULL;
13548 			BUMP_MIB(&ip_mib, ipInDiscards);
13549 			freemsg(mp);
13550 			return (B_FALSE);
13551 		}
13552 	}
13553 	return (B_TRUE);
13554 }
13555 
13556 static boolean_t
13557 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13558 {
13559 	ill_group_t	*ill_group;
13560 	ill_group_t	*ire_group;
13561 	queue_t 	*q;
13562 	ill_t		*ire_ill;
13563 	uint_t		ill_ifindex;
13564 
13565 	q = *qp;
13566 	/*
13567 	 * We need to check to make sure the packet came in
13568 	 * on the queue associated with the destination IRE.
13569 	 * Note that for multicast packets and broadcast packets sent to
13570 	 * a broadcast address which is shared between multiple interfaces
13571 	 * we should not do this since we just got a random broadcast ire.
13572 	 */
13573 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13574 		boolean_t check_multi = B_TRUE;
13575 
13576 		/*
13577 		 * This packet came in on an interface other than the
13578 		 * one associated with the destination address.
13579 		 * "Gateway" it to the appropriate interface here.
13580 		 * As long as the ills belong to the same group,
13581 		 * we don't consider them to arriving on the wrong
13582 		 * interface. Thus, when the switch is doing inbound
13583 		 * load spreading, we won't drop packets when we
13584 		 * are doing strict multihoming checks. Note, the
13585 		 * same holds true for 'usesrc groups' where the
13586 		 * destination address may belong to another interface
13587 		 * to allow multipathing to happen
13588 		 */
13589 		ill_group = ill->ill_group;
13590 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13591 		ill_ifindex = ill->ill_usesrc_ifindex;
13592 		ire_group = ire_ill->ill_group;
13593 
13594 		/*
13595 		 * If it's part of the same IPMP group, or if it's a legal
13596 		 * address on the 'usesrc' interface, then bypass strict
13597 		 * checks.
13598 		 */
13599 		if (ill_group != NULL && ill_group == ire_group) {
13600 			check_multi = B_FALSE;
13601 		} else if (ill_ifindex != 0 &&
13602 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13603 			check_multi = B_FALSE;
13604 		}
13605 
13606 		if (check_multi &&
13607 		    ip_strict_dst_multihoming &&
13608 		    ((ill->ill_flags &
13609 		    ire->ire_ipif->ipif_ill->ill_flags &
13610 		    ILLF_ROUTER) == 0)) {
13611 			/* Drop packet */
13612 			BUMP_MIB(&ip_mib, ipForwProhibits);
13613 			freemsg(mp);
13614 			return (B_TRUE);
13615 		}
13616 
13617 		/*
13618 		 * Change the queue (for non-virtual destination network
13619 		 * interfaces) and ip_rput_local will be called with the right
13620 		 * queue
13621 		 */
13622 		q = ire->ire_rfq;
13623 	}
13624 	/* Must be broadcast.  We'll take it. */
13625 	*qp = q;
13626 	return (B_FALSE);
13627 }
13628 
13629 ire_t *
13630 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13631 {
13632 	ipha_t	*ipha;
13633 	ipaddr_t ip_dst, ip_src;
13634 	ire_t	*src_ire = NULL;
13635 	ill_t	*stq_ill;
13636 	uint_t	hlen;
13637 	uint32_t sum;
13638 	queue_t	*dev_q;
13639 	boolean_t check_multirt = B_FALSE;
13640 
13641 
13642 	ipha = (ipha_t *)mp->b_rptr;
13643 
13644 	/*
13645 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13646 	 * The loopback address check for both src and dst has already
13647 	 * been checked in ip_input
13648 	 */
13649 	ip_dst = ntohl(dst);
13650 	ip_src = ntohl(ipha->ipha_src);
13651 
13652 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13653 	    IN_CLASSD(ip_src)) {
13654 		BUMP_MIB(&ip_mib, ipForwProhibits);
13655 		goto drop;
13656 	}
13657 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13658 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13659 
13660 	if (src_ire != NULL) {
13661 		BUMP_MIB(&ip_mib, ipForwProhibits);
13662 		goto drop;
13663 	}
13664 
13665 	/* No ire cache of nexthop. So first create one  */
13666 	if (ire == NULL) {
13667 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13668 		/*
13669 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13670 		 * is not set. So upon return from ire_forward
13671 		 * check_multirt should remain as false.
13672 		 */
13673 		ASSERT(!check_multirt);
13674 		if (ire == NULL) {
13675 			BUMP_MIB(&ip_mib, ipInDiscards);
13676 			mp->b_prev = mp->b_next = 0;
13677 			/* send icmp unreachable */
13678 			/* Sent by forwarding path, and router is global zone */
13679 			if (ip_source_routed(ipha)) {
13680 				icmp_unreachable(ill->ill_wq, mp,
13681 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13682 			} else {
13683 				icmp_unreachable(ill->ill_wq, mp,
13684 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13685 			}
13686 			return (ire);
13687 		}
13688 	}
13689 
13690 	/*
13691 	 * Forwarding fastpath exception case:
13692 	 * If either of the follwoing case is true, we take
13693 	 * the slowpath
13694 	 *	o forwarding is not enabled
13695 	 *	o incoming and outgoing interface are the same, or the same
13696 	 *	  IPMP group
13697 	 *	o corresponding ire is in incomplete state
13698 	 *	o packet needs fragmentation
13699 	 *
13700 	 * The codeflow from here on is thus:
13701 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13702 	 */
13703 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13704 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13705 	    !(ill->ill_flags & ILLF_ROUTER) ||
13706 	    (ill == stq_ill) ||
13707 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13708 	    (ire->ire_nce == NULL) ||
13709 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13710 	    (ntohs(ipha->ipha_length) > ire->ire_max_frag) ||
13711 	    ipha->ipha_ttl <= 1) {
13712 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13713 		    ipha, ill, B_FALSE);
13714 		return (ire);
13715 	}
13716 
13717 	DTRACE_PROBE4(ip4__forwarding__start,
13718 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13719 
13720 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
13721 	    ill, stq_ill, ipha, mp, mp);
13722 
13723 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13724 
13725 	if (mp == NULL)
13726 		goto drop;
13727 
13728 	mp->b_datap->db_struioun.cksum.flags = 0;
13729 	/* Adjust the checksum to reflect the ttl decrement. */
13730 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13731 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13732 	ipha->ipha_ttl--;
13733 
13734 	dev_q = ire->ire_stq->q_next;
13735 	if ((dev_q->q_next != NULL ||
13736 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13737 		goto indiscard;
13738 	}
13739 
13740 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13741 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13742 
13743 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13744 		mblk_t *mpip = mp;
13745 
13746 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13747 		if (mp != NULL) {
13748 			DTRACE_PROBE4(ip4__physical__out__start,
13749 			    ill_t *, NULL, ill_t *, stq_ill,
13750 			    ipha_t *, ipha, mblk_t *, mp);
13751 			FW_HOOKS(ip4_physical_out_event,
13752 			    ipv4firewall_physical_out,
13753 			    NULL, stq_ill, ipha, mp, mpip);
13754 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13755 			    mp);
13756 			if (mp == NULL)
13757 				goto drop;
13758 
13759 			UPDATE_IB_PKT_COUNT(ire);
13760 			ire->ire_last_used_time = lbolt;
13761 			BUMP_MIB(&ip_mib, ipForwDatagrams);
13762 			putnext(ire->ire_stq, mp);
13763 			return (ire);
13764 		}
13765 	}
13766 
13767 indiscard:
13768 	BUMP_MIB(&ip_mib, ipInDiscards);
13769 drop:
13770 	if (mp != NULL)
13771 		freemsg(mp);
13772 	if (src_ire != NULL)
13773 		ire_refrele(src_ire);
13774 	return (ire);
13775 
13776 }
13777 
13778 /*
13779  * This function is called in the forwarding slowpath, when
13780  * either the ire lacks the link-layer address, or the packet needs
13781  * further processing(eg. fragmentation), before transmission.
13782  */
13783 
13784 static void
13785 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13786     ill_t *ill, boolean_t ll_multicast)
13787 {
13788 	ill_group_t	*ill_group;
13789 	ill_group_t	*ire_group;
13790 	queue_t		*dev_q;
13791 	ire_t		*src_ire;
13792 
13793 	ASSERT(ire->ire_stq != NULL);
13794 
13795 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13796 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13797 
13798 	if (ll_multicast != 0)
13799 		goto drop_pkt;
13800 
13801 	/*
13802 	 * check if ipha_src is a broadcast address. Note that this
13803 	 * check is redundant when we get here from ip_fast_forward()
13804 	 * which has already done this check. However, since we can
13805 	 * also get here from ip_rput_process_broadcast() or, for
13806 	 * for the slow path through ip_fast_forward(), we perform
13807 	 * the check again for code-reusability
13808 	 */
13809 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13810 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13811 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13812 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13813 		if (src_ire != NULL)
13814 			ire_refrele(src_ire);
13815 		BUMP_MIB(&ip_mib, ipForwProhibits);
13816 		ip2dbg(("ip_rput_process_forward: Received packet with"
13817 		    " bad src/dst address on %s\n", ill->ill_name));
13818 		goto drop_pkt;
13819 	}
13820 
13821 	ill_group = ill->ill_group;
13822 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13823 	/*
13824 	 * Check if we want to forward this one at this time.
13825 	 * We allow source routed packets on a host provided that
13826 	 * they go out the same interface or same interface group
13827 	 * as they came in on.
13828 	 *
13829 	 * XXX To be quicker, we may wish to not chase pointers to
13830 	 * get the ILLF_ROUTER flag and instead store the
13831 	 * forwarding policy in the ire.  An unfortunate
13832 	 * side-effect of that would be requiring an ire flush
13833 	 * whenever the ILLF_ROUTER flag changes.
13834 	 */
13835 	if (((ill->ill_flags &
13836 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13837 	    ILLF_ROUTER) == 0) &&
13838 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13839 	    (ill_group != NULL && ill_group == ire_group)))) {
13840 		BUMP_MIB(&ip_mib, ipForwProhibits);
13841 		if (ip_source_routed(ipha)) {
13842 			q = WR(q);
13843 			/*
13844 			 * Clear the indication that this may have
13845 			 * hardware checksum as we are not using it.
13846 			 */
13847 			DB_CKSUMFLAGS(mp) = 0;
13848 			/* Sent by forwarding path, and router is global zone */
13849 			icmp_unreachable(q, mp,
13850 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13851 			return;
13852 		}
13853 		goto drop_pkt;
13854 	}
13855 
13856 	/* Packet is being forwarded. Turning off hwcksum flag. */
13857 	DB_CKSUMFLAGS(mp) = 0;
13858 	if (ip_g_send_redirects) {
13859 		/*
13860 		 * Check whether the incoming interface and outgoing
13861 		 * interface is part of the same group. If so,
13862 		 * send redirects.
13863 		 *
13864 		 * Check the source address to see if it originated
13865 		 * on the same logical subnet it is going back out on.
13866 		 * If so, we should be able to send it a redirect.
13867 		 * Avoid sending a redirect if the destination
13868 		 * is directly connected (i.e., ipha_dst is the same
13869 		 * as ire_gateway_addr or the ire_addr of the
13870 		 * nexthop IRE_CACHE ), or if the packet was source
13871 		 * routed out this interface.
13872 		 */
13873 		ipaddr_t src, nhop;
13874 		mblk_t	*mp1;
13875 		ire_t	*nhop_ire = NULL;
13876 
13877 		/*
13878 		 * Check whether ire_rfq and q are from the same ill
13879 		 * or if they are not same, they at least belong
13880 		 * to the same group. If so, send redirects.
13881 		 */
13882 		if ((ire->ire_rfq == q ||
13883 		    (ill_group != NULL && ill_group == ire_group)) &&
13884 		    !ip_source_routed(ipha)) {
13885 
13886 			nhop = (ire->ire_gateway_addr != 0 ?
13887 			    ire->ire_gateway_addr : ire->ire_addr);
13888 
13889 			if (ipha->ipha_dst == nhop) {
13890 				/*
13891 				 * We avoid sending a redirect if the
13892 				 * destination is directly connected
13893 				 * because it is possible that multiple
13894 				 * IP subnets may have been configured on
13895 				 * the link, and the source may not
13896 				 * be on the same subnet as ip destination,
13897 				 * even though they are on the same
13898 				 * physical link.
13899 				 */
13900 				goto sendit;
13901 			}
13902 
13903 			src = ipha->ipha_src;
13904 
13905 			/*
13906 			 * We look up the interface ire for the nexthop,
13907 			 * to see if ipha_src is in the same subnet
13908 			 * as the nexthop.
13909 			 *
13910 			 * Note that, if, in the future, IRE_CACHE entries
13911 			 * are obsoleted,  this lookup will not be needed,
13912 			 * as the ire passed to this function will be the
13913 			 * same as the nhop_ire computed below.
13914 			 */
13915 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
13916 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
13917 			    0, NULL, MATCH_IRE_TYPE);
13918 
13919 			if (nhop_ire != NULL) {
13920 				if ((src & nhop_ire->ire_mask) ==
13921 				    (nhop & nhop_ire->ire_mask)) {
13922 					/*
13923 					 * The source is directly connected.
13924 					 * Just copy the ip header (which is
13925 					 * in the first mblk)
13926 					 */
13927 					mp1 = copyb(mp);
13928 					if (mp1 != NULL) {
13929 						icmp_send_redirect(WR(q), mp1,
13930 						    nhop);
13931 					}
13932 				}
13933 				ire_refrele(nhop_ire);
13934 			}
13935 		}
13936 	}
13937 sendit:
13938 	dev_q = ire->ire_stq->q_next;
13939 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13940 		BUMP_MIB(&ip_mib, ipInDiscards);
13941 		freemsg(mp);
13942 		return;
13943 	}
13944 
13945 	ip_rput_forward(ire, ipha, mp, ill);
13946 	return;
13947 
13948 drop_pkt:
13949 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
13950 	freemsg(mp);
13951 }
13952 
13953 ire_t *
13954 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13955     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13956 {
13957 	queue_t		*q;
13958 	uint16_t	hcksumflags;
13959 
13960 	q = *qp;
13961 
13962 	/*
13963 	 * Clear the indication that this may have hardware
13964 	 * checksum as we are not using it for forwarding.
13965 	 */
13966 	hcksumflags = DB_CKSUMFLAGS(mp);
13967 	DB_CKSUMFLAGS(mp) = 0;
13968 
13969 	/*
13970 	 * Directed broadcast forwarding: if the packet came in over a
13971 	 * different interface then it is routed out over we can forward it.
13972 	 */
13973 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13974 		ire_refrele(ire);
13975 		freemsg(mp);
13976 		BUMP_MIB(&ip_mib, ipInDiscards);
13977 		return (NULL);
13978 	}
13979 	/*
13980 	 * For multicast we have set dst to be INADDR_BROADCAST
13981 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13982 	 * only for broadcast packets.
13983 	 */
13984 	if (!CLASSD(ipha->ipha_dst)) {
13985 		ire_t *new_ire;
13986 		ipif_t *ipif;
13987 		/*
13988 		 * For ill groups, as the switch duplicates broadcasts
13989 		 * across all the ports, we need to filter out and
13990 		 * send up only one copy. There is one copy for every
13991 		 * broadcast address on each ill. Thus, we look for a
13992 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13993 		 * later to see whether this ill is eligible to receive
13994 		 * them or not. ill_nominate_bcast_rcv() nominates only
13995 		 * one set of IREs for receiving.
13996 		 */
13997 
13998 		ipif = ipif_get_next_ipif(NULL, ill);
13999 		if (ipif == NULL) {
14000 			ire_refrele(ire);
14001 			freemsg(mp);
14002 			BUMP_MIB(&ip_mib, ipInDiscards);
14003 			return (NULL);
14004 		}
14005 		new_ire = ire_ctable_lookup(dst, 0, 0,
14006 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
14007 		ipif_refrele(ipif);
14008 
14009 		if (new_ire != NULL) {
14010 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14011 				ire_refrele(ire);
14012 				ire_refrele(new_ire);
14013 				freemsg(mp);
14014 				BUMP_MIB(&ip_mib, ipInDiscards);
14015 				return (NULL);
14016 			}
14017 			/*
14018 			 * In the special case of multirouted broadcast
14019 			 * packets, we unconditionally need to "gateway"
14020 			 * them to the appropriate interface here.
14021 			 * In the normal case, this cannot happen, because
14022 			 * there is no broadcast IRE tagged with the
14023 			 * RTF_MULTIRT flag.
14024 			 */
14025 			if (new_ire->ire_flags & RTF_MULTIRT) {
14026 				ire_refrele(new_ire);
14027 				if (ire->ire_rfq != NULL) {
14028 					q = ire->ire_rfq;
14029 					*qp = q;
14030 				}
14031 			} else {
14032 				ire_refrele(ire);
14033 				ire = new_ire;
14034 			}
14035 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14036 			if (!ip_g_forward_directed_bcast) {
14037 				/*
14038 				 * Free the message if
14039 				 * ip_g_forward_directed_bcast is turned
14040 				 * off for non-local broadcast.
14041 				 */
14042 				ire_refrele(ire);
14043 				freemsg(mp);
14044 				BUMP_MIB(&ip_mib, ipInDiscards);
14045 				return (NULL);
14046 			}
14047 		} else {
14048 			/*
14049 			 * This CGTP packet successfully passed the
14050 			 * CGTP filter, but the related CGTP
14051 			 * broadcast IRE has not been found,
14052 			 * meaning that the redundant ipif is
14053 			 * probably down. However, if we discarded
14054 			 * this packet, its duplicate would be
14055 			 * filtered out by the CGTP filter so none
14056 			 * of them would get through. So we keep
14057 			 * going with this one.
14058 			 */
14059 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14060 			if (ire->ire_rfq != NULL) {
14061 				q = ire->ire_rfq;
14062 				*qp = q;
14063 			}
14064 		}
14065 	}
14066 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
14067 		/*
14068 		 * Verify that there are not more then one
14069 		 * IRE_BROADCAST with this broadcast address which
14070 		 * has ire_stq set.
14071 		 * TODO: simplify, loop over all IRE's
14072 		 */
14073 		ire_t	*ire1;
14074 		int	num_stq = 0;
14075 		mblk_t	*mp1;
14076 
14077 		/* Find the first one with ire_stq set */
14078 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14079 		for (ire1 = ire; ire1 &&
14080 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14081 		    ire1 = ire1->ire_next)
14082 			;
14083 		if (ire1) {
14084 			ire_refrele(ire);
14085 			ire = ire1;
14086 			IRE_REFHOLD(ire);
14087 		}
14088 
14089 		/* Check if there are additional ones with stq set */
14090 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14091 			if (ire->ire_addr != ire1->ire_addr)
14092 				break;
14093 			if (ire1->ire_stq) {
14094 				num_stq++;
14095 				break;
14096 			}
14097 		}
14098 		rw_exit(&ire->ire_bucket->irb_lock);
14099 		if (num_stq == 1 && ire->ire_stq != NULL) {
14100 			ip1dbg(("ip_rput_process_broadcast: directed "
14101 			    "broadcast to 0x%x\n",
14102 			    ntohl(ire->ire_addr)));
14103 			mp1 = copymsg(mp);
14104 			if (mp1) {
14105 				switch (ipha->ipha_protocol) {
14106 				case IPPROTO_UDP:
14107 					ip_udp_input(q, mp1, ipha, ire, ill);
14108 					break;
14109 				default:
14110 					ip_proto_input(q, mp1, ipha, ire, ill);
14111 					break;
14112 				}
14113 			}
14114 			/*
14115 			 * Adjust ttl to 2 (1+1 - the forward engine
14116 			 * will decrement it by one.
14117 			 */
14118 			if (ip_csum_hdr(ipha)) {
14119 				BUMP_MIB(&ip_mib, ipInCksumErrs);
14120 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14121 				freemsg(mp);
14122 				ire_refrele(ire);
14123 				return (NULL);
14124 			}
14125 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
14126 			ipha->ipha_hdr_checksum = 0;
14127 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14128 			ip_rput_process_forward(q, mp, ire, ipha,
14129 			    ill, ll_multicast);
14130 			ire_refrele(ire);
14131 			return (NULL);
14132 		}
14133 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14134 		    ntohl(ire->ire_addr)));
14135 	}
14136 
14137 
14138 	/* Restore any hardware checksum flags */
14139 	DB_CKSUMFLAGS(mp) = hcksumflags;
14140 	return (ire);
14141 }
14142 
14143 /* ARGSUSED */
14144 static boolean_t
14145 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14146     int *ll_multicast, ipaddr_t *dstp)
14147 {
14148 	/*
14149 	 * Forward packets only if we have joined the allmulti
14150 	 * group on this interface.
14151 	 */
14152 	if (ip_g_mrouter && ill->ill_join_allmulti) {
14153 		int retval;
14154 
14155 		/*
14156 		 * Clear the indication that this may have hardware
14157 		 * checksum as we are not using it.
14158 		 */
14159 		DB_CKSUMFLAGS(mp) = 0;
14160 		retval = ip_mforward(ill, ipha, mp);
14161 		/* ip_mforward updates mib variables if needed */
14162 		/* clear b_prev - used by ip_mroute_decap */
14163 		mp->b_prev = NULL;
14164 
14165 		switch (retval) {
14166 		case 0:
14167 			/*
14168 			 * pkt is okay and arrived on phyint.
14169 			 *
14170 			 * If we are running as a multicast router
14171 			 * we need to see all IGMP and/or PIM packets.
14172 			 */
14173 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14174 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14175 				goto done;
14176 			}
14177 			break;
14178 		case -1:
14179 			/* pkt is mal-formed, toss it */
14180 			goto drop_pkt;
14181 		case 1:
14182 			/* pkt is okay and arrived on a tunnel */
14183 			/*
14184 			 * If we are running a multicast router
14185 			 *  we need to see all igmp packets.
14186 			 */
14187 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14188 				*dstp = INADDR_BROADCAST;
14189 				*ll_multicast = 1;
14190 				return (B_FALSE);
14191 			}
14192 
14193 			goto drop_pkt;
14194 		}
14195 	}
14196 
14197 	ILM_WALKER_HOLD(ill);
14198 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14199 		/*
14200 		 * This might just be caused by the fact that
14201 		 * multiple IP Multicast addresses map to the same
14202 		 * link layer multicast - no need to increment counter!
14203 		 */
14204 		ILM_WALKER_RELE(ill);
14205 		freemsg(mp);
14206 		return (B_TRUE);
14207 	}
14208 	ILM_WALKER_RELE(ill);
14209 done:
14210 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14211 	/*
14212 	 * This assumes the we deliver to all streams for multicast
14213 	 * and broadcast packets.
14214 	 */
14215 	*dstp = INADDR_BROADCAST;
14216 	*ll_multicast = 1;
14217 	return (B_FALSE);
14218 drop_pkt:
14219 	ip2dbg(("ip_rput: drop pkt\n"));
14220 	freemsg(mp);
14221 	return (B_TRUE);
14222 }
14223 
14224 static boolean_t
14225 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14226     int *ll_multicast, mblk_t **mpp)
14227 {
14228 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14229 	boolean_t must_copy = B_FALSE;
14230 	struct iocblk   *iocp;
14231 	ipha_t		*ipha;
14232 
14233 #define	rptr    ((uchar_t *)ipha)
14234 
14235 	first_mp = *first_mpp;
14236 	mp = *mpp;
14237 
14238 	ASSERT(first_mp == mp);
14239 
14240 	/*
14241 	 * if db_ref > 1 then copymsg and free original. Packet may be
14242 	 * changed and do not want other entity who has a reference to this
14243 	 * message to trip over the changes. This is a blind change because
14244 	 * trying to catch all places that might change packet is too
14245 	 * difficult (since it may be a module above this one)
14246 	 *
14247 	 * This corresponds to the non-fast path case. We walk down the full
14248 	 * chain in this case, and check the db_ref count of all the dblks,
14249 	 * and do a copymsg if required. It is possible that the db_ref counts
14250 	 * of the data blocks in the mblk chain can be different.
14251 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14252 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14253 	 * 'snoop' is running.
14254 	 */
14255 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14256 		if (mp1->b_datap->db_ref > 1) {
14257 			must_copy = B_TRUE;
14258 			break;
14259 		}
14260 	}
14261 
14262 	if (must_copy) {
14263 		mp1 = copymsg(mp);
14264 		if (mp1 == NULL) {
14265 			for (mp1 = mp; mp1 != NULL;
14266 			    mp1 = mp1->b_cont) {
14267 				mp1->b_next = NULL;
14268 				mp1->b_prev = NULL;
14269 			}
14270 			freemsg(mp);
14271 			BUMP_MIB(&ip_mib, ipInDiscards);
14272 			return (B_TRUE);
14273 		}
14274 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14275 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14276 			/* Copy b_prev - used by ip_mroute_decap */
14277 			to_mp->b_prev = from_mp->b_prev;
14278 			from_mp->b_prev = NULL;
14279 		}
14280 		*first_mpp = first_mp = mp1;
14281 		freemsg(mp);
14282 		mp = mp1;
14283 		*mpp = mp1;
14284 	}
14285 
14286 	ipha = (ipha_t *)mp->b_rptr;
14287 
14288 	/*
14289 	 * previous code has a case for M_DATA.
14290 	 * We want to check how that happens.
14291 	 */
14292 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14293 	switch (first_mp->b_datap->db_type) {
14294 	case M_PROTO:
14295 	case M_PCPROTO:
14296 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14297 		    DL_UNITDATA_IND) {
14298 			/* Go handle anything other than data elsewhere. */
14299 			ip_rput_dlpi(q, mp);
14300 			return (B_TRUE);
14301 		}
14302 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14303 		/* Ditch the DLPI header. */
14304 		mp1 = mp->b_cont;
14305 		ASSERT(first_mp == mp);
14306 		*first_mpp = mp1;
14307 		freeb(mp);
14308 		*mpp = mp1;
14309 		return (B_FALSE);
14310 	case M_IOCACK:
14311 		ip1dbg(("got iocack "));
14312 		iocp = (struct iocblk *)mp->b_rptr;
14313 		switch (iocp->ioc_cmd) {
14314 		case DL_IOC_HDR_INFO:
14315 			ill = (ill_t *)q->q_ptr;
14316 			ill_fastpath_ack(ill, mp);
14317 			return (B_TRUE);
14318 		case SIOCSTUNPARAM:
14319 		case OSIOCSTUNPARAM:
14320 			/* Go through qwriter_ip */
14321 			break;
14322 		case SIOCGTUNPARAM:
14323 		case OSIOCGTUNPARAM:
14324 			ip_rput_other(NULL, q, mp, NULL);
14325 			return (B_TRUE);
14326 		default:
14327 			putnext(q, mp);
14328 			return (B_TRUE);
14329 		}
14330 		/* FALLTHRU */
14331 	case M_ERROR:
14332 	case M_HANGUP:
14333 		/*
14334 		 * Since this is on the ill stream we unconditionally
14335 		 * bump up the refcount
14336 		 */
14337 		ill_refhold(ill);
14338 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14339 		    B_FALSE);
14340 		return (B_TRUE);
14341 	case M_CTL:
14342 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14343 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14344 			IPHADA_M_CTL)) {
14345 			/*
14346 			 * It's an IPsec accelerated packet.
14347 			 * Make sure that the ill from which we received the
14348 			 * packet has enabled IPsec hardware acceleration.
14349 			 */
14350 			if (!(ill->ill_capabilities &
14351 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14352 				/* IPsec kstats: bean counter */
14353 				freemsg(mp);
14354 				return (B_TRUE);
14355 			}
14356 
14357 			/*
14358 			 * Make mp point to the mblk following the M_CTL,
14359 			 * then process according to type of mp.
14360 			 * After this processing, first_mp will point to
14361 			 * the data-attributes and mp to the pkt following
14362 			 * the M_CTL.
14363 			 */
14364 			mp = first_mp->b_cont;
14365 			if (mp == NULL) {
14366 				freemsg(first_mp);
14367 				return (B_TRUE);
14368 			}
14369 			/*
14370 			 * A Hardware Accelerated packet can only be M_DATA
14371 			 * ESP or AH packet.
14372 			 */
14373 			if (mp->b_datap->db_type != M_DATA) {
14374 				/* non-M_DATA IPsec accelerated packet */
14375 				IPSECHW_DEBUG(IPSECHW_PKT,
14376 				    ("non-M_DATA IPsec accelerated pkt\n"));
14377 				freemsg(first_mp);
14378 				return (B_TRUE);
14379 			}
14380 			ipha = (ipha_t *)mp->b_rptr;
14381 			if (ipha->ipha_protocol != IPPROTO_AH &&
14382 			    ipha->ipha_protocol != IPPROTO_ESP) {
14383 				IPSECHW_DEBUG(IPSECHW_PKT,
14384 				    ("non-M_DATA IPsec accelerated pkt\n"));
14385 				freemsg(first_mp);
14386 				return (B_TRUE);
14387 			}
14388 			*mpp = mp;
14389 			return (B_FALSE);
14390 		}
14391 		putnext(q, mp);
14392 		return (B_TRUE);
14393 	case M_FLUSH:
14394 		if (*mp->b_rptr & FLUSHW) {
14395 			*mp->b_rptr &= ~FLUSHR;
14396 			qreply(q, mp);
14397 			return (B_TRUE);
14398 		}
14399 		freemsg(mp);
14400 		return (B_TRUE);
14401 	case M_IOCNAK:
14402 		ip1dbg(("got iocnak "));
14403 		iocp = (struct iocblk *)mp->b_rptr;
14404 		switch (iocp->ioc_cmd) {
14405 		case DL_IOC_HDR_INFO:
14406 		case SIOCSTUNPARAM:
14407 		case OSIOCSTUNPARAM:
14408 			/*
14409 			 * Since this is on the ill stream we unconditionally
14410 			 * bump up the refcount
14411 			 */
14412 			ill_refhold(ill);
14413 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14414 			    CUR_OP, B_FALSE);
14415 			return (B_TRUE);
14416 		case SIOCGTUNPARAM:
14417 		case OSIOCGTUNPARAM:
14418 			ip_rput_other(NULL, q, mp, NULL);
14419 			return (B_TRUE);
14420 		default:
14421 			break;
14422 		}
14423 		/* FALLTHRU */
14424 	default:
14425 		putnext(q, mp);
14426 		return (B_TRUE);
14427 	}
14428 }
14429 
14430 /* Read side put procedure.  Packets coming from the wire arrive here. */
14431 void
14432 ip_rput(queue_t *q, mblk_t *mp)
14433 {
14434 	ill_t	*ill;
14435 	mblk_t	 *dmp = NULL;
14436 
14437 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14438 
14439 	ill = (ill_t *)q->q_ptr;
14440 
14441 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14442 		union DL_primitives *dl;
14443 
14444 		/*
14445 		 * Things are opening or closing. Only accept DLPI control
14446 		 * messages. In the open case, the ill->ill_ipif has not yet
14447 		 * been created. In the close case, things hanging off the
14448 		 * ill could have been freed already. In either case it
14449 		 * may not be safe to proceed further.
14450 		 */
14451 
14452 		dl = (union DL_primitives *)mp->b_rptr;
14453 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14454 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14455 			/*
14456 			 * Also SIOC[GS]TUN* ioctls can come here.
14457 			 */
14458 			inet_freemsg(mp);
14459 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14460 			    "ip_input_end: q %p (%S)", q, "uninit");
14461 			return;
14462 		}
14463 	}
14464 
14465 	/*
14466 	 * if db_ref > 1 then copymsg and free original. Packet may be
14467 	 * changed and we do not want the other entity who has a reference to
14468 	 * this message to trip over the changes. This is a blind change because
14469 	 * trying to catch all places that might change the packet is too
14470 	 * difficult.
14471 	 *
14472 	 * This corresponds to the fast path case, where we have a chain of
14473 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14474 	 * in the mblk chain. There doesn't seem to be a reason why a device
14475 	 * driver would send up data with varying db_ref counts in the mblk
14476 	 * chain. In any case the Fast path is a private interface, and our
14477 	 * drivers don't do such a thing. Given the above assumption, there is
14478 	 * no need to walk down the entire mblk chain (which could have a
14479 	 * potential performance problem)
14480 	 */
14481 	if (mp->b_datap->db_ref > 1) {
14482 		mblk_t  *mp1;
14483 		boolean_t adjusted = B_FALSE;
14484 		IP_STAT(ip_db_ref);
14485 
14486 		/*
14487 		 * The IP_RECVSLLA option depends on having the link layer
14488 		 * header. First check that:
14489 		 * a> the underlying device is of type ether, since this
14490 		 * option is currently supported only over ethernet.
14491 		 * b> there is enough room to copy over the link layer header.
14492 		 *
14493 		 * Once the checks are done, adjust rptr so that the link layer
14494 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14495 		 * be returned by some non-ethernet drivers but in this case the
14496 		 * second check will fail.
14497 		 */
14498 		if (ill->ill_type == IFT_ETHER &&
14499 		    (mp->b_rptr - mp->b_datap->db_base) >=
14500 		    sizeof (struct ether_header)) {
14501 			mp->b_rptr -= sizeof (struct ether_header);
14502 			adjusted = B_TRUE;
14503 		}
14504 		mp1 = copymsg(mp);
14505 		if (mp1 == NULL) {
14506 			mp->b_next = NULL;
14507 			/* clear b_prev - used by ip_mroute_decap */
14508 			mp->b_prev = NULL;
14509 			freemsg(mp);
14510 			BUMP_MIB(&ip_mib, ipInDiscards);
14511 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14512 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14513 			return;
14514 		}
14515 		if (adjusted) {
14516 			/*
14517 			 * Copy is done. Restore the pointer in the _new_ mblk
14518 			 */
14519 			mp1->b_rptr += sizeof (struct ether_header);
14520 		}
14521 		/* Copy b_prev - used by ip_mroute_decap */
14522 		mp1->b_prev = mp->b_prev;
14523 		mp->b_prev = NULL;
14524 		freemsg(mp);
14525 		mp = mp1;
14526 	}
14527 	if (DB_TYPE(mp) == M_DATA) {
14528 		dmp = mp;
14529 	} else if (DB_TYPE(mp) == M_PROTO &&
14530 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14531 		dmp = mp->b_cont;
14532 	}
14533 	if (dmp != NULL) {
14534 		/*
14535 		 * IP header ptr not aligned?
14536 		 * OR IP header not complete in first mblk
14537 		 */
14538 		if (!OK_32PTR(dmp->b_rptr) ||
14539 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14540 			if (!ip_check_and_align_header(q, dmp))
14541 				return;
14542 		}
14543 	}
14544 
14545 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14546 	    "ip_rput_end: q %p (%S)", q, "end");
14547 
14548 	ip_input(ill, NULL, mp, NULL);
14549 }
14550 
14551 /*
14552  * Direct read side procedure capable of dealing with chains. GLDv3 based
14553  * drivers call this function directly with mblk chains while STREAMS
14554  * read side procedure ip_rput() calls this for single packet with ip_ring
14555  * set to NULL to process one packet at a time.
14556  *
14557  * The ill will always be valid if this function is called directly from
14558  * the driver.
14559  *
14560  * If ip_input() is called from GLDv3:
14561  *
14562  *   - This must be a non-VLAN IP stream.
14563  *   - 'mp' is either an untagged or a special priority-tagged packet.
14564  *   - Any VLAN tag that was in the MAC header has been stripped.
14565  *
14566  * Thus, there is no need to adjust b_rptr in this function.
14567  */
14568 /* ARGSUSED */
14569 void
14570 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14571     struct mac_header_info_s *mhip)
14572 {
14573 	ipaddr_t		dst = NULL;
14574 	ipaddr_t		prev_dst;
14575 	ire_t			*ire = NULL;
14576 	ipha_t			*ipha;
14577 	uint_t			pkt_len;
14578 	ssize_t			len;
14579 	uint_t			opt_len;
14580 	int			ll_multicast;
14581 	int			cgtp_flt_pkt;
14582 	queue_t			*q = ill->ill_rq;
14583 	squeue_t		*curr_sqp = NULL;
14584 	mblk_t 			*head = NULL;
14585 	mblk_t			*tail = NULL;
14586 	mblk_t			*first_mp;
14587 	mblk_t 			*mp;
14588 	int			cnt = 0;
14589 
14590 	ASSERT(mp_chain != NULL);
14591 	ASSERT(ill != NULL);
14592 
14593 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14594 
14595 #define	rptr	((uchar_t *)ipha)
14596 
14597 	while (mp_chain != NULL) {
14598 		first_mp = mp = mp_chain;
14599 		mp_chain = mp_chain->b_next;
14600 		mp->b_next = NULL;
14601 		ll_multicast = 0;
14602 
14603 		/*
14604 		 * We do ire caching from one iteration to
14605 		 * another. In the event the packet chain contains
14606 		 * all packets from the same dst, this caching saves
14607 		 * an ire_cache_lookup for each of the succeeding
14608 		 * packets in a packet chain.
14609 		 */
14610 		prev_dst = dst;
14611 
14612 		/*
14613 		 * ip_input fast path
14614 		 */
14615 
14616 		/* mblk type is not M_DATA */
14617 		if (mp->b_datap->db_type != M_DATA) {
14618 			if (ip_rput_process_notdata(q, &first_mp, ill,
14619 			    &ll_multicast, &mp))
14620 				continue;
14621 		}
14622 
14623 		/* Make sure its an M_DATA and that its aligned */
14624 		ASSERT(mp->b_datap->db_type == M_DATA);
14625 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14626 
14627 		ipha = (ipha_t *)mp->b_rptr;
14628 		len = mp->b_wptr - rptr;
14629 
14630 		BUMP_MIB(&ip_mib, ipInReceives);
14631 
14632 
14633 		/* multiple mblk or too short */
14634 		pkt_len = ntohs(ipha->ipha_length);
14635 		len -= pkt_len;
14636 		if (len != 0) {
14637 			/*
14638 			 * Make sure we have data length consistent
14639 			 * with the IP header.
14640 			 */
14641 			if (mp->b_cont == NULL) {
14642 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14643 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14644 					ip2dbg(("ip_input: drop pkt\n"));
14645 					freemsg(mp);
14646 					continue;
14647 				}
14648 				mp->b_wptr = rptr + pkt_len;
14649 			} else if (len += msgdsize(mp->b_cont)) {
14650 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14651 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14652 					ip2dbg(("ip_input: drop pkt\n"));
14653 					freemsg(mp);
14654 					continue;
14655 				}
14656 				(void) adjmsg(mp, -len);
14657 				IP_STAT(ip_multimblk3);
14658 			}
14659 		}
14660 
14661 		/* Obtain the dst of the current packet */
14662 		dst = ipha->ipha_dst;
14663 
14664 		if (IP_LOOPBACK_ADDR(dst) ||
14665 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14666 			BUMP_MIB(&ip_mib, ipInAddrErrors);
14667 			cmn_err(CE_CONT, "dst %X src %X\n",
14668 			    dst, ipha->ipha_src);
14669 			freemsg(mp);
14670 			continue;
14671 		}
14672 
14673 		/*
14674 		 * The event for packets being received from a 'physical'
14675 		 * interface is placed after validation of the source and/or
14676 		 * destination address as being local so that packets can be
14677 		 * redirected to loopback addresses using ipnat.
14678 		 */
14679 		DTRACE_PROBE4(ip4__physical__in__start,
14680 		    ill_t *, ill, ill_t *, NULL,
14681 		    ipha_t *, ipha, mblk_t *, first_mp);
14682 
14683 		FW_HOOKS(ip4_physical_in_event, ipv4firewall_physical_in,
14684 		    ill, NULL, ipha, first_mp, mp);
14685 
14686 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14687 
14688 		if (first_mp == NULL) {
14689 			continue;
14690 		}
14691 		dst = ipha->ipha_dst;
14692 
14693 		/*
14694 		 * Attach any necessary label information to
14695 		 * this packet
14696 		 */
14697 		if (is_system_labeled() &&
14698 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14699 			BUMP_MIB(&ip_mib, ipInDiscards);
14700 			freemsg(mp);
14701 			continue;
14702 		}
14703 
14704 		/*
14705 		 * Reuse the cached ire only if the ipha_dst of the previous
14706 		 * packet is the same as the current packet AND it is not
14707 		 * INADDR_ANY.
14708 		 */
14709 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14710 		    (ire != NULL)) {
14711 			ire_refrele(ire);
14712 			ire = NULL;
14713 		}
14714 		opt_len = ipha->ipha_version_and_hdr_length -
14715 		    IP_SIMPLE_HDR_VERSION;
14716 
14717 		/*
14718 		 * Check to see if we can take the fastpath.
14719 		 * That is possible if the following conditions are met
14720 		 *	o Tsol disabled
14721 		 *	o CGTP disabled
14722 		 *	o ipp_action_count is 0
14723 		 *	o Mobile IP not running
14724 		 *	o no options in the packet
14725 		 *	o not a RSVP packet
14726 		 * 	o not a multicast packet
14727 		 */
14728 		if (!is_system_labeled() &&
14729 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14730 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14731 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14732 		    !ll_multicast && !CLASSD(dst)) {
14733 			if (ire == NULL)
14734 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14735 
14736 			/* incoming packet is for forwarding */
14737 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14738 				ire = ip_fast_forward(ire, dst, ill, mp);
14739 				continue;
14740 			}
14741 			/* incoming packet is for local consumption */
14742 			if (ire->ire_type & IRE_LOCAL)
14743 				goto local;
14744 		}
14745 
14746 		/*
14747 		 * Disable ire caching for anything more complex
14748 		 * than the simple fast path case we checked for above.
14749 		 */
14750 		if (ire != NULL) {
14751 			ire_refrele(ire);
14752 			ire = NULL;
14753 		}
14754 
14755 		/* Full-blown slow path */
14756 		if (opt_len != 0) {
14757 			if (len != 0)
14758 				IP_STAT(ip_multimblk4);
14759 			else
14760 				IP_STAT(ip_ipoptions);
14761 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
14762 				continue;
14763 		}
14764 
14765 		/*
14766 		 * Invoke the CGTP (multirouting) filtering module to process
14767 		 * the incoming packet. Packets identified as duplicates
14768 		 * must be discarded. Filtering is active only if the
14769 		 * the ip_cgtp_filter ndd variable is non-zero.
14770 		 */
14771 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14772 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
14773 			cgtp_flt_pkt =
14774 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14775 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14776 				freemsg(first_mp);
14777 				continue;
14778 			}
14779 		}
14780 
14781 		/*
14782 		 * If rsvpd is running, let RSVP daemon handle its processing
14783 		 * and forwarding of RSVP multicast/unicast packets.
14784 		 * If rsvpd is not running but mrouted is running, RSVP
14785 		 * multicast packets are forwarded as multicast traffic
14786 		 * and RSVP unicast packets are forwarded by unicast router.
14787 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14788 		 * packets are not forwarded, but the unicast packets are
14789 		 * forwarded like unicast traffic.
14790 		 */
14791 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14792 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
14793 			/* RSVP packet and rsvpd running. Treat as ours */
14794 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14795 			/*
14796 			 * This assumes that we deliver to all streams for
14797 			 * multicast and broadcast packets.
14798 			 * We have to force ll_multicast to 1 to handle the
14799 			 * M_DATA messages passed in from ip_mroute_decap.
14800 			 */
14801 			dst = INADDR_BROADCAST;
14802 			ll_multicast = 1;
14803 		} else if (CLASSD(dst)) {
14804 			/* packet is multicast */
14805 			mp->b_next = NULL;
14806 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14807 			    &ll_multicast, &dst))
14808 				continue;
14809 		}
14810 
14811 
14812 		/*
14813 		 * Check if the packet is coming from the Mobile IP
14814 		 * forward tunnel interface
14815 		 */
14816 		if (ill->ill_srcif_refcnt > 0) {
14817 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
14818 			    NULL, ill, MATCH_IRE_TYPE);
14819 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
14820 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
14821 
14822 				/* We need to resolve the link layer info */
14823 				ire_refrele(ire);
14824 				ire = NULL;
14825 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
14826 				    ll_multicast, dst);
14827 				continue;
14828 			}
14829 		}
14830 
14831 		if (ire == NULL) {
14832 			ire = ire_cache_lookup(dst, ALL_ZONES,
14833 			    MBLK_GETLABEL(mp));
14834 		}
14835 
14836 		/*
14837 		 * If mipagent is running and reverse tunnel is created as per
14838 		 * mobile node request, then any packet coming through the
14839 		 * incoming interface from the mobile-node, should be reverse
14840 		 * tunneled to it's home agent except those that are destined
14841 		 * to foreign agent only.
14842 		 * This needs source address based ire lookup. The routing
14843 		 * entries for source address based lookup are only created by
14844 		 * mipagent program only when a reverse tunnel is created.
14845 		 * Reference : RFC2002, RFC2344
14846 		 */
14847 		if (ill->ill_mrtun_refcnt > 0) {
14848 			ipaddr_t	srcaddr;
14849 			ire_t		*tmp_ire;
14850 
14851 			tmp_ire = ire;	/* Save, we might need it later */
14852 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14853 			    ire->ire_type != IRE_BROADCAST)) {
14854 				srcaddr = ipha->ipha_src;
14855 				ire = ire_mrtun_lookup(srcaddr, ill);
14856 				if (ire != NULL) {
14857 					/*
14858 					 * Should not be getting iphada packet
14859 					 * here. we should only get those for
14860 					 * IRE_LOCAL traffic, excluded above.
14861 					 * Fail-safe (drop packet) in the event
14862 					 * hardware is misbehaving.
14863 					 */
14864 					if (first_mp != mp) {
14865 						/* IPsec KSTATS: beancount me */
14866 						freemsg(first_mp);
14867 					} else {
14868 						/*
14869 						 * This packet must be forwarded
14870 						 * to Reverse Tunnel
14871 						 */
14872 						ip_mrtun_forward(ire, ill, mp);
14873 					}
14874 					ire_refrele(ire);
14875 					ire = NULL;
14876 					if (tmp_ire != NULL) {
14877 						ire_refrele(tmp_ire);
14878 						tmp_ire = NULL;
14879 					}
14880 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14881 					    "ip_input_end: q %p (%S)",
14882 					    q, "uninit");
14883 					continue;
14884 				}
14885 			}
14886 			/*
14887 			 * If this packet is from a non-mobilenode  or a
14888 			 * mobile-node which does not request reverse
14889 			 * tunnel service
14890 			 */
14891 			ire = tmp_ire;
14892 		}
14893 
14894 
14895 		/*
14896 		 * If we reach here that means the incoming packet satisfies
14897 		 * one of the following conditions:
14898 		 *   - packet is from a mobile node which does not request
14899 		 *	reverse tunnel
14900 		 *   - packet is from a non-mobile node, which is the most
14901 		 *	common case
14902 		 *   - packet is from a reverse tunnel enabled mobile node
14903 		 *	and destined to foreign agent only
14904 		 */
14905 
14906 		if (ire == NULL) {
14907 			/*
14908 			 * No IRE for this destination, so it can't be for us.
14909 			 * Unless we are forwarding, drop the packet.
14910 			 * We have to let source routed packets through
14911 			 * since we don't yet know if they are 'ping -l'
14912 			 * packets i.e. if they will go out over the
14913 			 * same interface as they came in on.
14914 			 */
14915 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14916 			if (ire == NULL)
14917 				continue;
14918 		}
14919 
14920 		/*
14921 		 * Broadcast IRE may indicate either broadcast or
14922 		 * multicast packet
14923 		 */
14924 		if (ire->ire_type == IRE_BROADCAST) {
14925 			/*
14926 			 * Skip broadcast checks if packet is UDP multicast;
14927 			 * we'd rather not enter ip_rput_process_broadcast()
14928 			 * unless the packet is broadcast for real, since
14929 			 * that routine is a no-op for multicast.
14930 			 */
14931 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14932 			    !CLASSD(ipha->ipha_dst)) {
14933 				ire = ip_rput_process_broadcast(&q, mp,
14934 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14935 				    ll_multicast);
14936 				if (ire == NULL)
14937 					continue;
14938 			}
14939 		} else if (ire->ire_stq != NULL) {
14940 			/* fowarding? */
14941 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14942 			    ll_multicast);
14943 			/* ip_rput_process_forward consumed the packet */
14944 			continue;
14945 		}
14946 
14947 local:
14948 		/* packet not for us */
14949 		if (ire->ire_rfq != q) {
14950 			if (ip_rput_notforus(&q, mp, ire, ill))
14951 				continue;
14952 		}
14953 
14954 		switch (ipha->ipha_protocol) {
14955 		case IPPROTO_TCP:
14956 			ASSERT(first_mp == mp);
14957 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14958 				mp, 0, q, ip_ring)) != NULL) {
14959 				if (curr_sqp == NULL) {
14960 					curr_sqp = GET_SQUEUE(mp);
14961 					ASSERT(cnt == 0);
14962 					cnt++;
14963 					head = tail = mp;
14964 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14965 					ASSERT(tail != NULL);
14966 					cnt++;
14967 					tail->b_next = mp;
14968 					tail = mp;
14969 				} else {
14970 					/*
14971 					 * A different squeue. Send the
14972 					 * chain for the previous squeue on
14973 					 * its way. This shouldn't happen
14974 					 * often unless interrupt binding
14975 					 * changes.
14976 					 */
14977 					IP_STAT(ip_input_multi_squeue);
14978 					squeue_enter_chain(curr_sqp, head,
14979 					    tail, cnt, SQTAG_IP_INPUT);
14980 					curr_sqp = GET_SQUEUE(mp);
14981 					head = mp;
14982 					tail = mp;
14983 					cnt = 1;
14984 				}
14985 			}
14986 			continue;
14987 		case IPPROTO_UDP:
14988 			ASSERT(first_mp == mp);
14989 			ip_udp_input(q, mp, ipha, ire, ill);
14990 			continue;
14991 		case IPPROTO_SCTP:
14992 			ASSERT(first_mp == mp);
14993 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14994 			    q, dst);
14995 			/* ire has been released by ip_sctp_input */
14996 			ire = NULL;
14997 			continue;
14998 		default:
14999 			ip_proto_input(q, first_mp, ipha, ire, ill);
15000 			continue;
15001 		}
15002 	}
15003 
15004 	if (ire != NULL)
15005 		ire_refrele(ire);
15006 
15007 	if (head != NULL)
15008 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15009 
15010 	/*
15011 	 * This code is there just to make netperf/ttcp look good.
15012 	 *
15013 	 * Its possible that after being in polling mode (and having cleared
15014 	 * the backlog), squeues have turned the interrupt frequency higher
15015 	 * to improve latency at the expense of more CPU utilization (less
15016 	 * packets per interrupts or more number of interrupts). Workloads
15017 	 * like ttcp/netperf do manage to tickle polling once in a while
15018 	 * but for the remaining time, stay in higher interrupt mode since
15019 	 * their packet arrival rate is pretty uniform and this shows up
15020 	 * as higher CPU utilization. Since people care about CPU utilization
15021 	 * while running netperf/ttcp, turn the interrupt frequency back to
15022 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15023 	 */
15024 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15025 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15026 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15027 			ip_ring->rr_blank(ip_ring->rr_handle,
15028 			    ip_ring->rr_normal_blank_time,
15029 			    ip_ring->rr_normal_pkt_cnt);
15030 		}
15031 	}
15032 
15033 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15034 	    "ip_input_end: q %p (%S)", q, "end");
15035 #undef	rptr
15036 }
15037 
15038 static void
15039 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15040     t_uscalar_t err)
15041 {
15042 	if (dl_err == DL_SYSERR) {
15043 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15044 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15045 		    ill->ill_name, dlpi_prim_str(prim), err);
15046 		return;
15047 	}
15048 
15049 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15050 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15051 	    dlpi_err_str(dl_err));
15052 }
15053 
15054 /*
15055  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15056  * than DL_UNITDATA_IND messages. If we need to process this message
15057  * exclusively, we call qwriter_ip, in which case we also need to call
15058  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15059  */
15060 void
15061 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15062 {
15063 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15064 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15065 	ill_t		*ill;
15066 
15067 	ip1dbg(("ip_rput_dlpi"));
15068 	ill = (ill_t *)q->q_ptr;
15069 	switch (dloa->dl_primitive) {
15070 	case DL_ERROR_ACK:
15071 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15072 		    "%s (0x%x), unix %u\n", ill->ill_name,
15073 		    dlpi_prim_str(dlea->dl_error_primitive),
15074 		    dlea->dl_error_primitive,
15075 		    dlpi_err_str(dlea->dl_errno),
15076 		    dlea->dl_errno,
15077 		    dlea->dl_unix_errno));
15078 		switch (dlea->dl_error_primitive) {
15079 		case DL_UNBIND_REQ:
15080 			mutex_enter(&ill->ill_lock);
15081 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15082 			cv_signal(&ill->ill_cv);
15083 			mutex_exit(&ill->ill_lock);
15084 			/* FALLTHRU */
15085 		case DL_NOTIFY_REQ:
15086 		case DL_ATTACH_REQ:
15087 		case DL_DETACH_REQ:
15088 		case DL_INFO_REQ:
15089 		case DL_BIND_REQ:
15090 		case DL_ENABMULTI_REQ:
15091 		case DL_PHYS_ADDR_REQ:
15092 		case DL_CAPABILITY_REQ:
15093 		case DL_CONTROL_REQ:
15094 			/*
15095 			 * Refhold the ill to match qwriter_ip which does a
15096 			 * refrele. Since this is on the ill stream we
15097 			 * unconditionally bump up the refcount without
15098 			 * checking for ILL_CAN_LOOKUP
15099 			 */
15100 			ill_refhold(ill);
15101 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15102 			    CUR_OP, B_FALSE);
15103 			return;
15104 		case DL_DISABMULTI_REQ:
15105 			freemsg(mp);	/* Don't want to pass this up */
15106 			return;
15107 		default:
15108 			break;
15109 		}
15110 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15111 		    dlea->dl_errno, dlea->dl_unix_errno);
15112 		freemsg(mp);
15113 		return;
15114 	case DL_INFO_ACK:
15115 	case DL_BIND_ACK:
15116 	case DL_PHYS_ADDR_ACK:
15117 	case DL_NOTIFY_ACK:
15118 	case DL_CAPABILITY_ACK:
15119 	case DL_CONTROL_ACK:
15120 		/*
15121 		 * Refhold the ill to match qwriter_ip which does a refrele
15122 		 * Since this is on the ill stream we unconditionally
15123 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15124 		 */
15125 		ill_refhold(ill);
15126 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15127 		    CUR_OP, B_FALSE);
15128 		return;
15129 	case DL_NOTIFY_IND:
15130 		ill_refhold(ill);
15131 		/*
15132 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15133 		 * relation to the current ioctl in progress (if any). Hence we
15134 		 * pass in NEW_OP in this case.
15135 		 */
15136 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15137 		    NEW_OP, B_FALSE);
15138 		return;
15139 	case DL_OK_ACK:
15140 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15141 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15142 		switch (dloa->dl_correct_primitive) {
15143 		case DL_UNBIND_REQ:
15144 			mutex_enter(&ill->ill_lock);
15145 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15146 			cv_signal(&ill->ill_cv);
15147 			mutex_exit(&ill->ill_lock);
15148 			/* FALLTHRU */
15149 		case DL_ATTACH_REQ:
15150 		case DL_DETACH_REQ:
15151 			/*
15152 			 * Refhold the ill to match qwriter_ip which does a
15153 			 * refrele. Since this is on the ill stream we
15154 			 * unconditionally bump up the refcount
15155 			 */
15156 			ill_refhold(ill);
15157 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15158 			    CUR_OP, B_FALSE);
15159 			return;
15160 		case DL_ENABMULTI_REQ:
15161 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15162 				ill->ill_dlpi_multicast_state = IDS_OK;
15163 			break;
15164 
15165 		}
15166 		break;
15167 	default:
15168 		break;
15169 	}
15170 	freemsg(mp);
15171 }
15172 
15173 /*
15174  * Handling of DLPI messages that require exclusive access to the ipsq.
15175  *
15176  * Need to do ill_pending_mp_release on ioctl completion, which could
15177  * happen here. (along with mi_copy_done)
15178  */
15179 /* ARGSUSED */
15180 static void
15181 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15182 {
15183 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15184 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15185 	int		err = 0;
15186 	ill_t		*ill;
15187 	ipif_t		*ipif = NULL;
15188 	mblk_t		*mp1 = NULL;
15189 	conn_t		*connp = NULL;
15190 	t_uscalar_t	physaddr_req;
15191 	mblk_t		*mp_hw;
15192 	union DL_primitives *dlp;
15193 	boolean_t	success;
15194 	boolean_t	ioctl_aborted = B_FALSE;
15195 	boolean_t	log = B_TRUE;
15196 	hook_nic_event_t	*info;
15197 
15198 	ip1dbg(("ip_rput_dlpi_writer .."));
15199 	ill = (ill_t *)q->q_ptr;
15200 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15201 
15202 	ASSERT(IAM_WRITER_ILL(ill));
15203 
15204 	/*
15205 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15206 	 * both are null or non-null. However we can assert that only
15207 	 * after grabbing the ipsq_lock. So we don't make any assertion
15208 	 * here and in other places in the code.
15209 	 */
15210 	ipif = ipsq->ipsq_pending_ipif;
15211 	/*
15212 	 * The current ioctl could have been aborted by the user and a new
15213 	 * ioctl to bring up another ill could have started. We could still
15214 	 * get a response from the driver later.
15215 	 */
15216 	if (ipif != NULL && ipif->ipif_ill != ill)
15217 		ioctl_aborted = B_TRUE;
15218 
15219 	switch (dloa->dl_primitive) {
15220 	case DL_ERROR_ACK:
15221 		switch (dlea->dl_error_primitive) {
15222 		case DL_UNBIND_REQ:
15223 		case DL_ATTACH_REQ:
15224 		case DL_DETACH_REQ:
15225 		case DL_INFO_REQ:
15226 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15227 			break;
15228 		case DL_NOTIFY_REQ:
15229 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15230 			log = B_FALSE;
15231 			break;
15232 		case DL_PHYS_ADDR_REQ:
15233 			/*
15234 			 * For IPv6 only, there are two additional
15235 			 * phys_addr_req's sent to the driver to get the
15236 			 * IPv6 token and lla. This allows IP to acquire
15237 			 * the hardware address format for a given interface
15238 			 * without having built in knowledge of the hardware
15239 			 * address. ill_phys_addr_pend keeps track of the last
15240 			 * DL_PAR sent so we know which response we are
15241 			 * dealing with. ill_dlpi_done will update
15242 			 * ill_phys_addr_pend when it sends the next req.
15243 			 * We don't complete the IOCTL until all three DL_PARs
15244 			 * have been attempted, so set *_len to 0 and break.
15245 			 */
15246 			physaddr_req = ill->ill_phys_addr_pend;
15247 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15248 			if (physaddr_req == DL_IPV6_TOKEN) {
15249 				ill->ill_token_length = 0;
15250 				log = B_FALSE;
15251 				break;
15252 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15253 				ill->ill_nd_lla_len = 0;
15254 				log = B_FALSE;
15255 				break;
15256 			}
15257 			/*
15258 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15259 			 * We presumably have an IOCTL hanging out waiting
15260 			 * for completion. Find it and complete the IOCTL
15261 			 * with the error noted.
15262 			 * However, ill_dl_phys was called on an ill queue
15263 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15264 			 * set. But the ioctl is known to be pending on ill_wq.
15265 			 */
15266 			if (!ill->ill_ifname_pending)
15267 				break;
15268 			ill->ill_ifname_pending = 0;
15269 			if (!ioctl_aborted)
15270 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15271 			if (mp1 != NULL) {
15272 				/*
15273 				 * This operation (SIOCSLIFNAME) must have
15274 				 * happened on the ill. Assert there is no conn
15275 				 */
15276 				ASSERT(connp == NULL);
15277 				q = ill->ill_wq;
15278 			}
15279 			break;
15280 		case DL_BIND_REQ:
15281 			ill_dlpi_done(ill, DL_BIND_REQ);
15282 			if (ill->ill_ifname_pending)
15283 				break;
15284 			/*
15285 			 * Something went wrong with the bind.  We presumably
15286 			 * have an IOCTL hanging out waiting for completion.
15287 			 * Find it, take down the interface that was coming
15288 			 * up, and complete the IOCTL with the error noted.
15289 			 */
15290 			if (!ioctl_aborted)
15291 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15292 			if (mp1 != NULL) {
15293 				/*
15294 				 * This operation (SIOCSLIFFLAGS) must have
15295 				 * happened from a conn.
15296 				 */
15297 				ASSERT(connp != NULL);
15298 				q = CONNP_TO_WQ(connp);
15299 				if (ill->ill_move_in_progress) {
15300 					ILL_CLEAR_MOVE(ill);
15301 				}
15302 				(void) ipif_down(ipif, NULL, NULL);
15303 				/* error is set below the switch */
15304 			}
15305 			break;
15306 		case DL_ENABMULTI_REQ:
15307 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15308 
15309 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15310 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15311 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15312 				ipif_t *ipif;
15313 
15314 				log = B_FALSE;
15315 				printf("ip: joining multicasts failed (%d)"
15316 				    " on %s - will use link layer "
15317 				    "broadcasts for multicast\n",
15318 				    dlea->dl_errno, ill->ill_name);
15319 
15320 				/*
15321 				 * Set up the multicast mapping alone.
15322 				 * writer, so ok to access ill->ill_ipif
15323 				 * without any lock.
15324 				 */
15325 				ipif = ill->ill_ipif;
15326 				mutex_enter(&ill->ill_phyint->phyint_lock);
15327 				ill->ill_phyint->phyint_flags |=
15328 				    PHYI_MULTI_BCAST;
15329 				mutex_exit(&ill->ill_phyint->phyint_lock);
15330 
15331 				if (!ill->ill_isv6) {
15332 					(void) ipif_arp_setup_multicast(ipif,
15333 					    NULL);
15334 				} else {
15335 					(void) ipif_ndp_setup_multicast(ipif,
15336 					    NULL);
15337 				}
15338 			}
15339 			freemsg(mp);	/* Don't want to pass this up */
15340 			return;
15341 		case DL_CAPABILITY_REQ:
15342 		case DL_CONTROL_REQ:
15343 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15344 			    "DL_CAPABILITY/CONTROL REQ\n"));
15345 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15346 			ill->ill_dlpi_capab_state = IDS_FAILED;
15347 			freemsg(mp);
15348 			return;
15349 		}
15350 		/*
15351 		 * Note the error for IOCTL completion (mp1 is set when
15352 		 * ready to complete ioctl). If ill_ifname_pending_err is
15353 		 * set, an error occured during plumbing (ill_ifname_pending),
15354 		 * so we want to report that error.
15355 		 *
15356 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15357 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15358 		 * expected to get errack'd if the driver doesn't support
15359 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15360 		 * if these error conditions are encountered.
15361 		 */
15362 		if (mp1 != NULL) {
15363 			if (ill->ill_ifname_pending_err != 0)  {
15364 				err = ill->ill_ifname_pending_err;
15365 				ill->ill_ifname_pending_err = 0;
15366 			} else {
15367 				err = dlea->dl_unix_errno ?
15368 				    dlea->dl_unix_errno : ENXIO;
15369 			}
15370 		/*
15371 		 * If we're plumbing an interface and an error hasn't already
15372 		 * been saved, set ill_ifname_pending_err to the error passed
15373 		 * up. Ignore the error if log is B_FALSE (see comment above).
15374 		 */
15375 		} else if (log && ill->ill_ifname_pending &&
15376 		    ill->ill_ifname_pending_err == 0) {
15377 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15378 			dlea->dl_unix_errno : ENXIO;
15379 		}
15380 
15381 		if (log)
15382 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15383 			    dlea->dl_errno, dlea->dl_unix_errno);
15384 		break;
15385 	case DL_CAPABILITY_ACK: {
15386 		boolean_t reneg_flag = B_FALSE;
15387 		/* Call a routine to handle this one. */
15388 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15389 		/*
15390 		 * Check if the ACK is due to renegotiation case since we
15391 		 * will need to send a new CAPABILITY_REQ later.
15392 		 */
15393 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15394 			/* This is the ack for a renogiation case */
15395 			reneg_flag = B_TRUE;
15396 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15397 		}
15398 		ill_capability_ack(ill, mp);
15399 		if (reneg_flag)
15400 			ill_capability_probe(ill);
15401 		break;
15402 	}
15403 	case DL_CONTROL_ACK:
15404 		/* We treat all of these as "fire and forget" */
15405 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15406 		break;
15407 	case DL_INFO_ACK:
15408 		/* Call a routine to handle this one. */
15409 		ill_dlpi_done(ill, DL_INFO_REQ);
15410 		ip_ll_subnet_defaults(ill, mp);
15411 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15412 		return;
15413 	case DL_BIND_ACK:
15414 		/*
15415 		 * We should have an IOCTL waiting on this unless
15416 		 * sent by ill_dl_phys, in which case just return
15417 		 */
15418 		ill_dlpi_done(ill, DL_BIND_REQ);
15419 		if (ill->ill_ifname_pending)
15420 			break;
15421 
15422 		if (!ioctl_aborted)
15423 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15424 		if (mp1 == NULL)
15425 			break;
15426 		ASSERT(connp != NULL);
15427 		q = CONNP_TO_WQ(connp);
15428 
15429 		/*
15430 		 * We are exclusive. So nothing can change even after
15431 		 * we get the pending mp. If need be we can put it back
15432 		 * and restart, as in calling ipif_arp_up()  below.
15433 		 */
15434 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15435 
15436 		mutex_enter(&ill->ill_lock);
15437 
15438 		ill->ill_dl_up = 1;
15439 
15440 		if ((info = ill->ill_nic_event_info) != NULL) {
15441 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15442 			    "attached for %s\n", info->hne_event,
15443 			    ill->ill_name));
15444 			if (info->hne_data != NULL)
15445 				kmem_free(info->hne_data, info->hne_datalen);
15446 			kmem_free(info, sizeof (hook_nic_event_t));
15447 		}
15448 
15449 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15450 		if (info != NULL) {
15451 			info->hne_nic = ill->ill_phyint->phyint_ifindex;
15452 			info->hne_lif = 0;
15453 			info->hne_event = NE_UP;
15454 			info->hne_data = NULL;
15455 			info->hne_datalen = 0;
15456 			info->hne_family = ill->ill_isv6 ? ipv6 : ipv4;
15457 		} else
15458 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15459 			    "event information for %s (ENOMEM)\n",
15460 			    ill->ill_name));
15461 
15462 		ill->ill_nic_event_info = info;
15463 
15464 		mutex_exit(&ill->ill_lock);
15465 
15466 		/*
15467 		 * Now bring up the resolver; when that is complete, we'll
15468 		 * create IREs.  Note that we intentionally mirror what
15469 		 * ipif_up() would have done, because we got here by way of
15470 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15471 		 */
15472 		if (ill->ill_isv6) {
15473 			/*
15474 			 * v6 interfaces.
15475 			 * Unlike ARP which has to do another bind
15476 			 * and attach, once we get here we are
15477 			 * done with NDP. Except in the case of
15478 			 * ILLF_XRESOLV, in which case we send an
15479 			 * AR_INTERFACE_UP to the external resolver.
15480 			 * If all goes well, the ioctl will complete
15481 			 * in ip_rput(). If there's an error, we
15482 			 * complete it here.
15483 			 */
15484 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15485 			    B_FALSE);
15486 			if (err == 0) {
15487 				if (ill->ill_flags & ILLF_XRESOLV) {
15488 					mutex_enter(&connp->conn_lock);
15489 					mutex_enter(&ill->ill_lock);
15490 					success = ipsq_pending_mp_add(
15491 					    connp, ipif, q, mp1, 0);
15492 					mutex_exit(&ill->ill_lock);
15493 					mutex_exit(&connp->conn_lock);
15494 					if (success) {
15495 						err = ipif_resolver_up(ipif,
15496 						    Res_act_initial);
15497 						if (err == EINPROGRESS) {
15498 							freemsg(mp);
15499 							return;
15500 						}
15501 						ASSERT(err != 0);
15502 						mp1 = ipsq_pending_mp_get(ipsq,
15503 						    &connp);
15504 						ASSERT(mp1 != NULL);
15505 					} else {
15506 						/* conn has started closing */
15507 						err = EINTR;
15508 					}
15509 				} else { /* Non XRESOLV interface */
15510 					(void) ipif_resolver_up(ipif,
15511 					    Res_act_initial);
15512 					err = ipif_up_done_v6(ipif);
15513 				}
15514 			}
15515 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15516 			/*
15517 			 * ARP and other v4 external resolvers.
15518 			 * Leave the pending mblk intact so that
15519 			 * the ioctl completes in ip_rput().
15520 			 */
15521 			mutex_enter(&connp->conn_lock);
15522 			mutex_enter(&ill->ill_lock);
15523 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15524 			mutex_exit(&ill->ill_lock);
15525 			mutex_exit(&connp->conn_lock);
15526 			if (success) {
15527 				err = ipif_resolver_up(ipif, Res_act_initial);
15528 				if (err == EINPROGRESS) {
15529 					freemsg(mp);
15530 					return;
15531 				}
15532 				ASSERT(err != 0);
15533 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15534 			} else {
15535 				/* The conn has started closing */
15536 				err = EINTR;
15537 			}
15538 		} else {
15539 			/*
15540 			 * This one is complete. Reply to pending ioctl.
15541 			 */
15542 			(void) ipif_resolver_up(ipif, Res_act_initial);
15543 			err = ipif_up_done(ipif);
15544 		}
15545 
15546 		if ((err == 0) && (ill->ill_up_ipifs)) {
15547 			err = ill_up_ipifs(ill, q, mp1);
15548 			if (err == EINPROGRESS) {
15549 				freemsg(mp);
15550 				return;
15551 			}
15552 		}
15553 
15554 		if (ill->ill_up_ipifs) {
15555 			ill_group_cleanup(ill);
15556 		}
15557 
15558 		break;
15559 	case DL_NOTIFY_IND: {
15560 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15561 		ire_t *ire;
15562 		boolean_t need_ire_walk_v4 = B_FALSE;
15563 		boolean_t need_ire_walk_v6 = B_FALSE;
15564 
15565 		/*
15566 		 * Change the address everywhere we need to.
15567 		 * What we're getting here is a link-level addr or phys addr.
15568 		 * The new addr is at notify + notify->dl_addr_offset
15569 		 * The address length is notify->dl_addr_length;
15570 		 */
15571 		switch (notify->dl_notification) {
15572 		case DL_NOTE_PHYS_ADDR:
15573 			mp_hw = copyb(mp);
15574 			if (mp_hw == NULL) {
15575 				err = ENOMEM;
15576 				break;
15577 			}
15578 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15579 			/*
15580 			 * We currently don't support changing
15581 			 * the token via DL_NOTIFY_IND.
15582 			 * When we do support it, we have to consider
15583 			 * what the implications are with respect to
15584 			 * the token and the link local address.
15585 			 */
15586 			mutex_enter(&ill->ill_lock);
15587 			if (dlp->notify_ind.dl_data ==
15588 			    DL_IPV6_LINK_LAYER_ADDR) {
15589 				if (ill->ill_nd_lla_mp != NULL)
15590 					freemsg(ill->ill_nd_lla_mp);
15591 				ill->ill_nd_lla_mp = mp_hw;
15592 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15593 				    dlp->notify_ind.dl_addr_offset;
15594 				ill->ill_nd_lla_len =
15595 				    dlp->notify_ind.dl_addr_length -
15596 				    ABS(ill->ill_sap_length);
15597 				mutex_exit(&ill->ill_lock);
15598 				break;
15599 			} else if (dlp->notify_ind.dl_data ==
15600 			    DL_CURR_PHYS_ADDR) {
15601 				if (ill->ill_phys_addr_mp != NULL)
15602 					freemsg(ill->ill_phys_addr_mp);
15603 				ill->ill_phys_addr_mp = mp_hw;
15604 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15605 				    dlp->notify_ind.dl_addr_offset;
15606 				ill->ill_phys_addr_length =
15607 				    dlp->notify_ind.dl_addr_length -
15608 				    ABS(ill->ill_sap_length);
15609 				if (ill->ill_isv6 &&
15610 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15611 					if (ill->ill_nd_lla_mp != NULL)
15612 						freemsg(ill->ill_nd_lla_mp);
15613 					ill->ill_nd_lla_mp = copyb(mp_hw);
15614 					ill->ill_nd_lla = (uchar_t *)
15615 					    ill->ill_nd_lla_mp->b_rptr +
15616 					    dlp->notify_ind.dl_addr_offset;
15617 					ill->ill_nd_lla_len =
15618 					    ill->ill_phys_addr_length;
15619 				}
15620 			}
15621 			mutex_exit(&ill->ill_lock);
15622 			/*
15623 			 * Send out gratuitous arp request for our new
15624 			 * hardware address.
15625 			 */
15626 			for (ipif = ill->ill_ipif; ipif != NULL;
15627 			    ipif = ipif->ipif_next) {
15628 				if (!(ipif->ipif_flags & IPIF_UP))
15629 					continue;
15630 				if (ill->ill_isv6) {
15631 					ipif_ndp_down(ipif);
15632 					/*
15633 					 * Set B_TRUE to enable
15634 					 * ipif_ndp_up() to send out
15635 					 * unsolicited advertisements.
15636 					 */
15637 					err = ipif_ndp_up(ipif,
15638 					    &ipif->ipif_v6lcl_addr,
15639 					    B_TRUE);
15640 					if (err) {
15641 						ip1dbg((
15642 						    "ip_rput_dlpi_writer: "
15643 						    "Failed to update ndp "
15644 						    "err %d\n", err));
15645 					}
15646 				} else {
15647 					/*
15648 					 * IPv4 ARP case
15649 					 *
15650 					 * Set Res_act_move, as we only want
15651 					 * ipif_resolver_up to send an
15652 					 * AR_ENTRY_ADD request up to
15653 					 * ARP.
15654 					 */
15655 					err = ipif_resolver_up(ipif,
15656 					    Res_act_move);
15657 					if (err) {
15658 						ip1dbg((
15659 						    "ip_rput_dlpi_writer: "
15660 						    "Failed to update arp "
15661 						    "err %d\n", err));
15662 					}
15663 				}
15664 			}
15665 			/*
15666 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15667 			 * case so that all old fastpath information can be
15668 			 * purged from IRE caches.
15669 			 */
15670 		/* FALLTHRU */
15671 		case DL_NOTE_FASTPATH_FLUSH:
15672 			/*
15673 			 * Any fastpath probe sent henceforth will get the
15674 			 * new fp mp. So we first delete any ires that are
15675 			 * waiting for the fastpath. Then walk all ires and
15676 			 * delete the ire or delete the fp mp. In the case of
15677 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15678 			 * recreate the ire's without going through a complex
15679 			 * ipif up/down dance. So we don't delete the ire
15680 			 * itself, but just the nce_fp_mp for these 2 ire's
15681 			 * In the case of the other ire's we delete the ire's
15682 			 * themselves. Access to nce_fp_mp is completely
15683 			 * protected by ire_lock for IRE_MIPRTUN and
15684 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15685 			 * other cases for performance.
15686 			 */
15687 			if (ill->ill_isv6) {
15688 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15689 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15690 				    NULL);
15691 			} else {
15692 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15693 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15694 				    IRE_CACHE | IRE_BROADCAST,
15695 				    ire_fastpath_flush, NULL, ill);
15696 				mutex_enter(&ire_mrtun_lock);
15697 				if (ire_mrtun_count != 0) {
15698 					mutex_exit(&ire_mrtun_lock);
15699 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15700 					    IRE_MIPRTUN, ire_fastpath_flush,
15701 					    NULL, ill);
15702 				} else {
15703 					mutex_exit(&ire_mrtun_lock);
15704 				}
15705 			}
15706 			break;
15707 		case DL_NOTE_SDU_SIZE:
15708 			/*
15709 			 * Change the MTU size of the interface, of all
15710 			 * attached ipif's, and of all relevant ire's.  The
15711 			 * new value's a uint32_t at notify->dl_data.
15712 			 * Mtu change Vs. new ire creation - protocol below.
15713 			 *
15714 			 * a Mark the ipif as IPIF_CHANGING.
15715 			 * b Set the new mtu in the ipif.
15716 			 * c Change the ire_max_frag on all affected ires
15717 			 * d Unmark the IPIF_CHANGING
15718 			 *
15719 			 * To see how the protocol works, assume an interface
15720 			 * route is also being added simultaneously by
15721 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15722 			 * the ire. If the ire is created before step a,
15723 			 * it will be cleaned up by step c. If the ire is
15724 			 * created after step d, it will see the new value of
15725 			 * ipif_mtu. Any attempt to create the ire between
15726 			 * steps a to d will fail because of the IPIF_CHANGING
15727 			 * flag. Note that ire_create() is passed a pointer to
15728 			 * the ipif_mtu, and not the value. During ire_add
15729 			 * under the bucket lock, the ire_max_frag of the
15730 			 * new ire being created is set from the ipif/ire from
15731 			 * which it is being derived.
15732 			 */
15733 			mutex_enter(&ill->ill_lock);
15734 			ill->ill_max_frag = (uint_t)notify->dl_data;
15735 
15736 			/*
15737 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15738 			 * leave it alone
15739 			 */
15740 			if (ill->ill_mtu_userspecified) {
15741 				mutex_exit(&ill->ill_lock);
15742 				break;
15743 			}
15744 			ill->ill_max_mtu = ill->ill_max_frag;
15745 			if (ill->ill_isv6) {
15746 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15747 					ill->ill_max_mtu = IPV6_MIN_MTU;
15748 			} else {
15749 				if (ill->ill_max_mtu < IP_MIN_MTU)
15750 					ill->ill_max_mtu = IP_MIN_MTU;
15751 			}
15752 			for (ipif = ill->ill_ipif; ipif != NULL;
15753 			    ipif = ipif->ipif_next) {
15754 				/*
15755 				 * Don't override the mtu if the user
15756 				 * has explicitly set it.
15757 				 */
15758 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15759 					continue;
15760 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15761 				if (ipif->ipif_isv6)
15762 					ire = ipif_to_ire_v6(ipif);
15763 				else
15764 					ire = ipif_to_ire(ipif);
15765 				if (ire != NULL) {
15766 					ire->ire_max_frag = ipif->ipif_mtu;
15767 					ire_refrele(ire);
15768 				}
15769 				if (ipif->ipif_flags & IPIF_UP) {
15770 					if (ill->ill_isv6)
15771 						need_ire_walk_v6 = B_TRUE;
15772 					else
15773 						need_ire_walk_v4 = B_TRUE;
15774 				}
15775 			}
15776 			mutex_exit(&ill->ill_lock);
15777 			if (need_ire_walk_v4)
15778 				ire_walk_v4(ill_mtu_change, (char *)ill,
15779 				    ALL_ZONES);
15780 			if (need_ire_walk_v6)
15781 				ire_walk_v6(ill_mtu_change, (char *)ill,
15782 				    ALL_ZONES);
15783 			break;
15784 		case DL_NOTE_LINK_UP:
15785 		case DL_NOTE_LINK_DOWN: {
15786 			/*
15787 			 * We are writer. ill / phyint / ipsq assocs stable.
15788 			 * The RUNNING flag reflects the state of the link.
15789 			 */
15790 			phyint_t *phyint = ill->ill_phyint;
15791 			uint64_t new_phyint_flags;
15792 			boolean_t changed = B_FALSE;
15793 			boolean_t went_up;
15794 
15795 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15796 			mutex_enter(&phyint->phyint_lock);
15797 			new_phyint_flags = went_up ?
15798 			    phyint->phyint_flags | PHYI_RUNNING :
15799 			    phyint->phyint_flags & ~PHYI_RUNNING;
15800 			if (new_phyint_flags != phyint->phyint_flags) {
15801 				phyint->phyint_flags = new_phyint_flags;
15802 				changed = B_TRUE;
15803 			}
15804 			mutex_exit(&phyint->phyint_lock);
15805 			/*
15806 			 * ill_restart_dad handles the DAD restart and routing
15807 			 * socket notification logic.
15808 			 */
15809 			if (changed) {
15810 				ill_restart_dad(phyint->phyint_illv4, went_up);
15811 				ill_restart_dad(phyint->phyint_illv6, went_up);
15812 			}
15813 			break;
15814 		}
15815 		case DL_NOTE_PROMISC_ON_PHYS:
15816 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15817 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15818 			mutex_enter(&ill->ill_lock);
15819 			ill->ill_promisc_on_phys = B_TRUE;
15820 			mutex_exit(&ill->ill_lock);
15821 			break;
15822 		case DL_NOTE_PROMISC_OFF_PHYS:
15823 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15824 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15825 			mutex_enter(&ill->ill_lock);
15826 			ill->ill_promisc_on_phys = B_FALSE;
15827 			mutex_exit(&ill->ill_lock);
15828 			break;
15829 		case DL_NOTE_CAPAB_RENEG:
15830 			/*
15831 			 * Something changed on the driver side.
15832 			 * It wants us to renegotiate the capabilities
15833 			 * on this ill. The most likely cause is the
15834 			 * aggregation interface under us where a
15835 			 * port got added or went away.
15836 			 *
15837 			 * We reset the capabilities and set the
15838 			 * state to IDS_RENG so that when the ack
15839 			 * comes back, we can start the
15840 			 * renegotiation process.
15841 			 */
15842 			ill_capability_reset(ill);
15843 			ill->ill_dlpi_capab_state = IDS_RENEG;
15844 			break;
15845 		default:
15846 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15847 			    "type 0x%x for DL_NOTIFY_IND\n",
15848 			    notify->dl_notification));
15849 			break;
15850 		}
15851 
15852 		/*
15853 		 * As this is an asynchronous operation, we
15854 		 * should not call ill_dlpi_done
15855 		 */
15856 		break;
15857 	}
15858 	case DL_NOTIFY_ACK: {
15859 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15860 
15861 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15862 			ill->ill_note_link = 1;
15863 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15864 		break;
15865 	}
15866 	case DL_PHYS_ADDR_ACK: {
15867 		/*
15868 		 * We should have an IOCTL waiting on this when request
15869 		 * sent by ill_dl_phys.
15870 		 * However, ill_dl_phys was called on an ill queue (from
15871 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15872 		 * ioctl is known to be pending on ill_wq.
15873 		 * There are two additional phys_addr_req's sent to the
15874 		 * driver to get the token and lla. ill_phys_addr_pend
15875 		 * keeps track of the last one sent so we know which
15876 		 * response we are dealing with. ill_dlpi_done will
15877 		 * update ill_phys_addr_pend when it sends the next req.
15878 		 * We don't complete the IOCTL until all three DL_PARs
15879 		 * have been attempted.
15880 		 *
15881 		 * We don't need any lock to update ill_nd_lla* fields,
15882 		 * since the ill is not yet up, We grab the lock just
15883 		 * for uniformity with other code that accesses ill_nd_lla.
15884 		 */
15885 		physaddr_req = ill->ill_phys_addr_pend;
15886 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15887 		if (physaddr_req == DL_IPV6_TOKEN ||
15888 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15889 			if (physaddr_req == DL_IPV6_TOKEN) {
15890 				/*
15891 				 * bcopy to low-order bits of ill_token
15892 				 *
15893 				 * XXX Temporary hack - currently,
15894 				 * all known tokens are 64 bits,
15895 				 * so I'll cheat for the moment.
15896 				 */
15897 				dlp = (union DL_primitives *)mp->b_rptr;
15898 
15899 				mutex_enter(&ill->ill_lock);
15900 				bcopy((uchar_t *)(mp->b_rptr +
15901 				dlp->physaddr_ack.dl_addr_offset),
15902 				(void *)&ill->ill_token.s6_addr32[2],
15903 				dlp->physaddr_ack.dl_addr_length);
15904 				ill->ill_token_length =
15905 					dlp->physaddr_ack.dl_addr_length;
15906 				mutex_exit(&ill->ill_lock);
15907 			} else {
15908 				ASSERT(ill->ill_nd_lla_mp == NULL);
15909 				mp_hw = copyb(mp);
15910 				if (mp_hw == NULL) {
15911 					err = ENOMEM;
15912 					break;
15913 				}
15914 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15915 				mutex_enter(&ill->ill_lock);
15916 				ill->ill_nd_lla_mp = mp_hw;
15917 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15918 				dlp->physaddr_ack.dl_addr_offset;
15919 				ill->ill_nd_lla_len =
15920 					dlp->physaddr_ack.dl_addr_length;
15921 				mutex_exit(&ill->ill_lock);
15922 			}
15923 			break;
15924 		}
15925 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15926 		ASSERT(ill->ill_phys_addr_mp == NULL);
15927 		if (!ill->ill_ifname_pending)
15928 			break;
15929 		ill->ill_ifname_pending = 0;
15930 		if (!ioctl_aborted)
15931 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15932 		if (mp1 != NULL) {
15933 			ASSERT(connp == NULL);
15934 			q = ill->ill_wq;
15935 		}
15936 		/*
15937 		 * If any error acks received during the plumbing sequence,
15938 		 * ill_ifname_pending_err will be set. Break out and send up
15939 		 * the error to the pending ioctl.
15940 		 */
15941 		if (ill->ill_ifname_pending_err != 0) {
15942 			err = ill->ill_ifname_pending_err;
15943 			ill->ill_ifname_pending_err = 0;
15944 			break;
15945 		}
15946 		/*
15947 		 * Get the interface token.  If the zeroth interface
15948 		 * address is zero then set the address to the link local
15949 		 * address
15950 		 */
15951 		mp_hw = copyb(mp);
15952 		if (mp_hw == NULL) {
15953 			err = ENOMEM;
15954 			break;
15955 		}
15956 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15957 		ill->ill_phys_addr_mp = mp_hw;
15958 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15959 				dlp->physaddr_ack.dl_addr_offset;
15960 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15961 		    ill->ill_phys_addr_length == 0 ||
15962 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15963 			/*
15964 			 * Compatibility: atun driver returns a length of 0.
15965 			 * ipdptp has an ill_phys_addr_length of zero(from
15966 			 * DL_BIND_ACK) but a non-zero length here.
15967 			 * ipd has an ill_phys_addr_length of 4(from
15968 			 * DL_BIND_ACK) but a non-zero length here.
15969 			 */
15970 			ill->ill_phys_addr = NULL;
15971 		} else if (dlp->physaddr_ack.dl_addr_length !=
15972 		    ill->ill_phys_addr_length) {
15973 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15974 			    "Address length mismatch %d %d\n",
15975 			    dlp->physaddr_ack.dl_addr_length,
15976 			    ill->ill_phys_addr_length));
15977 			err = EINVAL;
15978 			break;
15979 		}
15980 		mutex_enter(&ill->ill_lock);
15981 		if (ill->ill_nd_lla_mp == NULL) {
15982 			ill->ill_nd_lla_mp = copyb(mp_hw);
15983 			if (ill->ill_nd_lla_mp == NULL) {
15984 				err = ENOMEM;
15985 				mutex_exit(&ill->ill_lock);
15986 				break;
15987 			}
15988 			ill->ill_nd_lla =
15989 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15990 			    dlp->physaddr_ack.dl_addr_offset;
15991 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15992 		}
15993 		mutex_exit(&ill->ill_lock);
15994 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15995 			(void) ill_setdefaulttoken(ill);
15996 
15997 		/*
15998 		 * If the ill zero interface has a zero address assign
15999 		 * it the proper link local address.
16000 		 */
16001 		ASSERT(ill->ill_ipif->ipif_id == 0);
16002 		if (ipif != NULL &&
16003 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
16004 			(void) ipif_setlinklocal(ipif);
16005 		break;
16006 	}
16007 	case DL_OK_ACK:
16008 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16009 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16010 		    dloa->dl_correct_primitive));
16011 		switch (dloa->dl_correct_primitive) {
16012 		case DL_UNBIND_REQ:
16013 		case DL_ATTACH_REQ:
16014 		case DL_DETACH_REQ:
16015 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16016 			break;
16017 		}
16018 		break;
16019 	default:
16020 		break;
16021 	}
16022 
16023 	freemsg(mp);
16024 	if (mp1) {
16025 		struct iocblk *iocp;
16026 		int mode;
16027 
16028 		/*
16029 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
16030 		 * SIOCSLIFNAME do a copyout.
16031 		 */
16032 		iocp = (struct iocblk *)mp1->b_rptr;
16033 
16034 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
16035 		    iocp->ioc_cmd == SIOCSLIFNAME)
16036 			mode = COPYOUT;
16037 		else
16038 			mode = NO_COPYOUT;
16039 		/*
16040 		 * The ioctl must complete now without EINPROGRESS
16041 		 * since ipsq_pending_mp_get has removed the ioctl mblk
16042 		 * from ipsq_pending_mp. Otherwise the ioctl will be
16043 		 * stuck for ever in the ipsq.
16044 		 */
16045 		ASSERT(err != EINPROGRESS);
16046 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
16047 
16048 	}
16049 }
16050 
16051 /*
16052  * ip_rput_other is called by ip_rput to handle messages modifying the global
16053  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16054  */
16055 /* ARGSUSED */
16056 void
16057 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16058 {
16059 	ill_t		*ill;
16060 	struct iocblk	*iocp;
16061 	mblk_t		*mp1;
16062 	conn_t		*connp = NULL;
16063 
16064 	ip1dbg(("ip_rput_other "));
16065 	ill = (ill_t *)q->q_ptr;
16066 	/*
16067 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16068 	 * in which case ipsq is NULL.
16069 	 */
16070 	if (ipsq != NULL) {
16071 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16072 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16073 	}
16074 
16075 	switch (mp->b_datap->db_type) {
16076 	case M_ERROR:
16077 	case M_HANGUP:
16078 		/*
16079 		 * The device has a problem.  We force the ILL down.  It can
16080 		 * be brought up again manually using SIOCSIFFLAGS (via
16081 		 * ifconfig or equivalent).
16082 		 */
16083 		ASSERT(ipsq != NULL);
16084 		if (mp->b_rptr < mp->b_wptr)
16085 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16086 		if (ill->ill_error == 0)
16087 			ill->ill_error = ENXIO;
16088 		if (!ill_down_start(q, mp))
16089 			return;
16090 		ipif_all_down_tail(ipsq, q, mp, NULL);
16091 		break;
16092 	case M_IOCACK:
16093 		iocp = (struct iocblk *)mp->b_rptr;
16094 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16095 		switch (iocp->ioc_cmd) {
16096 		case SIOCSTUNPARAM:
16097 		case OSIOCSTUNPARAM:
16098 			ASSERT(ipsq != NULL);
16099 			/*
16100 			 * Finish socket ioctl passed through to tun.
16101 			 * We should have an IOCTL waiting on this.
16102 			 */
16103 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16104 			if (ill->ill_isv6) {
16105 				struct iftun_req *ta;
16106 
16107 				/*
16108 				 * if a source or destination is
16109 				 * being set, try and set the link
16110 				 * local address for the tunnel
16111 				 */
16112 				ta = (struct iftun_req *)mp->b_cont->
16113 				    b_cont->b_rptr;
16114 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16115 					ipif_set_tun_llink(ill, ta);
16116 				}
16117 
16118 			}
16119 			if (mp1 != NULL) {
16120 				/*
16121 				 * Now copy back the b_next/b_prev used by
16122 				 * mi code for the mi_copy* functions.
16123 				 * See ip_sioctl_tunparam() for the reason.
16124 				 * Also protect against missing b_cont.
16125 				 */
16126 				if (mp->b_cont != NULL) {
16127 					mp->b_cont->b_next =
16128 					    mp1->b_cont->b_next;
16129 					mp->b_cont->b_prev =
16130 					    mp1->b_cont->b_prev;
16131 				}
16132 				inet_freemsg(mp1);
16133 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16134 				ASSERT(connp != NULL);
16135 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16136 				    iocp->ioc_error, NO_COPYOUT,
16137 				    ipsq->ipsq_current_ipif, ipsq);
16138 			} else {
16139 				ASSERT(connp == NULL);
16140 				putnext(q, mp);
16141 			}
16142 			break;
16143 		case SIOCGTUNPARAM:
16144 		case OSIOCGTUNPARAM:
16145 			/*
16146 			 * This is really M_IOCDATA from the tunnel driver.
16147 			 * convert back and complete the ioctl.
16148 			 * We should have an IOCTL waiting on this.
16149 			 */
16150 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16151 			if (mp1) {
16152 				/*
16153 				 * Now copy back the b_next/b_prev used by
16154 				 * mi code for the mi_copy* functions.
16155 				 * See ip_sioctl_tunparam() for the reason.
16156 				 * Also protect against missing b_cont.
16157 				 */
16158 				if (mp->b_cont != NULL) {
16159 					mp->b_cont->b_next =
16160 					    mp1->b_cont->b_next;
16161 					mp->b_cont->b_prev =
16162 					    mp1->b_cont->b_prev;
16163 				}
16164 				inet_freemsg(mp1);
16165 				if (iocp->ioc_error == 0)
16166 					mp->b_datap->db_type = M_IOCDATA;
16167 				ASSERT(connp != NULL);
16168 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16169 				    iocp->ioc_error, COPYOUT, NULL, NULL);
16170 			} else {
16171 				ASSERT(connp == NULL);
16172 				putnext(q, mp);
16173 			}
16174 			break;
16175 		default:
16176 			break;
16177 		}
16178 		break;
16179 	case M_IOCNAK:
16180 		iocp = (struct iocblk *)mp->b_rptr;
16181 
16182 		switch (iocp->ioc_cmd) {
16183 		int mode;
16184 		ipif_t	*ipif;
16185 
16186 		case DL_IOC_HDR_INFO:
16187 			/*
16188 			 * If this was the first attempt turn of the
16189 			 * fastpath probing.
16190 			 */
16191 			mutex_enter(&ill->ill_lock);
16192 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16193 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16194 				mutex_exit(&ill->ill_lock);
16195 				ill_fastpath_nack(ill);
16196 				ip1dbg(("ip_rput: DLPI fastpath off on "
16197 				    "interface %s\n",
16198 				    ill->ill_name));
16199 			} else {
16200 				mutex_exit(&ill->ill_lock);
16201 			}
16202 			freemsg(mp);
16203 			break;
16204 		case SIOCSTUNPARAM:
16205 		case OSIOCSTUNPARAM:
16206 			ASSERT(ipsq != NULL);
16207 			/*
16208 			 * Finish socket ioctl passed through to tun
16209 			 * We should have an IOCTL waiting on this.
16210 			 */
16211 			/* FALLTHRU */
16212 		case SIOCGTUNPARAM:
16213 		case OSIOCGTUNPARAM:
16214 			/*
16215 			 * This is really M_IOCDATA from the tunnel driver.
16216 			 * convert back and complete the ioctl.
16217 			 * We should have an IOCTL waiting on this.
16218 			 */
16219 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16220 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16221 				mp1 = ill_pending_mp_get(ill, &connp,
16222 				    iocp->ioc_id);
16223 				mode = COPYOUT;
16224 				ipsq = NULL;
16225 				ipif = NULL;
16226 			} else {
16227 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16228 				mode = NO_COPYOUT;
16229 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16230 				ipif = ipsq->ipsq_current_ipif;
16231 			}
16232 			if (mp1 != NULL) {
16233 				/*
16234 				 * Now copy back the b_next/b_prev used by
16235 				 * mi code for the mi_copy* functions.
16236 				 * See ip_sioctl_tunparam() for the reason.
16237 				 * Also protect against missing b_cont.
16238 				 */
16239 				if (mp->b_cont != NULL) {
16240 					mp->b_cont->b_next =
16241 					    mp1->b_cont->b_next;
16242 					mp->b_cont->b_prev =
16243 					    mp1->b_cont->b_prev;
16244 				}
16245 				inet_freemsg(mp1);
16246 				if (iocp->ioc_error == 0)
16247 					iocp->ioc_error = EINVAL;
16248 				ASSERT(connp != NULL);
16249 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16250 				    iocp->ioc_error, mode, ipif, ipsq);
16251 			} else {
16252 				ASSERT(connp == NULL);
16253 				putnext(q, mp);
16254 			}
16255 			break;
16256 		default:
16257 			break;
16258 		}
16259 	default:
16260 		break;
16261 	}
16262 }
16263 
16264 /*
16265  * NOTE : This function does not ire_refrele the ire argument passed in.
16266  *
16267  * IPQoS notes
16268  * IP policy is invoked twice for a forwarded packet, once on the read side
16269  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16270  * enabled. An additional parameter, in_ill, has been added for this purpose.
16271  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16272  * because ip_mroute drops this information.
16273  *
16274  */
16275 void
16276 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16277 {
16278 	uint32_t	pkt_len;
16279 	queue_t	*q;
16280 	uint32_t	sum;
16281 #define	rptr	((uchar_t *)ipha)
16282 	uint32_t	max_frag;
16283 	uint32_t	ill_index;
16284 	ill_t		*out_ill;
16285 
16286 	/* Get the ill_index of the incoming ILL */
16287 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16288 
16289 	/* Initiate Read side IPPF processing */
16290 	if (IPP_ENABLED(IPP_FWD_IN)) {
16291 		ip_process(IPP_FWD_IN, &mp, ill_index);
16292 		if (mp == NULL) {
16293 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16294 			    "during IPPF processing\n"));
16295 			return;
16296 		}
16297 	}
16298 
16299 	pkt_len = ntohs(ipha->ipha_length);
16300 
16301 	/* Adjust the checksum to reflect the ttl decrement. */
16302 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16303 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16304 
16305 	if (ipha->ipha_ttl-- <= 1) {
16306 		if (ip_csum_hdr(ipha)) {
16307 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16308 			goto drop_pkt;
16309 		}
16310 		/*
16311 		 * Note: ire_stq this will be NULL for multicast
16312 		 * datagrams using the long path through arp (the IRE
16313 		 * is not an IRE_CACHE). This should not cause
16314 		 * problems since we don't generate ICMP errors for
16315 		 * multicast packets.
16316 		 */
16317 		q = ire->ire_stq;
16318 		if (q != NULL) {
16319 			/* Sent by forwarding path, and router is global zone */
16320 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16321 			    GLOBAL_ZONEID);
16322 		} else
16323 			freemsg(mp);
16324 		return;
16325 	}
16326 
16327 	/*
16328 	 * Don't forward if the interface is down
16329 	 */
16330 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16331 		BUMP_MIB(&ip_mib, ipInDiscards);
16332 		ip2dbg(("ip_rput_forward:interface is down\n"));
16333 		goto drop_pkt;
16334 	}
16335 
16336 	/* Get the ill_index of the outgoing ILL */
16337 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16338 
16339 	out_ill = ire->ire_ipif->ipif_ill;
16340 
16341 	DTRACE_PROBE4(ip4__forwarding__start,
16342 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16343 
16344 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
16345 	    in_ill, out_ill, ipha, mp, mp);
16346 
16347 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16348 
16349 	if (mp == NULL)
16350 		return;
16351 	pkt_len = ntohs(ipha->ipha_length);
16352 
16353 	if (is_system_labeled()) {
16354 		mblk_t *mp1;
16355 
16356 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16357 			BUMP_MIB(&ip_mib, ipForwProhibits);
16358 			goto drop_pkt;
16359 		}
16360 		/* Size may have changed */
16361 		mp = mp1;
16362 		ipha = (ipha_t *)mp->b_rptr;
16363 		pkt_len = ntohs(ipha->ipha_length);
16364 	}
16365 
16366 	/* Check if there are options to update */
16367 	if (!IS_SIMPLE_IPH(ipha)) {
16368 		if (ip_csum_hdr(ipha)) {
16369 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16370 			goto drop_pkt;
16371 		}
16372 		if (ip_rput_forward_options(mp, ipha, ire)) {
16373 			return;
16374 		}
16375 
16376 		ipha->ipha_hdr_checksum = 0;
16377 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16378 	}
16379 	max_frag = ire->ire_max_frag;
16380 	if (pkt_len > max_frag) {
16381 		/*
16382 		 * It needs fragging on its way out.  We haven't
16383 		 * verified the header checksum yet.  Since we
16384 		 * are going to put a surely good checksum in the
16385 		 * outgoing header, we have to make sure that it
16386 		 * was good coming in.
16387 		 */
16388 		if (ip_csum_hdr(ipha)) {
16389 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16390 			goto drop_pkt;
16391 		}
16392 		/* Initiate Write side IPPF processing */
16393 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16394 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16395 			if (mp == NULL) {
16396 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16397 				    " during IPPF processing\n"));
16398 				return;
16399 			}
16400 		}
16401 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
16402 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16403 		return;
16404 	}
16405 
16406 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16407 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16408 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
16409 	    NULL, out_ill, ipha, mp, mp);
16410 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16411 	if (mp == NULL)
16412 		return;
16413 
16414 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16415 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16416 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16417 	/* ip_xmit_v4 always consumes the packet */
16418 	return;
16419 
16420 drop_pkt:;
16421 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16422 	freemsg(mp);
16423 #undef	rptr
16424 }
16425 
16426 void
16427 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16428 {
16429 	ire_t	*ire;
16430 
16431 	ASSERT(!ipif->ipif_isv6);
16432 	/*
16433 	 * Find an IRE which matches the destination and the outgoing
16434 	 * queue in the cache table. All we need is an IRE_CACHE which
16435 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16436 	 * then it is enough to have some IRE_CACHE in the group.
16437 	 */
16438 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16439 		dst = ipif->ipif_pp_dst_addr;
16440 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16441 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16442 	if (ire == NULL) {
16443 		/*
16444 		 * Mark this packet to make it be delivered to
16445 		 * ip_rput_forward after the new ire has been
16446 		 * created.
16447 		 */
16448 		mp->b_prev = NULL;
16449 		mp->b_next = mp;
16450 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16451 		    NULL, 0, GLOBAL_ZONEID);
16452 	} else {
16453 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16454 		IRE_REFRELE(ire);
16455 	}
16456 }
16457 
16458 /* Update any source route, record route or timestamp options */
16459 static int
16460 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16461 {
16462 	ipoptp_t	opts;
16463 	uchar_t		*opt;
16464 	uint8_t		optval;
16465 	uint8_t		optlen;
16466 	ipaddr_t	dst;
16467 	uint32_t	ts;
16468 	ire_t		*dst_ire = NULL;
16469 	ire_t		*tmp_ire = NULL;
16470 	timestruc_t	now;
16471 
16472 	ip2dbg(("ip_rput_forward_options\n"));
16473 	dst = ipha->ipha_dst;
16474 	for (optval = ipoptp_first(&opts, ipha);
16475 	    optval != IPOPT_EOL;
16476 	    optval = ipoptp_next(&opts)) {
16477 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16478 		opt = opts.ipoptp_cur;
16479 		optlen = opts.ipoptp_len;
16480 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16481 		    optval, opts.ipoptp_len));
16482 		switch (optval) {
16483 			uint32_t off;
16484 		case IPOPT_SSRR:
16485 		case IPOPT_LSRR:
16486 			/* Check if adminstratively disabled */
16487 			if (!ip_forward_src_routed) {
16488 				BUMP_MIB(&ip_mib, ipForwProhibits);
16489 				if (ire->ire_stq != NULL) {
16490 					/*
16491 					 * Sent by forwarding path, and router
16492 					 * is global zone
16493 					 */
16494 					icmp_unreachable(ire->ire_stq, mp,
16495 					    ICMP_SOURCE_ROUTE_FAILED,
16496 					    GLOBAL_ZONEID);
16497 				} else {
16498 					ip0dbg(("ip_rput_forward_options: "
16499 					    "unable to send unreach\n"));
16500 					freemsg(mp);
16501 				}
16502 				return (-1);
16503 			}
16504 
16505 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16506 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16507 			if (dst_ire == NULL) {
16508 				/*
16509 				 * Must be partial since ip_rput_options
16510 				 * checked for strict.
16511 				 */
16512 				break;
16513 			}
16514 			off = opt[IPOPT_OFFSET];
16515 			off--;
16516 		redo_srr:
16517 			if (optlen < IP_ADDR_LEN ||
16518 			    off > optlen - IP_ADDR_LEN) {
16519 				/* End of source route */
16520 				ip1dbg((
16521 				    "ip_rput_forward_options: end of SR\n"));
16522 				ire_refrele(dst_ire);
16523 				break;
16524 			}
16525 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16526 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16527 			    IP_ADDR_LEN);
16528 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16529 			    ntohl(dst)));
16530 
16531 			/*
16532 			 * Check if our address is present more than
16533 			 * once as consecutive hops in source route.
16534 			 */
16535 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16536 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16537 			if (tmp_ire != NULL) {
16538 				ire_refrele(tmp_ire);
16539 				off += IP_ADDR_LEN;
16540 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16541 				goto redo_srr;
16542 			}
16543 			ipha->ipha_dst = dst;
16544 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16545 			ire_refrele(dst_ire);
16546 			break;
16547 		case IPOPT_RR:
16548 			off = opt[IPOPT_OFFSET];
16549 			off--;
16550 			if (optlen < IP_ADDR_LEN ||
16551 			    off > optlen - IP_ADDR_LEN) {
16552 				/* No more room - ignore */
16553 				ip1dbg((
16554 				    "ip_rput_forward_options: end of RR\n"));
16555 				break;
16556 			}
16557 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16558 			    IP_ADDR_LEN);
16559 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16560 			break;
16561 		case IPOPT_TS:
16562 			/* Insert timestamp if there is room */
16563 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16564 			case IPOPT_TS_TSONLY:
16565 				off = IPOPT_TS_TIMELEN;
16566 				break;
16567 			case IPOPT_TS_PRESPEC:
16568 			case IPOPT_TS_PRESPEC_RFC791:
16569 				/* Verify that the address matched */
16570 				off = opt[IPOPT_OFFSET] - 1;
16571 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16572 				dst_ire = ire_ctable_lookup(dst, 0,
16573 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16574 				    MATCH_IRE_TYPE);
16575 
16576 				if (dst_ire == NULL) {
16577 					/* Not for us */
16578 					break;
16579 				}
16580 				ire_refrele(dst_ire);
16581 				/* FALLTHRU */
16582 			case IPOPT_TS_TSANDADDR:
16583 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16584 				break;
16585 			default:
16586 				/*
16587 				 * ip_*put_options should have already
16588 				 * dropped this packet.
16589 				 */
16590 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16591 				    "unknown IT - bug in ip_rput_options?\n");
16592 				return (0);	/* Keep "lint" happy */
16593 			}
16594 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16595 				/* Increase overflow counter */
16596 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16597 				opt[IPOPT_POS_OV_FLG] =
16598 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16599 				    (off << 4));
16600 				break;
16601 			}
16602 			off = opt[IPOPT_OFFSET] - 1;
16603 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16604 			case IPOPT_TS_PRESPEC:
16605 			case IPOPT_TS_PRESPEC_RFC791:
16606 			case IPOPT_TS_TSANDADDR:
16607 				bcopy(&ire->ire_src_addr,
16608 				    (char *)opt + off, IP_ADDR_LEN);
16609 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16610 				/* FALLTHRU */
16611 			case IPOPT_TS_TSONLY:
16612 				off = opt[IPOPT_OFFSET] - 1;
16613 				/* Compute # of milliseconds since midnight */
16614 				gethrestime(&now);
16615 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16616 				    now.tv_nsec / (NANOSEC / MILLISEC);
16617 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16618 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16619 				break;
16620 			}
16621 			break;
16622 		}
16623 	}
16624 	return (0);
16625 }
16626 
16627 /*
16628  * This is called after processing at least one of AH/ESP headers.
16629  *
16630  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16631  * the actual, physical interface on which the packet was received,
16632  * but, when ip_strict_dst_multihoming is set to 1, could be the
16633  * interface which had the ipha_dst configured when the packet went
16634  * through ip_rput. The ill_index corresponding to the recv_ill
16635  * is saved in ipsec_in_rill_index
16636  */
16637 void
16638 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16639 {
16640 	mblk_t *mp;
16641 	ipaddr_t dst;
16642 	in6_addr_t *v6dstp;
16643 	ipha_t *ipha;
16644 	ip6_t *ip6h;
16645 	ipsec_in_t *ii;
16646 	boolean_t ill_need_rele = B_FALSE;
16647 	boolean_t rill_need_rele = B_FALSE;
16648 	boolean_t ire_need_rele = B_FALSE;
16649 
16650 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16651 	ASSERT(ii->ipsec_in_ill_index != 0);
16652 
16653 	mp = ipsec_mp->b_cont;
16654 	ASSERT(mp != NULL);
16655 
16656 
16657 	if (ill == NULL) {
16658 		ASSERT(recv_ill == NULL);
16659 		/*
16660 		 * We need to get the original queue on which ip_rput_local
16661 		 * or ip_rput_data_v6 was called.
16662 		 */
16663 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16664 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16665 		ill_need_rele = B_TRUE;
16666 
16667 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16668 			recv_ill = ill_lookup_on_ifindex(
16669 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16670 			    NULL, NULL, NULL, NULL);
16671 			rill_need_rele = B_TRUE;
16672 		} else {
16673 			recv_ill = ill;
16674 		}
16675 
16676 		if ((ill == NULL) || (recv_ill == NULL)) {
16677 			ip0dbg(("ip_fanout_proto_again: interface "
16678 			    "disappeared\n"));
16679 			if (ill != NULL)
16680 				ill_refrele(ill);
16681 			if (recv_ill != NULL)
16682 				ill_refrele(recv_ill);
16683 			freemsg(ipsec_mp);
16684 			return;
16685 		}
16686 	}
16687 
16688 	ASSERT(ill != NULL && recv_ill != NULL);
16689 
16690 	if (mp->b_datap->db_type == M_CTL) {
16691 		/*
16692 		 * AH/ESP is returning the ICMP message after
16693 		 * removing their headers. Fanout again till
16694 		 * it gets to the right protocol.
16695 		 */
16696 		if (ii->ipsec_in_v4) {
16697 			icmph_t *icmph;
16698 			int iph_hdr_length;
16699 			int hdr_length;
16700 
16701 			ipha = (ipha_t *)mp->b_rptr;
16702 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16703 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16704 			ipha = (ipha_t *)&icmph[1];
16705 			hdr_length = IPH_HDR_LENGTH(ipha);
16706 			/*
16707 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16708 			 * Reset the type to M_DATA.
16709 			 */
16710 			mp->b_datap->db_type = M_DATA;
16711 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16712 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16713 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16714 		} else {
16715 			icmp6_t *icmp6;
16716 			int hdr_length;
16717 
16718 			ip6h = (ip6_t *)mp->b_rptr;
16719 			/* Don't call hdr_length_v6() unless you have to. */
16720 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16721 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16722 			else
16723 				hdr_length = IPV6_HDR_LEN;
16724 
16725 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16726 			/*
16727 			 * icmp_inbound_error_fanout_v6 may need to do
16728 			 * pullupmsg.  Reset the type to M_DATA.
16729 			 */
16730 			mp->b_datap->db_type = M_DATA;
16731 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16732 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16733 		}
16734 		if (ill_need_rele)
16735 			ill_refrele(ill);
16736 		if (rill_need_rele)
16737 			ill_refrele(recv_ill);
16738 		return;
16739 	}
16740 
16741 	if (ii->ipsec_in_v4) {
16742 		ipha = (ipha_t *)mp->b_rptr;
16743 		dst = ipha->ipha_dst;
16744 		if (CLASSD(dst)) {
16745 			/*
16746 			 * Multicast has to be delivered to all streams.
16747 			 */
16748 			dst = INADDR_BROADCAST;
16749 		}
16750 
16751 		if (ire == NULL) {
16752 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16753 			    MBLK_GETLABEL(mp));
16754 			if (ire == NULL) {
16755 				if (ill_need_rele)
16756 					ill_refrele(ill);
16757 				if (rill_need_rele)
16758 					ill_refrele(recv_ill);
16759 				ip1dbg(("ip_fanout_proto_again: "
16760 				    "IRE not found"));
16761 				freemsg(ipsec_mp);
16762 				return;
16763 			}
16764 			ire_need_rele = B_TRUE;
16765 		}
16766 
16767 		switch (ipha->ipha_protocol) {
16768 			case IPPROTO_UDP:
16769 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16770 				    recv_ill);
16771 				if (ire_need_rele)
16772 					ire_refrele(ire);
16773 				break;
16774 			case IPPROTO_TCP:
16775 				if (!ire_need_rele)
16776 					IRE_REFHOLD(ire);
16777 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16778 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16779 				IRE_REFRELE(ire);
16780 				if (mp != NULL)
16781 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16782 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16783 				break;
16784 			case IPPROTO_SCTP:
16785 				if (!ire_need_rele)
16786 					IRE_REFHOLD(ire);
16787 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16788 				    ipsec_mp, 0, ill->ill_rq, dst);
16789 				break;
16790 			default:
16791 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16792 				    recv_ill);
16793 				if (ire_need_rele)
16794 					ire_refrele(ire);
16795 				break;
16796 		}
16797 	} else {
16798 		uint32_t rput_flags = 0;
16799 
16800 		ip6h = (ip6_t *)mp->b_rptr;
16801 		v6dstp = &ip6h->ip6_dst;
16802 		/*
16803 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16804 		 * address.
16805 		 *
16806 		 * Currently, we don't store that state in the IPSEC_IN
16807 		 * message, and we may need to.
16808 		 */
16809 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16810 		    IP6_IN_LLMCAST : 0);
16811 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16812 		    NULL, NULL);
16813 	}
16814 	if (ill_need_rele)
16815 		ill_refrele(ill);
16816 	if (rill_need_rele)
16817 		ill_refrele(recv_ill);
16818 }
16819 
16820 /*
16821  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16822  * returns 'true' if there are still fragments left on the queue, in
16823  * which case we restart the timer.
16824  */
16825 void
16826 ill_frag_timer(void *arg)
16827 {
16828 	ill_t	*ill = (ill_t *)arg;
16829 	boolean_t frag_pending;
16830 
16831 	mutex_enter(&ill->ill_lock);
16832 	ASSERT(!ill->ill_fragtimer_executing);
16833 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16834 		ill->ill_frag_timer_id = 0;
16835 		mutex_exit(&ill->ill_lock);
16836 		return;
16837 	}
16838 	ill->ill_fragtimer_executing = 1;
16839 	mutex_exit(&ill->ill_lock);
16840 
16841 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16842 
16843 	/*
16844 	 * Restart the timer, if we have fragments pending or if someone
16845 	 * wanted us to be scheduled again.
16846 	 */
16847 	mutex_enter(&ill->ill_lock);
16848 	ill->ill_fragtimer_executing = 0;
16849 	ill->ill_frag_timer_id = 0;
16850 	if (frag_pending || ill->ill_fragtimer_needrestart)
16851 		ill_frag_timer_start(ill);
16852 	mutex_exit(&ill->ill_lock);
16853 }
16854 
16855 void
16856 ill_frag_timer_start(ill_t *ill)
16857 {
16858 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16859 
16860 	/* If the ill is closing or opening don't proceed */
16861 	if (ill->ill_state_flags & ILL_CONDEMNED)
16862 		return;
16863 
16864 	if (ill->ill_fragtimer_executing) {
16865 		/*
16866 		 * ill_frag_timer is currently executing. Just record the
16867 		 * the fact that we want the timer to be restarted.
16868 		 * ill_frag_timer will post a timeout before it returns,
16869 		 * ensuring it will be called again.
16870 		 */
16871 		ill->ill_fragtimer_needrestart = 1;
16872 		return;
16873 	}
16874 
16875 	if (ill->ill_frag_timer_id == 0) {
16876 		/*
16877 		 * The timer is neither running nor is the timeout handler
16878 		 * executing. Post a timeout so that ill_frag_timer will be
16879 		 * called
16880 		 */
16881 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16882 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16883 		ill->ill_fragtimer_needrestart = 0;
16884 	}
16885 }
16886 
16887 /*
16888  * This routine is needed for loopback when forwarding multicasts.
16889  *
16890  * IPQoS Notes:
16891  * IPPF processing is done in fanout routines.
16892  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16893  * processing for IPSec packets is done when it comes back in clear.
16894  * NOTE : The callers of this function need to do the ire_refrele for the
16895  *	  ire that is being passed in.
16896  */
16897 void
16898 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16899     ill_t *recv_ill)
16900 {
16901 	ill_t	*ill = (ill_t *)q->q_ptr;
16902 	uint32_t	sum;
16903 	uint32_t	u1;
16904 	uint32_t	u2;
16905 	int		hdr_length;
16906 	boolean_t	mctl_present;
16907 	mblk_t		*first_mp = mp;
16908 	mblk_t		*hada_mp = NULL;
16909 	ipha_t		*inner_ipha;
16910 
16911 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16912 	    "ip_rput_locl_start: q %p", q);
16913 
16914 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16915 
16916 
16917 #define	rptr	((uchar_t *)ipha)
16918 #define	iphs	((uint16_t *)ipha)
16919 
16920 	/*
16921 	 * no UDP or TCP packet should come here anymore.
16922 	 */
16923 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16924 	    (ipha->ipha_protocol != IPPROTO_UDP));
16925 
16926 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16927 	if (mctl_present &&
16928 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16929 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16930 
16931 		/*
16932 		 * It's an IPsec accelerated packet.
16933 		 * Keep a pointer to the data attributes around until
16934 		 * we allocate the ipsec_info_t.
16935 		 */
16936 		IPSECHW_DEBUG(IPSECHW_PKT,
16937 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16938 		hada_mp = first_mp;
16939 		hada_mp->b_cont = NULL;
16940 		/*
16941 		 * Since it is accelerated, it comes directly from
16942 		 * the ill and the data attributes is followed by
16943 		 * the packet data.
16944 		 */
16945 		ASSERT(mp->b_datap->db_type != M_CTL);
16946 		first_mp = mp;
16947 		mctl_present = B_FALSE;
16948 	}
16949 
16950 	/*
16951 	 * IF M_CTL is not present, then ipsec_in_is_secure
16952 	 * should return B_TRUE. There is a case where loopback
16953 	 * packets has an M_CTL in the front with all the
16954 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16955 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16956 	 * packets never comes here, it is safe to ASSERT the
16957 	 * following.
16958 	 */
16959 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16960 
16961 
16962 	/* u1 is # words of IP options */
16963 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16964 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16965 
16966 	if (u1) {
16967 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16968 			if (hada_mp != NULL)
16969 				freemsg(hada_mp);
16970 			return;
16971 		}
16972 	} else {
16973 		/* Check the IP header checksum.  */
16974 #define	uph	((uint16_t *)ipha)
16975 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16976 		    uph[6] + uph[7] + uph[8] + uph[9];
16977 #undef  uph
16978 		/* finish doing IP checksum */
16979 		sum = (sum & 0xFFFF) + (sum >> 16);
16980 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16981 		/*
16982 		 * Don't verify header checksum if this packet is coming
16983 		 * back from AH/ESP as we already did it.
16984 		 */
16985 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16986 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16987 			goto drop_pkt;
16988 		}
16989 	}
16990 
16991 	/*
16992 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16993 	 * might be called more than once for secure packets, count only
16994 	 * the first time.
16995 	 */
16996 	if (!mctl_present) {
16997 		UPDATE_IB_PKT_COUNT(ire);
16998 		ire->ire_last_used_time = lbolt;
16999 	}
17000 
17001 	/* Check for fragmentation offset. */
17002 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17003 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17004 	if (u1) {
17005 		/*
17006 		 * We re-assemble fragments before we do the AH/ESP
17007 		 * processing. Thus, M_CTL should not be present
17008 		 * while we are re-assembling.
17009 		 */
17010 		ASSERT(!mctl_present);
17011 		ASSERT(first_mp == mp);
17012 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17013 			return;
17014 		}
17015 		/*
17016 		 * Make sure that first_mp points back to mp as
17017 		 * the mp we came in with could have changed in
17018 		 * ip_rput_fragment().
17019 		 */
17020 		ipha = (ipha_t *)mp->b_rptr;
17021 		first_mp = mp;
17022 	}
17023 
17024 	/*
17025 	 * Clear hardware checksumming flag as it is currently only
17026 	 * used by TCP and UDP.
17027 	 */
17028 	DB_CKSUMFLAGS(mp) = 0;
17029 
17030 	/* Now we have a complete datagram, destined for this machine. */
17031 	u1 = IPH_HDR_LENGTH(ipha);
17032 	switch (ipha->ipha_protocol) {
17033 	case IPPROTO_ICMP: {
17034 		ire_t		*ire_zone;
17035 		ilm_t		*ilm;
17036 		mblk_t		*mp1;
17037 		zoneid_t	last_zoneid;
17038 
17039 		if (CLASSD(ipha->ipha_dst) &&
17040 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17041 			ASSERT(ire->ire_type == IRE_BROADCAST);
17042 			/*
17043 			 * In the multicast case, applications may have joined
17044 			 * the group from different zones, so we need to deliver
17045 			 * the packet to each of them. Loop through the
17046 			 * multicast memberships structures (ilm) on the receive
17047 			 * ill and send a copy of the packet up each matching
17048 			 * one. However, we don't do this for multicasts sent on
17049 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17050 			 * they must stay in the sender's zone.
17051 			 *
17052 			 * ilm_add_v6() ensures that ilms in the same zone are
17053 			 * contiguous in the ill_ilm list. We use this property
17054 			 * to avoid sending duplicates needed when two
17055 			 * applications in the same zone join the same group on
17056 			 * different logical interfaces: we ignore the ilm if
17057 			 * its zoneid is the same as the last matching one.
17058 			 * In addition, the sending of the packet for
17059 			 * ire_zoneid is delayed until all of the other ilms
17060 			 * have been exhausted.
17061 			 */
17062 			last_zoneid = -1;
17063 			ILM_WALKER_HOLD(recv_ill);
17064 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17065 			    ilm = ilm->ilm_next) {
17066 				if ((ilm->ilm_flags & ILM_DELETED) ||
17067 				    ipha->ipha_dst != ilm->ilm_addr ||
17068 				    ilm->ilm_zoneid == last_zoneid ||
17069 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17070 				    ilm->ilm_zoneid == ALL_ZONES ||
17071 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17072 					continue;
17073 				mp1 = ip_copymsg(first_mp);
17074 				if (mp1 == NULL)
17075 					continue;
17076 				icmp_inbound(q, mp1, B_TRUE, ill,
17077 				    0, sum, mctl_present, B_TRUE,
17078 				    recv_ill, ilm->ilm_zoneid);
17079 				last_zoneid = ilm->ilm_zoneid;
17080 			}
17081 			ILM_WALKER_RELE(recv_ill);
17082 		} else if (ire->ire_type == IRE_BROADCAST) {
17083 			/*
17084 			 * In the broadcast case, there may be many zones
17085 			 * which need a copy of the packet delivered to them.
17086 			 * There is one IRE_BROADCAST per broadcast address
17087 			 * and per zone; we walk those using a helper function.
17088 			 * In addition, the sending of the packet for ire is
17089 			 * delayed until all of the other ires have been
17090 			 * processed.
17091 			 */
17092 			IRB_REFHOLD(ire->ire_bucket);
17093 			ire_zone = NULL;
17094 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17095 			    ire)) != NULL) {
17096 				mp1 = ip_copymsg(first_mp);
17097 				if (mp1 == NULL)
17098 					continue;
17099 
17100 				UPDATE_IB_PKT_COUNT(ire_zone);
17101 				ire_zone->ire_last_used_time = lbolt;
17102 				icmp_inbound(q, mp1, B_TRUE, ill,
17103 				    0, sum, mctl_present, B_TRUE,
17104 				    recv_ill, ire_zone->ire_zoneid);
17105 			}
17106 			IRB_REFRELE(ire->ire_bucket);
17107 		}
17108 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17109 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17110 		    ire->ire_zoneid);
17111 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17112 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17113 		return;
17114 	}
17115 	case IPPROTO_IGMP:
17116 		/*
17117 		 * If we are not willing to accept IGMP packets in clear,
17118 		 * then check with global policy.
17119 		 */
17120 		if (igmp_accept_clear_messages == 0) {
17121 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17122 			    ipha, NULL, mctl_present);
17123 			if (first_mp == NULL)
17124 				return;
17125 		}
17126 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17127 			freemsg(first_mp);
17128 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17129 			BUMP_MIB(&ip_mib, ipInDiscards);
17130 			return;
17131 		}
17132 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17133 			/* Bad packet - discarded by igmp_input */
17134 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17135 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17136 			if (mctl_present)
17137 				freeb(first_mp);
17138 			return;
17139 		}
17140 		/*
17141 		 * igmp_input() may have returned the pulled up message.
17142 		 * So first_mp and ipha need to be reinitialized.
17143 		 */
17144 		ipha = (ipha_t *)mp->b_rptr;
17145 		if (mctl_present)
17146 			first_mp->b_cont = mp;
17147 		else
17148 			first_mp = mp;
17149 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17150 			/* No user-level listener for IGMP packets */
17151 			goto drop_pkt;
17152 		}
17153 		/* deliver to local raw users */
17154 		break;
17155 	case IPPROTO_PIM:
17156 		/*
17157 		 * If we are not willing to accept PIM packets in clear,
17158 		 * then check with global policy.
17159 		 */
17160 		if (pim_accept_clear_messages == 0) {
17161 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17162 			    ipha, NULL, mctl_present);
17163 			if (first_mp == NULL)
17164 				return;
17165 		}
17166 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17167 			freemsg(first_mp);
17168 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17169 			BUMP_MIB(&ip_mib, ipInDiscards);
17170 			return;
17171 		}
17172 		if (pim_input(q, mp) != 0) {
17173 			/* Bad packet - discarded by pim_input */
17174 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17175 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17176 			if (mctl_present)
17177 				freeb(first_mp);
17178 			return;
17179 		}
17180 
17181 		/*
17182 		 * pim_input() may have pulled up the message so ipha needs to
17183 		 * be reinitialized.
17184 		 */
17185 		ipha = (ipha_t *)mp->b_rptr;
17186 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17187 			/* No user-level listener for PIM packets */
17188 			goto drop_pkt;
17189 		}
17190 		/* deliver to local raw users */
17191 		break;
17192 	case IPPROTO_ENCAP:
17193 		/*
17194 		 * Handle self-encapsulated packets (IP-in-IP where
17195 		 * the inner addresses == the outer addresses).
17196 		 */
17197 		hdr_length = IPH_HDR_LENGTH(ipha);
17198 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17199 		    mp->b_wptr) {
17200 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17201 			    sizeof (ipha_t) - mp->b_rptr)) {
17202 				BUMP_MIB(&ip_mib, ipInDiscards);
17203 				freemsg(first_mp);
17204 				return;
17205 			}
17206 			ipha = (ipha_t *)mp->b_rptr;
17207 		}
17208 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17209 		/*
17210 		 * Check the sanity of the inner IP header.
17211 		 */
17212 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17213 			BUMP_MIB(&ip_mib, ipInDiscards);
17214 			freemsg(first_mp);
17215 			return;
17216 		}
17217 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17218 			BUMP_MIB(&ip_mib, ipInDiscards);
17219 			freemsg(first_mp);
17220 			return;
17221 		}
17222 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17223 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17224 			ipsec_in_t *ii;
17225 
17226 			/*
17227 			 * Self-encapsulated tunnel packet. Remove
17228 			 * the outer IP header and fanout again.
17229 			 * We also need to make sure that the inner
17230 			 * header is pulled up until options.
17231 			 */
17232 			mp->b_rptr = (uchar_t *)inner_ipha;
17233 			ipha = inner_ipha;
17234 			hdr_length = IPH_HDR_LENGTH(ipha);
17235 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17236 				if (!pullupmsg(mp, (uchar_t *)ipha +
17237 				    + hdr_length - mp->b_rptr)) {
17238 					freemsg(first_mp);
17239 					return;
17240 				}
17241 				ipha = (ipha_t *)mp->b_rptr;
17242 			}
17243 			if (!mctl_present) {
17244 				ASSERT(first_mp == mp);
17245 				/*
17246 				 * This means that somebody is sending
17247 				 * Self-encapsualted packets without AH/ESP.
17248 				 * If AH/ESP was present, we would have already
17249 				 * allocated the first_mp.
17250 				 */
17251 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
17252 				    NULL) {
17253 					ip1dbg(("ip_proto_input: IPSEC_IN "
17254 					    "allocation failure.\n"));
17255 					BUMP_MIB(&ip_mib, ipInDiscards);
17256 					freemsg(mp);
17257 					return;
17258 				}
17259 				first_mp->b_cont = mp;
17260 			}
17261 			/*
17262 			 * We generally store the ill_index if we need to
17263 			 * do IPSEC processing as we lose the ill queue when
17264 			 * we come back. But in this case, we never should
17265 			 * have to store the ill_index here as it should have
17266 			 * been stored previously when we processed the
17267 			 * AH/ESP header in this routine or for non-ipsec
17268 			 * cases, we still have the queue. But for some bad
17269 			 * packets from the wire, we can get to IPSEC after
17270 			 * this and we better store the index for that case.
17271 			 */
17272 			ill = (ill_t *)q->q_ptr;
17273 			ii = (ipsec_in_t *)first_mp->b_rptr;
17274 			ii->ipsec_in_ill_index =
17275 			    ill->ill_phyint->phyint_ifindex;
17276 			ii->ipsec_in_rill_index =
17277 			    recv_ill->ill_phyint->phyint_ifindex;
17278 			if (ii->ipsec_in_decaps) {
17279 				/*
17280 				 * This packet is self-encapsulated multiple
17281 				 * times. We don't want to recurse infinitely.
17282 				 * To keep it simple, drop the packet.
17283 				 */
17284 				BUMP_MIB(&ip_mib, ipInDiscards);
17285 				freemsg(first_mp);
17286 				return;
17287 			}
17288 			ii->ipsec_in_decaps = B_TRUE;
17289 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17290 			    ire);
17291 			return;
17292 		}
17293 		break;
17294 	case IPPROTO_AH:
17295 	case IPPROTO_ESP: {
17296 		/*
17297 		 * Fast path for AH/ESP. If this is the first time
17298 		 * we are sending a datagram to AH/ESP, allocate
17299 		 * a IPSEC_IN message and prepend it. Otherwise,
17300 		 * just fanout.
17301 		 */
17302 
17303 		int ipsec_rc;
17304 		ipsec_in_t *ii;
17305 
17306 		IP_STAT(ipsec_proto_ahesp);
17307 		if (!mctl_present) {
17308 			ASSERT(first_mp == mp);
17309 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
17310 				ip1dbg(("ip_proto_input: IPSEC_IN "
17311 				    "allocation failure.\n"));
17312 				freemsg(hada_mp); /* okay ifnull */
17313 				BUMP_MIB(&ip_mib, ipInDiscards);
17314 				freemsg(mp);
17315 				return;
17316 			}
17317 			/*
17318 			 * Store the ill_index so that when we come back
17319 			 * from IPSEC we ride on the same queue.
17320 			 */
17321 			ill = (ill_t *)q->q_ptr;
17322 			ii = (ipsec_in_t *)first_mp->b_rptr;
17323 			ii->ipsec_in_ill_index =
17324 			    ill->ill_phyint->phyint_ifindex;
17325 			ii->ipsec_in_rill_index =
17326 			    recv_ill->ill_phyint->phyint_ifindex;
17327 			first_mp->b_cont = mp;
17328 			/*
17329 			 * Cache hardware acceleration info.
17330 			 */
17331 			if (hada_mp != NULL) {
17332 				IPSECHW_DEBUG(IPSECHW_PKT,
17333 				    ("ip_rput_local: caching data attr.\n"));
17334 				ii->ipsec_in_accelerated = B_TRUE;
17335 				ii->ipsec_in_da = hada_mp;
17336 				hada_mp = NULL;
17337 			}
17338 		} else {
17339 			ii = (ipsec_in_t *)first_mp->b_rptr;
17340 		}
17341 
17342 		if (!ipsec_loaded()) {
17343 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17344 			    ire->ire_zoneid);
17345 			return;
17346 		}
17347 
17348 		/* select inbound SA and have IPsec process the pkt */
17349 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17350 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17351 			if (esph == NULL)
17352 				return;
17353 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17354 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17355 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17356 			    first_mp, esph);
17357 		} else {
17358 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17359 			if (ah == NULL)
17360 				return;
17361 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17362 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17363 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17364 			    first_mp, ah);
17365 		}
17366 
17367 		switch (ipsec_rc) {
17368 		case IPSEC_STATUS_SUCCESS:
17369 			break;
17370 		case IPSEC_STATUS_FAILED:
17371 			BUMP_MIB(&ip_mib, ipInDiscards);
17372 			/* FALLTHRU */
17373 		case IPSEC_STATUS_PENDING:
17374 			return;
17375 		}
17376 		/* we're done with IPsec processing, send it up */
17377 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17378 		return;
17379 	}
17380 	default:
17381 		break;
17382 	}
17383 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17384 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17385 		    ire->ire_zoneid));
17386 		goto drop_pkt;
17387 	}
17388 	/*
17389 	 * Handle protocols with which IP is less intimate.  There
17390 	 * can be more than one stream bound to a particular
17391 	 * protocol.  When this is the case, each one gets a copy
17392 	 * of any incoming packets.
17393 	 */
17394 	ip_fanout_proto(q, first_mp, ill, ipha,
17395 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17396 	    B_TRUE, recv_ill, ire->ire_zoneid);
17397 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17398 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17399 	return;
17400 
17401 drop_pkt:
17402 	freemsg(first_mp);
17403 	if (hada_mp != NULL)
17404 		freeb(hada_mp);
17405 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17406 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17407 #undef	rptr
17408 #undef  iphs
17409 
17410 }
17411 
17412 /*
17413  * Update any source route, record route or timestamp options.
17414  * Check that we are at end of strict source route.
17415  * The options have already been checked for sanity in ip_rput_options().
17416  */
17417 static boolean_t
17418 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17419 {
17420 	ipoptp_t	opts;
17421 	uchar_t		*opt;
17422 	uint8_t		optval;
17423 	uint8_t		optlen;
17424 	ipaddr_t	dst;
17425 	uint32_t	ts;
17426 	ire_t		*dst_ire;
17427 	timestruc_t	now;
17428 	zoneid_t	zoneid;
17429 	ill_t		*ill;
17430 
17431 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17432 
17433 	ip2dbg(("ip_rput_local_options\n"));
17434 
17435 	for (optval = ipoptp_first(&opts, ipha);
17436 	    optval != IPOPT_EOL;
17437 	    optval = ipoptp_next(&opts)) {
17438 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17439 		opt = opts.ipoptp_cur;
17440 		optlen = opts.ipoptp_len;
17441 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17442 		    optval, optlen));
17443 		switch (optval) {
17444 			uint32_t off;
17445 		case IPOPT_SSRR:
17446 		case IPOPT_LSRR:
17447 			off = opt[IPOPT_OFFSET];
17448 			off--;
17449 			if (optlen < IP_ADDR_LEN ||
17450 			    off > optlen - IP_ADDR_LEN) {
17451 				/* End of source route */
17452 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17453 				break;
17454 			}
17455 			/*
17456 			 * This will only happen if two consecutive entries
17457 			 * in the source route contains our address or if
17458 			 * it is a packet with a loose source route which
17459 			 * reaches us before consuming the whole source route
17460 			 */
17461 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17462 			if (optval == IPOPT_SSRR) {
17463 				goto bad_src_route;
17464 			}
17465 			/*
17466 			 * Hack: instead of dropping the packet truncate the
17467 			 * source route to what has been used by filling the
17468 			 * rest with IPOPT_NOP.
17469 			 */
17470 			opt[IPOPT_OLEN] = (uint8_t)off;
17471 			while (off < optlen) {
17472 				opt[off++] = IPOPT_NOP;
17473 			}
17474 			break;
17475 		case IPOPT_RR:
17476 			off = opt[IPOPT_OFFSET];
17477 			off--;
17478 			if (optlen < IP_ADDR_LEN ||
17479 			    off > optlen - IP_ADDR_LEN) {
17480 				/* No more room - ignore */
17481 				ip1dbg((
17482 				    "ip_rput_local_options: end of RR\n"));
17483 				break;
17484 			}
17485 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17486 			    IP_ADDR_LEN);
17487 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17488 			break;
17489 		case IPOPT_TS:
17490 			/* Insert timestamp if there is romm */
17491 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17492 			case IPOPT_TS_TSONLY:
17493 				off = IPOPT_TS_TIMELEN;
17494 				break;
17495 			case IPOPT_TS_PRESPEC:
17496 			case IPOPT_TS_PRESPEC_RFC791:
17497 				/* Verify that the address matched */
17498 				off = opt[IPOPT_OFFSET] - 1;
17499 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17500 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17501 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17502 				if (dst_ire == NULL) {
17503 					/* Not for us */
17504 					break;
17505 				}
17506 				ire_refrele(dst_ire);
17507 				/* FALLTHRU */
17508 			case IPOPT_TS_TSANDADDR:
17509 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17510 				break;
17511 			default:
17512 				/*
17513 				 * ip_*put_options should have already
17514 				 * dropped this packet.
17515 				 */
17516 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17517 				    "unknown IT - bug in ip_rput_options?\n");
17518 				return (B_TRUE);	/* Keep "lint" happy */
17519 			}
17520 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17521 				/* Increase overflow counter */
17522 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17523 				opt[IPOPT_POS_OV_FLG] =
17524 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17525 				    (off << 4));
17526 				break;
17527 			}
17528 			off = opt[IPOPT_OFFSET] - 1;
17529 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17530 			case IPOPT_TS_PRESPEC:
17531 			case IPOPT_TS_PRESPEC_RFC791:
17532 			case IPOPT_TS_TSANDADDR:
17533 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17534 				    IP_ADDR_LEN);
17535 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17536 				/* FALLTHRU */
17537 			case IPOPT_TS_TSONLY:
17538 				off = opt[IPOPT_OFFSET] - 1;
17539 				/* Compute # of milliseconds since midnight */
17540 				gethrestime(&now);
17541 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17542 				    now.tv_nsec / (NANOSEC / MILLISEC);
17543 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17544 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17545 				break;
17546 			}
17547 			break;
17548 		}
17549 	}
17550 	return (B_TRUE);
17551 
17552 bad_src_route:
17553 	q = WR(q);
17554 	if (q->q_next != NULL)
17555 		ill = q->q_ptr;
17556 	else
17557 		ill = NULL;
17558 
17559 	/* make sure we clear any indication of a hardware checksum */
17560 	DB_CKSUMFLAGS(mp) = 0;
17561 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill);
17562 	if (zoneid == ALL_ZONES)
17563 		freemsg(mp);
17564 	else
17565 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17566 	return (B_FALSE);
17567 
17568 }
17569 
17570 /*
17571  * Process IP options in an inbound packet.  If an option affects the
17572  * effective destination address, return the next hop address via dstp.
17573  * Returns -1 if something fails in which case an ICMP error has been sent
17574  * and mp freed.
17575  */
17576 static int
17577 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17578 {
17579 	ipoptp_t	opts;
17580 	uchar_t		*opt;
17581 	uint8_t		optval;
17582 	uint8_t		optlen;
17583 	ipaddr_t	dst;
17584 	intptr_t	code = 0;
17585 	ire_t		*ire = NULL;
17586 	zoneid_t	zoneid;
17587 	ill_t		*ill;
17588 
17589 	ip2dbg(("ip_rput_options\n"));
17590 	dst = ipha->ipha_dst;
17591 	for (optval = ipoptp_first(&opts, ipha);
17592 	    optval != IPOPT_EOL;
17593 	    optval = ipoptp_next(&opts)) {
17594 		opt = opts.ipoptp_cur;
17595 		optlen = opts.ipoptp_len;
17596 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17597 		    optval, optlen));
17598 		/*
17599 		 * Note: we need to verify the checksum before we
17600 		 * modify anything thus this routine only extracts the next
17601 		 * hop dst from any source route.
17602 		 */
17603 		switch (optval) {
17604 			uint32_t off;
17605 		case IPOPT_SSRR:
17606 		case IPOPT_LSRR:
17607 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17608 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17609 			if (ire == NULL) {
17610 				if (optval == IPOPT_SSRR) {
17611 					ip1dbg(("ip_rput_options: not next"
17612 					    " strict source route 0x%x\n",
17613 					    ntohl(dst)));
17614 					code = (char *)&ipha->ipha_dst -
17615 					    (char *)ipha;
17616 					goto param_prob; /* RouterReq's */
17617 				}
17618 				ip2dbg(("ip_rput_options: "
17619 				    "not next source route 0x%x\n",
17620 				    ntohl(dst)));
17621 				break;
17622 			}
17623 			ire_refrele(ire);
17624 
17625 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17626 				ip1dbg((
17627 				    "ip_rput_options: bad option offset\n"));
17628 				code = (char *)&opt[IPOPT_OLEN] -
17629 				    (char *)ipha;
17630 				goto param_prob;
17631 			}
17632 			off = opt[IPOPT_OFFSET];
17633 			off--;
17634 		redo_srr:
17635 			if (optlen < IP_ADDR_LEN ||
17636 			    off > optlen - IP_ADDR_LEN) {
17637 				/* End of source route */
17638 				ip1dbg(("ip_rput_options: end of SR\n"));
17639 				break;
17640 			}
17641 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17642 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17643 			    ntohl(dst)));
17644 
17645 			/*
17646 			 * Check if our address is present more than
17647 			 * once as consecutive hops in source route.
17648 			 * XXX verify per-interface ip_forwarding
17649 			 * for source route?
17650 			 */
17651 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17652 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17653 
17654 			if (ire != NULL) {
17655 				ire_refrele(ire);
17656 				off += IP_ADDR_LEN;
17657 				goto redo_srr;
17658 			}
17659 
17660 			if (dst == htonl(INADDR_LOOPBACK)) {
17661 				ip1dbg(("ip_rput_options: loopback addr in "
17662 				    "source route!\n"));
17663 				goto bad_src_route;
17664 			}
17665 			/*
17666 			 * For strict: verify that dst is directly
17667 			 * reachable.
17668 			 */
17669 			if (optval == IPOPT_SSRR) {
17670 				ire = ire_ftable_lookup(dst, 0, 0,
17671 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17672 				    MBLK_GETLABEL(mp),
17673 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17674 				if (ire == NULL) {
17675 					ip1dbg(("ip_rput_options: SSRR not "
17676 					    "directly reachable: 0x%x\n",
17677 					    ntohl(dst)));
17678 					goto bad_src_route;
17679 				}
17680 				ire_refrele(ire);
17681 			}
17682 			/*
17683 			 * Defer update of the offset and the record route
17684 			 * until the packet is forwarded.
17685 			 */
17686 			break;
17687 		case IPOPT_RR:
17688 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17689 				ip1dbg((
17690 				    "ip_rput_options: bad option offset\n"));
17691 				code = (char *)&opt[IPOPT_OLEN] -
17692 				    (char *)ipha;
17693 				goto param_prob;
17694 			}
17695 			break;
17696 		case IPOPT_TS:
17697 			/*
17698 			 * Verify that length >= 5 and that there is either
17699 			 * room for another timestamp or that the overflow
17700 			 * counter is not maxed out.
17701 			 */
17702 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17703 			if (optlen < IPOPT_MINLEN_IT) {
17704 				goto param_prob;
17705 			}
17706 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17707 				ip1dbg((
17708 				    "ip_rput_options: bad option offset\n"));
17709 				code = (char *)&opt[IPOPT_OFFSET] -
17710 				    (char *)ipha;
17711 				goto param_prob;
17712 			}
17713 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17714 			case IPOPT_TS_TSONLY:
17715 				off = IPOPT_TS_TIMELEN;
17716 				break;
17717 			case IPOPT_TS_TSANDADDR:
17718 			case IPOPT_TS_PRESPEC:
17719 			case IPOPT_TS_PRESPEC_RFC791:
17720 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17721 				break;
17722 			default:
17723 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17724 				    (char *)ipha;
17725 				goto param_prob;
17726 			}
17727 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17728 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17729 				/*
17730 				 * No room and the overflow counter is 15
17731 				 * already.
17732 				 */
17733 				goto param_prob;
17734 			}
17735 			break;
17736 		}
17737 	}
17738 
17739 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17740 		*dstp = dst;
17741 		return (0);
17742 	}
17743 
17744 	ip1dbg(("ip_rput_options: error processing IP options."));
17745 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17746 
17747 param_prob:
17748 	q = WR(q);
17749 	if (q->q_next != NULL)
17750 		ill = q->q_ptr;
17751 	else
17752 		ill = NULL;
17753 
17754 	/* make sure we clear any indication of a hardware checksum */
17755 	DB_CKSUMFLAGS(mp) = 0;
17756 	/* Don't know whether this is for non-global or global/forwarding */
17757 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17758 	if (zoneid == ALL_ZONES)
17759 		freemsg(mp);
17760 	else
17761 		icmp_param_problem(q, mp, (uint8_t)code, zoneid);
17762 	return (-1);
17763 
17764 bad_src_route:
17765 	q = WR(q);
17766 	if (q->q_next != NULL)
17767 		ill = q->q_ptr;
17768 	else
17769 		ill = NULL;
17770 
17771 	/* make sure we clear any indication of a hardware checksum */
17772 	DB_CKSUMFLAGS(mp) = 0;
17773 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17774 	if (zoneid == ALL_ZONES)
17775 		freemsg(mp);
17776 	else
17777 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17778 	return (-1);
17779 }
17780 
17781 /*
17782  * IP & ICMP info in >=14 msg's ...
17783  *  - ip fixed part (mib2_ip_t)
17784  *  - icmp fixed part (mib2_icmp_t)
17785  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17786  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17787  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17788  *  - ipRouteAttributeTable (ip 102)	labeled routes
17789  *  - ip multicast membership (ip_member_t)
17790  *  - ip multicast source filtering (ip_grpsrc_t)
17791  *  - igmp fixed part (struct igmpstat)
17792  *  - multicast routing stats (struct mrtstat)
17793  *  - multicast routing vifs (array of struct vifctl)
17794  *  - multicast routing routes (array of struct mfcctl)
17795  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17796  *					One per ill plus one generic
17797  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17798  *					One per ill plus one generic
17799  *  - ipv6RouteEntry			all IPv6 IREs
17800  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17801  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17802  *  - ipv6AddrEntry			all IPv6 ipifs
17803  *  - ipv6 multicast membership (ipv6_member_t)
17804  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17805  *
17806  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17807  *
17808  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17809  * already filled in by the caller.
17810  * Return value of 0 indicates that no messages were sent and caller
17811  * should free mpctl.
17812  */
17813 int
17814 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17815 {
17816 
17817 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17818 		return (0);
17819 	}
17820 
17821 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
17822 		return (1);
17823 	}
17824 
17825 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17826 		return (1);
17827 	}
17828 
17829 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17830 		return (1);
17831 	}
17832 
17833 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17834 		return (1);
17835 	}
17836 
17837 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17838 		return (1);
17839 	}
17840 
17841 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17842 		return (1);
17843 	}
17844 
17845 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17846 		return (1);
17847 	}
17848 
17849 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17850 		return (1);
17851 	}
17852 
17853 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17854 		return (1);
17855 	}
17856 
17857 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17858 		return (1);
17859 	}
17860 
17861 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17862 		return (1);
17863 	}
17864 
17865 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17866 		return (1);
17867 	}
17868 
17869 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17870 		return (1);
17871 	}
17872 
17873 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17874 		return (1);
17875 	}
17876 
17877 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17878 		return (1);
17879 	}
17880 
17881 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17882 		return (1);
17883 	}
17884 
17885 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17886 		return (1);
17887 	}
17888 	freemsg(mpctl);
17889 	return (1);
17890 }
17891 
17892 
17893 /* Get global IPv4 statistics */
17894 static mblk_t *
17895 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
17896 {
17897 	struct opthdr		*optp;
17898 	mblk_t			*mp2ctl;
17899 
17900 	/*
17901 	 * make a copy of the original message
17902 	 */
17903 	mp2ctl = copymsg(mpctl);
17904 
17905 	/* fixed length IP structure... */
17906 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17907 	optp->level = MIB2_IP;
17908 	optp->name = 0;
17909 	SET_MIB(ip_mib.ipForwarding,
17910 	    (WE_ARE_FORWARDING ? 1 : 2));
17911 	SET_MIB(ip_mib.ipDefaultTTL,
17912 	    (uint32_t)ip_def_ttl);
17913 	SET_MIB(ip_mib.ipReasmTimeout,
17914 	    ip_g_frag_timeout);
17915 	SET_MIB(ip_mib.ipAddrEntrySize,
17916 	    sizeof (mib2_ipAddrEntry_t));
17917 	SET_MIB(ip_mib.ipRouteEntrySize,
17918 	    sizeof (mib2_ipRouteEntry_t));
17919 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
17920 	    sizeof (mib2_ipNetToMediaEntry_t));
17921 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17922 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17923 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
17924 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17925 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
17926 	    (int)sizeof (ip_mib))) {
17927 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17928 		    (uint_t)sizeof (ip_mib)));
17929 	}
17930 
17931 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17932 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17933 	    (int)optp->level, (int)optp->name, (int)optp->len));
17934 	qreply(q, mpctl);
17935 	return (mp2ctl);
17936 }
17937 
17938 /* Global IPv4 ICMP statistics */
17939 static mblk_t *
17940 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
17941 {
17942 	struct opthdr		*optp;
17943 	mblk_t			*mp2ctl;
17944 
17945 	/*
17946 	 * Make a copy of the original message
17947 	 */
17948 	mp2ctl = copymsg(mpctl);
17949 
17950 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17951 	optp->level = MIB2_ICMP;
17952 	optp->name = 0;
17953 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17954 	    (int)sizeof (icmp_mib))) {
17955 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17956 		    (uint_t)sizeof (icmp_mib)));
17957 	}
17958 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17959 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17960 	    (int)optp->level, (int)optp->name, (int)optp->len));
17961 	qreply(q, mpctl);
17962 	return (mp2ctl);
17963 }
17964 
17965 /* Global IPv4 IGMP statistics */
17966 static mblk_t *
17967 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17968 {
17969 	struct opthdr		*optp;
17970 	mblk_t			*mp2ctl;
17971 
17972 	/*
17973 	 * make a copy of the original message
17974 	 */
17975 	mp2ctl = copymsg(mpctl);
17976 
17977 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17978 	optp->level = EXPER_IGMP;
17979 	optp->name = 0;
17980 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17981 	    (int)sizeof (igmpstat))) {
17982 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17983 		    (uint_t)sizeof (igmpstat)));
17984 	}
17985 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17986 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17987 	    (int)optp->level, (int)optp->name, (int)optp->len));
17988 	qreply(q, mpctl);
17989 	return (mp2ctl);
17990 }
17991 
17992 /* Global IPv4 Multicast Routing statistics */
17993 static mblk_t *
17994 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17995 {
17996 	struct opthdr		*optp;
17997 	mblk_t			*mp2ctl;
17998 
17999 	/*
18000 	 * make a copy of the original message
18001 	 */
18002 	mp2ctl = copymsg(mpctl);
18003 
18004 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18005 	optp->level = EXPER_DVMRP;
18006 	optp->name = 0;
18007 	if (!ip_mroute_stats(mpctl->b_cont)) {
18008 		ip0dbg(("ip_mroute_stats: failed\n"));
18009 	}
18010 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18011 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18012 	    (int)optp->level, (int)optp->name, (int)optp->len));
18013 	qreply(q, mpctl);
18014 	return (mp2ctl);
18015 }
18016 
18017 /* IPv4 address information */
18018 static mblk_t *
18019 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
18020 {
18021 	struct opthdr		*optp;
18022 	mblk_t			*mp2ctl;
18023 	mblk_t			*mp_tail = NULL;
18024 	ill_t			*ill;
18025 	ipif_t			*ipif;
18026 	uint_t			bitval;
18027 	mib2_ipAddrEntry_t	mae;
18028 	zoneid_t		zoneid;
18029 	ill_walk_context_t ctx;
18030 
18031 	/*
18032 	 * make a copy of the original message
18033 	 */
18034 	mp2ctl = copymsg(mpctl);
18035 
18036 	/* ipAddrEntryTable */
18037 
18038 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18039 	optp->level = MIB2_IP;
18040 	optp->name = MIB2_IP_ADDR;
18041 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18042 
18043 	rw_enter(&ill_g_lock, RW_READER);
18044 	ill = ILL_START_WALK_V4(&ctx);
18045 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18046 		for (ipif = ill->ill_ipif; ipif != NULL;
18047 		    ipif = ipif->ipif_next) {
18048 			if (ipif->ipif_zoneid != zoneid &&
18049 			    ipif->ipif_zoneid != ALL_ZONES)
18050 				continue;
18051 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18052 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18053 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18054 
18055 			(void) ipif_get_name(ipif,
18056 			    mae.ipAdEntIfIndex.o_bytes,
18057 			    OCTET_LENGTH);
18058 			mae.ipAdEntIfIndex.o_length =
18059 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18060 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18061 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18062 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18063 			mae.ipAdEntInfo.ae_subnet_len =
18064 			    ip_mask_to_plen(ipif->ipif_net_mask);
18065 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18066 			for (bitval = 1;
18067 			    bitval &&
18068 			    !(bitval & ipif->ipif_brd_addr);
18069 			    bitval <<= 1)
18070 				noop;
18071 			mae.ipAdEntBcastAddr = bitval;
18072 			mae.ipAdEntReasmMaxSize = 65535;
18073 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18074 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18075 			mae.ipAdEntInfo.ae_broadcast_addr =
18076 			    ipif->ipif_brd_addr;
18077 			mae.ipAdEntInfo.ae_pp_dst_addr =
18078 			    ipif->ipif_pp_dst_addr;
18079 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18080 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18081 
18082 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18083 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18084 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18085 				    "allocate %u bytes\n",
18086 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18087 			}
18088 		}
18089 	}
18090 	rw_exit(&ill_g_lock);
18091 
18092 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18093 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18094 	    (int)optp->level, (int)optp->name, (int)optp->len));
18095 	qreply(q, mpctl);
18096 	return (mp2ctl);
18097 }
18098 
18099 /* IPv6 address information */
18100 static mblk_t *
18101 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
18102 {
18103 	struct opthdr		*optp;
18104 	mblk_t			*mp2ctl;
18105 	mblk_t			*mp_tail = NULL;
18106 	ill_t			*ill;
18107 	ipif_t			*ipif;
18108 	mib2_ipv6AddrEntry_t	mae6;
18109 	zoneid_t		zoneid;
18110 	ill_walk_context_t	ctx;
18111 
18112 	/*
18113 	 * make a copy of the original message
18114 	 */
18115 	mp2ctl = copymsg(mpctl);
18116 
18117 	/* ipv6AddrEntryTable */
18118 
18119 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18120 	optp->level = MIB2_IP6;
18121 	optp->name = MIB2_IP6_ADDR;
18122 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18123 
18124 	rw_enter(&ill_g_lock, RW_READER);
18125 	ill = ILL_START_WALK_V6(&ctx);
18126 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18127 		for (ipif = ill->ill_ipif; ipif != NULL;
18128 		    ipif = ipif->ipif_next) {
18129 			if (ipif->ipif_zoneid != zoneid &&
18130 			    ipif->ipif_zoneid != ALL_ZONES)
18131 				continue;
18132 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18133 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18134 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18135 
18136 			(void) ipif_get_name(ipif,
18137 			    mae6.ipv6AddrIfIndex.o_bytes,
18138 			    OCTET_LENGTH);
18139 			mae6.ipv6AddrIfIndex.o_length =
18140 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18141 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18142 			mae6.ipv6AddrPfxLength =
18143 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18144 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18145 			mae6.ipv6AddrInfo.ae_subnet_len =
18146 			    mae6.ipv6AddrPfxLength;
18147 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18148 
18149 			/* Type: stateless(1), stateful(2), unknown(3) */
18150 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18151 				mae6.ipv6AddrType = 1;
18152 			else
18153 				mae6.ipv6AddrType = 2;
18154 			/* Anycast: true(1), false(2) */
18155 			if (ipif->ipif_flags & IPIF_ANYCAST)
18156 				mae6.ipv6AddrAnycastFlag = 1;
18157 			else
18158 				mae6.ipv6AddrAnycastFlag = 2;
18159 
18160 			/*
18161 			 * Address status: preferred(1), deprecated(2),
18162 			 * invalid(3), inaccessible(4), unknown(5)
18163 			 */
18164 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18165 				mae6.ipv6AddrStatus = 3;
18166 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18167 				mae6.ipv6AddrStatus = 2;
18168 			else
18169 				mae6.ipv6AddrStatus = 1;
18170 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18171 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18172 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18173 						ipif->ipif_v6pp_dst_addr;
18174 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18175 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18176 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18177 				(char *)&mae6,
18178 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18179 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18180 				    "allocate %u bytes\n",
18181 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18182 			}
18183 		}
18184 	}
18185 	rw_exit(&ill_g_lock);
18186 
18187 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18188 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: 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 /* IPv4 multicast group membership. */
18195 static mblk_t *
18196 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
18197 {
18198 	struct opthdr		*optp;
18199 	mblk_t			*mp2ctl;
18200 	ill_t			*ill;
18201 	ipif_t			*ipif;
18202 	ilm_t			*ilm;
18203 	ip_member_t		ipm;
18204 	mblk_t			*mp_tail = NULL;
18205 	ill_walk_context_t	ctx;
18206 	zoneid_t		zoneid;
18207 
18208 	/*
18209 	 * make a copy of the original message
18210 	 */
18211 	mp2ctl = copymsg(mpctl);
18212 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18213 
18214 	/* ipGroupMember table */
18215 	optp = (struct opthdr *)&mpctl->b_rptr[
18216 	    sizeof (struct T_optmgmt_ack)];
18217 	optp->level = MIB2_IP;
18218 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18219 
18220 	rw_enter(&ill_g_lock, RW_READER);
18221 	ill = ILL_START_WALK_V4(&ctx);
18222 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18223 		ILM_WALKER_HOLD(ill);
18224 		for (ipif = ill->ill_ipif; ipif != NULL;
18225 		    ipif = ipif->ipif_next) {
18226 			if (ipif->ipif_zoneid != zoneid &&
18227 			    ipif->ipif_zoneid != ALL_ZONES)
18228 				continue;	/* not this zone */
18229 			(void) ipif_get_name(ipif,
18230 			    ipm.ipGroupMemberIfIndex.o_bytes,
18231 			    OCTET_LENGTH);
18232 			ipm.ipGroupMemberIfIndex.o_length =
18233 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18234 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18235 				ASSERT(ilm->ilm_ipif != NULL);
18236 				ASSERT(ilm->ilm_ill == NULL);
18237 				if (ilm->ilm_ipif != ipif)
18238 					continue;
18239 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18240 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18241 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18242 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18243 				    (char *)&ipm, (int)sizeof (ipm))) {
18244 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18245 					    "failed to allocate %u bytes\n",
18246 						(uint_t)sizeof (ipm)));
18247 				}
18248 			}
18249 		}
18250 		ILM_WALKER_RELE(ill);
18251 	}
18252 	rw_exit(&ill_g_lock);
18253 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18254 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18255 	    (int)optp->level, (int)optp->name, (int)optp->len));
18256 	qreply(q, mpctl);
18257 	return (mp2ctl);
18258 }
18259 
18260 /* IPv6 multicast group membership. */
18261 static mblk_t *
18262 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
18263 {
18264 	struct opthdr		*optp;
18265 	mblk_t			*mp2ctl;
18266 	ill_t			*ill;
18267 	ilm_t			*ilm;
18268 	ipv6_member_t		ipm6;
18269 	mblk_t			*mp_tail = NULL;
18270 	ill_walk_context_t	ctx;
18271 	zoneid_t		zoneid;
18272 
18273 	/*
18274 	 * make a copy of the original message
18275 	 */
18276 	mp2ctl = copymsg(mpctl);
18277 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18278 
18279 	/* ip6GroupMember table */
18280 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18281 	optp->level = MIB2_IP6;
18282 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18283 
18284 	rw_enter(&ill_g_lock, RW_READER);
18285 	ill = ILL_START_WALK_V6(&ctx);
18286 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18287 		ILM_WALKER_HOLD(ill);
18288 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18289 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18290 			ASSERT(ilm->ilm_ipif == NULL);
18291 			ASSERT(ilm->ilm_ill != NULL);
18292 			if (ilm->ilm_zoneid != zoneid)
18293 				continue;	/* not this zone */
18294 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18295 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18296 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18297 			if (!snmp_append_data2(mpctl->b_cont,
18298 			    &mp_tail,
18299 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18300 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18301 				    "failed to allocate %u bytes\n",
18302 				    (uint_t)sizeof (ipm6)));
18303 			}
18304 		}
18305 		ILM_WALKER_RELE(ill);
18306 	}
18307 	rw_exit(&ill_g_lock);
18308 
18309 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18310 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18311 	    (int)optp->level, (int)optp->name, (int)optp->len));
18312 	qreply(q, mpctl);
18313 	return (mp2ctl);
18314 }
18315 
18316 /* IP multicast filtered sources */
18317 static mblk_t *
18318 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
18319 {
18320 	struct opthdr		*optp;
18321 	mblk_t			*mp2ctl;
18322 	ill_t			*ill;
18323 	ipif_t			*ipif;
18324 	ilm_t			*ilm;
18325 	ip_grpsrc_t		ips;
18326 	mblk_t			*mp_tail = NULL;
18327 	ill_walk_context_t	ctx;
18328 	zoneid_t		zoneid;
18329 	int			i;
18330 	slist_t			*sl;
18331 
18332 	/*
18333 	 * make a copy of the original message
18334 	 */
18335 	mp2ctl = copymsg(mpctl);
18336 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18337 
18338 	/* ipGroupSource table */
18339 	optp = (struct opthdr *)&mpctl->b_rptr[
18340 	    sizeof (struct T_optmgmt_ack)];
18341 	optp->level = MIB2_IP;
18342 	optp->name = EXPER_IP_GROUP_SOURCES;
18343 
18344 	rw_enter(&ill_g_lock, RW_READER);
18345 	ill = ILL_START_WALK_V4(&ctx);
18346 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18347 		ILM_WALKER_HOLD(ill);
18348 		for (ipif = ill->ill_ipif; ipif != NULL;
18349 		    ipif = ipif->ipif_next) {
18350 			if (ipif->ipif_zoneid != zoneid)
18351 				continue;	/* not this zone */
18352 			(void) ipif_get_name(ipif,
18353 			    ips.ipGroupSourceIfIndex.o_bytes,
18354 			    OCTET_LENGTH);
18355 			ips.ipGroupSourceIfIndex.o_length =
18356 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18357 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18358 				ASSERT(ilm->ilm_ipif != NULL);
18359 				ASSERT(ilm->ilm_ill == NULL);
18360 				sl = ilm->ilm_filter;
18361 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18362 					continue;
18363 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18364 				for (i = 0; i < sl->sl_numsrc; i++) {
18365 					if (!IN6_IS_ADDR_V4MAPPED(
18366 					    &sl->sl_addr[i]))
18367 						continue;
18368 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18369 					    ips.ipGroupSourceAddress);
18370 					if (snmp_append_data2(mpctl->b_cont,
18371 					    &mp_tail, (char *)&ips,
18372 					    (int)sizeof (ips)) == 0) {
18373 						ip1dbg(("ip_snmp_get_mib2_"
18374 						    "ip_group_src: failed to "
18375 						    "allocate %u bytes\n",
18376 						    (uint_t)sizeof (ips)));
18377 					}
18378 				}
18379 			}
18380 		}
18381 		ILM_WALKER_RELE(ill);
18382 	}
18383 	rw_exit(&ill_g_lock);
18384 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18385 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18386 	    (int)optp->level, (int)optp->name, (int)optp->len));
18387 	qreply(q, mpctl);
18388 	return (mp2ctl);
18389 }
18390 
18391 /* IPv6 multicast filtered sources. */
18392 static mblk_t *
18393 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18394 {
18395 	struct opthdr		*optp;
18396 	mblk_t			*mp2ctl;
18397 	ill_t			*ill;
18398 	ilm_t			*ilm;
18399 	ipv6_grpsrc_t		ips6;
18400 	mblk_t			*mp_tail = NULL;
18401 	ill_walk_context_t	ctx;
18402 	zoneid_t		zoneid;
18403 	int			i;
18404 	slist_t			*sl;
18405 
18406 	/*
18407 	 * make a copy of the original message
18408 	 */
18409 	mp2ctl = copymsg(mpctl);
18410 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18411 
18412 	/* ip6GroupMember table */
18413 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18414 	optp->level = MIB2_IP6;
18415 	optp->name = EXPER_IP6_GROUP_SOURCES;
18416 
18417 	rw_enter(&ill_g_lock, RW_READER);
18418 	ill = ILL_START_WALK_V6(&ctx);
18419 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18420 		ILM_WALKER_HOLD(ill);
18421 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18422 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18423 			ASSERT(ilm->ilm_ipif == NULL);
18424 			ASSERT(ilm->ilm_ill != NULL);
18425 			sl = ilm->ilm_filter;
18426 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18427 				continue;
18428 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18429 			for (i = 0; i < sl->sl_numsrc; i++) {
18430 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18431 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18432 				    (char *)&ips6, (int)sizeof (ips6))) {
18433 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18434 					    "group_src: failed to allocate "
18435 					    "%u bytes\n",
18436 					    (uint_t)sizeof (ips6)));
18437 				}
18438 			}
18439 		}
18440 		ILM_WALKER_RELE(ill);
18441 	}
18442 	rw_exit(&ill_g_lock);
18443 
18444 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18445 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18446 	    (int)optp->level, (int)optp->name, (int)optp->len));
18447 	qreply(q, mpctl);
18448 	return (mp2ctl);
18449 }
18450 
18451 /* Multicast routing virtual interface table. */
18452 static mblk_t *
18453 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18454 {
18455 	struct opthdr		*optp;
18456 	mblk_t			*mp2ctl;
18457 
18458 	/*
18459 	 * make a copy of the original message
18460 	 */
18461 	mp2ctl = copymsg(mpctl);
18462 
18463 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18464 	optp->level = EXPER_DVMRP;
18465 	optp->name = EXPER_DVMRP_VIF;
18466 	if (!ip_mroute_vif(mpctl->b_cont)) {
18467 		ip0dbg(("ip_mroute_vif: failed\n"));
18468 	}
18469 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18470 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18471 	    (int)optp->level, (int)optp->name, (int)optp->len));
18472 	qreply(q, mpctl);
18473 	return (mp2ctl);
18474 }
18475 
18476 /* Multicast routing table. */
18477 static mblk_t *
18478 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18479 {
18480 	struct opthdr		*optp;
18481 	mblk_t			*mp2ctl;
18482 
18483 	/*
18484 	 * make a copy of the original message
18485 	 */
18486 	mp2ctl = copymsg(mpctl);
18487 
18488 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18489 	optp->level = EXPER_DVMRP;
18490 	optp->name = EXPER_DVMRP_MRT;
18491 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18492 		ip0dbg(("ip_mroute_mrt: failed\n"));
18493 	}
18494 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18495 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18496 	    (int)optp->level, (int)optp->name, (int)optp->len));
18497 	qreply(q, mpctl);
18498 	return (mp2ctl);
18499 }
18500 
18501 /*
18502  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18503  * in one IRE walk.
18504  */
18505 static mblk_t *
18506 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18507 {
18508 	struct opthdr	*optp;
18509 	mblk_t		*mp2ctl;	/* Returned */
18510 	mblk_t		*mp3ctl;	/* nettomedia */
18511 	mblk_t		*mp4ctl;	/* routeattrs */
18512 	iproutedata_t	ird;
18513 	zoneid_t	zoneid;
18514 
18515 	/*
18516 	 * make copies of the original message
18517 	 *	- mp2ctl is returned unchanged to the caller for his use
18518 	 *	- mpctl is sent upstream as ipRouteEntryTable
18519 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18520 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18521 	 */
18522 	mp2ctl = copymsg(mpctl);
18523 	mp3ctl = copymsg(mpctl);
18524 	mp4ctl = copymsg(mpctl);
18525 	if (mp3ctl == NULL || mp4ctl == NULL) {
18526 		freemsg(mp4ctl);
18527 		freemsg(mp3ctl);
18528 		freemsg(mp2ctl);
18529 		freemsg(mpctl);
18530 		return (NULL);
18531 	}
18532 
18533 	bzero(&ird, sizeof (ird));
18534 
18535 	ird.ird_route.lp_head = mpctl->b_cont;
18536 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18537 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18538 
18539 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18540 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18541 	if (zoneid == GLOBAL_ZONEID) {
18542 		/*
18543 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18544 		 * the sys_net_config privilege, it can only run in the global
18545 		 * zone, so we don't display these IREs in the other zones.
18546 		 */
18547 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18548 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18549 	}
18550 
18551 	/* ipRouteEntryTable in mpctl */
18552 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18553 	optp->level = MIB2_IP;
18554 	optp->name = MIB2_IP_ROUTE;
18555 	optp->len = msgdsize(ird.ird_route.lp_head);
18556 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18557 	    (int)optp->level, (int)optp->name, (int)optp->len));
18558 	qreply(q, mpctl);
18559 
18560 	/* ipNetToMediaEntryTable in mp3ctl */
18561 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18562 	optp->level = MIB2_IP;
18563 	optp->name = MIB2_IP_MEDIA;
18564 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18565 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18566 	    (int)optp->level, (int)optp->name, (int)optp->len));
18567 	qreply(q, mp3ctl);
18568 
18569 	/* ipRouteAttributeTable in mp4ctl */
18570 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18571 	optp->level = MIB2_IP;
18572 	optp->name = EXPER_IP_RTATTR;
18573 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18574 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18575 	    (int)optp->level, (int)optp->name, (int)optp->len));
18576 	if (optp->len == 0)
18577 		freemsg(mp4ctl);
18578 	else
18579 		qreply(q, mp4ctl);
18580 
18581 	return (mp2ctl);
18582 }
18583 
18584 /*
18585  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18586  * ipv6NetToMediaEntryTable in an NDP walk.
18587  */
18588 static mblk_t *
18589 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18590 {
18591 	struct opthdr	*optp;
18592 	mblk_t		*mp2ctl;	/* Returned */
18593 	mblk_t		*mp3ctl;	/* nettomedia */
18594 	mblk_t		*mp4ctl;	/* routeattrs */
18595 	iproutedata_t	ird;
18596 	zoneid_t	zoneid;
18597 
18598 	/*
18599 	 * make copies of the original message
18600 	 *	- mp2ctl is returned unchanged to the caller for his use
18601 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18602 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18603 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18604 	 */
18605 	mp2ctl = copymsg(mpctl);
18606 	mp3ctl = copymsg(mpctl);
18607 	mp4ctl = copymsg(mpctl);
18608 	if (mp3ctl == NULL || mp4ctl == NULL) {
18609 		freemsg(mp4ctl);
18610 		freemsg(mp3ctl);
18611 		freemsg(mp2ctl);
18612 		freemsg(mpctl);
18613 		return (NULL);
18614 	}
18615 
18616 	bzero(&ird, sizeof (ird));
18617 
18618 	ird.ird_route.lp_head = mpctl->b_cont;
18619 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18620 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18621 
18622 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18623 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18624 
18625 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18626 	optp->level = MIB2_IP6;
18627 	optp->name = MIB2_IP6_ROUTE;
18628 	optp->len = msgdsize(ird.ird_route.lp_head);
18629 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18630 	    (int)optp->level, (int)optp->name, (int)optp->len));
18631 	qreply(q, mpctl);
18632 
18633 	/* ipv6NetToMediaEntryTable in mp3ctl */
18634 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18635 
18636 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18637 	optp->level = MIB2_IP6;
18638 	optp->name = MIB2_IP6_MEDIA;
18639 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18640 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18641 	    (int)optp->level, (int)optp->name, (int)optp->len));
18642 	qreply(q, mp3ctl);
18643 
18644 	/* ipv6RouteAttributeTable in mp4ctl */
18645 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18646 	optp->level = MIB2_IP6;
18647 	optp->name = EXPER_IP_RTATTR;
18648 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18649 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18650 	    (int)optp->level, (int)optp->name, (int)optp->len));
18651 	if (optp->len == 0)
18652 		freemsg(mp4ctl);
18653 	else
18654 		qreply(q, mp4ctl);
18655 
18656 	return (mp2ctl);
18657 }
18658 
18659 /*
18660  * ICMPv6 mib: One per ill
18661  */
18662 static mblk_t *
18663 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18664 {
18665 	struct opthdr		*optp;
18666 	mblk_t			*mp2ctl;
18667 	ill_t			*ill;
18668 	ill_walk_context_t	ctx;
18669 	mblk_t			*mp_tail = NULL;
18670 
18671 	/*
18672 	 * Make a copy of the original message
18673 	 */
18674 	mp2ctl = copymsg(mpctl);
18675 
18676 	/* fixed length IPv6 structure ... */
18677 
18678 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18679 	optp->level = MIB2_IP6;
18680 	optp->name = 0;
18681 	/* Include "unknown interface" ip6_mib */
18682 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
18683 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
18684 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
18685 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
18686 	    sizeof (mib2_ipv6IfStatsEntry_t));
18687 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18688 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
18689 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
18690 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18691 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
18692 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18693 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18694 	    (int)sizeof (ip6_mib))) {
18695 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18696 		    (uint_t)sizeof (ip6_mib)));
18697 	}
18698 
18699 	rw_enter(&ill_g_lock, RW_READER);
18700 	ill = ILL_START_WALK_V6(&ctx);
18701 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18702 		ill->ill_ip6_mib->ipv6IfIndex =
18703 		    ill->ill_phyint->phyint_ifindex;
18704 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
18705 		    ipv6_forward ? 1 : 2);
18706 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
18707 		    ill->ill_max_hops);
18708 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
18709 		    sizeof (mib2_ipv6IfStatsEntry_t));
18710 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
18711 		    sizeof (mib2_ipv6AddrEntry_t));
18712 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
18713 		    sizeof (mib2_ipv6RouteEntry_t));
18714 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
18715 		    sizeof (mib2_ipv6NetToMediaEntry_t));
18716 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
18717 		    sizeof (ipv6_member_t));
18718 
18719 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18720 		    (char *)ill->ill_ip6_mib,
18721 		    (int)sizeof (*ill->ill_ip6_mib))) {
18722 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18723 				"%u bytes\n",
18724 				(uint_t)sizeof (*ill->ill_ip6_mib)));
18725 		}
18726 	}
18727 	rw_exit(&ill_g_lock);
18728 
18729 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18730 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18731 	    (int)optp->level, (int)optp->name, (int)optp->len));
18732 	qreply(q, mpctl);
18733 	return (mp2ctl);
18734 }
18735 
18736 /*
18737  * ICMPv6 mib: One per ill
18738  */
18739 static mblk_t *
18740 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18741 {
18742 	struct opthdr		*optp;
18743 	mblk_t			*mp2ctl;
18744 	ill_t			*ill;
18745 	ill_walk_context_t	ctx;
18746 	mblk_t			*mp_tail = NULL;
18747 	/*
18748 	 * Make a copy of the original message
18749 	 */
18750 	mp2ctl = copymsg(mpctl);
18751 
18752 	/* fixed length ICMPv6 structure ... */
18753 
18754 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18755 	optp->level = MIB2_ICMP6;
18756 	optp->name = 0;
18757 	/* Include "unknown interface" icmp6_mib */
18758 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
18759 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18760 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18761 	    (int)sizeof (icmp6_mib))) {
18762 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18763 		    (uint_t)sizeof (icmp6_mib)));
18764 	}
18765 
18766 	rw_enter(&ill_g_lock, RW_READER);
18767 	ill = ILL_START_WALK_V6(&ctx);
18768 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18769 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18770 		    ill->ill_phyint->phyint_ifindex;
18771 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
18772 		    sizeof (mib2_ipv6IfIcmpEntry_t);
18773 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18774 		    (char *)ill->ill_icmp6_mib,
18775 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18776 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18777 			    "%u bytes\n",
18778 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18779 		}
18780 	}
18781 	rw_exit(&ill_g_lock);
18782 
18783 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18784 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18785 	    (int)optp->level, (int)optp->name, (int)optp->len));
18786 	qreply(q, mpctl);
18787 	return (mp2ctl);
18788 }
18789 
18790 /*
18791  * ire_walk routine to create both ipRouteEntryTable and
18792  * ipRouteAttributeTable in one IRE walk
18793  */
18794 static void
18795 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18796 {
18797 	ill_t				*ill;
18798 	ipif_t				*ipif;
18799 	mib2_ipRouteEntry_t		*re;
18800 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18801 	ipaddr_t			gw_addr;
18802 	tsol_ire_gw_secattr_t		*attrp;
18803 	tsol_gc_t			*gc = NULL;
18804 	tsol_gcgrp_t			*gcgrp = NULL;
18805 	uint_t				sacnt = 0;
18806 	int				i;
18807 
18808 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18809 
18810 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18811 		return;
18812 
18813 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18814 		mutex_enter(&attrp->igsa_lock);
18815 		if ((gc = attrp->igsa_gc) != NULL) {
18816 			gcgrp = gc->gc_grp;
18817 			ASSERT(gcgrp != NULL);
18818 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18819 			sacnt = 1;
18820 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18821 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18822 			gc = gcgrp->gcgrp_head;
18823 			sacnt = gcgrp->gcgrp_count;
18824 		}
18825 		mutex_exit(&attrp->igsa_lock);
18826 
18827 		/* do nothing if there's no gc to report */
18828 		if (gc == NULL) {
18829 			ASSERT(sacnt == 0);
18830 			if (gcgrp != NULL) {
18831 				/* we might as well drop the lock now */
18832 				rw_exit(&gcgrp->gcgrp_rwlock);
18833 				gcgrp = NULL;
18834 			}
18835 			attrp = NULL;
18836 		}
18837 
18838 		ASSERT(gc == NULL || (gcgrp != NULL &&
18839 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18840 	}
18841 	ASSERT(sacnt == 0 || gc != NULL);
18842 
18843 	if (sacnt != 0 &&
18844 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18845 		kmem_free(re, sizeof (*re));
18846 		rw_exit(&gcgrp->gcgrp_rwlock);
18847 		return;
18848 	}
18849 
18850 	/*
18851 	 * Return all IRE types for route table... let caller pick and choose
18852 	 */
18853 	re->ipRouteDest = ire->ire_addr;
18854 	ipif = ire->ire_ipif;
18855 	re->ipRouteIfIndex.o_length = 0;
18856 	if (ire->ire_type == IRE_CACHE) {
18857 		ill = (ill_t *)ire->ire_stq->q_ptr;
18858 		re->ipRouteIfIndex.o_length =
18859 		    ill->ill_name_length == 0 ? 0 :
18860 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18861 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18862 		    re->ipRouteIfIndex.o_length);
18863 	} else if (ipif != NULL) {
18864 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18865 		    OCTET_LENGTH);
18866 		re->ipRouteIfIndex.o_length =
18867 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18868 	}
18869 	re->ipRouteMetric1 = -1;
18870 	re->ipRouteMetric2 = -1;
18871 	re->ipRouteMetric3 = -1;
18872 	re->ipRouteMetric4 = -1;
18873 
18874 	gw_addr = ire->ire_gateway_addr;
18875 
18876 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18877 		re->ipRouteNextHop = ire->ire_src_addr;
18878 	else
18879 		re->ipRouteNextHop = gw_addr;
18880 	/* indirect(4), direct(3), or invalid(2) */
18881 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18882 		re->ipRouteType = 2;
18883 	else
18884 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18885 	re->ipRouteProto = -1;
18886 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18887 	re->ipRouteMask = ire->ire_mask;
18888 	re->ipRouteMetric5 = -1;
18889 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
18890 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
18891 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
18892 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
18893 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
18894 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18895 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18896 	re->ipRouteInfo.re_flags	= ire->ire_flags;
18897 	re->ipRouteInfo.re_in_ill.o_length = 0;
18898 
18899 	if (ire->ire_flags & RTF_DYNAMIC) {
18900 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
18901 	} else {
18902 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
18903 	}
18904 
18905 	if (ire->ire_in_ill != NULL) {
18906 		re->ipRouteInfo.re_in_ill.o_length =
18907 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
18908 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
18909 		bcopy(ire->ire_in_ill->ill_name,
18910 		    re->ipRouteInfo.re_in_ill.o_bytes,
18911 		    re->ipRouteInfo.re_in_ill.o_length);
18912 	}
18913 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
18914 
18915 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18916 	    (char *)re, (int)sizeof (*re))) {
18917 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18918 		    (uint_t)sizeof (*re)));
18919 	}
18920 
18921 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18922 		iaeptr->iae_routeidx = ird->ird_idx;
18923 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18924 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18925 	}
18926 
18927 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18928 	    (char *)iae, sacnt * sizeof (*iae))) {
18929 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18930 		    (unsigned)(sacnt * sizeof (*iae))));
18931 	}
18932 
18933 	/* bump route index for next pass */
18934 	ird->ird_idx++;
18935 
18936 	kmem_free(re, sizeof (*re));
18937 	if (sacnt != 0)
18938 		kmem_free(iae, sacnt * sizeof (*iae));
18939 
18940 	if (gcgrp != NULL)
18941 		rw_exit(&gcgrp->gcgrp_rwlock);
18942 }
18943 
18944 /*
18945  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18946  */
18947 static void
18948 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18949 {
18950 	ill_t				*ill;
18951 	ipif_t				*ipif;
18952 	mib2_ipv6RouteEntry_t		*re;
18953 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18954 	in6_addr_t			gw_addr_v6;
18955 	tsol_ire_gw_secattr_t		*attrp;
18956 	tsol_gc_t			*gc = NULL;
18957 	tsol_gcgrp_t			*gcgrp = NULL;
18958 	uint_t				sacnt = 0;
18959 	int				i;
18960 
18961 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18962 
18963 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18964 		return;
18965 
18966 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18967 		mutex_enter(&attrp->igsa_lock);
18968 		if ((gc = attrp->igsa_gc) != NULL) {
18969 			gcgrp = gc->gc_grp;
18970 			ASSERT(gcgrp != NULL);
18971 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18972 			sacnt = 1;
18973 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18974 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18975 			gc = gcgrp->gcgrp_head;
18976 			sacnt = gcgrp->gcgrp_count;
18977 		}
18978 		mutex_exit(&attrp->igsa_lock);
18979 
18980 		/* do nothing if there's no gc to report */
18981 		if (gc == NULL) {
18982 			ASSERT(sacnt == 0);
18983 			if (gcgrp != NULL) {
18984 				/* we might as well drop the lock now */
18985 				rw_exit(&gcgrp->gcgrp_rwlock);
18986 				gcgrp = NULL;
18987 			}
18988 			attrp = NULL;
18989 		}
18990 
18991 		ASSERT(gc == NULL || (gcgrp != NULL &&
18992 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18993 	}
18994 	ASSERT(sacnt == 0 || gc != NULL);
18995 
18996 	if (sacnt != 0 &&
18997 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18998 		kmem_free(re, sizeof (*re));
18999 		rw_exit(&gcgrp->gcgrp_rwlock);
19000 		return;
19001 	}
19002 
19003 	/*
19004 	 * Return all IRE types for route table... let caller pick and choose
19005 	 */
19006 	re->ipv6RouteDest = ire->ire_addr_v6;
19007 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19008 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19009 	re->ipv6RouteIfIndex.o_length = 0;
19010 	ipif = ire->ire_ipif;
19011 	if (ire->ire_type == IRE_CACHE) {
19012 		ill = (ill_t *)ire->ire_stq->q_ptr;
19013 		re->ipv6RouteIfIndex.o_length =
19014 		    ill->ill_name_length == 0 ? 0 :
19015 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19016 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19017 		    re->ipv6RouteIfIndex.o_length);
19018 	} else if (ipif != NULL) {
19019 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19020 		    OCTET_LENGTH);
19021 		re->ipv6RouteIfIndex.o_length =
19022 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19023 	}
19024 
19025 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19026 
19027 	mutex_enter(&ire->ire_lock);
19028 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19029 	mutex_exit(&ire->ire_lock);
19030 
19031 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19032 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19033 	else
19034 		re->ipv6RouteNextHop = gw_addr_v6;
19035 
19036 	/* remote(4), local(3), or discard(2) */
19037 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19038 		re->ipv6RouteType = 2;
19039 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19040 		re->ipv6RouteType = 3;
19041 	else
19042 		re->ipv6RouteType = 4;
19043 
19044 	re->ipv6RouteProtocol	= -1;
19045 	re->ipv6RoutePolicy	= 0;
19046 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19047 	re->ipv6RouteNextHopRDI	= 0;
19048 	re->ipv6RouteWeight	= 0;
19049 	re->ipv6RouteMetric	= 0;
19050 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19051 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19052 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19053 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19054 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19055 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19056 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19057 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19058 
19059 	if (ire->ire_flags & RTF_DYNAMIC) {
19060 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19061 	} else {
19062 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19063 	}
19064 
19065 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19066 	    (char *)re, (int)sizeof (*re))) {
19067 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19068 		    (uint_t)sizeof (*re)));
19069 	}
19070 
19071 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19072 		iaeptr->iae_routeidx = ird->ird_idx;
19073 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19074 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19075 	}
19076 
19077 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19078 	    (char *)iae, sacnt * sizeof (*iae))) {
19079 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19080 		    (unsigned)(sacnt * sizeof (*iae))));
19081 	}
19082 
19083 	/* bump route index for next pass */
19084 	ird->ird_idx++;
19085 
19086 	kmem_free(re, sizeof (*re));
19087 	if (sacnt != 0)
19088 		kmem_free(iae, sacnt * sizeof (*iae));
19089 
19090 	if (gcgrp != NULL)
19091 		rw_exit(&gcgrp->gcgrp_rwlock);
19092 }
19093 
19094 /*
19095  * ndp_walk routine to create ipv6NetToMediaEntryTable
19096  */
19097 static int
19098 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19099 {
19100 	ill_t				*ill;
19101 	mib2_ipv6NetToMediaEntry_t	ntme;
19102 	dl_unitdata_req_t		*dl;
19103 
19104 	ill = nce->nce_ill;
19105 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19106 		return (0);
19107 
19108 	/*
19109 	 * Neighbor cache entry attached to IRE with on-link
19110 	 * destination.
19111 	 */
19112 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19113 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19114 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19115 	    (nce->nce_res_mp != NULL)) {
19116 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19117 		ntme.ipv6NetToMediaPhysAddress.o_length =
19118 		    dl->dl_dest_addr_length;
19119 	} else {
19120 		ntme.ipv6NetToMediaPhysAddress.o_length =
19121 		    ill->ill_phys_addr_length;
19122 	}
19123 	if (nce->nce_res_mp != NULL) {
19124 		bcopy((char *)nce->nce_res_mp->b_rptr +
19125 		    NCE_LL_ADDR_OFFSET(ill),
19126 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19127 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19128 	} else {
19129 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19130 		    ill->ill_phys_addr_length);
19131 	}
19132 	/*
19133 	 * Note: Returns ND_* states. Should be:
19134 	 * reachable(1), stale(2), delay(3), probe(4),
19135 	 * invalid(5), unknown(6)
19136 	 */
19137 	ntme.ipv6NetToMediaState = nce->nce_state;
19138 	ntme.ipv6NetToMediaLastUpdated = 0;
19139 
19140 	/* other(1), dynamic(2), static(3), local(4) */
19141 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19142 		ntme.ipv6NetToMediaType = 4;
19143 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19144 		ntme.ipv6NetToMediaType = 1;
19145 	} else {
19146 		ntme.ipv6NetToMediaType = 2;
19147 	}
19148 
19149 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19150 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19151 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19152 		    (uint_t)sizeof (ntme)));
19153 	}
19154 	return (0);
19155 }
19156 
19157 /*
19158  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19159  */
19160 /* ARGSUSED */
19161 int
19162 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19163 {
19164 	switch (level) {
19165 	case MIB2_IP:
19166 	case MIB2_ICMP:
19167 		switch (name) {
19168 		default:
19169 			break;
19170 		}
19171 		return (1);
19172 	default:
19173 		return (1);
19174 	}
19175 }
19176 
19177 /*
19178  * Called before the options are updated to check if this packet will
19179  * be source routed from here.
19180  * This routine assumes that the options are well formed i.e. that they
19181  * have already been checked.
19182  */
19183 static boolean_t
19184 ip_source_routed(ipha_t *ipha)
19185 {
19186 	ipoptp_t	opts;
19187 	uchar_t		*opt;
19188 	uint8_t		optval;
19189 	uint8_t		optlen;
19190 	ipaddr_t	dst;
19191 	ire_t		*ire;
19192 
19193 	if (IS_SIMPLE_IPH(ipha)) {
19194 		ip2dbg(("not source routed\n"));
19195 		return (B_FALSE);
19196 	}
19197 	dst = ipha->ipha_dst;
19198 	for (optval = ipoptp_first(&opts, ipha);
19199 	    optval != IPOPT_EOL;
19200 	    optval = ipoptp_next(&opts)) {
19201 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19202 		opt = opts.ipoptp_cur;
19203 		optlen = opts.ipoptp_len;
19204 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19205 		    optval, optlen));
19206 		switch (optval) {
19207 			uint32_t off;
19208 		case IPOPT_SSRR:
19209 		case IPOPT_LSRR:
19210 			/*
19211 			 * If dst is one of our addresses and there are some
19212 			 * entries left in the source route return (true).
19213 			 */
19214 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19215 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
19216 			if (ire == NULL) {
19217 				ip2dbg(("ip_source_routed: not next"
19218 				    " source route 0x%x\n",
19219 				    ntohl(dst)));
19220 				return (B_FALSE);
19221 			}
19222 			ire_refrele(ire);
19223 			off = opt[IPOPT_OFFSET];
19224 			off--;
19225 			if (optlen < IP_ADDR_LEN ||
19226 			    off > optlen - IP_ADDR_LEN) {
19227 				/* End of source route */
19228 				ip1dbg(("ip_source_routed: end of SR\n"));
19229 				return (B_FALSE);
19230 			}
19231 			return (B_TRUE);
19232 		}
19233 	}
19234 	ip2dbg(("not source routed\n"));
19235 	return (B_FALSE);
19236 }
19237 
19238 /*
19239  * Check if the packet contains any source route.
19240  */
19241 static boolean_t
19242 ip_source_route_included(ipha_t *ipha)
19243 {
19244 	ipoptp_t	opts;
19245 	uint8_t		optval;
19246 
19247 	if (IS_SIMPLE_IPH(ipha))
19248 		return (B_FALSE);
19249 	for (optval = ipoptp_first(&opts, ipha);
19250 	    optval != IPOPT_EOL;
19251 	    optval = ipoptp_next(&opts)) {
19252 		switch (optval) {
19253 		case IPOPT_SSRR:
19254 		case IPOPT_LSRR:
19255 			return (B_TRUE);
19256 		}
19257 	}
19258 	return (B_FALSE);
19259 }
19260 
19261 /*
19262  * Called when the IRE expiration timer fires.
19263  */
19264 /* ARGSUSED */
19265 void
19266 ip_trash_timer_expire(void *args)
19267 {
19268 	int	flush_flag = 0;
19269 
19270 	/*
19271 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19272 	 * This lock makes sure that a new invocation of this function
19273 	 * that occurs due to an almost immediate timer firing will not
19274 	 * progress beyond this point until the current invocation is done
19275 	 */
19276 	mutex_enter(&ip_trash_timer_lock);
19277 	ip_ire_expire_id = 0;
19278 	mutex_exit(&ip_trash_timer_lock);
19279 
19280 	/* Periodic timer */
19281 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
19282 		/*
19283 		 * Remove all IRE_CACHE entries since they might
19284 		 * contain arp information.
19285 		 */
19286 		flush_flag |= FLUSH_ARP_TIME;
19287 		ip_ire_arp_time_elapsed = 0;
19288 		IP_STAT(ip_ire_arp_timer_expired);
19289 	}
19290 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
19291 		/* Remove all redirects */
19292 		flush_flag |= FLUSH_REDIRECT_TIME;
19293 		ip_ire_rd_time_elapsed = 0;
19294 		IP_STAT(ip_ire_redirect_timer_expired);
19295 	}
19296 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
19297 		/* Increase path mtu */
19298 		flush_flag |= FLUSH_MTU_TIME;
19299 		ip_ire_pmtu_time_elapsed = 0;
19300 		IP_STAT(ip_ire_pmtu_timer_expired);
19301 	}
19302 
19303 	/*
19304 	 * Optimize for the case when there are no redirects in the
19305 	 * ftable, that is, no need to walk the ftable in that case.
19306 	 */
19307 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19308 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19309 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
19310 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
19311 	}
19312 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
19313 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19314 		    ire_expire, (char *)(uintptr_t)flush_flag,
19315 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
19316 	}
19317 	if (flush_flag & FLUSH_MTU_TIME) {
19318 		/*
19319 		 * Walk all IPv6 IRE's and update them
19320 		 * Note that ARP and redirect timers are not
19321 		 * needed since NUD handles stale entries.
19322 		 */
19323 		flush_flag = FLUSH_MTU_TIME;
19324 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
19325 		    ALL_ZONES);
19326 	}
19327 
19328 	ip_ire_arp_time_elapsed += ip_timer_interval;
19329 	ip_ire_rd_time_elapsed += ip_timer_interval;
19330 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19331 
19332 	/*
19333 	 * Hold the lock to serialize timeout calls and prevent
19334 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19335 	 * for the timer to fire and a new invocation of this function
19336 	 * to start before the return value of timeout has been stored
19337 	 * in ip_ire_expire_id by the current invocation.
19338 	 */
19339 	mutex_enter(&ip_trash_timer_lock);
19340 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19341 	    MSEC_TO_TICK(ip_timer_interval));
19342 	mutex_exit(&ip_trash_timer_lock);
19343 }
19344 
19345 /*
19346  * Called by the memory allocator subsystem directly, when the system
19347  * is running low on memory.
19348  */
19349 /* ARGSUSED */
19350 void
19351 ip_trash_ire_reclaim(void *args)
19352 {
19353 	ire_cache_count_t icc;
19354 	ire_cache_reclaim_t icr;
19355 	ncc_cache_count_t ncc;
19356 	nce_cache_reclaim_t ncr;
19357 	uint_t delete_cnt;
19358 	/*
19359 	 * Memory reclaim call back.
19360 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19361 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19362 	 * entries, determine what fraction to free for
19363 	 * each category of IRE_CACHE entries giving absolute priority
19364 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19365 	 * entry will be freed unless all offlink entries are freed).
19366 	 */
19367 	icc.icc_total = 0;
19368 	icc.icc_unused = 0;
19369 	icc.icc_offlink = 0;
19370 	icc.icc_pmtu = 0;
19371 	icc.icc_onlink = 0;
19372 	ire_walk(ire_cache_count, (char *)&icc);
19373 
19374 	/*
19375 	 * Free NCEs for IPv6 like the onlink ires.
19376 	 */
19377 	ncc.ncc_total = 0;
19378 	ncc.ncc_host = 0;
19379 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19380 
19381 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19382 	    icc.icc_pmtu + icc.icc_onlink);
19383 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19384 	IP_STAT(ip_trash_ire_reclaim_calls);
19385 	if (delete_cnt == 0)
19386 		return;
19387 	IP_STAT(ip_trash_ire_reclaim_success);
19388 	/* Always delete all unused offlink entries */
19389 	icr.icr_unused = 1;
19390 	if (delete_cnt <= icc.icc_unused) {
19391 		/*
19392 		 * Only need to free unused entries.  In other words,
19393 		 * there are enough unused entries to free to meet our
19394 		 * target number of freed ire cache entries.
19395 		 */
19396 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19397 		ncr.ncr_host = 0;
19398 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19399 		/*
19400 		 * Only need to free unused entries, plus a fraction of offlink
19401 		 * entries.  It follows from the first if statement that
19402 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19403 		 */
19404 		delete_cnt -= icc.icc_unused;
19405 		/* Round up # deleted by truncating fraction */
19406 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19407 		icr.icr_pmtu = icr.icr_onlink = 0;
19408 		ncr.ncr_host = 0;
19409 	} else if (delete_cnt <=
19410 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19411 		/*
19412 		 * Free all unused and offlink entries, plus a fraction of
19413 		 * pmtu entries.  It follows from the previous if statement
19414 		 * that icc_pmtu is non-zero, and that
19415 		 * delete_cnt != icc_unused + icc_offlink.
19416 		 */
19417 		icr.icr_offlink = 1;
19418 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19419 		/* Round up # deleted by truncating fraction */
19420 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19421 		icr.icr_onlink = 0;
19422 		ncr.ncr_host = 0;
19423 	} else {
19424 		/*
19425 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19426 		 * of onlink entries.  If we're here, then we know that
19427 		 * icc_onlink is non-zero, and that
19428 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19429 		 */
19430 		icr.icr_offlink = icr.icr_pmtu = 1;
19431 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19432 		    icc.icc_pmtu;
19433 		/* Round up # deleted by truncating fraction */
19434 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19435 		/* Using the same delete fraction as for onlink IREs */
19436 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19437 	}
19438 #ifdef DEBUG
19439 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19440 	    "fractions %d/%d/%d/%d\n",
19441 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19442 	    icc.icc_unused, icc.icc_offlink,
19443 	    icc.icc_pmtu, icc.icc_onlink,
19444 	    icr.icr_unused, icr.icr_offlink,
19445 	    icr.icr_pmtu, icr.icr_onlink));
19446 #endif
19447 	ire_walk(ire_cache_reclaim, (char *)&icr);
19448 	if (ncr.ncr_host != 0)
19449 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19450 		    (uchar_t *)&ncr);
19451 #ifdef DEBUG
19452 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19453 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19454 	ire_walk(ire_cache_count, (char *)&icc);
19455 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19456 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19457 	    icc.icc_pmtu, icc.icc_onlink));
19458 #endif
19459 }
19460 
19461 /*
19462  * ip_unbind is called when a copy of an unbind request is received from the
19463  * upper level protocol.  We remove this conn from any fanout hash list it is
19464  * on, and zero out the bind information.  No reply is expected up above.
19465  */
19466 mblk_t *
19467 ip_unbind(queue_t *q, mblk_t *mp)
19468 {
19469 	conn_t	*connp = Q_TO_CONN(q);
19470 
19471 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19472 
19473 	if (is_system_labeled() && connp->conn_anon_port) {
19474 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19475 		    connp->conn_mlp_type, connp->conn_ulp,
19476 		    ntohs(connp->conn_lport), B_FALSE);
19477 		connp->conn_anon_port = 0;
19478 	}
19479 	connp->conn_mlp_type = mlptSingle;
19480 
19481 	ipcl_hash_remove(connp);
19482 
19483 	ASSERT(mp->b_cont == NULL);
19484 	/*
19485 	 * Convert mp into a T_OK_ACK
19486 	 */
19487 	mp = mi_tpi_ok_ack_alloc(mp);
19488 
19489 	/*
19490 	 * should not happen in practice... T_OK_ACK is smaller than the
19491 	 * original message.
19492 	 */
19493 	if (mp == NULL)
19494 		return (NULL);
19495 
19496 	/*
19497 	 * Don't bzero the ports if its TCP since TCP still needs the
19498 	 * lport to remove it from its own bind hash. TCP will do the
19499 	 * cleanup.
19500 	 */
19501 	if (!IPCL_IS_TCP(connp))
19502 		bzero(&connp->u_port, sizeof (connp->u_port));
19503 
19504 	return (mp);
19505 }
19506 
19507 /*
19508  * Write side put procedure.  Outbound data, IOCTLs, responses from
19509  * resolvers, etc, come down through here.
19510  *
19511  * arg2 is always a queue_t *.
19512  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19513  * the zoneid.
19514  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19515  */
19516 void
19517 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19518 {
19519 	conn_t		*connp = NULL;
19520 	queue_t		*q = (queue_t *)arg2;
19521 	ipha_t		*ipha;
19522 #define	rptr	((uchar_t *)ipha)
19523 	ire_t		*ire = NULL;
19524 	ire_t		*sctp_ire = NULL;
19525 	uint32_t	v_hlen_tos_len;
19526 	ipaddr_t	dst;
19527 	mblk_t		*first_mp = NULL;
19528 	boolean_t	mctl_present;
19529 	ipsec_out_t	*io;
19530 	int		match_flags;
19531 	ill_t		*attach_ill = NULL;
19532 					/* Bind to IPIF_NOFAILOVER ill etc. */
19533 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19534 	ipif_t		*dst_ipif;
19535 	boolean_t	multirt_need_resolve = B_FALSE;
19536 	mblk_t		*copy_mp = NULL;
19537 	int		err;
19538 	zoneid_t	zoneid;
19539 	int	adjust;
19540 	uint16_t iplen;
19541 	boolean_t	need_decref = B_FALSE;
19542 	boolean_t	ignore_dontroute = B_FALSE;
19543 	boolean_t	ignore_nexthop = B_FALSE;
19544 	boolean_t	ip_nexthop = B_FALSE;
19545 	ipaddr_t	nexthop_addr;
19546 
19547 #ifdef	_BIG_ENDIAN
19548 #define	V_HLEN	(v_hlen_tos_len >> 24)
19549 #else
19550 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19551 #endif
19552 
19553 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19554 	    "ip_wput_start: q %p", q);
19555 
19556 	/*
19557 	 * ip_wput fast path
19558 	 */
19559 
19560 	/* is packet from ARP ? */
19561 	if (q->q_next != NULL) {
19562 		zoneid = (zoneid_t)(uintptr_t)arg;
19563 		goto qnext;
19564 	}
19565 
19566 	connp = (conn_t *)arg;
19567 	ASSERT(connp != NULL);
19568 	zoneid = connp->conn_zoneid;
19569 
19570 	/* is queue flow controlled? */
19571 	if ((q->q_first != NULL || connp->conn_draining) &&
19572 	    (caller == IP_WPUT)) {
19573 		ASSERT(!need_decref);
19574 		(void) putq(q, mp);
19575 		return;
19576 	}
19577 
19578 	/* Multidata transmit? */
19579 	if (DB_TYPE(mp) == M_MULTIDATA) {
19580 		/*
19581 		 * We should never get here, since all Multidata messages
19582 		 * originating from tcp should have been directed over to
19583 		 * tcp_multisend() in the first place.
19584 		 */
19585 		BUMP_MIB(&ip_mib, ipOutDiscards);
19586 		freemsg(mp);
19587 		return;
19588 	} else if (DB_TYPE(mp) != M_DATA)
19589 		goto notdata;
19590 
19591 	if (mp->b_flag & MSGHASREF) {
19592 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19593 		mp->b_flag &= ~MSGHASREF;
19594 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19595 		need_decref = B_TRUE;
19596 	}
19597 	ipha = (ipha_t *)mp->b_rptr;
19598 
19599 	/* is IP header non-aligned or mblk smaller than basic IP header */
19600 #ifndef SAFETY_BEFORE_SPEED
19601 	if (!OK_32PTR(rptr) ||
19602 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19603 		goto hdrtoosmall;
19604 #endif
19605 
19606 	ASSERT(OK_32PTR(ipha));
19607 
19608 	/*
19609 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19610 	 * wrong version, we'll catch it again in ip_output_v6.
19611 	 *
19612 	 * Note that this is *only* locally-generated output here, and never
19613 	 * forwarded data, and that we need to deal only with transports that
19614 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19615 	 * label.)
19616 	 */
19617 	if (is_system_labeled() &&
19618 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19619 	    !connp->conn_ulp_labeled) {
19620 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19621 		    connp->conn_mac_exempt);
19622 		ipha = (ipha_t *)mp->b_rptr;
19623 		if (err != 0) {
19624 			first_mp = mp;
19625 			if (err == EINVAL)
19626 				goto icmp_parameter_problem;
19627 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19628 			goto drop_pkt;
19629 		}
19630 		iplen = ntohs(ipha->ipha_length) + adjust;
19631 		ipha->ipha_length = htons(iplen);
19632 	}
19633 
19634 	/*
19635 	 * If there is a policy, try to attach an ipsec_out in
19636 	 * the front. At the end, first_mp either points to a
19637 	 * M_DATA message or IPSEC_OUT message linked to a
19638 	 * M_DATA message. We have to do it now as we might
19639 	 * lose the "conn" if we go through ip_newroute.
19640 	 */
19641 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19642 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
19643 		    ipha->ipha_protocol)) == NULL)) {
19644 			if (need_decref)
19645 				CONN_DEC_REF(connp);
19646 			return;
19647 		} else {
19648 			ASSERT(mp->b_datap->db_type == M_CTL);
19649 			first_mp = mp;
19650 			mp = mp->b_cont;
19651 			mctl_present = B_TRUE;
19652 		}
19653 	} else {
19654 		first_mp = mp;
19655 		mctl_present = B_FALSE;
19656 	}
19657 
19658 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19659 
19660 	/* is wrong version or IP options present */
19661 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19662 		goto version_hdrlen_check;
19663 	dst = ipha->ipha_dst;
19664 
19665 	if (connp->conn_nofailover_ill != NULL) {
19666 		attach_ill = conn_get_held_ill(connp,
19667 		    &connp->conn_nofailover_ill, &err);
19668 		if (err == ILL_LOOKUP_FAILED) {
19669 			if (need_decref)
19670 				CONN_DEC_REF(connp);
19671 			freemsg(first_mp);
19672 			return;
19673 		}
19674 	}
19675 
19676 	/* is packet multicast? */
19677 	if (CLASSD(dst))
19678 		goto multicast;
19679 
19680 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19681 	    (connp->conn_nexthop_set)) {
19682 		/*
19683 		 * If the destination is a broadcast or a loopback
19684 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
19685 		 * through the standard path. But in the case of local
19686 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
19687 		 * the standard path not IP_XMIT_IF.
19688 		 */
19689 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19690 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
19691 		    (ire->ire_type != IRE_LOOPBACK))) {
19692 			if ((connp->conn_dontroute ||
19693 			    connp->conn_nexthop_set) && (ire != NULL) &&
19694 			    (ire->ire_type == IRE_LOCAL))
19695 				goto standard_path;
19696 
19697 			if (ire != NULL) {
19698 				ire_refrele(ire);
19699 				/* No more access to ire */
19700 				ire = NULL;
19701 			}
19702 			/*
19703 			 * bypass routing checks and go directly to
19704 			 * interface.
19705 			 */
19706 			if (connp->conn_dontroute) {
19707 				goto dontroute;
19708 			} else if (connp->conn_nexthop_set) {
19709 				ip_nexthop = B_TRUE;
19710 				nexthop_addr = connp->conn_nexthop_v4;
19711 				goto send_from_ill;
19712 			}
19713 
19714 			/*
19715 			 * If IP_XMIT_IF socket option is set,
19716 			 * then we allow unicast and multicast
19717 			 * packets to go through the ill. It is
19718 			 * quite possible that the destination
19719 			 * is not in the ire cache table and we
19720 			 * do not want to go to ip_newroute()
19721 			 * instead we call ip_newroute_ipif.
19722 			 */
19723 			xmit_ill = conn_get_held_ill(connp,
19724 			    &connp->conn_xmit_if_ill, &err);
19725 			if (err == ILL_LOOKUP_FAILED) {
19726 				if (attach_ill != NULL)
19727 					ill_refrele(attach_ill);
19728 				if (need_decref)
19729 					CONN_DEC_REF(connp);
19730 				freemsg(first_mp);
19731 				return;
19732 			}
19733 			goto send_from_ill;
19734 		}
19735 standard_path:
19736 		/* Must be a broadcast, a loopback or a local ire */
19737 		if (ire != NULL) {
19738 			ire_refrele(ire);
19739 			/* No more access to ire */
19740 			ire = NULL;
19741 		}
19742 	}
19743 
19744 	if (attach_ill != NULL)
19745 		goto send_from_ill;
19746 
19747 	/*
19748 	 * We cache IRE_CACHEs to avoid lookups. We don't do
19749 	 * this for the tcp global queue and listen end point
19750 	 * as it does not really have a real destination to
19751 	 * talk to.  This is also true for SCTP.
19752 	 */
19753 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
19754 	    !connp->conn_fully_bound) {
19755 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19756 		if (ire == NULL)
19757 			goto noirefound;
19758 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19759 		    "ip_wput_end: q %p (%S)", q, "end");
19760 
19761 		/*
19762 		 * Check if the ire has the RTF_MULTIRT flag, inherited
19763 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19764 		 */
19765 		if (ire->ire_flags & RTF_MULTIRT) {
19766 
19767 			/*
19768 			 * Force the TTL of multirouted packets if required.
19769 			 * The TTL of such packets is bounded by the
19770 			 * ip_multirt_ttl ndd variable.
19771 			 */
19772 			if ((ip_multirt_ttl > 0) &&
19773 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
19774 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
19775 				    "(was %d), dst 0x%08x\n",
19776 				    ip_multirt_ttl, ipha->ipha_ttl,
19777 				    ntohl(ire->ire_addr)));
19778 				ipha->ipha_ttl = ip_multirt_ttl;
19779 			}
19780 			/*
19781 			 * We look at this point if there are pending
19782 			 * unresolved routes. ire_multirt_resolvable()
19783 			 * checks in O(n) that all IRE_OFFSUBNET ire
19784 			 * entries for the packet's destination and
19785 			 * flagged RTF_MULTIRT are currently resolved.
19786 			 * If some remain unresolved, we make a copy
19787 			 * of the current message. It will be used
19788 			 * to initiate additional route resolutions.
19789 			 */
19790 			multirt_need_resolve =
19791 			    ire_multirt_need_resolve(ire->ire_addr,
19792 			    MBLK_GETLABEL(first_mp));
19793 			ip2dbg(("ip_wput[TCP]: ire %p, "
19794 			    "multirt_need_resolve %d, first_mp %p\n",
19795 			    (void *)ire, multirt_need_resolve,
19796 			    (void *)first_mp));
19797 			if (multirt_need_resolve) {
19798 				copy_mp = copymsg(first_mp);
19799 				if (copy_mp != NULL) {
19800 					MULTIRT_DEBUG_TAG(copy_mp);
19801 				}
19802 			}
19803 		}
19804 
19805 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19806 
19807 		/*
19808 		 * Try to resolve another multiroute if
19809 		 * ire_multirt_need_resolve() deemed it necessary.
19810 		 */
19811 		if (copy_mp != NULL) {
19812 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19813 		}
19814 		if (need_decref)
19815 			CONN_DEC_REF(connp);
19816 		return;
19817 	}
19818 
19819 	/*
19820 	 * Access to conn_ire_cache. (protected by conn_lock)
19821 	 *
19822 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
19823 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
19824 	 * send a packet or two with the IRE_CACHE that is going away.
19825 	 * Access to the ire requires an ire refhold on the ire prior to
19826 	 * its use since an interface unplumb thread may delete the cached
19827 	 * ire and release the refhold at any time.
19828 	 *
19829 	 * Caching an ire in the conn_ire_cache
19830 	 *
19831 	 * o Caching an ire pointer in the conn requires a strict check for
19832 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
19833 	 * ires  before cleaning up the conns. So the caching of an ire pointer
19834 	 * in the conn is done after making sure under the bucket lock that the
19835 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
19836 	 * caching an ire after the unplumb thread has cleaned up the conn.
19837 	 * If the conn does not send a packet subsequently the unplumb thread
19838 	 * will be hanging waiting for the ire count to drop to zero.
19839 	 *
19840 	 * o We also need to atomically test for a null conn_ire_cache and
19841 	 * set the conn_ire_cache under the the protection of the conn_lock
19842 	 * to avoid races among concurrent threads trying to simultaneously
19843 	 * cache an ire in the conn_ire_cache.
19844 	 */
19845 	mutex_enter(&connp->conn_lock);
19846 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
19847 
19848 	if (ire != NULL && ire->ire_addr == dst &&
19849 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19850 
19851 		IRE_REFHOLD(ire);
19852 		mutex_exit(&connp->conn_lock);
19853 
19854 	} else {
19855 		boolean_t cached = B_FALSE;
19856 		connp->conn_ire_cache = NULL;
19857 		mutex_exit(&connp->conn_lock);
19858 		/* Release the old ire */
19859 		if (ire != NULL && sctp_ire == NULL)
19860 			IRE_REFRELE_NOTR(ire);
19861 
19862 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19863 		if (ire == NULL)
19864 			goto noirefound;
19865 		IRE_REFHOLD_NOTR(ire);
19866 
19867 		mutex_enter(&connp->conn_lock);
19868 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
19869 		    connp->conn_ire_cache == NULL) {
19870 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19871 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19872 				connp->conn_ire_cache = ire;
19873 				cached = B_TRUE;
19874 			}
19875 			rw_exit(&ire->ire_bucket->irb_lock);
19876 		}
19877 		mutex_exit(&connp->conn_lock);
19878 
19879 		/*
19880 		 * We can continue to use the ire but since it was
19881 		 * not cached, we should drop the extra reference.
19882 		 */
19883 		if (!cached)
19884 			IRE_REFRELE_NOTR(ire);
19885 	}
19886 
19887 
19888 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19889 	    "ip_wput_end: q %p (%S)", q, "end");
19890 
19891 	/*
19892 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19893 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19894 	 */
19895 	if (ire->ire_flags & RTF_MULTIRT) {
19896 
19897 		/*
19898 		 * Force the TTL of multirouted packets if required.
19899 		 * The TTL of such packets is bounded by the
19900 		 * ip_multirt_ttl ndd variable.
19901 		 */
19902 		if ((ip_multirt_ttl > 0) &&
19903 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19904 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19905 			    "(was %d), dst 0x%08x\n",
19906 			    ip_multirt_ttl, ipha->ipha_ttl,
19907 			    ntohl(ire->ire_addr)));
19908 			ipha->ipha_ttl = ip_multirt_ttl;
19909 		}
19910 
19911 		/*
19912 		 * At this point, we check to see if there are any pending
19913 		 * unresolved routes. ire_multirt_resolvable()
19914 		 * checks in O(n) that all IRE_OFFSUBNET ire
19915 		 * entries for the packet's destination and
19916 		 * flagged RTF_MULTIRT are currently resolved.
19917 		 * If some remain unresolved, we make a copy
19918 		 * of the current message. It will be used
19919 		 * to initiate additional route resolutions.
19920 		 */
19921 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19922 		    MBLK_GETLABEL(first_mp));
19923 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19924 		    "multirt_need_resolve %d, first_mp %p\n",
19925 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19926 		if (multirt_need_resolve) {
19927 			copy_mp = copymsg(first_mp);
19928 			if (copy_mp != NULL) {
19929 				MULTIRT_DEBUG_TAG(copy_mp);
19930 			}
19931 		}
19932 	}
19933 
19934 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19935 
19936 	/*
19937 	 * Try to resolve another multiroute if
19938 	 * ire_multirt_resolvable() deemed it necessary
19939 	 */
19940 	if (copy_mp != NULL) {
19941 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19942 	}
19943 	if (need_decref)
19944 		CONN_DEC_REF(connp);
19945 	return;
19946 
19947 qnext:
19948 	/*
19949 	 * Upper Level Protocols pass down complete IP datagrams
19950 	 * as M_DATA messages.	Everything else is a sideshow.
19951 	 *
19952 	 * 1) We could be re-entering ip_wput because of ip_neworute
19953 	 *    in which case we could have a IPSEC_OUT message. We
19954 	 *    need to pass through ip_wput like other datagrams and
19955 	 *    hence cannot branch to ip_wput_nondata.
19956 	 *
19957 	 * 2) ARP, AH, ESP, and other clients who are on the module
19958 	 *    instance of IP stream, give us something to deal with.
19959 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19960 	 *
19961 	 * 3) ICMP replies also could come here.
19962 	 */
19963 	if (DB_TYPE(mp) != M_DATA) {
19964 	    notdata:
19965 		if (DB_TYPE(mp) == M_CTL) {
19966 			/*
19967 			 * M_CTL messages are used by ARP, AH and ESP to
19968 			 * communicate with IP. We deal with IPSEC_IN and
19969 			 * IPSEC_OUT here. ip_wput_nondata handles other
19970 			 * cases.
19971 			 */
19972 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19973 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19974 				first_mp = mp->b_cont;
19975 				first_mp->b_flag &= ~MSGHASREF;
19976 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19977 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19978 				CONN_DEC_REF(connp);
19979 				connp = NULL;
19980 			}
19981 			if (ii->ipsec_info_type == IPSEC_IN) {
19982 				/*
19983 				 * Either this message goes back to
19984 				 * IPSEC for further processing or to
19985 				 * ULP after policy checks.
19986 				 */
19987 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19988 				return;
19989 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19990 				io = (ipsec_out_t *)ii;
19991 				if (io->ipsec_out_proc_begin) {
19992 					/*
19993 					 * IPSEC processing has already started.
19994 					 * Complete it.
19995 					 * IPQoS notes: We don't care what is
19996 					 * in ipsec_out_ill_index since this
19997 					 * won't be processed for IPQoS policies
19998 					 * in ipsec_out_process.
19999 					 */
20000 					ipsec_out_process(q, mp, NULL,
20001 					    io->ipsec_out_ill_index);
20002 					return;
20003 				} else {
20004 					connp = (q->q_next != NULL) ?
20005 					    NULL : Q_TO_CONN(q);
20006 					first_mp = mp;
20007 					mp = mp->b_cont;
20008 					mctl_present = B_TRUE;
20009 				}
20010 				zoneid = io->ipsec_out_zoneid;
20011 				ASSERT(zoneid != ALL_ZONES);
20012 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20013 				/*
20014 				 * It's an IPsec control message requesting
20015 				 * an SADB update to be sent to the IPsec
20016 				 * hardware acceleration capable ills.
20017 				 */
20018 				ipsec_ctl_t *ipsec_ctl =
20019 				    (ipsec_ctl_t *)mp->b_rptr;
20020 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20021 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20022 				mblk_t *cmp = mp->b_cont;
20023 
20024 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20025 				ASSERT(cmp != NULL);
20026 
20027 				freeb(mp);
20028 				ill_ipsec_capab_send_all(satype, cmp, sa);
20029 				return;
20030 			} else {
20031 				/*
20032 				 * This must be ARP or special TSOL signaling.
20033 				 */
20034 				ip_wput_nondata(NULL, q, mp, NULL);
20035 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20036 				    "ip_wput_end: q %p (%S)", q, "nondata");
20037 				return;
20038 			}
20039 		} else {
20040 			/*
20041 			 * This must be non-(ARP/AH/ESP) messages.
20042 			 */
20043 			ASSERT(!need_decref);
20044 			ip_wput_nondata(NULL, q, mp, NULL);
20045 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20046 			    "ip_wput_end: q %p (%S)", q, "nondata");
20047 			return;
20048 		}
20049 	} else {
20050 		first_mp = mp;
20051 		mctl_present = B_FALSE;
20052 	}
20053 
20054 	ASSERT(first_mp != NULL);
20055 	/*
20056 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20057 	 * to make sure that this packet goes out on the same interface it
20058 	 * came in. We handle that here.
20059 	 */
20060 	if (mctl_present) {
20061 		uint_t ifindex;
20062 
20063 		io = (ipsec_out_t *)first_mp->b_rptr;
20064 		if (io->ipsec_out_attach_if ||
20065 		    io->ipsec_out_xmit_if ||
20066 		    io->ipsec_out_ip_nexthop) {
20067 			ill_t	*ill;
20068 
20069 			/*
20070 			 * We may have lost the conn context if we are
20071 			 * coming here from ip_newroute(). Copy the
20072 			 * nexthop information.
20073 			 */
20074 			if (io->ipsec_out_ip_nexthop) {
20075 				ip_nexthop = B_TRUE;
20076 				nexthop_addr = io->ipsec_out_nexthop_addr;
20077 
20078 				ipha = (ipha_t *)mp->b_rptr;
20079 				dst = ipha->ipha_dst;
20080 				goto send_from_ill;
20081 			} else {
20082 				ASSERT(io->ipsec_out_ill_index != 0);
20083 				ifindex = io->ipsec_out_ill_index;
20084 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20085 				    NULL, NULL, NULL, NULL);
20086 				/*
20087 				 * ipsec_out_xmit_if bit is used to tell
20088 				 * ip_wput to use the ill to send outgoing data
20089 				 * as we have no conn when data comes from ICMP
20090 				 * error msg routines. Currently this feature is
20091 				 * only used by ip_mrtun_forward routine.
20092 				 */
20093 				if (io->ipsec_out_xmit_if) {
20094 					xmit_ill = ill;
20095 					if (xmit_ill == NULL) {
20096 						ip1dbg(("ip_output:bad ifindex "
20097 						    "for xmit_ill %d\n",
20098 						    ifindex));
20099 						freemsg(first_mp);
20100 						BUMP_MIB(&ip_mib,
20101 						    ipOutDiscards);
20102 						ASSERT(!need_decref);
20103 						return;
20104 					}
20105 					/* Free up the ipsec_out_t mblk */
20106 					ASSERT(first_mp->b_cont == mp);
20107 					first_mp->b_cont = NULL;
20108 					freeb(first_mp);
20109 					/* Just send the IP header+ICMP+data */
20110 					first_mp = mp;
20111 					ipha = (ipha_t *)mp->b_rptr;
20112 					dst = ipha->ipha_dst;
20113 					goto send_from_ill;
20114 				} else {
20115 					attach_ill = ill;
20116 				}
20117 
20118 				if (attach_ill == NULL) {
20119 					ASSERT(xmit_ill == NULL);
20120 					ip1dbg(("ip_output: bad ifindex for "
20121 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20122 					    ifindex));
20123 					freemsg(first_mp);
20124 					BUMP_MIB(&ip_mib, ipOutDiscards);
20125 					ASSERT(!need_decref);
20126 					return;
20127 				}
20128 			}
20129 		}
20130 	}
20131 
20132 	ASSERT(xmit_ill == NULL);
20133 
20134 	/* We have a complete IP datagram heading outbound. */
20135 	ipha = (ipha_t *)mp->b_rptr;
20136 
20137 #ifndef SPEED_BEFORE_SAFETY
20138 	/*
20139 	 * Make sure we have a full-word aligned message and that at least
20140 	 * a simple IP header is accessible in the first message.  If not,
20141 	 * try a pullup.
20142 	 */
20143 	if (!OK_32PTR(rptr) ||
20144 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20145 	    hdrtoosmall:
20146 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20147 			BUMP_MIB(&ip_mib, ipOutDiscards);
20148 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20149 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20150 			if (first_mp == NULL)
20151 				first_mp = mp;
20152 			goto drop_pkt;
20153 		}
20154 
20155 		/* This function assumes that mp points to an IPv4 packet. */
20156 		if (is_system_labeled() && q->q_next == NULL &&
20157 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20158 		    !connp->conn_ulp_labeled) {
20159 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20160 			    &adjust, connp->conn_mac_exempt);
20161 			ipha = (ipha_t *)mp->b_rptr;
20162 			if (first_mp != NULL)
20163 				first_mp->b_cont = mp;
20164 			if (err != 0) {
20165 				if (first_mp == NULL)
20166 					first_mp = mp;
20167 				if (err == EINVAL)
20168 					goto icmp_parameter_problem;
20169 				ip2dbg(("ip_wput: label check failed (%d)\n",
20170 				    err));
20171 				goto drop_pkt;
20172 			}
20173 			iplen = ntohs(ipha->ipha_length) + adjust;
20174 			ipha->ipha_length = htons(iplen);
20175 		}
20176 
20177 		ipha = (ipha_t *)mp->b_rptr;
20178 		if (first_mp == NULL) {
20179 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20180 			/*
20181 			 * If we got here because of "goto hdrtoosmall"
20182 			 * We need to attach a IPSEC_OUT.
20183 			 */
20184 			if (connp->conn_out_enforce_policy) {
20185 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20186 				    NULL, ipha->ipha_protocol)) == NULL)) {
20187 					if (need_decref)
20188 						CONN_DEC_REF(connp);
20189 					return;
20190 				} else {
20191 					ASSERT(mp->b_datap->db_type == M_CTL);
20192 					first_mp = mp;
20193 					mp = mp->b_cont;
20194 					mctl_present = B_TRUE;
20195 				}
20196 			} else {
20197 				first_mp = mp;
20198 				mctl_present = B_FALSE;
20199 			}
20200 		}
20201 	}
20202 #endif
20203 
20204 	/* Most of the code below is written for speed, not readability */
20205 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20206 
20207 	/*
20208 	 * If ip_newroute() fails, we're going to need a full
20209 	 * header for the icmp wraparound.
20210 	 */
20211 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20212 		uint_t	v_hlen;
20213 	    version_hdrlen_check:
20214 		ASSERT(first_mp != NULL);
20215 		v_hlen = V_HLEN;
20216 		/*
20217 		 * siphon off IPv6 packets coming down from transport
20218 		 * layer modules here.
20219 		 * Note: high-order bit carries NUD reachability confirmation
20220 		 */
20221 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20222 			/*
20223 			 * XXX implement a IPv4 and IPv6 packet counter per
20224 			 * conn and switch when ratio exceeds e.g. 10:1
20225 			 */
20226 #ifdef notyet
20227 			if (q->q_next == NULL) /* Avoid ill queue */
20228 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
20229 #endif
20230 			BUMP_MIB(&ip_mib, ipOutIPv6);
20231 			ASSERT(xmit_ill == NULL);
20232 			if (attach_ill != NULL)
20233 				ill_refrele(attach_ill);
20234 			if (need_decref)
20235 				mp->b_flag |= MSGHASREF;
20236 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20237 			return;
20238 		}
20239 
20240 		if ((v_hlen >> 4) != IP_VERSION) {
20241 			BUMP_MIB(&ip_mib, ipOutDiscards);
20242 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20243 			    "ip_wput_end: q %p (%S)", q, "badvers");
20244 			goto drop_pkt;
20245 		}
20246 		/*
20247 		 * Is the header length at least 20 bytes?
20248 		 *
20249 		 * Are there enough bytes accessible in the header?  If
20250 		 * not, try a pullup.
20251 		 */
20252 		v_hlen &= 0xF;
20253 		v_hlen <<= 2;
20254 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20255 			BUMP_MIB(&ip_mib, ipOutDiscards);
20256 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20257 			    "ip_wput_end: q %p (%S)", q, "badlen");
20258 			goto drop_pkt;
20259 		}
20260 		if (v_hlen > (mp->b_wptr - rptr)) {
20261 			if (!pullupmsg(mp, v_hlen)) {
20262 				BUMP_MIB(&ip_mib, ipOutDiscards);
20263 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20264 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20265 				goto drop_pkt;
20266 			}
20267 			ipha = (ipha_t *)mp->b_rptr;
20268 		}
20269 		/*
20270 		 * Move first entry from any source route into ipha_dst and
20271 		 * verify the options
20272 		 */
20273 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
20274 			ASSERT(xmit_ill == NULL);
20275 			if (attach_ill != NULL)
20276 				ill_refrele(attach_ill);
20277 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20278 			    "ip_wput_end: q %p (%S)", q, "badopts");
20279 			if (need_decref)
20280 				CONN_DEC_REF(connp);
20281 			return;
20282 		}
20283 	}
20284 	dst = ipha->ipha_dst;
20285 
20286 	/*
20287 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20288 	 * we have to run the packet through ip_newroute which will take
20289 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20290 	 * a resolver, or assigning a default gateway, etc.
20291 	 */
20292 	if (CLASSD(dst)) {
20293 		ipif_t	*ipif;
20294 		uint32_t setsrc = 0;
20295 
20296 	    multicast:
20297 		ASSERT(first_mp != NULL);
20298 		ASSERT(xmit_ill == NULL);
20299 		ip2dbg(("ip_wput: CLASSD\n"));
20300 		if (connp == NULL) {
20301 			/*
20302 			 * Use the first good ipif on the ill.
20303 			 * XXX Should this ever happen? (Appears
20304 			 * to show up with just ppp and no ethernet due
20305 			 * to in.rdisc.)
20306 			 * However, ire_send should be able to
20307 			 * call ip_wput_ire directly.
20308 			 *
20309 			 * XXX Also, this can happen for ICMP and other packets
20310 			 * with multicast source addresses.  Perhaps we should
20311 			 * fix things so that we drop the packet in question,
20312 			 * but for now, just run with it.
20313 			 */
20314 			ill_t *ill = (ill_t *)q->q_ptr;
20315 
20316 			/*
20317 			 * Don't honor attach_if for this case. If ill
20318 			 * is part of the group, ipif could belong to
20319 			 * any ill and we cannot maintain attach_ill
20320 			 * and ipif_ill same anymore and the assert
20321 			 * below would fail.
20322 			 */
20323 			if (mctl_present && io->ipsec_out_attach_if) {
20324 				io->ipsec_out_ill_index = 0;
20325 				io->ipsec_out_attach_if = B_FALSE;
20326 				ASSERT(attach_ill != NULL);
20327 				ill_refrele(attach_ill);
20328 				attach_ill = NULL;
20329 			}
20330 
20331 			ASSERT(attach_ill == NULL);
20332 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20333 			if (ipif == NULL) {
20334 				if (need_decref)
20335 					CONN_DEC_REF(connp);
20336 				freemsg(first_mp);
20337 				return;
20338 			}
20339 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20340 			    ntohl(dst), ill->ill_name));
20341 		} else {
20342 			/*
20343 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
20344 			 * IP_XMIT_IF is honoured.
20345 			 * Block comment above this function explains the
20346 			 * locking mechanism used here
20347 			 */
20348 			xmit_ill = conn_get_held_ill(connp,
20349 			    &connp->conn_xmit_if_ill, &err);
20350 			if (err == ILL_LOOKUP_FAILED) {
20351 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
20352 				goto drop_pkt;
20353 			}
20354 			if (xmit_ill == NULL) {
20355 				ipif = conn_get_held_ipif(connp,
20356 				    &connp->conn_multicast_ipif, &err);
20357 				if (err == IPIF_LOOKUP_FAILED) {
20358 					ip1dbg(("ip_wput: No ipif for "
20359 					    "multicast\n"));
20360 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20361 					goto drop_pkt;
20362 				}
20363 			}
20364 			if (xmit_ill != NULL) {
20365 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20366 				if (ipif == NULL) {
20367 					ip1dbg(("ip_wput: No ipif for "
20368 					    "IP_XMIT_IF\n"));
20369 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20370 					goto drop_pkt;
20371 				}
20372 			} else if (ipif == NULL || ipif->ipif_isv6) {
20373 				/*
20374 				 * We must do this ipif determination here
20375 				 * else we could pass through ip_newroute
20376 				 * and come back here without the conn context.
20377 				 *
20378 				 * Note: we do late binding i.e. we bind to
20379 				 * the interface when the first packet is sent.
20380 				 * For performance reasons we do not rebind on
20381 				 * each packet but keep the binding until the
20382 				 * next IP_MULTICAST_IF option.
20383 				 *
20384 				 * conn_multicast_{ipif,ill} are shared between
20385 				 * IPv4 and IPv6 and AF_INET6 sockets can
20386 				 * send both IPv4 and IPv6 packets. Hence
20387 				 * we have to check that "isv6" matches above.
20388 				 */
20389 				if (ipif != NULL)
20390 					ipif_refrele(ipif);
20391 				ipif = ipif_lookup_group(dst, zoneid);
20392 				if (ipif == NULL) {
20393 					ip1dbg(("ip_wput: No ipif for "
20394 					    "multicast\n"));
20395 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20396 					goto drop_pkt;
20397 				}
20398 				err = conn_set_held_ipif(connp,
20399 				    &connp->conn_multicast_ipif, ipif);
20400 				if (err == IPIF_LOOKUP_FAILED) {
20401 					ipif_refrele(ipif);
20402 					ip1dbg(("ip_wput: No ipif for "
20403 					    "multicast\n"));
20404 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20405 					goto drop_pkt;
20406 				}
20407 			}
20408 		}
20409 		ASSERT(!ipif->ipif_isv6);
20410 		/*
20411 		 * As we may lose the conn by the time we reach ip_wput_ire,
20412 		 * we copy conn_multicast_loop and conn_dontroute on to an
20413 		 * ipsec_out. In case if this datagram goes out secure,
20414 		 * we need the ill_index also. Copy that also into the
20415 		 * ipsec_out.
20416 		 */
20417 		if (mctl_present) {
20418 			io = (ipsec_out_t *)first_mp->b_rptr;
20419 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20420 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20421 		} else {
20422 			ASSERT(mp == first_mp);
20423 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20424 			    BPRI_HI)) == NULL) {
20425 				ipif_refrele(ipif);
20426 				first_mp = mp;
20427 				goto drop_pkt;
20428 			}
20429 			first_mp->b_datap->db_type = M_CTL;
20430 			first_mp->b_wptr += sizeof (ipsec_info_t);
20431 			/* ipsec_out_secure is B_FALSE now */
20432 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20433 			io = (ipsec_out_t *)first_mp->b_rptr;
20434 			io->ipsec_out_type = IPSEC_OUT;
20435 			io->ipsec_out_len = sizeof (ipsec_out_t);
20436 			io->ipsec_out_use_global_policy = B_TRUE;
20437 			first_mp->b_cont = mp;
20438 			mctl_present = B_TRUE;
20439 		}
20440 		if (attach_ill != NULL) {
20441 			ASSERT(attach_ill == ipif->ipif_ill);
20442 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20443 
20444 			/*
20445 			 * Check if we need an ire that will not be
20446 			 * looked up by anybody else i.e. HIDDEN.
20447 			 */
20448 			if (ill_is_probeonly(attach_ill)) {
20449 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20450 			}
20451 			io->ipsec_out_ill_index =
20452 			    attach_ill->ill_phyint->phyint_ifindex;
20453 			io->ipsec_out_attach_if = B_TRUE;
20454 		} else {
20455 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20456 			io->ipsec_out_ill_index =
20457 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20458 		}
20459 		if (connp != NULL) {
20460 			io->ipsec_out_multicast_loop =
20461 			    connp->conn_multicast_loop;
20462 			io->ipsec_out_dontroute = connp->conn_dontroute;
20463 			io->ipsec_out_zoneid = connp->conn_zoneid;
20464 		}
20465 		/*
20466 		 * If the application uses IP_MULTICAST_IF with
20467 		 * different logical addresses of the same ILL, we
20468 		 * need to make sure that the soruce address of
20469 		 * the packet matches the logical IP address used
20470 		 * in the option. We do it by initializing ipha_src
20471 		 * here. This should keep IPSEC also happy as
20472 		 * when we return from IPSEC processing, we don't
20473 		 * have to worry about getting the right address on
20474 		 * the packet. Thus it is sufficient to look for
20475 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20476 		 * MATCH_IRE_IPIF.
20477 		 *
20478 		 * NOTE : We need to do it for non-secure case also as
20479 		 * this might go out secure if there is a global policy
20480 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20481 		 * address, the source should be initialized already and
20482 		 * hence we won't be initializing here.
20483 		 *
20484 		 * As we do not have the ire yet, it is possible that
20485 		 * we set the source address here and then later discover
20486 		 * that the ire implies the source address to be assigned
20487 		 * through the RTF_SETSRC flag.
20488 		 * In that case, the setsrc variable will remind us
20489 		 * that overwritting the source address by the one
20490 		 * of the RTF_SETSRC-flagged ire is allowed.
20491 		 */
20492 		if (ipha->ipha_src == INADDR_ANY &&
20493 		    (connp == NULL || !connp->conn_unspec_src)) {
20494 			ipha->ipha_src = ipif->ipif_src_addr;
20495 			setsrc = RTF_SETSRC;
20496 		}
20497 		/*
20498 		 * Find an IRE which matches the destination and the outgoing
20499 		 * queue (i.e. the outgoing interface.)
20500 		 * For loopback use a unicast IP address for
20501 		 * the ire lookup.
20502 		 */
20503 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20504 		    PHYI_LOOPBACK) {
20505 			dst = ipif->ipif_lcl_addr;
20506 		}
20507 		/*
20508 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20509 		 * We don't need to lookup ire in ctable as the packet
20510 		 * needs to be sent to the destination through the specified
20511 		 * ill irrespective of ires in the cache table.
20512 		 */
20513 		ire = NULL;
20514 		if (xmit_ill == NULL) {
20515 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20516 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20517 		}
20518 
20519 		/*
20520 		 * refrele attach_ill as its not needed anymore.
20521 		 */
20522 		if (attach_ill != NULL) {
20523 			ill_refrele(attach_ill);
20524 			attach_ill = NULL;
20525 		}
20526 
20527 		if (ire == NULL) {
20528 			/*
20529 			 * Multicast loopback and multicast forwarding is
20530 			 * done in ip_wput_ire.
20531 			 *
20532 			 * Mark this packet to make it be delivered to
20533 			 * ip_wput_ire after the new ire has been
20534 			 * created.
20535 			 *
20536 			 * The call to ip_newroute_ipif takes into account
20537 			 * the setsrc reminder. In any case, we take care
20538 			 * of the RTF_MULTIRT flag.
20539 			 */
20540 			mp->b_prev = mp->b_next = NULL;
20541 			if (xmit_ill == NULL ||
20542 			    xmit_ill->ill_ipif_up_count > 0) {
20543 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20544 				    setsrc | RTF_MULTIRT, zoneid);
20545 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20546 				    "ip_wput_end: q %p (%S)", q, "noire");
20547 			} else {
20548 				freemsg(first_mp);
20549 			}
20550 			ipif_refrele(ipif);
20551 			if (xmit_ill != NULL)
20552 				ill_refrele(xmit_ill);
20553 			if (need_decref)
20554 				CONN_DEC_REF(connp);
20555 			return;
20556 		}
20557 
20558 		ipif_refrele(ipif);
20559 		ipif = NULL;
20560 		ASSERT(xmit_ill == NULL);
20561 
20562 		/*
20563 		 * Honor the RTF_SETSRC flag for multicast packets,
20564 		 * if allowed by the setsrc reminder.
20565 		 */
20566 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20567 			ipha->ipha_src = ire->ire_src_addr;
20568 		}
20569 
20570 		/*
20571 		 * Unconditionally force the TTL to 1 for
20572 		 * multirouted multicast packets:
20573 		 * multirouted multicast should not cross
20574 		 * multicast routers.
20575 		 */
20576 		if (ire->ire_flags & RTF_MULTIRT) {
20577 			if (ipha->ipha_ttl > 1) {
20578 				ip2dbg(("ip_wput: forcing multicast "
20579 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20580 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20581 				ipha->ipha_ttl = 1;
20582 			}
20583 		}
20584 	} else {
20585 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20586 		if ((ire != NULL) && (ire->ire_type &
20587 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20588 			ignore_dontroute = B_TRUE;
20589 			ignore_nexthop = B_TRUE;
20590 		}
20591 		if (ire != NULL) {
20592 			ire_refrele(ire);
20593 			ire = NULL;
20594 		}
20595 		/*
20596 		 * Guard against coming in from arp in which case conn is NULL.
20597 		 * Also guard against non M_DATA with dontroute set but
20598 		 * destined to local, loopback or broadcast addresses.
20599 		 */
20600 		if (connp != NULL && connp->conn_dontroute &&
20601 		    !ignore_dontroute) {
20602 dontroute:
20603 			/*
20604 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20605 			 * routing protocols from seeing false direct
20606 			 * connectivity.
20607 			 */
20608 			ipha->ipha_ttl = 1;
20609 			/*
20610 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20611 			 * along with SO_DONTROUTE, higher precedence is
20612 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20613 			 */
20614 			if (connp->conn_xmit_if_ill == NULL) {
20615 				/* If suitable ipif not found, drop packet */
20616 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20617 				if (dst_ipif == NULL) {
20618 					ip1dbg(("ip_wput: no route for "
20619 					    "dst using SO_DONTROUTE\n"));
20620 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20621 					mp->b_prev = mp->b_next = NULL;
20622 					if (first_mp == NULL)
20623 						first_mp = mp;
20624 					goto drop_pkt;
20625 				} else {
20626 					/*
20627 					 * If suitable ipif has been found, set
20628 					 * xmit_ill to the corresponding
20629 					 * ipif_ill because we'll be following
20630 					 * the IP_XMIT_IF logic.
20631 					 */
20632 					ASSERT(xmit_ill == NULL);
20633 					xmit_ill = dst_ipif->ipif_ill;
20634 					mutex_enter(&xmit_ill->ill_lock);
20635 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20636 						mutex_exit(&xmit_ill->ill_lock);
20637 						xmit_ill = NULL;
20638 						ipif_refrele(dst_ipif);
20639 						ip1dbg(("ip_wput: no route for"
20640 						    " dst using"
20641 						    " SO_DONTROUTE\n"));
20642 						BUMP_MIB(&ip_mib,
20643 						    ipOutNoRoutes);
20644 						mp->b_prev = mp->b_next = NULL;
20645 						if (first_mp == NULL)
20646 							first_mp = mp;
20647 						goto drop_pkt;
20648 					}
20649 					ill_refhold_locked(xmit_ill);
20650 					mutex_exit(&xmit_ill->ill_lock);
20651 					ipif_refrele(dst_ipif);
20652 				}
20653 			}
20654 
20655 		}
20656 		/*
20657 		 * If we are bound to IPIF_NOFAILOVER address, look for
20658 		 * an IRE_CACHE matching the ill.
20659 		 */
20660 send_from_ill:
20661 		if (attach_ill != NULL) {
20662 			ipif_t	*attach_ipif;
20663 
20664 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20665 
20666 			/*
20667 			 * Check if we need an ire that will not be
20668 			 * looked up by anybody else i.e. HIDDEN.
20669 			 */
20670 			if (ill_is_probeonly(attach_ill)) {
20671 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20672 			}
20673 
20674 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20675 			if (attach_ipif == NULL) {
20676 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20677 				goto drop_pkt;
20678 			}
20679 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20680 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20681 			ipif_refrele(attach_ipif);
20682 		} else if (xmit_ill != NULL || (connp != NULL &&
20683 			    connp->conn_xmit_if_ill != NULL)) {
20684 			/*
20685 			 * Mark this packet as originated locally
20686 			 */
20687 			mp->b_prev = mp->b_next = NULL;
20688 			/*
20689 			 * xmit_ill could be NULL if SO_DONTROUTE
20690 			 * is also set.
20691 			 */
20692 			if (xmit_ill == NULL) {
20693 				xmit_ill = conn_get_held_ill(connp,
20694 				    &connp->conn_xmit_if_ill, &err);
20695 				if (err == ILL_LOOKUP_FAILED) {
20696 					if (need_decref)
20697 						CONN_DEC_REF(connp);
20698 					freemsg(first_mp);
20699 					return;
20700 				}
20701 				if (xmit_ill == NULL) {
20702 					if (connp->conn_dontroute)
20703 						goto dontroute;
20704 					goto send_from_ill;
20705 				}
20706 			}
20707 			/*
20708 			 * could be SO_DONTROUTE case also.
20709 			 * check at least one interface is UP as
20710 			 * spcified by this ILL, and then call
20711 			 * ip_newroute_ipif()
20712 			 */
20713 			if (xmit_ill->ill_ipif_up_count > 0) {
20714 				ipif_t *ipif;
20715 
20716 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20717 				if (ipif != NULL) {
20718 					ip_newroute_ipif(q, first_mp, ipif,
20719 					    dst, connp, 0, zoneid);
20720 					ipif_refrele(ipif);
20721 					ip1dbg(("ip_wput: ip_unicast_if\n"));
20722 				}
20723 			} else {
20724 				freemsg(first_mp);
20725 			}
20726 			ill_refrele(xmit_ill);
20727 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20728 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
20729 			if (need_decref)
20730 				CONN_DEC_REF(connp);
20731 			return;
20732 		} else if (ip_nexthop || (connp != NULL &&
20733 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
20734 			if (!ip_nexthop) {
20735 				ip_nexthop = B_TRUE;
20736 				nexthop_addr = connp->conn_nexthop_v4;
20737 			}
20738 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
20739 			    MATCH_IRE_GW;
20740 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
20741 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
20742 		} else {
20743 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20744 		}
20745 		if (!ire) {
20746 			/*
20747 			 * Make sure we don't load spread if this
20748 			 * is IPIF_NOFAILOVER case.
20749 			 */
20750 			if ((attach_ill != NULL) ||
20751 			    (ip_nexthop && !ignore_nexthop)) {
20752 				if (mctl_present) {
20753 					io = (ipsec_out_t *)first_mp->b_rptr;
20754 					ASSERT(first_mp->b_datap->db_type ==
20755 					    M_CTL);
20756 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
20757 				} else {
20758 					ASSERT(mp == first_mp);
20759 					first_mp = allocb(
20760 					    sizeof (ipsec_info_t), BPRI_HI);
20761 					if (first_mp == NULL) {
20762 						first_mp = mp;
20763 						goto drop_pkt;
20764 					}
20765 					first_mp->b_datap->db_type = M_CTL;
20766 					first_mp->b_wptr +=
20767 					    sizeof (ipsec_info_t);
20768 					/* ipsec_out_secure is B_FALSE now */
20769 					bzero(first_mp->b_rptr,
20770 					    sizeof (ipsec_info_t));
20771 					io = (ipsec_out_t *)first_mp->b_rptr;
20772 					io->ipsec_out_type = IPSEC_OUT;
20773 					io->ipsec_out_len =
20774 					    sizeof (ipsec_out_t);
20775 					io->ipsec_out_use_global_policy =
20776 					    B_TRUE;
20777 					first_mp->b_cont = mp;
20778 					mctl_present = B_TRUE;
20779 				}
20780 				if (attach_ill != NULL) {
20781 					io->ipsec_out_ill_index = attach_ill->
20782 					    ill_phyint->phyint_ifindex;
20783 					io->ipsec_out_attach_if = B_TRUE;
20784 				} else {
20785 					io->ipsec_out_ip_nexthop = ip_nexthop;
20786 					io->ipsec_out_nexthop_addr =
20787 					    nexthop_addr;
20788 				}
20789 			}
20790 noirefound:
20791 			/*
20792 			 * Mark this packet as having originated on
20793 			 * this machine.  This will be noted in
20794 			 * ire_add_then_send, which needs to know
20795 			 * whether to run it back through ip_wput or
20796 			 * ip_rput following successful resolution.
20797 			 */
20798 			mp->b_prev = NULL;
20799 			mp->b_next = NULL;
20800 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid);
20801 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20802 			    "ip_wput_end: q %p (%S)", q, "newroute");
20803 			if (attach_ill != NULL)
20804 				ill_refrele(attach_ill);
20805 			if (xmit_ill != NULL)
20806 				ill_refrele(xmit_ill);
20807 			if (need_decref)
20808 				CONN_DEC_REF(connp);
20809 			return;
20810 		}
20811 	}
20812 
20813 	/* We now know where we are going with it. */
20814 
20815 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20816 	    "ip_wput_end: q %p (%S)", q, "end");
20817 
20818 	/*
20819 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20820 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
20821 	 */
20822 	if (ire->ire_flags & RTF_MULTIRT) {
20823 		/*
20824 		 * Force the TTL of multirouted packets if required.
20825 		 * The TTL of such packets is bounded by the
20826 		 * ip_multirt_ttl ndd variable.
20827 		 */
20828 		if ((ip_multirt_ttl > 0) &&
20829 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20830 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20831 			    "(was %d), dst 0x%08x\n",
20832 			    ip_multirt_ttl, ipha->ipha_ttl,
20833 			    ntohl(ire->ire_addr)));
20834 			ipha->ipha_ttl = ip_multirt_ttl;
20835 		}
20836 		/*
20837 		 * At this point, we check to see if there are any pending
20838 		 * unresolved routes. ire_multirt_resolvable()
20839 		 * checks in O(n) that all IRE_OFFSUBNET ire
20840 		 * entries for the packet's destination and
20841 		 * flagged RTF_MULTIRT are currently resolved.
20842 		 * If some remain unresolved, we make a copy
20843 		 * of the current message. It will be used
20844 		 * to initiate additional route resolutions.
20845 		 */
20846 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20847 		    MBLK_GETLABEL(first_mp));
20848 		ip2dbg(("ip_wput[noirefound]: ire %p, "
20849 		    "multirt_need_resolve %d, first_mp %p\n",
20850 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20851 		if (multirt_need_resolve) {
20852 			copy_mp = copymsg(first_mp);
20853 			if (copy_mp != NULL) {
20854 				MULTIRT_DEBUG_TAG(copy_mp);
20855 			}
20856 		}
20857 	}
20858 
20859 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20860 	/*
20861 	 * Try to resolve another multiroute if
20862 	 * ire_multirt_resolvable() deemed it necessary.
20863 	 * At this point, we need to distinguish
20864 	 * multicasts from other packets. For multicasts,
20865 	 * we call ip_newroute_ipif() and request that both
20866 	 * multirouting and setsrc flags are checked.
20867 	 */
20868 	if (copy_mp != NULL) {
20869 		if (CLASSD(dst)) {
20870 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
20871 			if (ipif) {
20872 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
20873 				    RTF_SETSRC | RTF_MULTIRT, zoneid);
20874 				ipif_refrele(ipif);
20875 			} else {
20876 				MULTIRT_DEBUG_UNTAG(copy_mp);
20877 				freemsg(copy_mp);
20878 				copy_mp = NULL;
20879 			}
20880 		} else {
20881 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20882 		}
20883 	}
20884 	if (attach_ill != NULL)
20885 		ill_refrele(attach_ill);
20886 	if (xmit_ill != NULL)
20887 		ill_refrele(xmit_ill);
20888 	if (need_decref)
20889 		CONN_DEC_REF(connp);
20890 	return;
20891 
20892 icmp_parameter_problem:
20893 	/* could not have originated externally */
20894 	ASSERT(mp->b_prev == NULL);
20895 	if (ip_hdr_complete(ipha, zoneid) == 0) {
20896 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
20897 		/* it's the IP header length that's in trouble */
20898 		icmp_param_problem(q, first_mp, 0, zoneid);
20899 		first_mp = NULL;
20900 	}
20901 
20902 drop_pkt:
20903 	ip1dbg(("ip_wput: dropped packet\n"));
20904 	if (ire != NULL)
20905 		ire_refrele(ire);
20906 	if (need_decref)
20907 		CONN_DEC_REF(connp);
20908 	freemsg(first_mp);
20909 	if (attach_ill != NULL)
20910 		ill_refrele(attach_ill);
20911 	if (xmit_ill != NULL)
20912 		ill_refrele(xmit_ill);
20913 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20914 	    "ip_wput_end: q %p (%S)", q, "droppkt");
20915 }
20916 
20917 /*
20918  * If this is a conn_t queue, then we pass in the conn. This includes the
20919  * zoneid.
20920  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
20921  * in which case we use the global zoneid since those are all part of
20922  * the global zone.
20923  */
20924 void
20925 ip_wput(queue_t *q, mblk_t *mp)
20926 {
20927 	if (CONN_Q(q))
20928 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20929 	else
20930 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
20931 }
20932 
20933 /*
20934  *
20935  * The following rules must be observed when accessing any ipif or ill
20936  * that has been cached in the conn. Typically conn_nofailover_ill,
20937  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20938  *
20939  * Access: The ipif or ill pointed to from the conn can be accessed under
20940  * the protection of the conn_lock or after it has been refheld under the
20941  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20942  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20943  * The reason for this is that a concurrent unplumb could actually be
20944  * cleaning up these cached pointers by walking the conns and might have
20945  * finished cleaning up the conn in question. The macros check that an
20946  * unplumb has not yet started on the ipif or ill.
20947  *
20948  * Caching: An ipif or ill pointer may be cached in the conn only after
20949  * making sure that an unplumb has not started. So the caching is done
20950  * while holding both the conn_lock and the ill_lock and after using the
20951  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20952  * flag before starting the cleanup of conns.
20953  *
20954  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20955  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20956  * or a reference to the ipif or a reference to an ire that references the
20957  * ipif. An ipif does not change its ill except for failover/failback. Since
20958  * failover/failback happens only after bringing down the ipif and making sure
20959  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20960  * the above holds.
20961  */
20962 ipif_t *
20963 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20964 {
20965 	ipif_t	*ipif;
20966 	ill_t	*ill;
20967 
20968 	*err = 0;
20969 	rw_enter(&ill_g_lock, RW_READER);
20970 	mutex_enter(&connp->conn_lock);
20971 	ipif = *ipifp;
20972 	if (ipif != NULL) {
20973 		ill = ipif->ipif_ill;
20974 		mutex_enter(&ill->ill_lock);
20975 		if (IPIF_CAN_LOOKUP(ipif)) {
20976 			ipif_refhold_locked(ipif);
20977 			mutex_exit(&ill->ill_lock);
20978 			mutex_exit(&connp->conn_lock);
20979 			rw_exit(&ill_g_lock);
20980 			return (ipif);
20981 		} else {
20982 			*err = IPIF_LOOKUP_FAILED;
20983 		}
20984 		mutex_exit(&ill->ill_lock);
20985 	}
20986 	mutex_exit(&connp->conn_lock);
20987 	rw_exit(&ill_g_lock);
20988 	return (NULL);
20989 }
20990 
20991 ill_t *
20992 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20993 {
20994 	ill_t	*ill;
20995 
20996 	*err = 0;
20997 	mutex_enter(&connp->conn_lock);
20998 	ill = *illp;
20999 	if (ill != NULL) {
21000 		mutex_enter(&ill->ill_lock);
21001 		if (ILL_CAN_LOOKUP(ill)) {
21002 			ill_refhold_locked(ill);
21003 			mutex_exit(&ill->ill_lock);
21004 			mutex_exit(&connp->conn_lock);
21005 			return (ill);
21006 		} else {
21007 			*err = ILL_LOOKUP_FAILED;
21008 		}
21009 		mutex_exit(&ill->ill_lock);
21010 	}
21011 	mutex_exit(&connp->conn_lock);
21012 	return (NULL);
21013 }
21014 
21015 static int
21016 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21017 {
21018 	ill_t	*ill;
21019 
21020 	ill = ipif->ipif_ill;
21021 	mutex_enter(&connp->conn_lock);
21022 	mutex_enter(&ill->ill_lock);
21023 	if (IPIF_CAN_LOOKUP(ipif)) {
21024 		*ipifp = ipif;
21025 		mutex_exit(&ill->ill_lock);
21026 		mutex_exit(&connp->conn_lock);
21027 		return (0);
21028 	}
21029 	mutex_exit(&ill->ill_lock);
21030 	mutex_exit(&connp->conn_lock);
21031 	return (IPIF_LOOKUP_FAILED);
21032 }
21033 
21034 /*
21035  * This is called if the outbound datagram needs fragmentation.
21036  *
21037  * NOTE : This function does not ire_refrele the ire argument passed in.
21038  */
21039 static void
21040 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid)
21041 {
21042 	ipha_t		*ipha;
21043 	mblk_t		*mp;
21044 	uint32_t	v_hlen_tos_len;
21045 	uint32_t	max_frag;
21046 	uint32_t	frag_flag;
21047 	boolean_t	dont_use;
21048 
21049 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21050 		mp = ipsec_mp->b_cont;
21051 	} else {
21052 		mp = ipsec_mp;
21053 	}
21054 
21055 	ipha = (ipha_t *)mp->b_rptr;
21056 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21057 
21058 #ifdef	_BIG_ENDIAN
21059 #define	V_HLEN	(v_hlen_tos_len >> 24)
21060 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21061 #else
21062 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21063 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21064 #endif
21065 
21066 #ifndef SPEED_BEFORE_SAFETY
21067 	/*
21068 	 * Check that ipha_length is consistent with
21069 	 * the mblk length
21070 	 */
21071 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21072 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21073 		    LENGTH, msgdsize(mp)));
21074 		freemsg(ipsec_mp);
21075 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21076 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21077 		    "packet length mismatch");
21078 		return;
21079 	}
21080 #endif
21081 	/*
21082 	 * Don't use frag_flag if pre-built packet or source
21083 	 * routed or if multicast (since multicast packets do not solicit
21084 	 * ICMP "packet too big" messages). Get the values of
21085 	 * max_frag and frag_flag atomically by acquiring the
21086 	 * ire_lock.
21087 	 */
21088 	mutex_enter(&ire->ire_lock);
21089 	max_frag = ire->ire_max_frag;
21090 	frag_flag = ire->ire_frag_flag;
21091 	mutex_exit(&ire->ire_lock);
21092 
21093 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21094 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21095 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21096 
21097 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21098 	    (dont_use ? 0 : frag_flag), zoneid);
21099 }
21100 
21101 /*
21102  * Used for deciding the MSS size for the upper layer. Thus
21103  * we need to check the outbound policy values in the conn.
21104  */
21105 int
21106 conn_ipsec_length(conn_t *connp)
21107 {
21108 	ipsec_latch_t *ipl;
21109 
21110 	ipl = connp->conn_latch;
21111 	if (ipl == NULL)
21112 		return (0);
21113 
21114 	if (ipl->ipl_out_policy == NULL)
21115 		return (0);
21116 
21117 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21118 }
21119 
21120 /*
21121  * Returns an estimate of the IPSEC headers size. This is used if
21122  * we don't want to call into IPSEC to get the exact size.
21123  */
21124 int
21125 ipsec_out_extra_length(mblk_t *ipsec_mp)
21126 {
21127 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21128 	ipsec_action_t *a;
21129 
21130 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21131 	if (!io->ipsec_out_secure)
21132 		return (0);
21133 
21134 	a = io->ipsec_out_act;
21135 
21136 	if (a == NULL) {
21137 		ASSERT(io->ipsec_out_policy != NULL);
21138 		a = io->ipsec_out_policy->ipsp_act;
21139 	}
21140 	ASSERT(a != NULL);
21141 
21142 	return (a->ipa_ovhd);
21143 }
21144 
21145 /*
21146  * Returns an estimate of the IPSEC headers size. This is used if
21147  * we don't want to call into IPSEC to get the exact size.
21148  */
21149 int
21150 ipsec_in_extra_length(mblk_t *ipsec_mp)
21151 {
21152 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21153 	ipsec_action_t *a;
21154 
21155 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21156 
21157 	a = ii->ipsec_in_action;
21158 	return (a == NULL ? 0 : a->ipa_ovhd);
21159 }
21160 
21161 /*
21162  * If there are any source route options, return the true final
21163  * destination. Otherwise, return the destination.
21164  */
21165 ipaddr_t
21166 ip_get_dst(ipha_t *ipha)
21167 {
21168 	ipoptp_t	opts;
21169 	uchar_t		*opt;
21170 	uint8_t		optval;
21171 	uint8_t		optlen;
21172 	ipaddr_t	dst;
21173 	uint32_t off;
21174 
21175 	dst = ipha->ipha_dst;
21176 
21177 	if (IS_SIMPLE_IPH(ipha))
21178 		return (dst);
21179 
21180 	for (optval = ipoptp_first(&opts, ipha);
21181 	    optval != IPOPT_EOL;
21182 	    optval = ipoptp_next(&opts)) {
21183 		opt = opts.ipoptp_cur;
21184 		optlen = opts.ipoptp_len;
21185 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21186 		switch (optval) {
21187 		case IPOPT_SSRR:
21188 		case IPOPT_LSRR:
21189 			off = opt[IPOPT_OFFSET];
21190 			/*
21191 			 * If one of the conditions is true, it means
21192 			 * end of options and dst already has the right
21193 			 * value.
21194 			 */
21195 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21196 				off = optlen - IP_ADDR_LEN;
21197 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21198 			}
21199 			return (dst);
21200 		default:
21201 			break;
21202 		}
21203 	}
21204 
21205 	return (dst);
21206 }
21207 
21208 mblk_t *
21209 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21210     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21211 {
21212 	ipsec_out_t	*io;
21213 	mblk_t		*first_mp;
21214 	boolean_t policy_present;
21215 
21216 	first_mp = mp;
21217 	if (mp->b_datap->db_type == M_CTL) {
21218 		io = (ipsec_out_t *)first_mp->b_rptr;
21219 		/*
21220 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21221 		 *
21222 		 * 1) There is per-socket policy (including cached global
21223 		 *    policy) or a policy on the IP-in-IP tunnel.
21224 		 * 2) There is no per-socket policy, but it is
21225 		 *    a multicast packet that needs to go out
21226 		 *    on a specific interface. This is the case
21227 		 *    where (ip_wput and ip_wput_multicast) attaches
21228 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21229 		 *
21230 		 * In case (2) we check with global policy to
21231 		 * see if there is a match and set the ill_index
21232 		 * appropriately so that we can lookup the ire
21233 		 * properly in ip_wput_ipsec_out.
21234 		 */
21235 
21236 		/*
21237 		 * ipsec_out_use_global_policy is set to B_FALSE
21238 		 * in ipsec_in_to_out(). Refer to that function for
21239 		 * details.
21240 		 */
21241 		if ((io->ipsec_out_latch == NULL) &&
21242 		    (io->ipsec_out_use_global_policy)) {
21243 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21244 				    ire, connp, unspec_src, zoneid));
21245 		}
21246 		if (!io->ipsec_out_secure) {
21247 			/*
21248 			 * If this is not a secure packet, drop
21249 			 * the IPSEC_OUT mp and treat it as a clear
21250 			 * packet. This happens when we are sending
21251 			 * a ICMP reply back to a clear packet. See
21252 			 * ipsec_in_to_out() for details.
21253 			 */
21254 			mp = first_mp->b_cont;
21255 			freeb(first_mp);
21256 		}
21257 		return (mp);
21258 	}
21259 	/*
21260 	 * See whether we need to attach a global policy here. We
21261 	 * don't depend on the conn (as it could be null) for deciding
21262 	 * what policy this datagram should go through because it
21263 	 * should have happened in ip_wput if there was some
21264 	 * policy. This normally happens for connections which are not
21265 	 * fully bound preventing us from caching policies in
21266 	 * ip_bind. Packets coming from the TCP listener/global queue
21267 	 * - which are non-hard_bound - could also be affected by
21268 	 * applying policy here.
21269 	 *
21270 	 * If this packet is coming from tcp global queue or listener,
21271 	 * we will be applying policy here.  This may not be *right*
21272 	 * if these packets are coming from the detached connection as
21273 	 * it could have gone in clear before. This happens only if a
21274 	 * TCP connection started when there is no policy and somebody
21275 	 * added policy before it became detached. Thus packets of the
21276 	 * detached connection could go out secure and the other end
21277 	 * would drop it because it will be expecting in clear. The
21278 	 * converse is not true i.e if somebody starts a TCP
21279 	 * connection and deletes the policy, all the packets will
21280 	 * still go out with the policy that existed before deleting
21281 	 * because ip_unbind sends up policy information which is used
21282 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21283 	 * TCP to attach a dummy IPSEC_OUT and set
21284 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21285 	 * affect performance for normal cases, we are not doing it.
21286 	 * Thus, set policy before starting any TCP connections.
21287 	 *
21288 	 * NOTE - We might apply policy even for a hard bound connection
21289 	 * - for which we cached policy in ip_bind - if somebody added
21290 	 * global policy after we inherited the policy in ip_bind.
21291 	 * This means that the packets that were going out in clear
21292 	 * previously would start going secure and hence get dropped
21293 	 * on the other side. To fix this, TCP attaches a dummy
21294 	 * ipsec_out and make sure that we don't apply global policy.
21295 	 */
21296 	if (ipha != NULL)
21297 		policy_present = ipsec_outbound_v4_policy_present;
21298 	else
21299 		policy_present = ipsec_outbound_v6_policy_present;
21300 	if (!policy_present)
21301 		return (mp);
21302 
21303 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21304 		    zoneid));
21305 }
21306 
21307 ire_t *
21308 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21309 {
21310 	ipaddr_t addr;
21311 	ire_t *save_ire;
21312 	irb_t *irb;
21313 	ill_group_t *illgrp;
21314 	int	err;
21315 
21316 	save_ire = ire;
21317 	addr = ire->ire_addr;
21318 
21319 	ASSERT(ire->ire_type == IRE_BROADCAST);
21320 
21321 	illgrp = connp->conn_outgoing_ill->ill_group;
21322 	if (illgrp == NULL) {
21323 		*conn_outgoing_ill = conn_get_held_ill(connp,
21324 		    &connp->conn_outgoing_ill, &err);
21325 		if (err == ILL_LOOKUP_FAILED) {
21326 			ire_refrele(save_ire);
21327 			return (NULL);
21328 		}
21329 		return (save_ire);
21330 	}
21331 	/*
21332 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21333 	 * If it is part of the group, we need to send on the ire
21334 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21335 	 * to this group. This is okay as IP_BOUND_IF really means
21336 	 * any ill in the group. We depend on the fact that the
21337 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21338 	 * if such an ire exists. This is possible only if you have
21339 	 * at least one ill in the group that has not failed.
21340 	 *
21341 	 * First get to the ire that matches the address and group.
21342 	 *
21343 	 * We don't look for an ire with a matching zoneid because a given zone
21344 	 * won't always have broadcast ires on all ills in the group.
21345 	 */
21346 	irb = ire->ire_bucket;
21347 	rw_enter(&irb->irb_lock, RW_READER);
21348 	if (ire->ire_marks & IRE_MARK_NORECV) {
21349 		/*
21350 		 * If the current zone only has an ire broadcast for this
21351 		 * address marked NORECV, the ire we want is ahead in the
21352 		 * bucket, so we look it up deliberately ignoring the zoneid.
21353 		 */
21354 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21355 			if (ire->ire_addr != addr)
21356 				continue;
21357 			/* skip over deleted ires */
21358 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21359 				continue;
21360 		}
21361 	}
21362 	while (ire != NULL) {
21363 		/*
21364 		 * If a new interface is coming up, we could end up
21365 		 * seeing the loopback ire and the non-loopback ire
21366 		 * may not have been added yet. So check for ire_stq
21367 		 */
21368 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21369 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21370 			break;
21371 		}
21372 		ire = ire->ire_next;
21373 	}
21374 	if (ire != NULL && ire->ire_addr == addr &&
21375 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21376 		IRE_REFHOLD(ire);
21377 		rw_exit(&irb->irb_lock);
21378 		ire_refrele(save_ire);
21379 		*conn_outgoing_ill = ire_to_ill(ire);
21380 		/*
21381 		 * Refhold the ill to make the conn_outgoing_ill
21382 		 * independent of the ire. ip_wput_ire goes in a loop
21383 		 * and may refrele the ire. Since we have an ire at this
21384 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21385 		 */
21386 		ill_refhold(*conn_outgoing_ill);
21387 		return (ire);
21388 	}
21389 	rw_exit(&irb->irb_lock);
21390 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21391 	/*
21392 	 * If we can't find a suitable ire, return the original ire.
21393 	 */
21394 	return (save_ire);
21395 }
21396 
21397 /*
21398  * This function does the ire_refrele of the ire passed in as the
21399  * argument. As this function looks up more ires i.e broadcast ires,
21400  * it needs to REFRELE them. Currently, for simplicity we don't
21401  * differentiate the one passed in and looked up here. We always
21402  * REFRELE.
21403  * IPQoS Notes:
21404  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21405  * IPSec packets are done in ipsec_out_process.
21406  *
21407  */
21408 void
21409 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21410     zoneid_t zoneid)
21411 {
21412 	ipha_t		*ipha;
21413 #define	rptr	((uchar_t *)ipha)
21414 	queue_t		*stq;
21415 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21416 	uint32_t	v_hlen_tos_len;
21417 	uint32_t	ttl_protocol;
21418 	ipaddr_t	src;
21419 	ipaddr_t	dst;
21420 	uint32_t	cksum;
21421 	ipaddr_t	orig_src;
21422 	ire_t		*ire1;
21423 	mblk_t		*next_mp;
21424 	uint_t		hlen;
21425 	uint16_t	*up;
21426 	uint32_t	max_frag = ire->ire_max_frag;
21427 	ill_t		*ill = ire_to_ill(ire);
21428 	int		clusterwide;
21429 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21430 	int		ipsec_len;
21431 	mblk_t		*first_mp;
21432 	ipsec_out_t	*io;
21433 	boolean_t	conn_dontroute;		/* conn value for multicast */
21434 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21435 	boolean_t	multicast_forward;	/* Should we forward ? */
21436 	boolean_t	unspec_src;
21437 	ill_t		*conn_outgoing_ill = NULL;
21438 	ill_t		*ire_ill;
21439 	ill_t		*ire1_ill;
21440 	ill_t		*out_ill;
21441 	uint32_t 	ill_index = 0;
21442 	boolean_t	multirt_send = B_FALSE;
21443 	int		err;
21444 	ipxmit_state_t	pktxmit_state;
21445 
21446 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21447 	    "ip_wput_ire_start: q %p", q);
21448 
21449 	multicast_forward = B_FALSE;
21450 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21451 
21452 	if (ire->ire_flags & RTF_MULTIRT) {
21453 		/*
21454 		 * Multirouting case. The bucket where ire is stored
21455 		 * probably holds other RTF_MULTIRT flagged ire
21456 		 * to the destination. In this call to ip_wput_ire,
21457 		 * we attempt to send the packet through all
21458 		 * those ires. Thus, we first ensure that ire is the
21459 		 * first RTF_MULTIRT ire in the bucket,
21460 		 * before walking the ire list.
21461 		 */
21462 		ire_t *first_ire;
21463 		irb_t *irb = ire->ire_bucket;
21464 		ASSERT(irb != NULL);
21465 
21466 		/* Make sure we do not omit any multiroute ire. */
21467 		IRB_REFHOLD(irb);
21468 		for (first_ire = irb->irb_ire;
21469 		    first_ire != NULL;
21470 		    first_ire = first_ire->ire_next) {
21471 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21472 			    (first_ire->ire_addr == ire->ire_addr) &&
21473 			    !(first_ire->ire_marks &
21474 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21475 				break;
21476 		}
21477 
21478 		if ((first_ire != NULL) && (first_ire != ire)) {
21479 			IRE_REFHOLD(first_ire);
21480 			ire_refrele(ire);
21481 			ire = first_ire;
21482 			ill = ire_to_ill(ire);
21483 		}
21484 		IRB_REFRELE(irb);
21485 	}
21486 
21487 	/*
21488 	 * conn_outgoing_ill is used only in the broadcast loop.
21489 	 * for performance we don't grab the mutexs in the fastpath
21490 	 */
21491 	if ((connp != NULL) &&
21492 	    (connp->conn_xmit_if_ill == NULL) &&
21493 	    (ire->ire_type == IRE_BROADCAST) &&
21494 	    ((connp->conn_nofailover_ill != NULL) ||
21495 	    (connp->conn_outgoing_ill != NULL))) {
21496 		/*
21497 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21498 		 * option. So, see if this endpoint is bound to a
21499 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21500 		 * that if the interface is failed, we will still send
21501 		 * the packet on the same ill which is what we want.
21502 		 */
21503 		conn_outgoing_ill = conn_get_held_ill(connp,
21504 		    &connp->conn_nofailover_ill, &err);
21505 		if (err == ILL_LOOKUP_FAILED) {
21506 			ire_refrele(ire);
21507 			freemsg(mp);
21508 			return;
21509 		}
21510 		if (conn_outgoing_ill == NULL) {
21511 			/*
21512 			 * Choose a good ill in the group to send the
21513 			 * packets on.
21514 			 */
21515 			ire = conn_set_outgoing_ill(connp, ire,
21516 			    &conn_outgoing_ill);
21517 			if (ire == NULL) {
21518 				freemsg(mp);
21519 				return;
21520 			}
21521 		}
21522 	}
21523 
21524 	if (mp->b_datap->db_type != M_CTL) {
21525 		ipha = (ipha_t *)mp->b_rptr;
21526 	} else {
21527 		io = (ipsec_out_t *)mp->b_rptr;
21528 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21529 		ASSERT(zoneid == io->ipsec_out_zoneid);
21530 		ASSERT(zoneid != ALL_ZONES);
21531 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21532 		dst = ipha->ipha_dst;
21533 		/*
21534 		 * For the multicast case, ipsec_out carries conn_dontroute and
21535 		 * conn_multicast_loop as conn may not be available here. We
21536 		 * need this for multicast loopback and forwarding which is done
21537 		 * later in the code.
21538 		 */
21539 		if (CLASSD(dst)) {
21540 			conn_dontroute = io->ipsec_out_dontroute;
21541 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21542 			/*
21543 			 * If conn_dontroute is not set or conn_multicast_loop
21544 			 * is set, we need to do forwarding/loopback. For
21545 			 * datagrams from ip_wput_multicast, conn_dontroute is
21546 			 * set to B_TRUE and conn_multicast_loop is set to
21547 			 * B_FALSE so that we neither do forwarding nor
21548 			 * loopback.
21549 			 */
21550 			if (!conn_dontroute || conn_multicast_loop)
21551 				multicast_forward = B_TRUE;
21552 		}
21553 	}
21554 
21555 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21556 	    ire->ire_zoneid != ALL_ZONES) {
21557 		/*
21558 		 * When a zone sends a packet to another zone, we try to deliver
21559 		 * the packet under the same conditions as if the destination
21560 		 * was a real node on the network. To do so, we look for a
21561 		 * matching route in the forwarding table.
21562 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21563 		 * ip_newroute() does.
21564 		 * Note that IRE_LOCAL are special, since they are used
21565 		 * when the zoneid doesn't match in some cases. This means that
21566 		 * we need to handle ipha_src differently since ire_src_addr
21567 		 * belongs to the receiving zone instead of the sending zone.
21568 		 * When ip_restrict_interzone_loopback is set, then
21569 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
21570 		 * for loopback between zones when the logical "Ethernet" would
21571 		 * have looped them back.
21572 		 */
21573 		ire_t *src_ire;
21574 
21575 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21576 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21577 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
21578 		if (src_ire != NULL &&
21579 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
21580 		    (!ip_restrict_interzone_loopback ||
21581 		    ire_local_same_ill_group(ire, src_ire))) {
21582 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21583 				ipha->ipha_src = src_ire->ire_src_addr;
21584 			ire_refrele(src_ire);
21585 		} else {
21586 			ire_refrele(ire);
21587 			if (conn_outgoing_ill != NULL)
21588 				ill_refrele(conn_outgoing_ill);
21589 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
21590 			if (src_ire != NULL) {
21591 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21592 					ire_refrele(src_ire);
21593 					freemsg(mp);
21594 					return;
21595 				}
21596 				ire_refrele(src_ire);
21597 			}
21598 			if (ip_hdr_complete(ipha, zoneid)) {
21599 				/* Failed */
21600 				freemsg(mp);
21601 				return;
21602 			}
21603 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid);
21604 			return;
21605 		}
21606 	}
21607 
21608 	if (mp->b_datap->db_type == M_CTL ||
21609 	    ipsec_outbound_v4_policy_present) {
21610 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21611 		    unspec_src, zoneid);
21612 		if (mp == NULL) {
21613 			ire_refrele(ire);
21614 			if (conn_outgoing_ill != NULL)
21615 				ill_refrele(conn_outgoing_ill);
21616 			return;
21617 		}
21618 	}
21619 
21620 	first_mp = mp;
21621 	ipsec_len = 0;
21622 
21623 	if (first_mp->b_datap->db_type == M_CTL) {
21624 		io = (ipsec_out_t *)first_mp->b_rptr;
21625 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21626 		mp = first_mp->b_cont;
21627 		ipsec_len = ipsec_out_extra_length(first_mp);
21628 		ASSERT(ipsec_len >= 0);
21629 		/* We already picked up the zoneid from the M_CTL above */
21630 		ASSERT(zoneid == io->ipsec_out_zoneid);
21631 		ASSERT(zoneid != ALL_ZONES);
21632 
21633 		/*
21634 		 * Drop M_CTL here if IPsec processing is not needed.
21635 		 * (Non-IPsec use of M_CTL extracted any information it
21636 		 * needed above).
21637 		 */
21638 		if (ipsec_len == 0) {
21639 			freeb(first_mp);
21640 			first_mp = mp;
21641 		}
21642 	}
21643 
21644 	/*
21645 	 * Fast path for ip_wput_ire
21646 	 */
21647 
21648 	ipha = (ipha_t *)mp->b_rptr;
21649 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21650 	dst = ipha->ipha_dst;
21651 
21652 	/*
21653 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21654 	 * if the socket is a SOCK_RAW type. The transport checksum should
21655 	 * be provided in the pre-built packet, so we don't need to compute it.
21656 	 * Also, other application set flags, like DF, should not be altered.
21657 	 * Other transport MUST pass down zero.
21658 	 */
21659 	ip_hdr_included = ipha->ipha_ident;
21660 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21661 
21662 	if (CLASSD(dst)) {
21663 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
21664 		    ntohl(dst),
21665 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
21666 		    ntohl(ire->ire_addr)));
21667 	}
21668 
21669 /* Macros to extract header fields from data already in registers */
21670 #ifdef	_BIG_ENDIAN
21671 #define	V_HLEN	(v_hlen_tos_len >> 24)
21672 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21673 #define	PROTO	(ttl_protocol & 0xFF)
21674 #else
21675 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21676 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21677 #define	PROTO	(ttl_protocol >> 8)
21678 #endif
21679 
21680 
21681 	orig_src = src = ipha->ipha_src;
21682 	/* (The loop back to "another" is explained down below.) */
21683 another:;
21684 	/*
21685 	 * Assign an ident value for this packet.  We assign idents on
21686 	 * a per destination basis out of the IRE.  There could be
21687 	 * other threads targeting the same destination, so we have to
21688 	 * arrange for a atomic increment.  Note that we use a 32-bit
21689 	 * atomic add because it has better performance than its
21690 	 * 16-bit sibling.
21691 	 *
21692 	 * If running in cluster mode and if the source address
21693 	 * belongs to a replicated service then vector through
21694 	 * cl_inet_ipident vector to allocate ip identifier
21695 	 * NOTE: This is a contract private interface with the
21696 	 * clustering group.
21697 	 */
21698 	clusterwide = 0;
21699 	if (cl_inet_ipident) {
21700 		ASSERT(cl_inet_isclusterwide);
21701 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21702 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
21703 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
21704 			    AF_INET, (uint8_t *)(uintptr_t)src,
21705 			    (uint8_t *)(uintptr_t)dst);
21706 			clusterwide = 1;
21707 		}
21708 	}
21709 	if (!clusterwide) {
21710 		ipha->ipha_ident =
21711 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
21712 	}
21713 
21714 #ifndef _BIG_ENDIAN
21715 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21716 #endif
21717 
21718 	/*
21719 	 * Set source address unless sent on an ill or conn_unspec_src is set.
21720 	 * This is needed to obey conn_unspec_src when packets go through
21721 	 * ip_newroute + arp.
21722 	 * Assumes ip_newroute{,_multi} sets the source address as well.
21723 	 */
21724 	if (src == INADDR_ANY && !unspec_src) {
21725 		/*
21726 		 * Assign the appropriate source address from the IRE if none
21727 		 * was specified.
21728 		 */
21729 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
21730 
21731 		/*
21732 		 * With IP multipathing, broadcast packets are sent on the ire
21733 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
21734 		 * the group. However, this ire might not be in the same zone so
21735 		 * we can't always use its source address. We look for a
21736 		 * broadcast ire in the same group and in the right zone.
21737 		 */
21738 		if (ire->ire_type == IRE_BROADCAST &&
21739 		    ire->ire_zoneid != zoneid) {
21740 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
21741 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
21742 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
21743 			if (src_ire != NULL) {
21744 				src = src_ire->ire_src_addr;
21745 				ire_refrele(src_ire);
21746 			} else {
21747 				ire_refrele(ire);
21748 				if (conn_outgoing_ill != NULL)
21749 					ill_refrele(conn_outgoing_ill);
21750 				freemsg(first_mp);
21751 				BUMP_MIB(&ip_mib, ipOutDiscards);
21752 				return;
21753 			}
21754 		} else {
21755 			src = ire->ire_src_addr;
21756 		}
21757 
21758 		if (connp == NULL) {
21759 			ip1dbg(("ip_wput_ire: no connp and no src "
21760 			    "address for dst 0x%x, using src 0x%x\n",
21761 			    ntohl(dst),
21762 			    ntohl(src)));
21763 		}
21764 		ipha->ipha_src = src;
21765 	}
21766 	stq = ire->ire_stq;
21767 
21768 	/*
21769 	 * We only allow ire chains for broadcasts since there will
21770 	 * be multiple IRE_CACHE entries for the same multicast
21771 	 * address (one per ipif).
21772 	 */
21773 	next_mp = NULL;
21774 
21775 	/* broadcast packet */
21776 	if (ire->ire_type == IRE_BROADCAST)
21777 		goto broadcast;
21778 
21779 	/* loopback ? */
21780 	if (stq == NULL)
21781 		goto nullstq;
21782 
21783 	/* The ill_index for outbound ILL */
21784 	ill_index = Q_TO_INDEX(stq);
21785 
21786 	BUMP_MIB(&ip_mib, ipOutRequests);
21787 	ttl_protocol = ((uint16_t *)ipha)[4];
21788 
21789 	/* pseudo checksum (do it in parts for IP header checksum) */
21790 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21791 
21792 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
21793 		queue_t *dev_q = stq->q_next;
21794 
21795 		/* flow controlled */
21796 		if ((dev_q->q_next || dev_q->q_first) &&
21797 		    !canput(dev_q))
21798 			goto blocked;
21799 		if ((PROTO == IPPROTO_UDP) &&
21800 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21801 			hlen = (V_HLEN & 0xF) << 2;
21802 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21803 			if (*up != 0) {
21804 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
21805 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
21806 				/* Software checksum? */
21807 				if (DB_CKSUMFLAGS(mp) == 0) {
21808 					IP_STAT(ip_out_sw_cksum);
21809 					IP_STAT_UPDATE(
21810 					    ip_udp_out_sw_cksum_bytes,
21811 					    LENGTH - hlen);
21812 				}
21813 			}
21814 		}
21815 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
21816 		hlen = (V_HLEN & 0xF) << 2;
21817 		if (PROTO == IPPROTO_TCP) {
21818 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21819 			/*
21820 			 * The packet header is processed once and for all, even
21821 			 * in the multirouting case. We disable hardware
21822 			 * checksum if the packet is multirouted, as it will be
21823 			 * replicated via several interfaces, and not all of
21824 			 * them may have this capability.
21825 			 */
21826 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
21827 			    LENGTH, max_frag, ipsec_len, cksum);
21828 			/* Software checksum? */
21829 			if (DB_CKSUMFLAGS(mp) == 0) {
21830 				IP_STAT(ip_out_sw_cksum);
21831 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21832 				    LENGTH - hlen);
21833 			}
21834 		} else {
21835 			sctp_hdr_t	*sctph;
21836 
21837 			ASSERT(PROTO == IPPROTO_SCTP);
21838 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21839 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21840 			/*
21841 			 * Zero out the checksum field to ensure proper
21842 			 * checksum calculation.
21843 			 */
21844 			sctph->sh_chksum = 0;
21845 #ifdef	DEBUG
21846 			if (!skip_sctp_cksum)
21847 #endif
21848 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21849 		}
21850 	}
21851 
21852 	/*
21853 	 * If this is a multicast packet and originated from ip_wput
21854 	 * we need to do loopback and forwarding checks. If it comes
21855 	 * from ip_wput_multicast, we SHOULD not do this.
21856 	 */
21857 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
21858 
21859 	/* checksum */
21860 	cksum += ttl_protocol;
21861 
21862 	/* fragment the packet */
21863 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
21864 		goto fragmentit;
21865 	/*
21866 	 * Don't use frag_flag if packet is pre-built or source
21867 	 * routed or if multicast (since multicast packets do
21868 	 * not solicit ICMP "packet too big" messages).
21869 	 */
21870 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21871 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21872 	    !ip_source_route_included(ipha)) &&
21873 	    !CLASSD(ipha->ipha_dst))
21874 		ipha->ipha_fragment_offset_and_flags |=
21875 		    htons(ire->ire_frag_flag);
21876 
21877 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21878 		/* calculate IP header checksum */
21879 		cksum += ipha->ipha_ident;
21880 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
21881 		cksum += ipha->ipha_fragment_offset_and_flags;
21882 
21883 		/* IP options present */
21884 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21885 		if (hlen)
21886 			goto checksumoptions;
21887 
21888 		/* calculate hdr checksum */
21889 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21890 		cksum = ~(cksum + (cksum >> 16));
21891 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
21892 	}
21893 	if (ipsec_len != 0) {
21894 		/*
21895 		 * We will do the rest of the processing after
21896 		 * we come back from IPSEC in ip_wput_ipsec_out().
21897 		 */
21898 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
21899 
21900 		io = (ipsec_out_t *)first_mp->b_rptr;
21901 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
21902 				ill_phyint->phyint_ifindex;
21903 
21904 		ipsec_out_process(q, first_mp, ire, ill_index);
21905 		ire_refrele(ire);
21906 		if (conn_outgoing_ill != NULL)
21907 			ill_refrele(conn_outgoing_ill);
21908 		return;
21909 	}
21910 
21911 	/*
21912 	 * In most cases, the emission loop below is entered only
21913 	 * once. Only in the case where the ire holds the
21914 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
21915 	 * flagged ires in the bucket, and send the packet
21916 	 * through all crossed RTF_MULTIRT routes.
21917 	 */
21918 	if (ire->ire_flags & RTF_MULTIRT) {
21919 		multirt_send = B_TRUE;
21920 	}
21921 	do {
21922 		if (multirt_send) {
21923 			irb_t *irb;
21924 			/*
21925 			 * We are in a multiple send case, need to get
21926 			 * the next ire and make a duplicate of the packet.
21927 			 * ire1 holds here the next ire to process in the
21928 			 * bucket. If multirouting is expected,
21929 			 * any non-RTF_MULTIRT ire that has the
21930 			 * right destination address is ignored.
21931 			 */
21932 			irb = ire->ire_bucket;
21933 			ASSERT(irb != NULL);
21934 
21935 			IRB_REFHOLD(irb);
21936 			for (ire1 = ire->ire_next;
21937 			    ire1 != NULL;
21938 			    ire1 = ire1->ire_next) {
21939 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21940 					continue;
21941 				if (ire1->ire_addr != ire->ire_addr)
21942 					continue;
21943 				if (ire1->ire_marks &
21944 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21945 					continue;
21946 
21947 				/* Got one */
21948 				IRE_REFHOLD(ire1);
21949 				break;
21950 			}
21951 			IRB_REFRELE(irb);
21952 
21953 			if (ire1 != NULL) {
21954 				next_mp = copyb(mp);
21955 				if ((next_mp == NULL) ||
21956 				    ((mp->b_cont != NULL) &&
21957 				    ((next_mp->b_cont =
21958 				    dupmsg(mp->b_cont)) == NULL))) {
21959 					freemsg(next_mp);
21960 					next_mp = NULL;
21961 					ire_refrele(ire1);
21962 					ire1 = NULL;
21963 				}
21964 			}
21965 
21966 			/* Last multiroute ire; don't loop anymore. */
21967 			if (ire1 == NULL) {
21968 				multirt_send = B_FALSE;
21969 			}
21970 		}
21971 
21972 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
21973 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
21974 		    mblk_t *, mp);
21975 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
21976 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp);
21977 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21978 		if (mp == NULL)
21979 			goto release_ire_and_ill;
21980 
21981 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
21982 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
21983 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
21984 		if ((pktxmit_state == SEND_FAILED) ||
21985 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
21986 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
21987 			    "- packet dropped\n"));
21988 release_ire_and_ill:
21989 			ire_refrele(ire);
21990 			if (next_mp != NULL) {
21991 				freemsg(next_mp);
21992 				ire_refrele(ire1);
21993 			}
21994 			if (conn_outgoing_ill != NULL)
21995 				ill_refrele(conn_outgoing_ill);
21996 			return;
21997 		}
21998 
21999 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22000 		    "ip_wput_ire_end: q %p (%S)",
22001 		    q, "last copy out");
22002 		IRE_REFRELE(ire);
22003 
22004 		if (multirt_send) {
22005 			ASSERT(ire1);
22006 			/*
22007 			 * Proceed with the next RTF_MULTIRT ire,
22008 			 * Also set up the send-to queue accordingly.
22009 			 */
22010 			ire = ire1;
22011 			ire1 = NULL;
22012 			stq = ire->ire_stq;
22013 			mp = next_mp;
22014 			next_mp = NULL;
22015 			ipha = (ipha_t *)mp->b_rptr;
22016 			ill_index = Q_TO_INDEX(stq);
22017 		}
22018 	} while (multirt_send);
22019 	if (conn_outgoing_ill != NULL)
22020 		ill_refrele(conn_outgoing_ill);
22021 	return;
22022 
22023 	/*
22024 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22025 	 */
22026 broadcast:
22027 	{
22028 		/*
22029 		 * Avoid broadcast storms by setting the ttl to 1
22030 		 * for broadcasts. This parameter can be set
22031 		 * via ndd, so make sure that for the SO_DONTROUTE
22032 		 * case that ipha_ttl is always set to 1.
22033 		 * In the event that we are replying to incoming
22034 		 * ICMP packets, conn could be NULL.
22035 		 */
22036 		if ((connp != NULL) && connp->conn_dontroute)
22037 			ipha->ipha_ttl = 1;
22038 		else
22039 			ipha->ipha_ttl = ip_broadcast_ttl;
22040 
22041 		/*
22042 		 * Note that we are not doing a IRB_REFHOLD here.
22043 		 * Actually we don't care if the list changes i.e
22044 		 * if somebody deletes an IRE from the list while
22045 		 * we drop the lock, the next time we come around
22046 		 * ire_next will be NULL and hence we won't send
22047 		 * out multiple copies which is fine.
22048 		 */
22049 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22050 		ire1 = ire->ire_next;
22051 		if (conn_outgoing_ill != NULL) {
22052 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22053 				ASSERT(ire1 == ire->ire_next);
22054 				if (ire1 != NULL && ire1->ire_addr == dst) {
22055 					ire_refrele(ire);
22056 					ire = ire1;
22057 					IRE_REFHOLD(ire);
22058 					ire1 = ire->ire_next;
22059 					continue;
22060 				}
22061 				rw_exit(&ire->ire_bucket->irb_lock);
22062 				/* Did not find a matching ill */
22063 				ip1dbg(("ip_wput_ire: broadcast with no "
22064 				    "matching IP_BOUND_IF ill %s\n",
22065 				    conn_outgoing_ill->ill_name));
22066 				freemsg(first_mp);
22067 				if (ire != NULL)
22068 					ire_refrele(ire);
22069 				ill_refrele(conn_outgoing_ill);
22070 				return;
22071 			}
22072 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22073 			/*
22074 			 * If the next IRE has the same address and is not one
22075 			 * of the two copies that we need to send, try to see
22076 			 * whether this copy should be sent at all. This
22077 			 * assumes that we insert loopbacks first and then
22078 			 * non-loopbacks. This is acheived by inserting the
22079 			 * loopback always before non-loopback.
22080 			 * This is used to send a single copy of a broadcast
22081 			 * packet out all physical interfaces that have an
22082 			 * matching IRE_BROADCAST while also looping
22083 			 * back one copy (to ip_wput_local) for each
22084 			 * matching physical interface. However, we avoid
22085 			 * sending packets out different logical that match by
22086 			 * having ipif_up/ipif_down supress duplicate
22087 			 * IRE_BROADCASTS.
22088 			 *
22089 			 * This feature is currently used to get broadcasts
22090 			 * sent to multiple interfaces, when the broadcast
22091 			 * address being used applies to multiple interfaces.
22092 			 * For example, a whole net broadcast will be
22093 			 * replicated on every connected subnet of
22094 			 * the target net.
22095 			 *
22096 			 * Each zone has its own set of IRE_BROADCASTs, so that
22097 			 * we're able to distribute inbound packets to multiple
22098 			 * zones who share a broadcast address. We avoid looping
22099 			 * back outbound packets in different zones but on the
22100 			 * same ill, as the application would see duplicates.
22101 			 *
22102 			 * If the interfaces are part of the same group,
22103 			 * we would want to send only one copy out for
22104 			 * whole group.
22105 			 *
22106 			 * This logic assumes that ire_add_v4() groups the
22107 			 * IRE_BROADCAST entries so that those with the same
22108 			 * ire_addr and ill_group are kept together.
22109 			 */
22110 			ire_ill = ire->ire_ipif->ipif_ill;
22111 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22112 				if (ire_ill->ill_group != NULL &&
22113 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22114 					/*
22115 					 * If the current zone only has an ire
22116 					 * broadcast for this address marked
22117 					 * NORECV, the ire we want is ahead in
22118 					 * the bucket, so we look it up
22119 					 * deliberately ignoring the zoneid.
22120 					 */
22121 					for (ire1 = ire->ire_bucket->irb_ire;
22122 					    ire1 != NULL;
22123 					    ire1 = ire1->ire_next) {
22124 						ire1_ill =
22125 						    ire1->ire_ipif->ipif_ill;
22126 						if (ire1->ire_addr != dst)
22127 							continue;
22128 						/* skip over the current ire */
22129 						if (ire1 == ire)
22130 							continue;
22131 						/* skip over deleted ires */
22132 						if (ire1->ire_marks &
22133 						    IRE_MARK_CONDEMNED)
22134 							continue;
22135 						/*
22136 						 * non-loopback ire in our
22137 						 * group: use it for the next
22138 						 * pass in the loop
22139 						 */
22140 						if (ire1->ire_stq != NULL &&
22141 						    ire1_ill->ill_group ==
22142 						    ire_ill->ill_group)
22143 							break;
22144 					}
22145 				}
22146 			} else {
22147 				while (ire1 != NULL && ire1->ire_addr == dst) {
22148 					ire1_ill = ire1->ire_ipif->ipif_ill;
22149 					/*
22150 					 * We can have two broadcast ires on the
22151 					 * same ill in different zones; here
22152 					 * we'll send a copy of the packet on
22153 					 * each ill and the fanout code will
22154 					 * call conn_wantpacket() to check that
22155 					 * the zone has the broadcast address
22156 					 * configured on the ill. If the two
22157 					 * ires are in the same group we only
22158 					 * send one copy up.
22159 					 */
22160 					if (ire1_ill != ire_ill &&
22161 					    (ire1_ill->ill_group == NULL ||
22162 					    ire_ill->ill_group == NULL ||
22163 					    ire1_ill->ill_group !=
22164 					    ire_ill->ill_group)) {
22165 						break;
22166 					}
22167 					ire1 = ire1->ire_next;
22168 				}
22169 			}
22170 		}
22171 		ASSERT(multirt_send == B_FALSE);
22172 		if (ire1 != NULL && ire1->ire_addr == dst) {
22173 			if ((ire->ire_flags & RTF_MULTIRT) &&
22174 			    (ire1->ire_flags & RTF_MULTIRT)) {
22175 				/*
22176 				 * We are in the multirouting case.
22177 				 * The message must be sent at least
22178 				 * on both ires. These ires have been
22179 				 * inserted AFTER the standard ones
22180 				 * in ip_rt_add(). There are thus no
22181 				 * other ire entries for the destination
22182 				 * address in the rest of the bucket
22183 				 * that do not have the RTF_MULTIRT
22184 				 * flag. We don't process a copy
22185 				 * of the message here. This will be
22186 				 * done in the final sending loop.
22187 				 */
22188 				multirt_send = B_TRUE;
22189 			} else {
22190 				next_mp = ip_copymsg(first_mp);
22191 				if (next_mp != NULL)
22192 					IRE_REFHOLD(ire1);
22193 			}
22194 		}
22195 		rw_exit(&ire->ire_bucket->irb_lock);
22196 	}
22197 
22198 	if (stq) {
22199 		/*
22200 		 * A non-NULL send-to queue means this packet is going
22201 		 * out of this machine.
22202 		 */
22203 
22204 		BUMP_MIB(&ip_mib, ipOutRequests);
22205 		ttl_protocol = ((uint16_t *)ipha)[4];
22206 		/*
22207 		 * We accumulate the pseudo header checksum in cksum.
22208 		 * This is pretty hairy code, so watch close.  One
22209 		 * thing to keep in mind is that UDP and TCP have
22210 		 * stored their respective datagram lengths in their
22211 		 * checksum fields.  This lines things up real nice.
22212 		 */
22213 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22214 		    (src >> 16) + (src & 0xFFFF);
22215 		/*
22216 		 * We assume the udp checksum field contains the
22217 		 * length, so to compute the pseudo header checksum,
22218 		 * all we need is the protocol number and src/dst.
22219 		 */
22220 		/* Provide the checksums for UDP and TCP. */
22221 		if ((PROTO == IPPROTO_TCP) &&
22222 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22223 			/* hlen gets the number of uchar_ts in the IP header */
22224 			hlen = (V_HLEN & 0xF) << 2;
22225 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22226 			IP_STAT(ip_out_sw_cksum);
22227 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22228 			    LENGTH - hlen);
22229 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22230 			if (*up == 0)
22231 				*up = 0xFFFF;
22232 		} else if (PROTO == IPPROTO_SCTP &&
22233 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22234 			sctp_hdr_t	*sctph;
22235 
22236 			hlen = (V_HLEN & 0xF) << 2;
22237 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22238 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22239 			sctph->sh_chksum = 0;
22240 #ifdef	DEBUG
22241 			if (!skip_sctp_cksum)
22242 #endif
22243 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22244 		} else {
22245 			queue_t *dev_q = stq->q_next;
22246 
22247 			if ((dev_q->q_next || dev_q->q_first) &&
22248 			    !canput(dev_q)) {
22249 			    blocked:
22250 				ipha->ipha_ident = ip_hdr_included;
22251 				/*
22252 				 * If we don't have a conn to apply
22253 				 * backpressure, free the message.
22254 				 * In the ire_send path, we don't know
22255 				 * the position to requeue the packet. Rather
22256 				 * than reorder packets, we just drop this
22257 				 * packet.
22258 				 */
22259 				if (ip_output_queue && connp != NULL &&
22260 				    caller != IRE_SEND) {
22261 					if (caller == IP_WSRV) {
22262 						connp->conn_did_putbq = 1;
22263 						(void) putbq(connp->conn_wq,
22264 						    first_mp);
22265 						conn_drain_insert(connp);
22266 						/*
22267 						 * This is the service thread,
22268 						 * and the queue is already
22269 						 * noenabled. The check for
22270 						 * canput and the putbq is not
22271 						 * atomic. So we need to check
22272 						 * again.
22273 						 */
22274 						if (canput(stq->q_next))
22275 							connp->conn_did_putbq
22276 							    = 0;
22277 						IP_STAT(ip_conn_flputbq);
22278 					} else {
22279 						/*
22280 						 * We are not the service proc.
22281 						 * ip_wsrv will be scheduled or
22282 						 * is already running.
22283 						 */
22284 						(void) putq(connp->conn_wq,
22285 						    first_mp);
22286 					}
22287 				} else {
22288 					BUMP_MIB(&ip_mib, ipOutDiscards);
22289 					freemsg(first_mp);
22290 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22291 					    "ip_wput_ire_end: q %p (%S)",
22292 					    q, "discard");
22293 				}
22294 				ire_refrele(ire);
22295 				if (next_mp) {
22296 					ire_refrele(ire1);
22297 					freemsg(next_mp);
22298 				}
22299 				if (conn_outgoing_ill != NULL)
22300 					ill_refrele(conn_outgoing_ill);
22301 				return;
22302 			}
22303 			if ((PROTO == IPPROTO_UDP) &&
22304 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22305 				/*
22306 				 * hlen gets the number of uchar_ts in the
22307 				 * IP header
22308 				 */
22309 				hlen = (V_HLEN & 0xF) << 2;
22310 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22311 				max_frag = ire->ire_max_frag;
22312 				if (*up != 0) {
22313 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22314 					    up, PROTO, hlen, LENGTH, max_frag,
22315 					    ipsec_len, cksum);
22316 					/* Software checksum? */
22317 					if (DB_CKSUMFLAGS(mp) == 0) {
22318 						IP_STAT(ip_out_sw_cksum);
22319 						IP_STAT_UPDATE(
22320 						    ip_udp_out_sw_cksum_bytes,
22321 						    LENGTH - hlen);
22322 					}
22323 				}
22324 			}
22325 		}
22326 		/*
22327 		 * Need to do this even when fragmenting. The local
22328 		 * loopback can be done without computing checksums
22329 		 * but forwarding out other interface must be done
22330 		 * after the IP checksum (and ULP checksums) have been
22331 		 * computed.
22332 		 *
22333 		 * NOTE : multicast_forward is set only if this packet
22334 		 * originated from ip_wput. For packets originating from
22335 		 * ip_wput_multicast, it is not set.
22336 		 */
22337 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22338 		    multi_loopback:
22339 			ip2dbg(("ip_wput: multicast, loop %d\n",
22340 			    conn_multicast_loop));
22341 
22342 			/*  Forget header checksum offload */
22343 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22344 
22345 			/*
22346 			 * Local loopback of multicasts?  Check the
22347 			 * ill.
22348 			 *
22349 			 * Note that the loopback function will not come
22350 			 * in through ip_rput - it will only do the
22351 			 * client fanout thus we need to do an mforward
22352 			 * as well.  The is different from the BSD
22353 			 * logic.
22354 			 */
22355 			if (ill != NULL) {
22356 				ilm_t	*ilm;
22357 
22358 				ILM_WALKER_HOLD(ill);
22359 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22360 				    ALL_ZONES);
22361 				ILM_WALKER_RELE(ill);
22362 				if (ilm != NULL) {
22363 					/*
22364 					 * Pass along the virtual output q.
22365 					 * ip_wput_local() will distribute the
22366 					 * packet to all the matching zones,
22367 					 * except the sending zone when
22368 					 * IP_MULTICAST_LOOP is false.
22369 					 */
22370 					ip_multicast_loopback(q, ill, first_mp,
22371 					    conn_multicast_loop ? 0 :
22372 					    IP_FF_NO_MCAST_LOOP, zoneid);
22373 				}
22374 			}
22375 			if (ipha->ipha_ttl == 0) {
22376 				/*
22377 				 * 0 => only to this host i.e. we are
22378 				 * done. We are also done if this was the
22379 				 * loopback interface since it is sufficient
22380 				 * to loopback one copy of a multicast packet.
22381 				 */
22382 				freemsg(first_mp);
22383 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22384 				    "ip_wput_ire_end: q %p (%S)",
22385 				    q, "loopback");
22386 				ire_refrele(ire);
22387 				if (conn_outgoing_ill != NULL)
22388 					ill_refrele(conn_outgoing_ill);
22389 				return;
22390 			}
22391 			/*
22392 			 * ILLF_MULTICAST is checked in ip_newroute
22393 			 * i.e. we don't need to check it here since
22394 			 * all IRE_CACHEs come from ip_newroute.
22395 			 * For multicast traffic, SO_DONTROUTE is interpreted
22396 			 * to mean only send the packet out the interface
22397 			 * (optionally specified with IP_MULTICAST_IF)
22398 			 * and do not forward it out additional interfaces.
22399 			 * RSVP and the rsvp daemon is an example of a
22400 			 * protocol and user level process that
22401 			 * handles it's own routing. Hence, it uses the
22402 			 * SO_DONTROUTE option to accomplish this.
22403 			 */
22404 
22405 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22406 				/* Unconditionally redo the checksum */
22407 				ipha->ipha_hdr_checksum = 0;
22408 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22409 
22410 				/*
22411 				 * If this needs to go out secure, we need
22412 				 * to wait till we finish the IPSEC
22413 				 * processing.
22414 				 */
22415 				if (ipsec_len == 0 &&
22416 				    ip_mforward(ill, ipha, mp)) {
22417 					freemsg(first_mp);
22418 					ip1dbg(("ip_wput: mforward failed\n"));
22419 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22420 					    "ip_wput_ire_end: q %p (%S)",
22421 					    q, "mforward failed");
22422 					ire_refrele(ire);
22423 					if (conn_outgoing_ill != NULL)
22424 						ill_refrele(conn_outgoing_ill);
22425 					return;
22426 				}
22427 			}
22428 		}
22429 		max_frag = ire->ire_max_frag;
22430 		cksum += ttl_protocol;
22431 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22432 			/* No fragmentation required for this one. */
22433 			/*
22434 			 * Don't use frag_flag if packet is pre-built or source
22435 			 * routed or if multicast (since multicast packets do
22436 			 * not solicit ICMP "packet too big" messages).
22437 			 */
22438 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22439 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22440 			    !ip_source_route_included(ipha)) &&
22441 			    !CLASSD(ipha->ipha_dst))
22442 				ipha->ipha_fragment_offset_and_flags |=
22443 				    htons(ire->ire_frag_flag);
22444 
22445 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22446 				/* Complete the IP header checksum. */
22447 				cksum += ipha->ipha_ident;
22448 				cksum += (v_hlen_tos_len >> 16)+
22449 				    (v_hlen_tos_len & 0xFFFF);
22450 				cksum += ipha->ipha_fragment_offset_and_flags;
22451 				hlen = (V_HLEN & 0xF) -
22452 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22453 				if (hlen) {
22454 				    checksumoptions:
22455 					/*
22456 					 * Account for the IP Options in the IP
22457 					 * header checksum.
22458 					 */
22459 					up = (uint16_t *)(rptr+
22460 					    IP_SIMPLE_HDR_LENGTH);
22461 					do {
22462 						cksum += up[0];
22463 						cksum += up[1];
22464 						up += 2;
22465 					} while (--hlen);
22466 				}
22467 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22468 				cksum = ~(cksum + (cksum >> 16));
22469 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22470 			}
22471 			if (ipsec_len != 0) {
22472 				ipsec_out_process(q, first_mp, ire, ill_index);
22473 				if (!next_mp) {
22474 					ire_refrele(ire);
22475 					if (conn_outgoing_ill != NULL)
22476 						ill_refrele(conn_outgoing_ill);
22477 					return;
22478 				}
22479 				goto next;
22480 			}
22481 
22482 			/*
22483 			 * multirt_send has already been handled
22484 			 * for broadcast, but not yet for multicast
22485 			 * or IP options.
22486 			 */
22487 			if (next_mp == NULL) {
22488 				if (ire->ire_flags & RTF_MULTIRT) {
22489 					multirt_send = B_TRUE;
22490 				}
22491 			}
22492 
22493 			/*
22494 			 * In most cases, the emission loop below is
22495 			 * entered only once. Only in the case where
22496 			 * the ire holds the RTF_MULTIRT flag, do we loop
22497 			 * to process all RTF_MULTIRT ires in the bucket,
22498 			 * and send the packet through all crossed
22499 			 * RTF_MULTIRT routes.
22500 			 */
22501 			do {
22502 				if (multirt_send) {
22503 					irb_t *irb;
22504 
22505 					irb = ire->ire_bucket;
22506 					ASSERT(irb != NULL);
22507 					/*
22508 					 * We are in a multiple send case,
22509 					 * need to get the next IRE and make
22510 					 * a duplicate of the packet.
22511 					 */
22512 					IRB_REFHOLD(irb);
22513 					for (ire1 = ire->ire_next;
22514 					    ire1 != NULL;
22515 					    ire1 = ire1->ire_next) {
22516 						if (!(ire1->ire_flags &
22517 						    RTF_MULTIRT))
22518 							continue;
22519 						if (ire1->ire_addr !=
22520 						    ire->ire_addr)
22521 							continue;
22522 						if (ire1->ire_marks &
22523 						    (IRE_MARK_CONDEMNED|
22524 							IRE_MARK_HIDDEN))
22525 							continue;
22526 
22527 						/* Got one */
22528 						IRE_REFHOLD(ire1);
22529 						break;
22530 					}
22531 					IRB_REFRELE(irb);
22532 
22533 					if (ire1 != NULL) {
22534 						next_mp = copyb(mp);
22535 						if ((next_mp == NULL) ||
22536 						    ((mp->b_cont != NULL) &&
22537 						    ((next_mp->b_cont =
22538 						    dupmsg(mp->b_cont))
22539 						    == NULL))) {
22540 							freemsg(next_mp);
22541 							next_mp = NULL;
22542 							ire_refrele(ire1);
22543 							ire1 = NULL;
22544 						}
22545 					}
22546 
22547 					/*
22548 					 * Last multiroute ire; don't loop
22549 					 * anymore. The emission is over
22550 					 * and next_mp is NULL.
22551 					 */
22552 					if (ire1 == NULL) {
22553 						multirt_send = B_FALSE;
22554 					}
22555 				}
22556 
22557 				out_ill = ire->ire_ipif->ipif_ill;
22558 				DTRACE_PROBE4(ip4__physical__out__start,
22559 				    ill_t *, NULL,
22560 				    ill_t *, out_ill,
22561 				    ipha_t *, ipha, mblk_t *, mp);
22562 				FW_HOOKS(ip4_physical_out_event,
22563 				    ipv4firewall_physical_out,
22564 				    NULL, out_ill, ipha, mp, mp);
22565 				DTRACE_PROBE1(ip4__physical__out__end,
22566 				    mblk_t *, mp);
22567 				if (mp == NULL)
22568 					goto release_ire_and_ill_2;
22569 
22570 				ASSERT(ipsec_len == 0);
22571 				mp->b_prev =
22572 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22573 				DTRACE_PROBE2(ip__xmit__2,
22574 				    mblk_t *, mp, ire_t *, ire);
22575 				pktxmit_state = ip_xmit_v4(mp, ire,
22576 				    NULL, B_TRUE);
22577 				if ((pktxmit_state == SEND_FAILED) ||
22578 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22579 release_ire_and_ill_2:
22580 					if (next_mp) {
22581 						freemsg(next_mp);
22582 						ire_refrele(ire1);
22583 					}
22584 					ire_refrele(ire);
22585 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22586 					    "ip_wput_ire_end: q %p (%S)",
22587 					    q, "discard MDATA");
22588 					if (conn_outgoing_ill != NULL)
22589 						ill_refrele(conn_outgoing_ill);
22590 					return;
22591 				}
22592 
22593 				if (multirt_send) {
22594 					/*
22595 					 * We are in a multiple send case,
22596 					 * need to re-enter the sending loop
22597 					 * using the next ire.
22598 					 */
22599 					ire_refrele(ire);
22600 					ire = ire1;
22601 					stq = ire->ire_stq;
22602 					mp = next_mp;
22603 					next_mp = NULL;
22604 					ipha = (ipha_t *)mp->b_rptr;
22605 					ill_index = Q_TO_INDEX(stq);
22606 				}
22607 			} while (multirt_send);
22608 
22609 			if (!next_mp) {
22610 				/*
22611 				 * Last copy going out (the ultra-common
22612 				 * case).  Note that we intentionally replicate
22613 				 * the putnext rather than calling it before
22614 				 * the next_mp check in hopes of a little
22615 				 * tail-call action out of the compiler.
22616 				 */
22617 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22618 				    "ip_wput_ire_end: q %p (%S)",
22619 				    q, "last copy out(1)");
22620 				ire_refrele(ire);
22621 				if (conn_outgoing_ill != NULL)
22622 					ill_refrele(conn_outgoing_ill);
22623 				return;
22624 			}
22625 			/* More copies going out below. */
22626 		} else {
22627 			int offset;
22628 		    fragmentit:
22629 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22630 			/*
22631 			 * If this would generate a icmp_frag_needed message,
22632 			 * we need to handle it before we do the IPSEC
22633 			 * processing. Otherwise, we need to strip the IPSEC
22634 			 * headers before we send up the message to the ULPs
22635 			 * which becomes messy and difficult.
22636 			 */
22637 			if (ipsec_len != 0) {
22638 				if ((max_frag < (unsigned int)(LENGTH +
22639 				    ipsec_len)) && (offset & IPH_DF)) {
22640 
22641 					BUMP_MIB(&ip_mib, ipFragFails);
22642 					ipha->ipha_hdr_checksum = 0;
22643 					ipha->ipha_hdr_checksum =
22644 					    (uint16_t)ip_csum_hdr(ipha);
22645 					icmp_frag_needed(ire->ire_stq, first_mp,
22646 					    max_frag, zoneid);
22647 					if (!next_mp) {
22648 						ire_refrele(ire);
22649 						if (conn_outgoing_ill != NULL) {
22650 							ill_refrele(
22651 							    conn_outgoing_ill);
22652 						}
22653 						return;
22654 					}
22655 				} else {
22656 					/*
22657 					 * This won't cause a icmp_frag_needed
22658 					 * message. to be gnerated. Send it on
22659 					 * the wire. Note that this could still
22660 					 * cause fragmentation and all we
22661 					 * do is the generation of the message
22662 					 * to the ULP if needed before IPSEC.
22663 					 */
22664 					if (!next_mp) {
22665 						ipsec_out_process(q, first_mp,
22666 						    ire, ill_index);
22667 						TRACE_2(TR_FAC_IP,
22668 						    TR_IP_WPUT_IRE_END,
22669 						    "ip_wput_ire_end: q %p "
22670 						    "(%S)", q,
22671 						    "last ipsec_out_process");
22672 						ire_refrele(ire);
22673 						if (conn_outgoing_ill != NULL) {
22674 							ill_refrele(
22675 							    conn_outgoing_ill);
22676 						}
22677 						return;
22678 					}
22679 					ipsec_out_process(q, first_mp,
22680 					    ire, ill_index);
22681 				}
22682 			} else {
22683 				/*
22684 				 * Initiate IPPF processing. For
22685 				 * fragmentable packets we finish
22686 				 * all QOS packet processing before
22687 				 * calling:
22688 				 * ip_wput_ire_fragmentit->ip_wput_frag
22689 				 */
22690 
22691 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22692 					ip_process(IPP_LOCAL_OUT, &mp,
22693 					    ill_index);
22694 					if (mp == NULL) {
22695 						BUMP_MIB(&ip_mib,
22696 						    ipOutDiscards);
22697 						if (next_mp != NULL) {
22698 							freemsg(next_mp);
22699 							ire_refrele(ire1);
22700 						}
22701 						ire_refrele(ire);
22702 						TRACE_2(TR_FAC_IP,
22703 						    TR_IP_WPUT_IRE_END,
22704 						    "ip_wput_ire: q %p (%S)",
22705 						    q, "discard MDATA");
22706 						if (conn_outgoing_ill != NULL) {
22707 							ill_refrele(
22708 							    conn_outgoing_ill);
22709 						}
22710 						return;
22711 					}
22712 				}
22713 				if (!next_mp) {
22714 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22715 					    "ip_wput_ire_end: q %p (%S)",
22716 					    q, "last fragmentation");
22717 					ip_wput_ire_fragmentit(mp, ire,
22718 					    zoneid);
22719 					ire_refrele(ire);
22720 					if (conn_outgoing_ill != NULL)
22721 						ill_refrele(conn_outgoing_ill);
22722 					return;
22723 				}
22724 				ip_wput_ire_fragmentit(mp, ire, zoneid);
22725 			}
22726 		}
22727 	} else {
22728 	    nullstq:
22729 		/* A NULL stq means the destination address is local. */
22730 		UPDATE_OB_PKT_COUNT(ire);
22731 		ire->ire_last_used_time = lbolt;
22732 		ASSERT(ire->ire_ipif != NULL);
22733 		if (!next_mp) {
22734 			/*
22735 			 * Is there an "in" and "out" for traffic local
22736 			 * to a host (loopback)?  The code in Solaris doesn't
22737 			 * explicitly draw a line in its code for in vs out,
22738 			 * so we've had to draw a line in the sand: ip_wput_ire
22739 			 * is considered to be the "output" side and
22740 			 * ip_wput_local to be the "input" side.
22741 			 */
22742 			out_ill = ire->ire_ipif->ipif_ill;
22743 
22744 			DTRACE_PROBE4(ip4__loopback__out__start,
22745 			    ill_t *, NULL, ill_t *, out_ill,
22746 			    ipha_t *, ipha, mblk_t *, first_mp);
22747 
22748 			FW_HOOKS(ip4_loopback_out_event,
22749 			    ipv4firewall_loopback_out,
22750 			    NULL, out_ill, ipha, first_mp, mp);
22751 
22752 			DTRACE_PROBE1(ip4__loopback__out_end,
22753 			    mblk_t *, first_mp);
22754 
22755 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22756 			    "ip_wput_ire_end: q %p (%S)",
22757 			    q, "local address");
22758 
22759 			if (first_mp != NULL)
22760 				ip_wput_local(q, out_ill, ipha,
22761 				    first_mp, ire, 0, ire->ire_zoneid);
22762 			ire_refrele(ire);
22763 			if (conn_outgoing_ill != NULL)
22764 				ill_refrele(conn_outgoing_ill);
22765 			return;
22766 		}
22767 
22768 		out_ill = ire->ire_ipif->ipif_ill;
22769 
22770 		DTRACE_PROBE4(ip4__loopback__out__start,
22771 		    ill_t *, NULL, ill_t *, out_ill,
22772 		    ipha_t *, ipha, mblk_t *, first_mp);
22773 
22774 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
22775 		    NULL, out_ill, ipha, first_mp, mp);
22776 
22777 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
22778 
22779 		if (first_mp != NULL)
22780 			ip_wput_local(q, out_ill, ipha,
22781 			    first_mp, ire, 0, ire->ire_zoneid);
22782 	}
22783 next:
22784 	/*
22785 	 * More copies going out to additional interfaces.
22786 	 * ire1 has already been held. We don't need the
22787 	 * "ire" anymore.
22788 	 */
22789 	ire_refrele(ire);
22790 	ire = ire1;
22791 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
22792 	mp = next_mp;
22793 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
22794 	ill = ire_to_ill(ire);
22795 	first_mp = mp;
22796 	if (ipsec_len != 0) {
22797 		ASSERT(first_mp->b_datap->db_type == M_CTL);
22798 		mp = mp->b_cont;
22799 	}
22800 	dst = ire->ire_addr;
22801 	ipha = (ipha_t *)mp->b_rptr;
22802 	/*
22803 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
22804 	 * Restore ipha_ident "no checksum" flag.
22805 	 */
22806 	src = orig_src;
22807 	ipha->ipha_ident = ip_hdr_included;
22808 	goto another;
22809 
22810 #undef	rptr
22811 #undef	Q_TO_INDEX
22812 }
22813 
22814 /*
22815  * Routine to allocate a message that is used to notify the ULP about MDT.
22816  * The caller may provide a pointer to the link-layer MDT capabilities,
22817  * or NULL if MDT is to be disabled on the stream.
22818  */
22819 mblk_t *
22820 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
22821 {
22822 	mblk_t *mp;
22823 	ip_mdt_info_t *mdti;
22824 	ill_mdt_capab_t *idst;
22825 
22826 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
22827 		DB_TYPE(mp) = M_CTL;
22828 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
22829 		mdti = (ip_mdt_info_t *)mp->b_rptr;
22830 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
22831 		idst = &(mdti->mdt_capab);
22832 
22833 		/*
22834 		 * If the caller provides us with the capability, copy
22835 		 * it over into our notification message; otherwise
22836 		 * we zero out the capability portion.
22837 		 */
22838 		if (isrc != NULL)
22839 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22840 		else
22841 			bzero((caddr_t)idst, sizeof (*idst));
22842 	}
22843 	return (mp);
22844 }
22845 
22846 /*
22847  * Routine which determines whether MDT can be enabled on the destination
22848  * IRE and IPC combination, and if so, allocates and returns the MDT
22849  * notification mblk that may be used by ULP.  We also check if we need to
22850  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
22851  * MDT usage in the past have been lifted.  This gets called during IP
22852  * and ULP binding.
22853  */
22854 mblk_t *
22855 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22856     ill_mdt_capab_t *mdt_cap)
22857 {
22858 	mblk_t *mp;
22859 	boolean_t rc = B_FALSE;
22860 
22861 	ASSERT(dst_ire != NULL);
22862 	ASSERT(connp != NULL);
22863 	ASSERT(mdt_cap != NULL);
22864 
22865 	/*
22866 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
22867 	 * Multidata, which is handled in tcp_multisend().  This
22868 	 * is the reason why we do all these checks here, to ensure
22869 	 * that we don't enable Multidata for the cases which we
22870 	 * can't handle at the moment.
22871 	 */
22872 	do {
22873 		/* Only do TCP at the moment */
22874 		if (connp->conn_ulp != IPPROTO_TCP)
22875 			break;
22876 
22877 		/*
22878 		 * IPSEC outbound policy present?  Note that we get here
22879 		 * after calling ipsec_conn_cache_policy() where the global
22880 		 * policy checking is performed.  conn_latch will be
22881 		 * non-NULL as long as there's a policy defined,
22882 		 * i.e. conn_out_enforce_policy may be NULL in such case
22883 		 * when the connection is non-secure, and hence we check
22884 		 * further if the latch refers to an outbound policy.
22885 		 */
22886 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
22887 			break;
22888 
22889 		/* CGTP (multiroute) is enabled? */
22890 		if (dst_ire->ire_flags & RTF_MULTIRT)
22891 			break;
22892 
22893 		/* Outbound IPQoS enabled? */
22894 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22895 			/*
22896 			 * In this case, we disable MDT for this and all
22897 			 * future connections going over the interface.
22898 			 */
22899 			mdt_cap->ill_mdt_on = 0;
22900 			break;
22901 		}
22902 
22903 		/* socket option(s) present? */
22904 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
22905 			break;
22906 
22907 		rc = B_TRUE;
22908 	/* CONSTCOND */
22909 	} while (0);
22910 
22911 	/* Remember the result */
22912 	connp->conn_mdt_ok = rc;
22913 
22914 	if (!rc)
22915 		return (NULL);
22916 	else if (!mdt_cap->ill_mdt_on) {
22917 		/*
22918 		 * If MDT has been previously turned off in the past, and we
22919 		 * currently can do MDT (due to IPQoS policy removal, etc.)
22920 		 * then enable it for this interface.
22921 		 */
22922 		mdt_cap->ill_mdt_on = 1;
22923 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
22924 		    "interface %s\n", ill_name));
22925 	}
22926 
22927 	/* Allocate the MDT info mblk */
22928 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
22929 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
22930 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
22931 		return (NULL);
22932 	}
22933 	return (mp);
22934 }
22935 
22936 /*
22937  * Routine to allocate a message that is used to notify the ULP about LSO.
22938  * The caller may provide a pointer to the link-layer LSO capabilities,
22939  * or NULL if LSO is to be disabled on the stream.
22940  */
22941 mblk_t *
22942 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
22943 {
22944 	mblk_t *mp;
22945 	ip_lso_info_t *lsoi;
22946 	ill_lso_capab_t *idst;
22947 
22948 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
22949 		DB_TYPE(mp) = M_CTL;
22950 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
22951 		lsoi = (ip_lso_info_t *)mp->b_rptr;
22952 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
22953 		idst = &(lsoi->lso_capab);
22954 
22955 		/*
22956 		 * If the caller provides us with the capability, copy
22957 		 * it over into our notification message; otherwise
22958 		 * we zero out the capability portion.
22959 		 */
22960 		if (isrc != NULL)
22961 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22962 		else
22963 			bzero((caddr_t)idst, sizeof (*idst));
22964 	}
22965 	return (mp);
22966 }
22967 
22968 /*
22969  * Routine which determines whether LSO can be enabled on the destination
22970  * IRE and IPC combination, and if so, allocates and returns the LSO
22971  * notification mblk that may be used by ULP.  We also check if we need to
22972  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
22973  * LSO usage in the past have been lifted.  This gets called during IP
22974  * and ULP binding.
22975  */
22976 mblk_t *
22977 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22978     ill_lso_capab_t *lso_cap)
22979 {
22980 	mblk_t *mp;
22981 
22982 	ASSERT(dst_ire != NULL);
22983 	ASSERT(connp != NULL);
22984 	ASSERT(lso_cap != NULL);
22985 
22986 	connp->conn_lso_ok = B_TRUE;
22987 
22988 	if ((connp->conn_ulp != IPPROTO_TCP) ||
22989 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
22990 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
22991 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
22992 	    (IPP_ENABLED(IPP_LOCAL_OUT))) {
22993 		connp->conn_lso_ok = B_FALSE;
22994 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22995 			/*
22996 			 * Disable LSO for this and all future connections going
22997 			 * over the interface.
22998 			 */
22999 			lso_cap->ill_lso_on = 0;
23000 		}
23001 	}
23002 
23003 	if (!connp->conn_lso_ok)
23004 		return (NULL);
23005 	else if (!lso_cap->ill_lso_on) {
23006 		/*
23007 		 * If LSO has been previously turned off in the past, and we
23008 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23009 		 * then enable it for this interface.
23010 		 */
23011 		lso_cap->ill_lso_on = 1;
23012 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23013 		    ill_name));
23014 	}
23015 
23016 	/* Allocate the LSO info mblk */
23017 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23018 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23019 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23020 
23021 	return (mp);
23022 }
23023 
23024 /*
23025  * Create destination address attribute, and fill it with the physical
23026  * destination address and SAP taken from the template DL_UNITDATA_REQ
23027  * message block.
23028  */
23029 boolean_t
23030 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23031 {
23032 	dl_unitdata_req_t *dlurp;
23033 	pattr_t *pa;
23034 	pattrinfo_t pa_info;
23035 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23036 	uint_t das_len, das_off;
23037 
23038 	ASSERT(dlmp != NULL);
23039 
23040 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23041 	das_len = dlurp->dl_dest_addr_length;
23042 	das_off = dlurp->dl_dest_addr_offset;
23043 
23044 	pa_info.type = PATTR_DSTADDRSAP;
23045 	pa_info.len = sizeof (**das) + das_len - 1;
23046 
23047 	/* create and associate the attribute */
23048 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23049 	if (pa != NULL) {
23050 		ASSERT(*das != NULL);
23051 		(*das)->addr_is_group = 0;
23052 		(*das)->addr_len = (uint8_t)das_len;
23053 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23054 	}
23055 
23056 	return (pa != NULL);
23057 }
23058 
23059 /*
23060  * Create hardware checksum attribute and fill it with the values passed.
23061  */
23062 boolean_t
23063 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23064     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23065 {
23066 	pattr_t *pa;
23067 	pattrinfo_t pa_info;
23068 
23069 	ASSERT(mmd != NULL);
23070 
23071 	pa_info.type = PATTR_HCKSUM;
23072 	pa_info.len = sizeof (pattr_hcksum_t);
23073 
23074 	/* create and associate the attribute */
23075 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23076 	if (pa != NULL) {
23077 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23078 
23079 		hck->hcksum_start_offset = start_offset;
23080 		hck->hcksum_stuff_offset = stuff_offset;
23081 		hck->hcksum_end_offset = end_offset;
23082 		hck->hcksum_flags = flags;
23083 	}
23084 	return (pa != NULL);
23085 }
23086 
23087 /*
23088  * Create zerocopy attribute and fill it with the specified flags
23089  */
23090 boolean_t
23091 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23092 {
23093 	pattr_t *pa;
23094 	pattrinfo_t pa_info;
23095 
23096 	ASSERT(mmd != NULL);
23097 	pa_info.type = PATTR_ZCOPY;
23098 	pa_info.len = sizeof (pattr_zcopy_t);
23099 
23100 	/* create and associate the attribute */
23101 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23102 	if (pa != NULL) {
23103 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23104 
23105 		zcopy->zcopy_flags = flags;
23106 	}
23107 	return (pa != NULL);
23108 }
23109 
23110 /*
23111  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23112  * block chain. We could rewrite to handle arbitrary message block chains but
23113  * that would make the code complicated and slow. Right now there three
23114  * restrictions:
23115  *
23116  *   1. The first message block must contain the complete IP header and
23117  *	at least 1 byte of payload data.
23118  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23119  *	so that we can use a single Multidata message.
23120  *   3. No frag must be distributed over two or more message blocks so
23121  *	that we don't need more than two packet descriptors per frag.
23122  *
23123  * The above restrictions allow us to support userland applications (which
23124  * will send down a single message block) and NFS over UDP (which will
23125  * send down a chain of at most three message blocks).
23126  *
23127  * We also don't use MDT for payloads with less than or equal to
23128  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23129  */
23130 boolean_t
23131 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23132 {
23133 	int	blocks;
23134 	ssize_t	total, missing, size;
23135 
23136 	ASSERT(mp != NULL);
23137 	ASSERT(hdr_len > 0);
23138 
23139 	size = MBLKL(mp) - hdr_len;
23140 	if (size <= 0)
23141 		return (B_FALSE);
23142 
23143 	/* The first mblk contains the header and some payload. */
23144 	blocks = 1;
23145 	total = size;
23146 	size %= len;
23147 	missing = (size == 0) ? 0 : (len - size);
23148 	mp = mp->b_cont;
23149 
23150 	while (mp != NULL) {
23151 		/*
23152 		 * Give up if we encounter a zero length message block.
23153 		 * In practice, this should rarely happen and therefore
23154 		 * not worth the trouble of freeing and re-linking the
23155 		 * mblk from the chain to handle such case.
23156 		 */
23157 		if ((size = MBLKL(mp)) == 0)
23158 			return (B_FALSE);
23159 
23160 		/* Too many payload buffers for a single Multidata message? */
23161 		if (++blocks > MULTIDATA_MAX_PBUFS)
23162 			return (B_FALSE);
23163 
23164 		total += size;
23165 		/* Is a frag distributed over two or more message blocks? */
23166 		if (missing > size)
23167 			return (B_FALSE);
23168 		size -= missing;
23169 
23170 		size %= len;
23171 		missing = (size == 0) ? 0 : (len - size);
23172 
23173 		mp = mp->b_cont;
23174 	}
23175 
23176 	return (total > ip_wput_frag_mdt_min);
23177 }
23178 
23179 /*
23180  * Outbound IPv4 fragmentation routine using MDT.
23181  */
23182 static void
23183 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23184     uint32_t frag_flag, int offset)
23185 {
23186 	ipha_t		*ipha_orig;
23187 	int		i1, ip_data_end;
23188 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23189 	mblk_t		*hdr_mp, *md_mp = NULL;
23190 	unsigned char	*hdr_ptr, *pld_ptr;
23191 	multidata_t	*mmd;
23192 	ip_pdescinfo_t	pdi;
23193 
23194 	ASSERT(DB_TYPE(mp) == M_DATA);
23195 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23196 
23197 	ipha_orig = (ipha_t *)mp->b_rptr;
23198 	mp->b_rptr += sizeof (ipha_t);
23199 
23200 	/* Calculate how many packets we will send out */
23201 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23202 	pkts = (i1 + len - 1) / len;
23203 	ASSERT(pkts > 1);
23204 
23205 	/* Allocate a message block which will hold all the IP Headers. */
23206 	wroff = ip_wroff_extra;
23207 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23208 
23209 	i1 = pkts * hdr_chunk_len;
23210 	/*
23211 	 * Create the header buffer, Multidata and destination address
23212 	 * and SAP attribute that should be associated with it.
23213 	 */
23214 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23215 	    ((hdr_mp->b_wptr += i1),
23216 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23217 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23218 		freemsg(mp);
23219 		if (md_mp == NULL) {
23220 			freemsg(hdr_mp);
23221 		} else {
23222 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
23223 			freemsg(md_mp);
23224 		}
23225 		IP_STAT(ip_frag_mdt_allocfail);
23226 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
23227 		return;
23228 	}
23229 	IP_STAT(ip_frag_mdt_allocd);
23230 
23231 	/*
23232 	 * Add a payload buffer to the Multidata; this operation must not
23233 	 * fail, or otherwise our logic in this routine is broken.  There
23234 	 * is no memory allocation done by the routine, so any returned
23235 	 * failure simply tells us that we've done something wrong.
23236 	 *
23237 	 * A failure tells us that either we're adding the same payload
23238 	 * buffer more than once, or we're trying to add more buffers than
23239 	 * allowed.  None of the above cases should happen, and we panic
23240 	 * because either there's horrible heap corruption, and/or
23241 	 * programming mistake.
23242 	 */
23243 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23244 		goto pbuf_panic;
23245 
23246 	hdr_ptr = hdr_mp->b_rptr;
23247 	pld_ptr = mp->b_rptr;
23248 
23249 	/* Establish the ending byte offset, based on the starting offset. */
23250 	offset <<= 3;
23251 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23252 	    IP_SIMPLE_HDR_LENGTH;
23253 
23254 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23255 
23256 	while (pld_ptr < mp->b_wptr) {
23257 		ipha_t		*ipha;
23258 		uint16_t	offset_and_flags;
23259 		uint16_t	ip_len;
23260 		int		error;
23261 
23262 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23263 		ipha = (ipha_t *)(hdr_ptr + wroff);
23264 		ASSERT(OK_32PTR(ipha));
23265 		*ipha = *ipha_orig;
23266 
23267 		if (ip_data_end - offset > len) {
23268 			offset_and_flags = IPH_MF;
23269 		} else {
23270 			/*
23271 			 * Last frag. Set len to the length of this last piece.
23272 			 */
23273 			len = ip_data_end - offset;
23274 			/* A frag of a frag might have IPH_MF non-zero */
23275 			offset_and_flags =
23276 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23277 			    IPH_MF;
23278 		}
23279 		offset_and_flags |= (uint16_t)(offset >> 3);
23280 		offset_and_flags |= (uint16_t)frag_flag;
23281 		/* Store the offset and flags in the IP header. */
23282 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23283 
23284 		/* Store the length in the IP header. */
23285 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23286 		ipha->ipha_length = htons(ip_len);
23287 
23288 		/*
23289 		 * Set the IP header checksum.  Note that mp is just
23290 		 * the header, so this is easy to pass to ip_csum.
23291 		 */
23292 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23293 
23294 		/*
23295 		 * Record offset and size of header and data of the next packet
23296 		 * in the multidata message.
23297 		 */
23298 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23299 		PDESC_PLD_INIT(&pdi);
23300 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23301 		ASSERT(i1 > 0);
23302 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23303 		if (i1 == len) {
23304 			pld_ptr += len;
23305 		} else {
23306 			i1 = len - i1;
23307 			mp = mp->b_cont;
23308 			ASSERT(mp != NULL);
23309 			ASSERT(MBLKL(mp) >= i1);
23310 			/*
23311 			 * Attach the next payload message block to the
23312 			 * multidata message.
23313 			 */
23314 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23315 				goto pbuf_panic;
23316 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23317 			pld_ptr = mp->b_rptr + i1;
23318 		}
23319 
23320 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23321 		    KM_NOSLEEP)) == NULL) {
23322 			/*
23323 			 * Any failure other than ENOMEM indicates that we
23324 			 * have passed in invalid pdesc info or parameters
23325 			 * to mmd_addpdesc, which must not happen.
23326 			 *
23327 			 * EINVAL is a result of failure on boundary checks
23328 			 * against the pdesc info contents.  It should not
23329 			 * happen, and we panic because either there's
23330 			 * horrible heap corruption, and/or programming
23331 			 * mistake.
23332 			 */
23333 			if (error != ENOMEM) {
23334 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23335 				    "pdesc logic error detected for "
23336 				    "mmd %p pinfo %p (%d)\n",
23337 				    (void *)mmd, (void *)&pdi, error);
23338 				/* NOTREACHED */
23339 			}
23340 			IP_STAT(ip_frag_mdt_addpdescfail);
23341 			/* Free unattached payload message blocks as well */
23342 			md_mp->b_cont = mp->b_cont;
23343 			goto free_mmd;
23344 		}
23345 
23346 		/* Advance fragment offset. */
23347 		offset += len;
23348 
23349 		/* Advance to location for next header in the buffer. */
23350 		hdr_ptr += hdr_chunk_len;
23351 
23352 		/* Did we reach the next payload message block? */
23353 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23354 			mp = mp->b_cont;
23355 			/*
23356 			 * Attach the next message block with payload
23357 			 * data to the multidata message.
23358 			 */
23359 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23360 				goto pbuf_panic;
23361 			pld_ptr = mp->b_rptr;
23362 		}
23363 	}
23364 
23365 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23366 	ASSERT(mp->b_wptr == pld_ptr);
23367 
23368 	/* Update IP statistics */
23369 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
23370 	BUMP_MIB(&ip_mib, ipFragOKs);
23371 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
23372 
23373 	if (pkt_type == OB_PKT) {
23374 		ire->ire_ob_pkt_count += pkts;
23375 		if (ire->ire_ipif != NULL)
23376 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23377 	} else {
23378 		/*
23379 		 * The type is IB_PKT in the forwarding path and in
23380 		 * the mobile IP case when the packet is being reverse-
23381 		 * tunneled to the home agent.
23382 		 */
23383 		ire->ire_ib_pkt_count += pkts;
23384 		ASSERT(!IRE_IS_LOCAL(ire));
23385 		if (ire->ire_type & IRE_BROADCAST)
23386 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23387 		else
23388 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23389 	}
23390 	ire->ire_last_used_time = lbolt;
23391 	/* Send it down */
23392 	putnext(ire->ire_stq, md_mp);
23393 	return;
23394 
23395 pbuf_panic:
23396 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23397 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23398 	    pbuf_idx);
23399 	/* NOTREACHED */
23400 }
23401 
23402 /*
23403  * Outbound IP fragmentation routine.
23404  *
23405  * NOTE : This routine does not ire_refrele the ire that is passed in
23406  * as the argument.
23407  */
23408 static void
23409 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23410     uint32_t frag_flag, zoneid_t zoneid)
23411 {
23412 	int		i1;
23413 	mblk_t		*ll_hdr_mp;
23414 	int 		ll_hdr_len;
23415 	int		hdr_len;
23416 	mblk_t		*hdr_mp;
23417 	ipha_t		*ipha;
23418 	int		ip_data_end;
23419 	int		len;
23420 	mblk_t		*mp = mp_orig, *mp1;
23421 	int		offset;
23422 	queue_t		*q;
23423 	uint32_t	v_hlen_tos_len;
23424 	mblk_t		*first_mp;
23425 	boolean_t	mctl_present;
23426 	ill_t		*ill;
23427 	ill_t		*out_ill;
23428 	mblk_t		*xmit_mp;
23429 	mblk_t		*carve_mp;
23430 	ire_t		*ire1 = NULL;
23431 	ire_t		*save_ire = NULL;
23432 	mblk_t  	*next_mp = NULL;
23433 	boolean_t	last_frag = B_FALSE;
23434 	boolean_t	multirt_send = B_FALSE;
23435 	ire_t		*first_ire = NULL;
23436 	irb_t		*irb = NULL;
23437 
23438 	/*
23439 	 * IPSEC does not allow hw accelerated packets to be fragmented
23440 	 * This check is made in ip_wput_ipsec_out prior to coming here
23441 	 * via ip_wput_ire_fragmentit.
23442 	 *
23443 	 * If at this point we have an ire whose ARP request has not
23444 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23445 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23446 	 * This packet and all fragmentable packets for this ire will
23447 	 * continue to get dropped while ire_nce->nce_state remains in
23448 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23449 	 * ND_REACHABLE, all subsquent large packets for this ire will
23450 	 * get fragemented and sent out by this function.
23451 	 */
23452 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23453 		/* If nce_state is ND_INITIAL, trigger ARP query */
23454 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23455 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23456 		    " -  dropping packet\n"));
23457 		BUMP_MIB(&ip_mib, ipFragFails);
23458 		freemsg(mp);
23459 		return;
23460 	}
23461 
23462 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23463 	    "ip_wput_frag_start:");
23464 
23465 	if (mp->b_datap->db_type == M_CTL) {
23466 		first_mp = mp;
23467 		mp_orig = mp = mp->b_cont;
23468 		mctl_present = B_TRUE;
23469 	} else {
23470 		first_mp = mp;
23471 		mctl_present = B_FALSE;
23472 	}
23473 
23474 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23475 	ipha = (ipha_t *)mp->b_rptr;
23476 
23477 	/*
23478 	 * If the Don't Fragment flag is on, generate an ICMP destination
23479 	 * unreachable, fragmentation needed.
23480 	 */
23481 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23482 	if (offset & IPH_DF) {
23483 		BUMP_MIB(&ip_mib, ipFragFails);
23484 		/*
23485 		 * Need to compute hdr checksum if called from ip_wput_ire.
23486 		 * Note that ip_rput_forward verifies the checksum before
23487 		 * calling this routine so in that case this is a noop.
23488 		 */
23489 		ipha->ipha_hdr_checksum = 0;
23490 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23491 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid);
23492 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23493 		    "ip_wput_frag_end:(%S)",
23494 		    "don't fragment");
23495 		return;
23496 	}
23497 	if (mctl_present)
23498 		freeb(first_mp);
23499 	/*
23500 	 * Establish the starting offset.  May not be zero if we are fragging
23501 	 * a fragment that is being forwarded.
23502 	 */
23503 	offset = offset & IPH_OFFSET;
23504 
23505 	/* TODO why is this test needed? */
23506 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23507 	if (((max_frag - LENGTH) & ~7) < 8) {
23508 		/* TODO: notify ulp somehow */
23509 		BUMP_MIB(&ip_mib, ipFragFails);
23510 		freemsg(mp);
23511 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23512 		    "ip_wput_frag_end:(%S)",
23513 		    "len < 8");
23514 		return;
23515 	}
23516 
23517 	hdr_len = (V_HLEN & 0xF) << 2;
23518 
23519 	ipha->ipha_hdr_checksum = 0;
23520 
23521 	/*
23522 	 * Establish the number of bytes maximum per frag, after putting
23523 	 * in the header.
23524 	 */
23525 	len = (max_frag - hdr_len) & ~7;
23526 
23527 	/* Check if we can use MDT to send out the frags. */
23528 	ASSERT(!IRE_IS_LOCAL(ire));
23529 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
23530 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
23531 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
23532 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23533 		ASSERT(ill->ill_mdt_capab != NULL);
23534 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23535 			/*
23536 			 * If MDT has been previously turned off in the past,
23537 			 * and we currently can do MDT (due to IPQoS policy
23538 			 * removal, etc.) then enable it for this interface.
23539 			 */
23540 			ill->ill_mdt_capab->ill_mdt_on = 1;
23541 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23542 			    ill->ill_name));
23543 		}
23544 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23545 		    offset);
23546 		return;
23547 	}
23548 
23549 	/* Get a copy of the header for the trailing frags */
23550 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
23551 	if (!hdr_mp) {
23552 		BUMP_MIB(&ip_mib, ipOutDiscards);
23553 		freemsg(mp);
23554 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23555 		    "ip_wput_frag_end:(%S)",
23556 		    "couldn't copy hdr");
23557 		return;
23558 	}
23559 	if (DB_CRED(mp) != NULL)
23560 		mblk_setcred(hdr_mp, DB_CRED(mp));
23561 
23562 	/* Store the starting offset, with the MoreFrags flag. */
23563 	i1 = offset | IPH_MF | frag_flag;
23564 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23565 
23566 	/* Establish the ending byte offset, based on the starting offset. */
23567 	offset <<= 3;
23568 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23569 
23570 	/* Store the length of the first fragment in the IP header. */
23571 	i1 = len + hdr_len;
23572 	ASSERT(i1 <= IP_MAXPACKET);
23573 	ipha->ipha_length = htons((uint16_t)i1);
23574 
23575 	/*
23576 	 * Compute the IP header checksum for the first frag.  We have to
23577 	 * watch out that we stop at the end of the header.
23578 	 */
23579 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23580 
23581 	/*
23582 	 * Now carve off the first frag.  Note that this will include the
23583 	 * original IP header.
23584 	 */
23585 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
23586 		BUMP_MIB(&ip_mib, ipOutDiscards);
23587 		freeb(hdr_mp);
23588 		freemsg(mp_orig);
23589 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23590 		    "ip_wput_frag_end:(%S)",
23591 		    "couldn't carve first");
23592 		return;
23593 	}
23594 
23595 	/*
23596 	 * Multirouting case. Each fragment is replicated
23597 	 * via all non-condemned RTF_MULTIRT routes
23598 	 * currently resolved.
23599 	 * We ensure that first_ire is the first RTF_MULTIRT
23600 	 * ire in the bucket.
23601 	 */
23602 	if (ire->ire_flags & RTF_MULTIRT) {
23603 		irb = ire->ire_bucket;
23604 		ASSERT(irb != NULL);
23605 
23606 		multirt_send = B_TRUE;
23607 
23608 		/* Make sure we do not omit any multiroute ire. */
23609 		IRB_REFHOLD(irb);
23610 		for (first_ire = irb->irb_ire;
23611 		    first_ire != NULL;
23612 		    first_ire = first_ire->ire_next) {
23613 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23614 			    (first_ire->ire_addr == ire->ire_addr) &&
23615 			    !(first_ire->ire_marks &
23616 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23617 				break;
23618 		}
23619 
23620 		if (first_ire != NULL) {
23621 			if (first_ire != ire) {
23622 				IRE_REFHOLD(first_ire);
23623 				/*
23624 				 * Do not release the ire passed in
23625 				 * as the argument.
23626 				 */
23627 				ire = first_ire;
23628 			} else {
23629 				first_ire = NULL;
23630 			}
23631 		}
23632 		IRB_REFRELE(irb);
23633 
23634 		/*
23635 		 * Save the first ire; we will need to restore it
23636 		 * for the trailing frags.
23637 		 * We REFHOLD save_ire, as each iterated ire will be
23638 		 * REFRELEd.
23639 		 */
23640 		save_ire = ire;
23641 		IRE_REFHOLD(save_ire);
23642 	}
23643 
23644 	/*
23645 	 * First fragment emission loop.
23646 	 * In most cases, the emission loop below is entered only
23647 	 * once. Only in the case where the ire holds the RTF_MULTIRT
23648 	 * flag, do we loop to process all RTF_MULTIRT ires in the
23649 	 * bucket, and send the fragment through all crossed
23650 	 * RTF_MULTIRT routes.
23651 	 */
23652 	do {
23653 		if (ire->ire_flags & RTF_MULTIRT) {
23654 			/*
23655 			 * We are in a multiple send case, need to get
23656 			 * the next ire and make a copy of the packet.
23657 			 * ire1 holds here the next ire to process in the
23658 			 * bucket. If multirouting is expected,
23659 			 * any non-RTF_MULTIRT ire that has the
23660 			 * right destination address is ignored.
23661 			 *
23662 			 * We have to take into account the MTU of
23663 			 * each walked ire. max_frag is set by the
23664 			 * the caller and generally refers to
23665 			 * the primary ire entry. Here we ensure that
23666 			 * no route with a lower MTU will be used, as
23667 			 * fragments are carved once for all ires,
23668 			 * then replicated.
23669 			 */
23670 			ASSERT(irb != NULL);
23671 			IRB_REFHOLD(irb);
23672 			for (ire1 = ire->ire_next;
23673 			    ire1 != NULL;
23674 			    ire1 = ire1->ire_next) {
23675 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23676 					continue;
23677 				if (ire1->ire_addr != ire->ire_addr)
23678 					continue;
23679 				if (ire1->ire_marks &
23680 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23681 					continue;
23682 				/*
23683 				 * Ensure we do not exceed the MTU
23684 				 * of the next route.
23685 				 */
23686 				if (ire1->ire_max_frag < max_frag) {
23687 					ip_multirt_bad_mtu(ire1, max_frag);
23688 					continue;
23689 				}
23690 
23691 				/* Got one. */
23692 				IRE_REFHOLD(ire1);
23693 				break;
23694 			}
23695 			IRB_REFRELE(irb);
23696 
23697 			if (ire1 != NULL) {
23698 				next_mp = copyb(mp);
23699 				if ((next_mp == NULL) ||
23700 				    ((mp->b_cont != NULL) &&
23701 				    ((next_mp->b_cont =
23702 				    dupmsg(mp->b_cont)) == NULL))) {
23703 					freemsg(next_mp);
23704 					next_mp = NULL;
23705 					ire_refrele(ire1);
23706 					ire1 = NULL;
23707 				}
23708 			}
23709 
23710 			/* Last multiroute ire; don't loop anymore. */
23711 			if (ire1 == NULL) {
23712 				multirt_send = B_FALSE;
23713 			}
23714 		}
23715 
23716 		ll_hdr_len = 0;
23717 		LOCK_IRE_FP_MP(ire);
23718 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23719 		if (ll_hdr_mp != NULL) {
23720 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23721 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
23722 		} else {
23723 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
23724 		}
23725 
23726 		/* If there is a transmit header, get a copy for this frag. */
23727 		/*
23728 		 * TODO: should check db_ref before calling ip_carve_mp since
23729 		 * it might give us a dup.
23730 		 */
23731 		if (!ll_hdr_mp) {
23732 			/* No xmit header. */
23733 			xmit_mp = mp;
23734 
23735 		/* We have a link-layer header that can fit in our mblk. */
23736 		} else if (mp->b_datap->db_ref == 1 &&
23737 		    ll_hdr_len != 0 &&
23738 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23739 			/* M_DATA fastpath */
23740 			mp->b_rptr -= ll_hdr_len;
23741 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
23742 			xmit_mp = mp;
23743 
23744 		/* Corner case if copyb has failed */
23745 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
23746 			UNLOCK_IRE_FP_MP(ire);
23747 			BUMP_MIB(&ip_mib, ipOutDiscards);
23748 			freeb(hdr_mp);
23749 			freemsg(mp);
23750 			freemsg(mp_orig);
23751 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23752 			    "ip_wput_frag_end:(%S)",
23753 			    "discard");
23754 
23755 			if (multirt_send) {
23756 				ASSERT(ire1);
23757 				ASSERT(next_mp);
23758 
23759 				freemsg(next_mp);
23760 				ire_refrele(ire1);
23761 			}
23762 			if (save_ire != NULL)
23763 				IRE_REFRELE(save_ire);
23764 
23765 			if (first_ire != NULL)
23766 				ire_refrele(first_ire);
23767 			return;
23768 
23769 		/*
23770 		 * Case of res_mp OR the fastpath mp can't fit
23771 		 * in the mblk
23772 		 */
23773 		} else {
23774 			xmit_mp->b_cont = mp;
23775 			if (DB_CRED(mp) != NULL)
23776 				mblk_setcred(xmit_mp, DB_CRED(mp));
23777 			/*
23778 			 * Get priority marking, if any.
23779 			 * We propagate the CoS marking from the
23780 			 * original packet that went to QoS processing
23781 			 * in ip_wput_ire to the newly carved mp.
23782 			 */
23783 			if (DB_TYPE(xmit_mp) == M_DATA)
23784 				xmit_mp->b_band = mp->b_band;
23785 		}
23786 		UNLOCK_IRE_FP_MP(ire);
23787 		q = ire->ire_stq;
23788 		BUMP_MIB(&ip_mib, ipFragCreates);
23789 
23790 		out_ill = (ill_t *)q->q_ptr;
23791 
23792 		DTRACE_PROBE4(ip4__physical__out__start,
23793 		    ill_t *, NULL, ill_t *, out_ill,
23794 		    ipha_t *, ipha, mblk_t *, xmit_mp);
23795 
23796 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
23797 		    NULL, out_ill, ipha, xmit_mp, mp);
23798 
23799 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
23800 
23801 		if (xmit_mp != NULL) {
23802 			putnext(q, xmit_mp);
23803 			if (pkt_type != OB_PKT) {
23804 				/*
23805 				 * Update the packet count of trailing
23806 				 * RTF_MULTIRT ires.
23807 				 */
23808 				UPDATE_OB_PKT_COUNT(ire);
23809 			}
23810 		}
23811 
23812 		if (multirt_send) {
23813 			/*
23814 			 * We are in a multiple send case; look for
23815 			 * the next ire and re-enter the loop.
23816 			 */
23817 			ASSERT(ire1);
23818 			ASSERT(next_mp);
23819 			/* REFRELE the current ire before looping */
23820 			ire_refrele(ire);
23821 			ire = ire1;
23822 			ire1 = NULL;
23823 			mp = next_mp;
23824 			next_mp = NULL;
23825 		}
23826 	} while (multirt_send);
23827 
23828 	ASSERT(ire1 == NULL);
23829 
23830 	/* Restore the original ire; we need it for the trailing frags */
23831 	if (save_ire != NULL) {
23832 		/* REFRELE the last iterated ire */
23833 		ire_refrele(ire);
23834 		/* save_ire has been REFHOLDed */
23835 		ire = save_ire;
23836 		save_ire = NULL;
23837 		q = ire->ire_stq;
23838 	}
23839 
23840 	if (pkt_type == OB_PKT) {
23841 		UPDATE_OB_PKT_COUNT(ire);
23842 	} else {
23843 		UPDATE_IB_PKT_COUNT(ire);
23844 	}
23845 
23846 	/* Advance the offset to the second frag starting point. */
23847 	offset += len;
23848 	/*
23849 	 * Update hdr_len from the copied header - there might be less options
23850 	 * in the later fragments.
23851 	 */
23852 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
23853 	/* Loop until done. */
23854 	for (;;) {
23855 		uint16_t	offset_and_flags;
23856 		uint16_t	ip_len;
23857 
23858 		if (ip_data_end - offset > len) {
23859 			/*
23860 			 * Carve off the appropriate amount from the original
23861 			 * datagram.
23862 			 */
23863 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23864 				mp = NULL;
23865 				break;
23866 			}
23867 			/*
23868 			 * More frags after this one.  Get another copy
23869 			 * of the header.
23870 			 */
23871 			if (carve_mp->b_datap->db_ref == 1 &&
23872 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23873 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23874 				/* Inline IP header */
23875 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23876 				    hdr_mp->b_rptr;
23877 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23878 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23879 				mp = carve_mp;
23880 			} else {
23881 				if (!(mp = copyb(hdr_mp))) {
23882 					freemsg(carve_mp);
23883 					break;
23884 				}
23885 				/* Get priority marking, if any. */
23886 				mp->b_band = carve_mp->b_band;
23887 				mp->b_cont = carve_mp;
23888 			}
23889 			ipha = (ipha_t *)mp->b_rptr;
23890 			offset_and_flags = IPH_MF;
23891 		} else {
23892 			/*
23893 			 * Last frag.  Consume the header. Set len to
23894 			 * the length of this last piece.
23895 			 */
23896 			len = ip_data_end - offset;
23897 
23898 			/*
23899 			 * Carve off the appropriate amount from the original
23900 			 * datagram.
23901 			 */
23902 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23903 				mp = NULL;
23904 				break;
23905 			}
23906 			if (carve_mp->b_datap->db_ref == 1 &&
23907 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23908 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23909 				/* Inline IP header */
23910 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23911 				    hdr_mp->b_rptr;
23912 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23913 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23914 				mp = carve_mp;
23915 				freeb(hdr_mp);
23916 				hdr_mp = mp;
23917 			} else {
23918 				mp = hdr_mp;
23919 				/* Get priority marking, if any. */
23920 				mp->b_band = carve_mp->b_band;
23921 				mp->b_cont = carve_mp;
23922 			}
23923 			ipha = (ipha_t *)mp->b_rptr;
23924 			/* A frag of a frag might have IPH_MF non-zero */
23925 			offset_and_flags =
23926 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23927 			    IPH_MF;
23928 		}
23929 		offset_and_flags |= (uint16_t)(offset >> 3);
23930 		offset_and_flags |= (uint16_t)frag_flag;
23931 		/* Store the offset and flags in the IP header. */
23932 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23933 
23934 		/* Store the length in the IP header. */
23935 		ip_len = (uint16_t)(len + hdr_len);
23936 		ipha->ipha_length = htons(ip_len);
23937 
23938 		/*
23939 		 * Set the IP header checksum.	Note that mp is just
23940 		 * the header, so this is easy to pass to ip_csum.
23941 		 */
23942 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23943 
23944 		/* Attach a transmit header, if any, and ship it. */
23945 		if (pkt_type == OB_PKT) {
23946 			UPDATE_OB_PKT_COUNT(ire);
23947 		} else {
23948 			UPDATE_IB_PKT_COUNT(ire);
23949 		}
23950 
23951 		if (ire->ire_flags & RTF_MULTIRT) {
23952 			irb = ire->ire_bucket;
23953 			ASSERT(irb != NULL);
23954 
23955 			multirt_send = B_TRUE;
23956 
23957 			/*
23958 			 * Save the original ire; we will need to restore it
23959 			 * for the tailing frags.
23960 			 */
23961 			save_ire = ire;
23962 			IRE_REFHOLD(save_ire);
23963 		}
23964 		/*
23965 		 * Emission loop for this fragment, similar
23966 		 * to what is done for the first fragment.
23967 		 */
23968 		do {
23969 			if (multirt_send) {
23970 				/*
23971 				 * We are in a multiple send case, need to get
23972 				 * the next ire and make a copy of the packet.
23973 				 */
23974 				ASSERT(irb != NULL);
23975 				IRB_REFHOLD(irb);
23976 				for (ire1 = ire->ire_next;
23977 				    ire1 != NULL;
23978 				    ire1 = ire1->ire_next) {
23979 					if (!(ire1->ire_flags & RTF_MULTIRT))
23980 						continue;
23981 					if (ire1->ire_addr != ire->ire_addr)
23982 						continue;
23983 					if (ire1->ire_marks &
23984 					    (IRE_MARK_CONDEMNED|
23985 						IRE_MARK_HIDDEN))
23986 						continue;
23987 					/*
23988 					 * Ensure we do not exceed the MTU
23989 					 * of the next route.
23990 					 */
23991 					if (ire1->ire_max_frag < max_frag) {
23992 						ip_multirt_bad_mtu(ire1,
23993 						    max_frag);
23994 						continue;
23995 					}
23996 
23997 					/* Got one. */
23998 					IRE_REFHOLD(ire1);
23999 					break;
24000 				}
24001 				IRB_REFRELE(irb);
24002 
24003 				if (ire1 != NULL) {
24004 					next_mp = copyb(mp);
24005 					if ((next_mp == NULL) ||
24006 					    ((mp->b_cont != NULL) &&
24007 					    ((next_mp->b_cont =
24008 					    dupmsg(mp->b_cont)) == NULL))) {
24009 						freemsg(next_mp);
24010 						next_mp = NULL;
24011 						ire_refrele(ire1);
24012 						ire1 = NULL;
24013 					}
24014 				}
24015 
24016 				/* Last multiroute ire; don't loop anymore. */
24017 				if (ire1 == NULL) {
24018 					multirt_send = B_FALSE;
24019 				}
24020 			}
24021 
24022 			/* Update transmit header */
24023 			ll_hdr_len = 0;
24024 			LOCK_IRE_FP_MP(ire);
24025 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24026 			if (ll_hdr_mp != NULL) {
24027 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24028 				ll_hdr_len = MBLKL(ll_hdr_mp);
24029 			} else {
24030 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24031 			}
24032 
24033 			if (!ll_hdr_mp) {
24034 				xmit_mp = mp;
24035 
24036 			/*
24037 			 * We have link-layer header that can fit in
24038 			 * our mblk.
24039 			 */
24040 			} else if (mp->b_datap->db_ref == 1 &&
24041 			    ll_hdr_len != 0 &&
24042 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24043 				/* M_DATA fastpath */
24044 				mp->b_rptr -= ll_hdr_len;
24045 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24046 				    ll_hdr_len);
24047 				xmit_mp = mp;
24048 
24049 			/*
24050 			 * Case of res_mp OR the fastpath mp can't fit
24051 			 * in the mblk
24052 			 */
24053 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24054 				xmit_mp->b_cont = mp;
24055 				if (DB_CRED(mp) != NULL)
24056 					mblk_setcred(xmit_mp, DB_CRED(mp));
24057 				/* Get priority marking, if any. */
24058 				if (DB_TYPE(xmit_mp) == M_DATA)
24059 					xmit_mp->b_band = mp->b_band;
24060 
24061 			/* Corner case if copyb failed */
24062 			} else {
24063 				/*
24064 				 * Exit both the replication and
24065 				 * fragmentation loops.
24066 				 */
24067 				UNLOCK_IRE_FP_MP(ire);
24068 				goto drop_pkt;
24069 			}
24070 			UNLOCK_IRE_FP_MP(ire);
24071 			BUMP_MIB(&ip_mib, ipFragCreates);
24072 
24073 			mp1 = mp;
24074 			out_ill = (ill_t *)q->q_ptr;
24075 
24076 			DTRACE_PROBE4(ip4__physical__out__start,
24077 			    ill_t *, NULL, ill_t *, out_ill,
24078 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24079 
24080 			FW_HOOKS(ip4_physical_out_event,
24081 			    ipv4firewall_physical_out,
24082 			    NULL, out_ill, ipha, xmit_mp, mp);
24083 
24084 			DTRACE_PROBE1(ip4__physical__out__end,
24085 			    mblk_t *, xmit_mp);
24086 
24087 			if (mp != mp1 && hdr_mp == mp1)
24088 				hdr_mp = mp;
24089 			if (mp != mp1 && mp_orig == mp1)
24090 				mp_orig = mp;
24091 
24092 			if (xmit_mp != NULL) {
24093 				putnext(q, xmit_mp);
24094 
24095 				if (pkt_type != OB_PKT) {
24096 					/*
24097 					 * Update the packet count of trailing
24098 					 * RTF_MULTIRT ires.
24099 					 */
24100 					UPDATE_OB_PKT_COUNT(ire);
24101 				}
24102 			}
24103 
24104 			/* All done if we just consumed the hdr_mp. */
24105 			if (mp == hdr_mp) {
24106 				last_frag = B_TRUE;
24107 			}
24108 
24109 			if (multirt_send) {
24110 				/*
24111 				 * We are in a multiple send case; look for
24112 				 * the next ire and re-enter the loop.
24113 				 */
24114 				ASSERT(ire1);
24115 				ASSERT(next_mp);
24116 				/* REFRELE the current ire before looping */
24117 				ire_refrele(ire);
24118 				ire = ire1;
24119 				ire1 = NULL;
24120 				q = ire->ire_stq;
24121 				mp = next_mp;
24122 				next_mp = NULL;
24123 			}
24124 		} while (multirt_send);
24125 		/*
24126 		 * Restore the original ire; we need it for the
24127 		 * trailing frags
24128 		 */
24129 		if (save_ire != NULL) {
24130 			ASSERT(ire1 == NULL);
24131 			/* REFRELE the last iterated ire */
24132 			ire_refrele(ire);
24133 			/* save_ire has been REFHOLDed */
24134 			ire = save_ire;
24135 			q = ire->ire_stq;
24136 			save_ire = NULL;
24137 		}
24138 
24139 		if (last_frag) {
24140 			BUMP_MIB(&ip_mib, ipFragOKs);
24141 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24142 			    "ip_wput_frag_end:(%S)",
24143 			    "consumed hdr_mp");
24144 
24145 			if (first_ire != NULL)
24146 				ire_refrele(first_ire);
24147 			return;
24148 		}
24149 		/* Otherwise, advance and loop. */
24150 		offset += len;
24151 	}
24152 
24153 drop_pkt:
24154 	/* Clean up following allocation failure. */
24155 	BUMP_MIB(&ip_mib, ipOutDiscards);
24156 	freemsg(mp);
24157 	if (mp != hdr_mp)
24158 		freeb(hdr_mp);
24159 	if (mp != mp_orig)
24160 		freemsg(mp_orig);
24161 
24162 	if (save_ire != NULL)
24163 		IRE_REFRELE(save_ire);
24164 	if (first_ire != NULL)
24165 		ire_refrele(first_ire);
24166 
24167 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24168 	    "ip_wput_frag_end:(%S)",
24169 	    "end--alloc failure");
24170 }
24171 
24172 /*
24173  * Copy the header plus those options which have the copy bit set
24174  */
24175 static mblk_t *
24176 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
24177 {
24178 	mblk_t	*mp;
24179 	uchar_t	*up;
24180 
24181 	/*
24182 	 * Quick check if we need to look for options without the copy bit
24183 	 * set
24184 	 */
24185 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
24186 	if (!mp)
24187 		return (mp);
24188 	mp->b_rptr += ip_wroff_extra;
24189 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24190 		bcopy(rptr, mp->b_rptr, hdr_len);
24191 		mp->b_wptr += hdr_len + ip_wroff_extra;
24192 		return (mp);
24193 	}
24194 	up  = mp->b_rptr;
24195 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24196 	up += IP_SIMPLE_HDR_LENGTH;
24197 	rptr += IP_SIMPLE_HDR_LENGTH;
24198 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24199 	while (hdr_len > 0) {
24200 		uint32_t optval;
24201 		uint32_t optlen;
24202 
24203 		optval = *rptr;
24204 		if (optval == IPOPT_EOL)
24205 			break;
24206 		if (optval == IPOPT_NOP)
24207 			optlen = 1;
24208 		else
24209 			optlen = rptr[1];
24210 		if (optval & IPOPT_COPY) {
24211 			bcopy(rptr, up, optlen);
24212 			up += optlen;
24213 		}
24214 		rptr += optlen;
24215 		hdr_len -= optlen;
24216 	}
24217 	/*
24218 	 * Make sure that we drop an even number of words by filling
24219 	 * with EOL to the next word boundary.
24220 	 */
24221 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24222 	    hdr_len & 0x3; hdr_len++)
24223 		*up++ = IPOPT_EOL;
24224 	mp->b_wptr = up;
24225 	/* Update header length */
24226 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24227 	return (mp);
24228 }
24229 
24230 /*
24231  * Delivery to local recipients including fanout to multiple recipients.
24232  * Does not do checksumming of UDP/TCP.
24233  * Note: q should be the read side queue for either the ill or conn.
24234  * Note: rq should be the read side q for the lower (ill) stream.
24235  * We don't send packets to IPPF processing, thus the last argument
24236  * to all the fanout calls are B_FALSE.
24237  */
24238 void
24239 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24240     int fanout_flags, zoneid_t zoneid)
24241 {
24242 	uint32_t	protocol;
24243 	mblk_t		*first_mp;
24244 	boolean_t	mctl_present;
24245 	int		ire_type;
24246 #define	rptr	((uchar_t *)ipha)
24247 
24248 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24249 	    "ip_wput_local_start: q %p", q);
24250 
24251 	if (ire != NULL) {
24252 		ire_type = ire->ire_type;
24253 	} else {
24254 		/*
24255 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24256 		 * packet is not multicast, we can't tell the ire type.
24257 		 */
24258 		ASSERT(CLASSD(ipha->ipha_dst));
24259 		ire_type = IRE_BROADCAST;
24260 	}
24261 
24262 	first_mp = mp;
24263 	if (first_mp->b_datap->db_type == M_CTL) {
24264 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24265 		if (!io->ipsec_out_secure) {
24266 			/*
24267 			 * This ipsec_out_t was allocated in ip_wput
24268 			 * for multicast packets to store the ill_index.
24269 			 * As this is being delivered locally, we don't
24270 			 * need this anymore.
24271 			 */
24272 			mp = first_mp->b_cont;
24273 			freeb(first_mp);
24274 			first_mp = mp;
24275 			mctl_present = B_FALSE;
24276 		} else {
24277 			/*
24278 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24279 			 * security properties for the looped-back packet.
24280 			 */
24281 			mctl_present = B_TRUE;
24282 			mp = first_mp->b_cont;
24283 			ASSERT(mp != NULL);
24284 			ipsec_out_to_in(first_mp);
24285 		}
24286 	} else {
24287 		mctl_present = B_FALSE;
24288 	}
24289 
24290 	DTRACE_PROBE4(ip4__loopback__in__start,
24291 	    ill_t *, ill, ill_t *, NULL,
24292 	    ipha_t *, ipha, mblk_t *, first_mp);
24293 
24294 	FW_HOOKS(ip4_loopback_in_event, ipv4firewall_loopback_in,
24295 	    ill, NULL, ipha, first_mp, mp);
24296 
24297 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24298 
24299 	if (first_mp == NULL)
24300 		return;
24301 
24302 	loopback_packets++;
24303 
24304 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24305 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24306 	if (!IS_SIMPLE_IPH(ipha)) {
24307 		ip_wput_local_options(ipha);
24308 	}
24309 
24310 	protocol = ipha->ipha_protocol;
24311 	switch (protocol) {
24312 	case IPPROTO_ICMP: {
24313 		ire_t		*ire_zone;
24314 		ilm_t		*ilm;
24315 		mblk_t		*mp1;
24316 		zoneid_t	last_zoneid;
24317 
24318 		if (CLASSD(ipha->ipha_dst) &&
24319 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
24320 			ASSERT(ire_type == IRE_BROADCAST);
24321 			/*
24322 			 * In the multicast case, applications may have joined
24323 			 * the group from different zones, so we need to deliver
24324 			 * the packet to each of them. Loop through the
24325 			 * multicast memberships structures (ilm) on the receive
24326 			 * ill and send a copy of the packet up each matching
24327 			 * one. However, we don't do this for multicasts sent on
24328 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24329 			 * they must stay in the sender's zone.
24330 			 *
24331 			 * ilm_add_v6() ensures that ilms in the same zone are
24332 			 * contiguous in the ill_ilm list. We use this property
24333 			 * to avoid sending duplicates needed when two
24334 			 * applications in the same zone join the same group on
24335 			 * different logical interfaces: we ignore the ilm if
24336 			 * it's zoneid is the same as the last matching one.
24337 			 * In addition, the sending of the packet for
24338 			 * ire_zoneid is delayed until all of the other ilms
24339 			 * have been exhausted.
24340 			 */
24341 			last_zoneid = -1;
24342 			ILM_WALKER_HOLD(ill);
24343 			for (ilm = ill->ill_ilm; ilm != NULL;
24344 			    ilm = ilm->ilm_next) {
24345 				if ((ilm->ilm_flags & ILM_DELETED) ||
24346 				    ipha->ipha_dst != ilm->ilm_addr ||
24347 				    ilm->ilm_zoneid == last_zoneid ||
24348 				    ilm->ilm_zoneid == zoneid ||
24349 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24350 					continue;
24351 				mp1 = ip_copymsg(first_mp);
24352 				if (mp1 == NULL)
24353 					continue;
24354 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24355 				    mctl_present, B_FALSE, ill,
24356 				    ilm->ilm_zoneid);
24357 				last_zoneid = ilm->ilm_zoneid;
24358 			}
24359 			ILM_WALKER_RELE(ill);
24360 			/*
24361 			 * Loopback case: the sending endpoint has
24362 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24363 			 * dispatch the multicast packet to the sending zone.
24364 			 */
24365 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24366 				freemsg(first_mp);
24367 				return;
24368 			}
24369 		} else if (ire_type == IRE_BROADCAST) {
24370 			/*
24371 			 * In the broadcast case, there may be many zones
24372 			 * which need a copy of the packet delivered to them.
24373 			 * There is one IRE_BROADCAST per broadcast address
24374 			 * and per zone; we walk those using a helper function.
24375 			 * In addition, the sending of the packet for zoneid is
24376 			 * delayed until all of the other ires have been
24377 			 * processed.
24378 			 */
24379 			IRB_REFHOLD(ire->ire_bucket);
24380 			ire_zone = NULL;
24381 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24382 			    ire)) != NULL) {
24383 				mp1 = ip_copymsg(first_mp);
24384 				if (mp1 == NULL)
24385 					continue;
24386 
24387 				UPDATE_IB_PKT_COUNT(ire_zone);
24388 				ire_zone->ire_last_used_time = lbolt;
24389 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24390 				    mctl_present, B_FALSE, ill,
24391 				    ire_zone->ire_zoneid);
24392 			}
24393 			IRB_REFRELE(ire->ire_bucket);
24394 		}
24395 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
24396 		    0, mctl_present, B_FALSE, ill, zoneid);
24397 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24398 		    "ip_wput_local_end: q %p (%S)",
24399 		    q, "icmp");
24400 		return;
24401 	}
24402 	case IPPROTO_IGMP:
24403 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
24404 			/* Bad packet - discarded by igmp_input */
24405 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24406 			    "ip_wput_local_end: q %p (%S)",
24407 			    q, "igmp_input--bad packet");
24408 			if (mctl_present)
24409 				freeb(first_mp);
24410 			return;
24411 		}
24412 		/*
24413 		 * igmp_input() may have returned the pulled up message.
24414 		 * So first_mp and ipha need to be reinitialized.
24415 		 */
24416 		ipha = (ipha_t *)mp->b_rptr;
24417 		if (mctl_present)
24418 			first_mp->b_cont = mp;
24419 		else
24420 			first_mp = mp;
24421 		/* deliver to local raw users */
24422 		break;
24423 	case IPPROTO_ENCAP:
24424 		/*
24425 		 * This case is covered by either ip_fanout_proto, or by
24426 		 * the above security processing for self-tunneled packets.
24427 		 */
24428 		break;
24429 	case IPPROTO_UDP: {
24430 		uint16_t	*up;
24431 		uint32_t	ports;
24432 
24433 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
24434 		    UDP_PORTS_OFFSET);
24435 		/* Force a 'valid' checksum. */
24436 		up[3] = 0;
24437 
24438 		ports = *(uint32_t *)up;
24439 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24440 		    (ire_type == IRE_BROADCAST),
24441 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24442 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
24443 		    ill, zoneid);
24444 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24445 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24446 		return;
24447 	}
24448 	case IPPROTO_TCP: {
24449 
24450 		/*
24451 		 * For TCP, discard broadcast packets.
24452 		 */
24453 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24454 			freemsg(first_mp);
24455 			BUMP_MIB(&ip_mib, ipInDiscards);
24456 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24457 			return;
24458 		}
24459 
24460 		if (mp->b_datap->db_type == M_DATA) {
24461 			/*
24462 			 * M_DATA mblk, so init mblk (chain) for no struio().
24463 			 */
24464 			mblk_t	*mp1 = mp;
24465 
24466 			do
24467 				mp1->b_datap->db_struioflag = 0;
24468 			while ((mp1 = mp1->b_cont) != NULL);
24469 		}
24470 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24471 		    <= mp->b_wptr);
24472 		ip_fanout_tcp(q, first_mp, ill, ipha,
24473 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24474 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
24475 		    mctl_present, B_FALSE, zoneid);
24476 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24477 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24478 		return;
24479 	}
24480 	case IPPROTO_SCTP:
24481 	{
24482 		uint32_t	ports;
24483 
24484 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24485 		ip_fanout_sctp(first_mp, ill, ipha, ports,
24486 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24487 		    IP_FF_IP6INFO,
24488 		    mctl_present, B_FALSE, 0, zoneid);
24489 		return;
24490 	}
24491 
24492 	default:
24493 		break;
24494 	}
24495 	/*
24496 	 * Find a client for some other protocol.  We give
24497 	 * copies to multiple clients, if more than one is
24498 	 * bound.
24499 	 */
24500 	ip_fanout_proto(q, first_mp, ill, ipha,
24501 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
24502 	    mctl_present, B_FALSE, ill, zoneid);
24503 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24504 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
24505 #undef	rptr
24506 }
24507 
24508 /*
24509  * Update any source route, record route, or timestamp options.
24510  * Check that we are at end of strict source route.
24511  * The options have been sanity checked by ip_wput_options().
24512  */
24513 static void
24514 ip_wput_local_options(ipha_t *ipha)
24515 {
24516 	ipoptp_t	opts;
24517 	uchar_t		*opt;
24518 	uint8_t		optval;
24519 	uint8_t		optlen;
24520 	ipaddr_t	dst;
24521 	uint32_t	ts;
24522 	ire_t		*ire;
24523 	timestruc_t	now;
24524 
24525 	ip2dbg(("ip_wput_local_options\n"));
24526 	for (optval = ipoptp_first(&opts, ipha);
24527 	    optval != IPOPT_EOL;
24528 	    optval = ipoptp_next(&opts)) {
24529 		opt = opts.ipoptp_cur;
24530 		optlen = opts.ipoptp_len;
24531 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
24532 		switch (optval) {
24533 			uint32_t off;
24534 		case IPOPT_SSRR:
24535 		case IPOPT_LSRR:
24536 			off = opt[IPOPT_OFFSET];
24537 			off--;
24538 			if (optlen < IP_ADDR_LEN ||
24539 			    off > optlen - IP_ADDR_LEN) {
24540 				/* End of source route */
24541 				break;
24542 			}
24543 			/*
24544 			 * This will only happen if two consecutive entries
24545 			 * in the source route contains our address or if
24546 			 * it is a packet with a loose source route which
24547 			 * reaches us before consuming the whole source route
24548 			 */
24549 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
24550 			if (optval == IPOPT_SSRR) {
24551 				return;
24552 			}
24553 			/*
24554 			 * Hack: instead of dropping the packet truncate the
24555 			 * source route to what has been used by filling the
24556 			 * rest with IPOPT_NOP.
24557 			 */
24558 			opt[IPOPT_OLEN] = (uint8_t)off;
24559 			while (off < optlen) {
24560 				opt[off++] = IPOPT_NOP;
24561 			}
24562 			break;
24563 		case IPOPT_RR:
24564 			off = opt[IPOPT_OFFSET];
24565 			off--;
24566 			if (optlen < IP_ADDR_LEN ||
24567 			    off > optlen - IP_ADDR_LEN) {
24568 				/* No more room - ignore */
24569 				ip1dbg((
24570 				    "ip_wput_forward_options: end of RR\n"));
24571 				break;
24572 			}
24573 			dst = htonl(INADDR_LOOPBACK);
24574 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24575 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24576 			break;
24577 		case IPOPT_TS:
24578 			/* Insert timestamp if there is romm */
24579 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24580 			case IPOPT_TS_TSONLY:
24581 				off = IPOPT_TS_TIMELEN;
24582 				break;
24583 			case IPOPT_TS_PRESPEC:
24584 			case IPOPT_TS_PRESPEC_RFC791:
24585 				/* Verify that the address matched */
24586 				off = opt[IPOPT_OFFSET] - 1;
24587 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
24588 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
24589 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
24590 				if (ire == NULL) {
24591 					/* Not for us */
24592 					break;
24593 				}
24594 				ire_refrele(ire);
24595 				/* FALLTHRU */
24596 			case IPOPT_TS_TSANDADDR:
24597 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24598 				break;
24599 			default:
24600 				/*
24601 				 * ip_*put_options should have already
24602 				 * dropped this packet.
24603 				 */
24604 				cmn_err(CE_PANIC, "ip_wput_local_options: "
24605 				    "unknown IT - bug in ip_wput_options?\n");
24606 				return;	/* Keep "lint" happy */
24607 			}
24608 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
24609 				/* Increase overflow counter */
24610 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
24611 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
24612 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
24613 				    (off << 4);
24614 				break;
24615 			}
24616 			off = opt[IPOPT_OFFSET] - 1;
24617 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24618 			case IPOPT_TS_PRESPEC:
24619 			case IPOPT_TS_PRESPEC_RFC791:
24620 			case IPOPT_TS_TSANDADDR:
24621 				dst = htonl(INADDR_LOOPBACK);
24622 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24623 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24624 				/* FALLTHRU */
24625 			case IPOPT_TS_TSONLY:
24626 				off = opt[IPOPT_OFFSET] - 1;
24627 				/* Compute # of milliseconds since midnight */
24628 				gethrestime(&now);
24629 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
24630 				    now.tv_nsec / (NANOSEC / MILLISEC);
24631 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
24632 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
24633 				break;
24634 			}
24635 			break;
24636 		}
24637 	}
24638 }
24639 
24640 /*
24641  * Send out a multicast packet on interface ipif.
24642  * The sender does not have an conn.
24643  * Caller verifies that this isn't a PHYI_LOOPBACK.
24644  */
24645 void
24646 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
24647 {
24648 	ipha_t	*ipha;
24649 	ire_t	*ire;
24650 	ipaddr_t	dst;
24651 	mblk_t		*first_mp;
24652 
24653 	/* igmp_sendpkt always allocates a ipsec_out_t */
24654 	ASSERT(mp->b_datap->db_type == M_CTL);
24655 	ASSERT(!ipif->ipif_isv6);
24656 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
24657 
24658 	first_mp = mp;
24659 	mp = first_mp->b_cont;
24660 	ASSERT(mp->b_datap->db_type == M_DATA);
24661 	ipha = (ipha_t *)mp->b_rptr;
24662 
24663 	/*
24664 	 * Find an IRE which matches the destination and the outgoing
24665 	 * queue (i.e. the outgoing interface.)
24666 	 */
24667 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
24668 		dst = ipif->ipif_pp_dst_addr;
24669 	else
24670 		dst = ipha->ipha_dst;
24671 	/*
24672 	 * The source address has already been initialized by the
24673 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
24674 	 * be sufficient rather than MATCH_IRE_IPIF.
24675 	 *
24676 	 * This function is used for sending IGMP packets. We need
24677 	 * to make sure that we send the packet out of the interface
24678 	 * (ipif->ipif_ill) where we joined the group. This is to
24679 	 * prevent from switches doing IGMP snooping to send us multicast
24680 	 * packets for a given group on the interface we have joined.
24681 	 * If we can't find an ire, igmp_sendpkt has already initialized
24682 	 * ipsec_out_attach_if so that this will not be load spread in
24683 	 * ip_newroute_ipif.
24684 	 */
24685 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
24686 	    MATCH_IRE_ILL);
24687 	if (!ire) {
24688 		/*
24689 		 * Mark this packet to make it be delivered to
24690 		 * ip_wput_ire after the new ire has been
24691 		 * created.
24692 		 */
24693 		mp->b_prev = NULL;
24694 		mp->b_next = NULL;
24695 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
24696 		    zoneid);
24697 		return;
24698 	}
24699 
24700 	/*
24701 	 * Honor the RTF_SETSRC flag; this is the only case
24702 	 * where we force this addr whatever the current src addr is,
24703 	 * because this address is set by igmp_sendpkt(), and
24704 	 * cannot be specified by any user.
24705 	 */
24706 	if (ire->ire_flags & RTF_SETSRC) {
24707 		ipha->ipha_src = ire->ire_src_addr;
24708 	}
24709 
24710 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
24711 }
24712 
24713 /*
24714  * NOTE : This function does not ire_refrele the ire argument passed in.
24715  *
24716  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
24717  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
24718  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
24719  * the ire_lock to access the nce_fp_mp in this case.
24720  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
24721  * prepending a fastpath message IPQoS processing must precede it, we also set
24722  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
24723  * (IPQoS might have set the b_band for CoS marking).
24724  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
24725  * must follow it so that IPQoS can mark the dl_priority field for CoS
24726  * marking, if needed.
24727  */
24728 static mblk_t *
24729 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
24730 {
24731 	uint_t	hlen;
24732 	ipha_t *ipha;
24733 	mblk_t *mp1;
24734 	boolean_t qos_done = B_FALSE;
24735 	uchar_t	*ll_hdr;
24736 
24737 #define	rptr	((uchar_t *)ipha)
24738 
24739 	ipha = (ipha_t *)mp->b_rptr;
24740 	hlen = 0;
24741 	LOCK_IRE_FP_MP(ire);
24742 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
24743 		ASSERT(DB_TYPE(mp1) == M_DATA);
24744 		/* Initiate IPPF processing */
24745 		if ((proc != 0) && IPP_ENABLED(proc)) {
24746 			UNLOCK_IRE_FP_MP(ire);
24747 			ip_process(proc, &mp, ill_index);
24748 			if (mp == NULL)
24749 				return (NULL);
24750 
24751 			ipha = (ipha_t *)mp->b_rptr;
24752 			LOCK_IRE_FP_MP(ire);
24753 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
24754 				qos_done = B_TRUE;
24755 				goto no_fp_mp;
24756 			}
24757 			ASSERT(DB_TYPE(mp1) == M_DATA);
24758 		}
24759 		hlen = MBLKL(mp1);
24760 		/*
24761 		 * Check if we have enough room to prepend fastpath
24762 		 * header
24763 		 */
24764 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
24765 			ll_hdr = rptr - hlen;
24766 			bcopy(mp1->b_rptr, ll_hdr, hlen);
24767 			/*
24768 			 * Set the b_rptr to the start of the link layer
24769 			 * header
24770 			 */
24771 			mp->b_rptr = ll_hdr;
24772 			mp1 = mp;
24773 		} else {
24774 			mp1 = copyb(mp1);
24775 			if (mp1 == NULL)
24776 				goto unlock_err;
24777 			mp1->b_band = mp->b_band;
24778 			mp1->b_cont = mp;
24779 			/*
24780 			 * certain system generated traffic may not
24781 			 * have cred/label in ip header block. This
24782 			 * is true even for a labeled system. But for
24783 			 * labeled traffic, inherit the label in the
24784 			 * new header.
24785 			 */
24786 			if (DB_CRED(mp) != NULL)
24787 				mblk_setcred(mp1, DB_CRED(mp));
24788 			/*
24789 			 * XXX disable ICK_VALID and compute checksum
24790 			 * here; can happen if nce_fp_mp changes and
24791 			 * it can't be copied now due to insufficient
24792 			 * space. (unlikely, fp mp can change, but it
24793 			 * does not increase in length)
24794 			 */
24795 		}
24796 		UNLOCK_IRE_FP_MP(ire);
24797 	} else {
24798 no_fp_mp:
24799 		mp1 = copyb(ire->ire_nce->nce_res_mp);
24800 		if (mp1 == NULL) {
24801 unlock_err:
24802 			UNLOCK_IRE_FP_MP(ire);
24803 			freemsg(mp);
24804 			return (NULL);
24805 		}
24806 		UNLOCK_IRE_FP_MP(ire);
24807 		mp1->b_cont = mp;
24808 		/*
24809 		 * certain system generated traffic may not
24810 		 * have cred/label in ip header block. This
24811 		 * is true even for a labeled system. But for
24812 		 * labeled traffic, inherit the label in the
24813 		 * new header.
24814 		 */
24815 		if (DB_CRED(mp) != NULL)
24816 			mblk_setcred(mp1, DB_CRED(mp));
24817 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
24818 			ip_process(proc, &mp1, ill_index);
24819 			if (mp1 == NULL)
24820 				return (NULL);
24821 		}
24822 	}
24823 	return (mp1);
24824 #undef rptr
24825 }
24826 
24827 /*
24828  * Finish the outbound IPsec processing for an IPv6 packet. This function
24829  * is called from ipsec_out_process() if the IPsec packet was processed
24830  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24831  * asynchronously.
24832  */
24833 void
24834 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
24835     ire_t *ire_arg)
24836 {
24837 	in6_addr_t *v6dstp;
24838 	ire_t *ire;
24839 	mblk_t *mp;
24840 	ip6_t *ip6h1;
24841 	uint_t	ill_index;
24842 	ipsec_out_t *io;
24843 	boolean_t attach_if, hwaccel;
24844 	uint32_t flags = IP6_NO_IPPOLICY;
24845 	int match_flags;
24846 	zoneid_t zoneid;
24847 	boolean_t ill_need_rele = B_FALSE;
24848 	boolean_t ire_need_rele = B_FALSE;
24849 
24850 	mp = ipsec_mp->b_cont;
24851 	ip6h1 = (ip6_t *)mp->b_rptr;
24852 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24853 	ill_index = io->ipsec_out_ill_index;
24854 	if (io->ipsec_out_reachable) {
24855 		flags |= IPV6_REACHABILITY_CONFIRMATION;
24856 	}
24857 	attach_if = io->ipsec_out_attach_if;
24858 	hwaccel = io->ipsec_out_accelerated;
24859 	zoneid = io->ipsec_out_zoneid;
24860 	ASSERT(zoneid != ALL_ZONES);
24861 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24862 	/* Multicast addresses should have non-zero ill_index. */
24863 	v6dstp = &ip6h->ip6_dst;
24864 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
24865 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
24866 	ASSERT(!attach_if || ill_index != 0);
24867 	if (ill_index != 0) {
24868 		if (ill == NULL) {
24869 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
24870 			    B_TRUE);
24871 
24872 			/* Failure case frees things for us. */
24873 			if (ill == NULL)
24874 				return;
24875 
24876 			ill_need_rele = B_TRUE;
24877 		}
24878 		/*
24879 		 * If this packet needs to go out on a particular interface
24880 		 * honor it.
24881 		 */
24882 		if (attach_if) {
24883 			match_flags = MATCH_IRE_ILL;
24884 
24885 			/*
24886 			 * Check if we need an ire that will not be
24887 			 * looked up by anybody else i.e. HIDDEN.
24888 			 */
24889 			if (ill_is_probeonly(ill)) {
24890 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24891 			}
24892 		}
24893 	}
24894 	ASSERT(mp != NULL);
24895 
24896 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
24897 		boolean_t unspec_src;
24898 		ipif_t	*ipif;
24899 
24900 		/*
24901 		 * Use the ill_index to get the right ill.
24902 		 */
24903 		unspec_src = io->ipsec_out_unspec_src;
24904 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24905 		if (ipif == NULL) {
24906 			if (ill_need_rele)
24907 				ill_refrele(ill);
24908 			freemsg(ipsec_mp);
24909 			return;
24910 		}
24911 
24912 		if (ire_arg != NULL) {
24913 			ire = ire_arg;
24914 		} else {
24915 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24916 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24917 			ire_need_rele = B_TRUE;
24918 		}
24919 		if (ire != NULL) {
24920 			ipif_refrele(ipif);
24921 			/*
24922 			 * XXX Do the multicast forwarding now, as the IPSEC
24923 			 * processing has been done.
24924 			 */
24925 			goto send;
24926 		}
24927 
24928 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
24929 		mp->b_prev = NULL;
24930 		mp->b_next = NULL;
24931 
24932 		/*
24933 		 * If the IPsec packet was processed asynchronously,
24934 		 * drop it now.
24935 		 */
24936 		if (q == NULL) {
24937 			if (ill_need_rele)
24938 				ill_refrele(ill);
24939 			freemsg(ipsec_mp);
24940 			return;
24941 		}
24942 
24943 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
24944 		    unspec_src, zoneid);
24945 		ipif_refrele(ipif);
24946 	} else {
24947 		if (attach_if) {
24948 			ipif_t	*ipif;
24949 
24950 			ipif = ipif_get_next_ipif(NULL, ill);
24951 			if (ipif == NULL) {
24952 				if (ill_need_rele)
24953 					ill_refrele(ill);
24954 				freemsg(ipsec_mp);
24955 				return;
24956 			}
24957 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24958 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24959 			ire_need_rele = B_TRUE;
24960 			ipif_refrele(ipif);
24961 		} else {
24962 			if (ire_arg != NULL) {
24963 				ire = ire_arg;
24964 			} else {
24965 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
24966 				ire_need_rele = B_TRUE;
24967 			}
24968 		}
24969 		if (ire != NULL)
24970 			goto send;
24971 		/*
24972 		 * ire disappeared underneath.
24973 		 *
24974 		 * What we need to do here is the ip_newroute
24975 		 * logic to get the ire without doing the IPSEC
24976 		 * processing. Follow the same old path. But this
24977 		 * time, ip_wput or ire_add_then_send will call us
24978 		 * directly as all the IPSEC operations are done.
24979 		 */
24980 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
24981 		mp->b_prev = NULL;
24982 		mp->b_next = NULL;
24983 
24984 		/*
24985 		 * If the IPsec packet was processed asynchronously,
24986 		 * drop it now.
24987 		 */
24988 		if (q == NULL) {
24989 			if (ill_need_rele)
24990 				ill_refrele(ill);
24991 			freemsg(ipsec_mp);
24992 			return;
24993 		}
24994 
24995 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
24996 		    zoneid);
24997 	}
24998 	if (ill != NULL && ill_need_rele)
24999 		ill_refrele(ill);
25000 	return;
25001 send:
25002 	if (ill != NULL && ill_need_rele)
25003 		ill_refrele(ill);
25004 
25005 	/* Local delivery */
25006 	if (ire->ire_stq == NULL) {
25007 		ill_t	*out_ill;
25008 		ASSERT(q != NULL);
25009 
25010 		/* PFHooks: LOOPBACK_OUT */
25011 		out_ill = ire->ire_ipif->ipif_ill;
25012 
25013 		DTRACE_PROBE4(ip6__loopback__out__start,
25014 		    ill_t *, NULL, ill_t *, out_ill,
25015 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25016 
25017 		FW_HOOKS6(ip6_loopback_out_event, ipv6firewall_loopback_out,
25018 		    NULL, out_ill, ip6h1, ipsec_mp, mp);
25019 
25020 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25021 
25022 		if (ipsec_mp != NULL)
25023 			ip_wput_local_v6(RD(q), out_ill,
25024 			    ip6h, ipsec_mp, ire, 0);
25025 		if (ire_need_rele)
25026 			ire_refrele(ire);
25027 		return;
25028 	}
25029 	/*
25030 	 * Everything is done. Send it out on the wire.
25031 	 * We force the insertion of a fragment header using the
25032 	 * IPH_FRAG_HDR flag in two cases:
25033 	 * - after reception of an ICMPv6 "packet too big" message
25034 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25035 	 * - for multirouted IPv6 packets, so that the receiver can
25036 	 *   discard duplicates according to their fragment identifier
25037 	 */
25038 	/* XXX fix flow control problems. */
25039 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25040 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25041 		if (hwaccel) {
25042 			/*
25043 			 * hardware acceleration does not handle these
25044 			 * "slow path" cases.
25045 			 */
25046 			/* IPsec KSTATS: should bump bean counter here. */
25047 			if (ire_need_rele)
25048 				ire_refrele(ire);
25049 			freemsg(ipsec_mp);
25050 			return;
25051 		}
25052 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25053 		    (mp->b_cont ? msgdsize(mp) :
25054 		    mp->b_wptr - (uchar_t *)ip6h)) {
25055 			/* IPsec KSTATS: should bump bean counter here. */
25056 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25057 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25058 			    msgdsize(mp)));
25059 			if (ire_need_rele)
25060 				ire_refrele(ire);
25061 			freemsg(ipsec_mp);
25062 			return;
25063 		}
25064 		ASSERT(mp->b_prev == NULL);
25065 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25066 		    ntohs(ip6h->ip6_plen) +
25067 		    IPV6_HDR_LEN, ire->ire_max_frag));
25068 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25069 		    ire->ire_max_frag);
25070 	} else {
25071 		UPDATE_OB_PKT_COUNT(ire);
25072 		ire->ire_last_used_time = lbolt;
25073 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25074 	}
25075 	if (ire_need_rele)
25076 		ire_refrele(ire);
25077 	freeb(ipsec_mp);
25078 }
25079 
25080 void
25081 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25082 {
25083 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25084 	da_ipsec_t *hada;	/* data attributes */
25085 	ill_t *ill = (ill_t *)q->q_ptr;
25086 
25087 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25088 
25089 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25090 		/* IPsec KSTATS: Bump lose counter here! */
25091 		freemsg(mp);
25092 		return;
25093 	}
25094 
25095 	/*
25096 	 * It's an IPsec packet that must be
25097 	 * accelerated by the Provider, and the
25098 	 * outbound ill is IPsec acceleration capable.
25099 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25100 	 * to the ill.
25101 	 * IPsec KSTATS: should bump packet counter here.
25102 	 */
25103 
25104 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25105 	if (hada_mp == NULL) {
25106 		/* IPsec KSTATS: should bump packet counter here. */
25107 		freemsg(mp);
25108 		return;
25109 	}
25110 
25111 	hada_mp->b_datap->db_type = M_CTL;
25112 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25113 	hada_mp->b_cont = mp;
25114 
25115 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25116 	bzero(hada, sizeof (da_ipsec_t));
25117 	hada->da_type = IPHADA_M_CTL;
25118 
25119 	putnext(q, hada_mp);
25120 }
25121 
25122 /*
25123  * Finish the outbound IPsec processing. This function is called from
25124  * ipsec_out_process() if the IPsec packet was processed
25125  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25126  * asynchronously.
25127  */
25128 void
25129 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25130     ire_t *ire_arg)
25131 {
25132 	uint32_t v_hlen_tos_len;
25133 	ipaddr_t	dst;
25134 	ipif_t	*ipif = NULL;
25135 	ire_t *ire;
25136 	ire_t *ire1 = NULL;
25137 	mblk_t *next_mp = NULL;
25138 	uint32_t max_frag;
25139 	boolean_t multirt_send = B_FALSE;
25140 	mblk_t *mp;
25141 	mblk_t *mp1;
25142 	ipha_t *ipha1;
25143 	uint_t	ill_index;
25144 	ipsec_out_t *io;
25145 	boolean_t attach_if;
25146 	int match_flags, offset;
25147 	irb_t *irb = NULL;
25148 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25149 	zoneid_t zoneid;
25150 	uint32_t cksum;
25151 	uint16_t *up;
25152 	ipxmit_state_t	pktxmit_state;
25153 #ifdef	_BIG_ENDIAN
25154 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25155 #else
25156 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25157 #endif
25158 
25159 	mp = ipsec_mp->b_cont;
25160 	ipha1 = (ipha_t *)mp->b_rptr;
25161 	ASSERT(mp != NULL);
25162 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25163 	dst = ipha->ipha_dst;
25164 
25165 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25166 	ill_index = io->ipsec_out_ill_index;
25167 	attach_if = io->ipsec_out_attach_if;
25168 	zoneid = io->ipsec_out_zoneid;
25169 	ASSERT(zoneid != ALL_ZONES);
25170 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25171 	if (ill_index != 0) {
25172 		if (ill == NULL) {
25173 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25174 			    ill_index, B_FALSE);
25175 
25176 			/* Failure case frees things for us. */
25177 			if (ill == NULL)
25178 				return;
25179 
25180 			ill_need_rele = B_TRUE;
25181 		}
25182 		/*
25183 		 * If this packet needs to go out on a particular interface
25184 		 * honor it.
25185 		 */
25186 		if (attach_if) {
25187 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25188 
25189 			/*
25190 			 * Check if we need an ire that will not be
25191 			 * looked up by anybody else i.e. HIDDEN.
25192 			 */
25193 			if (ill_is_probeonly(ill)) {
25194 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25195 			}
25196 		}
25197 	}
25198 
25199 	if (CLASSD(dst)) {
25200 		boolean_t conn_dontroute;
25201 		/*
25202 		 * Use the ill_index to get the right ipif.
25203 		 */
25204 		conn_dontroute = io->ipsec_out_dontroute;
25205 		if (ill_index == 0)
25206 			ipif = ipif_lookup_group(dst, zoneid);
25207 		else
25208 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25209 		if (ipif == NULL) {
25210 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25211 			    " multicast\n"));
25212 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
25213 			freemsg(ipsec_mp);
25214 			goto done;
25215 		}
25216 		/*
25217 		 * ipha_src has already been intialized with the
25218 		 * value of the ipif in ip_wput. All we need now is
25219 		 * an ire to send this downstream.
25220 		 */
25221 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25222 		    MBLK_GETLABEL(mp), match_flags);
25223 		if (ire != NULL) {
25224 			ill_t *ill1;
25225 			/*
25226 			 * Do the multicast forwarding now, as the IPSEC
25227 			 * processing has been done.
25228 			 */
25229 			if (ip_g_mrouter && !conn_dontroute &&
25230 			    (ill1 = ire_to_ill(ire))) {
25231 				if (ip_mforward(ill1, ipha, mp)) {
25232 					freemsg(ipsec_mp);
25233 					ip1dbg(("ip_wput_ipsec_out: mforward "
25234 					    "failed\n"));
25235 					ire_refrele(ire);
25236 					goto done;
25237 				}
25238 			}
25239 			goto send;
25240 		}
25241 
25242 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25243 		mp->b_prev = NULL;
25244 		mp->b_next = NULL;
25245 
25246 		/*
25247 		 * If the IPsec packet was processed asynchronously,
25248 		 * drop it now.
25249 		 */
25250 		if (q == NULL) {
25251 			freemsg(ipsec_mp);
25252 			goto done;
25253 		}
25254 
25255 		/*
25256 		 * We may be using a wrong ipif to create the ire.
25257 		 * But it is okay as the source address is assigned
25258 		 * for the packet already. Next outbound packet would
25259 		 * create the IRE with the right IPIF in ip_wput.
25260 		 *
25261 		 * Also handle RTF_MULTIRT routes.
25262 		 */
25263 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25264 		    zoneid);
25265 	} else {
25266 		if (attach_if) {
25267 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25268 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25269 		} else {
25270 			if (ire_arg != NULL) {
25271 				ire = ire_arg;
25272 				ire_need_rele = B_FALSE;
25273 			} else {
25274 				ire = ire_cache_lookup(dst, zoneid,
25275 				    MBLK_GETLABEL(mp));
25276 			}
25277 		}
25278 		if (ire != NULL) {
25279 			goto send;
25280 		}
25281 
25282 		/*
25283 		 * ire disappeared underneath.
25284 		 *
25285 		 * What we need to do here is the ip_newroute
25286 		 * logic to get the ire without doing the IPSEC
25287 		 * processing. Follow the same old path. But this
25288 		 * time, ip_wput or ire_add_then_put will call us
25289 		 * directly as all the IPSEC operations are done.
25290 		 */
25291 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25292 		mp->b_prev = NULL;
25293 		mp->b_next = NULL;
25294 
25295 		/*
25296 		 * If the IPsec packet was processed asynchronously,
25297 		 * drop it now.
25298 		 */
25299 		if (q == NULL) {
25300 			freemsg(ipsec_mp);
25301 			goto done;
25302 		}
25303 
25304 		/*
25305 		 * Since we're going through ip_newroute() again, we
25306 		 * need to make sure we don't:
25307 		 *
25308 		 *	1.) Trigger the ASSERT() with the ipha_ident
25309 		 *	    overloading.
25310 		 *	2.) Redo transport-layer checksumming, since we've
25311 		 *	    already done all that to get this far.
25312 		 *
25313 		 * The easiest way not do either of the above is to set
25314 		 * the ipha_ident field to IP_HDR_INCLUDED.
25315 		 */
25316 		ipha->ipha_ident = IP_HDR_INCLUDED;
25317 		ip_newroute(q, ipsec_mp, dst, NULL,
25318 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid);
25319 	}
25320 	goto done;
25321 send:
25322 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
25323 		/*
25324 		 * ESP NAT-Traversal packet.
25325 		 *
25326 		 * Just do software checksum for now.
25327 		 */
25328 
25329 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
25330 		IP_STAT(ip_out_sw_cksum);
25331 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
25332 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
25333 #define	iphs	((uint16_t *)ipha)
25334 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
25335 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
25336 		    IP_SIMPLE_HDR_LENGTH);
25337 #undef iphs
25338 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
25339 			cksum = 0xFFFF;
25340 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
25341 			if (mp1->b_wptr - mp1->b_rptr >=
25342 			    offset + sizeof (uint16_t)) {
25343 				up = (uint16_t *)(mp1->b_rptr + offset);
25344 				*up = cksum;
25345 				break;	/* out of for loop */
25346 			} else {
25347 				offset -= (mp->b_wptr - mp->b_rptr);
25348 			}
25349 	} /* Otherwise, just keep the all-zero checksum. */
25350 
25351 	if (ire->ire_stq == NULL) {
25352 		ill_t	*out_ill;
25353 		/*
25354 		 * Loopbacks go through ip_wput_local except for one case.
25355 		 * We come here if we generate a icmp_frag_needed message
25356 		 * after IPSEC processing is over. When this function calls
25357 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25358 		 * icmp_frag_needed. The message generated comes back here
25359 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25360 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25361 		 * source address as it is usually set in ip_wput_ire. As
25362 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25363 		 * and we end up here. We can't enter ip_wput_ire once the
25364 		 * IPSEC processing is over and hence we need to do it here.
25365 		 */
25366 		ASSERT(q != NULL);
25367 		UPDATE_OB_PKT_COUNT(ire);
25368 		ire->ire_last_used_time = lbolt;
25369 		if (ipha->ipha_src == 0)
25370 			ipha->ipha_src = ire->ire_src_addr;
25371 
25372 		/* PFHooks: LOOPBACK_OUT */
25373 		out_ill = ire->ire_ipif->ipif_ill;
25374 
25375 		DTRACE_PROBE4(ip4__loopback__out__start,
25376 		    ill_t *, NULL, ill_t *, out_ill,
25377 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25378 
25379 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
25380 		    NULL, out_ill, ipha1, ipsec_mp, mp);
25381 
25382 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25383 
25384 		if (ipsec_mp != NULL)
25385 			ip_wput_local(RD(q), out_ill,
25386 			    ipha, ipsec_mp, ire, 0, zoneid);
25387 		if (ire_need_rele)
25388 			ire_refrele(ire);
25389 		goto done;
25390 	}
25391 
25392 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25393 		/*
25394 		 * We are through with IPSEC processing.
25395 		 * Fragment this and send it on the wire.
25396 		 */
25397 		if (io->ipsec_out_accelerated) {
25398 			/*
25399 			 * The packet has been accelerated but must
25400 			 * be fragmented. This should not happen
25401 			 * since AH and ESP must not accelerate
25402 			 * packets that need fragmentation, however
25403 			 * the configuration could have changed
25404 			 * since the AH or ESP processing.
25405 			 * Drop packet.
25406 			 * IPsec KSTATS: bump bean counter here.
25407 			 */
25408 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25409 			    "fragmented accelerated packet!\n"));
25410 			freemsg(ipsec_mp);
25411 		} else {
25412 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid);
25413 		}
25414 		if (ire_need_rele)
25415 			ire_refrele(ire);
25416 		goto done;
25417 	}
25418 
25419 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25420 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25421 	    (void *)ire->ire_ipif, (void *)ipif));
25422 
25423 	/*
25424 	 * Multiroute the secured packet, unless IPsec really
25425 	 * requires the packet to go out only through a particular
25426 	 * interface.
25427 	 */
25428 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
25429 		ire_t *first_ire;
25430 		irb = ire->ire_bucket;
25431 		ASSERT(irb != NULL);
25432 		/*
25433 		 * This ire has been looked up as the one that
25434 		 * goes through the given ipif;
25435 		 * make sure we do not omit any other multiroute ire
25436 		 * that may be present in the bucket before this one.
25437 		 */
25438 		IRB_REFHOLD(irb);
25439 		for (first_ire = irb->irb_ire;
25440 		    first_ire != NULL;
25441 		    first_ire = first_ire->ire_next) {
25442 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25443 			    (first_ire->ire_addr == ire->ire_addr) &&
25444 			    !(first_ire->ire_marks &
25445 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
25446 				break;
25447 		}
25448 
25449 		if ((first_ire != NULL) && (first_ire != ire)) {
25450 			/*
25451 			 * Don't change the ire if the packet must
25452 			 * be fragmented if sent via this new one.
25453 			 */
25454 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25455 				IRE_REFHOLD(first_ire);
25456 				if (ire_need_rele)
25457 					ire_refrele(ire);
25458 				else
25459 					ire_need_rele = B_TRUE;
25460 				ire = first_ire;
25461 			}
25462 		}
25463 		IRB_REFRELE(irb);
25464 
25465 		multirt_send = B_TRUE;
25466 		max_frag = ire->ire_max_frag;
25467 	} else {
25468 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
25469 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25470 			    "flag, attach_if %d\n", attach_if));
25471 		}
25472 	}
25473 
25474 	/*
25475 	 * In most cases, the emission loop below is entered only once.
25476 	 * Only in the case where the ire holds the RTF_MULTIRT
25477 	 * flag, we loop to process all RTF_MULTIRT ires in the
25478 	 * bucket, and send the packet through all crossed
25479 	 * RTF_MULTIRT routes.
25480 	 */
25481 	do {
25482 		if (multirt_send) {
25483 			/*
25484 			 * ire1 holds here the next ire to process in the
25485 			 * bucket. If multirouting is expected,
25486 			 * any non-RTF_MULTIRT ire that has the
25487 			 * right destination address is ignored.
25488 			 */
25489 			ASSERT(irb != NULL);
25490 			IRB_REFHOLD(irb);
25491 			for (ire1 = ire->ire_next;
25492 			    ire1 != NULL;
25493 			    ire1 = ire1->ire_next) {
25494 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
25495 					continue;
25496 				if (ire1->ire_addr != ire->ire_addr)
25497 					continue;
25498 				if (ire1->ire_marks &
25499 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
25500 					continue;
25501 				/* No loopback here */
25502 				if (ire1->ire_stq == NULL)
25503 					continue;
25504 				/*
25505 				 * Ensure we do not exceed the MTU
25506 				 * of the next route.
25507 				 */
25508 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
25509 					ip_multirt_bad_mtu(ire1, max_frag);
25510 					continue;
25511 				}
25512 
25513 				IRE_REFHOLD(ire1);
25514 				break;
25515 			}
25516 			IRB_REFRELE(irb);
25517 			if (ire1 != NULL) {
25518 				/*
25519 				 * We are in a multiple send case, need to
25520 				 * make a copy of the packet.
25521 				 */
25522 				next_mp = copymsg(ipsec_mp);
25523 				if (next_mp == NULL) {
25524 					ire_refrele(ire1);
25525 					ire1 = NULL;
25526 				}
25527 			}
25528 		}
25529 		/*
25530 		 * Everything is done. Send it out on the wire
25531 		 *
25532 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
25533 		 * either send it on the wire or, in the case of
25534 		 * HW acceleration, call ipsec_hw_putnext.
25535 		 */
25536 		if (ire->ire_nce &&
25537 		    ire->ire_nce->nce_state != ND_REACHABLE) {
25538 			DTRACE_PROBE2(ip__wput__ipsec__bail,
25539 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
25540 			/*
25541 			 * If ire's link-layer is unresolved (this
25542 			 * would only happen if the incomplete ire
25543 			 * was added to cachetable via forwarding path)
25544 			 * don't bother going to ip_xmit_v4. Just drop the
25545 			 * packet.
25546 			 * There is a slight risk here, in that, if we
25547 			 * have the forwarding path create an incomplete
25548 			 * IRE, then until the IRE is completed, any
25549 			 * transmitted IPSEC packets will be dropped
25550 			 * instead of being queued waiting for resolution.
25551 			 *
25552 			 * But the likelihood of a forwarding packet and a wput
25553 			 * packet sending to the same dst at the same time
25554 			 * and there not yet be an ARP entry for it is small.
25555 			 * Furthermore, if this actually happens, it might
25556 			 * be likely that wput would generate multiple
25557 			 * packets (and forwarding would also have a train
25558 			 * of packets) for that destination. If this is
25559 			 * the case, some of them would have been dropped
25560 			 * anyway, since ARP only queues a few packets while
25561 			 * waiting for resolution
25562 			 *
25563 			 * NOTE: We should really call ip_xmit_v4,
25564 			 * and let it queue the packet and send the
25565 			 * ARP query and have ARP come back thus:
25566 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
25567 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
25568 			 * hw accel work. But it's too complex to get
25569 			 * the IPsec hw  acceleration approach to fit
25570 			 * well with ip_xmit_v4 doing ARP without
25571 			 * doing IPSEC simplification. For now, we just
25572 			 * poke ip_xmit_v4 to trigger the arp resolve, so
25573 			 * that we can continue with the send on the next
25574 			 * attempt.
25575 			 *
25576 			 * XXX THis should be revisited, when
25577 			 * the IPsec/IP interaction is cleaned up
25578 			 */
25579 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
25580 			    " - dropping packet\n"));
25581 			freemsg(ipsec_mp);
25582 			/*
25583 			 * Call ip_xmit_v4() to trigger ARP query
25584 			 * in case the nce_state is ND_INITIAL
25585 			 */
25586 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
25587 			goto drop_pkt;
25588 		}
25589 
25590 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
25591 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
25592 		    mblk_t *, mp);
25593 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
25594 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp);
25595 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
25596 		if (mp == NULL)
25597 			goto drop_pkt;
25598 
25599 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
25600 		pktxmit_state = ip_xmit_v4(mp, ire,
25601 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
25602 
25603 		if ((pktxmit_state ==  SEND_FAILED) ||
25604 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
25605 
25606 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
25607 drop_pkt:
25608 			BUMP_MIB(&ip_mib, ipOutDiscards);
25609 			if (ire_need_rele)
25610 				ire_refrele(ire);
25611 			if (ire1 != NULL) {
25612 				ire_refrele(ire1);
25613 				freemsg(next_mp);
25614 			}
25615 			goto done;
25616 		}
25617 
25618 		freeb(ipsec_mp);
25619 		if (ire_need_rele)
25620 			ire_refrele(ire);
25621 
25622 		if (ire1 != NULL) {
25623 			ire = ire1;
25624 			ire_need_rele = B_TRUE;
25625 			ASSERT(next_mp);
25626 			ipsec_mp = next_mp;
25627 			mp = ipsec_mp->b_cont;
25628 			ire1 = NULL;
25629 			next_mp = NULL;
25630 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
25631 		} else {
25632 			multirt_send = B_FALSE;
25633 		}
25634 	} while (multirt_send);
25635 done:
25636 	if (ill != NULL && ill_need_rele)
25637 		ill_refrele(ill);
25638 	if (ipif != NULL)
25639 		ipif_refrele(ipif);
25640 }
25641 
25642 /*
25643  * Get the ill corresponding to the specified ire, and compare its
25644  * capabilities with the protocol and algorithms specified by the
25645  * the SA obtained from ipsec_out. If they match, annotate the
25646  * ipsec_out structure to indicate that the packet needs acceleration.
25647  *
25648  *
25649  * A packet is eligible for outbound hardware acceleration if the
25650  * following conditions are satisfied:
25651  *
25652  * 1. the packet will not be fragmented
25653  * 2. the provider supports the algorithm
25654  * 3. there is no pending control message being exchanged
25655  * 4. snoop is not attached
25656  * 5. the destination address is not a broadcast or multicast address.
25657  *
25658  * Rationale:
25659  *	- Hardware drivers do not support fragmentation with
25660  *	  the current interface.
25661  *	- snoop, multicast, and broadcast may result in exposure of
25662  *	  a cleartext datagram.
25663  * We check all five of these conditions here.
25664  *
25665  * XXX would like to nuke "ire_t *" parameter here; problem is that
25666  * IRE is only way to figure out if a v4 address is a broadcast and
25667  * thus ineligible for acceleration...
25668  */
25669 static void
25670 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
25671 {
25672 	ipsec_out_t *io;
25673 	mblk_t *data_mp;
25674 	uint_t plen, overhead;
25675 
25676 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
25677 		return;
25678 
25679 	if (ill == NULL)
25680 		return;
25681 
25682 	/*
25683 	 * Destination address is a broadcast or multicast.  Punt.
25684 	 */
25685 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
25686 	    IRE_LOCAL)))
25687 		return;
25688 
25689 	data_mp = ipsec_mp->b_cont;
25690 
25691 	if (ill->ill_isv6) {
25692 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
25693 
25694 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
25695 			return;
25696 
25697 		plen = ip6h->ip6_plen;
25698 	} else {
25699 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
25700 
25701 		if (CLASSD(ipha->ipha_dst))
25702 			return;
25703 
25704 		plen = ipha->ipha_length;
25705 	}
25706 	/*
25707 	 * Is there a pending DLPI control message being exchanged
25708 	 * between IP/IPsec and the DLS Provider? If there is, it
25709 	 * could be a SADB update, and the state of the DLS Provider
25710 	 * SADB might not be in sync with the SADB maintained by
25711 	 * IPsec. To avoid dropping packets or using the wrong keying
25712 	 * material, we do not accelerate this packet.
25713 	 */
25714 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
25715 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25716 		    "ill_dlpi_pending! don't accelerate packet\n"));
25717 		return;
25718 	}
25719 
25720 	/*
25721 	 * Is the Provider in promiscous mode? If it does, we don't
25722 	 * accelerate the packet since it will bounce back up to the
25723 	 * listeners in the clear.
25724 	 */
25725 	if (ill->ill_promisc_on_phys) {
25726 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25727 		    "ill in promiscous mode, don't accelerate packet\n"));
25728 		return;
25729 	}
25730 
25731 	/*
25732 	 * Will the packet require fragmentation?
25733 	 */
25734 
25735 	/*
25736 	 * IPsec ESP note: this is a pessimistic estimate, but the same
25737 	 * as is used elsewhere.
25738 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
25739 	 *	+ 2-byte trailer
25740 	 */
25741 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
25742 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
25743 
25744 	if ((plen + overhead) > ill->ill_max_mtu)
25745 		return;
25746 
25747 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25748 
25749 	/*
25750 	 * Can the ill accelerate this IPsec protocol and algorithm
25751 	 * specified by the SA?
25752 	 */
25753 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
25754 	    ill->ill_isv6, sa)) {
25755 		return;
25756 	}
25757 
25758 	/*
25759 	 * Tell AH or ESP that the outbound ill is capable of
25760 	 * accelerating this packet.
25761 	 */
25762 	io->ipsec_out_is_capab_ill = B_TRUE;
25763 }
25764 
25765 /*
25766  * Select which AH & ESP SA's to use (if any) for the outbound packet.
25767  *
25768  * If this function returns B_TRUE, the requested SA's have been filled
25769  * into the ipsec_out_*_sa pointers.
25770  *
25771  * If the function returns B_FALSE, the packet has been "consumed", most
25772  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
25773  *
25774  * The SA references created by the protocol-specific "select"
25775  * function will be released when the ipsec_mp is freed, thanks to the
25776  * ipsec_out_free destructor -- see spd.c.
25777  */
25778 static boolean_t
25779 ipsec_out_select_sa(mblk_t *ipsec_mp)
25780 {
25781 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
25782 	ipsec_out_t *io;
25783 	ipsec_policy_t *pp;
25784 	ipsec_action_t *ap;
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 
25789 	if (!io->ipsec_out_secure) {
25790 		/*
25791 		 * We came here by mistake.
25792 		 * Don't bother with ipsec processing
25793 		 * We should "discourage" this path in the future.
25794 		 */
25795 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25796 		return (B_FALSE);
25797 	}
25798 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25799 	ASSERT((io->ipsec_out_policy != NULL) ||
25800 	    (io->ipsec_out_act != NULL));
25801 
25802 	ASSERT(io->ipsec_out_failed == B_FALSE);
25803 
25804 	/*
25805 	 * IPSEC processing has started.
25806 	 */
25807 	io->ipsec_out_proc_begin = B_TRUE;
25808 	ap = io->ipsec_out_act;
25809 	if (ap == NULL) {
25810 		pp = io->ipsec_out_policy;
25811 		ASSERT(pp != NULL);
25812 		ap = pp->ipsp_act;
25813 		ASSERT(ap != NULL);
25814 	}
25815 
25816 	/*
25817 	 * We have an action.  now, let's select SA's.
25818 	 * (In the future, we can cache this in the conn_t..)
25819 	 */
25820 	if (ap->ipa_want_esp) {
25821 		if (io->ipsec_out_esp_sa == NULL) {
25822 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
25823 			    IPPROTO_ESP);
25824 		}
25825 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
25826 	}
25827 
25828 	if (ap->ipa_want_ah) {
25829 		if (io->ipsec_out_ah_sa == NULL) {
25830 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
25831 			    IPPROTO_AH);
25832 		}
25833 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
25834 		/*
25835 		 * The ESP and AH processing order needs to be preserved
25836 		 * when both protocols are required (ESP should be applied
25837 		 * before AH for an outbound packet). Force an ESP ACQUIRE
25838 		 * when both ESP and AH are required, and an AH ACQUIRE
25839 		 * is needed.
25840 		 */
25841 		if (ap->ipa_want_esp && need_ah_acquire)
25842 			need_esp_acquire = B_TRUE;
25843 	}
25844 
25845 	/*
25846 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
25847 	 * Release SAs that got referenced, but will not be used until we
25848 	 * acquire _all_ of the SAs we need.
25849 	 */
25850 	if (need_ah_acquire || need_esp_acquire) {
25851 		if (io->ipsec_out_ah_sa != NULL) {
25852 			IPSA_REFRELE(io->ipsec_out_ah_sa);
25853 			io->ipsec_out_ah_sa = NULL;
25854 		}
25855 		if (io->ipsec_out_esp_sa != NULL) {
25856 			IPSA_REFRELE(io->ipsec_out_esp_sa);
25857 			io->ipsec_out_esp_sa = NULL;
25858 		}
25859 
25860 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
25861 		return (B_FALSE);
25862 	}
25863 
25864 	return (B_TRUE);
25865 }
25866 
25867 /*
25868  * Process an IPSEC_OUT message and see what you can
25869  * do with it.
25870  * IPQoS Notes:
25871  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
25872  * IPSec.
25873  * XXX would like to nuke ire_t.
25874  * XXX ill_index better be "real"
25875  */
25876 void
25877 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
25878 {
25879 	ipsec_out_t *io;
25880 	ipsec_policy_t *pp;
25881 	ipsec_action_t *ap;
25882 	ipha_t *ipha;
25883 	ip6_t *ip6h;
25884 	mblk_t *mp;
25885 	ill_t *ill;
25886 	zoneid_t zoneid;
25887 	ipsec_status_t ipsec_rc;
25888 	boolean_t ill_need_rele = B_FALSE;
25889 
25890 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25891 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25892 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25893 	mp = ipsec_mp->b_cont;
25894 
25895 	/*
25896 	 * Initiate IPPF processing. We do it here to account for packets
25897 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
25898 	 * We can check for ipsec_out_proc_begin even for such packets, as
25899 	 * they will always be false (asserted below).
25900 	 */
25901 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
25902 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
25903 		    io->ipsec_out_ill_index : ill_index);
25904 		if (mp == NULL) {
25905 			ip2dbg(("ipsec_out_process: packet dropped "\
25906 			    "during IPPF processing\n"));
25907 			freeb(ipsec_mp);
25908 			BUMP_MIB(&ip_mib, ipOutDiscards);
25909 			return;
25910 		}
25911 	}
25912 
25913 	if (!io->ipsec_out_secure) {
25914 		/*
25915 		 * We came here by mistake.
25916 		 * Don't bother with ipsec processing
25917 		 * Should "discourage" this path in the future.
25918 		 */
25919 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25920 		goto done;
25921 	}
25922 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25923 	ASSERT((io->ipsec_out_policy != NULL) ||
25924 	    (io->ipsec_out_act != NULL));
25925 	ASSERT(io->ipsec_out_failed == B_FALSE);
25926 
25927 	if (!ipsec_loaded()) {
25928 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
25929 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25930 			BUMP_MIB(&ip_mib, ipOutDiscards);
25931 		} else {
25932 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
25933 		}
25934 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
25935 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
25936 		return;
25937 	}
25938 
25939 	/*
25940 	 * IPSEC processing has started.
25941 	 */
25942 	io->ipsec_out_proc_begin = B_TRUE;
25943 	ap = io->ipsec_out_act;
25944 	if (ap == NULL) {
25945 		pp = io->ipsec_out_policy;
25946 		ASSERT(pp != NULL);
25947 		ap = pp->ipsp_act;
25948 		ASSERT(ap != NULL);
25949 	}
25950 
25951 	/*
25952 	 * Save the outbound ill index. When the packet comes back
25953 	 * from IPsec, we make sure the ill hasn't changed or disappeared
25954 	 * before sending it the accelerated packet.
25955 	 */
25956 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
25957 		int ifindex;
25958 		ill = ire_to_ill(ire);
25959 		ifindex = ill->ill_phyint->phyint_ifindex;
25960 		io->ipsec_out_capab_ill_index = ifindex;
25961 	}
25962 
25963 	/*
25964 	 * The order of processing is first insert a IP header if needed.
25965 	 * Then insert the ESP header and then the AH header.
25966 	 */
25967 	if ((io->ipsec_out_se_done == B_FALSE) &&
25968 	    (ap->ipa_want_se)) {
25969 		/*
25970 		 * First get the outer IP header before sending
25971 		 * it to ESP.
25972 		 */
25973 		ipha_t *oipha, *iipha;
25974 		mblk_t *outer_mp, *inner_mp;
25975 
25976 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
25977 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
25978 			    "ipsec_out_process: "
25979 			    "Self-Encapsulation failed: Out of memory\n");
25980 			freemsg(ipsec_mp);
25981 			BUMP_MIB(&ip_mib, ipOutDiscards);
25982 			return;
25983 		}
25984 		inner_mp = ipsec_mp->b_cont;
25985 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
25986 		oipha = (ipha_t *)outer_mp->b_rptr;
25987 		iipha = (ipha_t *)inner_mp->b_rptr;
25988 		*oipha = *iipha;
25989 		outer_mp->b_wptr += sizeof (ipha_t);
25990 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
25991 		    sizeof (ipha_t));
25992 		oipha->ipha_protocol = IPPROTO_ENCAP;
25993 		oipha->ipha_version_and_hdr_length =
25994 		    IP_SIMPLE_HDR_VERSION;
25995 		oipha->ipha_hdr_checksum = 0;
25996 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
25997 		outer_mp->b_cont = inner_mp;
25998 		ipsec_mp->b_cont = outer_mp;
25999 
26000 		io->ipsec_out_se_done = B_TRUE;
26001 		io->ipsec_out_tunnel = B_TRUE;
26002 	}
26003 
26004 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26005 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26006 	    !ipsec_out_select_sa(ipsec_mp))
26007 		return;
26008 
26009 	/*
26010 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26011 	 * to do the heavy lifting.
26012 	 */
26013 	zoneid = io->ipsec_out_zoneid;
26014 	ASSERT(zoneid != ALL_ZONES);
26015 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26016 		ASSERT(io->ipsec_out_esp_sa != NULL);
26017 		io->ipsec_out_esp_done = B_TRUE;
26018 		/*
26019 		 * Note that since hw accel can only apply one transform,
26020 		 * not two, we skip hw accel for ESP if we also have AH
26021 		 * This is an design limitation of the interface
26022 		 * which should be revisited.
26023 		 */
26024 		ASSERT(ire != NULL);
26025 		if (io->ipsec_out_ah_sa == NULL) {
26026 			ill = (ill_t *)ire->ire_stq->q_ptr;
26027 			ipsec_out_is_accelerated(ipsec_mp,
26028 			    io->ipsec_out_esp_sa, ill, ire);
26029 		}
26030 
26031 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26032 		switch (ipsec_rc) {
26033 		case IPSEC_STATUS_SUCCESS:
26034 			break;
26035 		case IPSEC_STATUS_FAILED:
26036 			BUMP_MIB(&ip_mib, ipOutDiscards);
26037 			/* FALLTHRU */
26038 		case IPSEC_STATUS_PENDING:
26039 			return;
26040 		}
26041 	}
26042 
26043 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26044 		ASSERT(io->ipsec_out_ah_sa != NULL);
26045 		io->ipsec_out_ah_done = B_TRUE;
26046 		if (ire == NULL) {
26047 			int idx = io->ipsec_out_capab_ill_index;
26048 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26049 			    NULL, NULL, NULL, NULL);
26050 			ill_need_rele = B_TRUE;
26051 		} else {
26052 			ill = (ill_t *)ire->ire_stq->q_ptr;
26053 		}
26054 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26055 		    ire);
26056 
26057 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26058 		switch (ipsec_rc) {
26059 		case IPSEC_STATUS_SUCCESS:
26060 			break;
26061 		case IPSEC_STATUS_FAILED:
26062 			BUMP_MIB(&ip_mib, ipOutDiscards);
26063 			/* FALLTHRU */
26064 		case IPSEC_STATUS_PENDING:
26065 			if (ill != NULL && ill_need_rele)
26066 				ill_refrele(ill);
26067 			return;
26068 		}
26069 	}
26070 	/*
26071 	 * We are done with IPSEC processing. Send it over
26072 	 * the wire.
26073 	 */
26074 done:
26075 	mp = ipsec_mp->b_cont;
26076 	ipha = (ipha_t *)mp->b_rptr;
26077 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26078 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26079 	} else {
26080 		ip6h = (ip6_t *)ipha;
26081 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26082 	}
26083 	if (ill != NULL && ill_need_rele)
26084 		ill_refrele(ill);
26085 }
26086 
26087 /* ARGSUSED */
26088 void
26089 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26090 {
26091 	opt_restart_t	*or;
26092 	int	err;
26093 	conn_t	*connp;
26094 
26095 	ASSERT(CONN_Q(q));
26096 	connp = Q_TO_CONN(q);
26097 
26098 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26099 	or = (opt_restart_t *)first_mp->b_rptr;
26100 	/*
26101 	 * We don't need to pass any credentials here since this is just
26102 	 * a restart. The credentials are passed in when svr4_optcom_req
26103 	 * is called the first time (from ip_wput_nondata).
26104 	 */
26105 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26106 		err = svr4_optcom_req(q, first_mp, NULL,
26107 		    &ip_opt_obj);
26108 	} else {
26109 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26110 		err = tpi_optcom_req(q, first_mp, NULL,
26111 		    &ip_opt_obj);
26112 	}
26113 	if (err != EINPROGRESS) {
26114 		/* operation is done */
26115 		CONN_OPER_PENDING_DONE(connp);
26116 	}
26117 }
26118 
26119 /*
26120  * ioctls that go through a down/up sequence may need to wait for the down
26121  * to complete. This involves waiting for the ire and ipif refcnts to go down
26122  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26123  */
26124 /* ARGSUSED */
26125 void
26126 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26127 {
26128 	struct iocblk *iocp;
26129 	mblk_t *mp1;
26130 	ipif_t	*ipif;
26131 	ip_ioctl_cmd_t *ipip;
26132 	int err;
26133 	sin_t	*sin;
26134 	struct lifreq *lifr;
26135 	struct ifreq *ifr;
26136 
26137 	iocp = (struct iocblk *)mp->b_rptr;
26138 	ASSERT(ipsq != NULL);
26139 	/* Existence of mp1 verified in ip_wput_nondata */
26140 	mp1 = mp->b_cont->b_cont;
26141 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26142 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26143 		ill_t *ill;
26144 		/*
26145 		 * Special case where ipsq_current_ipif may not be set.
26146 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26147 		 * ill could also have become part of a ipmp group in the
26148 		 * process, we are here as were not able to complete the
26149 		 * operation in ipif_set_values because we could not become
26150 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26151 		 * will not be set so we need to set it.
26152 		 */
26153 		ill = (ill_t *)q->q_ptr;
26154 		ipsq->ipsq_current_ipif = ill->ill_ipif;
26155 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26156 	}
26157 
26158 	ipif = ipsq->ipsq_current_ipif;
26159 	ASSERT(ipif != NULL);
26160 	if (ipip->ipi_cmd_type == IF_CMD) {
26161 		/* This a old style SIOC[GS]IF* command */
26162 		ifr = (struct ifreq *)mp1->b_rptr;
26163 		sin = (sin_t *)&ifr->ifr_addr;
26164 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26165 		/* This a new style SIOC[GS]LIF* command */
26166 		lifr = (struct lifreq *)mp1->b_rptr;
26167 		sin = (sin_t *)&lifr->lifr_addr;
26168 	} else {
26169 		sin = NULL;
26170 	}
26171 
26172 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
26173 	    (void *)mp1->b_rptr);
26174 
26175 	/* SIOCLIFREMOVEIF could have removed the ipif */
26176 	ip_ioctl_finish(q, mp, err,
26177 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26178 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
26179 }
26180 
26181 /*
26182  * ioctl processing
26183  *
26184  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
26185  * the ioctl command in the ioctl tables and determines the copyin data size
26186  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
26187  * size.
26188  *
26189  * ioctl processing then continues when the M_IOCDATA makes its way down.
26190  * Now the ioctl is looked up again in the ioctl table, and its properties are
26191  * extracted. The associated 'conn' is then refheld till the end of the ioctl
26192  * and the general ioctl processing function ip_process_ioctl is called.
26193  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26194  * so goes thru the serialization primitive ipsq_try_enter. Then the
26195  * appropriate function to handle the ioctl is called based on the entry in
26196  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26197  * which also refreleases the 'conn' that was refheld at the start of the
26198  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26199  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
26200  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
26201  *
26202  * Many exclusive ioctls go thru an internal down up sequence as part of
26203  * the operation. For example an attempt to change the IP address of an
26204  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26205  * does all the cleanup such as deleting all ires that use this address.
26206  * Then we need to wait till all references to the interface go away.
26207  */
26208 void
26209 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26210 {
26211 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26212 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
26213 	cmd_info_t ci;
26214 	int err;
26215 	boolean_t entered_ipsq = B_FALSE;
26216 
26217 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26218 
26219 	if (ipip == NULL)
26220 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26221 
26222 	/*
26223 	 * SIOCLIFADDIF needs to go thru a special path since the
26224 	 * ill may not exist yet. This happens in the case of lo0
26225 	 * which is created using this ioctl.
26226 	 */
26227 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26228 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26229 		ip_ioctl_finish(q, mp, err,
26230 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26231 		    NULL, NULL);
26232 		return;
26233 	}
26234 
26235 	ci.ci_ipif = NULL;
26236 	switch (ipip->ipi_cmd_type) {
26237 	case IF_CMD:
26238 	case LIF_CMD:
26239 		/*
26240 		 * ioctls that pass in a [l]ifreq appear here.
26241 		 * ip_extract_lifreq_cmn returns a refheld ipif in
26242 		 * ci.ci_ipif
26243 		 */
26244 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
26245 		    ipip->ipi_flags, &ci, ip_process_ioctl);
26246 		if (err != 0) {
26247 			ip_ioctl_finish(q, mp, err,
26248 			    ipip->ipi_flags & IPI_GET_CMD ?
26249 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26250 			return;
26251 		}
26252 		ASSERT(ci.ci_ipif != NULL);
26253 		break;
26254 
26255 	case TUN_CMD:
26256 		/*
26257 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
26258 		 * a refheld ipif in ci.ci_ipif
26259 		 */
26260 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
26261 		if (err != 0) {
26262 			ip_ioctl_finish(q, mp, err,
26263 			    ipip->ipi_flags & IPI_GET_CMD ?
26264 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26265 			return;
26266 		}
26267 		ASSERT(ci.ci_ipif != NULL);
26268 		break;
26269 
26270 	case MISC_CMD:
26271 		/*
26272 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
26273 		 * For eg. SIOCGLIFCONF will appear here.
26274 		 */
26275 		switch (ipip->ipi_cmd) {
26276 		case IF_UNITSEL:
26277 			/* ioctl comes down the ill */
26278 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26279 			ipif_refhold(ci.ci_ipif);
26280 			break;
26281 		case SIOCGMSFILTER:
26282 		case SIOCSMSFILTER:
26283 		case SIOCGIPMSFILTER:
26284 		case SIOCSIPMSFILTER:
26285 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
26286 			    ip_process_ioctl);
26287 			if (err != 0) {
26288 				ip_ioctl_finish(q, mp, err,
26289 				    ipip->ipi_flags & IPI_GET_CMD ?
26290 				    COPYOUT : NO_COPYOUT, NULL, NULL);
26291 				return;
26292 			}
26293 			break;
26294 		}
26295 		err = 0;
26296 		ci.ci_sin = NULL;
26297 		ci.ci_sin6 = NULL;
26298 		ci.ci_lifr = NULL;
26299 		break;
26300 	}
26301 
26302 	/*
26303 	 * If ipsq is non-null, we are already being called exclusively
26304 	 */
26305 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26306 	if (!(ipip->ipi_flags & IPI_WR)) {
26307 		/*
26308 		 * A return value of EINPROGRESS means the ioctl is
26309 		 * either queued and waiting for some reason or has
26310 		 * already completed.
26311 		 */
26312 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26313 		    ci.ci_lifr);
26314 		if (ci.ci_ipif != NULL)
26315 			ipif_refrele(ci.ci_ipif);
26316 		ip_ioctl_finish(q, mp, err,
26317 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26318 		    NULL, NULL);
26319 		return;
26320 	}
26321 
26322 	ASSERT(ci.ci_ipif != NULL);
26323 
26324 	if (ipsq == NULL) {
26325 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26326 		    ip_process_ioctl, NEW_OP, B_TRUE);
26327 		entered_ipsq = B_TRUE;
26328 	}
26329 	/*
26330 	 * Release the ipif so that ipif_down and friends that wait for
26331 	 * references to go away are not misled about the current ipif_refcnt
26332 	 * values. We are writer so we can access the ipif even after releasing
26333 	 * the ipif.
26334 	 */
26335 	ipif_refrele(ci.ci_ipif);
26336 	if (ipsq == NULL)
26337 		return;
26338 
26339 	mutex_enter(&ipsq->ipsq_lock);
26340 	ASSERT(ipsq->ipsq_current_ipif == NULL);
26341 	ipsq->ipsq_current_ipif = ci.ci_ipif;
26342 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26343 	mutex_exit(&ipsq->ipsq_lock);
26344 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26345 	/*
26346 	 * For most set ioctls that come here, this serves as a single point
26347 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26348 	 * be any new references to the ipif. This helps functions that go
26349 	 * through this path and end up trying to wait for the refcnts
26350 	 * associated with the ipif to go down to zero. Some exceptions are
26351 	 * Failover, Failback, and Groupname commands that operate on more than
26352 	 * just the ci.ci_ipif. These commands internally determine the
26353 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26354 	 * flags on that set. Another exception is the Removeif command that
26355 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26356 	 * ipif to operate on.
26357 	 */
26358 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26359 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26360 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26361 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26362 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26363 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26364 
26365 	/*
26366 	 * A return value of EINPROGRESS means the ioctl is
26367 	 * either queued and waiting for some reason or has
26368 	 * already completed.
26369 	 */
26370 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26371 	    ci.ci_lifr);
26372 
26373 	/* SIOCLIFREMOVEIF could have removed the ipif */
26374 	ip_ioctl_finish(q, mp, err,
26375 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26376 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
26377 
26378 	if (entered_ipsq)
26379 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26380 }
26381 
26382 /*
26383  * Complete the ioctl. Typically ioctls use the mi package and need to
26384  * do mi_copyout/mi_copy_done.
26385  */
26386 void
26387 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
26388     ipif_t *ipif, ipsq_t *ipsq)
26389 {
26390 	conn_t	*connp = NULL;
26391 	hook_nic_event_t *info;
26392 
26393 	if (err == EINPROGRESS)
26394 		return;
26395 
26396 	if (CONN_Q(q)) {
26397 		connp = Q_TO_CONN(q);
26398 		ASSERT(connp->conn_ref >= 2);
26399 	}
26400 
26401 	switch (mode) {
26402 	case COPYOUT:
26403 		if (err == 0)
26404 			mi_copyout(q, mp);
26405 		else
26406 			mi_copy_done(q, mp, err);
26407 		break;
26408 
26409 	case NO_COPYOUT:
26410 		mi_copy_done(q, mp, err);
26411 		break;
26412 
26413 	default:
26414 		/* An ioctl aborted through a conn close would take this path */
26415 		break;
26416 	}
26417 
26418 	/*
26419 	 * The refhold placed at the start of the ioctl is released here.
26420 	 */
26421 	if (connp != NULL)
26422 		CONN_OPER_PENDING_DONE(connp);
26423 
26424 	/*
26425 	 * If the ioctl were an exclusive ioctl it would have set
26426 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
26427 	 */
26428 	if (ipif != NULL) {
26429 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
26430 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
26431 
26432 		/*
26433 		 * Unhook the nic event message from the ill and enqueue it into
26434 		 * the nic event taskq.
26435 		 */
26436 		if ((info = ipif->ipif_ill->ill_nic_event_info) != NULL) {
26437 			if (ddi_taskq_dispatch(eventq_queue_nic,
26438 			    ip_ne_queue_func, (void *)info, DDI_SLEEP)
26439 			    == DDI_FAILURE) {
26440 				ip2dbg(("ip_ioctl_finish: ddi_taskq_dispatch"
26441 				    "failed\n"));
26442 				if (info->hne_data != NULL)
26443 					kmem_free(info->hne_data,
26444 					    info->hne_datalen);
26445 				kmem_free(info, sizeof (hook_nic_event_t));
26446 			}
26447 
26448 			ipif->ipif_ill->ill_nic_event_info = NULL;
26449 		}
26450 
26451 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
26452 	}
26453 
26454 	/*
26455 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
26456 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
26457 	 * entering the ipsq
26458 	 */
26459 	if (ipsq != NULL) {
26460 		mutex_enter(&ipsq->ipsq_lock);
26461 		ipsq->ipsq_current_ipif = NULL;
26462 		mutex_exit(&ipsq->ipsq_lock);
26463 	}
26464 }
26465 
26466 /*
26467  * This is called from ip_wput_nondata to resume a deferred TCP bind.
26468  */
26469 /* ARGSUSED */
26470 void
26471 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
26472 {
26473 	conn_t *connp = arg;
26474 	tcp_t	*tcp;
26475 
26476 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
26477 	tcp = connp->conn_tcp;
26478 
26479 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
26480 		freemsg(mp);
26481 	else
26482 		tcp_rput_other(tcp, mp);
26483 	CONN_OPER_PENDING_DONE(connp);
26484 }
26485 
26486 /* Called from ip_wput for all non data messages */
26487 /* ARGSUSED */
26488 void
26489 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26490 {
26491 	mblk_t		*mp1;
26492 	ire_t		*ire, *fake_ire;
26493 	ill_t		*ill;
26494 	struct iocblk	*iocp;
26495 	ip_ioctl_cmd_t	*ipip;
26496 	cred_t		*cr;
26497 	conn_t		*connp = NULL;
26498 	int		cmd, err;
26499 	nce_t		*nce;
26500 	ipif_t		*ipif;
26501 
26502 	if (CONN_Q(q))
26503 		connp = Q_TO_CONN(q);
26504 
26505 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26506 
26507 	/* Check if it is a queue to /dev/sctp. */
26508 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26509 	    connp->conn_rq == NULL) {
26510 		sctp_wput(q, mp);
26511 		return;
26512 	}
26513 
26514 	switch (DB_TYPE(mp)) {
26515 	case M_IOCTL:
26516 		/*
26517 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26518 		 * will arrange to copy in associated control structures.
26519 		 */
26520 		ip_sioctl_copyin_setup(q, mp);
26521 		return;
26522 	case M_IOCDATA:
26523 		/*
26524 		 * Ensure that this is associated with one of our trans-
26525 		 * parent ioctls.  If it's not ours, discard it if we're
26526 		 * running as a driver, or pass it on if we're a module.
26527 		 */
26528 		iocp = (struct iocblk *)mp->b_rptr;
26529 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26530 		if (ipip == NULL) {
26531 			if (q->q_next == NULL) {
26532 				goto nak;
26533 			} else {
26534 				putnext(q, mp);
26535 			}
26536 			return;
26537 		} else if ((q->q_next != NULL) &&
26538 		    !(ipip->ipi_flags & IPI_MODOK)) {
26539 			/*
26540 			 * the ioctl is one we recognise, but is not
26541 			 * consumed by IP as a module, pass M_IOCDATA
26542 			 * for processing downstream, but only for
26543 			 * common Streams ioctls.
26544 			 */
26545 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26546 				putnext(q, mp);
26547 				return;
26548 			} else {
26549 				goto nak;
26550 			}
26551 		}
26552 
26553 		/* IOCTL continuation following copyin or copyout. */
26554 		if (mi_copy_state(q, mp, NULL) == -1) {
26555 			/*
26556 			 * The copy operation failed.  mi_copy_state already
26557 			 * cleaned up, so we're out of here.
26558 			 */
26559 			return;
26560 		}
26561 		/*
26562 		 * If we just completed a copy in, we become writer and
26563 		 * continue processing in ip_sioctl_copyin_done.  If it
26564 		 * was a copy out, we call mi_copyout again.  If there is
26565 		 * nothing more to copy out, it will complete the IOCTL.
26566 		 */
26567 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
26568 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
26569 				mi_copy_done(q, mp, EPROTO);
26570 				return;
26571 			}
26572 			/*
26573 			 * Check for cases that need more copying.  A return
26574 			 * value of 0 means a second copyin has been started,
26575 			 * so we return; a return value of 1 means no more
26576 			 * copying is needed, so we continue.
26577 			 */
26578 			cmd = iocp->ioc_cmd;
26579 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
26580 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
26581 			    MI_COPY_COUNT(mp) == 1) {
26582 				if (ip_copyin_msfilter(q, mp) == 0)
26583 					return;
26584 			}
26585 			/*
26586 			 * Refhold the conn, till the ioctl completes. This is
26587 			 * needed in case the ioctl ends up in the pending mp
26588 			 * list. Every mp in the ill_pending_mp list and
26589 			 * the ipsq_pending_mp must have a refhold on the conn
26590 			 * to resume processing. The refhold is released when
26591 			 * the ioctl completes. (normally or abnormally)
26592 			 * In all cases ip_ioctl_finish is called to finish
26593 			 * the ioctl.
26594 			 */
26595 			if (connp != NULL) {
26596 				/* This is not a reentry */
26597 				ASSERT(ipsq == NULL);
26598 				CONN_INC_REF(connp);
26599 			} else {
26600 				if (!(ipip->ipi_flags & IPI_MODOK)) {
26601 					mi_copy_done(q, mp, EINVAL);
26602 					return;
26603 				}
26604 			}
26605 
26606 			ip_process_ioctl(ipsq, q, mp, ipip);
26607 
26608 		} else {
26609 			mi_copyout(q, mp);
26610 		}
26611 		return;
26612 nak:
26613 		iocp->ioc_error = EINVAL;
26614 		mp->b_datap->db_type = M_IOCNAK;
26615 		iocp->ioc_count = 0;
26616 		qreply(q, mp);
26617 		return;
26618 
26619 	case M_IOCNAK:
26620 		/*
26621 		 * The only way we could get here is if a resolver didn't like
26622 		 * an IOCTL we sent it.	 This shouldn't happen.
26623 		 */
26624 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
26625 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
26626 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
26627 		freemsg(mp);
26628 		return;
26629 	case M_IOCACK:
26630 		/* Finish socket ioctls passed through to ARP. */
26631 		ip_sioctl_iocack(q, mp);
26632 		return;
26633 	case M_FLUSH:
26634 		if (*mp->b_rptr & FLUSHW)
26635 			flushq(q, FLUSHALL);
26636 		if (q->q_next) {
26637 			/*
26638 			 * M_FLUSH is sent up to IP by some drivers during
26639 			 * unbind. ip_rput has already replied to it. We are
26640 			 * here for the M_FLUSH that we originated in IP
26641 			 * before sending the unbind request to the driver.
26642 			 * Just free it as we don't queue packets in IP
26643 			 * on the write side of the device instance.
26644 			 */
26645 			freemsg(mp);
26646 			return;
26647 		}
26648 		if (*mp->b_rptr & FLUSHR) {
26649 			*mp->b_rptr &= ~FLUSHW;
26650 			qreply(q, mp);
26651 			return;
26652 		}
26653 		freemsg(mp);
26654 		return;
26655 	case IRE_DB_REQ_TYPE:
26656 		/* An Upper Level Protocol wants a copy of an IRE. */
26657 		ip_ire_req(q, mp);
26658 		return;
26659 	case M_CTL:
26660 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
26661 			break;
26662 
26663 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
26664 		    TUN_HELLO) {
26665 			ASSERT(connp != NULL);
26666 			connp->conn_flags |= IPCL_IPTUN;
26667 			freeb(mp);
26668 			return;
26669 		}
26670 
26671 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
26672 		    IP_ULP_OUT_LABELED) {
26673 			out_labeled_t *olp;
26674 
26675 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
26676 				break;
26677 			olp = (out_labeled_t *)mp->b_rptr;
26678 			connp->conn_ulp_labeled = olp->out_qnext == q;
26679 			freemsg(mp);
26680 			return;
26681 		}
26682 
26683 		/* M_CTL messages are used by ARP to tell us things. */
26684 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
26685 			break;
26686 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
26687 		case AR_ENTRY_SQUERY:
26688 			ip_wput_ctl(q, mp);
26689 			return;
26690 		case AR_CLIENT_NOTIFY:
26691 			ip_arp_news(q, mp);
26692 			return;
26693 		case AR_DLPIOP_DONE:
26694 			ASSERT(q->q_next != NULL);
26695 			ill = (ill_t *)q->q_ptr;
26696 			/* qwriter_ip releases the refhold */
26697 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
26698 			ill_refhold(ill);
26699 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
26700 			    CUR_OP, B_FALSE);
26701 			return;
26702 		case AR_ARP_CLOSING:
26703 			/*
26704 			 * ARP (above us) is closing. If no ARP bringup is
26705 			 * currently pending, ack the message so that ARP
26706 			 * can complete its close. Also mark ill_arp_closing
26707 			 * so that new ARP bringups will fail. If any
26708 			 * ARP bringup is currently in progress, we will
26709 			 * ack this when the current ARP bringup completes.
26710 			 */
26711 			ASSERT(q->q_next != NULL);
26712 			ill = (ill_t *)q->q_ptr;
26713 			mutex_enter(&ill->ill_lock);
26714 			ill->ill_arp_closing = 1;
26715 			if (!ill->ill_arp_bringup_pending) {
26716 				mutex_exit(&ill->ill_lock);
26717 				qreply(q, mp);
26718 			} else {
26719 				mutex_exit(&ill->ill_lock);
26720 				freemsg(mp);
26721 			}
26722 			return;
26723 		case AR_ARP_EXTEND:
26724 			/*
26725 			 * The ARP module above us is capable of duplicate
26726 			 * address detection.  Old ATM drivers will not send
26727 			 * this message.
26728 			 */
26729 			ASSERT(q->q_next != NULL);
26730 			ill = (ill_t *)q->q_ptr;
26731 			ill->ill_arp_extend = B_TRUE;
26732 			freemsg(mp);
26733 			return;
26734 		default:
26735 			break;
26736 		}
26737 		break;
26738 	case M_PROTO:
26739 	case M_PCPROTO:
26740 		/*
26741 		 * The only PROTO messages we expect are ULP binds and
26742 		 * copies of option negotiation acknowledgements.
26743 		 */
26744 		switch (((union T_primitives *)mp->b_rptr)->type) {
26745 		case O_T_BIND_REQ:
26746 		case T_BIND_REQ: {
26747 			/* Request can get queued in bind */
26748 			ASSERT(connp != NULL);
26749 			/*
26750 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
26751 			 * instead of going through this path.  We only get
26752 			 * here in the following cases:
26753 			 *
26754 			 * a. Bind retries, where ipsq is non-NULL.
26755 			 * b. T_BIND_REQ is issued from non TCP/UDP
26756 			 *    transport, e.g. icmp for raw socket,
26757 			 *    in which case ipsq will be NULL.
26758 			 */
26759 			ASSERT(ipsq != NULL ||
26760 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
26761 
26762 			/* Don't increment refcnt if this is a re-entry */
26763 			if (ipsq == NULL)
26764 				CONN_INC_REF(connp);
26765 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
26766 			    connp, NULL) : ip_bind_v4(q, mp, connp);
26767 			if (mp == NULL)
26768 				return;
26769 			if (IPCL_IS_TCP(connp)) {
26770 				/*
26771 				 * In the case of TCP endpoint we
26772 				 * come here only for bind retries
26773 				 */
26774 				ASSERT(ipsq != NULL);
26775 				CONN_INC_REF(connp);
26776 				squeue_fill(connp->conn_sqp, mp,
26777 				    ip_resume_tcp_bind, connp,
26778 				    SQTAG_BIND_RETRY);
26779 				return;
26780 			} else if (IPCL_IS_UDP(connp)) {
26781 				/*
26782 				 * In the case of UDP endpoint we
26783 				 * come here only for bind retries
26784 				 */
26785 				ASSERT(ipsq != NULL);
26786 				udp_resume_bind(connp, mp);
26787 				return;
26788 			}
26789 			qreply(q, mp);
26790 			CONN_OPER_PENDING_DONE(connp);
26791 			return;
26792 		}
26793 		case T_SVR4_OPTMGMT_REQ:
26794 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
26795 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
26796 
26797 			ASSERT(connp != NULL);
26798 			if (!snmpcom_req(q, mp, ip_snmp_set,
26799 			    ip_snmp_get, cr)) {
26800 				/*
26801 				 * Call svr4_optcom_req so that it can
26802 				 * generate the ack. We don't come here
26803 				 * if this operation is being restarted.
26804 				 * ip_restart_optmgmt will drop the conn ref.
26805 				 * In the case of ipsec option after the ipsec
26806 				 * load is complete conn_restart_ipsec_waiter
26807 				 * drops the conn ref.
26808 				 */
26809 				ASSERT(ipsq == NULL);
26810 				CONN_INC_REF(connp);
26811 				if (ip_check_for_ipsec_opt(q, mp))
26812 					return;
26813 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
26814 				if (err != EINPROGRESS) {
26815 					/* Operation is done */
26816 					CONN_OPER_PENDING_DONE(connp);
26817 				}
26818 			}
26819 			return;
26820 		case T_OPTMGMT_REQ:
26821 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
26822 			/*
26823 			 * Note: No snmpcom_req support through new
26824 			 * T_OPTMGMT_REQ.
26825 			 * Call tpi_optcom_req so that it can
26826 			 * generate the ack.
26827 			 */
26828 			ASSERT(connp != NULL);
26829 			ASSERT(ipsq == NULL);
26830 			/*
26831 			 * We don't come here for restart. ip_restart_optmgmt
26832 			 * will drop the conn ref. In the case of ipsec option
26833 			 * after the ipsec load is complete
26834 			 * conn_restart_ipsec_waiter drops the conn ref.
26835 			 */
26836 			CONN_INC_REF(connp);
26837 			if (ip_check_for_ipsec_opt(q, mp))
26838 				return;
26839 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
26840 			if (err != EINPROGRESS) {
26841 				/* Operation is done */
26842 				CONN_OPER_PENDING_DONE(connp);
26843 			}
26844 			return;
26845 		case T_UNBIND_REQ:
26846 			mp = ip_unbind(q, mp);
26847 			qreply(q, mp);
26848 			return;
26849 		default:
26850 			/*
26851 			 * Have to drop any DLPI messages coming down from
26852 			 * arp (such as an info_req which would cause ip
26853 			 * to receive an extra info_ack if it was passed
26854 			 * through.
26855 			 */
26856 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
26857 			    (int)*(uint_t *)mp->b_rptr));
26858 			freemsg(mp);
26859 			return;
26860 		}
26861 		/* NOTREACHED */
26862 	case IRE_DB_TYPE: {
26863 		nce_t		*nce;
26864 		ill_t		*ill;
26865 		in6_addr_t	gw_addr_v6;
26866 
26867 
26868 		/*
26869 		 * This is a response back from a resolver.  It
26870 		 * consists of a message chain containing:
26871 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
26872 		 * The IRE_MBLK is the one we allocated in ip_newroute.
26873 		 * The LL_HDR_MBLK is the DLPI header to use to get
26874 		 * the attached packet, and subsequent ones for the
26875 		 * same destination, transmitted.
26876 		 */
26877 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
26878 			break;
26879 		/*
26880 		 * First, check to make sure the resolution succeeded.
26881 		 * If it failed, the second mblk will be empty.
26882 		 * If it is, free the chain, dropping the packet.
26883 		 * (We must ire_delete the ire; that frees the ire mblk)
26884 		 * We're doing this now to support PVCs for ATM; it's
26885 		 * a partial xresolv implementation. When we fully implement
26886 		 * xresolv interfaces, instead of freeing everything here
26887 		 * we'll initiate neighbor discovery.
26888 		 *
26889 		 * For v4 (ARP and other external resolvers) the resolver
26890 		 * frees the message, so no check is needed. This check
26891 		 * is required, though, for a full xresolve implementation.
26892 		 * Including this code here now both shows how external
26893 		 * resolvers can NACK a resolution request using an
26894 		 * existing design that has no specific provisions for NACKs,
26895 		 * and also takes into account that the current non-ARP
26896 		 * external resolver has been coded to use this method of
26897 		 * NACKing for all IPv6 (xresolv) cases,
26898 		 * whether our xresolv implementation is complete or not.
26899 		 *
26900 		 */
26901 		ire = (ire_t *)mp->b_rptr;
26902 		ill = ire_to_ill(ire);
26903 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26904 		if (mp1->b_rptr == mp1->b_wptr) {
26905 			if (ire->ire_ipversion == IPV6_VERSION) {
26906 				/*
26907 				 * XRESOLV interface.
26908 				 */
26909 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
26910 				mutex_enter(&ire->ire_lock);
26911 				gw_addr_v6 = ire->ire_gateway_addr_v6;
26912 				mutex_exit(&ire->ire_lock);
26913 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26914 					nce = ndp_lookup_v6(ill,
26915 					    &ire->ire_addr_v6, B_FALSE);
26916 				} else {
26917 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
26918 					    B_FALSE);
26919 				}
26920 				if (nce != NULL) {
26921 					nce_resolv_failed(nce);
26922 					ndp_delete(nce);
26923 					NCE_REFRELE(nce);
26924 				}
26925 			}
26926 			mp->b_cont = NULL;
26927 			freemsg(mp1);		/* frees the pkt as well */
26928 			ASSERT(ire->ire_nce == NULL);
26929 			ire_delete((ire_t *)mp->b_rptr);
26930 			return;
26931 		}
26932 
26933 		/*
26934 		 * Split them into IRE_MBLK and pkt and feed it into
26935 		 * ire_add_then_send. Then in ire_add_then_send
26936 		 * the IRE will be added, and then the packet will be
26937 		 * run back through ip_wput. This time it will make
26938 		 * it to the wire.
26939 		 */
26940 		mp->b_cont = NULL;
26941 		mp = mp1->b_cont;		/* now, mp points to pkt */
26942 		mp1->b_cont = NULL;
26943 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
26944 		if (ire->ire_ipversion == IPV6_VERSION) {
26945 			/*
26946 			 * XRESOLV interface. Find the nce and put a copy
26947 			 * of the dl_unitdata_req in nce_res_mp
26948 			 */
26949 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
26950 			mutex_enter(&ire->ire_lock);
26951 			gw_addr_v6 = ire->ire_gateway_addr_v6;
26952 			mutex_exit(&ire->ire_lock);
26953 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26954 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
26955 				    B_FALSE);
26956 			} else {
26957 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
26958 			}
26959 			if (nce != NULL) {
26960 				/*
26961 				 * We have to protect nce_res_mp here
26962 				 * from being accessed by other threads
26963 				 * while we change the mblk pointer.
26964 				 * Other functions will also lock the nce when
26965 				 * accessing nce_res_mp.
26966 				 *
26967 				 * The reason we change the mblk pointer
26968 				 * here rather than copying the resolved address
26969 				 * into the template is that, unlike with
26970 				 * ethernet, we have no guarantee that the
26971 				 * resolved address length will be
26972 				 * smaller than or equal to the lla length
26973 				 * with which the template was allocated,
26974 				 * (for ethernet, they're equal)
26975 				 * so we have to use the actual resolved
26976 				 * address mblk - which holds the real
26977 				 * dl_unitdata_req with the resolved address.
26978 				 *
26979 				 * Doing this is the same behavior as was
26980 				 * previously used in the v4 ARP case.
26981 				 */
26982 				mutex_enter(&nce->nce_lock);
26983 				if (nce->nce_res_mp != NULL)
26984 					freemsg(nce->nce_res_mp);
26985 				nce->nce_res_mp = mp1;
26986 				mutex_exit(&nce->nce_lock);
26987 				/*
26988 				 * We do a fastpath probe here because
26989 				 * we have resolved the address without
26990 				 * using Neighbor Discovery.
26991 				 * In the non-XRESOLV v6 case, the fastpath
26992 				 * probe is done right after neighbor
26993 				 * discovery completes.
26994 				 */
26995 				if (nce->nce_res_mp != NULL) {
26996 					int res;
26997 					nce_fastpath_list_add(nce);
26998 					res = ill_fastpath_probe(ill,
26999 					    nce->nce_res_mp);
27000 					if (res != 0 && res != EAGAIN)
27001 						nce_fastpath_list_delete(nce);
27002 				}
27003 
27004 				ire_add_then_send(q, ire, mp);
27005 				/*
27006 				 * Now we have to clean out any packets
27007 				 * that may have been queued on the nce
27008 				 * while it was waiting for address resolution
27009 				 * to complete.
27010 				 */
27011 				mutex_enter(&nce->nce_lock);
27012 				mp1 = nce->nce_qd_mp;
27013 				nce->nce_qd_mp = NULL;
27014 				mutex_exit(&nce->nce_lock);
27015 				while (mp1 != NULL) {
27016 					mblk_t *nxt_mp;
27017 					queue_t *fwdq = NULL;
27018 					ill_t   *inbound_ill;
27019 					uint_t ifindex;
27020 
27021 					nxt_mp = mp1->b_next;
27022 					mp1->b_next = NULL;
27023 					/*
27024 					 * Retrieve ifindex stored in
27025 					 * ip_rput_data_v6()
27026 					 */
27027 					ifindex =
27028 					    (uint_t)(uintptr_t)mp1->b_prev;
27029 					inbound_ill =
27030 						ill_lookup_on_ifindex(ifindex,
27031 						    B_TRUE, NULL, NULL, NULL,
27032 						    NULL);
27033 					mp1->b_prev = NULL;
27034 					if (inbound_ill != NULL)
27035 						fwdq = inbound_ill->ill_rq;
27036 
27037 					if (fwdq != NULL) {
27038 						put(fwdq, mp1);
27039 						ill_refrele(inbound_ill);
27040 					} else
27041 						put(WR(ill->ill_rq), mp1);
27042 					mp1 = nxt_mp;
27043 				}
27044 				NCE_REFRELE(nce);
27045 			} else {	/* nce is NULL; clean up */
27046 				ire_delete(ire);
27047 				freemsg(mp);
27048 				freemsg(mp1);
27049 				return;
27050 			}
27051 		} else {
27052 			nce_t *arpce;
27053 			/*
27054 			 * Link layer resolution succeeded. Recompute the
27055 			 * ire_nce.
27056 			 */
27057 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27058 			if ((arpce = ndp_lookup_v4(ill,
27059 			    (ire->ire_gateway_addr != INADDR_ANY ?
27060 			    &ire->ire_gateway_addr : &ire->ire_addr),
27061 			    B_FALSE)) == NULL) {
27062 				freeb(ire->ire_mp);
27063 				freeb(mp1);
27064 				freemsg(mp);
27065 				return;
27066 			}
27067 			mutex_enter(&arpce->nce_lock);
27068 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27069 			if (arpce->nce_state == ND_REACHABLE) {
27070 				/*
27071 				 * Someone resolved this before us;
27072 				 * cleanup the res_mp. Since ire has
27073 				 * not been added yet, the call to ire_add_v4
27074 				 * from ire_add_then_send (when a dup is
27075 				 * detected) will clean up the ire.
27076 				 */
27077 				freeb(mp1);
27078 			} else {
27079 				if (arpce->nce_res_mp != NULL)
27080 					freemsg(arpce->nce_res_mp);
27081 				arpce->nce_res_mp = mp1;
27082 				arpce->nce_state = ND_REACHABLE;
27083 			}
27084 			mutex_exit(&arpce->nce_lock);
27085 			if (ire->ire_marks & IRE_MARK_NOADD) {
27086 				/*
27087 				 * this ire will not be added to the ire
27088 				 * cache table, so we can set the ire_nce
27089 				 * here, as there are no atomicity constraints.
27090 				 */
27091 				ire->ire_nce = arpce;
27092 				/*
27093 				 * We are associating this nce with the ire
27094 				 * so change the nce ref taken in
27095 				 * ndp_lookup_v4() from
27096 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27097 				 */
27098 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27099 			} else {
27100 				NCE_REFRELE(arpce);
27101 			}
27102 			ire_add_then_send(q, ire, mp);
27103 		}
27104 		return;	/* All is well, the packet has been sent. */
27105 	}
27106 	case IRE_ARPRESOLVE_TYPE: {
27107 
27108 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27109 			break;
27110 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27111 		mp->b_cont = NULL;
27112 		/*
27113 		 * First, check to make sure the resolution succeeded.
27114 		 * If it failed, the second mblk will be empty.
27115 		 */
27116 		if (mp1->b_rptr == mp1->b_wptr) {
27117 			/* cleanup  the incomplete ire, free queued packets */
27118 			freemsg(mp); /* fake ire */
27119 			freeb(mp1);  /* dl_unitdata response */
27120 			return;
27121 		}
27122 
27123 		/*
27124 		 * update any incomplete nce_t found. we lookup the ctable
27125 		 * and find the nce from the ire->ire_nce because we need
27126 		 * to pass the ire to ip_xmit_v4 later, and can find both
27127 		 * ire and nce in one lookup from the ctable.
27128 		 */
27129 		fake_ire = (ire_t *)mp->b_rptr;
27130 		/*
27131 		 * By the time we come back here from ARP
27132 		 * the logical outgoing interface  of the incomplete ire
27133 		 * we added in ire_forward could have disappeared,
27134 		 * causing the incomplete ire to also have
27135 		 * dissapeared. So we need to retreive the
27136 		 * proper ipif for the ire  before looking
27137 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27138 		 */
27139 		ill = q->q_ptr;
27140 
27141 		/* Get the outgoing ipif */
27142 		mutex_enter(&ill->ill_lock);
27143 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27144 			mutex_exit(&ill->ill_lock);
27145 			freemsg(mp); /* fake ire */
27146 			freeb(mp1);  /* dl_unitdata response */
27147 			return;
27148 		}
27149 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27150 
27151 		if (ipif == NULL) {
27152 			mutex_exit(&ill->ill_lock);
27153 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27154 			freemsg(mp);
27155 			freeb(mp1);
27156 			return;
27157 		}
27158 		ipif_refhold_locked(ipif);
27159 		mutex_exit(&ill->ill_lock);
27160 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27161 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27162 		    ipif, fake_ire->ire_zoneid, NULL,
27163 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
27164 		ipif_refrele(ipif);
27165 		if (ire == NULL) {
27166 			/*
27167 			 * no ire was found; check if there is an nce
27168 			 * for this lookup; if it has no ire's pointing at it
27169 			 * cleanup.
27170 			 */
27171 			if ((nce = ndp_lookup_v4(ill,
27172 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27173 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27174 			    B_FALSE)) != NULL) {
27175 				/*
27176 				 * cleanup: just reset nce.
27177 				 * We check for refcnt 2 (one for the nce
27178 				 * hash list + 1 for the ref taken by
27179 				 * ndp_lookup_v4) to ensure that there are
27180 				 * no ire's pointing at the nce.
27181 				 */
27182 				if (nce->nce_refcnt == 2) {
27183 					nce = nce_reinit(nce);
27184 				}
27185 				if (nce != NULL)
27186 					NCE_REFRELE(nce);
27187 			}
27188 			freeb(mp1);  /* dl_unitdata response */
27189 			freemsg(mp); /* fake ire */
27190 			return;
27191 		}
27192 		nce = ire->ire_nce;
27193 		DTRACE_PROBE2(ire__arpresolve__type,
27194 		    ire_t *, ire, nce_t *, nce);
27195 		ASSERT(nce->nce_state != ND_INITIAL);
27196 		mutex_enter(&nce->nce_lock);
27197 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27198 		if (nce->nce_state == ND_REACHABLE) {
27199 			/*
27200 			 * Someone resolved this before us;
27201 			 * our response is not needed any more.
27202 			 */
27203 			mutex_exit(&nce->nce_lock);
27204 			freeb(mp1);  /* dl_unitdata response */
27205 		} else {
27206 			if (nce->nce_res_mp != NULL) {
27207 				freemsg(nce->nce_res_mp);
27208 				/* existing dl_unitdata template */
27209 			}
27210 			nce->nce_res_mp = mp1;
27211 			nce->nce_state = ND_REACHABLE;
27212 			mutex_exit(&nce->nce_lock);
27213 			ire_fastpath(ire);
27214 		}
27215 		/*
27216 		 * The cached nce_t has been updated to be reachable;
27217 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
27218 		 */
27219 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27220 		freemsg(mp);
27221 		/*
27222 		 * send out queued packets.
27223 		 */
27224 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27225 
27226 		IRE_REFRELE(ire);
27227 		return;
27228 	}
27229 	default:
27230 		break;
27231 	}
27232 	if (q->q_next) {
27233 		putnext(q, mp);
27234 	} else
27235 		freemsg(mp);
27236 }
27237 
27238 /*
27239  * Process IP options in an outbound packet.  Modify the destination if there
27240  * is a source route option.
27241  * Returns non-zero if something fails in which case an ICMP error has been
27242  * sent and mp freed.
27243  */
27244 static int
27245 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27246     boolean_t mctl_present, zoneid_t zoneid)
27247 {
27248 	ipoptp_t	opts;
27249 	uchar_t		*opt;
27250 	uint8_t		optval;
27251 	uint8_t		optlen;
27252 	ipaddr_t	dst;
27253 	intptr_t	code = 0;
27254 	mblk_t		*mp;
27255 	ire_t		*ire = NULL;
27256 
27257 	ip2dbg(("ip_wput_options\n"));
27258 	mp = ipsec_mp;
27259 	if (mctl_present) {
27260 		mp = ipsec_mp->b_cont;
27261 	}
27262 
27263 	dst = ipha->ipha_dst;
27264 	for (optval = ipoptp_first(&opts, ipha);
27265 	    optval != IPOPT_EOL;
27266 	    optval = ipoptp_next(&opts)) {
27267 		opt = opts.ipoptp_cur;
27268 		optlen = opts.ipoptp_len;
27269 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27270 		    optval, optlen));
27271 		switch (optval) {
27272 			uint32_t off;
27273 		case IPOPT_SSRR:
27274 		case IPOPT_LSRR:
27275 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27276 				ip1dbg((
27277 				    "ip_wput_options: bad option offset\n"));
27278 				code = (char *)&opt[IPOPT_OLEN] -
27279 				    (char *)ipha;
27280 				goto param_prob;
27281 			}
27282 			off = opt[IPOPT_OFFSET];
27283 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27284 			    ntohl(dst)));
27285 			/*
27286 			 * For strict: verify that dst is directly
27287 			 * reachable.
27288 			 */
27289 			if (optval == IPOPT_SSRR) {
27290 				ire = ire_ftable_lookup(dst, 0, 0,
27291 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27292 				    MBLK_GETLABEL(mp),
27293 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
27294 				if (ire == NULL) {
27295 					ip1dbg(("ip_wput_options: SSRR not"
27296 					    " directly reachable: 0x%x\n",
27297 					    ntohl(dst)));
27298 					goto bad_src_route;
27299 				}
27300 				ire_refrele(ire);
27301 			}
27302 			break;
27303 		case IPOPT_RR:
27304 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27305 				ip1dbg((
27306 				    "ip_wput_options: bad option offset\n"));
27307 				code = (char *)&opt[IPOPT_OLEN] -
27308 				    (char *)ipha;
27309 				goto param_prob;
27310 			}
27311 			break;
27312 		case IPOPT_TS:
27313 			/*
27314 			 * Verify that length >=5 and that there is either
27315 			 * room for another timestamp or that the overflow
27316 			 * counter is not maxed out.
27317 			 */
27318 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27319 			if (optlen < IPOPT_MINLEN_IT) {
27320 				goto param_prob;
27321 			}
27322 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27323 				ip1dbg((
27324 				    "ip_wput_options: bad option offset\n"));
27325 				code = (char *)&opt[IPOPT_OFFSET] -
27326 				    (char *)ipha;
27327 				goto param_prob;
27328 			}
27329 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27330 			case IPOPT_TS_TSONLY:
27331 				off = IPOPT_TS_TIMELEN;
27332 				break;
27333 			case IPOPT_TS_TSANDADDR:
27334 			case IPOPT_TS_PRESPEC:
27335 			case IPOPT_TS_PRESPEC_RFC791:
27336 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27337 				break;
27338 			default:
27339 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27340 				    (char *)ipha;
27341 				goto param_prob;
27342 			}
27343 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27344 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27345 				/*
27346 				 * No room and the overflow counter is 15
27347 				 * already.
27348 				 */
27349 				goto param_prob;
27350 			}
27351 			break;
27352 		}
27353 	}
27354 
27355 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27356 		return (0);
27357 
27358 	ip1dbg(("ip_wput_options: error processing IP options."));
27359 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27360 
27361 param_prob:
27362 	/*
27363 	 * Since ip_wput() isn't close to finished, we fill
27364 	 * in enough of the header for credible error reporting.
27365 	 */
27366 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27367 		/* Failed */
27368 		freemsg(ipsec_mp);
27369 		return (-1);
27370 	}
27371 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid);
27372 	return (-1);
27373 
27374 bad_src_route:
27375 	/*
27376 	 * Since ip_wput() isn't close to finished, we fill
27377 	 * in enough of the header for credible error reporting.
27378 	 */
27379 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27380 		/* Failed */
27381 		freemsg(ipsec_mp);
27382 		return (-1);
27383 	}
27384 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
27385 	return (-1);
27386 }
27387 
27388 /*
27389  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27390  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27391  * thru /etc/system.
27392  */
27393 #define	CONN_MAXDRAINCNT	64
27394 
27395 static void
27396 conn_drain_init(void)
27397 {
27398 	int i;
27399 
27400 	conn_drain_list_cnt = conn_drain_nthreads;
27401 
27402 	if ((conn_drain_list_cnt == 0) ||
27403 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27404 		/*
27405 		 * Default value of the number of drainers is the
27406 		 * number of cpus, subject to maximum of 8 drainers.
27407 		 */
27408 		if (boot_max_ncpus != -1)
27409 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27410 		else
27411 			conn_drain_list_cnt = MIN(max_ncpus, 8);
27412 	}
27413 
27414 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
27415 	    KM_SLEEP);
27416 
27417 	for (i = 0; i < conn_drain_list_cnt; i++) {
27418 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
27419 		    MUTEX_DEFAULT, NULL);
27420 	}
27421 }
27422 
27423 static void
27424 conn_drain_fini(void)
27425 {
27426 	int i;
27427 
27428 	for (i = 0; i < conn_drain_list_cnt; i++)
27429 		mutex_destroy(&conn_drain_list[i].idl_lock);
27430 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
27431 	conn_drain_list = NULL;
27432 }
27433 
27434 /*
27435  * Note: For an overview of how flowcontrol is handled in IP please see the
27436  * IP Flowcontrol notes at the top of this file.
27437  *
27438  * Flow control has blocked us from proceeding. Insert the given conn in one
27439  * of the conn drain lists. These conn wq's will be qenabled later on when
27440  * STREAMS flow control does a backenable. conn_walk_drain will enable
27441  * the first conn in each of these drain lists. Each of these qenabled conns
27442  * in turn enables the next in the list, after it runs, or when it closes,
27443  * thus sustaining the drain process.
27444  *
27445  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27446  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27447  * running at any time, on a given conn, since there can be only 1 service proc
27448  * running on a queue at any time.
27449  */
27450 void
27451 conn_drain_insert(conn_t *connp)
27452 {
27453 	idl_t	*idl;
27454 	uint_t	index;
27455 
27456 	mutex_enter(&connp->conn_lock);
27457 	if (connp->conn_state_flags & CONN_CLOSING) {
27458 		/*
27459 		 * The conn is closing as a result of which CONN_CLOSING
27460 		 * is set. Return.
27461 		 */
27462 		mutex_exit(&connp->conn_lock);
27463 		return;
27464 	} else if (connp->conn_idl == NULL) {
27465 		/*
27466 		 * Assign the next drain list round robin. We dont' use
27467 		 * a lock, and thus it may not be strictly round robin.
27468 		 * Atomicity of load/stores is enough to make sure that
27469 		 * conn_drain_list_index is always within bounds.
27470 		 */
27471 		index = conn_drain_list_index;
27472 		ASSERT(index < conn_drain_list_cnt);
27473 		connp->conn_idl = &conn_drain_list[index];
27474 		index++;
27475 		if (index == conn_drain_list_cnt)
27476 			index = 0;
27477 		conn_drain_list_index = index;
27478 	}
27479 	mutex_exit(&connp->conn_lock);
27480 
27481 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27482 	if ((connp->conn_drain_prev != NULL) ||
27483 	    (connp->conn_state_flags & CONN_CLOSING)) {
27484 		/*
27485 		 * The conn is already in the drain list, OR
27486 		 * the conn is closing. We need to check again for
27487 		 * the closing case again since close can happen
27488 		 * after we drop the conn_lock, and before we
27489 		 * acquire the CONN_DRAIN_LIST_LOCK.
27490 		 */
27491 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27492 		return;
27493 	} else {
27494 		idl = connp->conn_idl;
27495 	}
27496 
27497 	/*
27498 	 * The conn is not in the drain list. Insert it at the
27499 	 * tail of the drain list. The drain list is circular
27500 	 * and doubly linked. idl_conn points to the 1st element
27501 	 * in the list.
27502 	 */
27503 	if (idl->idl_conn == NULL) {
27504 		idl->idl_conn = connp;
27505 		connp->conn_drain_next = connp;
27506 		connp->conn_drain_prev = connp;
27507 	} else {
27508 		conn_t *head = idl->idl_conn;
27509 
27510 		connp->conn_drain_next = head;
27511 		connp->conn_drain_prev = head->conn_drain_prev;
27512 		head->conn_drain_prev->conn_drain_next = connp;
27513 		head->conn_drain_prev = connp;
27514 	}
27515 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27516 }
27517 
27518 /*
27519  * This conn is closing, and we are called from ip_close. OR
27520  * This conn has been serviced by ip_wsrv, and we need to do the tail
27521  * processing.
27522  * If this conn is part of the drain list, we may need to sustain the drain
27523  * process by qenabling the next conn in the drain list. We may also need to
27524  * remove this conn from the list, if it is done.
27525  */
27526 static void
27527 conn_drain_tail(conn_t *connp, boolean_t closing)
27528 {
27529 	idl_t *idl;
27530 
27531 	/*
27532 	 * connp->conn_idl is stable at this point, and no lock is needed
27533 	 * to check it. If we are called from ip_close, close has already
27534 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27535 	 * called us only because conn_idl is non-null. If we are called thru
27536 	 * service, conn_idl could be null, but it cannot change because
27537 	 * service is single-threaded per queue, and there cannot be another
27538 	 * instance of service trying to call conn_drain_insert on this conn
27539 	 * now.
27540 	 */
27541 	ASSERT(!closing || (connp->conn_idl != NULL));
27542 
27543 	/*
27544 	 * If connp->conn_idl is null, the conn has not been inserted into any
27545 	 * drain list even once since creation of the conn. Just return.
27546 	 */
27547 	if (connp->conn_idl == NULL)
27548 		return;
27549 
27550 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27551 
27552 	if (connp->conn_drain_prev == NULL) {
27553 		/* This conn is currently not in the drain list.  */
27554 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27555 		return;
27556 	}
27557 	idl = connp->conn_idl;
27558 	if (idl->idl_conn_draining == connp) {
27559 		/*
27560 		 * This conn is the current drainer. If this is the last conn
27561 		 * in the drain list, we need to do more checks, in the 'if'
27562 		 * below. Otherwwise we need to just qenable the next conn,
27563 		 * to sustain the draining, and is handled in the 'else'
27564 		 * below.
27565 		 */
27566 		if (connp->conn_drain_next == idl->idl_conn) {
27567 			/*
27568 			 * This conn is the last in this list. This round
27569 			 * of draining is complete. If idl_repeat is set,
27570 			 * it means another flow enabling has happened from
27571 			 * the driver/streams and we need to another round
27572 			 * of draining.
27573 			 * If there are more than 2 conns in the drain list,
27574 			 * do a left rotate by 1, so that all conns except the
27575 			 * conn at the head move towards the head by 1, and the
27576 			 * the conn at the head goes to the tail. This attempts
27577 			 * a more even share for all queues that are being
27578 			 * drained.
27579 			 */
27580 			if ((connp->conn_drain_next != connp) &&
27581 			    (idl->idl_conn->conn_drain_next != connp)) {
27582 				idl->idl_conn = idl->idl_conn->conn_drain_next;
27583 			}
27584 			if (idl->idl_repeat) {
27585 				qenable(idl->idl_conn->conn_wq);
27586 				idl->idl_conn_draining = idl->idl_conn;
27587 				idl->idl_repeat = 0;
27588 			} else {
27589 				idl->idl_conn_draining = NULL;
27590 			}
27591 		} else {
27592 			/*
27593 			 * If the next queue that we are now qenable'ing,
27594 			 * is closing, it will remove itself from this list
27595 			 * and qenable the subsequent queue in ip_close().
27596 			 * Serialization is acheived thru idl_lock.
27597 			 */
27598 			qenable(connp->conn_drain_next->conn_wq);
27599 			idl->idl_conn_draining = connp->conn_drain_next;
27600 		}
27601 	}
27602 	if (!connp->conn_did_putbq || closing) {
27603 		/*
27604 		 * Remove ourself from the drain list, if we did not do
27605 		 * a putbq, or if the conn is closing.
27606 		 * Note: It is possible that q->q_first is non-null. It means
27607 		 * that these messages landed after we did a enableok() in
27608 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
27609 		 * service them.
27610 		 */
27611 		if (connp->conn_drain_next == connp) {
27612 			/* Singleton in the list */
27613 			ASSERT(connp->conn_drain_prev == connp);
27614 			idl->idl_conn = NULL;
27615 			idl->idl_conn_draining = NULL;
27616 		} else {
27617 			connp->conn_drain_prev->conn_drain_next =
27618 			    connp->conn_drain_next;
27619 			connp->conn_drain_next->conn_drain_prev =
27620 			    connp->conn_drain_prev;
27621 			if (idl->idl_conn == connp)
27622 				idl->idl_conn = connp->conn_drain_next;
27623 			ASSERT(idl->idl_conn_draining != connp);
27624 
27625 		}
27626 		connp->conn_drain_next = NULL;
27627 		connp->conn_drain_prev = NULL;
27628 	}
27629 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27630 }
27631 
27632 /*
27633  * Write service routine. Shared perimeter entry point.
27634  * ip_wsrv can be called in any of the following ways.
27635  * 1. The device queue's messages has fallen below the low water mark
27636  *    and STREAMS has backenabled the ill_wq. We walk thru all the
27637  *    the drain lists and backenable the first conn in each list.
27638  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
27639  *    qenabled non-tcp upper layers. We start dequeing messages and call
27640  *    ip_wput for each message.
27641  */
27642 
27643 void
27644 ip_wsrv(queue_t *q)
27645 {
27646 	conn_t	*connp;
27647 	ill_t	*ill;
27648 	mblk_t	*mp;
27649 
27650 	if (q->q_next) {
27651 		ill = (ill_t *)q->q_ptr;
27652 		if (ill->ill_state_flags == 0) {
27653 			/*
27654 			 * The device flow control has opened up.
27655 			 * Walk through conn drain lists and qenable the
27656 			 * first conn in each list. This makes sense only
27657 			 * if the stream is fully plumbed and setup.
27658 			 * Hence the if check above.
27659 			 */
27660 			ip1dbg(("ip_wsrv: walking\n"));
27661 			conn_walk_drain();
27662 		}
27663 		return;
27664 	}
27665 
27666 	connp = Q_TO_CONN(q);
27667 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
27668 
27669 	/*
27670 	 * 1. Set conn_draining flag to signal that service is active.
27671 	 *
27672 	 * 2. ip_output determines whether it has been called from service,
27673 	 *    based on the last parameter. If it is IP_WSRV it concludes it
27674 	 *    has been called from service.
27675 	 *
27676 	 * 3. Message ordering is preserved by the following logic.
27677 	 *    i. A directly called ip_output (i.e. not thru service) will queue
27678 	 *    the message at the tail, if conn_draining is set (i.e. service
27679 	 *    is running) or if q->q_first is non-null.
27680 	 *
27681 	 *    ii. If ip_output is called from service, and if ip_output cannot
27682 	 *    putnext due to flow control, it does a putbq.
27683 	 *
27684 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
27685 	 *    (causing an infinite loop).
27686 	 */
27687 	ASSERT(!connp->conn_did_putbq);
27688 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
27689 		connp->conn_draining = 1;
27690 		noenable(q);
27691 		while ((mp = getq(q)) != NULL) {
27692 			ASSERT(CONN_Q(q));
27693 
27694 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
27695 			if (connp->conn_did_putbq) {
27696 				/* ip_wput did a putbq */
27697 				break;
27698 			}
27699 		}
27700 		/*
27701 		 * At this point, a thread coming down from top, calling
27702 		 * ip_wput, may end up queueing the message. We have not yet
27703 		 * enabled the queue, so ip_wsrv won't be called again.
27704 		 * To avoid this race, check q->q_first again (in the loop)
27705 		 * If the other thread queued the message before we call
27706 		 * enableok(), we will catch it in the q->q_first check.
27707 		 * If the other thread queues the message after we call
27708 		 * enableok(), ip_wsrv will be called again by STREAMS.
27709 		 */
27710 		connp->conn_draining = 0;
27711 		enableok(q);
27712 	}
27713 
27714 	/* Enable the next conn for draining */
27715 	conn_drain_tail(connp, B_FALSE);
27716 
27717 	connp->conn_did_putbq = 0;
27718 }
27719 
27720 /*
27721  * Walk the list of all conn's calling the function provided with the
27722  * specified argument for each.	 Note that this only walks conn's that
27723  * have been bound.
27724  * Applies to both IPv4 and IPv6.
27725  */
27726 static void
27727 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
27728 {
27729 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
27730 	    func, arg, zoneid);
27731 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
27732 	    func, arg, zoneid);
27733 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
27734 	    func, arg, zoneid);
27735 	conn_walk_fanout_table(ipcl_proto_fanout,
27736 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
27737 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
27738 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
27739 }
27740 
27741 /*
27742  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
27743  * of conns that need to be drained, check if drain is already in progress.
27744  * If so set the idl_repeat bit, indicating that the last conn in the list
27745  * needs to reinitiate the drain once again, for the list. If drain is not
27746  * in progress for the list, initiate the draining, by qenabling the 1st
27747  * conn in the list. The drain is self-sustaining, each qenabled conn will
27748  * in turn qenable the next conn, when it is done/blocked/closing.
27749  */
27750 static void
27751 conn_walk_drain(void)
27752 {
27753 	int i;
27754 	idl_t *idl;
27755 
27756 	IP_STAT(ip_conn_walk_drain);
27757 
27758 	for (i = 0; i < conn_drain_list_cnt; i++) {
27759 		idl = &conn_drain_list[i];
27760 		mutex_enter(&idl->idl_lock);
27761 		if (idl->idl_conn == NULL) {
27762 			mutex_exit(&idl->idl_lock);
27763 			continue;
27764 		}
27765 		/*
27766 		 * If this list is not being drained currently by
27767 		 * an ip_wsrv thread, start the process.
27768 		 */
27769 		if (idl->idl_conn_draining == NULL) {
27770 			ASSERT(idl->idl_repeat == 0);
27771 			qenable(idl->idl_conn->conn_wq);
27772 			idl->idl_conn_draining = idl->idl_conn;
27773 		} else {
27774 			idl->idl_repeat = 1;
27775 		}
27776 		mutex_exit(&idl->idl_lock);
27777 	}
27778 }
27779 
27780 /*
27781  * Walk an conn hash table of `count' buckets, calling func for each entry.
27782  */
27783 static void
27784 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
27785     zoneid_t zoneid)
27786 {
27787 	conn_t	*connp;
27788 
27789 	while (count-- > 0) {
27790 		mutex_enter(&connfp->connf_lock);
27791 		for (connp = connfp->connf_head; connp != NULL;
27792 		    connp = connp->conn_next) {
27793 			if (zoneid == GLOBAL_ZONEID ||
27794 			    zoneid == connp->conn_zoneid) {
27795 				CONN_INC_REF(connp);
27796 				mutex_exit(&connfp->connf_lock);
27797 				(*func)(connp, arg);
27798 				mutex_enter(&connfp->connf_lock);
27799 				CONN_DEC_REF(connp);
27800 			}
27801 		}
27802 		mutex_exit(&connfp->connf_lock);
27803 		connfp++;
27804 	}
27805 }
27806 
27807 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
27808 static void
27809 conn_report1(conn_t *connp, void *mp)
27810 {
27811 	char	buf1[INET6_ADDRSTRLEN];
27812 	char	buf2[INET6_ADDRSTRLEN];
27813 	uint_t	print_len, buf_len;
27814 
27815 	ASSERT(connp != NULL);
27816 
27817 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
27818 	if (buf_len <= 0)
27819 		return;
27820 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
27821 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
27822 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
27823 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
27824 	    "%5d %s/%05d %s/%05d\n",
27825 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
27826 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
27827 	    buf1, connp->conn_lport,
27828 	    buf2, connp->conn_fport);
27829 	if (print_len < buf_len) {
27830 		((mblk_t *)mp)->b_wptr += print_len;
27831 	} else {
27832 		((mblk_t *)mp)->b_wptr += buf_len;
27833 	}
27834 }
27835 
27836 /*
27837  * Named Dispatch routine to produce a formatted report on all conns
27838  * that are listed in one of the fanout tables.
27839  * This report is accessed by using the ndd utility to "get" ND variable
27840  * "ip_conn_status".
27841  */
27842 /* ARGSUSED */
27843 static int
27844 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
27845 {
27846 	(void) mi_mpprintf(mp,
27847 	    "CONN      " MI_COL_HDRPAD_STR
27848 	    "rfq      " MI_COL_HDRPAD_STR
27849 	    "stq      " MI_COL_HDRPAD_STR
27850 	    " zone local                 remote");
27851 
27852 	/*
27853 	 * Because of the ndd constraint, at most we can have 64K buffer
27854 	 * to put in all conn info.  So to be more efficient, just
27855 	 * allocate a 64K buffer here, assuming we need that large buffer.
27856 	 * This should be OK as only privileged processes can do ndd /dev/ip.
27857 	 */
27858 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
27859 		/* The following may work even if we cannot get a large buf. */
27860 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
27861 		return (0);
27862 	}
27863 
27864 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
27865 	return (0);
27866 }
27867 
27868 /*
27869  * Determine if the ill and multicast aspects of that packets
27870  * "matches" the conn.
27871  */
27872 boolean_t
27873 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
27874     zoneid_t zoneid)
27875 {
27876 	ill_t *in_ill;
27877 	boolean_t found;
27878 	ipif_t *ipif;
27879 	ire_t *ire;
27880 	ipaddr_t dst, src;
27881 
27882 	dst = ipha->ipha_dst;
27883 	src = ipha->ipha_src;
27884 
27885 	/*
27886 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
27887 	 * unicast, broadcast and multicast reception to
27888 	 * conn_incoming_ill. conn_wantpacket itself is called
27889 	 * only for BROADCAST and multicast.
27890 	 *
27891 	 * 1) ip_rput supresses duplicate broadcasts if the ill
27892 	 *    is part of a group. Hence, we should be receiving
27893 	 *    just one copy of broadcast for the whole group.
27894 	 *    Thus, if it is part of the group the packet could
27895 	 *    come on any ill of the group and hence we need a
27896 	 *    match on the group. Otherwise, match on ill should
27897 	 *    be sufficient.
27898 	 *
27899 	 * 2) ip_rput does not suppress duplicate multicast packets.
27900 	 *    If there are two interfaces in a ill group and we have
27901 	 *    2 applications (conns) joined a multicast group G on
27902 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
27903 	 *    will give us two packets because we join G on both the
27904 	 *    interfaces rather than nominating just one interface
27905 	 *    for receiving multicast like broadcast above. So,
27906 	 *    we have to call ilg_lookup_ill to filter out duplicate
27907 	 *    copies, if ill is part of a group.
27908 	 */
27909 	in_ill = connp->conn_incoming_ill;
27910 	if (in_ill != NULL) {
27911 		if (in_ill->ill_group == NULL) {
27912 			if (in_ill != ill)
27913 				return (B_FALSE);
27914 		} else if (in_ill->ill_group != ill->ill_group) {
27915 			return (B_FALSE);
27916 		}
27917 	}
27918 
27919 	if (!CLASSD(dst)) {
27920 		if (IPCL_ZONE_MATCH(connp, zoneid))
27921 			return (B_TRUE);
27922 		/*
27923 		 * The conn is in a different zone; we need to check that this
27924 		 * broadcast address is configured in the application's zone and
27925 		 * on one ill in the group.
27926 		 */
27927 		ipif = ipif_get_next_ipif(NULL, ill);
27928 		if (ipif == NULL)
27929 			return (B_FALSE);
27930 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
27931 		    connp->conn_zoneid, NULL,
27932 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
27933 		ipif_refrele(ipif);
27934 		if (ire != NULL) {
27935 			ire_refrele(ire);
27936 			return (B_TRUE);
27937 		} else {
27938 			return (B_FALSE);
27939 		}
27940 	}
27941 
27942 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
27943 	    connp->conn_zoneid == zoneid) {
27944 		/*
27945 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
27946 		 * disabled, therefore we don't dispatch the multicast packet to
27947 		 * the sending zone.
27948 		 */
27949 		return (B_FALSE);
27950 	}
27951 
27952 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
27953 	    connp->conn_zoneid != zoneid) {
27954 		/*
27955 		 * Multicast packet on the loopback interface: we only match
27956 		 * conns who joined the group in the specified zone.
27957 		 */
27958 		return (B_FALSE);
27959 	}
27960 
27961 	if (connp->conn_multi_router) {
27962 		/* multicast packet and multicast router socket: send up */
27963 		return (B_TRUE);
27964 	}
27965 
27966 	mutex_enter(&connp->conn_lock);
27967 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
27968 	mutex_exit(&connp->conn_lock);
27969 	return (found);
27970 }
27971 
27972 /*
27973  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
27974  */
27975 /* ARGSUSED */
27976 static void
27977 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
27978 {
27979 	ill_t *ill = (ill_t *)q->q_ptr;
27980 	mblk_t	*mp1, *mp2;
27981 	ipif_t  *ipif;
27982 	int err = 0;
27983 	conn_t *connp = NULL;
27984 	ipsq_t	*ipsq;
27985 	arc_t	*arc;
27986 
27987 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
27988 
27989 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
27990 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
27991 
27992 	ASSERT(IAM_WRITER_ILL(ill));
27993 	mp2 = mp->b_cont;
27994 	mp->b_cont = NULL;
27995 
27996 	/*
27997 	 * We have now received the arp bringup completion message
27998 	 * from ARP. Mark the arp bringup as done. Also if the arp
27999 	 * stream has already started closing, send up the AR_ARP_CLOSING
28000 	 * ack now since ARP is waiting in close for this ack.
28001 	 */
28002 	mutex_enter(&ill->ill_lock);
28003 	ill->ill_arp_bringup_pending = 0;
28004 	if (ill->ill_arp_closing) {
28005 		mutex_exit(&ill->ill_lock);
28006 		/* Let's reuse the mp for sending the ack */
28007 		arc = (arc_t *)mp->b_rptr;
28008 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28009 		arc->arc_cmd = AR_ARP_CLOSING;
28010 		qreply(q, mp);
28011 	} else {
28012 		mutex_exit(&ill->ill_lock);
28013 		freeb(mp);
28014 	}
28015 
28016 	/* We should have an IOCTL waiting on this. */
28017 	ipsq = ill->ill_phyint->phyint_ipsq;
28018 	ipif = ipsq->ipsq_pending_ipif;
28019 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28020 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
28021 	if (mp1 == NULL) {
28022 		/* bringup was aborted by the user */
28023 		freemsg(mp2);
28024 		return;
28025 	}
28026 	ASSERT(connp != NULL);
28027 	q = CONNP_TO_WQ(connp);
28028 	/*
28029 	 * If the DL_BIND_REQ fails, it is noted
28030 	 * in arc_name_offset.
28031 	 */
28032 	err = *((int *)mp2->b_rptr);
28033 	if (err == 0) {
28034 		if (ipif->ipif_isv6) {
28035 			if ((err = ipif_up_done_v6(ipif)) != 0)
28036 				ip0dbg(("ip_arp_done: init failed\n"));
28037 		} else {
28038 			if ((err = ipif_up_done(ipif)) != 0)
28039 				ip0dbg(("ip_arp_done: init failed\n"));
28040 		}
28041 	} else {
28042 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28043 	}
28044 
28045 	freemsg(mp2);
28046 
28047 	if ((err == 0) && (ill->ill_up_ipifs)) {
28048 		err = ill_up_ipifs(ill, q, mp1);
28049 		if (err == EINPROGRESS)
28050 			return;
28051 	}
28052 
28053 	if (ill->ill_up_ipifs) {
28054 		ill_group_cleanup(ill);
28055 	}
28056 
28057 	/*
28058 	 * The ioctl must complete now without EINPROGRESS
28059 	 * since ipsq_pending_mp_get has removed the ioctl mblk
28060 	 * from ipsq_pending_mp. Otherwise the ioctl will be
28061 	 * stuck for ever in the ipsq.
28062 	 */
28063 	ASSERT(err != EINPROGRESS);
28064 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
28065 }
28066 
28067 /* Allocate the private structure */
28068 static int
28069 ip_priv_alloc(void **bufp)
28070 {
28071 	void	*buf;
28072 
28073 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28074 		return (ENOMEM);
28075 
28076 	*bufp = buf;
28077 	return (0);
28078 }
28079 
28080 /* Function to delete the private structure */
28081 void
28082 ip_priv_free(void *buf)
28083 {
28084 	ASSERT(buf != NULL);
28085 	kmem_free(buf, sizeof (ip_priv_t));
28086 }
28087 
28088 /*
28089  * The entry point for IPPF processing.
28090  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28091  * routine just returns.
28092  *
28093  * When called, ip_process generates an ipp_packet_t structure
28094  * which holds the state information for this packet and invokes the
28095  * the classifier (via ipp_packet_process). The classification, depending on
28096  * configured filters, results in a list of actions for this packet. Invoking
28097  * an action may cause the packet to be dropped, in which case the resulting
28098  * mblk (*mpp) is NULL. proc indicates the callout position for
28099  * this packet and ill_index is the interface this packet on or will leave
28100  * on (inbound and outbound resp.).
28101  */
28102 void
28103 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28104 {
28105 	mblk_t		*mp;
28106 	ip_priv_t	*priv;
28107 	ipp_action_id_t	aid;
28108 	int		rc = 0;
28109 	ipp_packet_t	*pp;
28110 #define	IP_CLASS	"ip"
28111 
28112 	/* If the classifier is not loaded, return  */
28113 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28114 		return;
28115 	}
28116 
28117 	mp = *mpp;
28118 	ASSERT(mp != NULL);
28119 
28120 	/* Allocate the packet structure */
28121 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28122 	if (rc != 0) {
28123 		*mpp = NULL;
28124 		freemsg(mp);
28125 		return;
28126 	}
28127 
28128 	/* Allocate the private structure */
28129 	rc = ip_priv_alloc((void **)&priv);
28130 	if (rc != 0) {
28131 		*mpp = NULL;
28132 		freemsg(mp);
28133 		ipp_packet_free(pp);
28134 		return;
28135 	}
28136 	priv->proc = proc;
28137 	priv->ill_index = ill_index;
28138 	ipp_packet_set_private(pp, priv, ip_priv_free);
28139 	ipp_packet_set_data(pp, mp);
28140 
28141 	/* Invoke the classifier */
28142 	rc = ipp_packet_process(&pp);
28143 	if (pp != NULL) {
28144 		mp = ipp_packet_get_data(pp);
28145 		ipp_packet_free(pp);
28146 		if (rc != 0) {
28147 			freemsg(mp);
28148 			*mpp = NULL;
28149 		}
28150 	} else {
28151 		*mpp = NULL;
28152 	}
28153 #undef	IP_CLASS
28154 }
28155 
28156 /*
28157  * Propagate a multicast group membership operation (add/drop) on
28158  * all the interfaces crossed by the related multirt routes.
28159  * The call is considered successful if the operation succeeds
28160  * on at least one interface.
28161  */
28162 static int
28163 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28164     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28165     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28166     mblk_t *first_mp)
28167 {
28168 	ire_t		*ire_gw;
28169 	irb_t		*irb;
28170 	int		error = 0;
28171 	opt_restart_t	*or;
28172 
28173 	irb = ire->ire_bucket;
28174 	ASSERT(irb != NULL);
28175 
28176 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28177 
28178 	or = (opt_restart_t *)first_mp->b_rptr;
28179 	IRB_REFHOLD(irb);
28180 	for (; ire != NULL; ire = ire->ire_next) {
28181 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28182 			continue;
28183 		if (ire->ire_addr != group)
28184 			continue;
28185 
28186 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28187 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28188 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
28189 		/* No resolver exists for the gateway; skip this ire. */
28190 		if (ire_gw == NULL)
28191 			continue;
28192 
28193 		/*
28194 		 * This function can return EINPROGRESS. If so the operation
28195 		 * will be restarted from ip_restart_optmgmt which will
28196 		 * call ip_opt_set and option processing will restart for
28197 		 * this option. So we may end up calling 'fn' more than once.
28198 		 * This requires that 'fn' is idempotent except for the
28199 		 * return value. The operation is considered a success if
28200 		 * it succeeds at least once on any one interface.
28201 		 */
28202 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28203 		    NULL, fmode, src, first_mp);
28204 		if (error == 0)
28205 			or->or_private = CGTP_MCAST_SUCCESS;
28206 
28207 		if (ip_debug > 0) {
28208 			ulong_t	off;
28209 			char	*ksym;
28210 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28211 			ip2dbg(("ip_multirt_apply_membership: "
28212 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28213 			    "error %d [success %u]\n",
28214 			    ksym ? ksym : "?",
28215 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28216 			    error, or->or_private));
28217 		}
28218 
28219 		ire_refrele(ire_gw);
28220 		if (error == EINPROGRESS) {
28221 			IRB_REFRELE(irb);
28222 			return (error);
28223 		}
28224 	}
28225 	IRB_REFRELE(irb);
28226 	/*
28227 	 * Consider the call as successful if we succeeded on at least
28228 	 * one interface. Otherwise, return the last encountered error.
28229 	 */
28230 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28231 }
28232 
28233 
28234 /*
28235  * Issue a warning regarding a route crossing an interface with an
28236  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28237  * amount of time is logged.
28238  */
28239 static void
28240 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28241 {
28242 	hrtime_t	current = gethrtime();
28243 	char		buf[INET_ADDRSTRLEN];
28244 
28245 	/* Convert interval in ms to hrtime in ns */
28246 	if (multirt_bad_mtu_last_time +
28247 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
28248 	    current) {
28249 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28250 		    "to %s, incorrect MTU %u (expected %u)\n",
28251 		    ip_dot_addr(ire->ire_addr, buf),
28252 		    ire->ire_max_frag, max_frag);
28253 
28254 		multirt_bad_mtu_last_time = current;
28255 	}
28256 }
28257 
28258 
28259 /*
28260  * Get the CGTP (multirouting) filtering status.
28261  * If 0, the CGTP hooks are transparent.
28262  */
28263 /* ARGSUSED */
28264 static int
28265 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28266 {
28267 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28268 
28269 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28270 	return (0);
28271 }
28272 
28273 
28274 /*
28275  * Set the CGTP (multirouting) filtering status.
28276  * If the status is changed from active to transparent
28277  * or from transparent to active, forward the new status
28278  * to the filtering module (if loaded).
28279  */
28280 /* ARGSUSED */
28281 static int
28282 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28283     cred_t *ioc_cr)
28284 {
28285 	long		new_value;
28286 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28287 
28288 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28289 	    new_value < 0 || new_value > 1) {
28290 		return (EINVAL);
28291 	}
28292 
28293 	/*
28294 	 * Do not enable CGTP filtering - thus preventing the hooks
28295 	 * from being invoked - if the version number of the
28296 	 * filtering module hooks does not match.
28297 	 */
28298 	if ((ip_cgtp_filter_ops != NULL) &&
28299 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
28300 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
28301 		    "(module hooks version %d, expecting %d)\n",
28302 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
28303 		return (ENOTSUP);
28304 	}
28305 
28306 	if ((!*ip_cgtp_filter_value) && new_value) {
28307 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28308 		    ip_cgtp_filter_ops == NULL ?
28309 		    " (module not loaded)" : "");
28310 	}
28311 	if (*ip_cgtp_filter_value && (!new_value)) {
28312 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28313 		    ip_cgtp_filter_ops == NULL ?
28314 		    " (module not loaded)" : "");
28315 	}
28316 
28317 	if (ip_cgtp_filter_ops != NULL) {
28318 		int	res;
28319 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
28320 			return (res);
28321 		}
28322 	}
28323 
28324 	*ip_cgtp_filter_value = (boolean_t)new_value;
28325 
28326 	return (0);
28327 }
28328 
28329 
28330 /*
28331  * Return the expected CGTP hooks version number.
28332  */
28333 int
28334 ip_cgtp_filter_supported(void)
28335 {
28336 	return (ip_cgtp_filter_rev);
28337 }
28338 
28339 
28340 /*
28341  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
28342  * or by invoking this function. In the first case, the version number
28343  * of the registered structure is checked at hooks activation time
28344  * in ip_cgtp_filter_set().
28345  */
28346 int
28347 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
28348 {
28349 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28350 		return (ENOTSUP);
28351 
28352 	ip_cgtp_filter_ops = ops;
28353 	return (0);
28354 }
28355 
28356 static squeue_func_t
28357 ip_squeue_switch(int val)
28358 {
28359 	squeue_func_t rval = squeue_fill;
28360 
28361 	switch (val) {
28362 	case IP_SQUEUE_ENTER_NODRAIN:
28363 		rval = squeue_enter_nodrain;
28364 		break;
28365 	case IP_SQUEUE_ENTER:
28366 		rval = squeue_enter;
28367 		break;
28368 	default:
28369 		break;
28370 	}
28371 	return (rval);
28372 }
28373 
28374 /* ARGSUSED */
28375 static int
28376 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28377     caddr_t addr, cred_t *cr)
28378 {
28379 	int *v = (int *)addr;
28380 	long new_value;
28381 
28382 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28383 		return (EINVAL);
28384 
28385 	ip_input_proc = ip_squeue_switch(new_value);
28386 	*v = new_value;
28387 	return (0);
28388 }
28389 
28390 /* ARGSUSED */
28391 static int
28392 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28393     caddr_t addr, cred_t *cr)
28394 {
28395 	int *v = (int *)addr;
28396 	long new_value;
28397 
28398 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28399 		return (EINVAL);
28400 
28401 	*v = new_value;
28402 	return (0);
28403 }
28404 
28405 static void
28406 ip_kstat_init(void)
28407 {
28408 	ip_named_kstat_t template = {
28409 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
28410 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
28411 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
28412 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
28413 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
28414 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
28415 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
28416 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
28417 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
28418 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
28419 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
28420 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
28421 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
28422 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
28423 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
28424 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
28425 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
28426 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
28427 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
28428 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
28429 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
28430 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
28431 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
28432 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
28433 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
28434 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
28435 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
28436 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
28437 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
28438 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
28439 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
28440 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
28441 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
28442 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
28443 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
28444 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
28445 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
28446 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
28447 	};
28448 
28449 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
28450 					NUM_OF_FIELDS(ip_named_kstat_t),
28451 					0);
28452 	if (!ip_mibkp)
28453 		return;
28454 
28455 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
28456 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
28457 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
28458 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
28459 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
28460 
28461 	template.netToMediaEntrySize.value.i32 =
28462 		sizeof (mib2_ipNetToMediaEntry_t);
28463 
28464 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
28465 
28466 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
28467 
28468 	ip_mibkp->ks_update = ip_kstat_update;
28469 
28470 	kstat_install(ip_mibkp);
28471 }
28472 
28473 static void
28474 ip_kstat_fini(void)
28475 {
28476 
28477 	if (ip_mibkp != NULL) {
28478 		kstat_delete(ip_mibkp);
28479 		ip_mibkp = NULL;
28480 	}
28481 }
28482 
28483 static int
28484 ip_kstat_update(kstat_t *kp, int rw)
28485 {
28486 	ip_named_kstat_t *ipkp;
28487 
28488 	if (!kp || !kp->ks_data)
28489 		return (EIO);
28490 
28491 	if (rw == KSTAT_WRITE)
28492 		return (EACCES);
28493 
28494 	ipkp = (ip_named_kstat_t *)kp->ks_data;
28495 
28496 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
28497 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
28498 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
28499 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
28500 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
28501 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
28502 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
28503 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
28504 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
28505 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
28506 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
28507 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
28508 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
28509 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
28510 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
28511 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
28512 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
28513 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
28514 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
28515 
28516 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
28517 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
28518 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
28519 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
28520 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
28521 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
28522 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
28523 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
28524 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
28525 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
28526 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
28527 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
28528 
28529 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
28530 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
28531 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
28532 
28533 	return (0);
28534 }
28535 
28536 static void
28537 icmp_kstat_init(void)
28538 {
28539 	icmp_named_kstat_t template = {
28540 		{ "inMsgs",		KSTAT_DATA_UINT32 },
28541 		{ "inErrors",		KSTAT_DATA_UINT32 },
28542 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
28543 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
28544 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
28545 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
28546 		{ "inRedirects",	KSTAT_DATA_UINT32 },
28547 		{ "inEchos",		KSTAT_DATA_UINT32 },
28548 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
28549 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
28550 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
28551 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
28552 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
28553 		{ "outMsgs",		KSTAT_DATA_UINT32 },
28554 		{ "outErrors",		KSTAT_DATA_UINT32 },
28555 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
28556 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
28557 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
28558 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
28559 		{ "outRedirects",	KSTAT_DATA_UINT32 },
28560 		{ "outEchos",		KSTAT_DATA_UINT32 },
28561 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
28562 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
28563 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
28564 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
28565 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
28566 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
28567 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
28568 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
28569 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
28570 		{ "outDrops",		KSTAT_DATA_UINT32 },
28571 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
28572 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
28573 	};
28574 
28575 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
28576 					NUM_OF_FIELDS(icmp_named_kstat_t),
28577 					0);
28578 	if (icmp_mibkp == NULL)
28579 		return;
28580 
28581 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
28582 
28583 	icmp_mibkp->ks_update = icmp_kstat_update;
28584 
28585 	kstat_install(icmp_mibkp);
28586 }
28587 
28588 static void
28589 icmp_kstat_fini(void)
28590 {
28591 
28592 	if (icmp_mibkp != NULL) {
28593 		kstat_delete(icmp_mibkp);
28594 		icmp_mibkp = NULL;
28595 	}
28596 }
28597 
28598 static int
28599 icmp_kstat_update(kstat_t *kp, int rw)
28600 {
28601 	icmp_named_kstat_t *icmpkp;
28602 
28603 	if ((kp == NULL) || (kp->ks_data == NULL))
28604 		return (EIO);
28605 
28606 	if (rw == KSTAT_WRITE)
28607 		return (EACCES);
28608 
28609 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
28610 
28611 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
28612 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
28613 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
28614 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
28615 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
28616 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
28617 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
28618 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
28619 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
28620 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
28621 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
28622 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
28623 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
28624 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
28625 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
28626 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
28627 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
28628 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
28629 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
28630 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
28631 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
28632 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
28633 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
28634 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
28635 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
28636 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
28637 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
28638 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
28639 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
28640 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
28641 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
28642 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
28643 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
28644 
28645 	return (0);
28646 }
28647 
28648 /*
28649  * This is the fanout function for raw socket opened for SCTP.  Note
28650  * that it is called after SCTP checks that there is no socket which
28651  * wants a packet.  Then before SCTP handles this out of the blue packet,
28652  * this function is called to see if there is any raw socket for SCTP.
28653  * If there is and it is bound to the correct address, the packet will
28654  * be sent to that socket.  Note that only one raw socket can be bound to
28655  * a port.  This is assured in ipcl_sctp_hash_insert();
28656  */
28657 void
28658 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
28659     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
28660     uint_t ipif_seqid, zoneid_t zoneid)
28661 {
28662 	conn_t		*connp;
28663 	queue_t		*rq;
28664 	mblk_t		*first_mp;
28665 	boolean_t	secure;
28666 	ip6_t		*ip6h;
28667 
28668 	first_mp = mp;
28669 	if (mctl_present) {
28670 		mp = first_mp->b_cont;
28671 		secure = ipsec_in_is_secure(first_mp);
28672 		ASSERT(mp != NULL);
28673 	} else {
28674 		secure = B_FALSE;
28675 	}
28676 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
28677 
28678 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
28679 	if (connp == NULL) {
28680 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
28681 		    mctl_present);
28682 		return;
28683 	}
28684 	rq = connp->conn_rq;
28685 	if (!canputnext(rq)) {
28686 		CONN_DEC_REF(connp);
28687 		BUMP_MIB(&ip_mib, rawipInOverflows);
28688 		freemsg(first_mp);
28689 		return;
28690 	}
28691 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
28692 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
28693 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
28694 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
28695 		if (first_mp == NULL) {
28696 			CONN_DEC_REF(connp);
28697 			return;
28698 		}
28699 	}
28700 	/*
28701 	 * We probably should not send M_CTL message up to
28702 	 * raw socket.
28703 	 */
28704 	if (mctl_present)
28705 		freeb(first_mp);
28706 
28707 	/* Initiate IPPF processing here if needed. */
28708 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
28709 	    (!isv4 && IP6_IN_IPP(flags))) {
28710 		ip_process(IPP_LOCAL_IN, &mp,
28711 		    recv_ill->ill_phyint->phyint_ifindex);
28712 		if (mp == NULL) {
28713 			CONN_DEC_REF(connp);
28714 			return;
28715 		}
28716 	}
28717 
28718 	if (connp->conn_recvif || connp->conn_recvslla ||
28719 	    ((connp->conn_ipv6_recvpktinfo ||
28720 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
28721 	    (flags & IP_FF_IP6INFO))) {
28722 		int in_flags = 0;
28723 
28724 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
28725 			in_flags = IPF_RECVIF;
28726 		}
28727 		if (connp->conn_recvslla) {
28728 			in_flags |= IPF_RECVSLLA;
28729 		}
28730 		if (isv4) {
28731 			mp = ip_add_info(mp, recv_ill, in_flags);
28732 		} else {
28733 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
28734 			if (mp == NULL) {
28735 				CONN_DEC_REF(connp);
28736 				return;
28737 			}
28738 		}
28739 	}
28740 
28741 	BUMP_MIB(&ip_mib, ipInDelivers);
28742 	/*
28743 	 * We are sending the IPSEC_IN message also up. Refer
28744 	 * to comments above this function.
28745 	 */
28746 	putnext(rq, mp);
28747 	CONN_DEC_REF(connp);
28748 }
28749 
28750 /*
28751  * This function should be called only if all packet processing
28752  * including fragmentation is complete. Callers of this function
28753  * must set mp->b_prev to one of these values:
28754  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
28755  * prior to handing over the mp as first argument to this function.
28756  *
28757  * If the ire passed by caller is incomplete, this function
28758  * queues the packet and if necessary, sends ARP request and bails.
28759  * If the ire passed is fully resolved, we simply prepend
28760  * the link-layer header to the packet, do ipsec hw acceleration
28761  * work if necessary, and send the packet out on the wire.
28762  *
28763  * NOTE: IPSEC will only call this function with fully resolved
28764  * ires if hw acceleration is involved.
28765  * TODO list :
28766  * 	a Handle M_MULTIDATA so that
28767  *	  tcp_multisend->tcp_multisend_data can
28768  *	  call ip_xmit_v4 directly
28769  *	b Handle post-ARP work for fragments so that
28770  *	  ip_wput_frag can call this function.
28771  */
28772 ipxmit_state_t
28773 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
28774 {
28775 	nce_t		*arpce;
28776 	queue_t		*q;
28777 	int		ill_index;
28778 	mblk_t		*nxt_mp, *first_mp;
28779 	boolean_t	xmit_drop = B_FALSE;
28780 	ip_proc_t	proc;
28781 	ill_t		*out_ill;
28782 
28783 	arpce = ire->ire_nce;
28784 	ASSERT(arpce != NULL);
28785 
28786 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
28787 
28788 	mutex_enter(&arpce->nce_lock);
28789 	switch (arpce->nce_state) {
28790 	case ND_REACHABLE:
28791 		/* If there are other queued packets, queue this packet */
28792 		if (arpce->nce_qd_mp != NULL) {
28793 			if (mp != NULL)
28794 				nce_queue_mp_common(arpce, mp, B_FALSE);
28795 			mp = arpce->nce_qd_mp;
28796 		}
28797 		arpce->nce_qd_mp = NULL;
28798 		mutex_exit(&arpce->nce_lock);
28799 
28800 		/*
28801 		 * Flush the queue.  In the common case, where the
28802 		 * ARP is already resolved,  it will go through the
28803 		 * while loop only once.
28804 		 */
28805 		while (mp != NULL) {
28806 
28807 			nxt_mp = mp->b_next;
28808 			mp->b_next = NULL;
28809 			/*
28810 			 * This info is needed for IPQOS to do COS marking
28811 			 * in ip_wput_attach_llhdr->ip_process.
28812 			 */
28813 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
28814 			mp->b_prev = NULL;
28815 
28816 			/* set up ill index for outbound qos processing */
28817 			out_ill = ire->ire_ipif->ipif_ill;
28818 			ill_index = out_ill->ill_phyint->phyint_ifindex;
28819 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
28820 			    ill_index);
28821 			if (first_mp == NULL) {
28822 				xmit_drop = B_TRUE;
28823 				if (proc == IPP_FWD_OUT) {
28824 					BUMP_MIB(&ip_mib, ipInDiscards);
28825 				} else {
28826 					BUMP_MIB(&ip_mib, ipOutDiscards);
28827 				}
28828 				goto next_mp;
28829 			}
28830 			/* non-ipsec hw accel case */
28831 			if (io == NULL || !io->ipsec_out_accelerated) {
28832 				/* send it */
28833 				q = ire->ire_stq;
28834 				if (proc == IPP_FWD_OUT) {
28835 					UPDATE_IB_PKT_COUNT(ire);
28836 				} else {
28837 					UPDATE_OB_PKT_COUNT(ire);
28838 				}
28839 				ire->ire_last_used_time = lbolt;
28840 
28841 				if (flow_ctl_enabled || canputnext(q))  {
28842 					if (proc == IPP_FWD_OUT) {
28843 						BUMP_MIB(&ip_mib,
28844 						    ipForwDatagrams);
28845 					}
28846 
28847 					if (mp == NULL)
28848 						goto next_mp;
28849 					putnext(q, first_mp);
28850 				} else {
28851 					BUMP_MIB(&ip_mib,
28852 					    ipOutDiscards);
28853 					xmit_drop = B_TRUE;
28854 					freemsg(first_mp);
28855 				}
28856 			} else {
28857 				/*
28858 				 * Safety Pup says: make sure this
28859 				 *  is going to the right interface!
28860 				 */
28861 				ill_t *ill1 =
28862 				    (ill_t *)ire->ire_stq->q_ptr;
28863 				int ifindex =
28864 				    ill1->ill_phyint->phyint_ifindex;
28865 				if (ifindex !=
28866 				    io->ipsec_out_capab_ill_index) {
28867 					xmit_drop = B_TRUE;
28868 					freemsg(mp);
28869 				} else {
28870 					ipsec_hw_putnext(ire->ire_stq,
28871 					    mp);
28872 				}
28873 			}
28874 next_mp:
28875 			mp = nxt_mp;
28876 		} /* while (mp != NULL) */
28877 		if (xmit_drop)
28878 			return (SEND_FAILED);
28879 		else
28880 			return (SEND_PASSED);
28881 
28882 	case ND_INITIAL:
28883 	case ND_INCOMPLETE:
28884 
28885 		/*
28886 		 * While we do send off packets to dests that
28887 		 * use fully-resolved CGTP routes, we do not
28888 		 * handle unresolved CGTP routes.
28889 		 */
28890 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
28891 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
28892 
28893 		if (mp != NULL) {
28894 			/* queue the packet */
28895 			nce_queue_mp_common(arpce, mp, B_FALSE);
28896 		}
28897 
28898 		if (arpce->nce_state == ND_INCOMPLETE) {
28899 			mutex_exit(&arpce->nce_lock);
28900 			DTRACE_PROBE3(ip__xmit__incomplete,
28901 			    (ire_t *), ire, (mblk_t *), mp,
28902 			    (ipsec_out_t *), io);
28903 			return (LOOKUP_IN_PROGRESS);
28904 		}
28905 
28906 		arpce->nce_state = ND_INCOMPLETE;
28907 		mutex_exit(&arpce->nce_lock);
28908 		/*
28909 		 * Note that ire_add() (called from ire_forward())
28910 		 * holds a ref on the ire until ARP is completed.
28911 		 */
28912 
28913 		ire_arpresolve(ire, ire_to_ill(ire));
28914 		return (LOOKUP_IN_PROGRESS);
28915 	default:
28916 		ASSERT(0);
28917 		mutex_exit(&arpce->nce_lock);
28918 		return (LLHDR_RESLV_FAILED);
28919 	}
28920 }
28921 
28922 /*
28923  * Return B_TRUE if the buffers differ in length or content.
28924  * This is used for comparing extension header buffers.
28925  * Note that an extension header would be declared different
28926  * even if all that changed was the next header value in that header i.e.
28927  * what really changed is the next extension header.
28928  */
28929 boolean_t
28930 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
28931     uint_t blen)
28932 {
28933 	if (!b_valid)
28934 		blen = 0;
28935 
28936 	if (alen != blen)
28937 		return (B_TRUE);
28938 	if (alen == 0)
28939 		return (B_FALSE);	/* Both zero length */
28940 	return (bcmp(abuf, bbuf, alen));
28941 }
28942 
28943 /*
28944  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
28945  * Return B_FALSE if memory allocation fails - don't change any state!
28946  */
28947 boolean_t
28948 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28949     const void *src, uint_t srclen)
28950 {
28951 	void *dst;
28952 
28953 	if (!src_valid)
28954 		srclen = 0;
28955 
28956 	ASSERT(*dstlenp == 0);
28957 	if (src != NULL && srclen != 0) {
28958 		dst = mi_alloc(srclen, BPRI_MED);
28959 		if (dst == NULL)
28960 			return (B_FALSE);
28961 	} else {
28962 		dst = NULL;
28963 	}
28964 	if (*dstp != NULL)
28965 		mi_free(*dstp);
28966 	*dstp = dst;
28967 	*dstlenp = dst == NULL ? 0 : srclen;
28968 	return (B_TRUE);
28969 }
28970 
28971 /*
28972  * Replace what is in *dst, *dstlen with the source.
28973  * Assumes ip_allocbuf has already been called.
28974  */
28975 void
28976 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28977     const void *src, uint_t srclen)
28978 {
28979 	if (!src_valid)
28980 		srclen = 0;
28981 
28982 	ASSERT(*dstlenp == srclen);
28983 	if (src != NULL && srclen != 0)
28984 		bcopy(src, *dstp, srclen);
28985 }
28986 
28987 /*
28988  * Free the storage pointed to by the members of an ip6_pkt_t.
28989  */
28990 void
28991 ip6_pkt_free(ip6_pkt_t *ipp)
28992 {
28993 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
28994 
28995 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
28996 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
28997 		ipp->ipp_hopopts = NULL;
28998 		ipp->ipp_hopoptslen = 0;
28999 	}
29000 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29001 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29002 		ipp->ipp_rtdstopts = NULL;
29003 		ipp->ipp_rtdstoptslen = 0;
29004 	}
29005 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29006 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29007 		ipp->ipp_dstopts = NULL;
29008 		ipp->ipp_dstoptslen = 0;
29009 	}
29010 	if (ipp->ipp_fields & IPPF_RTHDR) {
29011 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29012 		ipp->ipp_rthdr = NULL;
29013 		ipp->ipp_rthdrlen = 0;
29014 	}
29015 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29016 	    IPPF_RTHDR);
29017 }
29018