xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision 753d2d2e8e7fd0c9bcf736d9bf2f2faf4d6234cc)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /* Copyright (c) 1990 Mentat Inc. */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/stream.h>
31 #include <sys/dlpi.h>
32 #include <sys/stropts.h>
33 #include <sys/sysmacros.h>
34 #include <sys/strsubr.h>
35 #include <sys/strlog.h>
36 #include <sys/strsun.h>
37 #include <sys/zone.h>
38 #define	_SUN_TPI_VERSION 2
39 #include <sys/tihdr.h>
40 #include <sys/xti_inet.h>
41 #include <sys/ddi.h>
42 #include <sys/sunddi.h>
43 #include <sys/cmn_err.h>
44 #include <sys/debug.h>
45 #include <sys/kobj.h>
46 #include <sys/modctl.h>
47 #include <sys/atomic.h>
48 #include <sys/policy.h>
49 #include <sys/priv.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <net/if.h>
58 #include <net/if_arp.h>
59 #include <net/route.h>
60 #include <sys/sockio.h>
61 #include <netinet/in.h>
62 #include <net/if_dl.h>
63 
64 #include <inet/common.h>
65 #include <inet/mi.h>
66 #include <inet/mib2.h>
67 #include <inet/nd.h>
68 #include <inet/arp.h>
69 #include <inet/snmpcom.h>
70 #include <inet/kstatcom.h>
71 
72 #include <netinet/igmp_var.h>
73 #include <netinet/ip6.h>
74 #include <netinet/icmp6.h>
75 #include <netinet/sctp.h>
76 
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip6_asp.h>
81 #include <inet/tcp.h>
82 #include <inet/tcp_impl.h>
83 #include <inet/ip_multi.h>
84 #include <inet/ip_if.h>
85 #include <inet/ip_ire.h>
86 #include <inet/ip_ftable.h>
87 #include <inet/ip_rts.h>
88 #include <inet/optcom.h>
89 #include <inet/ip_ndp.h>
90 #include <inet/ip_listutils.h>
91 #include <netinet/igmp.h>
92 #include <netinet/ip_mroute.h>
93 #include <inet/ipp_common.h>
94 
95 #include <net/pfkeyv2.h>
96 #include <inet/ipsec_info.h>
97 #include <inet/sadb.h>
98 #include <inet/ipsec_impl.h>
99 #include <sys/iphada.h>
100 #include <inet/tun.h>
101 #include <inet/ipdrop.h>
102 
103 #include <sys/ethernet.h>
104 #include <net/if_types.h>
105 #include <sys/cpuvar.h>
106 
107 #include <ipp/ipp.h>
108 #include <ipp/ipp_impl.h>
109 #include <ipp/ipgpc/ipgpc.h>
110 
111 #include <sys/multidata.h>
112 #include <sys/pattr.h>
113 
114 #include <inet/ipclassifier.h>
115 #include <inet/sctp_ip.h>
116 #include <inet/sctp/sctp_impl.h>
117 #include <inet/udp_impl.h>
118 
119 #include <sys/tsol/label.h>
120 #include <sys/tsol/tnet.h>
121 
122 #include <rpc/pmap_prot.h>
123 
124 /*
125  * Values for squeue switch:
126  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
127  * IP_SQUEUE_ENTER: squeue_enter
128  * IP_SQUEUE_FILL: squeue_fill
129  */
130 int ip_squeue_enter = 2;
131 squeue_func_t ip_input_proc;
132 /*
133  * IP statistics.
134  */
135 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
136 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
137 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
138 
139 typedef struct ip_stat {
140 	kstat_named_t	ipsec_fanout_proto;
141 	kstat_named_t	ip_udp_fannorm;
142 	kstat_named_t	ip_udp_fanmb;
143 	kstat_named_t	ip_udp_fanothers;
144 	kstat_named_t	ip_udp_fast_path;
145 	kstat_named_t	ip_udp_slow_path;
146 	kstat_named_t	ip_udp_input_err;
147 	kstat_named_t	ip_tcppullup;
148 	kstat_named_t	ip_tcpoptions;
149 	kstat_named_t	ip_multipkttcp;
150 	kstat_named_t	ip_tcp_fast_path;
151 	kstat_named_t	ip_tcp_slow_path;
152 	kstat_named_t	ip_tcp_input_error;
153 	kstat_named_t	ip_db_ref;
154 	kstat_named_t	ip_notaligned1;
155 	kstat_named_t	ip_notaligned2;
156 	kstat_named_t	ip_multimblk3;
157 	kstat_named_t	ip_multimblk4;
158 	kstat_named_t	ip_ipoptions;
159 	kstat_named_t	ip_classify_fail;
160 	kstat_named_t	ip_opt;
161 	kstat_named_t	ip_udp_rput_local;
162 	kstat_named_t	ipsec_proto_ahesp;
163 	kstat_named_t	ip_conn_flputbq;
164 	kstat_named_t	ip_conn_walk_drain;
165 	kstat_named_t   ip_out_sw_cksum;
166 	kstat_named_t   ip_in_sw_cksum;
167 	kstat_named_t   ip_trash_ire_reclaim_calls;
168 	kstat_named_t   ip_trash_ire_reclaim_success;
169 	kstat_named_t   ip_ire_arp_timer_expired;
170 	kstat_named_t   ip_ire_redirect_timer_expired;
171 	kstat_named_t	ip_ire_pmtu_timer_expired;
172 	kstat_named_t	ip_input_multi_squeue;
173 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
174 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
175 	kstat_named_t	ip_tcp_in_sw_cksum_err;
176 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
177 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
178 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
179 	kstat_named_t	ip_udp_in_sw_cksum_err;
180 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
181 	kstat_named_t	ip_frag_mdt_pkt_out;
182 	kstat_named_t	ip_frag_mdt_discarded;
183 	kstat_named_t	ip_frag_mdt_allocfail;
184 	kstat_named_t	ip_frag_mdt_addpdescfail;
185 	kstat_named_t	ip_frag_mdt_allocd;
186 } ip_stat_t;
187 
188 static ip_stat_t ip_statistics = {
189 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
190 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
191 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
192 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
193 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
194 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
195 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
196 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
197 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
198 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
199 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
200 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
201 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
202 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
203 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
204 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
205 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
206 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
207 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
208 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
209 	{ "ip_opt",				KSTAT_DATA_UINT64 },
210 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
211 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
212 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
213 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
214 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
215 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
216 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
217 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
218 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
219 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
220 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
221 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
222 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
223 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
224 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
225 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
226 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
227 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
228 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
229 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
230 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
231 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
232 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
233 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
234 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
235 };
236 
237 static kstat_t *ip_kstat;
238 
239 #define	TCP6 "tcp6"
240 #define	TCP "tcp"
241 #define	SCTP "sctp"
242 #define	SCTP6 "sctp6"
243 
244 major_t TCP6_MAJ;
245 major_t TCP_MAJ;
246 major_t SCTP_MAJ;
247 major_t SCTP6_MAJ;
248 
249 int ip_poll_normal_ms = 100;
250 int ip_poll_normal_ticks = 0;
251 
252 /*
253  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
254  */
255 
256 struct listptr_s {
257 	mblk_t	*lp_head;	/* pointer to the head of the list */
258 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
259 };
260 
261 typedef struct listptr_s listptr_t;
262 
263 /*
264  * This is used by ip_snmp_get_mib2_ip_route_media and
265  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
266  */
267 typedef struct iproutedata_s {
268 	uint_t		ird_idx;
269 	listptr_t	ird_route;	/* ipRouteEntryTable */
270 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
271 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
272 } iproutedata_t;
273 
274 /*
275  * Cluster specific hooks. These should be NULL when booted as a non-cluster
276  */
277 
278 /*
279  * Hook functions to enable cluster networking
280  * On non-clustered systems these vectors must always be NULL.
281  *
282  * Hook function to Check ip specified ip address is a shared ip address
283  * in the cluster
284  *
285  */
286 int (*cl_inet_isclusterwide)(uint8_t protocol,
287     sa_family_t addr_family, uint8_t *laddrp) = NULL;
288 
289 /*
290  * Hook function to generate cluster wide ip fragment identifier
291  */
292 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
293     uint8_t *laddrp, uint8_t *faddrp) = NULL;
294 
295 /*
296  * Synchronization notes:
297  *
298  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
299  * MT level protection given by STREAMS. IP uses a combination of its own
300  * internal serialization mechanism and standard Solaris locking techniques.
301  * The internal serialization is per phyint (no IPMP) or per IPMP group.
302  * This is used to serialize plumbing operations, IPMP operations, certain
303  * multicast operations, most set ioctls, igmp/mld timers etc.
304  *
305  * Plumbing is a long sequence of operations involving message
306  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
307  * involved in plumbing operations. A natural model is to serialize these
308  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
309  * parallel without any interference. But various set ioctls on hme0 are best
310  * serialized. However if the system uses IPMP, the operations are easier if
311  * they are serialized on a per IPMP group basis since IPMP operations
312  * happen across ill's of a group. Thus the lowest common denominator is to
313  * serialize most set ioctls, multicast join/leave operations, IPMP operations
314  * igmp/mld timer operations, and processing of DLPI control messages received
315  * from drivers on a per IPMP group basis. If the system does not employ
316  * IPMP the serialization is on a per phyint basis. This serialization is
317  * provided by the ipsq_t and primitives operating on this. Details can
318  * be found in ip_if.c above the core primitives operating on ipsq_t.
319  *
320  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
321  * Simiarly lookup of an ire by a thread also returns a refheld ire.
322  * In addition ipif's and ill's referenced by the ire are also indirectly
323  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
324  * the ipif's address or netmask change as long as an ipif is refheld
325  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
326  * address of an ipif has to go through the ipsq_t. This ensures that only
327  * 1 such exclusive operation proceeds at any time on the ipif. It then
328  * deletes all ires associated with this ipif, and waits for all refcnts
329  * associated with this ipif to come down to zero. The address is changed
330  * only after the ipif has been quiesced. Then the ipif is brought up again.
331  * More details are described above the comment in ip_sioctl_flags.
332  *
333  * Packet processing is based mostly on IREs and are fully multi-threaded
334  * using standard Solaris MT techniques.
335  *
336  * There are explicit locks in IP to handle:
337  * - The ip_g_head list maintained by mi_open_link() and friends.
338  *
339  * - The reassembly data structures (one lock per hash bucket)
340  *
341  * - conn_lock is meant to protect conn_t fields. The fields actually
342  *   protected by conn_lock are documented in the conn_t definition.
343  *
344  * - ire_lock to protect some of the fields of the ire, IRE tables
345  *   (one lock per hash bucket). Refer to ip_ire.c for details.
346  *
347  * - ndp_g_lock and nce_lock for protecting NCEs.
348  *
349  * - ill_lock protects fields of the ill and ipif. Details in ip.h
350  *
351  * - ill_g_lock: This is a global reader/writer lock. Protects the following
352  *	* The AVL tree based global multi list of all ills.
353  *	* The linked list of all ipifs of an ill
354  *	* The <ill-ipsq> mapping
355  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
356  *	* The illgroup list threaded by ill_group_next.
357  *	* <ill-phyint> association
358  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
359  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
360  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
361  *   will all have to hold the ill_g_lock as writer for the actual duration
362  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
363  *   may be found in the IPMP section.
364  *
365  * - ill_lock:  This is a per ill mutex.
366  *   It protects some members of the ill and is documented below.
367  *   It also protects the <ill-ipsq> mapping
368  *   It also protects the illgroup list threaded by ill_group_next.
369  *   It also protects the <ill-phyint> assoc.
370  *   It also protects the list of ipifs hanging off the ill.
371  *
372  * - ipsq_lock: This is a per ipsq_t mutex lock.
373  *   This protects all the other members of the ipsq struct except
374  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
375  *
376  * - illgrp_lock: This is a per ill_group mutex lock.
377  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
378  *   which dictates which is the next ill in an ill_group that is to be chosen
379  *   for sending outgoing packets, through creation of an IRE_CACHE that
380  *   references this ill.
381  *
382  * - phyint_lock: This is a per phyint mutex lock. Protects just the
383  *   phyint_flags
384  *
385  * - ip_g_nd_lock: This is a global reader/writer lock.
386  *   Any call to nd_load to load a new parameter to the ND table must hold the
387  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
388  *   as reader.
389  *
390  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
391  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
392  *   uniqueness check also done atomically.
393  *
394  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
395  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
396  *   as a writer when adding or deleting elements from these lists, and
397  *   as a reader when walking these lists to send a SADB update to the
398  *   IPsec capable ills.
399  *
400  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
401  *   group list linked by ill_usesrc_grp_next. It also protects the
402  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
403  *   group is being added or deleted.  This lock is taken as a reader when
404  *   walking the list/group(eg: to get the number of members in a usesrc group).
405  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
406  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
407  *   example, it is not necessary to take this lock in the initial portion
408  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
409  *   ip_sioctl_flags since the these operations are executed exclusively and
410  *   that ensures that the "usesrc group state" cannot change. The "usesrc
411  *   group state" change can happen only in the latter part of
412  *   ip_sioctl_slifusesrc and in ill_delete.
413  *
414  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
415  *
416  * To change the <ill-phyint> association, the ill_g_lock must be held
417  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
418  * must be held.
419  *
420  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
421  * and the ill_lock of the ill in question must be held.
422  *
423  * To change the <ill-illgroup> association the ill_g_lock must be held as
424  * writer and the ill_lock of the ill in question must be held.
425  *
426  * To add or delete an ipif from the list of ipifs hanging off the ill,
427  * ill_g_lock (writer) and ill_lock must be held and the thread must be
428  * a writer on the associated ipsq,.
429  *
430  * To add or delete an ill to the system, the ill_g_lock must be held as
431  * writer and the thread must be a writer on the associated ipsq.
432  *
433  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
434  * must be a writer on the associated ipsq.
435  *
436  * Lock hierarchy
437  *
438  * Some lock hierarchy scenarios are listed below.
439  *
440  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
441  * ill_g_lock -> illgrp_lock -> ill_lock
442  * ill_g_lock -> ill_lock(s) -> phyint_lock
443  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
444  * ill_g_lock -> ip_addr_avail_lock
445  * conn_lock -> irb_lock -> ill_lock -> ire_lock
446  * ill_g_lock -> ip_g_nd_lock
447  *
448  * When more than 1 ill lock is needed to be held, all ill lock addresses
449  * are sorted on address and locked starting from highest addressed lock
450  * downward.
451  *
452  * Mobile-IP scenarios
453  *
454  * irb_lock -> ill_lock -> ire_mrtun_lock
455  * irb_lock -> ill_lock -> ire_srcif_table_lock
456  *
457  * IPsec scenarios
458  *
459  * ipsa_lock -> ill_g_lock -> ill_lock
460  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
461  * ipsec_capab_ills_lock -> ipsa_lock
462  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
463  *
464  * Trusted Solaris scenarios
465  *
466  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
467  * igsa_lock -> gcdb_lock
468  * gcgrp_rwlock -> ire_lock
469  * gcgrp_rwlock -> gcdb_lock
470  *
471  *
472  * Routing/forwarding table locking notes:
473  *
474  * Lock acquisition order: Radix tree lock, irb_lock.
475  * Requirements:
476  * i.  Walker must not hold any locks during the walker callback.
477  * ii  Walker must not see a truncated tree during the walk because of any node
478  *     deletion.
479  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
480  *     in many places in the code to walk the irb list. Thus even if all the
481  *     ires in a bucket have been deleted, we still can't free the radix node
482  *     until the ires have actually been inactive'd (freed).
483  *
484  * Tree traversal - Need to hold the global tree lock in read mode.
485  * Before dropping the global tree lock, need to either increment the ire_refcnt
486  * to ensure that the radix node can't be deleted.
487  *
488  * Tree add - Need to hold the global tree lock in write mode to add a
489  * radix node. To prevent the node from being deleted, increment the
490  * irb_refcnt, after the node is added to the tree. The ire itself is
491  * added later while holding the irb_lock, but not the tree lock.
492  *
493  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
494  * All associated ires must be inactive (i.e. freed), and irb_refcnt
495  * must be zero.
496  *
497  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
498  * global tree lock (read mode) for traversal.
499  *
500  * IPSEC notes :
501  *
502  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
503  * in front of the actual packet. For outbound datagrams, the M_CTL
504  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
505  * information used by the IPSEC code for applying the right level of
506  * protection. The information initialized by IP in the ipsec_out_t
507  * is determined by the per-socket policy or global policy in the system.
508  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
509  * ipsec_info.h) which starts out with nothing in it. It gets filled
510  * with the right information if it goes through the AH/ESP code, which
511  * happens if the incoming packet is secure. The information initialized
512  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
513  * the policy requirements needed by per-socket policy or global policy
514  * is met or not.
515  *
516  * If there is both per-socket policy (set using setsockopt) and there
517  * is also global policy match for the 5 tuples of the socket,
518  * ipsec_override_policy() makes the decision of which one to use.
519  *
520  * For fully connected sockets i.e dst, src [addr, port] is known,
521  * conn_policy_cached is set indicating that policy has been cached.
522  * conn_in_enforce_policy may or may not be set depending on whether
523  * there is a global policy match or per-socket policy match.
524  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
525  * Once the right policy is set on the conn_t, policy cannot change for
526  * this socket. This makes life simpler for TCP (UDP ?) where
527  * re-transmissions go out with the same policy. For symmetry, policy
528  * is cached for fully connected UDP sockets also. Thus if policy is cached,
529  * it also implies that policy is latched i.e policy cannot change
530  * on these sockets. As we have the right policy on the conn, we don't
531  * have to lookup global policy for every outbound and inbound datagram
532  * and thus serving as an optimization. Note that a global policy change
533  * does not affect fully connected sockets if they have policy. If fully
534  * connected sockets did not have any policy associated with it, global
535  * policy change may affect them.
536  *
537  * IP Flow control notes:
538  *
539  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
540  * cannot be sent down to the driver by IP, because of a canput failure, IP
541  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
542  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
543  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
544  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
545  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
546  * the queued messages, and removes the conn from the drain list, if all
547  * messages were drained. It also qenables the next conn in the drain list to
548  * continue the drain process.
549  *
550  * In reality the drain list is not a single list, but a configurable number
551  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
552  * list. If the ip_wsrv of the next qenabled conn does not run, because the
553  * stream closes, ip_close takes responsibility to qenable the next conn in
554  * the drain list. The directly called ip_wput path always does a putq, if
555  * it cannot putnext. Thus synchronization problems are handled between
556  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
557  * functions that manipulate this drain list. Furthermore conn_drain_insert
558  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
559  * running on a queue at any time. conn_drain_tail can be simultaneously called
560  * from both ip_wsrv and ip_close.
561  *
562  * IPQOS notes:
563  *
564  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
565  * and IPQoS modules. IPPF includes hooks in IP at different control points
566  * (callout positions) which direct packets to IPQoS modules for policy
567  * processing. Policies, if present, are global.
568  *
569  * The callout positions are located in the following paths:
570  *		o local_in (packets destined for this host)
571  *		o local_out (packets orginating from this host )
572  *		o fwd_in  (packets forwarded by this m/c - inbound)
573  *		o fwd_out (packets forwarded by this m/c - outbound)
574  * Hooks at these callout points can be enabled/disabled using the ndd variable
575  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
576  * By default all the callout positions are enabled.
577  *
578  * Outbound (local_out)
579  * Hooks are placed in ip_wput_ire and ipsec_out_process.
580  *
581  * Inbound (local_in)
582  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
583  * TCP and UDP fanout routines.
584  *
585  * Forwarding (in and out)
586  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
587  *
588  * IP Policy Framework processing (IPPF processing)
589  * Policy processing for a packet is initiated by ip_process, which ascertains
590  * that the classifier (ipgpc) is loaded and configured, failing which the
591  * packet resumes normal processing in IP. If the clasifier is present, the
592  * packet is acted upon by one or more IPQoS modules (action instances), per
593  * filters configured in ipgpc and resumes normal IP processing thereafter.
594  * An action instance can drop a packet in course of its processing.
595  *
596  * A boolean variable, ip_policy, is used in all the fanout routines that can
597  * invoke ip_process for a packet. This variable indicates if the packet should
598  * to be sent for policy processing. The variable is set to B_TRUE by default,
599  * i.e. when the routines are invoked in the normal ip procesing path for a
600  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
601  * ip_policy is set to B_FALSE for all the routines called in these two
602  * functions because, in the former case,  we don't process loopback traffic
603  * currently while in the latter, the packets have already been processed in
604  * icmp_inbound.
605  *
606  * Zones notes:
607  *
608  * The partitioning rules for networking are as follows:
609  * 1) Packets coming from a zone must have a source address belonging to that
610  * zone.
611  * 2) Packets coming from a zone can only be sent on a physical interface on
612  * which the zone has an IP address.
613  * 3) Between two zones on the same machine, packet delivery is only allowed if
614  * there's a matching route for the destination and zone in the forwarding
615  * table.
616  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
617  * different zones can bind to the same port with the wildcard address
618  * (INADDR_ANY).
619  *
620  * The granularity of interface partitioning is at the logical interface level.
621  * Therefore, every zone has its own IP addresses, and incoming packets can be
622  * attributed to a zone unambiguously. A logical interface is placed into a zone
623  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
624  * structure. Rule (1) is implemented by modifying the source address selection
625  * algorithm so that the list of eligible addresses is filtered based on the
626  * sending process zone.
627  *
628  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
629  * across all zones, depending on their type. Here is the break-up:
630  *
631  * IRE type				Shared/exclusive
632  * --------				----------------
633  * IRE_BROADCAST			Exclusive
634  * IRE_DEFAULT (default routes)		Shared (*)
635  * IRE_LOCAL				Exclusive (x)
636  * IRE_LOOPBACK				Exclusive
637  * IRE_PREFIX (net routes)		Shared (*)
638  * IRE_CACHE				Exclusive
639  * IRE_IF_NORESOLVER (interface routes)	Exclusive
640  * IRE_IF_RESOLVER (interface routes)	Exclusive
641  * IRE_HOST (host routes)		Shared (*)
642  *
643  * (*) A zone can only use a default or off-subnet route if the gateway is
644  * directly reachable from the zone, that is, if the gateway's address matches
645  * one of the zone's logical interfaces.
646  *
647  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
648  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
649  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
650  * address of the zone itself (the destination). Since IRE_LOCAL is used
651  * for communication between zones, ip_wput_ire has special logic to set
652  * the right source address when sending using an IRE_LOCAL.
653  *
654  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
655  * ire_cache_lookup restricts loopback using an IRE_LOCAL
656  * between zone to the case when L2 would have conceptually looped the packet
657  * back, i.e. the loopback which is required since neither Ethernet drivers
658  * nor Ethernet hardware loops them back. This is the case when the normal
659  * routes (ignoring IREs with different zoneids) would send out the packet on
660  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
661  * associated.
662  *
663  * Multiple zones can share a common broadcast address; typically all zones
664  * share the 255.255.255.255 address. Incoming as well as locally originated
665  * broadcast packets must be dispatched to all the zones on the broadcast
666  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
667  * since some zones may not be on the 10.16.72/24 network. To handle this, each
668  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
669  * sent to every zone that has an IRE_BROADCAST entry for the destination
670  * address on the input ill, see conn_wantpacket().
671  *
672  * Applications in different zones can join the same multicast group address.
673  * For IPv4, group memberships are per-logical interface, so they're already
674  * inherently part of a zone. For IPv6, group memberships are per-physical
675  * interface, so we distinguish IPv6 group memberships based on group address,
676  * interface and zoneid. In both cases, received multicast packets are sent to
677  * every zone for which a group membership entry exists. On IPv6 we need to
678  * check that the target zone still has an address on the receiving physical
679  * interface; it could have been removed since the application issued the
680  * IPV6_JOIN_GROUP.
681  */
682 
683 /*
684  * Squeue Fanout flags:
685  *	0: No fanout.
686  *	1: Fanout across all squeues
687  */
688 boolean_t	ip_squeue_fanout = 0;
689 
690 /*
691  * Maximum dups allowed per packet.
692  */
693 uint_t ip_max_frag_dups = 10;
694 
695 #define	IS_SIMPLE_IPH(ipha)						\
696 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
697 
698 /* RFC1122 Conformance */
699 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
700 
701 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
702 
703 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
704 
705 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
706 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
707 
708 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t);
709 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
710     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
711 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
712 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
713 		    mblk_t *, int);
714 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
715 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
716 		    ill_t *, zoneid_t);
717 static void	icmp_options_update(ipha_t *);
718 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t);
719 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
720 		    zoneid_t zoneid);
721 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
722 static void	icmp_redirect(mblk_t *);
723 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
724 
725 static void	ip_arp_news(queue_t *, mblk_t *);
726 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
727 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
728 char		*ip_dot_addr(ipaddr_t, char *);
729 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
730 int		ip_close(queue_t *, int);
731 static char	*ip_dot_saddr(uchar_t *, char *);
732 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
733 		    boolean_t, boolean_t, ill_t *, zoneid_t);
734 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
735 		    boolean_t, boolean_t, zoneid_t);
736 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
737 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
738 static void	ip_lrput(queue_t *, mblk_t *);
739 ipaddr_t	ip_massage_options(ipha_t *);
740 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
741 ipaddr_t	ip_net_mask(ipaddr_t);
742 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
743 		    zoneid_t);
744 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
745 		    conn_t *, uint32_t, zoneid_t);
746 char		*ip_nv_lookup(nv_t *, int);
747 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
748 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
749 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
750 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
751 			    size_t);
752 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
753 void	ip_rput(queue_t *, mblk_t *);
754 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
755 		    void *dummy_arg);
756 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
757 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
758 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
759 			    ire_t *);
760 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
761 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
762 		    uint16_t *);
763 int		ip_snmp_get(queue_t *, mblk_t *);
764 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
765 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
766 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
767 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
768 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
769 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
770 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
771 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
772 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
773 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
775 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
776 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
777 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
778 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
779 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
780 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
781 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
782 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
783 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
784 static boolean_t	ip_source_routed(ipha_t *);
785 static boolean_t	ip_source_route_included(ipha_t *);
786 
787 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
788 		    zoneid_t);
789 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
790 static void	ip_wput_local_options(ipha_t *);
791 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
792 		    zoneid_t);
793 
794 static void	conn_drain_init(void);
795 static void	conn_drain_fini(void);
796 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
797 
798 static void	conn_walk_drain(void);
799 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
800     zoneid_t);
801 
802 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
803     zoneid_t);
804 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
805     void *dummy_arg);
806 
807 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
808 
809 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
810     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
811     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
812 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
813 
814 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
815 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
816     caddr_t, cred_t *);
817 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
818     caddr_t cp, cred_t *cr);
819 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
820     cred_t *);
821 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
822     caddr_t cp, cred_t *cr);
823 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
824     cred_t *);
825 static squeue_func_t ip_squeue_switch(int);
826 
827 static void	ip_kstat_init(void);
828 static void	ip_kstat_fini(void);
829 static int	ip_kstat_update(kstat_t *kp, int rw);
830 static void	icmp_kstat_init(void);
831 static void	icmp_kstat_fini(void);
832 static int	icmp_kstat_update(kstat_t *kp, int rw);
833 
834 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
835 
836 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
837     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
838 
839 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
840     ipha_t *, ill_t *, boolean_t);
841 
842 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
843 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
844 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
845 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
846 
847 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
848 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
849 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
850 
851 /* How long, in seconds, we allow frags to hang around. */
852 #define	IP_FRAG_TIMEOUT	60
853 
854 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
855 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
856 
857 /*
858  * Threshold which determines whether MDT should be used when
859  * generating IP fragments; payload size must be greater than
860  * this threshold for MDT to take place.
861  */
862 #define	IP_WPUT_FRAG_MDT_MIN	32768
863 
864 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
865 
866 /* Protected by ip_mi_lock */
867 static void	*ip_g_head;		/* Instance Data List Head */
868 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
869 
870 /* Only modified during _init and _fini thus no locking is needed. */
871 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
872 
873 
874 static long ip_rput_pullups;
875 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
876 
877 vmem_t *ip_minor_arena;
878 
879 /*
880  * MIB-2 stuff for SNMP (both IP and ICMP)
881  */
882 mib2_ip_t	ip_mib;
883 mib2_icmp_t	icmp_mib;
884 
885 #ifdef DEBUG
886 uint32_t ipsechw_debug = 0;
887 #endif
888 
889 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
890 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
891 
892 uint_t	loopback_packets = 0;
893 
894 /*
895  * Multirouting/CGTP stuff
896  */
897 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
898 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
899 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
900 /* Interval (in ms) between consecutive 'bad MTU' warnings */
901 hrtime_t ip_multirt_log_interval = 1000;
902 /* Time since last warning issued. */
903 static hrtime_t	multirt_bad_mtu_last_time = 0;
904 
905 kmutex_t ip_trash_timer_lock;
906 krwlock_t ip_g_nd_lock;
907 
908 /*
909  * XXX following really should only be in a header. Would need more
910  * header and .c clean up first.
911  */
912 extern optdb_obj_t	ip_opt_obj;
913 
914 ulong_t ip_squeue_enter_unbound = 0;
915 
916 /*
917  * Named Dispatch Parameter Table.
918  * All of these are alterable, within the min/max values given, at run time.
919  */
920 static ipparam_t	lcl_param_arr[] = {
921 	/* min	max	value	name */
922 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
923 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
924 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
925 	{  0,	1,	0,	"ip_respond_to_timestamp"},
926 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
927 	{  0,	1,	1,	"ip_send_redirects"},
928 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
929 	{  0,	10,	0,	"ip_debug"},
930 	{  0,	10,	0,	"ip_mrtdebug"},
931 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
932 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
933 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
934 	{  1,	255,	255,	"ip_def_ttl" },
935 	{  0,	1,	0,	"ip_forward_src_routed"},
936 	{  0,	256,	32,	"ip_wroff_extra" },
937 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
938 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
939 	{  0,	1,	1,	"ip_path_mtu_discovery" },
940 	{  0,	240,	30,	"ip_ignore_delete_time" },
941 	{  0,	1,	0,	"ip_ignore_redirect" },
942 	{  0,	1,	1,	"ip_output_queue" },
943 	{  1,	254,	1,	"ip_broadcast_ttl" },
944 	{  0,	99999,	100,	"ip_icmp_err_interval" },
945 	{  1,	99999,	10,	"ip_icmp_err_burst" },
946 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
947 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
948 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
949 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
950 	{  0,	1,	1,	"icmp_accept_clear_messages" },
951 	{  0,	1,	1,	"igmp_accept_clear_messages" },
952 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
953 				"ip_ndp_delay_first_probe_time"},
954 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
955 				"ip_ndp_max_unicast_solicit"},
956 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
957 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
958 	{  0,	1,	0,	"ip6_forward_src_routed"},
959 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
960 	{  0,	1,	1,	"ip6_send_redirects"},
961 	{  0,	1,	0,	"ip6_ignore_redirect" },
962 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
963 
964 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
965 
966 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
967 
968 	{  0,	1,	1,	"pim_accept_clear_messages" },
969 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
970 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
971 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
972 	{  0,	15,	0,	"ip_policy_mask" },
973 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
974 	{  0,	255,	1,	"ip_multirt_ttl" },
975 	{  0,	1,	1,	"ip_multidata_outbound" },
976 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
977 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
978 	{  0,	1000,	1,	"ip_max_temp_defend" },
979 	{  0,	1000,	3,	"ip_max_defend" },
980 	{  0,	999999,	30,	"ip_defend_interval" },
981 	{  0,	3600000, 300000, "ip_dup_recovery" },
982 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
983 #ifdef DEBUG
984 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
985 #endif
986 };
987 
988 ipparam_t	*ip_param_arr = lcl_param_arr;
989 
990 /* Extended NDP table */
991 static ipndp_t	lcl_ndp_arr[] = {
992 	/* getf			setf		data			name */
993 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
994 	    "ip_forwarding" },
995 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
996 	    "ip6_forwarding" },
997 	{  ip_ill_report,	NULL,		NULL,
998 	    "ip_ill_status" },
999 	{  ip_ipif_report,	NULL,		NULL,
1000 	    "ip_ipif_status" },
1001 	{  ip_ire_report,	NULL,		NULL,
1002 	    "ipv4_ire_status" },
1003 	{  ip_ire_report_mrtun,	NULL,		NULL,
1004 	    "ipv4_mrtun_ire_status" },
1005 	{  ip_ire_report_srcif,	NULL,		NULL,
1006 	    "ipv4_srcif_ire_status" },
1007 	{  ip_ire_report_v6,	NULL,		NULL,
1008 	    "ipv6_ire_status" },
1009 	{  ip_conn_report,	NULL,		NULL,
1010 	    "ip_conn_status" },
1011 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1012 	    "ip_rput_pullups" },
1013 	{  ndp_report,		NULL,		NULL,
1014 	    "ip_ndp_cache_report" },
1015 	{  ip_srcid_report,	NULL,		NULL,
1016 	    "ip_srcid_status" },
1017 	{ ip_param_generic_get, ip_squeue_profile_set,
1018 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
1019 	{ ip_param_generic_get, ip_squeue_bind_set,
1020 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
1021 	{ ip_param_generic_get, ip_input_proc_set,
1022 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1023 	{ ip_param_generic_get, ip_int_set,
1024 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1025 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
1026 	    "ip_cgtp_filter" },
1027 	{ ip_param_generic_get, ip_int_set,
1028 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
1029 };
1030 
1031 /*
1032  * ip_g_forward controls IP forwarding.  It takes two values:
1033  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
1034  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
1035  *
1036  * RFC1122 says there must be a configuration switch to control forwarding,
1037  * but that the default MUST be to not forward packets ever.  Implicit
1038  * control based on configuration of multiple interfaces MUST NOT be
1039  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
1040  * and, in fact, it was the default.  That capability is now provided in the
1041  * /etc/rc2.d/S69inet script.
1042  */
1043 int ip_g_forward = IP_FORWARD_DEFAULT;
1044 
1045 /* It also has an IPv6 counterpart. */
1046 
1047 int ipv6_forward = IP_FORWARD_DEFAULT;
1048 
1049 /*
1050  * Table of IP ioctls encoding the various properties of the ioctl and
1051  * indexed based on the last byte of the ioctl command. Occasionally there
1052  * is a clash, and there is more than 1 ioctl with the same last byte.
1053  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1054  * ioctls are encoded in the misc table. An entry in the ndx table is
1055  * retrieved by indexing on the last byte of the ioctl command and comparing
1056  * the ioctl command with the value in the ndx table. In the event of a
1057  * mismatch the misc table is then searched sequentially for the desired
1058  * ioctl command.
1059  *
1060  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1061  */
1062 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1063 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 
1074 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1075 			MISC_CMD, ip_siocaddrt, NULL },
1076 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1077 			MISC_CMD, ip_siocdelrt, NULL },
1078 
1079 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1080 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1081 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1082 			IF_CMD, ip_sioctl_get_addr, NULL },
1083 
1084 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1085 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1086 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1087 			IPI_GET_CMD | IPI_REPL,
1088 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1089 
1090 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1091 			IPI_PRIV | IPI_WR | IPI_REPL,
1092 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1093 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1094 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1095 			IF_CMD, ip_sioctl_get_flags, NULL },
1096 
1097 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 
1100 	/* copyin size cannot be coded for SIOCGIFCONF */
1101 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1102 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1103 
1104 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1105 			IF_CMD, ip_sioctl_mtu, NULL },
1106 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1107 			IF_CMD, ip_sioctl_get_mtu, NULL },
1108 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1109 			IPI_GET_CMD | IPI_REPL,
1110 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1111 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1112 			IF_CMD, ip_sioctl_brdaddr, NULL },
1113 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1114 			IPI_GET_CMD | IPI_REPL,
1115 			IF_CMD, ip_sioctl_get_netmask, NULL },
1116 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1117 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1118 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1119 			IPI_GET_CMD | IPI_REPL,
1120 			IF_CMD, ip_sioctl_get_metric, NULL },
1121 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1122 			IF_CMD, ip_sioctl_metric, NULL },
1123 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 
1125 	/* See 166-168 below for extended SIOC*XARP ioctls */
1126 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1127 			MISC_CMD, ip_sioctl_arp, NULL },
1128 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1129 			MISC_CMD, ip_sioctl_arp, NULL },
1130 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1131 			MISC_CMD, ip_sioctl_arp, NULL },
1132 
1133 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1135 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1136 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 
1155 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1156 			MISC_CMD, if_unitsel, if_unitsel_restart },
1157 
1158 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1159 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1160 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1161 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 
1177 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1178 			IPI_PRIV | IPI_WR | IPI_MODOK,
1179 			IF_CMD, ip_sioctl_sifname, NULL },
1180 
1181 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1190 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 
1195 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1196 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1197 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1198 			IF_CMD, ip_sioctl_get_muxid, NULL },
1199 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1200 			IPI_PRIV | IPI_WR | IPI_REPL,
1201 			IF_CMD, ip_sioctl_muxid, NULL },
1202 
1203 	/* Both if and lif variants share same func */
1204 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1205 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1206 	/* Both if and lif variants share same func */
1207 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1208 			IPI_PRIV | IPI_WR | IPI_REPL,
1209 			IF_CMD, ip_sioctl_slifindex, NULL },
1210 
1211 	/* copyin size cannot be coded for SIOCGIFCONF */
1212 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1213 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1214 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1215 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1216 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1217 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1218 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1219 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1220 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1221 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1222 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1223 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1226 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1227 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1228 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1229 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1230 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1231 
1232 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1233 			IPI_PRIV | IPI_WR | IPI_REPL,
1234 			LIF_CMD, ip_sioctl_removeif,
1235 			ip_sioctl_removeif_restart },
1236 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1237 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1238 			LIF_CMD, ip_sioctl_addif, NULL },
1239 #define	SIOCLIFADDR_NDX 112
1240 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1241 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1242 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1243 			IPI_GET_CMD | IPI_REPL,
1244 			LIF_CMD, ip_sioctl_get_addr, NULL },
1245 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1246 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1247 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1248 			IPI_GET_CMD | IPI_REPL,
1249 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1250 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1251 			IPI_PRIV | IPI_WR | IPI_REPL,
1252 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1253 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1254 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1255 			LIF_CMD, ip_sioctl_get_flags, NULL },
1256 
1257 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1258 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1259 
1260 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1261 			ip_sioctl_get_lifconf, NULL },
1262 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1263 			LIF_CMD, ip_sioctl_mtu, NULL },
1264 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1265 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1266 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1267 			IPI_GET_CMD | IPI_REPL,
1268 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1269 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1270 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1271 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1272 			IPI_GET_CMD | IPI_REPL,
1273 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1274 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1275 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1276 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1277 			IPI_GET_CMD | IPI_REPL,
1278 			LIF_CMD, ip_sioctl_get_metric, NULL },
1279 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1280 			LIF_CMD, ip_sioctl_metric, NULL },
1281 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1282 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1283 			LIF_CMD, ip_sioctl_slifname,
1284 			ip_sioctl_slifname_restart },
1285 
1286 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1287 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1288 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1289 			IPI_GET_CMD | IPI_REPL,
1290 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1291 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1292 			IPI_PRIV | IPI_WR | IPI_REPL,
1293 			LIF_CMD, ip_sioctl_muxid, NULL },
1294 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1295 			IPI_GET_CMD | IPI_REPL,
1296 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1297 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1298 			IPI_PRIV | IPI_WR | IPI_REPL,
1299 			LIF_CMD, ip_sioctl_slifindex, 0 },
1300 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1301 			LIF_CMD, ip_sioctl_token, NULL },
1302 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1303 			IPI_GET_CMD | IPI_REPL,
1304 			LIF_CMD, ip_sioctl_get_token, NULL },
1305 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1306 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1307 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1308 			IPI_GET_CMD | IPI_REPL,
1309 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1310 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1311 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1312 
1313 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1314 			IPI_GET_CMD | IPI_REPL,
1315 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1316 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1317 			LIF_CMD, ip_siocdelndp_v6, NULL },
1318 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1319 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1320 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1321 			LIF_CMD, ip_siocsetndp_v6, NULL },
1322 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1323 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1324 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1325 			MISC_CMD, ip_sioctl_tonlink, NULL },
1326 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1327 			MISC_CMD, ip_sioctl_tmysite, NULL },
1328 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1329 			TUN_CMD, ip_sioctl_tunparam, NULL },
1330 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1331 			IPI_PRIV | IPI_WR,
1332 			TUN_CMD, ip_sioctl_tunparam, NULL },
1333 
1334 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1335 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1336 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1337 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1338 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1339 
1340 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1341 			IPI_PRIV | IPI_WR | IPI_REPL,
1342 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1343 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1344 			IPI_PRIV | IPI_WR | IPI_REPL,
1345 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1346 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1347 			IPI_PRIV | IPI_WR,
1348 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1349 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1350 			IPI_GET_CMD | IPI_REPL,
1351 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1352 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1353 			IPI_GET_CMD | IPI_REPL,
1354 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1355 
1356 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1357 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1358 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1359 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1360 
1361 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1362 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1363 
1364 	/* These are handled in ip_sioctl_copyin_setup itself */
1365 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1366 			MISC_CMD, NULL, NULL },
1367 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1368 			MISC_CMD, NULL, NULL },
1369 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1370 
1371 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1372 			ip_sioctl_get_lifconf, NULL },
1373 
1374 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1375 			MISC_CMD, ip_sioctl_xarp, NULL },
1376 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1377 			MISC_CMD, ip_sioctl_xarp, NULL },
1378 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1379 			MISC_CMD, ip_sioctl_xarp, NULL },
1380 
1381 	/* SIOCPOPSOCKFS is not handled by IP */
1382 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1383 
1384 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1385 			IPI_GET_CMD | IPI_REPL,
1386 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1387 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1388 			IPI_PRIV | IPI_WR | IPI_REPL,
1389 			LIF_CMD, ip_sioctl_slifzone,
1390 			ip_sioctl_slifzone_restart },
1391 	/* 172-174 are SCTP ioctls and not handled by IP */
1392 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1393 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1394 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1395 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1396 			IPI_GET_CMD, LIF_CMD,
1397 			ip_sioctl_get_lifusesrc, 0 },
1398 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1399 			IPI_PRIV | IPI_WR,
1400 			LIF_CMD, ip_sioctl_slifusesrc,
1401 			NULL },
1402 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1403 			ip_sioctl_get_lifsrcof, NULL },
1404 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1405 			MISC_CMD, ip_sioctl_msfilter, NULL },
1406 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1407 			MISC_CMD, ip_sioctl_msfilter, NULL },
1408 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1409 			MISC_CMD, ip_sioctl_msfilter, NULL },
1410 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1411 			MISC_CMD, ip_sioctl_msfilter, NULL },
1412 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1413 			ip_sioctl_set_ipmpfailback, NULL }
1414 };
1415 
1416 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1417 
1418 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1419 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1420 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1421 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1422 		TUN_CMD, ip_sioctl_tunparam, NULL },
1423 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1424 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1425 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1426 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1427 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1428 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1429 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1430 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1431 		MISC_CMD, mrt_ioctl},
1432 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1433 		MISC_CMD, mrt_ioctl},
1434 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1435 		MISC_CMD, mrt_ioctl}
1436 };
1437 
1438 int ip_misc_ioctl_count =
1439     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1440 
1441 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1442 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1443 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1444 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1445 					/* Settable in /etc/system */
1446 uint_t	ip_redirect_cnt;		/* Num of redirect routes in ftable */
1447 
1448 /* Defined in ip_ire.c */
1449 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1450 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1451 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1452 
1453 static nv_t	ire_nv_arr[] = {
1454 	{ IRE_BROADCAST, "BROADCAST" },
1455 	{ IRE_LOCAL, "LOCAL" },
1456 	{ IRE_LOOPBACK, "LOOPBACK" },
1457 	{ IRE_CACHE, "CACHE" },
1458 	{ IRE_DEFAULT, "DEFAULT" },
1459 	{ IRE_PREFIX, "PREFIX" },
1460 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1461 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1462 	{ IRE_HOST, "HOST" },
1463 	{ IRE_HOST_REDIRECT, "HOST_REDIRECT" },
1464 	{ 0 }
1465 };
1466 
1467 nv_t	*ire_nv_tbl = ire_nv_arr;
1468 
1469 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1470 extern krwlock_t ipsec_capab_ills_lock;
1471 
1472 /* Packet dropper for IP IPsec processing failures */
1473 ipdropper_t ip_dropper;
1474 
1475 /* Simple ICMP IP Header Template */
1476 static ipha_t icmp_ipha = {
1477 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1478 };
1479 
1480 struct module_info ip_mod_info = {
1481 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1482 };
1483 
1484 /*
1485  * Duplicate static symbols within a module confuses mdb; so we avoid the
1486  * problem by making the symbols here distinct from those in udp.c.
1487  */
1488 
1489 static struct qinit iprinit = {
1490 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1491 	&ip_mod_info
1492 };
1493 
1494 static struct qinit ipwinit = {
1495 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1496 	&ip_mod_info
1497 };
1498 
1499 static struct qinit iplrinit = {
1500 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1501 	&ip_mod_info
1502 };
1503 
1504 static struct qinit iplwinit = {
1505 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1506 	&ip_mod_info
1507 };
1508 
1509 struct streamtab ipinfo = {
1510 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1511 };
1512 
1513 #ifdef	DEBUG
1514 static boolean_t skip_sctp_cksum = B_FALSE;
1515 #endif
1516 
1517 /*
1518  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1519  * ip_rput_v6(), ip_output(), etc.  If the message
1520  * block already has a M_CTL at the front of it, then simply set the zoneid
1521  * appropriately.
1522  */
1523 mblk_t *
1524 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid)
1525 {
1526 	mblk_t		*first_mp;
1527 	ipsec_out_t	*io;
1528 
1529 	ASSERT(zoneid != ALL_ZONES);
1530 	if (mp->b_datap->db_type == M_CTL) {
1531 		io = (ipsec_out_t *)mp->b_rptr;
1532 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1533 		io->ipsec_out_zoneid = zoneid;
1534 		return (mp);
1535 	}
1536 
1537 	first_mp = ipsec_alloc_ipsec_out();
1538 	if (first_mp == NULL)
1539 		return (NULL);
1540 	io = (ipsec_out_t *)first_mp->b_rptr;
1541 	/* This is not a secure packet */
1542 	io->ipsec_out_secure = B_FALSE;
1543 	io->ipsec_out_zoneid = zoneid;
1544 	first_mp->b_cont = mp;
1545 	return (first_mp);
1546 }
1547 
1548 /*
1549  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1550  */
1551 mblk_t *
1552 ip_copymsg(mblk_t *mp)
1553 {
1554 	mblk_t *nmp;
1555 	ipsec_info_t *in;
1556 
1557 	if (mp->b_datap->db_type != M_CTL)
1558 		return (copymsg(mp));
1559 
1560 	in = (ipsec_info_t *)mp->b_rptr;
1561 
1562 	/*
1563 	 * Note that M_CTL is also used for delivering ICMP error messages
1564 	 * upstream to transport layers.
1565 	 */
1566 	if (in->ipsec_info_type != IPSEC_OUT &&
1567 	    in->ipsec_info_type != IPSEC_IN)
1568 		return (copymsg(mp));
1569 
1570 	nmp = copymsg(mp->b_cont);
1571 
1572 	if (in->ipsec_info_type == IPSEC_OUT)
1573 		return (ipsec_out_tag(mp, nmp));
1574 	else
1575 		return (ipsec_in_tag(mp, nmp));
1576 }
1577 
1578 /* Generate an ICMP fragmentation needed message. */
1579 static void
1580 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid)
1581 {
1582 	icmph_t	icmph;
1583 	mblk_t *first_mp;
1584 	boolean_t mctl_present;
1585 
1586 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1587 
1588 	if (!(mp = icmp_pkt_err_ok(mp))) {
1589 		if (mctl_present)
1590 			freeb(first_mp);
1591 		return;
1592 	}
1593 
1594 	bzero(&icmph, sizeof (icmph_t));
1595 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1596 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1597 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1598 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1599 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1600 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
1601 }
1602 
1603 /*
1604  * icmp_inbound deals with ICMP messages in the following ways.
1605  *
1606  * 1) It needs to send a reply back and possibly delivering it
1607  *    to the "interested" upper clients.
1608  * 2) It needs to send it to the upper clients only.
1609  * 3) It needs to change some values in IP only.
1610  * 4) It needs to change some values in IP and upper layers e.g TCP.
1611  *
1612  * We need to accomodate icmp messages coming in clear until we get
1613  * everything secure from the wire. If icmp_accept_clear_messages
1614  * is zero we check with the global policy and act accordingly. If
1615  * it is non-zero, we accept the message without any checks. But
1616  * *this does not mean* that this will be delivered to the upper
1617  * clients. By accepting we might send replies back, change our MTU
1618  * value etc. but delivery to the ULP/clients depends on their policy
1619  * dispositions.
1620  *
1621  * We handle the above 4 cases in the context of IPSEC in the
1622  * following way :
1623  *
1624  * 1) Send the reply back in the same way as the request came in.
1625  *    If it came in encrypted, it goes out encrypted. If it came in
1626  *    clear, it goes out in clear. Thus, this will prevent chosen
1627  *    plain text attack.
1628  * 2) The client may or may not expect things to come in secure.
1629  *    If it comes in secure, the policy constraints are checked
1630  *    before delivering it to the upper layers. If it comes in
1631  *    clear, ipsec_inbound_accept_clear will decide whether to
1632  *    accept this in clear or not. In both the cases, if the returned
1633  *    message (IP header + 8 bytes) that caused the icmp message has
1634  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1635  *    sending up. If there are only 8 bytes of returned message, then
1636  *    upper client will not be notified.
1637  * 3) Check with global policy to see whether it matches the constaints.
1638  *    But this will be done only if icmp_accept_messages_in_clear is
1639  *    zero.
1640  * 4) If we need to change both in IP and ULP, then the decision taken
1641  *    while affecting the values in IP and while delivering up to TCP
1642  *    should be the same.
1643  *
1644  * 	There are two cases.
1645  *
1646  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1647  *	   failed), we will not deliver it to the ULP, even though they
1648  *	   are *willing* to accept in *clear*. This is fine as our global
1649  *	   disposition to icmp messages asks us reject the datagram.
1650  *
1651  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1652  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1653  *	   to deliver it to ULP (policy failed), it can lead to
1654  *	   consistency problems. The cases known at this time are
1655  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1656  *	   values :
1657  *
1658  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1659  *	     and Upper layer rejects. Then the communication will
1660  *	     come to a stop. This is solved by making similar decisions
1661  *	     at both levels. Currently, when we are unable to deliver
1662  *	     to the Upper Layer (due to policy failures) while IP has
1663  *	     adjusted ire_max_frag, the next outbound datagram would
1664  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1665  *	     will be with the right level of protection. Thus the right
1666  *	     value will be communicated even if we are not able to
1667  *	     communicate when we get from the wire initially. But this
1668  *	     assumes there would be at least one outbound datagram after
1669  *	     IP has adjusted its ire_max_frag value. To make things
1670  *	     simpler, we accept in clear after the validation of
1671  *	     AH/ESP headers.
1672  *
1673  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1674  *	     upper layer depending on the level of protection the upper
1675  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1676  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1677  *	     should be accepted in clear when the Upper layer expects secure.
1678  *	     Thus the communication may get aborted by some bad ICMP
1679  *	     packets.
1680  *
1681  * IPQoS Notes:
1682  * The only instance when a packet is sent for processing is when there
1683  * isn't an ICMP client and if we are interested in it.
1684  * If there is a client, IPPF processing will take place in the
1685  * ip_fanout_proto routine.
1686  *
1687  * Zones notes:
1688  * The packet is only processed in the context of the specified zone: typically
1689  * only this zone will reply to an echo request, and only interested clients in
1690  * this zone will receive a copy of the packet. This means that the caller must
1691  * call icmp_inbound() for each relevant zone.
1692  */
1693 static void
1694 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1695     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1696     ill_t *recv_ill, zoneid_t zoneid)
1697 {
1698 	icmph_t	*icmph;
1699 	ipha_t	*ipha;
1700 	int	iph_hdr_length;
1701 	int	hdr_length;
1702 	boolean_t	interested;
1703 	uint32_t	ts;
1704 	uchar_t	*wptr;
1705 	ipif_t	*ipif;
1706 	mblk_t *first_mp;
1707 	ipsec_in_t *ii;
1708 	ire_t *src_ire;
1709 	boolean_t onlink;
1710 	timestruc_t now;
1711 	uint32_t ill_index;
1712 
1713 	ASSERT(ill != NULL);
1714 
1715 	first_mp = mp;
1716 	if (mctl_present) {
1717 		mp = first_mp->b_cont;
1718 		ASSERT(mp != NULL);
1719 	}
1720 
1721 	ipha = (ipha_t *)mp->b_rptr;
1722 	if (icmp_accept_clear_messages == 0) {
1723 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1724 		    ipha, NULL, mctl_present);
1725 		if (first_mp == NULL)
1726 			return;
1727 	}
1728 
1729 	/*
1730 	 * On a labeled system, we have to check whether the zone itself is
1731 	 * permitted to receive raw traffic.
1732 	 */
1733 	if (is_system_labeled()) {
1734 		if (zoneid == ALL_ZONES)
1735 			zoneid = tsol_packet_to_zoneid(mp);
1736 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1737 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1738 			    zoneid));
1739 			BUMP_MIB(&icmp_mib, icmpInErrors);
1740 			freemsg(first_mp);
1741 			return;
1742 		}
1743 	}
1744 
1745 	/*
1746 	 * We have accepted the ICMP message. It means that we will
1747 	 * respond to the packet if needed. It may not be delivered
1748 	 * to the upper client depending on the policy constraints
1749 	 * and the disposition in ipsec_inbound_accept_clear.
1750 	 */
1751 
1752 	ASSERT(ill != NULL);
1753 
1754 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1755 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1756 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1757 		/* Last chance to get real. */
1758 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1759 			BUMP_MIB(&icmp_mib, icmpInErrors);
1760 			freemsg(first_mp);
1761 			return;
1762 		}
1763 		/* Refresh iph following the pullup. */
1764 		ipha = (ipha_t *)mp->b_rptr;
1765 	}
1766 	/* ICMP header checksum, including checksum field, should be zero. */
1767 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1768 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1769 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1770 		freemsg(first_mp);
1771 		return;
1772 	}
1773 	/* The IP header will always be a multiple of four bytes */
1774 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1775 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1776 	    icmph->icmph_code));
1777 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1778 	/* We will set "interested" to "true" if we want a copy */
1779 	interested = B_FALSE;
1780 	switch (icmph->icmph_type) {
1781 	case ICMP_ECHO_REPLY:
1782 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1783 		break;
1784 	case ICMP_DEST_UNREACHABLE:
1785 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1786 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1787 		interested = B_TRUE;	/* Pass up to transport */
1788 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1789 		break;
1790 	case ICMP_SOURCE_QUENCH:
1791 		interested = B_TRUE;	/* Pass up to transport */
1792 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1793 		break;
1794 	case ICMP_REDIRECT:
1795 		if (!ip_ignore_redirect)
1796 			interested = B_TRUE;
1797 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1798 		break;
1799 	case ICMP_ECHO_REQUEST:
1800 		/*
1801 		 * Whether to respond to echo requests that come in as IP
1802 		 * broadcasts or as IP multicast is subject to debate
1803 		 * (what isn't?).  We aim to please, you pick it.
1804 		 * Default is do it.
1805 		 */
1806 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1807 			/* unicast: always respond */
1808 			interested = B_TRUE;
1809 		} else if (CLASSD(ipha->ipha_dst)) {
1810 			/* multicast: respond based on tunable */
1811 			interested = ip_g_resp_to_echo_mcast;
1812 		} else if (broadcast) {
1813 			/* broadcast: respond based on tunable */
1814 			interested = ip_g_resp_to_echo_bcast;
1815 		}
1816 		BUMP_MIB(&icmp_mib, icmpInEchos);
1817 		break;
1818 	case ICMP_ROUTER_ADVERTISEMENT:
1819 	case ICMP_ROUTER_SOLICITATION:
1820 		break;
1821 	case ICMP_TIME_EXCEEDED:
1822 		interested = B_TRUE;	/* Pass up to transport */
1823 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1824 		break;
1825 	case ICMP_PARAM_PROBLEM:
1826 		interested = B_TRUE;	/* Pass up to transport */
1827 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1828 		break;
1829 	case ICMP_TIME_STAMP_REQUEST:
1830 		/* Response to Time Stamp Requests is local policy. */
1831 		if (ip_g_resp_to_timestamp &&
1832 		    /* So is whether to respond if it was an IP broadcast. */
1833 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1834 			int tstamp_len = 3 * sizeof (uint32_t);
1835 
1836 			if (wptr +  tstamp_len > mp->b_wptr) {
1837 				if (!pullupmsg(mp, wptr + tstamp_len -
1838 				    mp->b_rptr)) {
1839 					BUMP_MIB(&ip_mib, ipInDiscards);
1840 					freemsg(first_mp);
1841 					return;
1842 				}
1843 				/* Refresh ipha following the pullup. */
1844 				ipha = (ipha_t *)mp->b_rptr;
1845 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1846 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1847 			}
1848 			interested = B_TRUE;
1849 		}
1850 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1851 		break;
1852 	case ICMP_TIME_STAMP_REPLY:
1853 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1854 		break;
1855 	case ICMP_INFO_REQUEST:
1856 		/* Per RFC 1122 3.2.2.7, ignore this. */
1857 	case ICMP_INFO_REPLY:
1858 		break;
1859 	case ICMP_ADDRESS_MASK_REQUEST:
1860 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1861 		    /* TODO m_pullup of complete header? */
1862 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1863 			interested = B_TRUE;
1864 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1865 		break;
1866 	case ICMP_ADDRESS_MASK_REPLY:
1867 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1868 		break;
1869 	default:
1870 		interested = B_TRUE;	/* Pass up to transport */
1871 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1872 		break;
1873 	}
1874 	/* See if there is an ICMP client. */
1875 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1876 		/* If there is an ICMP client and we want one too, copy it. */
1877 		mblk_t *first_mp1;
1878 
1879 		if (!interested) {
1880 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1881 			    ip_policy, recv_ill, zoneid);
1882 			return;
1883 		}
1884 		first_mp1 = ip_copymsg(first_mp);
1885 		if (first_mp1 != NULL) {
1886 			ip_fanout_proto(q, first_mp1, ill, ipha,
1887 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1888 		}
1889 	} else if (!interested) {
1890 		freemsg(first_mp);
1891 		return;
1892 	} else {
1893 		/*
1894 		 * Initiate policy processing for this packet if ip_policy
1895 		 * is true.
1896 		 */
1897 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1898 			ill_index = ill->ill_phyint->phyint_ifindex;
1899 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1900 			if (mp == NULL) {
1901 				if (mctl_present) {
1902 					freeb(first_mp);
1903 				}
1904 				BUMP_MIB(&icmp_mib, icmpInErrors);
1905 				return;
1906 			}
1907 		}
1908 	}
1909 	/* We want to do something with it. */
1910 	/* Check db_ref to make sure we can modify the packet. */
1911 	if (mp->b_datap->db_ref > 1) {
1912 		mblk_t	*first_mp1;
1913 
1914 		first_mp1 = ip_copymsg(first_mp);
1915 		freemsg(first_mp);
1916 		if (!first_mp1) {
1917 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1918 			return;
1919 		}
1920 		first_mp = first_mp1;
1921 		if (mctl_present) {
1922 			mp = first_mp->b_cont;
1923 			ASSERT(mp != NULL);
1924 		} else {
1925 			mp = first_mp;
1926 		}
1927 		ipha = (ipha_t *)mp->b_rptr;
1928 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1929 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1930 	}
1931 	switch (icmph->icmph_type) {
1932 	case ICMP_ADDRESS_MASK_REQUEST:
1933 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1934 		if (ipif == NULL) {
1935 			freemsg(first_mp);
1936 			return;
1937 		}
1938 		/*
1939 		 * outging interface must be IPv4
1940 		 */
1941 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1942 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1943 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1944 		ipif_refrele(ipif);
1945 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1946 		break;
1947 	case ICMP_ECHO_REQUEST:
1948 		icmph->icmph_type = ICMP_ECHO_REPLY;
1949 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1950 		break;
1951 	case ICMP_TIME_STAMP_REQUEST: {
1952 		uint32_t *tsp;
1953 
1954 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1955 		tsp = (uint32_t *)wptr;
1956 		tsp++;		/* Skip past 'originate time' */
1957 		/* Compute # of milliseconds since midnight */
1958 		gethrestime(&now);
1959 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1960 		    now.tv_nsec / (NANOSEC / MILLISEC);
1961 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1962 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1963 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1964 		break;
1965 	}
1966 	default:
1967 		ipha = (ipha_t *)&icmph[1];
1968 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1969 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1970 				BUMP_MIB(&ip_mib, ipInDiscards);
1971 				freemsg(first_mp);
1972 				return;
1973 			}
1974 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1975 			ipha = (ipha_t *)&icmph[1];
1976 		}
1977 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1978 			BUMP_MIB(&ip_mib, ipInDiscards);
1979 			freemsg(first_mp);
1980 			return;
1981 		}
1982 		hdr_length = IPH_HDR_LENGTH(ipha);
1983 		if (hdr_length < sizeof (ipha_t)) {
1984 			BUMP_MIB(&ip_mib, ipInDiscards);
1985 			freemsg(first_mp);
1986 			return;
1987 		}
1988 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1989 			if (!pullupmsg(mp,
1990 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1991 				BUMP_MIB(&ip_mib, ipInDiscards);
1992 				freemsg(first_mp);
1993 				return;
1994 			}
1995 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1996 			ipha = (ipha_t *)&icmph[1];
1997 		}
1998 		switch (icmph->icmph_type) {
1999 		case ICMP_REDIRECT:
2000 			/*
2001 			 * As there is no upper client to deliver, we don't
2002 			 * need the first_mp any more.
2003 			 */
2004 			if (mctl_present) {
2005 				freeb(first_mp);
2006 			}
2007 			icmp_redirect(mp);
2008 			return;
2009 		case ICMP_DEST_UNREACHABLE:
2010 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
2011 				if (!icmp_inbound_too_big(icmph, ipha, ill,
2012 				    zoneid, mp, iph_hdr_length)) {
2013 					freemsg(first_mp);
2014 					return;
2015 				}
2016 				/*
2017 				 * icmp_inbound_too_big() may alter mp.
2018 				 * Resynch ipha and icmph accordingly.
2019 				 */
2020 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2021 				ipha = (ipha_t *)&icmph[1];
2022 			}
2023 			/* FALLTHRU */
2024 		default :
2025 			/*
2026 			 * IPQoS notes: Since we have already done IPQoS
2027 			 * processing we don't want to do it again in
2028 			 * the fanout routines called by
2029 			 * icmp_inbound_error_fanout, hence the last
2030 			 * argument, ip_policy, is B_FALSE.
2031 			 */
2032 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2033 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2034 			    B_FALSE, recv_ill, zoneid);
2035 		}
2036 		return;
2037 	}
2038 	/* Send out an ICMP packet */
2039 	icmph->icmph_checksum = 0;
2040 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2041 	if (icmph->icmph_checksum == 0)
2042 		icmph->icmph_checksum = 0xFFFF;
2043 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2044 		ipif_t	*ipif_chosen;
2045 		/*
2046 		 * Make it look like it was directed to us, so we don't look
2047 		 * like a fool with a broadcast or multicast source address.
2048 		 */
2049 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2050 		/*
2051 		 * Make sure that we haven't grabbed an interface that's DOWN.
2052 		 */
2053 		if (ipif != NULL) {
2054 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2055 			    ipha->ipha_src, zoneid);
2056 			if (ipif_chosen != NULL) {
2057 				ipif_refrele(ipif);
2058 				ipif = ipif_chosen;
2059 			}
2060 		}
2061 		if (ipif == NULL) {
2062 			ip0dbg(("icmp_inbound: "
2063 			    "No source for broadcast/multicast:\n"
2064 			    "\tsrc 0x%x dst 0x%x ill %p "
2065 			    "ipif_lcl_addr 0x%x\n",
2066 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2067 			    (void *)ill,
2068 			    ill->ill_ipif->ipif_lcl_addr));
2069 			freemsg(first_mp);
2070 			return;
2071 		}
2072 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2073 		ipha->ipha_dst = ipif->ipif_src_addr;
2074 		ipif_refrele(ipif);
2075 	}
2076 	/* Reset time to live. */
2077 	ipha->ipha_ttl = ip_def_ttl;
2078 	{
2079 		/* Swap source and destination addresses */
2080 		ipaddr_t tmp;
2081 
2082 		tmp = ipha->ipha_src;
2083 		ipha->ipha_src = ipha->ipha_dst;
2084 		ipha->ipha_dst = tmp;
2085 	}
2086 	ipha->ipha_ident = 0;
2087 	if (!IS_SIMPLE_IPH(ipha))
2088 		icmp_options_update(ipha);
2089 
2090 	/*
2091 	 * ICMP echo replies should go out on the same interface
2092 	 * the request came on as probes used by in.mpathd for detecting
2093 	 * NIC failures are ECHO packets. We turn-off load spreading
2094 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2095 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2096 	 * function. This is in turn handled by ip_wput and ip_newroute
2097 	 * to make sure that the packet goes out on the interface it came
2098 	 * in on. If we don't turnoff load spreading, the packets might get
2099 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2100 	 * to go out and in.mpathd would wrongly detect a failure or
2101 	 * mis-detect a NIC failure for link failure. As load spreading
2102 	 * can happen only if ill_group is not NULL, we do only for
2103 	 * that case and this does not affect the normal case.
2104 	 *
2105 	 * We turn off load spreading only on echo packets that came from
2106 	 * on-link hosts. If the interface route has been deleted, this will
2107 	 * not be enforced as we can't do much. For off-link hosts, as the
2108 	 * default routes in IPv4 does not typically have an ire_ipif
2109 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2110 	 * Moreover, expecting a default route through this interface may
2111 	 * not be correct. We use ipha_dst because of the swap above.
2112 	 */
2113 	onlink = B_FALSE;
2114 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2115 		/*
2116 		 * First, we need to make sure that it is not one of our
2117 		 * local addresses. If we set onlink when it is one of
2118 		 * our local addresses, we will end up creating IRE_CACHES
2119 		 * for one of our local addresses. Then, we will never
2120 		 * accept packets for them afterwards.
2121 		 */
2122 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2123 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2124 		if (src_ire == NULL) {
2125 			ipif = ipif_get_next_ipif(NULL, ill);
2126 			if (ipif == NULL) {
2127 				BUMP_MIB(&ip_mib, ipInDiscards);
2128 				freemsg(mp);
2129 				return;
2130 			}
2131 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2132 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2133 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2134 			ipif_refrele(ipif);
2135 			if (src_ire != NULL) {
2136 				onlink = B_TRUE;
2137 				ire_refrele(src_ire);
2138 			}
2139 		} else {
2140 			ire_refrele(src_ire);
2141 		}
2142 	}
2143 	if (!mctl_present) {
2144 		/*
2145 		 * This packet should go out the same way as it
2146 		 * came in i.e in clear. To make sure that global
2147 		 * policy will not be applied to this in ip_wput_ire,
2148 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2149 		 */
2150 		ASSERT(first_mp == mp);
2151 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2152 			BUMP_MIB(&ip_mib, ipInDiscards);
2153 			freemsg(mp);
2154 			return;
2155 		}
2156 		ii = (ipsec_in_t *)first_mp->b_rptr;
2157 
2158 		/* This is not a secure packet */
2159 		ii->ipsec_in_secure = B_FALSE;
2160 		if (onlink) {
2161 			ii->ipsec_in_attach_if = B_TRUE;
2162 			ii->ipsec_in_ill_index =
2163 			    ill->ill_phyint->phyint_ifindex;
2164 			ii->ipsec_in_rill_index =
2165 			    recv_ill->ill_phyint->phyint_ifindex;
2166 		}
2167 		first_mp->b_cont = mp;
2168 	} else if (onlink) {
2169 		ii = (ipsec_in_t *)first_mp->b_rptr;
2170 		ii->ipsec_in_attach_if = B_TRUE;
2171 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2172 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2173 	} else {
2174 		ii = (ipsec_in_t *)first_mp->b_rptr;
2175 	}
2176 	ii->ipsec_in_zoneid = zoneid;
2177 	ASSERT(zoneid != ALL_ZONES);
2178 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2179 		BUMP_MIB(&ip_mib, ipInDiscards);
2180 		return;
2181 	}
2182 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2183 	put(WR(q), first_mp);
2184 }
2185 
2186 static ipaddr_t
2187 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2188 {
2189 	conn_t *connp;
2190 	connf_t *connfp;
2191 	ipaddr_t nexthop_addr = INADDR_ANY;
2192 	int hdr_length = IPH_HDR_LENGTH(ipha);
2193 	uint16_t *up;
2194 	uint32_t ports;
2195 
2196 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2197 	switch (ipha->ipha_protocol) {
2198 		case IPPROTO_TCP:
2199 		{
2200 			tcph_t *tcph;
2201 
2202 			/* do a reverse lookup */
2203 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2204 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2205 			    TCPS_LISTEN);
2206 			break;
2207 		}
2208 		case IPPROTO_UDP:
2209 		{
2210 			uint32_t dstport, srcport;
2211 
2212 			((uint16_t *)&ports)[0] = up[1];
2213 			((uint16_t *)&ports)[1] = up[0];
2214 
2215 			/* Extract ports in net byte order */
2216 			dstport = htons(ntohl(ports) & 0xFFFF);
2217 			srcport = htons(ntohl(ports) >> 16);
2218 
2219 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2220 			mutex_enter(&connfp->connf_lock);
2221 			connp = connfp->connf_head;
2222 
2223 			/* do a reverse lookup */
2224 			while ((connp != NULL) &&
2225 			    (!IPCL_UDP_MATCH(connp, dstport,
2226 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2227 			    connp->conn_zoneid != zoneid)) {
2228 				connp = connp->conn_next;
2229 			}
2230 			if (connp != NULL)
2231 				CONN_INC_REF(connp);
2232 			mutex_exit(&connfp->connf_lock);
2233 			break;
2234 		}
2235 		case IPPROTO_SCTP:
2236 		{
2237 			in6_addr_t map_src, map_dst;
2238 
2239 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2240 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2241 			((uint16_t *)&ports)[0] = up[1];
2242 			((uint16_t *)&ports)[1] = up[0];
2243 
2244 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2245 			    0, zoneid)) == NULL) {
2246 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2247 				    zoneid, ports, ipha);
2248 			} else {
2249 				CONN_INC_REF(connp);
2250 				SCTP_REFRELE(CONN2SCTP(connp));
2251 			}
2252 			break;
2253 		}
2254 		default:
2255 		{
2256 			ipha_t ripha;
2257 
2258 			ripha.ipha_src = ipha->ipha_dst;
2259 			ripha.ipha_dst = ipha->ipha_src;
2260 			ripha.ipha_protocol = ipha->ipha_protocol;
2261 
2262 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2263 			mutex_enter(&connfp->connf_lock);
2264 			connp = connfp->connf_head;
2265 			for (connp = connfp->connf_head; connp != NULL;
2266 			    connp = connp->conn_next) {
2267 				if (IPCL_PROTO_MATCH(connp,
2268 				    ipha->ipha_protocol, &ripha, ill,
2269 				    0, zoneid)) {
2270 					CONN_INC_REF(connp);
2271 					break;
2272 				}
2273 			}
2274 			mutex_exit(&connfp->connf_lock);
2275 		}
2276 	}
2277 	if (connp != NULL) {
2278 		if (connp->conn_nexthop_set)
2279 			nexthop_addr = connp->conn_nexthop_v4;
2280 		CONN_DEC_REF(connp);
2281 	}
2282 	return (nexthop_addr);
2283 }
2284 
2285 /* Table from RFC 1191 */
2286 static int icmp_frag_size_table[] =
2287 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2288 
2289 /*
2290  * Process received ICMP Packet too big.
2291  * After updating any IRE it does the fanout to any matching transport streams.
2292  * Assumes the message has been pulled up till the IP header that caused
2293  * the error.
2294  *
2295  * Returns B_FALSE on failure and B_TRUE on success.
2296  */
2297 static boolean_t
2298 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2299     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2300 {
2301 	ire_t	*ire, *first_ire;
2302 	int	mtu;
2303 	int	hdr_length;
2304 	ipaddr_t nexthop_addr;
2305 
2306 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2307 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2308 
2309 	hdr_length = IPH_HDR_LENGTH(ipha);
2310 
2311 	/* Drop if the original packet contained a source route */
2312 	if (ip_source_route_included(ipha)) {
2313 		return (B_FALSE);
2314 	}
2315 	/*
2316 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2317 	 * header.
2318 	 */
2319 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2320 	    mp->b_wptr) {
2321 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2322 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2323 			BUMP_MIB(&ip_mib, ipInDiscards);
2324 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2325 			return (B_FALSE);
2326 		}
2327 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2328 		ipha = (ipha_t *)&icmph[1];
2329 	}
2330 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2331 	if (nexthop_addr != INADDR_ANY) {
2332 		/* nexthop set */
2333 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2334 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2335 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2336 	} else {
2337 		/* nexthop not set */
2338 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2339 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2340 	}
2341 
2342 	if (!first_ire) {
2343 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2344 		    ntohl(ipha->ipha_dst)));
2345 		return (B_FALSE);
2346 	}
2347 	/* Check for MTU discovery advice as described in RFC 1191 */
2348 	mtu = ntohs(icmph->icmph_du_mtu);
2349 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2350 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2351 	    ire = ire->ire_next) {
2352 		/*
2353 		 * Look for the connection to which this ICMP message is
2354 		 * directed. If it has the IP_NEXTHOP option set, then the
2355 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2356 		 * option. Else the search is limited to regular IREs.
2357 		 */
2358 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2359 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2360 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2361 		    (nexthop_addr != INADDR_ANY)))
2362 			continue;
2363 
2364 		mutex_enter(&ire->ire_lock);
2365 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2366 			/* Reduce the IRE max frag value as advised. */
2367 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2368 			    mtu, ire->ire_max_frag));
2369 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2370 		} else {
2371 			uint32_t length;
2372 			int	i;
2373 
2374 			/*
2375 			 * Use the table from RFC 1191 to figure out
2376 			 * the next "plateau" based on the length in
2377 			 * the original IP packet.
2378 			 */
2379 			length = ntohs(ipha->ipha_length);
2380 			if (ire->ire_max_frag <= length &&
2381 			    ire->ire_max_frag >= length - hdr_length) {
2382 				/*
2383 				 * Handle broken BSD 4.2 systems that
2384 				 * return the wrong iph_length in ICMP
2385 				 * errors.
2386 				 */
2387 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2388 				    length, ire->ire_max_frag));
2389 				length -= hdr_length;
2390 			}
2391 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2392 				if (length > icmp_frag_size_table[i])
2393 					break;
2394 			}
2395 			if (i == A_CNT(icmp_frag_size_table)) {
2396 				/* Smaller than 68! */
2397 				ip1dbg(("Too big for packet size %d\n",
2398 				    length));
2399 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2400 				ire->ire_frag_flag = 0;
2401 			} else {
2402 				mtu = icmp_frag_size_table[i];
2403 				ip1dbg(("Calculated mtu %d, packet size %d, "
2404 				    "before %d", mtu, length,
2405 				    ire->ire_max_frag));
2406 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2407 				ip1dbg((", after %d\n", ire->ire_max_frag));
2408 			}
2409 			/* Record the new max frag size for the ULP. */
2410 			icmph->icmph_du_zero = 0;
2411 			icmph->icmph_du_mtu =
2412 			    htons((uint16_t)ire->ire_max_frag);
2413 		}
2414 		mutex_exit(&ire->ire_lock);
2415 	}
2416 	rw_exit(&first_ire->ire_bucket->irb_lock);
2417 	ire_refrele(first_ire);
2418 	return (B_TRUE);
2419 }
2420 
2421 /*
2422  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2423  * calls this function.
2424  */
2425 static mblk_t *
2426 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2427 {
2428 	ipha_t *ipha;
2429 	icmph_t *icmph;
2430 	ipha_t *in_ipha;
2431 	int length;
2432 
2433 	ASSERT(mp->b_datap->db_type == M_DATA);
2434 
2435 	/*
2436 	 * For Self-encapsulated packets, we added an extra IP header
2437 	 * without the options. Inner IP header is the one from which
2438 	 * the outer IP header was formed. Thus, we need to remove the
2439 	 * outer IP header. To do this, we pullup the whole message
2440 	 * and overlay whatever follows the outer IP header over the
2441 	 * outer IP header.
2442 	 */
2443 
2444 	if (!pullupmsg(mp, -1)) {
2445 		BUMP_MIB(&ip_mib, ipInDiscards);
2446 		return (NULL);
2447 	}
2448 
2449 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2450 	ipha = (ipha_t *)&icmph[1];
2451 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2452 
2453 	/*
2454 	 * The length that we want to overlay is following the inner
2455 	 * IP header. Subtracting the IP header + icmp header + outer
2456 	 * IP header's length should give us the length that we want to
2457 	 * overlay.
2458 	 */
2459 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2460 	    hdr_length;
2461 	/*
2462 	 * Overlay whatever follows the inner header over the
2463 	 * outer header.
2464 	 */
2465 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2466 
2467 	/* Set the wptr to account for the outer header */
2468 	mp->b_wptr -= hdr_length;
2469 	return (mp);
2470 }
2471 
2472 /*
2473  * Try to pass the ICMP message upstream in case the ULP cares.
2474  *
2475  * If the packet that caused the ICMP error is secure, we send
2476  * it to AH/ESP to make sure that the attached packet has a
2477  * valid association. ipha in the code below points to the
2478  * IP header of the packet that caused the error.
2479  *
2480  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2481  * in the context of IPSEC. Normally we tell the upper layer
2482  * whenever we send the ire (including ip_bind), the IPSEC header
2483  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2484  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2485  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2486  * same thing. As TCP has the IPSEC options size that needs to be
2487  * adjusted, we just pass the MTU unchanged.
2488  *
2489  * IFN could have been generated locally or by some router.
2490  *
2491  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2492  *	    This happens because IP adjusted its value of MTU on an
2493  *	    earlier IFN message and could not tell the upper layer,
2494  *	    the new adjusted value of MTU e.g. Packet was encrypted
2495  *	    or there was not enough information to fanout to upper
2496  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2497  *	    generates the IFN, where IPSEC processing has *not* been
2498  *	    done.
2499  *
2500  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2501  *	    could have generated this. This happens because ire_max_frag
2502  *	    value in IP was set to a new value, while the IPSEC processing
2503  *	    was being done and after we made the fragmentation check in
2504  *	    ip_wput_ire. Thus on return from IPSEC processing,
2505  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2506  *	    and generates the IFN. As IPSEC processing is over, we fanout
2507  *	    to AH/ESP to remove the header.
2508  *
2509  *	    In both these cases, ipsec_in_loopback will be set indicating
2510  *	    that IFN was generated locally.
2511  *
2512  * ROUTER : IFN could be secure or non-secure.
2513  *
2514  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2515  *	      packet in error has AH/ESP headers to validate the AH/ESP
2516  *	      headers. AH/ESP will verify whether there is a valid SA or
2517  *	      not and send it back. We will fanout again if we have more
2518  *	      data in the packet.
2519  *
2520  *	      If the packet in error does not have AH/ESP, we handle it
2521  *	      like any other case.
2522  *
2523  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2524  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2525  *	      for validation. AH/ESP will verify whether there is a
2526  *	      valid SA or not and send it back. We will fanout again if
2527  *	      we have more data in the packet.
2528  *
2529  *	      If the packet in error does not have AH/ESP, we handle it
2530  *	      like any other case.
2531  */
2532 static void
2533 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2534     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2535     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2536     zoneid_t zoneid)
2537 {
2538 	uint16_t *up;	/* Pointer to ports in ULP header */
2539 	uint32_t ports;	/* reversed ports for fanout */
2540 	ipha_t ripha;	/* With reversed addresses */
2541 	mblk_t *first_mp;
2542 	ipsec_in_t *ii;
2543 	tcph_t	*tcph;
2544 	conn_t	*connp;
2545 
2546 	first_mp = mp;
2547 	if (mctl_present) {
2548 		mp = first_mp->b_cont;
2549 		ASSERT(mp != NULL);
2550 
2551 		ii = (ipsec_in_t *)first_mp->b_rptr;
2552 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2553 	} else {
2554 		ii = NULL;
2555 	}
2556 
2557 	switch (ipha->ipha_protocol) {
2558 	case IPPROTO_UDP:
2559 		/*
2560 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2561 		 * transport header.
2562 		 */
2563 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2564 		    mp->b_wptr) {
2565 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2566 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2567 				BUMP_MIB(&ip_mib, ipInDiscards);
2568 				goto drop_pkt;
2569 			}
2570 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2571 			ipha = (ipha_t *)&icmph[1];
2572 		}
2573 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2574 
2575 		/*
2576 		 * Attempt to find a client stream based on port.
2577 		 * Note that we do a reverse lookup since the header is
2578 		 * in the form we sent it out.
2579 		 * The ripha header is only used for the IP_UDP_MATCH and we
2580 		 * only set the src and dst addresses and protocol.
2581 		 */
2582 		ripha.ipha_src = ipha->ipha_dst;
2583 		ripha.ipha_dst = ipha->ipha_src;
2584 		ripha.ipha_protocol = ipha->ipha_protocol;
2585 		((uint16_t *)&ports)[0] = up[1];
2586 		((uint16_t *)&ports)[1] = up[0];
2587 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2588 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2589 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2590 		    icmph->icmph_type, icmph->icmph_code));
2591 
2592 		/* Have to change db_type after any pullupmsg */
2593 		DB_TYPE(mp) = M_CTL;
2594 
2595 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2596 		    mctl_present, ip_policy, recv_ill, zoneid);
2597 		return;
2598 
2599 	case IPPROTO_TCP:
2600 		/*
2601 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2602 		 * transport header.
2603 		 */
2604 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2605 		    mp->b_wptr) {
2606 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2607 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2608 				BUMP_MIB(&ip_mib, ipInDiscards);
2609 				goto drop_pkt;
2610 			}
2611 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2612 			ipha = (ipha_t *)&icmph[1];
2613 		}
2614 		/*
2615 		 * Find a TCP client stream for this packet.
2616 		 * Note that we do a reverse lookup since the header is
2617 		 * in the form we sent it out.
2618 		 */
2619 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2620 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2621 		if (connp == NULL) {
2622 			BUMP_MIB(&ip_mib, ipInDiscards);
2623 			goto drop_pkt;
2624 		}
2625 
2626 		/* Have to change db_type after any pullupmsg */
2627 		DB_TYPE(mp) = M_CTL;
2628 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2629 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2630 		return;
2631 
2632 	case IPPROTO_SCTP:
2633 		/*
2634 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2635 		 * transport header.
2636 		 */
2637 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2638 		    mp->b_wptr) {
2639 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2640 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2641 				BUMP_MIB(&ip_mib, ipInDiscards);
2642 				goto drop_pkt;
2643 			}
2644 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2645 			ipha = (ipha_t *)&icmph[1];
2646 		}
2647 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2648 		/*
2649 		 * Find a SCTP client stream for this packet.
2650 		 * Note that we do a reverse lookup since the header is
2651 		 * in the form we sent it out.
2652 		 * The ripha header is only used for the matching and we
2653 		 * only set the src and dst addresses, protocol, and version.
2654 		 */
2655 		ripha.ipha_src = ipha->ipha_dst;
2656 		ripha.ipha_dst = ipha->ipha_src;
2657 		ripha.ipha_protocol = ipha->ipha_protocol;
2658 		ripha.ipha_version_and_hdr_length =
2659 		    ipha->ipha_version_and_hdr_length;
2660 		((uint16_t *)&ports)[0] = up[1];
2661 		((uint16_t *)&ports)[1] = up[0];
2662 
2663 		/* Have to change db_type after any pullupmsg */
2664 		DB_TYPE(mp) = M_CTL;
2665 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2666 		    mctl_present, ip_policy, 0, zoneid);
2667 		return;
2668 
2669 	case IPPROTO_ESP:
2670 	case IPPROTO_AH: {
2671 		int ipsec_rc;
2672 
2673 		/*
2674 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2675 		 * We will re-use the IPSEC_IN if it is already present as
2676 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2677 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2678 		 * one and attach it in the front.
2679 		 */
2680 		if (ii != NULL) {
2681 			/*
2682 			 * ip_fanout_proto_again converts the ICMP errors
2683 			 * that come back from AH/ESP to M_DATA so that
2684 			 * if it is non-AH/ESP and we do a pullupmsg in
2685 			 * this function, it would work. Convert it back
2686 			 * to M_CTL before we send up as this is a ICMP
2687 			 * error. This could have been generated locally or
2688 			 * by some router. Validate the inner IPSEC
2689 			 * headers.
2690 			 *
2691 			 * NOTE : ill_index is used by ip_fanout_proto_again
2692 			 * to locate the ill.
2693 			 */
2694 			ASSERT(ill != NULL);
2695 			ii->ipsec_in_ill_index =
2696 			    ill->ill_phyint->phyint_ifindex;
2697 			ii->ipsec_in_rill_index =
2698 			    recv_ill->ill_phyint->phyint_ifindex;
2699 			DB_TYPE(first_mp->b_cont) = M_CTL;
2700 		} else {
2701 			/*
2702 			 * IPSEC_IN is not present. We attach a ipsec_in
2703 			 * message and send up to IPSEC for validating
2704 			 * and removing the IPSEC headers. Clear
2705 			 * ipsec_in_secure so that when we return
2706 			 * from IPSEC, we don't mistakenly think that this
2707 			 * is a secure packet came from the network.
2708 			 *
2709 			 * NOTE : ill_index is used by ip_fanout_proto_again
2710 			 * to locate the ill.
2711 			 */
2712 			ASSERT(first_mp == mp);
2713 			first_mp = ipsec_in_alloc(B_TRUE);
2714 			if (first_mp == NULL) {
2715 				freemsg(mp);
2716 				BUMP_MIB(&ip_mib, ipInDiscards);
2717 				return;
2718 			}
2719 			ii = (ipsec_in_t *)first_mp->b_rptr;
2720 
2721 			/* This is not a secure packet */
2722 			ii->ipsec_in_secure = B_FALSE;
2723 			first_mp->b_cont = mp;
2724 			DB_TYPE(mp) = M_CTL;
2725 			ASSERT(ill != NULL);
2726 			ii->ipsec_in_ill_index =
2727 			    ill->ill_phyint->phyint_ifindex;
2728 			ii->ipsec_in_rill_index =
2729 			    recv_ill->ill_phyint->phyint_ifindex;
2730 		}
2731 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2732 
2733 		if (!ipsec_loaded()) {
2734 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2735 			return;
2736 		}
2737 
2738 		if (ipha->ipha_protocol == IPPROTO_ESP)
2739 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2740 		else
2741 			ipsec_rc = ipsecah_icmp_error(first_mp);
2742 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2743 			return;
2744 
2745 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2746 		return;
2747 	}
2748 	default:
2749 		/*
2750 		 * The ripha header is only used for the lookup and we
2751 		 * only set the src and dst addresses and protocol.
2752 		 */
2753 		ripha.ipha_src = ipha->ipha_dst;
2754 		ripha.ipha_dst = ipha->ipha_src;
2755 		ripha.ipha_protocol = ipha->ipha_protocol;
2756 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2757 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2758 		    ntohl(ipha->ipha_dst),
2759 		    icmph->icmph_type, icmph->icmph_code));
2760 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2761 			ipha_t *in_ipha;
2762 
2763 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2764 			    mp->b_wptr) {
2765 				if (!pullupmsg(mp, (uchar_t *)ipha +
2766 				    hdr_length + sizeof (ipha_t) -
2767 				    mp->b_rptr)) {
2768 
2769 					BUMP_MIB(&ip_mib, ipInDiscards);
2770 					goto drop_pkt;
2771 				}
2772 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2773 				ipha = (ipha_t *)&icmph[1];
2774 			}
2775 			/*
2776 			 * Caller has verified that length has to be
2777 			 * at least the size of IP header.
2778 			 */
2779 			ASSERT(hdr_length >= sizeof (ipha_t));
2780 			/*
2781 			 * Check the sanity of the inner IP header like
2782 			 * we did for the outer header.
2783 			 */
2784 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2785 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2786 				BUMP_MIB(&ip_mib, ipInDiscards);
2787 				goto drop_pkt;
2788 			}
2789 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2790 				BUMP_MIB(&ip_mib, ipInDiscards);
2791 				goto drop_pkt;
2792 			}
2793 			/* Check for Self-encapsulated tunnels */
2794 			if (in_ipha->ipha_src == ipha->ipha_src &&
2795 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2796 
2797 				mp = icmp_inbound_self_encap_error(mp,
2798 				    iph_hdr_length, hdr_length);
2799 				if (mp == NULL)
2800 					goto drop_pkt;
2801 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2802 				ipha = (ipha_t *)&icmph[1];
2803 				hdr_length = IPH_HDR_LENGTH(ipha);
2804 				/*
2805 				 * The packet in error is self-encapsualted.
2806 				 * And we are finding it further encapsulated
2807 				 * which we could not have possibly generated.
2808 				 */
2809 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2810 					BUMP_MIB(&ip_mib, ipInDiscards);
2811 					goto drop_pkt;
2812 				}
2813 				icmp_inbound_error_fanout(q, ill, first_mp,
2814 				    icmph, ipha, iph_hdr_length, hdr_length,
2815 				    mctl_present, ip_policy, recv_ill, zoneid);
2816 				return;
2817 			}
2818 		}
2819 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2820 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2821 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2822 		    ii != NULL &&
2823 		    ii->ipsec_in_loopback &&
2824 		    ii->ipsec_in_secure) {
2825 			/*
2826 			 * For IP tunnels that get a looped-back
2827 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2828 			 * reported new MTU to take into account the IPsec
2829 			 * headers protecting this configured tunnel.
2830 			 *
2831 			 * This allows the tunnel module (tun.c) to blindly
2832 			 * accept the MTU reported in an ICMP "too big"
2833 			 * message.
2834 			 *
2835 			 * Non-looped back ICMP messages will just be
2836 			 * handled by the security protocols (if needed),
2837 			 * and the first subsequent packet will hit this
2838 			 * path.
2839 			 */
2840 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2841 			    ipsec_in_extra_length(first_mp));
2842 		}
2843 		/* Have to change db_type after any pullupmsg */
2844 		DB_TYPE(mp) = M_CTL;
2845 
2846 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2847 		    ip_policy, recv_ill, zoneid);
2848 		return;
2849 	}
2850 	/* NOTREACHED */
2851 drop_pkt:;
2852 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2853 	freemsg(first_mp);
2854 }
2855 
2856 /*
2857  * Common IP options parser.
2858  *
2859  * Setup routine: fill in *optp with options-parsing state, then
2860  * tail-call ipoptp_next to return the first option.
2861  */
2862 uint8_t
2863 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2864 {
2865 	uint32_t totallen; /* total length of all options */
2866 
2867 	totallen = ipha->ipha_version_and_hdr_length -
2868 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2869 	totallen <<= 2;
2870 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2871 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2872 	optp->ipoptp_flags = 0;
2873 	return (ipoptp_next(optp));
2874 }
2875 
2876 /*
2877  * Common IP options parser: extract next option.
2878  */
2879 uint8_t
2880 ipoptp_next(ipoptp_t *optp)
2881 {
2882 	uint8_t *end = optp->ipoptp_end;
2883 	uint8_t *cur = optp->ipoptp_next;
2884 	uint8_t opt, len, pointer;
2885 
2886 	/*
2887 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2888 	 * has been corrupted.
2889 	 */
2890 	ASSERT(cur <= end);
2891 
2892 	if (cur == end)
2893 		return (IPOPT_EOL);
2894 
2895 	opt = cur[IPOPT_OPTVAL];
2896 
2897 	/*
2898 	 * Skip any NOP options.
2899 	 */
2900 	while (opt == IPOPT_NOP) {
2901 		cur++;
2902 		if (cur == end)
2903 			return (IPOPT_EOL);
2904 		opt = cur[IPOPT_OPTVAL];
2905 	}
2906 
2907 	if (opt == IPOPT_EOL)
2908 		return (IPOPT_EOL);
2909 
2910 	/*
2911 	 * Option requiring a length.
2912 	 */
2913 	if ((cur + 1) >= end) {
2914 		optp->ipoptp_flags |= IPOPTP_ERROR;
2915 		return (IPOPT_EOL);
2916 	}
2917 	len = cur[IPOPT_OLEN];
2918 	if (len < 2) {
2919 		optp->ipoptp_flags |= IPOPTP_ERROR;
2920 		return (IPOPT_EOL);
2921 	}
2922 	optp->ipoptp_cur = cur;
2923 	optp->ipoptp_len = len;
2924 	optp->ipoptp_next = cur + len;
2925 	if (cur + len > end) {
2926 		optp->ipoptp_flags |= IPOPTP_ERROR;
2927 		return (IPOPT_EOL);
2928 	}
2929 
2930 	/*
2931 	 * For the options which require a pointer field, make sure
2932 	 * its there, and make sure it points to either something
2933 	 * inside this option, or the end of the option.
2934 	 */
2935 	switch (opt) {
2936 	case IPOPT_RR:
2937 	case IPOPT_TS:
2938 	case IPOPT_LSRR:
2939 	case IPOPT_SSRR:
2940 		if (len <= IPOPT_OFFSET) {
2941 			optp->ipoptp_flags |= IPOPTP_ERROR;
2942 			return (opt);
2943 		}
2944 		pointer = cur[IPOPT_OFFSET];
2945 		if (pointer - 1 > len) {
2946 			optp->ipoptp_flags |= IPOPTP_ERROR;
2947 			return (opt);
2948 		}
2949 		break;
2950 	}
2951 
2952 	/*
2953 	 * Sanity check the pointer field based on the type of the
2954 	 * option.
2955 	 */
2956 	switch (opt) {
2957 	case IPOPT_RR:
2958 	case IPOPT_SSRR:
2959 	case IPOPT_LSRR:
2960 		if (pointer < IPOPT_MINOFF_SR)
2961 			optp->ipoptp_flags |= IPOPTP_ERROR;
2962 		break;
2963 	case IPOPT_TS:
2964 		if (pointer < IPOPT_MINOFF_IT)
2965 			optp->ipoptp_flags |= IPOPTP_ERROR;
2966 		/*
2967 		 * Note that the Internet Timestamp option also
2968 		 * contains two four bit fields (the Overflow field,
2969 		 * and the Flag field), which follow the pointer
2970 		 * field.  We don't need to check that these fields
2971 		 * fall within the length of the option because this
2972 		 * was implicitely done above.  We've checked that the
2973 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2974 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2975 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2976 		 */
2977 		ASSERT(len > IPOPT_POS_OV_FLG);
2978 		break;
2979 	}
2980 
2981 	return (opt);
2982 }
2983 
2984 /*
2985  * Use the outgoing IP header to create an IP_OPTIONS option the way
2986  * it was passed down from the application.
2987  */
2988 int
2989 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2990 {
2991 	ipoptp_t	opts;
2992 	const uchar_t	*opt;
2993 	uint8_t		optval;
2994 	uint8_t		optlen;
2995 	uint32_t	len = 0;
2996 	uchar_t	*buf1 = buf;
2997 
2998 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2999 	len += IP_ADDR_LEN;
3000 	bzero(buf1, IP_ADDR_LEN);
3001 
3002 	/*
3003 	 * OK to cast away const here, as we don't store through the returned
3004 	 * opts.ipoptp_cur pointer.
3005 	 */
3006 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
3007 	    optval != IPOPT_EOL;
3008 	    optval = ipoptp_next(&opts)) {
3009 		int	off;
3010 
3011 		opt = opts.ipoptp_cur;
3012 		optlen = opts.ipoptp_len;
3013 		switch (optval) {
3014 		case IPOPT_SSRR:
3015 		case IPOPT_LSRR:
3016 
3017 			/*
3018 			 * Insert ipha_dst as the first entry in the source
3019 			 * route and move down the entries on step.
3020 			 * The last entry gets placed at buf1.
3021 			 */
3022 			buf[IPOPT_OPTVAL] = optval;
3023 			buf[IPOPT_OLEN] = optlen;
3024 			buf[IPOPT_OFFSET] = optlen;
3025 
3026 			off = optlen - IP_ADDR_LEN;
3027 			if (off < 0) {
3028 				/* No entries in source route */
3029 				break;
3030 			}
3031 			/* Last entry in source route */
3032 			bcopy(opt + off, buf1, IP_ADDR_LEN);
3033 			off -= IP_ADDR_LEN;
3034 
3035 			while (off > 0) {
3036 				bcopy(opt + off,
3037 				    buf + off + IP_ADDR_LEN,
3038 				    IP_ADDR_LEN);
3039 				off -= IP_ADDR_LEN;
3040 			}
3041 			/* ipha_dst into first slot */
3042 			bcopy(&ipha->ipha_dst,
3043 			    buf + off + IP_ADDR_LEN,
3044 			    IP_ADDR_LEN);
3045 			buf += optlen;
3046 			len += optlen;
3047 			break;
3048 
3049 		case IPOPT_COMSEC:
3050 		case IPOPT_SECURITY:
3051 			/* if passing up a label is not ok, then remove */
3052 			if (is_system_labeled())
3053 				break;
3054 			/* FALLTHROUGH */
3055 		default:
3056 			bcopy(opt, buf, optlen);
3057 			buf += optlen;
3058 			len += optlen;
3059 			break;
3060 		}
3061 	}
3062 done:
3063 	/* Pad the resulting options */
3064 	while (len & 0x3) {
3065 		*buf++ = IPOPT_EOL;
3066 		len++;
3067 	}
3068 	return (len);
3069 }
3070 
3071 /*
3072  * Update any record route or timestamp options to include this host.
3073  * Reverse any source route option.
3074  * This routine assumes that the options are well formed i.e. that they
3075  * have already been checked.
3076  */
3077 static void
3078 icmp_options_update(ipha_t *ipha)
3079 {
3080 	ipoptp_t	opts;
3081 	uchar_t		*opt;
3082 	uint8_t		optval;
3083 	ipaddr_t	src;		/* Our local address */
3084 	ipaddr_t	dst;
3085 
3086 	ip2dbg(("icmp_options_update\n"));
3087 	src = ipha->ipha_src;
3088 	dst = ipha->ipha_dst;
3089 
3090 	for (optval = ipoptp_first(&opts, ipha);
3091 	    optval != IPOPT_EOL;
3092 	    optval = ipoptp_next(&opts)) {
3093 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3094 		opt = opts.ipoptp_cur;
3095 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3096 		    optval, opts.ipoptp_len));
3097 		switch (optval) {
3098 			int off1, off2;
3099 		case IPOPT_SSRR:
3100 		case IPOPT_LSRR:
3101 			/*
3102 			 * Reverse the source route.  The first entry
3103 			 * should be the next to last one in the current
3104 			 * source route (the last entry is our address).
3105 			 * The last entry should be the final destination.
3106 			 */
3107 			off1 = IPOPT_MINOFF_SR - 1;
3108 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3109 			if (off2 < 0) {
3110 				/* No entries in source route */
3111 				ip1dbg((
3112 				    "icmp_options_update: bad src route\n"));
3113 				break;
3114 			}
3115 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3116 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3117 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3118 			off2 -= IP_ADDR_LEN;
3119 
3120 			while (off1 < off2) {
3121 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3122 				bcopy((char *)opt + off2, (char *)opt + off1,
3123 				    IP_ADDR_LEN);
3124 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3125 				off1 += IP_ADDR_LEN;
3126 				off2 -= IP_ADDR_LEN;
3127 			}
3128 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3129 			break;
3130 		}
3131 	}
3132 }
3133 
3134 /*
3135  * Process received ICMP Redirect messages.
3136  */
3137 /* ARGSUSED */
3138 static void
3139 icmp_redirect(mblk_t *mp)
3140 {
3141 	ipha_t	*ipha;
3142 	int	iph_hdr_length;
3143 	icmph_t	*icmph;
3144 	ipha_t	*ipha_err;
3145 	ire_t	*ire;
3146 	ire_t	*prev_ire;
3147 	ire_t	*save_ire;
3148 	ipaddr_t  src, dst, gateway;
3149 	iulp_t	ulp_info = { 0 };
3150 	int	error;
3151 
3152 	ipha = (ipha_t *)mp->b_rptr;
3153 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3154 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3155 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3156 		BUMP_MIB(&icmp_mib, icmpInErrors);
3157 		freemsg(mp);
3158 		return;
3159 	}
3160 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3161 	ipha_err = (ipha_t *)&icmph[1];
3162 	src = ipha->ipha_src;
3163 	dst = ipha_err->ipha_dst;
3164 	gateway = icmph->icmph_rd_gateway;
3165 	/* Make sure the new gateway is reachable somehow. */
3166 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3167 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3168 	/*
3169 	 * Make sure we had a route for the dest in question and that
3170 	 * that route was pointing to the old gateway (the source of the
3171 	 * redirect packet.)
3172 	 */
3173 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3174 	    NULL, MATCH_IRE_GW);
3175 	/*
3176 	 * Check that
3177 	 *	the redirect was not from ourselves
3178 	 *	the new gateway and the old gateway are directly reachable
3179 	 */
3180 	if (!prev_ire ||
3181 	    !ire ||
3182 	    ire->ire_type == IRE_LOCAL) {
3183 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3184 		freemsg(mp);
3185 		if (ire != NULL)
3186 			ire_refrele(ire);
3187 		if (prev_ire != NULL)
3188 			ire_refrele(prev_ire);
3189 		return;
3190 	}
3191 
3192 	/*
3193 	 * Should we use the old ULP info to create the new gateway?  From
3194 	 * a user's perspective, we should inherit the info so that it
3195 	 * is a "smooth" transition.  If we do not do that, then new
3196 	 * connections going thru the new gateway will have no route metrics,
3197 	 * which is counter-intuitive to user.  From a network point of
3198 	 * view, this may or may not make sense even though the new gateway
3199 	 * is still directly connected to us so the route metrics should not
3200 	 * change much.
3201 	 *
3202 	 * But if the old ire_uinfo is not initialized, we do another
3203 	 * recursive lookup on the dest using the new gateway.  There may
3204 	 * be a route to that.  If so, use it to initialize the redirect
3205 	 * route.
3206 	 */
3207 	if (prev_ire->ire_uinfo.iulp_set) {
3208 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3209 	} else {
3210 		ire_t *tmp_ire;
3211 		ire_t *sire;
3212 
3213 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3214 		    ALL_ZONES, 0, NULL,
3215 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3216 		if (sire != NULL) {
3217 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3218 			/*
3219 			 * If sire != NULL, ire_ftable_lookup() should not
3220 			 * return a NULL value.
3221 			 */
3222 			ASSERT(tmp_ire != NULL);
3223 			ire_refrele(tmp_ire);
3224 			ire_refrele(sire);
3225 		} else if (tmp_ire != NULL) {
3226 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3227 			    sizeof (iulp_t));
3228 			ire_refrele(tmp_ire);
3229 		}
3230 	}
3231 	if (prev_ire->ire_type == IRE_CACHE)
3232 		ire_delete(prev_ire);
3233 	ire_refrele(prev_ire);
3234 	/*
3235 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3236 	 * require TOS routing
3237 	 */
3238 	switch (icmph->icmph_code) {
3239 	case 0:
3240 	case 1:
3241 		/* TODO: TOS specificity for cases 2 and 3 */
3242 	case 2:
3243 	case 3:
3244 		break;
3245 	default:
3246 		freemsg(mp);
3247 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3248 		ire_refrele(ire);
3249 		return;
3250 	}
3251 	/*
3252 	 * Create a Route Association.  This will allow us to remember that
3253 	 * someone we believe told us to use the particular gateway.
3254 	 */
3255 	save_ire = ire;
3256 	ire = ire_create(
3257 		(uchar_t *)&dst,			/* dest addr */
3258 		(uchar_t *)&ip_g_all_ones,		/* mask */
3259 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3260 		(uchar_t *)&gateway,			/* gateway addr */
3261 		NULL,					/* no in_srcaddr */
3262 		&save_ire->ire_max_frag,		/* max frag */
3263 		NULL,					/* Fast Path header */
3264 		NULL,					/* no rfq */
3265 		NULL,					/* no stq */
3266 		IRE_HOST_REDIRECT,
3267 		NULL,
3268 		NULL,
3269 		NULL,
3270 		0,
3271 		0,
3272 		0,
3273 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3274 		&ulp_info,
3275 		NULL,
3276 		NULL);
3277 
3278 	if (ire == NULL) {
3279 		freemsg(mp);
3280 		ire_refrele(save_ire);
3281 		return;
3282 	}
3283 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3284 	ire_refrele(save_ire);
3285 	atomic_inc_32(&ip_redirect_cnt);
3286 
3287 	if (error == 0) {
3288 		ire_refrele(ire);		/* Held in ire_add_v4 */
3289 		/* tell routing sockets that we received a redirect */
3290 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3291 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3292 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3293 	}
3294 
3295 	/*
3296 	 * Delete any existing IRE_HOST_REDIRECT for this destination.
3297 	 * This together with the added IRE has the effect of
3298 	 * modifying an existing redirect.
3299 	 */
3300 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST_REDIRECT, NULL, NULL,
3301 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3302 	if (prev_ire) {
3303 		ire_delete(prev_ire);
3304 		ire_refrele(prev_ire);
3305 	}
3306 
3307 	freemsg(mp);
3308 }
3309 
3310 /*
3311  * Generate an ICMP parameter problem message.
3312  */
3313 static void
3314 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid)
3315 {
3316 	icmph_t	icmph;
3317 	boolean_t mctl_present;
3318 	mblk_t *first_mp;
3319 
3320 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3321 
3322 	if (!(mp = icmp_pkt_err_ok(mp))) {
3323 		if (mctl_present)
3324 			freeb(first_mp);
3325 		return;
3326 	}
3327 
3328 	bzero(&icmph, sizeof (icmph_t));
3329 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3330 	icmph.icmph_pp_ptr = ptr;
3331 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3332 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3333 }
3334 
3335 /*
3336  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3337  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3338  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3339  * an icmp error packet can be sent.
3340  * Assigns an appropriate source address to the packet. If ipha_dst is
3341  * one of our addresses use it for source. Otherwise pick a source based
3342  * on a route lookup back to ipha_src.
3343  * Note that ipha_src must be set here since the
3344  * packet is likely to arrive on an ill queue in ip_wput() which will
3345  * not set a source address.
3346  */
3347 static void
3348 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3349     boolean_t mctl_present, zoneid_t zoneid)
3350 {
3351 	ipaddr_t dst;
3352 	icmph_t	*icmph;
3353 	ipha_t	*ipha;
3354 	uint_t	len_needed;
3355 	size_t	msg_len;
3356 	mblk_t	*mp1;
3357 	ipaddr_t src;
3358 	ire_t	*ire;
3359 	mblk_t *ipsec_mp;
3360 	ipsec_out_t	*io = NULL;
3361 	boolean_t xmit_if_on = B_FALSE;
3362 
3363 	if (mctl_present) {
3364 		/*
3365 		 * If it is :
3366 		 *
3367 		 * 1) a IPSEC_OUT, then this is caused by outbound
3368 		 *    datagram originating on this host. IPSEC processing
3369 		 *    may or may not have been done. Refer to comments above
3370 		 *    icmp_inbound_error_fanout for details.
3371 		 *
3372 		 * 2) a IPSEC_IN if we are generating a icmp_message
3373 		 *    for an incoming datagram destined for us i.e called
3374 		 *    from ip_fanout_send_icmp.
3375 		 */
3376 		ipsec_info_t *in;
3377 		ipsec_mp = mp;
3378 		mp = ipsec_mp->b_cont;
3379 
3380 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3381 		ipha = (ipha_t *)mp->b_rptr;
3382 
3383 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3384 		    in->ipsec_info_type == IPSEC_IN);
3385 
3386 		if (in->ipsec_info_type == IPSEC_IN) {
3387 			/*
3388 			 * Convert the IPSEC_IN to IPSEC_OUT.
3389 			 */
3390 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3391 				BUMP_MIB(&ip_mib, ipOutDiscards);
3392 				return;
3393 			}
3394 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3395 		} else {
3396 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3397 			io = (ipsec_out_t *)in;
3398 			if (io->ipsec_out_xmit_if)
3399 				xmit_if_on = B_TRUE;
3400 			/*
3401 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3402 			 * ire lookup.
3403 			 */
3404 			io->ipsec_out_proc_begin = B_FALSE;
3405 		}
3406 		ASSERT(zoneid == io->ipsec_out_zoneid);
3407 		ASSERT(zoneid != ALL_ZONES);
3408 	} else {
3409 		/*
3410 		 * This is in clear. The icmp message we are building
3411 		 * here should go out in clear.
3412 		 *
3413 		 * Pardon the convolution of it all, but it's easier to
3414 		 * allocate a "use cleartext" IPSEC_IN message and convert
3415 		 * it than it is to allocate a new one.
3416 		 */
3417 		ipsec_in_t *ii;
3418 		ASSERT(DB_TYPE(mp) == M_DATA);
3419 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3420 			freemsg(mp);
3421 			BUMP_MIB(&ip_mib, ipOutDiscards);
3422 			return;
3423 		}
3424 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3425 
3426 		/* This is not a secure packet */
3427 		ii->ipsec_in_secure = B_FALSE;
3428 		/*
3429 		 * For trusted extensions using a shared IP address we can
3430 		 * send using any zoneid.
3431 		 */
3432 		if (zoneid == ALL_ZONES)
3433 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3434 		else
3435 			ii->ipsec_in_zoneid = zoneid;
3436 		ipsec_mp->b_cont = mp;
3437 		ipha = (ipha_t *)mp->b_rptr;
3438 		/*
3439 		 * Convert the IPSEC_IN to IPSEC_OUT.
3440 		 */
3441 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3442 			BUMP_MIB(&ip_mib, ipOutDiscards);
3443 			return;
3444 		}
3445 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3446 	}
3447 
3448 	/* Remember our eventual destination */
3449 	dst = ipha->ipha_src;
3450 
3451 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3452 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3453 	if (ire != NULL &&
3454 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3455 		src = ipha->ipha_dst;
3456 	} else if (!xmit_if_on) {
3457 		if (ire != NULL)
3458 			ire_refrele(ire);
3459 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3460 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3461 		if (ire == NULL) {
3462 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3463 			freemsg(ipsec_mp);
3464 			return;
3465 		}
3466 		src = ire->ire_src_addr;
3467 	} else {
3468 		ipif_t	*ipif = NULL;
3469 		ill_t	*ill;
3470 		/*
3471 		 * This must be an ICMP error coming from
3472 		 * ip_mrtun_forward(). The src addr should
3473 		 * be equal to the IP-addr of the outgoing
3474 		 * interface.
3475 		 */
3476 		if (io == NULL) {
3477 			/* This is not a IPSEC_OUT type control msg */
3478 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3479 			freemsg(ipsec_mp);
3480 			return;
3481 		}
3482 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3483 		    NULL, NULL, NULL, NULL);
3484 		if (ill != NULL) {
3485 			ipif = ipif_get_next_ipif(NULL, ill);
3486 			ill_refrele(ill);
3487 		}
3488 		if (ipif == NULL) {
3489 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3490 			freemsg(ipsec_mp);
3491 			return;
3492 		}
3493 		src = ipif->ipif_src_addr;
3494 		ipif_refrele(ipif);
3495 	}
3496 
3497 	if (ire != NULL)
3498 		ire_refrele(ire);
3499 
3500 	/*
3501 	 * Check if we can send back more then 8 bytes in addition
3502 	 * to the IP header. We will include as much as 64 bytes.
3503 	 */
3504 	len_needed = IPH_HDR_LENGTH(ipha);
3505 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3506 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3507 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3508 	}
3509 	len_needed += ip_icmp_return;
3510 	msg_len = msgdsize(mp);
3511 	if (msg_len > len_needed) {
3512 		(void) adjmsg(mp, len_needed - msg_len);
3513 		msg_len = len_needed;
3514 	}
3515 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3516 	if (mp1 == NULL) {
3517 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3518 		freemsg(ipsec_mp);
3519 		return;
3520 	}
3521 	/*
3522 	 * On an unlabeled system, dblks don't necessarily have creds.
3523 	 */
3524 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3525 	if (DB_CRED(mp) != NULL)
3526 		mblk_setcred(mp1, DB_CRED(mp));
3527 	mp1->b_cont = mp;
3528 	mp = mp1;
3529 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3530 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3531 	    io->ipsec_out_type == IPSEC_OUT);
3532 	ipsec_mp->b_cont = mp;
3533 
3534 	/*
3535 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3536 	 * node generates be accepted in peace by all on-host destinations.
3537 	 * If we do NOT assume that all on-host destinations trust
3538 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3539 	 * (Look for ipsec_out_icmp_loopback).
3540 	 */
3541 	io->ipsec_out_icmp_loopback = B_TRUE;
3542 
3543 	ipha = (ipha_t *)mp->b_rptr;
3544 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3545 	*ipha = icmp_ipha;
3546 	ipha->ipha_src = src;
3547 	ipha->ipha_dst = dst;
3548 	ipha->ipha_ttl = ip_def_ttl;
3549 	msg_len += sizeof (icmp_ipha) + len;
3550 	if (msg_len > IP_MAXPACKET) {
3551 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3552 		msg_len = IP_MAXPACKET;
3553 	}
3554 	ipha->ipha_length = htons((uint16_t)msg_len);
3555 	icmph = (icmph_t *)&ipha[1];
3556 	bcopy(stuff, icmph, len);
3557 	icmph->icmph_checksum = 0;
3558 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3559 	if (icmph->icmph_checksum == 0)
3560 		icmph->icmph_checksum = 0xFFFF;
3561 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3562 	put(q, ipsec_mp);
3563 }
3564 
3565 /*
3566  * Determine if an ICMP error packet can be sent given the rate limit.
3567  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3568  * in milliseconds) and a burst size. Burst size number of packets can
3569  * be sent arbitrarely closely spaced.
3570  * The state is tracked using two variables to implement an approximate
3571  * token bucket filter:
3572  *	icmp_pkt_err_last - lbolt value when the last burst started
3573  *	icmp_pkt_err_sent - number of packets sent in current burst
3574  */
3575 boolean_t
3576 icmp_err_rate_limit(void)
3577 {
3578 	clock_t now = TICK_TO_MSEC(lbolt);
3579 	uint_t refilled; /* Number of packets refilled in tbf since last */
3580 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3581 
3582 	if (err_interval == 0)
3583 		return (B_FALSE);
3584 
3585 	if (icmp_pkt_err_last > now) {
3586 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3587 		icmp_pkt_err_last = 0;
3588 		icmp_pkt_err_sent = 0;
3589 	}
3590 	/*
3591 	 * If we are in a burst update the token bucket filter.
3592 	 * Update the "last" time to be close to "now" but make sure
3593 	 * we don't loose precision.
3594 	 */
3595 	if (icmp_pkt_err_sent != 0) {
3596 		refilled = (now - icmp_pkt_err_last)/err_interval;
3597 		if (refilled > icmp_pkt_err_sent) {
3598 			icmp_pkt_err_sent = 0;
3599 		} else {
3600 			icmp_pkt_err_sent -= refilled;
3601 			icmp_pkt_err_last += refilled * err_interval;
3602 		}
3603 	}
3604 	if (icmp_pkt_err_sent == 0) {
3605 		/* Start of new burst */
3606 		icmp_pkt_err_last = now;
3607 	}
3608 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3609 		icmp_pkt_err_sent++;
3610 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3611 		    icmp_pkt_err_sent));
3612 		return (B_FALSE);
3613 	}
3614 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3615 	return (B_TRUE);
3616 }
3617 
3618 /*
3619  * Check if it is ok to send an IPv4 ICMP error packet in
3620  * response to the IPv4 packet in mp.
3621  * Free the message and return null if no
3622  * ICMP error packet should be sent.
3623  */
3624 static mblk_t *
3625 icmp_pkt_err_ok(mblk_t *mp)
3626 {
3627 	icmph_t	*icmph;
3628 	ipha_t	*ipha;
3629 	uint_t	len_needed;
3630 	ire_t	*src_ire;
3631 	ire_t	*dst_ire;
3632 
3633 	if (!mp)
3634 		return (NULL);
3635 	ipha = (ipha_t *)mp->b_rptr;
3636 	if (ip_csum_hdr(ipha)) {
3637 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3638 		freemsg(mp);
3639 		return (NULL);
3640 	}
3641 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3642 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3643 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3644 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3645 	if (src_ire != NULL || dst_ire != NULL ||
3646 	    CLASSD(ipha->ipha_dst) ||
3647 	    CLASSD(ipha->ipha_src) ||
3648 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3649 		/* Note: only errors to the fragment with offset 0 */
3650 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3651 		freemsg(mp);
3652 		if (src_ire != NULL)
3653 			ire_refrele(src_ire);
3654 		if (dst_ire != NULL)
3655 			ire_refrele(dst_ire);
3656 		return (NULL);
3657 	}
3658 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3659 		/*
3660 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3661 		 * errors in response to any ICMP errors.
3662 		 */
3663 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3664 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3665 			if (!pullupmsg(mp, len_needed)) {
3666 				BUMP_MIB(&icmp_mib, icmpInErrors);
3667 				freemsg(mp);
3668 				return (NULL);
3669 			}
3670 			ipha = (ipha_t *)mp->b_rptr;
3671 		}
3672 		icmph = (icmph_t *)
3673 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3674 		switch (icmph->icmph_type) {
3675 		case ICMP_DEST_UNREACHABLE:
3676 		case ICMP_SOURCE_QUENCH:
3677 		case ICMP_TIME_EXCEEDED:
3678 		case ICMP_PARAM_PROBLEM:
3679 		case ICMP_REDIRECT:
3680 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3681 			freemsg(mp);
3682 			return (NULL);
3683 		default:
3684 			break;
3685 		}
3686 	}
3687 	/*
3688 	 * If this is a labeled system, then check to see if we're allowed to
3689 	 * send a response to this particular sender.  If not, then just drop.
3690 	 */
3691 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3692 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3693 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3694 		freemsg(mp);
3695 		return (NULL);
3696 	}
3697 	if (icmp_err_rate_limit()) {
3698 		/*
3699 		 * Only send ICMP error packets every so often.
3700 		 * This should be done on a per port/source basis,
3701 		 * but for now this will suffice.
3702 		 */
3703 		freemsg(mp);
3704 		return (NULL);
3705 	}
3706 	return (mp);
3707 }
3708 
3709 /*
3710  * Generate an ICMP redirect message.
3711  */
3712 static void
3713 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3714 {
3715 	icmph_t	icmph;
3716 
3717 	/*
3718 	 * We are called from ip_rput where we could
3719 	 * not have attached an IPSEC_IN.
3720 	 */
3721 	ASSERT(mp->b_datap->db_type == M_DATA);
3722 
3723 	if (!(mp = icmp_pkt_err_ok(mp))) {
3724 		return;
3725 	}
3726 
3727 	bzero(&icmph, sizeof (icmph_t));
3728 	icmph.icmph_type = ICMP_REDIRECT;
3729 	icmph.icmph_code = 1;
3730 	icmph.icmph_rd_gateway = gateway;
3731 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3732 	/* Redirects sent by router, and router is global zone */
3733 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID);
3734 }
3735 
3736 /*
3737  * Generate an ICMP time exceeded message.
3738  */
3739 void
3740 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3741 {
3742 	icmph_t	icmph;
3743 	boolean_t mctl_present;
3744 	mblk_t *first_mp;
3745 
3746 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3747 
3748 	if (!(mp = icmp_pkt_err_ok(mp))) {
3749 		if (mctl_present)
3750 			freeb(first_mp);
3751 		return;
3752 	}
3753 
3754 	bzero(&icmph, sizeof (icmph_t));
3755 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3756 	icmph.icmph_code = code;
3757 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3758 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3759 }
3760 
3761 /*
3762  * Generate an ICMP unreachable message.
3763  */
3764 void
3765 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3766 {
3767 	icmph_t	icmph;
3768 	mblk_t *first_mp;
3769 	boolean_t mctl_present;
3770 
3771 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3772 
3773 	if (!(mp = icmp_pkt_err_ok(mp))) {
3774 		if (mctl_present)
3775 			freeb(first_mp);
3776 		return;
3777 	}
3778 
3779 	bzero(&icmph, sizeof (icmph_t));
3780 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3781 	icmph.icmph_code = code;
3782 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3783 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3784 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3785 	    zoneid);
3786 }
3787 
3788 /*
3789  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3790  * duplicate.  As long as someone else holds the address, the interface will
3791  * stay down.  When that conflict goes away, the interface is brought back up.
3792  * This is done so that accidental shutdowns of addresses aren't made
3793  * permanent.  Your server will recover from a failure.
3794  *
3795  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3796  * user space process (dhcpagent).
3797  *
3798  * Recovery completes if ARP reports that the address is now ours (via
3799  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3800  *
3801  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3802  */
3803 static void
3804 ipif_dup_recovery(void *arg)
3805 {
3806 	ipif_t *ipif = arg;
3807 	ill_t *ill = ipif->ipif_ill;
3808 	mblk_t *arp_add_mp;
3809 	mblk_t *arp_del_mp;
3810 	area_t *area;
3811 
3812 	ipif->ipif_recovery_id = 0;
3813 
3814 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3815 	    (ipif->ipif_flags & IPIF_POINTOPOINT)) {
3816 		/* No reason to try to bring this address back. */
3817 		return;
3818 	}
3819 
3820 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3821 		goto alloc_fail;
3822 
3823 	if (ipif->ipif_arp_del_mp == NULL) {
3824 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3825 			goto alloc_fail;
3826 		ipif->ipif_arp_del_mp = arp_del_mp;
3827 	}
3828 
3829 	/* Setting the 'unverified' flag restarts DAD */
3830 	area = (area_t *)arp_add_mp->b_rptr;
3831 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3832 	    ACE_F_UNVERIFIED;
3833 	putnext(ill->ill_rq, arp_add_mp);
3834 	return;
3835 
3836 alloc_fail:
3837 	/* On allocation failure, just restart the timer */
3838 	freemsg(arp_add_mp);
3839 	if (ip_dup_recovery > 0) {
3840 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3841 		    MSEC_TO_TICK(ip_dup_recovery));
3842 	}
3843 }
3844 
3845 /*
3846  * This is for exclusive changes due to ARP.  Either tear down an interface due
3847  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3848  */
3849 /* ARGSUSED */
3850 static void
3851 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3852 {
3853 	ill_t	*ill = rq->q_ptr;
3854 	arh_t *arh;
3855 	ipaddr_t src;
3856 	ipif_t	*ipif;
3857 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3858 	char hbuf[MAC_STR_LEN];
3859 	char sbuf[INET_ADDRSTRLEN];
3860 	const char *failtype;
3861 	boolean_t bring_up;
3862 
3863 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3864 	case AR_CN_READY:
3865 		failtype = NULL;
3866 		bring_up = B_TRUE;
3867 		break;
3868 	case AR_CN_FAILED:
3869 		failtype = "in use";
3870 		bring_up = B_FALSE;
3871 		break;
3872 	default:
3873 		failtype = "claimed";
3874 		bring_up = B_FALSE;
3875 		break;
3876 	}
3877 
3878 	arh = (arh_t *)mp->b_cont->b_rptr;
3879 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3880 
3881 	/* Handle failures due to probes */
3882 	if (src == 0) {
3883 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3884 		    IP_ADDR_LEN);
3885 	}
3886 
3887 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3888 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3889 	    sizeof (hbuf));
3890 	(void) ip_dot_addr(src, sbuf);
3891 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3892 
3893 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3894 		    ipif->ipif_lcl_addr != src) {
3895 			continue;
3896 		}
3897 
3898 		/*
3899 		 * If we failed on a recovery probe, then restart the timer to
3900 		 * try again later.
3901 		 */
3902 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3903 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3904 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3905 		    ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0) {
3906 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3907 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3908 			continue;
3909 		}
3910 
3911 		/*
3912 		 * If what we're trying to do has already been done, then do
3913 		 * nothing.
3914 		 */
3915 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3916 			continue;
3917 
3918 		if (ipif->ipif_id != 0) {
3919 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3920 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3921 			    ipif->ipif_id);
3922 		}
3923 		if (failtype == NULL) {
3924 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3925 			    ibuf);
3926 		} else {
3927 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3928 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3929 		}
3930 
3931 		if (bring_up) {
3932 			ASSERT(ill->ill_dl_up);
3933 			/*
3934 			 * Free up the ARP delete message so we can allocate
3935 			 * a fresh one through the normal path.
3936 			 */
3937 			freemsg(ipif->ipif_arp_del_mp);
3938 			ipif->ipif_arp_del_mp = NULL;
3939 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3940 			    EINPROGRESS) {
3941 				ipif->ipif_addr_ready = 1;
3942 				(void) ipif_up_done(ipif);
3943 			}
3944 			continue;
3945 		}
3946 
3947 		mutex_enter(&ill->ill_lock);
3948 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3949 		ipif->ipif_flags |= IPIF_DUPLICATE;
3950 		ill->ill_ipif_dup_count++;
3951 		mutex_exit(&ill->ill_lock);
3952 		/*
3953 		 * Already exclusive on the ill; no need to handle deferred
3954 		 * processing here.
3955 		 */
3956 		(void) ipif_down(ipif, NULL, NULL);
3957 		ipif_down_tail(ipif);
3958 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3959 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3960 		    ip_dup_recovery > 0) {
3961 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3962 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3963 		}
3964 	}
3965 	freemsg(mp);
3966 }
3967 
3968 /* ARGSUSED */
3969 static void
3970 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3971 {
3972 	ill_t	*ill = rq->q_ptr;
3973 	arh_t *arh;
3974 	ipaddr_t src;
3975 	ipif_t	*ipif;
3976 
3977 	arh = (arh_t *)mp->b_cont->b_rptr;
3978 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3979 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3980 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3981 			(void) ipif_resolver_up(ipif, Res_act_defend);
3982 	}
3983 	freemsg(mp);
3984 }
3985 
3986 /*
3987  * News from ARP.  ARP sends notification of interesting events down
3988  * to its clients using M_CTL messages with the interesting ARP packet
3989  * attached via b_cont.
3990  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3991  * queue as opposed to ARP sending the message to all the clients, i.e. all
3992  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3993  * table if a cache IRE is found to delete all the entries for the address in
3994  * the packet.
3995  */
3996 static void
3997 ip_arp_news(queue_t *q, mblk_t *mp)
3998 {
3999 	arcn_t		*arcn;
4000 	arh_t		*arh;
4001 	ire_t		*ire = NULL;
4002 	char		hbuf[MAC_STR_LEN];
4003 	char		sbuf[INET_ADDRSTRLEN];
4004 	ipaddr_t	src;
4005 	in6_addr_t	v6src;
4006 	boolean_t	isv6 = B_FALSE;
4007 	ipif_t		*ipif;
4008 	ill_t		*ill;
4009 
4010 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
4011 		if (q->q_next) {
4012 			putnext(q, mp);
4013 		} else
4014 			freemsg(mp);
4015 		return;
4016 	}
4017 	arh = (arh_t *)mp->b_cont->b_rptr;
4018 	/* Is it one we are interested in? */
4019 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
4020 		isv6 = B_TRUE;
4021 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
4022 		    IPV6_ADDR_LEN);
4023 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
4024 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
4025 		    IP_ADDR_LEN);
4026 	} else {
4027 		freemsg(mp);
4028 		return;
4029 	}
4030 
4031 	ill = q->q_ptr;
4032 
4033 	arcn = (arcn_t *)mp->b_rptr;
4034 	switch (arcn->arcn_code) {
4035 	case AR_CN_BOGON:
4036 		/*
4037 		 * Someone is sending ARP packets with a source protocol
4038 		 * address that we have published and for which we believe our
4039 		 * entry is authoritative and (when ill_arp_extend is set)
4040 		 * verified to be unique on the network.
4041 		 *
4042 		 * The ARP module internally handles the cases where the sender
4043 		 * is just probing (for DAD) and where the hardware address of
4044 		 * a non-authoritative entry has changed.  Thus, these are the
4045 		 * real conflicts, and we have to do resolution.
4046 		 *
4047 		 * We back away quickly from the address if it's from DHCP or
4048 		 * otherwise temporary and hasn't been used recently (or at
4049 		 * all).  We'd like to include "deprecated" addresses here as
4050 		 * well (as there's no real reason to defend something we're
4051 		 * discarding), but IPMP "reuses" this flag to mean something
4052 		 * other than the standard meaning.
4053 		 *
4054 		 * If the ARP module above is not extended (meaning that it
4055 		 * doesn't know how to defend the address), then we just log
4056 		 * the problem as we always did and continue on.  It's not
4057 		 * right, but there's little else we can do, and those old ATM
4058 		 * users are going away anyway.
4059 		 */
4060 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4061 		    hbuf, sizeof (hbuf));
4062 		(void) ip_dot_addr(src, sbuf);
4063 		if (isv6)
4064 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
4065 		else
4066 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
4067 
4068 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4069 			uint32_t now;
4070 			uint32_t maxage;
4071 			clock_t lused;
4072 			uint_t maxdefense;
4073 			uint_t defs;
4074 
4075 			/*
4076 			 * First, figure out if this address hasn't been used
4077 			 * in a while.  If it hasn't, then it's a better
4078 			 * candidate for abandoning.
4079 			 */
4080 			ipif = ire->ire_ipif;
4081 			ASSERT(ipif != NULL);
4082 			now = gethrestime_sec();
4083 			maxage = now - ire->ire_create_time;
4084 			if (maxage > ip_max_temp_idle)
4085 				maxage = ip_max_temp_idle;
4086 			lused = drv_hztousec(ddi_get_lbolt() -
4087 			    ire->ire_last_used_time) / MICROSEC + 1;
4088 			if (lused >= maxage && (ipif->ipif_flags &
4089 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4090 				maxdefense = ip_max_temp_defend;
4091 			else
4092 				maxdefense = ip_max_defend;
4093 
4094 			/*
4095 			 * Now figure out how many times we've defended
4096 			 * ourselves.  Ignore defenses that happened long in
4097 			 * the past.
4098 			 */
4099 			mutex_enter(&ire->ire_lock);
4100 			if ((defs = ire->ire_defense_count) > 0 &&
4101 			    now - ire->ire_defense_time > ip_defend_interval) {
4102 				ire->ire_defense_count = defs = 0;
4103 			}
4104 			ire->ire_defense_count++;
4105 			ire->ire_defense_time = now;
4106 			mutex_exit(&ire->ire_lock);
4107 			ill_refhold(ill);
4108 			ire_refrele(ire);
4109 
4110 			/*
4111 			 * If we've defended ourselves too many times already,
4112 			 * then give up and tear down the interface(s) using
4113 			 * this address.  Otherwise, defend by sending out a
4114 			 * gratuitous ARP.
4115 			 */
4116 			if (defs >= maxdefense && ill->ill_arp_extend) {
4117 				(void) qwriter_ip(NULL, ill, q, mp,
4118 				    ip_arp_excl, CUR_OP, B_FALSE);
4119 			} else {
4120 				cmn_err(CE_WARN,
4121 				    "node %s is using our IP address %s on %s",
4122 				    hbuf, sbuf, ill->ill_name);
4123 				/*
4124 				 * If this is an old (ATM) ARP module, then
4125 				 * don't try to defend the address.  Remain
4126 				 * compatible with the old behavior.  Defend
4127 				 * only with new ARP.
4128 				 */
4129 				if (ill->ill_arp_extend) {
4130 					(void) qwriter_ip(NULL, ill, q, mp,
4131 					    ip_arp_defend, CUR_OP, B_FALSE);
4132 				} else {
4133 					ill_refrele(ill);
4134 				}
4135 			}
4136 			return;
4137 		}
4138 		cmn_err(CE_WARN,
4139 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4140 		    hbuf, sbuf, ill->ill_name);
4141 		if (ire != NULL)
4142 			ire_refrele(ire);
4143 		break;
4144 	case AR_CN_ANNOUNCE:
4145 		if (isv6) {
4146 			/*
4147 			 * For XRESOLV interfaces.
4148 			 * Delete the IRE cache entry and NCE for this
4149 			 * v6 address
4150 			 */
4151 			ip_ire_clookup_and_delete_v6(&v6src);
4152 			/*
4153 			 * If v6src is a non-zero, it's a router address
4154 			 * as below. Do the same sort of thing to clean
4155 			 * out off-net IRE_CACHE entries that go through
4156 			 * the router.
4157 			 */
4158 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4159 				ire_walk_v6(ire_delete_cache_gw_v6,
4160 				    (char *)&v6src, ALL_ZONES);
4161 			}
4162 		} else {
4163 			nce_hw_map_t hwm;
4164 
4165 			/*
4166 			 * ARP gives us a copy of any packet where it thinks
4167 			 * the address has changed, so that we can update our
4168 			 * caches.  We're responsible for caching known answers
4169 			 * in the current design.  We check whether the
4170 			 * hardware address really has changed in all of our
4171 			 * entries that have cached this mapping, and if so, we
4172 			 * blow them away.  This way we will immediately pick
4173 			 * up the rare case of a host changing hardware
4174 			 * address.
4175 			 */
4176 			if (src == 0)
4177 				break;
4178 			hwm.hwm_addr = src;
4179 			hwm.hwm_hwlen = arh->arh_hlen;
4180 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4181 			ndp_walk_common(&ndp4, NULL,
4182 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4183 		}
4184 		break;
4185 	case AR_CN_READY:
4186 		/* No external v6 resolver has a contract to use this */
4187 		if (isv6)
4188 			break;
4189 		/* If the link is down, we'll retry this later */
4190 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4191 			break;
4192 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4193 		    NULL, NULL);
4194 		if (ipif != NULL) {
4195 			/*
4196 			 * If this is a duplicate recovery, then we now need to
4197 			 * go exclusive to bring this thing back up.
4198 			 */
4199 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4200 			    IPIF_DUPLICATE) {
4201 				ipif_refrele(ipif);
4202 				ill_refhold(ill);
4203 				(void) qwriter_ip(NULL, ill, q, mp,
4204 				    ip_arp_excl, CUR_OP, B_FALSE);
4205 				return;
4206 			}
4207 			/*
4208 			 * If this is the first notice that this address is
4209 			 * ready, then let the user know now.
4210 			 */
4211 			if ((ipif->ipif_flags & IPIF_UP) &&
4212 			    !ipif->ipif_addr_ready) {
4213 				ipif_mask_reply(ipif);
4214 				ip_rts_ifmsg(ipif);
4215 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4216 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4217 			}
4218 			ipif->ipif_addr_ready = 1;
4219 			ipif_refrele(ipif);
4220 		}
4221 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp));
4222 		if (ire != NULL) {
4223 			ire->ire_defense_count = 0;
4224 			ire_refrele(ire);
4225 		}
4226 		break;
4227 	case AR_CN_FAILED:
4228 		/* No external v6 resolver has a contract to use this */
4229 		if (isv6)
4230 			break;
4231 		ill_refhold(ill);
4232 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4233 		    B_FALSE);
4234 		return;
4235 	}
4236 	freemsg(mp);
4237 }
4238 
4239 /*
4240  * Create a mblk suitable for carrying the interface index and/or source link
4241  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4242  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4243  * application.
4244  */
4245 mblk_t *
4246 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
4247 {
4248 	mblk_t		*mp;
4249 	in_pktinfo_t	*pinfo;
4250 	ipha_t *ipha;
4251 	struct ether_header *pether;
4252 
4253 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
4254 	if (mp == NULL) {
4255 		ip1dbg(("ip_add_info: allocation failure.\n"));
4256 		return (data_mp);
4257 	}
4258 
4259 	ipha	= (ipha_t *)data_mp->b_rptr;
4260 	pinfo = (in_pktinfo_t *)mp->b_rptr;
4261 	bzero(pinfo, sizeof (in_pktinfo_t));
4262 	pinfo->in_pkt_flags = (uchar_t)flags;
4263 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4264 
4265 	if (flags & IPF_RECVIF)
4266 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4267 
4268 	pether = (struct ether_header *)((char *)ipha
4269 	    - sizeof (struct ether_header));
4270 	/*
4271 	 * Make sure the interface is an ethernet type, since this option
4272 	 * is currently supported only on this type of interface. Also make
4273 	 * sure we are pointing correctly above db_base.
4274 	 */
4275 
4276 	if ((flags & IPF_RECVSLLA) &&
4277 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4278 	    (ill->ill_type == IFT_ETHER) &&
4279 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4280 
4281 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
4282 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4283 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
4284 	} else {
4285 		/*
4286 		 * Clear the bit. Indicate to upper layer that IP is not
4287 		 * sending this ancillary info.
4288 		 */
4289 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
4290 	}
4291 
4292 	mp->b_datap->db_type = M_CTL;
4293 	mp->b_wptr += sizeof (in_pktinfo_t);
4294 	mp->b_cont = data_mp;
4295 
4296 	return (mp);
4297 }
4298 
4299 /*
4300  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4301  * part of the bind request.
4302  */
4303 
4304 boolean_t
4305 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4306 {
4307 	ipsec_in_t *ii;
4308 
4309 	ASSERT(policy_mp != NULL);
4310 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4311 
4312 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4313 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4314 
4315 	connp->conn_policy = ii->ipsec_in_policy;
4316 	ii->ipsec_in_policy = NULL;
4317 
4318 	if (ii->ipsec_in_action != NULL) {
4319 		if (connp->conn_latch == NULL) {
4320 			connp->conn_latch = iplatch_create();
4321 			if (connp->conn_latch == NULL)
4322 				return (B_FALSE);
4323 		}
4324 		ipsec_latch_inbound(connp->conn_latch, ii);
4325 	}
4326 	return (B_TRUE);
4327 }
4328 
4329 /*
4330  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4331  * and to arrange for power-fanout assist.  The ULP is identified by
4332  * adding a single byte at the end of the original bind message.
4333  * A ULP other than UDP or TCP that wishes to be recognized passes
4334  * down a bind with a zero length address.
4335  *
4336  * The binding works as follows:
4337  * - A zero byte address means just bind to the protocol.
4338  * - A four byte address is treated as a request to validate
4339  *   that the address is a valid local address, appropriate for
4340  *   an application to bind to. This does not affect any fanout
4341  *   information in IP.
4342  * - A sizeof sin_t byte address is used to bind to only the local address
4343  *   and port.
4344  * - A sizeof ipa_conn_t byte address contains complete fanout information
4345  *   consisting of local and remote addresses and ports.  In
4346  *   this case, the addresses are both validated as appropriate
4347  *   for this operation, and, if so, the information is retained
4348  *   for use in the inbound fanout.
4349  *
4350  * The ULP (except in the zero-length bind) can append an
4351  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4352  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4353  * a copy of the source or destination IRE (source for local bind;
4354  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4355  * policy information contained should be copied on to the conn.
4356  *
4357  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4358  */
4359 mblk_t *
4360 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4361 {
4362 	ssize_t		len;
4363 	struct T_bind_req	*tbr;
4364 	sin_t		*sin;
4365 	ipa_conn_t	*ac;
4366 	uchar_t		*ucp;
4367 	mblk_t		*mp1;
4368 	boolean_t	ire_requested;
4369 	boolean_t	ipsec_policy_set = B_FALSE;
4370 	int		error = 0;
4371 	int		protocol;
4372 	ipa_conn_x_t	*acx;
4373 
4374 	ASSERT(!connp->conn_af_isv6);
4375 	connp->conn_pkt_isv6 = B_FALSE;
4376 
4377 	len = MBLKL(mp);
4378 	if (len < (sizeof (*tbr) + 1)) {
4379 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4380 		    "ip_bind: bogus msg, len %ld", len);
4381 		/* XXX: Need to return something better */
4382 		goto bad_addr;
4383 	}
4384 	/* Back up and extract the protocol identifier. */
4385 	mp->b_wptr--;
4386 	protocol = *mp->b_wptr & 0xFF;
4387 	tbr = (struct T_bind_req *)mp->b_rptr;
4388 	/* Reset the message type in preparation for shipping it back. */
4389 	DB_TYPE(mp) = M_PCPROTO;
4390 
4391 	connp->conn_ulp = (uint8_t)protocol;
4392 
4393 	/*
4394 	 * Check for a zero length address.  This is from a protocol that
4395 	 * wants to register to receive all packets of its type.
4396 	 */
4397 	if (tbr->ADDR_length == 0) {
4398 		/*
4399 		 * These protocols are now intercepted in ip_bind_v6().
4400 		 * Reject protocol-level binds here for now.
4401 		 *
4402 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4403 		 * so that the protocol type cannot be SCTP.
4404 		 */
4405 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4406 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4407 			goto bad_addr;
4408 		}
4409 
4410 		/*
4411 		 *
4412 		 * The udp module never sends down a zero-length address,
4413 		 * and allowing this on a labeled system will break MLP
4414 		 * functionality.
4415 		 */
4416 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4417 			goto bad_addr;
4418 
4419 		if (connp->conn_mac_exempt)
4420 			goto bad_addr;
4421 
4422 		/* No hash here really.  The table is big enough. */
4423 		connp->conn_srcv6 = ipv6_all_zeros;
4424 
4425 		ipcl_proto_insert(connp, protocol);
4426 
4427 		tbr->PRIM_type = T_BIND_ACK;
4428 		return (mp);
4429 	}
4430 
4431 	/* Extract the address pointer from the message. */
4432 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4433 	    tbr->ADDR_length);
4434 	if (ucp == NULL) {
4435 		ip1dbg(("ip_bind: no address\n"));
4436 		goto bad_addr;
4437 	}
4438 	if (!OK_32PTR(ucp)) {
4439 		ip1dbg(("ip_bind: unaligned address\n"));
4440 		goto bad_addr;
4441 	}
4442 	/*
4443 	 * Check for trailing mps.
4444 	 */
4445 
4446 	mp1 = mp->b_cont;
4447 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4448 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4449 
4450 	switch (tbr->ADDR_length) {
4451 	default:
4452 		ip1dbg(("ip_bind: bad address length %d\n",
4453 		    (int)tbr->ADDR_length));
4454 		goto bad_addr;
4455 
4456 	case IP_ADDR_LEN:
4457 		/* Verification of local address only */
4458 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4459 		    ire_requested, ipsec_policy_set, B_FALSE);
4460 		break;
4461 
4462 	case sizeof (sin_t):
4463 		sin = (sin_t *)ucp;
4464 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4465 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4466 		if (protocol == IPPROTO_TCP)
4467 			connp->conn_recv = tcp_conn_request;
4468 		break;
4469 
4470 	case sizeof (ipa_conn_t):
4471 		ac = (ipa_conn_t *)ucp;
4472 		/* For raw socket, the local port is not set. */
4473 		if (ac->ac_lport == 0)
4474 			ac->ac_lport = connp->conn_lport;
4475 		/* Always verify destination reachability. */
4476 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4477 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4478 		    ipsec_policy_set, B_TRUE, B_TRUE);
4479 		if (protocol == IPPROTO_TCP)
4480 			connp->conn_recv = tcp_input;
4481 		break;
4482 
4483 	case sizeof (ipa_conn_x_t):
4484 		acx = (ipa_conn_x_t *)ucp;
4485 		/*
4486 		 * Whether or not to verify destination reachability depends
4487 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4488 		 */
4489 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4490 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4491 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4492 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4493 		if (protocol == IPPROTO_TCP)
4494 			connp->conn_recv = tcp_input;
4495 		break;
4496 	}
4497 	if (error == EINPROGRESS)
4498 		return (NULL);
4499 	else if (error != 0)
4500 		goto bad_addr;
4501 	/*
4502 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4503 	 * We can't do this in ip_bind_insert_ire because the policy
4504 	 * may not have been inherited at that point in time and hence
4505 	 * conn_out_enforce_policy may not be set.
4506 	 */
4507 	mp1 = mp->b_cont;
4508 	if (ire_requested && connp->conn_out_enforce_policy &&
4509 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4510 		ire_t *ire = (ire_t *)mp1->b_rptr;
4511 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4512 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4513 	}
4514 
4515 	/* Send it home. */
4516 	mp->b_datap->db_type = M_PCPROTO;
4517 	tbr->PRIM_type = T_BIND_ACK;
4518 	return (mp);
4519 
4520 bad_addr:
4521 	/*
4522 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4523 	 * a unix errno.
4524 	 */
4525 	if (error > 0)
4526 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4527 	else
4528 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4529 	return (mp);
4530 }
4531 
4532 /*
4533  * Here address is verified to be a valid local address.
4534  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4535  * address is also considered a valid local address.
4536  * In the case of a broadcast/multicast address, however, the
4537  * upper protocol is expected to reset the src address
4538  * to 0 if it sees a IRE_BROADCAST type returned so that
4539  * no packets are emitted with broadcast/multicast address as
4540  * source address (that violates hosts requirements RFC1122)
4541  * The addresses valid for bind are:
4542  *	(1) - INADDR_ANY (0)
4543  *	(2) - IP address of an UP interface
4544  *	(3) - IP address of a DOWN interface
4545  *	(4) - valid local IP broadcast addresses. In this case
4546  *	the conn will only receive packets destined to
4547  *	the specified broadcast address.
4548  *	(5) - a multicast address. In this case
4549  *	the conn will only receive packets destined to
4550  *	the specified multicast address. Note: the
4551  *	application still has to issue an
4552  *	IP_ADD_MEMBERSHIP socket option.
4553  *
4554  * On error, return -1 for TBADADDR otherwise pass the
4555  * errno with TSYSERR reply.
4556  *
4557  * In all the above cases, the bound address must be valid in the current zone.
4558  * When the address is loopback, multicast or broadcast, there might be many
4559  * matching IREs so bind has to look up based on the zone.
4560  *
4561  * Note: lport is in network byte order.
4562  */
4563 int
4564 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4565     boolean_t ire_requested, boolean_t ipsec_policy_set,
4566     boolean_t fanout_insert)
4567 {
4568 	int		error = 0;
4569 	ire_t		*src_ire;
4570 	mblk_t		*policy_mp;
4571 	ipif_t		*ipif;
4572 	zoneid_t	zoneid;
4573 
4574 	if (ipsec_policy_set) {
4575 		policy_mp = mp->b_cont;
4576 	}
4577 
4578 	/*
4579 	 * If it was previously connected, conn_fully_bound would have
4580 	 * been set.
4581 	 */
4582 	connp->conn_fully_bound = B_FALSE;
4583 
4584 	src_ire = NULL;
4585 	ipif = NULL;
4586 
4587 	zoneid = IPCL_ZONEID(connp);
4588 
4589 	if (src_addr) {
4590 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4591 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4592 		/*
4593 		 * If an address other than 0.0.0.0 is requested,
4594 		 * we verify that it is a valid address for bind
4595 		 * Note: Following code is in if-else-if form for
4596 		 * readability compared to a condition check.
4597 		 */
4598 		/* LINTED - statement has no consequent */
4599 		if (IRE_IS_LOCAL(src_ire)) {
4600 			/*
4601 			 * (2) Bind to address of local UP interface
4602 			 */
4603 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4604 			/*
4605 			 * (4) Bind to broadcast address
4606 			 * Note: permitted only from transports that
4607 			 * request IRE
4608 			 */
4609 			if (!ire_requested)
4610 				error = EADDRNOTAVAIL;
4611 		} else {
4612 			/*
4613 			 * (3) Bind to address of local DOWN interface
4614 			 * (ipif_lookup_addr() looks up all interfaces
4615 			 * but we do not get here for UP interfaces
4616 			 * - case (2) above)
4617 			 * We put the protocol byte back into the mblk
4618 			 * since we may come back via ip_wput_nondata()
4619 			 * later with this mblk if ipif_lookup_addr chooses
4620 			 * to defer processing.
4621 			 */
4622 			*mp->b_wptr++ = (char)connp->conn_ulp;
4623 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4624 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4625 			    &error)) != NULL) {
4626 				ipif_refrele(ipif);
4627 			} else if (error == EINPROGRESS) {
4628 				if (src_ire != NULL)
4629 					ire_refrele(src_ire);
4630 				return (EINPROGRESS);
4631 			} else if (CLASSD(src_addr)) {
4632 				error = 0;
4633 				if (src_ire != NULL)
4634 					ire_refrele(src_ire);
4635 				/*
4636 				 * (5) bind to multicast address.
4637 				 * Fake out the IRE returned to upper
4638 				 * layer to be a broadcast IRE.
4639 				 */
4640 				src_ire = ire_ctable_lookup(
4641 				    INADDR_BROADCAST, INADDR_ANY,
4642 				    IRE_BROADCAST, NULL, zoneid, NULL,
4643 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4644 				if (src_ire == NULL || !ire_requested)
4645 					error = EADDRNOTAVAIL;
4646 			} else {
4647 				/*
4648 				 * Not a valid address for bind
4649 				 */
4650 				error = EADDRNOTAVAIL;
4651 			}
4652 			/*
4653 			 * Just to keep it consistent with the processing in
4654 			 * ip_bind_v4()
4655 			 */
4656 			mp->b_wptr--;
4657 		}
4658 		if (error) {
4659 			/* Red Alert!  Attempting to be a bogon! */
4660 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4661 			    ntohl(src_addr)));
4662 			goto bad_addr;
4663 		}
4664 	}
4665 
4666 	/*
4667 	 * Allow setting new policies. For example, disconnects come
4668 	 * down as ipa_t bind. As we would have set conn_policy_cached
4669 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4670 	 * can change after the disconnect.
4671 	 */
4672 	connp->conn_policy_cached = B_FALSE;
4673 
4674 	/*
4675 	 * If not fanout_insert this was just an address verification
4676 	 */
4677 	if (fanout_insert) {
4678 		/*
4679 		 * The addresses have been verified. Time to insert in
4680 		 * the correct fanout list.
4681 		 */
4682 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4683 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4684 		connp->conn_lport = lport;
4685 		connp->conn_fport = 0;
4686 		/*
4687 		 * Do we need to add a check to reject Multicast packets
4688 		 */
4689 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4690 	}
4691 
4692 	if (error == 0) {
4693 		if (ire_requested) {
4694 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4695 				error = -1;
4696 				/* Falls through to bad_addr */
4697 			}
4698 		} else if (ipsec_policy_set) {
4699 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4700 				error = -1;
4701 				/* Falls through to bad_addr */
4702 			}
4703 		}
4704 	}
4705 bad_addr:
4706 	if (error != 0) {
4707 		if (connp->conn_anon_port) {
4708 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4709 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4710 			    B_FALSE);
4711 		}
4712 		connp->conn_mlp_type = mlptSingle;
4713 	}
4714 	if (src_ire != NULL)
4715 		IRE_REFRELE(src_ire);
4716 	if (ipsec_policy_set) {
4717 		ASSERT(policy_mp == mp->b_cont);
4718 		ASSERT(policy_mp != NULL);
4719 		freeb(policy_mp);
4720 		/*
4721 		 * As of now assume that nothing else accompanies
4722 		 * IPSEC_POLICY_SET.
4723 		 */
4724 		mp->b_cont = NULL;
4725 	}
4726 	return (error);
4727 }
4728 
4729 /*
4730  * Verify that both the source and destination addresses
4731  * are valid.  If verify_dst is false, then the destination address may be
4732  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4733  * destination reachability, while tunnels do not.
4734  * Note that we allow connect to broadcast and multicast
4735  * addresses when ire_requested is set. Thus the ULP
4736  * has to check for IRE_BROADCAST and multicast.
4737  *
4738  * Returns zero if ok.
4739  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4740  * (for use with TSYSERR reply).
4741  *
4742  * Note: lport and fport are in network byte order.
4743  */
4744 int
4745 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4746     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4747     boolean_t ire_requested, boolean_t ipsec_policy_set,
4748     boolean_t fanout_insert, boolean_t verify_dst)
4749 {
4750 	ire_t		*src_ire;
4751 	ire_t		*dst_ire;
4752 	int		error = 0;
4753 	int 		protocol;
4754 	mblk_t		*policy_mp;
4755 	ire_t		*sire = NULL;
4756 	ire_t		*md_dst_ire = NULL;
4757 	ill_t		*md_ill = NULL;
4758 	zoneid_t	zoneid;
4759 	ipaddr_t	src_addr = *src_addrp;
4760 
4761 	src_ire = dst_ire = NULL;
4762 	protocol = *mp->b_wptr & 0xFF;
4763 
4764 	/*
4765 	 * If we never got a disconnect before, clear it now.
4766 	 */
4767 	connp->conn_fully_bound = B_FALSE;
4768 
4769 	if (ipsec_policy_set) {
4770 		policy_mp = mp->b_cont;
4771 	}
4772 
4773 	zoneid = IPCL_ZONEID(connp);
4774 
4775 	if (CLASSD(dst_addr)) {
4776 		/* Pick up an IRE_BROADCAST */
4777 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4778 		    NULL, zoneid, MBLK_GETLABEL(mp),
4779 		    (MATCH_IRE_RECURSIVE |
4780 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4781 		    MATCH_IRE_SECATTR));
4782 	} else {
4783 		/*
4784 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4785 		 * and onlink ipif is not found set ENETUNREACH error.
4786 		 */
4787 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4788 			ipif_t *ipif;
4789 
4790 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4791 			    dst_addr : connp->conn_nexthop_v4, zoneid);
4792 			if (ipif == NULL) {
4793 				error = ENETUNREACH;
4794 				goto bad_addr;
4795 			}
4796 			ipif_refrele(ipif);
4797 		}
4798 
4799 		if (connp->conn_nexthop_set) {
4800 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4801 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4802 			    MATCH_IRE_SECATTR);
4803 		} else {
4804 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4805 			    &sire, zoneid, MBLK_GETLABEL(mp),
4806 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4807 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4808 			    MATCH_IRE_SECATTR));
4809 		}
4810 	}
4811 	/*
4812 	 * dst_ire can't be a broadcast when not ire_requested.
4813 	 * We also prevent ire's with src address INADDR_ANY to
4814 	 * be used, which are created temporarily for
4815 	 * sending out packets from endpoints that have
4816 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4817 	 * reachable.  If verify_dst is false, the destination needn't be
4818 	 * reachable.
4819 	 *
4820 	 * If we match on a reject or black hole, then we've got a
4821 	 * local failure.  May as well fail out the connect() attempt,
4822 	 * since it's never going to succeed.
4823 	 */
4824 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4825 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4826 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4827 		/*
4828 		 * If we're verifying destination reachability, we always want
4829 		 * to complain here.
4830 		 *
4831 		 * If we're not verifying destination reachability but the
4832 		 * destination has a route, we still want to fail on the
4833 		 * temporary address and broadcast address tests.
4834 		 */
4835 		if (verify_dst || (dst_ire != NULL)) {
4836 			if (ip_debug > 2) {
4837 				pr_addr_dbg("ip_bind_connected: bad connected "
4838 				    "dst %s\n", AF_INET, &dst_addr);
4839 			}
4840 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4841 				error = ENETUNREACH;
4842 			else
4843 				error = EHOSTUNREACH;
4844 			goto bad_addr;
4845 		}
4846 	}
4847 
4848 	/*
4849 	 * We now know that routing will allow us to reach the destination.
4850 	 * Check whether Trusted Solaris policy allows communication with this
4851 	 * host, and pretend that the destination is unreachable if not.
4852 	 *
4853 	 * This is never a problem for TCP, since that transport is known to
4854 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4855 	 * handling.  If the remote is unreachable, it will be detected at that
4856 	 * point, so there's no reason to check it here.
4857 	 *
4858 	 * Note that for sendto (and other datagram-oriented friends), this
4859 	 * check is done as part of the data path label computation instead.
4860 	 * The check here is just to make non-TCP connect() report the right
4861 	 * error.
4862 	 */
4863 	if (dst_ire != NULL && is_system_labeled() &&
4864 	    !IPCL_IS_TCP(connp) &&
4865 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4866 	    connp->conn_mac_exempt) != 0) {
4867 		error = EHOSTUNREACH;
4868 		if (ip_debug > 2) {
4869 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4870 			    AF_INET, &dst_addr);
4871 		}
4872 		goto bad_addr;
4873 	}
4874 
4875 	/*
4876 	 * If the app does a connect(), it means that it will most likely
4877 	 * send more than 1 packet to the destination.  It makes sense
4878 	 * to clear the temporary flag.
4879 	 */
4880 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4881 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4882 		irb_t *irb = dst_ire->ire_bucket;
4883 
4884 		rw_enter(&irb->irb_lock, RW_WRITER);
4885 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4886 		irb->irb_tmp_ire_cnt--;
4887 		rw_exit(&irb->irb_lock);
4888 	}
4889 
4890 	/*
4891 	 * See if we should notify ULP about MDT; we do this whether or not
4892 	 * ire_requested is TRUE, in order to handle active connects; MDT
4893 	 * eligibility tests for passive connects are handled separately
4894 	 * through tcp_adapt_ire().  We do this before the source address
4895 	 * selection, because dst_ire may change after a call to
4896 	 * ipif_select_source().  This is a best-effort check, as the
4897 	 * packet for this connection may not actually go through
4898 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4899 	 * calling ip_newroute().  This is why we further check on the
4900 	 * IRE during Multidata packet transmission in tcp_multisend().
4901 	 */
4902 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4903 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4904 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4905 	    ILL_MDT_CAPABLE(md_ill)) {
4906 		md_dst_ire = dst_ire;
4907 		IRE_REFHOLD(md_dst_ire);
4908 	}
4909 
4910 	if (dst_ire != NULL &&
4911 	    dst_ire->ire_type == IRE_LOCAL &&
4912 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4913 		/*
4914 		 * If the IRE belongs to a different zone, look for a matching
4915 		 * route in the forwarding table and use the source address from
4916 		 * that route.
4917 		 */
4918 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4919 		    zoneid, 0, NULL,
4920 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4921 		    MATCH_IRE_RJ_BHOLE);
4922 		if (src_ire == NULL) {
4923 			error = EHOSTUNREACH;
4924 			goto bad_addr;
4925 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4926 			if (!(src_ire->ire_type & IRE_HOST))
4927 				error = ENETUNREACH;
4928 			else
4929 				error = EHOSTUNREACH;
4930 			goto bad_addr;
4931 		}
4932 		if (src_addr == INADDR_ANY)
4933 			src_addr = src_ire->ire_src_addr;
4934 		ire_refrele(src_ire);
4935 		src_ire = NULL;
4936 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4937 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4938 			src_addr = sire->ire_src_addr;
4939 			ire_refrele(dst_ire);
4940 			dst_ire = sire;
4941 			sire = NULL;
4942 		} else {
4943 			/*
4944 			 * Pick a source address so that a proper inbound
4945 			 * load spreading would happen.
4946 			 */
4947 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4948 			ipif_t *src_ipif = NULL;
4949 			ire_t *ipif_ire;
4950 
4951 			/*
4952 			 * Supply a local source address such that inbound
4953 			 * load spreading happens.
4954 			 *
4955 			 * Determine the best source address on this ill for
4956 			 * the destination.
4957 			 *
4958 			 * 1) For broadcast, we should return a broadcast ire
4959 			 *    found above so that upper layers know that the
4960 			 *    destination address is a broadcast address.
4961 			 *
4962 			 * 2) If this is part of a group, select a better
4963 			 *    source address so that better inbound load
4964 			 *    balancing happens. Do the same if the ipif
4965 			 *    is DEPRECATED.
4966 			 *
4967 			 * 3) If the outgoing interface is part of a usesrc
4968 			 *    group, then try selecting a source address from
4969 			 *    the usesrc ILL.
4970 			 */
4971 			if ((dst_ire->ire_zoneid != zoneid &&
4972 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4973 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4974 			    ((dst_ill->ill_group != NULL) ||
4975 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4976 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4977 				/*
4978 				 * If the destination is reachable via a
4979 				 * given gateway, the selected source address
4980 				 * should be in the same subnet as the gateway.
4981 				 * Otherwise, the destination is not reachable.
4982 				 *
4983 				 * If there are no interfaces on the same subnet
4984 				 * as the destination, ipif_select_source gives
4985 				 * first non-deprecated interface which might be
4986 				 * on a different subnet than the gateway.
4987 				 * This is not desirable. Hence pass the dst_ire
4988 				 * source address to ipif_select_source.
4989 				 * It is sure that the destination is reachable
4990 				 * with the dst_ire source address subnet.
4991 				 * So passing dst_ire source address to
4992 				 * ipif_select_source will make sure that the
4993 				 * selected source will be on the same subnet
4994 				 * as dst_ire source address.
4995 				 */
4996 				ipaddr_t saddr =
4997 				    dst_ire->ire_ipif->ipif_src_addr;
4998 				src_ipif = ipif_select_source(dst_ill,
4999 				    saddr, zoneid);
5000 				if (src_ipif != NULL) {
5001 					if (IS_VNI(src_ipif->ipif_ill)) {
5002 						/*
5003 						 * For VNI there is no
5004 						 * interface route
5005 						 */
5006 						src_addr =
5007 						    src_ipif->ipif_src_addr;
5008 					} else {
5009 						ipif_ire =
5010 						    ipif_to_ire(src_ipif);
5011 						if (ipif_ire != NULL) {
5012 							IRE_REFRELE(dst_ire);
5013 							dst_ire = ipif_ire;
5014 						}
5015 						src_addr =
5016 						    dst_ire->ire_src_addr;
5017 					}
5018 					ipif_refrele(src_ipif);
5019 				} else {
5020 					src_addr = dst_ire->ire_src_addr;
5021 				}
5022 			} else {
5023 				src_addr = dst_ire->ire_src_addr;
5024 			}
5025 		}
5026 	}
5027 
5028 	/*
5029 	 * We do ire_route_lookup() here (and not
5030 	 * interface lookup as we assert that
5031 	 * src_addr should only come from an
5032 	 * UP interface for hard binding.
5033 	 */
5034 	ASSERT(src_ire == NULL);
5035 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5036 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
5037 	/* src_ire must be a local|loopback */
5038 	if (!IRE_IS_LOCAL(src_ire)) {
5039 		if (ip_debug > 2) {
5040 			pr_addr_dbg("ip_bind_connected: bad connected "
5041 			    "src %s\n", AF_INET, &src_addr);
5042 		}
5043 		error = EADDRNOTAVAIL;
5044 		goto bad_addr;
5045 	}
5046 
5047 	/*
5048 	 * If the source address is a loopback address, the
5049 	 * destination had best be local or multicast.
5050 	 * The transports that can't handle multicast will reject
5051 	 * those addresses.
5052 	 */
5053 	if (src_ire->ire_type == IRE_LOOPBACK &&
5054 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5055 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5056 		error = -1;
5057 		goto bad_addr;
5058 	}
5059 
5060 	/*
5061 	 * Allow setting new policies. For example, disconnects come
5062 	 * down as ipa_t bind. As we would have set conn_policy_cached
5063 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5064 	 * can change after the disconnect.
5065 	 */
5066 	connp->conn_policy_cached = B_FALSE;
5067 
5068 	/*
5069 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5070 	 * can handle their passed-in conn's.
5071 	 */
5072 
5073 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5074 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5075 	connp->conn_lport = lport;
5076 	connp->conn_fport = fport;
5077 	*src_addrp = src_addr;
5078 
5079 	ASSERT(!(ipsec_policy_set && ire_requested));
5080 	if (ire_requested) {
5081 		iulp_t *ulp_info = NULL;
5082 
5083 		/*
5084 		 * Note that sire will not be NULL if this is an off-link
5085 		 * connection and there is not cache for that dest yet.
5086 		 *
5087 		 * XXX Because of an existing bug, if there are multiple
5088 		 * default routes, the IRE returned now may not be the actual
5089 		 * default route used (default routes are chosen in a
5090 		 * round robin fashion).  So if the metrics for different
5091 		 * default routes are different, we may return the wrong
5092 		 * metrics.  This will not be a problem if the existing
5093 		 * bug is fixed.
5094 		 */
5095 		if (sire != NULL) {
5096 			ulp_info = &(sire->ire_uinfo);
5097 		}
5098 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5099 			error = -1;
5100 			goto bad_addr;
5101 		}
5102 	} else if (ipsec_policy_set) {
5103 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5104 			error = -1;
5105 			goto bad_addr;
5106 		}
5107 	}
5108 
5109 	/*
5110 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5111 	 * we'll cache that.  If we don't, we'll inherit global policy.
5112 	 *
5113 	 * We can't insert until the conn reflects the policy. Note that
5114 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5115 	 * connections where we don't have a policy. This is to prevent
5116 	 * global policy lookups in the inbound path.
5117 	 *
5118 	 * If we insert before we set conn_policy_cached,
5119 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5120 	 * because global policy cound be non-empty. We normally call
5121 	 * ipsec_check_policy() for conn_policy_cached connections only if
5122 	 * ipc_in_enforce_policy is set. But in this case,
5123 	 * conn_policy_cached can get set anytime since we made the
5124 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5125 	 * called, which will make the above assumption false.  Thus, we
5126 	 * need to insert after we set conn_policy_cached.
5127 	 */
5128 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5129 		goto bad_addr;
5130 
5131 	if (fanout_insert) {
5132 		/*
5133 		 * The addresses have been verified. Time to insert in
5134 		 * the correct fanout list.
5135 		 */
5136 		error = ipcl_conn_insert(connp, protocol, src_addr,
5137 		    dst_addr, connp->conn_ports);
5138 	}
5139 
5140 	if (error == 0) {
5141 		connp->conn_fully_bound = B_TRUE;
5142 		/*
5143 		 * Our initial checks for MDT have passed; the IRE is not
5144 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5145 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
5146 		 * ip_mdinfo_return(), which performs further checks
5147 		 * against them and upon success, returns the MDT info
5148 		 * mblk which we will attach to the bind acknowledgment.
5149 		 */
5150 		if (md_dst_ire != NULL) {
5151 			mblk_t *mdinfo_mp;
5152 
5153 			ASSERT(md_ill != NULL);
5154 			ASSERT(md_ill->ill_mdt_capab != NULL);
5155 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5156 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
5157 				linkb(mp, mdinfo_mp);
5158 		}
5159 	}
5160 bad_addr:
5161 	if (ipsec_policy_set) {
5162 		ASSERT(policy_mp == mp->b_cont);
5163 		ASSERT(policy_mp != NULL);
5164 		freeb(policy_mp);
5165 		/*
5166 		 * As of now assume that nothing else accompanies
5167 		 * IPSEC_POLICY_SET.
5168 		 */
5169 		mp->b_cont = NULL;
5170 	}
5171 	if (src_ire != NULL)
5172 		IRE_REFRELE(src_ire);
5173 	if (dst_ire != NULL)
5174 		IRE_REFRELE(dst_ire);
5175 	if (sire != NULL)
5176 		IRE_REFRELE(sire);
5177 	if (md_dst_ire != NULL)
5178 		IRE_REFRELE(md_dst_ire);
5179 	return (error);
5180 }
5181 
5182 /*
5183  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5184  * Prefers dst_ire over src_ire.
5185  */
5186 static boolean_t
5187 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5188 {
5189 	mblk_t	*mp1;
5190 	ire_t *ret_ire = NULL;
5191 
5192 	mp1 = mp->b_cont;
5193 	ASSERT(mp1 != NULL);
5194 
5195 	if (ire != NULL) {
5196 		/*
5197 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5198 		 * appended mblk. Its <upper protocol>'s
5199 		 * job to make sure there is room.
5200 		 */
5201 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5202 			return (0);
5203 
5204 		mp1->b_datap->db_type = IRE_DB_TYPE;
5205 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5206 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5207 		ret_ire = (ire_t *)mp1->b_rptr;
5208 		/*
5209 		 * Pass the latest setting of the ip_path_mtu_discovery and
5210 		 * copy the ulp info if any.
5211 		 */
5212 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5213 		    IPH_DF : 0;
5214 		if (ulp_info != NULL) {
5215 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5216 			    sizeof (iulp_t));
5217 		}
5218 		ret_ire->ire_mp = mp1;
5219 	} else {
5220 		/*
5221 		 * No IRE was found. Remove IRE mblk.
5222 		 */
5223 		mp->b_cont = mp1->b_cont;
5224 		freeb(mp1);
5225 	}
5226 
5227 	return (1);
5228 }
5229 
5230 /*
5231  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5232  * the final piece where we don't.  Return a pointer to the first mblk in the
5233  * result, and update the pointer to the next mblk to chew on.  If anything
5234  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5235  * NULL pointer.
5236  */
5237 mblk_t *
5238 ip_carve_mp(mblk_t **mpp, ssize_t len)
5239 {
5240 	mblk_t	*mp0;
5241 	mblk_t	*mp1;
5242 	mblk_t	*mp2;
5243 
5244 	if (!len || !mpp || !(mp0 = *mpp))
5245 		return (NULL);
5246 	/* If we aren't going to consume the first mblk, we need a dup. */
5247 	if (mp0->b_wptr - mp0->b_rptr > len) {
5248 		mp1 = dupb(mp0);
5249 		if (mp1) {
5250 			/* Partition the data between the two mblks. */
5251 			mp1->b_wptr = mp1->b_rptr + len;
5252 			mp0->b_rptr = mp1->b_wptr;
5253 			/*
5254 			 * after adjustments if mblk not consumed is now
5255 			 * unaligned, try to align it. If this fails free
5256 			 * all messages and let upper layer recover.
5257 			 */
5258 			if (!OK_32PTR(mp0->b_rptr)) {
5259 				if (!pullupmsg(mp0, -1)) {
5260 					freemsg(mp0);
5261 					freemsg(mp1);
5262 					*mpp = NULL;
5263 					return (NULL);
5264 				}
5265 			}
5266 		}
5267 		return (mp1);
5268 	}
5269 	/* Eat through as many mblks as we need to get len bytes. */
5270 	len -= mp0->b_wptr - mp0->b_rptr;
5271 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5272 		if (mp2->b_wptr - mp2->b_rptr > len) {
5273 			/*
5274 			 * We won't consume the entire last mblk.  Like
5275 			 * above, dup and partition it.
5276 			 */
5277 			mp1->b_cont = dupb(mp2);
5278 			mp1 = mp1->b_cont;
5279 			if (!mp1) {
5280 				/*
5281 				 * Trouble.  Rather than go to a lot of
5282 				 * trouble to clean up, we free the messages.
5283 				 * This won't be any worse than losing it on
5284 				 * the wire.
5285 				 */
5286 				freemsg(mp0);
5287 				freemsg(mp2);
5288 				*mpp = NULL;
5289 				return (NULL);
5290 			}
5291 			mp1->b_wptr = mp1->b_rptr + len;
5292 			mp2->b_rptr = mp1->b_wptr;
5293 			/*
5294 			 * after adjustments if mblk not consumed is now
5295 			 * unaligned, try to align it. If this fails free
5296 			 * all messages and let upper layer recover.
5297 			 */
5298 			if (!OK_32PTR(mp2->b_rptr)) {
5299 				if (!pullupmsg(mp2, -1)) {
5300 					freemsg(mp0);
5301 					freemsg(mp2);
5302 					*mpp = NULL;
5303 					return (NULL);
5304 				}
5305 			}
5306 			*mpp = mp2;
5307 			return (mp0);
5308 		}
5309 		/* Decrement len by the amount we just got. */
5310 		len -= mp2->b_wptr - mp2->b_rptr;
5311 	}
5312 	/*
5313 	 * len should be reduced to zero now.  If not our caller has
5314 	 * screwed up.
5315 	 */
5316 	if (len) {
5317 		/* Shouldn't happen! */
5318 		freemsg(mp0);
5319 		*mpp = NULL;
5320 		return (NULL);
5321 	}
5322 	/*
5323 	 * We consumed up to exactly the end of an mblk.  Detach the part
5324 	 * we are returning from the rest of the chain.
5325 	 */
5326 	mp1->b_cont = NULL;
5327 	*mpp = mp2;
5328 	return (mp0);
5329 }
5330 
5331 /* The ill stream is being unplumbed. Called from ip_close */
5332 int
5333 ip_modclose(ill_t *ill)
5334 {
5335 
5336 	boolean_t success;
5337 	ipsq_t	*ipsq;
5338 	ipif_t	*ipif;
5339 	queue_t	*q = ill->ill_rq;
5340 
5341 	/*
5342 	 * Forcibly enter the ipsq after some delay. This is to take
5343 	 * care of the case when some ioctl does not complete because
5344 	 * we sent a control message to the driver and it did not
5345 	 * send us a reply. We want to be able to at least unplumb
5346 	 * and replumb rather than force the user to reboot the system.
5347 	 */
5348 	success = ipsq_enter(ill, B_FALSE);
5349 
5350 	/*
5351 	 * Open/close/push/pop is guaranteed to be single threaded
5352 	 * per stream by STREAMS. FS guarantees that all references
5353 	 * from top are gone before close is called. So there can't
5354 	 * be another close thread that has set CONDEMNED on this ill.
5355 	 * and cause ipsq_enter to return failure.
5356 	 */
5357 	ASSERT(success);
5358 	ipsq = ill->ill_phyint->phyint_ipsq;
5359 
5360 	/*
5361 	 * Mark it condemned. No new reference will be made to this ill.
5362 	 * Lookup functions will return an error. Threads that try to
5363 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5364 	 * that the refcnt will drop down to zero.
5365 	 */
5366 	mutex_enter(&ill->ill_lock);
5367 	ill->ill_state_flags |= ILL_CONDEMNED;
5368 	for (ipif = ill->ill_ipif; ipif != NULL;
5369 	    ipif = ipif->ipif_next) {
5370 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5371 	}
5372 	/*
5373 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5374 	 * returns  error if ILL_CONDEMNED is set
5375 	 */
5376 	cv_broadcast(&ill->ill_cv);
5377 	mutex_exit(&ill->ill_lock);
5378 
5379 	/*
5380 	 * Shut down fragmentation reassembly.
5381 	 * ill_frag_timer won't start a timer again.
5382 	 * Now cancel any existing timer
5383 	 */
5384 	(void) untimeout(ill->ill_frag_timer_id);
5385 	(void) ill_frag_timeout(ill, 0);
5386 
5387 	/*
5388 	 * If MOVE was in progress, clear the
5389 	 * move_in_progress fields also.
5390 	 */
5391 	if (ill->ill_move_in_progress) {
5392 		ILL_CLEAR_MOVE(ill);
5393 	}
5394 
5395 	/*
5396 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5397 	 * this ill. Then wait for the refcnts to drop to zero.
5398 	 * ill_is_quiescent checks whether the ill is really quiescent.
5399 	 * Then make sure that threads that are waiting to enter the
5400 	 * ipsq have seen the error returned by ipsq_enter and have
5401 	 * gone away. Then we call ill_delete_tail which does the
5402 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5403 	 */
5404 	ill_delete(ill);
5405 	mutex_enter(&ill->ill_lock);
5406 	while (!ill_is_quiescent(ill))
5407 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5408 	while (ill->ill_waiters)
5409 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5410 
5411 	mutex_exit(&ill->ill_lock);
5412 
5413 	/* qprocsoff is called in ill_delete_tail */
5414 	ill_delete_tail(ill);
5415 
5416 	/*
5417 	 * Walk through all upper (conn) streams and qenable
5418 	 * those that have queued data.
5419 	 * close synchronization needs this to
5420 	 * be done to ensure that all upper layers blocked
5421 	 * due to flow control to the closing device
5422 	 * get unblocked.
5423 	 */
5424 	ip1dbg(("ip_wsrv: walking\n"));
5425 	conn_walk_drain();
5426 
5427 	mutex_enter(&ip_mi_lock);
5428 	mi_close_unlink(&ip_g_head, (IDP)ill);
5429 	mutex_exit(&ip_mi_lock);
5430 
5431 	/*
5432 	 * credp could be null if the open didn't succeed and ip_modopen
5433 	 * itself calls ip_close.
5434 	 */
5435 	if (ill->ill_credp != NULL)
5436 		crfree(ill->ill_credp);
5437 
5438 	mi_close_free((IDP)ill);
5439 	q->q_ptr = WR(q)->q_ptr = NULL;
5440 
5441 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5442 
5443 	return (0);
5444 }
5445 
5446 /*
5447  * This is called as part of close() for both IP and UDP
5448  * in order to quiesce the conn.
5449  */
5450 void
5451 ip_quiesce_conn(conn_t *connp)
5452 {
5453 	boolean_t	drain_cleanup_reqd = B_FALSE;
5454 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5455 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5456 
5457 	ASSERT(!IPCL_IS_TCP(connp));
5458 
5459 	/*
5460 	 * Mark the conn as closing, and this conn must not be
5461 	 * inserted in future into any list. Eg. conn_drain_insert(),
5462 	 * won't insert this conn into the conn_drain_list.
5463 	 * Similarly ill_pending_mp_add() will not add any mp to
5464 	 * the pending mp list, after this conn has started closing.
5465 	 *
5466 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5467 	 * cannot get set henceforth.
5468 	 */
5469 	mutex_enter(&connp->conn_lock);
5470 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5471 	connp->conn_state_flags |= CONN_CLOSING;
5472 	if (connp->conn_idl != NULL)
5473 		drain_cleanup_reqd = B_TRUE;
5474 	if (connp->conn_oper_pending_ill != NULL)
5475 		conn_ioctl_cleanup_reqd = B_TRUE;
5476 	if (connp->conn_ilg_inuse != 0)
5477 		ilg_cleanup_reqd = B_TRUE;
5478 	mutex_exit(&connp->conn_lock);
5479 
5480 	if (IPCL_IS_UDP(connp))
5481 		udp_quiesce_conn(connp);
5482 
5483 	if (conn_ioctl_cleanup_reqd)
5484 		conn_ioctl_cleanup(connp);
5485 
5486 	if (is_system_labeled() && connp->conn_anon_port) {
5487 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5488 		    connp->conn_mlp_type, connp->conn_ulp,
5489 		    ntohs(connp->conn_lport), B_FALSE);
5490 		connp->conn_anon_port = 0;
5491 	}
5492 	connp->conn_mlp_type = mlptSingle;
5493 
5494 	/*
5495 	 * Remove this conn from any fanout list it is on.
5496 	 * and then wait for any threads currently operating
5497 	 * on this endpoint to finish
5498 	 */
5499 	ipcl_hash_remove(connp);
5500 
5501 	/*
5502 	 * Remove this conn from the drain list, and do
5503 	 * any other cleanup that may be required.
5504 	 * (Only non-tcp streams may have a non-null conn_idl.
5505 	 * TCP streams are never flow controlled, and
5506 	 * conn_idl will be null)
5507 	 */
5508 	if (drain_cleanup_reqd)
5509 		conn_drain_tail(connp, B_TRUE);
5510 
5511 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5512 		(void) ip_mrouter_done(NULL);
5513 
5514 	if (ilg_cleanup_reqd)
5515 		ilg_delete_all(connp);
5516 
5517 	conn_delete_ire(connp, NULL);
5518 
5519 	/*
5520 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5521 	 * callers from write side can't be there now because close
5522 	 * is in progress. The only other caller is ipcl_walk
5523 	 * which checks for the condemned flag.
5524 	 */
5525 	mutex_enter(&connp->conn_lock);
5526 	connp->conn_state_flags |= CONN_CONDEMNED;
5527 	while (connp->conn_ref != 1)
5528 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5529 	connp->conn_state_flags |= CONN_QUIESCED;
5530 	mutex_exit(&connp->conn_lock);
5531 }
5532 
5533 /* ARGSUSED */
5534 int
5535 ip_close(queue_t *q, int flags)
5536 {
5537 	conn_t		*connp;
5538 
5539 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5540 
5541 	/*
5542 	 * Call the appropriate delete routine depending on whether this is
5543 	 * a module or device.
5544 	 */
5545 	if (WR(q)->q_next != NULL) {
5546 		/* This is a module close */
5547 		return (ip_modclose((ill_t *)q->q_ptr));
5548 	}
5549 
5550 	connp = q->q_ptr;
5551 	ip_quiesce_conn(connp);
5552 
5553 	qprocsoff(q);
5554 
5555 	/*
5556 	 * Now we are truly single threaded on this stream, and can
5557 	 * delete the things hanging off the connp, and finally the connp.
5558 	 * We removed this connp from the fanout list, it cannot be
5559 	 * accessed thru the fanouts, and we already waited for the
5560 	 * conn_ref to drop to 0. We are already in close, so
5561 	 * there cannot be any other thread from the top. qprocsoff
5562 	 * has completed, and service has completed or won't run in
5563 	 * future.
5564 	 */
5565 	ASSERT(connp->conn_ref == 1);
5566 
5567 	/*
5568 	 * A conn which was previously marked as IPCL_UDP cannot
5569 	 * retain the flag because it would have been cleared by
5570 	 * udp_close().
5571 	 */
5572 	ASSERT(!IPCL_IS_UDP(connp));
5573 
5574 	if (connp->conn_latch != NULL) {
5575 		IPLATCH_REFRELE(connp->conn_latch);
5576 		connp->conn_latch = NULL;
5577 	}
5578 	if (connp->conn_policy != NULL) {
5579 		IPPH_REFRELE(connp->conn_policy);
5580 		connp->conn_policy = NULL;
5581 	}
5582 	if (connp->conn_ipsec_opt_mp != NULL) {
5583 		freemsg(connp->conn_ipsec_opt_mp);
5584 		connp->conn_ipsec_opt_mp = NULL;
5585 	}
5586 
5587 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5588 
5589 	connp->conn_ref--;
5590 	ipcl_conn_destroy(connp);
5591 
5592 	q->q_ptr = WR(q)->q_ptr = NULL;
5593 	return (0);
5594 }
5595 
5596 int
5597 ip_snmpmod_close(queue_t *q)
5598 {
5599 	conn_t *connp = Q_TO_CONN(q);
5600 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5601 
5602 	qprocsoff(q);
5603 
5604 	if (connp->conn_flags & IPCL_UDPMOD)
5605 		udp_close_free(connp);
5606 
5607 	if (connp->conn_cred != NULL) {
5608 		crfree(connp->conn_cred);
5609 		connp->conn_cred = NULL;
5610 	}
5611 	CONN_DEC_REF(connp);
5612 	q->q_ptr = WR(q)->q_ptr = NULL;
5613 	return (0);
5614 }
5615 
5616 /*
5617  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5618  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5619  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5620  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5621  * queues as we never enqueue messages there and we don't handle any ioctls.
5622  * Everything else is freed.
5623  */
5624 void
5625 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5626 {
5627 	conn_t	*connp = q->q_ptr;
5628 	pfi_t	setfn;
5629 	pfi_t	getfn;
5630 
5631 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5632 
5633 	switch (DB_TYPE(mp)) {
5634 	case M_PROTO:
5635 	case M_PCPROTO:
5636 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5637 		    ((((union T_primitives *)mp->b_rptr)->type ==
5638 			T_SVR4_OPTMGMT_REQ) ||
5639 		    (((union T_primitives *)mp->b_rptr)->type ==
5640 			T_OPTMGMT_REQ))) {
5641 			/*
5642 			 * This is the only TPI primitive supported. Its
5643 			 * handling does not require tcp_t, but it does require
5644 			 * conn_t to check permissions.
5645 			 */
5646 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5647 
5648 			if (connp->conn_flags & IPCL_TCPMOD) {
5649 				setfn = tcp_snmp_set;
5650 				getfn = tcp_snmp_get;
5651 			} else {
5652 				setfn = udp_snmp_set;
5653 				getfn = udp_snmp_get;
5654 			}
5655 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5656 				freemsg(mp);
5657 				return;
5658 			}
5659 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5660 		    != NULL)
5661 			qreply(q, mp);
5662 		break;
5663 	case M_FLUSH:
5664 	case M_IOCTL:
5665 		putnext(q, mp);
5666 		break;
5667 	default:
5668 		freemsg(mp);
5669 		break;
5670 	}
5671 }
5672 
5673 /* Return the IP checksum for the IP header at "iph". */
5674 uint16_t
5675 ip_csum_hdr(ipha_t *ipha)
5676 {
5677 	uint16_t	*uph;
5678 	uint32_t	sum;
5679 	int		opt_len;
5680 
5681 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5682 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5683 	uph = (uint16_t *)ipha;
5684 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5685 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5686 	if (opt_len > 0) {
5687 		do {
5688 			sum += uph[10];
5689 			sum += uph[11];
5690 			uph += 2;
5691 		} while (--opt_len);
5692 	}
5693 	sum = (sum & 0xFFFF) + (sum >> 16);
5694 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5695 	if (sum == 0xffff)
5696 		sum = 0;
5697 	return ((uint16_t)sum);
5698 }
5699 
5700 void
5701 ip_ddi_destroy(void)
5702 {
5703 	tnet_fini();
5704 	tcp_ddi_destroy();
5705 	sctp_ddi_destroy();
5706 	ipsec_loader_destroy();
5707 	ipsec_policy_destroy();
5708 	ipsec_kstat_destroy();
5709 	nd_free(&ip_g_nd);
5710 	mutex_destroy(&igmp_timer_lock);
5711 	mutex_destroy(&mld_timer_lock);
5712 	mutex_destroy(&igmp_slowtimeout_lock);
5713 	mutex_destroy(&mld_slowtimeout_lock);
5714 	mutex_destroy(&ip_mi_lock);
5715 	mutex_destroy(&rts_clients.connf_lock);
5716 	ip_ire_fini();
5717 	ip6_asp_free();
5718 	conn_drain_fini();
5719 	ipcl_destroy();
5720 	inet_minor_destroy(ip_minor_arena);
5721 	icmp_kstat_fini();
5722 	ip_kstat_fini();
5723 	rw_destroy(&ipsec_capab_ills_lock);
5724 	rw_destroy(&ill_g_usesrc_lock);
5725 	ip_drop_unregister(&ip_dropper);
5726 }
5727 
5728 
5729 void
5730 ip_ddi_init(void)
5731 {
5732 	TCP6_MAJ = ddi_name_to_major(TCP6);
5733 	TCP_MAJ	= ddi_name_to_major(TCP);
5734 	SCTP_MAJ = ddi_name_to_major(SCTP);
5735 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5736 
5737 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5738 
5739 	/* IP's IPsec code calls the packet dropper */
5740 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5741 
5742 	if (!ip_g_nd) {
5743 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5744 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5745 			nd_free(&ip_g_nd);
5746 		}
5747 	}
5748 
5749 	ipsec_loader_init();
5750 	ipsec_policy_init();
5751 	ipsec_kstat_init();
5752 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5753 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5754 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5755 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5756 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5757 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5758 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5759 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5760 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5761 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5762 
5763 	/*
5764 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5765 	 * initial devices: ip, ip6, tcp, tcp6.
5766 	 */
5767 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5768 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5769 		cmn_err(CE_PANIC,
5770 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5771 	}
5772 
5773 	ipcl_init();
5774 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5775 	ip_ire_init();
5776 	ip6_asp_init();
5777 	ipif_init();
5778 	conn_drain_init();
5779 	tcp_ddi_init();
5780 	sctp_ddi_init();
5781 
5782 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5783 
5784 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5785 		"net", KSTAT_TYPE_NAMED,
5786 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5787 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5788 		ip_kstat->ks_data = &ip_statistics;
5789 		kstat_install(ip_kstat);
5790 	}
5791 	ip_kstat_init();
5792 	ip6_kstat_init();
5793 	icmp_kstat_init();
5794 	ipsec_loader_start();
5795 	tnet_init();
5796 }
5797 
5798 /*
5799  * Allocate and initialize a DLPI template of the specified length.  (May be
5800  * called as writer.)
5801  */
5802 mblk_t *
5803 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5804 {
5805 	mblk_t	*mp;
5806 
5807 	mp = allocb(len, BPRI_MED);
5808 	if (!mp)
5809 		return (NULL);
5810 
5811 	/*
5812 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5813 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5814 	 * that other DLPI are M_PROTO.
5815 	 */
5816 	if (prim == DL_INFO_REQ) {
5817 		mp->b_datap->db_type = M_PCPROTO;
5818 	} else {
5819 		mp->b_datap->db_type = M_PROTO;
5820 	}
5821 
5822 	mp->b_wptr = mp->b_rptr + len;
5823 	bzero(mp->b_rptr, len);
5824 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5825 	return (mp);
5826 }
5827 
5828 const char *
5829 dlpi_prim_str(int prim)
5830 {
5831 	switch (prim) {
5832 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5833 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5834 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5835 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5836 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5837 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5838 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5839 	case DL_OK_ACK:		return ("DL_OK_ACK");
5840 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5841 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5842 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5843 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5844 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5845 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5846 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5847 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5848 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5849 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5850 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5851 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5852 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5853 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5854 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5855 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5856 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5857 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5858 	default:		return ("<unknown primitive>");
5859 	}
5860 }
5861 
5862 const char *
5863 dlpi_err_str(int err)
5864 {
5865 	switch (err) {
5866 	case DL_ACCESS:		return ("DL_ACCESS");
5867 	case DL_BADADDR:	return ("DL_BADADDR");
5868 	case DL_BADCORR:	return ("DL_BADCORR");
5869 	case DL_BADDATA:	return ("DL_BADDATA");
5870 	case DL_BADPPA:		return ("DL_BADPPA");
5871 	case DL_BADPRIM:	return ("DL_BADPRIM");
5872 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5873 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5874 	case DL_BADSAP:		return ("DL_BADSAP");
5875 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5876 	case DL_BOUND:		return ("DL_BOUND");
5877 	case DL_INITFAILED:	return ("DL_INITFAILED");
5878 	case DL_NOADDR:		return ("DL_NOADDR");
5879 	case DL_NOTINIT:	return ("DL_NOTINIT");
5880 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5881 	case DL_SYSERR:		return ("DL_SYSERR");
5882 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5883 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5884 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5885 	case DL_TOOMANY:	return ("DL_TOOMANY");
5886 	case DL_NOTENAB:	return ("DL_NOTENAB");
5887 	case DL_BUSY:		return ("DL_BUSY");
5888 	case DL_NOAUTO:		return ("DL_NOAUTO");
5889 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5890 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5891 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5892 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5893 	case DL_PENDING:	return ("DL_PENDING");
5894 	default:		return ("<unknown error>");
5895 	}
5896 }
5897 
5898 /*
5899  * Debug formatting routine.  Returns a character string representation of the
5900  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5901  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5902  *
5903  * Once the ndd table-printing interfaces are removed, this can be changed to
5904  * standard dotted-decimal form.
5905  */
5906 char *
5907 ip_dot_addr(ipaddr_t addr, char *buf)
5908 {
5909 	uint8_t *ap = (uint8_t *)&addr;
5910 
5911 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5912 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
5913 	return (buf);
5914 }
5915 
5916 /*
5917  * Write the given MAC address as a printable string in the usual colon-
5918  * separated format.
5919  */
5920 const char *
5921 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
5922 {
5923 	char *bp;
5924 
5925 	if (alen == 0 || buflen < 4)
5926 		return ("?");
5927 	bp = buf;
5928 	for (;;) {
5929 		/*
5930 		 * If there are more MAC address bytes available, but we won't
5931 		 * have any room to print them, then add "..." to the string
5932 		 * instead.  See below for the 'magic number' explanation.
5933 		 */
5934 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
5935 			(void) strcpy(bp, "...");
5936 			break;
5937 		}
5938 		(void) sprintf(bp, "%02x", *addr++);
5939 		bp += 2;
5940 		if (--alen == 0)
5941 			break;
5942 		*bp++ = ':';
5943 		buflen -= 3;
5944 		/*
5945 		 * At this point, based on the first 'if' statement above,
5946 		 * either alen == 1 and buflen >= 3, or alen > 1 and
5947 		 * buflen >= 4.  The first case leaves room for the final "xx"
5948 		 * number and trailing NUL byte.  The second leaves room for at
5949 		 * least "...".  Thus the apparently 'magic' numbers chosen for
5950 		 * that statement.
5951 		 */
5952 	}
5953 	return (buf);
5954 }
5955 
5956 /*
5957  * Send an ICMP error after patching up the packet appropriately.  Returns
5958  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5959  */
5960 static boolean_t
5961 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5962     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5963 {
5964 	ipha_t *ipha;
5965 	mblk_t *first_mp;
5966 	boolean_t secure;
5967 	unsigned char db_type;
5968 
5969 	first_mp = mp;
5970 	if (mctl_present) {
5971 		mp = mp->b_cont;
5972 		secure = ipsec_in_is_secure(first_mp);
5973 		ASSERT(mp != NULL);
5974 	} else {
5975 		/*
5976 		 * If this is an ICMP error being reported - which goes
5977 		 * up as M_CTLs, we need to convert them to M_DATA till
5978 		 * we finish checking with global policy because
5979 		 * ipsec_check_global_policy() assumes M_DATA as clear
5980 		 * and M_CTL as secure.
5981 		 */
5982 		db_type = DB_TYPE(mp);
5983 		DB_TYPE(mp) = M_DATA;
5984 		secure = B_FALSE;
5985 	}
5986 	/*
5987 	 * We are generating an icmp error for some inbound packet.
5988 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
5989 	 * Before we generate an error, check with global policy
5990 	 * to see whether this is allowed to enter the system. As
5991 	 * there is no "conn", we are checking with global policy.
5992 	 */
5993 	ipha = (ipha_t *)mp->b_rptr;
5994 	if (secure || ipsec_inbound_v4_policy_present) {
5995 		first_mp = ipsec_check_global_policy(first_mp, NULL,
5996 		    ipha, NULL, mctl_present);
5997 		if (first_mp == NULL)
5998 			return (B_FALSE);
5999 	}
6000 
6001 	if (!mctl_present)
6002 		DB_TYPE(mp) = db_type;
6003 
6004 	if (flags & IP_FF_SEND_ICMP) {
6005 		if (flags & IP_FF_HDR_COMPLETE) {
6006 			if (ip_hdr_complete(ipha, zoneid)) {
6007 				freemsg(first_mp);
6008 				return (B_TRUE);
6009 			}
6010 		}
6011 		if (flags & IP_FF_CKSUM) {
6012 			/*
6013 			 * Have to correct checksum since
6014 			 * the packet might have been
6015 			 * fragmented and the reassembly code in ip_rput
6016 			 * does not restore the IP checksum.
6017 			 */
6018 			ipha->ipha_hdr_checksum = 0;
6019 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6020 		}
6021 		switch (icmp_type) {
6022 		case ICMP_DEST_UNREACHABLE:
6023 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid);
6024 			break;
6025 		default:
6026 			freemsg(first_mp);
6027 			break;
6028 		}
6029 	} else {
6030 		freemsg(first_mp);
6031 		return (B_FALSE);
6032 	}
6033 
6034 	return (B_TRUE);
6035 }
6036 
6037 /*
6038  * Used to send an ICMP error message when a packet is received for
6039  * a protocol that is not supported. The mblk passed as argument
6040  * is consumed by this function.
6041  */
6042 void
6043 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
6044 {
6045 	mblk_t *mp;
6046 	ipha_t *ipha;
6047 	ill_t *ill;
6048 	ipsec_in_t *ii;
6049 
6050 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6051 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6052 
6053 	mp = ipsec_mp->b_cont;
6054 	ipsec_mp->b_cont = NULL;
6055 	ipha = (ipha_t *)mp->b_rptr;
6056 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6057 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
6058 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6059 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
6060 		}
6061 	} else {
6062 		/* Get ill from index in ipsec_in_t. */
6063 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6064 		    B_TRUE, NULL, NULL, NULL, NULL);
6065 		if (ill != NULL) {
6066 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6067 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6068 			    0, B_FALSE, zoneid)) {
6069 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
6070 			}
6071 
6072 			ill_refrele(ill);
6073 		} else { /* re-link for the freemsg() below. */
6074 			ipsec_mp->b_cont = mp;
6075 		}
6076 	}
6077 
6078 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6079 	freemsg(ipsec_mp);
6080 }
6081 
6082 /*
6083  * See if the inbound datagram has had IPsec processing applied to it.
6084  */
6085 boolean_t
6086 ipsec_in_is_secure(mblk_t *ipsec_mp)
6087 {
6088 	ipsec_in_t *ii;
6089 
6090 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6091 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6092 
6093 	if (ii->ipsec_in_loopback) {
6094 		return (ii->ipsec_in_secure);
6095 	} else {
6096 		return (ii->ipsec_in_ah_sa != NULL ||
6097 		    ii->ipsec_in_esp_sa != NULL ||
6098 		    ii->ipsec_in_decaps);
6099 	}
6100 }
6101 
6102 /*
6103  * Handle protocols with which IP is less intimate.  There
6104  * can be more than one stream bound to a particular
6105  * protocol.  When this is the case, normally each one gets a copy
6106  * of any incoming packets.
6107  *
6108  * IPSEC NOTE :
6109  *
6110  * Don't allow a secure packet going up a non-secure connection.
6111  * We don't allow this because
6112  *
6113  * 1) Reply might go out in clear which will be dropped at
6114  *    the sending side.
6115  * 2) If the reply goes out in clear it will give the
6116  *    adversary enough information for getting the key in
6117  *    most of the cases.
6118  *
6119  * Moreover getting a secure packet when we expect clear
6120  * implies that SA's were added without checking for
6121  * policy on both ends. This should not happen once ISAKMP
6122  * is used to negotiate SAs as SAs will be added only after
6123  * verifying the policy.
6124  *
6125  * NOTE : If the packet was tunneled and not multicast we only send
6126  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6127  * back to delivering packets to AF_INET6 raw sockets.
6128  *
6129  * IPQoS Notes:
6130  * Once we have determined the client, invoke IPPF processing.
6131  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6132  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6133  * ip_policy will be false.
6134  *
6135  * Zones notes:
6136  * Currently only applications in the global zone can create raw sockets for
6137  * protocols other than ICMP. So unlike the broadcast / multicast case of
6138  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6139  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6140  */
6141 static void
6142 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6143     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6144     zoneid_t zoneid)
6145 {
6146 	queue_t	*rq;
6147 	mblk_t	*mp1, *first_mp1;
6148 	uint_t	protocol = ipha->ipha_protocol;
6149 	ipaddr_t dst;
6150 	boolean_t one_only;
6151 	mblk_t *first_mp = mp;
6152 	boolean_t secure;
6153 	uint32_t ill_index;
6154 	conn_t	*connp, *first_connp, *next_connp;
6155 	connf_t	*connfp;
6156 	boolean_t shared_addr;
6157 
6158 	if (mctl_present) {
6159 		mp = first_mp->b_cont;
6160 		secure = ipsec_in_is_secure(first_mp);
6161 		ASSERT(mp != NULL);
6162 	} else {
6163 		secure = B_FALSE;
6164 	}
6165 	dst = ipha->ipha_dst;
6166 	/*
6167 	 * If the packet was tunneled and not multicast we only send to it
6168 	 * the first match.
6169 	 */
6170 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6171 	    !CLASSD(dst));
6172 
6173 	shared_addr = (zoneid == ALL_ZONES);
6174 	if (shared_addr) {
6175 		/*
6176 		 * We don't allow multilevel ports for raw IP, so no need to
6177 		 * check for that here.
6178 		 */
6179 		zoneid = tsol_packet_to_zoneid(mp);
6180 	}
6181 
6182 	connfp = &ipcl_proto_fanout[protocol];
6183 	mutex_enter(&connfp->connf_lock);
6184 	connp = connfp->connf_head;
6185 	for (connp = connfp->connf_head; connp != NULL;
6186 		connp = connp->conn_next) {
6187 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6188 		    zoneid) &&
6189 		    (!is_system_labeled() ||
6190 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6191 		    connp)))
6192 			break;
6193 	}
6194 
6195 	if (connp == NULL || connp->conn_upq == NULL) {
6196 		/*
6197 		 * No one bound to these addresses.  Is
6198 		 * there a client that wants all
6199 		 * unclaimed datagrams?
6200 		 */
6201 		mutex_exit(&connfp->connf_lock);
6202 		/*
6203 		 * Check for IPPROTO_ENCAP...
6204 		 */
6205 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6206 			/*
6207 			 * XXX If an IPsec mblk is here on a multicast
6208 			 * tunnel (using ip_mroute stuff), what should
6209 			 * I do?
6210 			 *
6211 			 * For now, just free the IPsec mblk before
6212 			 * passing it up to the multicast routing
6213 			 * stuff.
6214 			 *
6215 			 * BTW,  If I match a configured IP-in-IP
6216 			 * tunnel, ip_mroute_decap will never be
6217 			 * called.
6218 			 */
6219 			if (mp != first_mp)
6220 				freeb(first_mp);
6221 			ip_mroute_decap(q, mp);
6222 		} else {
6223 			/*
6224 			 * Otherwise send an ICMP protocol unreachable.
6225 			 */
6226 			if (ip_fanout_send_icmp(q, first_mp, flags,
6227 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6228 			    mctl_present, zoneid)) {
6229 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
6230 			}
6231 		}
6232 		return;
6233 	}
6234 	CONN_INC_REF(connp);
6235 	first_connp = connp;
6236 
6237 	/*
6238 	 * Only send message to one tunnel driver by immediately
6239 	 * terminating the loop.
6240 	 */
6241 	connp = one_only ? NULL : connp->conn_next;
6242 
6243 	for (;;) {
6244 		while (connp != NULL) {
6245 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6246 			    flags, zoneid) &&
6247 			    (!is_system_labeled() ||
6248 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6249 			    shared_addr, connp)))
6250 				break;
6251 			connp = connp->conn_next;
6252 		}
6253 
6254 		/*
6255 		 * Copy the packet.
6256 		 */
6257 		if (connp == NULL || connp->conn_upq == NULL ||
6258 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6259 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6260 			/*
6261 			 * No more interested clients or memory
6262 			 * allocation failed
6263 			 */
6264 			connp = first_connp;
6265 			break;
6266 		}
6267 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6268 		CONN_INC_REF(connp);
6269 		mutex_exit(&connfp->connf_lock);
6270 		rq = connp->conn_rq;
6271 		if (!canputnext(rq)) {
6272 			if (flags & IP_FF_RAWIP) {
6273 				BUMP_MIB(&ip_mib, rawipInOverflows);
6274 			} else {
6275 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6276 			}
6277 
6278 			freemsg(first_mp1);
6279 		} else {
6280 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6281 				first_mp1 = ipsec_check_inbound_policy
6282 				    (first_mp1, connp, ipha, NULL,
6283 				    mctl_present);
6284 			}
6285 			if (first_mp1 != NULL) {
6286 				/*
6287 				 * ip_fanout_proto also gets called from
6288 				 * icmp_inbound_error_fanout, in which case
6289 				 * the msg type is M_CTL.  Don't add info
6290 				 * in this case for the time being. In future
6291 				 * when there is a need for knowing the
6292 				 * inbound iface index for ICMP error msgs,
6293 				 * then this can be changed.
6294 				 */
6295 				if ((connp->conn_recvif != 0) &&
6296 				    (mp->b_datap->db_type != M_CTL)) {
6297 					/*
6298 					 * the actual data will be
6299 					 * contained in b_cont upon
6300 					 * successful return of the
6301 					 * following call else
6302 					 * original mblk is returned
6303 					 */
6304 					ASSERT(recv_ill != NULL);
6305 					mp1 = ip_add_info(mp1, recv_ill,
6306 						IPF_RECVIF);
6307 				}
6308 				BUMP_MIB(&ip_mib, ipInDelivers);
6309 				if (mctl_present)
6310 					freeb(first_mp1);
6311 				putnext(rq, mp1);
6312 			}
6313 		}
6314 		mutex_enter(&connfp->connf_lock);
6315 		/* Follow the next pointer before releasing the conn. */
6316 		next_connp = connp->conn_next;
6317 		CONN_DEC_REF(connp);
6318 		connp = next_connp;
6319 	}
6320 
6321 	/* Last one.  Send it upstream. */
6322 	mutex_exit(&connfp->connf_lock);
6323 
6324 	/*
6325 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6326 	 * will be set to false.
6327 	 */
6328 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6329 		ill_index = ill->ill_phyint->phyint_ifindex;
6330 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6331 		if (mp == NULL) {
6332 			CONN_DEC_REF(connp);
6333 			if (mctl_present) {
6334 				freeb(first_mp);
6335 			}
6336 			return;
6337 		}
6338 	}
6339 
6340 	rq = connp->conn_rq;
6341 	if (!canputnext(rq)) {
6342 		if (flags & IP_FF_RAWIP) {
6343 			BUMP_MIB(&ip_mib, rawipInOverflows);
6344 		} else {
6345 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6346 		}
6347 
6348 		freemsg(first_mp);
6349 	} else {
6350 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6351 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6352 			    ipha, NULL, mctl_present);
6353 		}
6354 		if (first_mp != NULL) {
6355 			/*
6356 			 * ip_fanout_proto also gets called
6357 			 * from icmp_inbound_error_fanout, in
6358 			 * which case the msg type is M_CTL.
6359 			 * Don't add info in this case for time
6360 			 * being. In future when there is a
6361 			 * need for knowing the inbound iface
6362 			 * index for ICMP error msgs, then this
6363 			 * can be changed
6364 			 */
6365 			if ((connp->conn_recvif != 0) &&
6366 			    (mp->b_datap->db_type != M_CTL)) {
6367 				/*
6368 				 * the actual data will be contained in
6369 				 * b_cont upon successful return
6370 				 * of the following call else original
6371 				 * mblk is returned
6372 				 */
6373 				ASSERT(recv_ill != NULL);
6374 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6375 			}
6376 			BUMP_MIB(&ip_mib, ipInDelivers);
6377 			putnext(rq, mp);
6378 			if (mctl_present)
6379 				freeb(first_mp);
6380 		}
6381 	}
6382 	CONN_DEC_REF(connp);
6383 }
6384 
6385 /*
6386  * Fanout for TCP packets
6387  * The caller puts <fport, lport> in the ports parameter.
6388  *
6389  * IPQoS Notes
6390  * Before sending it to the client, invoke IPPF processing.
6391  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6392  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6393  * ip_policy is false.
6394  */
6395 static void
6396 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6397     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6398 {
6399 	mblk_t  *first_mp;
6400 	boolean_t secure;
6401 	uint32_t ill_index;
6402 	int	ip_hdr_len;
6403 	tcph_t	*tcph;
6404 	boolean_t syn_present = B_FALSE;
6405 	conn_t	*connp;
6406 
6407 	first_mp = mp;
6408 	if (mctl_present) {
6409 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6410 		mp = first_mp->b_cont;
6411 		secure = ipsec_in_is_secure(first_mp);
6412 		ASSERT(mp != NULL);
6413 	} else {
6414 		secure = B_FALSE;
6415 	}
6416 
6417 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6418 
6419 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6420 	    NULL) {
6421 		/*
6422 		 * No connected connection or listener. Send a
6423 		 * TH_RST via tcp_xmit_listeners_reset.
6424 		 */
6425 
6426 		/* Initiate IPPf processing, if needed. */
6427 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6428 			uint32_t ill_index;
6429 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6430 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6431 			if (first_mp == NULL)
6432 				return;
6433 		}
6434 		BUMP_MIB(&ip_mib, ipInDelivers);
6435 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6436 		    zoneid));
6437 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6438 		return;
6439 	}
6440 
6441 	/*
6442 	 * Allocate the SYN for the TCP connection here itself
6443 	 */
6444 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6445 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6446 		if (IPCL_IS_TCP(connp)) {
6447 			squeue_t *sqp;
6448 
6449 			/*
6450 			 * For fused tcp loopback, assign the eager's
6451 			 * squeue to be that of the active connect's.
6452 			 * Note that we don't check for IP_FF_LOOPBACK
6453 			 * here since this routine gets called only
6454 			 * for loopback (unlike the IPv6 counterpart).
6455 			 */
6456 			ASSERT(Q_TO_CONN(q) != NULL);
6457 			if (do_tcp_fusion &&
6458 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6459 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6460 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6461 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6462 				sqp = Q_TO_CONN(q)->conn_sqp;
6463 			} else {
6464 				sqp = IP_SQUEUE_GET(lbolt);
6465 			}
6466 
6467 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6468 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6469 			syn_present = B_TRUE;
6470 		}
6471 	}
6472 
6473 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6474 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6475 		if ((flags & TH_RST) || (flags & TH_URG)) {
6476 			CONN_DEC_REF(connp);
6477 			freemsg(first_mp);
6478 			return;
6479 		}
6480 		if (flags & TH_ACK) {
6481 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6482 			CONN_DEC_REF(connp);
6483 			return;
6484 		}
6485 
6486 		CONN_DEC_REF(connp);
6487 		freemsg(first_mp);
6488 		return;
6489 	}
6490 
6491 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6492 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6493 		    NULL, mctl_present);
6494 		if (first_mp == NULL) {
6495 			CONN_DEC_REF(connp);
6496 			return;
6497 		}
6498 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6499 			ASSERT(syn_present);
6500 			if (mctl_present) {
6501 				ASSERT(first_mp != mp);
6502 				first_mp->b_datap->db_struioflag |=
6503 				    STRUIO_POLICY;
6504 			} else {
6505 				ASSERT(first_mp == mp);
6506 				mp->b_datap->db_struioflag &=
6507 				    ~STRUIO_EAGER;
6508 				mp->b_datap->db_struioflag |=
6509 				    STRUIO_POLICY;
6510 			}
6511 		} else {
6512 			/*
6513 			 * Discard first_mp early since we're dealing with a
6514 			 * fully-connected conn_t and tcp doesn't do policy in
6515 			 * this case.
6516 			 */
6517 			if (mctl_present) {
6518 				freeb(first_mp);
6519 				mctl_present = B_FALSE;
6520 			}
6521 			first_mp = mp;
6522 		}
6523 	}
6524 
6525 	/*
6526 	 * Initiate policy processing here if needed. If we get here from
6527 	 * icmp_inbound_error_fanout, ip_policy is false.
6528 	 */
6529 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6530 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6531 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6532 		if (mp == NULL) {
6533 			CONN_DEC_REF(connp);
6534 			if (mctl_present)
6535 				freeb(first_mp);
6536 			return;
6537 		} else if (mctl_present) {
6538 			ASSERT(first_mp != mp);
6539 			first_mp->b_cont = mp;
6540 		} else {
6541 			first_mp = mp;
6542 		}
6543 	}
6544 
6545 
6546 
6547 	/* Handle IPv6 socket options. */
6548 	if (!syn_present &&
6549 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6550 		/* Add header */
6551 		ASSERT(recv_ill != NULL);
6552 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6553 		if (mp == NULL) {
6554 			CONN_DEC_REF(connp);
6555 			if (mctl_present)
6556 				freeb(first_mp);
6557 			return;
6558 		} else if (mctl_present) {
6559 			/*
6560 			 * ip_add_info might return a new mp.
6561 			 */
6562 			ASSERT(first_mp != mp);
6563 			first_mp->b_cont = mp;
6564 		} else {
6565 			first_mp = mp;
6566 		}
6567 	}
6568 
6569 	BUMP_MIB(&ip_mib, ipInDelivers);
6570 	if (IPCL_IS_TCP(connp)) {
6571 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6572 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6573 	} else {
6574 		putnext(connp->conn_rq, first_mp);
6575 		CONN_DEC_REF(connp);
6576 	}
6577 }
6578 
6579 /*
6580  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6581  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6582  * Caller is responsible for dropping references to the conn, and freeing
6583  * first_mp.
6584  *
6585  * IPQoS Notes
6586  * Before sending it to the client, invoke IPPF processing. Policy processing
6587  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6588  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6589  * ip_wput_local, ip_policy is false.
6590  */
6591 static void
6592 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6593     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6594     boolean_t ip_policy)
6595 {
6596 	boolean_t	mctl_present = (first_mp != NULL);
6597 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6598 	uint32_t	ill_index;
6599 
6600 	if (mctl_present)
6601 		first_mp->b_cont = mp;
6602 	else
6603 		first_mp = mp;
6604 
6605 	if (CONN_UDP_FLOWCTLD(connp)) {
6606 		BUMP_MIB(&ip_mib, udpInOverflows);
6607 		freemsg(first_mp);
6608 		return;
6609 	}
6610 
6611 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6612 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6613 		    NULL, mctl_present);
6614 		if (first_mp == NULL)
6615 			return;	/* Freed by ipsec_check_inbound_policy(). */
6616 	}
6617 	if (mctl_present)
6618 		freeb(first_mp);
6619 
6620 	if (connp->conn_recvif)
6621 		in_flags = IPF_RECVIF;
6622 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6623 		in_flags |= IPF_RECVSLLA;
6624 
6625 	/* Handle IPv6 options. */
6626 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6627 		in_flags |= IPF_RECVIF;
6628 
6629 	/*
6630 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6631 	 * freed if the packet is dropped. The caller will do so.
6632 	 */
6633 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6634 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6635 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6636 		if (mp == NULL) {
6637 			return;
6638 		}
6639 	}
6640 	if ((in_flags != 0) &&
6641 	    (mp->b_datap->db_type != M_CTL)) {
6642 		/*
6643 		 * The actual data will be contained in b_cont
6644 		 * upon successful return of the following call
6645 		 * else original mblk is returned
6646 		 */
6647 		ASSERT(recv_ill != NULL);
6648 		mp = ip_add_info(mp, recv_ill, in_flags);
6649 	}
6650 	BUMP_MIB(&ip_mib, ipInDelivers);
6651 
6652 	/* Send it upstream */
6653 	CONN_UDP_RECV(connp, mp);
6654 }
6655 
6656 /*
6657  * Fanout for UDP packets.
6658  * The caller puts <fport, lport> in the ports parameter.
6659  *
6660  * If SO_REUSEADDR is set all multicast and broadcast packets
6661  * will be delivered to all streams bound to the same port.
6662  *
6663  * Zones notes:
6664  * Multicast and broadcast packets will be distributed to streams in all zones.
6665  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6666  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6667  * packets. To maintain this behavior with multiple zones, the conns are grouped
6668  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6669  * each zone. If unset, all the following conns in the same zone are skipped.
6670  */
6671 static void
6672 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6673     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6674     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6675 {
6676 	uint32_t	dstport, srcport;
6677 	ipaddr_t	dst;
6678 	mblk_t		*first_mp;
6679 	boolean_t	secure;
6680 	in6_addr_t	v6src;
6681 	conn_t		*connp;
6682 	connf_t		*connfp;
6683 	conn_t		*first_connp;
6684 	conn_t		*next_connp;
6685 	mblk_t		*mp1, *first_mp1;
6686 	ipaddr_t	src;
6687 	zoneid_t	last_zoneid;
6688 	boolean_t	reuseaddr;
6689 	boolean_t	shared_addr;
6690 
6691 	first_mp = mp;
6692 	if (mctl_present) {
6693 		mp = first_mp->b_cont;
6694 		first_mp->b_cont = NULL;
6695 		secure = ipsec_in_is_secure(first_mp);
6696 		ASSERT(mp != NULL);
6697 	} else {
6698 		first_mp = NULL;
6699 		secure = B_FALSE;
6700 	}
6701 
6702 	/* Extract ports in net byte order */
6703 	dstport = htons(ntohl(ports) & 0xFFFF);
6704 	srcport = htons(ntohl(ports) >> 16);
6705 	dst = ipha->ipha_dst;
6706 	src = ipha->ipha_src;
6707 
6708 	shared_addr = (zoneid == ALL_ZONES);
6709 	if (shared_addr) {
6710 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6711 		if (zoneid == ALL_ZONES)
6712 			zoneid = tsol_packet_to_zoneid(mp);
6713 	}
6714 
6715 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6716 	mutex_enter(&connfp->connf_lock);
6717 	connp = connfp->connf_head;
6718 	if (!broadcast && !CLASSD(dst)) {
6719 		/*
6720 		 * Not broadcast or multicast. Send to the one (first)
6721 		 * client we find. No need to check conn_wantpacket()
6722 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6723 		 * IPv4 unicast packets.
6724 		 */
6725 		while ((connp != NULL) &&
6726 		    (!IPCL_UDP_MATCH(connp, dstport, dst,
6727 		    srcport, src) ||
6728 		    (connp->conn_zoneid != zoneid && !connp->conn_allzones))) {
6729 			connp = connp->conn_next;
6730 		}
6731 
6732 		if (connp == NULL || connp->conn_upq == NULL)
6733 			goto notfound;
6734 
6735 		if (is_system_labeled() &&
6736 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6737 		    connp))
6738 			goto notfound;
6739 
6740 		CONN_INC_REF(connp);
6741 		mutex_exit(&connfp->connf_lock);
6742 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6743 		    recv_ill, ip_policy);
6744 		IP_STAT(ip_udp_fannorm);
6745 		CONN_DEC_REF(connp);
6746 		return;
6747 	}
6748 
6749 	/*
6750 	 * Broadcast and multicast case
6751 	 *
6752 	 * Need to check conn_wantpacket().
6753 	 * If SO_REUSEADDR has been set on the first we send the
6754 	 * packet to all clients that have joined the group and
6755 	 * match the port.
6756 	 */
6757 
6758 	while (connp != NULL) {
6759 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6760 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6761 		    (!is_system_labeled() ||
6762 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6763 		    connp)))
6764 			break;
6765 		connp = connp->conn_next;
6766 	}
6767 
6768 	if (connp == NULL || connp->conn_upq == NULL)
6769 		goto notfound;
6770 
6771 	first_connp = connp;
6772 	/*
6773 	 * When SO_REUSEADDR is not set, send the packet only to the first
6774 	 * matching connection in its zone by keeping track of the zoneid.
6775 	 */
6776 	reuseaddr = first_connp->conn_reuseaddr;
6777 	last_zoneid = first_connp->conn_zoneid;
6778 
6779 	CONN_INC_REF(connp);
6780 	connp = connp->conn_next;
6781 	for (;;) {
6782 		while (connp != NULL) {
6783 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6784 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6785 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6786 			    (!is_system_labeled() ||
6787 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6788 			    shared_addr, connp)))
6789 				break;
6790 			connp = connp->conn_next;
6791 		}
6792 		/*
6793 		 * Just copy the data part alone. The mctl part is
6794 		 * needed just for verifying policy and it is never
6795 		 * sent up.
6796 		 */
6797 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6798 		    ((mp1 = copymsg(mp)) == NULL))) {
6799 			/*
6800 			 * No more interested clients or memory
6801 			 * allocation failed
6802 			 */
6803 			connp = first_connp;
6804 			break;
6805 		}
6806 		if (connp->conn_zoneid != last_zoneid) {
6807 			/*
6808 			 * Update the zoneid so that the packet isn't sent to
6809 			 * any more conns in the same zone unless SO_REUSEADDR
6810 			 * is set.
6811 			 */
6812 			reuseaddr = connp->conn_reuseaddr;
6813 			last_zoneid = connp->conn_zoneid;
6814 		}
6815 		if (first_mp != NULL) {
6816 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6817 			    ipsec_info_type == IPSEC_IN);
6818 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6819 			if (first_mp1 == NULL) {
6820 				freemsg(mp1);
6821 				connp = first_connp;
6822 				break;
6823 			}
6824 		} else {
6825 			first_mp1 = NULL;
6826 		}
6827 		CONN_INC_REF(connp);
6828 		mutex_exit(&connfp->connf_lock);
6829 		/*
6830 		 * IPQoS notes: We don't send the packet for policy
6831 		 * processing here, will do it for the last one (below).
6832 		 * i.e. we do it per-packet now, but if we do policy
6833 		 * processing per-conn, then we would need to do it
6834 		 * here too.
6835 		 */
6836 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6837 		    ipha, flags, recv_ill, B_FALSE);
6838 		mutex_enter(&connfp->connf_lock);
6839 		/* Follow the next pointer before releasing the conn. */
6840 		next_connp = connp->conn_next;
6841 		IP_STAT(ip_udp_fanmb);
6842 		CONN_DEC_REF(connp);
6843 		connp = next_connp;
6844 	}
6845 
6846 	/* Last one.  Send it upstream. */
6847 	mutex_exit(&connfp->connf_lock);
6848 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6849 	    ip_policy);
6850 	IP_STAT(ip_udp_fanmb);
6851 	CONN_DEC_REF(connp);
6852 	return;
6853 
6854 notfound:
6855 
6856 	mutex_exit(&connfp->connf_lock);
6857 	IP_STAT(ip_udp_fanothers);
6858 	/*
6859 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6860 	 * have already been matched above, since they live in the IPv4
6861 	 * fanout tables. This implies we only need to
6862 	 * check for IPv6 in6addr_any endpoints here.
6863 	 * Thus we compare using ipv6_all_zeros instead of the destination
6864 	 * address, except for the multicast group membership lookup which
6865 	 * uses the IPv4 destination.
6866 	 */
6867 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6868 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6869 	mutex_enter(&connfp->connf_lock);
6870 	connp = connfp->connf_head;
6871 	if (!broadcast && !CLASSD(dst)) {
6872 		while (connp != NULL) {
6873 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6874 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6875 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6876 			    !connp->conn_ipv6_v6only)
6877 				break;
6878 			connp = connp->conn_next;
6879 		}
6880 
6881 		if (connp != NULL && is_system_labeled() &&
6882 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6883 		    connp))
6884 			connp = NULL;
6885 
6886 		if (connp == NULL || connp->conn_upq == NULL) {
6887 			/*
6888 			 * No one bound to this port.  Is
6889 			 * there a client that wants all
6890 			 * unclaimed datagrams?
6891 			 */
6892 			mutex_exit(&connfp->connf_lock);
6893 
6894 			if (mctl_present)
6895 				first_mp->b_cont = mp;
6896 			else
6897 				first_mp = mp;
6898 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6899 				ip_fanout_proto(q, first_mp, ill, ipha,
6900 				    flags | IP_FF_RAWIP, mctl_present,
6901 				    ip_policy, recv_ill, zoneid);
6902 			} else {
6903 				if (ip_fanout_send_icmp(q, first_mp, flags,
6904 				    ICMP_DEST_UNREACHABLE,
6905 				    ICMP_PORT_UNREACHABLE,
6906 				    mctl_present, zoneid)) {
6907 					BUMP_MIB(&ip_mib, udpNoPorts);
6908 				}
6909 			}
6910 			return;
6911 		}
6912 
6913 		CONN_INC_REF(connp);
6914 		mutex_exit(&connfp->connf_lock);
6915 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6916 		    recv_ill, ip_policy);
6917 		CONN_DEC_REF(connp);
6918 		return;
6919 	}
6920 	/*
6921 	 * IPv4 multicast packet being delivered to an AF_INET6
6922 	 * in6addr_any endpoint.
6923 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6924 	 * and not conn_wantpacket_v6() since any multicast membership is
6925 	 * for an IPv4-mapped multicast address.
6926 	 * The packet is sent to all clients in all zones that have joined the
6927 	 * group and match the port.
6928 	 */
6929 	while (connp != NULL) {
6930 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6931 		    srcport, v6src) &&
6932 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6933 		    (!is_system_labeled() ||
6934 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6935 		    connp)))
6936 			break;
6937 		connp = connp->conn_next;
6938 	}
6939 
6940 	if (connp == NULL || connp->conn_upq == NULL) {
6941 		/*
6942 		 * No one bound to this port.  Is
6943 		 * there a client that wants all
6944 		 * unclaimed datagrams?
6945 		 */
6946 		mutex_exit(&connfp->connf_lock);
6947 
6948 		if (mctl_present)
6949 			first_mp->b_cont = mp;
6950 		else
6951 			first_mp = mp;
6952 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6953 			ip_fanout_proto(q, first_mp, ill, ipha,
6954 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6955 			    recv_ill, zoneid);
6956 		} else {
6957 			/*
6958 			 * We used to attempt to send an icmp error here, but
6959 			 * since this is known to be a multicast packet
6960 			 * and we don't send icmp errors in response to
6961 			 * multicast, just drop the packet and give up sooner.
6962 			 */
6963 			BUMP_MIB(&ip_mib, udpNoPorts);
6964 			freemsg(first_mp);
6965 		}
6966 		return;
6967 	}
6968 
6969 	first_connp = connp;
6970 
6971 	CONN_INC_REF(connp);
6972 	connp = connp->conn_next;
6973 	for (;;) {
6974 		while (connp != NULL) {
6975 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6976 			    ipv6_all_zeros, srcport, v6src) &&
6977 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6978 			    (!is_system_labeled() ||
6979 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6980 			    shared_addr, connp)))
6981 				break;
6982 			connp = connp->conn_next;
6983 		}
6984 		/*
6985 		 * Just copy the data part alone. The mctl part is
6986 		 * needed just for verifying policy and it is never
6987 		 * sent up.
6988 		 */
6989 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6990 		    ((mp1 = copymsg(mp)) == NULL))) {
6991 			/*
6992 			 * No more intested clients or memory
6993 			 * allocation failed
6994 			 */
6995 			connp = first_connp;
6996 			break;
6997 		}
6998 		if (first_mp != NULL) {
6999 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7000 			    ipsec_info_type == IPSEC_IN);
7001 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7002 			if (first_mp1 == NULL) {
7003 				freemsg(mp1);
7004 				connp = first_connp;
7005 				break;
7006 			}
7007 		} else {
7008 			first_mp1 = NULL;
7009 		}
7010 		CONN_INC_REF(connp);
7011 		mutex_exit(&connfp->connf_lock);
7012 		/*
7013 		 * IPQoS notes: We don't send the packet for policy
7014 		 * processing here, will do it for the last one (below).
7015 		 * i.e. we do it per-packet now, but if we do policy
7016 		 * processing per-conn, then we would need to do it
7017 		 * here too.
7018 		 */
7019 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
7020 		    ipha, flags, recv_ill, B_FALSE);
7021 		mutex_enter(&connfp->connf_lock);
7022 		/* Follow the next pointer before releasing the conn. */
7023 		next_connp = connp->conn_next;
7024 		CONN_DEC_REF(connp);
7025 		connp = next_connp;
7026 	}
7027 
7028 	/* Last one.  Send it upstream. */
7029 	mutex_exit(&connfp->connf_lock);
7030 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
7031 	    ip_policy);
7032 	CONN_DEC_REF(connp);
7033 }
7034 
7035 /*
7036  * Complete the ip_wput header so that it
7037  * is possible to generate ICMP
7038  * errors.
7039  */
7040 int
7041 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
7042 {
7043 	ire_t *ire;
7044 
7045 	if (ipha->ipha_src == INADDR_ANY) {
7046 		ire = ire_lookup_local(zoneid);
7047 		if (ire == NULL) {
7048 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7049 			return (1);
7050 		}
7051 		ipha->ipha_src = ire->ire_addr;
7052 		ire_refrele(ire);
7053 	}
7054 	ipha->ipha_ttl = ip_def_ttl;
7055 	ipha->ipha_hdr_checksum = 0;
7056 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7057 	return (0);
7058 }
7059 
7060 /*
7061  * Nobody should be sending
7062  * packets up this stream
7063  */
7064 static void
7065 ip_lrput(queue_t *q, mblk_t *mp)
7066 {
7067 	mblk_t *mp1;
7068 
7069 	switch (mp->b_datap->db_type) {
7070 	case M_FLUSH:
7071 		/* Turn around */
7072 		if (*mp->b_rptr & FLUSHW) {
7073 			*mp->b_rptr &= ~FLUSHR;
7074 			qreply(q, mp);
7075 			return;
7076 		}
7077 		break;
7078 	}
7079 	/* Could receive messages that passed through ar_rput */
7080 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7081 		mp1->b_prev = mp1->b_next = NULL;
7082 	freemsg(mp);
7083 }
7084 
7085 /* Nobody should be sending packets down this stream */
7086 /* ARGSUSED */
7087 void
7088 ip_lwput(queue_t *q, mblk_t *mp)
7089 {
7090 	freemsg(mp);
7091 }
7092 
7093 /*
7094  * Move the first hop in any source route to ipha_dst and remove that part of
7095  * the source route.  Called by other protocols.  Errors in option formatting
7096  * are ignored - will be handled by ip_wput_options Return the final
7097  * destination (either ipha_dst or the last entry in a source route.)
7098  */
7099 ipaddr_t
7100 ip_massage_options(ipha_t *ipha)
7101 {
7102 	ipoptp_t	opts;
7103 	uchar_t		*opt;
7104 	uint8_t		optval;
7105 	uint8_t		optlen;
7106 	ipaddr_t	dst;
7107 	int		i;
7108 	ire_t		*ire;
7109 
7110 	ip2dbg(("ip_massage_options\n"));
7111 	dst = ipha->ipha_dst;
7112 	for (optval = ipoptp_first(&opts, ipha);
7113 	    optval != IPOPT_EOL;
7114 	    optval = ipoptp_next(&opts)) {
7115 		opt = opts.ipoptp_cur;
7116 		switch (optval) {
7117 			uint8_t off;
7118 		case IPOPT_SSRR:
7119 		case IPOPT_LSRR:
7120 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7121 				ip1dbg(("ip_massage_options: bad src route\n"));
7122 				break;
7123 			}
7124 			optlen = opts.ipoptp_len;
7125 			off = opt[IPOPT_OFFSET];
7126 			off--;
7127 		redo_srr:
7128 			if (optlen < IP_ADDR_LEN ||
7129 			    off > optlen - IP_ADDR_LEN) {
7130 				/* End of source route */
7131 				ip1dbg(("ip_massage_options: end of SR\n"));
7132 				break;
7133 			}
7134 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7135 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7136 			    ntohl(dst)));
7137 			/*
7138 			 * Check if our address is present more than
7139 			 * once as consecutive hops in source route.
7140 			 * XXX verify per-interface ip_forwarding
7141 			 * for source route?
7142 			 */
7143 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7144 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
7145 			if (ire != NULL) {
7146 				ire_refrele(ire);
7147 				off += IP_ADDR_LEN;
7148 				goto redo_srr;
7149 			}
7150 			if (dst == htonl(INADDR_LOOPBACK)) {
7151 				ip1dbg(("ip_massage_options: loopback addr in "
7152 				    "source route!\n"));
7153 				break;
7154 			}
7155 			/*
7156 			 * Update ipha_dst to be the first hop and remove the
7157 			 * first hop from the source route (by overwriting
7158 			 * part of the option with NOP options).
7159 			 */
7160 			ipha->ipha_dst = dst;
7161 			/* Put the last entry in dst */
7162 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7163 			    3;
7164 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7165 
7166 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7167 			    ntohl(dst)));
7168 			/* Move down and overwrite */
7169 			opt[IP_ADDR_LEN] = opt[0];
7170 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7171 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7172 			for (i = 0; i < IP_ADDR_LEN; i++)
7173 				opt[i] = IPOPT_NOP;
7174 			break;
7175 		}
7176 	}
7177 	return (dst);
7178 }
7179 
7180 /*
7181  * This function's job is to forward data to the reverse tunnel (FA->HA)
7182  * after doing a few checks. It is assumed that the incoming interface
7183  * of the packet is always different than the outgoing interface and the
7184  * ire_type of the found ire has to be a non-resolver type.
7185  *
7186  * IPQoS notes
7187  * IP policy is invoked twice for a forwarded packet, once on the read side
7188  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7189  * enabled.
7190  */
7191 static void
7192 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7193 {
7194 	ipha_t		*ipha;
7195 	queue_t		*q;
7196 	uint32_t 	pkt_len;
7197 #define	rptr    ((uchar_t *)ipha)
7198 	uint32_t 	sum;
7199 	uint32_t 	max_frag;
7200 	mblk_t		*first_mp;
7201 	uint32_t	ill_index;
7202 	ipxmit_state_t	pktxmit_state;
7203 
7204 	ASSERT(ire != NULL);
7205 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7206 	ASSERT(ire->ire_stq != NULL);
7207 
7208 	/* Initiate read side IPPF processing */
7209 	if (IPP_ENABLED(IPP_FWD_IN)) {
7210 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7211 		ip_process(IPP_FWD_IN, &mp, ill_index);
7212 		if (mp == NULL) {
7213 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7214 			    "dropped during IPPF processing\n"));
7215 			return;
7216 		}
7217 	}
7218 
7219 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7220 		ILLF_ROUTER) == 0) ||
7221 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7222 		BUMP_MIB(&ip_mib, ipForwProhibits);
7223 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7224 		    "forwarding is not turned on\n"));
7225 		goto drop_pkt;
7226 	}
7227 
7228 	/*
7229 	 * Don't forward if the interface is down
7230 	 */
7231 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7232 		BUMP_MIB(&ip_mib, ipInDiscards);
7233 		goto drop_pkt;
7234 	}
7235 
7236 	ipha = (ipha_t *)mp->b_rptr;
7237 	pkt_len = ntohs(ipha->ipha_length);
7238 	/* Adjust the checksum to reflect the ttl decrement. */
7239 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7240 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7241 	if (ipha->ipha_ttl-- <= 1) {
7242 		if (ip_csum_hdr(ipha)) {
7243 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7244 			goto drop_pkt;
7245 		}
7246 		q = ire->ire_stq;
7247 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7248 		    BPRI_HI)) == NULL) {
7249 			goto drop_pkt;
7250 		}
7251 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7252 		/* Sent by forwarding path, and router is global zone */
7253 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7254 		    GLOBAL_ZONEID);
7255 		return;
7256 	}
7257 
7258 	/* Get the ill_index of the ILL */
7259 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7260 
7261 	/*
7262 	 * ip_mrtun_forward is only used by foreign agent to reverse
7263 	 * tunnel the incoming packet. So it does not do any option
7264 	 * processing for source routing.
7265 	 */
7266 	max_frag = ire->ire_max_frag;
7267 	if (pkt_len > max_frag) {
7268 		/*
7269 		 * It needs fragging on its way out.  We haven't
7270 		 * verified the header checksum yet.  Since we
7271 		 * are going to put a surely good checksum in the
7272 		 * outgoing header, we have to make sure that it
7273 		 * was good coming in.
7274 		 */
7275 		if (ip_csum_hdr(ipha)) {
7276 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7277 			goto drop_pkt;
7278 		}
7279 
7280 		/* Initiate write side IPPF processing */
7281 		if (IPP_ENABLED(IPP_FWD_OUT)) {
7282 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7283 			if (mp == NULL) {
7284 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7285 				    "dropped/deferred during ip policy "\
7286 				    "processing\n"));
7287 				return;
7288 			}
7289 		}
7290 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7291 		    BPRI_HI)) == NULL) {
7292 			goto drop_pkt;
7293 		}
7294 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7295 		mp = first_mp;
7296 
7297 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
7298 		return;
7299 	}
7300 
7301 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7302 
7303 	ASSERT(ire->ire_ipif != NULL);
7304 
7305 	/* Now send the packet to the tunnel interface */
7306 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7307 	q = ire->ire_stq;
7308 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7309 	if ((pktxmit_state == SEND_FAILED) ||
7310 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7311 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7312 		    q->q_ptr));
7313 	}
7314 
7315 	return;
7316 
7317 drop_pkt:;
7318 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7319 	freemsg(mp);
7320 #undef	rptr
7321 }
7322 
7323 /*
7324  * Fills the ipsec_out_t data structure with appropriate fields and
7325  * prepends it to mp which contains the IP hdr + data that was meant
7326  * to be forwarded. Please note that ipsec_out_info data structure
7327  * is used here to communicate the outgoing ill path at ip_wput()
7328  * for the ICMP error packet. This has nothing to do with ipsec IP
7329  * security. ipsec_out_t is really used to pass the info to the module
7330  * IP where this information cannot be extracted from conn.
7331  * This functions is called by ip_mrtun_forward().
7332  */
7333 void
7334 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7335 {
7336 	ipsec_out_t	*io;
7337 
7338 	ASSERT(xmit_ill != NULL);
7339 	first_mp->b_datap->db_type = M_CTL;
7340 	first_mp->b_wptr += sizeof (ipsec_info_t);
7341 	/*
7342 	 * This is to pass info to ip_wput in absence of conn.
7343 	 * ipsec_out_secure will be B_FALSE because of this.
7344 	 * Thus ipsec_out_secure being B_FALSE indicates that
7345 	 * this is not IPSEC security related information.
7346 	 */
7347 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7348 	io = (ipsec_out_t *)first_mp->b_rptr;
7349 	io->ipsec_out_type = IPSEC_OUT;
7350 	io->ipsec_out_len = sizeof (ipsec_out_t);
7351 	first_mp->b_cont = mp;
7352 	io->ipsec_out_ill_index =
7353 	    xmit_ill->ill_phyint->phyint_ifindex;
7354 	io->ipsec_out_xmit_if = B_TRUE;
7355 }
7356 
7357 /*
7358  * Return the network mask
7359  * associated with the specified address.
7360  */
7361 ipaddr_t
7362 ip_net_mask(ipaddr_t addr)
7363 {
7364 	uchar_t	*up = (uchar_t *)&addr;
7365 	ipaddr_t mask = 0;
7366 	uchar_t	*maskp = (uchar_t *)&mask;
7367 
7368 #if defined(__i386) || defined(__amd64)
7369 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7370 #endif
7371 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7372 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7373 #endif
7374 	if (CLASSD(addr)) {
7375 		maskp[0] = 0xF0;
7376 		return (mask);
7377 	}
7378 	if (addr == 0)
7379 		return (0);
7380 	maskp[0] = 0xFF;
7381 	if ((up[0] & 0x80) == 0)
7382 		return (mask);
7383 
7384 	maskp[1] = 0xFF;
7385 	if ((up[0] & 0xC0) == 0x80)
7386 		return (mask);
7387 
7388 	maskp[2] = 0xFF;
7389 	if ((up[0] & 0xE0) == 0xC0)
7390 		return (mask);
7391 
7392 	/* Must be experimental or multicast, indicate as much */
7393 	return ((ipaddr_t)0);
7394 }
7395 
7396 /*
7397  * Select an ill for the packet by considering load spreading across
7398  * a different ill in the group if dst_ill is part of some group.
7399  */
7400 ill_t *
7401 ip_newroute_get_dst_ill(ill_t *dst_ill)
7402 {
7403 	ill_t *ill;
7404 
7405 	/*
7406 	 * We schedule irrespective of whether the source address is
7407 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7408 	 */
7409 	ill = illgrp_scheduler(dst_ill);
7410 	if (ill == NULL)
7411 		return (NULL);
7412 
7413 	/*
7414 	 * For groups with names ip_sioctl_groupname ensures that all
7415 	 * ills are of same type. For groups without names, ifgrp_insert
7416 	 * ensures this.
7417 	 */
7418 	ASSERT(dst_ill->ill_type == ill->ill_type);
7419 
7420 	return (ill);
7421 }
7422 
7423 /*
7424  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7425  */
7426 ill_t *
7427 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7428 {
7429 	ill_t *ret_ill;
7430 
7431 	ASSERT(ifindex != 0);
7432 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7433 	if (ret_ill == NULL ||
7434 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7435 		if (isv6) {
7436 			if (ill != NULL) {
7437 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7438 			} else {
7439 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7440 			}
7441 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7442 			    "bad ifindex %d.\n", ifindex));
7443 		} else {
7444 			BUMP_MIB(&ip_mib, ipOutDiscards);
7445 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7446 			    "bad ifindex %d.\n", ifindex));
7447 		}
7448 		if (ret_ill != NULL)
7449 			ill_refrele(ret_ill);
7450 		freemsg(first_mp);
7451 		return (NULL);
7452 	}
7453 
7454 	return (ret_ill);
7455 }
7456 
7457 /*
7458  * IPv4 -
7459  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7460  * out a packet to a destination address for which we do not have specific
7461  * (or sufficient) routing information.
7462  *
7463  * NOTE : These are the scopes of some of the variables that point at IRE,
7464  *	  which needs to be followed while making any future modifications
7465  *	  to avoid memory leaks.
7466  *
7467  *	- ire and sire are the entries looked up initially by
7468  *	  ire_ftable_lookup.
7469  *	- ipif_ire is used to hold the interface ire associated with
7470  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7471  *	  it before branching out to error paths.
7472  *	- save_ire is initialized before ire_create, so that ire returned
7473  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7474  *	  before breaking out of the switch.
7475  *
7476  *	Thus on failures, we have to REFRELE only ire and sire, if they
7477  *	are not NULL.
7478  */
7479 void
7480 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7481     zoneid_t zoneid)
7482 {
7483 	areq_t	*areq;
7484 	ipaddr_t gw = 0;
7485 	ire_t	*ire = NULL;
7486 	mblk_t	*res_mp;
7487 	ipaddr_t *addrp;
7488 	ipaddr_t nexthop_addr;
7489 	ipif_t  *src_ipif = NULL;
7490 	ill_t	*dst_ill = NULL;
7491 	ipha_t  *ipha;
7492 	ire_t	*sire = NULL;
7493 	mblk_t	*first_mp;
7494 	ire_t	*save_ire;
7495 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7496 	ushort_t ire_marks = 0;
7497 	boolean_t mctl_present;
7498 	ipsec_out_t *io;
7499 	mblk_t	*saved_mp;
7500 	ire_t	*first_sire = NULL;
7501 	mblk_t	*copy_mp = NULL;
7502 	mblk_t	*xmit_mp = NULL;
7503 	ipaddr_t save_dst;
7504 	uint32_t multirt_flags =
7505 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7506 	boolean_t multirt_is_resolvable;
7507 	boolean_t multirt_resolve_next;
7508 	boolean_t do_attach_ill = B_FALSE;
7509 	boolean_t ip_nexthop = B_FALSE;
7510 	tsol_ire_gw_secattr_t *attrp = NULL;
7511 	tsol_gcgrp_t *gcgrp = NULL;
7512 	tsol_gcgrp_addr_t ga;
7513 
7514 	if (ip_debug > 2) {
7515 		/* ip1dbg */
7516 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7517 	}
7518 
7519 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7520 	if (mctl_present) {
7521 		io = (ipsec_out_t *)first_mp->b_rptr;
7522 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7523 		ASSERT(zoneid == io->ipsec_out_zoneid);
7524 		ASSERT(zoneid != ALL_ZONES);
7525 	}
7526 
7527 	ipha = (ipha_t *)mp->b_rptr;
7528 
7529 	/* All multicast lookups come through ip_newroute_ipif() */
7530 	if (CLASSD(dst)) {
7531 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7532 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7533 		freemsg(first_mp);
7534 		return;
7535 	}
7536 
7537 	if (mctl_present && io->ipsec_out_attach_if) {
7538 		/* ip_grab_attach_ill returns a held ill */
7539 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7540 		    io->ipsec_out_ill_index, B_FALSE);
7541 
7542 		/* Failure case frees things for us. */
7543 		if (attach_ill == NULL)
7544 			return;
7545 
7546 		/*
7547 		 * Check if we need an ire that will not be
7548 		 * looked up by anybody else i.e. HIDDEN.
7549 		 */
7550 		if (ill_is_probeonly(attach_ill))
7551 			ire_marks = IRE_MARK_HIDDEN;
7552 	}
7553 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7554 		ip_nexthop = B_TRUE;
7555 		nexthop_addr = io->ipsec_out_nexthop_addr;
7556 	}
7557 	/*
7558 	 * If this IRE is created for forwarding or it is not for
7559 	 * traffic for congestion controlled protocols, mark it as temporary.
7560 	 */
7561 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7562 		ire_marks |= IRE_MARK_TEMPORARY;
7563 
7564 	/*
7565 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7566 	 * chain until it gets the most specific information available.
7567 	 * For example, we know that there is no IRE_CACHE for this dest,
7568 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7569 	 * ire_ftable_lookup will look up the gateway, etc.
7570 	 * Check if in_ill != NULL. If it is true, the packet must be
7571 	 * from an incoming interface where RTA_SRCIFP is set.
7572 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7573 	 * to the destination, of equal netmask length in the forward table,
7574 	 * will be recursively explored. If no information is available
7575 	 * for the final gateway of that route, we force the returned ire
7576 	 * to be equal to sire using MATCH_IRE_PARENT.
7577 	 * At least, in this case we have a starting point (in the buckets)
7578 	 * to look for other routes to the destination in the forward table.
7579 	 * This is actually used only for multirouting, where a list
7580 	 * of routes has to be processed in sequence.
7581 	 *
7582 	 * In the process of coming up with the most specific information,
7583 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7584 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7585 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7586 	 * Two caveats when handling incomplete ire's in ip_newroute:
7587 	 * - we should be careful when accessing its ire_nce (specifically
7588 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7589 	 * - not all legacy code path callers are prepared to handle
7590 	 *   incomplete ire's, so we should not create/add incomplete
7591 	 *   ire_cache entries here. (See discussion about temporary solution
7592 	 *   further below).
7593 	 *
7594 	 * In order to minimize packet dropping, and to preserve existing
7595 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7596 	 * gateway, and instead use the IF_RESOLVER ire to send out
7597 	 * another request to ARP (this is achieved by passing the
7598 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7599 	 * arp response comes back in ip_wput_nondata, we will create
7600 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7601 	 *
7602 	 * Note that this is a temporary solution; the correct solution is
7603 	 * to create an incomplete  per-dst ire_cache entry, and send the
7604 	 * packet out when the gw's nce is resolved. In order to achieve this,
7605 	 * all packet processing must have been completed prior to calling
7606 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7607 	 * to be modified to accomodate this solution.
7608 	 */
7609 	if (in_ill != NULL) {
7610 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7611 		    in_ill, MATCH_IRE_TYPE);
7612 	} else if (ip_nexthop) {
7613 		/*
7614 		 * The first time we come here, we look for an IRE_INTERFACE
7615 		 * entry for the specified nexthop, set the dst to be the
7616 		 * nexthop address and create an IRE_CACHE entry for the
7617 		 * nexthop. The next time around, we are able to find an
7618 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7619 		 * nexthop address and create an IRE_CACHE entry for the
7620 		 * destination address via the specified nexthop.
7621 		 */
7622 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7623 		    MBLK_GETLABEL(mp));
7624 		if (ire != NULL) {
7625 			gw = nexthop_addr;
7626 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7627 		} else {
7628 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7629 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7630 			    MBLK_GETLABEL(mp),
7631 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7632 			if (ire != NULL) {
7633 				dst = nexthop_addr;
7634 			}
7635 		}
7636 	} else if (attach_ill == NULL) {
7637 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7638 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7639 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7640 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7641 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7642 	} else {
7643 		/*
7644 		 * attach_ill is set only for communicating with
7645 		 * on-link hosts. So, don't look for DEFAULT.
7646 		 */
7647 		ipif_t	*attach_ipif;
7648 
7649 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7650 		if (attach_ipif == NULL) {
7651 			ill_refrele(attach_ill);
7652 			goto icmp_err_ret;
7653 		}
7654 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7655 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7656 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7657 		    MATCH_IRE_SECATTR);
7658 		ipif_refrele(attach_ipif);
7659 	}
7660 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7661 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7662 
7663 	/*
7664 	 * This loop is run only once in most cases.
7665 	 * We loop to resolve further routes only when the destination
7666 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7667 	 */
7668 	do {
7669 		/* Clear the previous iteration's values */
7670 		if (src_ipif != NULL) {
7671 			ipif_refrele(src_ipif);
7672 			src_ipif = NULL;
7673 		}
7674 		if (dst_ill != NULL) {
7675 			ill_refrele(dst_ill);
7676 			dst_ill = NULL;
7677 		}
7678 
7679 		multirt_resolve_next = B_FALSE;
7680 		/*
7681 		 * We check if packets have to be multirouted.
7682 		 * In this case, given the current <ire, sire> couple,
7683 		 * we look for the next suitable <ire, sire>.
7684 		 * This check is done in ire_multirt_lookup(),
7685 		 * which applies various criteria to find the next route
7686 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7687 		 * unchanged if it detects it has not been tried yet.
7688 		 */
7689 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7690 			ip3dbg(("ip_newroute: starting next_resolution "
7691 			    "with first_mp %p, tag %d\n",
7692 			    (void *)first_mp,
7693 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7694 
7695 			ASSERT(sire != NULL);
7696 			multirt_is_resolvable =
7697 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7698 				MBLK_GETLABEL(mp));
7699 
7700 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7701 			    "ire %p, sire %p\n",
7702 			    multirt_is_resolvable,
7703 			    (void *)ire, (void *)sire));
7704 
7705 			if (!multirt_is_resolvable) {
7706 				/*
7707 				 * No more multirt route to resolve; give up
7708 				 * (all routes resolved or no more
7709 				 * resolvable routes).
7710 				 */
7711 				if (ire != NULL) {
7712 					ire_refrele(ire);
7713 					ire = NULL;
7714 				}
7715 			} else {
7716 				ASSERT(sire != NULL);
7717 				ASSERT(ire != NULL);
7718 				/*
7719 				 * We simply use first_sire as a flag that
7720 				 * indicates if a resolvable multirt route
7721 				 * has already been found.
7722 				 * If it is not the case, we may have to send
7723 				 * an ICMP error to report that the
7724 				 * destination is unreachable.
7725 				 * We do not IRE_REFHOLD first_sire.
7726 				 */
7727 				if (first_sire == NULL) {
7728 					first_sire = sire;
7729 				}
7730 			}
7731 		}
7732 		if (ire == NULL) {
7733 			if (ip_debug > 3) {
7734 				/* ip2dbg */
7735 				pr_addr_dbg("ip_newroute: "
7736 				    "can't resolve %s\n", AF_INET, &dst);
7737 			}
7738 			ip3dbg(("ip_newroute: "
7739 			    "ire %p, sire %p, first_sire %p\n",
7740 			    (void *)ire, (void *)sire, (void *)first_sire));
7741 
7742 			if (sire != NULL) {
7743 				ire_refrele(sire);
7744 				sire = NULL;
7745 			}
7746 
7747 			if (first_sire != NULL) {
7748 				/*
7749 				 * At least one multirt route has been found
7750 				 * in the same call to ip_newroute();
7751 				 * there is no need to report an ICMP error.
7752 				 * first_sire was not IRE_REFHOLDed.
7753 				 */
7754 				MULTIRT_DEBUG_UNTAG(first_mp);
7755 				freemsg(first_mp);
7756 				return;
7757 			}
7758 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7759 			    RTA_DST);
7760 			if (attach_ill != NULL)
7761 				ill_refrele(attach_ill);
7762 			goto icmp_err_ret;
7763 		}
7764 
7765 		/*
7766 		 * When RTA_SRCIFP is used to add a route, then an interface
7767 		 * route is added in the source interface's routing table.
7768 		 * If the outgoing interface of this route is of type
7769 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7770 		 * ire_nce->nce_res_mp is set to NULL.
7771 		 * Later, when this route is first used for forwarding
7772 		 * a packet, ip_newroute() is called
7773 		 * to resolve the hardware address of the outgoing ipif.
7774 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7775 		 * source interface based table. We only come here if the
7776 		 * outgoing interface is a resolver interface and we don't
7777 		 * have the ire_nce->nce_res_mp information yet.
7778 		 * If in_ill is not null that means it is called from
7779 		 * ip_rput.
7780 		 */
7781 
7782 		ASSERT(ire->ire_in_ill == NULL ||
7783 		    (ire->ire_type == IRE_IF_RESOLVER &&
7784 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
7785 
7786 		/*
7787 		 * Verify that the returned IRE does not have either
7788 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7789 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7790 		 */
7791 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7792 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7793 			if (attach_ill != NULL)
7794 				ill_refrele(attach_ill);
7795 			goto icmp_err_ret;
7796 		}
7797 		/*
7798 		 * Increment the ire_ob_pkt_count field for ire if it is an
7799 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7800 		 * increment the same for the parent IRE, sire, if it is some
7801 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7802 		 * and HOST_REDIRECT).
7803 		 */
7804 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7805 			UPDATE_OB_PKT_COUNT(ire);
7806 			ire->ire_last_used_time = lbolt;
7807 		}
7808 
7809 		if (sire != NULL) {
7810 			gw = sire->ire_gateway_addr;
7811 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7812 			    IRE_INTERFACE)) == 0);
7813 			UPDATE_OB_PKT_COUNT(sire);
7814 			sire->ire_last_used_time = lbolt;
7815 		}
7816 		/*
7817 		 * We have a route to reach the destination.
7818 		 *
7819 		 * 1) If the interface is part of ill group, try to get a new
7820 		 *    ill taking load spreading into account.
7821 		 *
7822 		 * 2) After selecting the ill, get a source address that
7823 		 *    might create good inbound load spreading.
7824 		 *    ipif_select_source does this for us.
7825 		 *
7826 		 * If the application specified the ill (ifindex), we still
7827 		 * load spread. Only if the packets needs to go out
7828 		 * specifically on a given ill e.g. binding to
7829 		 * IPIF_NOFAILOVER address, then we don't try to use a
7830 		 * different ill for load spreading.
7831 		 */
7832 		if (attach_ill == NULL) {
7833 			/*
7834 			 * Don't perform outbound load spreading in the
7835 			 * case of an RTF_MULTIRT route, as we actually
7836 			 * typically want to replicate outgoing packets
7837 			 * through particular interfaces.
7838 			 */
7839 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7840 				dst_ill = ire->ire_ipif->ipif_ill;
7841 				/* for uniformity */
7842 				ill_refhold(dst_ill);
7843 			} else {
7844 				/*
7845 				 * If we are here trying to create an IRE_CACHE
7846 				 * for an offlink destination and have the
7847 				 * IRE_CACHE for the next hop and the latter is
7848 				 * using virtual IP source address selection i.e
7849 				 * it's ire->ire_ipif is pointing to a virtual
7850 				 * network interface (vni) then
7851 				 * ip_newroute_get_dst_ll() will return the vni
7852 				 * interface as the dst_ill. Since the vni is
7853 				 * virtual i.e not associated with any physical
7854 				 * interface, it cannot be the dst_ill, hence
7855 				 * in such a case call ip_newroute_get_dst_ll()
7856 				 * with the stq_ill instead of the ire_ipif ILL.
7857 				 * The function returns a refheld ill.
7858 				 */
7859 				if ((ire->ire_type == IRE_CACHE) &&
7860 				    IS_VNI(ire->ire_ipif->ipif_ill))
7861 					dst_ill = ip_newroute_get_dst_ill(
7862 						ire->ire_stq->q_ptr);
7863 				else
7864 					dst_ill = ip_newroute_get_dst_ill(
7865 						ire->ire_ipif->ipif_ill);
7866 			}
7867 			if (dst_ill == NULL) {
7868 				if (ip_debug > 2) {
7869 					pr_addr_dbg("ip_newroute: "
7870 					    "no dst ill for dst"
7871 					    " %s\n", AF_INET, &dst);
7872 				}
7873 				goto icmp_err_ret;
7874 			}
7875 		} else {
7876 			dst_ill = ire->ire_ipif->ipif_ill;
7877 			/* for uniformity */
7878 			ill_refhold(dst_ill);
7879 			/*
7880 			 * We should have found a route matching ill as we
7881 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7882 			 * Rather than asserting, when there is a mismatch,
7883 			 * we just drop the packet.
7884 			 */
7885 			if (dst_ill != attach_ill) {
7886 				ip0dbg(("ip_newroute: Packet dropped as "
7887 				    "IPIF_NOFAILOVER ill is %s, "
7888 				    "ire->ire_ipif->ipif_ill is %s\n",
7889 				    attach_ill->ill_name,
7890 				    dst_ill->ill_name));
7891 				ill_refrele(attach_ill);
7892 				goto icmp_err_ret;
7893 			}
7894 		}
7895 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7896 		if (attach_ill != NULL) {
7897 			ill_refrele(attach_ill);
7898 			attach_ill = NULL;
7899 			do_attach_ill = B_TRUE;
7900 		}
7901 		ASSERT(dst_ill != NULL);
7902 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7903 
7904 		/*
7905 		 * Pick the best source address from dst_ill.
7906 		 *
7907 		 * 1) If it is part of a multipathing group, we would
7908 		 *    like to spread the inbound packets across different
7909 		 *    interfaces. ipif_select_source picks a random source
7910 		 *    across the different ills in the group.
7911 		 *
7912 		 * 2) If it is not part of a multipathing group, we try
7913 		 *    to pick the source address from the destination
7914 		 *    route. Clustering assumes that when we have multiple
7915 		 *    prefixes hosted on an interface, the prefix of the
7916 		 *    source address matches the prefix of the destination
7917 		 *    route. We do this only if the address is not
7918 		 *    DEPRECATED.
7919 		 *
7920 		 * 3) If the conn is in a different zone than the ire, we
7921 		 *    need to pick a source address from the right zone.
7922 		 *
7923 		 * NOTE : If we hit case (1) above, the prefix of the source
7924 		 *	  address picked may not match the prefix of the
7925 		 *	  destination routes prefix as ipif_select_source
7926 		 *	  does not look at "dst" while picking a source
7927 		 *	  address.
7928 		 *	  If we want the same behavior as (2), we will need
7929 		 *	  to change the behavior of ipif_select_source.
7930 		 */
7931 		ASSERT(src_ipif == NULL);
7932 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7933 			/*
7934 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7935 			 * Check that the ipif matching the requested source
7936 			 * address still exists.
7937 			 */
7938 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7939 			    zoneid, NULL, NULL, NULL, NULL);
7940 		}
7941 		if (src_ipif == NULL) {
7942 			ire_marks |= IRE_MARK_USESRC_CHECK;
7943 			if ((dst_ill->ill_group != NULL) ||
7944 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
7945 			    (connp != NULL && ire->ire_zoneid != zoneid &&
7946 			    ire->ire_zoneid != ALL_ZONES) ||
7947 			    (dst_ill->ill_usesrc_ifindex != 0)) {
7948 				/*
7949 				 * If the destination is reachable via a
7950 				 * given gateway, the selected source address
7951 				 * should be in the same subnet as the gateway.
7952 				 * Otherwise, the destination is not reachable.
7953 				 *
7954 				 * If there are no interfaces on the same subnet
7955 				 * as the destination, ipif_select_source gives
7956 				 * first non-deprecated interface which might be
7957 				 * on a different subnet than the gateway.
7958 				 * This is not desirable. Hence pass the dst_ire
7959 				 * source address to ipif_select_source.
7960 				 * It is sure that the destination is reachable
7961 				 * with the dst_ire source address subnet.
7962 				 * So passing dst_ire source address to
7963 				 * ipif_select_source will make sure that the
7964 				 * selected source will be on the same subnet
7965 				 * as dst_ire source address.
7966 				 */
7967 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
7968 				src_ipif = ipif_select_source(dst_ill, saddr,
7969 				    zoneid);
7970 				if (src_ipif == NULL) {
7971 					if (ip_debug > 2) {
7972 						pr_addr_dbg("ip_newroute: "
7973 						    "no src for dst %s ",
7974 						    AF_INET, &dst);
7975 						printf("through interface %s\n",
7976 						    dst_ill->ill_name);
7977 					}
7978 					goto icmp_err_ret;
7979 				}
7980 			} else {
7981 				src_ipif = ire->ire_ipif;
7982 				ASSERT(src_ipif != NULL);
7983 				/* hold src_ipif for uniformity */
7984 				ipif_refhold(src_ipif);
7985 			}
7986 		}
7987 
7988 		/*
7989 		 * Assign a source address while we have the conn.
7990 		 * We can't have ip_wput_ire pick a source address when the
7991 		 * packet returns from arp since we need to look at
7992 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7993 		 * going through arp.
7994 		 *
7995 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7996 		 *	  it uses ip6i to store this information.
7997 		 */
7998 		if (ipha->ipha_src == INADDR_ANY &&
7999 		    (connp == NULL || !connp->conn_unspec_src)) {
8000 			ipha->ipha_src = src_ipif->ipif_src_addr;
8001 		}
8002 		if (ip_debug > 3) {
8003 			/* ip2dbg */
8004 			pr_addr_dbg("ip_newroute: first hop %s\n",
8005 			    AF_INET, &gw);
8006 		}
8007 		ip2dbg(("\tire type %s (%d)\n",
8008 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8009 
8010 		/*
8011 		 * The TTL of multirouted packets is bounded by the
8012 		 * ip_multirt_ttl ndd variable.
8013 		 */
8014 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8015 			/* Force TTL of multirouted packets */
8016 			if ((ip_multirt_ttl > 0) &&
8017 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
8018 				ip2dbg(("ip_newroute: forcing multirt TTL "
8019 				    "to %d (was %d), dst 0x%08x\n",
8020 				    ip_multirt_ttl, ipha->ipha_ttl,
8021 				    ntohl(sire->ire_addr)));
8022 				ipha->ipha_ttl = ip_multirt_ttl;
8023 			}
8024 		}
8025 		/*
8026 		 * At this point in ip_newroute(), ire is either the
8027 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8028 		 * destination or an IRE_INTERFACE type that should be used
8029 		 * to resolve an on-subnet destination or an on-subnet
8030 		 * next-hop gateway.
8031 		 *
8032 		 * In the IRE_CACHE case, we have the following :
8033 		 *
8034 		 * 1) src_ipif - used for getting a source address.
8035 		 *
8036 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8037 		 *    means packets using this IRE_CACHE will go out on
8038 		 *    dst_ill.
8039 		 *
8040 		 * 3) The IRE sire will point to the prefix that is the
8041 		 *    longest  matching route for the destination. These
8042 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
8043 		 *    and IRE_HOST_REDIRECT.
8044 		 *
8045 		 *    The newly created IRE_CACHE entry for the off-subnet
8046 		 *    destination is tied to both the prefix route and the
8047 		 *    interface route used to resolve the next-hop gateway
8048 		 *    via the ire_phandle and ire_ihandle fields,
8049 		 *    respectively.
8050 		 *
8051 		 * In the IRE_INTERFACE case, we have the following :
8052 		 *
8053 		 * 1) src_ipif - used for getting a source address.
8054 		 *
8055 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8056 		 *    means packets using the IRE_CACHE that we will build
8057 		 *    here will go out on dst_ill.
8058 		 *
8059 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8060 		 *    to be created will only be tied to the IRE_INTERFACE
8061 		 *    that was derived from the ire_ihandle field.
8062 		 *
8063 		 *    If sire is non-NULL, it means the destination is
8064 		 *    off-link and we will first create the IRE_CACHE for the
8065 		 *    gateway. Next time through ip_newroute, we will create
8066 		 *    the IRE_CACHE for the final destination as described
8067 		 *    above.
8068 		 *
8069 		 * In both cases, after the current resolution has been
8070 		 * completed (or possibly initialised, in the IRE_INTERFACE
8071 		 * case), the loop may be re-entered to attempt the resolution
8072 		 * of another RTF_MULTIRT route.
8073 		 *
8074 		 * When an IRE_CACHE entry for the off-subnet destination is
8075 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8076 		 * for further processing in emission loops.
8077 		 */
8078 		save_ire = ire;
8079 		switch (ire->ire_type) {
8080 		case IRE_CACHE: {
8081 			ire_t	*ipif_ire;
8082 			mblk_t	*ire_fp_mp;
8083 
8084 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8085 			if (gw == 0)
8086 				gw = ire->ire_gateway_addr;
8087 			/*
8088 			 * We need 3 ire's to create a new cache ire for an
8089 			 * off-link destination from the cache ire of the
8090 			 * gateway.
8091 			 *
8092 			 *	1. The prefix ire 'sire' (Note that this does
8093 			 *	   not apply to the conn_nexthop_set case)
8094 			 *	2. The cache ire of the gateway 'ire'
8095 			 *	3. The interface ire 'ipif_ire'
8096 			 *
8097 			 * We have (1) and (2). We lookup (3) below.
8098 			 *
8099 			 * If there is no interface route to the gateway,
8100 			 * it is a race condition, where we found the cache
8101 			 * but the interface route has been deleted.
8102 			 */
8103 			if (ip_nexthop) {
8104 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8105 			} else {
8106 				ipif_ire =
8107 				    ire_ihandle_lookup_offlink(ire, sire);
8108 			}
8109 			if (ipif_ire == NULL) {
8110 				ip1dbg(("ip_newroute: "
8111 				    "ire_ihandle_lookup_offlink failed\n"));
8112 				goto icmp_err_ret;
8113 			}
8114 			/*
8115 			 * XXX We are using the same res_mp
8116 			 * (DL_UNITDATA_REQ) though the save_ire is not
8117 			 * pointing at the same ill.
8118 			 * This is incorrect. We need to send it up to the
8119 			 * resolver to get the right res_mp. For ethernets
8120 			 * this may be okay (ill_type == DL_ETHER).
8121 			 */
8122 			res_mp = save_ire->ire_nce->nce_res_mp;
8123 			ire_fp_mp = NULL;
8124 			/*
8125 			 * save_ire's nce_fp_mp can't change since it is
8126 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8127 			 * LOCK_IRE_FP_MP does not do any useful work in
8128 			 * the case of IRE_CACHE. So we don't use it below.
8129 			 */
8130 			if (save_ire->ire_stq == dst_ill->ill_wq)
8131 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8132 
8133 			/*
8134 			 * Check cached gateway IRE for any security
8135 			 * attributes; if found, associate the gateway
8136 			 * credentials group to the destination IRE.
8137 			 */
8138 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8139 				mutex_enter(&attrp->igsa_lock);
8140 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8141 					GCGRP_REFHOLD(gcgrp);
8142 				mutex_exit(&attrp->igsa_lock);
8143 			}
8144 
8145 			ire = ire_create(
8146 			    (uchar_t *)&dst,		/* dest address */
8147 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8148 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8149 			    (uchar_t *)&gw,		/* gateway address */
8150 			    NULL,
8151 			    &save_ire->ire_max_frag,
8152 			    ire_fp_mp,			/* Fast Path header */
8153 			    dst_ill->ill_rq,		/* recv-from queue */
8154 			    dst_ill->ill_wq,		/* send-to queue */
8155 			    IRE_CACHE,			/* IRE type */
8156 			    res_mp,
8157 			    src_ipif,
8158 			    in_ill,			/* incoming ill */
8159 			    (sire != NULL) ?
8160 				sire->ire_mask : 0, 	/* Parent mask */
8161 			    (sire != NULL) ?
8162 				sire->ire_phandle : 0,  /* Parent handle */
8163 			    ipif_ire->ire_ihandle,	/* Interface handle */
8164 			    (sire != NULL) ? (sire->ire_flags &
8165 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8166 			    (sire != NULL) ?
8167 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8168 			    NULL,
8169 			    gcgrp);
8170 
8171 			if (ire == NULL) {
8172 				if (gcgrp != NULL) {
8173 					GCGRP_REFRELE(gcgrp);
8174 					gcgrp = NULL;
8175 				}
8176 				ire_refrele(ipif_ire);
8177 				ire_refrele(save_ire);
8178 				break;
8179 			}
8180 
8181 			/* reference now held by IRE */
8182 			gcgrp = NULL;
8183 
8184 			ire->ire_marks |= ire_marks;
8185 
8186 			/*
8187 			 * Prevent sire and ipif_ire from getting deleted.
8188 			 * The newly created ire is tied to both of them via
8189 			 * the phandle and ihandle respectively.
8190 			 */
8191 			if (sire != NULL) {
8192 				IRB_REFHOLD(sire->ire_bucket);
8193 				/* Has it been removed already ? */
8194 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8195 					IRB_REFRELE(sire->ire_bucket);
8196 					ire_refrele(ipif_ire);
8197 					ire_refrele(save_ire);
8198 					break;
8199 				}
8200 			}
8201 
8202 			IRB_REFHOLD(ipif_ire->ire_bucket);
8203 			/* Has it been removed already ? */
8204 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8205 				IRB_REFRELE(ipif_ire->ire_bucket);
8206 				if (sire != NULL)
8207 					IRB_REFRELE(sire->ire_bucket);
8208 				ire_refrele(ipif_ire);
8209 				ire_refrele(save_ire);
8210 				break;
8211 			}
8212 
8213 			xmit_mp = first_mp;
8214 			/*
8215 			 * In the case of multirouting, a copy
8216 			 * of the packet is done before its sending.
8217 			 * The copy is used to attempt another
8218 			 * route resolution, in a next loop.
8219 			 */
8220 			if (ire->ire_flags & RTF_MULTIRT) {
8221 				copy_mp = copymsg(first_mp);
8222 				if (copy_mp != NULL) {
8223 					xmit_mp = copy_mp;
8224 					MULTIRT_DEBUG_TAG(first_mp);
8225 				}
8226 			}
8227 			ire_add_then_send(q, ire, xmit_mp);
8228 			ire_refrele(save_ire);
8229 
8230 			/* Assert that sire is not deleted yet. */
8231 			if (sire != NULL) {
8232 				ASSERT(sire->ire_ptpn != NULL);
8233 				IRB_REFRELE(sire->ire_bucket);
8234 			}
8235 
8236 			/* Assert that ipif_ire is not deleted yet. */
8237 			ASSERT(ipif_ire->ire_ptpn != NULL);
8238 			IRB_REFRELE(ipif_ire->ire_bucket);
8239 			ire_refrele(ipif_ire);
8240 
8241 			/*
8242 			 * If copy_mp is not NULL, multirouting was
8243 			 * requested. We loop to initiate a next
8244 			 * route resolution attempt, starting from sire.
8245 			 */
8246 			if (copy_mp != NULL) {
8247 				/*
8248 				 * Search for the next unresolved
8249 				 * multirt route.
8250 				 */
8251 				copy_mp = NULL;
8252 				ipif_ire = NULL;
8253 				ire = NULL;
8254 				multirt_resolve_next = B_TRUE;
8255 				continue;
8256 			}
8257 			if (sire != NULL)
8258 				ire_refrele(sire);
8259 			ipif_refrele(src_ipif);
8260 			ill_refrele(dst_ill);
8261 			return;
8262 		}
8263 		case IRE_IF_NORESOLVER: {
8264 			/*
8265 			 * We have what we need to build an IRE_CACHE.
8266 			 *
8267 			 * Create a new res_mp with the IP gateway address
8268 			 * in destination address in the DLPI hdr if the
8269 			 * physical length is exactly 4 bytes.
8270 			 */
8271 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8272 				uchar_t *addr;
8273 
8274 				if (gw)
8275 					addr = (uchar_t *)&gw;
8276 				else
8277 					addr = (uchar_t *)&dst;
8278 
8279 				res_mp = ill_dlur_gen(addr,
8280 				    dst_ill->ill_phys_addr_length,
8281 				    dst_ill->ill_sap,
8282 				    dst_ill->ill_sap_length);
8283 
8284 				if (res_mp == NULL) {
8285 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8286 					break;
8287 				}
8288 			} else {
8289 				res_mp = NULL;
8290 			}
8291 
8292 			/*
8293 			 * TSol note: We are creating the ire cache for the
8294 			 * destination 'dst'. If 'dst' is offlink, going
8295 			 * through the first hop 'gw', the security attributes
8296 			 * of 'dst' must be set to point to the gateway
8297 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8298 			 * is possible that 'dst' is a potential gateway that is
8299 			 * referenced by some route that has some security
8300 			 * attributes. Thus in the former case, we need to do a
8301 			 * gcgrp_lookup of 'gw' while in the latter case we
8302 			 * need to do gcgrp_lookup of 'dst' itself.
8303 			 */
8304 			ga.ga_af = AF_INET;
8305 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8306 			    &ga.ga_addr);
8307 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8308 
8309 			ire = ire_create(
8310 			    (uchar_t *)&dst,		/* dest address */
8311 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8312 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8313 			    (uchar_t *)&gw,		/* gateway address */
8314 			    NULL,
8315 			    &save_ire->ire_max_frag,
8316 			    NULL,			/* Fast Path header */
8317 			    dst_ill->ill_rq,		/* recv-from queue */
8318 			    dst_ill->ill_wq,		/* send-to queue */
8319 			    IRE_CACHE,
8320 			    res_mp,
8321 			    src_ipif,
8322 			    in_ill,			/* Incoming ill */
8323 			    save_ire->ire_mask,		/* Parent mask */
8324 			    (sire != NULL) ?		/* Parent handle */
8325 				sire->ire_phandle : 0,
8326 			    save_ire->ire_ihandle,	/* Interface handle */
8327 			    (sire != NULL) ? sire->ire_flags &
8328 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8329 			    &(save_ire->ire_uinfo),
8330 			    NULL,
8331 			    gcgrp);
8332 
8333 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8334 				freeb(res_mp);
8335 
8336 			if (ire == NULL) {
8337 				if (gcgrp != NULL) {
8338 					GCGRP_REFRELE(gcgrp);
8339 					gcgrp = NULL;
8340 				}
8341 				ire_refrele(save_ire);
8342 				break;
8343 			}
8344 
8345 			/* reference now held by IRE */
8346 			gcgrp = NULL;
8347 
8348 			ire->ire_marks |= ire_marks;
8349 
8350 			/* Prevent save_ire from getting deleted */
8351 			IRB_REFHOLD(save_ire->ire_bucket);
8352 			/* Has it been removed already ? */
8353 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8354 				IRB_REFRELE(save_ire->ire_bucket);
8355 				ire_refrele(save_ire);
8356 				break;
8357 			}
8358 
8359 			/*
8360 			 * In the case of multirouting, a copy
8361 			 * of the packet is made before it is sent.
8362 			 * The copy is used in the next
8363 			 * loop to attempt another resolution.
8364 			 */
8365 			xmit_mp = first_mp;
8366 			if ((sire != NULL) &&
8367 			    (sire->ire_flags & RTF_MULTIRT)) {
8368 				copy_mp = copymsg(first_mp);
8369 				if (copy_mp != NULL) {
8370 					xmit_mp = copy_mp;
8371 					MULTIRT_DEBUG_TAG(first_mp);
8372 				}
8373 			}
8374 			ire_add_then_send(q, ire, xmit_mp);
8375 
8376 			/* Assert that it is not deleted yet. */
8377 			ASSERT(save_ire->ire_ptpn != NULL);
8378 			IRB_REFRELE(save_ire->ire_bucket);
8379 			ire_refrele(save_ire);
8380 
8381 			if (copy_mp != NULL) {
8382 				/*
8383 				 * If we found a (no)resolver, we ignore any
8384 				 * trailing top priority IRE_CACHE in further
8385 				 * loops. This ensures that we do not omit any
8386 				 * (no)resolver.
8387 				 * This IRE_CACHE, if any, will be processed
8388 				 * by another thread entering ip_newroute().
8389 				 * IRE_CACHE entries, if any, will be processed
8390 				 * by another thread entering ip_newroute(),
8391 				 * (upon resolver response, for instance).
8392 				 * This aims to force parallel multirt
8393 				 * resolutions as soon as a packet must be sent.
8394 				 * In the best case, after the tx of only one
8395 				 * packet, all reachable routes are resolved.
8396 				 * Otherwise, the resolution of all RTF_MULTIRT
8397 				 * routes would require several emissions.
8398 				 */
8399 				multirt_flags &= ~MULTIRT_CACHEGW;
8400 
8401 				/*
8402 				 * Search for the next unresolved multirt
8403 				 * route.
8404 				 */
8405 				copy_mp = NULL;
8406 				save_ire = NULL;
8407 				ire = NULL;
8408 				multirt_resolve_next = B_TRUE;
8409 				continue;
8410 			}
8411 
8412 			/*
8413 			 * Don't need sire anymore
8414 			 */
8415 			if (sire != NULL)
8416 				ire_refrele(sire);
8417 
8418 			ipif_refrele(src_ipif);
8419 			ill_refrele(dst_ill);
8420 			return;
8421 		}
8422 		case IRE_IF_RESOLVER:
8423 			/*
8424 			 * We can't build an IRE_CACHE yet, but at least we
8425 			 * found a resolver that can help.
8426 			 */
8427 			res_mp = dst_ill->ill_resolver_mp;
8428 			if (!OK_RESOLVER_MP(res_mp))
8429 				break;
8430 
8431 			/*
8432 			 * To be at this point in the code with a non-zero gw
8433 			 * means that dst is reachable through a gateway that
8434 			 * we have never resolved.  By changing dst to the gw
8435 			 * addr we resolve the gateway first.
8436 			 * When ire_add_then_send() tries to put the IP dg
8437 			 * to dst, it will reenter ip_newroute() at which
8438 			 * time we will find the IRE_CACHE for the gw and
8439 			 * create another IRE_CACHE in case IRE_CACHE above.
8440 			 */
8441 			if (gw != INADDR_ANY) {
8442 				/*
8443 				 * The source ipif that was determined above was
8444 				 * relative to the destination address, not the
8445 				 * gateway's. If src_ipif was not taken out of
8446 				 * the IRE_IF_RESOLVER entry, we'll need to call
8447 				 * ipif_select_source() again.
8448 				 */
8449 				if (src_ipif != ire->ire_ipif) {
8450 					ipif_refrele(src_ipif);
8451 					src_ipif = ipif_select_source(dst_ill,
8452 					    gw, zoneid);
8453 					if (src_ipif == NULL) {
8454 						if (ip_debug > 2) {
8455 							pr_addr_dbg(
8456 							    "ip_newroute: no "
8457 							    "src for gw %s ",
8458 							    AF_INET, &gw);
8459 							printf("through "
8460 							    "interface %s\n",
8461 							    dst_ill->ill_name);
8462 						}
8463 						goto icmp_err_ret;
8464 					}
8465 				}
8466 				save_dst = dst;
8467 				dst = gw;
8468 				gw = INADDR_ANY;
8469 			}
8470 
8471 			/*
8472 			 * We obtain a partial IRE_CACHE which we will pass
8473 			 * along with the resolver query.  When the response
8474 			 * comes back it will be there ready for us to add.
8475 			 * The ire_max_frag is atomically set under the
8476 			 * irebucket lock in ire_add_v[46].
8477 			 */
8478 
8479 			ire = ire_create_mp(
8480 			    (uchar_t *)&dst,		/* dest address */
8481 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8482 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8483 			    (uchar_t *)&gw,		/* gateway address */
8484 			    NULL,			/* no in_src_addr */
8485 			    NULL,			/* ire_max_frag */
8486 			    NULL,			/* Fast Path header */
8487 			    dst_ill->ill_rq,		/* recv-from queue */
8488 			    dst_ill->ill_wq,		/* send-to queue */
8489 			    IRE_CACHE,
8490 			    NULL,
8491 			    src_ipif,			/* Interface ipif */
8492 			    in_ill,			/* Incoming ILL */
8493 			    save_ire->ire_mask,		/* Parent mask */
8494 			    0,
8495 			    save_ire->ire_ihandle,	/* Interface handle */
8496 			    0,				/* flags if any */
8497 			    &(save_ire->ire_uinfo),
8498 			    NULL,
8499 			    NULL);
8500 
8501 			if (ire == NULL) {
8502 				ire_refrele(save_ire);
8503 				break;
8504 			}
8505 
8506 			if ((sire != NULL) &&
8507 			    (sire->ire_flags & RTF_MULTIRT)) {
8508 				copy_mp = copymsg(first_mp);
8509 				if (copy_mp != NULL)
8510 					MULTIRT_DEBUG_TAG(copy_mp);
8511 			}
8512 
8513 			ire->ire_marks |= ire_marks;
8514 
8515 			/*
8516 			 * Construct message chain for the resolver
8517 			 * of the form:
8518 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8519 			 * Packet could contain a IPSEC_OUT mp.
8520 			 *
8521 			 * NOTE : ire will be added later when the response
8522 			 * comes back from ARP. If the response does not
8523 			 * come back, ARP frees the packet. For this reason,
8524 			 * we can't REFHOLD the bucket of save_ire to prevent
8525 			 * deletions. We may not be able to REFRELE the bucket
8526 			 * if the response never comes back. Thus, before
8527 			 * adding the ire, ire_add_v4 will make sure that the
8528 			 * interface route does not get deleted. This is the
8529 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8530 			 * where we can always prevent deletions because of
8531 			 * the synchronous nature of adding IRES i.e
8532 			 * ire_add_then_send is called after creating the IRE.
8533 			 */
8534 			ASSERT(ire->ire_mp != NULL);
8535 			ire->ire_mp->b_cont = first_mp;
8536 			/* Have saved_mp handy, for cleanup if canput fails */
8537 			saved_mp = mp;
8538 			mp = copyb(res_mp);
8539 			ASSERT(mp != NULL);
8540 			linkb(mp, ire->ire_mp);
8541 
8542 
8543 			/*
8544 			 * Fill in the source and dest addrs for the resolver.
8545 			 * NOTE: this depends on memory layouts imposed by
8546 			 * ill_init().
8547 			 */
8548 			areq = (areq_t *)mp->b_rptr;
8549 			addrp = (ipaddr_t *)((char *)areq +
8550 			    areq->areq_sender_addr_offset);
8551 			if (do_attach_ill) {
8552 				/*
8553 				 * This is bind to no failover case.
8554 				 * arp packet also must go out on attach_ill.
8555 				 */
8556 				ASSERT(ipha->ipha_src != NULL);
8557 				*addrp = ipha->ipha_src;
8558 			} else {
8559 				*addrp = save_ire->ire_src_addr;
8560 			}
8561 
8562 			ire_refrele(save_ire);
8563 			addrp = (ipaddr_t *)((char *)areq +
8564 			    areq->areq_target_addr_offset);
8565 			*addrp = dst;
8566 			/* Up to the resolver. */
8567 			if (canputnext(dst_ill->ill_rq) &&
8568 			    !(dst_ill->ill_arp_closing)) {
8569 				putnext(dst_ill->ill_rq, mp);
8570 				ire = NULL;
8571 				if (copy_mp != NULL) {
8572 					/*
8573 					 * If we found a resolver, we ignore
8574 					 * any trailing top priority IRE_CACHE
8575 					 * in the further loops. This ensures
8576 					 * that we do not omit any resolver.
8577 					 * IRE_CACHE entries, if any, will be
8578 					 * processed next time we enter
8579 					 * ip_newroute().
8580 					 */
8581 					multirt_flags &= ~MULTIRT_CACHEGW;
8582 					/*
8583 					 * Search for the next unresolved
8584 					 * multirt route.
8585 					 */
8586 					first_mp = copy_mp;
8587 					copy_mp = NULL;
8588 					/* Prepare the next resolution loop. */
8589 					mp = first_mp;
8590 					EXTRACT_PKT_MP(mp, first_mp,
8591 					    mctl_present);
8592 					if (mctl_present)
8593 						io = (ipsec_out_t *)
8594 						    first_mp->b_rptr;
8595 					ipha = (ipha_t *)mp->b_rptr;
8596 
8597 					ASSERT(sire != NULL);
8598 
8599 					dst = save_dst;
8600 					multirt_resolve_next = B_TRUE;
8601 					continue;
8602 				}
8603 
8604 				if (sire != NULL)
8605 					ire_refrele(sire);
8606 
8607 				/*
8608 				 * The response will come back in ip_wput
8609 				 * with db_type IRE_DB_TYPE.
8610 				 */
8611 				ipif_refrele(src_ipif);
8612 				ill_refrele(dst_ill);
8613 				return;
8614 			} else {
8615 				/* Prepare for cleanup */
8616 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8617 				    mp);
8618 				mp->b_cont = NULL;
8619 				freeb(mp); /* areq */
8620 				/*
8621 				 * this is an ire that is not added to the
8622 				 * cache. ire_freemblk will handle the release
8623 				 * of any resources associated with the ire.
8624 				 */
8625 				ire_delete(ire); /* ire_mp */
8626 				mp = saved_mp; /* pkt */
8627 				ire = NULL;
8628 				if (copy_mp != NULL) {
8629 					MULTIRT_DEBUG_UNTAG(copy_mp);
8630 					freemsg(copy_mp);
8631 					copy_mp = NULL;
8632 				}
8633 				break;
8634 			}
8635 		default:
8636 			break;
8637 		}
8638 	} while (multirt_resolve_next);
8639 
8640 	ip1dbg(("ip_newroute: dropped\n"));
8641 	/* Did this packet originate externally? */
8642 	if (mp->b_prev) {
8643 		mp->b_next = NULL;
8644 		mp->b_prev = NULL;
8645 		BUMP_MIB(&ip_mib, ipInDiscards);
8646 	} else {
8647 		BUMP_MIB(&ip_mib, ipOutDiscards);
8648 	}
8649 	ASSERT(copy_mp == NULL);
8650 	MULTIRT_DEBUG_UNTAG(first_mp);
8651 	freemsg(first_mp);
8652 	if (ire != NULL)
8653 		ire_refrele(ire);
8654 	if (sire != NULL)
8655 		ire_refrele(sire);
8656 	if (src_ipif != NULL)
8657 		ipif_refrele(src_ipif);
8658 	if (dst_ill != NULL)
8659 		ill_refrele(dst_ill);
8660 	return;
8661 
8662 icmp_err_ret:
8663 	ip1dbg(("ip_newroute: no route\n"));
8664 	if (src_ipif != NULL)
8665 		ipif_refrele(src_ipif);
8666 	if (dst_ill != NULL)
8667 		ill_refrele(dst_ill);
8668 	if (sire != NULL)
8669 		ire_refrele(sire);
8670 	/* Did this packet originate externally? */
8671 	if (mp->b_prev) {
8672 		mp->b_next = NULL;
8673 		mp->b_prev = NULL;
8674 		/* XXX ipInNoRoutes */
8675 		q = WR(q);
8676 	} else {
8677 		/*
8678 		 * Since ip_wput() isn't close to finished, we fill
8679 		 * in enough of the header for credible error reporting.
8680 		 */
8681 		if (ip_hdr_complete(ipha, zoneid)) {
8682 			/* Failed */
8683 			MULTIRT_DEBUG_UNTAG(first_mp);
8684 			freemsg(first_mp);
8685 			if (ire != NULL)
8686 				ire_refrele(ire);
8687 			return;
8688 		}
8689 	}
8690 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8691 
8692 	/*
8693 	 * At this point we will have ire only if RTF_BLACKHOLE
8694 	 * or RTF_REJECT flags are set on the IRE. It will not
8695 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8696 	 */
8697 	if (ire != NULL) {
8698 		if (ire->ire_flags & RTF_BLACKHOLE) {
8699 			ire_refrele(ire);
8700 			MULTIRT_DEBUG_UNTAG(first_mp);
8701 			freemsg(first_mp);
8702 			return;
8703 		}
8704 		ire_refrele(ire);
8705 	}
8706 	if (ip_source_routed(ipha)) {
8707 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8708 		    zoneid);
8709 		return;
8710 	}
8711 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
8712 }
8713 
8714 /*
8715  * IPv4 -
8716  * ip_newroute_ipif is called by ip_wput_multicast and
8717  * ip_rput_forward_multicast whenever we need to send
8718  * out a packet to a destination address for which we do not have specific
8719  * routing information. It is used when the packet will be sent out
8720  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8721  * socket option is set or icmp error message wants to go out on a particular
8722  * interface for a unicast packet.
8723  *
8724  * In most cases, the destination address is resolved thanks to the ipif
8725  * intrinsic resolver. However, there are some cases where the call to
8726  * ip_newroute_ipif must take into account the potential presence of
8727  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8728  * that uses the interface. This is specified through flags,
8729  * which can be a combination of:
8730  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8731  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8732  *   and flags. Additionally, the packet source address has to be set to
8733  *   the specified address. The caller is thus expected to set this flag
8734  *   if the packet has no specific source address yet.
8735  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8736  *   flag, the resulting ire will inherit the flag. All unresolved routes
8737  *   to the destination must be explored in the same call to
8738  *   ip_newroute_ipif().
8739  */
8740 static void
8741 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8742     conn_t *connp, uint32_t flags, zoneid_t zoneid)
8743 {
8744 	areq_t	*areq;
8745 	ire_t	*ire = NULL;
8746 	mblk_t	*res_mp;
8747 	ipaddr_t *addrp;
8748 	mblk_t *first_mp;
8749 	ire_t	*save_ire = NULL;
8750 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8751 	ipif_t	*src_ipif = NULL;
8752 	ushort_t ire_marks = 0;
8753 	ill_t	*dst_ill = NULL;
8754 	boolean_t mctl_present;
8755 	ipsec_out_t *io;
8756 	ipha_t *ipha;
8757 	int	ihandle = 0;
8758 	mblk_t	*saved_mp;
8759 	ire_t   *fire = NULL;
8760 	mblk_t  *copy_mp = NULL;
8761 	boolean_t multirt_resolve_next;
8762 	ipaddr_t ipha_dst;
8763 
8764 	/*
8765 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8766 	 * here for uniformity
8767 	 */
8768 	ipif_refhold(ipif);
8769 
8770 	/*
8771 	 * This loop is run only once in most cases.
8772 	 * We loop to resolve further routes only when the destination
8773 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8774 	 */
8775 	do {
8776 		if (dst_ill != NULL) {
8777 			ill_refrele(dst_ill);
8778 			dst_ill = NULL;
8779 		}
8780 		if (src_ipif != NULL) {
8781 			ipif_refrele(src_ipif);
8782 			src_ipif = NULL;
8783 		}
8784 		multirt_resolve_next = B_FALSE;
8785 
8786 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8787 		    ipif->ipif_ill->ill_name));
8788 
8789 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8790 		if (mctl_present)
8791 			io = (ipsec_out_t *)first_mp->b_rptr;
8792 
8793 		ipha = (ipha_t *)mp->b_rptr;
8794 
8795 		/*
8796 		 * Save the packet destination address, we may need it after
8797 		 * the packet has been consumed.
8798 		 */
8799 		ipha_dst = ipha->ipha_dst;
8800 
8801 		/*
8802 		 * If the interface is a pt-pt interface we look for an
8803 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8804 		 * local_address and the pt-pt destination address. Otherwise
8805 		 * we just match the local address.
8806 		 * NOTE: dst could be different than ipha->ipha_dst in case
8807 		 * of sending igmp multicast packets over a point-to-point
8808 		 * connection.
8809 		 * Thus we must be careful enough to check ipha_dst to be a
8810 		 * multicast address, otherwise it will take xmit_if path for
8811 		 * multicast packets resulting into kernel stack overflow by
8812 		 * repeated calls to ip_newroute_ipif from ire_send().
8813 		 */
8814 		if (CLASSD(ipha_dst) &&
8815 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8816 			goto err_ret;
8817 		}
8818 
8819 		/*
8820 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8821 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8822 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8823 		 * propagate its flags to the new ire.
8824 		 */
8825 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8826 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8827 			ip2dbg(("ip_newroute_ipif: "
8828 			    "ipif_lookup_multi_ire("
8829 			    "ipif %p, dst %08x) = fire %p\n",
8830 			    (void *)ipif, ntohl(dst), (void *)fire));
8831 		}
8832 
8833 		if (mctl_present && io->ipsec_out_attach_if) {
8834 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8835 			    io->ipsec_out_ill_index, B_FALSE);
8836 
8837 			/* Failure case frees things for us. */
8838 			if (attach_ill == NULL) {
8839 				ipif_refrele(ipif);
8840 				if (fire != NULL)
8841 					ire_refrele(fire);
8842 				return;
8843 			}
8844 
8845 			/*
8846 			 * Check if we need an ire that will not be
8847 			 * looked up by anybody else i.e. HIDDEN.
8848 			 */
8849 			if (ill_is_probeonly(attach_ill)) {
8850 				ire_marks = IRE_MARK_HIDDEN;
8851 			}
8852 			/*
8853 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8854 			 * case.
8855 			 */
8856 			dst_ill = ipif->ipif_ill;
8857 			/* attach_ill has been refheld by ip_grab_attach_ill */
8858 			ASSERT(dst_ill == attach_ill);
8859 		} else {
8860 			/*
8861 			 * If this is set by IP_XMIT_IF, then make sure that
8862 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8863 			 * specified ill.
8864 			 */
8865 			ASSERT((connp == NULL) ||
8866 			    (connp->conn_xmit_if_ill == NULL) ||
8867 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8868 			/*
8869 			 * If the interface belongs to an interface group,
8870 			 * make sure the next possible interface in the group
8871 			 * is used.  This encourages load spreading among
8872 			 * peers in an interface group.
8873 			 * Note: load spreading is disabled for RTF_MULTIRT
8874 			 * routes.
8875 			 */
8876 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8877 			    (fire->ire_flags & RTF_MULTIRT)) {
8878 				/*
8879 				 * Don't perform outbound load spreading
8880 				 * in the case of an RTF_MULTIRT issued route,
8881 				 * we actually typically want to replicate
8882 				 * outgoing packets through particular
8883 				 * interfaces.
8884 				 */
8885 				dst_ill = ipif->ipif_ill;
8886 				ill_refhold(dst_ill);
8887 			} else {
8888 				dst_ill = ip_newroute_get_dst_ill(
8889 				    ipif->ipif_ill);
8890 			}
8891 			if (dst_ill == NULL) {
8892 				if (ip_debug > 2) {
8893 					pr_addr_dbg("ip_newroute_ipif: "
8894 					    "no dst ill for dst %s\n",
8895 					    AF_INET, &dst);
8896 				}
8897 				goto err_ret;
8898 			}
8899 		}
8900 
8901 		/*
8902 		 * Pick a source address preferring non-deprecated ones.
8903 		 * Unlike ip_newroute, we don't do any source address
8904 		 * selection here since for multicast it really does not help
8905 		 * in inbound load spreading as in the unicast case.
8906 		 */
8907 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8908 		    (fire->ire_flags & RTF_SETSRC)) {
8909 			/*
8910 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8911 			 * on that interface. This ire has RTF_SETSRC flag, so
8912 			 * the source address of the packet must be changed.
8913 			 * Check that the ipif matching the requested source
8914 			 * address still exists.
8915 			 */
8916 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8917 			    zoneid, NULL, NULL, NULL, NULL);
8918 		}
8919 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8920 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
8921 		    ipif->ipif_zoneid != ALL_ZONES)) &&
8922 		    (src_ipif == NULL)) {
8923 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8924 			if (src_ipif == NULL) {
8925 				if (ip_debug > 2) {
8926 					/* ip1dbg */
8927 					pr_addr_dbg("ip_newroute_ipif: "
8928 					    "no src for dst %s",
8929 					    AF_INET, &dst);
8930 				}
8931 				ip1dbg((" through interface %s\n",
8932 				    dst_ill->ill_name));
8933 				goto err_ret;
8934 			}
8935 			ipif_refrele(ipif);
8936 			ipif = src_ipif;
8937 			ipif_refhold(ipif);
8938 		}
8939 		if (src_ipif == NULL) {
8940 			src_ipif = ipif;
8941 			ipif_refhold(src_ipif);
8942 		}
8943 
8944 		/*
8945 		 * Assign a source address while we have the conn.
8946 		 * We can't have ip_wput_ire pick a source address when the
8947 		 * packet returns from arp since conn_unspec_src might be set
8948 		 * and we loose the conn when going through arp.
8949 		 */
8950 		if (ipha->ipha_src == INADDR_ANY &&
8951 		    (connp == NULL || !connp->conn_unspec_src)) {
8952 			ipha->ipha_src = src_ipif->ipif_src_addr;
8953 		}
8954 
8955 		/*
8956 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8957 		 * interface does not have an interface ire.
8958 		 * Example: Thousands of mobileip PPP interfaces to mobile
8959 		 * nodes. We don't want to create interface ires because
8960 		 * packets from other mobile nodes must not take the route
8961 		 * via interface ires to the visiting mobile node without
8962 		 * going through the home agent, in absence of mobileip
8963 		 * route optimization.
8964 		 */
8965 		if (CLASSD(ipha_dst) && (connp == NULL ||
8966 		    connp->conn_xmit_if_ill == NULL)) {
8967 			/* ipif_to_ire returns an held ire */
8968 			ire = ipif_to_ire(ipif);
8969 			if (ire == NULL)
8970 				goto err_ret;
8971 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8972 				goto err_ret;
8973 			/*
8974 			 * ihandle is needed when the ire is added to
8975 			 * cache table.
8976 			 */
8977 			save_ire = ire;
8978 			ihandle = save_ire->ire_ihandle;
8979 
8980 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8981 			    "flags %04x\n",
8982 			    (void *)ire, (void *)ipif, flags));
8983 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8984 			    (fire->ire_flags & RTF_MULTIRT)) {
8985 				/*
8986 				 * As requested by flags, an IRE_OFFSUBNET was
8987 				 * looked up on that interface. This ire has
8988 				 * RTF_MULTIRT flag, so the resolution loop will
8989 				 * be re-entered to resolve additional routes on
8990 				 * other interfaces. For that purpose, a copy of
8991 				 * the packet is performed at this point.
8992 				 */
8993 				fire->ire_last_used_time = lbolt;
8994 				copy_mp = copymsg(first_mp);
8995 				if (copy_mp) {
8996 					MULTIRT_DEBUG_TAG(copy_mp);
8997 				}
8998 			}
8999 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9000 			    (fire->ire_flags & RTF_SETSRC)) {
9001 				/*
9002 				 * As requested by flags, an IRE_OFFSUBET was
9003 				 * looked up on that interface. This ire has
9004 				 * RTF_SETSRC flag, so the source address of the
9005 				 * packet must be changed.
9006 				 */
9007 				ipha->ipha_src = fire->ire_src_addr;
9008 			}
9009 		} else {
9010 			ASSERT((connp == NULL) ||
9011 			    (connp->conn_xmit_if_ill != NULL) ||
9012 			    (connp->conn_dontroute));
9013 			/*
9014 			 * The only ways we can come here are:
9015 			 * 1) IP_XMIT_IF socket option is set
9016 			 * 2) ICMP error message generated from
9017 			 *    ip_mrtun_forward() routine and it needs
9018 			 *    to go through the specified ill.
9019 			 * 3) SO_DONTROUTE socket option is set
9020 			 * In all cases, the new ire will not be added
9021 			 * into cache table.
9022 			 */
9023 			ire_marks |= IRE_MARK_NOADD;
9024 		}
9025 
9026 		switch (ipif->ipif_net_type) {
9027 		case IRE_IF_NORESOLVER: {
9028 			/* We have what we need to build an IRE_CACHE. */
9029 			mblk_t	*res_mp;
9030 
9031 			/*
9032 			 * Create a new res_mp with the
9033 			 * IP gateway address as destination address in the
9034 			 * DLPI hdr if the physical length is exactly 4 bytes.
9035 			 */
9036 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9037 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9038 				    dst_ill->ill_phys_addr_length,
9039 				    dst_ill->ill_sap,
9040 				    dst_ill->ill_sap_length);
9041 			} else {
9042 				/* use the value set in ip_ll_subnet_defaults */
9043 				res_mp = ill_dlur_gen(NULL,
9044 				    dst_ill->ill_phys_addr_length,
9045 				    dst_ill->ill_sap,
9046 				    dst_ill->ill_sap_length);
9047 			}
9048 
9049 			if (res_mp == NULL)
9050 				break;
9051 			/*
9052 			 * The new ire inherits the IRE_OFFSUBNET flags
9053 			 * and source address, if this was requested.
9054 			 */
9055 			ire = ire_create(
9056 			    (uchar_t *)&dst,		/* dest address */
9057 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9058 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9059 			    NULL,			/* gateway address */
9060 			    NULL,
9061 			    &ipif->ipif_mtu,
9062 			    NULL,			/* Fast Path header */
9063 			    dst_ill->ill_rq,		/* recv-from queue */
9064 			    dst_ill->ill_wq,		/* send-to queue */
9065 			    IRE_CACHE,
9066 			    res_mp,
9067 			    src_ipif,
9068 			    NULL,
9069 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9070 			    (fire != NULL) ?		/* Parent handle */
9071 				fire->ire_phandle : 0,
9072 			    ihandle,			/* Interface handle */
9073 			    (fire != NULL) ?
9074 				(fire->ire_flags &
9075 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9076 			    (save_ire == NULL ? &ire_uinfo_null :
9077 				&save_ire->ire_uinfo),
9078 			    NULL,
9079 			    NULL);
9080 
9081 			freeb(res_mp);
9082 
9083 			if (ire == NULL) {
9084 				if (save_ire != NULL)
9085 					ire_refrele(save_ire);
9086 				break;
9087 			}
9088 
9089 			ire->ire_marks |= ire_marks;
9090 
9091 			/*
9092 			 * If IRE_MARK_NOADD is set then we need to convert
9093 			 * the max_fragp to a useable value now. This is
9094 			 * normally done in ire_add_v[46]. We also need to
9095 			 * associate the ire with an nce (normally would be
9096 			 * done in ip_wput_nondata()).
9097 			 *
9098 			 * Note that IRE_MARK_NOADD packets created here
9099 			 * do not have a non-null ire_mp pointer. The null
9100 			 * value of ire_bucket indicates that they were
9101 			 * never added.
9102 			 */
9103 			if (ire->ire_marks & IRE_MARK_NOADD) {
9104 				uint_t  max_frag;
9105 
9106 				max_frag = *ire->ire_max_fragp;
9107 				ire->ire_max_fragp = NULL;
9108 				ire->ire_max_frag = max_frag;
9109 
9110 				if ((ire->ire_nce = ndp_lookup_v4(
9111 				    ire_to_ill(ire),
9112 				    (ire->ire_gateway_addr != INADDR_ANY ?
9113 				    &ire->ire_gateway_addr : &ire->ire_addr),
9114 				    B_FALSE)) == NULL) {
9115 					if (save_ire != NULL)
9116 						ire_refrele(save_ire);
9117 					break;
9118 				}
9119 				ASSERT(ire->ire_nce->nce_state ==
9120 				    ND_REACHABLE);
9121 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9122 			}
9123 
9124 			/* Prevent save_ire from getting deleted */
9125 			if (save_ire != NULL) {
9126 				IRB_REFHOLD(save_ire->ire_bucket);
9127 				/* Has it been removed already ? */
9128 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9129 					IRB_REFRELE(save_ire->ire_bucket);
9130 					ire_refrele(save_ire);
9131 					break;
9132 				}
9133 			}
9134 
9135 			ire_add_then_send(q, ire, first_mp);
9136 
9137 			/* Assert that save_ire is not deleted yet. */
9138 			if (save_ire != NULL) {
9139 				ASSERT(save_ire->ire_ptpn != NULL);
9140 				IRB_REFRELE(save_ire->ire_bucket);
9141 				ire_refrele(save_ire);
9142 				save_ire = NULL;
9143 			}
9144 			if (fire != NULL) {
9145 				ire_refrele(fire);
9146 				fire = NULL;
9147 			}
9148 
9149 			/*
9150 			 * the resolution loop is re-entered if this
9151 			 * was requested through flags and if we
9152 			 * actually are in a multirouting case.
9153 			 */
9154 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9155 				boolean_t need_resolve =
9156 				    ire_multirt_need_resolve(ipha_dst,
9157 					MBLK_GETLABEL(copy_mp));
9158 				if (!need_resolve) {
9159 					MULTIRT_DEBUG_UNTAG(copy_mp);
9160 					freemsg(copy_mp);
9161 					copy_mp = NULL;
9162 				} else {
9163 					/*
9164 					 * ipif_lookup_group() calls
9165 					 * ire_lookup_multi() that uses
9166 					 * ire_ftable_lookup() to find
9167 					 * an IRE_INTERFACE for the group.
9168 					 * In the multirt case,
9169 					 * ire_lookup_multi() then invokes
9170 					 * ire_multirt_lookup() to find
9171 					 * the next resolvable ire.
9172 					 * As a result, we obtain an new
9173 					 * interface, derived from the
9174 					 * next ire.
9175 					 */
9176 					ipif_refrele(ipif);
9177 					ipif = ipif_lookup_group(ipha_dst,
9178 					    zoneid);
9179 					ip2dbg(("ip_newroute_ipif: "
9180 					    "multirt dst %08x, ipif %p\n",
9181 					    htonl(dst), (void *)ipif));
9182 					if (ipif != NULL) {
9183 						mp = copy_mp;
9184 						copy_mp = NULL;
9185 						multirt_resolve_next = B_TRUE;
9186 						continue;
9187 					} else {
9188 						freemsg(copy_mp);
9189 					}
9190 				}
9191 			}
9192 			if (ipif != NULL)
9193 				ipif_refrele(ipif);
9194 			ill_refrele(dst_ill);
9195 			ipif_refrele(src_ipif);
9196 			return;
9197 		}
9198 		case IRE_IF_RESOLVER:
9199 			/*
9200 			 * We can't build an IRE_CACHE yet, but at least
9201 			 * we found a resolver that can help.
9202 			 */
9203 			res_mp = dst_ill->ill_resolver_mp;
9204 			if (!OK_RESOLVER_MP(res_mp))
9205 				break;
9206 
9207 			/*
9208 			 * We obtain a partial IRE_CACHE which we will pass
9209 			 * along with the resolver query.  When the response
9210 			 * comes back it will be there ready for us to add.
9211 			 * The new ire inherits the IRE_OFFSUBNET flags
9212 			 * and source address, if this was requested.
9213 			 * The ire_max_frag is atomically set under the
9214 			 * irebucket lock in ire_add_v[46]. Only in the
9215 			 * case of IRE_MARK_NOADD, we set it here itself.
9216 			 */
9217 			ire = ire_create_mp(
9218 			    (uchar_t *)&dst,		/* dest address */
9219 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9220 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9221 			    NULL,			/* gateway address */
9222 			    NULL,			/* no in_src_addr */
9223 			    (ire_marks & IRE_MARK_NOADD) ?
9224 				ipif->ipif_mtu : 0,	/* max_frag */
9225 			    NULL,			/* Fast path header */
9226 			    dst_ill->ill_rq,		/* recv-from queue */
9227 			    dst_ill->ill_wq,		/* send-to queue */
9228 			    IRE_CACHE,
9229 			    NULL,	/* let ire_nce_init figure res_mp out */
9230 			    src_ipif,
9231 			    NULL,
9232 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9233 			    (fire != NULL) ?		/* Parent handle */
9234 				fire->ire_phandle : 0,
9235 			    ihandle,			/* Interface handle */
9236 			    (fire != NULL) ?		/* flags if any */
9237 				(fire->ire_flags &
9238 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9239 			    (save_ire == NULL ? &ire_uinfo_null :
9240 				&save_ire->ire_uinfo),
9241 			    NULL,
9242 			    NULL);
9243 
9244 			if (save_ire != NULL) {
9245 				ire_refrele(save_ire);
9246 				save_ire = NULL;
9247 			}
9248 			if (ire == NULL)
9249 				break;
9250 
9251 			ire->ire_marks |= ire_marks;
9252 			/*
9253 			 * Construct message chain for the resolver of the
9254 			 * form:
9255 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9256 			 *
9257 			 * NOTE : ire will be added later when the response
9258 			 * comes back from ARP. If the response does not
9259 			 * come back, ARP frees the packet. For this reason,
9260 			 * we can't REFHOLD the bucket of save_ire to prevent
9261 			 * deletions. We may not be able to REFRELE the
9262 			 * bucket if the response never comes back.
9263 			 * Thus, before adding the ire, ire_add_v4 will make
9264 			 * sure that the interface route does not get deleted.
9265 			 * This is the only case unlike ip_newroute_v6,
9266 			 * ip_newroute_ipif_v6 where we can always prevent
9267 			 * deletions because ire_add_then_send is called after
9268 			 * creating the IRE.
9269 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9270 			 * does not add this IRE into the IRE CACHE.
9271 			 */
9272 			ASSERT(ire->ire_mp != NULL);
9273 			ire->ire_mp->b_cont = first_mp;
9274 			/* Have saved_mp handy, for cleanup if canput fails */
9275 			saved_mp = mp;
9276 			mp = copyb(res_mp);
9277 			ASSERT(mp != NULL);
9278 			linkb(mp, ire->ire_mp);
9279 
9280 			/*
9281 			 * Fill in the source and dest addrs for the resolver.
9282 			 * NOTE: this depends on memory layouts imposed by
9283 			 * ill_init().
9284 			 */
9285 			areq = (areq_t *)mp->b_rptr;
9286 			addrp = (ipaddr_t *)((char *)areq +
9287 			    areq->areq_sender_addr_offset);
9288 			*addrp = ire->ire_src_addr;
9289 			addrp = (ipaddr_t *)((char *)areq +
9290 			    areq->areq_target_addr_offset);
9291 			*addrp = dst;
9292 			/* Up to the resolver. */
9293 			if (canputnext(dst_ill->ill_rq) &&
9294 			    !(dst_ill->ill_arp_closing)) {
9295 				putnext(dst_ill->ill_rq, mp);
9296 				/*
9297 				 * The response will come back in ip_wput
9298 				 * with db_type IRE_DB_TYPE.
9299 				 */
9300 			} else {
9301 				mp->b_cont = NULL;
9302 				freeb(mp); /* areq */
9303 				ire_delete(ire); /* ire_mp */
9304 				saved_mp->b_next = NULL;
9305 				saved_mp->b_prev = NULL;
9306 				freemsg(first_mp); /* pkt */
9307 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9308 			}
9309 
9310 			if (fire != NULL) {
9311 				ire_refrele(fire);
9312 				fire = NULL;
9313 			}
9314 
9315 
9316 			/*
9317 			 * The resolution loop is re-entered if this was
9318 			 * requested through flags and we actually are
9319 			 * in a multirouting case.
9320 			 */
9321 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9322 				boolean_t need_resolve =
9323 				    ire_multirt_need_resolve(ipha_dst,
9324 					MBLK_GETLABEL(copy_mp));
9325 				if (!need_resolve) {
9326 					MULTIRT_DEBUG_UNTAG(copy_mp);
9327 					freemsg(copy_mp);
9328 					copy_mp = NULL;
9329 				} else {
9330 					/*
9331 					 * ipif_lookup_group() calls
9332 					 * ire_lookup_multi() that uses
9333 					 * ire_ftable_lookup() to find
9334 					 * an IRE_INTERFACE for the group.
9335 					 * In the multirt case,
9336 					 * ire_lookup_multi() then invokes
9337 					 * ire_multirt_lookup() to find
9338 					 * the next resolvable ire.
9339 					 * As a result, we obtain an new
9340 					 * interface, derived from the
9341 					 * next ire.
9342 					 */
9343 					ipif_refrele(ipif);
9344 					ipif = ipif_lookup_group(ipha_dst,
9345 					    zoneid);
9346 					if (ipif != NULL) {
9347 						mp = copy_mp;
9348 						copy_mp = NULL;
9349 						multirt_resolve_next = B_TRUE;
9350 						continue;
9351 					} else {
9352 						freemsg(copy_mp);
9353 					}
9354 				}
9355 			}
9356 			if (ipif != NULL)
9357 				ipif_refrele(ipif);
9358 			ill_refrele(dst_ill);
9359 			ipif_refrele(src_ipif);
9360 			return;
9361 		default:
9362 			break;
9363 		}
9364 	} while (multirt_resolve_next);
9365 
9366 err_ret:
9367 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9368 	if (fire != NULL)
9369 		ire_refrele(fire);
9370 	ipif_refrele(ipif);
9371 	/* Did this packet originate externally? */
9372 	if (dst_ill != NULL)
9373 		ill_refrele(dst_ill);
9374 	if (src_ipif != NULL)
9375 		ipif_refrele(src_ipif);
9376 	if (mp->b_prev || mp->b_next) {
9377 		mp->b_next = NULL;
9378 		mp->b_prev = NULL;
9379 	} else {
9380 		/*
9381 		 * Since ip_wput() isn't close to finished, we fill
9382 		 * in enough of the header for credible error reporting.
9383 		 */
9384 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9385 			/* Failed */
9386 			freemsg(first_mp);
9387 			if (ire != NULL)
9388 				ire_refrele(ire);
9389 			return;
9390 		}
9391 	}
9392 	/*
9393 	 * At this point we will have ire only if RTF_BLACKHOLE
9394 	 * or RTF_REJECT flags are set on the IRE. It will not
9395 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9396 	 */
9397 	if (ire != NULL) {
9398 		if (ire->ire_flags & RTF_BLACKHOLE) {
9399 			ire_refrele(ire);
9400 			freemsg(first_mp);
9401 			return;
9402 		}
9403 		ire_refrele(ire);
9404 	}
9405 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9406 }
9407 
9408 /* Name/Value Table Lookup Routine */
9409 char *
9410 ip_nv_lookup(nv_t *nv, int value)
9411 {
9412 	if (!nv)
9413 		return (NULL);
9414 	for (; nv->nv_name; nv++) {
9415 		if (nv->nv_value == value)
9416 			return (nv->nv_name);
9417 	}
9418 	return ("unknown");
9419 }
9420 
9421 /*
9422  * one day it can be patched to 1 from /etc/system for machines that have few
9423  * fast network interfaces feeding multiple cpus.
9424  */
9425 int ill_stream_putlocks = 0;
9426 
9427 /*
9428  * This is a module open, i.e. this is a control stream for access
9429  * to a DLPI device.  We allocate an ill_t as the instance data in
9430  * this case.
9431  */
9432 int
9433 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9434 {
9435 	uint32_t mem_cnt;
9436 	uint32_t cpu_cnt;
9437 	uint32_t min_cnt;
9438 	pgcnt_t mem_avail;
9439 	ill_t	*ill;
9440 	int	err;
9441 
9442 	/*
9443 	 * Prevent unprivileged processes from pushing IP so that
9444 	 * they can't send raw IP.
9445 	 */
9446 	if (secpolicy_net_rawaccess(credp) != 0)
9447 		return (EPERM);
9448 
9449 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9450 	q->q_ptr = WR(q)->q_ptr = ill;
9451 
9452 	/*
9453 	 * ill_init initializes the ill fields and then sends down
9454 	 * down a DL_INFO_REQ after calling qprocson.
9455 	 */
9456 	err = ill_init(q, ill);
9457 	if (err != 0) {
9458 		mi_free(ill);
9459 		q->q_ptr = NULL;
9460 		WR(q)->q_ptr = NULL;
9461 		return (err);
9462 	}
9463 
9464 	/* ill_init initializes the ipsq marking this thread as writer */
9465 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9466 	/* Wait for the DL_INFO_ACK */
9467 	mutex_enter(&ill->ill_lock);
9468 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9469 		/*
9470 		 * Return value of 0 indicates a pending signal.
9471 		 */
9472 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9473 		if (err == 0) {
9474 			mutex_exit(&ill->ill_lock);
9475 			(void) ip_close(q, 0);
9476 			return (EINTR);
9477 		}
9478 	}
9479 	mutex_exit(&ill->ill_lock);
9480 
9481 	/*
9482 	 * ip_rput_other could have set an error  in ill_error on
9483 	 * receipt of M_ERROR.
9484 	 */
9485 
9486 	err = ill->ill_error;
9487 	if (err != 0) {
9488 		(void) ip_close(q, 0);
9489 		return (err);
9490 	}
9491 
9492 	/*
9493 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9494 	 * size and the cpu speed of the machine. This is upper
9495 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9496 	 * and is lower bounded by the compile time value of
9497 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9498 	 * ip6_ire_max_bucket_cnt.
9499 	 */
9500 	mem_avail = kmem_avail();
9501 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9502 	    ip_cache_table_size / sizeof (ire_t);
9503 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9504 
9505 	min_cnt = MIN(cpu_cnt, mem_cnt);
9506 	if (min_cnt < ip_ire_min_bucket_cnt)
9507 		min_cnt = ip_ire_min_bucket_cnt;
9508 	if (ip_ire_max_bucket_cnt > min_cnt) {
9509 		ip_ire_max_bucket_cnt = min_cnt;
9510 	}
9511 
9512 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9513 	    ip6_cache_table_size / sizeof (ire_t);
9514 	min_cnt = MIN(cpu_cnt, mem_cnt);
9515 	if (min_cnt < ip6_ire_min_bucket_cnt)
9516 		min_cnt = ip6_ire_min_bucket_cnt;
9517 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9518 		ip6_ire_max_bucket_cnt = min_cnt;
9519 	}
9520 
9521 	ill->ill_credp = credp;
9522 	crhold(credp);
9523 
9524 	mutex_enter(&ip_mi_lock);
9525 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9526 	mutex_exit(&ip_mi_lock);
9527 	if (err) {
9528 		(void) ip_close(q, 0);
9529 		return (err);
9530 	}
9531 	return (0);
9532 }
9533 
9534 /* IP open routine. */
9535 int
9536 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9537 {
9538 	conn_t 		*connp;
9539 	major_t		maj;
9540 
9541 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9542 
9543 	/* Allow reopen. */
9544 	if (q->q_ptr != NULL)
9545 		return (0);
9546 
9547 	if (sflag & MODOPEN) {
9548 		/* This is a module open */
9549 		return (ip_modopen(q, devp, flag, sflag, credp));
9550 	}
9551 
9552 	/*
9553 	 * We are opening as a device. This is an IP client stream, and we
9554 	 * allocate an conn_t as the instance data.
9555 	 */
9556 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9557 	connp->conn_upq = q;
9558 	q->q_ptr = WR(q)->q_ptr = connp;
9559 
9560 	if (flag & SO_SOCKSTR)
9561 		connp->conn_flags |= IPCL_SOCKET;
9562 
9563 	/* Minor tells us which /dev entry was opened */
9564 	if (geteminor(*devp) == IPV6_MINOR) {
9565 		connp->conn_flags |= IPCL_ISV6;
9566 		connp->conn_af_isv6 = B_TRUE;
9567 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9568 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9569 	} else {
9570 		connp->conn_af_isv6 = B_FALSE;
9571 		connp->conn_pkt_isv6 = B_FALSE;
9572 	}
9573 
9574 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9575 		q->q_ptr = WR(q)->q_ptr = NULL;
9576 		CONN_DEC_REF(connp);
9577 		return (EBUSY);
9578 	}
9579 
9580 	maj = getemajor(*devp);
9581 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9582 
9583 	/*
9584 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9585 	 */
9586 	connp->conn_cred = credp;
9587 	crhold(connp->conn_cred);
9588 
9589 	/*
9590 	 * If the caller has the process-wide flag set, then default to MAC
9591 	 * exempt mode.  This allows read-down to unlabeled hosts.
9592 	 */
9593 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9594 		connp->conn_mac_exempt = B_TRUE;
9595 
9596 	connp->conn_zoneid = getzoneid();
9597 
9598 	/*
9599 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9600 	 * administrative ops.  In these cases, we just need a normal conn_t
9601 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9602 	 * an error will be returned.
9603 	 */
9604 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9605 		connp->conn_rq = q;
9606 		connp->conn_wq = WR(q);
9607 	} else {
9608 		connp->conn_ulp = IPPROTO_SCTP;
9609 		connp->conn_rq = connp->conn_wq = NULL;
9610 	}
9611 	/* Non-zero default values */
9612 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9613 
9614 	/*
9615 	 * Make the conn globally visible to walkers
9616 	 */
9617 	mutex_enter(&connp->conn_lock);
9618 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9619 	mutex_exit(&connp->conn_lock);
9620 	ASSERT(connp->conn_ref == 1);
9621 
9622 	qprocson(q);
9623 
9624 	return (0);
9625 }
9626 
9627 /*
9628  * Change q_qinfo based on the value of isv6.
9629  * This can not called on an ill queue.
9630  * Note that there is no race since either q_qinfo works for conn queues - it
9631  * is just an optimization to enter the best wput routine directly.
9632  */
9633 void
9634 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9635 {
9636 	ASSERT(q->q_flag & QREADR);
9637 	ASSERT(WR(q)->q_next == NULL);
9638 	ASSERT(q->q_ptr != NULL);
9639 
9640 	if (minor == IPV6_MINOR)  {
9641 		if (bump_mib)
9642 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9643 		q->q_qinfo = &rinit_ipv6;
9644 		WR(q)->q_qinfo = &winit_ipv6;
9645 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9646 	} else {
9647 		if (bump_mib)
9648 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9649 		q->q_qinfo = &iprinit;
9650 		WR(q)->q_qinfo = &ipwinit;
9651 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9652 	}
9653 
9654 }
9655 
9656 /*
9657  * See if IPsec needs loading because of the options in mp.
9658  */
9659 static boolean_t
9660 ipsec_opt_present(mblk_t *mp)
9661 {
9662 	uint8_t *optcp, *next_optcp, *opt_endcp;
9663 	struct opthdr *opt;
9664 	struct T_opthdr *topt;
9665 	int opthdr_len;
9666 	t_uscalar_t optname, optlevel;
9667 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9668 	ipsec_req_t *ipsr;
9669 
9670 	/*
9671 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9672 	 * return TRUE.
9673 	 */
9674 
9675 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9676 	opt_endcp = optcp + tor->OPT_length;
9677 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9678 		opthdr_len = sizeof (struct T_opthdr);
9679 	} else {		/* O_OPTMGMT_REQ */
9680 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9681 		opthdr_len = sizeof (struct opthdr);
9682 	}
9683 	for (; optcp < opt_endcp; optcp = next_optcp) {
9684 		if (optcp + opthdr_len > opt_endcp)
9685 			return (B_FALSE);	/* Not enough option header. */
9686 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9687 			topt = (struct T_opthdr *)optcp;
9688 			optlevel = topt->level;
9689 			optname = topt->name;
9690 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9691 		} else {
9692 			opt = (struct opthdr *)optcp;
9693 			optlevel = opt->level;
9694 			optname = opt->name;
9695 			next_optcp = optcp + opthdr_len +
9696 			    _TPI_ALIGN_OPT(opt->len);
9697 		}
9698 		if ((next_optcp < optcp) || /* wraparound pointer space */
9699 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9700 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9701 			return (B_FALSE); /* bad option buffer */
9702 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9703 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9704 			/*
9705 			 * Check to see if it's an all-bypass or all-zeroes
9706 			 * IPsec request.  Don't bother loading IPsec if
9707 			 * the socket doesn't want to use it.  (A good example
9708 			 * is a bypass request.)
9709 			 *
9710 			 * Basically, if any of the non-NEVER bits are set,
9711 			 * load IPsec.
9712 			 */
9713 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9714 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9715 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9716 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9717 			    != 0)
9718 				return (B_TRUE);
9719 		}
9720 	}
9721 	return (B_FALSE);
9722 }
9723 
9724 /*
9725  * If conn is is waiting for ipsec to finish loading, kick it.
9726  */
9727 /* ARGSUSED */
9728 static void
9729 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9730 {
9731 	t_scalar_t	optreq_prim;
9732 	mblk_t		*mp;
9733 	cred_t		*cr;
9734 	int		err = 0;
9735 
9736 	/*
9737 	 * This function is called, after ipsec loading is complete.
9738 	 * Since IP checks exclusively and atomically (i.e it prevents
9739 	 * ipsec load from completing until ip_optcom_req completes)
9740 	 * whether ipsec load is complete, there cannot be a race with IP
9741 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9742 	 */
9743 	mutex_enter(&connp->conn_lock);
9744 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9745 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9746 		mp = connp->conn_ipsec_opt_mp;
9747 		connp->conn_ipsec_opt_mp = NULL;
9748 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9749 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9750 		mutex_exit(&connp->conn_lock);
9751 
9752 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9753 
9754 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9755 		if (optreq_prim == T_OPTMGMT_REQ) {
9756 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9757 			    &ip_opt_obj);
9758 		} else {
9759 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9760 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9761 			    &ip_opt_obj);
9762 		}
9763 		if (err != EINPROGRESS)
9764 			CONN_OPER_PENDING_DONE(connp);
9765 		return;
9766 	}
9767 	mutex_exit(&connp->conn_lock);
9768 }
9769 
9770 /*
9771  * Called from the ipsec_loader thread, outside any perimeter, to tell
9772  * ip qenable any of the queues waiting for the ipsec loader to
9773  * complete.
9774  *
9775  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9776  * are done with this lock held, so it's guaranteed that none of the
9777  * links will change along the way.
9778  */
9779 void
9780 ip_ipsec_load_complete()
9781 {
9782 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9783 }
9784 
9785 /*
9786  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9787  * determines the grp on which it has to become exclusive, queues the mp
9788  * and sq draining restarts the optmgmt
9789  */
9790 static boolean_t
9791 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9792 {
9793 	conn_t *connp;
9794 
9795 	/*
9796 	 * Take IPsec requests and treat them special.
9797 	 */
9798 	if (ipsec_opt_present(mp)) {
9799 		/* First check if IPsec is loaded. */
9800 		mutex_enter(&ipsec_loader_lock);
9801 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9802 			mutex_exit(&ipsec_loader_lock);
9803 			return (B_FALSE);
9804 		}
9805 		connp = Q_TO_CONN(q);
9806 		mutex_enter(&connp->conn_lock);
9807 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9808 
9809 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9810 		connp->conn_ipsec_opt_mp = mp;
9811 		mutex_exit(&connp->conn_lock);
9812 		mutex_exit(&ipsec_loader_lock);
9813 
9814 		ipsec_loader_loadnow();
9815 		return (B_TRUE);
9816 	}
9817 	return (B_FALSE);
9818 }
9819 
9820 /*
9821  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9822  * all of them are copied to the conn_t. If the req is "zero", the policy is
9823  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9824  * fields.
9825  * We keep only the latest setting of the policy and thus policy setting
9826  * is not incremental/cumulative.
9827  *
9828  * Requests to set policies with multiple alternative actions will
9829  * go through a different API.
9830  */
9831 int
9832 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9833 {
9834 	uint_t ah_req = 0;
9835 	uint_t esp_req = 0;
9836 	uint_t se_req = 0;
9837 	ipsec_selkey_t sel;
9838 	ipsec_act_t *actp = NULL;
9839 	uint_t nact;
9840 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9841 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9842 	ipsec_policy_root_t *pr;
9843 	ipsec_policy_head_t *ph;
9844 	int fam;
9845 	boolean_t is_pol_reset;
9846 	int error = 0;
9847 
9848 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9849 
9850 	/*
9851 	 * The IP_SEC_OPT option does not allow variable length parameters,
9852 	 * hence a request cannot be NULL.
9853 	 */
9854 	if (req == NULL)
9855 		return (EINVAL);
9856 
9857 	ah_req = req->ipsr_ah_req;
9858 	esp_req = req->ipsr_esp_req;
9859 	se_req = req->ipsr_self_encap_req;
9860 
9861 	/*
9862 	 * Are we dealing with a request to reset the policy (i.e.
9863 	 * zero requests).
9864 	 */
9865 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9866 	    (esp_req & REQ_MASK) == 0 &&
9867 	    (se_req & REQ_MASK) == 0);
9868 
9869 	if (!is_pol_reset) {
9870 		/*
9871 		 * If we couldn't load IPsec, fail with "protocol
9872 		 * not supported".
9873 		 * IPsec may not have been loaded for a request with zero
9874 		 * policies, so we don't fail in this case.
9875 		 */
9876 		mutex_enter(&ipsec_loader_lock);
9877 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9878 			mutex_exit(&ipsec_loader_lock);
9879 			return (EPROTONOSUPPORT);
9880 		}
9881 		mutex_exit(&ipsec_loader_lock);
9882 
9883 		/*
9884 		 * Test for valid requests. Invalid algorithms
9885 		 * need to be tested by IPSEC code because new
9886 		 * algorithms can be added dynamically.
9887 		 */
9888 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9889 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9890 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9891 			return (EINVAL);
9892 		}
9893 
9894 		/*
9895 		 * Only privileged users can issue these
9896 		 * requests.
9897 		 */
9898 		if (((ah_req & IPSEC_PREF_NEVER) ||
9899 		    (esp_req & IPSEC_PREF_NEVER) ||
9900 		    (se_req & IPSEC_PREF_NEVER)) &&
9901 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9902 			return (EPERM);
9903 		}
9904 
9905 		/*
9906 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9907 		 * are mutually exclusive.
9908 		 */
9909 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9910 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9911 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9912 			/* Both of them are set */
9913 			return (EINVAL);
9914 		}
9915 	}
9916 
9917 	mutex_enter(&connp->conn_lock);
9918 
9919 	/*
9920 	 * If we have already cached policies in ip_bind_connected*(), don't
9921 	 * let them change now. We cache policies for connections
9922 	 * whose src,dst [addr, port] is known.  The exception to this is
9923 	 * tunnels.  Tunnels are allowed to change policies after having
9924 	 * become fully bound.
9925 	 */
9926 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
9927 		mutex_exit(&connp->conn_lock);
9928 		return (EINVAL);
9929 	}
9930 
9931 	/*
9932 	 * We have a zero policies, reset the connection policy if already
9933 	 * set. This will cause the connection to inherit the
9934 	 * global policy, if any.
9935 	 */
9936 	if (is_pol_reset) {
9937 		if (connp->conn_policy != NULL) {
9938 			IPPH_REFRELE(connp->conn_policy);
9939 			connp->conn_policy = NULL;
9940 		}
9941 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
9942 		connp->conn_in_enforce_policy = B_FALSE;
9943 		connp->conn_out_enforce_policy = B_FALSE;
9944 		mutex_exit(&connp->conn_lock);
9945 		return (0);
9946 	}
9947 
9948 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
9949 	if (ph == NULL)
9950 		goto enomem;
9951 
9952 	ipsec_actvec_from_req(req, &actp, &nact);
9953 	if (actp == NULL)
9954 		goto enomem;
9955 
9956 	/*
9957 	 * Always allocate IPv4 policy entries, since they can also
9958 	 * apply to ipv6 sockets being used in ipv4-compat mode.
9959 	 */
9960 	bzero(&sel, sizeof (sel));
9961 	sel.ipsl_valid = IPSL_IPV4;
9962 
9963 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9964 	if (pin4 == NULL)
9965 		goto enomem;
9966 
9967 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9968 	if (pout4 == NULL)
9969 		goto enomem;
9970 
9971 	if (connp->conn_pkt_isv6) {
9972 		/*
9973 		 * We're looking at a v6 socket, also allocate the
9974 		 * v6-specific entries...
9975 		 */
9976 		sel.ipsl_valid = IPSL_IPV6;
9977 		pin6 = ipsec_policy_create(&sel, actp, nact,
9978 		    IPSEC_PRIO_SOCKET);
9979 		if (pin6 == NULL)
9980 			goto enomem;
9981 
9982 		pout6 = ipsec_policy_create(&sel, actp, nact,
9983 		    IPSEC_PRIO_SOCKET);
9984 		if (pout6 == NULL)
9985 			goto enomem;
9986 
9987 		/*
9988 		 * .. and file them away in the right place.
9989 		 */
9990 		fam = IPSEC_AF_V6;
9991 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9992 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
9993 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
9994 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9995 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
9996 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
9997 	}
9998 
9999 	ipsec_actvec_free(actp, nact);
10000 
10001 	/*
10002 	 * File the v4 policies.
10003 	 */
10004 	fam = IPSEC_AF_V4;
10005 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10006 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10007 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10008 
10009 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10010 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10011 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10012 
10013 	/*
10014 	 * If the requests need security, set enforce_policy.
10015 	 * If the requests are IPSEC_PREF_NEVER, one should
10016 	 * still set conn_out_enforce_policy so that an ipsec_out
10017 	 * gets attached in ip_wput. This is needed so that
10018 	 * for connections that we don't cache policy in ip_bind,
10019 	 * if global policy matches in ip_wput_attach_policy, we
10020 	 * don't wrongly inherit global policy. Similarly, we need
10021 	 * to set conn_in_enforce_policy also so that we don't verify
10022 	 * policy wrongly.
10023 	 */
10024 	if ((ah_req & REQ_MASK) != 0 ||
10025 	    (esp_req & REQ_MASK) != 0 ||
10026 	    (se_req & REQ_MASK) != 0) {
10027 		connp->conn_in_enforce_policy = B_TRUE;
10028 		connp->conn_out_enforce_policy = B_TRUE;
10029 		connp->conn_flags |= IPCL_CHECK_POLICY;
10030 	}
10031 
10032 	/*
10033 	 * Tunnels are allowed to set policy after having been fully bound.
10034 	 * If that's the case, cache policy here.
10035 	 */
10036 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
10037 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
10038 
10039 	mutex_exit(&connp->conn_lock);
10040 	return (error);
10041 #undef REQ_MASK
10042 
10043 	/*
10044 	 * Common memory-allocation-failure exit path.
10045 	 */
10046 enomem:
10047 	mutex_exit(&connp->conn_lock);
10048 	if (actp != NULL)
10049 		ipsec_actvec_free(actp, nact);
10050 	if (pin4 != NULL)
10051 		IPPOL_REFRELE(pin4);
10052 	if (pout4 != NULL)
10053 		IPPOL_REFRELE(pout4);
10054 	if (pin6 != NULL)
10055 		IPPOL_REFRELE(pin6);
10056 	if (pout6 != NULL)
10057 		IPPOL_REFRELE(pout6);
10058 	return (ENOMEM);
10059 }
10060 
10061 /*
10062  * Only for options that pass in an IP addr. Currently only V4 options
10063  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10064  * So this function assumes level is IPPROTO_IP
10065  */
10066 int
10067 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10068     mblk_t *first_mp)
10069 {
10070 	ipif_t *ipif = NULL;
10071 	int error;
10072 	ill_t *ill;
10073 	int zoneid;
10074 
10075 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10076 
10077 	if (addr != INADDR_ANY || checkonly) {
10078 		ASSERT(connp != NULL);
10079 		zoneid = IPCL_ZONEID(connp);
10080 		if (option == IP_NEXTHOP) {
10081 			ipif = ipif_lookup_onlink_addr(addr, zoneid);
10082 		} else {
10083 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10084 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10085 			    &error);
10086 		}
10087 		if (ipif == NULL) {
10088 			if (error == EINPROGRESS)
10089 				return (error);
10090 			else if ((option == IP_MULTICAST_IF) ||
10091 			    (option == IP_NEXTHOP))
10092 				return (EHOSTUNREACH);
10093 			else
10094 				return (EINVAL);
10095 		} else if (checkonly) {
10096 			if (option == IP_MULTICAST_IF) {
10097 				ill = ipif->ipif_ill;
10098 				/* not supported by the virtual network iface */
10099 				if (IS_VNI(ill)) {
10100 					ipif_refrele(ipif);
10101 					return (EINVAL);
10102 				}
10103 			}
10104 			ipif_refrele(ipif);
10105 			return (0);
10106 		}
10107 		ill = ipif->ipif_ill;
10108 		mutex_enter(&connp->conn_lock);
10109 		mutex_enter(&ill->ill_lock);
10110 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10111 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10112 			mutex_exit(&ill->ill_lock);
10113 			mutex_exit(&connp->conn_lock);
10114 			ipif_refrele(ipif);
10115 			return (option == IP_MULTICAST_IF ?
10116 			    EHOSTUNREACH : EINVAL);
10117 		}
10118 	} else {
10119 		mutex_enter(&connp->conn_lock);
10120 	}
10121 
10122 	/* None of the options below are supported on the VNI */
10123 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10124 		mutex_exit(&ill->ill_lock);
10125 		mutex_exit(&connp->conn_lock);
10126 		ipif_refrele(ipif);
10127 		return (EINVAL);
10128 	}
10129 
10130 	switch (option) {
10131 	case IP_DONTFAILOVER_IF:
10132 		/*
10133 		 * This option is used by in.mpathd to ensure
10134 		 * that IPMP probe packets only go out on the
10135 		 * test interfaces. in.mpathd sets this option
10136 		 * on the non-failover interfaces.
10137 		 * For backward compatibility, this option
10138 		 * implicitly sets IP_MULTICAST_IF, as used
10139 		 * be done in bind(), so that ip_wput gets
10140 		 * this ipif to send mcast packets.
10141 		 */
10142 		if (ipif != NULL) {
10143 			ASSERT(addr != INADDR_ANY);
10144 			connp->conn_nofailover_ill = ipif->ipif_ill;
10145 			connp->conn_multicast_ipif = ipif;
10146 		} else {
10147 			ASSERT(addr == INADDR_ANY);
10148 			connp->conn_nofailover_ill = NULL;
10149 			connp->conn_multicast_ipif = NULL;
10150 		}
10151 		break;
10152 
10153 	case IP_MULTICAST_IF:
10154 		connp->conn_multicast_ipif = ipif;
10155 		break;
10156 	case IP_NEXTHOP:
10157 		connp->conn_nexthop_v4 = addr;
10158 		connp->conn_nexthop_set = B_TRUE;
10159 		break;
10160 	}
10161 
10162 	if (ipif != NULL) {
10163 		mutex_exit(&ill->ill_lock);
10164 		mutex_exit(&connp->conn_lock);
10165 		ipif_refrele(ipif);
10166 		return (0);
10167 	}
10168 	mutex_exit(&connp->conn_lock);
10169 	/* We succeded in cleared the option */
10170 	return (0);
10171 }
10172 
10173 /*
10174  * For options that pass in an ifindex specifying the ill. V6 options always
10175  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10176  */
10177 int
10178 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10179     int level, int option, mblk_t *first_mp)
10180 {
10181 	ill_t *ill = NULL;
10182 	int error = 0;
10183 
10184 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10185 	if (ifindex != 0) {
10186 		ASSERT(connp != NULL);
10187 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10188 		    first_mp, ip_restart_optmgmt, &error);
10189 		if (ill != NULL) {
10190 			if (checkonly) {
10191 				/* not supported by the virtual network iface */
10192 				if (IS_VNI(ill)) {
10193 					ill_refrele(ill);
10194 					return (EINVAL);
10195 				}
10196 				ill_refrele(ill);
10197 				return (0);
10198 			}
10199 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10200 			    0, NULL)) {
10201 				ill_refrele(ill);
10202 				ill = NULL;
10203 				mutex_enter(&connp->conn_lock);
10204 				goto setit;
10205 			}
10206 			mutex_enter(&connp->conn_lock);
10207 			mutex_enter(&ill->ill_lock);
10208 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10209 				mutex_exit(&ill->ill_lock);
10210 				mutex_exit(&connp->conn_lock);
10211 				ill_refrele(ill);
10212 				ill = NULL;
10213 				mutex_enter(&connp->conn_lock);
10214 			}
10215 			goto setit;
10216 		} else if (error == EINPROGRESS) {
10217 			return (error);
10218 		} else {
10219 			error = 0;
10220 		}
10221 	}
10222 	mutex_enter(&connp->conn_lock);
10223 setit:
10224 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10225 
10226 	/*
10227 	 * The options below assume that the ILL (if any) transmits and/or
10228 	 * receives traffic. Neither of which is true for the virtual network
10229 	 * interface, so fail setting these on a VNI.
10230 	 */
10231 	if (IS_VNI(ill)) {
10232 		ASSERT(ill != NULL);
10233 		mutex_exit(&ill->ill_lock);
10234 		mutex_exit(&connp->conn_lock);
10235 		ill_refrele(ill);
10236 		return (EINVAL);
10237 	}
10238 
10239 	if (level == IPPROTO_IP) {
10240 		switch (option) {
10241 		case IP_BOUND_IF:
10242 			connp->conn_incoming_ill = ill;
10243 			connp->conn_outgoing_ill = ill;
10244 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10245 			    0 : ifindex;
10246 			break;
10247 
10248 		case IP_XMIT_IF:
10249 			/*
10250 			 * Similar to IP_BOUND_IF, but this only
10251 			 * determines the outgoing interface for
10252 			 * unicast packets. Also no IRE_CACHE entry
10253 			 * is added for the destination of the
10254 			 * outgoing packets. This feature is needed
10255 			 * for mobile IP.
10256 			 */
10257 			connp->conn_xmit_if_ill = ill;
10258 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10259 			    0 : ifindex;
10260 			break;
10261 
10262 		case IP_MULTICAST_IF:
10263 			/*
10264 			 * This option is an internal special. The socket
10265 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10266 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10267 			 * specifies an ifindex and we try first on V6 ill's.
10268 			 * If we don't find one, we they try using on v4 ill's
10269 			 * intenally and we come here.
10270 			 */
10271 			if (!checkonly && ill != NULL) {
10272 				ipif_t	*ipif;
10273 				ipif = ill->ill_ipif;
10274 
10275 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10276 					mutex_exit(&ill->ill_lock);
10277 					mutex_exit(&connp->conn_lock);
10278 					ill_refrele(ill);
10279 					ill = NULL;
10280 					mutex_enter(&connp->conn_lock);
10281 				} else {
10282 					connp->conn_multicast_ipif = ipif;
10283 				}
10284 			}
10285 			break;
10286 		}
10287 	} else {
10288 		switch (option) {
10289 		case IPV6_BOUND_IF:
10290 			connp->conn_incoming_ill = ill;
10291 			connp->conn_outgoing_ill = ill;
10292 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10293 			    0 : ifindex;
10294 			break;
10295 
10296 		case IPV6_BOUND_PIF:
10297 			/*
10298 			 * Limit all transmit to this ill.
10299 			 * Unlike IPV6_BOUND_IF, using this option
10300 			 * prevents load spreading and failover from
10301 			 * happening when the interface is part of the
10302 			 * group. That's why we don't need to remember
10303 			 * the ifindex in orig_bound_ifindex as in
10304 			 * IPV6_BOUND_IF.
10305 			 */
10306 			connp->conn_outgoing_pill = ill;
10307 			break;
10308 
10309 		case IPV6_DONTFAILOVER_IF:
10310 			/*
10311 			 * This option is used by in.mpathd to ensure
10312 			 * that IPMP probe packets only go out on the
10313 			 * test interfaces. in.mpathd sets this option
10314 			 * on the non-failover interfaces.
10315 			 */
10316 			connp->conn_nofailover_ill = ill;
10317 			/*
10318 			 * For backward compatibility, this option
10319 			 * implicitly sets ip_multicast_ill as used in
10320 			 * IP_MULTICAST_IF so that ip_wput gets
10321 			 * this ipif to send mcast packets.
10322 			 */
10323 			connp->conn_multicast_ill = ill;
10324 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10325 			    0 : ifindex;
10326 			break;
10327 
10328 		case IPV6_MULTICAST_IF:
10329 			/*
10330 			 * Set conn_multicast_ill to be the IPv6 ill.
10331 			 * Set conn_multicast_ipif to be an IPv4 ipif
10332 			 * for ifindex to make IPv4 mapped addresses
10333 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10334 			 * Even if no IPv6 ill exists for the ifindex
10335 			 * we need to check for an IPv4 ifindex in order
10336 			 * for this to work with mapped addresses. In that
10337 			 * case only set conn_multicast_ipif.
10338 			 */
10339 			if (!checkonly) {
10340 				if (ifindex == 0) {
10341 					connp->conn_multicast_ill = NULL;
10342 					connp->conn_orig_multicast_ifindex = 0;
10343 					connp->conn_multicast_ipif = NULL;
10344 				} else if (ill != NULL) {
10345 					connp->conn_multicast_ill = ill;
10346 					connp->conn_orig_multicast_ifindex =
10347 					    ifindex;
10348 				}
10349 			}
10350 			break;
10351 		}
10352 	}
10353 
10354 	if (ill != NULL) {
10355 		mutex_exit(&ill->ill_lock);
10356 		mutex_exit(&connp->conn_lock);
10357 		ill_refrele(ill);
10358 		return (0);
10359 	}
10360 	mutex_exit(&connp->conn_lock);
10361 	/*
10362 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10363 	 * locate the ill and could not set the option (ifindex != 0)
10364 	 */
10365 	return (ifindex == 0 ? 0 : EINVAL);
10366 }
10367 
10368 /* This routine sets socket options. */
10369 /* ARGSUSED */
10370 int
10371 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10372     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10373     void *dummy, cred_t *cr, mblk_t *first_mp)
10374 {
10375 	int		*i1 = (int *)invalp;
10376 	conn_t		*connp = Q_TO_CONN(q);
10377 	int		error = 0;
10378 	boolean_t	checkonly;
10379 	ire_t		*ire;
10380 	boolean_t	found;
10381 
10382 	switch (optset_context) {
10383 
10384 	case SETFN_OPTCOM_CHECKONLY:
10385 		checkonly = B_TRUE;
10386 		/*
10387 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10388 		 * inlen != 0 implies value supplied and
10389 		 * 	we have to "pretend" to set it.
10390 		 * inlen == 0 implies that there is no
10391 		 * 	value part in T_CHECK request and just validation
10392 		 * done elsewhere should be enough, we just return here.
10393 		 */
10394 		if (inlen == 0) {
10395 			*outlenp = 0;
10396 			return (0);
10397 		}
10398 		break;
10399 	case SETFN_OPTCOM_NEGOTIATE:
10400 	case SETFN_UD_NEGOTIATE:
10401 	case SETFN_CONN_NEGOTIATE:
10402 		checkonly = B_FALSE;
10403 		break;
10404 	default:
10405 		/*
10406 		 * We should never get here
10407 		 */
10408 		*outlenp = 0;
10409 		return (EINVAL);
10410 	}
10411 
10412 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10413 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10414 
10415 	/*
10416 	 * For fixed length options, no sanity check
10417 	 * of passed in length is done. It is assumed *_optcom_req()
10418 	 * routines do the right thing.
10419 	 */
10420 
10421 	switch (level) {
10422 	case SOL_SOCKET:
10423 		/*
10424 		 * conn_lock protects the bitfields, and is used to
10425 		 * set the fields atomically.
10426 		 */
10427 		switch (name) {
10428 		case SO_BROADCAST:
10429 			if (!checkonly) {
10430 				/* TODO: use value someplace? */
10431 				mutex_enter(&connp->conn_lock);
10432 				connp->conn_broadcast = *i1 ? 1 : 0;
10433 				mutex_exit(&connp->conn_lock);
10434 			}
10435 			break;	/* goto sizeof (int) option return */
10436 		case SO_USELOOPBACK:
10437 			if (!checkonly) {
10438 				/* TODO: use value someplace? */
10439 				mutex_enter(&connp->conn_lock);
10440 				connp->conn_loopback = *i1 ? 1 : 0;
10441 				mutex_exit(&connp->conn_lock);
10442 			}
10443 			break;	/* goto sizeof (int) option return */
10444 		case SO_DONTROUTE:
10445 			if (!checkonly) {
10446 				mutex_enter(&connp->conn_lock);
10447 				connp->conn_dontroute = *i1 ? 1 : 0;
10448 				mutex_exit(&connp->conn_lock);
10449 			}
10450 			break;	/* goto sizeof (int) option return */
10451 		case SO_REUSEADDR:
10452 			if (!checkonly) {
10453 				mutex_enter(&connp->conn_lock);
10454 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10455 				mutex_exit(&connp->conn_lock);
10456 			}
10457 			break;	/* goto sizeof (int) option return */
10458 		case SO_PROTOTYPE:
10459 			if (!checkonly) {
10460 				mutex_enter(&connp->conn_lock);
10461 				connp->conn_proto = *i1;
10462 				mutex_exit(&connp->conn_lock);
10463 			}
10464 			break;	/* goto sizeof (int) option return */
10465 		case SO_ALLZONES:
10466 			if (!checkonly) {
10467 				mutex_enter(&connp->conn_lock);
10468 				if (IPCL_IS_BOUND(connp)) {
10469 					mutex_exit(&connp->conn_lock);
10470 					return (EINVAL);
10471 				}
10472 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10473 				mutex_exit(&connp->conn_lock);
10474 			}
10475 			break;	/* goto sizeof (int) option return */
10476 		case SO_ANON_MLP:
10477 			if (!checkonly) {
10478 				mutex_enter(&connp->conn_lock);
10479 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10480 				mutex_exit(&connp->conn_lock);
10481 			}
10482 			break;	/* goto sizeof (int) option return */
10483 		case SO_MAC_EXEMPT:
10484 			if (secpolicy_net_mac_aware(cr) != 0 ||
10485 			    IPCL_IS_BOUND(connp))
10486 				return (EACCES);
10487 			if (!checkonly) {
10488 				mutex_enter(&connp->conn_lock);
10489 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10490 				mutex_exit(&connp->conn_lock);
10491 			}
10492 			break;	/* goto sizeof (int) option return */
10493 		default:
10494 			/*
10495 			 * "soft" error (negative)
10496 			 * option not handled at this level
10497 			 * Note: Do not modify *outlenp
10498 			 */
10499 			return (-EINVAL);
10500 		}
10501 		break;
10502 	case IPPROTO_IP:
10503 		switch (name) {
10504 		case IP_NEXTHOP:
10505 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10506 				return (EPERM);
10507 			/* FALLTHRU */
10508 		case IP_MULTICAST_IF:
10509 		case IP_DONTFAILOVER_IF: {
10510 			ipaddr_t addr = *i1;
10511 
10512 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10513 			    first_mp);
10514 			if (error != 0)
10515 				return (error);
10516 			break;	/* goto sizeof (int) option return */
10517 		}
10518 
10519 		case IP_MULTICAST_TTL:
10520 			/* Recorded in transport above IP */
10521 			*outvalp = *invalp;
10522 			*outlenp = sizeof (uchar_t);
10523 			return (0);
10524 		case IP_MULTICAST_LOOP:
10525 			if (!checkonly) {
10526 				mutex_enter(&connp->conn_lock);
10527 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10528 				mutex_exit(&connp->conn_lock);
10529 			}
10530 			*outvalp = *invalp;
10531 			*outlenp = sizeof (uchar_t);
10532 			return (0);
10533 		case IP_ADD_MEMBERSHIP:
10534 		case MCAST_JOIN_GROUP:
10535 		case IP_DROP_MEMBERSHIP:
10536 		case MCAST_LEAVE_GROUP: {
10537 			struct ip_mreq *mreqp;
10538 			struct group_req *greqp;
10539 			ire_t *ire;
10540 			boolean_t done = B_FALSE;
10541 			ipaddr_t group, ifaddr;
10542 			struct sockaddr_in *sin;
10543 			uint32_t *ifindexp;
10544 			boolean_t mcast_opt = B_TRUE;
10545 			mcast_record_t fmode;
10546 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10547 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10548 
10549 			switch (name) {
10550 			case IP_ADD_MEMBERSHIP:
10551 				mcast_opt = B_FALSE;
10552 				/* FALLTHRU */
10553 			case MCAST_JOIN_GROUP:
10554 				fmode = MODE_IS_EXCLUDE;
10555 				optfn = ip_opt_add_group;
10556 				break;
10557 
10558 			case IP_DROP_MEMBERSHIP:
10559 				mcast_opt = B_FALSE;
10560 				/* FALLTHRU */
10561 			case MCAST_LEAVE_GROUP:
10562 				fmode = MODE_IS_INCLUDE;
10563 				optfn = ip_opt_delete_group;
10564 				break;
10565 			}
10566 
10567 			if (mcast_opt) {
10568 				greqp = (struct group_req *)i1;
10569 				sin = (struct sockaddr_in *)&greqp->gr_group;
10570 				if (sin->sin_family != AF_INET) {
10571 					*outlenp = 0;
10572 					return (ENOPROTOOPT);
10573 				}
10574 				group = (ipaddr_t)sin->sin_addr.s_addr;
10575 				ifaddr = INADDR_ANY;
10576 				ifindexp = &greqp->gr_interface;
10577 			} else {
10578 				mreqp = (struct ip_mreq *)i1;
10579 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10580 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10581 				ifindexp = NULL;
10582 			}
10583 
10584 			/*
10585 			 * In the multirouting case, we need to replicate
10586 			 * the request on all interfaces that will take part
10587 			 * in replication.  We do so because multirouting is
10588 			 * reflective, thus we will probably receive multi-
10589 			 * casts on those interfaces.
10590 			 * The ip_multirt_apply_membership() succeeds if the
10591 			 * operation succeeds on at least one interface.
10592 			 */
10593 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10594 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10595 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10596 			if (ire != NULL) {
10597 				if (ire->ire_flags & RTF_MULTIRT) {
10598 					error = ip_multirt_apply_membership(
10599 					    optfn, ire, connp, checkonly, group,
10600 					    fmode, INADDR_ANY, first_mp);
10601 					done = B_TRUE;
10602 				}
10603 				ire_refrele(ire);
10604 			}
10605 			if (!done) {
10606 				error = optfn(connp, checkonly, group, ifaddr,
10607 				    ifindexp, fmode, INADDR_ANY, first_mp);
10608 			}
10609 			if (error) {
10610 				/*
10611 				 * EINPROGRESS is a soft error, needs retry
10612 				 * so don't make *outlenp zero.
10613 				 */
10614 				if (error != EINPROGRESS)
10615 					*outlenp = 0;
10616 				return (error);
10617 			}
10618 			/* OK return - copy input buffer into output buffer */
10619 			if (invalp != outvalp) {
10620 				/* don't trust bcopy for identical src/dst */
10621 				bcopy(invalp, outvalp, inlen);
10622 			}
10623 			*outlenp = inlen;
10624 			return (0);
10625 		}
10626 		case IP_BLOCK_SOURCE:
10627 		case IP_UNBLOCK_SOURCE:
10628 		case IP_ADD_SOURCE_MEMBERSHIP:
10629 		case IP_DROP_SOURCE_MEMBERSHIP:
10630 		case MCAST_BLOCK_SOURCE:
10631 		case MCAST_UNBLOCK_SOURCE:
10632 		case MCAST_JOIN_SOURCE_GROUP:
10633 		case MCAST_LEAVE_SOURCE_GROUP: {
10634 			struct ip_mreq_source *imreqp;
10635 			struct group_source_req *gsreqp;
10636 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10637 			uint32_t ifindex = 0;
10638 			mcast_record_t fmode;
10639 			struct sockaddr_in *sin;
10640 			ire_t *ire;
10641 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10642 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10643 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10644 
10645 			switch (name) {
10646 			case IP_BLOCK_SOURCE:
10647 				mcast_opt = B_FALSE;
10648 				/* FALLTHRU */
10649 			case MCAST_BLOCK_SOURCE:
10650 				fmode = MODE_IS_EXCLUDE;
10651 				optfn = ip_opt_add_group;
10652 				break;
10653 
10654 			case IP_UNBLOCK_SOURCE:
10655 				mcast_opt = B_FALSE;
10656 				/* FALLTHRU */
10657 			case MCAST_UNBLOCK_SOURCE:
10658 				fmode = MODE_IS_EXCLUDE;
10659 				optfn = ip_opt_delete_group;
10660 				break;
10661 
10662 			case IP_ADD_SOURCE_MEMBERSHIP:
10663 				mcast_opt = B_FALSE;
10664 				/* FALLTHRU */
10665 			case MCAST_JOIN_SOURCE_GROUP:
10666 				fmode = MODE_IS_INCLUDE;
10667 				optfn = ip_opt_add_group;
10668 				break;
10669 
10670 			case IP_DROP_SOURCE_MEMBERSHIP:
10671 				mcast_opt = B_FALSE;
10672 				/* FALLTHRU */
10673 			case MCAST_LEAVE_SOURCE_GROUP:
10674 				fmode = MODE_IS_INCLUDE;
10675 				optfn = ip_opt_delete_group;
10676 				break;
10677 			}
10678 
10679 			if (mcast_opt) {
10680 				gsreqp = (struct group_source_req *)i1;
10681 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10682 					*outlenp = 0;
10683 					return (ENOPROTOOPT);
10684 				}
10685 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10686 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10687 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10688 				src = (ipaddr_t)sin->sin_addr.s_addr;
10689 				ifindex = gsreqp->gsr_interface;
10690 			} else {
10691 				imreqp = (struct ip_mreq_source *)i1;
10692 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10693 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10694 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10695 			}
10696 
10697 			/*
10698 			 * In the multirouting case, we need to replicate
10699 			 * the request as noted in the mcast cases above.
10700 			 */
10701 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10702 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10703 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10704 			if (ire != NULL) {
10705 				if (ire->ire_flags & RTF_MULTIRT) {
10706 					error = ip_multirt_apply_membership(
10707 					    optfn, ire, connp, checkonly, grp,
10708 					    fmode, src, first_mp);
10709 					done = B_TRUE;
10710 				}
10711 				ire_refrele(ire);
10712 			}
10713 			if (!done) {
10714 				error = optfn(connp, checkonly, grp, ifaddr,
10715 				    &ifindex, fmode, src, first_mp);
10716 			}
10717 			if (error != 0) {
10718 				/*
10719 				 * EINPROGRESS is a soft error, needs retry
10720 				 * so don't make *outlenp zero.
10721 				 */
10722 				if (error != EINPROGRESS)
10723 					*outlenp = 0;
10724 				return (error);
10725 			}
10726 			/* OK return - copy input buffer into output buffer */
10727 			if (invalp != outvalp) {
10728 				bcopy(invalp, outvalp, inlen);
10729 			}
10730 			*outlenp = inlen;
10731 			return (0);
10732 		}
10733 		case IP_SEC_OPT:
10734 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10735 			if (error != 0) {
10736 				*outlenp = 0;
10737 				return (error);
10738 			}
10739 			break;
10740 		case IP_HDRINCL:
10741 		case IP_OPTIONS:
10742 		case T_IP_OPTIONS:
10743 		case IP_TOS:
10744 		case T_IP_TOS:
10745 		case IP_TTL:
10746 		case IP_RECVDSTADDR:
10747 		case IP_RECVOPTS:
10748 			/* OK return - copy input buffer into output buffer */
10749 			if (invalp != outvalp) {
10750 				/* don't trust bcopy for identical src/dst */
10751 				bcopy(invalp, outvalp, inlen);
10752 			}
10753 			*outlenp = inlen;
10754 			return (0);
10755 		case IP_RECVIF:
10756 			/* Retrieve the inbound interface index */
10757 			if (!checkonly) {
10758 				mutex_enter(&connp->conn_lock);
10759 				connp->conn_recvif = *i1 ? 1 : 0;
10760 				mutex_exit(&connp->conn_lock);
10761 			}
10762 			break;	/* goto sizeof (int) option return */
10763 		case IP_RECVSLLA:
10764 			/* Retrieve the source link layer address */
10765 			if (!checkonly) {
10766 				mutex_enter(&connp->conn_lock);
10767 				connp->conn_recvslla = *i1 ? 1 : 0;
10768 				mutex_exit(&connp->conn_lock);
10769 			}
10770 			break;	/* goto sizeof (int) option return */
10771 		case MRT_INIT:
10772 		case MRT_DONE:
10773 		case MRT_ADD_VIF:
10774 		case MRT_DEL_VIF:
10775 		case MRT_ADD_MFC:
10776 		case MRT_DEL_MFC:
10777 		case MRT_ASSERT:
10778 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10779 				*outlenp = 0;
10780 				return (error);
10781 			}
10782 			error = ip_mrouter_set((int)name, q, checkonly,
10783 			    (uchar_t *)invalp, inlen, first_mp);
10784 			if (error) {
10785 				*outlenp = 0;
10786 				return (error);
10787 			}
10788 			/* OK return - copy input buffer into output buffer */
10789 			if (invalp != outvalp) {
10790 				/* don't trust bcopy for identical src/dst */
10791 				bcopy(invalp, outvalp, inlen);
10792 			}
10793 			*outlenp = inlen;
10794 			return (0);
10795 		case IP_BOUND_IF:
10796 		case IP_XMIT_IF:
10797 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10798 			    level, name, first_mp);
10799 			if (error != 0)
10800 				return (error);
10801 			break; 		/* goto sizeof (int) option return */
10802 
10803 		case IP_UNSPEC_SRC:
10804 			/* Allow sending with a zero source address */
10805 			if (!checkonly) {
10806 				mutex_enter(&connp->conn_lock);
10807 				connp->conn_unspec_src = *i1 ? 1 : 0;
10808 				mutex_exit(&connp->conn_lock);
10809 			}
10810 			break;	/* goto sizeof (int) option return */
10811 		default:
10812 			/*
10813 			 * "soft" error (negative)
10814 			 * option not handled at this level
10815 			 * Note: Do not modify *outlenp
10816 			 */
10817 			return (-EINVAL);
10818 		}
10819 		break;
10820 	case IPPROTO_IPV6:
10821 		switch (name) {
10822 		case IPV6_BOUND_IF:
10823 		case IPV6_BOUND_PIF:
10824 		case IPV6_DONTFAILOVER_IF:
10825 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10826 			    level, name, first_mp);
10827 			if (error != 0)
10828 				return (error);
10829 			break; 		/* goto sizeof (int) option return */
10830 
10831 		case IPV6_MULTICAST_IF:
10832 			/*
10833 			 * The only possible errors are EINPROGRESS and
10834 			 * EINVAL. EINPROGRESS will be restarted and is not
10835 			 * a hard error. We call this option on both V4 and V6
10836 			 * If both return EINVAL, then this call returns
10837 			 * EINVAL. If at least one of them succeeds we
10838 			 * return success.
10839 			 */
10840 			found = B_FALSE;
10841 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10842 			    level, name, first_mp);
10843 			if (error == EINPROGRESS)
10844 				return (error);
10845 			if (error == 0)
10846 				found = B_TRUE;
10847 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10848 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10849 			if (error == 0)
10850 				found = B_TRUE;
10851 			if (!found)
10852 				return (error);
10853 			break; 		/* goto sizeof (int) option return */
10854 
10855 		case IPV6_MULTICAST_HOPS:
10856 			/* Recorded in transport above IP */
10857 			break;	/* goto sizeof (int) option return */
10858 		case IPV6_MULTICAST_LOOP:
10859 			if (!checkonly) {
10860 				mutex_enter(&connp->conn_lock);
10861 				connp->conn_multicast_loop = *i1;
10862 				mutex_exit(&connp->conn_lock);
10863 			}
10864 			break;	/* goto sizeof (int) option return */
10865 		case IPV6_JOIN_GROUP:
10866 		case MCAST_JOIN_GROUP:
10867 		case IPV6_LEAVE_GROUP:
10868 		case MCAST_LEAVE_GROUP: {
10869 			struct ipv6_mreq *ip_mreqp;
10870 			struct group_req *greqp;
10871 			ire_t *ire;
10872 			boolean_t done = B_FALSE;
10873 			in6_addr_t groupv6;
10874 			uint32_t ifindex;
10875 			boolean_t mcast_opt = B_TRUE;
10876 			mcast_record_t fmode;
10877 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10878 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10879 
10880 			switch (name) {
10881 			case IPV6_JOIN_GROUP:
10882 				mcast_opt = B_FALSE;
10883 				/* FALLTHRU */
10884 			case MCAST_JOIN_GROUP:
10885 				fmode = MODE_IS_EXCLUDE;
10886 				optfn = ip_opt_add_group_v6;
10887 				break;
10888 
10889 			case IPV6_LEAVE_GROUP:
10890 				mcast_opt = B_FALSE;
10891 				/* FALLTHRU */
10892 			case MCAST_LEAVE_GROUP:
10893 				fmode = MODE_IS_INCLUDE;
10894 				optfn = ip_opt_delete_group_v6;
10895 				break;
10896 			}
10897 
10898 			if (mcast_opt) {
10899 				struct sockaddr_in *sin;
10900 				struct sockaddr_in6 *sin6;
10901 				greqp = (struct group_req *)i1;
10902 				if (greqp->gr_group.ss_family == AF_INET) {
10903 					sin = (struct sockaddr_in *)
10904 					    &(greqp->gr_group);
10905 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10906 					    &groupv6);
10907 				} else {
10908 					sin6 = (struct sockaddr_in6 *)
10909 					    &(greqp->gr_group);
10910 					groupv6 = sin6->sin6_addr;
10911 				}
10912 				ifindex = greqp->gr_interface;
10913 			} else {
10914 				ip_mreqp = (struct ipv6_mreq *)i1;
10915 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10916 				ifindex = ip_mreqp->ipv6mr_interface;
10917 			}
10918 			/*
10919 			 * In the multirouting case, we need to replicate
10920 			 * the request on all interfaces that will take part
10921 			 * in replication.  We do so because multirouting is
10922 			 * reflective, thus we will probably receive multi-
10923 			 * casts on those interfaces.
10924 			 * The ip_multirt_apply_membership_v6() succeeds if
10925 			 * the operation succeeds on at least one interface.
10926 			 */
10927 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
10928 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10929 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10930 			if (ire != NULL) {
10931 				if (ire->ire_flags & RTF_MULTIRT) {
10932 					error = ip_multirt_apply_membership_v6(
10933 					    optfn, ire, connp, checkonly,
10934 					    &groupv6, fmode, &ipv6_all_zeros,
10935 					    first_mp);
10936 					done = B_TRUE;
10937 				}
10938 				ire_refrele(ire);
10939 			}
10940 			if (!done) {
10941 				error = optfn(connp, checkonly, &groupv6,
10942 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10943 			}
10944 			if (error) {
10945 				/*
10946 				 * EINPROGRESS is a soft error, needs retry
10947 				 * so don't make *outlenp zero.
10948 				 */
10949 				if (error != EINPROGRESS)
10950 					*outlenp = 0;
10951 				return (error);
10952 			}
10953 			/* OK return - copy input buffer into output buffer */
10954 			if (invalp != outvalp) {
10955 				/* don't trust bcopy for identical src/dst */
10956 				bcopy(invalp, outvalp, inlen);
10957 			}
10958 			*outlenp = inlen;
10959 			return (0);
10960 		}
10961 		case MCAST_BLOCK_SOURCE:
10962 		case MCAST_UNBLOCK_SOURCE:
10963 		case MCAST_JOIN_SOURCE_GROUP:
10964 		case MCAST_LEAVE_SOURCE_GROUP: {
10965 			struct group_source_req *gsreqp;
10966 			in6_addr_t v6grp, v6src;
10967 			uint32_t ifindex;
10968 			mcast_record_t fmode;
10969 			ire_t *ire;
10970 			boolean_t done = B_FALSE;
10971 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10972 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10973 
10974 			switch (name) {
10975 			case MCAST_BLOCK_SOURCE:
10976 				fmode = MODE_IS_EXCLUDE;
10977 				optfn = ip_opt_add_group_v6;
10978 				break;
10979 			case MCAST_UNBLOCK_SOURCE:
10980 				fmode = MODE_IS_EXCLUDE;
10981 				optfn = ip_opt_delete_group_v6;
10982 				break;
10983 			case MCAST_JOIN_SOURCE_GROUP:
10984 				fmode = MODE_IS_INCLUDE;
10985 				optfn = ip_opt_add_group_v6;
10986 				break;
10987 			case MCAST_LEAVE_SOURCE_GROUP:
10988 				fmode = MODE_IS_INCLUDE;
10989 				optfn = ip_opt_delete_group_v6;
10990 				break;
10991 			}
10992 
10993 			gsreqp = (struct group_source_req *)i1;
10994 			ifindex = gsreqp->gsr_interface;
10995 			if (gsreqp->gsr_group.ss_family == AF_INET) {
10996 				struct sockaddr_in *s;
10997 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
10998 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
10999 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11000 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11001 			} else {
11002 				struct sockaddr_in6 *s6;
11003 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11004 				v6grp = s6->sin6_addr;
11005 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11006 				v6src = s6->sin6_addr;
11007 			}
11008 
11009 			/*
11010 			 * In the multirouting case, we need to replicate
11011 			 * the request as noted in the mcast cases above.
11012 			 */
11013 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11014 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11015 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11016 			if (ire != NULL) {
11017 				if (ire->ire_flags & RTF_MULTIRT) {
11018 					error = ip_multirt_apply_membership_v6(
11019 					    optfn, ire, connp, checkonly,
11020 					    &v6grp, fmode, &v6src, first_mp);
11021 					done = B_TRUE;
11022 				}
11023 				ire_refrele(ire);
11024 			}
11025 			if (!done) {
11026 				error = optfn(connp, checkonly, &v6grp,
11027 				    ifindex, fmode, &v6src, first_mp);
11028 			}
11029 			if (error != 0) {
11030 				/*
11031 				 * EINPROGRESS is a soft error, needs retry
11032 				 * so don't make *outlenp zero.
11033 				 */
11034 				if (error != EINPROGRESS)
11035 					*outlenp = 0;
11036 				return (error);
11037 			}
11038 			/* OK return - copy input buffer into output buffer */
11039 			if (invalp != outvalp) {
11040 				bcopy(invalp, outvalp, inlen);
11041 			}
11042 			*outlenp = inlen;
11043 			return (0);
11044 		}
11045 		case IPV6_UNICAST_HOPS:
11046 			/* Recorded in transport above IP */
11047 			break;	/* goto sizeof (int) option return */
11048 		case IPV6_UNSPEC_SRC:
11049 			/* Allow sending with a zero source address */
11050 			if (!checkonly) {
11051 				mutex_enter(&connp->conn_lock);
11052 				connp->conn_unspec_src = *i1 ? 1 : 0;
11053 				mutex_exit(&connp->conn_lock);
11054 			}
11055 			break;	/* goto sizeof (int) option return */
11056 		case IPV6_RECVPKTINFO:
11057 			if (!checkonly) {
11058 				mutex_enter(&connp->conn_lock);
11059 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
11060 				mutex_exit(&connp->conn_lock);
11061 			}
11062 			break;	/* goto sizeof (int) option return */
11063 		case IPV6_RECVTCLASS:
11064 			if (!checkonly) {
11065 				if (*i1 < 0 || *i1 > 1) {
11066 					return (EINVAL);
11067 				}
11068 				mutex_enter(&connp->conn_lock);
11069 				connp->conn_ipv6_recvtclass = *i1;
11070 				mutex_exit(&connp->conn_lock);
11071 			}
11072 			break;
11073 		case IPV6_RECVPATHMTU:
11074 			if (!checkonly) {
11075 				if (*i1 < 0 || *i1 > 1) {
11076 					return (EINVAL);
11077 				}
11078 				mutex_enter(&connp->conn_lock);
11079 				connp->conn_ipv6_recvpathmtu = *i1;
11080 				mutex_exit(&connp->conn_lock);
11081 			}
11082 			break;
11083 		case IPV6_RECVHOPLIMIT:
11084 			if (!checkonly) {
11085 				mutex_enter(&connp->conn_lock);
11086 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11087 				mutex_exit(&connp->conn_lock);
11088 			}
11089 			break;	/* goto sizeof (int) option return */
11090 		case IPV6_RECVHOPOPTS:
11091 			if (!checkonly) {
11092 				mutex_enter(&connp->conn_lock);
11093 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11094 				mutex_exit(&connp->conn_lock);
11095 			}
11096 			break;	/* goto sizeof (int) option return */
11097 		case IPV6_RECVDSTOPTS:
11098 			if (!checkonly) {
11099 				mutex_enter(&connp->conn_lock);
11100 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11101 				mutex_exit(&connp->conn_lock);
11102 			}
11103 			break;	/* goto sizeof (int) option return */
11104 		case IPV6_RECVRTHDR:
11105 			if (!checkonly) {
11106 				mutex_enter(&connp->conn_lock);
11107 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11108 				mutex_exit(&connp->conn_lock);
11109 			}
11110 			break;	/* goto sizeof (int) option return */
11111 		case IPV6_RECVRTHDRDSTOPTS:
11112 			if (!checkonly) {
11113 				mutex_enter(&connp->conn_lock);
11114 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11115 				mutex_exit(&connp->conn_lock);
11116 			}
11117 			break;	/* goto sizeof (int) option return */
11118 		case IPV6_PKTINFO:
11119 			if (inlen == 0)
11120 				return (-EINVAL);	/* clearing option */
11121 			error = ip6_set_pktinfo(cr, connp,
11122 			    (struct in6_pktinfo *)invalp, first_mp);
11123 			if (error != 0)
11124 				*outlenp = 0;
11125 			else
11126 				*outlenp = inlen;
11127 			return (error);
11128 		case IPV6_NEXTHOP: {
11129 			struct sockaddr_in6 *sin6;
11130 
11131 			/* Verify that the nexthop is reachable */
11132 			if (inlen == 0)
11133 				return (-EINVAL);	/* clearing option */
11134 
11135 			sin6 = (struct sockaddr_in6 *)invalp;
11136 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11137 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11138 			    NULL, MATCH_IRE_DEFAULT);
11139 
11140 			if (ire == NULL) {
11141 				*outlenp = 0;
11142 				return (EHOSTUNREACH);
11143 			}
11144 			ire_refrele(ire);
11145 			return (-EINVAL);
11146 		}
11147 		case IPV6_SEC_OPT:
11148 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11149 			if (error != 0) {
11150 				*outlenp = 0;
11151 				return (error);
11152 			}
11153 			break;
11154 		case IPV6_SRC_PREFERENCES: {
11155 			/*
11156 			 * This is implemented strictly in the ip module
11157 			 * (here and in tcp_opt_*() to accomodate tcp
11158 			 * sockets).  Modules above ip pass this option
11159 			 * down here since ip is the only one that needs to
11160 			 * be aware of source address preferences.
11161 			 *
11162 			 * This socket option only affects connected
11163 			 * sockets that haven't already bound to a specific
11164 			 * IPv6 address.  In other words, sockets that
11165 			 * don't call bind() with an address other than the
11166 			 * unspecified address and that call connect().
11167 			 * ip_bind_connected_v6() passes these preferences
11168 			 * to the ipif_select_source_v6() function.
11169 			 */
11170 			if (inlen != sizeof (uint32_t))
11171 				return (EINVAL);
11172 			error = ip6_set_src_preferences(connp,
11173 			    *(uint32_t *)invalp);
11174 			if (error != 0) {
11175 				*outlenp = 0;
11176 				return (error);
11177 			} else {
11178 				*outlenp = sizeof (uint32_t);
11179 			}
11180 			break;
11181 		}
11182 		case IPV6_V6ONLY:
11183 			if (*i1 < 0 || *i1 > 1) {
11184 				return (EINVAL);
11185 			}
11186 			mutex_enter(&connp->conn_lock);
11187 			connp->conn_ipv6_v6only = *i1;
11188 			mutex_exit(&connp->conn_lock);
11189 			break;
11190 		default:
11191 			return (-EINVAL);
11192 		}
11193 		break;
11194 	default:
11195 		/*
11196 		 * "soft" error (negative)
11197 		 * option not handled at this level
11198 		 * Note: Do not modify *outlenp
11199 		 */
11200 		return (-EINVAL);
11201 	}
11202 	/*
11203 	 * Common case of return from an option that is sizeof (int)
11204 	 */
11205 	*(int *)outvalp = *i1;
11206 	*outlenp = sizeof (int);
11207 	return (0);
11208 }
11209 
11210 /*
11211  * This routine gets default values of certain options whose default
11212  * values are maintained by protocol specific code
11213  */
11214 /* ARGSUSED */
11215 int
11216 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11217 {
11218 	int *i1 = (int *)ptr;
11219 
11220 	switch (level) {
11221 	case IPPROTO_IP:
11222 		switch (name) {
11223 		case IP_MULTICAST_TTL:
11224 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11225 			return (sizeof (uchar_t));
11226 		case IP_MULTICAST_LOOP:
11227 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11228 			return (sizeof (uchar_t));
11229 		default:
11230 			return (-1);
11231 		}
11232 	case IPPROTO_IPV6:
11233 		switch (name) {
11234 		case IPV6_UNICAST_HOPS:
11235 			*i1 = ipv6_def_hops;
11236 			return (sizeof (int));
11237 		case IPV6_MULTICAST_HOPS:
11238 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11239 			return (sizeof (int));
11240 		case IPV6_MULTICAST_LOOP:
11241 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11242 			return (sizeof (int));
11243 		case IPV6_V6ONLY:
11244 			*i1 = 1;
11245 			return (sizeof (int));
11246 		default:
11247 			return (-1);
11248 		}
11249 	default:
11250 		return (-1);
11251 	}
11252 	/* NOTREACHED */
11253 }
11254 
11255 /*
11256  * Given a destination address and a pointer to where to put the information
11257  * this routine fills in the mtuinfo.
11258  */
11259 int
11260 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11261     struct ip6_mtuinfo *mtuinfo)
11262 {
11263 	ire_t *ire;
11264 
11265 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11266 		return (-1);
11267 
11268 	bzero(mtuinfo, sizeof (*mtuinfo));
11269 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11270 	mtuinfo->ip6m_addr.sin6_port = port;
11271 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11272 
11273 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11274 	if (ire != NULL) {
11275 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11276 		ire_refrele(ire);
11277 	} else {
11278 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11279 	}
11280 	return (sizeof (struct ip6_mtuinfo));
11281 }
11282 
11283 /*
11284  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11285  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11286  * isn't.  This doesn't matter as the error checking is done properly for the
11287  * other MRT options coming in through ip_opt_set.
11288  */
11289 int
11290 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11291 {
11292 	conn_t		*connp = Q_TO_CONN(q);
11293 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11294 
11295 	switch (level) {
11296 	case IPPROTO_IP:
11297 		switch (name) {
11298 		case MRT_VERSION:
11299 		case MRT_ASSERT:
11300 			(void) ip_mrouter_get(name, q, ptr);
11301 			return (sizeof (int));
11302 		case IP_SEC_OPT:
11303 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11304 		case IP_NEXTHOP:
11305 			if (connp->conn_nexthop_set) {
11306 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11307 				return (sizeof (ipaddr_t));
11308 			} else
11309 				return (0);
11310 		default:
11311 			break;
11312 		}
11313 		break;
11314 	case IPPROTO_IPV6:
11315 		switch (name) {
11316 		case IPV6_SEC_OPT:
11317 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11318 		case IPV6_SRC_PREFERENCES: {
11319 			return (ip6_get_src_preferences(connp,
11320 			    (uint32_t *)ptr));
11321 		}
11322 		case IPV6_V6ONLY:
11323 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11324 			return (sizeof (int));
11325 		case IPV6_PATHMTU:
11326 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11327 				(struct ip6_mtuinfo *)ptr));
11328 		default:
11329 			break;
11330 		}
11331 		break;
11332 	default:
11333 		break;
11334 	}
11335 	return (-1);
11336 }
11337 
11338 /* Named Dispatch routine to get a current value out of our parameter table. */
11339 /* ARGSUSED */
11340 static int
11341 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11342 {
11343 	ipparam_t *ippa = (ipparam_t *)cp;
11344 
11345 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11346 	return (0);
11347 }
11348 
11349 /* ARGSUSED */
11350 static int
11351 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11352 {
11353 
11354 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11355 	return (0);
11356 }
11357 
11358 /*
11359  * Set ip{,6}_forwarding values.  This means walking through all of the
11360  * ill's and toggling their forwarding values.
11361  */
11362 /* ARGSUSED */
11363 static int
11364 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11365 {
11366 	long new_value;
11367 	int *forwarding_value = (int *)cp;
11368 	ill_t *walker;
11369 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11370 	ill_walk_context_t ctx;
11371 
11372 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11373 	    new_value < 0 || new_value > 1) {
11374 		return (EINVAL);
11375 	}
11376 
11377 	*forwarding_value = new_value;
11378 
11379 	/*
11380 	 * Regardless of the current value of ip_forwarding, set all per-ill
11381 	 * values of ip_forwarding to the value being set.
11382 	 *
11383 	 * Bring all the ill's up to date with the new global value.
11384 	 */
11385 	rw_enter(&ill_g_lock, RW_READER);
11386 
11387 	if (isv6)
11388 		walker = ILL_START_WALK_V6(&ctx);
11389 	else
11390 		walker = ILL_START_WALK_V4(&ctx);
11391 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11392 		(void) ill_forward_set(q, mp, (new_value != 0),
11393 		    (caddr_t)walker);
11394 	}
11395 	rw_exit(&ill_g_lock);
11396 
11397 	return (0);
11398 }
11399 
11400 /*
11401  * Walk through the param array specified registering each element with the
11402  * Named Dispatch handler. This is called only during init. So it is ok
11403  * not to acquire any locks
11404  */
11405 static boolean_t
11406 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11407     ipndp_t *ipnd, size_t ipnd_cnt)
11408 {
11409 	for (; ippa_cnt-- > 0; ippa++) {
11410 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11411 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11412 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11413 				nd_free(&ip_g_nd);
11414 				return (B_FALSE);
11415 			}
11416 		}
11417 	}
11418 
11419 	for (; ipnd_cnt-- > 0; ipnd++) {
11420 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11421 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11422 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11423 			    ipnd->ip_ndp_data)) {
11424 				nd_free(&ip_g_nd);
11425 				return (B_FALSE);
11426 			}
11427 		}
11428 	}
11429 
11430 	return (B_TRUE);
11431 }
11432 
11433 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11434 /* ARGSUSED */
11435 static int
11436 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11437 {
11438 	long		new_value;
11439 	ipparam_t	*ippa = (ipparam_t *)cp;
11440 
11441 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11442 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11443 		return (EINVAL);
11444 	}
11445 	ippa->ip_param_value = new_value;
11446 	return (0);
11447 }
11448 
11449 /*
11450  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11451  * When an ipf is passed here for the first time, if
11452  * we already have in-order fragments on the queue, we convert from the fast-
11453  * path reassembly scheme to the hard-case scheme.  From then on, additional
11454  * fragments are reassembled here.  We keep track of the start and end offsets
11455  * of each piece, and the number of holes in the chain.  When the hole count
11456  * goes to zero, we are done!
11457  *
11458  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11459  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11460  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11461  * after the call to ip_reassemble().
11462  */
11463 int
11464 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11465     size_t msg_len)
11466 {
11467 	uint_t	end;
11468 	mblk_t	*next_mp;
11469 	mblk_t	*mp1;
11470 	uint_t	offset;
11471 	boolean_t incr_dups = B_TRUE;
11472 	boolean_t offset_zero_seen = B_FALSE;
11473 	boolean_t pkt_boundary_checked = B_FALSE;
11474 
11475 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11476 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11477 
11478 	/* Add in byte count */
11479 	ipf->ipf_count += msg_len;
11480 	if (ipf->ipf_end) {
11481 		/*
11482 		 * We were part way through in-order reassembly, but now there
11483 		 * is a hole.  We walk through messages already queued, and
11484 		 * mark them for hard case reassembly.  We know that up till
11485 		 * now they were in order starting from offset zero.
11486 		 */
11487 		offset = 0;
11488 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11489 			IP_REASS_SET_START(mp1, offset);
11490 			if (offset == 0) {
11491 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11492 				offset = -ipf->ipf_nf_hdr_len;
11493 			}
11494 			offset += mp1->b_wptr - mp1->b_rptr;
11495 			IP_REASS_SET_END(mp1, offset);
11496 		}
11497 		/* One hole at the end. */
11498 		ipf->ipf_hole_cnt = 1;
11499 		/* Brand it as a hard case, forever. */
11500 		ipf->ipf_end = 0;
11501 	}
11502 	/* Walk through all the new pieces. */
11503 	do {
11504 		end = start + (mp->b_wptr - mp->b_rptr);
11505 		/*
11506 		 * If start is 0, decrease 'end' only for the first mblk of
11507 		 * the fragment. Otherwise 'end' can get wrong value in the
11508 		 * second pass of the loop if first mblk is exactly the
11509 		 * size of ipf_nf_hdr_len.
11510 		 */
11511 		if (start == 0 && !offset_zero_seen) {
11512 			/* First segment */
11513 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11514 			end -= ipf->ipf_nf_hdr_len;
11515 			offset_zero_seen = B_TRUE;
11516 		}
11517 		next_mp = mp->b_cont;
11518 		/*
11519 		 * We are checking to see if there is any interesing data
11520 		 * to process.  If there isn't and the mblk isn't the
11521 		 * one which carries the unfragmentable header then we
11522 		 * drop it.  It's possible to have just the unfragmentable
11523 		 * header come through without any data.  That needs to be
11524 		 * saved.
11525 		 *
11526 		 * If the assert at the top of this function holds then the
11527 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11528 		 * is infrequently traveled enough that the test is left in
11529 		 * to protect against future code changes which break that
11530 		 * invariant.
11531 		 */
11532 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11533 			/* Empty.  Blast it. */
11534 			IP_REASS_SET_START(mp, 0);
11535 			IP_REASS_SET_END(mp, 0);
11536 			/*
11537 			 * If the ipf points to the mblk we are about to free,
11538 			 * update ipf to point to the next mblk (or NULL
11539 			 * if none).
11540 			 */
11541 			if (ipf->ipf_mp->b_cont == mp)
11542 				ipf->ipf_mp->b_cont = next_mp;
11543 			freeb(mp);
11544 			continue;
11545 		}
11546 		mp->b_cont = NULL;
11547 		IP_REASS_SET_START(mp, start);
11548 		IP_REASS_SET_END(mp, end);
11549 		if (!ipf->ipf_tail_mp) {
11550 			ipf->ipf_tail_mp = mp;
11551 			ipf->ipf_mp->b_cont = mp;
11552 			if (start == 0 || !more) {
11553 				ipf->ipf_hole_cnt = 1;
11554 				/*
11555 				 * if the first fragment comes in more than one
11556 				 * mblk, this loop will be executed for each
11557 				 * mblk. Need to adjust hole count so exiting
11558 				 * this routine will leave hole count at 1.
11559 				 */
11560 				if (next_mp)
11561 					ipf->ipf_hole_cnt++;
11562 			} else
11563 				ipf->ipf_hole_cnt = 2;
11564 			continue;
11565 		} else if (ipf->ipf_last_frag_seen && !more &&
11566 			    !pkt_boundary_checked) {
11567 			/*
11568 			 * We check datagram boundary only if this fragment
11569 			 * claims to be the last fragment and we have seen a
11570 			 * last fragment in the past too. We do this only
11571 			 * once for a given fragment.
11572 			 *
11573 			 * start cannot be 0 here as fragments with start=0
11574 			 * and MF=0 gets handled as a complete packet. These
11575 			 * fragments should not reach here.
11576 			 */
11577 
11578 			if (start + msgdsize(mp) !=
11579 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11580 				/*
11581 				 * We have two fragments both of which claim
11582 				 * to be the last fragment but gives conflicting
11583 				 * information about the whole datagram size.
11584 				 * Something fishy is going on. Drop the
11585 				 * fragment and free up the reassembly list.
11586 				 */
11587 				return (IP_REASS_FAILED);
11588 			}
11589 
11590 			/*
11591 			 * We shouldn't come to this code block again for this
11592 			 * particular fragment.
11593 			 */
11594 			pkt_boundary_checked = B_TRUE;
11595 		}
11596 
11597 		/* New stuff at or beyond tail? */
11598 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11599 		if (start >= offset) {
11600 			if (ipf->ipf_last_frag_seen) {
11601 				/* current fragment is beyond last fragment */
11602 				return (IP_REASS_FAILED);
11603 			}
11604 			/* Link it on end. */
11605 			ipf->ipf_tail_mp->b_cont = mp;
11606 			ipf->ipf_tail_mp = mp;
11607 			if (more) {
11608 				if (start != offset)
11609 					ipf->ipf_hole_cnt++;
11610 			} else if (start == offset && next_mp == NULL)
11611 					ipf->ipf_hole_cnt--;
11612 			continue;
11613 		}
11614 		mp1 = ipf->ipf_mp->b_cont;
11615 		offset = IP_REASS_START(mp1);
11616 		/* New stuff at the front? */
11617 		if (start < offset) {
11618 			if (start == 0) {
11619 				if (end >= offset) {
11620 					/* Nailed the hole at the begining. */
11621 					ipf->ipf_hole_cnt--;
11622 				}
11623 			} else if (end < offset) {
11624 				/*
11625 				 * A hole, stuff, and a hole where there used
11626 				 * to be just a hole.
11627 				 */
11628 				ipf->ipf_hole_cnt++;
11629 			}
11630 			mp->b_cont = mp1;
11631 			/* Check for overlap. */
11632 			while (end > offset) {
11633 				if (end < IP_REASS_END(mp1)) {
11634 					mp->b_wptr -= end - offset;
11635 					IP_REASS_SET_END(mp, offset);
11636 					if (ill->ill_isv6) {
11637 						BUMP_MIB(ill->ill_ip6_mib,
11638 						    ipv6ReasmPartDups);
11639 					} else {
11640 						BUMP_MIB(&ip_mib,
11641 						    ipReasmPartDups);
11642 					}
11643 					break;
11644 				}
11645 				/* Did we cover another hole? */
11646 				if ((mp1->b_cont &&
11647 				    IP_REASS_END(mp1) !=
11648 				    IP_REASS_START(mp1->b_cont) &&
11649 				    end >= IP_REASS_START(mp1->b_cont)) ||
11650 				    (!ipf->ipf_last_frag_seen && !more)) {
11651 					ipf->ipf_hole_cnt--;
11652 				}
11653 				/* Clip out mp1. */
11654 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11655 					/*
11656 					 * After clipping out mp1, this guy
11657 					 * is now hanging off the end.
11658 					 */
11659 					ipf->ipf_tail_mp = mp;
11660 				}
11661 				IP_REASS_SET_START(mp1, 0);
11662 				IP_REASS_SET_END(mp1, 0);
11663 				/* Subtract byte count */
11664 				ipf->ipf_count -= mp1->b_datap->db_lim -
11665 				    mp1->b_datap->db_base;
11666 				freeb(mp1);
11667 				if (ill->ill_isv6) {
11668 					BUMP_MIB(ill->ill_ip6_mib,
11669 					    ipv6ReasmPartDups);
11670 				} else {
11671 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11672 				}
11673 				mp1 = mp->b_cont;
11674 				if (!mp1)
11675 					break;
11676 				offset = IP_REASS_START(mp1);
11677 			}
11678 			ipf->ipf_mp->b_cont = mp;
11679 			continue;
11680 		}
11681 		/*
11682 		 * The new piece starts somewhere between the start of the head
11683 		 * and before the end of the tail.
11684 		 */
11685 		for (; mp1; mp1 = mp1->b_cont) {
11686 			offset = IP_REASS_END(mp1);
11687 			if (start < offset) {
11688 				if (end <= offset) {
11689 					/* Nothing new. */
11690 					IP_REASS_SET_START(mp, 0);
11691 					IP_REASS_SET_END(mp, 0);
11692 					/* Subtract byte count */
11693 					ipf->ipf_count -= mp->b_datap->db_lim -
11694 					    mp->b_datap->db_base;
11695 					if (incr_dups) {
11696 						ipf->ipf_num_dups++;
11697 						incr_dups = B_FALSE;
11698 					}
11699 					freeb(mp);
11700 					if (ill->ill_isv6) {
11701 						BUMP_MIB(ill->ill_ip6_mib,
11702 						    ipv6ReasmDuplicates);
11703 					} else {
11704 						BUMP_MIB(&ip_mib,
11705 						    ipReasmDuplicates);
11706 					}
11707 					break;
11708 				}
11709 				/*
11710 				 * Trim redundant stuff off beginning of new
11711 				 * piece.
11712 				 */
11713 				IP_REASS_SET_START(mp, offset);
11714 				mp->b_rptr += offset - start;
11715 				if (ill->ill_isv6) {
11716 					BUMP_MIB(ill->ill_ip6_mib,
11717 					    ipv6ReasmPartDups);
11718 				} else {
11719 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11720 				}
11721 				start = offset;
11722 				if (!mp1->b_cont) {
11723 					/*
11724 					 * After trimming, this guy is now
11725 					 * hanging off the end.
11726 					 */
11727 					mp1->b_cont = mp;
11728 					ipf->ipf_tail_mp = mp;
11729 					if (!more) {
11730 						ipf->ipf_hole_cnt--;
11731 					}
11732 					break;
11733 				}
11734 			}
11735 			if (start >= IP_REASS_START(mp1->b_cont))
11736 				continue;
11737 			/* Fill a hole */
11738 			if (start > offset)
11739 				ipf->ipf_hole_cnt++;
11740 			mp->b_cont = mp1->b_cont;
11741 			mp1->b_cont = mp;
11742 			mp1 = mp->b_cont;
11743 			offset = IP_REASS_START(mp1);
11744 			if (end >= offset) {
11745 				ipf->ipf_hole_cnt--;
11746 				/* Check for overlap. */
11747 				while (end > offset) {
11748 					if (end < IP_REASS_END(mp1)) {
11749 						mp->b_wptr -= end - offset;
11750 						IP_REASS_SET_END(mp, offset);
11751 						/*
11752 						 * TODO we might bump
11753 						 * this up twice if there is
11754 						 * overlap at both ends.
11755 						 */
11756 						if (ill->ill_isv6) {
11757 							BUMP_MIB(
11758 							    ill->ill_ip6_mib,
11759 							    ipv6ReasmPartDups);
11760 						} else {
11761 							BUMP_MIB(&ip_mib,
11762 							    ipReasmPartDups);
11763 						}
11764 						break;
11765 					}
11766 					/* Did we cover another hole? */
11767 					if ((mp1->b_cont &&
11768 					    IP_REASS_END(mp1)
11769 					    != IP_REASS_START(mp1->b_cont) &&
11770 					    end >=
11771 					    IP_REASS_START(mp1->b_cont)) ||
11772 					    (!ipf->ipf_last_frag_seen &&
11773 					    !more)) {
11774 						ipf->ipf_hole_cnt--;
11775 					}
11776 					/* Clip out mp1. */
11777 					if ((mp->b_cont = mp1->b_cont) ==
11778 					    NULL) {
11779 						/*
11780 						 * After clipping out mp1,
11781 						 * this guy is now hanging
11782 						 * off the end.
11783 						 */
11784 						ipf->ipf_tail_mp = mp;
11785 					}
11786 					IP_REASS_SET_START(mp1, 0);
11787 					IP_REASS_SET_END(mp1, 0);
11788 					/* Subtract byte count */
11789 					ipf->ipf_count -=
11790 					    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,
11798 						    ipReasmPartDups);
11799 					}
11800 					mp1 = mp->b_cont;
11801 					if (!mp1)
11802 						break;
11803 					offset = IP_REASS_START(mp1);
11804 				}
11805 			}
11806 			break;
11807 		}
11808 	} while (start = end, mp = next_mp);
11809 
11810 	/* Fragment just processed could be the last one. Remember this fact */
11811 	if (!more)
11812 		ipf->ipf_last_frag_seen = B_TRUE;
11813 
11814 	/* Still got holes? */
11815 	if (ipf->ipf_hole_cnt)
11816 		return (IP_REASS_PARTIAL);
11817 	/* Clean up overloaded fields to avoid upstream disasters. */
11818 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11819 		IP_REASS_SET_START(mp1, 0);
11820 		IP_REASS_SET_END(mp1, 0);
11821 	}
11822 	return (IP_REASS_COMPLETE);
11823 }
11824 
11825 /*
11826  * ipsec processing for the fast path, used for input UDP Packets
11827  */
11828 static boolean_t
11829 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11830     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11831 {
11832 	uint32_t	ill_index;
11833 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11834 
11835 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11836 	/* The ill_index of the incoming ILL */
11837 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11838 
11839 	/* pass packet up to the transport */
11840 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11841 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11842 		    NULL, mctl_present);
11843 		if (*first_mpp == NULL) {
11844 			return (B_FALSE);
11845 		}
11846 	}
11847 
11848 	/* Initiate IPPF processing for fastpath UDP */
11849 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11850 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11851 		if (*mpp == NULL) {
11852 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11853 			    "deferred/dropped during IPPF processing\n"));
11854 			return (B_FALSE);
11855 		}
11856 	}
11857 	/*
11858 	 * We make the checks as below since we are in the fast path
11859 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11860 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11861 	 */
11862 	if (connp->conn_recvif || connp->conn_recvslla ||
11863 	    connp->conn_ipv6_recvpktinfo) {
11864 		if (connp->conn_recvif ||
11865 		    connp->conn_ipv6_recvpktinfo) {
11866 			in_flags = IPF_RECVIF;
11867 		}
11868 		if (connp->conn_recvslla) {
11869 			in_flags |= IPF_RECVSLLA;
11870 		}
11871 		/*
11872 		 * since in_flags are being set ill will be
11873 		 * referenced in ip_add_info, so it better not
11874 		 * be NULL.
11875 		 */
11876 		/*
11877 		 * the actual data will be contained in b_cont
11878 		 * upon successful return of the following call.
11879 		 * If the call fails then the original mblk is
11880 		 * returned.
11881 		 */
11882 		*mpp = ip_add_info(*mpp, ill, in_flags);
11883 	}
11884 
11885 	return (B_TRUE);
11886 }
11887 
11888 /*
11889  * Fragmentation reassembly.  Each ILL has a hash table for
11890  * queuing packets undergoing reassembly for all IPIFs
11891  * associated with the ILL.  The hash is based on the packet
11892  * IP ident field.  The ILL frag hash table was allocated
11893  * as a timer block at the time the ILL was created.  Whenever
11894  * there is anything on the reassembly queue, the timer will
11895  * be running.  Returns B_TRUE if successful else B_FALSE;
11896  * frees mp on failure.
11897  */
11898 static boolean_t
11899 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11900     uint32_t *cksum_val, uint16_t *cksum_flags)
11901 {
11902 	uint32_t	frag_offset_flags;
11903 	ill_t		*ill = (ill_t *)q->q_ptr;
11904 	mblk_t		*mp = *mpp;
11905 	mblk_t		*t_mp;
11906 	ipaddr_t	dst;
11907 	uint8_t		proto = ipha->ipha_protocol;
11908 	uint32_t	sum_val;
11909 	uint16_t	sum_flags;
11910 	ipf_t		*ipf;
11911 	ipf_t		**ipfp;
11912 	ipfb_t		*ipfb;
11913 	uint16_t	ident;
11914 	uint32_t	offset;
11915 	ipaddr_t	src;
11916 	uint_t		hdr_length;
11917 	uint32_t	end;
11918 	mblk_t		*mp1;
11919 	mblk_t		*tail_mp;
11920 	size_t		count;
11921 	size_t		msg_len;
11922 	uint8_t		ecn_info = 0;
11923 	uint32_t	packet_size;
11924 	boolean_t	pruned = B_FALSE;
11925 
11926 	if (cksum_val != NULL)
11927 		*cksum_val = 0;
11928 	if (cksum_flags != NULL)
11929 		*cksum_flags = 0;
11930 
11931 	/*
11932 	 * Drop the fragmented as early as possible, if
11933 	 * we don't have resource(s) to re-assemble.
11934 	 */
11935 	if (ip_reass_queue_bytes == 0) {
11936 		freemsg(mp);
11937 		return (B_FALSE);
11938 	}
11939 
11940 	/* Check for fragmentation offset; return if there's none */
11941 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
11942 	    (IPH_MF | IPH_OFFSET)) == 0)
11943 		return (B_TRUE);
11944 
11945 	/*
11946 	 * We utilize hardware computed checksum info only for UDP since
11947 	 * IP fragmentation is a normal occurence for the protocol.  In
11948 	 * addition, checksum offload support for IP fragments carrying
11949 	 * UDP payload is commonly implemented across network adapters.
11950 	 */
11951 	ASSERT(ill != NULL);
11952 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
11953 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
11954 		mblk_t *mp1 = mp->b_cont;
11955 		int32_t len;
11956 
11957 		/* Record checksum information from the packet */
11958 		sum_val = (uint32_t)DB_CKSUM16(mp);
11959 		sum_flags = DB_CKSUMFLAGS(mp);
11960 
11961 		/* IP payload offset from beginning of mblk */
11962 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
11963 
11964 		if ((sum_flags & HCK_PARTIALCKSUM) &&
11965 		    (mp1 == NULL || mp1->b_cont == NULL) &&
11966 		    offset >= DB_CKSUMSTART(mp) &&
11967 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
11968 			uint32_t adj;
11969 			/*
11970 			 * Partial checksum has been calculated by hardware
11971 			 * and attached to the packet; in addition, any
11972 			 * prepended extraneous data is even byte aligned.
11973 			 * If any such data exists, we adjust the checksum;
11974 			 * this would also handle any postpended data.
11975 			 */
11976 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
11977 			    mp, mp1, len, adj);
11978 
11979 			/* One's complement subtract extraneous checksum */
11980 			if (adj >= sum_val)
11981 				sum_val = ~(adj - sum_val) & 0xFFFF;
11982 			else
11983 				sum_val -= adj;
11984 		}
11985 	} else {
11986 		sum_val = 0;
11987 		sum_flags = 0;
11988 	}
11989 
11990 	/* Clear hardware checksumming flag */
11991 	DB_CKSUMFLAGS(mp) = 0;
11992 
11993 	ident = ipha->ipha_ident;
11994 	offset = (frag_offset_flags << 3) & 0xFFFF;
11995 	src = ipha->ipha_src;
11996 	dst = ipha->ipha_dst;
11997 	hdr_length = IPH_HDR_LENGTH(ipha);
11998 	end = ntohs(ipha->ipha_length) - hdr_length;
11999 
12000 	/* If end == 0 then we have a packet with no data, so just free it */
12001 	if (end == 0) {
12002 		freemsg(mp);
12003 		return (B_FALSE);
12004 	}
12005 
12006 	/* Record the ECN field info. */
12007 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12008 	if (offset != 0) {
12009 		/*
12010 		 * If this isn't the first piece, strip the header, and
12011 		 * add the offset to the end value.
12012 		 */
12013 		mp->b_rptr += hdr_length;
12014 		end += offset;
12015 	}
12016 
12017 	msg_len = MBLKSIZE(mp);
12018 	tail_mp = mp;
12019 	while (tail_mp->b_cont != NULL) {
12020 		tail_mp = tail_mp->b_cont;
12021 		msg_len += MBLKSIZE(tail_mp);
12022 	}
12023 
12024 	/* If the reassembly list for this ILL will get too big, prune it */
12025 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12026 	    ip_reass_queue_bytes) {
12027 		ill_frag_prune(ill,
12028 		    (ip_reass_queue_bytes < msg_len) ? 0 :
12029 		    (ip_reass_queue_bytes - msg_len));
12030 		pruned = B_TRUE;
12031 	}
12032 
12033 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12034 	mutex_enter(&ipfb->ipfb_lock);
12035 
12036 	ipfp = &ipfb->ipfb_ipf;
12037 	/* Try to find an existing fragment queue for this packet. */
12038 	for (;;) {
12039 		ipf = ipfp[0];
12040 		if (ipf != NULL) {
12041 			/*
12042 			 * It has to match on ident and src/dst address.
12043 			 */
12044 			if (ipf->ipf_ident == ident &&
12045 			    ipf->ipf_src == src &&
12046 			    ipf->ipf_dst == dst &&
12047 			    ipf->ipf_protocol == proto) {
12048 				/*
12049 				 * If we have received too many
12050 				 * duplicate fragments for this packet
12051 				 * free it.
12052 				 */
12053 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12054 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12055 					freemsg(mp);
12056 					mutex_exit(&ipfb->ipfb_lock);
12057 					return (B_FALSE);
12058 				}
12059 				/* Found it. */
12060 				break;
12061 			}
12062 			ipfp = &ipf->ipf_hash_next;
12063 			continue;
12064 		}
12065 
12066 		/*
12067 		 * If we pruned the list, do we want to store this new
12068 		 * fragment?. We apply an optimization here based on the
12069 		 * fact that most fragments will be received in order.
12070 		 * So if the offset of this incoming fragment is zero,
12071 		 * it is the first fragment of a new packet. We will
12072 		 * keep it.  Otherwise drop the fragment, as we have
12073 		 * probably pruned the packet already (since the
12074 		 * packet cannot be found).
12075 		 */
12076 		if (pruned && offset != 0) {
12077 			mutex_exit(&ipfb->ipfb_lock);
12078 			freemsg(mp);
12079 			return (B_FALSE);
12080 		}
12081 
12082 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12083 			/*
12084 			 * Too many fragmented packets in this hash
12085 			 * bucket. Free the oldest.
12086 			 */
12087 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12088 		}
12089 
12090 		/* New guy.  Allocate a frag message. */
12091 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12092 		if (mp1 == NULL) {
12093 			BUMP_MIB(&ip_mib, ipInDiscards);
12094 			freemsg(mp);
12095 reass_done:
12096 			mutex_exit(&ipfb->ipfb_lock);
12097 			return (B_FALSE);
12098 		}
12099 
12100 
12101 		BUMP_MIB(&ip_mib, ipReasmReqds);
12102 		mp1->b_cont = mp;
12103 
12104 		/* Initialize the fragment header. */
12105 		ipf = (ipf_t *)mp1->b_rptr;
12106 		ipf->ipf_mp = mp1;
12107 		ipf->ipf_ptphn = ipfp;
12108 		ipfp[0] = ipf;
12109 		ipf->ipf_hash_next = NULL;
12110 		ipf->ipf_ident = ident;
12111 		ipf->ipf_protocol = proto;
12112 		ipf->ipf_src = src;
12113 		ipf->ipf_dst = dst;
12114 		ipf->ipf_nf_hdr_len = 0;
12115 		/* Record reassembly start time. */
12116 		ipf->ipf_timestamp = gethrestime_sec();
12117 		/* Record ipf generation and account for frag header */
12118 		ipf->ipf_gen = ill->ill_ipf_gen++;
12119 		ipf->ipf_count = MBLKSIZE(mp1);
12120 		ipf->ipf_last_frag_seen = B_FALSE;
12121 		ipf->ipf_ecn = ecn_info;
12122 		ipf->ipf_num_dups = 0;
12123 		ipfb->ipfb_frag_pkts++;
12124 		ipf->ipf_checksum = 0;
12125 		ipf->ipf_checksum_flags = 0;
12126 
12127 		/* Store checksum value in fragment header */
12128 		if (sum_flags != 0) {
12129 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12130 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12131 			ipf->ipf_checksum = sum_val;
12132 			ipf->ipf_checksum_flags = sum_flags;
12133 		}
12134 
12135 		/*
12136 		 * We handle reassembly two ways.  In the easy case,
12137 		 * where all the fragments show up in order, we do
12138 		 * minimal bookkeeping, and just clip new pieces on
12139 		 * the end.  If we ever see a hole, then we go off
12140 		 * to ip_reassemble which has to mark the pieces and
12141 		 * keep track of the number of holes, etc.  Obviously,
12142 		 * the point of having both mechanisms is so we can
12143 		 * handle the easy case as efficiently as possible.
12144 		 */
12145 		if (offset == 0) {
12146 			/* Easy case, in-order reassembly so far. */
12147 			ipf->ipf_count += msg_len;
12148 			ipf->ipf_tail_mp = tail_mp;
12149 			/*
12150 			 * Keep track of next expected offset in
12151 			 * ipf_end.
12152 			 */
12153 			ipf->ipf_end = end;
12154 			ipf->ipf_nf_hdr_len = hdr_length;
12155 		} else {
12156 			/* Hard case, hole at the beginning. */
12157 			ipf->ipf_tail_mp = NULL;
12158 			/*
12159 			 * ipf_end == 0 means that we have given up
12160 			 * on easy reassembly.
12161 			 */
12162 			ipf->ipf_end = 0;
12163 
12164 			/* Forget checksum offload from now on */
12165 			ipf->ipf_checksum_flags = 0;
12166 
12167 			/*
12168 			 * ipf_hole_cnt is set by ip_reassemble.
12169 			 * ipf_count is updated by ip_reassemble.
12170 			 * No need to check for return value here
12171 			 * as we don't expect reassembly to complete
12172 			 * or fail for the first fragment itself.
12173 			 */
12174 			(void) ip_reassemble(mp, ipf,
12175 			    (frag_offset_flags & IPH_OFFSET) << 3,
12176 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12177 		}
12178 		/* Update per ipfb and ill byte counts */
12179 		ipfb->ipfb_count += ipf->ipf_count;
12180 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12181 		ill->ill_frag_count += ipf->ipf_count;
12182 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12183 		/* If the frag timer wasn't already going, start it. */
12184 		mutex_enter(&ill->ill_lock);
12185 		ill_frag_timer_start(ill);
12186 		mutex_exit(&ill->ill_lock);
12187 		goto reass_done;
12188 	}
12189 
12190 	/*
12191 	 * If the packet's flag has changed (it could be coming up
12192 	 * from an interface different than the previous, therefore
12193 	 * possibly different checksum capability), then forget about
12194 	 * any stored checksum states.  Otherwise add the value to
12195 	 * the existing one stored in the fragment header.
12196 	 */
12197 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12198 		sum_val += ipf->ipf_checksum;
12199 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12200 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12201 		ipf->ipf_checksum = sum_val;
12202 	} else if (ipf->ipf_checksum_flags != 0) {
12203 		/* Forget checksum offload from now on */
12204 		ipf->ipf_checksum_flags = 0;
12205 	}
12206 
12207 	/*
12208 	 * We have a new piece of a datagram which is already being
12209 	 * reassembled.  Update the ECN info if all IP fragments
12210 	 * are ECN capable.  If there is one which is not, clear
12211 	 * all the info.  If there is at least one which has CE
12212 	 * code point, IP needs to report that up to transport.
12213 	 */
12214 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12215 		if (ecn_info == IPH_ECN_CE)
12216 			ipf->ipf_ecn = IPH_ECN_CE;
12217 	} else {
12218 		ipf->ipf_ecn = IPH_ECN_NECT;
12219 	}
12220 	if (offset && ipf->ipf_end == offset) {
12221 		/* The new fragment fits at the end */
12222 		ipf->ipf_tail_mp->b_cont = mp;
12223 		/* Update the byte count */
12224 		ipf->ipf_count += msg_len;
12225 		/* Update per ipfb and ill byte counts */
12226 		ipfb->ipfb_count += msg_len;
12227 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12228 		ill->ill_frag_count += msg_len;
12229 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12230 		if (frag_offset_flags & IPH_MF) {
12231 			/* More to come. */
12232 			ipf->ipf_end = end;
12233 			ipf->ipf_tail_mp = tail_mp;
12234 			goto reass_done;
12235 		}
12236 	} else {
12237 		/* Go do the hard cases. */
12238 		int ret;
12239 
12240 		if (offset == 0)
12241 			ipf->ipf_nf_hdr_len = hdr_length;
12242 
12243 		/* Save current byte count */
12244 		count = ipf->ipf_count;
12245 		ret = ip_reassemble(mp, ipf,
12246 		    (frag_offset_flags & IPH_OFFSET) << 3,
12247 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12248 		/* Count of bytes added and subtracted (freeb()ed) */
12249 		count = ipf->ipf_count - count;
12250 		if (count) {
12251 			/* Update per ipfb and ill byte counts */
12252 			ipfb->ipfb_count += count;
12253 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12254 			ill->ill_frag_count += count;
12255 			ASSERT(ill->ill_frag_count > 0);
12256 		}
12257 		if (ret == IP_REASS_PARTIAL) {
12258 			goto reass_done;
12259 		} else if (ret == IP_REASS_FAILED) {
12260 			/* Reassembly failed. Free up all resources */
12261 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12262 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12263 				IP_REASS_SET_START(t_mp, 0);
12264 				IP_REASS_SET_END(t_mp, 0);
12265 			}
12266 			freemsg(mp);
12267 			goto reass_done;
12268 		}
12269 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12270 	}
12271 	/*
12272 	 * We have completed reassembly.  Unhook the frag header from
12273 	 * the reassembly list.
12274 	 *
12275 	 * Before we free the frag header, record the ECN info
12276 	 * to report back to the transport.
12277 	 */
12278 	ecn_info = ipf->ipf_ecn;
12279 	BUMP_MIB(&ip_mib, ipReasmOKs);
12280 	ipfp = ipf->ipf_ptphn;
12281 
12282 	/* We need to supply these to caller */
12283 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12284 		sum_val = ipf->ipf_checksum;
12285 	else
12286 		sum_val = 0;
12287 
12288 	mp1 = ipf->ipf_mp;
12289 	count = ipf->ipf_count;
12290 	ipf = ipf->ipf_hash_next;
12291 	if (ipf != NULL)
12292 		ipf->ipf_ptphn = ipfp;
12293 	ipfp[0] = ipf;
12294 	ill->ill_frag_count -= count;
12295 	ASSERT(ipfb->ipfb_count >= count);
12296 	ipfb->ipfb_count -= count;
12297 	ipfb->ipfb_frag_pkts--;
12298 	mutex_exit(&ipfb->ipfb_lock);
12299 	/* Ditch the frag header. */
12300 	mp = mp1->b_cont;
12301 
12302 	freeb(mp1);
12303 
12304 	/* Restore original IP length in header. */
12305 	packet_size = (uint32_t)msgdsize(mp);
12306 	if (packet_size > IP_MAXPACKET) {
12307 		freemsg(mp);
12308 		BUMP_MIB(&ip_mib, ipInHdrErrors);
12309 		return (B_FALSE);
12310 	}
12311 
12312 	if (DB_REF(mp) > 1) {
12313 		mblk_t *mp2 = copymsg(mp);
12314 
12315 		freemsg(mp);
12316 		if (mp2 == NULL) {
12317 			BUMP_MIB(&ip_mib, ipInDiscards);
12318 			return (B_FALSE);
12319 		}
12320 		mp = mp2;
12321 	}
12322 	ipha = (ipha_t *)mp->b_rptr;
12323 
12324 	ipha->ipha_length = htons((uint16_t)packet_size);
12325 	/* We're now complete, zip the frag state */
12326 	ipha->ipha_fragment_offset_and_flags = 0;
12327 	/* Record the ECN info. */
12328 	ipha->ipha_type_of_service &= 0xFC;
12329 	ipha->ipha_type_of_service |= ecn_info;
12330 	*mpp = mp;
12331 
12332 	/* Reassembly is successful; return checksum information if needed */
12333 	if (cksum_val != NULL)
12334 		*cksum_val = sum_val;
12335 	if (cksum_flags != NULL)
12336 		*cksum_flags = sum_flags;
12337 
12338 	return (B_TRUE);
12339 }
12340 
12341 /*
12342  * Perform ip header check sum update local options.
12343  * return B_TRUE if all is well, else return B_FALSE and release
12344  * the mp. caller is responsible for decrementing ire ref cnt.
12345  */
12346 static boolean_t
12347 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12348 {
12349 	mblk_t		*first_mp;
12350 	boolean_t	mctl_present;
12351 	uint16_t	sum;
12352 
12353 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12354 	/*
12355 	 * Don't do the checksum if it has gone through AH/ESP
12356 	 * processing.
12357 	 */
12358 	if (!mctl_present) {
12359 		sum = ip_csum_hdr(ipha);
12360 		if (sum != 0) {
12361 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12362 			freemsg(first_mp);
12363 			return (B_FALSE);
12364 		}
12365 	}
12366 
12367 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12368 		if (mctl_present)
12369 			freeb(first_mp);
12370 		return (B_FALSE);
12371 	}
12372 
12373 	return (B_TRUE);
12374 }
12375 
12376 /*
12377  * All udp packet are delivered to the local host via this routine.
12378  */
12379 void
12380 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12381     ill_t *recv_ill)
12382 {
12383 	uint32_t	sum;
12384 	uint32_t	u1;
12385 	boolean_t	mctl_present;
12386 	conn_t		*connp;
12387 	mblk_t		*first_mp;
12388 	uint16_t	*up;
12389 	ill_t		*ill = (ill_t *)q->q_ptr;
12390 	uint16_t	reass_hck_flags = 0;
12391 
12392 #define	rptr    ((uchar_t *)ipha)
12393 
12394 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12395 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12396 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12397 
12398 	/*
12399 	 * FAST PATH for udp packets
12400 	 */
12401 
12402 	/* u1 is # words of IP options */
12403 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12404 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12405 
12406 	/* IP options present */
12407 	if (u1 != 0)
12408 		goto ipoptions;
12409 
12410 	/* Check the IP header checksum.  */
12411 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12412 		/* Clear the IP header h/w cksum flag */
12413 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12414 	} else {
12415 #define	uph	((uint16_t *)ipha)
12416 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12417 		    uph[6] + uph[7] + uph[8] + uph[9];
12418 #undef	uph
12419 		/* finish doing IP checksum */
12420 		sum = (sum & 0xFFFF) + (sum >> 16);
12421 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12422 		/*
12423 		 * Don't verify header checksum if this packet is coming
12424 		 * back from AH/ESP as we already did it.
12425 		 */
12426 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12427 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12428 			freemsg(first_mp);
12429 			return;
12430 		}
12431 	}
12432 
12433 	/*
12434 	 * Count for SNMP of inbound packets for ire.
12435 	 * if mctl is present this might be a secure packet and
12436 	 * has already been counted for in ip_proto_input().
12437 	 */
12438 	if (!mctl_present) {
12439 		UPDATE_IB_PKT_COUNT(ire);
12440 		ire->ire_last_used_time = lbolt;
12441 	}
12442 
12443 	/* packet part of fragmented IP packet? */
12444 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12445 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12446 		goto fragmented;
12447 	}
12448 
12449 	/* u1 = IP header length (20 bytes) */
12450 	u1 = IP_SIMPLE_HDR_LENGTH;
12451 
12452 	/* packet does not contain complete IP & UDP headers */
12453 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12454 		goto udppullup;
12455 
12456 	/* up points to UDP header */
12457 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12458 #define	iphs    ((uint16_t *)ipha)
12459 
12460 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12461 	if (up[3] != 0) {
12462 		mblk_t *mp1 = mp->b_cont;
12463 		boolean_t cksum_err;
12464 		uint16_t hck_flags = 0;
12465 
12466 		/* Pseudo-header checksum */
12467 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12468 		    iphs[9] + up[2];
12469 
12470 		/*
12471 		 * Revert to software checksum calculation if the interface
12472 		 * isn't capable of checksum offload or if IPsec is present.
12473 		 */
12474 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12475 			hck_flags = DB_CKSUMFLAGS(mp);
12476 
12477 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12478 			IP_STAT(ip_in_sw_cksum);
12479 
12480 		IP_CKSUM_RECV(hck_flags, u1,
12481 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12482 		    (int32_t)((uchar_t *)up - rptr),
12483 		    mp, mp1, cksum_err);
12484 
12485 		if (cksum_err) {
12486 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12487 
12488 			if (hck_flags & HCK_FULLCKSUM)
12489 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12490 			else if (hck_flags & HCK_PARTIALCKSUM)
12491 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12492 			else
12493 				IP_STAT(ip_udp_in_sw_cksum_err);
12494 
12495 			freemsg(first_mp);
12496 			return;
12497 		}
12498 	}
12499 
12500 	/* Non-fragmented broadcast or multicast packet? */
12501 	if (ire->ire_type == IRE_BROADCAST)
12502 		goto udpslowpath;
12503 
12504 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12505 	    ire->ire_zoneid)) != NULL) {
12506 		ASSERT(connp->conn_upq != NULL);
12507 		IP_STAT(ip_udp_fast_path);
12508 
12509 		if (CONN_UDP_FLOWCTLD(connp)) {
12510 			freemsg(mp);
12511 			BUMP_MIB(&ip_mib, udpInOverflows);
12512 		} else {
12513 			if (!mctl_present) {
12514 				BUMP_MIB(&ip_mib, ipInDelivers);
12515 			}
12516 			/*
12517 			 * mp and first_mp can change.
12518 			 */
12519 			if (ip_udp_check(q, connp, recv_ill,
12520 			    ipha, &mp, &first_mp, mctl_present)) {
12521 				/* Send it upstream */
12522 				CONN_UDP_RECV(connp, mp);
12523 			}
12524 		}
12525 		/*
12526 		 * freeb() cannot deal with null mblk being passed
12527 		 * in and first_mp can be set to null in the call
12528 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12529 		 */
12530 		if (mctl_present && first_mp != NULL) {
12531 			freeb(first_mp);
12532 		}
12533 		CONN_DEC_REF(connp);
12534 		return;
12535 	}
12536 
12537 	/*
12538 	 * if we got here we know the packet is not fragmented and
12539 	 * has no options. The classifier could not find a conn_t and
12540 	 * most likely its an icmp packet so send it through slow path.
12541 	 */
12542 
12543 	goto udpslowpath;
12544 
12545 ipoptions:
12546 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12547 		goto slow_done;
12548 	}
12549 
12550 	UPDATE_IB_PKT_COUNT(ire);
12551 	ire->ire_last_used_time = lbolt;
12552 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12553 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12554 fragmented:
12555 		/*
12556 		 * "sum" and "reass_hck_flags" are non-zero if the
12557 		 * reassembled packet has a valid hardware computed
12558 		 * checksum information associated with it.
12559 		 */
12560 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12561 			goto slow_done;
12562 		/*
12563 		 * Make sure that first_mp points back to mp as
12564 		 * the mp we came in with could have changed in
12565 		 * ip_rput_fragment().
12566 		 */
12567 		ASSERT(!mctl_present);
12568 		ipha = (ipha_t *)mp->b_rptr;
12569 		first_mp = mp;
12570 	}
12571 
12572 	/* Now we have a complete datagram, destined for this machine. */
12573 	u1 = IPH_HDR_LENGTH(ipha);
12574 	/* Pull up the UDP header, if necessary. */
12575 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12576 udppullup:
12577 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12578 			BUMP_MIB(&ip_mib, ipInDiscards);
12579 			freemsg(first_mp);
12580 			goto slow_done;
12581 		}
12582 		ipha = (ipha_t *)mp->b_rptr;
12583 	}
12584 
12585 	/*
12586 	 * Validate the checksum for the reassembled packet; for the
12587 	 * pullup case we calculate the payload checksum in software.
12588 	 */
12589 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12590 	if (up[3] != 0) {
12591 		boolean_t cksum_err;
12592 
12593 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12594 			IP_STAT(ip_in_sw_cksum);
12595 
12596 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12597 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12598 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12599 		    iphs[9] + up[2], sum, cksum_err);
12600 
12601 		if (cksum_err) {
12602 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12603 
12604 			if (reass_hck_flags & HCK_FULLCKSUM)
12605 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12606 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12607 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12608 			else
12609 				IP_STAT(ip_udp_in_sw_cksum_err);
12610 
12611 			freemsg(first_mp);
12612 			goto slow_done;
12613 		}
12614 	}
12615 udpslowpath:
12616 
12617 	/* Clear hardware checksum flag to be safe */
12618 	DB_CKSUMFLAGS(mp) = 0;
12619 
12620 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12621 	    (ire->ire_type == IRE_BROADCAST),
12622 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12623 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12624 
12625 slow_done:
12626 	IP_STAT(ip_udp_slow_path);
12627 	return;
12628 
12629 #undef  iphs
12630 #undef  rptr
12631 }
12632 
12633 /* ARGSUSED */
12634 static mblk_t *
12635 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12636     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12637     ill_rx_ring_t *ill_ring)
12638 {
12639 	conn_t		*connp;
12640 	uint32_t	sum;
12641 	uint32_t	u1;
12642 	uint16_t	*up;
12643 	int		offset;
12644 	ssize_t		len;
12645 	mblk_t		*mp1;
12646 	boolean_t	syn_present = B_FALSE;
12647 	tcph_t		*tcph;
12648 	uint_t		ip_hdr_len;
12649 	ill_t		*ill = (ill_t *)q->q_ptr;
12650 	zoneid_t	zoneid = ire->ire_zoneid;
12651 	boolean_t	cksum_err;
12652 	uint16_t	hck_flags = 0;
12653 
12654 #define	rptr	((uchar_t *)ipha)
12655 
12656 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12657 
12658 	/*
12659 	 * FAST PATH for tcp packets
12660 	 */
12661 
12662 	/* u1 is # words of IP options */
12663 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12664 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12665 
12666 	/* IP options present */
12667 	if (u1) {
12668 		goto ipoptions;
12669 	} else {
12670 		/* Check the IP header checksum.  */
12671 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12672 			/* Clear the IP header h/w cksum flag */
12673 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12674 		} else {
12675 #define	uph	((uint16_t *)ipha)
12676 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12677 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12678 #undef	uph
12679 			/* finish doing IP checksum */
12680 			sum = (sum & 0xFFFF) + (sum >> 16);
12681 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12682 			/*
12683 			 * Don't verify header checksum if this packet
12684 			 * is coming back from AH/ESP as we already did it.
12685 			 */
12686 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12687 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12688 				goto error;
12689 			}
12690 		}
12691 	}
12692 
12693 	if (!mctl_present) {
12694 		UPDATE_IB_PKT_COUNT(ire);
12695 		ire->ire_last_used_time = lbolt;
12696 	}
12697 
12698 	/* packet part of fragmented IP packet? */
12699 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12700 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12701 		goto fragmented;
12702 	}
12703 
12704 	/* u1 = IP header length (20 bytes) */
12705 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12706 
12707 	/* does packet contain IP+TCP headers? */
12708 	len = mp->b_wptr - rptr;
12709 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12710 		IP_STAT(ip_tcppullup);
12711 		goto tcppullup;
12712 	}
12713 
12714 	/* TCP options present? */
12715 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12716 
12717 	/*
12718 	 * If options need to be pulled up, then goto tcpoptions.
12719 	 * otherwise we are still in the fast path
12720 	 */
12721 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12722 		IP_STAT(ip_tcpoptions);
12723 		goto tcpoptions;
12724 	}
12725 
12726 	/* multiple mblks of tcp data? */
12727 	if ((mp1 = mp->b_cont) != NULL) {
12728 		/* more then two? */
12729 		if (mp1->b_cont != NULL) {
12730 			IP_STAT(ip_multipkttcp);
12731 			goto multipkttcp;
12732 		}
12733 		len += mp1->b_wptr - mp1->b_rptr;
12734 	}
12735 
12736 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12737 
12738 	/* part of pseudo checksum */
12739 
12740 	/* TCP datagram length */
12741 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12742 
12743 #define	iphs    ((uint16_t *)ipha)
12744 
12745 #ifdef	_BIG_ENDIAN
12746 	u1 += IPPROTO_TCP;
12747 #else
12748 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12749 #endif
12750 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12751 
12752 	/*
12753 	 * Revert to software checksum calculation if the interface
12754 	 * isn't capable of checksum offload or if IPsec is present.
12755 	 */
12756 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12757 		hck_flags = DB_CKSUMFLAGS(mp);
12758 
12759 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12760 		IP_STAT(ip_in_sw_cksum);
12761 
12762 	IP_CKSUM_RECV(hck_flags, u1,
12763 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12764 	    (int32_t)((uchar_t *)up - rptr),
12765 	    mp, mp1, cksum_err);
12766 
12767 	if (cksum_err) {
12768 		BUMP_MIB(&ip_mib, tcpInErrs);
12769 
12770 		if (hck_flags & HCK_FULLCKSUM)
12771 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12772 		else if (hck_flags & HCK_PARTIALCKSUM)
12773 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12774 		else
12775 			IP_STAT(ip_tcp_in_sw_cksum_err);
12776 
12777 		goto error;
12778 	}
12779 
12780 try_again:
12781 
12782 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12783 	    NULL) {
12784 		/* Send the TH_RST */
12785 		goto no_conn;
12786 	}
12787 
12788 	/*
12789 	 * TCP FAST PATH for AF_INET socket.
12790 	 *
12791 	 * TCP fast path to avoid extra work. An AF_INET socket type
12792 	 * does not have facility to receive extra information via
12793 	 * ip_process or ip_add_info. Also, when the connection was
12794 	 * established, we made a check if this connection is impacted
12795 	 * by any global IPSec policy or per connection policy (a
12796 	 * policy that comes in effect later will not apply to this
12797 	 * connection). Since all this can be determined at the
12798 	 * connection establishment time, a quick check of flags
12799 	 * can avoid extra work.
12800 	 */
12801 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12802 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12803 		ASSERT(first_mp == mp);
12804 		SET_SQUEUE(mp, tcp_rput_data, connp);
12805 		return (mp);
12806 	}
12807 
12808 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12809 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12810 		if (IPCL_IS_TCP(connp)) {
12811 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12812 			DB_CKSUMSTART(mp) =
12813 			    (intptr_t)ip_squeue_get(ill_ring);
12814 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12815 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12816 				SET_SQUEUE(mp, connp->conn_recv, connp);
12817 				return (mp);
12818 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12819 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12820 				ip_squeue_enter_unbound++;
12821 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12822 				    connp);
12823 				return (mp);
12824 			}
12825 			syn_present = B_TRUE;
12826 		}
12827 
12828 	}
12829 
12830 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12831 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12832 
12833 		/* No need to send this packet to TCP */
12834 		if ((flags & TH_RST) || (flags & TH_URG)) {
12835 			CONN_DEC_REF(connp);
12836 			freemsg(first_mp);
12837 			return (NULL);
12838 		}
12839 		if (flags & TH_ACK) {
12840 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
12841 			CONN_DEC_REF(connp);
12842 			return (NULL);
12843 		}
12844 
12845 		CONN_DEC_REF(connp);
12846 		freemsg(first_mp);
12847 		return (NULL);
12848 	}
12849 
12850 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12851 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12852 		    ipha, NULL, mctl_present);
12853 		if (first_mp == NULL) {
12854 			CONN_DEC_REF(connp);
12855 			return (NULL);
12856 		}
12857 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12858 			ASSERT(syn_present);
12859 			if (mctl_present) {
12860 				ASSERT(first_mp != mp);
12861 				first_mp->b_datap->db_struioflag |=
12862 				    STRUIO_POLICY;
12863 			} else {
12864 				ASSERT(first_mp == mp);
12865 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12866 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12867 			}
12868 		} else {
12869 			/*
12870 			 * Discard first_mp early since we're dealing with a
12871 			 * fully-connected conn_t and tcp doesn't do policy in
12872 			 * this case.
12873 			 */
12874 			if (mctl_present) {
12875 				freeb(first_mp);
12876 				mctl_present = B_FALSE;
12877 			}
12878 			first_mp = mp;
12879 		}
12880 	}
12881 
12882 	/* Initiate IPPF processing for fastpath */
12883 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12884 		uint32_t	ill_index;
12885 
12886 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12887 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12888 		if (mp == NULL) {
12889 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12890 			    "deferred/dropped during IPPF processing\n"));
12891 			CONN_DEC_REF(connp);
12892 			if (mctl_present)
12893 				freeb(first_mp);
12894 			return (NULL);
12895 		} else if (mctl_present) {
12896 			/*
12897 			 * ip_process might return a new mp.
12898 			 */
12899 			ASSERT(first_mp != mp);
12900 			first_mp->b_cont = mp;
12901 		} else {
12902 			first_mp = mp;
12903 		}
12904 
12905 	}
12906 
12907 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12908 		mp = ip_add_info(mp, recv_ill, flags);
12909 		if (mp == NULL) {
12910 			CONN_DEC_REF(connp);
12911 			if (mctl_present)
12912 				freeb(first_mp);
12913 			return (NULL);
12914 		} else if (mctl_present) {
12915 			/*
12916 			 * ip_add_info might return a new mp.
12917 			 */
12918 			ASSERT(first_mp != mp);
12919 			first_mp->b_cont = mp;
12920 		} else {
12921 			first_mp = mp;
12922 		}
12923 	}
12924 
12925 	if (IPCL_IS_TCP(connp)) {
12926 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
12927 		return (first_mp);
12928 	} else {
12929 		putnext(connp->conn_rq, first_mp);
12930 		CONN_DEC_REF(connp);
12931 		return (NULL);
12932 	}
12933 
12934 no_conn:
12935 	/* Initiate IPPf processing, if needed. */
12936 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12937 		uint32_t ill_index;
12938 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12939 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
12940 		if (first_mp == NULL) {
12941 			return (NULL);
12942 		}
12943 	}
12944 	BUMP_MIB(&ip_mib, ipInDelivers);
12945 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid);
12946 	return (NULL);
12947 ipoptions:
12948 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
12949 		goto slow_done;
12950 	}
12951 
12952 	UPDATE_IB_PKT_COUNT(ire);
12953 	ire->ire_last_used_time = lbolt;
12954 
12955 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12956 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12957 fragmented:
12958 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
12959 			if (mctl_present)
12960 				freeb(first_mp);
12961 			goto slow_done;
12962 		}
12963 		/*
12964 		 * Make sure that first_mp points back to mp as
12965 		 * the mp we came in with could have changed in
12966 		 * ip_rput_fragment().
12967 		 */
12968 		ASSERT(!mctl_present);
12969 		ipha = (ipha_t *)mp->b_rptr;
12970 		first_mp = mp;
12971 	}
12972 
12973 	/* Now we have a complete datagram, destined for this machine. */
12974 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12975 
12976 	len = mp->b_wptr - mp->b_rptr;
12977 	/* Pull up a minimal TCP header, if necessary. */
12978 	if (len < (u1 + 20)) {
12979 tcppullup:
12980 		if (!pullupmsg(mp, u1 + 20)) {
12981 			BUMP_MIB(&ip_mib, ipInDiscards);
12982 			goto error;
12983 		}
12984 		ipha = (ipha_t *)mp->b_rptr;
12985 		len = mp->b_wptr - mp->b_rptr;
12986 	}
12987 
12988 	/*
12989 	 * Extract the offset field from the TCP header.  As usual, we
12990 	 * try to help the compiler more than the reader.
12991 	 */
12992 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
12993 	if (offset != 5) {
12994 tcpoptions:
12995 		if (offset < 5) {
12996 			BUMP_MIB(&ip_mib, ipInDiscards);
12997 			goto error;
12998 		}
12999 		/*
13000 		 * There must be TCP options.
13001 		 * Make sure we can grab them.
13002 		 */
13003 		offset <<= 2;
13004 		offset += u1;
13005 		if (len < offset) {
13006 			if (!pullupmsg(mp, offset)) {
13007 				BUMP_MIB(&ip_mib, ipInDiscards);
13008 				goto error;
13009 			}
13010 			ipha = (ipha_t *)mp->b_rptr;
13011 			len = mp->b_wptr - rptr;
13012 		}
13013 	}
13014 
13015 	/* Get the total packet length in len, including headers. */
13016 	if (mp->b_cont) {
13017 multipkttcp:
13018 		len = msgdsize(mp);
13019 	}
13020 
13021 	/*
13022 	 * Check the TCP checksum by pulling together the pseudo-
13023 	 * header checksum, and passing it to ip_csum to be added in
13024 	 * with the TCP datagram.
13025 	 *
13026 	 * Since we are not using the hwcksum if available we must
13027 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13028 	 * If either of these fails along the way the mblk is freed.
13029 	 * If this logic ever changes and mblk is reused to say send
13030 	 * ICMP's back, then this flag may need to be cleared in
13031 	 * other places as well.
13032 	 */
13033 	DB_CKSUMFLAGS(mp) = 0;
13034 
13035 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13036 
13037 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13038 #ifdef	_BIG_ENDIAN
13039 	u1 += IPPROTO_TCP;
13040 #else
13041 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13042 #endif
13043 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13044 	/*
13045 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13046 	 */
13047 	IP_STAT(ip_in_sw_cksum);
13048 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13049 		BUMP_MIB(&ip_mib, tcpInErrs);
13050 		goto error;
13051 	}
13052 
13053 	IP_STAT(ip_tcp_slow_path);
13054 	goto try_again;
13055 #undef  iphs
13056 #undef  rptr
13057 
13058 error:
13059 	freemsg(first_mp);
13060 slow_done:
13061 	return (NULL);
13062 }
13063 
13064 /* ARGSUSED */
13065 static void
13066 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13067     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13068 {
13069 	conn_t		*connp;
13070 	uint32_t	sum;
13071 	uint32_t	u1;
13072 	ssize_t		len;
13073 	sctp_hdr_t	*sctph;
13074 	zoneid_t	zoneid = ire->ire_zoneid;
13075 	uint32_t	pktsum;
13076 	uint32_t	calcsum;
13077 	uint32_t	ports;
13078 	uint_t		ipif_seqid;
13079 	in6_addr_t	map_src, map_dst;
13080 	ill_t		*ill = (ill_t *)q->q_ptr;
13081 
13082 #define	rptr	((uchar_t *)ipha)
13083 
13084 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13085 
13086 	/* u1 is # words of IP options */
13087 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13088 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13089 
13090 	/* IP options present */
13091 	if (u1 > 0) {
13092 		goto ipoptions;
13093 	} else {
13094 		/* Check the IP header checksum.  */
13095 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13096 #define	uph	((uint16_t *)ipha)
13097 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13098 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13099 #undef	uph
13100 			/* finish doing IP checksum */
13101 			sum = (sum & 0xFFFF) + (sum >> 16);
13102 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13103 			/*
13104 			 * Don't verify header checksum if this packet
13105 			 * is coming back from AH/ESP as we already did it.
13106 			 */
13107 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13108 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13109 				goto error;
13110 			}
13111 		}
13112 		/*
13113 		 * Since there is no SCTP h/w cksum support yet, just
13114 		 * clear the flag.
13115 		 */
13116 		DB_CKSUMFLAGS(mp) = 0;
13117 	}
13118 
13119 	/*
13120 	 * Don't verify header checksum if this packet is coming
13121 	 * back from AH/ESP as we already did it.
13122 	 */
13123 	if (!mctl_present) {
13124 		UPDATE_IB_PKT_COUNT(ire);
13125 		ire->ire_last_used_time = lbolt;
13126 	}
13127 
13128 	/* packet part of fragmented IP packet? */
13129 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13130 	if (u1 & (IPH_MF | IPH_OFFSET))
13131 		goto fragmented;
13132 
13133 	/* u1 = IP header length (20 bytes) */
13134 	u1 = IP_SIMPLE_HDR_LENGTH;
13135 
13136 find_sctp_client:
13137 	/* Pullup if we don't have the sctp common header. */
13138 	len = MBLKL(mp);
13139 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13140 		if (mp->b_cont == NULL ||
13141 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13142 			BUMP_MIB(&ip_mib, ipInDiscards);
13143 			goto error;
13144 		}
13145 		ipha = (ipha_t *)mp->b_rptr;
13146 		len = MBLKL(mp);
13147 	}
13148 
13149 	sctph = (sctp_hdr_t *)(rptr + u1);
13150 #ifdef	DEBUG
13151 	if (!skip_sctp_cksum) {
13152 #endif
13153 		pktsum = sctph->sh_chksum;
13154 		sctph->sh_chksum = 0;
13155 		calcsum = sctp_cksum(mp, u1);
13156 		if (calcsum != pktsum) {
13157 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13158 			goto error;
13159 		}
13160 		sctph->sh_chksum = pktsum;
13161 #ifdef	DEBUG	/* skip_sctp_cksum */
13162 	}
13163 #endif
13164 	/* get the ports */
13165 	ports = *(uint32_t *)&sctph->sh_sport;
13166 
13167 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13168 	IRE_REFRELE(ire);
13169 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13170 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13171 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13172 	    mp)) == NULL) {
13173 		/* Check for raw socket or OOTB handling */
13174 		goto no_conn;
13175 	}
13176 
13177 	/* Found a client; up it goes */
13178 	BUMP_MIB(&ip_mib, ipInDelivers);
13179 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13180 	return;
13181 
13182 no_conn:
13183 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13184 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13185 	return;
13186 
13187 ipoptions:
13188 	DB_CKSUMFLAGS(mp) = 0;
13189 	if (!ip_options_cksum(q, first_mp, ipha, ire))
13190 		goto slow_done;
13191 
13192 	UPDATE_IB_PKT_COUNT(ire);
13193 	ire->ire_last_used_time = lbolt;
13194 
13195 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13196 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13197 fragmented:
13198 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13199 			goto slow_done;
13200 		/*
13201 		 * Make sure that first_mp points back to mp as
13202 		 * the mp we came in with could have changed in
13203 		 * ip_rput_fragment().
13204 		 */
13205 		ASSERT(!mctl_present);
13206 		ipha = (ipha_t *)mp->b_rptr;
13207 		first_mp = mp;
13208 	}
13209 
13210 	/* Now we have a complete datagram, destined for this machine. */
13211 	u1 = IPH_HDR_LENGTH(ipha);
13212 	goto find_sctp_client;
13213 #undef  iphs
13214 #undef  rptr
13215 
13216 error:
13217 	freemsg(first_mp);
13218 slow_done:
13219 	IRE_REFRELE(ire);
13220 }
13221 
13222 #define	VER_BITS	0xF0
13223 #define	VERSION_6	0x60
13224 
13225 static boolean_t
13226 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
13227     ipaddr_t *dstp)
13228 {
13229 	uint_t	opt_len;
13230 	ipha_t *ipha;
13231 	ssize_t len;
13232 	uint_t	pkt_len;
13233 
13234 	IP_STAT(ip_ipoptions);
13235 	ipha = *iphapp;
13236 
13237 #define	rptr    ((uchar_t *)ipha)
13238 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13239 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13240 		BUMP_MIB(&ip_mib, ipInIPv6);
13241 		freemsg(mp);
13242 		return (B_FALSE);
13243 	}
13244 
13245 	/* multiple mblk or too short */
13246 	pkt_len = ntohs(ipha->ipha_length);
13247 
13248 	/* Get the number of words of IP options in the IP header. */
13249 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13250 	if (opt_len) {
13251 		/* IP Options present!  Validate and process. */
13252 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13253 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13254 			goto done;
13255 		}
13256 		/*
13257 		 * Recompute complete header length and make sure we
13258 		 * have access to all of it.
13259 		 */
13260 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13261 		if (len > (mp->b_wptr - rptr)) {
13262 			if (len > pkt_len) {
13263 				BUMP_MIB(&ip_mib, ipInHdrErrors);
13264 				goto done;
13265 			}
13266 			if (!pullupmsg(mp, len)) {
13267 				BUMP_MIB(&ip_mib, ipInDiscards);
13268 				goto done;
13269 			}
13270 			ipha = (ipha_t *)mp->b_rptr;
13271 		}
13272 		/*
13273 		 * Go off to ip_rput_options which returns the next hop
13274 		 * destination address, which may have been affected
13275 		 * by source routing.
13276 		 */
13277 		IP_STAT(ip_opt);
13278 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13279 			return (B_FALSE);
13280 		}
13281 	}
13282 	*iphapp = ipha;
13283 	return (B_TRUE);
13284 done:
13285 	/* clear b_prev - used by ip_mroute_decap */
13286 	mp->b_prev = NULL;
13287 	freemsg(mp);
13288 	return (B_FALSE);
13289 #undef  rptr
13290 }
13291 
13292 /*
13293  * Deal with the fact that there is no ire for the destination.
13294  * The incoming ill (in_ill) is passed in to ip_newroute only
13295  * in the case of packets coming from mobile ip forward tunnel.
13296  * It must be null otherwise.
13297  */
13298 static ire_t *
13299 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13300     ipaddr_t dst)
13301 {
13302 	ipha_t	*ipha;
13303 	ill_t	*ill;
13304 	ire_t	*ire;
13305 	boolean_t	check_multirt = B_FALSE;
13306 
13307 	ipha = (ipha_t *)mp->b_rptr;
13308 	ill = (ill_t *)q->q_ptr;
13309 
13310 	ASSERT(ill != NULL);
13311 	/*
13312 	 * No IRE for this destination, so it can't be for us.
13313 	 * Unless we are forwarding, drop the packet.
13314 	 * We have to let source routed packets through
13315 	 * since we don't yet know if they are 'ping -l'
13316 	 * packets i.e. if they will go out over the
13317 	 * same interface as they came in on.
13318 	 */
13319 	if (ll_multicast) {
13320 		freemsg(mp);
13321 		return (NULL);
13322 	}
13323 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13324 		BUMP_MIB(&ip_mib, ipForwProhibits);
13325 		freemsg(mp);
13326 		return (NULL);
13327 	}
13328 
13329 	/*
13330 	 * Mark this packet as having originated externally.
13331 	 *
13332 	 * For non-forwarding code path, ire_send later double
13333 	 * checks this interface to see if it is still exists
13334 	 * post-ARP resolution.
13335 	 *
13336 	 * Also, IPQOS uses this to differentiate between
13337 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13338 	 * QOS packet processing in ip_wput_attach_llhdr().
13339 	 * The QoS module can mark the b_band for a fastpath message
13340 	 * or the dl_priority field in a unitdata_req header for
13341 	 * CoS marking. This info can only be found in
13342 	 * ip_wput_attach_llhdr().
13343 	 */
13344 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13345 	/*
13346 	 * Clear the indication that this may have a hardware checksum
13347 	 * as we are not using it
13348 	 */
13349 	DB_CKSUMFLAGS(mp) = 0;
13350 
13351 	if (in_ill != NULL) {
13352 		/*
13353 		 * Now hand the packet to ip_newroute.
13354 		 */
13355 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13356 		return (NULL);
13357 	}
13358 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13359 	    MBLK_GETLABEL(mp));
13360 
13361 	if (ire == NULL && check_multirt) {
13362 		/* Let ip_newroute handle CGTP  */
13363 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13364 		return (NULL);
13365 	}
13366 
13367 	if (ire != NULL)
13368 		return (ire);
13369 
13370 	mp->b_prev = mp->b_next = 0;
13371 	/* send icmp unreachable */
13372 	q = WR(q);
13373 	/* Sent by forwarding path, and router is global zone */
13374 	if (ip_source_routed(ipha)) {
13375 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13376 		    GLOBAL_ZONEID);
13377 	} else {
13378 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13379 	}
13380 
13381 	return (NULL);
13382 
13383 }
13384 
13385 /*
13386  * check ip header length and align it.
13387  */
13388 static boolean_t
13389 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13390 {
13391 	ssize_t len;
13392 	ill_t *ill;
13393 	ipha_t	*ipha;
13394 
13395 	len = MBLKL(mp);
13396 
13397 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13398 		if (!OK_32PTR(mp->b_rptr))
13399 			IP_STAT(ip_notaligned1);
13400 		else
13401 			IP_STAT(ip_notaligned2);
13402 		/* Guard against bogus device drivers */
13403 		if (len < 0) {
13404 			/* clear b_prev - used by ip_mroute_decap */
13405 			mp->b_prev = NULL;
13406 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13407 			freemsg(mp);
13408 			return (B_FALSE);
13409 		}
13410 
13411 		if (ip_rput_pullups++ == 0) {
13412 			ill = (ill_t *)q->q_ptr;
13413 			ipha = (ipha_t *)mp->b_rptr;
13414 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13415 			    "ip_check_and_align_header: %s forced us to "
13416 			    " pullup pkt, hdr len %ld, hdr addr %p",
13417 			    ill->ill_name, len, ipha);
13418 		}
13419 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13420 			/* clear b_prev - used by ip_mroute_decap */
13421 			mp->b_prev = NULL;
13422 			BUMP_MIB(&ip_mib, ipInDiscards);
13423 			freemsg(mp);
13424 			return (B_FALSE);
13425 		}
13426 	}
13427 	return (B_TRUE);
13428 }
13429 
13430 static boolean_t
13431 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13432 {
13433 	ill_group_t	*ill_group;
13434 	ill_group_t	*ire_group;
13435 	queue_t 	*q;
13436 	ill_t		*ire_ill;
13437 	uint_t		ill_ifindex;
13438 
13439 	q = *qp;
13440 	/*
13441 	 * We need to check to make sure the packet came in
13442 	 * on the queue associated with the destination IRE.
13443 	 * Note that for multicast packets and broadcast packets sent to
13444 	 * a broadcast address which is shared between multiple interfaces
13445 	 * we should not do this since we just got a random broadcast ire.
13446 	 */
13447 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13448 		boolean_t check_multi = B_TRUE;
13449 
13450 		/*
13451 		 * This packet came in on an interface other than the
13452 		 * one associated with the destination address.
13453 		 * "Gateway" it to the appropriate interface here.
13454 		 * As long as the ills belong to the same group,
13455 		 * we don't consider them to arriving on the wrong
13456 		 * interface. Thus, when the switch is doing inbound
13457 		 * load spreading, we won't drop packets when we
13458 		 * are doing strict multihoming checks. Note, the
13459 		 * same holds true for 'usesrc groups' where the
13460 		 * destination address may belong to another interface
13461 		 * to allow multipathing to happen
13462 		 */
13463 		ill_group = ill->ill_group;
13464 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13465 		ill_ifindex = ill->ill_usesrc_ifindex;
13466 		ire_group = ire_ill->ill_group;
13467 
13468 		/*
13469 		 * If it's part of the same IPMP group, or if it's a legal
13470 		 * address on the 'usesrc' interface, then bypass strict
13471 		 * checks.
13472 		 */
13473 		if (ill_group != NULL && ill_group == ire_group) {
13474 			check_multi = B_FALSE;
13475 		} else if (ill_ifindex != 0 &&
13476 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13477 			check_multi = B_FALSE;
13478 		}
13479 
13480 		if (check_multi &&
13481 		    ip_strict_dst_multihoming &&
13482 		    ((ill->ill_flags &
13483 		    ire->ire_ipif->ipif_ill->ill_flags &
13484 		    ILLF_ROUTER) == 0)) {
13485 			/* Drop packet */
13486 			BUMP_MIB(&ip_mib, ipForwProhibits);
13487 			freemsg(mp);
13488 			return (B_TRUE);
13489 		}
13490 
13491 		/*
13492 		 * Change the queue (for non-virtual destination network
13493 		 * interfaces) and ip_rput_local will be called with the right
13494 		 * queue
13495 		 */
13496 		q = ire->ire_rfq;
13497 	}
13498 	/* Must be broadcast.  We'll take it. */
13499 	*qp = q;
13500 	return (B_FALSE);
13501 }
13502 
13503 #define	SEND_PKT(ire, mp)			\
13504 {						\
13505 	UPDATE_IB_PKT_COUNT(ire);		\
13506 	(ire)->ire_last_used_time = lbolt;	\
13507 	BUMP_MIB(&ip_mib, ipForwDatagrams);	\
13508 	putnext((ire)->ire_stq, mp);		\
13509 }
13510 
13511 ire_t *
13512 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13513 {
13514 	ipha_t	*ipha;
13515 	ipaddr_t ip_dst, ip_src;
13516 	ire_t	*src_ire = NULL;
13517 	ill_t	*stq_ill;
13518 	uint_t	hlen;
13519 	uint32_t sum;
13520 	queue_t	*dev_q;
13521 	boolean_t check_multirt = B_FALSE;
13522 
13523 
13524 	ipha = (ipha_t *)mp->b_rptr;
13525 
13526 	/*
13527 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13528 	 * The loopback address check for both src and dst has already
13529 	 * been checked in ip_input
13530 	 */
13531 	ip_dst = ntohl(dst);
13532 	ip_src = ntohl(ipha->ipha_src);
13533 
13534 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13535 	    IN_CLASSD(ip_src)) {
13536 		BUMP_MIB(&ip_mib, ipForwProhibits);
13537 		goto drop;
13538 	}
13539 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13540 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13541 
13542 	if (src_ire != NULL) {
13543 		BUMP_MIB(&ip_mib, ipForwProhibits);
13544 		goto drop;
13545 	}
13546 
13547 	/* No ire cache of nexthop. So first create one  */
13548 	if (ire == NULL) {
13549 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13550 		/*
13551 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13552 		 * is not set. So upon return from ire_forward
13553 		 * check_multirt should remain as false.
13554 		 */
13555 		ASSERT(!check_multirt);
13556 		if (ire == NULL) {
13557 			BUMP_MIB(&ip_mib, ipInDiscards);
13558 			mp->b_prev = mp->b_next = 0;
13559 			/* send icmp unreachable */
13560 			/* Sent by forwarding path, and router is global zone */
13561 			if (ip_source_routed(ipha)) {
13562 				icmp_unreachable(ill->ill_wq, mp,
13563 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13564 			} else {
13565 				icmp_unreachable(ill->ill_wq, mp,
13566 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13567 			}
13568 			return (ire);
13569 		}
13570 	}
13571 
13572 	/*
13573 	 * Forwarding fastpath exception case:
13574 	 * If either of the follwoing case is true, we take
13575 	 * the slowpath
13576 	 *	o forwarding is not enabled
13577 	 *	o IPMP is enabled
13578 	 *	o corresponding ire is in incomplete state
13579 	 *	o packet needs fragmentation
13580 	 *
13581 	 * The codeflow from here on is thus:
13582 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13583 	 */
13584 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13585 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13586 	    !(ill->ill_flags & ILLF_ROUTER) || SAME_IPMP_GROUP(ill, stq_ill) ||
13587 	    (ire->ire_nce == NULL) ||
13588 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13589 	    (ntohs(ipha->ipha_length) > ire->ire_max_frag) ||
13590 	    ipha->ipha_ttl <= 1) {
13591 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13592 		    ipha, ill, B_FALSE);
13593 		return (ire);
13594 	}
13595 
13596 	mp->b_datap->db_struioun.cksum.flags = 0;
13597 	/* Adjust the checksum to reflect the ttl decrement. */
13598 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13599 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13600 	ipha->ipha_ttl--;
13601 
13602 	dev_q = ire->ire_stq->q_next;
13603 	if ((dev_q->q_next != NULL ||
13604 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13605 		goto indiscard;
13606 	}
13607 
13608 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13609 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13610 
13611 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13612 		mp = ip_wput_attach_llhdr(mp, ire, 0, 0);
13613 		if (mp != NULL) {
13614 			SEND_PKT(ire, mp);
13615 			return (ire);
13616 		}
13617 	}
13618 
13619 indiscard:
13620 	BUMP_MIB(&ip_mib, ipInDiscards);
13621 drop:
13622 	if (mp != NULL)
13623 		freemsg(mp);
13624 	if (src_ire != NULL)
13625 		ire_refrele(src_ire);
13626 	return (ire);
13627 
13628 }
13629 
13630 /*
13631  * This function is called in the forwarding slowpath, when
13632  * either the ire lacks the link-layer address, or the packet needs
13633  * further processing(eg. fragmentation), before transmission.
13634  */
13635 static void
13636 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13637     ill_t *ill, boolean_t ll_multicast)
13638 {
13639 	ill_group_t	*ill_group;
13640 	ill_group_t	*ire_group;
13641 	queue_t		*dev_q;
13642 	ire_t		*src_ire;
13643 
13644 	ASSERT(ire->ire_stq != NULL);
13645 
13646 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13647 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13648 
13649 	if (ll_multicast != 0)
13650 		goto drop_pkt;
13651 
13652 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13653 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13654 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13655 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13656 		if (src_ire != NULL)
13657 			ire_refrele(src_ire);
13658 		BUMP_MIB(&ip_mib, ipForwProhibits);
13659 		ip2dbg(("ip_rput_process_forward: Received packet with"
13660 		    " bad src/dst address on %s\n", ill->ill_name));
13661 	}
13662 
13663 	ill_group = ill->ill_group;
13664 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13665 	/*
13666 	 * Check if we want to forward this one at this time.
13667 	 * We allow source routed packets on a host provided that
13668 	 * they go out the same interface or same interface group
13669 	 * as they came in on.
13670 	 *
13671 	 * XXX To be quicker, we may wish to not chase pointers to
13672 	 * get the ILLF_ROUTER flag and instead store the
13673 	 * forwarding policy in the ire.  An unfortunate
13674 	 * side-effect of that would be requiring an ire flush
13675 	 * whenever the ILLF_ROUTER flag changes.
13676 	 */
13677 	if (((ill->ill_flags &
13678 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13679 	    ILLF_ROUTER) == 0) &&
13680 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13681 	    (ill_group != NULL && ill_group == ire_group)))) {
13682 		BUMP_MIB(&ip_mib, ipForwProhibits);
13683 		if (ip_source_routed(ipha)) {
13684 			q = WR(q);
13685 			/*
13686 			 * Clear the indication that this may have
13687 			 * hardware checksum as we are not using it.
13688 			 */
13689 			DB_CKSUMFLAGS(mp) = 0;
13690 			/* Sent by forwarding path, and router is global zone */
13691 			icmp_unreachable(q, mp,
13692 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13693 			return;
13694 		}
13695 		goto drop_pkt;
13696 	}
13697 
13698 	/* Packet is being forwarded. Turning off hwcksum flag. */
13699 	DB_CKSUMFLAGS(mp) = 0;
13700 	if (ip_g_send_redirects) {
13701 		/*
13702 		 * Check whether the incoming interface and outgoing
13703 		 * interface is part of the same group. If so,
13704 		 * send redirects.
13705 		 *
13706 		 * Check the source address to see if it originated
13707 		 * on the same logical subnet it is going back out on.
13708 		 * If so, we should be able to send it a redirect.
13709 		 * Avoid sending a redirect if the destination
13710 		 * is directly connected (gw_addr == 0),
13711 		 * or if the packet was source routed out this
13712 		 * interface.
13713 		 */
13714 		ipaddr_t src;
13715 		mblk_t	*mp1;
13716 		ire_t	*src_ire = NULL;
13717 
13718 		/*
13719 		 * Check whether ire_rfq and q are from the same ill
13720 		 * or if they are not same, they at least belong
13721 		 * to the same group. If so, send redirects.
13722 		 */
13723 		if ((ire->ire_rfq == q ||
13724 		    (ill_group != NULL && ill_group == ire_group)) &&
13725 		    (ire->ire_gateway_addr != 0) &&
13726 		    !ip_source_routed(ipha)) {
13727 
13728 			src = ipha->ipha_src;
13729 			src_ire = ire_ftable_lookup(src, 0, 0,
13730 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
13731 			    0, NULL, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
13732 
13733 			if (src_ire != NULL) {
13734 				/*
13735 				 * The source is directly connected.
13736 				 * Just copy the ip header (which is
13737 				 * in the first mblk)
13738 				 */
13739 				mp1 = copyb(mp);
13740 				if (mp1 != NULL) {
13741 					icmp_send_redirect(WR(q), mp1,
13742 					    ire->ire_gateway_addr);
13743 				}
13744 				ire_refrele(src_ire);
13745 			}
13746 		}
13747 	}
13748 
13749 	dev_q = ire->ire_stq->q_next;
13750 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13751 		BUMP_MIB(&ip_mib, ipInDiscards);
13752 		freemsg(mp);
13753 		return;
13754 	}
13755 
13756 	ip_rput_forward(ire, ipha, mp, ill);
13757 	return;
13758 
13759 drop_pkt:
13760 	ip2dbg(("ip_rput_forward: drop pkt\n"));
13761 	freemsg(mp);
13762 }
13763 
13764 ire_t *
13765 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13766     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13767 {
13768 	queue_t		*q;
13769 	uint16_t	hcksumflags;
13770 
13771 	q = *qp;
13772 
13773 	/*
13774 	 * Clear the indication that this may have hardware
13775 	 * checksum as we are not using it for forwarding.
13776 	 */
13777 	hcksumflags = DB_CKSUMFLAGS(mp);
13778 	DB_CKSUMFLAGS(mp) = 0;
13779 
13780 	/*
13781 	 * Directed broadcast forwarding: if the packet came in over a
13782 	 * different interface then it is routed out over we can forward it.
13783 	 */
13784 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13785 		ire_refrele(ire);
13786 		freemsg(mp);
13787 		BUMP_MIB(&ip_mib, ipInDiscards);
13788 		return (NULL);
13789 	}
13790 	/*
13791 	 * For multicast we have set dst to be INADDR_BROADCAST
13792 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13793 	 * only for broadcast packets.
13794 	 */
13795 	if (!CLASSD(ipha->ipha_dst)) {
13796 		ire_t *new_ire;
13797 		ipif_t *ipif;
13798 		/*
13799 		 * For ill groups, as the switch duplicates broadcasts
13800 		 * across all the ports, we need to filter out and
13801 		 * send up only one copy. There is one copy for every
13802 		 * broadcast address on each ill. Thus, we look for a
13803 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13804 		 * later to see whether this ill is eligible to receive
13805 		 * them or not. ill_nominate_bcast_rcv() nominates only
13806 		 * one set of IREs for receiving.
13807 		 */
13808 
13809 		ipif = ipif_get_next_ipif(NULL, ill);
13810 		if (ipif == NULL) {
13811 			ire_refrele(ire);
13812 			freemsg(mp);
13813 			BUMP_MIB(&ip_mib, ipInDiscards);
13814 			return (NULL);
13815 		}
13816 		new_ire = ire_ctable_lookup(dst, 0, 0,
13817 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13818 		ipif_refrele(ipif);
13819 
13820 		if (new_ire != NULL) {
13821 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13822 				ire_refrele(ire);
13823 				ire_refrele(new_ire);
13824 				freemsg(mp);
13825 				BUMP_MIB(&ip_mib, ipInDiscards);
13826 				return (NULL);
13827 			}
13828 			/*
13829 			 * In the special case of multirouted broadcast
13830 			 * packets, we unconditionally need to "gateway"
13831 			 * them to the appropriate interface here.
13832 			 * In the normal case, this cannot happen, because
13833 			 * there is no broadcast IRE tagged with the
13834 			 * RTF_MULTIRT flag.
13835 			 */
13836 			if (new_ire->ire_flags & RTF_MULTIRT) {
13837 				ire_refrele(new_ire);
13838 				if (ire->ire_rfq != NULL) {
13839 					q = ire->ire_rfq;
13840 					*qp = q;
13841 				}
13842 			} else {
13843 				ire_refrele(ire);
13844 				ire = new_ire;
13845 			}
13846 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
13847 			if (!ip_g_forward_directed_bcast) {
13848 				/*
13849 				 * Free the message if
13850 				 * ip_g_forward_directed_bcast is turned
13851 				 * off for non-local broadcast.
13852 				 */
13853 				ire_refrele(ire);
13854 				freemsg(mp);
13855 				BUMP_MIB(&ip_mib, ipInDiscards);
13856 				return (NULL);
13857 			}
13858 		} else {
13859 			/*
13860 			 * This CGTP packet successfully passed the
13861 			 * CGTP filter, but the related CGTP
13862 			 * broadcast IRE has not been found,
13863 			 * meaning that the redundant ipif is
13864 			 * probably down. However, if we discarded
13865 			 * this packet, its duplicate would be
13866 			 * filtered out by the CGTP filter so none
13867 			 * of them would get through. So we keep
13868 			 * going with this one.
13869 			 */
13870 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
13871 			if (ire->ire_rfq != NULL) {
13872 				q = ire->ire_rfq;
13873 				*qp = q;
13874 			}
13875 		}
13876 	}
13877 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
13878 		/*
13879 		 * Verify that there are not more then one
13880 		 * IRE_BROADCAST with this broadcast address which
13881 		 * has ire_stq set.
13882 		 * TODO: simplify, loop over all IRE's
13883 		 */
13884 		ire_t	*ire1;
13885 		int	num_stq = 0;
13886 		mblk_t	*mp1;
13887 
13888 		/* Find the first one with ire_stq set */
13889 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
13890 		for (ire1 = ire; ire1 &&
13891 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
13892 		    ire1 = ire1->ire_next)
13893 			;
13894 		if (ire1) {
13895 			ire_refrele(ire);
13896 			ire = ire1;
13897 			IRE_REFHOLD(ire);
13898 		}
13899 
13900 		/* Check if there are additional ones with stq set */
13901 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
13902 			if (ire->ire_addr != ire1->ire_addr)
13903 				break;
13904 			if (ire1->ire_stq) {
13905 				num_stq++;
13906 				break;
13907 			}
13908 		}
13909 		rw_exit(&ire->ire_bucket->irb_lock);
13910 		if (num_stq == 1 && ire->ire_stq != NULL) {
13911 			ip1dbg(("ip_rput_process_broadcast: directed "
13912 			    "broadcast to 0x%x\n",
13913 			    ntohl(ire->ire_addr)));
13914 			mp1 = copymsg(mp);
13915 			if (mp1) {
13916 				switch (ipha->ipha_protocol) {
13917 				case IPPROTO_UDP:
13918 					ip_udp_input(q, mp1, ipha, ire, ill);
13919 					break;
13920 				default:
13921 					ip_proto_input(q, mp1, ipha, ire, ill);
13922 					break;
13923 				}
13924 			}
13925 			/*
13926 			 * Adjust ttl to 2 (1+1 - the forward engine
13927 			 * will decrement it by one.
13928 			 */
13929 			if (ip_csum_hdr(ipha)) {
13930 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13931 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
13932 				freemsg(mp);
13933 				ire_refrele(ire);
13934 				return (NULL);
13935 			}
13936 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
13937 			ipha->ipha_hdr_checksum = 0;
13938 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
13939 			ip_rput_process_forward(q, mp, ire, ipha,
13940 			    ill, ll_multicast);
13941 			ire_refrele(ire);
13942 			return (NULL);
13943 		}
13944 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
13945 		    ntohl(ire->ire_addr)));
13946 	}
13947 
13948 
13949 	/* Restore any hardware checksum flags */
13950 	DB_CKSUMFLAGS(mp) = hcksumflags;
13951 	return (ire);
13952 }
13953 
13954 /* ARGSUSED */
13955 static boolean_t
13956 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
13957     int *ll_multicast, ipaddr_t *dstp)
13958 {
13959 	/*
13960 	 * Forward packets only if we have joined the allmulti
13961 	 * group on this interface.
13962 	 */
13963 	if (ip_g_mrouter && ill->ill_join_allmulti) {
13964 		int retval;
13965 
13966 		/*
13967 		 * Clear the indication that this may have hardware
13968 		 * checksum as we are not using it.
13969 		 */
13970 		DB_CKSUMFLAGS(mp) = 0;
13971 		retval = ip_mforward(ill, ipha, mp);
13972 		/* ip_mforward updates mib variables if needed */
13973 		/* clear b_prev - used by ip_mroute_decap */
13974 		mp->b_prev = NULL;
13975 
13976 		switch (retval) {
13977 		case 0:
13978 			/*
13979 			 * pkt is okay and arrived on phyint.
13980 			 *
13981 			 * If we are running as a multicast router
13982 			 * we need to see all IGMP and/or PIM packets.
13983 			 */
13984 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
13985 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
13986 				goto done;
13987 			}
13988 			break;
13989 		case -1:
13990 			/* pkt is mal-formed, toss it */
13991 			goto drop_pkt;
13992 		case 1:
13993 			/* pkt is okay and arrived on a tunnel */
13994 			/*
13995 			 * If we are running a multicast router
13996 			 *  we need to see all igmp packets.
13997 			 */
13998 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
13999 				*dstp = INADDR_BROADCAST;
14000 				*ll_multicast = 1;
14001 				return (B_FALSE);
14002 			}
14003 
14004 			goto drop_pkt;
14005 		}
14006 	}
14007 
14008 	ILM_WALKER_HOLD(ill);
14009 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14010 		/*
14011 		 * This might just be caused by the fact that
14012 		 * multiple IP Multicast addresses map to the same
14013 		 * link layer multicast - no need to increment counter!
14014 		 */
14015 		ILM_WALKER_RELE(ill);
14016 		freemsg(mp);
14017 		return (B_TRUE);
14018 	}
14019 	ILM_WALKER_RELE(ill);
14020 done:
14021 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14022 	/*
14023 	 * This assumes the we deliver to all streams for multicast
14024 	 * and broadcast packets.
14025 	 */
14026 	*dstp = INADDR_BROADCAST;
14027 	*ll_multicast = 1;
14028 	return (B_FALSE);
14029 drop_pkt:
14030 	ip2dbg(("ip_rput: drop pkt\n"));
14031 	freemsg(mp);
14032 	return (B_TRUE);
14033 }
14034 
14035 static boolean_t
14036 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14037     int *ll_multicast, mblk_t **mpp)
14038 {
14039 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14040 	boolean_t must_copy = B_FALSE;
14041 	struct iocblk   *iocp;
14042 	ipha_t		*ipha;
14043 
14044 #define	rptr    ((uchar_t *)ipha)
14045 
14046 	first_mp = *first_mpp;
14047 	mp = *mpp;
14048 
14049 	ASSERT(first_mp == mp);
14050 
14051 	/*
14052 	 * if db_ref > 1 then copymsg and free original. Packet may be
14053 	 * changed and do not want other entity who has a reference to this
14054 	 * message to trip over the changes. This is a blind change because
14055 	 * trying to catch all places that might change packet is too
14056 	 * difficult (since it may be a module above this one)
14057 	 *
14058 	 * This corresponds to the non-fast path case. We walk down the full
14059 	 * chain in this case, and check the db_ref count of all the dblks,
14060 	 * and do a copymsg if required. It is possible that the db_ref counts
14061 	 * of the data blocks in the mblk chain can be different.
14062 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14063 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14064 	 * 'snoop' is running.
14065 	 */
14066 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14067 		if (mp1->b_datap->db_ref > 1) {
14068 			must_copy = B_TRUE;
14069 			break;
14070 		}
14071 	}
14072 
14073 	if (must_copy) {
14074 		mp1 = copymsg(mp);
14075 		if (mp1 == NULL) {
14076 			for (mp1 = mp; mp1 != NULL;
14077 			    mp1 = mp1->b_cont) {
14078 				mp1->b_next = NULL;
14079 				mp1->b_prev = NULL;
14080 			}
14081 			freemsg(mp);
14082 			BUMP_MIB(&ip_mib, ipInDiscards);
14083 			return (B_TRUE);
14084 		}
14085 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14086 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14087 			/* Copy b_prev - used by ip_mroute_decap */
14088 			to_mp->b_prev = from_mp->b_prev;
14089 			from_mp->b_prev = NULL;
14090 		}
14091 		*first_mpp = first_mp = mp1;
14092 		freemsg(mp);
14093 		mp = mp1;
14094 		*mpp = mp1;
14095 	}
14096 
14097 	ipha = (ipha_t *)mp->b_rptr;
14098 
14099 	/*
14100 	 * previous code has a case for M_DATA.
14101 	 * We want to check how that happens.
14102 	 */
14103 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14104 	switch (first_mp->b_datap->db_type) {
14105 	case M_PROTO:
14106 	case M_PCPROTO:
14107 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14108 		    DL_UNITDATA_IND) {
14109 			/* Go handle anything other than data elsewhere. */
14110 			ip_rput_dlpi(q, mp);
14111 			return (B_TRUE);
14112 		}
14113 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14114 		/* Ditch the DLPI header. */
14115 		mp1 = mp->b_cont;
14116 		ASSERT(first_mp == mp);
14117 		*first_mpp = mp1;
14118 		freeb(mp);
14119 		*mpp = mp1;
14120 		return (B_FALSE);
14121 	case M_IOCACK:
14122 		ip1dbg(("got iocack "));
14123 		iocp = (struct iocblk *)mp->b_rptr;
14124 		switch (iocp->ioc_cmd) {
14125 		case DL_IOC_HDR_INFO:
14126 			ill = (ill_t *)q->q_ptr;
14127 			ill_fastpath_ack(ill, mp);
14128 			return (B_TRUE);
14129 		case SIOCSTUNPARAM:
14130 		case OSIOCSTUNPARAM:
14131 			/* Go through qwriter_ip */
14132 			break;
14133 		case SIOCGTUNPARAM:
14134 		case OSIOCGTUNPARAM:
14135 			ip_rput_other(NULL, q, mp, NULL);
14136 			return (B_TRUE);
14137 		default:
14138 			putnext(q, mp);
14139 			return (B_TRUE);
14140 		}
14141 		/* FALLTHRU */
14142 	case M_ERROR:
14143 	case M_HANGUP:
14144 		/*
14145 		 * Since this is on the ill stream we unconditionally
14146 		 * bump up the refcount
14147 		 */
14148 		ill_refhold(ill);
14149 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14150 		    B_FALSE);
14151 		return (B_TRUE);
14152 	case M_CTL:
14153 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14154 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14155 			IPHADA_M_CTL)) {
14156 			/*
14157 			 * It's an IPsec accelerated packet.
14158 			 * Make sure that the ill from which we received the
14159 			 * packet has enabled IPsec hardware acceleration.
14160 			 */
14161 			if (!(ill->ill_capabilities &
14162 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14163 				/* IPsec kstats: bean counter */
14164 				freemsg(mp);
14165 				return (B_TRUE);
14166 			}
14167 
14168 			/*
14169 			 * Make mp point to the mblk following the M_CTL,
14170 			 * then process according to type of mp.
14171 			 * After this processing, first_mp will point to
14172 			 * the data-attributes and mp to the pkt following
14173 			 * the M_CTL.
14174 			 */
14175 			mp = first_mp->b_cont;
14176 			if (mp == NULL) {
14177 				freemsg(first_mp);
14178 				return (B_TRUE);
14179 			}
14180 			/*
14181 			 * A Hardware Accelerated packet can only be M_DATA
14182 			 * ESP or AH packet.
14183 			 */
14184 			if (mp->b_datap->db_type != M_DATA) {
14185 				/* non-M_DATA IPsec accelerated packet */
14186 				IPSECHW_DEBUG(IPSECHW_PKT,
14187 				    ("non-M_DATA IPsec accelerated pkt\n"));
14188 				freemsg(first_mp);
14189 				return (B_TRUE);
14190 			}
14191 			ipha = (ipha_t *)mp->b_rptr;
14192 			if (ipha->ipha_protocol != IPPROTO_AH &&
14193 			    ipha->ipha_protocol != IPPROTO_ESP) {
14194 				IPSECHW_DEBUG(IPSECHW_PKT,
14195 				    ("non-M_DATA IPsec accelerated pkt\n"));
14196 				freemsg(first_mp);
14197 				return (B_TRUE);
14198 			}
14199 			*mpp = mp;
14200 			return (B_FALSE);
14201 		}
14202 		putnext(q, mp);
14203 		return (B_TRUE);
14204 	case M_FLUSH:
14205 		if (*mp->b_rptr & FLUSHW) {
14206 			*mp->b_rptr &= ~FLUSHR;
14207 			qreply(q, mp);
14208 			return (B_TRUE);
14209 		}
14210 		freemsg(mp);
14211 		return (B_TRUE);
14212 	case M_IOCNAK:
14213 		ip1dbg(("got iocnak "));
14214 		iocp = (struct iocblk *)mp->b_rptr;
14215 		switch (iocp->ioc_cmd) {
14216 		case DL_IOC_HDR_INFO:
14217 		case SIOCSTUNPARAM:
14218 		case OSIOCSTUNPARAM:
14219 			/*
14220 			 * Since this is on the ill stream we unconditionally
14221 			 * bump up the refcount
14222 			 */
14223 			ill_refhold(ill);
14224 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14225 			    CUR_OP, B_FALSE);
14226 			return (B_TRUE);
14227 		case SIOCGTUNPARAM:
14228 		case OSIOCGTUNPARAM:
14229 			ip_rput_other(NULL, q, mp, NULL);
14230 			return (B_TRUE);
14231 		default:
14232 			break;
14233 		}
14234 		/* FALLTHRU */
14235 	default:
14236 		putnext(q, mp);
14237 		return (B_TRUE);
14238 	}
14239 }
14240 
14241 /* Read side put procedure.  Packets coming from the wire arrive here. */
14242 void
14243 ip_rput(queue_t *q, mblk_t *mp)
14244 {
14245 	ill_t	*ill;
14246 	mblk_t	 *dmp = NULL;
14247 
14248 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14249 
14250 	ill = (ill_t *)q->q_ptr;
14251 
14252 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14253 		union DL_primitives *dl;
14254 
14255 		/*
14256 		 * Things are opening or closing. Only accept DLPI control
14257 		 * messages. In the open case, the ill->ill_ipif has not yet
14258 		 * been created. In the close case, things hanging off the
14259 		 * ill could have been freed already. In either case it
14260 		 * may not be safe to proceed further.
14261 		 */
14262 
14263 		dl = (union DL_primitives *)mp->b_rptr;
14264 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14265 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14266 			/*
14267 			 * Also SIOC[GS]TUN* ioctls can come here.
14268 			 */
14269 			inet_freemsg(mp);
14270 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14271 			    "ip_input_end: q %p (%S)", q, "uninit");
14272 			return;
14273 		}
14274 	}
14275 
14276 	/*
14277 	 * if db_ref > 1 then copymsg and free original. Packet may be
14278 	 * changed and we do not want the other entity who has a reference to
14279 	 * this message to trip over the changes. This is a blind change because
14280 	 * trying to catch all places that might change the packet is too
14281 	 * difficult.
14282 	 *
14283 	 * This corresponds to the fast path case, where we have a chain of
14284 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14285 	 * in the mblk chain. There doesn't seem to be a reason why a device
14286 	 * driver would send up data with varying db_ref counts in the mblk
14287 	 * chain. In any case the Fast path is a private interface, and our
14288 	 * drivers don't do such a thing. Given the above assumption, there is
14289 	 * no need to walk down the entire mblk chain (which could have a
14290 	 * potential performance problem)
14291 	 */
14292 	if (mp->b_datap->db_ref > 1) {
14293 		mblk_t  *mp1;
14294 		boolean_t adjusted = B_FALSE;
14295 		IP_STAT(ip_db_ref);
14296 
14297 		/*
14298 		 * The IP_RECVSLLA option depends on having the link layer
14299 		 * header. First check that:
14300 		 * a> the underlying device is of type ether, since this
14301 		 * option is currently supported only over ethernet.
14302 		 * b> there is enough room to copy over the link layer header.
14303 		 *
14304 		 * Once the checks are done, adjust rptr so that the link layer
14305 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14306 		 * be returned by some non-ethernet drivers but in this case the
14307 		 * second check will fail.
14308 		 */
14309 		if (ill->ill_type == IFT_ETHER &&
14310 		    (mp->b_rptr - mp->b_datap->db_base) >=
14311 		    sizeof (struct ether_header)) {
14312 			mp->b_rptr -= sizeof (struct ether_header);
14313 			adjusted = B_TRUE;
14314 		}
14315 		mp1 = copymsg(mp);
14316 		if (mp1 == NULL) {
14317 			mp->b_next = NULL;
14318 			/* clear b_prev - used by ip_mroute_decap */
14319 			mp->b_prev = NULL;
14320 			freemsg(mp);
14321 			BUMP_MIB(&ip_mib, ipInDiscards);
14322 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14323 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14324 			return;
14325 		}
14326 		if (adjusted) {
14327 			/*
14328 			 * Copy is done. Restore the pointer in the _new_ mblk
14329 			 */
14330 			mp1->b_rptr += sizeof (struct ether_header);
14331 		}
14332 		/* Copy b_prev - used by ip_mroute_decap */
14333 		mp1->b_prev = mp->b_prev;
14334 		mp->b_prev = NULL;
14335 		freemsg(mp);
14336 		mp = mp1;
14337 	}
14338 	if (DB_TYPE(mp) == M_DATA) {
14339 		dmp = mp;
14340 	} else if (DB_TYPE(mp) == M_PROTO &&
14341 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14342 		dmp = mp->b_cont;
14343 	}
14344 	if (dmp != NULL) {
14345 		/*
14346 		 * IP header ptr not aligned?
14347 		 * OR IP header not complete in first mblk
14348 		 */
14349 		if (!OK_32PTR(dmp->b_rptr) ||
14350 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14351 			if (!ip_check_and_align_header(q, dmp))
14352 				return;
14353 		}
14354 	}
14355 
14356 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14357 	    "ip_rput_end: q %p (%S)", q, "end");
14358 
14359 	ip_input(ill, NULL, mp, NULL);
14360 }
14361 
14362 /*
14363  * Direct read side procedure capable of dealing with chains. GLDv3 based
14364  * drivers call this function directly with mblk chains while STREAMS
14365  * read side procedure ip_rput() calls this for single packet with ip_ring
14366  * set to NULL to process one packet at a time.
14367  *
14368  * The ill will always be valid if this function is called directly from
14369  * the driver.
14370  *
14371  * If ip_input() is called from GLDv3:
14372  *
14373  *   - This must be a non-VLAN IP stream.
14374  *   - 'mp' is either an untagged or a special priority-tagged packet.
14375  *   - Any VLAN tag that was in the MAC header has been stripped.
14376  *
14377  * Thus, there is no need to adjust b_rptr in this function.
14378  */
14379 /* ARGSUSED */
14380 void
14381 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14382     struct mac_header_info_s *mhip)
14383 {
14384 	ipaddr_t		dst = NULL;
14385 	ipaddr_t		prev_dst;
14386 	ire_t			*ire = NULL;
14387 	ipha_t			*ipha;
14388 	uint_t			pkt_len;
14389 	ssize_t			len;
14390 	uint_t			opt_len;
14391 	int			ll_multicast;
14392 	int			cgtp_flt_pkt;
14393 	queue_t			*q = ill->ill_rq;
14394 	squeue_t		*curr_sqp = NULL;
14395 	mblk_t 			*head = NULL;
14396 	mblk_t			*tail = NULL;
14397 	mblk_t			*first_mp;
14398 	mblk_t 			*mp;
14399 	int			cnt = 0;
14400 
14401 	ASSERT(mp_chain != NULL);
14402 	ASSERT(ill != NULL);
14403 
14404 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14405 
14406 #define	rptr	((uchar_t *)ipha)
14407 
14408 	while (mp_chain != NULL) {
14409 		first_mp = mp = mp_chain;
14410 		mp_chain = mp_chain->b_next;
14411 		mp->b_next = NULL;
14412 		ll_multicast = 0;
14413 
14414 		/*
14415 		 * We do ire caching from one iteration to
14416 		 * another. In the event the packet chain contains
14417 		 * all packets from the same dst, this caching saves
14418 		 * an ire_cache_lookup for each of the succeeding
14419 		 * packets in a packet chain.
14420 		 */
14421 		prev_dst = dst;
14422 
14423 		/*
14424 		 * ip_input fast path
14425 		 */
14426 
14427 		/* mblk type is not M_DATA */
14428 		if (mp->b_datap->db_type != M_DATA) {
14429 			if (ip_rput_process_notdata(q, &first_mp, ill,
14430 			    &ll_multicast, &mp))
14431 				continue;
14432 		}
14433 
14434 		/* Make sure its an M_DATA and that its aligned */
14435 		ASSERT(mp->b_datap->db_type == M_DATA);
14436 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14437 
14438 		ipha = (ipha_t *)mp->b_rptr;
14439 		len = mp->b_wptr - rptr;
14440 
14441 		BUMP_MIB(&ip_mib, ipInReceives);
14442 
14443 
14444 		/* multiple mblk or too short */
14445 		pkt_len = ntohs(ipha->ipha_length);
14446 		len -= pkt_len;
14447 		if (len != 0) {
14448 			/*
14449 			 * Make sure we have data length consistent
14450 			 * with the IP header.
14451 			 */
14452 			if (mp->b_cont == NULL) {
14453 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14454 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14455 					ip2dbg(("ip_input: drop pkt\n"));
14456 					freemsg(mp);
14457 					continue;
14458 				}
14459 				mp->b_wptr = rptr + pkt_len;
14460 			} else if (len += msgdsize(mp->b_cont)) {
14461 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14462 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14463 					ip2dbg(("ip_input: drop pkt\n"));
14464 					freemsg(mp);
14465 					continue;
14466 				}
14467 				(void) adjmsg(mp, -len);
14468 				IP_STAT(ip_multimblk3);
14469 			}
14470 		}
14471 
14472 		/* Obtain the dst of the current packet */
14473 		dst = ipha->ipha_dst;
14474 
14475 		if (IP_LOOPBACK_ADDR(dst) ||
14476 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14477 			BUMP_MIB(&ip_mib, ipInAddrErrors);
14478 			cmn_err(CE_CONT, "dst %X src %X\n",
14479 			    dst, ipha->ipha_src);
14480 			freemsg(mp);
14481 			continue;
14482 		}
14483 
14484 		/*
14485 		 * Attach any necessary label information to
14486 		 * this packet
14487 		 */
14488 		if (is_system_labeled() &&
14489 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14490 			BUMP_MIB(&ip_mib, ipInDiscards);
14491 			freemsg(mp);
14492 			continue;
14493 		}
14494 
14495 		/*
14496 		 * Reuse the cached ire only if the ipha_dst of the previous
14497 		 * packet is the same as the current packet AND it is not
14498 		 * INADDR_ANY.
14499 		 */
14500 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14501 		    (ire != NULL)) {
14502 			ire_refrele(ire);
14503 			ire = NULL;
14504 		}
14505 		opt_len = ipha->ipha_version_and_hdr_length -
14506 		    IP_SIMPLE_HDR_VERSION;
14507 
14508 		/*
14509 		 * Check to see if we can take the fastpath.
14510 		 * That is possible if the following conditions are met
14511 		 *	o Tsol disabled
14512 		 *	o CGTP disabled
14513 		 *	o ipp_action_count is 0
14514 		 *	o Mobile IP not running
14515 		 *	o no options in the packet
14516 		 *	o not a RSVP packet
14517 		 * 	o not a multicast packet
14518 		 */
14519 		if (!is_system_labeled() &&
14520 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14521 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14522 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14523 		    !ll_multicast && !CLASSD(dst)) {
14524 			if (ire == NULL)
14525 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14526 
14527 			/* incoming packet is for forwarding */
14528 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14529 				ire = ip_fast_forward(ire, dst, ill, mp);
14530 				continue;
14531 			}
14532 			/* incoming packet is for local consumption */
14533 			if (ire->ire_type & IRE_LOCAL)
14534 				goto local;
14535 		}
14536 
14537 		/*
14538 		 * Disable ire caching for anything more complex
14539 		 * than the simple fast path case we checked for above.
14540 		 */
14541 		if (ire != NULL) {
14542 			ire_refrele(ire);
14543 			ire = NULL;
14544 		}
14545 
14546 		/* Full-blown slow path */
14547 		if (opt_len != 0) {
14548 			if (len != 0)
14549 				IP_STAT(ip_multimblk4);
14550 			else
14551 				IP_STAT(ip_ipoptions);
14552 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
14553 				continue;
14554 		}
14555 
14556 		/*
14557 		 * Invoke the CGTP (multirouting) filtering module to process
14558 		 * the incoming packet. Packets identified as duplicates
14559 		 * must be discarded. Filtering is active only if the
14560 		 * the ip_cgtp_filter ndd variable is non-zero.
14561 		 */
14562 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14563 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
14564 			cgtp_flt_pkt =
14565 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14566 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14567 				freemsg(first_mp);
14568 				continue;
14569 			}
14570 		}
14571 
14572 		/*
14573 		 * If rsvpd is running, let RSVP daemon handle its processing
14574 		 * and forwarding of RSVP multicast/unicast packets.
14575 		 * If rsvpd is not running but mrouted is running, RSVP
14576 		 * multicast packets are forwarded as multicast traffic
14577 		 * and RSVP unicast packets are forwarded by unicast router.
14578 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14579 		 * packets are not forwarded, but the unicast packets are
14580 		 * forwarded like unicast traffic.
14581 		 */
14582 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14583 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
14584 			/* RSVP packet and rsvpd running. Treat as ours */
14585 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14586 			/*
14587 			 * This assumes that we deliver to all streams for
14588 			 * multicast and broadcast packets.
14589 			 * We have to force ll_multicast to 1 to handle the
14590 			 * M_DATA messages passed in from ip_mroute_decap.
14591 			 */
14592 			dst = INADDR_BROADCAST;
14593 			ll_multicast = 1;
14594 		} else if (CLASSD(dst)) {
14595 			/* packet is multicast */
14596 			mp->b_next = NULL;
14597 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14598 			    &ll_multicast, &dst))
14599 				continue;
14600 		}
14601 
14602 
14603 		/*
14604 		 * Check if the packet is coming from the Mobile IP
14605 		 * forward tunnel interface
14606 		 */
14607 		if (ill->ill_srcif_refcnt > 0) {
14608 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
14609 			    NULL, ill, MATCH_IRE_TYPE);
14610 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
14611 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
14612 
14613 				/* We need to resolve the link layer info */
14614 				ire_refrele(ire);
14615 				ire = NULL;
14616 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
14617 				    ll_multicast, dst);
14618 				continue;
14619 			}
14620 		}
14621 
14622 		if (ire == NULL) {
14623 			ire = ire_cache_lookup(dst, ALL_ZONES,
14624 			    MBLK_GETLABEL(mp));
14625 		}
14626 
14627 		/*
14628 		 * If mipagent is running and reverse tunnel is created as per
14629 		 * mobile node request, then any packet coming through the
14630 		 * incoming interface from the mobile-node, should be reverse
14631 		 * tunneled to it's home agent except those that are destined
14632 		 * to foreign agent only.
14633 		 * This needs source address based ire lookup. The routing
14634 		 * entries for source address based lookup are only created by
14635 		 * mipagent program only when a reverse tunnel is created.
14636 		 * Reference : RFC2002, RFC2344
14637 		 */
14638 		if (ill->ill_mrtun_refcnt > 0) {
14639 			ipaddr_t	srcaddr;
14640 			ire_t		*tmp_ire;
14641 
14642 			tmp_ire = ire;	/* Save, we might need it later */
14643 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14644 			    ire->ire_type != IRE_BROADCAST)) {
14645 				srcaddr = ipha->ipha_src;
14646 				ire = ire_mrtun_lookup(srcaddr, ill);
14647 				if (ire != NULL) {
14648 					/*
14649 					 * Should not be getting iphada packet
14650 					 * here. we should only get those for
14651 					 * IRE_LOCAL traffic, excluded above.
14652 					 * Fail-safe (drop packet) in the event
14653 					 * hardware is misbehaving.
14654 					 */
14655 					if (first_mp != mp) {
14656 						/* IPsec KSTATS: beancount me */
14657 						freemsg(first_mp);
14658 					} else {
14659 						/*
14660 						 * This packet must be forwarded
14661 						 * to Reverse Tunnel
14662 						 */
14663 						ip_mrtun_forward(ire, ill, mp);
14664 					}
14665 					ire_refrele(ire);
14666 					ire = NULL;
14667 					if (tmp_ire != NULL) {
14668 						ire_refrele(tmp_ire);
14669 						tmp_ire = NULL;
14670 					}
14671 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14672 					    "ip_input_end: q %p (%S)",
14673 					    q, "uninit");
14674 					continue;
14675 				}
14676 			}
14677 			/*
14678 			 * If this packet is from a non-mobilenode  or a
14679 			 * mobile-node which does not request reverse
14680 			 * tunnel service
14681 			 */
14682 			ire = tmp_ire;
14683 		}
14684 
14685 
14686 		/*
14687 		 * If we reach here that means the incoming packet satisfies
14688 		 * one of the following conditions:
14689 		 *   - packet is from a mobile node which does not request
14690 		 *	reverse tunnel
14691 		 *   - packet is from a non-mobile node, which is the most
14692 		 *	common case
14693 		 *   - packet is from a reverse tunnel enabled mobile node
14694 		 *	and destined to foreign agent only
14695 		 */
14696 
14697 		if (ire == NULL) {
14698 			/*
14699 			 * No IRE for this destination, so it can't be for us.
14700 			 * Unless we are forwarding, drop the packet.
14701 			 * We have to let source routed packets through
14702 			 * since we don't yet know if they are 'ping -l'
14703 			 * packets i.e. if they will go out over the
14704 			 * same interface as they came in on.
14705 			 */
14706 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14707 			if (ire == NULL)
14708 				continue;
14709 		}
14710 
14711 		/*
14712 		 * Broadcast IRE may indicate either broadcast or
14713 		 * multicast packet
14714 		 */
14715 		if (ire->ire_type == IRE_BROADCAST) {
14716 			/*
14717 			 * Skip broadcast checks if packet is UDP multicast;
14718 			 * we'd rather not enter ip_rput_process_broadcast()
14719 			 * unless the packet is broadcast for real, since
14720 			 * that routine is a no-op for multicast.
14721 			 */
14722 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14723 			    !CLASSD(ipha->ipha_dst)) {
14724 				ire = ip_rput_process_broadcast(&q, mp,
14725 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14726 				    ll_multicast);
14727 				if (ire == NULL)
14728 					continue;
14729 			}
14730 		} else if (ire->ire_stq != NULL) {
14731 			/* fowarding? */
14732 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14733 			    ll_multicast);
14734 			/* ip_rput_process_forward consumed the packet */
14735 			continue;
14736 		}
14737 
14738 local:
14739 		/* packet not for us */
14740 		if (ire->ire_rfq != q) {
14741 			if (ip_rput_notforus(&q, mp, ire, ill))
14742 				continue;
14743 		}
14744 
14745 		switch (ipha->ipha_protocol) {
14746 		case IPPROTO_TCP:
14747 			ASSERT(first_mp == mp);
14748 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14749 				mp, 0, q, ip_ring)) != NULL) {
14750 				if (curr_sqp == NULL) {
14751 					curr_sqp = GET_SQUEUE(mp);
14752 					ASSERT(cnt == 0);
14753 					cnt++;
14754 					head = tail = mp;
14755 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14756 					ASSERT(tail != NULL);
14757 					cnt++;
14758 					tail->b_next = mp;
14759 					tail = mp;
14760 				} else {
14761 					/*
14762 					 * A different squeue. Send the
14763 					 * chain for the previous squeue on
14764 					 * its way. This shouldn't happen
14765 					 * often unless interrupt binding
14766 					 * changes.
14767 					 */
14768 					IP_STAT(ip_input_multi_squeue);
14769 					squeue_enter_chain(curr_sqp, head,
14770 					    tail, cnt, SQTAG_IP_INPUT);
14771 					curr_sqp = GET_SQUEUE(mp);
14772 					head = mp;
14773 					tail = mp;
14774 					cnt = 1;
14775 				}
14776 			}
14777 			continue;
14778 		case IPPROTO_UDP:
14779 			ASSERT(first_mp == mp);
14780 			ip_udp_input(q, mp, ipha, ire, ill);
14781 			continue;
14782 		case IPPROTO_SCTP:
14783 			ASSERT(first_mp == mp);
14784 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14785 			    q, dst);
14786 			/* ire has been released by ip_sctp_input */
14787 			ire = NULL;
14788 			continue;
14789 		default:
14790 			ip_proto_input(q, first_mp, ipha, ire, ill);
14791 			continue;
14792 		}
14793 	}
14794 
14795 	if (ire != NULL)
14796 		ire_refrele(ire);
14797 
14798 	if (head != NULL)
14799 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14800 
14801 	/*
14802 	 * This code is there just to make netperf/ttcp look good.
14803 	 *
14804 	 * Its possible that after being in polling mode (and having cleared
14805 	 * the backlog), squeues have turned the interrupt frequency higher
14806 	 * to improve latency at the expense of more CPU utilization (less
14807 	 * packets per interrupts or more number of interrupts). Workloads
14808 	 * like ttcp/netperf do manage to tickle polling once in a while
14809 	 * but for the remaining time, stay in higher interrupt mode since
14810 	 * their packet arrival rate is pretty uniform and this shows up
14811 	 * as higher CPU utilization. Since people care about CPU utilization
14812 	 * while running netperf/ttcp, turn the interrupt frequency back to
14813 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14814 	 */
14815 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14816 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14817 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14818 			ip_ring->rr_blank(ip_ring->rr_handle,
14819 			    ip_ring->rr_normal_blank_time,
14820 			    ip_ring->rr_normal_pkt_cnt);
14821 		}
14822 	}
14823 
14824 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14825 	    "ip_input_end: q %p (%S)", q, "end");
14826 #undef	rptr
14827 }
14828 
14829 static void
14830 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
14831     t_uscalar_t err)
14832 {
14833 	if (dl_err == DL_SYSERR) {
14834 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14835 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
14836 		    ill->ill_name, dlpi_prim_str(prim), err);
14837 		return;
14838 	}
14839 
14840 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14841 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
14842 	    dlpi_err_str(dl_err));
14843 }
14844 
14845 /*
14846  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
14847  * than DL_UNITDATA_IND messages. If we need to process this message
14848  * exclusively, we call qwriter_ip, in which case we also need to call
14849  * ill_refhold before that, since qwriter_ip does an ill_refrele.
14850  */
14851 void
14852 ip_rput_dlpi(queue_t *q, mblk_t *mp)
14853 {
14854 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14855 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14856 	ill_t		*ill;
14857 
14858 	ip1dbg(("ip_rput_dlpi"));
14859 	ill = (ill_t *)q->q_ptr;
14860 	switch (dloa->dl_primitive) {
14861 	case DL_ERROR_ACK:
14862 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
14863 		    "%s (0x%x), unix %u\n", ill->ill_name,
14864 		    dlpi_prim_str(dlea->dl_error_primitive),
14865 		    dlea->dl_error_primitive,
14866 		    dlpi_err_str(dlea->dl_errno),
14867 		    dlea->dl_errno,
14868 		    dlea->dl_unix_errno));
14869 		switch (dlea->dl_error_primitive) {
14870 		case DL_UNBIND_REQ:
14871 			mutex_enter(&ill->ill_lock);
14872 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14873 			cv_signal(&ill->ill_cv);
14874 			mutex_exit(&ill->ill_lock);
14875 			/* FALLTHRU */
14876 		case DL_NOTIFY_REQ:
14877 		case DL_ATTACH_REQ:
14878 		case DL_DETACH_REQ:
14879 		case DL_INFO_REQ:
14880 		case DL_BIND_REQ:
14881 		case DL_ENABMULTI_REQ:
14882 		case DL_PHYS_ADDR_REQ:
14883 		case DL_CAPABILITY_REQ:
14884 		case DL_CONTROL_REQ:
14885 			/*
14886 			 * Refhold the ill to match qwriter_ip which does a
14887 			 * refrele. Since this is on the ill stream we
14888 			 * unconditionally bump up the refcount without
14889 			 * checking for ILL_CAN_LOOKUP
14890 			 */
14891 			ill_refhold(ill);
14892 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14893 			    CUR_OP, B_FALSE);
14894 			return;
14895 		case DL_DISABMULTI_REQ:
14896 			freemsg(mp);	/* Don't want to pass this up */
14897 			return;
14898 		default:
14899 			break;
14900 		}
14901 		ip_dlpi_error(ill, dlea->dl_error_primitive,
14902 		    dlea->dl_errno, dlea->dl_unix_errno);
14903 		freemsg(mp);
14904 		return;
14905 	case DL_INFO_ACK:
14906 	case DL_BIND_ACK:
14907 	case DL_PHYS_ADDR_ACK:
14908 	case DL_NOTIFY_ACK:
14909 	case DL_CAPABILITY_ACK:
14910 	case DL_CONTROL_ACK:
14911 		/*
14912 		 * Refhold the ill to match qwriter_ip which does a refrele
14913 		 * Since this is on the ill stream we unconditionally
14914 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
14915 		 */
14916 		ill_refhold(ill);
14917 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14918 		    CUR_OP, B_FALSE);
14919 		return;
14920 	case DL_NOTIFY_IND:
14921 		ill_refhold(ill);
14922 		/*
14923 		 * The DL_NOTIFY_IND is an asynchronous message that has no
14924 		 * relation to the current ioctl in progress (if any). Hence we
14925 		 * pass in NEW_OP in this case.
14926 		 */
14927 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14928 		    NEW_OP, B_FALSE);
14929 		return;
14930 	case DL_OK_ACK:
14931 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
14932 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
14933 		switch (dloa->dl_correct_primitive) {
14934 		case DL_UNBIND_REQ:
14935 			mutex_enter(&ill->ill_lock);
14936 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14937 			cv_signal(&ill->ill_cv);
14938 			mutex_exit(&ill->ill_lock);
14939 			/* FALLTHRU */
14940 		case DL_ATTACH_REQ:
14941 		case DL_DETACH_REQ:
14942 			/*
14943 			 * Refhold the ill to match qwriter_ip which does a
14944 			 * refrele. Since this is on the ill stream we
14945 			 * unconditionally bump up the refcount
14946 			 */
14947 			ill_refhold(ill);
14948 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14949 			    CUR_OP, B_FALSE);
14950 			return;
14951 		case DL_ENABMULTI_REQ:
14952 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14953 				ill->ill_dlpi_multicast_state = IDMS_OK;
14954 			break;
14955 
14956 		}
14957 		break;
14958 	default:
14959 		break;
14960 	}
14961 	freemsg(mp);
14962 }
14963 
14964 /*
14965  * Handling of DLPI messages that require exclusive access to the ipsq.
14966  *
14967  * Need to do ill_pending_mp_release on ioctl completion, which could
14968  * happen here. (along with mi_copy_done)
14969  */
14970 /* ARGSUSED */
14971 static void
14972 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14973 {
14974 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14975 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14976 	int		err = 0;
14977 	ill_t		*ill;
14978 	ipif_t		*ipif = NULL;
14979 	mblk_t		*mp1 = NULL;
14980 	conn_t		*connp = NULL;
14981 	t_uscalar_t	physaddr_req;
14982 	mblk_t		*mp_hw;
14983 	union DL_primitives *dlp;
14984 	boolean_t	success;
14985 	boolean_t	ioctl_aborted = B_FALSE;
14986 	boolean_t	log = B_TRUE;
14987 
14988 	ip1dbg(("ip_rput_dlpi_writer .."));
14989 	ill = (ill_t *)q->q_ptr;
14990 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14991 
14992 	ASSERT(IAM_WRITER_ILL(ill));
14993 
14994 	/*
14995 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
14996 	 * both are null or non-null. However we can assert that only
14997 	 * after grabbing the ipsq_lock. So we don't make any assertion
14998 	 * here and in other places in the code.
14999 	 */
15000 	ipif = ipsq->ipsq_pending_ipif;
15001 	/*
15002 	 * The current ioctl could have been aborted by the user and a new
15003 	 * ioctl to bring up another ill could have started. We could still
15004 	 * get a response from the driver later.
15005 	 */
15006 	if (ipif != NULL && ipif->ipif_ill != ill)
15007 		ioctl_aborted = B_TRUE;
15008 
15009 	switch (dloa->dl_primitive) {
15010 	case DL_ERROR_ACK:
15011 		switch (dlea->dl_error_primitive) {
15012 		case DL_UNBIND_REQ:
15013 		case DL_ATTACH_REQ:
15014 		case DL_DETACH_REQ:
15015 		case DL_INFO_REQ:
15016 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15017 			break;
15018 		case DL_NOTIFY_REQ:
15019 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15020 			log = B_FALSE;
15021 			break;
15022 		case DL_PHYS_ADDR_REQ:
15023 			/*
15024 			 * For IPv6 only, there are two additional
15025 			 * phys_addr_req's sent to the driver to get the
15026 			 * IPv6 token and lla. This allows IP to acquire
15027 			 * the hardware address format for a given interface
15028 			 * without having built in knowledge of the hardware
15029 			 * address. ill_phys_addr_pend keeps track of the last
15030 			 * DL_PAR sent so we know which response we are
15031 			 * dealing with. ill_dlpi_done will update
15032 			 * ill_phys_addr_pend when it sends the next req.
15033 			 * We don't complete the IOCTL until all three DL_PARs
15034 			 * have been attempted, so set *_len to 0 and break.
15035 			 */
15036 			physaddr_req = ill->ill_phys_addr_pend;
15037 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15038 			if (physaddr_req == DL_IPV6_TOKEN) {
15039 				ill->ill_token_length = 0;
15040 				log = B_FALSE;
15041 				break;
15042 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15043 				ill->ill_nd_lla_len = 0;
15044 				log = B_FALSE;
15045 				break;
15046 			}
15047 			/*
15048 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15049 			 * We presumably have an IOCTL hanging out waiting
15050 			 * for completion. Find it and complete the IOCTL
15051 			 * with the error noted.
15052 			 * However, ill_dl_phys was called on an ill queue
15053 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15054 			 * set. But the ioctl is known to be pending on ill_wq.
15055 			 */
15056 			if (!ill->ill_ifname_pending)
15057 				break;
15058 			ill->ill_ifname_pending = 0;
15059 			if (!ioctl_aborted)
15060 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15061 			if (mp1 != NULL) {
15062 				/*
15063 				 * This operation (SIOCSLIFNAME) must have
15064 				 * happened on the ill. Assert there is no conn
15065 				 */
15066 				ASSERT(connp == NULL);
15067 				q = ill->ill_wq;
15068 			}
15069 			break;
15070 		case DL_BIND_REQ:
15071 			ill_dlpi_done(ill, DL_BIND_REQ);
15072 			if (ill->ill_ifname_pending)
15073 				break;
15074 			/*
15075 			 * Something went wrong with the bind.  We presumably
15076 			 * have an IOCTL hanging out waiting for completion.
15077 			 * Find it, take down the interface that was coming
15078 			 * up, and complete the IOCTL with the error noted.
15079 			 */
15080 			if (!ioctl_aborted)
15081 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15082 			if (mp1 != NULL) {
15083 				/*
15084 				 * This operation (SIOCSLIFFLAGS) must have
15085 				 * happened from a conn.
15086 				 */
15087 				ASSERT(connp != NULL);
15088 				q = CONNP_TO_WQ(connp);
15089 				if (ill->ill_move_in_progress) {
15090 					ILL_CLEAR_MOVE(ill);
15091 				}
15092 				(void) ipif_down(ipif, NULL, NULL);
15093 				/* error is set below the switch */
15094 			}
15095 			break;
15096 		case DL_ENABMULTI_REQ:
15097 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15098 
15099 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
15100 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
15101 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
15102 				ipif_t *ipif;
15103 
15104 				log = B_FALSE;
15105 				printf("ip: joining multicasts failed (%d)"
15106 				    " on %s - will use link layer "
15107 				    "broadcasts for multicast\n",
15108 				    dlea->dl_errno, ill->ill_name);
15109 
15110 				/*
15111 				 * Set up the multicast mapping alone.
15112 				 * writer, so ok to access ill->ill_ipif
15113 				 * without any lock.
15114 				 */
15115 				ipif = ill->ill_ipif;
15116 				mutex_enter(&ill->ill_phyint->phyint_lock);
15117 				ill->ill_phyint->phyint_flags |=
15118 				    PHYI_MULTI_BCAST;
15119 				mutex_exit(&ill->ill_phyint->phyint_lock);
15120 
15121 				if (!ill->ill_isv6) {
15122 					(void) ipif_arp_setup_multicast(ipif,
15123 					    NULL);
15124 				} else {
15125 					(void) ipif_ndp_setup_multicast(ipif,
15126 					    NULL);
15127 				}
15128 			}
15129 			freemsg(mp);	/* Don't want to pass this up */
15130 			return;
15131 		case DL_CAPABILITY_REQ:
15132 		case DL_CONTROL_REQ:
15133 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15134 			    "DL_CAPABILITY/CONTROL REQ\n"));
15135 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15136 			ill->ill_capab_state = IDMS_FAILED;
15137 			freemsg(mp);
15138 			return;
15139 		}
15140 		/*
15141 		 * Note the error for IOCTL completion (mp1 is set when
15142 		 * ready to complete ioctl). If ill_ifname_pending_err is
15143 		 * set, an error occured during plumbing (ill_ifname_pending),
15144 		 * so we want to report that error.
15145 		 *
15146 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15147 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15148 		 * expected to get errack'd if the driver doesn't support
15149 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15150 		 * if these error conditions are encountered.
15151 		 */
15152 		if (mp1 != NULL) {
15153 			if (ill->ill_ifname_pending_err != 0)  {
15154 				err = ill->ill_ifname_pending_err;
15155 				ill->ill_ifname_pending_err = 0;
15156 			} else {
15157 				err = dlea->dl_unix_errno ?
15158 				    dlea->dl_unix_errno : ENXIO;
15159 			}
15160 		/*
15161 		 * If we're plumbing an interface and an error hasn't already
15162 		 * been saved, set ill_ifname_pending_err to the error passed
15163 		 * up. Ignore the error if log is B_FALSE (see comment above).
15164 		 */
15165 		} else if (log && ill->ill_ifname_pending &&
15166 		    ill->ill_ifname_pending_err == 0) {
15167 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15168 			dlea->dl_unix_errno : ENXIO;
15169 		}
15170 
15171 		if (log)
15172 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15173 			    dlea->dl_errno, dlea->dl_unix_errno);
15174 		break;
15175 	case DL_CAPABILITY_ACK: {
15176 		boolean_t reneg_flag = B_FALSE;
15177 		/* Call a routine to handle this one. */
15178 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15179 		/*
15180 		 * Check if the ACK is due to renegotiation case since we
15181 		 * will need to send a new CAPABILITY_REQ later.
15182 		 */
15183 		if (ill->ill_capab_state == IDMS_RENEG) {
15184 			/* This is the ack for a renogiation case */
15185 			reneg_flag = B_TRUE;
15186 			ill->ill_capab_state = IDMS_UNKNOWN;
15187 		}
15188 		ill_capability_ack(ill, mp);
15189 		if (reneg_flag)
15190 			ill_capability_probe(ill);
15191 		break;
15192 	}
15193 	case DL_CONTROL_ACK:
15194 		/* We treat all of these as "fire and forget" */
15195 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15196 		break;
15197 	case DL_INFO_ACK:
15198 		/* Call a routine to handle this one. */
15199 		ill_dlpi_done(ill, DL_INFO_REQ);
15200 		ip_ll_subnet_defaults(ill, mp);
15201 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15202 		return;
15203 	case DL_BIND_ACK:
15204 		/*
15205 		 * We should have an IOCTL waiting on this unless
15206 		 * sent by ill_dl_phys, in which case just return
15207 		 */
15208 		ill_dlpi_done(ill, DL_BIND_REQ);
15209 		if (ill->ill_ifname_pending)
15210 			break;
15211 
15212 		if (!ioctl_aborted)
15213 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15214 		if (mp1 == NULL)
15215 			break;
15216 		ASSERT(connp != NULL);
15217 		q = CONNP_TO_WQ(connp);
15218 
15219 		/*
15220 		 * We are exclusive. So nothing can change even after
15221 		 * we get the pending mp. If need be we can put it back
15222 		 * and restart, as in calling ipif_arp_up()  below.
15223 		 */
15224 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15225 
15226 		mutex_enter(&ill->ill_lock);
15227 		ill->ill_dl_up = 1;
15228 		mutex_exit(&ill->ill_lock);
15229 
15230 		/*
15231 		 * Now bring up the resolver; when that is complete, we'll
15232 		 * create IREs.  Note that we intentionally mirror what
15233 		 * ipif_up() would have done, because we got here by way of
15234 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15235 		 */
15236 		if (ill->ill_isv6) {
15237 			/*
15238 			 * v6 interfaces.
15239 			 * Unlike ARP which has to do another bind
15240 			 * and attach, once we get here we are
15241 			 * done with NDP. Except in the case of
15242 			 * ILLF_XRESOLV, in which case we send an
15243 			 * AR_INTERFACE_UP to the external resolver.
15244 			 * If all goes well, the ioctl will complete
15245 			 * in ip_rput(). If there's an error, we
15246 			 * complete it here.
15247 			 */
15248 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15249 			    B_FALSE);
15250 			if (err == 0) {
15251 				if (ill->ill_flags & ILLF_XRESOLV) {
15252 					mutex_enter(&connp->conn_lock);
15253 					mutex_enter(&ill->ill_lock);
15254 					success = ipsq_pending_mp_add(
15255 					    connp, ipif, q, mp1, 0);
15256 					mutex_exit(&ill->ill_lock);
15257 					mutex_exit(&connp->conn_lock);
15258 					if (success) {
15259 						err = ipif_resolver_up(ipif,
15260 						    Res_act_initial);
15261 						if (err == EINPROGRESS) {
15262 							freemsg(mp);
15263 							return;
15264 						}
15265 						ASSERT(err != 0);
15266 						mp1 = ipsq_pending_mp_get(ipsq,
15267 						    &connp);
15268 						ASSERT(mp1 != NULL);
15269 					} else {
15270 						/* conn has started closing */
15271 						err = EINTR;
15272 					}
15273 				} else { /* Non XRESOLV interface */
15274 					(void) ipif_resolver_up(ipif,
15275 					    Res_act_initial);
15276 					err = ipif_up_done_v6(ipif);
15277 				}
15278 			}
15279 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15280 			/*
15281 			 * ARP and other v4 external resolvers.
15282 			 * Leave the pending mblk intact so that
15283 			 * the ioctl completes in ip_rput().
15284 			 */
15285 			mutex_enter(&connp->conn_lock);
15286 			mutex_enter(&ill->ill_lock);
15287 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15288 			mutex_exit(&ill->ill_lock);
15289 			mutex_exit(&connp->conn_lock);
15290 			if (success) {
15291 				err = ipif_resolver_up(ipif, Res_act_initial);
15292 				if (err == EINPROGRESS) {
15293 					freemsg(mp);
15294 					return;
15295 				}
15296 				ASSERT(err != 0);
15297 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15298 			} else {
15299 				/* The conn has started closing */
15300 				err = EINTR;
15301 			}
15302 		} else {
15303 			/*
15304 			 * This one is complete. Reply to pending ioctl.
15305 			 */
15306 			(void) ipif_resolver_up(ipif, Res_act_initial);
15307 			err = ipif_up_done(ipif);
15308 		}
15309 
15310 		if ((err == 0) && (ill->ill_up_ipifs)) {
15311 			err = ill_up_ipifs(ill, q, mp1);
15312 			if (err == EINPROGRESS) {
15313 				freemsg(mp);
15314 				return;
15315 			}
15316 		}
15317 
15318 		if (ill->ill_up_ipifs) {
15319 			ill_group_cleanup(ill);
15320 		}
15321 
15322 		break;
15323 	case DL_NOTIFY_IND: {
15324 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15325 		ire_t *ire;
15326 		boolean_t need_ire_walk_v4 = B_FALSE;
15327 		boolean_t need_ire_walk_v6 = B_FALSE;
15328 
15329 		/*
15330 		 * Change the address everywhere we need to.
15331 		 * What we're getting here is a link-level addr or phys addr.
15332 		 * The new addr is at notify + notify->dl_addr_offset
15333 		 * The address length is notify->dl_addr_length;
15334 		 */
15335 		switch (notify->dl_notification) {
15336 		case DL_NOTE_PHYS_ADDR:
15337 			mp_hw = copyb(mp);
15338 			if (mp_hw == NULL) {
15339 				err = ENOMEM;
15340 				break;
15341 			}
15342 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15343 			/*
15344 			 * We currently don't support changing
15345 			 * the token via DL_NOTIFY_IND.
15346 			 * When we do support it, we have to consider
15347 			 * what the implications are with respect to
15348 			 * the token and the link local address.
15349 			 */
15350 			mutex_enter(&ill->ill_lock);
15351 			if (dlp->notify_ind.dl_data ==
15352 			    DL_IPV6_LINK_LAYER_ADDR) {
15353 				if (ill->ill_nd_lla_mp != NULL)
15354 					freemsg(ill->ill_nd_lla_mp);
15355 				ill->ill_nd_lla_mp = mp_hw;
15356 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15357 				    dlp->notify_ind.dl_addr_offset;
15358 				ill->ill_nd_lla_len =
15359 				    dlp->notify_ind.dl_addr_length -
15360 				    ABS(ill->ill_sap_length);
15361 				mutex_exit(&ill->ill_lock);
15362 				break;
15363 			} else if (dlp->notify_ind.dl_data ==
15364 			    DL_CURR_PHYS_ADDR) {
15365 				if (ill->ill_phys_addr_mp != NULL)
15366 					freemsg(ill->ill_phys_addr_mp);
15367 				ill->ill_phys_addr_mp = mp_hw;
15368 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15369 				    dlp->notify_ind.dl_addr_offset;
15370 				ill->ill_phys_addr_length =
15371 				    dlp->notify_ind.dl_addr_length -
15372 				    ABS(ill->ill_sap_length);
15373 				if (ill->ill_isv6 &&
15374 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15375 					if (ill->ill_nd_lla_mp != NULL)
15376 						freemsg(ill->ill_nd_lla_mp);
15377 					ill->ill_nd_lla_mp = copyb(mp_hw);
15378 					ill->ill_nd_lla = (uchar_t *)
15379 					    ill->ill_nd_lla_mp->b_rptr +
15380 					    dlp->notify_ind.dl_addr_offset;
15381 					ill->ill_nd_lla_len =
15382 					    ill->ill_phys_addr_length;
15383 				}
15384 			}
15385 			mutex_exit(&ill->ill_lock);
15386 			/*
15387 			 * Send out gratuitous arp request for our new
15388 			 * hardware address.
15389 			 */
15390 			for (ipif = ill->ill_ipif; ipif != NULL;
15391 			    ipif = ipif->ipif_next) {
15392 				if (!(ipif->ipif_flags & IPIF_UP))
15393 					continue;
15394 				if (ill->ill_isv6) {
15395 					ipif_ndp_down(ipif);
15396 					/*
15397 					 * Set B_TRUE to enable
15398 					 * ipif_ndp_up() to send out
15399 					 * unsolicited advertisements.
15400 					 */
15401 					err = ipif_ndp_up(ipif,
15402 					    &ipif->ipif_v6lcl_addr,
15403 					    B_TRUE);
15404 					if (err) {
15405 						ip1dbg((
15406 						    "ip_rput_dlpi_writer: "
15407 						    "Failed to update ndp "
15408 						    "err %d\n", err));
15409 					}
15410 				} else {
15411 					/*
15412 					 * IPv4 ARP case
15413 					 *
15414 					 * Set Res_act_move, as we only want
15415 					 * ipif_resolver_up to send an
15416 					 * AR_ENTRY_ADD request up to
15417 					 * ARP.
15418 					 */
15419 					err = ipif_resolver_up(ipif,
15420 					    Res_act_move);
15421 					if (err) {
15422 						ip1dbg((
15423 						    "ip_rput_dlpi_writer: "
15424 						    "Failed to update arp "
15425 						    "err %d\n", err));
15426 					}
15427 				}
15428 			}
15429 			/*
15430 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15431 			 * case so that all old fastpath information can be
15432 			 * purged from IRE caches.
15433 			 */
15434 		/* FALLTHRU */
15435 		case DL_NOTE_FASTPATH_FLUSH:
15436 			/*
15437 			 * Any fastpath probe sent henceforth will get the
15438 			 * new fp mp. So we first delete any ires that are
15439 			 * waiting for the fastpath. Then walk all ires and
15440 			 * delete the ire or delete the fp mp. In the case of
15441 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15442 			 * recreate the ire's without going through a complex
15443 			 * ipif up/down dance. So we don't delete the ire
15444 			 * itself, but just the nce_fp_mp for these 2 ire's
15445 			 * In the case of the other ire's we delete the ire's
15446 			 * themselves. Access to nce_fp_mp is completely
15447 			 * protected by ire_lock for IRE_MIPRTUN and
15448 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15449 			 * other cases for performance.
15450 			 */
15451 			if (ill->ill_isv6) {
15452 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15453 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15454 				    NULL);
15455 			} else {
15456 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15457 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15458 				    IRE_CACHE | IRE_BROADCAST,
15459 				    ire_fastpath_flush, NULL, ill);
15460 				mutex_enter(&ire_mrtun_lock);
15461 				if (ire_mrtun_count != 0) {
15462 					mutex_exit(&ire_mrtun_lock);
15463 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15464 					    IRE_MIPRTUN, ire_fastpath_flush,
15465 					    NULL, ill);
15466 				} else {
15467 					mutex_exit(&ire_mrtun_lock);
15468 				}
15469 			}
15470 			break;
15471 		case DL_NOTE_SDU_SIZE:
15472 			/*
15473 			 * Change the MTU size of the interface, of all
15474 			 * attached ipif's, and of all relevant ire's.  The
15475 			 * new value's a uint32_t at notify->dl_data.
15476 			 * Mtu change Vs. new ire creation - protocol below.
15477 			 *
15478 			 * a Mark the ipif as IPIF_CHANGING.
15479 			 * b Set the new mtu in the ipif.
15480 			 * c Change the ire_max_frag on all affected ires
15481 			 * d Unmark the IPIF_CHANGING
15482 			 *
15483 			 * To see how the protocol works, assume an interface
15484 			 * route is also being added simultaneously by
15485 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15486 			 * the ire. If the ire is created before step a,
15487 			 * it will be cleaned up by step c. If the ire is
15488 			 * created after step d, it will see the new value of
15489 			 * ipif_mtu. Any attempt to create the ire between
15490 			 * steps a to d will fail because of the IPIF_CHANGING
15491 			 * flag. Note that ire_create() is passed a pointer to
15492 			 * the ipif_mtu, and not the value. During ire_add
15493 			 * under the bucket lock, the ire_max_frag of the
15494 			 * new ire being created is set from the ipif/ire from
15495 			 * which it is being derived.
15496 			 */
15497 			mutex_enter(&ill->ill_lock);
15498 			ill->ill_max_frag = (uint_t)notify->dl_data;
15499 
15500 			/*
15501 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15502 			 * leave it alone
15503 			 */
15504 			if (ill->ill_mtu_userspecified) {
15505 				mutex_exit(&ill->ill_lock);
15506 				break;
15507 			}
15508 			ill->ill_max_mtu = ill->ill_max_frag;
15509 			if (ill->ill_isv6) {
15510 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15511 					ill->ill_max_mtu = IPV6_MIN_MTU;
15512 			} else {
15513 				if (ill->ill_max_mtu < IP_MIN_MTU)
15514 					ill->ill_max_mtu = IP_MIN_MTU;
15515 			}
15516 			for (ipif = ill->ill_ipif; ipif != NULL;
15517 			    ipif = ipif->ipif_next) {
15518 				/*
15519 				 * Don't override the mtu if the user
15520 				 * has explicitly set it.
15521 				 */
15522 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15523 					continue;
15524 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15525 				if (ipif->ipif_isv6)
15526 					ire = ipif_to_ire_v6(ipif);
15527 				else
15528 					ire = ipif_to_ire(ipif);
15529 				if (ire != NULL) {
15530 					ire->ire_max_frag = ipif->ipif_mtu;
15531 					ire_refrele(ire);
15532 				}
15533 				if (ipif->ipif_flags & IPIF_UP) {
15534 					if (ill->ill_isv6)
15535 						need_ire_walk_v6 = B_TRUE;
15536 					else
15537 						need_ire_walk_v4 = B_TRUE;
15538 				}
15539 			}
15540 			mutex_exit(&ill->ill_lock);
15541 			if (need_ire_walk_v4)
15542 				ire_walk_v4(ill_mtu_change, (char *)ill,
15543 				    ALL_ZONES);
15544 			if (need_ire_walk_v6)
15545 				ire_walk_v6(ill_mtu_change, (char *)ill,
15546 				    ALL_ZONES);
15547 			break;
15548 		case DL_NOTE_LINK_UP:
15549 		case DL_NOTE_LINK_DOWN: {
15550 			/*
15551 			 * We are writer. ill / phyint / ipsq assocs stable.
15552 			 * The RUNNING flag reflects the state of the link.
15553 			 */
15554 			phyint_t *phyint = ill->ill_phyint;
15555 			uint64_t new_phyint_flags;
15556 			boolean_t changed = B_FALSE;
15557 			boolean_t went_up;
15558 
15559 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15560 			mutex_enter(&phyint->phyint_lock);
15561 			new_phyint_flags = went_up ?
15562 			    phyint->phyint_flags | PHYI_RUNNING :
15563 			    phyint->phyint_flags & ~PHYI_RUNNING;
15564 			if (new_phyint_flags != phyint->phyint_flags) {
15565 				phyint->phyint_flags = new_phyint_flags;
15566 				changed = B_TRUE;
15567 			}
15568 			mutex_exit(&phyint->phyint_lock);
15569 			/*
15570 			 * ill_restart_dad handles the DAD restart and routing
15571 			 * socket notification logic.
15572 			 */
15573 			if (changed) {
15574 				ill_restart_dad(phyint->phyint_illv4, went_up);
15575 				ill_restart_dad(phyint->phyint_illv6, went_up);
15576 			}
15577 			break;
15578 		}
15579 		case DL_NOTE_PROMISC_ON_PHYS:
15580 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15581 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15582 			mutex_enter(&ill->ill_lock);
15583 			ill->ill_promisc_on_phys = B_TRUE;
15584 			mutex_exit(&ill->ill_lock);
15585 			break;
15586 		case DL_NOTE_PROMISC_OFF_PHYS:
15587 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15588 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15589 			mutex_enter(&ill->ill_lock);
15590 			ill->ill_promisc_on_phys = B_FALSE;
15591 			mutex_exit(&ill->ill_lock);
15592 			break;
15593 		case DL_NOTE_CAPAB_RENEG:
15594 			/*
15595 			 * Something changed on the driver side.
15596 			 * It wants us to renegotiate the capabilities
15597 			 * on this ill. The most likely cause is the
15598 			 * aggregation interface under us where a
15599 			 * port got added or went away.
15600 			 *
15601 			 * We reset the capabilities and set the
15602 			 * state to IDMS_RENG so that when the ack
15603 			 * comes back, we can start the
15604 			 * renegotiation process.
15605 			 */
15606 			ill_capability_reset(ill);
15607 			ill->ill_capab_state = IDMS_RENEG;
15608 			break;
15609 		default:
15610 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15611 			    "type 0x%x for DL_NOTIFY_IND\n",
15612 			    notify->dl_notification));
15613 			break;
15614 		}
15615 
15616 		/*
15617 		 * As this is an asynchronous operation, we
15618 		 * should not call ill_dlpi_done
15619 		 */
15620 		break;
15621 	}
15622 	case DL_NOTIFY_ACK: {
15623 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15624 
15625 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15626 			ill->ill_note_link = 1;
15627 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15628 		break;
15629 	}
15630 	case DL_PHYS_ADDR_ACK: {
15631 		/*
15632 		 * We should have an IOCTL waiting on this when request
15633 		 * sent by ill_dl_phys.
15634 		 * However, ill_dl_phys was called on an ill queue (from
15635 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15636 		 * ioctl is known to be pending on ill_wq.
15637 		 * There are two additional phys_addr_req's sent to the
15638 		 * driver to get the token and lla. ill_phys_addr_pend
15639 		 * keeps track of the last one sent so we know which
15640 		 * response we are dealing with. ill_dlpi_done will
15641 		 * update ill_phys_addr_pend when it sends the next req.
15642 		 * We don't complete the IOCTL until all three DL_PARs
15643 		 * have been attempted.
15644 		 *
15645 		 * We don't need any lock to update ill_nd_lla* fields,
15646 		 * since the ill is not yet up, We grab the lock just
15647 		 * for uniformity with other code that accesses ill_nd_lla.
15648 		 */
15649 		physaddr_req = ill->ill_phys_addr_pend;
15650 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15651 		if (physaddr_req == DL_IPV6_TOKEN ||
15652 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15653 			if (physaddr_req == DL_IPV6_TOKEN) {
15654 				/*
15655 				 * bcopy to low-order bits of ill_token
15656 				 *
15657 				 * XXX Temporary hack - currently,
15658 				 * all known tokens are 64 bits,
15659 				 * so I'll cheat for the moment.
15660 				 */
15661 				dlp = (union DL_primitives *)mp->b_rptr;
15662 
15663 				mutex_enter(&ill->ill_lock);
15664 				bcopy((uchar_t *)(mp->b_rptr +
15665 				dlp->physaddr_ack.dl_addr_offset),
15666 				(void *)&ill->ill_token.s6_addr32[2],
15667 				dlp->physaddr_ack.dl_addr_length);
15668 				ill->ill_token_length =
15669 					dlp->physaddr_ack.dl_addr_length;
15670 				mutex_exit(&ill->ill_lock);
15671 			} else {
15672 				ASSERT(ill->ill_nd_lla_mp == NULL);
15673 				mp_hw = copyb(mp);
15674 				if (mp_hw == NULL) {
15675 					err = ENOMEM;
15676 					break;
15677 				}
15678 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15679 				mutex_enter(&ill->ill_lock);
15680 				ill->ill_nd_lla_mp = mp_hw;
15681 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15682 				dlp->physaddr_ack.dl_addr_offset;
15683 				ill->ill_nd_lla_len =
15684 					dlp->physaddr_ack.dl_addr_length;
15685 				mutex_exit(&ill->ill_lock);
15686 			}
15687 			break;
15688 		}
15689 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15690 		ASSERT(ill->ill_phys_addr_mp == NULL);
15691 		if (!ill->ill_ifname_pending)
15692 			break;
15693 		ill->ill_ifname_pending = 0;
15694 		if (!ioctl_aborted)
15695 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15696 		if (mp1 != NULL) {
15697 			ASSERT(connp == NULL);
15698 			q = ill->ill_wq;
15699 		}
15700 		/*
15701 		 * If any error acks received during the plumbing sequence,
15702 		 * ill_ifname_pending_err will be set. Break out and send up
15703 		 * the error to the pending ioctl.
15704 		 */
15705 		if (ill->ill_ifname_pending_err != 0) {
15706 			err = ill->ill_ifname_pending_err;
15707 			ill->ill_ifname_pending_err = 0;
15708 			break;
15709 		}
15710 		/*
15711 		 * Get the interface token.  If the zeroth interface
15712 		 * address is zero then set the address to the link local
15713 		 * address
15714 		 */
15715 		mp_hw = copyb(mp);
15716 		if (mp_hw == NULL) {
15717 			err = ENOMEM;
15718 			break;
15719 		}
15720 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15721 		ill->ill_phys_addr_mp = mp_hw;
15722 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15723 				dlp->physaddr_ack.dl_addr_offset;
15724 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15725 		    ill->ill_phys_addr_length == 0 ||
15726 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15727 			/*
15728 			 * Compatibility: atun driver returns a length of 0.
15729 			 * ipdptp has an ill_phys_addr_length of zero(from
15730 			 * DL_BIND_ACK) but a non-zero length here.
15731 			 * ipd has an ill_phys_addr_length of 4(from
15732 			 * DL_BIND_ACK) but a non-zero length here.
15733 			 */
15734 			ill->ill_phys_addr = NULL;
15735 		} else if (dlp->physaddr_ack.dl_addr_length !=
15736 		    ill->ill_phys_addr_length) {
15737 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15738 			    "Address length mismatch %d %d\n",
15739 			    dlp->physaddr_ack.dl_addr_length,
15740 			    ill->ill_phys_addr_length));
15741 			err = EINVAL;
15742 			break;
15743 		}
15744 		mutex_enter(&ill->ill_lock);
15745 		if (ill->ill_nd_lla_mp == NULL) {
15746 			ill->ill_nd_lla_mp = copyb(mp_hw);
15747 			if (ill->ill_nd_lla_mp == NULL) {
15748 				err = ENOMEM;
15749 				mutex_exit(&ill->ill_lock);
15750 				break;
15751 			}
15752 			ill->ill_nd_lla =
15753 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15754 			    dlp->physaddr_ack.dl_addr_offset;
15755 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15756 		}
15757 		mutex_exit(&ill->ill_lock);
15758 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15759 			(void) ill_setdefaulttoken(ill);
15760 
15761 		/*
15762 		 * If the ill zero interface has a zero address assign
15763 		 * it the proper link local address.
15764 		 */
15765 		ASSERT(ill->ill_ipif->ipif_id == 0);
15766 		if (ipif != NULL &&
15767 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15768 			(void) ipif_setlinklocal(ipif);
15769 		break;
15770 	}
15771 	case DL_OK_ACK:
15772 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15773 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15774 		    dloa->dl_correct_primitive));
15775 		switch (dloa->dl_correct_primitive) {
15776 		case DL_UNBIND_REQ:
15777 		case DL_ATTACH_REQ:
15778 		case DL_DETACH_REQ:
15779 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15780 			break;
15781 		}
15782 		break;
15783 	default:
15784 		break;
15785 	}
15786 
15787 	freemsg(mp);
15788 	if (mp1) {
15789 		struct iocblk *iocp;
15790 		int mode;
15791 
15792 		/*
15793 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15794 		 * SIOCSLIFNAME do a copyout.
15795 		 */
15796 		iocp = (struct iocblk *)mp1->b_rptr;
15797 
15798 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
15799 		    iocp->ioc_cmd == SIOCSLIFNAME)
15800 			mode = COPYOUT;
15801 		else
15802 			mode = NO_COPYOUT;
15803 		/*
15804 		 * The ioctl must complete now without EINPROGRESS
15805 		 * since ipsq_pending_mp_get has removed the ioctl mblk
15806 		 * from ipsq_pending_mp. Otherwise the ioctl will be
15807 		 * stuck for ever in the ipsq.
15808 		 */
15809 		ASSERT(err != EINPROGRESS);
15810 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
15811 
15812 	}
15813 }
15814 
15815 /*
15816  * ip_rput_other is called by ip_rput to handle messages modifying the global
15817  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15818  */
15819 /* ARGSUSED */
15820 void
15821 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15822 {
15823 	ill_t		*ill;
15824 	struct iocblk	*iocp;
15825 	mblk_t		*mp1;
15826 	conn_t		*connp = NULL;
15827 
15828 	ip1dbg(("ip_rput_other "));
15829 	ill = (ill_t *)q->q_ptr;
15830 	/*
15831 	 * This routine is not a writer in the case of SIOCGTUNPARAM
15832 	 * in which case ipsq is NULL.
15833 	 */
15834 	if (ipsq != NULL) {
15835 		ASSERT(IAM_WRITER_IPSQ(ipsq));
15836 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15837 	}
15838 
15839 	switch (mp->b_datap->db_type) {
15840 	case M_ERROR:
15841 	case M_HANGUP:
15842 		/*
15843 		 * The device has a problem.  We force the ILL down.  It can
15844 		 * be brought up again manually using SIOCSIFFLAGS (via
15845 		 * ifconfig or equivalent).
15846 		 */
15847 		ASSERT(ipsq != NULL);
15848 		if (mp->b_rptr < mp->b_wptr)
15849 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
15850 		if (ill->ill_error == 0)
15851 			ill->ill_error = ENXIO;
15852 		if (!ill_down_start(q, mp))
15853 			return;
15854 		ipif_all_down_tail(ipsq, q, mp, NULL);
15855 		break;
15856 	case M_IOCACK:
15857 		iocp = (struct iocblk *)mp->b_rptr;
15858 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
15859 		switch (iocp->ioc_cmd) {
15860 		case SIOCSTUNPARAM:
15861 		case OSIOCSTUNPARAM:
15862 			ASSERT(ipsq != NULL);
15863 			/*
15864 			 * Finish socket ioctl passed through to tun.
15865 			 * We should have an IOCTL waiting on this.
15866 			 */
15867 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15868 			if (ill->ill_isv6) {
15869 				struct iftun_req *ta;
15870 
15871 				/*
15872 				 * if a source or destination is
15873 				 * being set, try and set the link
15874 				 * local address for the tunnel
15875 				 */
15876 				ta = (struct iftun_req *)mp->b_cont->
15877 				    b_cont->b_rptr;
15878 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
15879 					ipif_set_tun_llink(ill, ta);
15880 				}
15881 
15882 			}
15883 			if (mp1 != NULL) {
15884 				/*
15885 				 * Now copy back the b_next/b_prev used by
15886 				 * mi code for the mi_copy* functions.
15887 				 * See ip_sioctl_tunparam() for the reason.
15888 				 * Also protect against missing b_cont.
15889 				 */
15890 				if (mp->b_cont != NULL) {
15891 					mp->b_cont->b_next =
15892 					    mp1->b_cont->b_next;
15893 					mp->b_cont->b_prev =
15894 					    mp1->b_cont->b_prev;
15895 				}
15896 				inet_freemsg(mp1);
15897 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15898 				ASSERT(connp != NULL);
15899 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15900 				    iocp->ioc_error, NO_COPYOUT,
15901 				    ipsq->ipsq_current_ipif, ipsq);
15902 			} else {
15903 				ASSERT(connp == NULL);
15904 				putnext(q, mp);
15905 			}
15906 			break;
15907 		case SIOCGTUNPARAM:
15908 		case OSIOCGTUNPARAM:
15909 			/*
15910 			 * This is really M_IOCDATA from the tunnel driver.
15911 			 * convert back and complete the ioctl.
15912 			 * We should have an IOCTL waiting on this.
15913 			 */
15914 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
15915 			if (mp1) {
15916 				/*
15917 				 * Now copy back the b_next/b_prev used by
15918 				 * mi code for the mi_copy* functions.
15919 				 * See ip_sioctl_tunparam() for the reason.
15920 				 * Also protect against missing b_cont.
15921 				 */
15922 				if (mp->b_cont != NULL) {
15923 					mp->b_cont->b_next =
15924 					    mp1->b_cont->b_next;
15925 					mp->b_cont->b_prev =
15926 					    mp1->b_cont->b_prev;
15927 				}
15928 				inet_freemsg(mp1);
15929 				if (iocp->ioc_error == 0)
15930 					mp->b_datap->db_type = M_IOCDATA;
15931 				ASSERT(connp != NULL);
15932 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15933 				    iocp->ioc_error, COPYOUT, NULL, NULL);
15934 			} else {
15935 				ASSERT(connp == NULL);
15936 				putnext(q, mp);
15937 			}
15938 			break;
15939 		default:
15940 			break;
15941 		}
15942 		break;
15943 	case M_IOCNAK:
15944 		iocp = (struct iocblk *)mp->b_rptr;
15945 
15946 		switch (iocp->ioc_cmd) {
15947 		int mode;
15948 		ipif_t	*ipif;
15949 
15950 		case DL_IOC_HDR_INFO:
15951 			/*
15952 			 * If this was the first attempt turn of the
15953 			 * fastpath probing.
15954 			 */
15955 			mutex_enter(&ill->ill_lock);
15956 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
15957 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
15958 				mutex_exit(&ill->ill_lock);
15959 				ill_fastpath_nack(ill);
15960 				ip1dbg(("ip_rput: DLPI fastpath off on "
15961 				    "interface %s\n",
15962 				    ill->ill_name));
15963 			} else {
15964 				mutex_exit(&ill->ill_lock);
15965 			}
15966 			freemsg(mp);
15967 			break;
15968 		case SIOCSTUNPARAM:
15969 		case OSIOCSTUNPARAM:
15970 			ASSERT(ipsq != NULL);
15971 			/*
15972 			 * Finish socket ioctl passed through to tun
15973 			 * We should have an IOCTL waiting on this.
15974 			 */
15975 			/* FALLTHRU */
15976 		case SIOCGTUNPARAM:
15977 		case OSIOCGTUNPARAM:
15978 			/*
15979 			 * This is really M_IOCDATA from the tunnel driver.
15980 			 * convert back and complete the ioctl.
15981 			 * We should have an IOCTL waiting on this.
15982 			 */
15983 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
15984 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
15985 				mp1 = ill_pending_mp_get(ill, &connp,
15986 				    iocp->ioc_id);
15987 				mode = COPYOUT;
15988 				ipsq = NULL;
15989 				ipif = NULL;
15990 			} else {
15991 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15992 				mode = NO_COPYOUT;
15993 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15994 				ipif = ipsq->ipsq_current_ipif;
15995 			}
15996 			if (mp1 != NULL) {
15997 				/*
15998 				 * Now copy back the b_next/b_prev used by
15999 				 * mi code for the mi_copy* functions.
16000 				 * See ip_sioctl_tunparam() for the reason.
16001 				 * Also protect against missing b_cont.
16002 				 */
16003 				if (mp->b_cont != NULL) {
16004 					mp->b_cont->b_next =
16005 					    mp1->b_cont->b_next;
16006 					mp->b_cont->b_prev =
16007 					    mp1->b_cont->b_prev;
16008 				}
16009 				inet_freemsg(mp1);
16010 				if (iocp->ioc_error == 0)
16011 					iocp->ioc_error = EINVAL;
16012 				ASSERT(connp != NULL);
16013 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16014 				    iocp->ioc_error, mode, ipif, ipsq);
16015 			} else {
16016 				ASSERT(connp == NULL);
16017 				putnext(q, mp);
16018 			}
16019 			break;
16020 		default:
16021 			break;
16022 		}
16023 	default:
16024 		break;
16025 	}
16026 }
16027 
16028 /*
16029  * NOTE : This function does not ire_refrele the ire argument passed in.
16030  *
16031  * IPQoS notes
16032  * IP policy is invoked twice for a forwarded packet, once on the read side
16033  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16034  * enabled. An additional parameter, in_ill, has been added for this purpose.
16035  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16036  * because ip_mroute drops this information.
16037  *
16038  */
16039 void
16040 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16041 {
16042 	uint32_t	pkt_len;
16043 	queue_t	*q;
16044 	uint32_t	sum;
16045 #define	rptr	((uchar_t *)ipha)
16046 	uint32_t	max_frag;
16047 	uint32_t	ill_index;
16048 
16049 	/* Get the ill_index of the incoming ILL */
16050 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16051 
16052 	/* Initiate Read side IPPF processing */
16053 	if (IPP_ENABLED(IPP_FWD_IN)) {
16054 		ip_process(IPP_FWD_IN, &mp, ill_index);
16055 		if (mp == NULL) {
16056 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16057 			    "during IPPF processing\n"));
16058 			return;
16059 		}
16060 	}
16061 
16062 	pkt_len = ntohs(ipha->ipha_length);
16063 
16064 	/* Adjust the checksum to reflect the ttl decrement. */
16065 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16066 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16067 
16068 	if (ipha->ipha_ttl-- <= 1) {
16069 		if (ip_csum_hdr(ipha)) {
16070 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16071 			goto drop_pkt;
16072 		}
16073 		/*
16074 		 * Note: ire_stq this will be NULL for multicast
16075 		 * datagrams using the long path through arp (the IRE
16076 		 * is not an IRE_CACHE). This should not cause
16077 		 * problems since we don't generate ICMP errors for
16078 		 * multicast packets.
16079 		 */
16080 		q = ire->ire_stq;
16081 		if (q != NULL) {
16082 			/* Sent by forwarding path, and router is global zone */
16083 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16084 			    GLOBAL_ZONEID);
16085 		} else
16086 			freemsg(mp);
16087 		return;
16088 	}
16089 
16090 	/*
16091 	 * Don't forward if the interface is down
16092 	 */
16093 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16094 		BUMP_MIB(&ip_mib, ipInDiscards);
16095 		ip2dbg(("ip_rput_forward:interface is down\n"));
16096 		goto drop_pkt;
16097 	}
16098 
16099 	/* Get the ill_index of the outgoing ILL */
16100 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16101 
16102 	if (is_system_labeled()) {
16103 		mblk_t *mp1;
16104 
16105 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16106 			BUMP_MIB(&ip_mib, ipForwProhibits);
16107 			goto drop_pkt;
16108 		}
16109 		/* Size may have changed */
16110 		mp = mp1;
16111 		ipha = (ipha_t *)mp->b_rptr;
16112 		pkt_len = ntohs(ipha->ipha_length);
16113 	}
16114 
16115 	/* Check if there are options to update */
16116 	if (!IS_SIMPLE_IPH(ipha)) {
16117 		if (ip_csum_hdr(ipha)) {
16118 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16119 			goto drop_pkt;
16120 		}
16121 		if (ip_rput_forward_options(mp, ipha, ire)) {
16122 			return;
16123 		}
16124 
16125 		ipha->ipha_hdr_checksum = 0;
16126 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16127 	}
16128 	max_frag = ire->ire_max_frag;
16129 	if (pkt_len > max_frag) {
16130 		/*
16131 		 * It needs fragging on its way out.  We haven't
16132 		 * verified the header checksum yet.  Since we
16133 		 * are going to put a surely good checksum in the
16134 		 * outgoing header, we have to make sure that it
16135 		 * was good coming in.
16136 		 */
16137 		if (ip_csum_hdr(ipha)) {
16138 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16139 			goto drop_pkt;
16140 		}
16141 		/* Initiate Write side IPPF processing */
16142 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16143 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16144 			if (mp == NULL) {
16145 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16146 				    " during IPPF processing\n"));
16147 				return;
16148 			}
16149 		}
16150 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
16151 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16152 		return;
16153 	}
16154 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16155 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16156 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16157 	/* ip_xmit_v4 always consumes the packet */
16158 	return;
16159 
16160 drop_pkt:;
16161 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16162 	freemsg(mp);
16163 #undef	rptr
16164 }
16165 
16166 void
16167 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16168 {
16169 	ire_t	*ire;
16170 
16171 	ASSERT(!ipif->ipif_isv6);
16172 	/*
16173 	 * Find an IRE which matches the destination and the outgoing
16174 	 * queue in the cache table. All we need is an IRE_CACHE which
16175 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16176 	 * then it is enough to have some IRE_CACHE in the group.
16177 	 */
16178 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16179 		dst = ipif->ipif_pp_dst_addr;
16180 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16181 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16182 	if (ire == NULL) {
16183 		/*
16184 		 * Mark this packet to make it be delivered to
16185 		 * ip_rput_forward after the new ire has been
16186 		 * created.
16187 		 */
16188 		mp->b_prev = NULL;
16189 		mp->b_next = mp;
16190 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16191 		    NULL, 0, GLOBAL_ZONEID);
16192 	} else {
16193 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16194 		IRE_REFRELE(ire);
16195 	}
16196 }
16197 
16198 /* Update any source route, record route or timestamp options */
16199 static int
16200 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16201 {
16202 	ipoptp_t	opts;
16203 	uchar_t		*opt;
16204 	uint8_t		optval;
16205 	uint8_t		optlen;
16206 	ipaddr_t	dst;
16207 	uint32_t	ts;
16208 	ire_t		*dst_ire = NULL;
16209 	ire_t		*tmp_ire = NULL;
16210 	timestruc_t	now;
16211 
16212 	ip2dbg(("ip_rput_forward_options\n"));
16213 	dst = ipha->ipha_dst;
16214 	for (optval = ipoptp_first(&opts, ipha);
16215 	    optval != IPOPT_EOL;
16216 	    optval = ipoptp_next(&opts)) {
16217 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16218 		opt = opts.ipoptp_cur;
16219 		optlen = opts.ipoptp_len;
16220 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16221 		    optval, opts.ipoptp_len));
16222 		switch (optval) {
16223 			uint32_t off;
16224 		case IPOPT_SSRR:
16225 		case IPOPT_LSRR:
16226 			/* Check if adminstratively disabled */
16227 			if (!ip_forward_src_routed) {
16228 				BUMP_MIB(&ip_mib, ipForwProhibits);
16229 				if (ire->ire_stq != NULL) {
16230 					/*
16231 					 * Sent by forwarding path, and router
16232 					 * is global zone
16233 					 */
16234 					icmp_unreachable(ire->ire_stq, mp,
16235 					    ICMP_SOURCE_ROUTE_FAILED,
16236 					    GLOBAL_ZONEID);
16237 				} else {
16238 					ip0dbg(("ip_rput_forward_options: "
16239 					    "unable to send unreach\n"));
16240 					freemsg(mp);
16241 				}
16242 				return (-1);
16243 			}
16244 
16245 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16246 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16247 			if (dst_ire == NULL) {
16248 				/*
16249 				 * Must be partial since ip_rput_options
16250 				 * checked for strict.
16251 				 */
16252 				break;
16253 			}
16254 			off = opt[IPOPT_OFFSET];
16255 			off--;
16256 		redo_srr:
16257 			if (optlen < IP_ADDR_LEN ||
16258 			    off > optlen - IP_ADDR_LEN) {
16259 				/* End of source route */
16260 				ip1dbg((
16261 				    "ip_rput_forward_options: end of SR\n"));
16262 				ire_refrele(dst_ire);
16263 				break;
16264 			}
16265 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16266 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16267 			    IP_ADDR_LEN);
16268 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16269 			    ntohl(dst)));
16270 
16271 			/*
16272 			 * Check if our address is present more than
16273 			 * once as consecutive hops in source route.
16274 			 */
16275 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16276 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16277 			if (tmp_ire != NULL) {
16278 				ire_refrele(tmp_ire);
16279 				off += IP_ADDR_LEN;
16280 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16281 				goto redo_srr;
16282 			}
16283 			ipha->ipha_dst = dst;
16284 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16285 			ire_refrele(dst_ire);
16286 			break;
16287 		case IPOPT_RR:
16288 			off = opt[IPOPT_OFFSET];
16289 			off--;
16290 			if (optlen < IP_ADDR_LEN ||
16291 			    off > optlen - IP_ADDR_LEN) {
16292 				/* No more room - ignore */
16293 				ip1dbg((
16294 				    "ip_rput_forward_options: end of RR\n"));
16295 				break;
16296 			}
16297 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16298 			    IP_ADDR_LEN);
16299 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16300 			break;
16301 		case IPOPT_TS:
16302 			/* Insert timestamp if there is room */
16303 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16304 			case IPOPT_TS_TSONLY:
16305 				off = IPOPT_TS_TIMELEN;
16306 				break;
16307 			case IPOPT_TS_PRESPEC:
16308 			case IPOPT_TS_PRESPEC_RFC791:
16309 				/* Verify that the address matched */
16310 				off = opt[IPOPT_OFFSET] - 1;
16311 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16312 				dst_ire = ire_ctable_lookup(dst, 0,
16313 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16314 				    MATCH_IRE_TYPE);
16315 
16316 				if (dst_ire == NULL) {
16317 					/* Not for us */
16318 					break;
16319 				}
16320 				ire_refrele(dst_ire);
16321 				/* FALLTHRU */
16322 			case IPOPT_TS_TSANDADDR:
16323 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16324 				break;
16325 			default:
16326 				/*
16327 				 * ip_*put_options should have already
16328 				 * dropped this packet.
16329 				 */
16330 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16331 				    "unknown IT - bug in ip_rput_options?\n");
16332 				return (0);	/* Keep "lint" happy */
16333 			}
16334 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16335 				/* Increase overflow counter */
16336 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16337 				opt[IPOPT_POS_OV_FLG] =
16338 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16339 				    (off << 4));
16340 				break;
16341 			}
16342 			off = opt[IPOPT_OFFSET] - 1;
16343 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16344 			case IPOPT_TS_PRESPEC:
16345 			case IPOPT_TS_PRESPEC_RFC791:
16346 			case IPOPT_TS_TSANDADDR:
16347 				bcopy(&ire->ire_src_addr,
16348 				    (char *)opt + off, IP_ADDR_LEN);
16349 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16350 				/* FALLTHRU */
16351 			case IPOPT_TS_TSONLY:
16352 				off = opt[IPOPT_OFFSET] - 1;
16353 				/* Compute # of milliseconds since midnight */
16354 				gethrestime(&now);
16355 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16356 				    now.tv_nsec / (NANOSEC / MILLISEC);
16357 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16358 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16359 				break;
16360 			}
16361 			break;
16362 		}
16363 	}
16364 	return (0);
16365 }
16366 
16367 /*
16368  * This is called after processing at least one of AH/ESP headers.
16369  *
16370  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16371  * the actual, physical interface on which the packet was received,
16372  * but, when ip_strict_dst_multihoming is set to 1, could be the
16373  * interface which had the ipha_dst configured when the packet went
16374  * through ip_rput. The ill_index corresponding to the recv_ill
16375  * is saved in ipsec_in_rill_index
16376  */
16377 void
16378 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16379 {
16380 	mblk_t *mp;
16381 	ipaddr_t dst;
16382 	in6_addr_t *v6dstp;
16383 	ipha_t *ipha;
16384 	ip6_t *ip6h;
16385 	ipsec_in_t *ii;
16386 	boolean_t ill_need_rele = B_FALSE;
16387 	boolean_t rill_need_rele = B_FALSE;
16388 	boolean_t ire_need_rele = B_FALSE;
16389 
16390 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16391 	ASSERT(ii->ipsec_in_ill_index != 0);
16392 
16393 	mp = ipsec_mp->b_cont;
16394 	ASSERT(mp != NULL);
16395 
16396 
16397 	if (ill == NULL) {
16398 		ASSERT(recv_ill == NULL);
16399 		/*
16400 		 * We need to get the original queue on which ip_rput_local
16401 		 * or ip_rput_data_v6 was called.
16402 		 */
16403 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16404 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16405 		ill_need_rele = B_TRUE;
16406 
16407 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16408 			recv_ill = ill_lookup_on_ifindex(
16409 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16410 			    NULL, NULL, NULL, NULL);
16411 			rill_need_rele = B_TRUE;
16412 		} else {
16413 			recv_ill = ill;
16414 		}
16415 
16416 		if ((ill == NULL) || (recv_ill == NULL)) {
16417 			ip0dbg(("ip_fanout_proto_again: interface "
16418 			    "disappeared\n"));
16419 			if (ill != NULL)
16420 				ill_refrele(ill);
16421 			if (recv_ill != NULL)
16422 				ill_refrele(recv_ill);
16423 			freemsg(ipsec_mp);
16424 			return;
16425 		}
16426 	}
16427 
16428 	ASSERT(ill != NULL && recv_ill != NULL);
16429 
16430 	if (mp->b_datap->db_type == M_CTL) {
16431 		/*
16432 		 * AH/ESP is returning the ICMP message after
16433 		 * removing their headers. Fanout again till
16434 		 * it gets to the right protocol.
16435 		 */
16436 		if (ii->ipsec_in_v4) {
16437 			icmph_t *icmph;
16438 			int iph_hdr_length;
16439 			int hdr_length;
16440 
16441 			ipha = (ipha_t *)mp->b_rptr;
16442 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16443 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16444 			ipha = (ipha_t *)&icmph[1];
16445 			hdr_length = IPH_HDR_LENGTH(ipha);
16446 			/*
16447 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16448 			 * Reset the type to M_DATA.
16449 			 */
16450 			mp->b_datap->db_type = M_DATA;
16451 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16452 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16453 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16454 		} else {
16455 			icmp6_t *icmp6;
16456 			int hdr_length;
16457 
16458 			ip6h = (ip6_t *)mp->b_rptr;
16459 			/* Don't call hdr_length_v6() unless you have to. */
16460 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16461 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16462 			else
16463 				hdr_length = IPV6_HDR_LEN;
16464 
16465 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16466 			/*
16467 			 * icmp_inbound_error_fanout_v6 may need to do
16468 			 * pullupmsg.  Reset the type to M_DATA.
16469 			 */
16470 			mp->b_datap->db_type = M_DATA;
16471 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16472 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16473 		}
16474 		if (ill_need_rele)
16475 			ill_refrele(ill);
16476 		if (rill_need_rele)
16477 			ill_refrele(recv_ill);
16478 		return;
16479 	}
16480 
16481 	if (ii->ipsec_in_v4) {
16482 		ipha = (ipha_t *)mp->b_rptr;
16483 		dst = ipha->ipha_dst;
16484 		if (CLASSD(dst)) {
16485 			/*
16486 			 * Multicast has to be delivered to all streams.
16487 			 */
16488 			dst = INADDR_BROADCAST;
16489 		}
16490 
16491 		if (ire == NULL) {
16492 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16493 			    MBLK_GETLABEL(mp));
16494 			if (ire == NULL) {
16495 				if (ill_need_rele)
16496 					ill_refrele(ill);
16497 				if (rill_need_rele)
16498 					ill_refrele(recv_ill);
16499 				ip1dbg(("ip_fanout_proto_again: "
16500 				    "IRE not found"));
16501 				freemsg(ipsec_mp);
16502 				return;
16503 			}
16504 			ire_need_rele = B_TRUE;
16505 		}
16506 
16507 		switch (ipha->ipha_protocol) {
16508 			case IPPROTO_UDP:
16509 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16510 				    recv_ill);
16511 				if (ire_need_rele)
16512 					ire_refrele(ire);
16513 				break;
16514 			case IPPROTO_TCP:
16515 				if (!ire_need_rele)
16516 					IRE_REFHOLD(ire);
16517 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16518 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16519 				IRE_REFRELE(ire);
16520 				if (mp != NULL)
16521 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16522 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16523 				break;
16524 			case IPPROTO_SCTP:
16525 				if (!ire_need_rele)
16526 					IRE_REFHOLD(ire);
16527 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16528 				    ipsec_mp, 0, ill->ill_rq, dst);
16529 				break;
16530 			default:
16531 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16532 				    recv_ill);
16533 				if (ire_need_rele)
16534 					ire_refrele(ire);
16535 				break;
16536 		}
16537 	} else {
16538 		uint32_t rput_flags = 0;
16539 
16540 		ip6h = (ip6_t *)mp->b_rptr;
16541 		v6dstp = &ip6h->ip6_dst;
16542 		/*
16543 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16544 		 * address.
16545 		 *
16546 		 * Currently, we don't store that state in the IPSEC_IN
16547 		 * message, and we may need to.
16548 		 */
16549 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16550 		    IP6_IN_LLMCAST : 0);
16551 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16552 		    NULL, NULL);
16553 	}
16554 	if (ill_need_rele)
16555 		ill_refrele(ill);
16556 	if (rill_need_rele)
16557 		ill_refrele(recv_ill);
16558 }
16559 
16560 /*
16561  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16562  * returns 'true' if there are still fragments left on the queue, in
16563  * which case we restart the timer.
16564  */
16565 void
16566 ill_frag_timer(void *arg)
16567 {
16568 	ill_t	*ill = (ill_t *)arg;
16569 	boolean_t frag_pending;
16570 
16571 	mutex_enter(&ill->ill_lock);
16572 	ASSERT(!ill->ill_fragtimer_executing);
16573 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16574 		ill->ill_frag_timer_id = 0;
16575 		mutex_exit(&ill->ill_lock);
16576 		return;
16577 	}
16578 	ill->ill_fragtimer_executing = 1;
16579 	mutex_exit(&ill->ill_lock);
16580 
16581 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16582 
16583 	/*
16584 	 * Restart the timer, if we have fragments pending or if someone
16585 	 * wanted us to be scheduled again.
16586 	 */
16587 	mutex_enter(&ill->ill_lock);
16588 	ill->ill_fragtimer_executing = 0;
16589 	ill->ill_frag_timer_id = 0;
16590 	if (frag_pending || ill->ill_fragtimer_needrestart)
16591 		ill_frag_timer_start(ill);
16592 	mutex_exit(&ill->ill_lock);
16593 }
16594 
16595 void
16596 ill_frag_timer_start(ill_t *ill)
16597 {
16598 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16599 
16600 	/* If the ill is closing or opening don't proceed */
16601 	if (ill->ill_state_flags & ILL_CONDEMNED)
16602 		return;
16603 
16604 	if (ill->ill_fragtimer_executing) {
16605 		/*
16606 		 * ill_frag_timer is currently executing. Just record the
16607 		 * the fact that we want the timer to be restarted.
16608 		 * ill_frag_timer will post a timeout before it returns,
16609 		 * ensuring it will be called again.
16610 		 */
16611 		ill->ill_fragtimer_needrestart = 1;
16612 		return;
16613 	}
16614 
16615 	if (ill->ill_frag_timer_id == 0) {
16616 		/*
16617 		 * The timer is neither running nor is the timeout handler
16618 		 * executing. Post a timeout so that ill_frag_timer will be
16619 		 * called
16620 		 */
16621 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16622 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16623 		ill->ill_fragtimer_needrestart = 0;
16624 	}
16625 }
16626 
16627 /*
16628  * This routine is needed for loopback when forwarding multicasts.
16629  *
16630  * IPQoS Notes:
16631  * IPPF processing is done in fanout routines.
16632  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16633  * processing for IPSec packets is done when it comes back in clear.
16634  * NOTE : The callers of this function need to do the ire_refrele for the
16635  *	  ire that is being passed in.
16636  */
16637 void
16638 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16639     ill_t *recv_ill)
16640 {
16641 	ill_t	*ill = (ill_t *)q->q_ptr;
16642 	uint32_t	sum;
16643 	uint32_t	u1;
16644 	uint32_t	u2;
16645 	int		hdr_length;
16646 	boolean_t	mctl_present;
16647 	mblk_t		*first_mp = mp;
16648 	mblk_t		*hada_mp = NULL;
16649 	ipha_t		*inner_ipha;
16650 
16651 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16652 	    "ip_rput_locl_start: q %p", q);
16653 
16654 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16655 
16656 
16657 #define	rptr	((uchar_t *)ipha)
16658 #define	iphs	((uint16_t *)ipha)
16659 
16660 	/*
16661 	 * no UDP or TCP packet should come here anymore.
16662 	 */
16663 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16664 	    (ipha->ipha_protocol != IPPROTO_UDP));
16665 
16666 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16667 	if (mctl_present &&
16668 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16669 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16670 
16671 		/*
16672 		 * It's an IPsec accelerated packet.
16673 		 * Keep a pointer to the data attributes around until
16674 		 * we allocate the ipsec_info_t.
16675 		 */
16676 		IPSECHW_DEBUG(IPSECHW_PKT,
16677 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16678 		hada_mp = first_mp;
16679 		hada_mp->b_cont = NULL;
16680 		/*
16681 		 * Since it is accelerated, it comes directly from
16682 		 * the ill and the data attributes is followed by
16683 		 * the packet data.
16684 		 */
16685 		ASSERT(mp->b_datap->db_type != M_CTL);
16686 		first_mp = mp;
16687 		mctl_present = B_FALSE;
16688 	}
16689 
16690 	/*
16691 	 * IF M_CTL is not present, then ipsec_in_is_secure
16692 	 * should return B_TRUE. There is a case where loopback
16693 	 * packets has an M_CTL in the front with all the
16694 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16695 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16696 	 * packets never comes here, it is safe to ASSERT the
16697 	 * following.
16698 	 */
16699 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16700 
16701 
16702 	/* u1 is # words of IP options */
16703 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16704 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16705 
16706 	if (u1) {
16707 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16708 			if (hada_mp != NULL)
16709 				freemsg(hada_mp);
16710 			return;
16711 		}
16712 	} else {
16713 		/* Check the IP header checksum.  */
16714 #define	uph	((uint16_t *)ipha)
16715 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16716 		    uph[6] + uph[7] + uph[8] + uph[9];
16717 #undef  uph
16718 		/* finish doing IP checksum */
16719 		sum = (sum & 0xFFFF) + (sum >> 16);
16720 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16721 		/*
16722 		 * Don't verify header checksum if this packet is coming
16723 		 * back from AH/ESP as we already did it.
16724 		 */
16725 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16726 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16727 			goto drop_pkt;
16728 		}
16729 	}
16730 
16731 	/*
16732 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16733 	 * might be called more than once for secure packets, count only
16734 	 * the first time.
16735 	 */
16736 	if (!mctl_present) {
16737 		UPDATE_IB_PKT_COUNT(ire);
16738 		ire->ire_last_used_time = lbolt;
16739 	}
16740 
16741 	/* Check for fragmentation offset. */
16742 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16743 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16744 	if (u1) {
16745 		/*
16746 		 * We re-assemble fragments before we do the AH/ESP
16747 		 * processing. Thus, M_CTL should not be present
16748 		 * while we are re-assembling.
16749 		 */
16750 		ASSERT(!mctl_present);
16751 		ASSERT(first_mp == mp);
16752 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16753 			return;
16754 		}
16755 		/*
16756 		 * Make sure that first_mp points back to mp as
16757 		 * the mp we came in with could have changed in
16758 		 * ip_rput_fragment().
16759 		 */
16760 		ipha = (ipha_t *)mp->b_rptr;
16761 		first_mp = mp;
16762 	}
16763 
16764 	/*
16765 	 * Clear hardware checksumming flag as it is currently only
16766 	 * used by TCP and UDP.
16767 	 */
16768 	DB_CKSUMFLAGS(mp) = 0;
16769 
16770 	/* Now we have a complete datagram, destined for this machine. */
16771 	u1 = IPH_HDR_LENGTH(ipha);
16772 	switch (ipha->ipha_protocol) {
16773 	case IPPROTO_ICMP: {
16774 		ire_t		*ire_zone;
16775 		ilm_t		*ilm;
16776 		mblk_t		*mp1;
16777 		zoneid_t	last_zoneid;
16778 
16779 		if (CLASSD(ipha->ipha_dst) &&
16780 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
16781 			ASSERT(ire->ire_type == IRE_BROADCAST);
16782 			/*
16783 			 * In the multicast case, applications may have joined
16784 			 * the group from different zones, so we need to deliver
16785 			 * the packet to each of them. Loop through the
16786 			 * multicast memberships structures (ilm) on the receive
16787 			 * ill and send a copy of the packet up each matching
16788 			 * one. However, we don't do this for multicasts sent on
16789 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16790 			 * they must stay in the sender's zone.
16791 			 *
16792 			 * ilm_add_v6() ensures that ilms in the same zone are
16793 			 * contiguous in the ill_ilm list. We use this property
16794 			 * to avoid sending duplicates needed when two
16795 			 * applications in the same zone join the same group on
16796 			 * different logical interfaces: we ignore the ilm if
16797 			 * its zoneid is the same as the last matching one.
16798 			 * In addition, the sending of the packet for
16799 			 * ire_zoneid is delayed until all of the other ilms
16800 			 * have been exhausted.
16801 			 */
16802 			last_zoneid = -1;
16803 			ILM_WALKER_HOLD(recv_ill);
16804 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
16805 			    ilm = ilm->ilm_next) {
16806 				if ((ilm->ilm_flags & ILM_DELETED) ||
16807 				    ipha->ipha_dst != ilm->ilm_addr ||
16808 				    ilm->ilm_zoneid == last_zoneid ||
16809 				    ilm->ilm_zoneid == ire->ire_zoneid ||
16810 				    ilm->ilm_zoneid == ALL_ZONES ||
16811 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
16812 					continue;
16813 				mp1 = ip_copymsg(first_mp);
16814 				if (mp1 == NULL)
16815 					continue;
16816 				icmp_inbound(q, mp1, B_TRUE, ill,
16817 				    0, sum, mctl_present, B_TRUE,
16818 				    recv_ill, ilm->ilm_zoneid);
16819 				last_zoneid = ilm->ilm_zoneid;
16820 			}
16821 			ILM_WALKER_RELE(recv_ill);
16822 		} else if (ire->ire_type == IRE_BROADCAST) {
16823 			/*
16824 			 * In the broadcast case, there may be many zones
16825 			 * which need a copy of the packet delivered to them.
16826 			 * There is one IRE_BROADCAST per broadcast address
16827 			 * and per zone; we walk those using a helper function.
16828 			 * In addition, the sending of the packet for ire is
16829 			 * delayed until all of the other ires have been
16830 			 * processed.
16831 			 */
16832 			IRB_REFHOLD(ire->ire_bucket);
16833 			ire_zone = NULL;
16834 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
16835 			    ire)) != NULL) {
16836 				mp1 = ip_copymsg(first_mp);
16837 				if (mp1 == NULL)
16838 					continue;
16839 
16840 				UPDATE_IB_PKT_COUNT(ire_zone);
16841 				ire_zone->ire_last_used_time = lbolt;
16842 				icmp_inbound(q, mp1, B_TRUE, ill,
16843 				    0, sum, mctl_present, B_TRUE,
16844 				    recv_ill, ire_zone->ire_zoneid);
16845 			}
16846 			IRB_REFRELE(ire->ire_bucket);
16847 		}
16848 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
16849 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
16850 		    ire->ire_zoneid);
16851 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16852 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
16853 		return;
16854 	}
16855 	case IPPROTO_IGMP:
16856 		/*
16857 		 * If we are not willing to accept IGMP packets in clear,
16858 		 * then check with global policy.
16859 		 */
16860 		if (igmp_accept_clear_messages == 0) {
16861 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16862 			    ipha, NULL, mctl_present);
16863 			if (first_mp == NULL)
16864 				return;
16865 		}
16866 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16867 			freemsg(first_mp);
16868 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
16869 			BUMP_MIB(&ip_mib, ipInDiscards);
16870 			return;
16871 		}
16872 		if (igmp_input(q, mp, ill)) {
16873 			/* Bad packet - discarded by igmp_input */
16874 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16875 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
16876 			if (mctl_present)
16877 				freeb(first_mp);
16878 			return;
16879 		}
16880 		/*
16881 		 * igmp_input() may have pulled up the message so ipha needs to
16882 		 * be reinitialized.
16883 		 */
16884 		ipha = (ipha_t *)mp->b_rptr;
16885 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16886 			/* No user-level listener for IGMP packets */
16887 			goto drop_pkt;
16888 		}
16889 		/* deliver to local raw users */
16890 		break;
16891 	case IPPROTO_PIM:
16892 		/*
16893 		 * If we are not willing to accept PIM packets in clear,
16894 		 * then check with global policy.
16895 		 */
16896 		if (pim_accept_clear_messages == 0) {
16897 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16898 			    ipha, NULL, mctl_present);
16899 			if (first_mp == NULL)
16900 				return;
16901 		}
16902 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16903 			freemsg(first_mp);
16904 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
16905 			BUMP_MIB(&ip_mib, ipInDiscards);
16906 			return;
16907 		}
16908 		if (pim_input(q, mp) != 0) {
16909 			/* Bad packet - discarded by pim_input */
16910 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16911 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
16912 			if (mctl_present)
16913 				freeb(first_mp);
16914 			return;
16915 		}
16916 
16917 		/*
16918 		 * pim_input() may have pulled up the message so ipha needs to
16919 		 * be reinitialized.
16920 		 */
16921 		ipha = (ipha_t *)mp->b_rptr;
16922 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16923 			/* No user-level listener for PIM packets */
16924 			goto drop_pkt;
16925 		}
16926 		/* deliver to local raw users */
16927 		break;
16928 	case IPPROTO_ENCAP:
16929 		/*
16930 		 * Handle self-encapsulated packets (IP-in-IP where
16931 		 * the inner addresses == the outer addresses).
16932 		 */
16933 		hdr_length = IPH_HDR_LENGTH(ipha);
16934 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
16935 		    mp->b_wptr) {
16936 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
16937 			    sizeof (ipha_t) - mp->b_rptr)) {
16938 				BUMP_MIB(&ip_mib, ipInDiscards);
16939 				freemsg(first_mp);
16940 				return;
16941 			}
16942 			ipha = (ipha_t *)mp->b_rptr;
16943 		}
16944 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
16945 		/*
16946 		 * Check the sanity of the inner IP header.
16947 		 */
16948 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
16949 			BUMP_MIB(&ip_mib, ipInDiscards);
16950 			freemsg(first_mp);
16951 			return;
16952 		}
16953 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
16954 			BUMP_MIB(&ip_mib, ipInDiscards);
16955 			freemsg(first_mp);
16956 			return;
16957 		}
16958 		if (inner_ipha->ipha_src == ipha->ipha_src &&
16959 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
16960 			ipsec_in_t *ii;
16961 
16962 			/*
16963 			 * Self-encapsulated tunnel packet. Remove
16964 			 * the outer IP header and fanout again.
16965 			 * We also need to make sure that the inner
16966 			 * header is pulled up until options.
16967 			 */
16968 			mp->b_rptr = (uchar_t *)inner_ipha;
16969 			ipha = inner_ipha;
16970 			hdr_length = IPH_HDR_LENGTH(ipha);
16971 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
16972 				if (!pullupmsg(mp, (uchar_t *)ipha +
16973 				    + hdr_length - mp->b_rptr)) {
16974 					freemsg(first_mp);
16975 					return;
16976 				}
16977 				ipha = (ipha_t *)mp->b_rptr;
16978 			}
16979 			if (!mctl_present) {
16980 				ASSERT(first_mp == mp);
16981 				/*
16982 				 * This means that somebody is sending
16983 				 * Self-encapsualted packets without AH/ESP.
16984 				 * If AH/ESP was present, we would have already
16985 				 * allocated the first_mp.
16986 				 */
16987 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
16988 				    NULL) {
16989 					ip1dbg(("ip_proto_input: IPSEC_IN "
16990 					    "allocation failure.\n"));
16991 					BUMP_MIB(&ip_mib, ipInDiscards);
16992 					freemsg(mp);
16993 					return;
16994 				}
16995 				first_mp->b_cont = mp;
16996 			}
16997 			/*
16998 			 * We generally store the ill_index if we need to
16999 			 * do IPSEC processing as we lose the ill queue when
17000 			 * we come back. But in this case, we never should
17001 			 * have to store the ill_index here as it should have
17002 			 * been stored previously when we processed the
17003 			 * AH/ESP header in this routine or for non-ipsec
17004 			 * cases, we still have the queue. But for some bad
17005 			 * packets from the wire, we can get to IPSEC after
17006 			 * this and we better store the index for that case.
17007 			 */
17008 			ill = (ill_t *)q->q_ptr;
17009 			ii = (ipsec_in_t *)first_mp->b_rptr;
17010 			ii->ipsec_in_ill_index =
17011 			    ill->ill_phyint->phyint_ifindex;
17012 			ii->ipsec_in_rill_index =
17013 			    recv_ill->ill_phyint->phyint_ifindex;
17014 			if (ii->ipsec_in_decaps) {
17015 				/*
17016 				 * This packet is self-encapsulated multiple
17017 				 * times. We don't want to recurse infinitely.
17018 				 * To keep it simple, drop the packet.
17019 				 */
17020 				BUMP_MIB(&ip_mib, ipInDiscards);
17021 				freemsg(first_mp);
17022 				return;
17023 			}
17024 			ii->ipsec_in_decaps = B_TRUE;
17025 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
17026 			return;
17027 		}
17028 		break;
17029 	case IPPROTO_AH:
17030 	case IPPROTO_ESP: {
17031 		/*
17032 		 * Fast path for AH/ESP. If this is the first time
17033 		 * we are sending a datagram to AH/ESP, allocate
17034 		 * a IPSEC_IN message and prepend it. Otherwise,
17035 		 * just fanout.
17036 		 */
17037 
17038 		int ipsec_rc;
17039 		ipsec_in_t *ii;
17040 
17041 		IP_STAT(ipsec_proto_ahesp);
17042 		if (!mctl_present) {
17043 			ASSERT(first_mp == mp);
17044 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
17045 				ip1dbg(("ip_proto_input: IPSEC_IN "
17046 				    "allocation failure.\n"));
17047 				freemsg(hada_mp); /* okay ifnull */
17048 				BUMP_MIB(&ip_mib, ipInDiscards);
17049 				freemsg(mp);
17050 				return;
17051 			}
17052 			/*
17053 			 * Store the ill_index so that when we come back
17054 			 * from IPSEC we ride on the same queue.
17055 			 */
17056 			ill = (ill_t *)q->q_ptr;
17057 			ii = (ipsec_in_t *)first_mp->b_rptr;
17058 			ii->ipsec_in_ill_index =
17059 			    ill->ill_phyint->phyint_ifindex;
17060 			ii->ipsec_in_rill_index =
17061 			    recv_ill->ill_phyint->phyint_ifindex;
17062 			first_mp->b_cont = mp;
17063 			/*
17064 			 * Cache hardware acceleration info.
17065 			 */
17066 			if (hada_mp != NULL) {
17067 				IPSECHW_DEBUG(IPSECHW_PKT,
17068 				    ("ip_rput_local: caching data attr.\n"));
17069 				ii->ipsec_in_accelerated = B_TRUE;
17070 				ii->ipsec_in_da = hada_mp;
17071 				hada_mp = NULL;
17072 			}
17073 		} else {
17074 			ii = (ipsec_in_t *)first_mp->b_rptr;
17075 		}
17076 
17077 		if (!ipsec_loaded()) {
17078 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17079 			    ire->ire_zoneid);
17080 			return;
17081 		}
17082 
17083 		/* select inbound SA and have IPsec process the pkt */
17084 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17085 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17086 			if (esph == NULL)
17087 				return;
17088 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17089 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17090 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17091 			    first_mp, esph);
17092 		} else {
17093 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17094 			if (ah == NULL)
17095 				return;
17096 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17097 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17098 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17099 			    first_mp, ah);
17100 		}
17101 
17102 		switch (ipsec_rc) {
17103 		case IPSEC_STATUS_SUCCESS:
17104 			break;
17105 		case IPSEC_STATUS_FAILED:
17106 			BUMP_MIB(&ip_mib, ipInDiscards);
17107 			/* FALLTHRU */
17108 		case IPSEC_STATUS_PENDING:
17109 			return;
17110 		}
17111 		/* we're done with IPsec processing, send it up */
17112 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17113 		return;
17114 	}
17115 	default:
17116 		break;
17117 	}
17118 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17119 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17120 		    ire->ire_zoneid));
17121 		goto drop_pkt;
17122 	}
17123 	/*
17124 	 * Handle protocols with which IP is less intimate.  There
17125 	 * can be more than one stream bound to a particular
17126 	 * protocol.  When this is the case, each one gets a copy
17127 	 * of any incoming packets.
17128 	 */
17129 	ip_fanout_proto(q, first_mp, ill, ipha,
17130 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17131 	    B_TRUE, recv_ill, ire->ire_zoneid);
17132 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17133 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17134 	return;
17135 
17136 drop_pkt:
17137 	freemsg(first_mp);
17138 	if (hada_mp != NULL)
17139 		freeb(hada_mp);
17140 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17141 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17142 #undef	rptr
17143 #undef  iphs
17144 
17145 }
17146 
17147 /*
17148  * Update any source route, record route or timestamp options.
17149  * Check that we are at end of strict source route.
17150  * The options have already been checked for sanity in ip_rput_options().
17151  */
17152 static boolean_t
17153 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17154 {
17155 	ipoptp_t	opts;
17156 	uchar_t		*opt;
17157 	uint8_t		optval;
17158 	uint8_t		optlen;
17159 	ipaddr_t	dst;
17160 	uint32_t	ts;
17161 	ire_t		*dst_ire;
17162 	timestruc_t	now;
17163 	zoneid_t	zoneid;
17164 	ill_t		*ill;
17165 
17166 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17167 
17168 	ip2dbg(("ip_rput_local_options\n"));
17169 
17170 	for (optval = ipoptp_first(&opts, ipha);
17171 	    optval != IPOPT_EOL;
17172 	    optval = ipoptp_next(&opts)) {
17173 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17174 		opt = opts.ipoptp_cur;
17175 		optlen = opts.ipoptp_len;
17176 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17177 		    optval, optlen));
17178 		switch (optval) {
17179 			uint32_t off;
17180 		case IPOPT_SSRR:
17181 		case IPOPT_LSRR:
17182 			off = opt[IPOPT_OFFSET];
17183 			off--;
17184 			if (optlen < IP_ADDR_LEN ||
17185 			    off > optlen - IP_ADDR_LEN) {
17186 				/* End of source route */
17187 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17188 				break;
17189 			}
17190 			/*
17191 			 * This will only happen if two consecutive entries
17192 			 * in the source route contains our address or if
17193 			 * it is a packet with a loose source route which
17194 			 * reaches us before consuming the whole source route
17195 			 */
17196 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17197 			if (optval == IPOPT_SSRR) {
17198 				goto bad_src_route;
17199 			}
17200 			/*
17201 			 * Hack: instead of dropping the packet truncate the
17202 			 * source route to what has been used by filling the
17203 			 * rest with IPOPT_NOP.
17204 			 */
17205 			opt[IPOPT_OLEN] = (uint8_t)off;
17206 			while (off < optlen) {
17207 				opt[off++] = IPOPT_NOP;
17208 			}
17209 			break;
17210 		case IPOPT_RR:
17211 			off = opt[IPOPT_OFFSET];
17212 			off--;
17213 			if (optlen < IP_ADDR_LEN ||
17214 			    off > optlen - IP_ADDR_LEN) {
17215 				/* No more room - ignore */
17216 				ip1dbg((
17217 				    "ip_rput_local_options: end of RR\n"));
17218 				break;
17219 			}
17220 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17221 			    IP_ADDR_LEN);
17222 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17223 			break;
17224 		case IPOPT_TS:
17225 			/* Insert timestamp if there is romm */
17226 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17227 			case IPOPT_TS_TSONLY:
17228 				off = IPOPT_TS_TIMELEN;
17229 				break;
17230 			case IPOPT_TS_PRESPEC:
17231 			case IPOPT_TS_PRESPEC_RFC791:
17232 				/* Verify that the address matched */
17233 				off = opt[IPOPT_OFFSET] - 1;
17234 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17235 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17236 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17237 				if (dst_ire == NULL) {
17238 					/* Not for us */
17239 					break;
17240 				}
17241 				ire_refrele(dst_ire);
17242 				/* FALLTHRU */
17243 			case IPOPT_TS_TSANDADDR:
17244 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17245 				break;
17246 			default:
17247 				/*
17248 				 * ip_*put_options should have already
17249 				 * dropped this packet.
17250 				 */
17251 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17252 				    "unknown IT - bug in ip_rput_options?\n");
17253 				return (B_TRUE);	/* Keep "lint" happy */
17254 			}
17255 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17256 				/* Increase overflow counter */
17257 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17258 				opt[IPOPT_POS_OV_FLG] =
17259 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17260 				    (off << 4));
17261 				break;
17262 			}
17263 			off = opt[IPOPT_OFFSET] - 1;
17264 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17265 			case IPOPT_TS_PRESPEC:
17266 			case IPOPT_TS_PRESPEC_RFC791:
17267 			case IPOPT_TS_TSANDADDR:
17268 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17269 				    IP_ADDR_LEN);
17270 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17271 				/* FALLTHRU */
17272 			case IPOPT_TS_TSONLY:
17273 				off = opt[IPOPT_OFFSET] - 1;
17274 				/* Compute # of milliseconds since midnight */
17275 				gethrestime(&now);
17276 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17277 				    now.tv_nsec / (NANOSEC / MILLISEC);
17278 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17279 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17280 				break;
17281 			}
17282 			break;
17283 		}
17284 	}
17285 	return (B_TRUE);
17286 
17287 bad_src_route:
17288 	q = WR(q);
17289 	if (q->q_next != NULL)
17290 		ill = q->q_ptr;
17291 	else
17292 		ill = NULL;
17293 
17294 	/* make sure we clear any indication of a hardware checksum */
17295 	DB_CKSUMFLAGS(mp) = 0;
17296 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill);
17297 	if (zoneid == ALL_ZONES)
17298 		freemsg(mp);
17299 	else
17300 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17301 	return (B_FALSE);
17302 
17303 }
17304 
17305 /*
17306  * Process IP options in an inbound packet.  If an option affects the
17307  * effective destination address, return the next hop address via dstp.
17308  * Returns -1 if something fails in which case an ICMP error has been sent
17309  * and mp freed.
17310  */
17311 static int
17312 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17313 {
17314 	ipoptp_t	opts;
17315 	uchar_t		*opt;
17316 	uint8_t		optval;
17317 	uint8_t		optlen;
17318 	ipaddr_t	dst;
17319 	intptr_t	code = 0;
17320 	ire_t		*ire = NULL;
17321 	zoneid_t	zoneid;
17322 	ill_t		*ill;
17323 
17324 	ip2dbg(("ip_rput_options\n"));
17325 	dst = ipha->ipha_dst;
17326 	for (optval = ipoptp_first(&opts, ipha);
17327 	    optval != IPOPT_EOL;
17328 	    optval = ipoptp_next(&opts)) {
17329 		opt = opts.ipoptp_cur;
17330 		optlen = opts.ipoptp_len;
17331 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17332 		    optval, optlen));
17333 		/*
17334 		 * Note: we need to verify the checksum before we
17335 		 * modify anything thus this routine only extracts the next
17336 		 * hop dst from any source route.
17337 		 */
17338 		switch (optval) {
17339 			uint32_t off;
17340 		case IPOPT_SSRR:
17341 		case IPOPT_LSRR:
17342 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17343 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17344 			if (ire == NULL) {
17345 				if (optval == IPOPT_SSRR) {
17346 					ip1dbg(("ip_rput_options: not next"
17347 					    " strict source route 0x%x\n",
17348 					    ntohl(dst)));
17349 					code = (char *)&ipha->ipha_dst -
17350 					    (char *)ipha;
17351 					goto param_prob; /* RouterReq's */
17352 				}
17353 				ip2dbg(("ip_rput_options: "
17354 				    "not next source route 0x%x\n",
17355 				    ntohl(dst)));
17356 				break;
17357 			}
17358 			ire_refrele(ire);
17359 
17360 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17361 				ip1dbg((
17362 				    "ip_rput_options: bad option offset\n"));
17363 				code = (char *)&opt[IPOPT_OLEN] -
17364 				    (char *)ipha;
17365 				goto param_prob;
17366 			}
17367 			off = opt[IPOPT_OFFSET];
17368 			off--;
17369 		redo_srr:
17370 			if (optlen < IP_ADDR_LEN ||
17371 			    off > optlen - IP_ADDR_LEN) {
17372 				/* End of source route */
17373 				ip1dbg(("ip_rput_options: end of SR\n"));
17374 				break;
17375 			}
17376 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17377 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17378 			    ntohl(dst)));
17379 
17380 			/*
17381 			 * Check if our address is present more than
17382 			 * once as consecutive hops in source route.
17383 			 * XXX verify per-interface ip_forwarding
17384 			 * for source route?
17385 			 */
17386 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17387 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17388 
17389 			if (ire != NULL) {
17390 				ire_refrele(ire);
17391 				off += IP_ADDR_LEN;
17392 				goto redo_srr;
17393 			}
17394 
17395 			if (dst == htonl(INADDR_LOOPBACK)) {
17396 				ip1dbg(("ip_rput_options: loopback addr in "
17397 				    "source route!\n"));
17398 				goto bad_src_route;
17399 			}
17400 			/*
17401 			 * For strict: verify that dst is directly
17402 			 * reachable.
17403 			 */
17404 			if (optval == IPOPT_SSRR) {
17405 				ire = ire_ftable_lookup(dst, 0, 0,
17406 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17407 				    MBLK_GETLABEL(mp),
17408 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17409 				if (ire == NULL) {
17410 					ip1dbg(("ip_rput_options: SSRR not "
17411 					    "directly reachable: 0x%x\n",
17412 					    ntohl(dst)));
17413 					goto bad_src_route;
17414 				}
17415 				ire_refrele(ire);
17416 			}
17417 			/*
17418 			 * Defer update of the offset and the record route
17419 			 * until the packet is forwarded.
17420 			 */
17421 			break;
17422 		case IPOPT_RR:
17423 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17424 				ip1dbg((
17425 				    "ip_rput_options: bad option offset\n"));
17426 				code = (char *)&opt[IPOPT_OLEN] -
17427 				    (char *)ipha;
17428 				goto param_prob;
17429 			}
17430 			break;
17431 		case IPOPT_TS:
17432 			/*
17433 			 * Verify that length >= 5 and that there is either
17434 			 * room for another timestamp or that the overflow
17435 			 * counter is not maxed out.
17436 			 */
17437 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17438 			if (optlen < IPOPT_MINLEN_IT) {
17439 				goto param_prob;
17440 			}
17441 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17442 				ip1dbg((
17443 				    "ip_rput_options: bad option offset\n"));
17444 				code = (char *)&opt[IPOPT_OFFSET] -
17445 				    (char *)ipha;
17446 				goto param_prob;
17447 			}
17448 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17449 			case IPOPT_TS_TSONLY:
17450 				off = IPOPT_TS_TIMELEN;
17451 				break;
17452 			case IPOPT_TS_TSANDADDR:
17453 			case IPOPT_TS_PRESPEC:
17454 			case IPOPT_TS_PRESPEC_RFC791:
17455 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17456 				break;
17457 			default:
17458 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17459 				    (char *)ipha;
17460 				goto param_prob;
17461 			}
17462 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17463 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17464 				/*
17465 				 * No room and the overflow counter is 15
17466 				 * already.
17467 				 */
17468 				goto param_prob;
17469 			}
17470 			break;
17471 		}
17472 	}
17473 
17474 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17475 		*dstp = dst;
17476 		return (0);
17477 	}
17478 
17479 	ip1dbg(("ip_rput_options: error processing IP options."));
17480 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17481 
17482 param_prob:
17483 	q = WR(q);
17484 	if (q->q_next != NULL)
17485 		ill = q->q_ptr;
17486 	else
17487 		ill = NULL;
17488 
17489 	/* make sure we clear any indication of a hardware checksum */
17490 	DB_CKSUMFLAGS(mp) = 0;
17491 	/* Don't know whether this is for non-global or global/forwarding */
17492 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17493 	if (zoneid == ALL_ZONES)
17494 		freemsg(mp);
17495 	else
17496 		icmp_param_problem(q, mp, (uint8_t)code, zoneid);
17497 	return (-1);
17498 
17499 bad_src_route:
17500 	q = WR(q);
17501 	if (q->q_next != NULL)
17502 		ill = q->q_ptr;
17503 	else
17504 		ill = NULL;
17505 
17506 	/* make sure we clear any indication of a hardware checksum */
17507 	DB_CKSUMFLAGS(mp) = 0;
17508 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17509 	if (zoneid == ALL_ZONES)
17510 		freemsg(mp);
17511 	else
17512 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17513 	return (-1);
17514 }
17515 
17516 /*
17517  * IP & ICMP info in >=14 msg's ...
17518  *  - ip fixed part (mib2_ip_t)
17519  *  - icmp fixed part (mib2_icmp_t)
17520  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17521  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17522  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
17523  *  - ipRouteAttributeTable (ip 102)	labeled routes
17524  *  - ip multicast membership (ip_member_t)
17525  *  - ip multicast source filtering (ip_grpsrc_t)
17526  *  - igmp fixed part (struct igmpstat)
17527  *  - multicast routing stats (struct mrtstat)
17528  *  - multicast routing vifs (array of struct vifctl)
17529  *  - multicast routing routes (array of struct mfcctl)
17530  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17531  *					One per ill plus one generic
17532  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17533  *					One per ill plus one generic
17534  *  - ipv6RouteEntry			all IPv6 IREs
17535  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17536  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17537  *  - ipv6AddrEntry			all IPv6 ipifs
17538  *  - ipv6 multicast membership (ipv6_member_t)
17539  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17540  *
17541  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
17542  * already present.
17543  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17544  * already filled in by the caller.
17545  * Return value of 0 indicates that no messages were sent and caller
17546  * should free mpctl.
17547  */
17548 int
17549 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17550 {
17551 
17552 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17553 		return (0);
17554 	}
17555 
17556 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
17557 		return (1);
17558 	}
17559 
17560 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17561 		return (1);
17562 	}
17563 
17564 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17565 		return (1);
17566 	}
17567 
17568 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17569 		return (1);
17570 	}
17571 
17572 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17573 		return (1);
17574 	}
17575 
17576 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17577 		return (1);
17578 	}
17579 
17580 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17581 		return (1);
17582 	}
17583 
17584 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17585 		return (1);
17586 	}
17587 
17588 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17589 		return (1);
17590 	}
17591 
17592 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17593 		return (1);
17594 	}
17595 
17596 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17597 		return (1);
17598 	}
17599 
17600 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17601 		return (1);
17602 	}
17603 
17604 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17605 		return (1);
17606 	}
17607 
17608 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17609 		return (1);
17610 	}
17611 
17612 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17613 		return (1);
17614 	}
17615 
17616 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17617 		return (1);
17618 	}
17619 
17620 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17621 		return (1);
17622 	}
17623 	freemsg(mpctl);
17624 	return (1);
17625 }
17626 
17627 
17628 /* Get global IPv4 statistics */
17629 static mblk_t *
17630 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
17631 {
17632 	struct opthdr		*optp;
17633 	mblk_t			*mp2ctl;
17634 
17635 	/*
17636 	 * make a copy of the original message
17637 	 */
17638 	mp2ctl = copymsg(mpctl);
17639 
17640 	/* fixed length IP structure... */
17641 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17642 	optp->level = MIB2_IP;
17643 	optp->name = 0;
17644 	SET_MIB(ip_mib.ipForwarding,
17645 	    (WE_ARE_FORWARDING ? 1 : 2));
17646 	SET_MIB(ip_mib.ipDefaultTTL,
17647 	    (uint32_t)ip_def_ttl);
17648 	SET_MIB(ip_mib.ipReasmTimeout,
17649 	    ip_g_frag_timeout);
17650 	SET_MIB(ip_mib.ipAddrEntrySize,
17651 	    sizeof (mib2_ipAddrEntry_t));
17652 	SET_MIB(ip_mib.ipRouteEntrySize,
17653 	    sizeof (mib2_ipRouteEntry_t));
17654 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
17655 	    sizeof (mib2_ipNetToMediaEntry_t));
17656 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17657 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17658 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
17659 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17660 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
17661 	    (int)sizeof (ip_mib))) {
17662 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17663 		    (uint_t)sizeof (ip_mib)));
17664 	}
17665 
17666 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17667 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17668 	    (int)optp->level, (int)optp->name, (int)optp->len));
17669 	qreply(q, mpctl);
17670 	return (mp2ctl);
17671 }
17672 
17673 /* Global IPv4 ICMP statistics */
17674 static mblk_t *
17675 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
17676 {
17677 	struct opthdr		*optp;
17678 	mblk_t			*mp2ctl;
17679 
17680 	/*
17681 	 * Make a copy of the original message
17682 	 */
17683 	mp2ctl = copymsg(mpctl);
17684 
17685 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17686 	optp->level = MIB2_ICMP;
17687 	optp->name = 0;
17688 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17689 	    (int)sizeof (icmp_mib))) {
17690 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17691 		    (uint_t)sizeof (icmp_mib)));
17692 	}
17693 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17694 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17695 	    (int)optp->level, (int)optp->name, (int)optp->len));
17696 	qreply(q, mpctl);
17697 	return (mp2ctl);
17698 }
17699 
17700 /* Global IPv4 IGMP statistics */
17701 static mblk_t *
17702 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17703 {
17704 	struct opthdr		*optp;
17705 	mblk_t			*mp2ctl;
17706 
17707 	/*
17708 	 * make a copy of the original message
17709 	 */
17710 	mp2ctl = copymsg(mpctl);
17711 
17712 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17713 	optp->level = EXPER_IGMP;
17714 	optp->name = 0;
17715 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17716 	    (int)sizeof (igmpstat))) {
17717 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17718 		    (uint_t)sizeof (igmpstat)));
17719 	}
17720 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17721 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17722 	    (int)optp->level, (int)optp->name, (int)optp->len));
17723 	qreply(q, mpctl);
17724 	return (mp2ctl);
17725 }
17726 
17727 /* Global IPv4 Multicast Routing statistics */
17728 static mblk_t *
17729 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17730 {
17731 	struct opthdr		*optp;
17732 	mblk_t			*mp2ctl;
17733 
17734 	/*
17735 	 * make a copy of the original message
17736 	 */
17737 	mp2ctl = copymsg(mpctl);
17738 
17739 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17740 	optp->level = EXPER_DVMRP;
17741 	optp->name = 0;
17742 	if (!ip_mroute_stats(mpctl->b_cont)) {
17743 		ip0dbg(("ip_mroute_stats: failed\n"));
17744 	}
17745 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17746 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17747 	    (int)optp->level, (int)optp->name, (int)optp->len));
17748 	qreply(q, mpctl);
17749 	return (mp2ctl);
17750 }
17751 
17752 /* IPv4 address information */
17753 static mblk_t *
17754 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17755 {
17756 	struct opthdr		*optp;
17757 	mblk_t			*mp2ctl;
17758 	mblk_t			*mp_tail = NULL;
17759 	ill_t			*ill;
17760 	ipif_t			*ipif;
17761 	uint_t			bitval;
17762 	mib2_ipAddrEntry_t	mae;
17763 	zoneid_t		zoneid;
17764 	ill_walk_context_t ctx;
17765 
17766 	/*
17767 	 * make a copy of the original message
17768 	 */
17769 	mp2ctl = copymsg(mpctl);
17770 
17771 	/* ipAddrEntryTable */
17772 
17773 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17774 	optp->level = MIB2_IP;
17775 	optp->name = MIB2_IP_ADDR;
17776 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17777 
17778 	rw_enter(&ill_g_lock, RW_READER);
17779 	ill = ILL_START_WALK_V4(&ctx);
17780 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17781 		for (ipif = ill->ill_ipif; ipif != NULL;
17782 		    ipif = ipif->ipif_next) {
17783 			if (ipif->ipif_zoneid != zoneid &&
17784 			    ipif->ipif_zoneid != ALL_ZONES)
17785 				continue;
17786 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17787 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17788 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17789 
17790 			(void) ipif_get_name(ipif,
17791 			    mae.ipAdEntIfIndex.o_bytes,
17792 			    OCTET_LENGTH);
17793 			mae.ipAdEntIfIndex.o_length =
17794 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
17795 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
17796 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
17797 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
17798 			mae.ipAdEntInfo.ae_subnet_len =
17799 			    ip_mask_to_plen(ipif->ipif_net_mask);
17800 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
17801 			for (bitval = 1;
17802 			    bitval &&
17803 			    !(bitval & ipif->ipif_brd_addr);
17804 			    bitval <<= 1)
17805 				noop;
17806 			mae.ipAdEntBcastAddr = bitval;
17807 			mae.ipAdEntReasmMaxSize = 65535;
17808 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
17809 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
17810 			mae.ipAdEntInfo.ae_broadcast_addr =
17811 			    ipif->ipif_brd_addr;
17812 			mae.ipAdEntInfo.ae_pp_dst_addr =
17813 			    ipif->ipif_pp_dst_addr;
17814 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
17815 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17816 
17817 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17818 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
17819 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
17820 				    "allocate %u bytes\n",
17821 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
17822 			}
17823 		}
17824 	}
17825 	rw_exit(&ill_g_lock);
17826 
17827 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17828 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
17829 	    (int)optp->level, (int)optp->name, (int)optp->len));
17830 	qreply(q, mpctl);
17831 	return (mp2ctl);
17832 }
17833 
17834 /* IPv6 address information */
17835 static mblk_t *
17836 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
17837 {
17838 	struct opthdr		*optp;
17839 	mblk_t			*mp2ctl;
17840 	mblk_t			*mp_tail = NULL;
17841 	ill_t			*ill;
17842 	ipif_t			*ipif;
17843 	mib2_ipv6AddrEntry_t	mae6;
17844 	zoneid_t		zoneid;
17845 	ill_walk_context_t	ctx;
17846 
17847 	/*
17848 	 * make a copy of the original message
17849 	 */
17850 	mp2ctl = copymsg(mpctl);
17851 
17852 	/* ipv6AddrEntryTable */
17853 
17854 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17855 	optp->level = MIB2_IP6;
17856 	optp->name = MIB2_IP6_ADDR;
17857 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17858 
17859 	rw_enter(&ill_g_lock, RW_READER);
17860 	ill = ILL_START_WALK_V6(&ctx);
17861 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17862 		for (ipif = ill->ill_ipif; ipif != NULL;
17863 		    ipif = ipif->ipif_next) {
17864 			if (ipif->ipif_zoneid != zoneid &&
17865 			    ipif->ipif_zoneid != ALL_ZONES)
17866 				continue;
17867 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17868 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17869 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17870 
17871 			(void) ipif_get_name(ipif,
17872 			    mae6.ipv6AddrIfIndex.o_bytes,
17873 			    OCTET_LENGTH);
17874 			mae6.ipv6AddrIfIndex.o_length =
17875 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
17876 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
17877 			mae6.ipv6AddrPfxLength =
17878 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
17879 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
17880 			mae6.ipv6AddrInfo.ae_subnet_len =
17881 			    mae6.ipv6AddrPfxLength;
17882 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
17883 
17884 			/* Type: stateless(1), stateful(2), unknown(3) */
17885 			if (ipif->ipif_flags & IPIF_ADDRCONF)
17886 				mae6.ipv6AddrType = 1;
17887 			else
17888 				mae6.ipv6AddrType = 2;
17889 			/* Anycast: true(1), false(2) */
17890 			if (ipif->ipif_flags & IPIF_ANYCAST)
17891 				mae6.ipv6AddrAnycastFlag = 1;
17892 			else
17893 				mae6.ipv6AddrAnycastFlag = 2;
17894 
17895 			/*
17896 			 * Address status: preferred(1), deprecated(2),
17897 			 * invalid(3), inaccessible(4), unknown(5)
17898 			 */
17899 			if (ipif->ipif_flags & IPIF_NOLOCAL)
17900 				mae6.ipv6AddrStatus = 3;
17901 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
17902 				mae6.ipv6AddrStatus = 2;
17903 			else
17904 				mae6.ipv6AddrStatus = 1;
17905 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
17906 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
17907 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
17908 						ipif->ipif_v6pp_dst_addr;
17909 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
17910 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17911 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17912 				(char *)&mae6,
17913 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
17914 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
17915 				    "allocate %u bytes\n",
17916 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
17917 			}
17918 		}
17919 	}
17920 	rw_exit(&ill_g_lock);
17921 
17922 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17923 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
17924 	    (int)optp->level, (int)optp->name, (int)optp->len));
17925 	qreply(q, mpctl);
17926 	return (mp2ctl);
17927 }
17928 
17929 /* IPv4 multicast group membership. */
17930 static mblk_t *
17931 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
17932 {
17933 	struct opthdr		*optp;
17934 	mblk_t			*mp2ctl;
17935 	ill_t			*ill;
17936 	ipif_t			*ipif;
17937 	ilm_t			*ilm;
17938 	ip_member_t		ipm;
17939 	mblk_t			*mp_tail = NULL;
17940 	ill_walk_context_t	ctx;
17941 	zoneid_t		zoneid;
17942 
17943 	/*
17944 	 * make a copy of the original message
17945 	 */
17946 	mp2ctl = copymsg(mpctl);
17947 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17948 
17949 	/* ipGroupMember table */
17950 	optp = (struct opthdr *)&mpctl->b_rptr[
17951 	    sizeof (struct T_optmgmt_ack)];
17952 	optp->level = MIB2_IP;
17953 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
17954 
17955 	rw_enter(&ill_g_lock, RW_READER);
17956 	ill = ILL_START_WALK_V4(&ctx);
17957 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17958 		ILM_WALKER_HOLD(ill);
17959 		for (ipif = ill->ill_ipif; ipif != NULL;
17960 		    ipif = ipif->ipif_next) {
17961 			if (ipif->ipif_zoneid != zoneid &&
17962 			    ipif->ipif_zoneid != ALL_ZONES)
17963 				continue;	/* not this zone */
17964 			(void) ipif_get_name(ipif,
17965 			    ipm.ipGroupMemberIfIndex.o_bytes,
17966 			    OCTET_LENGTH);
17967 			ipm.ipGroupMemberIfIndex.o_length =
17968 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
17969 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17970 				ASSERT(ilm->ilm_ipif != NULL);
17971 				ASSERT(ilm->ilm_ill == NULL);
17972 				if (ilm->ilm_ipif != ipif)
17973 					continue;
17974 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
17975 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
17976 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
17977 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17978 				    (char *)&ipm, (int)sizeof (ipm))) {
17979 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
17980 					    "failed to allocate %u bytes\n",
17981 						(uint_t)sizeof (ipm)));
17982 				}
17983 			}
17984 		}
17985 		ILM_WALKER_RELE(ill);
17986 	}
17987 	rw_exit(&ill_g_lock);
17988 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17989 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17990 	    (int)optp->level, (int)optp->name, (int)optp->len));
17991 	qreply(q, mpctl);
17992 	return (mp2ctl);
17993 }
17994 
17995 /* IPv6 multicast group membership. */
17996 static mblk_t *
17997 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
17998 {
17999 	struct opthdr		*optp;
18000 	mblk_t			*mp2ctl;
18001 	ill_t			*ill;
18002 	ilm_t			*ilm;
18003 	ipv6_member_t		ipm6;
18004 	mblk_t			*mp_tail = NULL;
18005 	ill_walk_context_t	ctx;
18006 	zoneid_t		zoneid;
18007 
18008 	/*
18009 	 * make a copy of the original message
18010 	 */
18011 	mp2ctl = copymsg(mpctl);
18012 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18013 
18014 	/* ip6GroupMember table */
18015 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18016 	optp->level = MIB2_IP6;
18017 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18018 
18019 	rw_enter(&ill_g_lock, RW_READER);
18020 	ill = ILL_START_WALK_V6(&ctx);
18021 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18022 		ILM_WALKER_HOLD(ill);
18023 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18024 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18025 			ASSERT(ilm->ilm_ipif == NULL);
18026 			ASSERT(ilm->ilm_ill != NULL);
18027 			if (ilm->ilm_zoneid != zoneid)
18028 				continue;	/* not this zone */
18029 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18030 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18031 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18032 			if (!snmp_append_data2(mpctl->b_cont,
18033 			    &mp_tail,
18034 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18035 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18036 				    "failed to allocate %u bytes\n",
18037 				    (uint_t)sizeof (ipm6)));
18038 			}
18039 		}
18040 		ILM_WALKER_RELE(ill);
18041 	}
18042 	rw_exit(&ill_g_lock);
18043 
18044 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18045 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18046 	    (int)optp->level, (int)optp->name, (int)optp->len));
18047 	qreply(q, mpctl);
18048 	return (mp2ctl);
18049 }
18050 
18051 /* IP multicast filtered sources */
18052 static mblk_t *
18053 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
18054 {
18055 	struct opthdr		*optp;
18056 	mblk_t			*mp2ctl;
18057 	ill_t			*ill;
18058 	ipif_t			*ipif;
18059 	ilm_t			*ilm;
18060 	ip_grpsrc_t		ips;
18061 	mblk_t			*mp_tail = NULL;
18062 	ill_walk_context_t	ctx;
18063 	zoneid_t		zoneid;
18064 	int			i;
18065 	slist_t			*sl;
18066 
18067 	/*
18068 	 * make a copy of the original message
18069 	 */
18070 	mp2ctl = copymsg(mpctl);
18071 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18072 
18073 	/* ipGroupSource table */
18074 	optp = (struct opthdr *)&mpctl->b_rptr[
18075 	    sizeof (struct T_optmgmt_ack)];
18076 	optp->level = MIB2_IP;
18077 	optp->name = EXPER_IP_GROUP_SOURCES;
18078 
18079 	rw_enter(&ill_g_lock, RW_READER);
18080 	ill = ILL_START_WALK_V4(&ctx);
18081 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18082 		ILM_WALKER_HOLD(ill);
18083 		for (ipif = ill->ill_ipif; ipif != NULL;
18084 		    ipif = ipif->ipif_next) {
18085 			if (ipif->ipif_zoneid != zoneid)
18086 				continue;	/* not this zone */
18087 			(void) ipif_get_name(ipif,
18088 			    ips.ipGroupSourceIfIndex.o_bytes,
18089 			    OCTET_LENGTH);
18090 			ips.ipGroupSourceIfIndex.o_length =
18091 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18092 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18093 				ASSERT(ilm->ilm_ipif != NULL);
18094 				ASSERT(ilm->ilm_ill == NULL);
18095 				sl = ilm->ilm_filter;
18096 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18097 					continue;
18098 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18099 				for (i = 0; i < sl->sl_numsrc; i++) {
18100 					if (!IN6_IS_ADDR_V4MAPPED(
18101 					    &sl->sl_addr[i]))
18102 						continue;
18103 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18104 					    ips.ipGroupSourceAddress);
18105 					if (snmp_append_data2(mpctl->b_cont,
18106 					    &mp_tail, (char *)&ips,
18107 					    (int)sizeof (ips)) == 0) {
18108 						ip1dbg(("ip_snmp_get_mib2_"
18109 						    "ip_group_src: failed to "
18110 						    "allocate %u bytes\n",
18111 						    (uint_t)sizeof (ips)));
18112 					}
18113 				}
18114 			}
18115 		}
18116 		ILM_WALKER_RELE(ill);
18117 	}
18118 	rw_exit(&ill_g_lock);
18119 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18120 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18121 	    (int)optp->level, (int)optp->name, (int)optp->len));
18122 	qreply(q, mpctl);
18123 	return (mp2ctl);
18124 }
18125 
18126 /* IPv6 multicast filtered sources. */
18127 static mblk_t *
18128 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18129 {
18130 	struct opthdr		*optp;
18131 	mblk_t			*mp2ctl;
18132 	ill_t			*ill;
18133 	ilm_t			*ilm;
18134 	ipv6_grpsrc_t		ips6;
18135 	mblk_t			*mp_tail = NULL;
18136 	ill_walk_context_t	ctx;
18137 	zoneid_t		zoneid;
18138 	int			i;
18139 	slist_t			*sl;
18140 
18141 	/*
18142 	 * make a copy of the original message
18143 	 */
18144 	mp2ctl = copymsg(mpctl);
18145 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18146 
18147 	/* ip6GroupMember table */
18148 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18149 	optp->level = MIB2_IP6;
18150 	optp->name = EXPER_IP6_GROUP_SOURCES;
18151 
18152 	rw_enter(&ill_g_lock, RW_READER);
18153 	ill = ILL_START_WALK_V6(&ctx);
18154 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18155 		ILM_WALKER_HOLD(ill);
18156 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18157 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18158 			ASSERT(ilm->ilm_ipif == NULL);
18159 			ASSERT(ilm->ilm_ill != NULL);
18160 			sl = ilm->ilm_filter;
18161 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18162 				continue;
18163 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18164 			for (i = 0; i < sl->sl_numsrc; i++) {
18165 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18166 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18167 				    (char *)&ips6, (int)sizeof (ips6))) {
18168 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18169 					    "group_src: failed to allocate "
18170 					    "%u bytes\n",
18171 					    (uint_t)sizeof (ips6)));
18172 				}
18173 			}
18174 		}
18175 		ILM_WALKER_RELE(ill);
18176 	}
18177 	rw_exit(&ill_g_lock);
18178 
18179 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18180 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18181 	    (int)optp->level, (int)optp->name, (int)optp->len));
18182 	qreply(q, mpctl);
18183 	return (mp2ctl);
18184 }
18185 
18186 /* Multicast routing virtual interface table. */
18187 static mblk_t *
18188 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18189 {
18190 	struct opthdr		*optp;
18191 	mblk_t			*mp2ctl;
18192 
18193 	/*
18194 	 * make a copy of the original message
18195 	 */
18196 	mp2ctl = copymsg(mpctl);
18197 
18198 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18199 	optp->level = EXPER_DVMRP;
18200 	optp->name = EXPER_DVMRP_VIF;
18201 	if (!ip_mroute_vif(mpctl->b_cont)) {
18202 		ip0dbg(("ip_mroute_vif: failed\n"));
18203 	}
18204 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18205 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18206 	    (int)optp->level, (int)optp->name, (int)optp->len));
18207 	qreply(q, mpctl);
18208 	return (mp2ctl);
18209 }
18210 
18211 /* Multicast routing table. */
18212 static mblk_t *
18213 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18214 {
18215 	struct opthdr		*optp;
18216 	mblk_t			*mp2ctl;
18217 
18218 	/*
18219 	 * make a copy of the original message
18220 	 */
18221 	mp2ctl = copymsg(mpctl);
18222 
18223 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18224 	optp->level = EXPER_DVMRP;
18225 	optp->name = EXPER_DVMRP_MRT;
18226 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18227 		ip0dbg(("ip_mroute_mrt: failed\n"));
18228 	}
18229 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18230 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18231 	    (int)optp->level, (int)optp->name, (int)optp->len));
18232 	qreply(q, mpctl);
18233 	return (mp2ctl);
18234 }
18235 
18236 /*
18237  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18238  * in one IRE walk.
18239  */
18240 static mblk_t *
18241 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18242 {
18243 	struct opthdr	*optp;
18244 	mblk_t		*mp2ctl;	/* Returned */
18245 	mblk_t		*mp3ctl;	/* nettomedia */
18246 	mblk_t		*mp4ctl;	/* routeattrs */
18247 	iproutedata_t	ird;
18248 	zoneid_t	zoneid;
18249 
18250 	/*
18251 	 * make copies of the original message
18252 	 *	- mp2ctl is returned unchanged to the caller for his use
18253 	 *	- mpctl is sent upstream as ipRouteEntryTable
18254 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18255 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18256 	 */
18257 	mp2ctl = copymsg(mpctl);
18258 	mp3ctl = copymsg(mpctl);
18259 	mp4ctl = copymsg(mpctl);
18260 	if (mp3ctl == NULL || mp4ctl == NULL) {
18261 		freemsg(mp4ctl);
18262 		freemsg(mp3ctl);
18263 		freemsg(mp2ctl);
18264 		freemsg(mpctl);
18265 		return (NULL);
18266 	}
18267 
18268 	bzero(&ird, sizeof (ird));
18269 
18270 	ird.ird_route.lp_head = mpctl->b_cont;
18271 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18272 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18273 
18274 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18275 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18276 	if (zoneid == GLOBAL_ZONEID) {
18277 		/*
18278 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18279 		 * the sys_net_config privilege, it can only run in the global
18280 		 * zone, so we don't display these IREs in the other zones.
18281 		 */
18282 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18283 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18284 	}
18285 
18286 	/* ipRouteEntryTable in mpctl */
18287 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18288 	optp->level = MIB2_IP;
18289 	optp->name = MIB2_IP_ROUTE;
18290 	optp->len = msgdsize(ird.ird_route.lp_head);
18291 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18292 	    (int)optp->level, (int)optp->name, (int)optp->len));
18293 	qreply(q, mpctl);
18294 
18295 	/* ipNetToMediaEntryTable in mp3ctl */
18296 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18297 	optp->level = MIB2_IP;
18298 	optp->name = MIB2_IP_MEDIA;
18299 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18300 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18301 	    (int)optp->level, (int)optp->name, (int)optp->len));
18302 	qreply(q, mp3ctl);
18303 
18304 	/* ipRouteAttributeTable in mp4ctl */
18305 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18306 	optp->level = MIB2_IP;
18307 	optp->name = EXPER_IP_RTATTR;
18308 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18309 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18310 	    (int)optp->level, (int)optp->name, (int)optp->len));
18311 	if (optp->len == 0)
18312 		freemsg(mp4ctl);
18313 	else
18314 		qreply(q, mp4ctl);
18315 
18316 	return (mp2ctl);
18317 }
18318 
18319 /*
18320  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18321  * ipv6NetToMediaEntryTable in an NDP walk.
18322  */
18323 static mblk_t *
18324 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18325 {
18326 	struct opthdr	*optp;
18327 	mblk_t		*mp2ctl;	/* Returned */
18328 	mblk_t		*mp3ctl;	/* nettomedia */
18329 	mblk_t		*mp4ctl;	/* routeattrs */
18330 	iproutedata_t	ird;
18331 	zoneid_t	zoneid;
18332 
18333 	/*
18334 	 * make copies of the original message
18335 	 *	- mp2ctl is returned unchanged to the caller for his use
18336 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18337 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18338 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18339 	 */
18340 	mp2ctl = copymsg(mpctl);
18341 	mp3ctl = copymsg(mpctl);
18342 	mp4ctl = copymsg(mpctl);
18343 	if (mp3ctl == NULL || mp4ctl == NULL) {
18344 		freemsg(mp4ctl);
18345 		freemsg(mp3ctl);
18346 		freemsg(mp2ctl);
18347 		freemsg(mpctl);
18348 		return (NULL);
18349 	}
18350 
18351 	bzero(&ird, sizeof (ird));
18352 
18353 	ird.ird_route.lp_head = mpctl->b_cont;
18354 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18355 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18356 
18357 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18358 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18359 
18360 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18361 	optp->level = MIB2_IP6;
18362 	optp->name = MIB2_IP6_ROUTE;
18363 	optp->len = msgdsize(ird.ird_route.lp_head);
18364 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18365 	    (int)optp->level, (int)optp->name, (int)optp->len));
18366 	qreply(q, mpctl);
18367 
18368 	/* ipv6NetToMediaEntryTable in mp3ctl */
18369 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18370 
18371 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18372 	optp->level = MIB2_IP6;
18373 	optp->name = MIB2_IP6_MEDIA;
18374 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18375 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18376 	    (int)optp->level, (int)optp->name, (int)optp->len));
18377 	qreply(q, mp3ctl);
18378 
18379 	/* ipv6RouteAttributeTable in mp4ctl */
18380 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18381 	optp->level = MIB2_IP6;
18382 	optp->name = EXPER_IP_RTATTR;
18383 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18384 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18385 	    (int)optp->level, (int)optp->name, (int)optp->len));
18386 	if (optp->len == 0)
18387 		freemsg(mp4ctl);
18388 	else
18389 		qreply(q, mp4ctl);
18390 
18391 	return (mp2ctl);
18392 }
18393 
18394 /*
18395  * ICMPv6 mib: One per ill
18396  */
18397 static mblk_t *
18398 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18399 {
18400 	struct opthdr		*optp;
18401 	mblk_t			*mp2ctl;
18402 	ill_t			*ill;
18403 	ill_walk_context_t	ctx;
18404 	mblk_t			*mp_tail = NULL;
18405 
18406 	/*
18407 	 * Make a copy of the original message
18408 	 */
18409 	mp2ctl = copymsg(mpctl);
18410 
18411 	/* fixed length IPv6 structure ... */
18412 
18413 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18414 	optp->level = MIB2_IP6;
18415 	optp->name = 0;
18416 	/* Include "unknown interface" ip6_mib */
18417 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
18418 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
18419 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
18420 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
18421 	    sizeof (mib2_ipv6IfStatsEntry_t));
18422 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18423 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
18424 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
18425 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18426 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
18427 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18428 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18429 	    (int)sizeof (ip6_mib))) {
18430 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18431 		    (uint_t)sizeof (ip6_mib)));
18432 	}
18433 
18434 	rw_enter(&ill_g_lock, RW_READER);
18435 	ill = ILL_START_WALK_V6(&ctx);
18436 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18437 		ill->ill_ip6_mib->ipv6IfIndex =
18438 		    ill->ill_phyint->phyint_ifindex;
18439 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
18440 		    ipv6_forward ? 1 : 2);
18441 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
18442 		    ill->ill_max_hops);
18443 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
18444 		    sizeof (mib2_ipv6IfStatsEntry_t));
18445 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
18446 		    sizeof (mib2_ipv6AddrEntry_t));
18447 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
18448 		    sizeof (mib2_ipv6RouteEntry_t));
18449 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
18450 		    sizeof (mib2_ipv6NetToMediaEntry_t));
18451 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
18452 		    sizeof (ipv6_member_t));
18453 
18454 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18455 		    (char *)ill->ill_ip6_mib,
18456 		    (int)sizeof (*ill->ill_ip6_mib))) {
18457 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18458 				"%u bytes\n",
18459 				(uint_t)sizeof (*ill->ill_ip6_mib)));
18460 		}
18461 	}
18462 	rw_exit(&ill_g_lock);
18463 
18464 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18465 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18466 	    (int)optp->level, (int)optp->name, (int)optp->len));
18467 	qreply(q, mpctl);
18468 	return (mp2ctl);
18469 }
18470 
18471 /*
18472  * ICMPv6 mib: One per ill
18473  */
18474 static mblk_t *
18475 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18476 {
18477 	struct opthdr		*optp;
18478 	mblk_t			*mp2ctl;
18479 	ill_t			*ill;
18480 	ill_walk_context_t	ctx;
18481 	mblk_t			*mp_tail = NULL;
18482 	/*
18483 	 * Make a copy of the original message
18484 	 */
18485 	mp2ctl = copymsg(mpctl);
18486 
18487 	/* fixed length ICMPv6 structure ... */
18488 
18489 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18490 	optp->level = MIB2_ICMP6;
18491 	optp->name = 0;
18492 	/* Include "unknown interface" icmp6_mib */
18493 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
18494 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18495 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18496 	    (int)sizeof (icmp6_mib))) {
18497 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18498 		    (uint_t)sizeof (icmp6_mib)));
18499 	}
18500 
18501 	rw_enter(&ill_g_lock, RW_READER);
18502 	ill = ILL_START_WALK_V6(&ctx);
18503 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18504 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18505 		    ill->ill_phyint->phyint_ifindex;
18506 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
18507 		    sizeof (mib2_ipv6IfIcmpEntry_t);
18508 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18509 		    (char *)ill->ill_icmp6_mib,
18510 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18511 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18512 			    "%u bytes\n",
18513 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18514 		}
18515 	}
18516 	rw_exit(&ill_g_lock);
18517 
18518 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18519 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18520 	    (int)optp->level, (int)optp->name, (int)optp->len));
18521 	qreply(q, mpctl);
18522 	return (mp2ctl);
18523 }
18524 
18525 /*
18526  * ire_walk routine to create both ipRouteEntryTable and
18527  * ipNetToMediaEntryTable in one IRE walk
18528  */
18529 static void
18530 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18531 {
18532 	ill_t				*ill;
18533 	ipif_t				*ipif;
18534 	mblk_t				*llmp;
18535 	dl_unitdata_req_t		*dlup;
18536 	mib2_ipRouteEntry_t		*re;
18537 	mib2_ipNetToMediaEntry_t	ntme;
18538 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18539 	ipaddr_t			gw_addr;
18540 	tsol_ire_gw_secattr_t		*attrp;
18541 	tsol_gc_t			*gc = NULL;
18542 	tsol_gcgrp_t			*gcgrp = NULL;
18543 	uint_t				sacnt = 0;
18544 	int				i;
18545 
18546 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18547 
18548 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18549 		return;
18550 
18551 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18552 		mutex_enter(&attrp->igsa_lock);
18553 		if ((gc = attrp->igsa_gc) != NULL) {
18554 			gcgrp = gc->gc_grp;
18555 			ASSERT(gcgrp != NULL);
18556 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18557 			sacnt = 1;
18558 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18559 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18560 			gc = gcgrp->gcgrp_head;
18561 			sacnt = gcgrp->gcgrp_count;
18562 		}
18563 		mutex_exit(&attrp->igsa_lock);
18564 
18565 		/* do nothing if there's no gc to report */
18566 		if (gc == NULL) {
18567 			ASSERT(sacnt == 0);
18568 			if (gcgrp != NULL) {
18569 				/* we might as well drop the lock now */
18570 				rw_exit(&gcgrp->gcgrp_rwlock);
18571 				gcgrp = NULL;
18572 			}
18573 			attrp = NULL;
18574 		}
18575 
18576 		ASSERT(gc == NULL || (gcgrp != NULL &&
18577 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18578 	}
18579 	ASSERT(sacnt == 0 || gc != NULL);
18580 
18581 	if (sacnt != 0 &&
18582 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18583 		kmem_free(re, sizeof (*re));
18584 		rw_exit(&gcgrp->gcgrp_rwlock);
18585 		return;
18586 	}
18587 
18588 	/*
18589 	 * Return all IRE types for route table... let caller pick and choose
18590 	 */
18591 	re->ipRouteDest = ire->ire_addr;
18592 	ipif = ire->ire_ipif;
18593 	re->ipRouteIfIndex.o_length = 0;
18594 	if (ire->ire_type == IRE_CACHE) {
18595 		ill = (ill_t *)ire->ire_stq->q_ptr;
18596 		re->ipRouteIfIndex.o_length =
18597 		    ill->ill_name_length == 0 ? 0 :
18598 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18599 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18600 		    re->ipRouteIfIndex.o_length);
18601 	} else if (ipif != NULL) {
18602 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18603 		    OCTET_LENGTH);
18604 		re->ipRouteIfIndex.o_length =
18605 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18606 	}
18607 	re->ipRouteMetric1 = -1;
18608 	re->ipRouteMetric2 = -1;
18609 	re->ipRouteMetric3 = -1;
18610 	re->ipRouteMetric4 = -1;
18611 
18612 	gw_addr = ire->ire_gateway_addr;
18613 
18614 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18615 		re->ipRouteNextHop = ire->ire_src_addr;
18616 	else
18617 		re->ipRouteNextHop = gw_addr;
18618 	/* indirect(4), direct(3), or invalid(2) */
18619 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18620 		re->ipRouteType = 2;
18621 	else
18622 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18623 	re->ipRouteProto = -1;
18624 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18625 	re->ipRouteMask = ire->ire_mask;
18626 	re->ipRouteMetric5 = -1;
18627 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
18628 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
18629 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
18630 	if (ire->ire_nce &&
18631 	    ire->ire_nce->nce_state == ND_REACHABLE)
18632 		llmp = ire->ire_nce->nce_res_mp;
18633 	else
18634 		llmp = NULL;
18635 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
18636 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
18637 	re->ipRouteInfo.re_ire_type	= ire->ire_type;
18638 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18639 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18640 	re->ipRouteInfo.re_flags	= ire->ire_flags;
18641 	re->ipRouteInfo.re_in_ill.o_length = 0;
18642 	if (ire->ire_in_ill != NULL) {
18643 		re->ipRouteInfo.re_in_ill.o_length =
18644 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
18645 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
18646 		bcopy(ire->ire_in_ill->ill_name,
18647 		    re->ipRouteInfo.re_in_ill.o_bytes,
18648 		    re->ipRouteInfo.re_in_ill.o_length);
18649 	}
18650 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
18651 
18652 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18653 	    (char *)re, (int)sizeof (*re))) {
18654 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18655 		    (uint_t)sizeof (*re)));
18656 	}
18657 
18658 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18659 		iaeptr->iae_routeidx = ird->ird_idx;
18660 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18661 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18662 	}
18663 
18664 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18665 	    (char *)iae, sacnt * sizeof (*iae))) {
18666 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18667 		    (unsigned)(sacnt * sizeof (*iae))));
18668 	}
18669 
18670 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
18671 		goto done;
18672 	/*
18673 	 * only IRE_CACHE entries that are for a directly connected subnet
18674 	 * get appended to net -> phys addr table
18675 	 * (others in arp)
18676 	 */
18677 	ntme.ipNetToMediaIfIndex.o_length = 0;
18678 	ill = ire_to_ill(ire);
18679 	ASSERT(ill != NULL);
18680 	ntme.ipNetToMediaIfIndex.o_length =
18681 	    ill->ill_name_length == 0 ? 0 :
18682 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18683 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
18684 		    ntme.ipNetToMediaIfIndex.o_length);
18685 
18686 	ntme.ipNetToMediaPhysAddress.o_length = 0;
18687 	if (llmp) {
18688 		uchar_t *addr;
18689 
18690 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
18691 		/* Remove sap from  address */
18692 		if (ill->ill_sap_length < 0)
18693 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
18694 		else
18695 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
18696 			    ill->ill_sap_length;
18697 
18698 		ntme.ipNetToMediaPhysAddress.o_length =
18699 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18700 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18701 		    ntme.ipNetToMediaPhysAddress.o_length);
18702 	}
18703 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18704 	/* assume dynamic (may be changed in arp) */
18705 	ntme.ipNetToMediaType = 3;
18706 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18707 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18708 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18709 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18710 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18711 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18712 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18713 		    (uint_t)sizeof (ntme)));
18714 	}
18715 done:
18716 	/* bump route index for next pass */
18717 	ird->ird_idx++;
18718 
18719 	kmem_free(re, sizeof (*re));
18720 	if (sacnt != 0)
18721 		kmem_free(iae, sacnt * sizeof (*iae));
18722 
18723 	if (gcgrp != NULL)
18724 		rw_exit(&gcgrp->gcgrp_rwlock);
18725 }
18726 
18727 /*
18728  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18729  */
18730 static void
18731 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18732 {
18733 	ill_t				*ill;
18734 	ipif_t				*ipif;
18735 	mib2_ipv6RouteEntry_t		*re;
18736 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18737 	in6_addr_t			gw_addr_v6;
18738 	tsol_ire_gw_secattr_t		*attrp;
18739 	tsol_gc_t			*gc = NULL;
18740 	tsol_gcgrp_t			*gcgrp = NULL;
18741 	uint_t				sacnt = 0;
18742 	int				i;
18743 
18744 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18745 
18746 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18747 		return;
18748 
18749 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18750 		mutex_enter(&attrp->igsa_lock);
18751 		if ((gc = attrp->igsa_gc) != NULL) {
18752 			gcgrp = gc->gc_grp;
18753 			ASSERT(gcgrp != NULL);
18754 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18755 			sacnt = 1;
18756 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18757 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18758 			gc = gcgrp->gcgrp_head;
18759 			sacnt = gcgrp->gcgrp_count;
18760 		}
18761 		mutex_exit(&attrp->igsa_lock);
18762 
18763 		/* do nothing if there's no gc to report */
18764 		if (gc == NULL) {
18765 			ASSERT(sacnt == 0);
18766 			if (gcgrp != NULL) {
18767 				/* we might as well drop the lock now */
18768 				rw_exit(&gcgrp->gcgrp_rwlock);
18769 				gcgrp = NULL;
18770 			}
18771 			attrp = NULL;
18772 		}
18773 
18774 		ASSERT(gc == NULL || (gcgrp != NULL &&
18775 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18776 	}
18777 	ASSERT(sacnt == 0 || gc != NULL);
18778 
18779 	if (sacnt != 0 &&
18780 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18781 		kmem_free(re, sizeof (*re));
18782 		rw_exit(&gcgrp->gcgrp_rwlock);
18783 		return;
18784 	}
18785 
18786 	/*
18787 	 * Return all IRE types for route table... let caller pick and choose
18788 	 */
18789 	re->ipv6RouteDest = ire->ire_addr_v6;
18790 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18791 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18792 	re->ipv6RouteIfIndex.o_length = 0;
18793 	ipif = ire->ire_ipif;
18794 	if (ire->ire_type == IRE_CACHE) {
18795 		ill = (ill_t *)ire->ire_stq->q_ptr;
18796 		re->ipv6RouteIfIndex.o_length =
18797 		    ill->ill_name_length == 0 ? 0 :
18798 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18799 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
18800 		    re->ipv6RouteIfIndex.o_length);
18801 	} else if (ipif != NULL) {
18802 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
18803 		    OCTET_LENGTH);
18804 		re->ipv6RouteIfIndex.o_length =
18805 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
18806 	}
18807 
18808 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18809 
18810 	mutex_enter(&ire->ire_lock);
18811 	gw_addr_v6 = ire->ire_gateway_addr_v6;
18812 	mutex_exit(&ire->ire_lock);
18813 
18814 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
18815 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
18816 	else
18817 		re->ipv6RouteNextHop = gw_addr_v6;
18818 
18819 	/* remote(4), local(3), or discard(2) */
18820 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18821 		re->ipv6RouteType = 2;
18822 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
18823 		re->ipv6RouteType = 3;
18824 	else
18825 		re->ipv6RouteType = 4;
18826 
18827 	re->ipv6RouteProtocol	= -1;
18828 	re->ipv6RoutePolicy	= 0;
18829 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
18830 	re->ipv6RouteNextHopRDI	= 0;
18831 	re->ipv6RouteWeight	= 0;
18832 	re->ipv6RouteMetric	= 0;
18833 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
18834 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
18835 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
18836 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
18837 	re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
18838 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18839 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18840 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
18841 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
18842 
18843 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18844 	    (char *)re, (int)sizeof (*re))) {
18845 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18846 		    (uint_t)sizeof (*re)));
18847 	}
18848 
18849 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18850 		iaeptr->iae_routeidx = ird->ird_idx;
18851 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18852 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18853 	}
18854 
18855 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18856 	    (char *)iae, sacnt * sizeof (*iae))) {
18857 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18858 		    (unsigned)(sacnt * sizeof (*iae))));
18859 	}
18860 
18861 	/* bump route index for next pass */
18862 	ird->ird_idx++;
18863 
18864 	kmem_free(re, sizeof (*re));
18865 	if (sacnt != 0)
18866 		kmem_free(iae, sacnt * sizeof (*iae));
18867 
18868 	if (gcgrp != NULL)
18869 		rw_exit(&gcgrp->gcgrp_rwlock);
18870 }
18871 
18872 /*
18873  * ndp_walk routine to create ipv6NetToMediaEntryTable
18874  */
18875 static int
18876 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
18877 {
18878 	ill_t				*ill;
18879 	mib2_ipv6NetToMediaEntry_t	ntme;
18880 	dl_unitdata_req_t		*dl;
18881 
18882 	ill = nce->nce_ill;
18883 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
18884 		return (0);
18885 
18886 	/*
18887 	 * Neighbor cache entry attached to IRE with on-link
18888 	 * destination.
18889 	 */
18890 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
18891 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
18892 	if ((ill->ill_flags & ILLF_XRESOLV) &&
18893 	    (nce->nce_res_mp != NULL)) {
18894 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
18895 		ntme.ipv6NetToMediaPhysAddress.o_length =
18896 		    dl->dl_dest_addr_length;
18897 	} else {
18898 		ntme.ipv6NetToMediaPhysAddress.o_length =
18899 		    ill->ill_phys_addr_length;
18900 	}
18901 	if (nce->nce_res_mp != NULL) {
18902 		bcopy((char *)nce->nce_res_mp->b_rptr +
18903 		    NCE_LL_ADDR_OFFSET(ill),
18904 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
18905 		    ntme.ipv6NetToMediaPhysAddress.o_length);
18906 	} else {
18907 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
18908 		    ill->ill_phys_addr_length);
18909 	}
18910 	/*
18911 	 * Note: Returns ND_* states. Should be:
18912 	 * reachable(1), stale(2), delay(3), probe(4),
18913 	 * invalid(5), unknown(6)
18914 	 */
18915 	ntme.ipv6NetToMediaState = nce->nce_state;
18916 	ntme.ipv6NetToMediaLastUpdated = 0;
18917 
18918 	/* other(1), dynamic(2), static(3), local(4) */
18919 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
18920 		ntme.ipv6NetToMediaType = 4;
18921 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
18922 		ntme.ipv6NetToMediaType = 1;
18923 	} else {
18924 		ntme.ipv6NetToMediaType = 2;
18925 	}
18926 
18927 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18928 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18929 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
18930 		    (uint_t)sizeof (ntme)));
18931 	}
18932 	return (0);
18933 }
18934 
18935 /*
18936  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
18937  */
18938 /* ARGSUSED */
18939 int
18940 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
18941 {
18942 	switch (level) {
18943 	case MIB2_IP:
18944 	case MIB2_ICMP:
18945 		switch (name) {
18946 		default:
18947 			break;
18948 		}
18949 		return (1);
18950 	default:
18951 		return (1);
18952 	}
18953 }
18954 
18955 /*
18956  * Called before the options are updated to check if this packet will
18957  * be source routed from here.
18958  * This routine assumes that the options are well formed i.e. that they
18959  * have already been checked.
18960  */
18961 static boolean_t
18962 ip_source_routed(ipha_t *ipha)
18963 {
18964 	ipoptp_t	opts;
18965 	uchar_t		*opt;
18966 	uint8_t		optval;
18967 	uint8_t		optlen;
18968 	ipaddr_t	dst;
18969 	ire_t		*ire;
18970 
18971 	if (IS_SIMPLE_IPH(ipha)) {
18972 		ip2dbg(("not source routed\n"));
18973 		return (B_FALSE);
18974 	}
18975 	dst = ipha->ipha_dst;
18976 	for (optval = ipoptp_first(&opts, ipha);
18977 	    optval != IPOPT_EOL;
18978 	    optval = ipoptp_next(&opts)) {
18979 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18980 		opt = opts.ipoptp_cur;
18981 		optlen = opts.ipoptp_len;
18982 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
18983 		    optval, optlen));
18984 		switch (optval) {
18985 			uint32_t off;
18986 		case IPOPT_SSRR:
18987 		case IPOPT_LSRR:
18988 			/*
18989 			 * If dst is one of our addresses and there are some
18990 			 * entries left in the source route return (true).
18991 			 */
18992 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18993 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
18994 			if (ire == NULL) {
18995 				ip2dbg(("ip_source_routed: not next"
18996 				    " source route 0x%x\n",
18997 				    ntohl(dst)));
18998 				return (B_FALSE);
18999 			}
19000 			ire_refrele(ire);
19001 			off = opt[IPOPT_OFFSET];
19002 			off--;
19003 			if (optlen < IP_ADDR_LEN ||
19004 			    off > optlen - IP_ADDR_LEN) {
19005 				/* End of source route */
19006 				ip1dbg(("ip_source_routed: end of SR\n"));
19007 				return (B_FALSE);
19008 			}
19009 			return (B_TRUE);
19010 		}
19011 	}
19012 	ip2dbg(("not source routed\n"));
19013 	return (B_FALSE);
19014 }
19015 
19016 /*
19017  * Check if the packet contains any source route.
19018  */
19019 static boolean_t
19020 ip_source_route_included(ipha_t *ipha)
19021 {
19022 	ipoptp_t	opts;
19023 	uint8_t		optval;
19024 
19025 	if (IS_SIMPLE_IPH(ipha))
19026 		return (B_FALSE);
19027 	for (optval = ipoptp_first(&opts, ipha);
19028 	    optval != IPOPT_EOL;
19029 	    optval = ipoptp_next(&opts)) {
19030 		switch (optval) {
19031 		case IPOPT_SSRR:
19032 		case IPOPT_LSRR:
19033 			return (B_TRUE);
19034 		}
19035 	}
19036 	return (B_FALSE);
19037 }
19038 
19039 /*
19040  * Called when the IRE expiration timer fires.
19041  */
19042 /* ARGSUSED */
19043 void
19044 ip_trash_timer_expire(void *args)
19045 {
19046 	int	flush_flag = 0;
19047 
19048 	/*
19049 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19050 	 * This lock makes sure that a new invocation of this function
19051 	 * that occurs due to an almost immediate timer firing will not
19052 	 * progress beyond this point until the current invocation is done
19053 	 */
19054 	mutex_enter(&ip_trash_timer_lock);
19055 	ip_ire_expire_id = 0;
19056 	mutex_exit(&ip_trash_timer_lock);
19057 
19058 	/* Periodic timer */
19059 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
19060 		/*
19061 		 * Remove all IRE_CACHE entries since they might
19062 		 * contain arp information.
19063 		 */
19064 		flush_flag |= FLUSH_ARP_TIME;
19065 		ip_ire_arp_time_elapsed = 0;
19066 		IP_STAT(ip_ire_arp_timer_expired);
19067 	}
19068 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
19069 		/* Remove all redirects */
19070 		flush_flag |= FLUSH_REDIRECT_TIME;
19071 		ip_ire_rd_time_elapsed = 0;
19072 		IP_STAT(ip_ire_redirect_timer_expired);
19073 	}
19074 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
19075 		/* Increase path mtu */
19076 		flush_flag |= FLUSH_MTU_TIME;
19077 		ip_ire_pmtu_time_elapsed = 0;
19078 		IP_STAT(ip_ire_pmtu_timer_expired);
19079 	}
19080 
19081 	/*
19082 	 * Optimize for the case when there are no redirects in the
19083 	 * ftable, that is, no need to walk the ftable in that case.
19084 	 */
19085 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19086 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19087 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
19088 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
19089 	}
19090 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
19091 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19092 		    ire_expire, (char *)(uintptr_t)flush_flag,
19093 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
19094 	}
19095 	if (flush_flag & FLUSH_MTU_TIME) {
19096 		/*
19097 		 * Walk all IPv6 IRE's and update them
19098 		 * Note that ARP and redirect timers are not
19099 		 * needed since NUD handles stale entries.
19100 		 */
19101 		flush_flag = FLUSH_MTU_TIME;
19102 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
19103 		    ALL_ZONES);
19104 	}
19105 
19106 	ip_ire_arp_time_elapsed += ip_timer_interval;
19107 	ip_ire_rd_time_elapsed += ip_timer_interval;
19108 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19109 
19110 	/*
19111 	 * Hold the lock to serialize timeout calls and prevent
19112 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19113 	 * for the timer to fire and a new invocation of this function
19114 	 * to start before the return value of timeout has been stored
19115 	 * in ip_ire_expire_id by the current invocation.
19116 	 */
19117 	mutex_enter(&ip_trash_timer_lock);
19118 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19119 	    MSEC_TO_TICK(ip_timer_interval));
19120 	mutex_exit(&ip_trash_timer_lock);
19121 }
19122 
19123 /*
19124  * Called by the memory allocator subsystem directly, when the system
19125  * is running low on memory.
19126  */
19127 /* ARGSUSED */
19128 void
19129 ip_trash_ire_reclaim(void *args)
19130 {
19131 	ire_cache_count_t icc;
19132 	ire_cache_reclaim_t icr;
19133 	ncc_cache_count_t ncc;
19134 	nce_cache_reclaim_t ncr;
19135 	uint_t delete_cnt;
19136 	/*
19137 	 * Memory reclaim call back.
19138 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19139 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19140 	 * entries, determine what fraction to free for
19141 	 * each category of IRE_CACHE entries giving absolute priority
19142 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19143 	 * entry will be freed unless all offlink entries are freed).
19144 	 */
19145 	icc.icc_total = 0;
19146 	icc.icc_unused = 0;
19147 	icc.icc_offlink = 0;
19148 	icc.icc_pmtu = 0;
19149 	icc.icc_onlink = 0;
19150 	ire_walk(ire_cache_count, (char *)&icc);
19151 
19152 	/*
19153 	 * Free NCEs for IPv6 like the onlink ires.
19154 	 */
19155 	ncc.ncc_total = 0;
19156 	ncc.ncc_host = 0;
19157 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19158 
19159 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19160 	    icc.icc_pmtu + icc.icc_onlink);
19161 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19162 	IP_STAT(ip_trash_ire_reclaim_calls);
19163 	if (delete_cnt == 0)
19164 		return;
19165 	IP_STAT(ip_trash_ire_reclaim_success);
19166 	/* Always delete all unused offlink entries */
19167 	icr.icr_unused = 1;
19168 	if (delete_cnt <= icc.icc_unused) {
19169 		/*
19170 		 * Only need to free unused entries.  In other words,
19171 		 * there are enough unused entries to free to meet our
19172 		 * target number of freed ire cache entries.
19173 		 */
19174 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19175 		ncr.ncr_host = 0;
19176 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19177 		/*
19178 		 * Only need to free unused entries, plus a fraction of offlink
19179 		 * entries.  It follows from the first if statement that
19180 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19181 		 */
19182 		delete_cnt -= icc.icc_unused;
19183 		/* Round up # deleted by truncating fraction */
19184 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19185 		icr.icr_pmtu = icr.icr_onlink = 0;
19186 		ncr.ncr_host = 0;
19187 	} else if (delete_cnt <=
19188 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19189 		/*
19190 		 * Free all unused and offlink entries, plus a fraction of
19191 		 * pmtu entries.  It follows from the previous if statement
19192 		 * that icc_pmtu is non-zero, and that
19193 		 * delete_cnt != icc_unused + icc_offlink.
19194 		 */
19195 		icr.icr_offlink = 1;
19196 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19197 		/* Round up # deleted by truncating fraction */
19198 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19199 		icr.icr_onlink = 0;
19200 		ncr.ncr_host = 0;
19201 	} else {
19202 		/*
19203 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19204 		 * of onlink entries.  If we're here, then we know that
19205 		 * icc_onlink is non-zero, and that
19206 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19207 		 */
19208 		icr.icr_offlink = icr.icr_pmtu = 1;
19209 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19210 		    icc.icc_pmtu;
19211 		/* Round up # deleted by truncating fraction */
19212 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19213 		/* Using the same delete fraction as for onlink IREs */
19214 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19215 	}
19216 #ifdef DEBUG
19217 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19218 	    "fractions %d/%d/%d/%d\n",
19219 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19220 	    icc.icc_unused, icc.icc_offlink,
19221 	    icc.icc_pmtu, icc.icc_onlink,
19222 	    icr.icr_unused, icr.icr_offlink,
19223 	    icr.icr_pmtu, icr.icr_onlink));
19224 #endif
19225 	ire_walk(ire_cache_reclaim, (char *)&icr);
19226 	if (ncr.ncr_host != 0)
19227 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19228 		    (uchar_t *)&ncr);
19229 #ifdef DEBUG
19230 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19231 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19232 	ire_walk(ire_cache_count, (char *)&icc);
19233 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19234 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19235 	    icc.icc_pmtu, icc.icc_onlink));
19236 #endif
19237 }
19238 
19239 /*
19240  * ip_unbind is called when a copy of an unbind request is received from the
19241  * upper level protocol.  We remove this conn from any fanout hash list it is
19242  * on, and zero out the bind information.  No reply is expected up above.
19243  */
19244 mblk_t *
19245 ip_unbind(queue_t *q, mblk_t *mp)
19246 {
19247 	conn_t	*connp = Q_TO_CONN(q);
19248 
19249 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19250 
19251 	if (is_system_labeled() && connp->conn_anon_port) {
19252 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19253 		    connp->conn_mlp_type, connp->conn_ulp,
19254 		    ntohs(connp->conn_lport), B_FALSE);
19255 		connp->conn_anon_port = 0;
19256 	}
19257 	connp->conn_mlp_type = mlptSingle;
19258 
19259 	ipcl_hash_remove(connp);
19260 
19261 	ASSERT(mp->b_cont == NULL);
19262 	/*
19263 	 * Convert mp into a T_OK_ACK
19264 	 */
19265 	mp = mi_tpi_ok_ack_alloc(mp);
19266 
19267 	/*
19268 	 * should not happen in practice... T_OK_ACK is smaller than the
19269 	 * original message.
19270 	 */
19271 	if (mp == NULL)
19272 		return (NULL);
19273 
19274 	/*
19275 	 * Don't bzero the ports if its TCP since TCP still needs the
19276 	 * lport to remove it from its own bind hash. TCP will do the
19277 	 * cleanup.
19278 	 */
19279 	if (!IPCL_IS_TCP(connp))
19280 		bzero(&connp->u_port, sizeof (connp->u_port));
19281 
19282 	return (mp);
19283 }
19284 
19285 /*
19286  * Write side put procedure.  Outbound data, IOCTLs, responses from
19287  * resolvers, etc, come down through here.
19288  *
19289  * arg2 is always a queue_t *.
19290  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19291  * the zoneid.
19292  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19293  */
19294 void
19295 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19296 {
19297 	conn_t		*connp = NULL;
19298 	queue_t		*q = (queue_t *)arg2;
19299 	ipha_t		*ipha;
19300 #define	rptr	((uchar_t *)ipha)
19301 	ire_t		*ire = NULL;
19302 	ire_t		*sctp_ire = NULL;
19303 	uint32_t	v_hlen_tos_len;
19304 	ipaddr_t	dst;
19305 	mblk_t		*first_mp = NULL;
19306 	boolean_t	mctl_present;
19307 	ipsec_out_t	*io;
19308 	int		match_flags;
19309 	ill_t		*attach_ill = NULL;
19310 					/* Bind to IPIF_NOFAILOVER ill etc. */
19311 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19312 	ipif_t		*dst_ipif;
19313 	boolean_t	multirt_need_resolve = B_FALSE;
19314 	mblk_t		*copy_mp = NULL;
19315 	int		err;
19316 	zoneid_t	zoneid;
19317 	int	adjust;
19318 	uint16_t iplen;
19319 	boolean_t	need_decref = B_FALSE;
19320 	boolean_t	ignore_dontroute = B_FALSE;
19321 	boolean_t	ignore_nexthop = B_FALSE;
19322 	boolean_t	ip_nexthop = B_FALSE;
19323 	ipaddr_t	nexthop_addr;
19324 
19325 #ifdef	_BIG_ENDIAN
19326 #define	V_HLEN	(v_hlen_tos_len >> 24)
19327 #else
19328 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19329 #endif
19330 
19331 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19332 	    "ip_wput_start: q %p", q);
19333 
19334 	/*
19335 	 * ip_wput fast path
19336 	 */
19337 
19338 	/* is packet from ARP ? */
19339 	if (q->q_next != NULL) {
19340 		zoneid = (zoneid_t)(uintptr_t)arg;
19341 		goto qnext;
19342 	}
19343 
19344 	connp = (conn_t *)arg;
19345 	ASSERT(connp != NULL);
19346 	zoneid = connp->conn_zoneid;
19347 
19348 	/* is queue flow controlled? */
19349 	if ((q->q_first != NULL || connp->conn_draining) &&
19350 	    (caller == IP_WPUT)) {
19351 		ASSERT(!need_decref);
19352 		(void) putq(q, mp);
19353 		return;
19354 	}
19355 
19356 	/* Multidata transmit? */
19357 	if (DB_TYPE(mp) == M_MULTIDATA) {
19358 		/*
19359 		 * We should never get here, since all Multidata messages
19360 		 * originating from tcp should have been directed over to
19361 		 * tcp_multisend() in the first place.
19362 		 */
19363 		BUMP_MIB(&ip_mib, ipOutDiscards);
19364 		freemsg(mp);
19365 		return;
19366 	} else if (DB_TYPE(mp) != M_DATA)
19367 		goto notdata;
19368 
19369 	if (mp->b_flag & MSGHASREF) {
19370 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19371 		mp->b_flag &= ~MSGHASREF;
19372 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19373 		need_decref = B_TRUE;
19374 	}
19375 	ipha = (ipha_t *)mp->b_rptr;
19376 
19377 	/* is IP header non-aligned or mblk smaller than basic IP header */
19378 #ifndef SAFETY_BEFORE_SPEED
19379 	if (!OK_32PTR(rptr) ||
19380 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19381 		goto hdrtoosmall;
19382 #endif
19383 
19384 	ASSERT(OK_32PTR(ipha));
19385 
19386 	/*
19387 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19388 	 * wrong version, we'll catch it again in ip_output_v6.
19389 	 *
19390 	 * Note that this is *only* locally-generated output here, and never
19391 	 * forwarded data, and that we need to deal only with transports that
19392 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19393 	 * label.)
19394 	 */
19395 	if (is_system_labeled() &&
19396 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19397 	    !connp->conn_ulp_labeled) {
19398 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19399 		    connp->conn_mac_exempt);
19400 		ipha = (ipha_t *)mp->b_rptr;
19401 		if (err != 0) {
19402 			first_mp = mp;
19403 			if (err == EINVAL)
19404 				goto icmp_parameter_problem;
19405 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19406 			goto drop_pkt;
19407 		}
19408 		iplen = ntohs(ipha->ipha_length) + adjust;
19409 		ipha->ipha_length = htons(iplen);
19410 	}
19411 
19412 	/*
19413 	 * If there is a policy, try to attach an ipsec_out in
19414 	 * the front. At the end, first_mp either points to a
19415 	 * M_DATA message or IPSEC_OUT message linked to a
19416 	 * M_DATA message. We have to do it now as we might
19417 	 * lose the "conn" if we go through ip_newroute.
19418 	 */
19419 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19420 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
19421 		    ipha->ipha_protocol)) == NULL)) {
19422 			if (need_decref)
19423 				CONN_DEC_REF(connp);
19424 			return;
19425 		} else {
19426 			ASSERT(mp->b_datap->db_type == M_CTL);
19427 			first_mp = mp;
19428 			mp = mp->b_cont;
19429 			mctl_present = B_TRUE;
19430 		}
19431 	} else {
19432 		first_mp = mp;
19433 		mctl_present = B_FALSE;
19434 	}
19435 
19436 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19437 
19438 	/* is wrong version or IP options present */
19439 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19440 		goto version_hdrlen_check;
19441 	dst = ipha->ipha_dst;
19442 
19443 	if (connp->conn_nofailover_ill != NULL) {
19444 		attach_ill = conn_get_held_ill(connp,
19445 		    &connp->conn_nofailover_ill, &err);
19446 		if (err == ILL_LOOKUP_FAILED) {
19447 			if (need_decref)
19448 				CONN_DEC_REF(connp);
19449 			freemsg(first_mp);
19450 			return;
19451 		}
19452 	}
19453 
19454 	/* is packet multicast? */
19455 	if (CLASSD(dst))
19456 		goto multicast;
19457 
19458 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19459 	    (connp->conn_nexthop_set)) {
19460 		/*
19461 		 * If the destination is a broadcast or a loopback
19462 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
19463 		 * through the standard path. But in the case of local
19464 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
19465 		 * the standard path not IP_XMIT_IF.
19466 		 */
19467 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19468 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
19469 		    (ire->ire_type != IRE_LOOPBACK))) {
19470 			if ((connp->conn_dontroute ||
19471 			    connp->conn_nexthop_set) && (ire != NULL) &&
19472 			    (ire->ire_type == IRE_LOCAL))
19473 				goto standard_path;
19474 
19475 			if (ire != NULL) {
19476 				ire_refrele(ire);
19477 				/* No more access to ire */
19478 				ire = NULL;
19479 			}
19480 			/*
19481 			 * bypass routing checks and go directly to
19482 			 * interface.
19483 			 */
19484 			if (connp->conn_dontroute) {
19485 				goto dontroute;
19486 			} else if (connp->conn_nexthop_set) {
19487 				ip_nexthop = B_TRUE;
19488 				nexthop_addr = connp->conn_nexthop_v4;
19489 				goto send_from_ill;
19490 			}
19491 
19492 			/*
19493 			 * If IP_XMIT_IF socket option is set,
19494 			 * then we allow unicast and multicast
19495 			 * packets to go through the ill. It is
19496 			 * quite possible that the destination
19497 			 * is not in the ire cache table and we
19498 			 * do not want to go to ip_newroute()
19499 			 * instead we call ip_newroute_ipif.
19500 			 */
19501 			xmit_ill = conn_get_held_ill(connp,
19502 			    &connp->conn_xmit_if_ill, &err);
19503 			if (err == ILL_LOOKUP_FAILED) {
19504 				if (attach_ill != NULL)
19505 					ill_refrele(attach_ill);
19506 				if (need_decref)
19507 					CONN_DEC_REF(connp);
19508 				freemsg(first_mp);
19509 				return;
19510 			}
19511 			goto send_from_ill;
19512 		}
19513 standard_path:
19514 		/* Must be a broadcast, a loopback or a local ire */
19515 		if (ire != NULL) {
19516 			ire_refrele(ire);
19517 			/* No more access to ire */
19518 			ire = NULL;
19519 		}
19520 	}
19521 
19522 	if (attach_ill != NULL)
19523 		goto send_from_ill;
19524 
19525 	/*
19526 	 * We cache IRE_CACHEs to avoid lookups. We don't do
19527 	 * this for the tcp global queue and listen end point
19528 	 * as it does not really have a real destination to
19529 	 * talk to.  This is also true for SCTP.
19530 	 */
19531 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
19532 	    !connp->conn_fully_bound) {
19533 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19534 		if (ire == NULL)
19535 			goto noirefound;
19536 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19537 		    "ip_wput_end: q %p (%S)", q, "end");
19538 
19539 		/*
19540 		 * Check if the ire has the RTF_MULTIRT flag, inherited
19541 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19542 		 */
19543 		if (ire->ire_flags & RTF_MULTIRT) {
19544 
19545 			/*
19546 			 * Force the TTL of multirouted packets if required.
19547 			 * The TTL of such packets is bounded by the
19548 			 * ip_multirt_ttl ndd variable.
19549 			 */
19550 			if ((ip_multirt_ttl > 0) &&
19551 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
19552 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
19553 				    "(was %d), dst 0x%08x\n",
19554 				    ip_multirt_ttl, ipha->ipha_ttl,
19555 				    ntohl(ire->ire_addr)));
19556 				ipha->ipha_ttl = ip_multirt_ttl;
19557 			}
19558 			/*
19559 			 * We look at this point if there are pending
19560 			 * unresolved routes. ire_multirt_resolvable()
19561 			 * checks in O(n) that all IRE_OFFSUBNET ire
19562 			 * entries for the packet's destination and
19563 			 * flagged RTF_MULTIRT are currently resolved.
19564 			 * If some remain unresolved, we make a copy
19565 			 * of the current message. It will be used
19566 			 * to initiate additional route resolutions.
19567 			 */
19568 			multirt_need_resolve =
19569 			    ire_multirt_need_resolve(ire->ire_addr,
19570 			    MBLK_GETLABEL(first_mp));
19571 			ip2dbg(("ip_wput[TCP]: ire %p, "
19572 			    "multirt_need_resolve %d, first_mp %p\n",
19573 			    (void *)ire, multirt_need_resolve,
19574 			    (void *)first_mp));
19575 			if (multirt_need_resolve) {
19576 				copy_mp = copymsg(first_mp);
19577 				if (copy_mp != NULL) {
19578 					MULTIRT_DEBUG_TAG(copy_mp);
19579 				}
19580 			}
19581 		}
19582 
19583 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19584 
19585 		/*
19586 		 * Try to resolve another multiroute if
19587 		 * ire_multirt_need_resolve() deemed it necessary.
19588 		 */
19589 		if (copy_mp != NULL) {
19590 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19591 		}
19592 		if (need_decref)
19593 			CONN_DEC_REF(connp);
19594 		return;
19595 	}
19596 
19597 	/*
19598 	 * Access to conn_ire_cache. (protected by conn_lock)
19599 	 *
19600 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
19601 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
19602 	 * send a packet or two with the IRE_CACHE that is going away.
19603 	 * Access to the ire requires an ire refhold on the ire prior to
19604 	 * its use since an interface unplumb thread may delete the cached
19605 	 * ire and release the refhold at any time.
19606 	 *
19607 	 * Caching an ire in the conn_ire_cache
19608 	 *
19609 	 * o Caching an ire pointer in the conn requires a strict check for
19610 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
19611 	 * ires  before cleaning up the conns. So the caching of an ire pointer
19612 	 * in the conn is done after making sure under the bucket lock that the
19613 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
19614 	 * caching an ire after the unplumb thread has cleaned up the conn.
19615 	 * If the conn does not send a packet subsequently the unplumb thread
19616 	 * will be hanging waiting for the ire count to drop to zero.
19617 	 *
19618 	 * o We also need to atomically test for a null conn_ire_cache and
19619 	 * set the conn_ire_cache under the the protection of the conn_lock
19620 	 * to avoid races among concurrent threads trying to simultaneously
19621 	 * cache an ire in the conn_ire_cache.
19622 	 */
19623 	mutex_enter(&connp->conn_lock);
19624 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
19625 
19626 	if (ire != NULL && ire->ire_addr == dst &&
19627 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19628 
19629 		IRE_REFHOLD(ire);
19630 		mutex_exit(&connp->conn_lock);
19631 
19632 	} else {
19633 		boolean_t cached = B_FALSE;
19634 		connp->conn_ire_cache = NULL;
19635 		mutex_exit(&connp->conn_lock);
19636 		/* Release the old ire */
19637 		if (ire != NULL && sctp_ire == NULL)
19638 			IRE_REFRELE_NOTR(ire);
19639 
19640 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19641 		if (ire == NULL)
19642 			goto noirefound;
19643 		IRE_REFHOLD_NOTR(ire);
19644 
19645 		mutex_enter(&connp->conn_lock);
19646 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
19647 		    connp->conn_ire_cache == NULL) {
19648 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19649 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19650 				connp->conn_ire_cache = ire;
19651 				cached = B_TRUE;
19652 			}
19653 			rw_exit(&ire->ire_bucket->irb_lock);
19654 		}
19655 		mutex_exit(&connp->conn_lock);
19656 
19657 		/*
19658 		 * We can continue to use the ire but since it was
19659 		 * not cached, we should drop the extra reference.
19660 		 */
19661 		if (!cached)
19662 			IRE_REFRELE_NOTR(ire);
19663 	}
19664 
19665 
19666 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19667 	    "ip_wput_end: q %p (%S)", q, "end");
19668 
19669 	/*
19670 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19671 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19672 	 */
19673 	if (ire->ire_flags & RTF_MULTIRT) {
19674 
19675 		/*
19676 		 * Force the TTL of multirouted packets if required.
19677 		 * The TTL of such packets is bounded by the
19678 		 * ip_multirt_ttl ndd variable.
19679 		 */
19680 		if ((ip_multirt_ttl > 0) &&
19681 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19682 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19683 			    "(was %d), dst 0x%08x\n",
19684 			    ip_multirt_ttl, ipha->ipha_ttl,
19685 			    ntohl(ire->ire_addr)));
19686 			ipha->ipha_ttl = ip_multirt_ttl;
19687 		}
19688 
19689 		/*
19690 		 * At this point, we check to see if there are any pending
19691 		 * unresolved routes. ire_multirt_resolvable()
19692 		 * checks in O(n) that all IRE_OFFSUBNET ire
19693 		 * entries for the packet's destination and
19694 		 * flagged RTF_MULTIRT are currently resolved.
19695 		 * If some remain unresolved, we make a copy
19696 		 * of the current message. It will be used
19697 		 * to initiate additional route resolutions.
19698 		 */
19699 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19700 		    MBLK_GETLABEL(first_mp));
19701 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19702 		    "multirt_need_resolve %d, first_mp %p\n",
19703 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19704 		if (multirt_need_resolve) {
19705 			copy_mp = copymsg(first_mp);
19706 			if (copy_mp != NULL) {
19707 				MULTIRT_DEBUG_TAG(copy_mp);
19708 			}
19709 		}
19710 	}
19711 
19712 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19713 
19714 	/*
19715 	 * Try to resolve another multiroute if
19716 	 * ire_multirt_resolvable() deemed it necessary
19717 	 */
19718 	if (copy_mp != NULL) {
19719 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19720 	}
19721 	if (need_decref)
19722 		CONN_DEC_REF(connp);
19723 	return;
19724 
19725 qnext:
19726 	/*
19727 	 * Upper Level Protocols pass down complete IP datagrams
19728 	 * as M_DATA messages.	Everything else is a sideshow.
19729 	 *
19730 	 * 1) We could be re-entering ip_wput because of ip_neworute
19731 	 *    in which case we could have a IPSEC_OUT message. We
19732 	 *    need to pass through ip_wput like other datagrams and
19733 	 *    hence cannot branch to ip_wput_nondata.
19734 	 *
19735 	 * 2) ARP, AH, ESP, and other clients who are on the module
19736 	 *    instance of IP stream, give us something to deal with.
19737 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19738 	 *
19739 	 * 3) ICMP replies also could come here.
19740 	 */
19741 	if (DB_TYPE(mp) != M_DATA) {
19742 	    notdata:
19743 		if (DB_TYPE(mp) == M_CTL) {
19744 			/*
19745 			 * M_CTL messages are used by ARP, AH and ESP to
19746 			 * communicate with IP. We deal with IPSEC_IN and
19747 			 * IPSEC_OUT here. ip_wput_nondata handles other
19748 			 * cases.
19749 			 */
19750 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19751 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19752 				first_mp = mp->b_cont;
19753 				first_mp->b_flag &= ~MSGHASREF;
19754 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19755 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19756 				CONN_DEC_REF(connp);
19757 				connp = NULL;
19758 			}
19759 			if (ii->ipsec_info_type == IPSEC_IN) {
19760 				/*
19761 				 * Either this message goes back to
19762 				 * IPSEC for further processing or to
19763 				 * ULP after policy checks.
19764 				 */
19765 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19766 				return;
19767 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19768 				io = (ipsec_out_t *)ii;
19769 				if (io->ipsec_out_proc_begin) {
19770 					/*
19771 					 * IPSEC processing has already started.
19772 					 * Complete it.
19773 					 * IPQoS notes: We don't care what is
19774 					 * in ipsec_out_ill_index since this
19775 					 * won't be processed for IPQoS policies
19776 					 * in ipsec_out_process.
19777 					 */
19778 					ipsec_out_process(q, mp, NULL,
19779 					    io->ipsec_out_ill_index);
19780 					return;
19781 				} else {
19782 					connp = (q->q_next != NULL) ?
19783 					    NULL : Q_TO_CONN(q);
19784 					first_mp = mp;
19785 					mp = mp->b_cont;
19786 					mctl_present = B_TRUE;
19787 				}
19788 				zoneid = io->ipsec_out_zoneid;
19789 				ASSERT(zoneid != ALL_ZONES);
19790 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
19791 				/*
19792 				 * It's an IPsec control message requesting
19793 				 * an SADB update to be sent to the IPsec
19794 				 * hardware acceleration capable ills.
19795 				 */
19796 				ipsec_ctl_t *ipsec_ctl =
19797 				    (ipsec_ctl_t *)mp->b_rptr;
19798 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
19799 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
19800 				mblk_t *cmp = mp->b_cont;
19801 
19802 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
19803 				ASSERT(cmp != NULL);
19804 
19805 				freeb(mp);
19806 				ill_ipsec_capab_send_all(satype, cmp, sa);
19807 				return;
19808 			} else {
19809 				/*
19810 				 * This must be ARP or special TSOL signaling.
19811 				 */
19812 				ip_wput_nondata(NULL, q, mp, NULL);
19813 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19814 				    "ip_wput_end: q %p (%S)", q, "nondata");
19815 				return;
19816 			}
19817 		} else {
19818 			/*
19819 			 * This must be non-(ARP/AH/ESP) messages.
19820 			 */
19821 			ASSERT(!need_decref);
19822 			ip_wput_nondata(NULL, q, mp, NULL);
19823 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19824 			    "ip_wput_end: q %p (%S)", q, "nondata");
19825 			return;
19826 		}
19827 	} else {
19828 		first_mp = mp;
19829 		mctl_present = B_FALSE;
19830 	}
19831 
19832 	ASSERT(first_mp != NULL);
19833 	/*
19834 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
19835 	 * to make sure that this packet goes out on the same interface it
19836 	 * came in. We handle that here.
19837 	 */
19838 	if (mctl_present) {
19839 		uint_t ifindex;
19840 
19841 		io = (ipsec_out_t *)first_mp->b_rptr;
19842 		if (io->ipsec_out_attach_if ||
19843 		    io->ipsec_out_xmit_if ||
19844 		    io->ipsec_out_ip_nexthop) {
19845 			ill_t	*ill;
19846 
19847 			/*
19848 			 * We may have lost the conn context if we are
19849 			 * coming here from ip_newroute(). Copy the
19850 			 * nexthop information.
19851 			 */
19852 			if (io->ipsec_out_ip_nexthop) {
19853 				ip_nexthop = B_TRUE;
19854 				nexthop_addr = io->ipsec_out_nexthop_addr;
19855 
19856 				ipha = (ipha_t *)mp->b_rptr;
19857 				dst = ipha->ipha_dst;
19858 				goto send_from_ill;
19859 			} else {
19860 				ASSERT(io->ipsec_out_ill_index != 0);
19861 				ifindex = io->ipsec_out_ill_index;
19862 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
19863 				    NULL, NULL, NULL, NULL);
19864 				/*
19865 				 * ipsec_out_xmit_if bit is used to tell
19866 				 * ip_wput to use the ill to send outgoing data
19867 				 * as we have no conn when data comes from ICMP
19868 				 * error msg routines. Currently this feature is
19869 				 * only used by ip_mrtun_forward routine.
19870 				 */
19871 				if (io->ipsec_out_xmit_if) {
19872 					xmit_ill = ill;
19873 					if (xmit_ill == NULL) {
19874 						ip1dbg(("ip_output:bad ifindex "
19875 						    "for xmit_ill %d\n",
19876 						    ifindex));
19877 						freemsg(first_mp);
19878 						BUMP_MIB(&ip_mib,
19879 						    ipOutDiscards);
19880 						ASSERT(!need_decref);
19881 						return;
19882 					}
19883 					/* Free up the ipsec_out_t mblk */
19884 					ASSERT(first_mp->b_cont == mp);
19885 					first_mp->b_cont = NULL;
19886 					freeb(first_mp);
19887 					/* Just send the IP header+ICMP+data */
19888 					first_mp = mp;
19889 					ipha = (ipha_t *)mp->b_rptr;
19890 					dst = ipha->ipha_dst;
19891 					goto send_from_ill;
19892 				} else {
19893 					attach_ill = ill;
19894 				}
19895 
19896 				if (attach_ill == NULL) {
19897 					ASSERT(xmit_ill == NULL);
19898 					ip1dbg(("ip_output: bad ifindex for "
19899 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
19900 					    ifindex));
19901 					freemsg(first_mp);
19902 					BUMP_MIB(&ip_mib, ipOutDiscards);
19903 					ASSERT(!need_decref);
19904 					return;
19905 				}
19906 			}
19907 		}
19908 	}
19909 
19910 	ASSERT(xmit_ill == NULL);
19911 
19912 	/* We have a complete IP datagram heading outbound. */
19913 	ipha = (ipha_t *)mp->b_rptr;
19914 
19915 #ifndef SPEED_BEFORE_SAFETY
19916 	/*
19917 	 * Make sure we have a full-word aligned message and that at least
19918 	 * a simple IP header is accessible in the first message.  If not,
19919 	 * try a pullup.
19920 	 */
19921 	if (!OK_32PTR(rptr) ||
19922 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
19923 	    hdrtoosmall:
19924 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
19925 			BUMP_MIB(&ip_mib, ipOutDiscards);
19926 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19927 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
19928 			if (first_mp == NULL)
19929 				first_mp = mp;
19930 			goto drop_pkt;
19931 		}
19932 
19933 		/* This function assumes that mp points to an IPv4 packet. */
19934 		if (is_system_labeled() && q->q_next == NULL &&
19935 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
19936 		    !connp->conn_ulp_labeled) {
19937 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
19938 			    &adjust, connp->conn_mac_exempt);
19939 			ipha = (ipha_t *)mp->b_rptr;
19940 			if (first_mp != NULL)
19941 				first_mp->b_cont = mp;
19942 			if (err != 0) {
19943 				if (first_mp == NULL)
19944 					first_mp = mp;
19945 				if (err == EINVAL)
19946 					goto icmp_parameter_problem;
19947 				ip2dbg(("ip_wput: label check failed (%d)\n",
19948 				    err));
19949 				goto drop_pkt;
19950 			}
19951 			iplen = ntohs(ipha->ipha_length) + adjust;
19952 			ipha->ipha_length = htons(iplen);
19953 		}
19954 
19955 		ipha = (ipha_t *)mp->b_rptr;
19956 		if (first_mp == NULL) {
19957 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
19958 			/*
19959 			 * If we got here because of "goto hdrtoosmall"
19960 			 * We need to attach a IPSEC_OUT.
19961 			 */
19962 			if (connp->conn_out_enforce_policy) {
19963 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
19964 				    NULL, ipha->ipha_protocol)) == NULL)) {
19965 					if (need_decref)
19966 						CONN_DEC_REF(connp);
19967 					return;
19968 				} else {
19969 					ASSERT(mp->b_datap->db_type == M_CTL);
19970 					first_mp = mp;
19971 					mp = mp->b_cont;
19972 					mctl_present = B_TRUE;
19973 				}
19974 			} else {
19975 				first_mp = mp;
19976 				mctl_present = B_FALSE;
19977 			}
19978 		}
19979 	}
19980 #endif
19981 
19982 	/* Most of the code below is written for speed, not readability */
19983 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19984 
19985 	/*
19986 	 * If ip_newroute() fails, we're going to need a full
19987 	 * header for the icmp wraparound.
19988 	 */
19989 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
19990 		uint_t	v_hlen;
19991 	    version_hdrlen_check:
19992 		ASSERT(first_mp != NULL);
19993 		v_hlen = V_HLEN;
19994 		/*
19995 		 * siphon off IPv6 packets coming down from transport
19996 		 * layer modules here.
19997 		 * Note: high-order bit carries NUD reachability confirmation
19998 		 */
19999 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20000 			/*
20001 			 * XXX implement a IPv4 and IPv6 packet counter per
20002 			 * conn and switch when ratio exceeds e.g. 10:1
20003 			 */
20004 #ifdef notyet
20005 			if (q->q_next == NULL) /* Avoid ill queue */
20006 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
20007 #endif
20008 			BUMP_MIB(&ip_mib, ipOutIPv6);
20009 			ASSERT(xmit_ill == NULL);
20010 			if (attach_ill != NULL)
20011 				ill_refrele(attach_ill);
20012 			if (need_decref)
20013 				mp->b_flag |= MSGHASREF;
20014 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20015 			return;
20016 		}
20017 
20018 		if ((v_hlen >> 4) != IP_VERSION) {
20019 			BUMP_MIB(&ip_mib, ipOutDiscards);
20020 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20021 			    "ip_wput_end: q %p (%S)", q, "badvers");
20022 			goto drop_pkt;
20023 		}
20024 		/*
20025 		 * Is the header length at least 20 bytes?
20026 		 *
20027 		 * Are there enough bytes accessible in the header?  If
20028 		 * not, try a pullup.
20029 		 */
20030 		v_hlen &= 0xF;
20031 		v_hlen <<= 2;
20032 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20033 			BUMP_MIB(&ip_mib, ipOutDiscards);
20034 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20035 			    "ip_wput_end: q %p (%S)", q, "badlen");
20036 			goto drop_pkt;
20037 		}
20038 		if (v_hlen > (mp->b_wptr - rptr)) {
20039 			if (!pullupmsg(mp, v_hlen)) {
20040 				BUMP_MIB(&ip_mib, ipOutDiscards);
20041 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20042 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20043 				goto drop_pkt;
20044 			}
20045 			ipha = (ipha_t *)mp->b_rptr;
20046 		}
20047 		/*
20048 		 * Move first entry from any source route into ipha_dst and
20049 		 * verify the options
20050 		 */
20051 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
20052 			ASSERT(xmit_ill == NULL);
20053 			if (attach_ill != NULL)
20054 				ill_refrele(attach_ill);
20055 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20056 			    "ip_wput_end: q %p (%S)", q, "badopts");
20057 			if (need_decref)
20058 				CONN_DEC_REF(connp);
20059 			return;
20060 		}
20061 	}
20062 	dst = ipha->ipha_dst;
20063 
20064 	/*
20065 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20066 	 * we have to run the packet through ip_newroute which will take
20067 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20068 	 * a resolver, or assigning a default gateway, etc.
20069 	 */
20070 	if (CLASSD(dst)) {
20071 		ipif_t	*ipif;
20072 		uint32_t setsrc = 0;
20073 
20074 	    multicast:
20075 		ASSERT(first_mp != NULL);
20076 		ASSERT(xmit_ill == NULL);
20077 		ip2dbg(("ip_wput: CLASSD\n"));
20078 		if (connp == NULL) {
20079 			/*
20080 			 * Use the first good ipif on the ill.
20081 			 * XXX Should this ever happen? (Appears
20082 			 * to show up with just ppp and no ethernet due
20083 			 * to in.rdisc.)
20084 			 * However, ire_send should be able to
20085 			 * call ip_wput_ire directly.
20086 			 *
20087 			 * XXX Also, this can happen for ICMP and other packets
20088 			 * with multicast source addresses.  Perhaps we should
20089 			 * fix things so that we drop the packet in question,
20090 			 * but for now, just run with it.
20091 			 */
20092 			ill_t *ill = (ill_t *)q->q_ptr;
20093 
20094 			/*
20095 			 * Don't honor attach_if for this case. If ill
20096 			 * is part of the group, ipif could belong to
20097 			 * any ill and we cannot maintain attach_ill
20098 			 * and ipif_ill same anymore and the assert
20099 			 * below would fail.
20100 			 */
20101 			if (mctl_present) {
20102 				io->ipsec_out_ill_index = 0;
20103 				io->ipsec_out_attach_if = B_FALSE;
20104 				ASSERT(attach_ill != NULL);
20105 				ill_refrele(attach_ill);
20106 				attach_ill = NULL;
20107 			}
20108 
20109 			ASSERT(attach_ill == NULL);
20110 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20111 			if (ipif == NULL) {
20112 				if (need_decref)
20113 					CONN_DEC_REF(connp);
20114 				freemsg(first_mp);
20115 				return;
20116 			}
20117 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20118 			    ntohl(dst), ill->ill_name));
20119 		} else {
20120 			/*
20121 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
20122 			 * IP_XMIT_IF is honoured.
20123 			 * Block comment above this function explains the
20124 			 * locking mechanism used here
20125 			 */
20126 			xmit_ill = conn_get_held_ill(connp,
20127 			    &connp->conn_xmit_if_ill, &err);
20128 			if (err == ILL_LOOKUP_FAILED) {
20129 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
20130 				goto drop_pkt;
20131 			}
20132 			if (xmit_ill == NULL) {
20133 				ipif = conn_get_held_ipif(connp,
20134 				    &connp->conn_multicast_ipif, &err);
20135 				if (err == IPIF_LOOKUP_FAILED) {
20136 					ip1dbg(("ip_wput: No ipif for "
20137 					    "multicast\n"));
20138 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20139 					goto drop_pkt;
20140 				}
20141 			}
20142 			if (xmit_ill != NULL) {
20143 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20144 				if (ipif == NULL) {
20145 					ip1dbg(("ip_wput: No ipif for "
20146 					    "IP_XMIT_IF\n"));
20147 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20148 					goto drop_pkt;
20149 				}
20150 			} else if (ipif == NULL || ipif->ipif_isv6) {
20151 				/*
20152 				 * We must do this ipif determination here
20153 				 * else we could pass through ip_newroute
20154 				 * and come back here without the conn context.
20155 				 *
20156 				 * Note: we do late binding i.e. we bind to
20157 				 * the interface when the first packet is sent.
20158 				 * For performance reasons we do not rebind on
20159 				 * each packet but keep the binding until the
20160 				 * next IP_MULTICAST_IF option.
20161 				 *
20162 				 * conn_multicast_{ipif,ill} are shared between
20163 				 * IPv4 and IPv6 and AF_INET6 sockets can
20164 				 * send both IPv4 and IPv6 packets. Hence
20165 				 * we have to check that "isv6" matches above.
20166 				 */
20167 				if (ipif != NULL)
20168 					ipif_refrele(ipif);
20169 				ipif = ipif_lookup_group(dst, zoneid);
20170 				if (ipif == NULL) {
20171 					ip1dbg(("ip_wput: No ipif for "
20172 					    "multicast\n"));
20173 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20174 					goto drop_pkt;
20175 				}
20176 				err = conn_set_held_ipif(connp,
20177 				    &connp->conn_multicast_ipif, ipif);
20178 				if (err == IPIF_LOOKUP_FAILED) {
20179 					ipif_refrele(ipif);
20180 					ip1dbg(("ip_wput: No ipif for "
20181 					    "multicast\n"));
20182 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20183 					goto drop_pkt;
20184 				}
20185 			}
20186 		}
20187 		ASSERT(!ipif->ipif_isv6);
20188 		/*
20189 		 * As we may lose the conn by the time we reach ip_wput_ire,
20190 		 * we copy conn_multicast_loop and conn_dontroute on to an
20191 		 * ipsec_out. In case if this datagram goes out secure,
20192 		 * we need the ill_index also. Copy that also into the
20193 		 * ipsec_out.
20194 		 */
20195 		if (mctl_present) {
20196 			io = (ipsec_out_t *)first_mp->b_rptr;
20197 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20198 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20199 		} else {
20200 			ASSERT(mp == first_mp);
20201 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20202 			    BPRI_HI)) == NULL) {
20203 				ipif_refrele(ipif);
20204 				first_mp = mp;
20205 				goto drop_pkt;
20206 			}
20207 			first_mp->b_datap->db_type = M_CTL;
20208 			first_mp->b_wptr += sizeof (ipsec_info_t);
20209 			/* ipsec_out_secure is B_FALSE now */
20210 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20211 			io = (ipsec_out_t *)first_mp->b_rptr;
20212 			io->ipsec_out_type = IPSEC_OUT;
20213 			io->ipsec_out_len = sizeof (ipsec_out_t);
20214 			io->ipsec_out_use_global_policy = B_TRUE;
20215 			first_mp->b_cont = mp;
20216 			mctl_present = B_TRUE;
20217 		}
20218 		if (attach_ill != NULL) {
20219 			ASSERT(attach_ill == ipif->ipif_ill);
20220 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20221 
20222 			/*
20223 			 * Check if we need an ire that will not be
20224 			 * looked up by anybody else i.e. HIDDEN.
20225 			 */
20226 			if (ill_is_probeonly(attach_ill)) {
20227 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20228 			}
20229 			io->ipsec_out_ill_index =
20230 			    attach_ill->ill_phyint->phyint_ifindex;
20231 			io->ipsec_out_attach_if = B_TRUE;
20232 		} else {
20233 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20234 			io->ipsec_out_ill_index =
20235 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20236 		}
20237 		if (connp != NULL) {
20238 			io->ipsec_out_multicast_loop =
20239 			    connp->conn_multicast_loop;
20240 			io->ipsec_out_dontroute = connp->conn_dontroute;
20241 			io->ipsec_out_zoneid = connp->conn_zoneid;
20242 		}
20243 		/*
20244 		 * If the application uses IP_MULTICAST_IF with
20245 		 * different logical addresses of the same ILL, we
20246 		 * need to make sure that the soruce address of
20247 		 * the packet matches the logical IP address used
20248 		 * in the option. We do it by initializing ipha_src
20249 		 * here. This should keep IPSEC also happy as
20250 		 * when we return from IPSEC processing, we don't
20251 		 * have to worry about getting the right address on
20252 		 * the packet. Thus it is sufficient to look for
20253 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20254 		 * MATCH_IRE_IPIF.
20255 		 *
20256 		 * NOTE : We need to do it for non-secure case also as
20257 		 * this might go out secure if there is a global policy
20258 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20259 		 * address, the source should be initialized already and
20260 		 * hence we won't be initializing here.
20261 		 *
20262 		 * As we do not have the ire yet, it is possible that
20263 		 * we set the source address here and then later discover
20264 		 * that the ire implies the source address to be assigned
20265 		 * through the RTF_SETSRC flag.
20266 		 * In that case, the setsrc variable will remind us
20267 		 * that overwritting the source address by the one
20268 		 * of the RTF_SETSRC-flagged ire is allowed.
20269 		 */
20270 		if (ipha->ipha_src == INADDR_ANY &&
20271 		    (connp == NULL || !connp->conn_unspec_src)) {
20272 			ipha->ipha_src = ipif->ipif_src_addr;
20273 			setsrc = RTF_SETSRC;
20274 		}
20275 		/*
20276 		 * Find an IRE which matches the destination and the outgoing
20277 		 * queue (i.e. the outgoing interface.)
20278 		 * For loopback use a unicast IP address for
20279 		 * the ire lookup.
20280 		 */
20281 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20282 		    PHYI_LOOPBACK) {
20283 			dst = ipif->ipif_lcl_addr;
20284 		}
20285 		/*
20286 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20287 		 * We don't need to lookup ire in ctable as the packet
20288 		 * needs to be sent to the destination through the specified
20289 		 * ill irrespective of ires in the cache table.
20290 		 */
20291 		ire = NULL;
20292 		if (xmit_ill == NULL) {
20293 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20294 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20295 		}
20296 
20297 		/*
20298 		 * refrele attach_ill as its not needed anymore.
20299 		 */
20300 		if (attach_ill != NULL) {
20301 			ill_refrele(attach_ill);
20302 			attach_ill = NULL;
20303 		}
20304 
20305 		if (ire == NULL) {
20306 			/*
20307 			 * Multicast loopback and multicast forwarding is
20308 			 * done in ip_wput_ire.
20309 			 *
20310 			 * Mark this packet to make it be delivered to
20311 			 * ip_wput_ire after the new ire has been
20312 			 * created.
20313 			 *
20314 			 * The call to ip_newroute_ipif takes into account
20315 			 * the setsrc reminder. In any case, we take care
20316 			 * of the RTF_MULTIRT flag.
20317 			 */
20318 			mp->b_prev = mp->b_next = NULL;
20319 			if (xmit_ill == NULL ||
20320 			    xmit_ill->ill_ipif_up_count > 0) {
20321 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20322 				    setsrc | RTF_MULTIRT, zoneid);
20323 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20324 				    "ip_wput_end: q %p (%S)", q, "noire");
20325 			} else {
20326 				freemsg(first_mp);
20327 			}
20328 			ipif_refrele(ipif);
20329 			if (xmit_ill != NULL)
20330 				ill_refrele(xmit_ill);
20331 			if (need_decref)
20332 				CONN_DEC_REF(connp);
20333 			return;
20334 		}
20335 
20336 		ipif_refrele(ipif);
20337 		ipif = NULL;
20338 		ASSERT(xmit_ill == NULL);
20339 
20340 		/*
20341 		 * Honor the RTF_SETSRC flag for multicast packets,
20342 		 * if allowed by the setsrc reminder.
20343 		 */
20344 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20345 			ipha->ipha_src = ire->ire_src_addr;
20346 		}
20347 
20348 		/*
20349 		 * Unconditionally force the TTL to 1 for
20350 		 * multirouted multicast packets:
20351 		 * multirouted multicast should not cross
20352 		 * multicast routers.
20353 		 */
20354 		if (ire->ire_flags & RTF_MULTIRT) {
20355 			if (ipha->ipha_ttl > 1) {
20356 				ip2dbg(("ip_wput: forcing multicast "
20357 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20358 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20359 				ipha->ipha_ttl = 1;
20360 			}
20361 		}
20362 	} else {
20363 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20364 		if ((ire != NULL) && (ire->ire_type &
20365 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20366 			ignore_dontroute = B_TRUE;
20367 			ignore_nexthop = B_TRUE;
20368 		}
20369 		if (ire != NULL) {
20370 			ire_refrele(ire);
20371 			ire = NULL;
20372 		}
20373 		/*
20374 		 * Guard against coming in from arp in which case conn is NULL.
20375 		 * Also guard against non M_DATA with dontroute set but
20376 		 * destined to local, loopback or broadcast addresses.
20377 		 */
20378 		if (connp != NULL && connp->conn_dontroute &&
20379 		    !ignore_dontroute) {
20380 dontroute:
20381 			/*
20382 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20383 			 * routing protocols from seeing false direct
20384 			 * connectivity.
20385 			 */
20386 			ipha->ipha_ttl = 1;
20387 			/*
20388 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20389 			 * along with SO_DONTROUTE, higher precedence is
20390 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20391 			 */
20392 			if (connp->conn_xmit_if_ill == NULL) {
20393 				/* If suitable ipif not found, drop packet */
20394 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20395 				if (dst_ipif == NULL) {
20396 					ip1dbg(("ip_wput: no route for "
20397 					    "dst using SO_DONTROUTE\n"));
20398 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20399 					mp->b_prev = mp->b_next = NULL;
20400 					if (first_mp == NULL)
20401 						first_mp = mp;
20402 					goto drop_pkt;
20403 				} else {
20404 					/*
20405 					 * If suitable ipif has been found, set
20406 					 * xmit_ill to the corresponding
20407 					 * ipif_ill because we'll be following
20408 					 * the IP_XMIT_IF logic.
20409 					 */
20410 					ASSERT(xmit_ill == NULL);
20411 					xmit_ill = dst_ipif->ipif_ill;
20412 					mutex_enter(&xmit_ill->ill_lock);
20413 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20414 						mutex_exit(&xmit_ill->ill_lock);
20415 						xmit_ill = NULL;
20416 						ipif_refrele(dst_ipif);
20417 						ip1dbg(("ip_wput: no route for"
20418 						    " dst using"
20419 						    " SO_DONTROUTE\n"));
20420 						BUMP_MIB(&ip_mib,
20421 						    ipOutNoRoutes);
20422 						mp->b_prev = mp->b_next = NULL;
20423 						if (first_mp == NULL)
20424 							first_mp = mp;
20425 						goto drop_pkt;
20426 					}
20427 					ill_refhold_locked(xmit_ill);
20428 					mutex_exit(&xmit_ill->ill_lock);
20429 					ipif_refrele(dst_ipif);
20430 				}
20431 			}
20432 
20433 		}
20434 		/*
20435 		 * If we are bound to IPIF_NOFAILOVER address, look for
20436 		 * an IRE_CACHE matching the ill.
20437 		 */
20438 send_from_ill:
20439 		if (attach_ill != NULL) {
20440 			ipif_t	*attach_ipif;
20441 
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 
20452 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20453 			if (attach_ipif == NULL) {
20454 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20455 				goto drop_pkt;
20456 			}
20457 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20458 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20459 			ipif_refrele(attach_ipif);
20460 		} else if (xmit_ill != NULL || (connp != NULL &&
20461 			    connp->conn_xmit_if_ill != NULL)) {
20462 			/*
20463 			 * Mark this packet as originated locally
20464 			 */
20465 			mp->b_prev = mp->b_next = NULL;
20466 			/*
20467 			 * xmit_ill could be NULL if SO_DONTROUTE
20468 			 * is also set.
20469 			 */
20470 			if (xmit_ill == NULL) {
20471 				xmit_ill = conn_get_held_ill(connp,
20472 				    &connp->conn_xmit_if_ill, &err);
20473 				if (err == ILL_LOOKUP_FAILED) {
20474 					if (need_decref)
20475 						CONN_DEC_REF(connp);
20476 					freemsg(first_mp);
20477 					return;
20478 				}
20479 				if (xmit_ill == NULL) {
20480 					if (connp->conn_dontroute)
20481 						goto dontroute;
20482 					goto send_from_ill;
20483 				}
20484 			}
20485 			/*
20486 			 * could be SO_DONTROUTE case also.
20487 			 * check at least one interface is UP as
20488 			 * spcified by this ILL, and then call
20489 			 * ip_newroute_ipif()
20490 			 */
20491 			if (xmit_ill->ill_ipif_up_count > 0) {
20492 				ipif_t *ipif;
20493 
20494 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20495 				if (ipif != NULL) {
20496 					ip_newroute_ipif(q, first_mp, ipif,
20497 					    dst, connp, 0, zoneid);
20498 					ipif_refrele(ipif);
20499 					ip1dbg(("ip_wput: ip_unicast_if\n"));
20500 				}
20501 			} else {
20502 				freemsg(first_mp);
20503 			}
20504 			ill_refrele(xmit_ill);
20505 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20506 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
20507 			if (need_decref)
20508 				CONN_DEC_REF(connp);
20509 			return;
20510 		} else if (ip_nexthop || (connp != NULL &&
20511 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
20512 			if (!ip_nexthop) {
20513 				ip_nexthop = B_TRUE;
20514 				nexthop_addr = connp->conn_nexthop_v4;
20515 			}
20516 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
20517 			    MATCH_IRE_GW;
20518 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
20519 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
20520 		} else {
20521 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20522 		}
20523 		if (!ire) {
20524 			/*
20525 			 * Make sure we don't load spread if this
20526 			 * is IPIF_NOFAILOVER case.
20527 			 */
20528 			if ((attach_ill != NULL) ||
20529 			    (ip_nexthop && !ignore_nexthop)) {
20530 				if (mctl_present) {
20531 					io = (ipsec_out_t *)first_mp->b_rptr;
20532 					ASSERT(first_mp->b_datap->db_type ==
20533 					    M_CTL);
20534 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
20535 				} else {
20536 					ASSERT(mp == first_mp);
20537 					first_mp = allocb(
20538 					    sizeof (ipsec_info_t), BPRI_HI);
20539 					if (first_mp == NULL) {
20540 						first_mp = mp;
20541 						goto drop_pkt;
20542 					}
20543 					first_mp->b_datap->db_type = M_CTL;
20544 					first_mp->b_wptr +=
20545 					    sizeof (ipsec_info_t);
20546 					/* ipsec_out_secure is B_FALSE now */
20547 					bzero(first_mp->b_rptr,
20548 					    sizeof (ipsec_info_t));
20549 					io = (ipsec_out_t *)first_mp->b_rptr;
20550 					io->ipsec_out_type = IPSEC_OUT;
20551 					io->ipsec_out_len =
20552 					    sizeof (ipsec_out_t);
20553 					io->ipsec_out_use_global_policy =
20554 					    B_TRUE;
20555 					first_mp->b_cont = mp;
20556 					mctl_present = B_TRUE;
20557 				}
20558 				if (attach_ill != NULL) {
20559 					io->ipsec_out_ill_index = attach_ill->
20560 					    ill_phyint->phyint_ifindex;
20561 					io->ipsec_out_attach_if = B_TRUE;
20562 				} else {
20563 					io->ipsec_out_ip_nexthop = ip_nexthop;
20564 					io->ipsec_out_nexthop_addr =
20565 					    nexthop_addr;
20566 				}
20567 			}
20568 noirefound:
20569 			/*
20570 			 * Mark this packet as having originated on
20571 			 * this machine.  This will be noted in
20572 			 * ire_add_then_send, which needs to know
20573 			 * whether to run it back through ip_wput or
20574 			 * ip_rput following successful resolution.
20575 			 */
20576 			mp->b_prev = NULL;
20577 			mp->b_next = NULL;
20578 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid);
20579 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20580 			    "ip_wput_end: q %p (%S)", q, "newroute");
20581 			if (attach_ill != NULL)
20582 				ill_refrele(attach_ill);
20583 			if (xmit_ill != NULL)
20584 				ill_refrele(xmit_ill);
20585 			if (need_decref)
20586 				CONN_DEC_REF(connp);
20587 			return;
20588 		}
20589 	}
20590 
20591 	/* We now know where we are going with it. */
20592 
20593 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20594 	    "ip_wput_end: q %p (%S)", q, "end");
20595 
20596 	/*
20597 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20598 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
20599 	 */
20600 	if (ire->ire_flags & RTF_MULTIRT) {
20601 		/*
20602 		 * Force the TTL of multirouted packets if required.
20603 		 * The TTL of such packets is bounded by the
20604 		 * ip_multirt_ttl ndd variable.
20605 		 */
20606 		if ((ip_multirt_ttl > 0) &&
20607 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20608 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20609 			    "(was %d), dst 0x%08x\n",
20610 			    ip_multirt_ttl, ipha->ipha_ttl,
20611 			    ntohl(ire->ire_addr)));
20612 			ipha->ipha_ttl = ip_multirt_ttl;
20613 		}
20614 		/*
20615 		 * At this point, we check to see if there are any pending
20616 		 * unresolved routes. ire_multirt_resolvable()
20617 		 * checks in O(n) that all IRE_OFFSUBNET ire
20618 		 * entries for the packet's destination and
20619 		 * flagged RTF_MULTIRT are currently resolved.
20620 		 * If some remain unresolved, we make a copy
20621 		 * of the current message. It will be used
20622 		 * to initiate additional route resolutions.
20623 		 */
20624 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20625 		    MBLK_GETLABEL(first_mp));
20626 		ip2dbg(("ip_wput[noirefound]: ire %p, "
20627 		    "multirt_need_resolve %d, first_mp %p\n",
20628 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20629 		if (multirt_need_resolve) {
20630 			copy_mp = copymsg(first_mp);
20631 			if (copy_mp != NULL) {
20632 				MULTIRT_DEBUG_TAG(copy_mp);
20633 			}
20634 		}
20635 	}
20636 
20637 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20638 	/*
20639 	 * Try to resolve another multiroute if
20640 	 * ire_multirt_resolvable() deemed it necessary.
20641 	 * At this point, we need to distinguish
20642 	 * multicasts from other packets. For multicasts,
20643 	 * we call ip_newroute_ipif() and request that both
20644 	 * multirouting and setsrc flags are checked.
20645 	 */
20646 	if (copy_mp != NULL) {
20647 		if (CLASSD(dst)) {
20648 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
20649 			if (ipif) {
20650 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
20651 				    RTF_SETSRC | RTF_MULTIRT, zoneid);
20652 				ipif_refrele(ipif);
20653 			} else {
20654 				MULTIRT_DEBUG_UNTAG(copy_mp);
20655 				freemsg(copy_mp);
20656 				copy_mp = NULL;
20657 			}
20658 		} else {
20659 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20660 		}
20661 	}
20662 	if (attach_ill != NULL)
20663 		ill_refrele(attach_ill);
20664 	if (xmit_ill != NULL)
20665 		ill_refrele(xmit_ill);
20666 	if (need_decref)
20667 		CONN_DEC_REF(connp);
20668 	return;
20669 
20670 icmp_parameter_problem:
20671 	/* could not have originated externally */
20672 	ASSERT(mp->b_prev == NULL);
20673 	if (ip_hdr_complete(ipha, zoneid) == 0) {
20674 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
20675 		/* it's the IP header length that's in trouble */
20676 		icmp_param_problem(q, first_mp, 0, zoneid);
20677 		first_mp = NULL;
20678 	}
20679 
20680 drop_pkt:
20681 	ip1dbg(("ip_wput: dropped packet\n"));
20682 	if (ire != NULL)
20683 		ire_refrele(ire);
20684 	if (need_decref)
20685 		CONN_DEC_REF(connp);
20686 	freemsg(first_mp);
20687 	if (attach_ill != NULL)
20688 		ill_refrele(attach_ill);
20689 	if (xmit_ill != NULL)
20690 		ill_refrele(xmit_ill);
20691 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20692 	    "ip_wput_end: q %p (%S)", q, "droppkt");
20693 }
20694 
20695 /*
20696  * If this is a conn_t queue, then we pass in the conn. This includes the
20697  * zoneid.
20698  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
20699  * in which case we use the global zoneid since those are all part of
20700  * the global zone.
20701  */
20702 void
20703 ip_wput(queue_t *q, mblk_t *mp)
20704 {
20705 	if (CONN_Q(q))
20706 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20707 	else
20708 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
20709 }
20710 
20711 /*
20712  *
20713  * The following rules must be observed when accessing any ipif or ill
20714  * that has been cached in the conn. Typically conn_nofailover_ill,
20715  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20716  *
20717  * Access: The ipif or ill pointed to from the conn can be accessed under
20718  * the protection of the conn_lock or after it has been refheld under the
20719  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20720  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20721  * The reason for this is that a concurrent unplumb could actually be
20722  * cleaning up these cached pointers by walking the conns and might have
20723  * finished cleaning up the conn in question. The macros check that an
20724  * unplumb has not yet started on the ipif or ill.
20725  *
20726  * Caching: An ipif or ill pointer may be cached in the conn only after
20727  * making sure that an unplumb has not started. So the caching is done
20728  * while holding both the conn_lock and the ill_lock and after using the
20729  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20730  * flag before starting the cleanup of conns.
20731  *
20732  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20733  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20734  * or a reference to the ipif or a reference to an ire that references the
20735  * ipif. An ipif does not change its ill except for failover/failback. Since
20736  * failover/failback happens only after bringing down the ipif and making sure
20737  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20738  * the above holds.
20739  */
20740 ipif_t *
20741 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20742 {
20743 	ipif_t	*ipif;
20744 	ill_t	*ill;
20745 
20746 	*err = 0;
20747 	rw_enter(&ill_g_lock, RW_READER);
20748 	mutex_enter(&connp->conn_lock);
20749 	ipif = *ipifp;
20750 	if (ipif != NULL) {
20751 		ill = ipif->ipif_ill;
20752 		mutex_enter(&ill->ill_lock);
20753 		if (IPIF_CAN_LOOKUP(ipif)) {
20754 			ipif_refhold_locked(ipif);
20755 			mutex_exit(&ill->ill_lock);
20756 			mutex_exit(&connp->conn_lock);
20757 			rw_exit(&ill_g_lock);
20758 			return (ipif);
20759 		} else {
20760 			*err = IPIF_LOOKUP_FAILED;
20761 		}
20762 		mutex_exit(&ill->ill_lock);
20763 	}
20764 	mutex_exit(&connp->conn_lock);
20765 	rw_exit(&ill_g_lock);
20766 	return (NULL);
20767 }
20768 
20769 ill_t *
20770 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20771 {
20772 	ill_t	*ill;
20773 
20774 	*err = 0;
20775 	mutex_enter(&connp->conn_lock);
20776 	ill = *illp;
20777 	if (ill != NULL) {
20778 		mutex_enter(&ill->ill_lock);
20779 		if (ILL_CAN_LOOKUP(ill)) {
20780 			ill_refhold_locked(ill);
20781 			mutex_exit(&ill->ill_lock);
20782 			mutex_exit(&connp->conn_lock);
20783 			return (ill);
20784 		} else {
20785 			*err = ILL_LOOKUP_FAILED;
20786 		}
20787 		mutex_exit(&ill->ill_lock);
20788 	}
20789 	mutex_exit(&connp->conn_lock);
20790 	return (NULL);
20791 }
20792 
20793 static int
20794 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
20795 {
20796 	ill_t	*ill;
20797 
20798 	ill = ipif->ipif_ill;
20799 	mutex_enter(&connp->conn_lock);
20800 	mutex_enter(&ill->ill_lock);
20801 	if (IPIF_CAN_LOOKUP(ipif)) {
20802 		*ipifp = ipif;
20803 		mutex_exit(&ill->ill_lock);
20804 		mutex_exit(&connp->conn_lock);
20805 		return (0);
20806 	}
20807 	mutex_exit(&ill->ill_lock);
20808 	mutex_exit(&connp->conn_lock);
20809 	return (IPIF_LOOKUP_FAILED);
20810 }
20811 
20812 /*
20813  * This is called if the outbound datagram needs fragmentation.
20814  *
20815  * NOTE : This function does not ire_refrele the ire argument passed in.
20816  */
20817 static void
20818 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid)
20819 {
20820 	ipha_t		*ipha;
20821 	mblk_t		*mp;
20822 	uint32_t	v_hlen_tos_len;
20823 	uint32_t	max_frag;
20824 	uint32_t	frag_flag;
20825 	boolean_t	dont_use;
20826 
20827 	if (ipsec_mp->b_datap->db_type == M_CTL) {
20828 		mp = ipsec_mp->b_cont;
20829 	} else {
20830 		mp = ipsec_mp;
20831 	}
20832 
20833 	ipha = (ipha_t *)mp->b_rptr;
20834 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20835 
20836 #ifdef	_BIG_ENDIAN
20837 #define	V_HLEN	(v_hlen_tos_len >> 24)
20838 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20839 #else
20840 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20841 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20842 #endif
20843 
20844 #ifndef SPEED_BEFORE_SAFETY
20845 	/*
20846 	 * Check that ipha_length is consistent with
20847 	 * the mblk length
20848 	 */
20849 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
20850 		ip0dbg(("Packet length mismatch: %d, %ld\n",
20851 		    LENGTH, msgdsize(mp)));
20852 		freemsg(ipsec_mp);
20853 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20854 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
20855 		    "packet length mismatch");
20856 		return;
20857 	}
20858 #endif
20859 	/*
20860 	 * Don't use frag_flag if pre-built packet or source
20861 	 * routed or if multicast (since multicast packets do not solicit
20862 	 * ICMP "packet too big" messages). Get the values of
20863 	 * max_frag and frag_flag atomically by acquiring the
20864 	 * ire_lock.
20865 	 */
20866 	mutex_enter(&ire->ire_lock);
20867 	max_frag = ire->ire_max_frag;
20868 	frag_flag = ire->ire_frag_flag;
20869 	mutex_exit(&ire->ire_lock);
20870 
20871 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
20872 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
20873 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
20874 
20875 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
20876 	    (dont_use ? 0 : frag_flag), zoneid);
20877 }
20878 
20879 /*
20880  * Used for deciding the MSS size for the upper layer. Thus
20881  * we need to check the outbound policy values in the conn.
20882  */
20883 int
20884 conn_ipsec_length(conn_t *connp)
20885 {
20886 	ipsec_latch_t *ipl;
20887 
20888 	ipl = connp->conn_latch;
20889 	if (ipl == NULL)
20890 		return (0);
20891 
20892 	if (ipl->ipl_out_policy == NULL)
20893 		return (0);
20894 
20895 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
20896 }
20897 
20898 /*
20899  * Returns an estimate of the IPSEC headers size. This is used if
20900  * we don't want to call into IPSEC to get the exact size.
20901  */
20902 int
20903 ipsec_out_extra_length(mblk_t *ipsec_mp)
20904 {
20905 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
20906 	ipsec_action_t *a;
20907 
20908 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
20909 	if (!io->ipsec_out_secure)
20910 		return (0);
20911 
20912 	a = io->ipsec_out_act;
20913 
20914 	if (a == NULL) {
20915 		ASSERT(io->ipsec_out_policy != NULL);
20916 		a = io->ipsec_out_policy->ipsp_act;
20917 	}
20918 	ASSERT(a != NULL);
20919 
20920 	return (a->ipa_ovhd);
20921 }
20922 
20923 /*
20924  * Returns an estimate of the IPSEC headers size. This is used if
20925  * we don't want to call into IPSEC to get the exact size.
20926  */
20927 int
20928 ipsec_in_extra_length(mblk_t *ipsec_mp)
20929 {
20930 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
20931 	ipsec_action_t *a;
20932 
20933 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
20934 
20935 	a = ii->ipsec_in_action;
20936 	return (a == NULL ? 0 : a->ipa_ovhd);
20937 }
20938 
20939 /*
20940  * If there are any source route options, return the true final
20941  * destination. Otherwise, return the destination.
20942  */
20943 ipaddr_t
20944 ip_get_dst(ipha_t *ipha)
20945 {
20946 	ipoptp_t	opts;
20947 	uchar_t		*opt;
20948 	uint8_t		optval;
20949 	uint8_t		optlen;
20950 	ipaddr_t	dst;
20951 	uint32_t off;
20952 
20953 	dst = ipha->ipha_dst;
20954 
20955 	if (IS_SIMPLE_IPH(ipha))
20956 		return (dst);
20957 
20958 	for (optval = ipoptp_first(&opts, ipha);
20959 	    optval != IPOPT_EOL;
20960 	    optval = ipoptp_next(&opts)) {
20961 		opt = opts.ipoptp_cur;
20962 		optlen = opts.ipoptp_len;
20963 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20964 		switch (optval) {
20965 		case IPOPT_SSRR:
20966 		case IPOPT_LSRR:
20967 			off = opt[IPOPT_OFFSET];
20968 			/*
20969 			 * If one of the conditions is true, it means
20970 			 * end of options and dst already has the right
20971 			 * value.
20972 			 */
20973 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
20974 				off = optlen - IP_ADDR_LEN;
20975 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
20976 			}
20977 			return (dst);
20978 		default:
20979 			break;
20980 		}
20981 	}
20982 
20983 	return (dst);
20984 }
20985 
20986 mblk_t *
20987 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
20988     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
20989 {
20990 	ipsec_out_t	*io;
20991 	mblk_t		*first_mp;
20992 	boolean_t policy_present;
20993 
20994 	first_mp = mp;
20995 	if (mp->b_datap->db_type == M_CTL) {
20996 		io = (ipsec_out_t *)first_mp->b_rptr;
20997 		/*
20998 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
20999 		 *
21000 		 * 1) There is per-socket policy (including cached global
21001 		 *    policy).
21002 		 * 2) There is no per-socket policy, but it is
21003 		 *    a multicast packet that needs to go out
21004 		 *    on a specific interface. This is the case
21005 		 *    where (ip_wput and ip_wput_multicast) attaches
21006 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21007 		 *
21008 		 * In case (2) we check with global policy to
21009 		 * see if there is a match and set the ill_index
21010 		 * appropriately so that we can lookup the ire
21011 		 * properly in ip_wput_ipsec_out.
21012 		 */
21013 
21014 		/*
21015 		 * ipsec_out_use_global_policy is set to B_FALSE
21016 		 * in ipsec_in_to_out(). Refer to that function for
21017 		 * details.
21018 		 */
21019 		if ((io->ipsec_out_latch == NULL) &&
21020 		    (io->ipsec_out_use_global_policy)) {
21021 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21022 				    ire, connp, unspec_src, zoneid));
21023 		}
21024 		if (!io->ipsec_out_secure) {
21025 			/*
21026 			 * If this is not a secure packet, drop
21027 			 * the IPSEC_OUT mp and treat it as a clear
21028 			 * packet. This happens when we are sending
21029 			 * a ICMP reply back to a clear packet. See
21030 			 * ipsec_in_to_out() for details.
21031 			 */
21032 			mp = first_mp->b_cont;
21033 			freeb(first_mp);
21034 		}
21035 		return (mp);
21036 	}
21037 	/*
21038 	 * See whether we need to attach a global policy here. We
21039 	 * don't depend on the conn (as it could be null) for deciding
21040 	 * what policy this datagram should go through because it
21041 	 * should have happened in ip_wput if there was some
21042 	 * policy. This normally happens for connections which are not
21043 	 * fully bound preventing us from caching policies in
21044 	 * ip_bind. Packets coming from the TCP listener/global queue
21045 	 * - which are non-hard_bound - could also be affected by
21046 	 * applying policy here.
21047 	 *
21048 	 * If this packet is coming from tcp global queue or listener,
21049 	 * we will be applying policy here.  This may not be *right*
21050 	 * if these packets are coming from the detached connection as
21051 	 * it could have gone in clear before. This happens only if a
21052 	 * TCP connection started when there is no policy and somebody
21053 	 * added policy before it became detached. Thus packets of the
21054 	 * detached connection could go out secure and the other end
21055 	 * would drop it because it will be expecting in clear. The
21056 	 * converse is not true i.e if somebody starts a TCP
21057 	 * connection and deletes the policy, all the packets will
21058 	 * still go out with the policy that existed before deleting
21059 	 * because ip_unbind sends up policy information which is used
21060 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21061 	 * TCP to attach a dummy IPSEC_OUT and set
21062 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21063 	 * affect performance for normal cases, we are not doing it.
21064 	 * Thus, set policy before starting any TCP connections.
21065 	 *
21066 	 * NOTE - We might apply policy even for a hard bound connection
21067 	 * - for which we cached policy in ip_bind - if somebody added
21068 	 * global policy after we inherited the policy in ip_bind.
21069 	 * This means that the packets that were going out in clear
21070 	 * previously would start going secure and hence get dropped
21071 	 * on the other side. To fix this, TCP attaches a dummy
21072 	 * ipsec_out and make sure that we don't apply global policy.
21073 	 */
21074 	if (ipha != NULL)
21075 		policy_present = ipsec_outbound_v4_policy_present;
21076 	else
21077 		policy_present = ipsec_outbound_v6_policy_present;
21078 	if (!policy_present)
21079 		return (mp);
21080 
21081 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21082 		    zoneid));
21083 }
21084 
21085 ire_t *
21086 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21087 {
21088 	ipaddr_t addr;
21089 	ire_t *save_ire;
21090 	irb_t *irb;
21091 	ill_group_t *illgrp;
21092 	int	err;
21093 
21094 	save_ire = ire;
21095 	addr = ire->ire_addr;
21096 
21097 	ASSERT(ire->ire_type == IRE_BROADCAST);
21098 
21099 	illgrp = connp->conn_outgoing_ill->ill_group;
21100 	if (illgrp == NULL) {
21101 		*conn_outgoing_ill = conn_get_held_ill(connp,
21102 		    &connp->conn_outgoing_ill, &err);
21103 		if (err == ILL_LOOKUP_FAILED) {
21104 			ire_refrele(save_ire);
21105 			return (NULL);
21106 		}
21107 		return (save_ire);
21108 	}
21109 	/*
21110 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21111 	 * If it is part of the group, we need to send on the ire
21112 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21113 	 * to this group. This is okay as IP_BOUND_IF really means
21114 	 * any ill in the group. We depend on the fact that the
21115 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21116 	 * if such an ire exists. This is possible only if you have
21117 	 * at least one ill in the group that has not failed.
21118 	 *
21119 	 * First get to the ire that matches the address and group.
21120 	 *
21121 	 * We don't look for an ire with a matching zoneid because a given zone
21122 	 * won't always have broadcast ires on all ills in the group.
21123 	 */
21124 	irb = ire->ire_bucket;
21125 	rw_enter(&irb->irb_lock, RW_READER);
21126 	if (ire->ire_marks & IRE_MARK_NORECV) {
21127 		/*
21128 		 * If the current zone only has an ire broadcast for this
21129 		 * address marked NORECV, the ire we want is ahead in the
21130 		 * bucket, so we look it up deliberately ignoring the zoneid.
21131 		 */
21132 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21133 			if (ire->ire_addr != addr)
21134 				continue;
21135 			/* skip over deleted ires */
21136 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21137 				continue;
21138 		}
21139 	}
21140 	while (ire != NULL) {
21141 		/*
21142 		 * If a new interface is coming up, we could end up
21143 		 * seeing the loopback ire and the non-loopback ire
21144 		 * may not have been added yet. So check for ire_stq
21145 		 */
21146 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21147 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21148 			break;
21149 		}
21150 		ire = ire->ire_next;
21151 	}
21152 	if (ire != NULL && ire->ire_addr == addr &&
21153 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21154 		IRE_REFHOLD(ire);
21155 		rw_exit(&irb->irb_lock);
21156 		ire_refrele(save_ire);
21157 		*conn_outgoing_ill = ire_to_ill(ire);
21158 		/*
21159 		 * Refhold the ill to make the conn_outgoing_ill
21160 		 * independent of the ire. ip_wput_ire goes in a loop
21161 		 * and may refrele the ire. Since we have an ire at this
21162 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21163 		 */
21164 		ill_refhold(*conn_outgoing_ill);
21165 		return (ire);
21166 	}
21167 	rw_exit(&irb->irb_lock);
21168 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21169 	/*
21170 	 * If we can't find a suitable ire, return the original ire.
21171 	 */
21172 	return (save_ire);
21173 }
21174 
21175 /*
21176  * This function does the ire_refrele of the ire passed in as the
21177  * argument. As this function looks up more ires i.e broadcast ires,
21178  * it needs to REFRELE them. Currently, for simplicity we don't
21179  * differentiate the one passed in and looked up here. We always
21180  * REFRELE.
21181  * IPQoS Notes:
21182  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21183  * IPSec packets are done in ipsec_out_process.
21184  *
21185  */
21186 void
21187 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21188     zoneid_t zoneid)
21189 {
21190 	ipha_t		*ipha;
21191 #define	rptr	((uchar_t *)ipha)
21192 	queue_t		*stq;
21193 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21194 	uint32_t	v_hlen_tos_len;
21195 	uint32_t	ttl_protocol;
21196 	ipaddr_t	src;
21197 	ipaddr_t	dst;
21198 	uint32_t	cksum;
21199 	ipaddr_t	orig_src;
21200 	ire_t		*ire1;
21201 	mblk_t		*next_mp;
21202 	uint_t		hlen;
21203 	uint16_t	*up;
21204 	uint32_t	max_frag = ire->ire_max_frag;
21205 	ill_t		*ill = ire_to_ill(ire);
21206 	int		clusterwide;
21207 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21208 	int		ipsec_len;
21209 	mblk_t		*first_mp;
21210 	ipsec_out_t	*io;
21211 	boolean_t	conn_dontroute;		/* conn value for multicast */
21212 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21213 	boolean_t	multicast_forward;	/* Should we forward ? */
21214 	boolean_t	unspec_src;
21215 	ill_t		*conn_outgoing_ill = NULL;
21216 	ill_t		*ire_ill;
21217 	ill_t		*ire1_ill;
21218 	uint32_t 	ill_index = 0;
21219 	boolean_t	multirt_send = B_FALSE;
21220 	int		err;
21221 	ipxmit_state_t	pktxmit_state;
21222 
21223 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21224 	    "ip_wput_ire_start: q %p", q);
21225 
21226 	multicast_forward = B_FALSE;
21227 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21228 
21229 	if (ire->ire_flags & RTF_MULTIRT) {
21230 		/*
21231 		 * Multirouting case. The bucket where ire is stored
21232 		 * probably holds other RTF_MULTIRT flagged ire
21233 		 * to the destination. In this call to ip_wput_ire,
21234 		 * we attempt to send the packet through all
21235 		 * those ires. Thus, we first ensure that ire is the
21236 		 * first RTF_MULTIRT ire in the bucket,
21237 		 * before walking the ire list.
21238 		 */
21239 		ire_t *first_ire;
21240 		irb_t *irb = ire->ire_bucket;
21241 		ASSERT(irb != NULL);
21242 
21243 		/* Make sure we do not omit any multiroute ire. */
21244 		IRB_REFHOLD(irb);
21245 		for (first_ire = irb->irb_ire;
21246 		    first_ire != NULL;
21247 		    first_ire = first_ire->ire_next) {
21248 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21249 			    (first_ire->ire_addr == ire->ire_addr) &&
21250 			    !(first_ire->ire_marks &
21251 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21252 				break;
21253 		}
21254 
21255 		if ((first_ire != NULL) && (first_ire != ire)) {
21256 			IRE_REFHOLD(first_ire);
21257 			ire_refrele(ire);
21258 			ire = first_ire;
21259 			ill = ire_to_ill(ire);
21260 		}
21261 		IRB_REFRELE(irb);
21262 	}
21263 
21264 	/*
21265 	 * conn_outgoing_ill is used only in the broadcast loop.
21266 	 * for performance we don't grab the mutexs in the fastpath
21267 	 */
21268 	if ((connp != NULL) &&
21269 	    (connp->conn_xmit_if_ill == NULL) &&
21270 	    (ire->ire_type == IRE_BROADCAST) &&
21271 	    ((connp->conn_nofailover_ill != NULL) ||
21272 	    (connp->conn_outgoing_ill != NULL))) {
21273 		/*
21274 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21275 		 * option. So, see if this endpoint is bound to a
21276 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21277 		 * that if the interface is failed, we will still send
21278 		 * the packet on the same ill which is what we want.
21279 		 */
21280 		conn_outgoing_ill = conn_get_held_ill(connp,
21281 		    &connp->conn_nofailover_ill, &err);
21282 		if (err == ILL_LOOKUP_FAILED) {
21283 			ire_refrele(ire);
21284 			freemsg(mp);
21285 			return;
21286 		}
21287 		if (conn_outgoing_ill == NULL) {
21288 			/*
21289 			 * Choose a good ill in the group to send the
21290 			 * packets on.
21291 			 */
21292 			ire = conn_set_outgoing_ill(connp, ire,
21293 			    &conn_outgoing_ill);
21294 			if (ire == NULL) {
21295 				freemsg(mp);
21296 				return;
21297 			}
21298 		}
21299 	}
21300 
21301 	if (mp->b_datap->db_type != M_CTL) {
21302 		ipha = (ipha_t *)mp->b_rptr;
21303 	} else {
21304 		io = (ipsec_out_t *)mp->b_rptr;
21305 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21306 		ASSERT(zoneid == io->ipsec_out_zoneid);
21307 		ASSERT(zoneid != ALL_ZONES);
21308 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21309 		dst = ipha->ipha_dst;
21310 		/*
21311 		 * For the multicast case, ipsec_out carries conn_dontroute and
21312 		 * conn_multicast_loop as conn may not be available here. We
21313 		 * need this for multicast loopback and forwarding which is done
21314 		 * later in the code.
21315 		 */
21316 		if (CLASSD(dst)) {
21317 			conn_dontroute = io->ipsec_out_dontroute;
21318 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21319 			/*
21320 			 * If conn_dontroute is not set or conn_multicast_loop
21321 			 * is set, we need to do forwarding/loopback. For
21322 			 * datagrams from ip_wput_multicast, conn_dontroute is
21323 			 * set to B_TRUE and conn_multicast_loop is set to
21324 			 * B_FALSE so that we neither do forwarding nor
21325 			 * loopback.
21326 			 */
21327 			if (!conn_dontroute || conn_multicast_loop)
21328 				multicast_forward = B_TRUE;
21329 		}
21330 	}
21331 
21332 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21333 	    ire->ire_zoneid != ALL_ZONES) {
21334 		/*
21335 		 * When a zone sends a packet to another zone, we try to deliver
21336 		 * the packet under the same conditions as if the destination
21337 		 * was a real node on the network. To do so, we look for a
21338 		 * matching route in the forwarding table.
21339 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21340 		 * ip_newroute() does.
21341 		 * Note that IRE_LOCAL are special, since they are used
21342 		 * when the zoneid doesn't match in some cases. This means that
21343 		 * we need to handle ipha_src differently since ire_src_addr
21344 		 * belongs to the receiving zone instead of the sending zone.
21345 		 * When ip_restrict_interzone_loopback is set, then
21346 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
21347 		 * for loopback between zones when the logical "Ethernet" would
21348 		 * have looped them back.
21349 		 */
21350 		ire_t *src_ire;
21351 
21352 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21353 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21354 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
21355 		if (src_ire != NULL &&
21356 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
21357 		    (!ip_restrict_interzone_loopback ||
21358 		    ire_local_same_ill_group(ire, src_ire))) {
21359 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21360 				ipha->ipha_src = src_ire->ire_src_addr;
21361 			ire_refrele(src_ire);
21362 		} else {
21363 			ire_refrele(ire);
21364 			if (conn_outgoing_ill != NULL)
21365 				ill_refrele(conn_outgoing_ill);
21366 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
21367 			if (src_ire != NULL) {
21368 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21369 					ire_refrele(src_ire);
21370 					freemsg(mp);
21371 					return;
21372 				}
21373 				ire_refrele(src_ire);
21374 			}
21375 			if (ip_hdr_complete(ipha, zoneid)) {
21376 				/* Failed */
21377 				freemsg(mp);
21378 				return;
21379 			}
21380 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid);
21381 			return;
21382 		}
21383 	}
21384 
21385 	if (mp->b_datap->db_type == M_CTL ||
21386 	    ipsec_outbound_v4_policy_present) {
21387 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21388 		    unspec_src, zoneid);
21389 		if (mp == NULL) {
21390 			ire_refrele(ire);
21391 			if (conn_outgoing_ill != NULL)
21392 				ill_refrele(conn_outgoing_ill);
21393 			return;
21394 		}
21395 	}
21396 
21397 	first_mp = mp;
21398 	ipsec_len = 0;
21399 
21400 	if (first_mp->b_datap->db_type == M_CTL) {
21401 		io = (ipsec_out_t *)first_mp->b_rptr;
21402 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21403 		mp = first_mp->b_cont;
21404 		ipsec_len = ipsec_out_extra_length(first_mp);
21405 		ASSERT(ipsec_len >= 0);
21406 		/* We already picked up the zoneid from the M_CTL above */
21407 		ASSERT(zoneid == io->ipsec_out_zoneid);
21408 		ASSERT(zoneid != ALL_ZONES);
21409 
21410 		/*
21411 		 * Drop M_CTL here if IPsec processing is not needed.
21412 		 * (Non-IPsec use of M_CTL extracted any information it
21413 		 * needed above).
21414 		 */
21415 		if (ipsec_len == 0) {
21416 			freeb(first_mp);
21417 			first_mp = mp;
21418 		}
21419 	}
21420 
21421 	/*
21422 	 * Fast path for ip_wput_ire
21423 	 */
21424 
21425 	ipha = (ipha_t *)mp->b_rptr;
21426 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21427 	dst = ipha->ipha_dst;
21428 
21429 	/*
21430 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21431 	 * if the socket is a SOCK_RAW type. The transport checksum should
21432 	 * be provided in the pre-built packet, so we don't need to compute it.
21433 	 * Also, other application set flags, like DF, should not be altered.
21434 	 * Other transport MUST pass down zero.
21435 	 */
21436 	ip_hdr_included = ipha->ipha_ident;
21437 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21438 
21439 	if (CLASSD(dst)) {
21440 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
21441 		    ntohl(dst),
21442 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
21443 		    ntohl(ire->ire_addr)));
21444 	}
21445 
21446 /* Macros to extract header fields from data already in registers */
21447 #ifdef	_BIG_ENDIAN
21448 #define	V_HLEN	(v_hlen_tos_len >> 24)
21449 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21450 #define	PROTO	(ttl_protocol & 0xFF)
21451 #else
21452 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21453 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21454 #define	PROTO	(ttl_protocol >> 8)
21455 #endif
21456 
21457 
21458 	orig_src = src = ipha->ipha_src;
21459 	/* (The loop back to "another" is explained down below.) */
21460 another:;
21461 	/*
21462 	 * Assign an ident value for this packet.  We assign idents on
21463 	 * a per destination basis out of the IRE.  There could be
21464 	 * other threads targeting the same destination, so we have to
21465 	 * arrange for a atomic increment.  Note that we use a 32-bit
21466 	 * atomic add because it has better performance than its
21467 	 * 16-bit sibling.
21468 	 *
21469 	 * If running in cluster mode and if the source address
21470 	 * belongs to a replicated service then vector through
21471 	 * cl_inet_ipident vector to allocate ip identifier
21472 	 * NOTE: This is a contract private interface with the
21473 	 * clustering group.
21474 	 */
21475 	clusterwide = 0;
21476 	if (cl_inet_ipident) {
21477 		ASSERT(cl_inet_isclusterwide);
21478 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21479 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
21480 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
21481 			    AF_INET, (uint8_t *)(uintptr_t)src,
21482 			    (uint8_t *)(uintptr_t)dst);
21483 			clusterwide = 1;
21484 		}
21485 	}
21486 	if (!clusterwide) {
21487 		ipha->ipha_ident =
21488 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
21489 	}
21490 
21491 #ifndef _BIG_ENDIAN
21492 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21493 #endif
21494 
21495 	/*
21496 	 * Set source address unless sent on an ill or conn_unspec_src is set.
21497 	 * This is needed to obey conn_unspec_src when packets go through
21498 	 * ip_newroute + arp.
21499 	 * Assumes ip_newroute{,_multi} sets the source address as well.
21500 	 */
21501 	if (src == INADDR_ANY && !unspec_src) {
21502 		/*
21503 		 * Assign the appropriate source address from the IRE if none
21504 		 * was specified.
21505 		 */
21506 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
21507 
21508 		/*
21509 		 * With IP multipathing, broadcast packets are sent on the ire
21510 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
21511 		 * the group. However, this ire might not be in the same zone so
21512 		 * we can't always use its source address. We look for a
21513 		 * broadcast ire in the same group and in the right zone.
21514 		 */
21515 		if (ire->ire_type == IRE_BROADCAST &&
21516 		    ire->ire_zoneid != zoneid) {
21517 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
21518 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
21519 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
21520 			if (src_ire != NULL) {
21521 				src = src_ire->ire_src_addr;
21522 				ire_refrele(src_ire);
21523 			} else {
21524 				ire_refrele(ire);
21525 				if (conn_outgoing_ill != NULL)
21526 					ill_refrele(conn_outgoing_ill);
21527 				freemsg(first_mp);
21528 				BUMP_MIB(&ip_mib, ipOutDiscards);
21529 				return;
21530 			}
21531 		} else {
21532 			src = ire->ire_src_addr;
21533 		}
21534 
21535 		if (connp == NULL) {
21536 			ip1dbg(("ip_wput_ire: no connp and no src "
21537 			    "address for dst 0x%x, using src 0x%x\n",
21538 			    ntohl(dst),
21539 			    ntohl(src)));
21540 		}
21541 		ipha->ipha_src = src;
21542 	}
21543 	stq = ire->ire_stq;
21544 
21545 	/*
21546 	 * We only allow ire chains for broadcasts since there will
21547 	 * be multiple IRE_CACHE entries for the same multicast
21548 	 * address (one per ipif).
21549 	 */
21550 	next_mp = NULL;
21551 
21552 	/* broadcast packet */
21553 	if (ire->ire_type == IRE_BROADCAST)
21554 		goto broadcast;
21555 
21556 	/* loopback ? */
21557 	if (stq == NULL)
21558 		goto nullstq;
21559 
21560 	/* The ill_index for outbound ILL */
21561 	ill_index = Q_TO_INDEX(stq);
21562 
21563 	BUMP_MIB(&ip_mib, ipOutRequests);
21564 	ttl_protocol = ((uint16_t *)ipha)[4];
21565 
21566 	/* pseudo checksum (do it in parts for IP header checksum) */
21567 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21568 
21569 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
21570 		queue_t *dev_q = stq->q_next;
21571 
21572 		/* flow controlled */
21573 		if ((dev_q->q_next || dev_q->q_first) &&
21574 		    !canput(dev_q))
21575 			goto blocked;
21576 		if ((PROTO == IPPROTO_UDP) &&
21577 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21578 			hlen = (V_HLEN & 0xF) << 2;
21579 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21580 			if (*up != 0) {
21581 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
21582 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
21583 				/* Software checksum? */
21584 				if (DB_CKSUMFLAGS(mp) == 0) {
21585 					IP_STAT(ip_out_sw_cksum);
21586 					IP_STAT_UPDATE(
21587 					    ip_udp_out_sw_cksum_bytes,
21588 					    LENGTH - hlen);
21589 				}
21590 			}
21591 		}
21592 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
21593 		hlen = (V_HLEN & 0xF) << 2;
21594 		if (PROTO == IPPROTO_TCP) {
21595 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21596 			/*
21597 			 * The packet header is processed once and for all, even
21598 			 * in the multirouting case. We disable hardware
21599 			 * checksum if the packet is multirouted, as it will be
21600 			 * replicated via several interfaces, and not all of
21601 			 * them may have this capability.
21602 			 */
21603 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
21604 			    LENGTH, max_frag, ipsec_len, cksum);
21605 			/* Software checksum? */
21606 			if (DB_CKSUMFLAGS(mp) == 0) {
21607 				IP_STAT(ip_out_sw_cksum);
21608 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21609 				    LENGTH - hlen);
21610 			}
21611 		} else {
21612 			sctp_hdr_t	*sctph;
21613 
21614 			ASSERT(PROTO == IPPROTO_SCTP);
21615 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21616 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21617 			/*
21618 			 * Zero out the checksum field to ensure proper
21619 			 * checksum calculation.
21620 			 */
21621 			sctph->sh_chksum = 0;
21622 #ifdef	DEBUG
21623 			if (!skip_sctp_cksum)
21624 #endif
21625 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21626 		}
21627 	}
21628 
21629 	/*
21630 	 * If this is a multicast packet and originated from ip_wput
21631 	 * we need to do loopback and forwarding checks. If it comes
21632 	 * from ip_wput_multicast, we SHOULD not do this.
21633 	 */
21634 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
21635 
21636 	/* checksum */
21637 	cksum += ttl_protocol;
21638 
21639 	/* fragment the packet */
21640 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
21641 		goto fragmentit;
21642 	/*
21643 	 * Don't use frag_flag if packet is pre-built or source
21644 	 * routed or if multicast (since multicast packets do
21645 	 * not solicit ICMP "packet too big" messages).
21646 	 */
21647 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21648 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21649 	    !ip_source_route_included(ipha)) &&
21650 	    !CLASSD(ipha->ipha_dst))
21651 		ipha->ipha_fragment_offset_and_flags |=
21652 		    htons(ire->ire_frag_flag);
21653 
21654 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21655 		/* calculate IP header checksum */
21656 		cksum += ipha->ipha_ident;
21657 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
21658 		cksum += ipha->ipha_fragment_offset_and_flags;
21659 
21660 		/* IP options present */
21661 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21662 		if (hlen)
21663 			goto checksumoptions;
21664 
21665 		/* calculate hdr checksum */
21666 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21667 		cksum = ~(cksum + (cksum >> 16));
21668 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
21669 	}
21670 	if (ipsec_len != 0) {
21671 		/*
21672 		 * We will do the rest of the processing after
21673 		 * we come back from IPSEC in ip_wput_ipsec_out().
21674 		 */
21675 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
21676 
21677 		io = (ipsec_out_t *)first_mp->b_rptr;
21678 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
21679 				ill_phyint->phyint_ifindex;
21680 
21681 		ipsec_out_process(q, first_mp, ire, ill_index);
21682 		ire_refrele(ire);
21683 		if (conn_outgoing_ill != NULL)
21684 			ill_refrele(conn_outgoing_ill);
21685 		return;
21686 	}
21687 
21688 	/*
21689 	 * In most cases, the emission loop below is entered only
21690 	 * once. Only in the case where the ire holds the
21691 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
21692 	 * flagged ires in the bucket, and send the packet
21693 	 * through all crossed RTF_MULTIRT routes.
21694 	 */
21695 	if (ire->ire_flags & RTF_MULTIRT) {
21696 		multirt_send = B_TRUE;
21697 	}
21698 	do {
21699 		if (multirt_send) {
21700 			irb_t *irb;
21701 			/*
21702 			 * We are in a multiple send case, need to get
21703 			 * the next ire and make a duplicate of the packet.
21704 			 * ire1 holds here the next ire to process in the
21705 			 * bucket. If multirouting is expected,
21706 			 * any non-RTF_MULTIRT ire that has the
21707 			 * right destination address is ignored.
21708 			 */
21709 			irb = ire->ire_bucket;
21710 			ASSERT(irb != NULL);
21711 
21712 			IRB_REFHOLD(irb);
21713 			for (ire1 = ire->ire_next;
21714 			    ire1 != NULL;
21715 			    ire1 = ire1->ire_next) {
21716 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21717 					continue;
21718 				if (ire1->ire_addr != ire->ire_addr)
21719 					continue;
21720 				if (ire1->ire_marks &
21721 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21722 					continue;
21723 
21724 				/* Got one */
21725 				IRE_REFHOLD(ire1);
21726 				break;
21727 			}
21728 			IRB_REFRELE(irb);
21729 
21730 			if (ire1 != NULL) {
21731 				next_mp = copyb(mp);
21732 				if ((next_mp == NULL) ||
21733 				    ((mp->b_cont != NULL) &&
21734 				    ((next_mp->b_cont =
21735 				    dupmsg(mp->b_cont)) == NULL))) {
21736 					freemsg(next_mp);
21737 					next_mp = NULL;
21738 					ire_refrele(ire1);
21739 					ire1 = NULL;
21740 				}
21741 			}
21742 
21743 			/* Last multiroute ire; don't loop anymore. */
21744 			if (ire1 == NULL) {
21745 				multirt_send = B_FALSE;
21746 			}
21747 		}
21748 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
21749 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
21750 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
21751 		if ((pktxmit_state == SEND_FAILED) ||
21752 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
21753 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
21754 			    "- packet dropped\n"));
21755 			ire_refrele(ire);
21756 			if (next_mp != NULL) {
21757 				freemsg(next_mp);
21758 				ire_refrele(ire1);
21759 			}
21760 			if (conn_outgoing_ill != NULL)
21761 				ill_refrele(conn_outgoing_ill);
21762 			return;
21763 		}
21764 
21765 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21766 		    "ip_wput_ire_end: q %p (%S)",
21767 		    q, "last copy out");
21768 		IRE_REFRELE(ire);
21769 
21770 		if (multirt_send) {
21771 			ASSERT(ire1);
21772 			/*
21773 			 * Proceed with the next RTF_MULTIRT ire,
21774 			 * Also set up the send-to queue accordingly.
21775 			 */
21776 			ire = ire1;
21777 			ire1 = NULL;
21778 			stq = ire->ire_stq;
21779 			mp = next_mp;
21780 			next_mp = NULL;
21781 			ipha = (ipha_t *)mp->b_rptr;
21782 			ill_index = Q_TO_INDEX(stq);
21783 		}
21784 	} while (multirt_send);
21785 	if (conn_outgoing_ill != NULL)
21786 		ill_refrele(conn_outgoing_ill);
21787 	return;
21788 
21789 	/*
21790 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
21791 	 */
21792 broadcast:
21793 	{
21794 		/*
21795 		 * Avoid broadcast storms by setting the ttl to 1
21796 		 * for broadcasts. This parameter can be set
21797 		 * via ndd, so make sure that for the SO_DONTROUTE
21798 		 * case that ipha_ttl is always set to 1.
21799 		 * In the event that we are replying to incoming
21800 		 * ICMP packets, conn could be NULL.
21801 		 */
21802 		if ((connp != NULL) && connp->conn_dontroute)
21803 			ipha->ipha_ttl = 1;
21804 		else
21805 			ipha->ipha_ttl = ip_broadcast_ttl;
21806 
21807 		/*
21808 		 * Note that we are not doing a IRB_REFHOLD here.
21809 		 * Actually we don't care if the list changes i.e
21810 		 * if somebody deletes an IRE from the list while
21811 		 * we drop the lock, the next time we come around
21812 		 * ire_next will be NULL and hence we won't send
21813 		 * out multiple copies which is fine.
21814 		 */
21815 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
21816 		ire1 = ire->ire_next;
21817 		if (conn_outgoing_ill != NULL) {
21818 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
21819 				ASSERT(ire1 == ire->ire_next);
21820 				if (ire1 != NULL && ire1->ire_addr == dst) {
21821 					ire_refrele(ire);
21822 					ire = ire1;
21823 					IRE_REFHOLD(ire);
21824 					ire1 = ire->ire_next;
21825 					continue;
21826 				}
21827 				rw_exit(&ire->ire_bucket->irb_lock);
21828 				/* Did not find a matching ill */
21829 				ip1dbg(("ip_wput_ire: broadcast with no "
21830 				    "matching IP_BOUND_IF ill %s\n",
21831 				    conn_outgoing_ill->ill_name));
21832 				freemsg(first_mp);
21833 				if (ire != NULL)
21834 					ire_refrele(ire);
21835 				ill_refrele(conn_outgoing_ill);
21836 				return;
21837 			}
21838 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
21839 			/*
21840 			 * If the next IRE has the same address and is not one
21841 			 * of the two copies that we need to send, try to see
21842 			 * whether this copy should be sent at all. This
21843 			 * assumes that we insert loopbacks first and then
21844 			 * non-loopbacks. This is acheived by inserting the
21845 			 * loopback always before non-loopback.
21846 			 * This is used to send a single copy of a broadcast
21847 			 * packet out all physical interfaces that have an
21848 			 * matching IRE_BROADCAST while also looping
21849 			 * back one copy (to ip_wput_local) for each
21850 			 * matching physical interface. However, we avoid
21851 			 * sending packets out different logical that match by
21852 			 * having ipif_up/ipif_down supress duplicate
21853 			 * IRE_BROADCASTS.
21854 			 *
21855 			 * This feature is currently used to get broadcasts
21856 			 * sent to multiple interfaces, when the broadcast
21857 			 * address being used applies to multiple interfaces.
21858 			 * For example, a whole net broadcast will be
21859 			 * replicated on every connected subnet of
21860 			 * the target net.
21861 			 *
21862 			 * Each zone has its own set of IRE_BROADCASTs, so that
21863 			 * we're able to distribute inbound packets to multiple
21864 			 * zones who share a broadcast address. We avoid looping
21865 			 * back outbound packets in different zones but on the
21866 			 * same ill, as the application would see duplicates.
21867 			 *
21868 			 * If the interfaces are part of the same group,
21869 			 * we would want to send only one copy out for
21870 			 * whole group.
21871 			 *
21872 			 * This logic assumes that ire_add_v4() groups the
21873 			 * IRE_BROADCAST entries so that those with the same
21874 			 * ire_addr and ill_group are kept together.
21875 			 */
21876 			ire_ill = ire->ire_ipif->ipif_ill;
21877 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
21878 				if (ire_ill->ill_group != NULL &&
21879 				    (ire->ire_marks & IRE_MARK_NORECV)) {
21880 					/*
21881 					 * If the current zone only has an ire
21882 					 * broadcast for this address marked
21883 					 * NORECV, the ire we want is ahead in
21884 					 * the bucket, so we look it up
21885 					 * deliberately ignoring the zoneid.
21886 					 */
21887 					for (ire1 = ire->ire_bucket->irb_ire;
21888 					    ire1 != NULL;
21889 					    ire1 = ire1->ire_next) {
21890 						ire1_ill =
21891 						    ire1->ire_ipif->ipif_ill;
21892 						if (ire1->ire_addr != dst)
21893 							continue;
21894 						/* skip over the current ire */
21895 						if (ire1 == ire)
21896 							continue;
21897 						/* skip over deleted ires */
21898 						if (ire1->ire_marks &
21899 						    IRE_MARK_CONDEMNED)
21900 							continue;
21901 						/*
21902 						 * non-loopback ire in our
21903 						 * group: use it for the next
21904 						 * pass in the loop
21905 						 */
21906 						if (ire1->ire_stq != NULL &&
21907 						    ire1_ill->ill_group ==
21908 						    ire_ill->ill_group)
21909 							break;
21910 					}
21911 				}
21912 			} else {
21913 				while (ire1 != NULL && ire1->ire_addr == dst) {
21914 					ire1_ill = ire1->ire_ipif->ipif_ill;
21915 					/*
21916 					 * We can have two broadcast ires on the
21917 					 * same ill in different zones; here
21918 					 * we'll send a copy of the packet on
21919 					 * each ill and the fanout code will
21920 					 * call conn_wantpacket() to check that
21921 					 * the zone has the broadcast address
21922 					 * configured on the ill. If the two
21923 					 * ires are in the same group we only
21924 					 * send one copy up.
21925 					 */
21926 					if (ire1_ill != ire_ill &&
21927 					    (ire1_ill->ill_group == NULL ||
21928 					    ire_ill->ill_group == NULL ||
21929 					    ire1_ill->ill_group !=
21930 					    ire_ill->ill_group)) {
21931 						break;
21932 					}
21933 					ire1 = ire1->ire_next;
21934 				}
21935 			}
21936 		}
21937 		ASSERT(multirt_send == B_FALSE);
21938 		if (ire1 != NULL && ire1->ire_addr == dst) {
21939 			if ((ire->ire_flags & RTF_MULTIRT) &&
21940 			    (ire1->ire_flags & RTF_MULTIRT)) {
21941 				/*
21942 				 * We are in the multirouting case.
21943 				 * The message must be sent at least
21944 				 * on both ires. These ires have been
21945 				 * inserted AFTER the standard ones
21946 				 * in ip_rt_add(). There are thus no
21947 				 * other ire entries for the destination
21948 				 * address in the rest of the bucket
21949 				 * that do not have the RTF_MULTIRT
21950 				 * flag. We don't process a copy
21951 				 * of the message here. This will be
21952 				 * done in the final sending loop.
21953 				 */
21954 				multirt_send = B_TRUE;
21955 			} else {
21956 				next_mp = ip_copymsg(first_mp);
21957 				if (next_mp != NULL)
21958 					IRE_REFHOLD(ire1);
21959 			}
21960 		}
21961 		rw_exit(&ire->ire_bucket->irb_lock);
21962 	}
21963 
21964 	if (stq) {
21965 		/*
21966 		 * A non-NULL send-to queue means this packet is going
21967 		 * out of this machine.
21968 		 */
21969 
21970 		BUMP_MIB(&ip_mib, ipOutRequests);
21971 		ttl_protocol = ((uint16_t *)ipha)[4];
21972 		/*
21973 		 * We accumulate the pseudo header checksum in cksum.
21974 		 * This is pretty hairy code, so watch close.  One
21975 		 * thing to keep in mind is that UDP and TCP have
21976 		 * stored their respective datagram lengths in their
21977 		 * checksum fields.  This lines things up real nice.
21978 		 */
21979 		cksum = (dst >> 16) + (dst & 0xFFFF) +
21980 		    (src >> 16) + (src & 0xFFFF);
21981 		/*
21982 		 * We assume the udp checksum field contains the
21983 		 * length, so to compute the pseudo header checksum,
21984 		 * all we need is the protocol number and src/dst.
21985 		 */
21986 		/* Provide the checksums for UDP and TCP. */
21987 		if ((PROTO == IPPROTO_TCP) &&
21988 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21989 			/* hlen gets the number of uchar_ts in the IP header */
21990 			hlen = (V_HLEN & 0xF) << 2;
21991 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21992 			IP_STAT(ip_out_sw_cksum);
21993 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21994 			    LENGTH - hlen);
21995 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
21996 			if (*up == 0)
21997 				*up = 0xFFFF;
21998 		} else if (PROTO == IPPROTO_SCTP &&
21999 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22000 			sctp_hdr_t	*sctph;
22001 
22002 			hlen = (V_HLEN & 0xF) << 2;
22003 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22004 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22005 			sctph->sh_chksum = 0;
22006 #ifdef	DEBUG
22007 			if (!skip_sctp_cksum)
22008 #endif
22009 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22010 		} else {
22011 			queue_t *dev_q = stq->q_next;
22012 
22013 			if ((dev_q->q_next || dev_q->q_first) &&
22014 			    !canput(dev_q)) {
22015 			    blocked:
22016 				ipha->ipha_ident = ip_hdr_included;
22017 				/*
22018 				 * If we don't have a conn to apply
22019 				 * backpressure, free the message.
22020 				 * In the ire_send path, we don't know
22021 				 * the position to requeue the packet. Rather
22022 				 * than reorder packets, we just drop this
22023 				 * packet.
22024 				 */
22025 				if (ip_output_queue && connp != NULL &&
22026 				    caller != IRE_SEND) {
22027 					if (caller == IP_WSRV) {
22028 						connp->conn_did_putbq = 1;
22029 						(void) putbq(connp->conn_wq,
22030 						    first_mp);
22031 						conn_drain_insert(connp);
22032 						/*
22033 						 * This is the service thread,
22034 						 * and the queue is already
22035 						 * noenabled. The check for
22036 						 * canput and the putbq is not
22037 						 * atomic. So we need to check
22038 						 * again.
22039 						 */
22040 						if (canput(stq->q_next))
22041 							connp->conn_did_putbq
22042 							    = 0;
22043 						IP_STAT(ip_conn_flputbq);
22044 					} else {
22045 						/*
22046 						 * We are not the service proc.
22047 						 * ip_wsrv will be scheduled or
22048 						 * is already running.
22049 						 */
22050 						(void) putq(connp->conn_wq,
22051 						    first_mp);
22052 					}
22053 				} else {
22054 					BUMP_MIB(&ip_mib, ipOutDiscards);
22055 					freemsg(first_mp);
22056 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22057 					    "ip_wput_ire_end: q %p (%S)",
22058 					    q, "discard");
22059 				}
22060 				ire_refrele(ire);
22061 				if (next_mp) {
22062 					ire_refrele(ire1);
22063 					freemsg(next_mp);
22064 				}
22065 				if (conn_outgoing_ill != NULL)
22066 					ill_refrele(conn_outgoing_ill);
22067 				return;
22068 			}
22069 			if ((PROTO == IPPROTO_UDP) &&
22070 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22071 				/*
22072 				 * hlen gets the number of uchar_ts in the
22073 				 * IP header
22074 				 */
22075 				hlen = (V_HLEN & 0xF) << 2;
22076 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22077 				max_frag = ire->ire_max_frag;
22078 				if (*up != 0) {
22079 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22080 					    up, PROTO, hlen, LENGTH, max_frag,
22081 					    ipsec_len, cksum);
22082 					/* Software checksum? */
22083 					if (DB_CKSUMFLAGS(mp) == 0) {
22084 						IP_STAT(ip_out_sw_cksum);
22085 						IP_STAT_UPDATE(
22086 						    ip_udp_out_sw_cksum_bytes,
22087 						    LENGTH - hlen);
22088 					}
22089 				}
22090 			}
22091 		}
22092 		/*
22093 		 * Need to do this even when fragmenting. The local
22094 		 * loopback can be done without computing checksums
22095 		 * but forwarding out other interface must be done
22096 		 * after the IP checksum (and ULP checksums) have been
22097 		 * computed.
22098 		 *
22099 		 * NOTE : multicast_forward is set only if this packet
22100 		 * originated from ip_wput. For packets originating from
22101 		 * ip_wput_multicast, it is not set.
22102 		 */
22103 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22104 		    multi_loopback:
22105 			ip2dbg(("ip_wput: multicast, loop %d\n",
22106 			    conn_multicast_loop));
22107 
22108 			/*  Forget header checksum offload */
22109 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22110 
22111 			/*
22112 			 * Local loopback of multicasts?  Check the
22113 			 * ill.
22114 			 *
22115 			 * Note that the loopback function will not come
22116 			 * in through ip_rput - it will only do the
22117 			 * client fanout thus we need to do an mforward
22118 			 * as well.  The is different from the BSD
22119 			 * logic.
22120 			 */
22121 			if (ill != NULL) {
22122 				ilm_t	*ilm;
22123 
22124 				ILM_WALKER_HOLD(ill);
22125 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22126 				    ALL_ZONES);
22127 				ILM_WALKER_RELE(ill);
22128 				if (ilm != NULL) {
22129 					/*
22130 					 * Pass along the virtual output q.
22131 					 * ip_wput_local() will distribute the
22132 					 * packet to all the matching zones,
22133 					 * except the sending zone when
22134 					 * IP_MULTICAST_LOOP is false.
22135 					 */
22136 					ip_multicast_loopback(q, ill, first_mp,
22137 					    conn_multicast_loop ? 0 :
22138 					    IP_FF_NO_MCAST_LOOP, zoneid);
22139 				}
22140 			}
22141 			if (ipha->ipha_ttl == 0) {
22142 				/*
22143 				 * 0 => only to this host i.e. we are
22144 				 * done. We are also done if this was the
22145 				 * loopback interface since it is sufficient
22146 				 * to loopback one copy of a multicast packet.
22147 				 */
22148 				freemsg(first_mp);
22149 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22150 				    "ip_wput_ire_end: q %p (%S)",
22151 				    q, "loopback");
22152 				ire_refrele(ire);
22153 				if (conn_outgoing_ill != NULL)
22154 					ill_refrele(conn_outgoing_ill);
22155 				return;
22156 			}
22157 			/*
22158 			 * ILLF_MULTICAST is checked in ip_newroute
22159 			 * i.e. we don't need to check it here since
22160 			 * all IRE_CACHEs come from ip_newroute.
22161 			 * For multicast traffic, SO_DONTROUTE is interpreted
22162 			 * to mean only send the packet out the interface
22163 			 * (optionally specified with IP_MULTICAST_IF)
22164 			 * and do not forward it out additional interfaces.
22165 			 * RSVP and the rsvp daemon is an example of a
22166 			 * protocol and user level process that
22167 			 * handles it's own routing. Hence, it uses the
22168 			 * SO_DONTROUTE option to accomplish this.
22169 			 */
22170 
22171 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22172 				/* Unconditionally redo the checksum */
22173 				ipha->ipha_hdr_checksum = 0;
22174 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22175 
22176 				/*
22177 				 * If this needs to go out secure, we need
22178 				 * to wait till we finish the IPSEC
22179 				 * processing.
22180 				 */
22181 				if (ipsec_len == 0 &&
22182 				    ip_mforward(ill, ipha, mp)) {
22183 					freemsg(first_mp);
22184 					ip1dbg(("ip_wput: mforward failed\n"));
22185 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22186 					    "ip_wput_ire_end: q %p (%S)",
22187 					    q, "mforward failed");
22188 					ire_refrele(ire);
22189 					if (conn_outgoing_ill != NULL)
22190 						ill_refrele(conn_outgoing_ill);
22191 					return;
22192 				}
22193 			}
22194 		}
22195 		max_frag = ire->ire_max_frag;
22196 		cksum += ttl_protocol;
22197 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22198 			/* No fragmentation required for this one. */
22199 			/*
22200 			 * Don't use frag_flag if packet is pre-built or source
22201 			 * routed or if multicast (since multicast packets do
22202 			 * not solicit ICMP "packet too big" messages).
22203 			 */
22204 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22205 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22206 			    !ip_source_route_included(ipha)) &&
22207 			    !CLASSD(ipha->ipha_dst))
22208 				ipha->ipha_fragment_offset_and_flags |=
22209 				    htons(ire->ire_frag_flag);
22210 
22211 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22212 				/* Complete the IP header checksum. */
22213 				cksum += ipha->ipha_ident;
22214 				cksum += (v_hlen_tos_len >> 16)+
22215 				    (v_hlen_tos_len & 0xFFFF);
22216 				cksum += ipha->ipha_fragment_offset_and_flags;
22217 				hlen = (V_HLEN & 0xF) -
22218 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22219 				if (hlen) {
22220 				    checksumoptions:
22221 					/*
22222 					 * Account for the IP Options in the IP
22223 					 * header checksum.
22224 					 */
22225 					up = (uint16_t *)(rptr+
22226 					    IP_SIMPLE_HDR_LENGTH);
22227 					do {
22228 						cksum += up[0];
22229 						cksum += up[1];
22230 						up += 2;
22231 					} while (--hlen);
22232 				}
22233 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22234 				cksum = ~(cksum + (cksum >> 16));
22235 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22236 			}
22237 			if (ipsec_len != 0) {
22238 				ipsec_out_process(q, first_mp, ire, ill_index);
22239 				if (!next_mp) {
22240 					ire_refrele(ire);
22241 					if (conn_outgoing_ill != NULL)
22242 						ill_refrele(conn_outgoing_ill);
22243 					return;
22244 				}
22245 				goto next;
22246 			}
22247 
22248 			/*
22249 			 * multirt_send has already been handled
22250 			 * for broadcast, but not yet for multicast
22251 			 * or IP options.
22252 			 */
22253 			if (next_mp == NULL) {
22254 				if (ire->ire_flags & RTF_MULTIRT) {
22255 					multirt_send = B_TRUE;
22256 				}
22257 			}
22258 
22259 			/*
22260 			 * In most cases, the emission loop below is
22261 			 * entered only once. Only in the case where
22262 			 * the ire holds the RTF_MULTIRT flag, do we loop
22263 			 * to process all RTF_MULTIRT ires in the bucket,
22264 			 * and send the packet through all crossed
22265 			 * RTF_MULTIRT routes.
22266 			 */
22267 			do {
22268 				if (multirt_send) {
22269 					irb_t *irb;
22270 
22271 					irb = ire->ire_bucket;
22272 					ASSERT(irb != NULL);
22273 					/*
22274 					 * We are in a multiple send case,
22275 					 * need to get the next IRE and make
22276 					 * a duplicate of the packet.
22277 					 */
22278 					IRB_REFHOLD(irb);
22279 					for (ire1 = ire->ire_next;
22280 					    ire1 != NULL;
22281 					    ire1 = ire1->ire_next) {
22282 						if (!(ire1->ire_flags &
22283 						    RTF_MULTIRT))
22284 							continue;
22285 						if (ire1->ire_addr !=
22286 						    ire->ire_addr)
22287 							continue;
22288 						if (ire1->ire_marks &
22289 						    (IRE_MARK_CONDEMNED|
22290 							IRE_MARK_HIDDEN))
22291 							continue;
22292 
22293 						/* Got one */
22294 						IRE_REFHOLD(ire1);
22295 						break;
22296 					}
22297 					IRB_REFRELE(irb);
22298 
22299 					if (ire1 != NULL) {
22300 						next_mp = copyb(mp);
22301 						if ((next_mp == NULL) ||
22302 						    ((mp->b_cont != NULL) &&
22303 						    ((next_mp->b_cont =
22304 						    dupmsg(mp->b_cont))
22305 						    == NULL))) {
22306 							freemsg(next_mp);
22307 							next_mp = NULL;
22308 							ire_refrele(ire1);
22309 							ire1 = NULL;
22310 						}
22311 					}
22312 
22313 					/*
22314 					 * Last multiroute ire; don't loop
22315 					 * anymore. The emission is over
22316 					 * and next_mp is NULL.
22317 					 */
22318 					if (ire1 == NULL) {
22319 						multirt_send = B_FALSE;
22320 					}
22321 				}
22322 
22323 				ASSERT(ipsec_len == 0);
22324 				mp->b_prev =
22325 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22326 				DTRACE_PROBE2(ip__xmit__2,
22327 				    mblk_t *, mp, ire_t *, ire);
22328 				pktxmit_state = ip_xmit_v4(mp, ire,
22329 				    NULL, B_TRUE);
22330 				if ((pktxmit_state == SEND_FAILED) ||
22331 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22332 					if (next_mp) {
22333 						freemsg(next_mp);
22334 						ire_refrele(ire1);
22335 					}
22336 					ire_refrele(ire);
22337 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22338 					    "ip_wput_ire_end: q %p (%S)",
22339 					    q, "discard MDATA");
22340 					if (conn_outgoing_ill != NULL)
22341 						ill_refrele(conn_outgoing_ill);
22342 					return;
22343 				}
22344 
22345 				if (multirt_send) {
22346 					/*
22347 					 * We are in a multiple send case,
22348 					 * need to re-enter the sending loop
22349 					 * using the next ire.
22350 					 */
22351 					ire_refrele(ire);
22352 					ire = ire1;
22353 					stq = ire->ire_stq;
22354 					mp = next_mp;
22355 					next_mp = NULL;
22356 					ipha = (ipha_t *)mp->b_rptr;
22357 					ill_index = Q_TO_INDEX(stq);
22358 				}
22359 			} while (multirt_send);
22360 
22361 			if (!next_mp) {
22362 				/*
22363 				 * Last copy going out (the ultra-common
22364 				 * case).  Note that we intentionally replicate
22365 				 * the putnext rather than calling it before
22366 				 * the next_mp check in hopes of a little
22367 				 * tail-call action out of the compiler.
22368 				 */
22369 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22370 				    "ip_wput_ire_end: q %p (%S)",
22371 				    q, "last copy out(1)");
22372 				ire_refrele(ire);
22373 				if (conn_outgoing_ill != NULL)
22374 					ill_refrele(conn_outgoing_ill);
22375 				return;
22376 			}
22377 			/* More copies going out below. */
22378 		} else {
22379 			int offset;
22380 		    fragmentit:
22381 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22382 			/*
22383 			 * If this would generate a icmp_frag_needed message,
22384 			 * we need to handle it before we do the IPSEC
22385 			 * processing. Otherwise, we need to strip the IPSEC
22386 			 * headers before we send up the message to the ULPs
22387 			 * which becomes messy and difficult.
22388 			 */
22389 			if (ipsec_len != 0) {
22390 				if ((max_frag < (unsigned int)(LENGTH +
22391 				    ipsec_len)) && (offset & IPH_DF)) {
22392 
22393 					BUMP_MIB(&ip_mib, ipFragFails);
22394 					ipha->ipha_hdr_checksum = 0;
22395 					ipha->ipha_hdr_checksum =
22396 					    (uint16_t)ip_csum_hdr(ipha);
22397 					icmp_frag_needed(ire->ire_stq, first_mp,
22398 					    max_frag, zoneid);
22399 					if (!next_mp) {
22400 						ire_refrele(ire);
22401 						if (conn_outgoing_ill != NULL) {
22402 							ill_refrele(
22403 							    conn_outgoing_ill);
22404 						}
22405 						return;
22406 					}
22407 				} else {
22408 					/*
22409 					 * This won't cause a icmp_frag_needed
22410 					 * message. to be gnerated. Send it on
22411 					 * the wire. Note that this could still
22412 					 * cause fragmentation and all we
22413 					 * do is the generation of the message
22414 					 * to the ULP if needed before IPSEC.
22415 					 */
22416 					if (!next_mp) {
22417 						ipsec_out_process(q, first_mp,
22418 						    ire, ill_index);
22419 						TRACE_2(TR_FAC_IP,
22420 						    TR_IP_WPUT_IRE_END,
22421 						    "ip_wput_ire_end: q %p "
22422 						    "(%S)", q,
22423 						    "last ipsec_out_process");
22424 						ire_refrele(ire);
22425 						if (conn_outgoing_ill != NULL) {
22426 							ill_refrele(
22427 							    conn_outgoing_ill);
22428 						}
22429 						return;
22430 					}
22431 					ipsec_out_process(q, first_mp,
22432 					    ire, ill_index);
22433 				}
22434 			} else {
22435 				/*
22436 				 * Initiate IPPF processing. For
22437 				 * fragmentable packets we finish
22438 				 * all QOS packet processing before
22439 				 * calling:
22440 				 * ip_wput_ire_fragmentit->ip_wput_frag
22441 				 */
22442 
22443 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22444 					ip_process(IPP_LOCAL_OUT, &mp,
22445 					    ill_index);
22446 					if (mp == NULL) {
22447 						BUMP_MIB(&ip_mib,
22448 						    ipOutDiscards);
22449 						if (next_mp != NULL) {
22450 							freemsg(next_mp);
22451 							ire_refrele(ire1);
22452 						}
22453 						ire_refrele(ire);
22454 						TRACE_2(TR_FAC_IP,
22455 						    TR_IP_WPUT_IRE_END,
22456 						    "ip_wput_ire: q %p (%S)",
22457 						    q, "discard MDATA");
22458 						if (conn_outgoing_ill != NULL) {
22459 							ill_refrele(
22460 							    conn_outgoing_ill);
22461 						}
22462 						return;
22463 					}
22464 				}
22465 				if (!next_mp) {
22466 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22467 					    "ip_wput_ire_end: q %p (%S)",
22468 					    q, "last fragmentation");
22469 					ip_wput_ire_fragmentit(mp, ire,
22470 					    zoneid);
22471 					ire_refrele(ire);
22472 					if (conn_outgoing_ill != NULL)
22473 						ill_refrele(conn_outgoing_ill);
22474 					return;
22475 				}
22476 				ip_wput_ire_fragmentit(mp, ire, zoneid);
22477 			}
22478 		}
22479 	} else {
22480 	    nullstq:
22481 		/* A NULL stq means the destination address is local. */
22482 		UPDATE_OB_PKT_COUNT(ire);
22483 		ire->ire_last_used_time = lbolt;
22484 		ASSERT(ire->ire_ipif != NULL);
22485 		if (!next_mp) {
22486 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22487 			    "ip_wput_ire_end: q %p (%S)",
22488 			    q, "local address");
22489 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
22490 			    first_mp, ire, 0, ire->ire_zoneid);
22491 			ire_refrele(ire);
22492 			if (conn_outgoing_ill != NULL)
22493 				ill_refrele(conn_outgoing_ill);
22494 			return;
22495 		}
22496 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
22497 		    ire, 0, ire->ire_zoneid);
22498 	}
22499 next:
22500 	/*
22501 	 * More copies going out to additional interfaces.
22502 	 * ire1 has already been held. We don't need the
22503 	 * "ire" anymore.
22504 	 */
22505 	ire_refrele(ire);
22506 	ire = ire1;
22507 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
22508 	mp = next_mp;
22509 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
22510 	ill = ire_to_ill(ire);
22511 	first_mp = mp;
22512 	if (ipsec_len != 0) {
22513 		ASSERT(first_mp->b_datap->db_type == M_CTL);
22514 		mp = mp->b_cont;
22515 	}
22516 	dst = ire->ire_addr;
22517 	ipha = (ipha_t *)mp->b_rptr;
22518 	/*
22519 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
22520 	 * Restore ipha_ident "no checksum" flag.
22521 	 */
22522 	src = orig_src;
22523 	ipha->ipha_ident = ip_hdr_included;
22524 	goto another;
22525 
22526 #undef	rptr
22527 #undef	Q_TO_INDEX
22528 }
22529 
22530 /*
22531  * Routine to allocate a message that is used to notify the ULP about MDT.
22532  * The caller may provide a pointer to the link-layer MDT capabilities,
22533  * or NULL if MDT is to be disabled on the stream.
22534  */
22535 mblk_t *
22536 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
22537 {
22538 	mblk_t *mp;
22539 	ip_mdt_info_t *mdti;
22540 	ill_mdt_capab_t *idst;
22541 
22542 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
22543 		DB_TYPE(mp) = M_CTL;
22544 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
22545 		mdti = (ip_mdt_info_t *)mp->b_rptr;
22546 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
22547 		idst = &(mdti->mdt_capab);
22548 
22549 		/*
22550 		 * If the caller provides us with the capability, copy
22551 		 * it over into our notification message; otherwise
22552 		 * we zero out the capability portion.
22553 		 */
22554 		if (isrc != NULL)
22555 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22556 		else
22557 			bzero((caddr_t)idst, sizeof (*idst));
22558 	}
22559 	return (mp);
22560 }
22561 
22562 /*
22563  * Routine which determines whether MDT can be enabled on the destination
22564  * IRE and IPC combination, and if so, allocates and returns the MDT
22565  * notification mblk that may be used by ULP.  We also check if we need to
22566  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
22567  * MDT usage in the past have been lifted.  This gets called during IP
22568  * and ULP binding.
22569  */
22570 mblk_t *
22571 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22572     ill_mdt_capab_t *mdt_cap)
22573 {
22574 	mblk_t *mp;
22575 	boolean_t rc = B_FALSE;
22576 
22577 	ASSERT(dst_ire != NULL);
22578 	ASSERT(connp != NULL);
22579 	ASSERT(mdt_cap != NULL);
22580 
22581 	/*
22582 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
22583 	 * Multidata, which is handled in tcp_multisend().  This
22584 	 * is the reason why we do all these checks here, to ensure
22585 	 * that we don't enable Multidata for the cases which we
22586 	 * can't handle at the moment.
22587 	 */
22588 	do {
22589 		/* Only do TCP at the moment */
22590 		if (connp->conn_ulp != IPPROTO_TCP)
22591 			break;
22592 
22593 		/*
22594 		 * IPSEC outbound policy present?  Note that we get here
22595 		 * after calling ipsec_conn_cache_policy() where the global
22596 		 * policy checking is performed.  conn_latch will be
22597 		 * non-NULL as long as there's a policy defined,
22598 		 * i.e. conn_out_enforce_policy may be NULL in such case
22599 		 * when the connection is non-secure, and hence we check
22600 		 * further if the latch refers to an outbound policy.
22601 		 */
22602 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
22603 			break;
22604 
22605 		/* CGTP (multiroute) is enabled? */
22606 		if (dst_ire->ire_flags & RTF_MULTIRT)
22607 			break;
22608 
22609 		/* Outbound IPQoS enabled? */
22610 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22611 			/*
22612 			 * In this case, we disable MDT for this and all
22613 			 * future connections going over the interface.
22614 			 */
22615 			mdt_cap->ill_mdt_on = 0;
22616 			break;
22617 		}
22618 
22619 		/* socket option(s) present? */
22620 		if (!CONN_IS_MD_FASTPATH(connp))
22621 			break;
22622 
22623 		rc = B_TRUE;
22624 	/* CONSTCOND */
22625 	} while (0);
22626 
22627 	/* Remember the result */
22628 	connp->conn_mdt_ok = rc;
22629 
22630 	if (!rc)
22631 		return (NULL);
22632 	else if (!mdt_cap->ill_mdt_on) {
22633 		/*
22634 		 * If MDT has been previously turned off in the past, and we
22635 		 * currently can do MDT (due to IPQoS policy removal, etc.)
22636 		 * then enable it for this interface.
22637 		 */
22638 		mdt_cap->ill_mdt_on = 1;
22639 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
22640 		    "interface %s\n", ill_name));
22641 	}
22642 
22643 	/* Allocate the MDT info mblk */
22644 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
22645 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
22646 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
22647 		return (NULL);
22648 	}
22649 	return (mp);
22650 }
22651 
22652 /*
22653  * Create destination address attribute, and fill it with the physical
22654  * destination address and SAP taken from the template DL_UNITDATA_REQ
22655  * message block.
22656  */
22657 boolean_t
22658 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
22659 {
22660 	dl_unitdata_req_t *dlurp;
22661 	pattr_t *pa;
22662 	pattrinfo_t pa_info;
22663 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
22664 	uint_t das_len, das_off;
22665 
22666 	ASSERT(dlmp != NULL);
22667 
22668 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
22669 	das_len = dlurp->dl_dest_addr_length;
22670 	das_off = dlurp->dl_dest_addr_offset;
22671 
22672 	pa_info.type = PATTR_DSTADDRSAP;
22673 	pa_info.len = sizeof (**das) + das_len - 1;
22674 
22675 	/* create and associate the attribute */
22676 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22677 	if (pa != NULL) {
22678 		ASSERT(*das != NULL);
22679 		(*das)->addr_is_group = 0;
22680 		(*das)->addr_len = (uint8_t)das_len;
22681 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
22682 	}
22683 
22684 	return (pa != NULL);
22685 }
22686 
22687 /*
22688  * Create hardware checksum attribute and fill it with the values passed.
22689  */
22690 boolean_t
22691 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
22692     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
22693 {
22694 	pattr_t *pa;
22695 	pattrinfo_t pa_info;
22696 
22697 	ASSERT(mmd != NULL);
22698 
22699 	pa_info.type = PATTR_HCKSUM;
22700 	pa_info.len = sizeof (pattr_hcksum_t);
22701 
22702 	/* create and associate the attribute */
22703 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22704 	if (pa != NULL) {
22705 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
22706 
22707 		hck->hcksum_start_offset = start_offset;
22708 		hck->hcksum_stuff_offset = stuff_offset;
22709 		hck->hcksum_end_offset = end_offset;
22710 		hck->hcksum_flags = flags;
22711 	}
22712 	return (pa != NULL);
22713 }
22714 
22715 /*
22716  * Create zerocopy attribute and fill it with the specified flags
22717  */
22718 boolean_t
22719 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
22720 {
22721 	pattr_t *pa;
22722 	pattrinfo_t pa_info;
22723 
22724 	ASSERT(mmd != NULL);
22725 	pa_info.type = PATTR_ZCOPY;
22726 	pa_info.len = sizeof (pattr_zcopy_t);
22727 
22728 	/* create and associate the attribute */
22729 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22730 	if (pa != NULL) {
22731 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
22732 
22733 		zcopy->zcopy_flags = flags;
22734 	}
22735 	return (pa != NULL);
22736 }
22737 
22738 /*
22739  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
22740  * block chain. We could rewrite to handle arbitrary message block chains but
22741  * that would make the code complicated and slow. Right now there three
22742  * restrictions:
22743  *
22744  *   1. The first message block must contain the complete IP header and
22745  *	at least 1 byte of payload data.
22746  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
22747  *	so that we can use a single Multidata message.
22748  *   3. No frag must be distributed over two or more message blocks so
22749  *	that we don't need more than two packet descriptors per frag.
22750  *
22751  * The above restrictions allow us to support userland applications (which
22752  * will send down a single message block) and NFS over UDP (which will
22753  * send down a chain of at most three message blocks).
22754  *
22755  * We also don't use MDT for payloads with less than or equal to
22756  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
22757  */
22758 boolean_t
22759 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
22760 {
22761 	int	blocks;
22762 	ssize_t	total, missing, size;
22763 
22764 	ASSERT(mp != NULL);
22765 	ASSERT(hdr_len > 0);
22766 
22767 	size = MBLKL(mp) - hdr_len;
22768 	if (size <= 0)
22769 		return (B_FALSE);
22770 
22771 	/* The first mblk contains the header and some payload. */
22772 	blocks = 1;
22773 	total = size;
22774 	size %= len;
22775 	missing = (size == 0) ? 0 : (len - size);
22776 	mp = mp->b_cont;
22777 
22778 	while (mp != NULL) {
22779 		/*
22780 		 * Give up if we encounter a zero length message block.
22781 		 * In practice, this should rarely happen and therefore
22782 		 * not worth the trouble of freeing and re-linking the
22783 		 * mblk from the chain to handle such case.
22784 		 */
22785 		if ((size = MBLKL(mp)) == 0)
22786 			return (B_FALSE);
22787 
22788 		/* Too many payload buffers for a single Multidata message? */
22789 		if (++blocks > MULTIDATA_MAX_PBUFS)
22790 			return (B_FALSE);
22791 
22792 		total += size;
22793 		/* Is a frag distributed over two or more message blocks? */
22794 		if (missing > size)
22795 			return (B_FALSE);
22796 		size -= missing;
22797 
22798 		size %= len;
22799 		missing = (size == 0) ? 0 : (len - size);
22800 
22801 		mp = mp->b_cont;
22802 	}
22803 
22804 	return (total > ip_wput_frag_mdt_min);
22805 }
22806 
22807 /*
22808  * Outbound IPv4 fragmentation routine using MDT.
22809  */
22810 static void
22811 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
22812     uint32_t frag_flag, int offset)
22813 {
22814 	ipha_t		*ipha_orig;
22815 	int		i1, ip_data_end;
22816 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
22817 	mblk_t		*hdr_mp, *md_mp = NULL;
22818 	unsigned char	*hdr_ptr, *pld_ptr;
22819 	multidata_t	*mmd;
22820 	ip_pdescinfo_t	pdi;
22821 
22822 	ASSERT(DB_TYPE(mp) == M_DATA);
22823 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
22824 
22825 	ipha_orig = (ipha_t *)mp->b_rptr;
22826 	mp->b_rptr += sizeof (ipha_t);
22827 
22828 	/* Calculate how many packets we will send out */
22829 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
22830 	pkts = (i1 + len - 1) / len;
22831 	ASSERT(pkts > 1);
22832 
22833 	/* Allocate a message block which will hold all the IP Headers. */
22834 	wroff = ip_wroff_extra;
22835 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
22836 
22837 	i1 = pkts * hdr_chunk_len;
22838 	/*
22839 	 * Create the header buffer, Multidata and destination address
22840 	 * and SAP attribute that should be associated with it.
22841 	 */
22842 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
22843 	    ((hdr_mp->b_wptr += i1),
22844 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
22845 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
22846 		freemsg(mp);
22847 		if (md_mp == NULL) {
22848 			freemsg(hdr_mp);
22849 		} else {
22850 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
22851 			freemsg(md_mp);
22852 		}
22853 		IP_STAT(ip_frag_mdt_allocfail);
22854 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
22855 		return;
22856 	}
22857 	IP_STAT(ip_frag_mdt_allocd);
22858 
22859 	/*
22860 	 * Add a payload buffer to the Multidata; this operation must not
22861 	 * fail, or otherwise our logic in this routine is broken.  There
22862 	 * is no memory allocation done by the routine, so any returned
22863 	 * failure simply tells us that we've done something wrong.
22864 	 *
22865 	 * A failure tells us that either we're adding the same payload
22866 	 * buffer more than once, or we're trying to add more buffers than
22867 	 * allowed.  None of the above cases should happen, and we panic
22868 	 * because either there's horrible heap corruption, and/or
22869 	 * programming mistake.
22870 	 */
22871 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22872 		goto pbuf_panic;
22873 
22874 	hdr_ptr = hdr_mp->b_rptr;
22875 	pld_ptr = mp->b_rptr;
22876 
22877 	/* Establish the ending byte offset, based on the starting offset. */
22878 	offset <<= 3;
22879 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
22880 	    IP_SIMPLE_HDR_LENGTH;
22881 
22882 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
22883 
22884 	while (pld_ptr < mp->b_wptr) {
22885 		ipha_t		*ipha;
22886 		uint16_t	offset_and_flags;
22887 		uint16_t	ip_len;
22888 		int		error;
22889 
22890 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
22891 		ipha = (ipha_t *)(hdr_ptr + wroff);
22892 		ASSERT(OK_32PTR(ipha));
22893 		*ipha = *ipha_orig;
22894 
22895 		if (ip_data_end - offset > len) {
22896 			offset_and_flags = IPH_MF;
22897 		} else {
22898 			/*
22899 			 * Last frag. Set len to the length of this last piece.
22900 			 */
22901 			len = ip_data_end - offset;
22902 			/* A frag of a frag might have IPH_MF non-zero */
22903 			offset_and_flags =
22904 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22905 			    IPH_MF;
22906 		}
22907 		offset_and_flags |= (uint16_t)(offset >> 3);
22908 		offset_and_flags |= (uint16_t)frag_flag;
22909 		/* Store the offset and flags in the IP header. */
22910 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22911 
22912 		/* Store the length in the IP header. */
22913 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
22914 		ipha->ipha_length = htons(ip_len);
22915 
22916 		/*
22917 		 * Set the IP header checksum.  Note that mp is just
22918 		 * the header, so this is easy to pass to ip_csum.
22919 		 */
22920 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22921 
22922 		/*
22923 		 * Record offset and size of header and data of the next packet
22924 		 * in the multidata message.
22925 		 */
22926 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
22927 		PDESC_PLD_INIT(&pdi);
22928 		i1 = MIN(mp->b_wptr - pld_ptr, len);
22929 		ASSERT(i1 > 0);
22930 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
22931 		if (i1 == len) {
22932 			pld_ptr += len;
22933 		} else {
22934 			i1 = len - i1;
22935 			mp = mp->b_cont;
22936 			ASSERT(mp != NULL);
22937 			ASSERT(MBLKL(mp) >= i1);
22938 			/*
22939 			 * Attach the next payload message block to the
22940 			 * multidata message.
22941 			 */
22942 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22943 				goto pbuf_panic;
22944 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
22945 			pld_ptr = mp->b_rptr + i1;
22946 		}
22947 
22948 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
22949 		    KM_NOSLEEP)) == NULL) {
22950 			/*
22951 			 * Any failure other than ENOMEM indicates that we
22952 			 * have passed in invalid pdesc info or parameters
22953 			 * to mmd_addpdesc, which must not happen.
22954 			 *
22955 			 * EINVAL is a result of failure on boundary checks
22956 			 * against the pdesc info contents.  It should not
22957 			 * happen, and we panic because either there's
22958 			 * horrible heap corruption, and/or programming
22959 			 * mistake.
22960 			 */
22961 			if (error != ENOMEM) {
22962 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
22963 				    "pdesc logic error detected for "
22964 				    "mmd %p pinfo %p (%d)\n",
22965 				    (void *)mmd, (void *)&pdi, error);
22966 				/* NOTREACHED */
22967 			}
22968 			IP_STAT(ip_frag_mdt_addpdescfail);
22969 			/* Free unattached payload message blocks as well */
22970 			md_mp->b_cont = mp->b_cont;
22971 			goto free_mmd;
22972 		}
22973 
22974 		/* Advance fragment offset. */
22975 		offset += len;
22976 
22977 		/* Advance to location for next header in the buffer. */
22978 		hdr_ptr += hdr_chunk_len;
22979 
22980 		/* Did we reach the next payload message block? */
22981 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
22982 			mp = mp->b_cont;
22983 			/*
22984 			 * Attach the next message block with payload
22985 			 * data to the multidata message.
22986 			 */
22987 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22988 				goto pbuf_panic;
22989 			pld_ptr = mp->b_rptr;
22990 		}
22991 	}
22992 
22993 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
22994 	ASSERT(mp->b_wptr == pld_ptr);
22995 
22996 	/* Update IP statistics */
22997 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
22998 	BUMP_MIB(&ip_mib, ipFragOKs);
22999 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
23000 
23001 	if (pkt_type == OB_PKT) {
23002 		ire->ire_ob_pkt_count += pkts;
23003 		if (ire->ire_ipif != NULL)
23004 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23005 	} else {
23006 		/*
23007 		 * The type is IB_PKT in the forwarding path and in
23008 		 * the mobile IP case when the packet is being reverse-
23009 		 * tunneled to the home agent.
23010 		 */
23011 		ire->ire_ib_pkt_count += pkts;
23012 		ASSERT(!IRE_IS_LOCAL(ire));
23013 		if (ire->ire_type & IRE_BROADCAST)
23014 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23015 		else
23016 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23017 	}
23018 	ire->ire_last_used_time = lbolt;
23019 	/* Send it down */
23020 	putnext(ire->ire_stq, md_mp);
23021 	return;
23022 
23023 pbuf_panic:
23024 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23025 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23026 	    pbuf_idx);
23027 	/* NOTREACHED */
23028 }
23029 
23030 /*
23031  * Outbound IP fragmentation routine.
23032  *
23033  * NOTE : This routine does not ire_refrele the ire that is passed in
23034  * as the argument.
23035  */
23036 static void
23037 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23038     uint32_t frag_flag, zoneid_t zoneid)
23039 {
23040 	int		i1;
23041 	mblk_t		*ll_hdr_mp;
23042 	int 		ll_hdr_len;
23043 	int		hdr_len;
23044 	mblk_t		*hdr_mp;
23045 	ipha_t		*ipha;
23046 	int		ip_data_end;
23047 	int		len;
23048 	mblk_t		*mp = mp_orig;
23049 	int		offset;
23050 	queue_t		*q;
23051 	uint32_t	v_hlen_tos_len;
23052 	mblk_t		*first_mp;
23053 	boolean_t	mctl_present;
23054 	ill_t		*ill;
23055 	mblk_t		*xmit_mp;
23056 	mblk_t		*carve_mp;
23057 	ire_t		*ire1 = NULL;
23058 	ire_t		*save_ire = NULL;
23059 	mblk_t  	*next_mp = NULL;
23060 	boolean_t	last_frag = B_FALSE;
23061 	boolean_t	multirt_send = B_FALSE;
23062 	ire_t		*first_ire = NULL;
23063 	irb_t		*irb = NULL;
23064 
23065 	/*
23066 	 * IPSEC does not allow hw accelerated packets to be fragmented
23067 	 * This check is made in ip_wput_ipsec_out prior to coming here
23068 	 * via ip_wput_ire_fragmentit.
23069 	 *
23070 	 * If at this point we have an ire whose ARP request has not
23071 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23072 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23073 	 * This packet and all fragmentable packets for this ire will
23074 	 * continue to get dropped while ire_nce->nce_state remains in
23075 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23076 	 * ND_REACHABLE, all subsquent large packets for this ire will
23077 	 * get fragemented and sent out by this function.
23078 	 */
23079 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23080 		/* If nce_state is ND_INITIAL, trigger ARP query */
23081 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23082 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23083 		    " -  dropping packet\n"));
23084 		BUMP_MIB(&ip_mib, ipFragFails);
23085 		freemsg(mp);
23086 		return;
23087 	}
23088 
23089 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23090 	    "ip_wput_frag_start:");
23091 
23092 	if (mp->b_datap->db_type == M_CTL) {
23093 		first_mp = mp;
23094 		mp_orig = mp = mp->b_cont;
23095 		mctl_present = B_TRUE;
23096 	} else {
23097 		first_mp = mp;
23098 		mctl_present = B_FALSE;
23099 	}
23100 
23101 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23102 	ipha = (ipha_t *)mp->b_rptr;
23103 
23104 	/*
23105 	 * If the Don't Fragment flag is on, generate an ICMP destination
23106 	 * unreachable, fragmentation needed.
23107 	 */
23108 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23109 	if (offset & IPH_DF) {
23110 		BUMP_MIB(&ip_mib, ipFragFails);
23111 		/*
23112 		 * Need to compute hdr checksum if called from ip_wput_ire.
23113 		 * Note that ip_rput_forward verifies the checksum before
23114 		 * calling this routine so in that case this is a noop.
23115 		 */
23116 		ipha->ipha_hdr_checksum = 0;
23117 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23118 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid);
23119 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23120 		    "ip_wput_frag_end:(%S)",
23121 		    "don't fragment");
23122 		return;
23123 	}
23124 	if (mctl_present)
23125 		freeb(first_mp);
23126 	/*
23127 	 * Establish the starting offset.  May not be zero if we are fragging
23128 	 * a fragment that is being forwarded.
23129 	 */
23130 	offset = offset & IPH_OFFSET;
23131 
23132 	/* TODO why is this test needed? */
23133 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23134 	if (((max_frag - LENGTH) & ~7) < 8) {
23135 		/* TODO: notify ulp somehow */
23136 		BUMP_MIB(&ip_mib, ipFragFails);
23137 		freemsg(mp);
23138 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23139 		    "ip_wput_frag_end:(%S)",
23140 		    "len < 8");
23141 		return;
23142 	}
23143 
23144 	hdr_len = (V_HLEN & 0xF) << 2;
23145 
23146 	ipha->ipha_hdr_checksum = 0;
23147 
23148 	/*
23149 	 * Establish the number of bytes maximum per frag, after putting
23150 	 * in the header.
23151 	 */
23152 	len = (max_frag - hdr_len) & ~7;
23153 
23154 	/* Check if we can use MDT to send out the frags. */
23155 	ASSERT(!IRE_IS_LOCAL(ire));
23156 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
23157 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
23158 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
23159 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23160 		ASSERT(ill->ill_mdt_capab != NULL);
23161 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23162 			/*
23163 			 * If MDT has been previously turned off in the past,
23164 			 * and we currently can do MDT (due to IPQoS policy
23165 			 * removal, etc.) then enable it for this interface.
23166 			 */
23167 			ill->ill_mdt_capab->ill_mdt_on = 1;
23168 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23169 			    ill->ill_name));
23170 		}
23171 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23172 		    offset);
23173 		return;
23174 	}
23175 
23176 	/* Get a copy of the header for the trailing frags */
23177 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
23178 	if (!hdr_mp) {
23179 		BUMP_MIB(&ip_mib, ipOutDiscards);
23180 		freemsg(mp);
23181 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23182 		    "ip_wput_frag_end:(%S)",
23183 		    "couldn't copy hdr");
23184 		return;
23185 	}
23186 	if (DB_CRED(mp) != NULL)
23187 		mblk_setcred(hdr_mp, DB_CRED(mp));
23188 
23189 	/* Store the starting offset, with the MoreFrags flag. */
23190 	i1 = offset | IPH_MF | frag_flag;
23191 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23192 
23193 	/* Establish the ending byte offset, based on the starting offset. */
23194 	offset <<= 3;
23195 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23196 
23197 	/* Store the length of the first fragment in the IP header. */
23198 	i1 = len + hdr_len;
23199 	ASSERT(i1 <= IP_MAXPACKET);
23200 	ipha->ipha_length = htons((uint16_t)i1);
23201 
23202 	/*
23203 	 * Compute the IP header checksum for the first frag.  We have to
23204 	 * watch out that we stop at the end of the header.
23205 	 */
23206 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23207 
23208 	/*
23209 	 * Now carve off the first frag.  Note that this will include the
23210 	 * original IP header.
23211 	 */
23212 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
23213 		BUMP_MIB(&ip_mib, ipOutDiscards);
23214 		freeb(hdr_mp);
23215 		freemsg(mp_orig);
23216 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23217 		    "ip_wput_frag_end:(%S)",
23218 		    "couldn't carve first");
23219 		return;
23220 	}
23221 
23222 	/*
23223 	 * Multirouting case. Each fragment is replicated
23224 	 * via all non-condemned RTF_MULTIRT routes
23225 	 * currently resolved.
23226 	 * We ensure that first_ire is the first RTF_MULTIRT
23227 	 * ire in the bucket.
23228 	 */
23229 	if (ire->ire_flags & RTF_MULTIRT) {
23230 		irb = ire->ire_bucket;
23231 		ASSERT(irb != NULL);
23232 
23233 		multirt_send = B_TRUE;
23234 
23235 		/* Make sure we do not omit any multiroute ire. */
23236 		IRB_REFHOLD(irb);
23237 		for (first_ire = irb->irb_ire;
23238 		    first_ire != NULL;
23239 		    first_ire = first_ire->ire_next) {
23240 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23241 			    (first_ire->ire_addr == ire->ire_addr) &&
23242 			    !(first_ire->ire_marks &
23243 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23244 				break;
23245 		}
23246 
23247 		if (first_ire != NULL) {
23248 			if (first_ire != ire) {
23249 				IRE_REFHOLD(first_ire);
23250 				/*
23251 				 * Do not release the ire passed in
23252 				 * as the argument.
23253 				 */
23254 				ire = first_ire;
23255 			} else {
23256 				first_ire = NULL;
23257 			}
23258 		}
23259 		IRB_REFRELE(irb);
23260 
23261 		/*
23262 		 * Save the first ire; we will need to restore it
23263 		 * for the trailing frags.
23264 		 * We REFHOLD save_ire, as each iterated ire will be
23265 		 * REFRELEd.
23266 		 */
23267 		save_ire = ire;
23268 		IRE_REFHOLD(save_ire);
23269 	}
23270 
23271 	/*
23272 	 * First fragment emission loop.
23273 	 * In most cases, the emission loop below is entered only
23274 	 * once. Only in the case where the ire holds the RTF_MULTIRT
23275 	 * flag, do we loop to process all RTF_MULTIRT ires in the
23276 	 * bucket, and send the fragment through all crossed
23277 	 * RTF_MULTIRT routes.
23278 	 */
23279 	do {
23280 		if (ire->ire_flags & RTF_MULTIRT) {
23281 			/*
23282 			 * We are in a multiple send case, need to get
23283 			 * the next ire and make a copy of the packet.
23284 			 * ire1 holds here the next ire to process in the
23285 			 * bucket. If multirouting is expected,
23286 			 * any non-RTF_MULTIRT ire that has the
23287 			 * right destination address is ignored.
23288 			 *
23289 			 * We have to take into account the MTU of
23290 			 * each walked ire. max_frag is set by the
23291 			 * the caller and generally refers to
23292 			 * the primary ire entry. Here we ensure that
23293 			 * no route with a lower MTU will be used, as
23294 			 * fragments are carved once for all ires,
23295 			 * then replicated.
23296 			 */
23297 			ASSERT(irb != NULL);
23298 			IRB_REFHOLD(irb);
23299 			for (ire1 = ire->ire_next;
23300 			    ire1 != NULL;
23301 			    ire1 = ire1->ire_next) {
23302 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23303 					continue;
23304 				if (ire1->ire_addr != ire->ire_addr)
23305 					continue;
23306 				if (ire1->ire_marks &
23307 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23308 					continue;
23309 				/*
23310 				 * Ensure we do not exceed the MTU
23311 				 * of the next route.
23312 				 */
23313 				if (ire1->ire_max_frag < max_frag) {
23314 					ip_multirt_bad_mtu(ire1, max_frag);
23315 					continue;
23316 				}
23317 
23318 				/* Got one. */
23319 				IRE_REFHOLD(ire1);
23320 				break;
23321 			}
23322 			IRB_REFRELE(irb);
23323 
23324 			if (ire1 != NULL) {
23325 				next_mp = copyb(mp);
23326 				if ((next_mp == NULL) ||
23327 				    ((mp->b_cont != NULL) &&
23328 				    ((next_mp->b_cont =
23329 				    dupmsg(mp->b_cont)) == NULL))) {
23330 					freemsg(next_mp);
23331 					next_mp = NULL;
23332 					ire_refrele(ire1);
23333 					ire1 = NULL;
23334 				}
23335 			}
23336 
23337 			/* Last multiroute ire; don't loop anymore. */
23338 			if (ire1 == NULL) {
23339 				multirt_send = B_FALSE;
23340 			}
23341 		}
23342 
23343 		ll_hdr_len = 0;
23344 		LOCK_IRE_FP_MP(ire);
23345 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23346 		if (ll_hdr_mp != NULL) {
23347 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23348 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
23349 		} else {
23350 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
23351 		}
23352 
23353 		/* If there is a transmit header, get a copy for this frag. */
23354 		/*
23355 		 * TODO: should check db_ref before calling ip_carve_mp since
23356 		 * it might give us a dup.
23357 		 */
23358 		if (!ll_hdr_mp) {
23359 			/* No xmit header. */
23360 			xmit_mp = mp;
23361 
23362 		/* We have a link-layer header that can fit in our mblk. */
23363 		} else if (mp->b_datap->db_ref == 1 &&
23364 		    ll_hdr_len != 0 &&
23365 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23366 			/* M_DATA fastpath */
23367 			mp->b_rptr -= ll_hdr_len;
23368 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
23369 			xmit_mp = mp;
23370 
23371 		/* Corner case if copyb has failed */
23372 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
23373 			UNLOCK_IRE_FP_MP(ire);
23374 			BUMP_MIB(&ip_mib, ipOutDiscards);
23375 			freeb(hdr_mp);
23376 			freemsg(mp);
23377 			freemsg(mp_orig);
23378 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23379 			    "ip_wput_frag_end:(%S)",
23380 			    "discard");
23381 
23382 			if (multirt_send) {
23383 				ASSERT(ire1);
23384 				ASSERT(next_mp);
23385 
23386 				freemsg(next_mp);
23387 				ire_refrele(ire1);
23388 			}
23389 			if (save_ire != NULL)
23390 				IRE_REFRELE(save_ire);
23391 
23392 			if (first_ire != NULL)
23393 				ire_refrele(first_ire);
23394 			return;
23395 
23396 		/*
23397 		 * Case of res_mp OR the fastpath mp can't fit
23398 		 * in the mblk
23399 		 */
23400 		} else {
23401 			xmit_mp->b_cont = mp;
23402 			if (DB_CRED(mp) != NULL)
23403 				mblk_setcred(xmit_mp, DB_CRED(mp));
23404 			/*
23405 			 * Get priority marking, if any.
23406 			 * We propagate the CoS marking from the
23407 			 * original packet that went to QoS processing
23408 			 * in ip_wput_ire to the newly carved mp.
23409 			 */
23410 			if (DB_TYPE(xmit_mp) == M_DATA)
23411 				xmit_mp->b_band = mp->b_band;
23412 		}
23413 		UNLOCK_IRE_FP_MP(ire);
23414 		q = ire->ire_stq;
23415 		BUMP_MIB(&ip_mib, ipFragCreates);
23416 		putnext(q, xmit_mp);
23417 		if (pkt_type != OB_PKT) {
23418 			/*
23419 			 * Update the packet count of trailing
23420 			 * RTF_MULTIRT ires.
23421 			 */
23422 			UPDATE_OB_PKT_COUNT(ire);
23423 		}
23424 
23425 		if (multirt_send) {
23426 			/*
23427 			 * We are in a multiple send case; look for
23428 			 * the next ire and re-enter the loop.
23429 			 */
23430 			ASSERT(ire1);
23431 			ASSERT(next_mp);
23432 			/* REFRELE the current ire before looping */
23433 			ire_refrele(ire);
23434 			ire = ire1;
23435 			ire1 = NULL;
23436 			mp = next_mp;
23437 			next_mp = NULL;
23438 		}
23439 	} while (multirt_send);
23440 
23441 	ASSERT(ire1 == NULL);
23442 
23443 	/* Restore the original ire; we need it for the trailing frags */
23444 	if (save_ire != NULL) {
23445 		/* REFRELE the last iterated ire */
23446 		ire_refrele(ire);
23447 		/* save_ire has been REFHOLDed */
23448 		ire = save_ire;
23449 		save_ire = NULL;
23450 		q = ire->ire_stq;
23451 	}
23452 
23453 	if (pkt_type == OB_PKT) {
23454 		UPDATE_OB_PKT_COUNT(ire);
23455 	} else {
23456 		UPDATE_IB_PKT_COUNT(ire);
23457 	}
23458 
23459 	/* Advance the offset to the second frag starting point. */
23460 	offset += len;
23461 	/*
23462 	 * Update hdr_len from the copied header - there might be less options
23463 	 * in the later fragments.
23464 	 */
23465 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
23466 	/* Loop until done. */
23467 	for (;;) {
23468 		uint16_t	offset_and_flags;
23469 		uint16_t	ip_len;
23470 
23471 		if (ip_data_end - offset > len) {
23472 			/*
23473 			 * Carve off the appropriate amount from the original
23474 			 * datagram.
23475 			 */
23476 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23477 				mp = NULL;
23478 				break;
23479 			}
23480 			/*
23481 			 * More frags after this one.  Get another copy
23482 			 * of the header.
23483 			 */
23484 			if (carve_mp->b_datap->db_ref == 1 &&
23485 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23486 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23487 				/* Inline IP header */
23488 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23489 				    hdr_mp->b_rptr;
23490 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23491 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23492 				mp = carve_mp;
23493 			} else {
23494 				if (!(mp = copyb(hdr_mp))) {
23495 					freemsg(carve_mp);
23496 					break;
23497 				}
23498 				/* Get priority marking, if any. */
23499 				mp->b_band = carve_mp->b_band;
23500 				mp->b_cont = carve_mp;
23501 			}
23502 			ipha = (ipha_t *)mp->b_rptr;
23503 			offset_and_flags = IPH_MF;
23504 		} else {
23505 			/*
23506 			 * Last frag.  Consume the header. Set len to
23507 			 * the length of this last piece.
23508 			 */
23509 			len = ip_data_end - offset;
23510 
23511 			/*
23512 			 * Carve off the appropriate amount from the original
23513 			 * datagram.
23514 			 */
23515 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23516 				mp = NULL;
23517 				break;
23518 			}
23519 			if (carve_mp->b_datap->db_ref == 1 &&
23520 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23521 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23522 				/* Inline IP header */
23523 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23524 				    hdr_mp->b_rptr;
23525 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23526 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23527 				mp = carve_mp;
23528 				freeb(hdr_mp);
23529 				hdr_mp = mp;
23530 			} else {
23531 				mp = hdr_mp;
23532 				/* Get priority marking, if any. */
23533 				mp->b_band = carve_mp->b_band;
23534 				mp->b_cont = carve_mp;
23535 			}
23536 			ipha = (ipha_t *)mp->b_rptr;
23537 			/* A frag of a frag might have IPH_MF non-zero */
23538 			offset_and_flags =
23539 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23540 			    IPH_MF;
23541 		}
23542 		offset_and_flags |= (uint16_t)(offset >> 3);
23543 		offset_and_flags |= (uint16_t)frag_flag;
23544 		/* Store the offset and flags in the IP header. */
23545 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23546 
23547 		/* Store the length in the IP header. */
23548 		ip_len = (uint16_t)(len + hdr_len);
23549 		ipha->ipha_length = htons(ip_len);
23550 
23551 		/*
23552 		 * Set the IP header checksum.	Note that mp is just
23553 		 * the header, so this is easy to pass to ip_csum.
23554 		 */
23555 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23556 
23557 		/* Attach a transmit header, if any, and ship it. */
23558 		if (pkt_type == OB_PKT) {
23559 			UPDATE_OB_PKT_COUNT(ire);
23560 		} else {
23561 			UPDATE_IB_PKT_COUNT(ire);
23562 		}
23563 
23564 		if (ire->ire_flags & RTF_MULTIRT) {
23565 			irb = ire->ire_bucket;
23566 			ASSERT(irb != NULL);
23567 
23568 			multirt_send = B_TRUE;
23569 
23570 			/*
23571 			 * Save the original ire; we will need to restore it
23572 			 * for the tailing frags.
23573 			 */
23574 			save_ire = ire;
23575 			IRE_REFHOLD(save_ire);
23576 		}
23577 		/*
23578 		 * Emission loop for this fragment, similar
23579 		 * to what is done for the first fragment.
23580 		 */
23581 		do {
23582 			if (multirt_send) {
23583 				/*
23584 				 * We are in a multiple send case, need to get
23585 				 * the next ire and make a copy of the packet.
23586 				 */
23587 				ASSERT(irb != NULL);
23588 				IRB_REFHOLD(irb);
23589 				for (ire1 = ire->ire_next;
23590 				    ire1 != NULL;
23591 				    ire1 = ire1->ire_next) {
23592 					if (!(ire1->ire_flags & RTF_MULTIRT))
23593 						continue;
23594 					if (ire1->ire_addr != ire->ire_addr)
23595 						continue;
23596 					if (ire1->ire_marks &
23597 					    (IRE_MARK_CONDEMNED|
23598 						IRE_MARK_HIDDEN))
23599 						continue;
23600 					/*
23601 					 * Ensure we do not exceed the MTU
23602 					 * of the next route.
23603 					 */
23604 					if (ire1->ire_max_frag < max_frag) {
23605 						ip_multirt_bad_mtu(ire1,
23606 						    max_frag);
23607 						continue;
23608 					}
23609 
23610 					/* Got one. */
23611 					IRE_REFHOLD(ire1);
23612 					break;
23613 				}
23614 				IRB_REFRELE(irb);
23615 
23616 				if (ire1 != NULL) {
23617 					next_mp = copyb(mp);
23618 					if ((next_mp == NULL) ||
23619 					    ((mp->b_cont != NULL) &&
23620 					    ((next_mp->b_cont =
23621 					    dupmsg(mp->b_cont)) == NULL))) {
23622 						freemsg(next_mp);
23623 						next_mp = NULL;
23624 						ire_refrele(ire1);
23625 						ire1 = NULL;
23626 					}
23627 				}
23628 
23629 				/* Last multiroute ire; don't loop anymore. */
23630 				if (ire1 == NULL) {
23631 					multirt_send = B_FALSE;
23632 				}
23633 			}
23634 
23635 			/* Update transmit header */
23636 			ll_hdr_len = 0;
23637 			LOCK_IRE_FP_MP(ire);
23638 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23639 			if (ll_hdr_mp != NULL) {
23640 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23641 				ll_hdr_len = MBLKL(ll_hdr_mp);
23642 			} else {
23643 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
23644 			}
23645 
23646 			if (!ll_hdr_mp) {
23647 				xmit_mp = mp;
23648 
23649 			/*
23650 			 * We have link-layer header that can fit in
23651 			 * our mblk.
23652 			 */
23653 			} else if (mp->b_datap->db_ref == 1 &&
23654 			    ll_hdr_len != 0 &&
23655 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23656 				/* M_DATA fastpath */
23657 				mp->b_rptr -= ll_hdr_len;
23658 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
23659 				    ll_hdr_len);
23660 				xmit_mp = mp;
23661 
23662 			/*
23663 			 * Case of res_mp OR the fastpath mp can't fit
23664 			 * in the mblk
23665 			 */
23666 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
23667 				xmit_mp->b_cont = mp;
23668 				if (DB_CRED(mp) != NULL)
23669 					mblk_setcred(xmit_mp, DB_CRED(mp));
23670 				/* Get priority marking, if any. */
23671 				if (DB_TYPE(xmit_mp) == M_DATA)
23672 					xmit_mp->b_band = mp->b_band;
23673 
23674 			/* Corner case if copyb failed */
23675 			} else {
23676 				/*
23677 				 * Exit both the replication and
23678 				 * fragmentation loops.
23679 				 */
23680 				UNLOCK_IRE_FP_MP(ire);
23681 				goto drop_pkt;
23682 			}
23683 			UNLOCK_IRE_FP_MP(ire);
23684 			BUMP_MIB(&ip_mib, ipFragCreates);
23685 			putnext(q, xmit_mp);
23686 
23687 			if (pkt_type != OB_PKT) {
23688 				/*
23689 				 * Update the packet count of trailing
23690 				 * RTF_MULTIRT ires.
23691 				 */
23692 				UPDATE_OB_PKT_COUNT(ire);
23693 			}
23694 
23695 			/* All done if we just consumed the hdr_mp. */
23696 			if (mp == hdr_mp) {
23697 				last_frag = B_TRUE;
23698 			}
23699 
23700 			if (multirt_send) {
23701 				/*
23702 				 * We are in a multiple send case; look for
23703 				 * the next ire and re-enter the loop.
23704 				 */
23705 				ASSERT(ire1);
23706 				ASSERT(next_mp);
23707 				/* REFRELE the current ire before looping */
23708 				ire_refrele(ire);
23709 				ire = ire1;
23710 				ire1 = NULL;
23711 				q = ire->ire_stq;
23712 				mp = next_mp;
23713 				next_mp = NULL;
23714 			}
23715 		} while (multirt_send);
23716 		/*
23717 		 * Restore the original ire; we need it for the
23718 		 * trailing frags
23719 		 */
23720 		if (save_ire != NULL) {
23721 			ASSERT(ire1 == NULL);
23722 			/* REFRELE the last iterated ire */
23723 			ire_refrele(ire);
23724 			/* save_ire has been REFHOLDed */
23725 			ire = save_ire;
23726 			q = ire->ire_stq;
23727 			save_ire = NULL;
23728 		}
23729 
23730 		if (last_frag) {
23731 			BUMP_MIB(&ip_mib, ipFragOKs);
23732 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23733 			    "ip_wput_frag_end:(%S)",
23734 			    "consumed hdr_mp");
23735 
23736 			if (first_ire != NULL)
23737 				ire_refrele(first_ire);
23738 			return;
23739 		}
23740 		/* Otherwise, advance and loop. */
23741 		offset += len;
23742 	}
23743 
23744 drop_pkt:
23745 	/* Clean up following allocation failure. */
23746 	BUMP_MIB(&ip_mib, ipOutDiscards);
23747 	freemsg(mp);
23748 	if (mp != hdr_mp)
23749 		freeb(hdr_mp);
23750 	if (mp != mp_orig)
23751 		freemsg(mp_orig);
23752 
23753 	if (save_ire != NULL)
23754 		IRE_REFRELE(save_ire);
23755 	if (first_ire != NULL)
23756 		ire_refrele(first_ire);
23757 
23758 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23759 	    "ip_wput_frag_end:(%S)",
23760 	    "end--alloc failure");
23761 }
23762 
23763 /*
23764  * Copy the header plus those options which have the copy bit set
23765  */
23766 static mblk_t *
23767 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
23768 {
23769 	mblk_t	*mp;
23770 	uchar_t	*up;
23771 
23772 	/*
23773 	 * Quick check if we need to look for options without the copy bit
23774 	 * set
23775 	 */
23776 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
23777 	if (!mp)
23778 		return (mp);
23779 	mp->b_rptr += ip_wroff_extra;
23780 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
23781 		bcopy(rptr, mp->b_rptr, hdr_len);
23782 		mp->b_wptr += hdr_len + ip_wroff_extra;
23783 		return (mp);
23784 	}
23785 	up  = mp->b_rptr;
23786 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
23787 	up += IP_SIMPLE_HDR_LENGTH;
23788 	rptr += IP_SIMPLE_HDR_LENGTH;
23789 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
23790 	while (hdr_len > 0) {
23791 		uint32_t optval;
23792 		uint32_t optlen;
23793 
23794 		optval = *rptr;
23795 		if (optval == IPOPT_EOL)
23796 			break;
23797 		if (optval == IPOPT_NOP)
23798 			optlen = 1;
23799 		else
23800 			optlen = rptr[1];
23801 		if (optval & IPOPT_COPY) {
23802 			bcopy(rptr, up, optlen);
23803 			up += optlen;
23804 		}
23805 		rptr += optlen;
23806 		hdr_len -= optlen;
23807 	}
23808 	/*
23809 	 * Make sure that we drop an even number of words by filling
23810 	 * with EOL to the next word boundary.
23811 	 */
23812 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
23813 	    hdr_len & 0x3; hdr_len++)
23814 		*up++ = IPOPT_EOL;
23815 	mp->b_wptr = up;
23816 	/* Update header length */
23817 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
23818 	return (mp);
23819 }
23820 
23821 /*
23822  * Delivery to local recipients including fanout to multiple recipients.
23823  * Does not do checksumming of UDP/TCP.
23824  * Note: q should be the read side queue for either the ill or conn.
23825  * Note: rq should be the read side q for the lower (ill) stream.
23826  * We don't send packets to IPPF processing, thus the last argument
23827  * to all the fanout calls are B_FALSE.
23828  */
23829 void
23830 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
23831     int fanout_flags, zoneid_t zoneid)
23832 {
23833 	uint32_t	protocol;
23834 	mblk_t		*first_mp;
23835 	boolean_t	mctl_present;
23836 	int		ire_type;
23837 #define	rptr	((uchar_t *)ipha)
23838 
23839 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
23840 	    "ip_wput_local_start: q %p", q);
23841 
23842 	if (ire != NULL) {
23843 		ire_type = ire->ire_type;
23844 	} else {
23845 		/*
23846 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
23847 		 * packet is not multicast, we can't tell the ire type.
23848 		 */
23849 		ASSERT(CLASSD(ipha->ipha_dst));
23850 		ire_type = IRE_BROADCAST;
23851 	}
23852 
23853 	first_mp = mp;
23854 	if (first_mp->b_datap->db_type == M_CTL) {
23855 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
23856 		if (!io->ipsec_out_secure) {
23857 			/*
23858 			 * This ipsec_out_t was allocated in ip_wput
23859 			 * for multicast packets to store the ill_index.
23860 			 * As this is being delivered locally, we don't
23861 			 * need this anymore.
23862 			 */
23863 			mp = first_mp->b_cont;
23864 			freeb(first_mp);
23865 			first_mp = mp;
23866 			mctl_present = B_FALSE;
23867 		} else {
23868 			mctl_present = B_TRUE;
23869 			mp = first_mp->b_cont;
23870 			ASSERT(mp != NULL);
23871 			ipsec_out_to_in(first_mp);
23872 		}
23873 	} else {
23874 		mctl_present = B_FALSE;
23875 	}
23876 
23877 	loopback_packets++;
23878 
23879 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
23880 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
23881 	if (!IS_SIMPLE_IPH(ipha)) {
23882 		ip_wput_local_options(ipha);
23883 	}
23884 
23885 	protocol = ipha->ipha_protocol;
23886 	switch (protocol) {
23887 	case IPPROTO_ICMP: {
23888 		ire_t		*ire_zone;
23889 		ilm_t		*ilm;
23890 		mblk_t		*mp1;
23891 		zoneid_t	last_zoneid;
23892 
23893 		if (CLASSD(ipha->ipha_dst) &&
23894 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
23895 			ASSERT(ire_type == IRE_BROADCAST);
23896 			/*
23897 			 * In the multicast case, applications may have joined
23898 			 * the group from different zones, so we need to deliver
23899 			 * the packet to each of them. Loop through the
23900 			 * multicast memberships structures (ilm) on the receive
23901 			 * ill and send a copy of the packet up each matching
23902 			 * one. However, we don't do this for multicasts sent on
23903 			 * the loopback interface (PHYI_LOOPBACK flag set) as
23904 			 * they must stay in the sender's zone.
23905 			 *
23906 			 * ilm_add_v6() ensures that ilms in the same zone are
23907 			 * contiguous in the ill_ilm list. We use this property
23908 			 * to avoid sending duplicates needed when two
23909 			 * applications in the same zone join the same group on
23910 			 * different logical interfaces: we ignore the ilm if
23911 			 * it's zoneid is the same as the last matching one.
23912 			 * In addition, the sending of the packet for
23913 			 * ire_zoneid is delayed until all of the other ilms
23914 			 * have been exhausted.
23915 			 */
23916 			last_zoneid = -1;
23917 			ILM_WALKER_HOLD(ill);
23918 			for (ilm = ill->ill_ilm; ilm != NULL;
23919 			    ilm = ilm->ilm_next) {
23920 				if ((ilm->ilm_flags & ILM_DELETED) ||
23921 				    ipha->ipha_dst != ilm->ilm_addr ||
23922 				    ilm->ilm_zoneid == last_zoneid ||
23923 				    ilm->ilm_zoneid == zoneid ||
23924 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
23925 					continue;
23926 				mp1 = ip_copymsg(first_mp);
23927 				if (mp1 == NULL)
23928 					continue;
23929 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23930 				    mctl_present, B_FALSE, ill,
23931 				    ilm->ilm_zoneid);
23932 				last_zoneid = ilm->ilm_zoneid;
23933 			}
23934 			ILM_WALKER_RELE(ill);
23935 			/*
23936 			 * Loopback case: the sending endpoint has
23937 			 * IP_MULTICAST_LOOP disabled, therefore we don't
23938 			 * dispatch the multicast packet to the sending zone.
23939 			 */
23940 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
23941 				freemsg(first_mp);
23942 				return;
23943 			}
23944 		} else if (ire_type == IRE_BROADCAST) {
23945 			/*
23946 			 * In the broadcast case, there may be many zones
23947 			 * which need a copy of the packet delivered to them.
23948 			 * There is one IRE_BROADCAST per broadcast address
23949 			 * and per zone; we walk those using a helper function.
23950 			 * In addition, the sending of the packet for zoneid is
23951 			 * delayed until all of the other ires have been
23952 			 * processed.
23953 			 */
23954 			IRB_REFHOLD(ire->ire_bucket);
23955 			ire_zone = NULL;
23956 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
23957 			    ire)) != NULL) {
23958 				mp1 = ip_copymsg(first_mp);
23959 				if (mp1 == NULL)
23960 					continue;
23961 
23962 				UPDATE_IB_PKT_COUNT(ire_zone);
23963 				ire_zone->ire_last_used_time = lbolt;
23964 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23965 				    mctl_present, B_FALSE, ill,
23966 				    ire_zone->ire_zoneid);
23967 			}
23968 			IRB_REFRELE(ire->ire_bucket);
23969 		}
23970 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
23971 		    0, mctl_present, B_FALSE, ill, zoneid);
23972 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23973 		    "ip_wput_local_end: q %p (%S)",
23974 		    q, "icmp");
23975 		return;
23976 	}
23977 	case IPPROTO_IGMP:
23978 		if (igmp_input(q, mp, ill)) {
23979 			/* Bad packet - discarded by igmp_input */
23980 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23981 			    "ip_wput_local_end: q %p (%S)",
23982 			    q, "igmp_input--bad packet");
23983 			if (mctl_present)
23984 				freeb(first_mp);
23985 			return;
23986 		}
23987 		/*
23988 		 * igmp_input() may have pulled up the message so ipha needs to
23989 		 * be reinitialized.
23990 		 */
23991 		ipha = (ipha_t *)mp->b_rptr;
23992 		/* deliver to local raw users */
23993 		break;
23994 	case IPPROTO_ENCAP:
23995 		/*
23996 		 * This case is covered by either ip_fanout_proto, or by
23997 		 * the above security processing for self-tunneled packets.
23998 		 */
23999 		break;
24000 	case IPPROTO_UDP: {
24001 		uint16_t	*up;
24002 		uint32_t	ports;
24003 
24004 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
24005 		    UDP_PORTS_OFFSET);
24006 		/* Force a 'valid' checksum. */
24007 		up[3] = 0;
24008 
24009 		ports = *(uint32_t *)up;
24010 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24011 		    (ire_type == IRE_BROADCAST),
24012 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24013 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
24014 		    ill, zoneid);
24015 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24016 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24017 		return;
24018 	}
24019 	case IPPROTO_TCP: {
24020 
24021 		/*
24022 		 * For TCP, discard broadcast packets.
24023 		 */
24024 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24025 			freemsg(first_mp);
24026 			BUMP_MIB(&ip_mib, ipInDiscards);
24027 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24028 			return;
24029 		}
24030 
24031 		if (mp->b_datap->db_type == M_DATA) {
24032 			/*
24033 			 * M_DATA mblk, so init mblk (chain) for no struio().
24034 			 */
24035 			mblk_t	*mp1 = mp;
24036 
24037 			do
24038 				mp1->b_datap->db_struioflag = 0;
24039 			while ((mp1 = mp1->b_cont) != NULL);
24040 		}
24041 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24042 		    <= mp->b_wptr);
24043 		ip_fanout_tcp(q, first_mp, ill, ipha,
24044 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24045 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
24046 		    mctl_present, B_FALSE, zoneid);
24047 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24048 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24049 		return;
24050 	}
24051 	case IPPROTO_SCTP:
24052 	{
24053 		uint32_t	ports;
24054 
24055 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24056 		ip_fanout_sctp(first_mp, ill, ipha, ports,
24057 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24058 		    IP_FF_IP6INFO,
24059 		    mctl_present, B_FALSE, 0, zoneid);
24060 		return;
24061 	}
24062 
24063 	default:
24064 		break;
24065 	}
24066 	/*
24067 	 * Find a client for some other protocol.  We give
24068 	 * copies to multiple clients, if more than one is
24069 	 * bound.
24070 	 */
24071 	ip_fanout_proto(q, first_mp, ill, ipha,
24072 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
24073 	    mctl_present, B_FALSE, ill, zoneid);
24074 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24075 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
24076 #undef	rptr
24077 }
24078 
24079 /*
24080  * Update any source route, record route, or timestamp options.
24081  * Check that we are at end of strict source route.
24082  * The options have been sanity checked by ip_wput_options().
24083  */
24084 static void
24085 ip_wput_local_options(ipha_t *ipha)
24086 {
24087 	ipoptp_t	opts;
24088 	uchar_t		*opt;
24089 	uint8_t		optval;
24090 	uint8_t		optlen;
24091 	ipaddr_t	dst;
24092 	uint32_t	ts;
24093 	ire_t		*ire;
24094 	timestruc_t	now;
24095 
24096 	ip2dbg(("ip_wput_local_options\n"));
24097 	for (optval = ipoptp_first(&opts, ipha);
24098 	    optval != IPOPT_EOL;
24099 	    optval = ipoptp_next(&opts)) {
24100 		opt = opts.ipoptp_cur;
24101 		optlen = opts.ipoptp_len;
24102 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
24103 		switch (optval) {
24104 			uint32_t off;
24105 		case IPOPT_SSRR:
24106 		case IPOPT_LSRR:
24107 			off = opt[IPOPT_OFFSET];
24108 			off--;
24109 			if (optlen < IP_ADDR_LEN ||
24110 			    off > optlen - IP_ADDR_LEN) {
24111 				/* End of source route */
24112 				break;
24113 			}
24114 			/*
24115 			 * This will only happen if two consecutive entries
24116 			 * in the source route contains our address or if
24117 			 * it is a packet with a loose source route which
24118 			 * reaches us before consuming the whole source route
24119 			 */
24120 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
24121 			if (optval == IPOPT_SSRR) {
24122 				return;
24123 			}
24124 			/*
24125 			 * Hack: instead of dropping the packet truncate the
24126 			 * source route to what has been used by filling the
24127 			 * rest with IPOPT_NOP.
24128 			 */
24129 			opt[IPOPT_OLEN] = (uint8_t)off;
24130 			while (off < optlen) {
24131 				opt[off++] = IPOPT_NOP;
24132 			}
24133 			break;
24134 		case IPOPT_RR:
24135 			off = opt[IPOPT_OFFSET];
24136 			off--;
24137 			if (optlen < IP_ADDR_LEN ||
24138 			    off > optlen - IP_ADDR_LEN) {
24139 				/* No more room - ignore */
24140 				ip1dbg((
24141 				    "ip_wput_forward_options: end of RR\n"));
24142 				break;
24143 			}
24144 			dst = htonl(INADDR_LOOPBACK);
24145 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24146 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24147 			break;
24148 		case IPOPT_TS:
24149 			/* Insert timestamp if there is romm */
24150 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24151 			case IPOPT_TS_TSONLY:
24152 				off = IPOPT_TS_TIMELEN;
24153 				break;
24154 			case IPOPT_TS_PRESPEC:
24155 			case IPOPT_TS_PRESPEC_RFC791:
24156 				/* Verify that the address matched */
24157 				off = opt[IPOPT_OFFSET] - 1;
24158 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
24159 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
24160 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
24161 				if (ire == NULL) {
24162 					/* Not for us */
24163 					break;
24164 				}
24165 				ire_refrele(ire);
24166 				/* FALLTHRU */
24167 			case IPOPT_TS_TSANDADDR:
24168 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24169 				break;
24170 			default:
24171 				/*
24172 				 * ip_*put_options should have already
24173 				 * dropped this packet.
24174 				 */
24175 				cmn_err(CE_PANIC, "ip_wput_local_options: "
24176 				    "unknown IT - bug in ip_wput_options?\n");
24177 				return;	/* Keep "lint" happy */
24178 			}
24179 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
24180 				/* Increase overflow counter */
24181 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
24182 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
24183 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
24184 				    (off << 4);
24185 				break;
24186 			}
24187 			off = opt[IPOPT_OFFSET] - 1;
24188 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24189 			case IPOPT_TS_PRESPEC:
24190 			case IPOPT_TS_PRESPEC_RFC791:
24191 			case IPOPT_TS_TSANDADDR:
24192 				dst = htonl(INADDR_LOOPBACK);
24193 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24194 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24195 				/* FALLTHRU */
24196 			case IPOPT_TS_TSONLY:
24197 				off = opt[IPOPT_OFFSET] - 1;
24198 				/* Compute # of milliseconds since midnight */
24199 				gethrestime(&now);
24200 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
24201 				    now.tv_nsec / (NANOSEC / MILLISEC);
24202 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
24203 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
24204 				break;
24205 			}
24206 			break;
24207 		}
24208 	}
24209 }
24210 
24211 /*
24212  * Send out a multicast packet on interface ipif.
24213  * The sender does not have an conn.
24214  * Caller verifies that this isn't a PHYI_LOOPBACK.
24215  */
24216 void
24217 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
24218 {
24219 	ipha_t	*ipha;
24220 	ire_t	*ire;
24221 	ipaddr_t	dst;
24222 	mblk_t		*first_mp;
24223 
24224 	/* igmp_sendpkt always allocates a ipsec_out_t */
24225 	ASSERT(mp->b_datap->db_type == M_CTL);
24226 	ASSERT(!ipif->ipif_isv6);
24227 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
24228 
24229 	first_mp = mp;
24230 	mp = first_mp->b_cont;
24231 	ASSERT(mp->b_datap->db_type == M_DATA);
24232 	ipha = (ipha_t *)mp->b_rptr;
24233 
24234 	/*
24235 	 * Find an IRE which matches the destination and the outgoing
24236 	 * queue (i.e. the outgoing interface.)
24237 	 */
24238 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
24239 		dst = ipif->ipif_pp_dst_addr;
24240 	else
24241 		dst = ipha->ipha_dst;
24242 	/*
24243 	 * The source address has already been initialized by the
24244 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
24245 	 * be sufficient rather than MATCH_IRE_IPIF.
24246 	 *
24247 	 * This function is used for sending IGMP packets. We need
24248 	 * to make sure that we send the packet out of the interface
24249 	 * (ipif->ipif_ill) where we joined the group. This is to
24250 	 * prevent from switches doing IGMP snooping to send us multicast
24251 	 * packets for a given group on the interface we have joined.
24252 	 * If we can't find an ire, igmp_sendpkt has already initialized
24253 	 * ipsec_out_attach_if so that this will not be load spread in
24254 	 * ip_newroute_ipif.
24255 	 */
24256 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
24257 	    MATCH_IRE_ILL);
24258 	if (!ire) {
24259 		/*
24260 		 * Mark this packet to make it be delivered to
24261 		 * ip_wput_ire after the new ire has been
24262 		 * created.
24263 		 */
24264 		mp->b_prev = NULL;
24265 		mp->b_next = NULL;
24266 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
24267 		    zoneid);
24268 		return;
24269 	}
24270 
24271 	/*
24272 	 * Honor the RTF_SETSRC flag; this is the only case
24273 	 * where we force this addr whatever the current src addr is,
24274 	 * because this address is set by igmp_sendpkt(), and
24275 	 * cannot be specified by any user.
24276 	 */
24277 	if (ire->ire_flags & RTF_SETSRC) {
24278 		ipha->ipha_src = ire->ire_src_addr;
24279 	}
24280 
24281 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
24282 }
24283 
24284 /*
24285  * NOTE : This function does not ire_refrele the ire argument passed in.
24286  *
24287  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
24288  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
24289  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
24290  * the ire_lock to access the nce_fp_mp in this case.
24291  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
24292  * prepending a fastpath message IPQoS processing must precede it, we also set
24293  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
24294  * (IPQoS might have set the b_band for CoS marking).
24295  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
24296  * must follow it so that IPQoS can mark the dl_priority field for CoS
24297  * marking, if needed.
24298  */
24299 static mblk_t *
24300 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
24301 {
24302 	uint_t	hlen;
24303 	ipha_t *ipha;
24304 	mblk_t *mp1;
24305 	boolean_t qos_done = B_FALSE;
24306 	uchar_t	*ll_hdr;
24307 
24308 #define	rptr	((uchar_t *)ipha)
24309 
24310 	ipha = (ipha_t *)mp->b_rptr;
24311 	hlen = 0;
24312 	LOCK_IRE_FP_MP(ire);
24313 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
24314 		ASSERT(DB_TYPE(mp1) == M_DATA);
24315 		/* Initiate IPPF processing */
24316 		if ((proc != 0) && IPP_ENABLED(proc)) {
24317 			UNLOCK_IRE_FP_MP(ire);
24318 			ip_process(proc, &mp, ill_index);
24319 			if (mp == NULL)
24320 				return (NULL);
24321 
24322 			ipha = (ipha_t *)mp->b_rptr;
24323 			LOCK_IRE_FP_MP(ire);
24324 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
24325 				qos_done = B_TRUE;
24326 				goto no_fp_mp;
24327 			}
24328 			ASSERT(DB_TYPE(mp1) == M_DATA);
24329 		}
24330 		hlen = MBLKL(mp1);
24331 		/*
24332 		 * Check if we have enough room to prepend fastpath
24333 		 * header
24334 		 */
24335 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
24336 			ll_hdr = rptr - hlen;
24337 			bcopy(mp1->b_rptr, ll_hdr, hlen);
24338 			/*
24339 			 * Set the b_rptr to the start of the link layer
24340 			 * header
24341 			 */
24342 			mp->b_rptr = ll_hdr;
24343 			mp1 = mp;
24344 		} else {
24345 			mp1 = copyb(mp1);
24346 			if (mp1 == NULL)
24347 				goto unlock_err;
24348 			mp1->b_band = mp->b_band;
24349 			mp1->b_cont = mp;
24350 			/*
24351 			 * certain system generated traffic may not
24352 			 * have cred/label in ip header block. This
24353 			 * is true even for a labeled system. But for
24354 			 * labeled traffic, inherit the label in the
24355 			 * new header.
24356 			 */
24357 			if (DB_CRED(mp) != NULL)
24358 				mblk_setcred(mp1, DB_CRED(mp));
24359 			/*
24360 			 * XXX disable ICK_VALID and compute checksum
24361 			 * here; can happen if nce_fp_mp changes and
24362 			 * it can't be copied now due to insufficient
24363 			 * space. (unlikely, fp mp can change, but it
24364 			 * does not increase in length)
24365 			 */
24366 		}
24367 		UNLOCK_IRE_FP_MP(ire);
24368 	} else {
24369 no_fp_mp:
24370 		mp1 = copyb(ire->ire_nce->nce_res_mp);
24371 		if (mp1 == NULL) {
24372 unlock_err:
24373 			UNLOCK_IRE_FP_MP(ire);
24374 			freemsg(mp);
24375 			return (NULL);
24376 		}
24377 		UNLOCK_IRE_FP_MP(ire);
24378 		mp1->b_cont = mp;
24379 		/*
24380 		 * certain system generated traffic may not
24381 		 * have cred/label in ip header block. This
24382 		 * is true even for a labeled system. But for
24383 		 * labeled traffic, inherit the label in the
24384 		 * new header.
24385 		 */
24386 		if (DB_CRED(mp) != NULL)
24387 			mblk_setcred(mp1, DB_CRED(mp));
24388 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
24389 			ip_process(proc, &mp1, ill_index);
24390 			if (mp1 == NULL)
24391 				return (NULL);
24392 		}
24393 	}
24394 	return (mp1);
24395 #undef rptr
24396 }
24397 
24398 /*
24399  * Finish the outbound IPsec processing for an IPv6 packet. This function
24400  * is called from ipsec_out_process() if the IPsec packet was processed
24401  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24402  * asynchronously.
24403  */
24404 void
24405 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
24406     ire_t *ire_arg)
24407 {
24408 	in6_addr_t *v6dstp;
24409 	ire_t *ire;
24410 	mblk_t *mp;
24411 	uint_t	ill_index;
24412 	ipsec_out_t *io;
24413 	boolean_t attach_if, hwaccel;
24414 	uint32_t flags = IP6_NO_IPPOLICY;
24415 	int match_flags;
24416 	zoneid_t zoneid;
24417 	boolean_t ill_need_rele = B_FALSE;
24418 	boolean_t ire_need_rele = B_FALSE;
24419 
24420 	mp = ipsec_mp->b_cont;
24421 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24422 	ill_index = io->ipsec_out_ill_index;
24423 	if (io->ipsec_out_reachable) {
24424 		flags |= IPV6_REACHABILITY_CONFIRMATION;
24425 	}
24426 	attach_if = io->ipsec_out_attach_if;
24427 	hwaccel = io->ipsec_out_accelerated;
24428 	zoneid = io->ipsec_out_zoneid;
24429 	ASSERT(zoneid != ALL_ZONES);
24430 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24431 	/* Multicast addresses should have non-zero ill_index. */
24432 	v6dstp = &ip6h->ip6_dst;
24433 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
24434 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
24435 	ASSERT(!attach_if || ill_index != 0);
24436 	if (ill_index != 0) {
24437 		if (ill == NULL) {
24438 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
24439 			    B_TRUE);
24440 
24441 			/* Failure case frees things for us. */
24442 			if (ill == NULL)
24443 				return;
24444 
24445 			ill_need_rele = B_TRUE;
24446 		}
24447 		/*
24448 		 * If this packet needs to go out on a particular interface
24449 		 * honor it.
24450 		 */
24451 		if (attach_if) {
24452 			match_flags = MATCH_IRE_ILL;
24453 
24454 			/*
24455 			 * Check if we need an ire that will not be
24456 			 * looked up by anybody else i.e. HIDDEN.
24457 			 */
24458 			if (ill_is_probeonly(ill)) {
24459 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24460 			}
24461 		}
24462 	}
24463 	ASSERT(mp != NULL);
24464 
24465 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
24466 		boolean_t unspec_src;
24467 		ipif_t	*ipif;
24468 
24469 		/*
24470 		 * Use the ill_index to get the right ill.
24471 		 */
24472 		unspec_src = io->ipsec_out_unspec_src;
24473 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24474 		if (ipif == NULL) {
24475 			if (ill_need_rele)
24476 				ill_refrele(ill);
24477 			freemsg(ipsec_mp);
24478 			return;
24479 		}
24480 
24481 		if (ire_arg != NULL) {
24482 			ire = ire_arg;
24483 		} else {
24484 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24485 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24486 			ire_need_rele = B_TRUE;
24487 		}
24488 		if (ire != NULL) {
24489 			ipif_refrele(ipif);
24490 			/*
24491 			 * XXX Do the multicast forwarding now, as the IPSEC
24492 			 * processing has been done.
24493 			 */
24494 			goto send;
24495 		}
24496 
24497 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
24498 		mp->b_prev = NULL;
24499 		mp->b_next = NULL;
24500 
24501 		/*
24502 		 * If the IPsec packet was processed asynchronously,
24503 		 * drop it now.
24504 		 */
24505 		if (q == NULL) {
24506 			if (ill_need_rele)
24507 				ill_refrele(ill);
24508 			freemsg(ipsec_mp);
24509 			return;
24510 		}
24511 
24512 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
24513 		    unspec_src, zoneid);
24514 		ipif_refrele(ipif);
24515 	} else {
24516 		if (attach_if) {
24517 			ipif_t	*ipif;
24518 
24519 			ipif = ipif_get_next_ipif(NULL, ill);
24520 			if (ipif == NULL) {
24521 				if (ill_need_rele)
24522 					ill_refrele(ill);
24523 				freemsg(ipsec_mp);
24524 				return;
24525 			}
24526 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24527 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24528 			ire_need_rele = B_TRUE;
24529 			ipif_refrele(ipif);
24530 		} else {
24531 			if (ire_arg != NULL) {
24532 				ire = ire_arg;
24533 			} else {
24534 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
24535 				ire_need_rele = B_TRUE;
24536 			}
24537 		}
24538 		if (ire != NULL)
24539 			goto send;
24540 		/*
24541 		 * ire disappeared underneath.
24542 		 *
24543 		 * What we need to do here is the ip_newroute
24544 		 * logic to get the ire without doing the IPSEC
24545 		 * processing. Follow the same old path. But this
24546 		 * time, ip_wput or ire_add_then_send will call us
24547 		 * directly as all the IPSEC operations are done.
24548 		 */
24549 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
24550 		mp->b_prev = NULL;
24551 		mp->b_next = NULL;
24552 
24553 		/*
24554 		 * If the IPsec packet was processed asynchronously,
24555 		 * drop it now.
24556 		 */
24557 		if (q == NULL) {
24558 			if (ill_need_rele)
24559 				ill_refrele(ill);
24560 			freemsg(ipsec_mp);
24561 			return;
24562 		}
24563 
24564 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
24565 		    zoneid);
24566 	}
24567 	if (ill != NULL && ill_need_rele)
24568 		ill_refrele(ill);
24569 	return;
24570 send:
24571 	if (ill != NULL && ill_need_rele)
24572 		ill_refrele(ill);
24573 
24574 	/* Local delivery */
24575 	if (ire->ire_stq == NULL) {
24576 		ASSERT(q != NULL);
24577 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
24578 		    ire, 0);
24579 		if (ire_need_rele)
24580 			ire_refrele(ire);
24581 		return;
24582 	}
24583 	/*
24584 	 * Everything is done. Send it out on the wire.
24585 	 * We force the insertion of a fragment header using the
24586 	 * IPH_FRAG_HDR flag in two cases:
24587 	 * - after reception of an ICMPv6 "packet too big" message
24588 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
24589 	 * - for multirouted IPv6 packets, so that the receiver can
24590 	 *   discard duplicates according to their fragment identifier
24591 	 */
24592 	/* XXX fix flow control problems. */
24593 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
24594 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
24595 		if (hwaccel) {
24596 			/*
24597 			 * hardware acceleration does not handle these
24598 			 * "slow path" cases.
24599 			 */
24600 			/* IPsec KSTATS: should bump bean counter here. */
24601 			if (ire_need_rele)
24602 				ire_refrele(ire);
24603 			freemsg(ipsec_mp);
24604 			return;
24605 		}
24606 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
24607 		    (mp->b_cont ? msgdsize(mp) :
24608 		    mp->b_wptr - (uchar_t *)ip6h)) {
24609 			/* IPsec KSTATS: should bump bean counter here. */
24610 			ip0dbg(("Packet length mismatch: %d, %ld\n",
24611 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
24612 			    msgdsize(mp)));
24613 			if (ire_need_rele)
24614 				ire_refrele(ire);
24615 			freemsg(ipsec_mp);
24616 			return;
24617 		}
24618 		ASSERT(mp->b_prev == NULL);
24619 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
24620 		    ntohs(ip6h->ip6_plen) +
24621 		    IPV6_HDR_LEN, ire->ire_max_frag));
24622 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
24623 		    ire->ire_max_frag);
24624 	} else {
24625 		UPDATE_OB_PKT_COUNT(ire);
24626 		ire->ire_last_used_time = lbolt;
24627 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
24628 	}
24629 	if (ire_need_rele)
24630 		ire_refrele(ire);
24631 	freeb(ipsec_mp);
24632 }
24633 
24634 void
24635 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
24636 {
24637 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
24638 	da_ipsec_t *hada;	/* data attributes */
24639 	ill_t *ill = (ill_t *)q->q_ptr;
24640 
24641 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
24642 
24643 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
24644 		/* IPsec KSTATS: Bump lose counter here! */
24645 		freemsg(mp);
24646 		return;
24647 	}
24648 
24649 	/*
24650 	 * It's an IPsec packet that must be
24651 	 * accelerated by the Provider, and the
24652 	 * outbound ill is IPsec acceleration capable.
24653 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
24654 	 * to the ill.
24655 	 * IPsec KSTATS: should bump packet counter here.
24656 	 */
24657 
24658 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
24659 	if (hada_mp == NULL) {
24660 		/* IPsec KSTATS: should bump packet counter here. */
24661 		freemsg(mp);
24662 		return;
24663 	}
24664 
24665 	hada_mp->b_datap->db_type = M_CTL;
24666 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
24667 	hada_mp->b_cont = mp;
24668 
24669 	hada = (da_ipsec_t *)hada_mp->b_rptr;
24670 	bzero(hada, sizeof (da_ipsec_t));
24671 	hada->da_type = IPHADA_M_CTL;
24672 
24673 	putnext(q, hada_mp);
24674 }
24675 
24676 /*
24677  * Finish the outbound IPsec processing. This function is called from
24678  * ipsec_out_process() if the IPsec packet was processed
24679  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24680  * asynchronously.
24681  */
24682 void
24683 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
24684     ire_t *ire_arg)
24685 {
24686 	uint32_t v_hlen_tos_len;
24687 	ipaddr_t	dst;
24688 	ipif_t	*ipif = NULL;
24689 	ire_t *ire;
24690 	ire_t *ire1 = NULL;
24691 	mblk_t *next_mp = NULL;
24692 	uint32_t max_frag;
24693 	boolean_t multirt_send = B_FALSE;
24694 	mblk_t *mp;
24695 	mblk_t *mp1;
24696 	uint_t	ill_index;
24697 	ipsec_out_t *io;
24698 	boolean_t attach_if;
24699 	int match_flags, offset;
24700 	irb_t *irb = NULL;
24701 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
24702 	zoneid_t zoneid;
24703 	uint32_t cksum;
24704 	uint16_t *up;
24705 	ipxmit_state_t	pktxmit_state;
24706 #ifdef	_BIG_ENDIAN
24707 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
24708 #else
24709 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
24710 #endif
24711 
24712 	mp = ipsec_mp->b_cont;
24713 	ASSERT(mp != NULL);
24714 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24715 	dst = ipha->ipha_dst;
24716 
24717 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24718 	ill_index = io->ipsec_out_ill_index;
24719 	attach_if = io->ipsec_out_attach_if;
24720 	zoneid = io->ipsec_out_zoneid;
24721 	ASSERT(zoneid != ALL_ZONES);
24722 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24723 	if (ill_index != 0) {
24724 		if (ill == NULL) {
24725 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
24726 			    ill_index, B_FALSE);
24727 
24728 			/* Failure case frees things for us. */
24729 			if (ill == NULL)
24730 				return;
24731 
24732 			ill_need_rele = B_TRUE;
24733 		}
24734 		/*
24735 		 * If this packet needs to go out on a particular interface
24736 		 * honor it.
24737 		 */
24738 		if (attach_if) {
24739 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
24740 
24741 			/*
24742 			 * Check if we need an ire that will not be
24743 			 * looked up by anybody else i.e. HIDDEN.
24744 			 */
24745 			if (ill_is_probeonly(ill)) {
24746 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24747 			}
24748 		}
24749 	}
24750 
24751 	if (CLASSD(dst)) {
24752 		boolean_t conn_dontroute;
24753 		/*
24754 		 * Use the ill_index to get the right ipif.
24755 		 */
24756 		conn_dontroute = io->ipsec_out_dontroute;
24757 		if (ill_index == 0)
24758 			ipif = ipif_lookup_group(dst, zoneid);
24759 		else
24760 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24761 		if (ipif == NULL) {
24762 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
24763 			    " multicast\n"));
24764 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
24765 			freemsg(ipsec_mp);
24766 			goto done;
24767 		}
24768 		/*
24769 		 * ipha_src has already been intialized with the
24770 		 * value of the ipif in ip_wput. All we need now is
24771 		 * an ire to send this downstream.
24772 		 */
24773 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
24774 		    MBLK_GETLABEL(mp), match_flags);
24775 		if (ire != NULL) {
24776 			ill_t *ill1;
24777 			/*
24778 			 * Do the multicast forwarding now, as the IPSEC
24779 			 * processing has been done.
24780 			 */
24781 			if (ip_g_mrouter && !conn_dontroute &&
24782 			    (ill1 = ire_to_ill(ire))) {
24783 				if (ip_mforward(ill1, ipha, mp)) {
24784 					freemsg(ipsec_mp);
24785 					ip1dbg(("ip_wput_ipsec_out: mforward "
24786 					    "failed\n"));
24787 					ire_refrele(ire);
24788 					goto done;
24789 				}
24790 			}
24791 			goto send;
24792 		}
24793 
24794 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
24795 		mp->b_prev = NULL;
24796 		mp->b_next = NULL;
24797 
24798 		/*
24799 		 * If the IPsec packet was processed asynchronously,
24800 		 * drop it now.
24801 		 */
24802 		if (q == NULL) {
24803 			freemsg(ipsec_mp);
24804 			goto done;
24805 		}
24806 
24807 		/*
24808 		 * We may be using a wrong ipif to create the ire.
24809 		 * But it is okay as the source address is assigned
24810 		 * for the packet already. Next outbound packet would
24811 		 * create the IRE with the right IPIF in ip_wput.
24812 		 *
24813 		 * Also handle RTF_MULTIRT routes.
24814 		 */
24815 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
24816 		    zoneid);
24817 	} else {
24818 		if (attach_if) {
24819 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
24820 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24821 		} else {
24822 			if (ire_arg != NULL) {
24823 				ire = ire_arg;
24824 				ire_need_rele = B_FALSE;
24825 			} else {
24826 				ire = ire_cache_lookup(dst, zoneid,
24827 				    MBLK_GETLABEL(mp));
24828 			}
24829 		}
24830 		if (ire != NULL) {
24831 			goto send;
24832 		}
24833 
24834 		/*
24835 		 * ire disappeared underneath.
24836 		 *
24837 		 * What we need to do here is the ip_newroute
24838 		 * logic to get the ire without doing the IPSEC
24839 		 * processing. Follow the same old path. But this
24840 		 * time, ip_wput or ire_add_then_put will call us
24841 		 * directly as all the IPSEC operations are done.
24842 		 */
24843 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
24844 		mp->b_prev = NULL;
24845 		mp->b_next = NULL;
24846 
24847 		/*
24848 		 * If the IPsec packet was processed asynchronously,
24849 		 * drop it now.
24850 		 */
24851 		if (q == NULL) {
24852 			freemsg(ipsec_mp);
24853 			goto done;
24854 		}
24855 
24856 		/*
24857 		 * Since we're going through ip_newroute() again, we
24858 		 * need to make sure we don't:
24859 		 *
24860 		 *	1.) Trigger the ASSERT() with the ipha_ident
24861 		 *	    overloading.
24862 		 *	2.) Redo transport-layer checksumming, since we've
24863 		 *	    already done all that to get this far.
24864 		 *
24865 		 * The easiest way not do either of the above is to set
24866 		 * the ipha_ident field to IP_HDR_INCLUDED.
24867 		 */
24868 		ipha->ipha_ident = IP_HDR_INCLUDED;
24869 		ip_newroute(q, ipsec_mp, dst, NULL,
24870 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid);
24871 	}
24872 	goto done;
24873 send:
24874 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
24875 		/*
24876 		 * ESP NAT-Traversal packet.
24877 		 *
24878 		 * Just do software checksum for now.
24879 		 */
24880 
24881 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
24882 		IP_STAT(ip_out_sw_cksum);
24883 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
24884 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
24885 #define	iphs	((uint16_t *)ipha)
24886 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
24887 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
24888 		    IP_SIMPLE_HDR_LENGTH);
24889 #undef iphs
24890 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
24891 			cksum = 0xFFFF;
24892 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
24893 			if (mp1->b_wptr - mp1->b_rptr >=
24894 			    offset + sizeof (uint16_t)) {
24895 				up = (uint16_t *)(mp1->b_rptr + offset);
24896 				*up = cksum;
24897 				break;	/* out of for loop */
24898 			} else {
24899 				offset -= (mp->b_wptr - mp->b_rptr);
24900 			}
24901 	} /* Otherwise, just keep the all-zero checksum. */
24902 
24903 	if (ire->ire_stq == NULL) {
24904 		/*
24905 		 * Loopbacks go through ip_wput_local except for one case.
24906 		 * We come here if we generate a icmp_frag_needed message
24907 		 * after IPSEC processing is over. When this function calls
24908 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
24909 		 * icmp_frag_needed. The message generated comes back here
24910 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
24911 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
24912 		 * source address as it is usually set in ip_wput_ire. As
24913 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
24914 		 * and we end up here. We can't enter ip_wput_ire once the
24915 		 * IPSEC processing is over and hence we need to do it here.
24916 		 */
24917 		ASSERT(q != NULL);
24918 		UPDATE_OB_PKT_COUNT(ire);
24919 		ire->ire_last_used_time = lbolt;
24920 		if (ipha->ipha_src == 0)
24921 			ipha->ipha_src = ire->ire_src_addr;
24922 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
24923 		    ire, 0, zoneid);
24924 		if (ire_need_rele)
24925 			ire_refrele(ire);
24926 		goto done;
24927 	}
24928 
24929 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
24930 		/*
24931 		 * We are through with IPSEC processing.
24932 		 * Fragment this and send it on the wire.
24933 		 */
24934 		if (io->ipsec_out_accelerated) {
24935 			/*
24936 			 * The packet has been accelerated but must
24937 			 * be fragmented. This should not happen
24938 			 * since AH and ESP must not accelerate
24939 			 * packets that need fragmentation, however
24940 			 * the configuration could have changed
24941 			 * since the AH or ESP processing.
24942 			 * Drop packet.
24943 			 * IPsec KSTATS: bump bean counter here.
24944 			 */
24945 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
24946 			    "fragmented accelerated packet!\n"));
24947 			freemsg(ipsec_mp);
24948 		} else {
24949 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid);
24950 		}
24951 		if (ire_need_rele)
24952 			ire_refrele(ire);
24953 		goto done;
24954 	}
24955 
24956 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
24957 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
24958 	    (void *)ire->ire_ipif, (void *)ipif));
24959 
24960 	/*
24961 	 * Multiroute the secured packet, unless IPsec really
24962 	 * requires the packet to go out only through a particular
24963 	 * interface.
24964 	 */
24965 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
24966 		ire_t *first_ire;
24967 		irb = ire->ire_bucket;
24968 		ASSERT(irb != NULL);
24969 		/*
24970 		 * This ire has been looked up as the one that
24971 		 * goes through the given ipif;
24972 		 * make sure we do not omit any other multiroute ire
24973 		 * that may be present in the bucket before this one.
24974 		 */
24975 		IRB_REFHOLD(irb);
24976 		for (first_ire = irb->irb_ire;
24977 		    first_ire != NULL;
24978 		    first_ire = first_ire->ire_next) {
24979 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24980 			    (first_ire->ire_addr == ire->ire_addr) &&
24981 			    !(first_ire->ire_marks &
24982 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24983 				break;
24984 		}
24985 
24986 		if ((first_ire != NULL) && (first_ire != ire)) {
24987 			/*
24988 			 * Don't change the ire if the packet must
24989 			 * be fragmented if sent via this new one.
24990 			 */
24991 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
24992 				IRE_REFHOLD(first_ire);
24993 				if (ire_need_rele)
24994 					ire_refrele(ire);
24995 				else
24996 					ire_need_rele = B_TRUE;
24997 				ire = first_ire;
24998 			}
24999 		}
25000 		IRB_REFRELE(irb);
25001 
25002 		multirt_send = B_TRUE;
25003 		max_frag = ire->ire_max_frag;
25004 	} else {
25005 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
25006 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25007 			    "flag, attach_if %d\n", attach_if));
25008 		}
25009 	}
25010 
25011 	/*
25012 	 * In most cases, the emission loop below is entered only once.
25013 	 * Only in the case where the ire holds the RTF_MULTIRT
25014 	 * flag, we loop to process all RTF_MULTIRT ires in the
25015 	 * bucket, and send the packet through all crossed
25016 	 * RTF_MULTIRT routes.
25017 	 */
25018 	do {
25019 		if (multirt_send) {
25020 			/*
25021 			 * ire1 holds here the next ire to process in the
25022 			 * bucket. If multirouting is expected,
25023 			 * any non-RTF_MULTIRT ire that has the
25024 			 * right destination address is ignored.
25025 			 */
25026 			ASSERT(irb != NULL);
25027 			IRB_REFHOLD(irb);
25028 			for (ire1 = ire->ire_next;
25029 			    ire1 != NULL;
25030 			    ire1 = ire1->ire_next) {
25031 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
25032 					continue;
25033 				if (ire1->ire_addr != ire->ire_addr)
25034 					continue;
25035 				if (ire1->ire_marks &
25036 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
25037 					continue;
25038 				/* No loopback here */
25039 				if (ire1->ire_stq == NULL)
25040 					continue;
25041 				/*
25042 				 * Ensure we do not exceed the MTU
25043 				 * of the next route.
25044 				 */
25045 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
25046 					ip_multirt_bad_mtu(ire1, max_frag);
25047 					continue;
25048 				}
25049 
25050 				IRE_REFHOLD(ire1);
25051 				break;
25052 			}
25053 			IRB_REFRELE(irb);
25054 			if (ire1 != NULL) {
25055 				/*
25056 				 * We are in a multiple send case, need to
25057 				 * make a copy of the packet.
25058 				 */
25059 				next_mp = copymsg(ipsec_mp);
25060 				if (next_mp == NULL) {
25061 					ire_refrele(ire1);
25062 					ire1 = NULL;
25063 				}
25064 			}
25065 		}
25066 		/*
25067 		 * Everything is done. Send it out on the wire
25068 		 *
25069 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
25070 		 * either send it on the wire or, in the case of
25071 		 * HW acceleration, call ipsec_hw_putnext.
25072 		 */
25073 		if (ire->ire_nce &&
25074 		    ire->ire_nce->nce_state != ND_REACHABLE) {
25075 			DTRACE_PROBE2(ip__wput__ipsec__bail,
25076 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
25077 			/*
25078 			 * If ire's link-layer is unresolved (this
25079 			 * would only happen if the incomplete ire
25080 			 * was added to cachetable via forwarding path)
25081 			 * don't bother going to ip_xmit_v4. Just drop the
25082 			 * packet.
25083 			 * There is a slight risk here, in that, if we
25084 			 * have the forwarding path create an incomplete
25085 			 * IRE, then until the IRE is completed, any
25086 			 * transmitted IPSEC packets will be dropped
25087 			 * instead of being queued waiting for resolution.
25088 			 *
25089 			 * But the likelihood of a forwarding packet and a wput
25090 			 * packet sending to the same dst at the same time
25091 			 * and there not yet be an ARP entry for it is small.
25092 			 * Furthermore, if this actually happens, it might
25093 			 * be likely that wput would generate multiple
25094 			 * packets (and forwarding would also have a train
25095 			 * of packets) for that destination. If this is
25096 			 * the case, some of them would have been dropped
25097 			 * anyway, since ARP only queues a few packets while
25098 			 * waiting for resolution
25099 			 *
25100 			 * NOTE: We should really call ip_xmit_v4,
25101 			 * and let it queue the packet and send the
25102 			 * ARP query and have ARP come back thus:
25103 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
25104 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
25105 			 * hw accel work. But it's too complex to get
25106 			 * the IPsec hw  acceleration approach to fit
25107 			 * well with ip_xmit_v4 doing ARP without
25108 			 * doing IPSEC simplification. For now, we just
25109 			 * poke ip_xmit_v4 to trigger the arp resolve, so
25110 			 * that we can continue with the send on the next
25111 			 * attempt.
25112 			 *
25113 			 * XXX THis should be revisited, when
25114 			 * the IPsec/IP interaction is cleaned up
25115 			 */
25116 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
25117 			    " - dropping packet\n"));
25118 			freemsg(ipsec_mp);
25119 			/*
25120 			 * Call ip_xmit_v4() to trigger ARP query
25121 			 * in case the nce_state is ND_INITIAL
25122 			 */
25123 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
25124 			goto drop_pkt;
25125 		}
25126 
25127 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
25128 		pktxmit_state = ip_xmit_v4(mp, ire,
25129 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
25130 
25131 		if ((pktxmit_state ==  SEND_FAILED) ||
25132 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
25133 
25134 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
25135 drop_pkt:
25136 			BUMP_MIB(&ip_mib, ipOutDiscards);
25137 			if (ire_need_rele)
25138 				ire_refrele(ire);
25139 			if (ire1 != NULL) {
25140 				ire_refrele(ire1);
25141 				freemsg(next_mp);
25142 			}
25143 			goto done;
25144 		}
25145 
25146 		freeb(ipsec_mp);
25147 		if (ire_need_rele)
25148 			ire_refrele(ire);
25149 
25150 		if (ire1 != NULL) {
25151 			ire = ire1;
25152 			ire_need_rele = B_TRUE;
25153 			ASSERT(next_mp);
25154 			ipsec_mp = next_mp;
25155 			mp = ipsec_mp->b_cont;
25156 			ire1 = NULL;
25157 			next_mp = NULL;
25158 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
25159 		} else {
25160 			multirt_send = B_FALSE;
25161 		}
25162 	} while (multirt_send);
25163 done:
25164 	if (ill != NULL && ill_need_rele)
25165 		ill_refrele(ill);
25166 	if (ipif != NULL)
25167 		ipif_refrele(ipif);
25168 }
25169 
25170 /*
25171  * Get the ill corresponding to the specified ire, and compare its
25172  * capabilities with the protocol and algorithms specified by the
25173  * the SA obtained from ipsec_out. If they match, annotate the
25174  * ipsec_out structure to indicate that the packet needs acceleration.
25175  *
25176  *
25177  * A packet is eligible for outbound hardware acceleration if the
25178  * following conditions are satisfied:
25179  *
25180  * 1. the packet will not be fragmented
25181  * 2. the provider supports the algorithm
25182  * 3. there is no pending control message being exchanged
25183  * 4. snoop is not attached
25184  * 5. the destination address is not a broadcast or multicast address.
25185  *
25186  * Rationale:
25187  *	- Hardware drivers do not support fragmentation with
25188  *	  the current interface.
25189  *	- snoop, multicast, and broadcast may result in exposure of
25190  *	  a cleartext datagram.
25191  * We check all five of these conditions here.
25192  *
25193  * XXX would like to nuke "ire_t *" parameter here; problem is that
25194  * IRE is only way to figure out if a v4 address is a broadcast and
25195  * thus ineligible for acceleration...
25196  */
25197 static void
25198 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
25199 {
25200 	ipsec_out_t *io;
25201 	mblk_t *data_mp;
25202 	uint_t plen, overhead;
25203 
25204 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
25205 		return;
25206 
25207 	if (ill == NULL)
25208 		return;
25209 
25210 	/*
25211 	 * Destination address is a broadcast or multicast.  Punt.
25212 	 */
25213 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
25214 	    IRE_LOCAL)))
25215 		return;
25216 
25217 	data_mp = ipsec_mp->b_cont;
25218 
25219 	if (ill->ill_isv6) {
25220 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
25221 
25222 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
25223 			return;
25224 
25225 		plen = ip6h->ip6_plen;
25226 	} else {
25227 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
25228 
25229 		if (CLASSD(ipha->ipha_dst))
25230 			return;
25231 
25232 		plen = ipha->ipha_length;
25233 	}
25234 	/*
25235 	 * Is there a pending DLPI control message being exchanged
25236 	 * between IP/IPsec and the DLS Provider? If there is, it
25237 	 * could be a SADB update, and the state of the DLS Provider
25238 	 * SADB might not be in sync with the SADB maintained by
25239 	 * IPsec. To avoid dropping packets or using the wrong keying
25240 	 * material, we do not accelerate this packet.
25241 	 */
25242 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
25243 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25244 		    "ill_dlpi_pending! don't accelerate packet\n"));
25245 		return;
25246 	}
25247 
25248 	/*
25249 	 * Is the Provider in promiscous mode? If it does, we don't
25250 	 * accelerate the packet since it will bounce back up to the
25251 	 * listeners in the clear.
25252 	 */
25253 	if (ill->ill_promisc_on_phys) {
25254 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25255 		    "ill in promiscous mode, don't accelerate packet\n"));
25256 		return;
25257 	}
25258 
25259 	/*
25260 	 * Will the packet require fragmentation?
25261 	 */
25262 
25263 	/*
25264 	 * IPsec ESP note: this is a pessimistic estimate, but the same
25265 	 * as is used elsewhere.
25266 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
25267 	 *	+ 2-byte trailer
25268 	 */
25269 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
25270 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
25271 
25272 	if ((plen + overhead) > ill->ill_max_mtu)
25273 		return;
25274 
25275 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25276 
25277 	/*
25278 	 * Can the ill accelerate this IPsec protocol and algorithm
25279 	 * specified by the SA?
25280 	 */
25281 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
25282 	    ill->ill_isv6, sa)) {
25283 		return;
25284 	}
25285 
25286 	/*
25287 	 * Tell AH or ESP that the outbound ill is capable of
25288 	 * accelerating this packet.
25289 	 */
25290 	io->ipsec_out_is_capab_ill = B_TRUE;
25291 }
25292 
25293 /*
25294  * Select which AH & ESP SA's to use (if any) for the outbound packet.
25295  *
25296  * If this function returns B_TRUE, the requested SA's have been filled
25297  * into the ipsec_out_*_sa pointers.
25298  *
25299  * If the function returns B_FALSE, the packet has been "consumed", most
25300  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
25301  *
25302  * The SA references created by the protocol-specific "select"
25303  * function will be released when the ipsec_mp is freed, thanks to the
25304  * ipsec_out_free destructor -- see spd.c.
25305  */
25306 static boolean_t
25307 ipsec_out_select_sa(mblk_t *ipsec_mp)
25308 {
25309 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
25310 	ipsec_out_t *io;
25311 	ipsec_policy_t *pp;
25312 	ipsec_action_t *ap;
25313 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25314 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25315 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25316 
25317 	if (!io->ipsec_out_secure) {
25318 		/*
25319 		 * We came here by mistake.
25320 		 * Don't bother with ipsec processing
25321 		 * We should "discourage" this path in the future.
25322 		 */
25323 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25324 		return (B_FALSE);
25325 	}
25326 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25327 	ASSERT((io->ipsec_out_policy != NULL) ||
25328 	    (io->ipsec_out_act != NULL));
25329 
25330 	ASSERT(io->ipsec_out_failed == B_FALSE);
25331 
25332 	/*
25333 	 * IPSEC processing has started.
25334 	 */
25335 	io->ipsec_out_proc_begin = B_TRUE;
25336 	ap = io->ipsec_out_act;
25337 	if (ap == NULL) {
25338 		pp = io->ipsec_out_policy;
25339 		ASSERT(pp != NULL);
25340 		ap = pp->ipsp_act;
25341 		ASSERT(ap != NULL);
25342 	}
25343 
25344 	/*
25345 	 * We have an action.  now, let's select SA's.
25346 	 * (In the future, we can cache this in the conn_t..)
25347 	 */
25348 	if (ap->ipa_want_esp) {
25349 		if (io->ipsec_out_esp_sa == NULL) {
25350 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
25351 			    IPPROTO_ESP);
25352 		}
25353 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
25354 	}
25355 
25356 	if (ap->ipa_want_ah) {
25357 		if (io->ipsec_out_ah_sa == NULL) {
25358 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
25359 			    IPPROTO_AH);
25360 		}
25361 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
25362 		/*
25363 		 * The ESP and AH processing order needs to be preserved
25364 		 * when both protocols are required (ESP should be applied
25365 		 * before AH for an outbound packet). Force an ESP ACQUIRE
25366 		 * when both ESP and AH are required, and an AH ACQUIRE
25367 		 * is needed.
25368 		 */
25369 		if (ap->ipa_want_esp && need_ah_acquire)
25370 			need_esp_acquire = B_TRUE;
25371 	}
25372 
25373 	/*
25374 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
25375 	 * Release SAs that got referenced, but will not be used until we
25376 	 * acquire _all_ of the SAs we need.
25377 	 */
25378 	if (need_ah_acquire || need_esp_acquire) {
25379 		if (io->ipsec_out_ah_sa != NULL) {
25380 			IPSA_REFRELE(io->ipsec_out_ah_sa);
25381 			io->ipsec_out_ah_sa = NULL;
25382 		}
25383 		if (io->ipsec_out_esp_sa != NULL) {
25384 			IPSA_REFRELE(io->ipsec_out_esp_sa);
25385 			io->ipsec_out_esp_sa = NULL;
25386 		}
25387 
25388 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
25389 		return (B_FALSE);
25390 	}
25391 
25392 	return (B_TRUE);
25393 }
25394 
25395 /*
25396  * Process an IPSEC_OUT message and see what you can
25397  * do with it.
25398  * IPQoS Notes:
25399  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
25400  * IPSec.
25401  * XXX would like to nuke ire_t.
25402  * XXX ill_index better be "real"
25403  */
25404 void
25405 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
25406 {
25407 	ipsec_out_t *io;
25408 	ipsec_policy_t *pp;
25409 	ipsec_action_t *ap;
25410 	ipha_t *ipha;
25411 	ip6_t *ip6h;
25412 	mblk_t *mp;
25413 	ill_t *ill;
25414 	zoneid_t zoneid;
25415 	ipsec_status_t ipsec_rc;
25416 	boolean_t ill_need_rele = B_FALSE;
25417 
25418 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25419 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25420 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25421 	mp = ipsec_mp->b_cont;
25422 
25423 	/*
25424 	 * Initiate IPPF processing. We do it here to account for packets
25425 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
25426 	 * We can check for ipsec_out_proc_begin even for such packets, as
25427 	 * they will always be false (asserted below).
25428 	 */
25429 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
25430 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
25431 		    io->ipsec_out_ill_index : ill_index);
25432 		if (mp == NULL) {
25433 			ip2dbg(("ipsec_out_process: packet dropped "\
25434 			    "during IPPF processing\n"));
25435 			freeb(ipsec_mp);
25436 			BUMP_MIB(&ip_mib, ipOutDiscards);
25437 			return;
25438 		}
25439 	}
25440 
25441 	if (!io->ipsec_out_secure) {
25442 		/*
25443 		 * We came here by mistake.
25444 		 * Don't bother with ipsec processing
25445 		 * Should "discourage" this path in the future.
25446 		 */
25447 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25448 		goto done;
25449 	}
25450 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25451 	ASSERT((io->ipsec_out_policy != NULL) ||
25452 	    (io->ipsec_out_act != NULL));
25453 	ASSERT(io->ipsec_out_failed == B_FALSE);
25454 
25455 	if (!ipsec_loaded()) {
25456 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
25457 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25458 			BUMP_MIB(&ip_mib, ipOutDiscards);
25459 		} else {
25460 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
25461 		}
25462 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
25463 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
25464 		return;
25465 	}
25466 
25467 	/*
25468 	 * IPSEC processing has started.
25469 	 */
25470 	io->ipsec_out_proc_begin = B_TRUE;
25471 	ap = io->ipsec_out_act;
25472 	if (ap == NULL) {
25473 		pp = io->ipsec_out_policy;
25474 		ASSERT(pp != NULL);
25475 		ap = pp->ipsp_act;
25476 		ASSERT(ap != NULL);
25477 	}
25478 
25479 	/*
25480 	 * Save the outbound ill index. When the packet comes back
25481 	 * from IPsec, we make sure the ill hasn't changed or disappeared
25482 	 * before sending it the accelerated packet.
25483 	 */
25484 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
25485 		int ifindex;
25486 		ill = ire_to_ill(ire);
25487 		ifindex = ill->ill_phyint->phyint_ifindex;
25488 		io->ipsec_out_capab_ill_index = ifindex;
25489 	}
25490 
25491 	/*
25492 	 * The order of processing is first insert a IP header if needed.
25493 	 * Then insert the ESP header and then the AH header.
25494 	 */
25495 	if ((io->ipsec_out_se_done == B_FALSE) &&
25496 	    (ap->ipa_want_se)) {
25497 		/*
25498 		 * First get the outer IP header before sending
25499 		 * it to ESP.
25500 		 */
25501 		ipha_t *oipha, *iipha;
25502 		mblk_t *outer_mp, *inner_mp;
25503 
25504 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
25505 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
25506 			    "ipsec_out_process: "
25507 			    "Self-Encapsulation failed: Out of memory\n");
25508 			freemsg(ipsec_mp);
25509 			BUMP_MIB(&ip_mib, ipOutDiscards);
25510 			return;
25511 		}
25512 		inner_mp = ipsec_mp->b_cont;
25513 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
25514 		oipha = (ipha_t *)outer_mp->b_rptr;
25515 		iipha = (ipha_t *)inner_mp->b_rptr;
25516 		*oipha = *iipha;
25517 		outer_mp->b_wptr += sizeof (ipha_t);
25518 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
25519 		    sizeof (ipha_t));
25520 		oipha->ipha_protocol = IPPROTO_ENCAP;
25521 		oipha->ipha_version_and_hdr_length =
25522 		    IP_SIMPLE_HDR_VERSION;
25523 		oipha->ipha_hdr_checksum = 0;
25524 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
25525 		outer_mp->b_cont = inner_mp;
25526 		ipsec_mp->b_cont = outer_mp;
25527 
25528 		io->ipsec_out_se_done = B_TRUE;
25529 		io->ipsec_out_encaps = B_TRUE;
25530 	}
25531 
25532 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
25533 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
25534 	    !ipsec_out_select_sa(ipsec_mp))
25535 		return;
25536 
25537 	/*
25538 	 * By now, we know what SA's to use.  Toss over to ESP & AH
25539 	 * to do the heavy lifting.
25540 	 */
25541 	zoneid = io->ipsec_out_zoneid;
25542 	ASSERT(zoneid != ALL_ZONES);
25543 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
25544 		ASSERT(io->ipsec_out_esp_sa != NULL);
25545 		io->ipsec_out_esp_done = B_TRUE;
25546 		/*
25547 		 * Note that since hw accel can only apply one transform,
25548 		 * not two, we skip hw accel for ESP if we also have AH
25549 		 * This is an design limitation of the interface
25550 		 * which should be revisited.
25551 		 */
25552 		ASSERT(ire != NULL);
25553 		if (io->ipsec_out_ah_sa == NULL) {
25554 			ill = (ill_t *)ire->ire_stq->q_ptr;
25555 			ipsec_out_is_accelerated(ipsec_mp,
25556 			    io->ipsec_out_esp_sa, ill, ire);
25557 		}
25558 
25559 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
25560 		switch (ipsec_rc) {
25561 		case IPSEC_STATUS_SUCCESS:
25562 			break;
25563 		case IPSEC_STATUS_FAILED:
25564 			BUMP_MIB(&ip_mib, ipOutDiscards);
25565 			/* FALLTHRU */
25566 		case IPSEC_STATUS_PENDING:
25567 			return;
25568 		}
25569 	}
25570 
25571 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
25572 		ASSERT(io->ipsec_out_ah_sa != NULL);
25573 		io->ipsec_out_ah_done = B_TRUE;
25574 		if (ire == NULL) {
25575 			int idx = io->ipsec_out_capab_ill_index;
25576 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
25577 			    NULL, NULL, NULL, NULL);
25578 			ill_need_rele = B_TRUE;
25579 		} else {
25580 			ill = (ill_t *)ire->ire_stq->q_ptr;
25581 		}
25582 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
25583 		    ire);
25584 
25585 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
25586 		switch (ipsec_rc) {
25587 		case IPSEC_STATUS_SUCCESS:
25588 			break;
25589 		case IPSEC_STATUS_FAILED:
25590 			BUMP_MIB(&ip_mib, ipOutDiscards);
25591 			/* FALLTHRU */
25592 		case IPSEC_STATUS_PENDING:
25593 			if (ill != NULL && ill_need_rele)
25594 				ill_refrele(ill);
25595 			return;
25596 		}
25597 	}
25598 	/*
25599 	 * We are done with IPSEC processing. Send it over
25600 	 * the wire.
25601 	 */
25602 done:
25603 	mp = ipsec_mp->b_cont;
25604 	ipha = (ipha_t *)mp->b_rptr;
25605 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25606 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
25607 	} else {
25608 		ip6h = (ip6_t *)ipha;
25609 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
25610 	}
25611 	if (ill != NULL && ill_need_rele)
25612 		ill_refrele(ill);
25613 }
25614 
25615 /* ARGSUSED */
25616 void
25617 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
25618 {
25619 	opt_restart_t	*or;
25620 	int	err;
25621 	conn_t	*connp;
25622 
25623 	ASSERT(CONN_Q(q));
25624 	connp = Q_TO_CONN(q);
25625 
25626 	ASSERT(first_mp->b_datap->db_type == M_CTL);
25627 	or = (opt_restart_t *)first_mp->b_rptr;
25628 	/*
25629 	 * We don't need to pass any credentials here since this is just
25630 	 * a restart. The credentials are passed in when svr4_optcom_req
25631 	 * is called the first time (from ip_wput_nondata).
25632 	 */
25633 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
25634 		err = svr4_optcom_req(q, first_mp, NULL,
25635 		    &ip_opt_obj);
25636 	} else {
25637 		ASSERT(or->or_type == T_OPTMGMT_REQ);
25638 		err = tpi_optcom_req(q, first_mp, NULL,
25639 		    &ip_opt_obj);
25640 	}
25641 	if (err != EINPROGRESS) {
25642 		/* operation is done */
25643 		CONN_OPER_PENDING_DONE(connp);
25644 	}
25645 }
25646 
25647 /*
25648  * ioctls that go through a down/up sequence may need to wait for the down
25649  * to complete. This involves waiting for the ire and ipif refcnts to go down
25650  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
25651  */
25652 /* ARGSUSED */
25653 void
25654 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25655 {
25656 	struct iocblk *iocp;
25657 	mblk_t *mp1;
25658 	ipif_t	*ipif;
25659 	ip_ioctl_cmd_t *ipip;
25660 	int err;
25661 	sin_t	*sin;
25662 	struct lifreq *lifr;
25663 	struct ifreq *ifr;
25664 
25665 	iocp = (struct iocblk *)mp->b_rptr;
25666 	ASSERT(ipsq != NULL);
25667 	/* Existence of mp1 verified in ip_wput_nondata */
25668 	mp1 = mp->b_cont->b_cont;
25669 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25670 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
25671 		ill_t *ill;
25672 		/*
25673 		 * Special case where ipsq_current_ipif may not be set.
25674 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
25675 		 * ill could also have become part of a ipmp group in the
25676 		 * process, we are here as were not able to complete the
25677 		 * operation in ipif_set_values because we could not become
25678 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
25679 		 * will not be set so we need to set it.
25680 		 */
25681 		ill = (ill_t *)q->q_ptr;
25682 		ipsq->ipsq_current_ipif = ill->ill_ipif;
25683 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25684 	}
25685 
25686 	ipif = ipsq->ipsq_current_ipif;
25687 	ASSERT(ipif != NULL);
25688 	if (ipip->ipi_cmd_type == IF_CMD) {
25689 		/* This a old style SIOC[GS]IF* command */
25690 		ifr = (struct ifreq *)mp1->b_rptr;
25691 		sin = (sin_t *)&ifr->ifr_addr;
25692 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
25693 		/* This a new style SIOC[GS]LIF* command */
25694 		lifr = (struct lifreq *)mp1->b_rptr;
25695 		sin = (sin_t *)&lifr->lifr_addr;
25696 	} else {
25697 		sin = NULL;
25698 	}
25699 
25700 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
25701 	    (void *)mp1->b_rptr);
25702 
25703 	/* SIOCLIFREMOVEIF could have removed the ipif */
25704 	ip_ioctl_finish(q, mp, err,
25705 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25706 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
25707 }
25708 
25709 /*
25710  * ioctl processing
25711  *
25712  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
25713  * the ioctl command in the ioctl tables and determines the copyin data size
25714  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
25715  * size.
25716  *
25717  * ioctl processing then continues when the M_IOCDATA makes its way down.
25718  * Now the ioctl is looked up again in the ioctl table, and its properties are
25719  * extracted. The associated 'conn' is then refheld till the end of the ioctl
25720  * and the general ioctl processing function ip_process_ioctl is called.
25721  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
25722  * so goes thru the serialization primitive ipsq_try_enter. Then the
25723  * appropriate function to handle the ioctl is called based on the entry in
25724  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
25725  * which also refreleases the 'conn' that was refheld at the start of the
25726  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
25727  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
25728  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
25729  *
25730  * Many exclusive ioctls go thru an internal down up sequence as part of
25731  * the operation. For example an attempt to change the IP address of an
25732  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
25733  * does all the cleanup such as deleting all ires that use this address.
25734  * Then we need to wait till all references to the interface go away.
25735  */
25736 void
25737 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
25738 {
25739 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
25740 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
25741 	cmd_info_t ci;
25742 	int err;
25743 	boolean_t entered_ipsq = B_FALSE;
25744 
25745 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
25746 
25747 	if (ipip == NULL)
25748 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25749 
25750 	/*
25751 	 * SIOCLIFADDIF needs to go thru a special path since the
25752 	 * ill may not exist yet. This happens in the case of lo0
25753 	 * which is created using this ioctl.
25754 	 */
25755 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
25756 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
25757 		ip_ioctl_finish(q, mp, err,
25758 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25759 		    NULL, NULL);
25760 		return;
25761 	}
25762 
25763 	ci.ci_ipif = NULL;
25764 	switch (ipip->ipi_cmd_type) {
25765 	case IF_CMD:
25766 	case LIF_CMD:
25767 		/*
25768 		 * ioctls that pass in a [l]ifreq appear here.
25769 		 * ip_extract_lifreq_cmn returns a refheld ipif in
25770 		 * ci.ci_ipif
25771 		 */
25772 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
25773 		    ipip->ipi_flags, &ci, ip_process_ioctl);
25774 		if (err != 0) {
25775 			ip_ioctl_finish(q, mp, err,
25776 			    ipip->ipi_flags & IPI_GET_CMD ?
25777 			    COPYOUT : NO_COPYOUT, NULL, NULL);
25778 			return;
25779 		}
25780 		ASSERT(ci.ci_ipif != NULL);
25781 		break;
25782 
25783 	case TUN_CMD:
25784 		/*
25785 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
25786 		 * a refheld ipif in ci.ci_ipif
25787 		 */
25788 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
25789 		if (err != 0) {
25790 			ip_ioctl_finish(q, mp, err,
25791 			    ipip->ipi_flags & IPI_GET_CMD ?
25792 			    COPYOUT : NO_COPYOUT, NULL, NULL);
25793 			return;
25794 		}
25795 		ASSERT(ci.ci_ipif != NULL);
25796 		break;
25797 
25798 	case MISC_CMD:
25799 		/*
25800 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
25801 		 * For eg. SIOCGLIFCONF will appear here.
25802 		 */
25803 		switch (ipip->ipi_cmd) {
25804 		case IF_UNITSEL:
25805 			/* ioctl comes down the ill */
25806 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
25807 			ipif_refhold(ci.ci_ipif);
25808 			break;
25809 		case SIOCGMSFILTER:
25810 		case SIOCSMSFILTER:
25811 		case SIOCGIPMSFILTER:
25812 		case SIOCSIPMSFILTER:
25813 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
25814 			    ip_process_ioctl);
25815 			if (err != 0) {
25816 				ip_ioctl_finish(q, mp, err,
25817 				    ipip->ipi_flags & IPI_GET_CMD ?
25818 				    COPYOUT : NO_COPYOUT, NULL, NULL);
25819 				return;
25820 			}
25821 			break;
25822 		}
25823 		err = 0;
25824 		ci.ci_sin = NULL;
25825 		ci.ci_sin6 = NULL;
25826 		ci.ci_lifr = NULL;
25827 		break;
25828 	}
25829 
25830 	/*
25831 	 * If ipsq is non-null, we are already being called exclusively
25832 	 */
25833 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
25834 	if (!(ipip->ipi_flags & IPI_WR)) {
25835 		/*
25836 		 * A return value of EINPROGRESS means the ioctl is
25837 		 * either queued and waiting for some reason or has
25838 		 * already completed.
25839 		 */
25840 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25841 		    ci.ci_lifr);
25842 		if (ci.ci_ipif != NULL)
25843 			ipif_refrele(ci.ci_ipif);
25844 		ip_ioctl_finish(q, mp, err,
25845 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25846 		    NULL, NULL);
25847 		return;
25848 	}
25849 
25850 	ASSERT(ci.ci_ipif != NULL);
25851 
25852 	if (ipsq == NULL) {
25853 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
25854 		    ip_process_ioctl, NEW_OP, B_TRUE);
25855 		entered_ipsq = B_TRUE;
25856 	}
25857 	/*
25858 	 * Release the ipif so that ipif_down and friends that wait for
25859 	 * references to go away are not misled about the current ipif_refcnt
25860 	 * values. We are writer so we can access the ipif even after releasing
25861 	 * the ipif.
25862 	 */
25863 	ipif_refrele(ci.ci_ipif);
25864 	if (ipsq == NULL)
25865 		return;
25866 
25867 	mutex_enter(&ipsq->ipsq_lock);
25868 	ASSERT(ipsq->ipsq_current_ipif == NULL);
25869 	ipsq->ipsq_current_ipif = ci.ci_ipif;
25870 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25871 	mutex_exit(&ipsq->ipsq_lock);
25872 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
25873 	/*
25874 	 * For most set ioctls that come here, this serves as a single point
25875 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
25876 	 * be any new references to the ipif. This helps functions that go
25877 	 * through this path and end up trying to wait for the refcnts
25878 	 * associated with the ipif to go down to zero. Some exceptions are
25879 	 * Failover, Failback, and Groupname commands that operate on more than
25880 	 * just the ci.ci_ipif. These commands internally determine the
25881 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
25882 	 * flags on that set. Another exception is the Removeif command that
25883 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
25884 	 * ipif to operate on.
25885 	 */
25886 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
25887 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
25888 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
25889 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
25890 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
25891 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
25892 
25893 	/*
25894 	 * A return value of EINPROGRESS means the ioctl is
25895 	 * either queued and waiting for some reason or has
25896 	 * already completed.
25897 	 */
25898 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25899 	    ci.ci_lifr);
25900 
25901 	/* SIOCLIFREMOVEIF could have removed the ipif */
25902 	ip_ioctl_finish(q, mp, err,
25903 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25904 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
25905 
25906 	if (entered_ipsq)
25907 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
25908 }
25909 
25910 /*
25911  * Complete the ioctl. Typically ioctls use the mi package and need to
25912  * do mi_copyout/mi_copy_done.
25913  */
25914 void
25915 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
25916     ipif_t *ipif, ipsq_t *ipsq)
25917 {
25918 	conn_t	*connp = NULL;
25919 
25920 	if (err == EINPROGRESS)
25921 		return;
25922 
25923 	if (CONN_Q(q)) {
25924 		connp = Q_TO_CONN(q);
25925 		ASSERT(connp->conn_ref >= 2);
25926 	}
25927 
25928 	switch (mode) {
25929 	case COPYOUT:
25930 		if (err == 0)
25931 			mi_copyout(q, mp);
25932 		else
25933 			mi_copy_done(q, mp, err);
25934 		break;
25935 
25936 	case NO_COPYOUT:
25937 		mi_copy_done(q, mp, err);
25938 		break;
25939 
25940 	default:
25941 		/* An ioctl aborted through a conn close would take this path */
25942 		break;
25943 	}
25944 
25945 	/*
25946 	 * The refhold placed at the start of the ioctl is released here.
25947 	 */
25948 	if (connp != NULL)
25949 		CONN_OPER_PENDING_DONE(connp);
25950 
25951 	/*
25952 	 * If the ioctl were an exclusive ioctl it would have set
25953 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
25954 	 */
25955 	if (ipif != NULL) {
25956 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
25957 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
25958 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
25959 	}
25960 
25961 	/*
25962 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
25963 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
25964 	 * entering the ipsq
25965 	 */
25966 	if (ipsq != NULL) {
25967 		mutex_enter(&ipsq->ipsq_lock);
25968 		ipsq->ipsq_current_ipif = NULL;
25969 		mutex_exit(&ipsq->ipsq_lock);
25970 	}
25971 }
25972 
25973 /*
25974  * This is called from ip_wput_nondata to resume a deferred TCP bind.
25975  */
25976 /* ARGSUSED */
25977 void
25978 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
25979 {
25980 	conn_t *connp = arg;
25981 	tcp_t	*tcp;
25982 
25983 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
25984 	tcp = connp->conn_tcp;
25985 
25986 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
25987 		freemsg(mp);
25988 	else
25989 		tcp_rput_other(tcp, mp);
25990 	CONN_OPER_PENDING_DONE(connp);
25991 }
25992 
25993 /* Called from ip_wput for all non data messages */
25994 /* ARGSUSED */
25995 void
25996 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25997 {
25998 	mblk_t		*mp1;
25999 	ire_t		*ire, *fake_ire;
26000 	ill_t		*ill;
26001 	struct iocblk	*iocp;
26002 	ip_ioctl_cmd_t	*ipip;
26003 	cred_t		*cr;
26004 	conn_t		*connp = NULL;
26005 	int		cmd, err;
26006 	nce_t		*nce;
26007 	ipif_t		*ipif;
26008 
26009 	if (CONN_Q(q))
26010 		connp = Q_TO_CONN(q);
26011 
26012 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26013 
26014 	/* Check if it is a queue to /dev/sctp. */
26015 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26016 	    connp->conn_rq == NULL) {
26017 		sctp_wput(q, mp);
26018 		return;
26019 	}
26020 
26021 	switch (DB_TYPE(mp)) {
26022 	case M_IOCTL:
26023 		/*
26024 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26025 		 * will arrange to copy in associated control structures.
26026 		 */
26027 		ip_sioctl_copyin_setup(q, mp);
26028 		return;
26029 	case M_IOCDATA:
26030 		/*
26031 		 * Ensure that this is associated with one of our trans-
26032 		 * parent ioctls.  If it's not ours, discard it if we're
26033 		 * running as a driver, or pass it on if we're a module.
26034 		 */
26035 		iocp = (struct iocblk *)mp->b_rptr;
26036 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26037 		if (ipip == NULL) {
26038 			if (q->q_next == NULL) {
26039 				goto nak;
26040 			} else {
26041 				putnext(q, mp);
26042 			}
26043 			return;
26044 		} else if ((q->q_next != NULL) &&
26045 		    !(ipip->ipi_flags & IPI_MODOK)) {
26046 			/*
26047 			 * the ioctl is one we recognise, but is not
26048 			 * consumed by IP as a module, pass M_IOCDATA
26049 			 * for processing downstream, but only for
26050 			 * common Streams ioctls.
26051 			 */
26052 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26053 				putnext(q, mp);
26054 				return;
26055 			} else {
26056 				goto nak;
26057 			}
26058 		}
26059 
26060 		/* IOCTL continuation following copyin or copyout. */
26061 		if (mi_copy_state(q, mp, NULL) == -1) {
26062 			/*
26063 			 * The copy operation failed.  mi_copy_state already
26064 			 * cleaned up, so we're out of here.
26065 			 */
26066 			return;
26067 		}
26068 		/*
26069 		 * If we just completed a copy in, we become writer and
26070 		 * continue processing in ip_sioctl_copyin_done.  If it
26071 		 * was a copy out, we call mi_copyout again.  If there is
26072 		 * nothing more to copy out, it will complete the IOCTL.
26073 		 */
26074 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
26075 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
26076 				mi_copy_done(q, mp, EPROTO);
26077 				return;
26078 			}
26079 			/*
26080 			 * Check for cases that need more copying.  A return
26081 			 * value of 0 means a second copyin has been started,
26082 			 * so we return; a return value of 1 means no more
26083 			 * copying is needed, so we continue.
26084 			 */
26085 			cmd = iocp->ioc_cmd;
26086 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
26087 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
26088 			    MI_COPY_COUNT(mp) == 1) {
26089 				if (ip_copyin_msfilter(q, mp) == 0)
26090 					return;
26091 			}
26092 			/*
26093 			 * Refhold the conn, till the ioctl completes. This is
26094 			 * needed in case the ioctl ends up in the pending mp
26095 			 * list. Every mp in the ill_pending_mp list and
26096 			 * the ipsq_pending_mp must have a refhold on the conn
26097 			 * to resume processing. The refhold is released when
26098 			 * the ioctl completes. (normally or abnormally)
26099 			 * In all cases ip_ioctl_finish is called to finish
26100 			 * the ioctl.
26101 			 */
26102 			if (connp != NULL) {
26103 				/* This is not a reentry */
26104 				ASSERT(ipsq == NULL);
26105 				CONN_INC_REF(connp);
26106 			} else {
26107 				if (!(ipip->ipi_flags & IPI_MODOK)) {
26108 					mi_copy_done(q, mp, EINVAL);
26109 					return;
26110 				}
26111 			}
26112 
26113 			ip_process_ioctl(ipsq, q, mp, ipip);
26114 
26115 		} else {
26116 			mi_copyout(q, mp);
26117 		}
26118 		return;
26119 nak:
26120 		iocp->ioc_error = EINVAL;
26121 		mp->b_datap->db_type = M_IOCNAK;
26122 		iocp->ioc_count = 0;
26123 		qreply(q, mp);
26124 		return;
26125 
26126 	case M_IOCNAK:
26127 		/*
26128 		 * The only way we could get here is if a resolver didn't like
26129 		 * an IOCTL we sent it.	 This shouldn't happen.
26130 		 */
26131 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
26132 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
26133 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
26134 		freemsg(mp);
26135 		return;
26136 	case M_IOCACK:
26137 		/* Finish socket ioctls passed through to ARP. */
26138 		ip_sioctl_iocack(q, mp);
26139 		return;
26140 	case M_FLUSH:
26141 		if (*mp->b_rptr & FLUSHW)
26142 			flushq(q, FLUSHALL);
26143 		if (q->q_next) {
26144 			/*
26145 			 * M_FLUSH is sent up to IP by some drivers during
26146 			 * unbind. ip_rput has already replied to it. We are
26147 			 * here for the M_FLUSH that we originated in IP
26148 			 * before sending the unbind request to the driver.
26149 			 * Just free it as we don't queue packets in IP
26150 			 * on the write side of the device instance.
26151 			 */
26152 			freemsg(mp);
26153 			return;
26154 		}
26155 		if (*mp->b_rptr & FLUSHR) {
26156 			*mp->b_rptr &= ~FLUSHW;
26157 			qreply(q, mp);
26158 			return;
26159 		}
26160 		freemsg(mp);
26161 		return;
26162 	case IRE_DB_REQ_TYPE:
26163 		/* An Upper Level Protocol wants a copy of an IRE. */
26164 		ip_ire_req(q, mp);
26165 		return;
26166 	case M_CTL:
26167 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
26168 			break;
26169 
26170 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
26171 		    IP_ULP_OUT_LABELED) {
26172 			out_labeled_t *olp;
26173 
26174 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
26175 				break;
26176 			olp = (out_labeled_t *)mp->b_rptr;
26177 			connp->conn_ulp_labeled = olp->out_qnext == q;
26178 			freemsg(mp);
26179 			return;
26180 		}
26181 
26182 		/* M_CTL messages are used by ARP to tell us things. */
26183 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
26184 			break;
26185 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
26186 		case AR_ENTRY_SQUERY:
26187 			ip_wput_ctl(q, mp);
26188 			return;
26189 		case AR_CLIENT_NOTIFY:
26190 			ip_arp_news(q, mp);
26191 			return;
26192 		case AR_DLPIOP_DONE:
26193 			ASSERT(q->q_next != NULL);
26194 			ill = (ill_t *)q->q_ptr;
26195 			/* qwriter_ip releases the refhold */
26196 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
26197 			ill_refhold(ill);
26198 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
26199 			    CUR_OP, B_FALSE);
26200 			return;
26201 		case AR_ARP_CLOSING:
26202 			/*
26203 			 * ARP (above us) is closing. If no ARP bringup is
26204 			 * currently pending, ack the message so that ARP
26205 			 * can complete its close. Also mark ill_arp_closing
26206 			 * so that new ARP bringups will fail. If any
26207 			 * ARP bringup is currently in progress, we will
26208 			 * ack this when the current ARP bringup completes.
26209 			 */
26210 			ASSERT(q->q_next != NULL);
26211 			ill = (ill_t *)q->q_ptr;
26212 			mutex_enter(&ill->ill_lock);
26213 			ill->ill_arp_closing = 1;
26214 			if (!ill->ill_arp_bringup_pending) {
26215 				mutex_exit(&ill->ill_lock);
26216 				qreply(q, mp);
26217 			} else {
26218 				mutex_exit(&ill->ill_lock);
26219 				freemsg(mp);
26220 			}
26221 			return;
26222 		case AR_ARP_EXTEND:
26223 			/*
26224 			 * The ARP module above us is capable of duplicate
26225 			 * address detection.  Old ATM drivers will not send
26226 			 * this message.
26227 			 */
26228 			ASSERT(q->q_next != NULL);
26229 			ill = (ill_t *)q->q_ptr;
26230 			ill->ill_arp_extend = B_TRUE;
26231 			freemsg(mp);
26232 			return;
26233 		default:
26234 			break;
26235 		}
26236 		break;
26237 	case M_PROTO:
26238 	case M_PCPROTO:
26239 		/*
26240 		 * The only PROTO messages we expect are ULP binds and
26241 		 * copies of option negotiation acknowledgements.
26242 		 */
26243 		switch (((union T_primitives *)mp->b_rptr)->type) {
26244 		case O_T_BIND_REQ:
26245 		case T_BIND_REQ: {
26246 			/* Request can get queued in bind */
26247 			ASSERT(connp != NULL);
26248 			/*
26249 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
26250 			 * instead of going through this path.  We only get
26251 			 * here in the following cases:
26252 			 *
26253 			 * a. Bind retries, where ipsq is non-NULL.
26254 			 * b. T_BIND_REQ is issued from non TCP/UDP
26255 			 *    transport, e.g. icmp for raw socket,
26256 			 *    in which case ipsq will be NULL.
26257 			 */
26258 			ASSERT(ipsq != NULL ||
26259 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
26260 
26261 			/* Don't increment refcnt if this is a re-entry */
26262 			if (ipsq == NULL)
26263 				CONN_INC_REF(connp);
26264 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
26265 			    connp, NULL) : ip_bind_v4(q, mp, connp);
26266 			if (mp == NULL)
26267 				return;
26268 			if (IPCL_IS_TCP(connp)) {
26269 				/*
26270 				 * In the case of TCP endpoint we
26271 				 * come here only for bind retries
26272 				 */
26273 				ASSERT(ipsq != NULL);
26274 				CONN_INC_REF(connp);
26275 				squeue_fill(connp->conn_sqp, mp,
26276 				    ip_resume_tcp_bind, connp,
26277 				    SQTAG_BIND_RETRY);
26278 				return;
26279 			} else if (IPCL_IS_UDP(connp)) {
26280 				/*
26281 				 * In the case of UDP endpoint we
26282 				 * come here only for bind retries
26283 				 */
26284 				ASSERT(ipsq != NULL);
26285 				udp_resume_bind(connp, mp);
26286 				return;
26287 			}
26288 			qreply(q, mp);
26289 			CONN_OPER_PENDING_DONE(connp);
26290 			return;
26291 		}
26292 		case T_SVR4_OPTMGMT_REQ:
26293 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
26294 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
26295 
26296 			ASSERT(connp != NULL);
26297 			if (!snmpcom_req(q, mp, ip_snmp_set,
26298 			    ip_snmp_get, cr)) {
26299 				/*
26300 				 * Call svr4_optcom_req so that it can
26301 				 * generate the ack. We don't come here
26302 				 * if this operation is being restarted.
26303 				 * ip_restart_optmgmt will drop the conn ref.
26304 				 * In the case of ipsec option after the ipsec
26305 				 * load is complete conn_restart_ipsec_waiter
26306 				 * drops the conn ref.
26307 				 */
26308 				ASSERT(ipsq == NULL);
26309 				CONN_INC_REF(connp);
26310 				if (ip_check_for_ipsec_opt(q, mp))
26311 					return;
26312 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
26313 				if (err != EINPROGRESS) {
26314 					/* Operation is done */
26315 					CONN_OPER_PENDING_DONE(connp);
26316 				}
26317 			}
26318 			return;
26319 		case T_OPTMGMT_REQ:
26320 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
26321 			/*
26322 			 * Note: No snmpcom_req support through new
26323 			 * T_OPTMGMT_REQ.
26324 			 * Call tpi_optcom_req so that it can
26325 			 * generate the ack.
26326 			 */
26327 			ASSERT(connp != NULL);
26328 			ASSERT(ipsq == NULL);
26329 			/*
26330 			 * We don't come here for restart. ip_restart_optmgmt
26331 			 * will drop the conn ref. In the case of ipsec option
26332 			 * after the ipsec load is complete
26333 			 * conn_restart_ipsec_waiter drops the conn ref.
26334 			 */
26335 			CONN_INC_REF(connp);
26336 			if (ip_check_for_ipsec_opt(q, mp))
26337 				return;
26338 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
26339 			if (err != EINPROGRESS) {
26340 				/* Operation is done */
26341 				CONN_OPER_PENDING_DONE(connp);
26342 			}
26343 			return;
26344 		case T_UNBIND_REQ:
26345 			mp = ip_unbind(q, mp);
26346 			qreply(q, mp);
26347 			return;
26348 		default:
26349 			/*
26350 			 * Have to drop any DLPI messages coming down from
26351 			 * arp (such as an info_req which would cause ip
26352 			 * to receive an extra info_ack if it was passed
26353 			 * through.
26354 			 */
26355 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
26356 			    (int)*(uint_t *)mp->b_rptr));
26357 			freemsg(mp);
26358 			return;
26359 		}
26360 		/* NOTREACHED */
26361 	case IRE_DB_TYPE: {
26362 		nce_t		*nce;
26363 		ill_t		*ill;
26364 		in6_addr_t	gw_addr_v6;
26365 
26366 
26367 		/*
26368 		 * This is a response back from a resolver.  It
26369 		 * consists of a message chain containing:
26370 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
26371 		 * The IRE_MBLK is the one we allocated in ip_newroute.
26372 		 * The LL_HDR_MBLK is the DLPI header to use to get
26373 		 * the attached packet, and subsequent ones for the
26374 		 * same destination, transmitted.
26375 		 */
26376 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
26377 			break;
26378 		/*
26379 		 * First, check to make sure the resolution succeeded.
26380 		 * If it failed, the second mblk will be empty.
26381 		 * If it is, free the chain, dropping the packet.
26382 		 * (We must ire_delete the ire; that frees the ire mblk)
26383 		 * We're doing this now to support PVCs for ATM; it's
26384 		 * a partial xresolv implementation. When we fully implement
26385 		 * xresolv interfaces, instead of freeing everything here
26386 		 * we'll initiate neighbor discovery.
26387 		 *
26388 		 * For v4 (ARP and other external resolvers) the resolver
26389 		 * frees the message, so no check is needed. This check
26390 		 * is required, though, for a full xresolve implementation.
26391 		 * Including this code here now both shows how external
26392 		 * resolvers can NACK a resolution request using an
26393 		 * existing design that has no specific provisions for NACKs,
26394 		 * and also takes into account that the current non-ARP
26395 		 * external resolver has been coded to use this method of
26396 		 * NACKing for all IPv6 (xresolv) cases,
26397 		 * whether our xresolv implementation is complete or not.
26398 		 *
26399 		 */
26400 		ire = (ire_t *)mp->b_rptr;
26401 		ill = ire_to_ill(ire);
26402 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26403 		if (mp1->b_rptr == mp1->b_wptr) {
26404 			if (ire->ire_ipversion == IPV6_VERSION) {
26405 				/*
26406 				 * XRESOLV interface.
26407 				 */
26408 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
26409 				mutex_enter(&ire->ire_lock);
26410 				gw_addr_v6 = ire->ire_gateway_addr_v6;
26411 				mutex_exit(&ire->ire_lock);
26412 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26413 					nce = ndp_lookup_v6(ill,
26414 					    &ire->ire_addr_v6, B_FALSE);
26415 				} else {
26416 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
26417 					    B_FALSE);
26418 				}
26419 				if (nce != NULL) {
26420 					nce_resolv_failed(nce);
26421 					ndp_delete(nce);
26422 					NCE_REFRELE(nce);
26423 				}
26424 			}
26425 			mp->b_cont = NULL;
26426 			freemsg(mp1);		/* frees the pkt as well */
26427 			ASSERT(ire->ire_nce == NULL);
26428 			ire_delete((ire_t *)mp->b_rptr);
26429 			return;
26430 		}
26431 
26432 		/*
26433 		 * Split them into IRE_MBLK and pkt and feed it into
26434 		 * ire_add_then_send. Then in ire_add_then_send
26435 		 * the IRE will be added, and then the packet will be
26436 		 * run back through ip_wput. This time it will make
26437 		 * it to the wire.
26438 		 */
26439 		mp->b_cont = NULL;
26440 		mp = mp1->b_cont;		/* now, mp points to pkt */
26441 		mp1->b_cont = NULL;
26442 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
26443 		if (ire->ire_ipversion == IPV6_VERSION) {
26444 			/*
26445 			 * XRESOLV interface. Find the nce and put a copy
26446 			 * of the dl_unitdata_req in nce_res_mp
26447 			 */
26448 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
26449 			mutex_enter(&ire->ire_lock);
26450 			gw_addr_v6 = ire->ire_gateway_addr_v6;
26451 			mutex_exit(&ire->ire_lock);
26452 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26453 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
26454 				    B_FALSE);
26455 			} else {
26456 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
26457 			}
26458 			if (nce != NULL) {
26459 				/*
26460 				 * We have to protect nce_res_mp here
26461 				 * from being accessed by other threads
26462 				 * while we change the mblk pointer.
26463 				 * Other functions will also lock the nce when
26464 				 * accessing nce_res_mp.
26465 				 *
26466 				 * The reason we change the mblk pointer
26467 				 * here rather than copying the resolved address
26468 				 * into the template is that, unlike with
26469 				 * ethernet, we have no guarantee that the
26470 				 * resolved address length will be
26471 				 * smaller than or equal to the lla length
26472 				 * with which the template was allocated,
26473 				 * (for ethernet, they're equal)
26474 				 * so we have to use the actual resolved
26475 				 * address mblk - which holds the real
26476 				 * dl_unitdata_req with the resolved address.
26477 				 *
26478 				 * Doing this is the same behavior as was
26479 				 * previously used in the v4 ARP case.
26480 				 */
26481 				mutex_enter(&nce->nce_lock);
26482 				if (nce->nce_res_mp != NULL)
26483 					freemsg(nce->nce_res_mp);
26484 				nce->nce_res_mp = mp1;
26485 				mutex_exit(&nce->nce_lock);
26486 				/*
26487 				 * We do a fastpath probe here because
26488 				 * we have resolved the address without
26489 				 * using Neighbor Discovery.
26490 				 * In the non-XRESOLV v6 case, the fastpath
26491 				 * probe is done right after neighbor
26492 				 * discovery completes.
26493 				 */
26494 				if (nce->nce_res_mp != NULL) {
26495 					int res;
26496 					nce_fastpath_list_add(nce);
26497 					res = ill_fastpath_probe(ill,
26498 					    nce->nce_res_mp);
26499 					if (res != 0 && res != EAGAIN)
26500 						nce_fastpath_list_delete(nce);
26501 				}
26502 
26503 				ire_add_then_send(q, ire, mp);
26504 				/*
26505 				 * Now we have to clean out any packets
26506 				 * that may have been queued on the nce
26507 				 * while it was waiting for address resolution
26508 				 * to complete.
26509 				 */
26510 				mutex_enter(&nce->nce_lock);
26511 				mp1 = nce->nce_qd_mp;
26512 				nce->nce_qd_mp = NULL;
26513 				mutex_exit(&nce->nce_lock);
26514 				while (mp1 != NULL) {
26515 					mblk_t *nxt_mp;
26516 					queue_t *fwdq = NULL;
26517 					ill_t   *inbound_ill;
26518 					uint_t ifindex;
26519 
26520 					nxt_mp = mp1->b_next;
26521 					mp1->b_next = NULL;
26522 					/*
26523 					 * Retrieve ifindex stored in
26524 					 * ip_rput_data_v6()
26525 					 */
26526 					ifindex =
26527 					    (uint_t)(uintptr_t)mp1->b_prev;
26528 					inbound_ill =
26529 						ill_lookup_on_ifindex(ifindex,
26530 						    B_TRUE, NULL, NULL, NULL,
26531 						    NULL);
26532 					mp1->b_prev = NULL;
26533 					if (inbound_ill != NULL)
26534 						fwdq = inbound_ill->ill_rq;
26535 
26536 					if (fwdq != NULL) {
26537 						put(fwdq, mp1);
26538 						ill_refrele(inbound_ill);
26539 					} else
26540 						put(WR(ill->ill_rq), mp1);
26541 					mp1 = nxt_mp;
26542 				}
26543 				NCE_REFRELE(nce);
26544 			} else {	/* nce is NULL; clean up */
26545 				ire_delete(ire);
26546 				freemsg(mp);
26547 				freemsg(mp1);
26548 				return;
26549 			}
26550 		} else {
26551 			nce_t *arpce;
26552 			/*
26553 			 * Link layer resolution succeeded. Recompute the
26554 			 * ire_nce.
26555 			 */
26556 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
26557 			if ((arpce = ndp_lookup_v4(ill,
26558 			    (ire->ire_gateway_addr != INADDR_ANY ?
26559 			    &ire->ire_gateway_addr : &ire->ire_addr),
26560 			    B_FALSE)) == NULL) {
26561 				freeb(ire->ire_mp);
26562 				freeb(mp1);
26563 				freemsg(mp);
26564 				return;
26565 			}
26566 			mutex_enter(&arpce->nce_lock);
26567 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
26568 			if (arpce->nce_state == ND_REACHABLE) {
26569 				/*
26570 				 * Someone resolved this before us;
26571 				 * cleanup the res_mp. Since ire has
26572 				 * not been added yet, the call to ire_add_v4
26573 				 * from ire_add_then_send (when a dup is
26574 				 * detected) will clean up the ire.
26575 				 */
26576 				freeb(mp1);
26577 			} else {
26578 				if (arpce->nce_res_mp != NULL)
26579 					freemsg(arpce->nce_res_mp);
26580 				arpce->nce_res_mp = mp1;
26581 				arpce->nce_state = ND_REACHABLE;
26582 			}
26583 			mutex_exit(&arpce->nce_lock);
26584 			if (ire->ire_marks & IRE_MARK_NOADD) {
26585 				/*
26586 				 * this ire will not be added to the ire
26587 				 * cache table, so we can set the ire_nce
26588 				 * here, as there are no atomicity constraints.
26589 				 */
26590 				ire->ire_nce = arpce;
26591 				/*
26592 				 * We are associating this nce with the ire
26593 				 * so change the nce ref taken in
26594 				 * ndp_lookup_v4() from
26595 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
26596 				 */
26597 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
26598 			} else {
26599 				NCE_REFRELE(arpce);
26600 			}
26601 			ire_add_then_send(q, ire, mp);
26602 		}
26603 		return;	/* All is well, the packet has been sent. */
26604 	}
26605 	case IRE_ARPRESOLVE_TYPE: {
26606 
26607 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
26608 			break;
26609 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26610 		mp->b_cont = NULL;
26611 		/*
26612 		 * First, check to make sure the resolution succeeded.
26613 		 * If it failed, the second mblk will be empty.
26614 		 */
26615 		if (mp1->b_rptr == mp1->b_wptr) {
26616 			/* cleanup  the incomplete ire, free queued packets */
26617 			freemsg(mp); /* fake ire */
26618 			freeb(mp1);  /* dl_unitdata response */
26619 			return;
26620 		}
26621 
26622 		/*
26623 		 * update any incomplete nce_t found. we lookup the ctable
26624 		 * and find the nce from the ire->ire_nce because we need
26625 		 * to pass the ire to ip_xmit_v4 later, and can find both
26626 		 * ire and nce in one lookup from the ctable.
26627 		 */
26628 		fake_ire = (ire_t *)mp->b_rptr;
26629 		/*
26630 		 * By the time we come back here from ARP
26631 		 * the logical outgoing interface  of the incomplete ire
26632 		 * we added in ire_forward could have disappeared,
26633 		 * causing the incomplete ire to also have
26634 		 * dissapeared. So we need to retreive the
26635 		 * proper ipif for the ire  before looking
26636 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
26637 		 */
26638 		ill = q->q_ptr;
26639 
26640 		/* Get the outgoing ipif */
26641 		mutex_enter(&ill->ill_lock);
26642 		if (ill->ill_state_flags & ILL_CONDEMNED) {
26643 			mutex_exit(&ill->ill_lock);
26644 			freemsg(mp); /* fake ire */
26645 			freeb(mp1);  /* dl_unitdata response */
26646 			return;
26647 		}
26648 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
26649 
26650 		if (ipif == NULL) {
26651 			mutex_exit(&ill->ill_lock);
26652 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
26653 			freemsg(mp);
26654 			freeb(mp1);
26655 			return;
26656 		}
26657 		ipif_refhold_locked(ipif);
26658 		mutex_exit(&ill->ill_lock);
26659 		ire = ire_ctable_lookup(fake_ire->ire_addr,
26660 		    fake_ire->ire_gateway_addr, IRE_CACHE,
26661 		    ipif, fake_ire->ire_zoneid, NULL,
26662 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
26663 		ipif_refrele(ipif);
26664 		if (ire == NULL) {
26665 			/*
26666 			 * no ire was found; check if there is an nce
26667 			 * for this lookup; if it has no ire's pointing at it
26668 			 * cleanup.
26669 			 */
26670 			if ((nce = ndp_lookup_v4(ill,
26671 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
26672 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
26673 			    B_FALSE)) != NULL) {
26674 				/*
26675 				 * cleanup: just reset nce.
26676 				 * We check for refcnt 2 (one for the nce
26677 				 * hash list + 1 for the ref taken by
26678 				 * ndp_lookup_v4) to ensure that there are
26679 				 * no ire's pointing at the nce.
26680 				 */
26681 				if (nce->nce_refcnt == 2) {
26682 					nce = nce_reinit(nce);
26683 				}
26684 				if (nce != NULL)
26685 					NCE_REFRELE(nce);
26686 			}
26687 			freeb(mp1);  /* dl_unitdata response */
26688 			freemsg(mp); /* fake ire */
26689 			return;
26690 		}
26691 		nce = ire->ire_nce;
26692 		DTRACE_PROBE2(ire__arpresolve__type,
26693 		    ire_t *, ire, nce_t *, nce);
26694 		ASSERT(nce->nce_state != ND_INITIAL);
26695 		mutex_enter(&nce->nce_lock);
26696 		nce->nce_last = TICK_TO_MSEC(lbolt64);
26697 		if (nce->nce_state == ND_REACHABLE) {
26698 			/*
26699 			 * Someone resolved this before us;
26700 			 * our response is not needed any more.
26701 			 */
26702 			mutex_exit(&nce->nce_lock);
26703 			freeb(mp1);  /* dl_unitdata response */
26704 		} else {
26705 			if (nce->nce_res_mp != NULL) {
26706 				freemsg(nce->nce_res_mp);
26707 				/* existing dl_unitdata template */
26708 			}
26709 			nce->nce_res_mp = mp1;
26710 			nce->nce_state = ND_REACHABLE;
26711 			mutex_exit(&nce->nce_lock);
26712 			ire_fastpath(ire);
26713 		}
26714 		/*
26715 		 * The cached nce_t has been updated to be reachable;
26716 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
26717 		 */
26718 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
26719 		freemsg(mp);
26720 		/*
26721 		 * send out queued packets.
26722 		 */
26723 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26724 
26725 		IRE_REFRELE(ire);
26726 		return;
26727 	}
26728 	default:
26729 		break;
26730 	}
26731 	if (q->q_next) {
26732 		putnext(q, mp);
26733 	} else
26734 		freemsg(mp);
26735 }
26736 
26737 /*
26738  * Process IP options in an outbound packet.  Modify the destination if there
26739  * is a source route option.
26740  * Returns non-zero if something fails in which case an ICMP error has been
26741  * sent and mp freed.
26742  */
26743 static int
26744 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
26745     boolean_t mctl_present, zoneid_t zoneid)
26746 {
26747 	ipoptp_t	opts;
26748 	uchar_t		*opt;
26749 	uint8_t		optval;
26750 	uint8_t		optlen;
26751 	ipaddr_t	dst;
26752 	intptr_t	code = 0;
26753 	mblk_t		*mp;
26754 	ire_t		*ire = NULL;
26755 
26756 	ip2dbg(("ip_wput_options\n"));
26757 	mp = ipsec_mp;
26758 	if (mctl_present) {
26759 		mp = ipsec_mp->b_cont;
26760 	}
26761 
26762 	dst = ipha->ipha_dst;
26763 	for (optval = ipoptp_first(&opts, ipha);
26764 	    optval != IPOPT_EOL;
26765 	    optval = ipoptp_next(&opts)) {
26766 		opt = opts.ipoptp_cur;
26767 		optlen = opts.ipoptp_len;
26768 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
26769 		    optval, optlen));
26770 		switch (optval) {
26771 			uint32_t off;
26772 		case IPOPT_SSRR:
26773 		case IPOPT_LSRR:
26774 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26775 				ip1dbg((
26776 				    "ip_wput_options: bad option offset\n"));
26777 				code = (char *)&opt[IPOPT_OLEN] -
26778 				    (char *)ipha;
26779 				goto param_prob;
26780 			}
26781 			off = opt[IPOPT_OFFSET];
26782 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
26783 			    ntohl(dst)));
26784 			/*
26785 			 * For strict: verify that dst is directly
26786 			 * reachable.
26787 			 */
26788 			if (optval == IPOPT_SSRR) {
26789 				ire = ire_ftable_lookup(dst, 0, 0,
26790 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
26791 				    MBLK_GETLABEL(mp),
26792 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
26793 				if (ire == NULL) {
26794 					ip1dbg(("ip_wput_options: SSRR not"
26795 					    " directly reachable: 0x%x\n",
26796 					    ntohl(dst)));
26797 					goto bad_src_route;
26798 				}
26799 				ire_refrele(ire);
26800 			}
26801 			break;
26802 		case IPOPT_RR:
26803 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26804 				ip1dbg((
26805 				    "ip_wput_options: bad option offset\n"));
26806 				code = (char *)&opt[IPOPT_OLEN] -
26807 				    (char *)ipha;
26808 				goto param_prob;
26809 			}
26810 			break;
26811 		case IPOPT_TS:
26812 			/*
26813 			 * Verify that length >=5 and that there is either
26814 			 * room for another timestamp or that the overflow
26815 			 * counter is not maxed out.
26816 			 */
26817 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
26818 			if (optlen < IPOPT_MINLEN_IT) {
26819 				goto param_prob;
26820 			}
26821 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26822 				ip1dbg((
26823 				    "ip_wput_options: bad option offset\n"));
26824 				code = (char *)&opt[IPOPT_OFFSET] -
26825 				    (char *)ipha;
26826 				goto param_prob;
26827 			}
26828 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
26829 			case IPOPT_TS_TSONLY:
26830 				off = IPOPT_TS_TIMELEN;
26831 				break;
26832 			case IPOPT_TS_TSANDADDR:
26833 			case IPOPT_TS_PRESPEC:
26834 			case IPOPT_TS_PRESPEC_RFC791:
26835 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
26836 				break;
26837 			default:
26838 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
26839 				    (char *)ipha;
26840 				goto param_prob;
26841 			}
26842 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
26843 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
26844 				/*
26845 				 * No room and the overflow counter is 15
26846 				 * already.
26847 				 */
26848 				goto param_prob;
26849 			}
26850 			break;
26851 		}
26852 	}
26853 
26854 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
26855 		return (0);
26856 
26857 	ip1dbg(("ip_wput_options: error processing IP options."));
26858 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
26859 
26860 param_prob:
26861 	/*
26862 	 * Since ip_wput() isn't close to finished, we fill
26863 	 * in enough of the header for credible error reporting.
26864 	 */
26865 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
26866 		/* Failed */
26867 		freemsg(ipsec_mp);
26868 		return (-1);
26869 	}
26870 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid);
26871 	return (-1);
26872 
26873 bad_src_route:
26874 	/*
26875 	 * Since ip_wput() isn't close to finished, we fill
26876 	 * in enough of the header for credible error reporting.
26877 	 */
26878 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
26879 		/* Failed */
26880 		freemsg(ipsec_mp);
26881 		return (-1);
26882 	}
26883 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
26884 	return (-1);
26885 }
26886 
26887 /*
26888  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
26889  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
26890  * thru /etc/system.
26891  */
26892 #define	CONN_MAXDRAINCNT	64
26893 
26894 static void
26895 conn_drain_init(void)
26896 {
26897 	int i;
26898 
26899 	conn_drain_list_cnt = conn_drain_nthreads;
26900 
26901 	if ((conn_drain_list_cnt == 0) ||
26902 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
26903 		/*
26904 		 * Default value of the number of drainers is the
26905 		 * number of cpus, subject to maximum of 8 drainers.
26906 		 */
26907 		if (boot_max_ncpus != -1)
26908 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
26909 		else
26910 			conn_drain_list_cnt = MIN(max_ncpus, 8);
26911 	}
26912 
26913 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
26914 	    KM_SLEEP);
26915 
26916 	for (i = 0; i < conn_drain_list_cnt; i++) {
26917 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
26918 		    MUTEX_DEFAULT, NULL);
26919 	}
26920 }
26921 
26922 static void
26923 conn_drain_fini(void)
26924 {
26925 	int i;
26926 
26927 	for (i = 0; i < conn_drain_list_cnt; i++)
26928 		mutex_destroy(&conn_drain_list[i].idl_lock);
26929 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
26930 	conn_drain_list = NULL;
26931 }
26932 
26933 /*
26934  * Note: For an overview of how flowcontrol is handled in IP please see the
26935  * IP Flowcontrol notes at the top of this file.
26936  *
26937  * Flow control has blocked us from proceeding. Insert the given conn in one
26938  * of the conn drain lists. These conn wq's will be qenabled later on when
26939  * STREAMS flow control does a backenable. conn_walk_drain will enable
26940  * the first conn in each of these drain lists. Each of these qenabled conns
26941  * in turn enables the next in the list, after it runs, or when it closes,
26942  * thus sustaining the drain process.
26943  *
26944  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
26945  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
26946  * running at any time, on a given conn, since there can be only 1 service proc
26947  * running on a queue at any time.
26948  */
26949 void
26950 conn_drain_insert(conn_t *connp)
26951 {
26952 	idl_t	*idl;
26953 	uint_t	index;
26954 
26955 	mutex_enter(&connp->conn_lock);
26956 	if (connp->conn_state_flags & CONN_CLOSING) {
26957 		/*
26958 		 * The conn is closing as a result of which CONN_CLOSING
26959 		 * is set. Return.
26960 		 */
26961 		mutex_exit(&connp->conn_lock);
26962 		return;
26963 	} else if (connp->conn_idl == NULL) {
26964 		/*
26965 		 * Assign the next drain list round robin. We dont' use
26966 		 * a lock, and thus it may not be strictly round robin.
26967 		 * Atomicity of load/stores is enough to make sure that
26968 		 * conn_drain_list_index is always within bounds.
26969 		 */
26970 		index = conn_drain_list_index;
26971 		ASSERT(index < conn_drain_list_cnt);
26972 		connp->conn_idl = &conn_drain_list[index];
26973 		index++;
26974 		if (index == conn_drain_list_cnt)
26975 			index = 0;
26976 		conn_drain_list_index = index;
26977 	}
26978 	mutex_exit(&connp->conn_lock);
26979 
26980 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
26981 	if ((connp->conn_drain_prev != NULL) ||
26982 	    (connp->conn_state_flags & CONN_CLOSING)) {
26983 		/*
26984 		 * The conn is already in the drain list, OR
26985 		 * the conn is closing. We need to check again for
26986 		 * the closing case again since close can happen
26987 		 * after we drop the conn_lock, and before we
26988 		 * acquire the CONN_DRAIN_LIST_LOCK.
26989 		 */
26990 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26991 		return;
26992 	} else {
26993 		idl = connp->conn_idl;
26994 	}
26995 
26996 	/*
26997 	 * The conn is not in the drain list. Insert it at the
26998 	 * tail of the drain list. The drain list is circular
26999 	 * and doubly linked. idl_conn points to the 1st element
27000 	 * in the list.
27001 	 */
27002 	if (idl->idl_conn == NULL) {
27003 		idl->idl_conn = connp;
27004 		connp->conn_drain_next = connp;
27005 		connp->conn_drain_prev = connp;
27006 	} else {
27007 		conn_t *head = idl->idl_conn;
27008 
27009 		connp->conn_drain_next = head;
27010 		connp->conn_drain_prev = head->conn_drain_prev;
27011 		head->conn_drain_prev->conn_drain_next = connp;
27012 		head->conn_drain_prev = connp;
27013 	}
27014 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27015 }
27016 
27017 /*
27018  * This conn is closing, and we are called from ip_close. OR
27019  * This conn has been serviced by ip_wsrv, and we need to do the tail
27020  * processing.
27021  * If this conn is part of the drain list, we may need to sustain the drain
27022  * process by qenabling the next conn in the drain list. We may also need to
27023  * remove this conn from the list, if it is done.
27024  */
27025 static void
27026 conn_drain_tail(conn_t *connp, boolean_t closing)
27027 {
27028 	idl_t *idl;
27029 
27030 	/*
27031 	 * connp->conn_idl is stable at this point, and no lock is needed
27032 	 * to check it. If we are called from ip_close, close has already
27033 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27034 	 * called us only because conn_idl is non-null. If we are called thru
27035 	 * service, conn_idl could be null, but it cannot change because
27036 	 * service is single-threaded per queue, and there cannot be another
27037 	 * instance of service trying to call conn_drain_insert on this conn
27038 	 * now.
27039 	 */
27040 	ASSERT(!closing || (connp->conn_idl != NULL));
27041 
27042 	/*
27043 	 * If connp->conn_idl is null, the conn has not been inserted into any
27044 	 * drain list even once since creation of the conn. Just return.
27045 	 */
27046 	if (connp->conn_idl == NULL)
27047 		return;
27048 
27049 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27050 
27051 	if (connp->conn_drain_prev == NULL) {
27052 		/* This conn is currently not in the drain list.  */
27053 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27054 		return;
27055 	}
27056 	idl = connp->conn_idl;
27057 	if (idl->idl_conn_draining == connp) {
27058 		/*
27059 		 * This conn is the current drainer. If this is the last conn
27060 		 * in the drain list, we need to do more checks, in the 'if'
27061 		 * below. Otherwwise we need to just qenable the next conn,
27062 		 * to sustain the draining, and is handled in the 'else'
27063 		 * below.
27064 		 */
27065 		if (connp->conn_drain_next == idl->idl_conn) {
27066 			/*
27067 			 * This conn is the last in this list. This round
27068 			 * of draining is complete. If idl_repeat is set,
27069 			 * it means another flow enabling has happened from
27070 			 * the driver/streams and we need to another round
27071 			 * of draining.
27072 			 * If there are more than 2 conns in the drain list,
27073 			 * do a left rotate by 1, so that all conns except the
27074 			 * conn at the head move towards the head by 1, and the
27075 			 * the conn at the head goes to the tail. This attempts
27076 			 * a more even share for all queues that are being
27077 			 * drained.
27078 			 */
27079 			if ((connp->conn_drain_next != connp) &&
27080 			    (idl->idl_conn->conn_drain_next != connp)) {
27081 				idl->idl_conn = idl->idl_conn->conn_drain_next;
27082 			}
27083 			if (idl->idl_repeat) {
27084 				qenable(idl->idl_conn->conn_wq);
27085 				idl->idl_conn_draining = idl->idl_conn;
27086 				idl->idl_repeat = 0;
27087 			} else {
27088 				idl->idl_conn_draining = NULL;
27089 			}
27090 		} else {
27091 			/*
27092 			 * If the next queue that we are now qenable'ing,
27093 			 * is closing, it will remove itself from this list
27094 			 * and qenable the subsequent queue in ip_close().
27095 			 * Serialization is acheived thru idl_lock.
27096 			 */
27097 			qenable(connp->conn_drain_next->conn_wq);
27098 			idl->idl_conn_draining = connp->conn_drain_next;
27099 		}
27100 	}
27101 	if (!connp->conn_did_putbq || closing) {
27102 		/*
27103 		 * Remove ourself from the drain list, if we did not do
27104 		 * a putbq, or if the conn is closing.
27105 		 * Note: It is possible that q->q_first is non-null. It means
27106 		 * that these messages landed after we did a enableok() in
27107 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
27108 		 * service them.
27109 		 */
27110 		if (connp->conn_drain_next == connp) {
27111 			/* Singleton in the list */
27112 			ASSERT(connp->conn_drain_prev == connp);
27113 			idl->idl_conn = NULL;
27114 			idl->idl_conn_draining = NULL;
27115 		} else {
27116 			connp->conn_drain_prev->conn_drain_next =
27117 			    connp->conn_drain_next;
27118 			connp->conn_drain_next->conn_drain_prev =
27119 			    connp->conn_drain_prev;
27120 			if (idl->idl_conn == connp)
27121 				idl->idl_conn = connp->conn_drain_next;
27122 			ASSERT(idl->idl_conn_draining != connp);
27123 
27124 		}
27125 		connp->conn_drain_next = NULL;
27126 		connp->conn_drain_prev = NULL;
27127 	}
27128 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27129 }
27130 
27131 /*
27132  * Write service routine. Shared perimeter entry point.
27133  * ip_wsrv can be called in any of the following ways.
27134  * 1. The device queue's messages has fallen below the low water mark
27135  *    and STREAMS has backenabled the ill_wq. We walk thru all the
27136  *    the drain lists and backenable the first conn in each list.
27137  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
27138  *    qenabled non-tcp upper layers. We start dequeing messages and call
27139  *    ip_wput for each message.
27140  */
27141 
27142 void
27143 ip_wsrv(queue_t *q)
27144 {
27145 	conn_t	*connp;
27146 	ill_t	*ill;
27147 	mblk_t	*mp;
27148 
27149 	if (q->q_next) {
27150 		ill = (ill_t *)q->q_ptr;
27151 		if (ill->ill_state_flags == 0) {
27152 			/*
27153 			 * The device flow control has opened up.
27154 			 * Walk through conn drain lists and qenable the
27155 			 * first conn in each list. This makes sense only
27156 			 * if the stream is fully plumbed and setup.
27157 			 * Hence the if check above.
27158 			 */
27159 			ip1dbg(("ip_wsrv: walking\n"));
27160 			conn_walk_drain();
27161 		}
27162 		return;
27163 	}
27164 
27165 	connp = Q_TO_CONN(q);
27166 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
27167 
27168 	/*
27169 	 * 1. Set conn_draining flag to signal that service is active.
27170 	 *
27171 	 * 2. ip_output determines whether it has been called from service,
27172 	 *    based on the last parameter. If it is IP_WSRV it concludes it
27173 	 *    has been called from service.
27174 	 *
27175 	 * 3. Message ordering is preserved by the following logic.
27176 	 *    i. A directly called ip_output (i.e. not thru service) will queue
27177 	 *    the message at the tail, if conn_draining is set (i.e. service
27178 	 *    is running) or if q->q_first is non-null.
27179 	 *
27180 	 *    ii. If ip_output is called from service, and if ip_output cannot
27181 	 *    putnext due to flow control, it does a putbq.
27182 	 *
27183 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
27184 	 *    (causing an infinite loop).
27185 	 */
27186 	ASSERT(!connp->conn_did_putbq);
27187 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
27188 		connp->conn_draining = 1;
27189 		noenable(q);
27190 		while ((mp = getq(q)) != NULL) {
27191 			ASSERT(CONN_Q(q));
27192 
27193 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
27194 			if (connp->conn_did_putbq) {
27195 				/* ip_wput did a putbq */
27196 				break;
27197 			}
27198 		}
27199 		/*
27200 		 * At this point, a thread coming down from top, calling
27201 		 * ip_wput, may end up queueing the message. We have not yet
27202 		 * enabled the queue, so ip_wsrv won't be called again.
27203 		 * To avoid this race, check q->q_first again (in the loop)
27204 		 * If the other thread queued the message before we call
27205 		 * enableok(), we will catch it in the q->q_first check.
27206 		 * If the other thread queues the message after we call
27207 		 * enableok(), ip_wsrv will be called again by STREAMS.
27208 		 */
27209 		connp->conn_draining = 0;
27210 		enableok(q);
27211 	}
27212 
27213 	/* Enable the next conn for draining */
27214 	conn_drain_tail(connp, B_FALSE);
27215 
27216 	connp->conn_did_putbq = 0;
27217 }
27218 
27219 /*
27220  * Walk the list of all conn's calling the function provided with the
27221  * specified argument for each.	 Note that this only walks conn's that
27222  * have been bound.
27223  * Applies to both IPv4 and IPv6.
27224  */
27225 static void
27226 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
27227 {
27228 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
27229 	    func, arg, zoneid);
27230 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
27231 	    func, arg, zoneid);
27232 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
27233 	    func, arg, zoneid);
27234 	conn_walk_fanout_table(ipcl_proto_fanout,
27235 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
27236 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
27237 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
27238 }
27239 
27240 /*
27241  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
27242  * of conns that need to be drained, check if drain is already in progress.
27243  * If so set the idl_repeat bit, indicating that the last conn in the list
27244  * needs to reinitiate the drain once again, for the list. If drain is not
27245  * in progress for the list, initiate the draining, by qenabling the 1st
27246  * conn in the list. The drain is self-sustaining, each qenabled conn will
27247  * in turn qenable the next conn, when it is done/blocked/closing.
27248  */
27249 static void
27250 conn_walk_drain(void)
27251 {
27252 	int i;
27253 	idl_t *idl;
27254 
27255 	IP_STAT(ip_conn_walk_drain);
27256 
27257 	for (i = 0; i < conn_drain_list_cnt; i++) {
27258 		idl = &conn_drain_list[i];
27259 		mutex_enter(&idl->idl_lock);
27260 		if (idl->idl_conn == NULL) {
27261 			mutex_exit(&idl->idl_lock);
27262 			continue;
27263 		}
27264 		/*
27265 		 * If this list is not being drained currently by
27266 		 * an ip_wsrv thread, start the process.
27267 		 */
27268 		if (idl->idl_conn_draining == NULL) {
27269 			ASSERT(idl->idl_repeat == 0);
27270 			qenable(idl->idl_conn->conn_wq);
27271 			idl->idl_conn_draining = idl->idl_conn;
27272 		} else {
27273 			idl->idl_repeat = 1;
27274 		}
27275 		mutex_exit(&idl->idl_lock);
27276 	}
27277 }
27278 
27279 /*
27280  * Walk an conn hash table of `count' buckets, calling func for each entry.
27281  */
27282 static void
27283 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
27284     zoneid_t zoneid)
27285 {
27286 	conn_t	*connp;
27287 
27288 	while (count-- > 0) {
27289 		mutex_enter(&connfp->connf_lock);
27290 		for (connp = connfp->connf_head; connp != NULL;
27291 		    connp = connp->conn_next) {
27292 			if (zoneid == GLOBAL_ZONEID ||
27293 			    zoneid == connp->conn_zoneid) {
27294 				CONN_INC_REF(connp);
27295 				mutex_exit(&connfp->connf_lock);
27296 				(*func)(connp, arg);
27297 				mutex_enter(&connfp->connf_lock);
27298 				CONN_DEC_REF(connp);
27299 			}
27300 		}
27301 		mutex_exit(&connfp->connf_lock);
27302 		connfp++;
27303 	}
27304 }
27305 
27306 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
27307 static void
27308 conn_report1(conn_t *connp, void *mp)
27309 {
27310 	char	buf1[INET6_ADDRSTRLEN];
27311 	char	buf2[INET6_ADDRSTRLEN];
27312 	uint_t	print_len, buf_len;
27313 
27314 	ASSERT(connp != NULL);
27315 
27316 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
27317 	if (buf_len <= 0)
27318 		return;
27319 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
27320 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
27321 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
27322 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
27323 	    "%5d %s/%05d %s/%05d\n",
27324 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
27325 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
27326 	    buf1, connp->conn_lport,
27327 	    buf2, connp->conn_fport);
27328 	if (print_len < buf_len) {
27329 		((mblk_t *)mp)->b_wptr += print_len;
27330 	} else {
27331 		((mblk_t *)mp)->b_wptr += buf_len;
27332 	}
27333 }
27334 
27335 /*
27336  * Named Dispatch routine to produce a formatted report on all conns
27337  * that are listed in one of the fanout tables.
27338  * This report is accessed by using the ndd utility to "get" ND variable
27339  * "ip_conn_status".
27340  */
27341 /* ARGSUSED */
27342 static int
27343 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
27344 {
27345 	(void) mi_mpprintf(mp,
27346 	    "CONN      " MI_COL_HDRPAD_STR
27347 	    "rfq      " MI_COL_HDRPAD_STR
27348 	    "stq      " MI_COL_HDRPAD_STR
27349 	    " zone local                 remote");
27350 
27351 	/*
27352 	 * Because of the ndd constraint, at most we can have 64K buffer
27353 	 * to put in all conn info.  So to be more efficient, just
27354 	 * allocate a 64K buffer here, assuming we need that large buffer.
27355 	 * This should be OK as only privileged processes can do ndd /dev/ip.
27356 	 */
27357 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
27358 		/* The following may work even if we cannot get a large buf. */
27359 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
27360 		return (0);
27361 	}
27362 
27363 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
27364 	return (0);
27365 }
27366 
27367 /*
27368  * Determine if the ill and multicast aspects of that packets
27369  * "matches" the conn.
27370  */
27371 boolean_t
27372 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
27373     zoneid_t zoneid)
27374 {
27375 	ill_t *in_ill;
27376 	boolean_t found;
27377 	ipif_t *ipif;
27378 	ire_t *ire;
27379 	ipaddr_t dst, src;
27380 
27381 	dst = ipha->ipha_dst;
27382 	src = ipha->ipha_src;
27383 
27384 	/*
27385 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
27386 	 * unicast, broadcast and multicast reception to
27387 	 * conn_incoming_ill. conn_wantpacket itself is called
27388 	 * only for BROADCAST and multicast.
27389 	 *
27390 	 * 1) ip_rput supresses duplicate broadcasts if the ill
27391 	 *    is part of a group. Hence, we should be receiving
27392 	 *    just one copy of broadcast for the whole group.
27393 	 *    Thus, if it is part of the group the packet could
27394 	 *    come on any ill of the group and hence we need a
27395 	 *    match on the group. Otherwise, match on ill should
27396 	 *    be sufficient.
27397 	 *
27398 	 * 2) ip_rput does not suppress duplicate multicast packets.
27399 	 *    If there are two interfaces in a ill group and we have
27400 	 *    2 applications (conns) joined a multicast group G on
27401 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
27402 	 *    will give us two packets because we join G on both the
27403 	 *    interfaces rather than nominating just one interface
27404 	 *    for receiving multicast like broadcast above. So,
27405 	 *    we have to call ilg_lookup_ill to filter out duplicate
27406 	 *    copies, if ill is part of a group.
27407 	 */
27408 	in_ill = connp->conn_incoming_ill;
27409 	if (in_ill != NULL) {
27410 		if (in_ill->ill_group == NULL) {
27411 			if (in_ill != ill)
27412 				return (B_FALSE);
27413 		} else if (in_ill->ill_group != ill->ill_group) {
27414 			return (B_FALSE);
27415 		}
27416 	}
27417 
27418 	if (!CLASSD(dst)) {
27419 		if (IPCL_ZONE_MATCH(connp, zoneid))
27420 			return (B_TRUE);
27421 		/*
27422 		 * The conn is in a different zone; we need to check that this
27423 		 * broadcast address is configured in the application's zone and
27424 		 * on one ill in the group.
27425 		 */
27426 		ipif = ipif_get_next_ipif(NULL, ill);
27427 		if (ipif == NULL)
27428 			return (B_FALSE);
27429 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
27430 		    connp->conn_zoneid, NULL,
27431 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
27432 		ipif_refrele(ipif);
27433 		if (ire != NULL) {
27434 			ire_refrele(ire);
27435 			return (B_TRUE);
27436 		} else {
27437 			return (B_FALSE);
27438 		}
27439 	}
27440 
27441 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
27442 	    connp->conn_zoneid == zoneid) {
27443 		/*
27444 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
27445 		 * disabled, therefore we don't dispatch the multicast packet to
27446 		 * the sending zone.
27447 		 */
27448 		return (B_FALSE);
27449 	}
27450 
27451 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
27452 	    connp->conn_zoneid != zoneid) {
27453 		/*
27454 		 * Multicast packet on the loopback interface: we only match
27455 		 * conns who joined the group in the specified zone.
27456 		 */
27457 		return (B_FALSE);
27458 	}
27459 
27460 	if (connp->conn_multi_router) {
27461 		/* multicast packet and multicast router socket: send up */
27462 		return (B_TRUE);
27463 	}
27464 
27465 	mutex_enter(&connp->conn_lock);
27466 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
27467 	mutex_exit(&connp->conn_lock);
27468 	return (found);
27469 }
27470 
27471 /*
27472  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
27473  */
27474 /* ARGSUSED */
27475 static void
27476 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
27477 {
27478 	ill_t *ill = (ill_t *)q->q_ptr;
27479 	mblk_t	*mp1, *mp2;
27480 	ipif_t  *ipif;
27481 	int err = 0;
27482 	conn_t *connp = NULL;
27483 	ipsq_t	*ipsq;
27484 	arc_t	*arc;
27485 
27486 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
27487 
27488 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
27489 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
27490 
27491 	ASSERT(IAM_WRITER_ILL(ill));
27492 	mp2 = mp->b_cont;
27493 	mp->b_cont = NULL;
27494 
27495 	/*
27496 	 * We have now received the arp bringup completion message
27497 	 * from ARP. Mark the arp bringup as done. Also if the arp
27498 	 * stream has already started closing, send up the AR_ARP_CLOSING
27499 	 * ack now since ARP is waiting in close for this ack.
27500 	 */
27501 	mutex_enter(&ill->ill_lock);
27502 	ill->ill_arp_bringup_pending = 0;
27503 	if (ill->ill_arp_closing) {
27504 		mutex_exit(&ill->ill_lock);
27505 		/* Let's reuse the mp for sending the ack */
27506 		arc = (arc_t *)mp->b_rptr;
27507 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
27508 		arc->arc_cmd = AR_ARP_CLOSING;
27509 		qreply(q, mp);
27510 	} else {
27511 		mutex_exit(&ill->ill_lock);
27512 		freeb(mp);
27513 	}
27514 
27515 	/* We should have an IOCTL waiting on this. */
27516 	ipsq = ill->ill_phyint->phyint_ipsq;
27517 	ipif = ipsq->ipsq_pending_ipif;
27518 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
27519 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
27520 	if (mp1 == NULL) {
27521 		/* bringup was aborted by the user */
27522 		freemsg(mp2);
27523 		return;
27524 	}
27525 	ASSERT(connp != NULL);
27526 	q = CONNP_TO_WQ(connp);
27527 	/*
27528 	 * If the DL_BIND_REQ fails, it is noted
27529 	 * in arc_name_offset.
27530 	 */
27531 	err = *((int *)mp2->b_rptr);
27532 	if (err == 0) {
27533 		if (ipif->ipif_isv6) {
27534 			if ((err = ipif_up_done_v6(ipif)) != 0)
27535 				ip0dbg(("ip_arp_done: init failed\n"));
27536 		} else {
27537 			if ((err = ipif_up_done(ipif)) != 0)
27538 				ip0dbg(("ip_arp_done: init failed\n"));
27539 		}
27540 	} else {
27541 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
27542 	}
27543 
27544 	freemsg(mp2);
27545 
27546 	if ((err == 0) && (ill->ill_up_ipifs)) {
27547 		err = ill_up_ipifs(ill, q, mp1);
27548 		if (err == EINPROGRESS)
27549 			return;
27550 	}
27551 
27552 	if (ill->ill_up_ipifs) {
27553 		ill_group_cleanup(ill);
27554 	}
27555 
27556 	/*
27557 	 * The ioctl must complete now without EINPROGRESS
27558 	 * since ipsq_pending_mp_get has removed the ioctl mblk
27559 	 * from ipsq_pending_mp. Otherwise the ioctl will be
27560 	 * stuck for ever in the ipsq.
27561 	 */
27562 	ASSERT(err != EINPROGRESS);
27563 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
27564 }
27565 
27566 /* Allocate the private structure */
27567 static int
27568 ip_priv_alloc(void **bufp)
27569 {
27570 	void	*buf;
27571 
27572 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
27573 		return (ENOMEM);
27574 
27575 	*bufp = buf;
27576 	return (0);
27577 }
27578 
27579 /* Function to delete the private structure */
27580 void
27581 ip_priv_free(void *buf)
27582 {
27583 	ASSERT(buf != NULL);
27584 	kmem_free(buf, sizeof (ip_priv_t));
27585 }
27586 
27587 /*
27588  * The entry point for IPPF processing.
27589  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
27590  * routine just returns.
27591  *
27592  * When called, ip_process generates an ipp_packet_t structure
27593  * which holds the state information for this packet and invokes the
27594  * the classifier (via ipp_packet_process). The classification, depending on
27595  * configured filters, results in a list of actions for this packet. Invoking
27596  * an action may cause the packet to be dropped, in which case the resulting
27597  * mblk (*mpp) is NULL. proc indicates the callout position for
27598  * this packet and ill_index is the interface this packet on or will leave
27599  * on (inbound and outbound resp.).
27600  */
27601 void
27602 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
27603 {
27604 	mblk_t		*mp;
27605 	ip_priv_t	*priv;
27606 	ipp_action_id_t	aid;
27607 	int		rc = 0;
27608 	ipp_packet_t	*pp;
27609 #define	IP_CLASS	"ip"
27610 
27611 	/* If the classifier is not loaded, return  */
27612 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
27613 		return;
27614 	}
27615 
27616 	mp = *mpp;
27617 	ASSERT(mp != NULL);
27618 
27619 	/* Allocate the packet structure */
27620 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
27621 	if (rc != 0) {
27622 		*mpp = NULL;
27623 		freemsg(mp);
27624 		return;
27625 	}
27626 
27627 	/* Allocate the private structure */
27628 	rc = ip_priv_alloc((void **)&priv);
27629 	if (rc != 0) {
27630 		*mpp = NULL;
27631 		freemsg(mp);
27632 		ipp_packet_free(pp);
27633 		return;
27634 	}
27635 	priv->proc = proc;
27636 	priv->ill_index = ill_index;
27637 	ipp_packet_set_private(pp, priv, ip_priv_free);
27638 	ipp_packet_set_data(pp, mp);
27639 
27640 	/* Invoke the classifier */
27641 	rc = ipp_packet_process(&pp);
27642 	if (pp != NULL) {
27643 		mp = ipp_packet_get_data(pp);
27644 		ipp_packet_free(pp);
27645 		if (rc != 0) {
27646 			freemsg(mp);
27647 			*mpp = NULL;
27648 		}
27649 	} else {
27650 		*mpp = NULL;
27651 	}
27652 #undef	IP_CLASS
27653 }
27654 
27655 /*
27656  * Propagate a multicast group membership operation (add/drop) on
27657  * all the interfaces crossed by the related multirt routes.
27658  * The call is considered successful if the operation succeeds
27659  * on at least one interface.
27660  */
27661 static int
27662 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
27663     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
27664     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
27665     mblk_t *first_mp)
27666 {
27667 	ire_t		*ire_gw;
27668 	irb_t		*irb;
27669 	int		error = 0;
27670 	opt_restart_t	*or;
27671 
27672 	irb = ire->ire_bucket;
27673 	ASSERT(irb != NULL);
27674 
27675 	ASSERT(DB_TYPE(first_mp) == M_CTL);
27676 
27677 	or = (opt_restart_t *)first_mp->b_rptr;
27678 	IRB_REFHOLD(irb);
27679 	for (; ire != NULL; ire = ire->ire_next) {
27680 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
27681 			continue;
27682 		if (ire->ire_addr != group)
27683 			continue;
27684 
27685 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
27686 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
27687 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
27688 		/* No resolver exists for the gateway; skip this ire. */
27689 		if (ire_gw == NULL)
27690 			continue;
27691 
27692 		/*
27693 		 * This function can return EINPROGRESS. If so the operation
27694 		 * will be restarted from ip_restart_optmgmt which will
27695 		 * call ip_opt_set and option processing will restart for
27696 		 * this option. So we may end up calling 'fn' more than once.
27697 		 * This requires that 'fn' is idempotent except for the
27698 		 * return value. The operation is considered a success if
27699 		 * it succeeds at least once on any one interface.
27700 		 */
27701 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
27702 		    NULL, fmode, src, first_mp);
27703 		if (error == 0)
27704 			or->or_private = CGTP_MCAST_SUCCESS;
27705 
27706 		if (ip_debug > 0) {
27707 			ulong_t	off;
27708 			char	*ksym;
27709 			ksym = kobj_getsymname((uintptr_t)fn, &off);
27710 			ip2dbg(("ip_multirt_apply_membership: "
27711 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
27712 			    "error %d [success %u]\n",
27713 			    ksym ? ksym : "?",
27714 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
27715 			    error, or->or_private));
27716 		}
27717 
27718 		ire_refrele(ire_gw);
27719 		if (error == EINPROGRESS) {
27720 			IRB_REFRELE(irb);
27721 			return (error);
27722 		}
27723 	}
27724 	IRB_REFRELE(irb);
27725 	/*
27726 	 * Consider the call as successful if we succeeded on at least
27727 	 * one interface. Otherwise, return the last encountered error.
27728 	 */
27729 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
27730 }
27731 
27732 
27733 /*
27734  * Issue a warning regarding a route crossing an interface with an
27735  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
27736  * amount of time is logged.
27737  */
27738 static void
27739 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
27740 {
27741 	hrtime_t	current = gethrtime();
27742 	char		buf[INET_ADDRSTRLEN];
27743 
27744 	/* Convert interval in ms to hrtime in ns */
27745 	if (multirt_bad_mtu_last_time +
27746 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
27747 	    current) {
27748 		cmn_err(CE_WARN, "ip: ignoring multiroute "
27749 		    "to %s, incorrect MTU %u (expected %u)\n",
27750 		    ip_dot_addr(ire->ire_addr, buf),
27751 		    ire->ire_max_frag, max_frag);
27752 
27753 		multirt_bad_mtu_last_time = current;
27754 	}
27755 }
27756 
27757 
27758 /*
27759  * Get the CGTP (multirouting) filtering status.
27760  * If 0, the CGTP hooks are transparent.
27761  */
27762 /* ARGSUSED */
27763 static int
27764 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
27765 {
27766 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
27767 
27768 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
27769 	return (0);
27770 }
27771 
27772 
27773 /*
27774  * Set the CGTP (multirouting) filtering status.
27775  * If the status is changed from active to transparent
27776  * or from transparent to active, forward the new status
27777  * to the filtering module (if loaded).
27778  */
27779 /* ARGSUSED */
27780 static int
27781 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
27782     cred_t *ioc_cr)
27783 {
27784 	long		new_value;
27785 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
27786 
27787 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
27788 	    new_value < 0 || new_value > 1) {
27789 		return (EINVAL);
27790 	}
27791 
27792 	/*
27793 	 * Do not enable CGTP filtering - thus preventing the hooks
27794 	 * from being invoked - if the version number of the
27795 	 * filtering module hooks does not match.
27796 	 */
27797 	if ((ip_cgtp_filter_ops != NULL) &&
27798 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
27799 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
27800 		    "(module hooks version %d, expecting %d)\n",
27801 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
27802 		return (ENOTSUP);
27803 	}
27804 
27805 	if ((!*ip_cgtp_filter_value) && new_value) {
27806 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
27807 		    ip_cgtp_filter_ops == NULL ?
27808 		    " (module not loaded)" : "");
27809 	}
27810 	if (*ip_cgtp_filter_value && (!new_value)) {
27811 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
27812 		    ip_cgtp_filter_ops == NULL ?
27813 		    " (module not loaded)" : "");
27814 	}
27815 
27816 	if (ip_cgtp_filter_ops != NULL) {
27817 		int	res;
27818 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
27819 			return (res);
27820 		}
27821 	}
27822 
27823 	*ip_cgtp_filter_value = (boolean_t)new_value;
27824 
27825 	return (0);
27826 }
27827 
27828 
27829 /*
27830  * Return the expected CGTP hooks version number.
27831  */
27832 int
27833 ip_cgtp_filter_supported(void)
27834 {
27835 	return (ip_cgtp_filter_rev);
27836 }
27837 
27838 
27839 /*
27840  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
27841  * or by invoking this function. In the first case, the version number
27842  * of the registered structure is checked at hooks activation time
27843  * in ip_cgtp_filter_set().
27844  */
27845 int
27846 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
27847 {
27848 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
27849 		return (ENOTSUP);
27850 
27851 	ip_cgtp_filter_ops = ops;
27852 	return (0);
27853 }
27854 
27855 static squeue_func_t
27856 ip_squeue_switch(int val)
27857 {
27858 	squeue_func_t rval = squeue_fill;
27859 
27860 	switch (val) {
27861 	case IP_SQUEUE_ENTER_NODRAIN:
27862 		rval = squeue_enter_nodrain;
27863 		break;
27864 	case IP_SQUEUE_ENTER:
27865 		rval = squeue_enter;
27866 		break;
27867 	default:
27868 		break;
27869 	}
27870 	return (rval);
27871 }
27872 
27873 /* ARGSUSED */
27874 static int
27875 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
27876     caddr_t addr, cred_t *cr)
27877 {
27878 	int *v = (int *)addr;
27879 	long new_value;
27880 
27881 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
27882 		return (EINVAL);
27883 
27884 	ip_input_proc = ip_squeue_switch(new_value);
27885 	*v = new_value;
27886 	return (0);
27887 }
27888 
27889 /* ARGSUSED */
27890 static int
27891 ip_int_set(queue_t *q, mblk_t *mp, char *value,
27892     caddr_t addr, cred_t *cr)
27893 {
27894 	int *v = (int *)addr;
27895 	long new_value;
27896 
27897 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
27898 		return (EINVAL);
27899 
27900 	*v = new_value;
27901 	return (0);
27902 }
27903 
27904 static void
27905 ip_kstat_init(void)
27906 {
27907 	ip_named_kstat_t template = {
27908 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
27909 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
27910 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
27911 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
27912 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
27913 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
27914 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
27915 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
27916 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
27917 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
27918 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
27919 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
27920 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
27921 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
27922 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
27923 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
27924 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
27925 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
27926 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
27927 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
27928 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
27929 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
27930 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
27931 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
27932 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
27933 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
27934 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
27935 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
27936 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
27937 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
27938 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
27939 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
27940 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
27941 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
27942 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
27943 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
27944 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
27945 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
27946 	};
27947 
27948 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
27949 					NUM_OF_FIELDS(ip_named_kstat_t),
27950 					0);
27951 	if (!ip_mibkp)
27952 		return;
27953 
27954 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
27955 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
27956 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
27957 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
27958 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
27959 
27960 	template.netToMediaEntrySize.value.i32 =
27961 		sizeof (mib2_ipNetToMediaEntry_t);
27962 
27963 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
27964 
27965 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
27966 
27967 	ip_mibkp->ks_update = ip_kstat_update;
27968 
27969 	kstat_install(ip_mibkp);
27970 }
27971 
27972 static void
27973 ip_kstat_fini(void)
27974 {
27975 
27976 	if (ip_mibkp != NULL) {
27977 		kstat_delete(ip_mibkp);
27978 		ip_mibkp = NULL;
27979 	}
27980 }
27981 
27982 static int
27983 ip_kstat_update(kstat_t *kp, int rw)
27984 {
27985 	ip_named_kstat_t *ipkp;
27986 
27987 	if (!kp || !kp->ks_data)
27988 		return (EIO);
27989 
27990 	if (rw == KSTAT_WRITE)
27991 		return (EACCES);
27992 
27993 	ipkp = (ip_named_kstat_t *)kp->ks_data;
27994 
27995 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
27996 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
27997 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
27998 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
27999 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
28000 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
28001 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
28002 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
28003 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
28004 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
28005 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
28006 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
28007 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
28008 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
28009 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
28010 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
28011 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
28012 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
28013 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
28014 
28015 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
28016 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
28017 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
28018 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
28019 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
28020 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
28021 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
28022 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
28023 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
28024 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
28025 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
28026 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
28027 
28028 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
28029 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
28030 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
28031 
28032 	return (0);
28033 }
28034 
28035 static void
28036 icmp_kstat_init(void)
28037 {
28038 	icmp_named_kstat_t template = {
28039 		{ "inMsgs",		KSTAT_DATA_UINT32 },
28040 		{ "inErrors",		KSTAT_DATA_UINT32 },
28041 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
28042 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
28043 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
28044 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
28045 		{ "inRedirects",	KSTAT_DATA_UINT32 },
28046 		{ "inEchos",		KSTAT_DATA_UINT32 },
28047 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
28048 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
28049 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
28050 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
28051 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
28052 		{ "outMsgs",		KSTAT_DATA_UINT32 },
28053 		{ "outErrors",		KSTAT_DATA_UINT32 },
28054 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
28055 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
28056 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
28057 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
28058 		{ "outRedirects",	KSTAT_DATA_UINT32 },
28059 		{ "outEchos",		KSTAT_DATA_UINT32 },
28060 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
28061 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
28062 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
28063 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
28064 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
28065 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
28066 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
28067 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
28068 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
28069 		{ "outDrops",		KSTAT_DATA_UINT32 },
28070 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
28071 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
28072 	};
28073 
28074 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
28075 					NUM_OF_FIELDS(icmp_named_kstat_t),
28076 					0);
28077 	if (icmp_mibkp == NULL)
28078 		return;
28079 
28080 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
28081 
28082 	icmp_mibkp->ks_update = icmp_kstat_update;
28083 
28084 	kstat_install(icmp_mibkp);
28085 }
28086 
28087 static void
28088 icmp_kstat_fini(void)
28089 {
28090 
28091 	if (icmp_mibkp != NULL) {
28092 		kstat_delete(icmp_mibkp);
28093 		icmp_mibkp = NULL;
28094 	}
28095 }
28096 
28097 static int
28098 icmp_kstat_update(kstat_t *kp, int rw)
28099 {
28100 	icmp_named_kstat_t *icmpkp;
28101 
28102 	if ((kp == NULL) || (kp->ks_data == NULL))
28103 		return (EIO);
28104 
28105 	if (rw == KSTAT_WRITE)
28106 		return (EACCES);
28107 
28108 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
28109 
28110 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
28111 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
28112 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
28113 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
28114 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
28115 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
28116 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
28117 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
28118 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
28119 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
28120 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
28121 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
28122 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
28123 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
28124 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
28125 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
28126 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
28127 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
28128 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
28129 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
28130 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
28131 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
28132 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
28133 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
28134 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
28135 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
28136 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
28137 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
28138 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
28139 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
28140 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
28141 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
28142 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
28143 
28144 	return (0);
28145 }
28146 
28147 /*
28148  * This is the fanout function for raw socket opened for SCTP.  Note
28149  * that it is called after SCTP checks that there is no socket which
28150  * wants a packet.  Then before SCTP handles this out of the blue packet,
28151  * this function is called to see if there is any raw socket for SCTP.
28152  * If there is and it is bound to the correct address, the packet will
28153  * be sent to that socket.  Note that only one raw socket can be bound to
28154  * a port.  This is assured in ipcl_sctp_hash_insert();
28155  */
28156 void
28157 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
28158     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
28159     uint_t ipif_seqid, zoneid_t zoneid)
28160 {
28161 	conn_t		*connp;
28162 	queue_t		*rq;
28163 	mblk_t		*first_mp;
28164 	boolean_t	secure;
28165 	ip6_t		*ip6h;
28166 
28167 	first_mp = mp;
28168 	if (mctl_present) {
28169 		mp = first_mp->b_cont;
28170 		secure = ipsec_in_is_secure(first_mp);
28171 		ASSERT(mp != NULL);
28172 	} else {
28173 		secure = B_FALSE;
28174 	}
28175 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
28176 
28177 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
28178 	if (connp == NULL) {
28179 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
28180 		    mctl_present);
28181 		return;
28182 	}
28183 	rq = connp->conn_rq;
28184 	if (!canputnext(rq)) {
28185 		CONN_DEC_REF(connp);
28186 		BUMP_MIB(&ip_mib, rawipInOverflows);
28187 		freemsg(first_mp);
28188 		return;
28189 	}
28190 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
28191 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
28192 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
28193 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
28194 		if (first_mp == NULL) {
28195 			CONN_DEC_REF(connp);
28196 			return;
28197 		}
28198 	}
28199 	/*
28200 	 * We probably should not send M_CTL message up to
28201 	 * raw socket.
28202 	 */
28203 	if (mctl_present)
28204 		freeb(first_mp);
28205 
28206 	/* Initiate IPPF processing here if needed. */
28207 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
28208 	    (!isv4 && IP6_IN_IPP(flags))) {
28209 		ip_process(IPP_LOCAL_IN, &mp,
28210 		    recv_ill->ill_phyint->phyint_ifindex);
28211 		if (mp == NULL) {
28212 			CONN_DEC_REF(connp);
28213 			return;
28214 		}
28215 	}
28216 
28217 	if (connp->conn_recvif || connp->conn_recvslla ||
28218 	    ((connp->conn_ipv6_recvpktinfo ||
28219 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
28220 	    (flags & IP_FF_IP6INFO))) {
28221 		int in_flags = 0;
28222 
28223 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
28224 			in_flags = IPF_RECVIF;
28225 		}
28226 		if (connp->conn_recvslla) {
28227 			in_flags |= IPF_RECVSLLA;
28228 		}
28229 		if (isv4) {
28230 			mp = ip_add_info(mp, recv_ill, in_flags);
28231 		} else {
28232 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
28233 			if (mp == NULL) {
28234 				CONN_DEC_REF(connp);
28235 				return;
28236 			}
28237 		}
28238 	}
28239 
28240 	BUMP_MIB(&ip_mib, ipInDelivers);
28241 	/*
28242 	 * We are sending the IPSEC_IN message also up. Refer
28243 	 * to comments above this function.
28244 	 */
28245 	putnext(rq, mp);
28246 	CONN_DEC_REF(connp);
28247 }
28248 
28249 /*
28250  * This function should be called only if all packet processing
28251  * including fragmentation is complete. Callers of this function
28252  * must set mp->b_prev to one of these values:
28253  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
28254  * prior to handing over the mp as first argument to this function.
28255  *
28256  * If the ire passed by caller is incomplete, this function
28257  * queues the packet and if necessary, sends ARP request and bails.
28258  * If the ire passed is fully resolved, we simply prepend
28259  * the link-layer header to the packet, do ipsec hw acceleration
28260  * work if necessary, and send the packet out on the wire.
28261  *
28262  * NOTE: IPSEC will only call this function with fully resolved
28263  * ires if hw acceleration is involved.
28264  * TODO list :
28265  * 	a Handle M_MULTIDATA so that
28266  *	  tcp_multisend->tcp_multisend_data can
28267  *	  call ip_xmit_v4 directly
28268  *	b Handle post-ARP work for fragments so that
28269  *	  ip_wput_frag can call this function.
28270  */
28271 ipxmit_state_t
28272 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
28273 {
28274 	nce_t		*arpce;
28275 	queue_t		*q;
28276 	int		ill_index;
28277 	mblk_t		*nxt_mp;
28278 	boolean_t	xmit_drop = B_FALSE;
28279 	ip_proc_t	proc;
28280 
28281 	arpce = ire->ire_nce;
28282 	ASSERT(arpce != NULL);
28283 
28284 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
28285 
28286 	mutex_enter(&arpce->nce_lock);
28287 	switch (arpce->nce_state) {
28288 	case ND_REACHABLE:
28289 		/* If there are other queued packets, queue this packet */
28290 		if (arpce->nce_qd_mp != NULL) {
28291 			if (mp != NULL)
28292 				nce_queue_mp_common(arpce, mp, B_FALSE);
28293 			mp = arpce->nce_qd_mp;
28294 		}
28295 		arpce->nce_qd_mp = NULL;
28296 		mutex_exit(&arpce->nce_lock);
28297 
28298 		/*
28299 		 * Flush the queue.  In the common case, where the
28300 		 * ARP is already resolved,  it will go through the
28301 		 * while loop only once.
28302 		 */
28303 		while (mp != NULL) {
28304 
28305 			nxt_mp = mp->b_next;
28306 			mp->b_next = NULL;
28307 			/*
28308 			 * This info is needed for IPQOS to do COS marking
28309 			 * in ip_wput_attach_llhdr->ip_process.
28310 			 */
28311 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
28312 			mp->b_prev = NULL;
28313 
28314 			/* set up ill index for outbound qos processing */
28315 			ill_index =
28316 			    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
28317 			mp = ip_wput_attach_llhdr(mp, ire, proc, ill_index);
28318 			if (mp == NULL) {
28319 				xmit_drop = B_TRUE;
28320 				if (proc == IPP_FWD_OUT) {
28321 					BUMP_MIB(&ip_mib, ipInDiscards);
28322 				} else {
28323 					BUMP_MIB(&ip_mib, ipOutDiscards);
28324 				}
28325 				goto next_mp;
28326 			}
28327 			/* non-ipsec hw accel case */
28328 			if (io == NULL || !io->ipsec_out_accelerated) {
28329 				/* send it */
28330 				q = ire->ire_stq;
28331 				if (proc == IPP_FWD_OUT) {
28332 					UPDATE_IB_PKT_COUNT(ire);
28333 				} else {
28334 					UPDATE_OB_PKT_COUNT(ire);
28335 				}
28336 				ire->ire_last_used_time = lbolt;
28337 
28338 				if (flow_ctl_enabled) {
28339 					/*
28340 					 * We are here from ip_wout_ire
28341 					 * which has already done canput
28342 					 * check and has enabled flow
28343 					 * control, so skip the canputnext
28344 					 * check.
28345 					 */
28346 					putnext(q, mp);
28347 					goto next_mp;
28348 				}
28349 				if (canputnext(q))  {
28350 					if (proc == IPP_FWD_OUT) {
28351 						BUMP_MIB(&ip_mib,
28352 						    ipForwDatagrams);
28353 					}
28354 					putnext(q, mp);
28355 				} else {
28356 					BUMP_MIB(&ip_mib,
28357 					    ipOutDiscards);
28358 					xmit_drop = B_TRUE;
28359 					freemsg(mp);
28360 				}
28361 			} else {
28362 				/*
28363 				 * Safety Pup says: make sure this
28364 				 *  is going to the right interface!
28365 				 */
28366 				ill_t *ill1 =
28367 				    (ill_t *)ire->ire_stq->q_ptr;
28368 				int ifindex =
28369 				    ill1->ill_phyint->phyint_ifindex;
28370 				if (ifindex !=
28371 				    io->ipsec_out_capab_ill_index) {
28372 					xmit_drop = B_TRUE;
28373 					freemsg(mp);
28374 				} else {
28375 					ipsec_hw_putnext(ire->ire_stq,
28376 					    mp);
28377 				}
28378 			}
28379 next_mp:
28380 			mp = nxt_mp;
28381 		} /* while (mp != NULL) */
28382 		if (xmit_drop)
28383 			return (SEND_FAILED);
28384 		else
28385 			return (SEND_PASSED);
28386 
28387 	case ND_INITIAL:
28388 	case ND_INCOMPLETE:
28389 
28390 		/*
28391 		 * While we do send off packets to dests that
28392 		 * use fully-resolved CGTP routes, we do not
28393 		 * handle unresolved CGTP routes.
28394 		 */
28395 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
28396 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
28397 
28398 		if (mp != NULL) {
28399 			/* queue the packet */
28400 			nce_queue_mp_common(arpce, mp, B_FALSE);
28401 		}
28402 
28403 		if (arpce->nce_state == ND_INCOMPLETE) {
28404 			mutex_exit(&arpce->nce_lock);
28405 			DTRACE_PROBE3(ip__xmit__incomplete,
28406 			    (ire_t *), ire, (mblk_t *), mp,
28407 			    (ipsec_out_t *), io);
28408 			return (LOOKUP_IN_PROGRESS);
28409 		}
28410 
28411 		arpce->nce_state = ND_INCOMPLETE;
28412 		mutex_exit(&arpce->nce_lock);
28413 		/*
28414 		 * Note that ire_add() (called from ire_forward())
28415 		 * holds a ref on the ire until ARP is completed.
28416 		 */
28417 
28418 		ire_arpresolve(ire, ire->ire_ipif->ipif_ill);
28419 		return (LOOKUP_IN_PROGRESS);
28420 	default:
28421 		ASSERT(0);
28422 		mutex_exit(&arpce->nce_lock);
28423 		return (LLHDR_RESLV_FAILED);
28424 	}
28425 }
28426 
28427 /*
28428  * Return B_TRUE if the buffers differ in length or content.
28429  * This is used for comparing extension header buffers.
28430  * Note that an extension header would be declared different
28431  * even if all that changed was the next header value in that header i.e.
28432  * what really changed is the next extension header.
28433  */
28434 boolean_t
28435 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
28436     uint_t blen)
28437 {
28438 	if (!b_valid)
28439 		blen = 0;
28440 
28441 	if (alen != blen)
28442 		return (B_TRUE);
28443 	if (alen == 0)
28444 		return (B_FALSE);	/* Both zero length */
28445 	return (bcmp(abuf, bbuf, alen));
28446 }
28447 
28448 /*
28449  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
28450  * Return B_FALSE if memory allocation fails - don't change any state!
28451  */
28452 boolean_t
28453 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28454     const void *src, uint_t srclen)
28455 {
28456 	void *dst;
28457 
28458 	if (!src_valid)
28459 		srclen = 0;
28460 
28461 	ASSERT(*dstlenp == 0);
28462 	if (src != NULL && srclen != 0) {
28463 		dst = mi_alloc(srclen, BPRI_MED);
28464 		if (dst == NULL)
28465 			return (B_FALSE);
28466 	} else {
28467 		dst = NULL;
28468 	}
28469 	if (*dstp != NULL)
28470 		mi_free(*dstp);
28471 	*dstp = dst;
28472 	*dstlenp = dst == NULL ? 0 : srclen;
28473 	return (B_TRUE);
28474 }
28475 
28476 /*
28477  * Replace what is in *dst, *dstlen with the source.
28478  * Assumes ip_allocbuf has already been called.
28479  */
28480 void
28481 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28482     const void *src, uint_t srclen)
28483 {
28484 	if (!src_valid)
28485 		srclen = 0;
28486 
28487 	ASSERT(*dstlenp == srclen);
28488 	if (src != NULL && srclen != 0)
28489 		bcopy(src, *dstp, srclen);
28490 }
28491 
28492 /*
28493  * Free the storage pointed to by the members of an ip6_pkt_t.
28494  */
28495 void
28496 ip6_pkt_free(ip6_pkt_t *ipp)
28497 {
28498 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
28499 
28500 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
28501 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
28502 		ipp->ipp_hopopts = NULL;
28503 		ipp->ipp_hopoptslen = 0;
28504 	}
28505 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
28506 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
28507 		ipp->ipp_rtdstopts = NULL;
28508 		ipp->ipp_rtdstoptslen = 0;
28509 	}
28510 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
28511 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
28512 		ipp->ipp_dstopts = NULL;
28513 		ipp->ipp_dstoptslen = 0;
28514 	}
28515 	if (ipp->ipp_fields & IPPF_RTHDR) {
28516 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
28517 		ipp->ipp_rthdr = NULL;
28518 		ipp->ipp_rthdrlen = 0;
28519 	}
28520 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
28521 	    IPPF_RTHDR);
28522 }
28523