xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision 2278144afd2005b3eabcfd9bc412fe5ceb78749d)
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 			    !IPCL_ZONE_MATCH(connp, 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,
4792 			    connp->conn_zoneid);
4793 			if (ipif == NULL) {
4794 				error = ENETUNREACH;
4795 				goto bad_addr;
4796 			}
4797 			ipif_refrele(ipif);
4798 		}
4799 
4800 		if (connp->conn_nexthop_set) {
4801 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4802 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4803 			    MATCH_IRE_SECATTR);
4804 		} else {
4805 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4806 			    &sire, zoneid, MBLK_GETLABEL(mp),
4807 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4808 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4809 			    MATCH_IRE_SECATTR));
4810 		}
4811 	}
4812 	/*
4813 	 * dst_ire can't be a broadcast when not ire_requested.
4814 	 * We also prevent ire's with src address INADDR_ANY to
4815 	 * be used, which are created temporarily for
4816 	 * sending out packets from endpoints that have
4817 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4818 	 * reachable.  If verify_dst is false, the destination needn't be
4819 	 * reachable.
4820 	 *
4821 	 * If we match on a reject or black hole, then we've got a
4822 	 * local failure.  May as well fail out the connect() attempt,
4823 	 * since it's never going to succeed.
4824 	 */
4825 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4826 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4827 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4828 		/*
4829 		 * If we're verifying destination reachability, we always want
4830 		 * to complain here.
4831 		 *
4832 		 * If we're not verifying destination reachability but the
4833 		 * destination has a route, we still want to fail on the
4834 		 * temporary address and broadcast address tests.
4835 		 */
4836 		if (verify_dst || (dst_ire != NULL)) {
4837 			if (ip_debug > 2) {
4838 				pr_addr_dbg("ip_bind_connected: bad connected "
4839 				    "dst %s\n", AF_INET, &dst_addr);
4840 			}
4841 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4842 				error = ENETUNREACH;
4843 			else
4844 				error = EHOSTUNREACH;
4845 			goto bad_addr;
4846 		}
4847 	}
4848 
4849 	/*
4850 	 * We now know that routing will allow us to reach the destination.
4851 	 * Check whether Trusted Solaris policy allows communication with this
4852 	 * host, and pretend that the destination is unreachable if not.
4853 	 *
4854 	 * This is never a problem for TCP, since that transport is known to
4855 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4856 	 * handling.  If the remote is unreachable, it will be detected at that
4857 	 * point, so there's no reason to check it here.
4858 	 *
4859 	 * Note that for sendto (and other datagram-oriented friends), this
4860 	 * check is done as part of the data path label computation instead.
4861 	 * The check here is just to make non-TCP connect() report the right
4862 	 * error.
4863 	 */
4864 	if (dst_ire != NULL && is_system_labeled() &&
4865 	    !IPCL_IS_TCP(connp) &&
4866 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4867 	    connp->conn_mac_exempt) != 0) {
4868 		error = EHOSTUNREACH;
4869 		if (ip_debug > 2) {
4870 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4871 			    AF_INET, &dst_addr);
4872 		}
4873 		goto bad_addr;
4874 	}
4875 
4876 	/*
4877 	 * If the app does a connect(), it means that it will most likely
4878 	 * send more than 1 packet to the destination.  It makes sense
4879 	 * to clear the temporary flag.
4880 	 */
4881 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4882 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4883 		irb_t *irb = dst_ire->ire_bucket;
4884 
4885 		rw_enter(&irb->irb_lock, RW_WRITER);
4886 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4887 		irb->irb_tmp_ire_cnt--;
4888 		rw_exit(&irb->irb_lock);
4889 	}
4890 
4891 	/*
4892 	 * See if we should notify ULP about MDT; we do this whether or not
4893 	 * ire_requested is TRUE, in order to handle active connects; MDT
4894 	 * eligibility tests for passive connects are handled separately
4895 	 * through tcp_adapt_ire().  We do this before the source address
4896 	 * selection, because dst_ire may change after a call to
4897 	 * ipif_select_source().  This is a best-effort check, as the
4898 	 * packet for this connection may not actually go through
4899 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4900 	 * calling ip_newroute().  This is why we further check on the
4901 	 * IRE during Multidata packet transmission in tcp_multisend().
4902 	 */
4903 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4904 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4905 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4906 	    ILL_MDT_CAPABLE(md_ill)) {
4907 		md_dst_ire = dst_ire;
4908 		IRE_REFHOLD(md_dst_ire);
4909 	}
4910 
4911 	if (dst_ire != NULL &&
4912 	    dst_ire->ire_type == IRE_LOCAL &&
4913 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4914 		/*
4915 		 * If the IRE belongs to a different zone, look for a matching
4916 		 * route in the forwarding table and use the source address from
4917 		 * that route.
4918 		 */
4919 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4920 		    zoneid, 0, NULL,
4921 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4922 		    MATCH_IRE_RJ_BHOLE);
4923 		if (src_ire == NULL) {
4924 			error = EHOSTUNREACH;
4925 			goto bad_addr;
4926 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4927 			if (!(src_ire->ire_type & IRE_HOST))
4928 				error = ENETUNREACH;
4929 			else
4930 				error = EHOSTUNREACH;
4931 			goto bad_addr;
4932 		}
4933 		if (src_addr == INADDR_ANY)
4934 			src_addr = src_ire->ire_src_addr;
4935 		ire_refrele(src_ire);
4936 		src_ire = NULL;
4937 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4938 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4939 			src_addr = sire->ire_src_addr;
4940 			ire_refrele(dst_ire);
4941 			dst_ire = sire;
4942 			sire = NULL;
4943 		} else {
4944 			/*
4945 			 * Pick a source address so that a proper inbound
4946 			 * load spreading would happen.
4947 			 */
4948 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4949 			ipif_t *src_ipif = NULL;
4950 			ire_t *ipif_ire;
4951 
4952 			/*
4953 			 * Supply a local source address such that inbound
4954 			 * load spreading happens.
4955 			 *
4956 			 * Determine the best source address on this ill for
4957 			 * the destination.
4958 			 *
4959 			 * 1) For broadcast, we should return a broadcast ire
4960 			 *    found above so that upper layers know that the
4961 			 *    destination address is a broadcast address.
4962 			 *
4963 			 * 2) If this is part of a group, select a better
4964 			 *    source address so that better inbound load
4965 			 *    balancing happens. Do the same if the ipif
4966 			 *    is DEPRECATED.
4967 			 *
4968 			 * 3) If the outgoing interface is part of a usesrc
4969 			 *    group, then try selecting a source address from
4970 			 *    the usesrc ILL.
4971 			 */
4972 			if ((dst_ire->ire_zoneid != zoneid &&
4973 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4974 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4975 			    ((dst_ill->ill_group != NULL) ||
4976 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4977 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4978 				/*
4979 				 * If the destination is reachable via a
4980 				 * given gateway, the selected source address
4981 				 * should be in the same subnet as the gateway.
4982 				 * Otherwise, the destination is not reachable.
4983 				 *
4984 				 * If there are no interfaces on the same subnet
4985 				 * as the destination, ipif_select_source gives
4986 				 * first non-deprecated interface which might be
4987 				 * on a different subnet than the gateway.
4988 				 * This is not desirable. Hence pass the dst_ire
4989 				 * source address to ipif_select_source.
4990 				 * It is sure that the destination is reachable
4991 				 * with the dst_ire source address subnet.
4992 				 * So passing dst_ire source address to
4993 				 * ipif_select_source will make sure that the
4994 				 * selected source will be on the same subnet
4995 				 * as dst_ire source address.
4996 				 */
4997 				ipaddr_t saddr =
4998 				    dst_ire->ire_ipif->ipif_src_addr;
4999 				src_ipif = ipif_select_source(dst_ill,
5000 				    saddr, zoneid);
5001 				if (src_ipif != NULL) {
5002 					if (IS_VNI(src_ipif->ipif_ill)) {
5003 						/*
5004 						 * For VNI there is no
5005 						 * interface route
5006 						 */
5007 						src_addr =
5008 						    src_ipif->ipif_src_addr;
5009 					} else {
5010 						ipif_ire =
5011 						    ipif_to_ire(src_ipif);
5012 						if (ipif_ire != NULL) {
5013 							IRE_REFRELE(dst_ire);
5014 							dst_ire = ipif_ire;
5015 						}
5016 						src_addr =
5017 						    dst_ire->ire_src_addr;
5018 					}
5019 					ipif_refrele(src_ipif);
5020 				} else {
5021 					src_addr = dst_ire->ire_src_addr;
5022 				}
5023 			} else {
5024 				src_addr = dst_ire->ire_src_addr;
5025 			}
5026 		}
5027 	}
5028 
5029 	/*
5030 	 * We do ire_route_lookup() here (and not
5031 	 * interface lookup as we assert that
5032 	 * src_addr should only come from an
5033 	 * UP interface for hard binding.
5034 	 */
5035 	ASSERT(src_ire == NULL);
5036 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5037 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
5038 	/* src_ire must be a local|loopback */
5039 	if (!IRE_IS_LOCAL(src_ire)) {
5040 		if (ip_debug > 2) {
5041 			pr_addr_dbg("ip_bind_connected: bad connected "
5042 			    "src %s\n", AF_INET, &src_addr);
5043 		}
5044 		error = EADDRNOTAVAIL;
5045 		goto bad_addr;
5046 	}
5047 
5048 	/*
5049 	 * If the source address is a loopback address, the
5050 	 * destination had best be local or multicast.
5051 	 * The transports that can't handle multicast will reject
5052 	 * those addresses.
5053 	 */
5054 	if (src_ire->ire_type == IRE_LOOPBACK &&
5055 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5056 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5057 		error = -1;
5058 		goto bad_addr;
5059 	}
5060 
5061 	/*
5062 	 * Allow setting new policies. For example, disconnects come
5063 	 * down as ipa_t bind. As we would have set conn_policy_cached
5064 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5065 	 * can change after the disconnect.
5066 	 */
5067 	connp->conn_policy_cached = B_FALSE;
5068 
5069 	/*
5070 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5071 	 * can handle their passed-in conn's.
5072 	 */
5073 
5074 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5075 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5076 	connp->conn_lport = lport;
5077 	connp->conn_fport = fport;
5078 	*src_addrp = src_addr;
5079 
5080 	ASSERT(!(ipsec_policy_set && ire_requested));
5081 	if (ire_requested) {
5082 		iulp_t *ulp_info = NULL;
5083 
5084 		/*
5085 		 * Note that sire will not be NULL if this is an off-link
5086 		 * connection and there is not cache for that dest yet.
5087 		 *
5088 		 * XXX Because of an existing bug, if there are multiple
5089 		 * default routes, the IRE returned now may not be the actual
5090 		 * default route used (default routes are chosen in a
5091 		 * round robin fashion).  So if the metrics for different
5092 		 * default routes are different, we may return the wrong
5093 		 * metrics.  This will not be a problem if the existing
5094 		 * bug is fixed.
5095 		 */
5096 		if (sire != NULL) {
5097 			ulp_info = &(sire->ire_uinfo);
5098 		}
5099 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5100 			error = -1;
5101 			goto bad_addr;
5102 		}
5103 	} else if (ipsec_policy_set) {
5104 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5105 			error = -1;
5106 			goto bad_addr;
5107 		}
5108 	}
5109 
5110 	/*
5111 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5112 	 * we'll cache that.  If we don't, we'll inherit global policy.
5113 	 *
5114 	 * We can't insert until the conn reflects the policy. Note that
5115 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5116 	 * connections where we don't have a policy. This is to prevent
5117 	 * global policy lookups in the inbound path.
5118 	 *
5119 	 * If we insert before we set conn_policy_cached,
5120 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5121 	 * because global policy cound be non-empty. We normally call
5122 	 * ipsec_check_policy() for conn_policy_cached connections only if
5123 	 * ipc_in_enforce_policy is set. But in this case,
5124 	 * conn_policy_cached can get set anytime since we made the
5125 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5126 	 * called, which will make the above assumption false.  Thus, we
5127 	 * need to insert after we set conn_policy_cached.
5128 	 */
5129 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5130 		goto bad_addr;
5131 
5132 	if (fanout_insert) {
5133 		/*
5134 		 * The addresses have been verified. Time to insert in
5135 		 * the correct fanout list.
5136 		 */
5137 		error = ipcl_conn_insert(connp, protocol, src_addr,
5138 		    dst_addr, connp->conn_ports);
5139 	}
5140 
5141 	if (error == 0) {
5142 		connp->conn_fully_bound = B_TRUE;
5143 		/*
5144 		 * Our initial checks for MDT have passed; the IRE is not
5145 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5146 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
5147 		 * ip_mdinfo_return(), which performs further checks
5148 		 * against them and upon success, returns the MDT info
5149 		 * mblk which we will attach to the bind acknowledgment.
5150 		 */
5151 		if (md_dst_ire != NULL) {
5152 			mblk_t *mdinfo_mp;
5153 
5154 			ASSERT(md_ill != NULL);
5155 			ASSERT(md_ill->ill_mdt_capab != NULL);
5156 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5157 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
5158 				linkb(mp, mdinfo_mp);
5159 		}
5160 	}
5161 bad_addr:
5162 	if (ipsec_policy_set) {
5163 		ASSERT(policy_mp == mp->b_cont);
5164 		ASSERT(policy_mp != NULL);
5165 		freeb(policy_mp);
5166 		/*
5167 		 * As of now assume that nothing else accompanies
5168 		 * IPSEC_POLICY_SET.
5169 		 */
5170 		mp->b_cont = NULL;
5171 	}
5172 	if (src_ire != NULL)
5173 		IRE_REFRELE(src_ire);
5174 	if (dst_ire != NULL)
5175 		IRE_REFRELE(dst_ire);
5176 	if (sire != NULL)
5177 		IRE_REFRELE(sire);
5178 	if (md_dst_ire != NULL)
5179 		IRE_REFRELE(md_dst_ire);
5180 	return (error);
5181 }
5182 
5183 /*
5184  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5185  * Prefers dst_ire over src_ire.
5186  */
5187 static boolean_t
5188 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5189 {
5190 	mblk_t	*mp1;
5191 	ire_t *ret_ire = NULL;
5192 
5193 	mp1 = mp->b_cont;
5194 	ASSERT(mp1 != NULL);
5195 
5196 	if (ire != NULL) {
5197 		/*
5198 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5199 		 * appended mblk. Its <upper protocol>'s
5200 		 * job to make sure there is room.
5201 		 */
5202 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5203 			return (0);
5204 
5205 		mp1->b_datap->db_type = IRE_DB_TYPE;
5206 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5207 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5208 		ret_ire = (ire_t *)mp1->b_rptr;
5209 		/*
5210 		 * Pass the latest setting of the ip_path_mtu_discovery and
5211 		 * copy the ulp info if any.
5212 		 */
5213 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5214 		    IPH_DF : 0;
5215 		if (ulp_info != NULL) {
5216 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5217 			    sizeof (iulp_t));
5218 		}
5219 		ret_ire->ire_mp = mp1;
5220 	} else {
5221 		/*
5222 		 * No IRE was found. Remove IRE mblk.
5223 		 */
5224 		mp->b_cont = mp1->b_cont;
5225 		freeb(mp1);
5226 	}
5227 
5228 	return (1);
5229 }
5230 
5231 /*
5232  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5233  * the final piece where we don't.  Return a pointer to the first mblk in the
5234  * result, and update the pointer to the next mblk to chew on.  If anything
5235  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5236  * NULL pointer.
5237  */
5238 mblk_t *
5239 ip_carve_mp(mblk_t **mpp, ssize_t len)
5240 {
5241 	mblk_t	*mp0;
5242 	mblk_t	*mp1;
5243 	mblk_t	*mp2;
5244 
5245 	if (!len || !mpp || !(mp0 = *mpp))
5246 		return (NULL);
5247 	/* If we aren't going to consume the first mblk, we need a dup. */
5248 	if (mp0->b_wptr - mp0->b_rptr > len) {
5249 		mp1 = dupb(mp0);
5250 		if (mp1) {
5251 			/* Partition the data between the two mblks. */
5252 			mp1->b_wptr = mp1->b_rptr + len;
5253 			mp0->b_rptr = mp1->b_wptr;
5254 			/*
5255 			 * after adjustments if mblk not consumed is now
5256 			 * unaligned, try to align it. If this fails free
5257 			 * all messages and let upper layer recover.
5258 			 */
5259 			if (!OK_32PTR(mp0->b_rptr)) {
5260 				if (!pullupmsg(mp0, -1)) {
5261 					freemsg(mp0);
5262 					freemsg(mp1);
5263 					*mpp = NULL;
5264 					return (NULL);
5265 				}
5266 			}
5267 		}
5268 		return (mp1);
5269 	}
5270 	/* Eat through as many mblks as we need to get len bytes. */
5271 	len -= mp0->b_wptr - mp0->b_rptr;
5272 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5273 		if (mp2->b_wptr - mp2->b_rptr > len) {
5274 			/*
5275 			 * We won't consume the entire last mblk.  Like
5276 			 * above, dup and partition it.
5277 			 */
5278 			mp1->b_cont = dupb(mp2);
5279 			mp1 = mp1->b_cont;
5280 			if (!mp1) {
5281 				/*
5282 				 * Trouble.  Rather than go to a lot of
5283 				 * trouble to clean up, we free the messages.
5284 				 * This won't be any worse than losing it on
5285 				 * the wire.
5286 				 */
5287 				freemsg(mp0);
5288 				freemsg(mp2);
5289 				*mpp = NULL;
5290 				return (NULL);
5291 			}
5292 			mp1->b_wptr = mp1->b_rptr + len;
5293 			mp2->b_rptr = mp1->b_wptr;
5294 			/*
5295 			 * after adjustments if mblk not consumed is now
5296 			 * unaligned, try to align it. If this fails free
5297 			 * all messages and let upper layer recover.
5298 			 */
5299 			if (!OK_32PTR(mp2->b_rptr)) {
5300 				if (!pullupmsg(mp2, -1)) {
5301 					freemsg(mp0);
5302 					freemsg(mp2);
5303 					*mpp = NULL;
5304 					return (NULL);
5305 				}
5306 			}
5307 			*mpp = mp2;
5308 			return (mp0);
5309 		}
5310 		/* Decrement len by the amount we just got. */
5311 		len -= mp2->b_wptr - mp2->b_rptr;
5312 	}
5313 	/*
5314 	 * len should be reduced to zero now.  If not our caller has
5315 	 * screwed up.
5316 	 */
5317 	if (len) {
5318 		/* Shouldn't happen! */
5319 		freemsg(mp0);
5320 		*mpp = NULL;
5321 		return (NULL);
5322 	}
5323 	/*
5324 	 * We consumed up to exactly the end of an mblk.  Detach the part
5325 	 * we are returning from the rest of the chain.
5326 	 */
5327 	mp1->b_cont = NULL;
5328 	*mpp = mp2;
5329 	return (mp0);
5330 }
5331 
5332 /* The ill stream is being unplumbed. Called from ip_close */
5333 int
5334 ip_modclose(ill_t *ill)
5335 {
5336 
5337 	boolean_t success;
5338 	ipsq_t	*ipsq;
5339 	ipif_t	*ipif;
5340 	queue_t	*q = ill->ill_rq;
5341 
5342 	/*
5343 	 * Forcibly enter the ipsq after some delay. This is to take
5344 	 * care of the case when some ioctl does not complete because
5345 	 * we sent a control message to the driver and it did not
5346 	 * send us a reply. We want to be able to at least unplumb
5347 	 * and replumb rather than force the user to reboot the system.
5348 	 */
5349 	success = ipsq_enter(ill, B_FALSE);
5350 
5351 	/*
5352 	 * Open/close/push/pop is guaranteed to be single threaded
5353 	 * per stream by STREAMS. FS guarantees that all references
5354 	 * from top are gone before close is called. So there can't
5355 	 * be another close thread that has set CONDEMNED on this ill.
5356 	 * and cause ipsq_enter to return failure.
5357 	 */
5358 	ASSERT(success);
5359 	ipsq = ill->ill_phyint->phyint_ipsq;
5360 
5361 	/*
5362 	 * Mark it condemned. No new reference will be made to this ill.
5363 	 * Lookup functions will return an error. Threads that try to
5364 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5365 	 * that the refcnt will drop down to zero.
5366 	 */
5367 	mutex_enter(&ill->ill_lock);
5368 	ill->ill_state_flags |= ILL_CONDEMNED;
5369 	for (ipif = ill->ill_ipif; ipif != NULL;
5370 	    ipif = ipif->ipif_next) {
5371 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5372 	}
5373 	/*
5374 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5375 	 * returns  error if ILL_CONDEMNED is set
5376 	 */
5377 	cv_broadcast(&ill->ill_cv);
5378 	mutex_exit(&ill->ill_lock);
5379 
5380 	/*
5381 	 * Shut down fragmentation reassembly.
5382 	 * ill_frag_timer won't start a timer again.
5383 	 * Now cancel any existing timer
5384 	 */
5385 	(void) untimeout(ill->ill_frag_timer_id);
5386 	(void) ill_frag_timeout(ill, 0);
5387 
5388 	/*
5389 	 * If MOVE was in progress, clear the
5390 	 * move_in_progress fields also.
5391 	 */
5392 	if (ill->ill_move_in_progress) {
5393 		ILL_CLEAR_MOVE(ill);
5394 	}
5395 
5396 	/*
5397 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5398 	 * this ill. Then wait for the refcnts to drop to zero.
5399 	 * ill_is_quiescent checks whether the ill is really quiescent.
5400 	 * Then make sure that threads that are waiting to enter the
5401 	 * ipsq have seen the error returned by ipsq_enter and have
5402 	 * gone away. Then we call ill_delete_tail which does the
5403 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5404 	 */
5405 	ill_delete(ill);
5406 	mutex_enter(&ill->ill_lock);
5407 	while (!ill_is_quiescent(ill))
5408 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5409 	while (ill->ill_waiters)
5410 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5411 
5412 	mutex_exit(&ill->ill_lock);
5413 
5414 	/* qprocsoff is called in ill_delete_tail */
5415 	ill_delete_tail(ill);
5416 
5417 	/*
5418 	 * Walk through all upper (conn) streams and qenable
5419 	 * those that have queued data.
5420 	 * close synchronization needs this to
5421 	 * be done to ensure that all upper layers blocked
5422 	 * due to flow control to the closing device
5423 	 * get unblocked.
5424 	 */
5425 	ip1dbg(("ip_wsrv: walking\n"));
5426 	conn_walk_drain();
5427 
5428 	mutex_enter(&ip_mi_lock);
5429 	mi_close_unlink(&ip_g_head, (IDP)ill);
5430 	mutex_exit(&ip_mi_lock);
5431 
5432 	/*
5433 	 * credp could be null if the open didn't succeed and ip_modopen
5434 	 * itself calls ip_close.
5435 	 */
5436 	if (ill->ill_credp != NULL)
5437 		crfree(ill->ill_credp);
5438 
5439 	mi_close_free((IDP)ill);
5440 	q->q_ptr = WR(q)->q_ptr = NULL;
5441 
5442 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5443 
5444 	return (0);
5445 }
5446 
5447 /*
5448  * This is called as part of close() for both IP and UDP
5449  * in order to quiesce the conn.
5450  */
5451 void
5452 ip_quiesce_conn(conn_t *connp)
5453 {
5454 	boolean_t	drain_cleanup_reqd = B_FALSE;
5455 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5456 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5457 
5458 	ASSERT(!IPCL_IS_TCP(connp));
5459 
5460 	/*
5461 	 * Mark the conn as closing, and this conn must not be
5462 	 * inserted in future into any list. Eg. conn_drain_insert(),
5463 	 * won't insert this conn into the conn_drain_list.
5464 	 * Similarly ill_pending_mp_add() will not add any mp to
5465 	 * the pending mp list, after this conn has started closing.
5466 	 *
5467 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5468 	 * cannot get set henceforth.
5469 	 */
5470 	mutex_enter(&connp->conn_lock);
5471 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5472 	connp->conn_state_flags |= CONN_CLOSING;
5473 	if (connp->conn_idl != NULL)
5474 		drain_cleanup_reqd = B_TRUE;
5475 	if (connp->conn_oper_pending_ill != NULL)
5476 		conn_ioctl_cleanup_reqd = B_TRUE;
5477 	if (connp->conn_ilg_inuse != 0)
5478 		ilg_cleanup_reqd = B_TRUE;
5479 	mutex_exit(&connp->conn_lock);
5480 
5481 	if (IPCL_IS_UDP(connp))
5482 		udp_quiesce_conn(connp);
5483 
5484 	if (conn_ioctl_cleanup_reqd)
5485 		conn_ioctl_cleanup(connp);
5486 
5487 	if (is_system_labeled() && connp->conn_anon_port) {
5488 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5489 		    connp->conn_mlp_type, connp->conn_ulp,
5490 		    ntohs(connp->conn_lport), B_FALSE);
5491 		connp->conn_anon_port = 0;
5492 	}
5493 	connp->conn_mlp_type = mlptSingle;
5494 
5495 	/*
5496 	 * Remove this conn from any fanout list it is on.
5497 	 * and then wait for any threads currently operating
5498 	 * on this endpoint to finish
5499 	 */
5500 	ipcl_hash_remove(connp);
5501 
5502 	/*
5503 	 * Remove this conn from the drain list, and do
5504 	 * any other cleanup that may be required.
5505 	 * (Only non-tcp streams may have a non-null conn_idl.
5506 	 * TCP streams are never flow controlled, and
5507 	 * conn_idl will be null)
5508 	 */
5509 	if (drain_cleanup_reqd)
5510 		conn_drain_tail(connp, B_TRUE);
5511 
5512 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5513 		(void) ip_mrouter_done(NULL);
5514 
5515 	if (ilg_cleanup_reqd)
5516 		ilg_delete_all(connp);
5517 
5518 	conn_delete_ire(connp, NULL);
5519 
5520 	/*
5521 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5522 	 * callers from write side can't be there now because close
5523 	 * is in progress. The only other caller is ipcl_walk
5524 	 * which checks for the condemned flag.
5525 	 */
5526 	mutex_enter(&connp->conn_lock);
5527 	connp->conn_state_flags |= CONN_CONDEMNED;
5528 	while (connp->conn_ref != 1)
5529 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5530 	connp->conn_state_flags |= CONN_QUIESCED;
5531 	mutex_exit(&connp->conn_lock);
5532 }
5533 
5534 /* ARGSUSED */
5535 int
5536 ip_close(queue_t *q, int flags)
5537 {
5538 	conn_t		*connp;
5539 
5540 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5541 
5542 	/*
5543 	 * Call the appropriate delete routine depending on whether this is
5544 	 * a module or device.
5545 	 */
5546 	if (WR(q)->q_next != NULL) {
5547 		/* This is a module close */
5548 		return (ip_modclose((ill_t *)q->q_ptr));
5549 	}
5550 
5551 	connp = q->q_ptr;
5552 	ip_quiesce_conn(connp);
5553 
5554 	qprocsoff(q);
5555 
5556 	/*
5557 	 * Now we are truly single threaded on this stream, and can
5558 	 * delete the things hanging off the connp, and finally the connp.
5559 	 * We removed this connp from the fanout list, it cannot be
5560 	 * accessed thru the fanouts, and we already waited for the
5561 	 * conn_ref to drop to 0. We are already in close, so
5562 	 * there cannot be any other thread from the top. qprocsoff
5563 	 * has completed, and service has completed or won't run in
5564 	 * future.
5565 	 */
5566 	ASSERT(connp->conn_ref == 1);
5567 
5568 	/*
5569 	 * A conn which was previously marked as IPCL_UDP cannot
5570 	 * retain the flag because it would have been cleared by
5571 	 * udp_close().
5572 	 */
5573 	ASSERT(!IPCL_IS_UDP(connp));
5574 
5575 	if (connp->conn_latch != NULL) {
5576 		IPLATCH_REFRELE(connp->conn_latch);
5577 		connp->conn_latch = NULL;
5578 	}
5579 	if (connp->conn_policy != NULL) {
5580 		IPPH_REFRELE(connp->conn_policy);
5581 		connp->conn_policy = NULL;
5582 	}
5583 	if (connp->conn_ipsec_opt_mp != NULL) {
5584 		freemsg(connp->conn_ipsec_opt_mp);
5585 		connp->conn_ipsec_opt_mp = NULL;
5586 	}
5587 
5588 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5589 
5590 	connp->conn_ref--;
5591 	ipcl_conn_destroy(connp);
5592 
5593 	q->q_ptr = WR(q)->q_ptr = NULL;
5594 	return (0);
5595 }
5596 
5597 int
5598 ip_snmpmod_close(queue_t *q)
5599 {
5600 	conn_t *connp = Q_TO_CONN(q);
5601 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5602 
5603 	qprocsoff(q);
5604 
5605 	if (connp->conn_flags & IPCL_UDPMOD)
5606 		udp_close_free(connp);
5607 
5608 	if (connp->conn_cred != NULL) {
5609 		crfree(connp->conn_cred);
5610 		connp->conn_cred = NULL;
5611 	}
5612 	CONN_DEC_REF(connp);
5613 	q->q_ptr = WR(q)->q_ptr = NULL;
5614 	return (0);
5615 }
5616 
5617 /*
5618  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5619  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5620  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5621  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5622  * queues as we never enqueue messages there and we don't handle any ioctls.
5623  * Everything else is freed.
5624  */
5625 void
5626 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5627 {
5628 	conn_t	*connp = q->q_ptr;
5629 	pfi_t	setfn;
5630 	pfi_t	getfn;
5631 
5632 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5633 
5634 	switch (DB_TYPE(mp)) {
5635 	case M_PROTO:
5636 	case M_PCPROTO:
5637 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5638 		    ((((union T_primitives *)mp->b_rptr)->type ==
5639 			T_SVR4_OPTMGMT_REQ) ||
5640 		    (((union T_primitives *)mp->b_rptr)->type ==
5641 			T_OPTMGMT_REQ))) {
5642 			/*
5643 			 * This is the only TPI primitive supported. Its
5644 			 * handling does not require tcp_t, but it does require
5645 			 * conn_t to check permissions.
5646 			 */
5647 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5648 
5649 			if (connp->conn_flags & IPCL_TCPMOD) {
5650 				setfn = tcp_snmp_set;
5651 				getfn = tcp_snmp_get;
5652 			} else {
5653 				setfn = udp_snmp_set;
5654 				getfn = udp_snmp_get;
5655 			}
5656 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5657 				freemsg(mp);
5658 				return;
5659 			}
5660 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5661 		    != NULL)
5662 			qreply(q, mp);
5663 		break;
5664 	case M_FLUSH:
5665 	case M_IOCTL:
5666 		putnext(q, mp);
5667 		break;
5668 	default:
5669 		freemsg(mp);
5670 		break;
5671 	}
5672 }
5673 
5674 /* Return the IP checksum for the IP header at "iph". */
5675 uint16_t
5676 ip_csum_hdr(ipha_t *ipha)
5677 {
5678 	uint16_t	*uph;
5679 	uint32_t	sum;
5680 	int		opt_len;
5681 
5682 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5683 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5684 	uph = (uint16_t *)ipha;
5685 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5686 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5687 	if (opt_len > 0) {
5688 		do {
5689 			sum += uph[10];
5690 			sum += uph[11];
5691 			uph += 2;
5692 		} while (--opt_len);
5693 	}
5694 	sum = (sum & 0xFFFF) + (sum >> 16);
5695 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5696 	if (sum == 0xffff)
5697 		sum = 0;
5698 	return ((uint16_t)sum);
5699 }
5700 
5701 void
5702 ip_ddi_destroy(void)
5703 {
5704 	tnet_fini();
5705 	tcp_ddi_destroy();
5706 	sctp_ddi_destroy();
5707 	ipsec_loader_destroy();
5708 	ipsec_policy_destroy();
5709 	ipsec_kstat_destroy();
5710 	nd_free(&ip_g_nd);
5711 	mutex_destroy(&igmp_timer_lock);
5712 	mutex_destroy(&mld_timer_lock);
5713 	mutex_destroy(&igmp_slowtimeout_lock);
5714 	mutex_destroy(&mld_slowtimeout_lock);
5715 	mutex_destroy(&ip_mi_lock);
5716 	mutex_destroy(&rts_clients.connf_lock);
5717 	ip_ire_fini();
5718 	ip6_asp_free();
5719 	conn_drain_fini();
5720 	ipcl_destroy();
5721 	inet_minor_destroy(ip_minor_arena);
5722 	icmp_kstat_fini();
5723 	ip_kstat_fini();
5724 	rw_destroy(&ipsec_capab_ills_lock);
5725 	rw_destroy(&ill_g_usesrc_lock);
5726 	ip_drop_unregister(&ip_dropper);
5727 }
5728 
5729 
5730 void
5731 ip_ddi_init(void)
5732 {
5733 	TCP6_MAJ = ddi_name_to_major(TCP6);
5734 	TCP_MAJ	= ddi_name_to_major(TCP);
5735 	SCTP_MAJ = ddi_name_to_major(SCTP);
5736 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5737 
5738 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5739 
5740 	/* IP's IPsec code calls the packet dropper */
5741 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5742 
5743 	if (!ip_g_nd) {
5744 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5745 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5746 			nd_free(&ip_g_nd);
5747 		}
5748 	}
5749 
5750 	ipsec_loader_init();
5751 	ipsec_policy_init();
5752 	ipsec_kstat_init();
5753 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5754 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5755 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5756 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5757 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5758 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5759 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5760 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5761 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5762 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5763 
5764 	/*
5765 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5766 	 * initial devices: ip, ip6, tcp, tcp6.
5767 	 */
5768 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5769 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5770 		cmn_err(CE_PANIC,
5771 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5772 	}
5773 
5774 	ipcl_init();
5775 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5776 	ip_ire_init();
5777 	ip6_asp_init();
5778 	ipif_init();
5779 	conn_drain_init();
5780 	tcp_ddi_init();
5781 	sctp_ddi_init();
5782 
5783 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5784 
5785 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5786 		"net", KSTAT_TYPE_NAMED,
5787 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5788 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5789 		ip_kstat->ks_data = &ip_statistics;
5790 		kstat_install(ip_kstat);
5791 	}
5792 	ip_kstat_init();
5793 	ip6_kstat_init();
5794 	icmp_kstat_init();
5795 	ipsec_loader_start();
5796 	tnet_init();
5797 }
5798 
5799 /*
5800  * Allocate and initialize a DLPI template of the specified length.  (May be
5801  * called as writer.)
5802  */
5803 mblk_t *
5804 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5805 {
5806 	mblk_t	*mp;
5807 
5808 	mp = allocb(len, BPRI_MED);
5809 	if (!mp)
5810 		return (NULL);
5811 
5812 	/*
5813 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5814 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5815 	 * that other DLPI are M_PROTO.
5816 	 */
5817 	if (prim == DL_INFO_REQ) {
5818 		mp->b_datap->db_type = M_PCPROTO;
5819 	} else {
5820 		mp->b_datap->db_type = M_PROTO;
5821 	}
5822 
5823 	mp->b_wptr = mp->b_rptr + len;
5824 	bzero(mp->b_rptr, len);
5825 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5826 	return (mp);
5827 }
5828 
5829 const char *
5830 dlpi_prim_str(int prim)
5831 {
5832 	switch (prim) {
5833 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5834 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5835 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5836 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5837 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5838 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5839 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5840 	case DL_OK_ACK:		return ("DL_OK_ACK");
5841 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5842 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5843 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5844 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5845 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5846 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5847 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5848 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5849 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5850 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5851 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5852 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5853 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5854 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5855 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5856 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5857 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5858 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5859 	default:		return ("<unknown primitive>");
5860 	}
5861 }
5862 
5863 const char *
5864 dlpi_err_str(int err)
5865 {
5866 	switch (err) {
5867 	case DL_ACCESS:		return ("DL_ACCESS");
5868 	case DL_BADADDR:	return ("DL_BADADDR");
5869 	case DL_BADCORR:	return ("DL_BADCORR");
5870 	case DL_BADDATA:	return ("DL_BADDATA");
5871 	case DL_BADPPA:		return ("DL_BADPPA");
5872 	case DL_BADPRIM:	return ("DL_BADPRIM");
5873 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5874 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5875 	case DL_BADSAP:		return ("DL_BADSAP");
5876 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5877 	case DL_BOUND:		return ("DL_BOUND");
5878 	case DL_INITFAILED:	return ("DL_INITFAILED");
5879 	case DL_NOADDR:		return ("DL_NOADDR");
5880 	case DL_NOTINIT:	return ("DL_NOTINIT");
5881 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5882 	case DL_SYSERR:		return ("DL_SYSERR");
5883 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5884 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5885 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5886 	case DL_TOOMANY:	return ("DL_TOOMANY");
5887 	case DL_NOTENAB:	return ("DL_NOTENAB");
5888 	case DL_BUSY:		return ("DL_BUSY");
5889 	case DL_NOAUTO:		return ("DL_NOAUTO");
5890 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5891 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5892 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5893 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5894 	case DL_PENDING:	return ("DL_PENDING");
5895 	default:		return ("<unknown error>");
5896 	}
5897 }
5898 
5899 /*
5900  * Debug formatting routine.  Returns a character string representation of the
5901  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5902  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5903  *
5904  * Once the ndd table-printing interfaces are removed, this can be changed to
5905  * standard dotted-decimal form.
5906  */
5907 char *
5908 ip_dot_addr(ipaddr_t addr, char *buf)
5909 {
5910 	uint8_t *ap = (uint8_t *)&addr;
5911 
5912 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5913 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
5914 	return (buf);
5915 }
5916 
5917 /*
5918  * Write the given MAC address as a printable string in the usual colon-
5919  * separated format.
5920  */
5921 const char *
5922 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
5923 {
5924 	char *bp;
5925 
5926 	if (alen == 0 || buflen < 4)
5927 		return ("?");
5928 	bp = buf;
5929 	for (;;) {
5930 		/*
5931 		 * If there are more MAC address bytes available, but we won't
5932 		 * have any room to print them, then add "..." to the string
5933 		 * instead.  See below for the 'magic number' explanation.
5934 		 */
5935 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
5936 			(void) strcpy(bp, "...");
5937 			break;
5938 		}
5939 		(void) sprintf(bp, "%02x", *addr++);
5940 		bp += 2;
5941 		if (--alen == 0)
5942 			break;
5943 		*bp++ = ':';
5944 		buflen -= 3;
5945 		/*
5946 		 * At this point, based on the first 'if' statement above,
5947 		 * either alen == 1 and buflen >= 3, or alen > 1 and
5948 		 * buflen >= 4.  The first case leaves room for the final "xx"
5949 		 * number and trailing NUL byte.  The second leaves room for at
5950 		 * least "...".  Thus the apparently 'magic' numbers chosen for
5951 		 * that statement.
5952 		 */
5953 	}
5954 	return (buf);
5955 }
5956 
5957 /*
5958  * Send an ICMP error after patching up the packet appropriately.  Returns
5959  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5960  */
5961 static boolean_t
5962 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5963     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5964 {
5965 	ipha_t *ipha;
5966 	mblk_t *first_mp;
5967 	boolean_t secure;
5968 	unsigned char db_type;
5969 
5970 	first_mp = mp;
5971 	if (mctl_present) {
5972 		mp = mp->b_cont;
5973 		secure = ipsec_in_is_secure(first_mp);
5974 		ASSERT(mp != NULL);
5975 	} else {
5976 		/*
5977 		 * If this is an ICMP error being reported - which goes
5978 		 * up as M_CTLs, we need to convert them to M_DATA till
5979 		 * we finish checking with global policy because
5980 		 * ipsec_check_global_policy() assumes M_DATA as clear
5981 		 * and M_CTL as secure.
5982 		 */
5983 		db_type = DB_TYPE(mp);
5984 		DB_TYPE(mp) = M_DATA;
5985 		secure = B_FALSE;
5986 	}
5987 	/*
5988 	 * We are generating an icmp error for some inbound packet.
5989 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
5990 	 * Before we generate an error, check with global policy
5991 	 * to see whether this is allowed to enter the system. As
5992 	 * there is no "conn", we are checking with global policy.
5993 	 */
5994 	ipha = (ipha_t *)mp->b_rptr;
5995 	if (secure || ipsec_inbound_v4_policy_present) {
5996 		first_mp = ipsec_check_global_policy(first_mp, NULL,
5997 		    ipha, NULL, mctl_present);
5998 		if (first_mp == NULL)
5999 			return (B_FALSE);
6000 	}
6001 
6002 	if (!mctl_present)
6003 		DB_TYPE(mp) = db_type;
6004 
6005 	if (flags & IP_FF_SEND_ICMP) {
6006 		if (flags & IP_FF_HDR_COMPLETE) {
6007 			if (ip_hdr_complete(ipha, zoneid)) {
6008 				freemsg(first_mp);
6009 				return (B_TRUE);
6010 			}
6011 		}
6012 		if (flags & IP_FF_CKSUM) {
6013 			/*
6014 			 * Have to correct checksum since
6015 			 * the packet might have been
6016 			 * fragmented and the reassembly code in ip_rput
6017 			 * does not restore the IP checksum.
6018 			 */
6019 			ipha->ipha_hdr_checksum = 0;
6020 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6021 		}
6022 		switch (icmp_type) {
6023 		case ICMP_DEST_UNREACHABLE:
6024 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid);
6025 			break;
6026 		default:
6027 			freemsg(first_mp);
6028 			break;
6029 		}
6030 	} else {
6031 		freemsg(first_mp);
6032 		return (B_FALSE);
6033 	}
6034 
6035 	return (B_TRUE);
6036 }
6037 
6038 /*
6039  * Used to send an ICMP error message when a packet is received for
6040  * a protocol that is not supported. The mblk passed as argument
6041  * is consumed by this function.
6042  */
6043 void
6044 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
6045 {
6046 	mblk_t *mp;
6047 	ipha_t *ipha;
6048 	ill_t *ill;
6049 	ipsec_in_t *ii;
6050 
6051 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6052 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6053 
6054 	mp = ipsec_mp->b_cont;
6055 	ipsec_mp->b_cont = NULL;
6056 	ipha = (ipha_t *)mp->b_rptr;
6057 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6058 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
6059 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6060 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
6061 		}
6062 	} else {
6063 		/* Get ill from index in ipsec_in_t. */
6064 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6065 		    B_TRUE, NULL, NULL, NULL, NULL);
6066 		if (ill != NULL) {
6067 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6068 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6069 			    0, B_FALSE, zoneid)) {
6070 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
6071 			}
6072 
6073 			ill_refrele(ill);
6074 		} else { /* re-link for the freemsg() below. */
6075 			ipsec_mp->b_cont = mp;
6076 		}
6077 	}
6078 
6079 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6080 	freemsg(ipsec_mp);
6081 }
6082 
6083 /*
6084  * See if the inbound datagram has had IPsec processing applied to it.
6085  */
6086 boolean_t
6087 ipsec_in_is_secure(mblk_t *ipsec_mp)
6088 {
6089 	ipsec_in_t *ii;
6090 
6091 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6092 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6093 
6094 	if (ii->ipsec_in_loopback) {
6095 		return (ii->ipsec_in_secure);
6096 	} else {
6097 		return (ii->ipsec_in_ah_sa != NULL ||
6098 		    ii->ipsec_in_esp_sa != NULL ||
6099 		    ii->ipsec_in_decaps);
6100 	}
6101 }
6102 
6103 /*
6104  * Handle protocols with which IP is less intimate.  There
6105  * can be more than one stream bound to a particular
6106  * protocol.  When this is the case, normally each one gets a copy
6107  * of any incoming packets.
6108  *
6109  * IPSEC NOTE :
6110  *
6111  * Don't allow a secure packet going up a non-secure connection.
6112  * We don't allow this because
6113  *
6114  * 1) Reply might go out in clear which will be dropped at
6115  *    the sending side.
6116  * 2) If the reply goes out in clear it will give the
6117  *    adversary enough information for getting the key in
6118  *    most of the cases.
6119  *
6120  * Moreover getting a secure packet when we expect clear
6121  * implies that SA's were added without checking for
6122  * policy on both ends. This should not happen once ISAKMP
6123  * is used to negotiate SAs as SAs will be added only after
6124  * verifying the policy.
6125  *
6126  * NOTE : If the packet was tunneled and not multicast we only send
6127  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6128  * back to delivering packets to AF_INET6 raw sockets.
6129  *
6130  * IPQoS Notes:
6131  * Once we have determined the client, invoke IPPF processing.
6132  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6133  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6134  * ip_policy will be false.
6135  *
6136  * Zones notes:
6137  * Currently only applications in the global zone can create raw sockets for
6138  * protocols other than ICMP. So unlike the broadcast / multicast case of
6139  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6140  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6141  */
6142 static void
6143 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6144     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6145     zoneid_t zoneid)
6146 {
6147 	queue_t	*rq;
6148 	mblk_t	*mp1, *first_mp1;
6149 	uint_t	protocol = ipha->ipha_protocol;
6150 	ipaddr_t dst;
6151 	boolean_t one_only;
6152 	mblk_t *first_mp = mp;
6153 	boolean_t secure;
6154 	uint32_t ill_index;
6155 	conn_t	*connp, *first_connp, *next_connp;
6156 	connf_t	*connfp;
6157 	boolean_t shared_addr;
6158 
6159 	if (mctl_present) {
6160 		mp = first_mp->b_cont;
6161 		secure = ipsec_in_is_secure(first_mp);
6162 		ASSERT(mp != NULL);
6163 	} else {
6164 		secure = B_FALSE;
6165 	}
6166 	dst = ipha->ipha_dst;
6167 	/*
6168 	 * If the packet was tunneled and not multicast we only send to it
6169 	 * the first match.
6170 	 */
6171 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6172 	    !CLASSD(dst));
6173 
6174 	shared_addr = (zoneid == ALL_ZONES);
6175 	if (shared_addr) {
6176 		/*
6177 		 * We don't allow multilevel ports for raw IP, so no need to
6178 		 * check for that here.
6179 		 */
6180 		zoneid = tsol_packet_to_zoneid(mp);
6181 	}
6182 
6183 	connfp = &ipcl_proto_fanout[protocol];
6184 	mutex_enter(&connfp->connf_lock);
6185 	connp = connfp->connf_head;
6186 	for (connp = connfp->connf_head; connp != NULL;
6187 		connp = connp->conn_next) {
6188 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6189 		    zoneid) &&
6190 		    (!is_system_labeled() ||
6191 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6192 		    connp)))
6193 			break;
6194 	}
6195 
6196 	if (connp == NULL || connp->conn_upq == NULL) {
6197 		/*
6198 		 * No one bound to these addresses.  Is
6199 		 * there a client that wants all
6200 		 * unclaimed datagrams?
6201 		 */
6202 		mutex_exit(&connfp->connf_lock);
6203 		/*
6204 		 * Check for IPPROTO_ENCAP...
6205 		 */
6206 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6207 			/*
6208 			 * XXX If an IPsec mblk is here on a multicast
6209 			 * tunnel (using ip_mroute stuff), what should
6210 			 * I do?
6211 			 *
6212 			 * For now, just free the IPsec mblk before
6213 			 * passing it up to the multicast routing
6214 			 * stuff.
6215 			 *
6216 			 * BTW,  If I match a configured IP-in-IP
6217 			 * tunnel, ip_mroute_decap will never be
6218 			 * called.
6219 			 */
6220 			if (mp != first_mp)
6221 				freeb(first_mp);
6222 			ip_mroute_decap(q, mp);
6223 		} else {
6224 			/*
6225 			 * Otherwise send an ICMP protocol unreachable.
6226 			 */
6227 			if (ip_fanout_send_icmp(q, first_mp, flags,
6228 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6229 			    mctl_present, zoneid)) {
6230 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
6231 			}
6232 		}
6233 		return;
6234 	}
6235 	CONN_INC_REF(connp);
6236 	first_connp = connp;
6237 
6238 	/*
6239 	 * Only send message to one tunnel driver by immediately
6240 	 * terminating the loop.
6241 	 */
6242 	connp = one_only ? NULL : connp->conn_next;
6243 
6244 	for (;;) {
6245 		while (connp != NULL) {
6246 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6247 			    flags, zoneid) &&
6248 			    (!is_system_labeled() ||
6249 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6250 			    shared_addr, connp)))
6251 				break;
6252 			connp = connp->conn_next;
6253 		}
6254 
6255 		/*
6256 		 * Copy the packet.
6257 		 */
6258 		if (connp == NULL || connp->conn_upq == NULL ||
6259 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6260 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6261 			/*
6262 			 * No more interested clients or memory
6263 			 * allocation failed
6264 			 */
6265 			connp = first_connp;
6266 			break;
6267 		}
6268 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6269 		CONN_INC_REF(connp);
6270 		mutex_exit(&connfp->connf_lock);
6271 		rq = connp->conn_rq;
6272 		if (!canputnext(rq)) {
6273 			if (flags & IP_FF_RAWIP) {
6274 				BUMP_MIB(&ip_mib, rawipInOverflows);
6275 			} else {
6276 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6277 			}
6278 
6279 			freemsg(first_mp1);
6280 		} else {
6281 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6282 				first_mp1 = ipsec_check_inbound_policy
6283 				    (first_mp1, connp, ipha, NULL,
6284 				    mctl_present);
6285 			}
6286 			if (first_mp1 != NULL) {
6287 				/*
6288 				 * ip_fanout_proto also gets called from
6289 				 * icmp_inbound_error_fanout, in which case
6290 				 * the msg type is M_CTL.  Don't add info
6291 				 * in this case for the time being. In future
6292 				 * when there is a need for knowing the
6293 				 * inbound iface index for ICMP error msgs,
6294 				 * then this can be changed.
6295 				 */
6296 				if ((connp->conn_recvif != 0) &&
6297 				    (mp->b_datap->db_type != M_CTL)) {
6298 					/*
6299 					 * the actual data will be
6300 					 * contained in b_cont upon
6301 					 * successful return of the
6302 					 * following call else
6303 					 * original mblk is returned
6304 					 */
6305 					ASSERT(recv_ill != NULL);
6306 					mp1 = ip_add_info(mp1, recv_ill,
6307 						IPF_RECVIF);
6308 				}
6309 				BUMP_MIB(&ip_mib, ipInDelivers);
6310 				if (mctl_present)
6311 					freeb(first_mp1);
6312 				putnext(rq, mp1);
6313 			}
6314 		}
6315 		mutex_enter(&connfp->connf_lock);
6316 		/* Follow the next pointer before releasing the conn. */
6317 		next_connp = connp->conn_next;
6318 		CONN_DEC_REF(connp);
6319 		connp = next_connp;
6320 	}
6321 
6322 	/* Last one.  Send it upstream. */
6323 	mutex_exit(&connfp->connf_lock);
6324 
6325 	/*
6326 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6327 	 * will be set to false.
6328 	 */
6329 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6330 		ill_index = ill->ill_phyint->phyint_ifindex;
6331 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6332 		if (mp == NULL) {
6333 			CONN_DEC_REF(connp);
6334 			if (mctl_present) {
6335 				freeb(first_mp);
6336 			}
6337 			return;
6338 		}
6339 	}
6340 
6341 	rq = connp->conn_rq;
6342 	if (!canputnext(rq)) {
6343 		if (flags & IP_FF_RAWIP) {
6344 			BUMP_MIB(&ip_mib, rawipInOverflows);
6345 		} else {
6346 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6347 		}
6348 
6349 		freemsg(first_mp);
6350 	} else {
6351 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6352 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6353 			    ipha, NULL, mctl_present);
6354 		}
6355 		if (first_mp != NULL) {
6356 			/*
6357 			 * ip_fanout_proto also gets called
6358 			 * from icmp_inbound_error_fanout, in
6359 			 * which case the msg type is M_CTL.
6360 			 * Don't add info in this case for time
6361 			 * being. In future when there is a
6362 			 * need for knowing the inbound iface
6363 			 * index for ICMP error msgs, then this
6364 			 * can be changed
6365 			 */
6366 			if ((connp->conn_recvif != 0) &&
6367 			    (mp->b_datap->db_type != M_CTL)) {
6368 				/*
6369 				 * the actual data will be contained in
6370 				 * b_cont upon successful return
6371 				 * of the following call else original
6372 				 * mblk is returned
6373 				 */
6374 				ASSERT(recv_ill != NULL);
6375 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6376 			}
6377 			BUMP_MIB(&ip_mib, ipInDelivers);
6378 			putnext(rq, mp);
6379 			if (mctl_present)
6380 				freeb(first_mp);
6381 		}
6382 	}
6383 	CONN_DEC_REF(connp);
6384 }
6385 
6386 /*
6387  * Fanout for TCP packets
6388  * The caller puts <fport, lport> in the ports parameter.
6389  *
6390  * IPQoS Notes
6391  * Before sending it to the client, invoke IPPF processing.
6392  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6393  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6394  * ip_policy is false.
6395  */
6396 static void
6397 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6398     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6399 {
6400 	mblk_t  *first_mp;
6401 	boolean_t secure;
6402 	uint32_t ill_index;
6403 	int	ip_hdr_len;
6404 	tcph_t	*tcph;
6405 	boolean_t syn_present = B_FALSE;
6406 	conn_t	*connp;
6407 
6408 	first_mp = mp;
6409 	if (mctl_present) {
6410 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6411 		mp = first_mp->b_cont;
6412 		secure = ipsec_in_is_secure(first_mp);
6413 		ASSERT(mp != NULL);
6414 	} else {
6415 		secure = B_FALSE;
6416 	}
6417 
6418 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6419 
6420 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6421 	    NULL) {
6422 		/*
6423 		 * No connected connection or listener. Send a
6424 		 * TH_RST via tcp_xmit_listeners_reset.
6425 		 */
6426 
6427 		/* Initiate IPPf processing, if needed. */
6428 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6429 			uint32_t ill_index;
6430 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6431 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6432 			if (first_mp == NULL)
6433 				return;
6434 		}
6435 		BUMP_MIB(&ip_mib, ipInDelivers);
6436 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6437 		    zoneid));
6438 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6439 		return;
6440 	}
6441 
6442 	/*
6443 	 * Allocate the SYN for the TCP connection here itself
6444 	 */
6445 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6446 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6447 		if (IPCL_IS_TCP(connp)) {
6448 			squeue_t *sqp;
6449 
6450 			/*
6451 			 * For fused tcp loopback, assign the eager's
6452 			 * squeue to be that of the active connect's.
6453 			 * Note that we don't check for IP_FF_LOOPBACK
6454 			 * here since this routine gets called only
6455 			 * for loopback (unlike the IPv6 counterpart).
6456 			 */
6457 			ASSERT(Q_TO_CONN(q) != NULL);
6458 			if (do_tcp_fusion &&
6459 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6460 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6461 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6462 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6463 				sqp = Q_TO_CONN(q)->conn_sqp;
6464 			} else {
6465 				sqp = IP_SQUEUE_GET(lbolt);
6466 			}
6467 
6468 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6469 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6470 			syn_present = B_TRUE;
6471 		}
6472 	}
6473 
6474 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6475 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6476 		if ((flags & TH_RST) || (flags & TH_URG)) {
6477 			CONN_DEC_REF(connp);
6478 			freemsg(first_mp);
6479 			return;
6480 		}
6481 		if (flags & TH_ACK) {
6482 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6483 			CONN_DEC_REF(connp);
6484 			return;
6485 		}
6486 
6487 		CONN_DEC_REF(connp);
6488 		freemsg(first_mp);
6489 		return;
6490 	}
6491 
6492 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6493 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6494 		    NULL, mctl_present);
6495 		if (first_mp == NULL) {
6496 			CONN_DEC_REF(connp);
6497 			return;
6498 		}
6499 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6500 			ASSERT(syn_present);
6501 			if (mctl_present) {
6502 				ASSERT(first_mp != mp);
6503 				first_mp->b_datap->db_struioflag |=
6504 				    STRUIO_POLICY;
6505 			} else {
6506 				ASSERT(first_mp == mp);
6507 				mp->b_datap->db_struioflag &=
6508 				    ~STRUIO_EAGER;
6509 				mp->b_datap->db_struioflag |=
6510 				    STRUIO_POLICY;
6511 			}
6512 		} else {
6513 			/*
6514 			 * Discard first_mp early since we're dealing with a
6515 			 * fully-connected conn_t and tcp doesn't do policy in
6516 			 * this case.
6517 			 */
6518 			if (mctl_present) {
6519 				freeb(first_mp);
6520 				mctl_present = B_FALSE;
6521 			}
6522 			first_mp = mp;
6523 		}
6524 	}
6525 
6526 	/*
6527 	 * Initiate policy processing here if needed. If we get here from
6528 	 * icmp_inbound_error_fanout, ip_policy is false.
6529 	 */
6530 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6531 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6532 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6533 		if (mp == NULL) {
6534 			CONN_DEC_REF(connp);
6535 			if (mctl_present)
6536 				freeb(first_mp);
6537 			return;
6538 		} else if (mctl_present) {
6539 			ASSERT(first_mp != mp);
6540 			first_mp->b_cont = mp;
6541 		} else {
6542 			first_mp = mp;
6543 		}
6544 	}
6545 
6546 
6547 
6548 	/* Handle IPv6 socket options. */
6549 	if (!syn_present &&
6550 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6551 		/* Add header */
6552 		ASSERT(recv_ill != NULL);
6553 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6554 		if (mp == NULL) {
6555 			CONN_DEC_REF(connp);
6556 			if (mctl_present)
6557 				freeb(first_mp);
6558 			return;
6559 		} else if (mctl_present) {
6560 			/*
6561 			 * ip_add_info might return a new mp.
6562 			 */
6563 			ASSERT(first_mp != mp);
6564 			first_mp->b_cont = mp;
6565 		} else {
6566 			first_mp = mp;
6567 		}
6568 	}
6569 
6570 	BUMP_MIB(&ip_mib, ipInDelivers);
6571 	if (IPCL_IS_TCP(connp)) {
6572 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6573 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6574 	} else {
6575 		putnext(connp->conn_rq, first_mp);
6576 		CONN_DEC_REF(connp);
6577 	}
6578 }
6579 
6580 /*
6581  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6582  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6583  * Caller is responsible for dropping references to the conn, and freeing
6584  * first_mp.
6585  *
6586  * IPQoS Notes
6587  * Before sending it to the client, invoke IPPF processing. Policy processing
6588  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6589  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6590  * ip_wput_local, ip_policy is false.
6591  */
6592 static void
6593 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6594     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6595     boolean_t ip_policy)
6596 {
6597 	boolean_t	mctl_present = (first_mp != NULL);
6598 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6599 	uint32_t	ill_index;
6600 
6601 	if (mctl_present)
6602 		first_mp->b_cont = mp;
6603 	else
6604 		first_mp = mp;
6605 
6606 	if (CONN_UDP_FLOWCTLD(connp)) {
6607 		BUMP_MIB(&ip_mib, udpInOverflows);
6608 		freemsg(first_mp);
6609 		return;
6610 	}
6611 
6612 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6613 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6614 		    NULL, mctl_present);
6615 		if (first_mp == NULL)
6616 			return;	/* Freed by ipsec_check_inbound_policy(). */
6617 	}
6618 	if (mctl_present)
6619 		freeb(first_mp);
6620 
6621 	if (connp->conn_recvif)
6622 		in_flags = IPF_RECVIF;
6623 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6624 		in_flags |= IPF_RECVSLLA;
6625 
6626 	/* Handle IPv6 options. */
6627 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6628 		in_flags |= IPF_RECVIF;
6629 
6630 	/*
6631 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6632 	 * freed if the packet is dropped. The caller will do so.
6633 	 */
6634 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6635 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6636 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6637 		if (mp == NULL) {
6638 			return;
6639 		}
6640 	}
6641 	if ((in_flags != 0) &&
6642 	    (mp->b_datap->db_type != M_CTL)) {
6643 		/*
6644 		 * The actual data will be contained in b_cont
6645 		 * upon successful return of the following call
6646 		 * else original mblk is returned
6647 		 */
6648 		ASSERT(recv_ill != NULL);
6649 		mp = ip_add_info(mp, recv_ill, in_flags);
6650 	}
6651 	BUMP_MIB(&ip_mib, ipInDelivers);
6652 
6653 	/* Send it upstream */
6654 	CONN_UDP_RECV(connp, mp);
6655 }
6656 
6657 /*
6658  * Fanout for UDP packets.
6659  * The caller puts <fport, lport> in the ports parameter.
6660  *
6661  * If SO_REUSEADDR is set all multicast and broadcast packets
6662  * will be delivered to all streams bound to the same port.
6663  *
6664  * Zones notes:
6665  * Multicast and broadcast packets will be distributed to streams in all zones.
6666  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6667  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6668  * packets. To maintain this behavior with multiple zones, the conns are grouped
6669  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6670  * each zone. If unset, all the following conns in the same zone are skipped.
6671  */
6672 static void
6673 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6674     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6675     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6676 {
6677 	uint32_t	dstport, srcport;
6678 	ipaddr_t	dst;
6679 	mblk_t		*first_mp;
6680 	boolean_t	secure;
6681 	in6_addr_t	v6src;
6682 	conn_t		*connp;
6683 	connf_t		*connfp;
6684 	conn_t		*first_connp;
6685 	conn_t		*next_connp;
6686 	mblk_t		*mp1, *first_mp1;
6687 	ipaddr_t	src;
6688 	zoneid_t	last_zoneid;
6689 	boolean_t	reuseaddr;
6690 	boolean_t	shared_addr;
6691 
6692 	first_mp = mp;
6693 	if (mctl_present) {
6694 		mp = first_mp->b_cont;
6695 		first_mp->b_cont = NULL;
6696 		secure = ipsec_in_is_secure(first_mp);
6697 		ASSERT(mp != NULL);
6698 	} else {
6699 		first_mp = NULL;
6700 		secure = B_FALSE;
6701 	}
6702 
6703 	/* Extract ports in net byte order */
6704 	dstport = htons(ntohl(ports) & 0xFFFF);
6705 	srcport = htons(ntohl(ports) >> 16);
6706 	dst = ipha->ipha_dst;
6707 	src = ipha->ipha_src;
6708 
6709 	shared_addr = (zoneid == ALL_ZONES);
6710 	if (shared_addr) {
6711 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6712 		if (zoneid == ALL_ZONES)
6713 			zoneid = tsol_packet_to_zoneid(mp);
6714 	}
6715 
6716 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6717 	mutex_enter(&connfp->connf_lock);
6718 	connp = connfp->connf_head;
6719 	if (!broadcast && !CLASSD(dst)) {
6720 		/*
6721 		 * Not broadcast or multicast. Send to the one (first)
6722 		 * client we find. No need to check conn_wantpacket()
6723 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6724 		 * IPv4 unicast packets.
6725 		 */
6726 		while ((connp != NULL) &&
6727 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
6728 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
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 			if (mp == NULL) {
8540 				/* Prepare for cleanup */
8541 				mp = saved_mp; /* pkt */
8542 				ire_delete(ire); /* ire_mp */
8543 				ire = NULL;
8544 				ire_refrele(save_ire);
8545 				if (copy_mp != NULL) {
8546 					MULTIRT_DEBUG_UNTAG(copy_mp);
8547 					freemsg(copy_mp);
8548 					copy_mp = NULL;
8549 				}
8550 				break;
8551 			}
8552 			linkb(mp, ire->ire_mp);
8553 
8554 			/*
8555 			 * Fill in the source and dest addrs for the resolver.
8556 			 * NOTE: this depends on memory layouts imposed by
8557 			 * ill_init().
8558 			 */
8559 			areq = (areq_t *)mp->b_rptr;
8560 			addrp = (ipaddr_t *)((char *)areq +
8561 			    areq->areq_sender_addr_offset);
8562 			if (do_attach_ill) {
8563 				/*
8564 				 * This is bind to no failover case.
8565 				 * arp packet also must go out on attach_ill.
8566 				 */
8567 				ASSERT(ipha->ipha_src != NULL);
8568 				*addrp = ipha->ipha_src;
8569 			} else {
8570 				*addrp = save_ire->ire_src_addr;
8571 			}
8572 
8573 			ire_refrele(save_ire);
8574 			addrp = (ipaddr_t *)((char *)areq +
8575 			    areq->areq_target_addr_offset);
8576 			*addrp = dst;
8577 			/* Up to the resolver. */
8578 			if (canputnext(dst_ill->ill_rq) &&
8579 			    !(dst_ill->ill_arp_closing)) {
8580 				putnext(dst_ill->ill_rq, mp);
8581 				ire = NULL;
8582 				if (copy_mp != NULL) {
8583 					/*
8584 					 * If we found a resolver, we ignore
8585 					 * any trailing top priority IRE_CACHE
8586 					 * in the further loops. This ensures
8587 					 * that we do not omit any resolver.
8588 					 * IRE_CACHE entries, if any, will be
8589 					 * processed next time we enter
8590 					 * ip_newroute().
8591 					 */
8592 					multirt_flags &= ~MULTIRT_CACHEGW;
8593 					/*
8594 					 * Search for the next unresolved
8595 					 * multirt route.
8596 					 */
8597 					first_mp = copy_mp;
8598 					copy_mp = NULL;
8599 					/* Prepare the next resolution loop. */
8600 					mp = first_mp;
8601 					EXTRACT_PKT_MP(mp, first_mp,
8602 					    mctl_present);
8603 					if (mctl_present)
8604 						io = (ipsec_out_t *)
8605 						    first_mp->b_rptr;
8606 					ipha = (ipha_t *)mp->b_rptr;
8607 
8608 					ASSERT(sire != NULL);
8609 
8610 					dst = save_dst;
8611 					multirt_resolve_next = B_TRUE;
8612 					continue;
8613 				}
8614 
8615 				if (sire != NULL)
8616 					ire_refrele(sire);
8617 
8618 				/*
8619 				 * The response will come back in ip_wput
8620 				 * with db_type IRE_DB_TYPE.
8621 				 */
8622 				ipif_refrele(src_ipif);
8623 				ill_refrele(dst_ill);
8624 				return;
8625 			} else {
8626 				/* Prepare for cleanup */
8627 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8628 				    mp);
8629 				mp->b_cont = NULL;
8630 				freeb(mp); /* areq */
8631 				/*
8632 				 * this is an ire that is not added to the
8633 				 * cache. ire_freemblk will handle the release
8634 				 * of any resources associated with the ire.
8635 				 */
8636 				ire_delete(ire); /* ire_mp */
8637 				mp = saved_mp; /* pkt */
8638 				ire = NULL;
8639 				if (copy_mp != NULL) {
8640 					MULTIRT_DEBUG_UNTAG(copy_mp);
8641 					freemsg(copy_mp);
8642 					copy_mp = NULL;
8643 				}
8644 				break;
8645 			}
8646 		default:
8647 			break;
8648 		}
8649 	} while (multirt_resolve_next);
8650 
8651 	ip1dbg(("ip_newroute: dropped\n"));
8652 	/* Did this packet originate externally? */
8653 	if (mp->b_prev) {
8654 		mp->b_next = NULL;
8655 		mp->b_prev = NULL;
8656 		BUMP_MIB(&ip_mib, ipInDiscards);
8657 	} else {
8658 		BUMP_MIB(&ip_mib, ipOutDiscards);
8659 	}
8660 	ASSERT(copy_mp == NULL);
8661 	MULTIRT_DEBUG_UNTAG(first_mp);
8662 	freemsg(first_mp);
8663 	if (ire != NULL)
8664 		ire_refrele(ire);
8665 	if (sire != NULL)
8666 		ire_refrele(sire);
8667 	if (src_ipif != NULL)
8668 		ipif_refrele(src_ipif);
8669 	if (dst_ill != NULL)
8670 		ill_refrele(dst_ill);
8671 	return;
8672 
8673 icmp_err_ret:
8674 	ip1dbg(("ip_newroute: no route\n"));
8675 	if (src_ipif != NULL)
8676 		ipif_refrele(src_ipif);
8677 	if (dst_ill != NULL)
8678 		ill_refrele(dst_ill);
8679 	if (sire != NULL)
8680 		ire_refrele(sire);
8681 	/* Did this packet originate externally? */
8682 	if (mp->b_prev) {
8683 		mp->b_next = NULL;
8684 		mp->b_prev = NULL;
8685 		/* XXX ipInNoRoutes */
8686 		q = WR(q);
8687 	} else {
8688 		/*
8689 		 * Since ip_wput() isn't close to finished, we fill
8690 		 * in enough of the header for credible error reporting.
8691 		 */
8692 		if (ip_hdr_complete(ipha, zoneid)) {
8693 			/* Failed */
8694 			MULTIRT_DEBUG_UNTAG(first_mp);
8695 			freemsg(first_mp);
8696 			if (ire != NULL)
8697 				ire_refrele(ire);
8698 			return;
8699 		}
8700 	}
8701 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8702 
8703 	/*
8704 	 * At this point we will have ire only if RTF_BLACKHOLE
8705 	 * or RTF_REJECT flags are set on the IRE. It will not
8706 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8707 	 */
8708 	if (ire != NULL) {
8709 		if (ire->ire_flags & RTF_BLACKHOLE) {
8710 			ire_refrele(ire);
8711 			MULTIRT_DEBUG_UNTAG(first_mp);
8712 			freemsg(first_mp);
8713 			return;
8714 		}
8715 		ire_refrele(ire);
8716 	}
8717 	if (ip_source_routed(ipha)) {
8718 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8719 		    zoneid);
8720 		return;
8721 	}
8722 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
8723 }
8724 
8725 /*
8726  * IPv4 -
8727  * ip_newroute_ipif is called by ip_wput_multicast and
8728  * ip_rput_forward_multicast whenever we need to send
8729  * out a packet to a destination address for which we do not have specific
8730  * routing information. It is used when the packet will be sent out
8731  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8732  * socket option is set or icmp error message wants to go out on a particular
8733  * interface for a unicast packet.
8734  *
8735  * In most cases, the destination address is resolved thanks to the ipif
8736  * intrinsic resolver. However, there are some cases where the call to
8737  * ip_newroute_ipif must take into account the potential presence of
8738  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8739  * that uses the interface. This is specified through flags,
8740  * which can be a combination of:
8741  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8742  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8743  *   and flags. Additionally, the packet source address has to be set to
8744  *   the specified address. The caller is thus expected to set this flag
8745  *   if the packet has no specific source address yet.
8746  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8747  *   flag, the resulting ire will inherit the flag. All unresolved routes
8748  *   to the destination must be explored in the same call to
8749  *   ip_newroute_ipif().
8750  */
8751 static void
8752 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8753     conn_t *connp, uint32_t flags, zoneid_t zoneid)
8754 {
8755 	areq_t	*areq;
8756 	ire_t	*ire = NULL;
8757 	mblk_t	*res_mp;
8758 	ipaddr_t *addrp;
8759 	mblk_t *first_mp;
8760 	ire_t	*save_ire = NULL;
8761 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8762 	ipif_t	*src_ipif = NULL;
8763 	ushort_t ire_marks = 0;
8764 	ill_t	*dst_ill = NULL;
8765 	boolean_t mctl_present;
8766 	ipsec_out_t *io;
8767 	ipha_t *ipha;
8768 	int	ihandle = 0;
8769 	mblk_t	*saved_mp;
8770 	ire_t   *fire = NULL;
8771 	mblk_t  *copy_mp = NULL;
8772 	boolean_t multirt_resolve_next;
8773 	ipaddr_t ipha_dst;
8774 
8775 	/*
8776 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8777 	 * here for uniformity
8778 	 */
8779 	ipif_refhold(ipif);
8780 
8781 	/*
8782 	 * This loop is run only once in most cases.
8783 	 * We loop to resolve further routes only when the destination
8784 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8785 	 */
8786 	do {
8787 		if (dst_ill != NULL) {
8788 			ill_refrele(dst_ill);
8789 			dst_ill = NULL;
8790 		}
8791 		if (src_ipif != NULL) {
8792 			ipif_refrele(src_ipif);
8793 			src_ipif = NULL;
8794 		}
8795 		multirt_resolve_next = B_FALSE;
8796 
8797 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8798 		    ipif->ipif_ill->ill_name));
8799 
8800 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8801 		if (mctl_present)
8802 			io = (ipsec_out_t *)first_mp->b_rptr;
8803 
8804 		ipha = (ipha_t *)mp->b_rptr;
8805 
8806 		/*
8807 		 * Save the packet destination address, we may need it after
8808 		 * the packet has been consumed.
8809 		 */
8810 		ipha_dst = ipha->ipha_dst;
8811 
8812 		/*
8813 		 * If the interface is a pt-pt interface we look for an
8814 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8815 		 * local_address and the pt-pt destination address. Otherwise
8816 		 * we just match the local address.
8817 		 * NOTE: dst could be different than ipha->ipha_dst in case
8818 		 * of sending igmp multicast packets over a point-to-point
8819 		 * connection.
8820 		 * Thus we must be careful enough to check ipha_dst to be a
8821 		 * multicast address, otherwise it will take xmit_if path for
8822 		 * multicast packets resulting into kernel stack overflow by
8823 		 * repeated calls to ip_newroute_ipif from ire_send().
8824 		 */
8825 		if (CLASSD(ipha_dst) &&
8826 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8827 			goto err_ret;
8828 		}
8829 
8830 		/*
8831 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8832 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8833 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8834 		 * propagate its flags to the new ire.
8835 		 */
8836 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8837 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8838 			ip2dbg(("ip_newroute_ipif: "
8839 			    "ipif_lookup_multi_ire("
8840 			    "ipif %p, dst %08x) = fire %p\n",
8841 			    (void *)ipif, ntohl(dst), (void *)fire));
8842 		}
8843 
8844 		if (mctl_present && io->ipsec_out_attach_if) {
8845 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8846 			    io->ipsec_out_ill_index, B_FALSE);
8847 
8848 			/* Failure case frees things for us. */
8849 			if (attach_ill == NULL) {
8850 				ipif_refrele(ipif);
8851 				if (fire != NULL)
8852 					ire_refrele(fire);
8853 				return;
8854 			}
8855 
8856 			/*
8857 			 * Check if we need an ire that will not be
8858 			 * looked up by anybody else i.e. HIDDEN.
8859 			 */
8860 			if (ill_is_probeonly(attach_ill)) {
8861 				ire_marks = IRE_MARK_HIDDEN;
8862 			}
8863 			/*
8864 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8865 			 * case.
8866 			 */
8867 			dst_ill = ipif->ipif_ill;
8868 			/* attach_ill has been refheld by ip_grab_attach_ill */
8869 			ASSERT(dst_ill == attach_ill);
8870 		} else {
8871 			/*
8872 			 * If this is set by IP_XMIT_IF, then make sure that
8873 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8874 			 * specified ill.
8875 			 */
8876 			ASSERT((connp == NULL) ||
8877 			    (connp->conn_xmit_if_ill == NULL) ||
8878 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8879 			/*
8880 			 * If the interface belongs to an interface group,
8881 			 * make sure the next possible interface in the group
8882 			 * is used.  This encourages load spreading among
8883 			 * peers in an interface group.
8884 			 * Note: load spreading is disabled for RTF_MULTIRT
8885 			 * routes.
8886 			 */
8887 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8888 			    (fire->ire_flags & RTF_MULTIRT)) {
8889 				/*
8890 				 * Don't perform outbound load spreading
8891 				 * in the case of an RTF_MULTIRT issued route,
8892 				 * we actually typically want to replicate
8893 				 * outgoing packets through particular
8894 				 * interfaces.
8895 				 */
8896 				dst_ill = ipif->ipif_ill;
8897 				ill_refhold(dst_ill);
8898 			} else {
8899 				dst_ill = ip_newroute_get_dst_ill(
8900 				    ipif->ipif_ill);
8901 			}
8902 			if (dst_ill == NULL) {
8903 				if (ip_debug > 2) {
8904 					pr_addr_dbg("ip_newroute_ipif: "
8905 					    "no dst ill for dst %s\n",
8906 					    AF_INET, &dst);
8907 				}
8908 				goto err_ret;
8909 			}
8910 		}
8911 
8912 		/*
8913 		 * Pick a source address preferring non-deprecated ones.
8914 		 * Unlike ip_newroute, we don't do any source address
8915 		 * selection here since for multicast it really does not help
8916 		 * in inbound load spreading as in the unicast case.
8917 		 */
8918 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8919 		    (fire->ire_flags & RTF_SETSRC)) {
8920 			/*
8921 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8922 			 * on that interface. This ire has RTF_SETSRC flag, so
8923 			 * the source address of the packet must be changed.
8924 			 * Check that the ipif matching the requested source
8925 			 * address still exists.
8926 			 */
8927 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8928 			    zoneid, NULL, NULL, NULL, NULL);
8929 		}
8930 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8931 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
8932 		    ipif->ipif_zoneid != ALL_ZONES)) &&
8933 		    (src_ipif == NULL)) {
8934 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8935 			if (src_ipif == NULL) {
8936 				if (ip_debug > 2) {
8937 					/* ip1dbg */
8938 					pr_addr_dbg("ip_newroute_ipif: "
8939 					    "no src for dst %s",
8940 					    AF_INET, &dst);
8941 				}
8942 				ip1dbg((" through interface %s\n",
8943 				    dst_ill->ill_name));
8944 				goto err_ret;
8945 			}
8946 			ipif_refrele(ipif);
8947 			ipif = src_ipif;
8948 			ipif_refhold(ipif);
8949 		}
8950 		if (src_ipif == NULL) {
8951 			src_ipif = ipif;
8952 			ipif_refhold(src_ipif);
8953 		}
8954 
8955 		/*
8956 		 * Assign a source address while we have the conn.
8957 		 * We can't have ip_wput_ire pick a source address when the
8958 		 * packet returns from arp since conn_unspec_src might be set
8959 		 * and we loose the conn when going through arp.
8960 		 */
8961 		if (ipha->ipha_src == INADDR_ANY &&
8962 		    (connp == NULL || !connp->conn_unspec_src)) {
8963 			ipha->ipha_src = src_ipif->ipif_src_addr;
8964 		}
8965 
8966 		/*
8967 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8968 		 * interface does not have an interface ire.
8969 		 * Example: Thousands of mobileip PPP interfaces to mobile
8970 		 * nodes. We don't want to create interface ires because
8971 		 * packets from other mobile nodes must not take the route
8972 		 * via interface ires to the visiting mobile node without
8973 		 * going through the home agent, in absence of mobileip
8974 		 * route optimization.
8975 		 */
8976 		if (CLASSD(ipha_dst) && (connp == NULL ||
8977 		    connp->conn_xmit_if_ill == NULL)) {
8978 			/* ipif_to_ire returns an held ire */
8979 			ire = ipif_to_ire(ipif);
8980 			if (ire == NULL)
8981 				goto err_ret;
8982 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8983 				goto err_ret;
8984 			/*
8985 			 * ihandle is needed when the ire is added to
8986 			 * cache table.
8987 			 */
8988 			save_ire = ire;
8989 			ihandle = save_ire->ire_ihandle;
8990 
8991 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8992 			    "flags %04x\n",
8993 			    (void *)ire, (void *)ipif, flags));
8994 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8995 			    (fire->ire_flags & RTF_MULTIRT)) {
8996 				/*
8997 				 * As requested by flags, an IRE_OFFSUBNET was
8998 				 * looked up on that interface. This ire has
8999 				 * RTF_MULTIRT flag, so the resolution loop will
9000 				 * be re-entered to resolve additional routes on
9001 				 * other interfaces. For that purpose, a copy of
9002 				 * the packet is performed at this point.
9003 				 */
9004 				fire->ire_last_used_time = lbolt;
9005 				copy_mp = copymsg(first_mp);
9006 				if (copy_mp) {
9007 					MULTIRT_DEBUG_TAG(copy_mp);
9008 				}
9009 			}
9010 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9011 			    (fire->ire_flags & RTF_SETSRC)) {
9012 				/*
9013 				 * As requested by flags, an IRE_OFFSUBET was
9014 				 * looked up on that interface. This ire has
9015 				 * RTF_SETSRC flag, so the source address of the
9016 				 * packet must be changed.
9017 				 */
9018 				ipha->ipha_src = fire->ire_src_addr;
9019 			}
9020 		} else {
9021 			ASSERT((connp == NULL) ||
9022 			    (connp->conn_xmit_if_ill != NULL) ||
9023 			    (connp->conn_dontroute));
9024 			/*
9025 			 * The only ways we can come here are:
9026 			 * 1) IP_XMIT_IF socket option is set
9027 			 * 2) ICMP error message generated from
9028 			 *    ip_mrtun_forward() routine and it needs
9029 			 *    to go through the specified ill.
9030 			 * 3) SO_DONTROUTE socket option is set
9031 			 * In all cases, the new ire will not be added
9032 			 * into cache table.
9033 			 */
9034 			ire_marks |= IRE_MARK_NOADD;
9035 		}
9036 
9037 		switch (ipif->ipif_net_type) {
9038 		case IRE_IF_NORESOLVER: {
9039 			/* We have what we need to build an IRE_CACHE. */
9040 			mblk_t	*res_mp;
9041 
9042 			/*
9043 			 * Create a new res_mp with the
9044 			 * IP gateway address as destination address in the
9045 			 * DLPI hdr if the physical length is exactly 4 bytes.
9046 			 */
9047 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9048 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9049 				    dst_ill->ill_phys_addr_length,
9050 				    dst_ill->ill_sap,
9051 				    dst_ill->ill_sap_length);
9052 			} else {
9053 				/* use the value set in ip_ll_subnet_defaults */
9054 				res_mp = ill_dlur_gen(NULL,
9055 				    dst_ill->ill_phys_addr_length,
9056 				    dst_ill->ill_sap,
9057 				    dst_ill->ill_sap_length);
9058 			}
9059 
9060 			if (res_mp == NULL)
9061 				break;
9062 			/*
9063 			 * The new ire inherits the IRE_OFFSUBNET flags
9064 			 * and source address, if this was requested.
9065 			 */
9066 			ire = ire_create(
9067 			    (uchar_t *)&dst,		/* dest address */
9068 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9069 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9070 			    NULL,			/* gateway address */
9071 			    NULL,
9072 			    &ipif->ipif_mtu,
9073 			    NULL,			/* Fast Path header */
9074 			    dst_ill->ill_rq,		/* recv-from queue */
9075 			    dst_ill->ill_wq,		/* send-to queue */
9076 			    IRE_CACHE,
9077 			    res_mp,
9078 			    src_ipif,
9079 			    NULL,
9080 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9081 			    (fire != NULL) ?		/* Parent handle */
9082 				fire->ire_phandle : 0,
9083 			    ihandle,			/* Interface handle */
9084 			    (fire != NULL) ?
9085 				(fire->ire_flags &
9086 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9087 			    (save_ire == NULL ? &ire_uinfo_null :
9088 				&save_ire->ire_uinfo),
9089 			    NULL,
9090 			    NULL);
9091 
9092 			freeb(res_mp);
9093 
9094 			if (ire == NULL) {
9095 				if (save_ire != NULL)
9096 					ire_refrele(save_ire);
9097 				break;
9098 			}
9099 
9100 			ire->ire_marks |= ire_marks;
9101 
9102 			/*
9103 			 * If IRE_MARK_NOADD is set then we need to convert
9104 			 * the max_fragp to a useable value now. This is
9105 			 * normally done in ire_add_v[46]. We also need to
9106 			 * associate the ire with an nce (normally would be
9107 			 * done in ip_wput_nondata()).
9108 			 *
9109 			 * Note that IRE_MARK_NOADD packets created here
9110 			 * do not have a non-null ire_mp pointer. The null
9111 			 * value of ire_bucket indicates that they were
9112 			 * never added.
9113 			 */
9114 			if (ire->ire_marks & IRE_MARK_NOADD) {
9115 				uint_t  max_frag;
9116 
9117 				max_frag = *ire->ire_max_fragp;
9118 				ire->ire_max_fragp = NULL;
9119 				ire->ire_max_frag = max_frag;
9120 
9121 				if ((ire->ire_nce = ndp_lookup_v4(
9122 				    ire_to_ill(ire),
9123 				    (ire->ire_gateway_addr != INADDR_ANY ?
9124 				    &ire->ire_gateway_addr : &ire->ire_addr),
9125 				    B_FALSE)) == NULL) {
9126 					if (save_ire != NULL)
9127 						ire_refrele(save_ire);
9128 					break;
9129 				}
9130 				ASSERT(ire->ire_nce->nce_state ==
9131 				    ND_REACHABLE);
9132 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9133 			}
9134 
9135 			/* Prevent save_ire from getting deleted */
9136 			if (save_ire != NULL) {
9137 				IRB_REFHOLD(save_ire->ire_bucket);
9138 				/* Has it been removed already ? */
9139 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9140 					IRB_REFRELE(save_ire->ire_bucket);
9141 					ire_refrele(save_ire);
9142 					break;
9143 				}
9144 			}
9145 
9146 			ire_add_then_send(q, ire, first_mp);
9147 
9148 			/* Assert that save_ire is not deleted yet. */
9149 			if (save_ire != NULL) {
9150 				ASSERT(save_ire->ire_ptpn != NULL);
9151 				IRB_REFRELE(save_ire->ire_bucket);
9152 				ire_refrele(save_ire);
9153 				save_ire = NULL;
9154 			}
9155 			if (fire != NULL) {
9156 				ire_refrele(fire);
9157 				fire = NULL;
9158 			}
9159 
9160 			/*
9161 			 * the resolution loop is re-entered if this
9162 			 * was requested through flags and if we
9163 			 * actually are in a multirouting case.
9164 			 */
9165 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9166 				boolean_t need_resolve =
9167 				    ire_multirt_need_resolve(ipha_dst,
9168 					MBLK_GETLABEL(copy_mp));
9169 				if (!need_resolve) {
9170 					MULTIRT_DEBUG_UNTAG(copy_mp);
9171 					freemsg(copy_mp);
9172 					copy_mp = NULL;
9173 				} else {
9174 					/*
9175 					 * ipif_lookup_group() calls
9176 					 * ire_lookup_multi() that uses
9177 					 * ire_ftable_lookup() to find
9178 					 * an IRE_INTERFACE for the group.
9179 					 * In the multirt case,
9180 					 * ire_lookup_multi() then invokes
9181 					 * ire_multirt_lookup() to find
9182 					 * the next resolvable ire.
9183 					 * As a result, we obtain an new
9184 					 * interface, derived from the
9185 					 * next ire.
9186 					 */
9187 					ipif_refrele(ipif);
9188 					ipif = ipif_lookup_group(ipha_dst,
9189 					    zoneid);
9190 					ip2dbg(("ip_newroute_ipif: "
9191 					    "multirt dst %08x, ipif %p\n",
9192 					    htonl(dst), (void *)ipif));
9193 					if (ipif != NULL) {
9194 						mp = copy_mp;
9195 						copy_mp = NULL;
9196 						multirt_resolve_next = B_TRUE;
9197 						continue;
9198 					} else {
9199 						freemsg(copy_mp);
9200 					}
9201 				}
9202 			}
9203 			if (ipif != NULL)
9204 				ipif_refrele(ipif);
9205 			ill_refrele(dst_ill);
9206 			ipif_refrele(src_ipif);
9207 			return;
9208 		}
9209 		case IRE_IF_RESOLVER:
9210 			/*
9211 			 * We can't build an IRE_CACHE yet, but at least
9212 			 * we found a resolver that can help.
9213 			 */
9214 			res_mp = dst_ill->ill_resolver_mp;
9215 			if (!OK_RESOLVER_MP(res_mp))
9216 				break;
9217 
9218 			/*
9219 			 * We obtain a partial IRE_CACHE which we will pass
9220 			 * along with the resolver query.  When the response
9221 			 * comes back it will be there ready for us to add.
9222 			 * The new ire inherits the IRE_OFFSUBNET flags
9223 			 * and source address, if this was requested.
9224 			 * The ire_max_frag is atomically set under the
9225 			 * irebucket lock in ire_add_v[46]. Only in the
9226 			 * case of IRE_MARK_NOADD, we set it here itself.
9227 			 */
9228 			ire = ire_create_mp(
9229 			    (uchar_t *)&dst,		/* dest address */
9230 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9231 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9232 			    NULL,			/* gateway address */
9233 			    NULL,			/* no in_src_addr */
9234 			    (ire_marks & IRE_MARK_NOADD) ?
9235 				ipif->ipif_mtu : 0,	/* max_frag */
9236 			    NULL,			/* Fast path header */
9237 			    dst_ill->ill_rq,		/* recv-from queue */
9238 			    dst_ill->ill_wq,		/* send-to queue */
9239 			    IRE_CACHE,
9240 			    NULL,	/* let ire_nce_init figure res_mp out */
9241 			    src_ipif,
9242 			    NULL,
9243 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9244 			    (fire != NULL) ?		/* Parent handle */
9245 				fire->ire_phandle : 0,
9246 			    ihandle,			/* Interface handle */
9247 			    (fire != NULL) ?		/* flags if any */
9248 				(fire->ire_flags &
9249 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9250 			    (save_ire == NULL ? &ire_uinfo_null :
9251 				&save_ire->ire_uinfo),
9252 			    NULL,
9253 			    NULL);
9254 
9255 			if (save_ire != NULL) {
9256 				ire_refrele(save_ire);
9257 				save_ire = NULL;
9258 			}
9259 			if (ire == NULL)
9260 				break;
9261 
9262 			ire->ire_marks |= ire_marks;
9263 			/*
9264 			 * Construct message chain for the resolver of the
9265 			 * form:
9266 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9267 			 *
9268 			 * NOTE : ire will be added later when the response
9269 			 * comes back from ARP. If the response does not
9270 			 * come back, ARP frees the packet. For this reason,
9271 			 * we can't REFHOLD the bucket of save_ire to prevent
9272 			 * deletions. We may not be able to REFRELE the
9273 			 * bucket if the response never comes back.
9274 			 * Thus, before adding the ire, ire_add_v4 will make
9275 			 * sure that the interface route does not get deleted.
9276 			 * This is the only case unlike ip_newroute_v6,
9277 			 * ip_newroute_ipif_v6 where we can always prevent
9278 			 * deletions because ire_add_then_send is called after
9279 			 * creating the IRE.
9280 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9281 			 * does not add this IRE into the IRE CACHE.
9282 			 */
9283 			ASSERT(ire->ire_mp != NULL);
9284 			ire->ire_mp->b_cont = first_mp;
9285 			/* Have saved_mp handy, for cleanup if canput fails */
9286 			saved_mp = mp;
9287 			mp = copyb(res_mp);
9288 			if (mp == NULL) {
9289 				/* Prepare for cleanup */
9290 				mp = saved_mp; /* pkt */
9291 				ire_delete(ire); /* ire_mp */
9292 				ire = NULL;
9293 				if (copy_mp != NULL) {
9294 					MULTIRT_DEBUG_UNTAG(copy_mp);
9295 					freemsg(copy_mp);
9296 					copy_mp = NULL;
9297 				}
9298 				break;
9299 			}
9300 			linkb(mp, ire->ire_mp);
9301 
9302 			/*
9303 			 * Fill in the source and dest addrs for the resolver.
9304 			 * NOTE: this depends on memory layouts imposed by
9305 			 * ill_init().
9306 			 */
9307 			areq = (areq_t *)mp->b_rptr;
9308 			addrp = (ipaddr_t *)((char *)areq +
9309 			    areq->areq_sender_addr_offset);
9310 			*addrp = ire->ire_src_addr;
9311 			addrp = (ipaddr_t *)((char *)areq +
9312 			    areq->areq_target_addr_offset);
9313 			*addrp = dst;
9314 			/* Up to the resolver. */
9315 			if (canputnext(dst_ill->ill_rq) &&
9316 			    !(dst_ill->ill_arp_closing)) {
9317 				putnext(dst_ill->ill_rq, mp);
9318 				/*
9319 				 * The response will come back in ip_wput
9320 				 * with db_type IRE_DB_TYPE.
9321 				 */
9322 			} else {
9323 				mp->b_cont = NULL;
9324 				freeb(mp); /* areq */
9325 				ire_delete(ire); /* ire_mp */
9326 				saved_mp->b_next = NULL;
9327 				saved_mp->b_prev = NULL;
9328 				freemsg(first_mp); /* pkt */
9329 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9330 			}
9331 
9332 			if (fire != NULL) {
9333 				ire_refrele(fire);
9334 				fire = NULL;
9335 			}
9336 
9337 
9338 			/*
9339 			 * The resolution loop is re-entered if this was
9340 			 * requested through flags and we actually are
9341 			 * in a multirouting case.
9342 			 */
9343 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9344 				boolean_t need_resolve =
9345 				    ire_multirt_need_resolve(ipha_dst,
9346 					MBLK_GETLABEL(copy_mp));
9347 				if (!need_resolve) {
9348 					MULTIRT_DEBUG_UNTAG(copy_mp);
9349 					freemsg(copy_mp);
9350 					copy_mp = NULL;
9351 				} else {
9352 					/*
9353 					 * ipif_lookup_group() calls
9354 					 * ire_lookup_multi() that uses
9355 					 * ire_ftable_lookup() to find
9356 					 * an IRE_INTERFACE for the group.
9357 					 * In the multirt case,
9358 					 * ire_lookup_multi() then invokes
9359 					 * ire_multirt_lookup() to find
9360 					 * the next resolvable ire.
9361 					 * As a result, we obtain an new
9362 					 * interface, derived from the
9363 					 * next ire.
9364 					 */
9365 					ipif_refrele(ipif);
9366 					ipif = ipif_lookup_group(ipha_dst,
9367 					    zoneid);
9368 					if (ipif != NULL) {
9369 						mp = copy_mp;
9370 						copy_mp = NULL;
9371 						multirt_resolve_next = B_TRUE;
9372 						continue;
9373 					} else {
9374 						freemsg(copy_mp);
9375 					}
9376 				}
9377 			}
9378 			if (ipif != NULL)
9379 				ipif_refrele(ipif);
9380 			ill_refrele(dst_ill);
9381 			ipif_refrele(src_ipif);
9382 			return;
9383 		default:
9384 			break;
9385 		}
9386 	} while (multirt_resolve_next);
9387 
9388 err_ret:
9389 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9390 	if (fire != NULL)
9391 		ire_refrele(fire);
9392 	ipif_refrele(ipif);
9393 	/* Did this packet originate externally? */
9394 	if (dst_ill != NULL)
9395 		ill_refrele(dst_ill);
9396 	if (src_ipif != NULL)
9397 		ipif_refrele(src_ipif);
9398 	if (mp->b_prev || mp->b_next) {
9399 		mp->b_next = NULL;
9400 		mp->b_prev = NULL;
9401 	} else {
9402 		/*
9403 		 * Since ip_wput() isn't close to finished, we fill
9404 		 * in enough of the header for credible error reporting.
9405 		 */
9406 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9407 			/* Failed */
9408 			freemsg(first_mp);
9409 			if (ire != NULL)
9410 				ire_refrele(ire);
9411 			return;
9412 		}
9413 	}
9414 	/*
9415 	 * At this point we will have ire only if RTF_BLACKHOLE
9416 	 * or RTF_REJECT flags are set on the IRE. It will not
9417 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9418 	 */
9419 	if (ire != NULL) {
9420 		if (ire->ire_flags & RTF_BLACKHOLE) {
9421 			ire_refrele(ire);
9422 			freemsg(first_mp);
9423 			return;
9424 		}
9425 		ire_refrele(ire);
9426 	}
9427 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9428 }
9429 
9430 /* Name/Value Table Lookup Routine */
9431 char *
9432 ip_nv_lookup(nv_t *nv, int value)
9433 {
9434 	if (!nv)
9435 		return (NULL);
9436 	for (; nv->nv_name; nv++) {
9437 		if (nv->nv_value == value)
9438 			return (nv->nv_name);
9439 	}
9440 	return ("unknown");
9441 }
9442 
9443 /*
9444  * one day it can be patched to 1 from /etc/system for machines that have few
9445  * fast network interfaces feeding multiple cpus.
9446  */
9447 int ill_stream_putlocks = 0;
9448 
9449 /*
9450  * This is a module open, i.e. this is a control stream for access
9451  * to a DLPI device.  We allocate an ill_t as the instance data in
9452  * this case.
9453  */
9454 int
9455 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9456 {
9457 	uint32_t mem_cnt;
9458 	uint32_t cpu_cnt;
9459 	uint32_t min_cnt;
9460 	pgcnt_t mem_avail;
9461 	ill_t	*ill;
9462 	int	err;
9463 
9464 	/*
9465 	 * Prevent unprivileged processes from pushing IP so that
9466 	 * they can't send raw IP.
9467 	 */
9468 	if (secpolicy_net_rawaccess(credp) != 0)
9469 		return (EPERM);
9470 
9471 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9472 	q->q_ptr = WR(q)->q_ptr = ill;
9473 
9474 	/*
9475 	 * ill_init initializes the ill fields and then sends down
9476 	 * down a DL_INFO_REQ after calling qprocson.
9477 	 */
9478 	err = ill_init(q, ill);
9479 	if (err != 0) {
9480 		mi_free(ill);
9481 		q->q_ptr = NULL;
9482 		WR(q)->q_ptr = NULL;
9483 		return (err);
9484 	}
9485 
9486 	/* ill_init initializes the ipsq marking this thread as writer */
9487 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9488 	/* Wait for the DL_INFO_ACK */
9489 	mutex_enter(&ill->ill_lock);
9490 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9491 		/*
9492 		 * Return value of 0 indicates a pending signal.
9493 		 */
9494 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9495 		if (err == 0) {
9496 			mutex_exit(&ill->ill_lock);
9497 			(void) ip_close(q, 0);
9498 			return (EINTR);
9499 		}
9500 	}
9501 	mutex_exit(&ill->ill_lock);
9502 
9503 	/*
9504 	 * ip_rput_other could have set an error  in ill_error on
9505 	 * receipt of M_ERROR.
9506 	 */
9507 
9508 	err = ill->ill_error;
9509 	if (err != 0) {
9510 		(void) ip_close(q, 0);
9511 		return (err);
9512 	}
9513 
9514 	/*
9515 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9516 	 * size and the cpu speed of the machine. This is upper
9517 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9518 	 * and is lower bounded by the compile time value of
9519 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9520 	 * ip6_ire_max_bucket_cnt.
9521 	 */
9522 	mem_avail = kmem_avail();
9523 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9524 	    ip_cache_table_size / sizeof (ire_t);
9525 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9526 
9527 	min_cnt = MIN(cpu_cnt, mem_cnt);
9528 	if (min_cnt < ip_ire_min_bucket_cnt)
9529 		min_cnt = ip_ire_min_bucket_cnt;
9530 	if (ip_ire_max_bucket_cnt > min_cnt) {
9531 		ip_ire_max_bucket_cnt = min_cnt;
9532 	}
9533 
9534 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9535 	    ip6_cache_table_size / sizeof (ire_t);
9536 	min_cnt = MIN(cpu_cnt, mem_cnt);
9537 	if (min_cnt < ip6_ire_min_bucket_cnt)
9538 		min_cnt = ip6_ire_min_bucket_cnt;
9539 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9540 		ip6_ire_max_bucket_cnt = min_cnt;
9541 	}
9542 
9543 	ill->ill_credp = credp;
9544 	crhold(credp);
9545 
9546 	mutex_enter(&ip_mi_lock);
9547 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9548 	mutex_exit(&ip_mi_lock);
9549 	if (err) {
9550 		(void) ip_close(q, 0);
9551 		return (err);
9552 	}
9553 	return (0);
9554 }
9555 
9556 /* IP open routine. */
9557 int
9558 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9559 {
9560 	conn_t 		*connp;
9561 	major_t		maj;
9562 
9563 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9564 
9565 	/* Allow reopen. */
9566 	if (q->q_ptr != NULL)
9567 		return (0);
9568 
9569 	if (sflag & MODOPEN) {
9570 		/* This is a module open */
9571 		return (ip_modopen(q, devp, flag, sflag, credp));
9572 	}
9573 
9574 	/*
9575 	 * We are opening as a device. This is an IP client stream, and we
9576 	 * allocate an conn_t as the instance data.
9577 	 */
9578 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9579 	connp->conn_upq = q;
9580 	q->q_ptr = WR(q)->q_ptr = connp;
9581 
9582 	if (flag & SO_SOCKSTR)
9583 		connp->conn_flags |= IPCL_SOCKET;
9584 
9585 	/* Minor tells us which /dev entry was opened */
9586 	if (geteminor(*devp) == IPV6_MINOR) {
9587 		connp->conn_flags |= IPCL_ISV6;
9588 		connp->conn_af_isv6 = B_TRUE;
9589 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9590 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9591 	} else {
9592 		connp->conn_af_isv6 = B_FALSE;
9593 		connp->conn_pkt_isv6 = B_FALSE;
9594 	}
9595 
9596 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9597 		q->q_ptr = WR(q)->q_ptr = NULL;
9598 		CONN_DEC_REF(connp);
9599 		return (EBUSY);
9600 	}
9601 
9602 	maj = getemajor(*devp);
9603 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9604 
9605 	/*
9606 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9607 	 */
9608 	connp->conn_cred = credp;
9609 	crhold(connp->conn_cred);
9610 
9611 	/*
9612 	 * If the caller has the process-wide flag set, then default to MAC
9613 	 * exempt mode.  This allows read-down to unlabeled hosts.
9614 	 */
9615 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9616 		connp->conn_mac_exempt = B_TRUE;
9617 
9618 	connp->conn_zoneid = getzoneid();
9619 
9620 	/*
9621 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9622 	 * administrative ops.  In these cases, we just need a normal conn_t
9623 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9624 	 * an error will be returned.
9625 	 */
9626 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9627 		connp->conn_rq = q;
9628 		connp->conn_wq = WR(q);
9629 	} else {
9630 		connp->conn_ulp = IPPROTO_SCTP;
9631 		connp->conn_rq = connp->conn_wq = NULL;
9632 	}
9633 	/* Non-zero default values */
9634 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9635 
9636 	/*
9637 	 * Make the conn globally visible to walkers
9638 	 */
9639 	mutex_enter(&connp->conn_lock);
9640 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9641 	mutex_exit(&connp->conn_lock);
9642 	ASSERT(connp->conn_ref == 1);
9643 
9644 	qprocson(q);
9645 
9646 	return (0);
9647 }
9648 
9649 /*
9650  * Change q_qinfo based on the value of isv6.
9651  * This can not called on an ill queue.
9652  * Note that there is no race since either q_qinfo works for conn queues - it
9653  * is just an optimization to enter the best wput routine directly.
9654  */
9655 void
9656 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9657 {
9658 	ASSERT(q->q_flag & QREADR);
9659 	ASSERT(WR(q)->q_next == NULL);
9660 	ASSERT(q->q_ptr != NULL);
9661 
9662 	if (minor == IPV6_MINOR)  {
9663 		if (bump_mib)
9664 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9665 		q->q_qinfo = &rinit_ipv6;
9666 		WR(q)->q_qinfo = &winit_ipv6;
9667 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9668 	} else {
9669 		if (bump_mib)
9670 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9671 		q->q_qinfo = &iprinit;
9672 		WR(q)->q_qinfo = &ipwinit;
9673 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9674 	}
9675 
9676 }
9677 
9678 /*
9679  * See if IPsec needs loading because of the options in mp.
9680  */
9681 static boolean_t
9682 ipsec_opt_present(mblk_t *mp)
9683 {
9684 	uint8_t *optcp, *next_optcp, *opt_endcp;
9685 	struct opthdr *opt;
9686 	struct T_opthdr *topt;
9687 	int opthdr_len;
9688 	t_uscalar_t optname, optlevel;
9689 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9690 	ipsec_req_t *ipsr;
9691 
9692 	/*
9693 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9694 	 * return TRUE.
9695 	 */
9696 
9697 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9698 	opt_endcp = optcp + tor->OPT_length;
9699 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9700 		opthdr_len = sizeof (struct T_opthdr);
9701 	} else {		/* O_OPTMGMT_REQ */
9702 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9703 		opthdr_len = sizeof (struct opthdr);
9704 	}
9705 	for (; optcp < opt_endcp; optcp = next_optcp) {
9706 		if (optcp + opthdr_len > opt_endcp)
9707 			return (B_FALSE);	/* Not enough option header. */
9708 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9709 			topt = (struct T_opthdr *)optcp;
9710 			optlevel = topt->level;
9711 			optname = topt->name;
9712 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9713 		} else {
9714 			opt = (struct opthdr *)optcp;
9715 			optlevel = opt->level;
9716 			optname = opt->name;
9717 			next_optcp = optcp + opthdr_len +
9718 			    _TPI_ALIGN_OPT(opt->len);
9719 		}
9720 		if ((next_optcp < optcp) || /* wraparound pointer space */
9721 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9722 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9723 			return (B_FALSE); /* bad option buffer */
9724 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9725 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9726 			/*
9727 			 * Check to see if it's an all-bypass or all-zeroes
9728 			 * IPsec request.  Don't bother loading IPsec if
9729 			 * the socket doesn't want to use it.  (A good example
9730 			 * is a bypass request.)
9731 			 *
9732 			 * Basically, if any of the non-NEVER bits are set,
9733 			 * load IPsec.
9734 			 */
9735 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9736 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9737 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9738 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9739 			    != 0)
9740 				return (B_TRUE);
9741 		}
9742 	}
9743 	return (B_FALSE);
9744 }
9745 
9746 /*
9747  * If conn is is waiting for ipsec to finish loading, kick it.
9748  */
9749 /* ARGSUSED */
9750 static void
9751 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9752 {
9753 	t_scalar_t	optreq_prim;
9754 	mblk_t		*mp;
9755 	cred_t		*cr;
9756 	int		err = 0;
9757 
9758 	/*
9759 	 * This function is called, after ipsec loading is complete.
9760 	 * Since IP checks exclusively and atomically (i.e it prevents
9761 	 * ipsec load from completing until ip_optcom_req completes)
9762 	 * whether ipsec load is complete, there cannot be a race with IP
9763 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9764 	 */
9765 	mutex_enter(&connp->conn_lock);
9766 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9767 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9768 		mp = connp->conn_ipsec_opt_mp;
9769 		connp->conn_ipsec_opt_mp = NULL;
9770 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9771 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9772 		mutex_exit(&connp->conn_lock);
9773 
9774 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9775 
9776 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9777 		if (optreq_prim == T_OPTMGMT_REQ) {
9778 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9779 			    &ip_opt_obj);
9780 		} else {
9781 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9782 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9783 			    &ip_opt_obj);
9784 		}
9785 		if (err != EINPROGRESS)
9786 			CONN_OPER_PENDING_DONE(connp);
9787 		return;
9788 	}
9789 	mutex_exit(&connp->conn_lock);
9790 }
9791 
9792 /*
9793  * Called from the ipsec_loader thread, outside any perimeter, to tell
9794  * ip qenable any of the queues waiting for the ipsec loader to
9795  * complete.
9796  *
9797  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9798  * are done with this lock held, so it's guaranteed that none of the
9799  * links will change along the way.
9800  */
9801 void
9802 ip_ipsec_load_complete()
9803 {
9804 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9805 }
9806 
9807 /*
9808  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9809  * determines the grp on which it has to become exclusive, queues the mp
9810  * and sq draining restarts the optmgmt
9811  */
9812 static boolean_t
9813 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9814 {
9815 	conn_t *connp;
9816 
9817 	/*
9818 	 * Take IPsec requests and treat them special.
9819 	 */
9820 	if (ipsec_opt_present(mp)) {
9821 		/* First check if IPsec is loaded. */
9822 		mutex_enter(&ipsec_loader_lock);
9823 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9824 			mutex_exit(&ipsec_loader_lock);
9825 			return (B_FALSE);
9826 		}
9827 		connp = Q_TO_CONN(q);
9828 		mutex_enter(&connp->conn_lock);
9829 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9830 
9831 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9832 		connp->conn_ipsec_opt_mp = mp;
9833 		mutex_exit(&connp->conn_lock);
9834 		mutex_exit(&ipsec_loader_lock);
9835 
9836 		ipsec_loader_loadnow();
9837 		return (B_TRUE);
9838 	}
9839 	return (B_FALSE);
9840 }
9841 
9842 /*
9843  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9844  * all of them are copied to the conn_t. If the req is "zero", the policy is
9845  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9846  * fields.
9847  * We keep only the latest setting of the policy and thus policy setting
9848  * is not incremental/cumulative.
9849  *
9850  * Requests to set policies with multiple alternative actions will
9851  * go through a different API.
9852  */
9853 int
9854 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9855 {
9856 	uint_t ah_req = 0;
9857 	uint_t esp_req = 0;
9858 	uint_t se_req = 0;
9859 	ipsec_selkey_t sel;
9860 	ipsec_act_t *actp = NULL;
9861 	uint_t nact;
9862 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9863 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9864 	ipsec_policy_root_t *pr;
9865 	ipsec_policy_head_t *ph;
9866 	int fam;
9867 	boolean_t is_pol_reset;
9868 	int error = 0;
9869 
9870 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9871 
9872 	/*
9873 	 * The IP_SEC_OPT option does not allow variable length parameters,
9874 	 * hence a request cannot be NULL.
9875 	 */
9876 	if (req == NULL)
9877 		return (EINVAL);
9878 
9879 	ah_req = req->ipsr_ah_req;
9880 	esp_req = req->ipsr_esp_req;
9881 	se_req = req->ipsr_self_encap_req;
9882 
9883 	/*
9884 	 * Are we dealing with a request to reset the policy (i.e.
9885 	 * zero requests).
9886 	 */
9887 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9888 	    (esp_req & REQ_MASK) == 0 &&
9889 	    (se_req & REQ_MASK) == 0);
9890 
9891 	if (!is_pol_reset) {
9892 		/*
9893 		 * If we couldn't load IPsec, fail with "protocol
9894 		 * not supported".
9895 		 * IPsec may not have been loaded for a request with zero
9896 		 * policies, so we don't fail in this case.
9897 		 */
9898 		mutex_enter(&ipsec_loader_lock);
9899 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9900 			mutex_exit(&ipsec_loader_lock);
9901 			return (EPROTONOSUPPORT);
9902 		}
9903 		mutex_exit(&ipsec_loader_lock);
9904 
9905 		/*
9906 		 * Test for valid requests. Invalid algorithms
9907 		 * need to be tested by IPSEC code because new
9908 		 * algorithms can be added dynamically.
9909 		 */
9910 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9911 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9912 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9913 			return (EINVAL);
9914 		}
9915 
9916 		/*
9917 		 * Only privileged users can issue these
9918 		 * requests.
9919 		 */
9920 		if (((ah_req & IPSEC_PREF_NEVER) ||
9921 		    (esp_req & IPSEC_PREF_NEVER) ||
9922 		    (se_req & IPSEC_PREF_NEVER)) &&
9923 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9924 			return (EPERM);
9925 		}
9926 
9927 		/*
9928 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9929 		 * are mutually exclusive.
9930 		 */
9931 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9932 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9933 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9934 			/* Both of them are set */
9935 			return (EINVAL);
9936 		}
9937 	}
9938 
9939 	mutex_enter(&connp->conn_lock);
9940 
9941 	/*
9942 	 * If we have already cached policies in ip_bind_connected*(), don't
9943 	 * let them change now. We cache policies for connections
9944 	 * whose src,dst [addr, port] is known.  The exception to this is
9945 	 * tunnels.  Tunnels are allowed to change policies after having
9946 	 * become fully bound.
9947 	 */
9948 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
9949 		mutex_exit(&connp->conn_lock);
9950 		return (EINVAL);
9951 	}
9952 
9953 	/*
9954 	 * We have a zero policies, reset the connection policy if already
9955 	 * set. This will cause the connection to inherit the
9956 	 * global policy, if any.
9957 	 */
9958 	if (is_pol_reset) {
9959 		if (connp->conn_policy != NULL) {
9960 			IPPH_REFRELE(connp->conn_policy);
9961 			connp->conn_policy = NULL;
9962 		}
9963 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
9964 		connp->conn_in_enforce_policy = B_FALSE;
9965 		connp->conn_out_enforce_policy = B_FALSE;
9966 		mutex_exit(&connp->conn_lock);
9967 		return (0);
9968 	}
9969 
9970 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
9971 	if (ph == NULL)
9972 		goto enomem;
9973 
9974 	ipsec_actvec_from_req(req, &actp, &nact);
9975 	if (actp == NULL)
9976 		goto enomem;
9977 
9978 	/*
9979 	 * Always allocate IPv4 policy entries, since they can also
9980 	 * apply to ipv6 sockets being used in ipv4-compat mode.
9981 	 */
9982 	bzero(&sel, sizeof (sel));
9983 	sel.ipsl_valid = IPSL_IPV4;
9984 
9985 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9986 	if (pin4 == NULL)
9987 		goto enomem;
9988 
9989 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9990 	if (pout4 == NULL)
9991 		goto enomem;
9992 
9993 	if (connp->conn_pkt_isv6) {
9994 		/*
9995 		 * We're looking at a v6 socket, also allocate the
9996 		 * v6-specific entries...
9997 		 */
9998 		sel.ipsl_valid = IPSL_IPV6;
9999 		pin6 = ipsec_policy_create(&sel, actp, nact,
10000 		    IPSEC_PRIO_SOCKET);
10001 		if (pin6 == NULL)
10002 			goto enomem;
10003 
10004 		pout6 = ipsec_policy_create(&sel, actp, nact,
10005 		    IPSEC_PRIO_SOCKET);
10006 		if (pout6 == NULL)
10007 			goto enomem;
10008 
10009 		/*
10010 		 * .. and file them away in the right place.
10011 		 */
10012 		fam = IPSEC_AF_V6;
10013 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10014 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10015 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10016 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10017 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10018 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10019 	}
10020 
10021 	ipsec_actvec_free(actp, nact);
10022 
10023 	/*
10024 	 * File the v4 policies.
10025 	 */
10026 	fam = IPSEC_AF_V4;
10027 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10028 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10029 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10030 
10031 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10032 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10033 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10034 
10035 	/*
10036 	 * If the requests need security, set enforce_policy.
10037 	 * If the requests are IPSEC_PREF_NEVER, one should
10038 	 * still set conn_out_enforce_policy so that an ipsec_out
10039 	 * gets attached in ip_wput. This is needed so that
10040 	 * for connections that we don't cache policy in ip_bind,
10041 	 * if global policy matches in ip_wput_attach_policy, we
10042 	 * don't wrongly inherit global policy. Similarly, we need
10043 	 * to set conn_in_enforce_policy also so that we don't verify
10044 	 * policy wrongly.
10045 	 */
10046 	if ((ah_req & REQ_MASK) != 0 ||
10047 	    (esp_req & REQ_MASK) != 0 ||
10048 	    (se_req & REQ_MASK) != 0) {
10049 		connp->conn_in_enforce_policy = B_TRUE;
10050 		connp->conn_out_enforce_policy = B_TRUE;
10051 		connp->conn_flags |= IPCL_CHECK_POLICY;
10052 	}
10053 
10054 	/*
10055 	 * Tunnels are allowed to set policy after having been fully bound.
10056 	 * If that's the case, cache policy here.
10057 	 */
10058 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
10059 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
10060 
10061 	mutex_exit(&connp->conn_lock);
10062 	return (error);
10063 #undef REQ_MASK
10064 
10065 	/*
10066 	 * Common memory-allocation-failure exit path.
10067 	 */
10068 enomem:
10069 	mutex_exit(&connp->conn_lock);
10070 	if (actp != NULL)
10071 		ipsec_actvec_free(actp, nact);
10072 	if (pin4 != NULL)
10073 		IPPOL_REFRELE(pin4);
10074 	if (pout4 != NULL)
10075 		IPPOL_REFRELE(pout4);
10076 	if (pin6 != NULL)
10077 		IPPOL_REFRELE(pin6);
10078 	if (pout6 != NULL)
10079 		IPPOL_REFRELE(pout6);
10080 	return (ENOMEM);
10081 }
10082 
10083 /*
10084  * Only for options that pass in an IP addr. Currently only V4 options
10085  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10086  * So this function assumes level is IPPROTO_IP
10087  */
10088 int
10089 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10090     mblk_t *first_mp)
10091 {
10092 	ipif_t *ipif = NULL;
10093 	int error;
10094 	ill_t *ill;
10095 	int zoneid;
10096 
10097 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10098 
10099 	if (addr != INADDR_ANY || checkonly) {
10100 		ASSERT(connp != NULL);
10101 		zoneid = IPCL_ZONEID(connp);
10102 		if (option == IP_NEXTHOP) {
10103 			ipif = ipif_lookup_onlink_addr(addr,
10104 			    connp->conn_zoneid);
10105 		} else {
10106 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10107 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10108 			    &error);
10109 		}
10110 		if (ipif == NULL) {
10111 			if (error == EINPROGRESS)
10112 				return (error);
10113 			else if ((option == IP_MULTICAST_IF) ||
10114 			    (option == IP_NEXTHOP))
10115 				return (EHOSTUNREACH);
10116 			else
10117 				return (EINVAL);
10118 		} else if (checkonly) {
10119 			if (option == IP_MULTICAST_IF) {
10120 				ill = ipif->ipif_ill;
10121 				/* not supported by the virtual network iface */
10122 				if (IS_VNI(ill)) {
10123 					ipif_refrele(ipif);
10124 					return (EINVAL);
10125 				}
10126 			}
10127 			ipif_refrele(ipif);
10128 			return (0);
10129 		}
10130 		ill = ipif->ipif_ill;
10131 		mutex_enter(&connp->conn_lock);
10132 		mutex_enter(&ill->ill_lock);
10133 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10134 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10135 			mutex_exit(&ill->ill_lock);
10136 			mutex_exit(&connp->conn_lock);
10137 			ipif_refrele(ipif);
10138 			return (option == IP_MULTICAST_IF ?
10139 			    EHOSTUNREACH : EINVAL);
10140 		}
10141 	} else {
10142 		mutex_enter(&connp->conn_lock);
10143 	}
10144 
10145 	/* None of the options below are supported on the VNI */
10146 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10147 		mutex_exit(&ill->ill_lock);
10148 		mutex_exit(&connp->conn_lock);
10149 		ipif_refrele(ipif);
10150 		return (EINVAL);
10151 	}
10152 
10153 	switch (option) {
10154 	case IP_DONTFAILOVER_IF:
10155 		/*
10156 		 * This option is used by in.mpathd to ensure
10157 		 * that IPMP probe packets only go out on the
10158 		 * test interfaces. in.mpathd sets this option
10159 		 * on the non-failover interfaces.
10160 		 * For backward compatibility, this option
10161 		 * implicitly sets IP_MULTICAST_IF, as used
10162 		 * be done in bind(), so that ip_wput gets
10163 		 * this ipif to send mcast packets.
10164 		 */
10165 		if (ipif != NULL) {
10166 			ASSERT(addr != INADDR_ANY);
10167 			connp->conn_nofailover_ill = ipif->ipif_ill;
10168 			connp->conn_multicast_ipif = ipif;
10169 		} else {
10170 			ASSERT(addr == INADDR_ANY);
10171 			connp->conn_nofailover_ill = NULL;
10172 			connp->conn_multicast_ipif = NULL;
10173 		}
10174 		break;
10175 
10176 	case IP_MULTICAST_IF:
10177 		connp->conn_multicast_ipif = ipif;
10178 		break;
10179 	case IP_NEXTHOP:
10180 		connp->conn_nexthop_v4 = addr;
10181 		connp->conn_nexthop_set = B_TRUE;
10182 		break;
10183 	}
10184 
10185 	if (ipif != NULL) {
10186 		mutex_exit(&ill->ill_lock);
10187 		mutex_exit(&connp->conn_lock);
10188 		ipif_refrele(ipif);
10189 		return (0);
10190 	}
10191 	mutex_exit(&connp->conn_lock);
10192 	/* We succeded in cleared the option */
10193 	return (0);
10194 }
10195 
10196 /*
10197  * For options that pass in an ifindex specifying the ill. V6 options always
10198  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10199  */
10200 int
10201 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10202     int level, int option, mblk_t *first_mp)
10203 {
10204 	ill_t *ill = NULL;
10205 	int error = 0;
10206 
10207 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10208 	if (ifindex != 0) {
10209 		ASSERT(connp != NULL);
10210 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10211 		    first_mp, ip_restart_optmgmt, &error);
10212 		if (ill != NULL) {
10213 			if (checkonly) {
10214 				/* not supported by the virtual network iface */
10215 				if (IS_VNI(ill)) {
10216 					ill_refrele(ill);
10217 					return (EINVAL);
10218 				}
10219 				ill_refrele(ill);
10220 				return (0);
10221 			}
10222 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10223 			    0, NULL)) {
10224 				ill_refrele(ill);
10225 				ill = NULL;
10226 				mutex_enter(&connp->conn_lock);
10227 				goto setit;
10228 			}
10229 			mutex_enter(&connp->conn_lock);
10230 			mutex_enter(&ill->ill_lock);
10231 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10232 				mutex_exit(&ill->ill_lock);
10233 				mutex_exit(&connp->conn_lock);
10234 				ill_refrele(ill);
10235 				ill = NULL;
10236 				mutex_enter(&connp->conn_lock);
10237 			}
10238 			goto setit;
10239 		} else if (error == EINPROGRESS) {
10240 			return (error);
10241 		} else {
10242 			error = 0;
10243 		}
10244 	}
10245 	mutex_enter(&connp->conn_lock);
10246 setit:
10247 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10248 
10249 	/*
10250 	 * The options below assume that the ILL (if any) transmits and/or
10251 	 * receives traffic. Neither of which is true for the virtual network
10252 	 * interface, so fail setting these on a VNI.
10253 	 */
10254 	if (IS_VNI(ill)) {
10255 		ASSERT(ill != NULL);
10256 		mutex_exit(&ill->ill_lock);
10257 		mutex_exit(&connp->conn_lock);
10258 		ill_refrele(ill);
10259 		return (EINVAL);
10260 	}
10261 
10262 	if (level == IPPROTO_IP) {
10263 		switch (option) {
10264 		case IP_BOUND_IF:
10265 			connp->conn_incoming_ill = ill;
10266 			connp->conn_outgoing_ill = ill;
10267 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10268 			    0 : ifindex;
10269 			break;
10270 
10271 		case IP_XMIT_IF:
10272 			/*
10273 			 * Similar to IP_BOUND_IF, but this only
10274 			 * determines the outgoing interface for
10275 			 * unicast packets. Also no IRE_CACHE entry
10276 			 * is added for the destination of the
10277 			 * outgoing packets. This feature is needed
10278 			 * for mobile IP.
10279 			 */
10280 			connp->conn_xmit_if_ill = ill;
10281 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10282 			    0 : ifindex;
10283 			break;
10284 
10285 		case IP_MULTICAST_IF:
10286 			/*
10287 			 * This option is an internal special. The socket
10288 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10289 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10290 			 * specifies an ifindex and we try first on V6 ill's.
10291 			 * If we don't find one, we they try using on v4 ill's
10292 			 * intenally and we come here.
10293 			 */
10294 			if (!checkonly && ill != NULL) {
10295 				ipif_t	*ipif;
10296 				ipif = ill->ill_ipif;
10297 
10298 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10299 					mutex_exit(&ill->ill_lock);
10300 					mutex_exit(&connp->conn_lock);
10301 					ill_refrele(ill);
10302 					ill = NULL;
10303 					mutex_enter(&connp->conn_lock);
10304 				} else {
10305 					connp->conn_multicast_ipif = ipif;
10306 				}
10307 			}
10308 			break;
10309 		}
10310 	} else {
10311 		switch (option) {
10312 		case IPV6_BOUND_IF:
10313 			connp->conn_incoming_ill = ill;
10314 			connp->conn_outgoing_ill = ill;
10315 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10316 			    0 : ifindex;
10317 			break;
10318 
10319 		case IPV6_BOUND_PIF:
10320 			/*
10321 			 * Limit all transmit to this ill.
10322 			 * Unlike IPV6_BOUND_IF, using this option
10323 			 * prevents load spreading and failover from
10324 			 * happening when the interface is part of the
10325 			 * group. That's why we don't need to remember
10326 			 * the ifindex in orig_bound_ifindex as in
10327 			 * IPV6_BOUND_IF.
10328 			 */
10329 			connp->conn_outgoing_pill = ill;
10330 			break;
10331 
10332 		case IPV6_DONTFAILOVER_IF:
10333 			/*
10334 			 * This option is used by in.mpathd to ensure
10335 			 * that IPMP probe packets only go out on the
10336 			 * test interfaces. in.mpathd sets this option
10337 			 * on the non-failover interfaces.
10338 			 */
10339 			connp->conn_nofailover_ill = ill;
10340 			/*
10341 			 * For backward compatibility, this option
10342 			 * implicitly sets ip_multicast_ill as used in
10343 			 * IP_MULTICAST_IF so that ip_wput gets
10344 			 * this ipif to send mcast packets.
10345 			 */
10346 			connp->conn_multicast_ill = ill;
10347 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10348 			    0 : ifindex;
10349 			break;
10350 
10351 		case IPV6_MULTICAST_IF:
10352 			/*
10353 			 * Set conn_multicast_ill to be the IPv6 ill.
10354 			 * Set conn_multicast_ipif to be an IPv4 ipif
10355 			 * for ifindex to make IPv4 mapped addresses
10356 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10357 			 * Even if no IPv6 ill exists for the ifindex
10358 			 * we need to check for an IPv4 ifindex in order
10359 			 * for this to work with mapped addresses. In that
10360 			 * case only set conn_multicast_ipif.
10361 			 */
10362 			if (!checkonly) {
10363 				if (ifindex == 0) {
10364 					connp->conn_multicast_ill = NULL;
10365 					connp->conn_orig_multicast_ifindex = 0;
10366 					connp->conn_multicast_ipif = NULL;
10367 				} else if (ill != NULL) {
10368 					connp->conn_multicast_ill = ill;
10369 					connp->conn_orig_multicast_ifindex =
10370 					    ifindex;
10371 				}
10372 			}
10373 			break;
10374 		}
10375 	}
10376 
10377 	if (ill != NULL) {
10378 		mutex_exit(&ill->ill_lock);
10379 		mutex_exit(&connp->conn_lock);
10380 		ill_refrele(ill);
10381 		return (0);
10382 	}
10383 	mutex_exit(&connp->conn_lock);
10384 	/*
10385 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10386 	 * locate the ill and could not set the option (ifindex != 0)
10387 	 */
10388 	return (ifindex == 0 ? 0 : EINVAL);
10389 }
10390 
10391 /* This routine sets socket options. */
10392 /* ARGSUSED */
10393 int
10394 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10395     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10396     void *dummy, cred_t *cr, mblk_t *first_mp)
10397 {
10398 	int		*i1 = (int *)invalp;
10399 	conn_t		*connp = Q_TO_CONN(q);
10400 	int		error = 0;
10401 	boolean_t	checkonly;
10402 	ire_t		*ire;
10403 	boolean_t	found;
10404 
10405 	switch (optset_context) {
10406 
10407 	case SETFN_OPTCOM_CHECKONLY:
10408 		checkonly = B_TRUE;
10409 		/*
10410 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10411 		 * inlen != 0 implies value supplied and
10412 		 * 	we have to "pretend" to set it.
10413 		 * inlen == 0 implies that there is no
10414 		 * 	value part in T_CHECK request and just validation
10415 		 * done elsewhere should be enough, we just return here.
10416 		 */
10417 		if (inlen == 0) {
10418 			*outlenp = 0;
10419 			return (0);
10420 		}
10421 		break;
10422 	case SETFN_OPTCOM_NEGOTIATE:
10423 	case SETFN_UD_NEGOTIATE:
10424 	case SETFN_CONN_NEGOTIATE:
10425 		checkonly = B_FALSE;
10426 		break;
10427 	default:
10428 		/*
10429 		 * We should never get here
10430 		 */
10431 		*outlenp = 0;
10432 		return (EINVAL);
10433 	}
10434 
10435 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10436 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10437 
10438 	/*
10439 	 * For fixed length options, no sanity check
10440 	 * of passed in length is done. It is assumed *_optcom_req()
10441 	 * routines do the right thing.
10442 	 */
10443 
10444 	switch (level) {
10445 	case SOL_SOCKET:
10446 		/*
10447 		 * conn_lock protects the bitfields, and is used to
10448 		 * set the fields atomically.
10449 		 */
10450 		switch (name) {
10451 		case SO_BROADCAST:
10452 			if (!checkonly) {
10453 				/* TODO: use value someplace? */
10454 				mutex_enter(&connp->conn_lock);
10455 				connp->conn_broadcast = *i1 ? 1 : 0;
10456 				mutex_exit(&connp->conn_lock);
10457 			}
10458 			break;	/* goto sizeof (int) option return */
10459 		case SO_USELOOPBACK:
10460 			if (!checkonly) {
10461 				/* TODO: use value someplace? */
10462 				mutex_enter(&connp->conn_lock);
10463 				connp->conn_loopback = *i1 ? 1 : 0;
10464 				mutex_exit(&connp->conn_lock);
10465 			}
10466 			break;	/* goto sizeof (int) option return */
10467 		case SO_DONTROUTE:
10468 			if (!checkonly) {
10469 				mutex_enter(&connp->conn_lock);
10470 				connp->conn_dontroute = *i1 ? 1 : 0;
10471 				mutex_exit(&connp->conn_lock);
10472 			}
10473 			break;	/* goto sizeof (int) option return */
10474 		case SO_REUSEADDR:
10475 			if (!checkonly) {
10476 				mutex_enter(&connp->conn_lock);
10477 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10478 				mutex_exit(&connp->conn_lock);
10479 			}
10480 			break;	/* goto sizeof (int) option return */
10481 		case SO_PROTOTYPE:
10482 			if (!checkonly) {
10483 				mutex_enter(&connp->conn_lock);
10484 				connp->conn_proto = *i1;
10485 				mutex_exit(&connp->conn_lock);
10486 			}
10487 			break;	/* goto sizeof (int) option return */
10488 		case SO_ALLZONES:
10489 			if (!checkonly) {
10490 				mutex_enter(&connp->conn_lock);
10491 				if (IPCL_IS_BOUND(connp)) {
10492 					mutex_exit(&connp->conn_lock);
10493 					return (EINVAL);
10494 				}
10495 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10496 				mutex_exit(&connp->conn_lock);
10497 			}
10498 			break;	/* goto sizeof (int) option return */
10499 		case SO_ANON_MLP:
10500 			if (!checkonly) {
10501 				mutex_enter(&connp->conn_lock);
10502 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10503 				mutex_exit(&connp->conn_lock);
10504 			}
10505 			break;	/* goto sizeof (int) option return */
10506 		case SO_MAC_EXEMPT:
10507 			if (secpolicy_net_mac_aware(cr) != 0 ||
10508 			    IPCL_IS_BOUND(connp))
10509 				return (EACCES);
10510 			if (!checkonly) {
10511 				mutex_enter(&connp->conn_lock);
10512 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10513 				mutex_exit(&connp->conn_lock);
10514 			}
10515 			break;	/* goto sizeof (int) option return */
10516 		default:
10517 			/*
10518 			 * "soft" error (negative)
10519 			 * option not handled at this level
10520 			 * Note: Do not modify *outlenp
10521 			 */
10522 			return (-EINVAL);
10523 		}
10524 		break;
10525 	case IPPROTO_IP:
10526 		switch (name) {
10527 		case IP_NEXTHOP:
10528 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10529 				return (EPERM);
10530 			/* FALLTHRU */
10531 		case IP_MULTICAST_IF:
10532 		case IP_DONTFAILOVER_IF: {
10533 			ipaddr_t addr = *i1;
10534 
10535 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10536 			    first_mp);
10537 			if (error != 0)
10538 				return (error);
10539 			break;	/* goto sizeof (int) option return */
10540 		}
10541 
10542 		case IP_MULTICAST_TTL:
10543 			/* Recorded in transport above IP */
10544 			*outvalp = *invalp;
10545 			*outlenp = sizeof (uchar_t);
10546 			return (0);
10547 		case IP_MULTICAST_LOOP:
10548 			if (!checkonly) {
10549 				mutex_enter(&connp->conn_lock);
10550 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10551 				mutex_exit(&connp->conn_lock);
10552 			}
10553 			*outvalp = *invalp;
10554 			*outlenp = sizeof (uchar_t);
10555 			return (0);
10556 		case IP_ADD_MEMBERSHIP:
10557 		case MCAST_JOIN_GROUP:
10558 		case IP_DROP_MEMBERSHIP:
10559 		case MCAST_LEAVE_GROUP: {
10560 			struct ip_mreq *mreqp;
10561 			struct group_req *greqp;
10562 			ire_t *ire;
10563 			boolean_t done = B_FALSE;
10564 			ipaddr_t group, ifaddr;
10565 			struct sockaddr_in *sin;
10566 			uint32_t *ifindexp;
10567 			boolean_t mcast_opt = B_TRUE;
10568 			mcast_record_t fmode;
10569 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10570 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10571 
10572 			switch (name) {
10573 			case IP_ADD_MEMBERSHIP:
10574 				mcast_opt = B_FALSE;
10575 				/* FALLTHRU */
10576 			case MCAST_JOIN_GROUP:
10577 				fmode = MODE_IS_EXCLUDE;
10578 				optfn = ip_opt_add_group;
10579 				break;
10580 
10581 			case IP_DROP_MEMBERSHIP:
10582 				mcast_opt = B_FALSE;
10583 				/* FALLTHRU */
10584 			case MCAST_LEAVE_GROUP:
10585 				fmode = MODE_IS_INCLUDE;
10586 				optfn = ip_opt_delete_group;
10587 				break;
10588 			}
10589 
10590 			if (mcast_opt) {
10591 				greqp = (struct group_req *)i1;
10592 				sin = (struct sockaddr_in *)&greqp->gr_group;
10593 				if (sin->sin_family != AF_INET) {
10594 					*outlenp = 0;
10595 					return (ENOPROTOOPT);
10596 				}
10597 				group = (ipaddr_t)sin->sin_addr.s_addr;
10598 				ifaddr = INADDR_ANY;
10599 				ifindexp = &greqp->gr_interface;
10600 			} else {
10601 				mreqp = (struct ip_mreq *)i1;
10602 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10603 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10604 				ifindexp = NULL;
10605 			}
10606 
10607 			/*
10608 			 * In the multirouting case, we need to replicate
10609 			 * the request on all interfaces that will take part
10610 			 * in replication.  We do so because multirouting is
10611 			 * reflective, thus we will probably receive multi-
10612 			 * casts on those interfaces.
10613 			 * The ip_multirt_apply_membership() succeeds if the
10614 			 * operation succeeds on at least one interface.
10615 			 */
10616 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10617 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10618 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10619 			if (ire != NULL) {
10620 				if (ire->ire_flags & RTF_MULTIRT) {
10621 					error = ip_multirt_apply_membership(
10622 					    optfn, ire, connp, checkonly, group,
10623 					    fmode, INADDR_ANY, first_mp);
10624 					done = B_TRUE;
10625 				}
10626 				ire_refrele(ire);
10627 			}
10628 			if (!done) {
10629 				error = optfn(connp, checkonly, group, ifaddr,
10630 				    ifindexp, fmode, INADDR_ANY, first_mp);
10631 			}
10632 			if (error) {
10633 				/*
10634 				 * EINPROGRESS is a soft error, needs retry
10635 				 * so don't make *outlenp zero.
10636 				 */
10637 				if (error != EINPROGRESS)
10638 					*outlenp = 0;
10639 				return (error);
10640 			}
10641 			/* OK return - copy input buffer into output buffer */
10642 			if (invalp != outvalp) {
10643 				/* don't trust bcopy for identical src/dst */
10644 				bcopy(invalp, outvalp, inlen);
10645 			}
10646 			*outlenp = inlen;
10647 			return (0);
10648 		}
10649 		case IP_BLOCK_SOURCE:
10650 		case IP_UNBLOCK_SOURCE:
10651 		case IP_ADD_SOURCE_MEMBERSHIP:
10652 		case IP_DROP_SOURCE_MEMBERSHIP:
10653 		case MCAST_BLOCK_SOURCE:
10654 		case MCAST_UNBLOCK_SOURCE:
10655 		case MCAST_JOIN_SOURCE_GROUP:
10656 		case MCAST_LEAVE_SOURCE_GROUP: {
10657 			struct ip_mreq_source *imreqp;
10658 			struct group_source_req *gsreqp;
10659 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10660 			uint32_t ifindex = 0;
10661 			mcast_record_t fmode;
10662 			struct sockaddr_in *sin;
10663 			ire_t *ire;
10664 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10665 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10666 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10667 
10668 			switch (name) {
10669 			case IP_BLOCK_SOURCE:
10670 				mcast_opt = B_FALSE;
10671 				/* FALLTHRU */
10672 			case MCAST_BLOCK_SOURCE:
10673 				fmode = MODE_IS_EXCLUDE;
10674 				optfn = ip_opt_add_group;
10675 				break;
10676 
10677 			case IP_UNBLOCK_SOURCE:
10678 				mcast_opt = B_FALSE;
10679 				/* FALLTHRU */
10680 			case MCAST_UNBLOCK_SOURCE:
10681 				fmode = MODE_IS_EXCLUDE;
10682 				optfn = ip_opt_delete_group;
10683 				break;
10684 
10685 			case IP_ADD_SOURCE_MEMBERSHIP:
10686 				mcast_opt = B_FALSE;
10687 				/* FALLTHRU */
10688 			case MCAST_JOIN_SOURCE_GROUP:
10689 				fmode = MODE_IS_INCLUDE;
10690 				optfn = ip_opt_add_group;
10691 				break;
10692 
10693 			case IP_DROP_SOURCE_MEMBERSHIP:
10694 				mcast_opt = B_FALSE;
10695 				/* FALLTHRU */
10696 			case MCAST_LEAVE_SOURCE_GROUP:
10697 				fmode = MODE_IS_INCLUDE;
10698 				optfn = ip_opt_delete_group;
10699 				break;
10700 			}
10701 
10702 			if (mcast_opt) {
10703 				gsreqp = (struct group_source_req *)i1;
10704 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10705 					*outlenp = 0;
10706 					return (ENOPROTOOPT);
10707 				}
10708 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10709 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10710 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10711 				src = (ipaddr_t)sin->sin_addr.s_addr;
10712 				ifindex = gsreqp->gsr_interface;
10713 			} else {
10714 				imreqp = (struct ip_mreq_source *)i1;
10715 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10716 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10717 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10718 			}
10719 
10720 			/*
10721 			 * In the multirouting case, we need to replicate
10722 			 * the request as noted in the mcast cases above.
10723 			 */
10724 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10725 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10726 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10727 			if (ire != NULL) {
10728 				if (ire->ire_flags & RTF_MULTIRT) {
10729 					error = ip_multirt_apply_membership(
10730 					    optfn, ire, connp, checkonly, grp,
10731 					    fmode, src, first_mp);
10732 					done = B_TRUE;
10733 				}
10734 				ire_refrele(ire);
10735 			}
10736 			if (!done) {
10737 				error = optfn(connp, checkonly, grp, ifaddr,
10738 				    &ifindex, fmode, src, first_mp);
10739 			}
10740 			if (error != 0) {
10741 				/*
10742 				 * EINPROGRESS is a soft error, needs retry
10743 				 * so don't make *outlenp zero.
10744 				 */
10745 				if (error != EINPROGRESS)
10746 					*outlenp = 0;
10747 				return (error);
10748 			}
10749 			/* OK return - copy input buffer into output buffer */
10750 			if (invalp != outvalp) {
10751 				bcopy(invalp, outvalp, inlen);
10752 			}
10753 			*outlenp = inlen;
10754 			return (0);
10755 		}
10756 		case IP_SEC_OPT:
10757 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10758 			if (error != 0) {
10759 				*outlenp = 0;
10760 				return (error);
10761 			}
10762 			break;
10763 		case IP_HDRINCL:
10764 		case IP_OPTIONS:
10765 		case T_IP_OPTIONS:
10766 		case IP_TOS:
10767 		case T_IP_TOS:
10768 		case IP_TTL:
10769 		case IP_RECVDSTADDR:
10770 		case IP_RECVOPTS:
10771 			/* OK return - copy input buffer into output buffer */
10772 			if (invalp != outvalp) {
10773 				/* don't trust bcopy for identical src/dst */
10774 				bcopy(invalp, outvalp, inlen);
10775 			}
10776 			*outlenp = inlen;
10777 			return (0);
10778 		case IP_RECVIF:
10779 			/* Retrieve the inbound interface index */
10780 			if (!checkonly) {
10781 				mutex_enter(&connp->conn_lock);
10782 				connp->conn_recvif = *i1 ? 1 : 0;
10783 				mutex_exit(&connp->conn_lock);
10784 			}
10785 			break;	/* goto sizeof (int) option return */
10786 		case IP_RECVSLLA:
10787 			/* Retrieve the source link layer address */
10788 			if (!checkonly) {
10789 				mutex_enter(&connp->conn_lock);
10790 				connp->conn_recvslla = *i1 ? 1 : 0;
10791 				mutex_exit(&connp->conn_lock);
10792 			}
10793 			break;	/* goto sizeof (int) option return */
10794 		case MRT_INIT:
10795 		case MRT_DONE:
10796 		case MRT_ADD_VIF:
10797 		case MRT_DEL_VIF:
10798 		case MRT_ADD_MFC:
10799 		case MRT_DEL_MFC:
10800 		case MRT_ASSERT:
10801 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10802 				*outlenp = 0;
10803 				return (error);
10804 			}
10805 			error = ip_mrouter_set((int)name, q, checkonly,
10806 			    (uchar_t *)invalp, inlen, first_mp);
10807 			if (error) {
10808 				*outlenp = 0;
10809 				return (error);
10810 			}
10811 			/* OK return - copy input buffer into output buffer */
10812 			if (invalp != outvalp) {
10813 				/* don't trust bcopy for identical src/dst */
10814 				bcopy(invalp, outvalp, inlen);
10815 			}
10816 			*outlenp = inlen;
10817 			return (0);
10818 		case IP_BOUND_IF:
10819 		case IP_XMIT_IF:
10820 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10821 			    level, name, first_mp);
10822 			if (error != 0)
10823 				return (error);
10824 			break; 		/* goto sizeof (int) option return */
10825 
10826 		case IP_UNSPEC_SRC:
10827 			/* Allow sending with a zero source address */
10828 			if (!checkonly) {
10829 				mutex_enter(&connp->conn_lock);
10830 				connp->conn_unspec_src = *i1 ? 1 : 0;
10831 				mutex_exit(&connp->conn_lock);
10832 			}
10833 			break;	/* goto sizeof (int) option return */
10834 		default:
10835 			/*
10836 			 * "soft" error (negative)
10837 			 * option not handled at this level
10838 			 * Note: Do not modify *outlenp
10839 			 */
10840 			return (-EINVAL);
10841 		}
10842 		break;
10843 	case IPPROTO_IPV6:
10844 		switch (name) {
10845 		case IPV6_BOUND_IF:
10846 		case IPV6_BOUND_PIF:
10847 		case IPV6_DONTFAILOVER_IF:
10848 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10849 			    level, name, first_mp);
10850 			if (error != 0)
10851 				return (error);
10852 			break; 		/* goto sizeof (int) option return */
10853 
10854 		case IPV6_MULTICAST_IF:
10855 			/*
10856 			 * The only possible errors are EINPROGRESS and
10857 			 * EINVAL. EINPROGRESS will be restarted and is not
10858 			 * a hard error. We call this option on both V4 and V6
10859 			 * If both return EINVAL, then this call returns
10860 			 * EINVAL. If at least one of them succeeds we
10861 			 * return success.
10862 			 */
10863 			found = B_FALSE;
10864 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10865 			    level, name, first_mp);
10866 			if (error == EINPROGRESS)
10867 				return (error);
10868 			if (error == 0)
10869 				found = B_TRUE;
10870 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10871 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10872 			if (error == 0)
10873 				found = B_TRUE;
10874 			if (!found)
10875 				return (error);
10876 			break; 		/* goto sizeof (int) option return */
10877 
10878 		case IPV6_MULTICAST_HOPS:
10879 			/* Recorded in transport above IP */
10880 			break;	/* goto sizeof (int) option return */
10881 		case IPV6_MULTICAST_LOOP:
10882 			if (!checkonly) {
10883 				mutex_enter(&connp->conn_lock);
10884 				connp->conn_multicast_loop = *i1;
10885 				mutex_exit(&connp->conn_lock);
10886 			}
10887 			break;	/* goto sizeof (int) option return */
10888 		case IPV6_JOIN_GROUP:
10889 		case MCAST_JOIN_GROUP:
10890 		case IPV6_LEAVE_GROUP:
10891 		case MCAST_LEAVE_GROUP: {
10892 			struct ipv6_mreq *ip_mreqp;
10893 			struct group_req *greqp;
10894 			ire_t *ire;
10895 			boolean_t done = B_FALSE;
10896 			in6_addr_t groupv6;
10897 			uint32_t ifindex;
10898 			boolean_t mcast_opt = B_TRUE;
10899 			mcast_record_t fmode;
10900 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10901 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10902 
10903 			switch (name) {
10904 			case IPV6_JOIN_GROUP:
10905 				mcast_opt = B_FALSE;
10906 				/* FALLTHRU */
10907 			case MCAST_JOIN_GROUP:
10908 				fmode = MODE_IS_EXCLUDE;
10909 				optfn = ip_opt_add_group_v6;
10910 				break;
10911 
10912 			case IPV6_LEAVE_GROUP:
10913 				mcast_opt = B_FALSE;
10914 				/* FALLTHRU */
10915 			case MCAST_LEAVE_GROUP:
10916 				fmode = MODE_IS_INCLUDE;
10917 				optfn = ip_opt_delete_group_v6;
10918 				break;
10919 			}
10920 
10921 			if (mcast_opt) {
10922 				struct sockaddr_in *sin;
10923 				struct sockaddr_in6 *sin6;
10924 				greqp = (struct group_req *)i1;
10925 				if (greqp->gr_group.ss_family == AF_INET) {
10926 					sin = (struct sockaddr_in *)
10927 					    &(greqp->gr_group);
10928 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10929 					    &groupv6);
10930 				} else {
10931 					sin6 = (struct sockaddr_in6 *)
10932 					    &(greqp->gr_group);
10933 					groupv6 = sin6->sin6_addr;
10934 				}
10935 				ifindex = greqp->gr_interface;
10936 			} else {
10937 				ip_mreqp = (struct ipv6_mreq *)i1;
10938 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10939 				ifindex = ip_mreqp->ipv6mr_interface;
10940 			}
10941 			/*
10942 			 * In the multirouting case, we need to replicate
10943 			 * the request on all interfaces that will take part
10944 			 * in replication.  We do so because multirouting is
10945 			 * reflective, thus we will probably receive multi-
10946 			 * casts on those interfaces.
10947 			 * The ip_multirt_apply_membership_v6() succeeds if
10948 			 * the operation succeeds on at least one interface.
10949 			 */
10950 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
10951 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10952 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10953 			if (ire != NULL) {
10954 				if (ire->ire_flags & RTF_MULTIRT) {
10955 					error = ip_multirt_apply_membership_v6(
10956 					    optfn, ire, connp, checkonly,
10957 					    &groupv6, fmode, &ipv6_all_zeros,
10958 					    first_mp);
10959 					done = B_TRUE;
10960 				}
10961 				ire_refrele(ire);
10962 			}
10963 			if (!done) {
10964 				error = optfn(connp, checkonly, &groupv6,
10965 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10966 			}
10967 			if (error) {
10968 				/*
10969 				 * EINPROGRESS is a soft error, needs retry
10970 				 * so don't make *outlenp zero.
10971 				 */
10972 				if (error != EINPROGRESS)
10973 					*outlenp = 0;
10974 				return (error);
10975 			}
10976 			/* OK return - copy input buffer into output buffer */
10977 			if (invalp != outvalp) {
10978 				/* don't trust bcopy for identical src/dst */
10979 				bcopy(invalp, outvalp, inlen);
10980 			}
10981 			*outlenp = inlen;
10982 			return (0);
10983 		}
10984 		case MCAST_BLOCK_SOURCE:
10985 		case MCAST_UNBLOCK_SOURCE:
10986 		case MCAST_JOIN_SOURCE_GROUP:
10987 		case MCAST_LEAVE_SOURCE_GROUP: {
10988 			struct group_source_req *gsreqp;
10989 			in6_addr_t v6grp, v6src;
10990 			uint32_t ifindex;
10991 			mcast_record_t fmode;
10992 			ire_t *ire;
10993 			boolean_t done = B_FALSE;
10994 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10995 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10996 
10997 			switch (name) {
10998 			case MCAST_BLOCK_SOURCE:
10999 				fmode = MODE_IS_EXCLUDE;
11000 				optfn = ip_opt_add_group_v6;
11001 				break;
11002 			case MCAST_UNBLOCK_SOURCE:
11003 				fmode = MODE_IS_EXCLUDE;
11004 				optfn = ip_opt_delete_group_v6;
11005 				break;
11006 			case MCAST_JOIN_SOURCE_GROUP:
11007 				fmode = MODE_IS_INCLUDE;
11008 				optfn = ip_opt_add_group_v6;
11009 				break;
11010 			case MCAST_LEAVE_SOURCE_GROUP:
11011 				fmode = MODE_IS_INCLUDE;
11012 				optfn = ip_opt_delete_group_v6;
11013 				break;
11014 			}
11015 
11016 			gsreqp = (struct group_source_req *)i1;
11017 			ifindex = gsreqp->gsr_interface;
11018 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11019 				struct sockaddr_in *s;
11020 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11021 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11022 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11023 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11024 			} else {
11025 				struct sockaddr_in6 *s6;
11026 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11027 				v6grp = s6->sin6_addr;
11028 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11029 				v6src = s6->sin6_addr;
11030 			}
11031 
11032 			/*
11033 			 * In the multirouting case, we need to replicate
11034 			 * the request as noted in the mcast cases above.
11035 			 */
11036 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11037 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11038 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11039 			if (ire != NULL) {
11040 				if (ire->ire_flags & RTF_MULTIRT) {
11041 					error = ip_multirt_apply_membership_v6(
11042 					    optfn, ire, connp, checkonly,
11043 					    &v6grp, fmode, &v6src, first_mp);
11044 					done = B_TRUE;
11045 				}
11046 				ire_refrele(ire);
11047 			}
11048 			if (!done) {
11049 				error = optfn(connp, checkonly, &v6grp,
11050 				    ifindex, fmode, &v6src, first_mp);
11051 			}
11052 			if (error != 0) {
11053 				/*
11054 				 * EINPROGRESS is a soft error, needs retry
11055 				 * so don't make *outlenp zero.
11056 				 */
11057 				if (error != EINPROGRESS)
11058 					*outlenp = 0;
11059 				return (error);
11060 			}
11061 			/* OK return - copy input buffer into output buffer */
11062 			if (invalp != outvalp) {
11063 				bcopy(invalp, outvalp, inlen);
11064 			}
11065 			*outlenp = inlen;
11066 			return (0);
11067 		}
11068 		case IPV6_UNICAST_HOPS:
11069 			/* Recorded in transport above IP */
11070 			break;	/* goto sizeof (int) option return */
11071 		case IPV6_UNSPEC_SRC:
11072 			/* Allow sending with a zero source address */
11073 			if (!checkonly) {
11074 				mutex_enter(&connp->conn_lock);
11075 				connp->conn_unspec_src = *i1 ? 1 : 0;
11076 				mutex_exit(&connp->conn_lock);
11077 			}
11078 			break;	/* goto sizeof (int) option return */
11079 		case IPV6_RECVPKTINFO:
11080 			if (!checkonly) {
11081 				mutex_enter(&connp->conn_lock);
11082 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
11083 				mutex_exit(&connp->conn_lock);
11084 			}
11085 			break;	/* goto sizeof (int) option return */
11086 		case IPV6_RECVTCLASS:
11087 			if (!checkonly) {
11088 				if (*i1 < 0 || *i1 > 1) {
11089 					return (EINVAL);
11090 				}
11091 				mutex_enter(&connp->conn_lock);
11092 				connp->conn_ipv6_recvtclass = *i1;
11093 				mutex_exit(&connp->conn_lock);
11094 			}
11095 			break;
11096 		case IPV6_RECVPATHMTU:
11097 			if (!checkonly) {
11098 				if (*i1 < 0 || *i1 > 1) {
11099 					return (EINVAL);
11100 				}
11101 				mutex_enter(&connp->conn_lock);
11102 				connp->conn_ipv6_recvpathmtu = *i1;
11103 				mutex_exit(&connp->conn_lock);
11104 			}
11105 			break;
11106 		case IPV6_RECVHOPLIMIT:
11107 			if (!checkonly) {
11108 				mutex_enter(&connp->conn_lock);
11109 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11110 				mutex_exit(&connp->conn_lock);
11111 			}
11112 			break;	/* goto sizeof (int) option return */
11113 		case IPV6_RECVHOPOPTS:
11114 			if (!checkonly) {
11115 				mutex_enter(&connp->conn_lock);
11116 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11117 				mutex_exit(&connp->conn_lock);
11118 			}
11119 			break;	/* goto sizeof (int) option return */
11120 		case IPV6_RECVDSTOPTS:
11121 			if (!checkonly) {
11122 				mutex_enter(&connp->conn_lock);
11123 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11124 				mutex_exit(&connp->conn_lock);
11125 			}
11126 			break;	/* goto sizeof (int) option return */
11127 		case IPV6_RECVRTHDR:
11128 			if (!checkonly) {
11129 				mutex_enter(&connp->conn_lock);
11130 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11131 				mutex_exit(&connp->conn_lock);
11132 			}
11133 			break;	/* goto sizeof (int) option return */
11134 		case IPV6_RECVRTHDRDSTOPTS:
11135 			if (!checkonly) {
11136 				mutex_enter(&connp->conn_lock);
11137 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11138 				mutex_exit(&connp->conn_lock);
11139 			}
11140 			break;	/* goto sizeof (int) option return */
11141 		case IPV6_PKTINFO:
11142 			if (inlen == 0)
11143 				return (-EINVAL);	/* clearing option */
11144 			error = ip6_set_pktinfo(cr, connp,
11145 			    (struct in6_pktinfo *)invalp, first_mp);
11146 			if (error != 0)
11147 				*outlenp = 0;
11148 			else
11149 				*outlenp = inlen;
11150 			return (error);
11151 		case IPV6_NEXTHOP: {
11152 			struct sockaddr_in6 *sin6;
11153 
11154 			/* Verify that the nexthop is reachable */
11155 			if (inlen == 0)
11156 				return (-EINVAL);	/* clearing option */
11157 
11158 			sin6 = (struct sockaddr_in6 *)invalp;
11159 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11160 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11161 			    NULL, MATCH_IRE_DEFAULT);
11162 
11163 			if (ire == NULL) {
11164 				*outlenp = 0;
11165 				return (EHOSTUNREACH);
11166 			}
11167 			ire_refrele(ire);
11168 			return (-EINVAL);
11169 		}
11170 		case IPV6_SEC_OPT:
11171 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11172 			if (error != 0) {
11173 				*outlenp = 0;
11174 				return (error);
11175 			}
11176 			break;
11177 		case IPV6_SRC_PREFERENCES: {
11178 			/*
11179 			 * This is implemented strictly in the ip module
11180 			 * (here and in tcp_opt_*() to accomodate tcp
11181 			 * sockets).  Modules above ip pass this option
11182 			 * down here since ip is the only one that needs to
11183 			 * be aware of source address preferences.
11184 			 *
11185 			 * This socket option only affects connected
11186 			 * sockets that haven't already bound to a specific
11187 			 * IPv6 address.  In other words, sockets that
11188 			 * don't call bind() with an address other than the
11189 			 * unspecified address and that call connect().
11190 			 * ip_bind_connected_v6() passes these preferences
11191 			 * to the ipif_select_source_v6() function.
11192 			 */
11193 			if (inlen != sizeof (uint32_t))
11194 				return (EINVAL);
11195 			error = ip6_set_src_preferences(connp,
11196 			    *(uint32_t *)invalp);
11197 			if (error != 0) {
11198 				*outlenp = 0;
11199 				return (error);
11200 			} else {
11201 				*outlenp = sizeof (uint32_t);
11202 			}
11203 			break;
11204 		}
11205 		case IPV6_V6ONLY:
11206 			if (*i1 < 0 || *i1 > 1) {
11207 				return (EINVAL);
11208 			}
11209 			mutex_enter(&connp->conn_lock);
11210 			connp->conn_ipv6_v6only = *i1;
11211 			mutex_exit(&connp->conn_lock);
11212 			break;
11213 		default:
11214 			return (-EINVAL);
11215 		}
11216 		break;
11217 	default:
11218 		/*
11219 		 * "soft" error (negative)
11220 		 * option not handled at this level
11221 		 * Note: Do not modify *outlenp
11222 		 */
11223 		return (-EINVAL);
11224 	}
11225 	/*
11226 	 * Common case of return from an option that is sizeof (int)
11227 	 */
11228 	*(int *)outvalp = *i1;
11229 	*outlenp = sizeof (int);
11230 	return (0);
11231 }
11232 
11233 /*
11234  * This routine gets default values of certain options whose default
11235  * values are maintained by protocol specific code
11236  */
11237 /* ARGSUSED */
11238 int
11239 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11240 {
11241 	int *i1 = (int *)ptr;
11242 
11243 	switch (level) {
11244 	case IPPROTO_IP:
11245 		switch (name) {
11246 		case IP_MULTICAST_TTL:
11247 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11248 			return (sizeof (uchar_t));
11249 		case IP_MULTICAST_LOOP:
11250 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11251 			return (sizeof (uchar_t));
11252 		default:
11253 			return (-1);
11254 		}
11255 	case IPPROTO_IPV6:
11256 		switch (name) {
11257 		case IPV6_UNICAST_HOPS:
11258 			*i1 = ipv6_def_hops;
11259 			return (sizeof (int));
11260 		case IPV6_MULTICAST_HOPS:
11261 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11262 			return (sizeof (int));
11263 		case IPV6_MULTICAST_LOOP:
11264 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11265 			return (sizeof (int));
11266 		case IPV6_V6ONLY:
11267 			*i1 = 1;
11268 			return (sizeof (int));
11269 		default:
11270 			return (-1);
11271 		}
11272 	default:
11273 		return (-1);
11274 	}
11275 	/* NOTREACHED */
11276 }
11277 
11278 /*
11279  * Given a destination address and a pointer to where to put the information
11280  * this routine fills in the mtuinfo.
11281  */
11282 int
11283 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11284     struct ip6_mtuinfo *mtuinfo)
11285 {
11286 	ire_t *ire;
11287 
11288 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11289 		return (-1);
11290 
11291 	bzero(mtuinfo, sizeof (*mtuinfo));
11292 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11293 	mtuinfo->ip6m_addr.sin6_port = port;
11294 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11295 
11296 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11297 	if (ire != NULL) {
11298 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11299 		ire_refrele(ire);
11300 	} else {
11301 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11302 	}
11303 	return (sizeof (struct ip6_mtuinfo));
11304 }
11305 
11306 /*
11307  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11308  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11309  * isn't.  This doesn't matter as the error checking is done properly for the
11310  * other MRT options coming in through ip_opt_set.
11311  */
11312 int
11313 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11314 {
11315 	conn_t		*connp = Q_TO_CONN(q);
11316 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11317 
11318 	switch (level) {
11319 	case IPPROTO_IP:
11320 		switch (name) {
11321 		case MRT_VERSION:
11322 		case MRT_ASSERT:
11323 			(void) ip_mrouter_get(name, q, ptr);
11324 			return (sizeof (int));
11325 		case IP_SEC_OPT:
11326 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11327 		case IP_NEXTHOP:
11328 			if (connp->conn_nexthop_set) {
11329 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11330 				return (sizeof (ipaddr_t));
11331 			} else
11332 				return (0);
11333 		default:
11334 			break;
11335 		}
11336 		break;
11337 	case IPPROTO_IPV6:
11338 		switch (name) {
11339 		case IPV6_SEC_OPT:
11340 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11341 		case IPV6_SRC_PREFERENCES: {
11342 			return (ip6_get_src_preferences(connp,
11343 			    (uint32_t *)ptr));
11344 		}
11345 		case IPV6_V6ONLY:
11346 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11347 			return (sizeof (int));
11348 		case IPV6_PATHMTU:
11349 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11350 				(struct ip6_mtuinfo *)ptr));
11351 		default:
11352 			break;
11353 		}
11354 		break;
11355 	default:
11356 		break;
11357 	}
11358 	return (-1);
11359 }
11360 
11361 /* Named Dispatch routine to get a current value out of our parameter table. */
11362 /* ARGSUSED */
11363 static int
11364 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11365 {
11366 	ipparam_t *ippa = (ipparam_t *)cp;
11367 
11368 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11369 	return (0);
11370 }
11371 
11372 /* ARGSUSED */
11373 static int
11374 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11375 {
11376 
11377 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11378 	return (0);
11379 }
11380 
11381 /*
11382  * Set ip{,6}_forwarding values.  This means walking through all of the
11383  * ill's and toggling their forwarding values.
11384  */
11385 /* ARGSUSED */
11386 static int
11387 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11388 {
11389 	long new_value;
11390 	int *forwarding_value = (int *)cp;
11391 	ill_t *walker;
11392 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11393 	ill_walk_context_t ctx;
11394 
11395 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11396 	    new_value < 0 || new_value > 1) {
11397 		return (EINVAL);
11398 	}
11399 
11400 	*forwarding_value = new_value;
11401 
11402 	/*
11403 	 * Regardless of the current value of ip_forwarding, set all per-ill
11404 	 * values of ip_forwarding to the value being set.
11405 	 *
11406 	 * Bring all the ill's up to date with the new global value.
11407 	 */
11408 	rw_enter(&ill_g_lock, RW_READER);
11409 
11410 	if (isv6)
11411 		walker = ILL_START_WALK_V6(&ctx);
11412 	else
11413 		walker = ILL_START_WALK_V4(&ctx);
11414 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11415 		(void) ill_forward_set(q, mp, (new_value != 0),
11416 		    (caddr_t)walker);
11417 	}
11418 	rw_exit(&ill_g_lock);
11419 
11420 	return (0);
11421 }
11422 
11423 /*
11424  * Walk through the param array specified registering each element with the
11425  * Named Dispatch handler. This is called only during init. So it is ok
11426  * not to acquire any locks
11427  */
11428 static boolean_t
11429 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11430     ipndp_t *ipnd, size_t ipnd_cnt)
11431 {
11432 	for (; ippa_cnt-- > 0; ippa++) {
11433 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11434 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11435 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11436 				nd_free(&ip_g_nd);
11437 				return (B_FALSE);
11438 			}
11439 		}
11440 	}
11441 
11442 	for (; ipnd_cnt-- > 0; ipnd++) {
11443 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11444 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11445 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11446 			    ipnd->ip_ndp_data)) {
11447 				nd_free(&ip_g_nd);
11448 				return (B_FALSE);
11449 			}
11450 		}
11451 	}
11452 
11453 	return (B_TRUE);
11454 }
11455 
11456 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11457 /* ARGSUSED */
11458 static int
11459 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11460 {
11461 	long		new_value;
11462 	ipparam_t	*ippa = (ipparam_t *)cp;
11463 
11464 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11465 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11466 		return (EINVAL);
11467 	}
11468 	ippa->ip_param_value = new_value;
11469 	return (0);
11470 }
11471 
11472 /*
11473  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11474  * When an ipf is passed here for the first time, if
11475  * we already have in-order fragments on the queue, we convert from the fast-
11476  * path reassembly scheme to the hard-case scheme.  From then on, additional
11477  * fragments are reassembled here.  We keep track of the start and end offsets
11478  * of each piece, and the number of holes in the chain.  When the hole count
11479  * goes to zero, we are done!
11480  *
11481  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11482  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11483  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11484  * after the call to ip_reassemble().
11485  */
11486 int
11487 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11488     size_t msg_len)
11489 {
11490 	uint_t	end;
11491 	mblk_t	*next_mp;
11492 	mblk_t	*mp1;
11493 	uint_t	offset;
11494 	boolean_t incr_dups = B_TRUE;
11495 	boolean_t offset_zero_seen = B_FALSE;
11496 	boolean_t pkt_boundary_checked = B_FALSE;
11497 
11498 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11499 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11500 
11501 	/* Add in byte count */
11502 	ipf->ipf_count += msg_len;
11503 	if (ipf->ipf_end) {
11504 		/*
11505 		 * We were part way through in-order reassembly, but now there
11506 		 * is a hole.  We walk through messages already queued, and
11507 		 * mark them for hard case reassembly.  We know that up till
11508 		 * now they were in order starting from offset zero.
11509 		 */
11510 		offset = 0;
11511 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11512 			IP_REASS_SET_START(mp1, offset);
11513 			if (offset == 0) {
11514 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11515 				offset = -ipf->ipf_nf_hdr_len;
11516 			}
11517 			offset += mp1->b_wptr - mp1->b_rptr;
11518 			IP_REASS_SET_END(mp1, offset);
11519 		}
11520 		/* One hole at the end. */
11521 		ipf->ipf_hole_cnt = 1;
11522 		/* Brand it as a hard case, forever. */
11523 		ipf->ipf_end = 0;
11524 	}
11525 	/* Walk through all the new pieces. */
11526 	do {
11527 		end = start + (mp->b_wptr - mp->b_rptr);
11528 		/*
11529 		 * If start is 0, decrease 'end' only for the first mblk of
11530 		 * the fragment. Otherwise 'end' can get wrong value in the
11531 		 * second pass of the loop if first mblk is exactly the
11532 		 * size of ipf_nf_hdr_len.
11533 		 */
11534 		if (start == 0 && !offset_zero_seen) {
11535 			/* First segment */
11536 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11537 			end -= ipf->ipf_nf_hdr_len;
11538 			offset_zero_seen = B_TRUE;
11539 		}
11540 		next_mp = mp->b_cont;
11541 		/*
11542 		 * We are checking to see if there is any interesing data
11543 		 * to process.  If there isn't and the mblk isn't the
11544 		 * one which carries the unfragmentable header then we
11545 		 * drop it.  It's possible to have just the unfragmentable
11546 		 * header come through without any data.  That needs to be
11547 		 * saved.
11548 		 *
11549 		 * If the assert at the top of this function holds then the
11550 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11551 		 * is infrequently traveled enough that the test is left in
11552 		 * to protect against future code changes which break that
11553 		 * invariant.
11554 		 */
11555 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11556 			/* Empty.  Blast it. */
11557 			IP_REASS_SET_START(mp, 0);
11558 			IP_REASS_SET_END(mp, 0);
11559 			/*
11560 			 * If the ipf points to the mblk we are about to free,
11561 			 * update ipf to point to the next mblk (or NULL
11562 			 * if none).
11563 			 */
11564 			if (ipf->ipf_mp->b_cont == mp)
11565 				ipf->ipf_mp->b_cont = next_mp;
11566 			freeb(mp);
11567 			continue;
11568 		}
11569 		mp->b_cont = NULL;
11570 		IP_REASS_SET_START(mp, start);
11571 		IP_REASS_SET_END(mp, end);
11572 		if (!ipf->ipf_tail_mp) {
11573 			ipf->ipf_tail_mp = mp;
11574 			ipf->ipf_mp->b_cont = mp;
11575 			if (start == 0 || !more) {
11576 				ipf->ipf_hole_cnt = 1;
11577 				/*
11578 				 * if the first fragment comes in more than one
11579 				 * mblk, this loop will be executed for each
11580 				 * mblk. Need to adjust hole count so exiting
11581 				 * this routine will leave hole count at 1.
11582 				 */
11583 				if (next_mp)
11584 					ipf->ipf_hole_cnt++;
11585 			} else
11586 				ipf->ipf_hole_cnt = 2;
11587 			continue;
11588 		} else if (ipf->ipf_last_frag_seen && !more &&
11589 			    !pkt_boundary_checked) {
11590 			/*
11591 			 * We check datagram boundary only if this fragment
11592 			 * claims to be the last fragment and we have seen a
11593 			 * last fragment in the past too. We do this only
11594 			 * once for a given fragment.
11595 			 *
11596 			 * start cannot be 0 here as fragments with start=0
11597 			 * and MF=0 gets handled as a complete packet. These
11598 			 * fragments should not reach here.
11599 			 */
11600 
11601 			if (start + msgdsize(mp) !=
11602 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11603 				/*
11604 				 * We have two fragments both of which claim
11605 				 * to be the last fragment but gives conflicting
11606 				 * information about the whole datagram size.
11607 				 * Something fishy is going on. Drop the
11608 				 * fragment and free up the reassembly list.
11609 				 */
11610 				return (IP_REASS_FAILED);
11611 			}
11612 
11613 			/*
11614 			 * We shouldn't come to this code block again for this
11615 			 * particular fragment.
11616 			 */
11617 			pkt_boundary_checked = B_TRUE;
11618 		}
11619 
11620 		/* New stuff at or beyond tail? */
11621 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11622 		if (start >= offset) {
11623 			if (ipf->ipf_last_frag_seen) {
11624 				/* current fragment is beyond last fragment */
11625 				return (IP_REASS_FAILED);
11626 			}
11627 			/* Link it on end. */
11628 			ipf->ipf_tail_mp->b_cont = mp;
11629 			ipf->ipf_tail_mp = mp;
11630 			if (more) {
11631 				if (start != offset)
11632 					ipf->ipf_hole_cnt++;
11633 			} else if (start == offset && next_mp == NULL)
11634 					ipf->ipf_hole_cnt--;
11635 			continue;
11636 		}
11637 		mp1 = ipf->ipf_mp->b_cont;
11638 		offset = IP_REASS_START(mp1);
11639 		/* New stuff at the front? */
11640 		if (start < offset) {
11641 			if (start == 0) {
11642 				if (end >= offset) {
11643 					/* Nailed the hole at the begining. */
11644 					ipf->ipf_hole_cnt--;
11645 				}
11646 			} else if (end < offset) {
11647 				/*
11648 				 * A hole, stuff, and a hole where there used
11649 				 * to be just a hole.
11650 				 */
11651 				ipf->ipf_hole_cnt++;
11652 			}
11653 			mp->b_cont = mp1;
11654 			/* Check for overlap. */
11655 			while (end > offset) {
11656 				if (end < IP_REASS_END(mp1)) {
11657 					mp->b_wptr -= end - offset;
11658 					IP_REASS_SET_END(mp, offset);
11659 					if (ill->ill_isv6) {
11660 						BUMP_MIB(ill->ill_ip6_mib,
11661 						    ipv6ReasmPartDups);
11662 					} else {
11663 						BUMP_MIB(&ip_mib,
11664 						    ipReasmPartDups);
11665 					}
11666 					break;
11667 				}
11668 				/* Did we cover another hole? */
11669 				if ((mp1->b_cont &&
11670 				    IP_REASS_END(mp1) !=
11671 				    IP_REASS_START(mp1->b_cont) &&
11672 				    end >= IP_REASS_START(mp1->b_cont)) ||
11673 				    (!ipf->ipf_last_frag_seen && !more)) {
11674 					ipf->ipf_hole_cnt--;
11675 				}
11676 				/* Clip out mp1. */
11677 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11678 					/*
11679 					 * After clipping out mp1, this guy
11680 					 * is now hanging off the end.
11681 					 */
11682 					ipf->ipf_tail_mp = mp;
11683 				}
11684 				IP_REASS_SET_START(mp1, 0);
11685 				IP_REASS_SET_END(mp1, 0);
11686 				/* Subtract byte count */
11687 				ipf->ipf_count -= mp1->b_datap->db_lim -
11688 				    mp1->b_datap->db_base;
11689 				freeb(mp1);
11690 				if (ill->ill_isv6) {
11691 					BUMP_MIB(ill->ill_ip6_mib,
11692 					    ipv6ReasmPartDups);
11693 				} else {
11694 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11695 				}
11696 				mp1 = mp->b_cont;
11697 				if (!mp1)
11698 					break;
11699 				offset = IP_REASS_START(mp1);
11700 			}
11701 			ipf->ipf_mp->b_cont = mp;
11702 			continue;
11703 		}
11704 		/*
11705 		 * The new piece starts somewhere between the start of the head
11706 		 * and before the end of the tail.
11707 		 */
11708 		for (; mp1; mp1 = mp1->b_cont) {
11709 			offset = IP_REASS_END(mp1);
11710 			if (start < offset) {
11711 				if (end <= offset) {
11712 					/* Nothing new. */
11713 					IP_REASS_SET_START(mp, 0);
11714 					IP_REASS_SET_END(mp, 0);
11715 					/* Subtract byte count */
11716 					ipf->ipf_count -= mp->b_datap->db_lim -
11717 					    mp->b_datap->db_base;
11718 					if (incr_dups) {
11719 						ipf->ipf_num_dups++;
11720 						incr_dups = B_FALSE;
11721 					}
11722 					freeb(mp);
11723 					if (ill->ill_isv6) {
11724 						BUMP_MIB(ill->ill_ip6_mib,
11725 						    ipv6ReasmDuplicates);
11726 					} else {
11727 						BUMP_MIB(&ip_mib,
11728 						    ipReasmDuplicates);
11729 					}
11730 					break;
11731 				}
11732 				/*
11733 				 * Trim redundant stuff off beginning of new
11734 				 * piece.
11735 				 */
11736 				IP_REASS_SET_START(mp, offset);
11737 				mp->b_rptr += offset - start;
11738 				if (ill->ill_isv6) {
11739 					BUMP_MIB(ill->ill_ip6_mib,
11740 					    ipv6ReasmPartDups);
11741 				} else {
11742 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11743 				}
11744 				start = offset;
11745 				if (!mp1->b_cont) {
11746 					/*
11747 					 * After trimming, this guy is now
11748 					 * hanging off the end.
11749 					 */
11750 					mp1->b_cont = mp;
11751 					ipf->ipf_tail_mp = mp;
11752 					if (!more) {
11753 						ipf->ipf_hole_cnt--;
11754 					}
11755 					break;
11756 				}
11757 			}
11758 			if (start >= IP_REASS_START(mp1->b_cont))
11759 				continue;
11760 			/* Fill a hole */
11761 			if (start > offset)
11762 				ipf->ipf_hole_cnt++;
11763 			mp->b_cont = mp1->b_cont;
11764 			mp1->b_cont = mp;
11765 			mp1 = mp->b_cont;
11766 			offset = IP_REASS_START(mp1);
11767 			if (end >= offset) {
11768 				ipf->ipf_hole_cnt--;
11769 				/* Check for overlap. */
11770 				while (end > offset) {
11771 					if (end < IP_REASS_END(mp1)) {
11772 						mp->b_wptr -= end - offset;
11773 						IP_REASS_SET_END(mp, offset);
11774 						/*
11775 						 * TODO we might bump
11776 						 * this up twice if there is
11777 						 * overlap at both ends.
11778 						 */
11779 						if (ill->ill_isv6) {
11780 							BUMP_MIB(
11781 							    ill->ill_ip6_mib,
11782 							    ipv6ReasmPartDups);
11783 						} else {
11784 							BUMP_MIB(&ip_mib,
11785 							    ipReasmPartDups);
11786 						}
11787 						break;
11788 					}
11789 					/* Did we cover another hole? */
11790 					if ((mp1->b_cont &&
11791 					    IP_REASS_END(mp1)
11792 					    != IP_REASS_START(mp1->b_cont) &&
11793 					    end >=
11794 					    IP_REASS_START(mp1->b_cont)) ||
11795 					    (!ipf->ipf_last_frag_seen &&
11796 					    !more)) {
11797 						ipf->ipf_hole_cnt--;
11798 					}
11799 					/* Clip out mp1. */
11800 					if ((mp->b_cont = mp1->b_cont) ==
11801 					    NULL) {
11802 						/*
11803 						 * After clipping out mp1,
11804 						 * this guy is now hanging
11805 						 * off the end.
11806 						 */
11807 						ipf->ipf_tail_mp = mp;
11808 					}
11809 					IP_REASS_SET_START(mp1, 0);
11810 					IP_REASS_SET_END(mp1, 0);
11811 					/* Subtract byte count */
11812 					ipf->ipf_count -=
11813 					    mp1->b_datap->db_lim -
11814 					    mp1->b_datap->db_base;
11815 					freeb(mp1);
11816 					if (ill->ill_isv6) {
11817 						BUMP_MIB(ill->ill_ip6_mib,
11818 						    ipv6ReasmPartDups);
11819 					} else {
11820 						BUMP_MIB(&ip_mib,
11821 						    ipReasmPartDups);
11822 					}
11823 					mp1 = mp->b_cont;
11824 					if (!mp1)
11825 						break;
11826 					offset = IP_REASS_START(mp1);
11827 				}
11828 			}
11829 			break;
11830 		}
11831 	} while (start = end, mp = next_mp);
11832 
11833 	/* Fragment just processed could be the last one. Remember this fact */
11834 	if (!more)
11835 		ipf->ipf_last_frag_seen = B_TRUE;
11836 
11837 	/* Still got holes? */
11838 	if (ipf->ipf_hole_cnt)
11839 		return (IP_REASS_PARTIAL);
11840 	/* Clean up overloaded fields to avoid upstream disasters. */
11841 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11842 		IP_REASS_SET_START(mp1, 0);
11843 		IP_REASS_SET_END(mp1, 0);
11844 	}
11845 	return (IP_REASS_COMPLETE);
11846 }
11847 
11848 /*
11849  * ipsec processing for the fast path, used for input UDP Packets
11850  */
11851 static boolean_t
11852 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11853     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11854 {
11855 	uint32_t	ill_index;
11856 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11857 
11858 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11859 	/* The ill_index of the incoming ILL */
11860 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11861 
11862 	/* pass packet up to the transport */
11863 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11864 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11865 		    NULL, mctl_present);
11866 		if (*first_mpp == NULL) {
11867 			return (B_FALSE);
11868 		}
11869 	}
11870 
11871 	/* Initiate IPPF processing for fastpath UDP */
11872 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11873 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11874 		if (*mpp == NULL) {
11875 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11876 			    "deferred/dropped during IPPF processing\n"));
11877 			return (B_FALSE);
11878 		}
11879 	}
11880 	/*
11881 	 * We make the checks as below since we are in the fast path
11882 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11883 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11884 	 */
11885 	if (connp->conn_recvif || connp->conn_recvslla ||
11886 	    connp->conn_ipv6_recvpktinfo) {
11887 		if (connp->conn_recvif ||
11888 		    connp->conn_ipv6_recvpktinfo) {
11889 			in_flags = IPF_RECVIF;
11890 		}
11891 		if (connp->conn_recvslla) {
11892 			in_flags |= IPF_RECVSLLA;
11893 		}
11894 		/*
11895 		 * since in_flags are being set ill will be
11896 		 * referenced in ip_add_info, so it better not
11897 		 * be NULL.
11898 		 */
11899 		/*
11900 		 * the actual data will be contained in b_cont
11901 		 * upon successful return of the following call.
11902 		 * If the call fails then the original mblk is
11903 		 * returned.
11904 		 */
11905 		*mpp = ip_add_info(*mpp, ill, in_flags);
11906 	}
11907 
11908 	return (B_TRUE);
11909 }
11910 
11911 /*
11912  * Fragmentation reassembly.  Each ILL has a hash table for
11913  * queuing packets undergoing reassembly for all IPIFs
11914  * associated with the ILL.  The hash is based on the packet
11915  * IP ident field.  The ILL frag hash table was allocated
11916  * as a timer block at the time the ILL was created.  Whenever
11917  * there is anything on the reassembly queue, the timer will
11918  * be running.  Returns B_TRUE if successful else B_FALSE;
11919  * frees mp on failure.
11920  */
11921 static boolean_t
11922 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11923     uint32_t *cksum_val, uint16_t *cksum_flags)
11924 {
11925 	uint32_t	frag_offset_flags;
11926 	ill_t		*ill = (ill_t *)q->q_ptr;
11927 	mblk_t		*mp = *mpp;
11928 	mblk_t		*t_mp;
11929 	ipaddr_t	dst;
11930 	uint8_t		proto = ipha->ipha_protocol;
11931 	uint32_t	sum_val;
11932 	uint16_t	sum_flags;
11933 	ipf_t		*ipf;
11934 	ipf_t		**ipfp;
11935 	ipfb_t		*ipfb;
11936 	uint16_t	ident;
11937 	uint32_t	offset;
11938 	ipaddr_t	src;
11939 	uint_t		hdr_length;
11940 	uint32_t	end;
11941 	mblk_t		*mp1;
11942 	mblk_t		*tail_mp;
11943 	size_t		count;
11944 	size_t		msg_len;
11945 	uint8_t		ecn_info = 0;
11946 	uint32_t	packet_size;
11947 	boolean_t	pruned = B_FALSE;
11948 
11949 	if (cksum_val != NULL)
11950 		*cksum_val = 0;
11951 	if (cksum_flags != NULL)
11952 		*cksum_flags = 0;
11953 
11954 	/*
11955 	 * Drop the fragmented as early as possible, if
11956 	 * we don't have resource(s) to re-assemble.
11957 	 */
11958 	if (ip_reass_queue_bytes == 0) {
11959 		freemsg(mp);
11960 		return (B_FALSE);
11961 	}
11962 
11963 	/* Check for fragmentation offset; return if there's none */
11964 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
11965 	    (IPH_MF | IPH_OFFSET)) == 0)
11966 		return (B_TRUE);
11967 
11968 	/*
11969 	 * We utilize hardware computed checksum info only for UDP since
11970 	 * IP fragmentation is a normal occurence for the protocol.  In
11971 	 * addition, checksum offload support for IP fragments carrying
11972 	 * UDP payload is commonly implemented across network adapters.
11973 	 */
11974 	ASSERT(ill != NULL);
11975 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
11976 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
11977 		mblk_t *mp1 = mp->b_cont;
11978 		int32_t len;
11979 
11980 		/* Record checksum information from the packet */
11981 		sum_val = (uint32_t)DB_CKSUM16(mp);
11982 		sum_flags = DB_CKSUMFLAGS(mp);
11983 
11984 		/* IP payload offset from beginning of mblk */
11985 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
11986 
11987 		if ((sum_flags & HCK_PARTIALCKSUM) &&
11988 		    (mp1 == NULL || mp1->b_cont == NULL) &&
11989 		    offset >= DB_CKSUMSTART(mp) &&
11990 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
11991 			uint32_t adj;
11992 			/*
11993 			 * Partial checksum has been calculated by hardware
11994 			 * and attached to the packet; in addition, any
11995 			 * prepended extraneous data is even byte aligned.
11996 			 * If any such data exists, we adjust the checksum;
11997 			 * this would also handle any postpended data.
11998 			 */
11999 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12000 			    mp, mp1, len, adj);
12001 
12002 			/* One's complement subtract extraneous checksum */
12003 			if (adj >= sum_val)
12004 				sum_val = ~(adj - sum_val) & 0xFFFF;
12005 			else
12006 				sum_val -= adj;
12007 		}
12008 	} else {
12009 		sum_val = 0;
12010 		sum_flags = 0;
12011 	}
12012 
12013 	/* Clear hardware checksumming flag */
12014 	DB_CKSUMFLAGS(mp) = 0;
12015 
12016 	ident = ipha->ipha_ident;
12017 	offset = (frag_offset_flags << 3) & 0xFFFF;
12018 	src = ipha->ipha_src;
12019 	dst = ipha->ipha_dst;
12020 	hdr_length = IPH_HDR_LENGTH(ipha);
12021 	end = ntohs(ipha->ipha_length) - hdr_length;
12022 
12023 	/* If end == 0 then we have a packet with no data, so just free it */
12024 	if (end == 0) {
12025 		freemsg(mp);
12026 		return (B_FALSE);
12027 	}
12028 
12029 	/* Record the ECN field info. */
12030 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12031 	if (offset != 0) {
12032 		/*
12033 		 * If this isn't the first piece, strip the header, and
12034 		 * add the offset to the end value.
12035 		 */
12036 		mp->b_rptr += hdr_length;
12037 		end += offset;
12038 	}
12039 
12040 	msg_len = MBLKSIZE(mp);
12041 	tail_mp = mp;
12042 	while (tail_mp->b_cont != NULL) {
12043 		tail_mp = tail_mp->b_cont;
12044 		msg_len += MBLKSIZE(tail_mp);
12045 	}
12046 
12047 	/* If the reassembly list for this ILL will get too big, prune it */
12048 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12049 	    ip_reass_queue_bytes) {
12050 		ill_frag_prune(ill,
12051 		    (ip_reass_queue_bytes < msg_len) ? 0 :
12052 		    (ip_reass_queue_bytes - msg_len));
12053 		pruned = B_TRUE;
12054 	}
12055 
12056 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12057 	mutex_enter(&ipfb->ipfb_lock);
12058 
12059 	ipfp = &ipfb->ipfb_ipf;
12060 	/* Try to find an existing fragment queue for this packet. */
12061 	for (;;) {
12062 		ipf = ipfp[0];
12063 		if (ipf != NULL) {
12064 			/*
12065 			 * It has to match on ident and src/dst address.
12066 			 */
12067 			if (ipf->ipf_ident == ident &&
12068 			    ipf->ipf_src == src &&
12069 			    ipf->ipf_dst == dst &&
12070 			    ipf->ipf_protocol == proto) {
12071 				/*
12072 				 * If we have received too many
12073 				 * duplicate fragments for this packet
12074 				 * free it.
12075 				 */
12076 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12077 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12078 					freemsg(mp);
12079 					mutex_exit(&ipfb->ipfb_lock);
12080 					return (B_FALSE);
12081 				}
12082 				/* Found it. */
12083 				break;
12084 			}
12085 			ipfp = &ipf->ipf_hash_next;
12086 			continue;
12087 		}
12088 
12089 		/*
12090 		 * If we pruned the list, do we want to store this new
12091 		 * fragment?. We apply an optimization here based on the
12092 		 * fact that most fragments will be received in order.
12093 		 * So if the offset of this incoming fragment is zero,
12094 		 * it is the first fragment of a new packet. We will
12095 		 * keep it.  Otherwise drop the fragment, as we have
12096 		 * probably pruned the packet already (since the
12097 		 * packet cannot be found).
12098 		 */
12099 		if (pruned && offset != 0) {
12100 			mutex_exit(&ipfb->ipfb_lock);
12101 			freemsg(mp);
12102 			return (B_FALSE);
12103 		}
12104 
12105 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12106 			/*
12107 			 * Too many fragmented packets in this hash
12108 			 * bucket. Free the oldest.
12109 			 */
12110 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12111 		}
12112 
12113 		/* New guy.  Allocate a frag message. */
12114 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12115 		if (mp1 == NULL) {
12116 			BUMP_MIB(&ip_mib, ipInDiscards);
12117 			freemsg(mp);
12118 reass_done:
12119 			mutex_exit(&ipfb->ipfb_lock);
12120 			return (B_FALSE);
12121 		}
12122 
12123 
12124 		BUMP_MIB(&ip_mib, ipReasmReqds);
12125 		mp1->b_cont = mp;
12126 
12127 		/* Initialize the fragment header. */
12128 		ipf = (ipf_t *)mp1->b_rptr;
12129 		ipf->ipf_mp = mp1;
12130 		ipf->ipf_ptphn = ipfp;
12131 		ipfp[0] = ipf;
12132 		ipf->ipf_hash_next = NULL;
12133 		ipf->ipf_ident = ident;
12134 		ipf->ipf_protocol = proto;
12135 		ipf->ipf_src = src;
12136 		ipf->ipf_dst = dst;
12137 		ipf->ipf_nf_hdr_len = 0;
12138 		/* Record reassembly start time. */
12139 		ipf->ipf_timestamp = gethrestime_sec();
12140 		/* Record ipf generation and account for frag header */
12141 		ipf->ipf_gen = ill->ill_ipf_gen++;
12142 		ipf->ipf_count = MBLKSIZE(mp1);
12143 		ipf->ipf_last_frag_seen = B_FALSE;
12144 		ipf->ipf_ecn = ecn_info;
12145 		ipf->ipf_num_dups = 0;
12146 		ipfb->ipfb_frag_pkts++;
12147 		ipf->ipf_checksum = 0;
12148 		ipf->ipf_checksum_flags = 0;
12149 
12150 		/* Store checksum value in fragment header */
12151 		if (sum_flags != 0) {
12152 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12153 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12154 			ipf->ipf_checksum = sum_val;
12155 			ipf->ipf_checksum_flags = sum_flags;
12156 		}
12157 
12158 		/*
12159 		 * We handle reassembly two ways.  In the easy case,
12160 		 * where all the fragments show up in order, we do
12161 		 * minimal bookkeeping, and just clip new pieces on
12162 		 * the end.  If we ever see a hole, then we go off
12163 		 * to ip_reassemble which has to mark the pieces and
12164 		 * keep track of the number of holes, etc.  Obviously,
12165 		 * the point of having both mechanisms is so we can
12166 		 * handle the easy case as efficiently as possible.
12167 		 */
12168 		if (offset == 0) {
12169 			/* Easy case, in-order reassembly so far. */
12170 			ipf->ipf_count += msg_len;
12171 			ipf->ipf_tail_mp = tail_mp;
12172 			/*
12173 			 * Keep track of next expected offset in
12174 			 * ipf_end.
12175 			 */
12176 			ipf->ipf_end = end;
12177 			ipf->ipf_nf_hdr_len = hdr_length;
12178 		} else {
12179 			/* Hard case, hole at the beginning. */
12180 			ipf->ipf_tail_mp = NULL;
12181 			/*
12182 			 * ipf_end == 0 means that we have given up
12183 			 * on easy reassembly.
12184 			 */
12185 			ipf->ipf_end = 0;
12186 
12187 			/* Forget checksum offload from now on */
12188 			ipf->ipf_checksum_flags = 0;
12189 
12190 			/*
12191 			 * ipf_hole_cnt is set by ip_reassemble.
12192 			 * ipf_count is updated by ip_reassemble.
12193 			 * No need to check for return value here
12194 			 * as we don't expect reassembly to complete
12195 			 * or fail for the first fragment itself.
12196 			 */
12197 			(void) ip_reassemble(mp, ipf,
12198 			    (frag_offset_flags & IPH_OFFSET) << 3,
12199 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12200 		}
12201 		/* Update per ipfb and ill byte counts */
12202 		ipfb->ipfb_count += ipf->ipf_count;
12203 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12204 		ill->ill_frag_count += ipf->ipf_count;
12205 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12206 		/* If the frag timer wasn't already going, start it. */
12207 		mutex_enter(&ill->ill_lock);
12208 		ill_frag_timer_start(ill);
12209 		mutex_exit(&ill->ill_lock);
12210 		goto reass_done;
12211 	}
12212 
12213 	/*
12214 	 * If the packet's flag has changed (it could be coming up
12215 	 * from an interface different than the previous, therefore
12216 	 * possibly different checksum capability), then forget about
12217 	 * any stored checksum states.  Otherwise add the value to
12218 	 * the existing one stored in the fragment header.
12219 	 */
12220 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12221 		sum_val += ipf->ipf_checksum;
12222 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12223 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12224 		ipf->ipf_checksum = sum_val;
12225 	} else if (ipf->ipf_checksum_flags != 0) {
12226 		/* Forget checksum offload from now on */
12227 		ipf->ipf_checksum_flags = 0;
12228 	}
12229 
12230 	/*
12231 	 * We have a new piece of a datagram which is already being
12232 	 * reassembled.  Update the ECN info if all IP fragments
12233 	 * are ECN capable.  If there is one which is not, clear
12234 	 * all the info.  If there is at least one which has CE
12235 	 * code point, IP needs to report that up to transport.
12236 	 */
12237 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12238 		if (ecn_info == IPH_ECN_CE)
12239 			ipf->ipf_ecn = IPH_ECN_CE;
12240 	} else {
12241 		ipf->ipf_ecn = IPH_ECN_NECT;
12242 	}
12243 	if (offset && ipf->ipf_end == offset) {
12244 		/* The new fragment fits at the end */
12245 		ipf->ipf_tail_mp->b_cont = mp;
12246 		/* Update the byte count */
12247 		ipf->ipf_count += msg_len;
12248 		/* Update per ipfb and ill byte counts */
12249 		ipfb->ipfb_count += msg_len;
12250 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12251 		ill->ill_frag_count += msg_len;
12252 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12253 		if (frag_offset_flags & IPH_MF) {
12254 			/* More to come. */
12255 			ipf->ipf_end = end;
12256 			ipf->ipf_tail_mp = tail_mp;
12257 			goto reass_done;
12258 		}
12259 	} else {
12260 		/* Go do the hard cases. */
12261 		int ret;
12262 
12263 		if (offset == 0)
12264 			ipf->ipf_nf_hdr_len = hdr_length;
12265 
12266 		/* Save current byte count */
12267 		count = ipf->ipf_count;
12268 		ret = ip_reassemble(mp, ipf,
12269 		    (frag_offset_flags & IPH_OFFSET) << 3,
12270 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12271 		/* Count of bytes added and subtracted (freeb()ed) */
12272 		count = ipf->ipf_count - count;
12273 		if (count) {
12274 			/* Update per ipfb and ill byte counts */
12275 			ipfb->ipfb_count += count;
12276 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12277 			ill->ill_frag_count += count;
12278 			ASSERT(ill->ill_frag_count > 0);
12279 		}
12280 		if (ret == IP_REASS_PARTIAL) {
12281 			goto reass_done;
12282 		} else if (ret == IP_REASS_FAILED) {
12283 			/* Reassembly failed. Free up all resources */
12284 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12285 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12286 				IP_REASS_SET_START(t_mp, 0);
12287 				IP_REASS_SET_END(t_mp, 0);
12288 			}
12289 			freemsg(mp);
12290 			goto reass_done;
12291 		}
12292 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12293 	}
12294 	/*
12295 	 * We have completed reassembly.  Unhook the frag header from
12296 	 * the reassembly list.
12297 	 *
12298 	 * Before we free the frag header, record the ECN info
12299 	 * to report back to the transport.
12300 	 */
12301 	ecn_info = ipf->ipf_ecn;
12302 	BUMP_MIB(&ip_mib, ipReasmOKs);
12303 	ipfp = ipf->ipf_ptphn;
12304 
12305 	/* We need to supply these to caller */
12306 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12307 		sum_val = ipf->ipf_checksum;
12308 	else
12309 		sum_val = 0;
12310 
12311 	mp1 = ipf->ipf_mp;
12312 	count = ipf->ipf_count;
12313 	ipf = ipf->ipf_hash_next;
12314 	if (ipf != NULL)
12315 		ipf->ipf_ptphn = ipfp;
12316 	ipfp[0] = ipf;
12317 	ill->ill_frag_count -= count;
12318 	ASSERT(ipfb->ipfb_count >= count);
12319 	ipfb->ipfb_count -= count;
12320 	ipfb->ipfb_frag_pkts--;
12321 	mutex_exit(&ipfb->ipfb_lock);
12322 	/* Ditch the frag header. */
12323 	mp = mp1->b_cont;
12324 
12325 	freeb(mp1);
12326 
12327 	/* Restore original IP length in header. */
12328 	packet_size = (uint32_t)msgdsize(mp);
12329 	if (packet_size > IP_MAXPACKET) {
12330 		freemsg(mp);
12331 		BUMP_MIB(&ip_mib, ipInHdrErrors);
12332 		return (B_FALSE);
12333 	}
12334 
12335 	if (DB_REF(mp) > 1) {
12336 		mblk_t *mp2 = copymsg(mp);
12337 
12338 		freemsg(mp);
12339 		if (mp2 == NULL) {
12340 			BUMP_MIB(&ip_mib, ipInDiscards);
12341 			return (B_FALSE);
12342 		}
12343 		mp = mp2;
12344 	}
12345 	ipha = (ipha_t *)mp->b_rptr;
12346 
12347 	ipha->ipha_length = htons((uint16_t)packet_size);
12348 	/* We're now complete, zip the frag state */
12349 	ipha->ipha_fragment_offset_and_flags = 0;
12350 	/* Record the ECN info. */
12351 	ipha->ipha_type_of_service &= 0xFC;
12352 	ipha->ipha_type_of_service |= ecn_info;
12353 	*mpp = mp;
12354 
12355 	/* Reassembly is successful; return checksum information if needed */
12356 	if (cksum_val != NULL)
12357 		*cksum_val = sum_val;
12358 	if (cksum_flags != NULL)
12359 		*cksum_flags = sum_flags;
12360 
12361 	return (B_TRUE);
12362 }
12363 
12364 /*
12365  * Perform ip header check sum update local options.
12366  * return B_TRUE if all is well, else return B_FALSE and release
12367  * the mp. caller is responsible for decrementing ire ref cnt.
12368  */
12369 static boolean_t
12370 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12371 {
12372 	mblk_t		*first_mp;
12373 	boolean_t	mctl_present;
12374 	uint16_t	sum;
12375 
12376 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12377 	/*
12378 	 * Don't do the checksum if it has gone through AH/ESP
12379 	 * processing.
12380 	 */
12381 	if (!mctl_present) {
12382 		sum = ip_csum_hdr(ipha);
12383 		if (sum != 0) {
12384 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12385 			freemsg(first_mp);
12386 			return (B_FALSE);
12387 		}
12388 	}
12389 
12390 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12391 		if (mctl_present)
12392 			freeb(first_mp);
12393 		return (B_FALSE);
12394 	}
12395 
12396 	return (B_TRUE);
12397 }
12398 
12399 /*
12400  * All udp packet are delivered to the local host via this routine.
12401  */
12402 void
12403 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12404     ill_t *recv_ill)
12405 {
12406 	uint32_t	sum;
12407 	uint32_t	u1;
12408 	boolean_t	mctl_present;
12409 	conn_t		*connp;
12410 	mblk_t		*first_mp;
12411 	uint16_t	*up;
12412 	ill_t		*ill = (ill_t *)q->q_ptr;
12413 	uint16_t	reass_hck_flags = 0;
12414 
12415 #define	rptr    ((uchar_t *)ipha)
12416 
12417 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12418 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12419 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12420 
12421 	/*
12422 	 * FAST PATH for udp packets
12423 	 */
12424 
12425 	/* u1 is # words of IP options */
12426 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12427 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12428 
12429 	/* IP options present */
12430 	if (u1 != 0)
12431 		goto ipoptions;
12432 
12433 	/* Check the IP header checksum.  */
12434 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12435 		/* Clear the IP header h/w cksum flag */
12436 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12437 	} else {
12438 #define	uph	((uint16_t *)ipha)
12439 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12440 		    uph[6] + uph[7] + uph[8] + uph[9];
12441 #undef	uph
12442 		/* finish doing IP checksum */
12443 		sum = (sum & 0xFFFF) + (sum >> 16);
12444 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12445 		/*
12446 		 * Don't verify header checksum if this packet is coming
12447 		 * back from AH/ESP as we already did it.
12448 		 */
12449 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12450 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12451 			freemsg(first_mp);
12452 			return;
12453 		}
12454 	}
12455 
12456 	/*
12457 	 * Count for SNMP of inbound packets for ire.
12458 	 * if mctl is present this might be a secure packet and
12459 	 * has already been counted for in ip_proto_input().
12460 	 */
12461 	if (!mctl_present) {
12462 		UPDATE_IB_PKT_COUNT(ire);
12463 		ire->ire_last_used_time = lbolt;
12464 	}
12465 
12466 	/* packet part of fragmented IP packet? */
12467 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12468 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12469 		goto fragmented;
12470 	}
12471 
12472 	/* u1 = IP header length (20 bytes) */
12473 	u1 = IP_SIMPLE_HDR_LENGTH;
12474 
12475 	/* packet does not contain complete IP & UDP headers */
12476 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12477 		goto udppullup;
12478 
12479 	/* up points to UDP header */
12480 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12481 #define	iphs    ((uint16_t *)ipha)
12482 
12483 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12484 	if (up[3] != 0) {
12485 		mblk_t *mp1 = mp->b_cont;
12486 		boolean_t cksum_err;
12487 		uint16_t hck_flags = 0;
12488 
12489 		/* Pseudo-header checksum */
12490 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12491 		    iphs[9] + up[2];
12492 
12493 		/*
12494 		 * Revert to software checksum calculation if the interface
12495 		 * isn't capable of checksum offload or if IPsec is present.
12496 		 */
12497 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12498 			hck_flags = DB_CKSUMFLAGS(mp);
12499 
12500 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12501 			IP_STAT(ip_in_sw_cksum);
12502 
12503 		IP_CKSUM_RECV(hck_flags, u1,
12504 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12505 		    (int32_t)((uchar_t *)up - rptr),
12506 		    mp, mp1, cksum_err);
12507 
12508 		if (cksum_err) {
12509 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12510 
12511 			if (hck_flags & HCK_FULLCKSUM)
12512 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12513 			else if (hck_flags & HCK_PARTIALCKSUM)
12514 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12515 			else
12516 				IP_STAT(ip_udp_in_sw_cksum_err);
12517 
12518 			freemsg(first_mp);
12519 			return;
12520 		}
12521 	}
12522 
12523 	/* Non-fragmented broadcast or multicast packet? */
12524 	if (ire->ire_type == IRE_BROADCAST)
12525 		goto udpslowpath;
12526 
12527 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12528 	    ire->ire_zoneid)) != NULL) {
12529 		ASSERT(connp->conn_upq != NULL);
12530 		IP_STAT(ip_udp_fast_path);
12531 
12532 		if (CONN_UDP_FLOWCTLD(connp)) {
12533 			freemsg(mp);
12534 			BUMP_MIB(&ip_mib, udpInOverflows);
12535 		} else {
12536 			if (!mctl_present) {
12537 				BUMP_MIB(&ip_mib, ipInDelivers);
12538 			}
12539 			/*
12540 			 * mp and first_mp can change.
12541 			 */
12542 			if (ip_udp_check(q, connp, recv_ill,
12543 			    ipha, &mp, &first_mp, mctl_present)) {
12544 				/* Send it upstream */
12545 				CONN_UDP_RECV(connp, mp);
12546 			}
12547 		}
12548 		/*
12549 		 * freeb() cannot deal with null mblk being passed
12550 		 * in and first_mp can be set to null in the call
12551 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12552 		 */
12553 		if (mctl_present && first_mp != NULL) {
12554 			freeb(first_mp);
12555 		}
12556 		CONN_DEC_REF(connp);
12557 		return;
12558 	}
12559 
12560 	/*
12561 	 * if we got here we know the packet is not fragmented and
12562 	 * has no options. The classifier could not find a conn_t and
12563 	 * most likely its an icmp packet so send it through slow path.
12564 	 */
12565 
12566 	goto udpslowpath;
12567 
12568 ipoptions:
12569 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12570 		goto slow_done;
12571 	}
12572 
12573 	UPDATE_IB_PKT_COUNT(ire);
12574 	ire->ire_last_used_time = lbolt;
12575 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12576 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12577 fragmented:
12578 		/*
12579 		 * "sum" and "reass_hck_flags" are non-zero if the
12580 		 * reassembled packet has a valid hardware computed
12581 		 * checksum information associated with it.
12582 		 */
12583 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12584 			goto slow_done;
12585 		/*
12586 		 * Make sure that first_mp points back to mp as
12587 		 * the mp we came in with could have changed in
12588 		 * ip_rput_fragment().
12589 		 */
12590 		ASSERT(!mctl_present);
12591 		ipha = (ipha_t *)mp->b_rptr;
12592 		first_mp = mp;
12593 	}
12594 
12595 	/* Now we have a complete datagram, destined for this machine. */
12596 	u1 = IPH_HDR_LENGTH(ipha);
12597 	/* Pull up the UDP header, if necessary. */
12598 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12599 udppullup:
12600 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12601 			BUMP_MIB(&ip_mib, ipInDiscards);
12602 			freemsg(first_mp);
12603 			goto slow_done;
12604 		}
12605 		ipha = (ipha_t *)mp->b_rptr;
12606 	}
12607 
12608 	/*
12609 	 * Validate the checksum for the reassembled packet; for the
12610 	 * pullup case we calculate the payload checksum in software.
12611 	 */
12612 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12613 	if (up[3] != 0) {
12614 		boolean_t cksum_err;
12615 
12616 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12617 			IP_STAT(ip_in_sw_cksum);
12618 
12619 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12620 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12621 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12622 		    iphs[9] + up[2], sum, cksum_err);
12623 
12624 		if (cksum_err) {
12625 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12626 
12627 			if (reass_hck_flags & HCK_FULLCKSUM)
12628 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12629 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12630 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12631 			else
12632 				IP_STAT(ip_udp_in_sw_cksum_err);
12633 
12634 			freemsg(first_mp);
12635 			goto slow_done;
12636 		}
12637 	}
12638 udpslowpath:
12639 
12640 	/* Clear hardware checksum flag to be safe */
12641 	DB_CKSUMFLAGS(mp) = 0;
12642 
12643 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12644 	    (ire->ire_type == IRE_BROADCAST),
12645 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12646 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12647 
12648 slow_done:
12649 	IP_STAT(ip_udp_slow_path);
12650 	return;
12651 
12652 #undef  iphs
12653 #undef  rptr
12654 }
12655 
12656 /* ARGSUSED */
12657 static mblk_t *
12658 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12659     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12660     ill_rx_ring_t *ill_ring)
12661 {
12662 	conn_t		*connp;
12663 	uint32_t	sum;
12664 	uint32_t	u1;
12665 	uint16_t	*up;
12666 	int		offset;
12667 	ssize_t		len;
12668 	mblk_t		*mp1;
12669 	boolean_t	syn_present = B_FALSE;
12670 	tcph_t		*tcph;
12671 	uint_t		ip_hdr_len;
12672 	ill_t		*ill = (ill_t *)q->q_ptr;
12673 	zoneid_t	zoneid = ire->ire_zoneid;
12674 	boolean_t	cksum_err;
12675 	uint16_t	hck_flags = 0;
12676 
12677 #define	rptr	((uchar_t *)ipha)
12678 
12679 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12680 
12681 	/*
12682 	 * FAST PATH for tcp packets
12683 	 */
12684 
12685 	/* u1 is # words of IP options */
12686 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12687 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12688 
12689 	/* IP options present */
12690 	if (u1) {
12691 		goto ipoptions;
12692 	} else {
12693 		/* Check the IP header checksum.  */
12694 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12695 			/* Clear the IP header h/w cksum flag */
12696 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12697 		} else {
12698 #define	uph	((uint16_t *)ipha)
12699 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12700 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12701 #undef	uph
12702 			/* finish doing IP checksum */
12703 			sum = (sum & 0xFFFF) + (sum >> 16);
12704 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12705 			/*
12706 			 * Don't verify header checksum if this packet
12707 			 * is coming back from AH/ESP as we already did it.
12708 			 */
12709 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12710 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12711 				goto error;
12712 			}
12713 		}
12714 	}
12715 
12716 	if (!mctl_present) {
12717 		UPDATE_IB_PKT_COUNT(ire);
12718 		ire->ire_last_used_time = lbolt;
12719 	}
12720 
12721 	/* packet part of fragmented IP packet? */
12722 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12723 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12724 		goto fragmented;
12725 	}
12726 
12727 	/* u1 = IP header length (20 bytes) */
12728 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12729 
12730 	/* does packet contain IP+TCP headers? */
12731 	len = mp->b_wptr - rptr;
12732 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12733 		IP_STAT(ip_tcppullup);
12734 		goto tcppullup;
12735 	}
12736 
12737 	/* TCP options present? */
12738 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12739 
12740 	/*
12741 	 * If options need to be pulled up, then goto tcpoptions.
12742 	 * otherwise we are still in the fast path
12743 	 */
12744 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12745 		IP_STAT(ip_tcpoptions);
12746 		goto tcpoptions;
12747 	}
12748 
12749 	/* multiple mblks of tcp data? */
12750 	if ((mp1 = mp->b_cont) != NULL) {
12751 		/* more then two? */
12752 		if (mp1->b_cont != NULL) {
12753 			IP_STAT(ip_multipkttcp);
12754 			goto multipkttcp;
12755 		}
12756 		len += mp1->b_wptr - mp1->b_rptr;
12757 	}
12758 
12759 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12760 
12761 	/* part of pseudo checksum */
12762 
12763 	/* TCP datagram length */
12764 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12765 
12766 #define	iphs    ((uint16_t *)ipha)
12767 
12768 #ifdef	_BIG_ENDIAN
12769 	u1 += IPPROTO_TCP;
12770 #else
12771 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12772 #endif
12773 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12774 
12775 	/*
12776 	 * Revert to software checksum calculation if the interface
12777 	 * isn't capable of checksum offload or if IPsec is present.
12778 	 */
12779 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12780 		hck_flags = DB_CKSUMFLAGS(mp);
12781 
12782 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12783 		IP_STAT(ip_in_sw_cksum);
12784 
12785 	IP_CKSUM_RECV(hck_flags, u1,
12786 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12787 	    (int32_t)((uchar_t *)up - rptr),
12788 	    mp, mp1, cksum_err);
12789 
12790 	if (cksum_err) {
12791 		BUMP_MIB(&ip_mib, tcpInErrs);
12792 
12793 		if (hck_flags & HCK_FULLCKSUM)
12794 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12795 		else if (hck_flags & HCK_PARTIALCKSUM)
12796 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12797 		else
12798 			IP_STAT(ip_tcp_in_sw_cksum_err);
12799 
12800 		goto error;
12801 	}
12802 
12803 try_again:
12804 
12805 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12806 	    NULL) {
12807 		/* Send the TH_RST */
12808 		goto no_conn;
12809 	}
12810 
12811 	/*
12812 	 * TCP FAST PATH for AF_INET socket.
12813 	 *
12814 	 * TCP fast path to avoid extra work. An AF_INET socket type
12815 	 * does not have facility to receive extra information via
12816 	 * ip_process or ip_add_info. Also, when the connection was
12817 	 * established, we made a check if this connection is impacted
12818 	 * by any global IPSec policy or per connection policy (a
12819 	 * policy that comes in effect later will not apply to this
12820 	 * connection). Since all this can be determined at the
12821 	 * connection establishment time, a quick check of flags
12822 	 * can avoid extra work.
12823 	 */
12824 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12825 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12826 		ASSERT(first_mp == mp);
12827 		SET_SQUEUE(mp, tcp_rput_data, connp);
12828 		return (mp);
12829 	}
12830 
12831 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12832 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12833 		if (IPCL_IS_TCP(connp)) {
12834 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12835 			DB_CKSUMSTART(mp) =
12836 			    (intptr_t)ip_squeue_get(ill_ring);
12837 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12838 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12839 				SET_SQUEUE(mp, connp->conn_recv, connp);
12840 				return (mp);
12841 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12842 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12843 				ip_squeue_enter_unbound++;
12844 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12845 				    connp);
12846 				return (mp);
12847 			}
12848 			syn_present = B_TRUE;
12849 		}
12850 
12851 	}
12852 
12853 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12854 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12855 
12856 		/* No need to send this packet to TCP */
12857 		if ((flags & TH_RST) || (flags & TH_URG)) {
12858 			CONN_DEC_REF(connp);
12859 			freemsg(first_mp);
12860 			return (NULL);
12861 		}
12862 		if (flags & TH_ACK) {
12863 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
12864 			CONN_DEC_REF(connp);
12865 			return (NULL);
12866 		}
12867 
12868 		CONN_DEC_REF(connp);
12869 		freemsg(first_mp);
12870 		return (NULL);
12871 	}
12872 
12873 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12874 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12875 		    ipha, NULL, mctl_present);
12876 		if (first_mp == NULL) {
12877 			CONN_DEC_REF(connp);
12878 			return (NULL);
12879 		}
12880 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12881 			ASSERT(syn_present);
12882 			if (mctl_present) {
12883 				ASSERT(first_mp != mp);
12884 				first_mp->b_datap->db_struioflag |=
12885 				    STRUIO_POLICY;
12886 			} else {
12887 				ASSERT(first_mp == mp);
12888 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12889 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12890 			}
12891 		} else {
12892 			/*
12893 			 * Discard first_mp early since we're dealing with a
12894 			 * fully-connected conn_t and tcp doesn't do policy in
12895 			 * this case.
12896 			 */
12897 			if (mctl_present) {
12898 				freeb(first_mp);
12899 				mctl_present = B_FALSE;
12900 			}
12901 			first_mp = mp;
12902 		}
12903 	}
12904 
12905 	/* Initiate IPPF processing for fastpath */
12906 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12907 		uint32_t	ill_index;
12908 
12909 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12910 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12911 		if (mp == NULL) {
12912 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12913 			    "deferred/dropped during IPPF processing\n"));
12914 			CONN_DEC_REF(connp);
12915 			if (mctl_present)
12916 				freeb(first_mp);
12917 			return (NULL);
12918 		} else if (mctl_present) {
12919 			/*
12920 			 * ip_process might return a new mp.
12921 			 */
12922 			ASSERT(first_mp != mp);
12923 			first_mp->b_cont = mp;
12924 		} else {
12925 			first_mp = mp;
12926 		}
12927 
12928 	}
12929 
12930 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12931 		mp = ip_add_info(mp, recv_ill, flags);
12932 		if (mp == NULL) {
12933 			CONN_DEC_REF(connp);
12934 			if (mctl_present)
12935 				freeb(first_mp);
12936 			return (NULL);
12937 		} else if (mctl_present) {
12938 			/*
12939 			 * ip_add_info might return a new mp.
12940 			 */
12941 			ASSERT(first_mp != mp);
12942 			first_mp->b_cont = mp;
12943 		} else {
12944 			first_mp = mp;
12945 		}
12946 	}
12947 
12948 	if (IPCL_IS_TCP(connp)) {
12949 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
12950 		return (first_mp);
12951 	} else {
12952 		putnext(connp->conn_rq, first_mp);
12953 		CONN_DEC_REF(connp);
12954 		return (NULL);
12955 	}
12956 
12957 no_conn:
12958 	/* Initiate IPPf processing, if needed. */
12959 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12960 		uint32_t ill_index;
12961 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12962 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
12963 		if (first_mp == NULL) {
12964 			return (NULL);
12965 		}
12966 	}
12967 	BUMP_MIB(&ip_mib, ipInDelivers);
12968 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid);
12969 	return (NULL);
12970 ipoptions:
12971 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
12972 		goto slow_done;
12973 	}
12974 
12975 	UPDATE_IB_PKT_COUNT(ire);
12976 	ire->ire_last_used_time = lbolt;
12977 
12978 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12979 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12980 fragmented:
12981 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
12982 			if (mctl_present)
12983 				freeb(first_mp);
12984 			goto slow_done;
12985 		}
12986 		/*
12987 		 * Make sure that first_mp points back to mp as
12988 		 * the mp we came in with could have changed in
12989 		 * ip_rput_fragment().
12990 		 */
12991 		ASSERT(!mctl_present);
12992 		ipha = (ipha_t *)mp->b_rptr;
12993 		first_mp = mp;
12994 	}
12995 
12996 	/* Now we have a complete datagram, destined for this machine. */
12997 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12998 
12999 	len = mp->b_wptr - mp->b_rptr;
13000 	/* Pull up a minimal TCP header, if necessary. */
13001 	if (len < (u1 + 20)) {
13002 tcppullup:
13003 		if (!pullupmsg(mp, u1 + 20)) {
13004 			BUMP_MIB(&ip_mib, ipInDiscards);
13005 			goto error;
13006 		}
13007 		ipha = (ipha_t *)mp->b_rptr;
13008 		len = mp->b_wptr - mp->b_rptr;
13009 	}
13010 
13011 	/*
13012 	 * Extract the offset field from the TCP header.  As usual, we
13013 	 * try to help the compiler more than the reader.
13014 	 */
13015 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13016 	if (offset != 5) {
13017 tcpoptions:
13018 		if (offset < 5) {
13019 			BUMP_MIB(&ip_mib, ipInDiscards);
13020 			goto error;
13021 		}
13022 		/*
13023 		 * There must be TCP options.
13024 		 * Make sure we can grab them.
13025 		 */
13026 		offset <<= 2;
13027 		offset += u1;
13028 		if (len < offset) {
13029 			if (!pullupmsg(mp, offset)) {
13030 				BUMP_MIB(&ip_mib, ipInDiscards);
13031 				goto error;
13032 			}
13033 			ipha = (ipha_t *)mp->b_rptr;
13034 			len = mp->b_wptr - rptr;
13035 		}
13036 	}
13037 
13038 	/* Get the total packet length in len, including headers. */
13039 	if (mp->b_cont) {
13040 multipkttcp:
13041 		len = msgdsize(mp);
13042 	}
13043 
13044 	/*
13045 	 * Check the TCP checksum by pulling together the pseudo-
13046 	 * header checksum, and passing it to ip_csum to be added in
13047 	 * with the TCP datagram.
13048 	 *
13049 	 * Since we are not using the hwcksum if available we must
13050 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13051 	 * If either of these fails along the way the mblk is freed.
13052 	 * If this logic ever changes and mblk is reused to say send
13053 	 * ICMP's back, then this flag may need to be cleared in
13054 	 * other places as well.
13055 	 */
13056 	DB_CKSUMFLAGS(mp) = 0;
13057 
13058 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13059 
13060 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13061 #ifdef	_BIG_ENDIAN
13062 	u1 += IPPROTO_TCP;
13063 #else
13064 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13065 #endif
13066 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13067 	/*
13068 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13069 	 */
13070 	IP_STAT(ip_in_sw_cksum);
13071 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13072 		BUMP_MIB(&ip_mib, tcpInErrs);
13073 		goto error;
13074 	}
13075 
13076 	IP_STAT(ip_tcp_slow_path);
13077 	goto try_again;
13078 #undef  iphs
13079 #undef  rptr
13080 
13081 error:
13082 	freemsg(first_mp);
13083 slow_done:
13084 	return (NULL);
13085 }
13086 
13087 /* ARGSUSED */
13088 static void
13089 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13090     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13091 {
13092 	conn_t		*connp;
13093 	uint32_t	sum;
13094 	uint32_t	u1;
13095 	ssize_t		len;
13096 	sctp_hdr_t	*sctph;
13097 	zoneid_t	zoneid = ire->ire_zoneid;
13098 	uint32_t	pktsum;
13099 	uint32_t	calcsum;
13100 	uint32_t	ports;
13101 	uint_t		ipif_seqid;
13102 	in6_addr_t	map_src, map_dst;
13103 	ill_t		*ill = (ill_t *)q->q_ptr;
13104 
13105 #define	rptr	((uchar_t *)ipha)
13106 
13107 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13108 
13109 	/* u1 is # words of IP options */
13110 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13111 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13112 
13113 	/* IP options present */
13114 	if (u1 > 0) {
13115 		goto ipoptions;
13116 	} else {
13117 		/* Check the IP header checksum.  */
13118 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13119 #define	uph	((uint16_t *)ipha)
13120 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13121 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13122 #undef	uph
13123 			/* finish doing IP checksum */
13124 			sum = (sum & 0xFFFF) + (sum >> 16);
13125 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13126 			/*
13127 			 * Don't verify header checksum if this packet
13128 			 * is coming back from AH/ESP as we already did it.
13129 			 */
13130 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13131 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13132 				goto error;
13133 			}
13134 		}
13135 		/*
13136 		 * Since there is no SCTP h/w cksum support yet, just
13137 		 * clear the flag.
13138 		 */
13139 		DB_CKSUMFLAGS(mp) = 0;
13140 	}
13141 
13142 	/*
13143 	 * Don't verify header checksum if this packet is coming
13144 	 * back from AH/ESP as we already did it.
13145 	 */
13146 	if (!mctl_present) {
13147 		UPDATE_IB_PKT_COUNT(ire);
13148 		ire->ire_last_used_time = lbolt;
13149 	}
13150 
13151 	/* packet part of fragmented IP packet? */
13152 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13153 	if (u1 & (IPH_MF | IPH_OFFSET))
13154 		goto fragmented;
13155 
13156 	/* u1 = IP header length (20 bytes) */
13157 	u1 = IP_SIMPLE_HDR_LENGTH;
13158 
13159 find_sctp_client:
13160 	/* Pullup if we don't have the sctp common header. */
13161 	len = MBLKL(mp);
13162 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13163 		if (mp->b_cont == NULL ||
13164 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13165 			BUMP_MIB(&ip_mib, ipInDiscards);
13166 			goto error;
13167 		}
13168 		ipha = (ipha_t *)mp->b_rptr;
13169 		len = MBLKL(mp);
13170 	}
13171 
13172 	sctph = (sctp_hdr_t *)(rptr + u1);
13173 #ifdef	DEBUG
13174 	if (!skip_sctp_cksum) {
13175 #endif
13176 		pktsum = sctph->sh_chksum;
13177 		sctph->sh_chksum = 0;
13178 		calcsum = sctp_cksum(mp, u1);
13179 		if (calcsum != pktsum) {
13180 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13181 			goto error;
13182 		}
13183 		sctph->sh_chksum = pktsum;
13184 #ifdef	DEBUG	/* skip_sctp_cksum */
13185 	}
13186 #endif
13187 	/* get the ports */
13188 	ports = *(uint32_t *)&sctph->sh_sport;
13189 
13190 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13191 	IRE_REFRELE(ire);
13192 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13193 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13194 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13195 	    mp)) == NULL) {
13196 		/* Check for raw socket or OOTB handling */
13197 		goto no_conn;
13198 	}
13199 
13200 	/* Found a client; up it goes */
13201 	BUMP_MIB(&ip_mib, ipInDelivers);
13202 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13203 	return;
13204 
13205 no_conn:
13206 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13207 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13208 	return;
13209 
13210 ipoptions:
13211 	DB_CKSUMFLAGS(mp) = 0;
13212 	if (!ip_options_cksum(q, first_mp, ipha, ire))
13213 		goto slow_done;
13214 
13215 	UPDATE_IB_PKT_COUNT(ire);
13216 	ire->ire_last_used_time = lbolt;
13217 
13218 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13219 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13220 fragmented:
13221 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13222 			goto slow_done;
13223 		/*
13224 		 * Make sure that first_mp points back to mp as
13225 		 * the mp we came in with could have changed in
13226 		 * ip_rput_fragment().
13227 		 */
13228 		ASSERT(!mctl_present);
13229 		ipha = (ipha_t *)mp->b_rptr;
13230 		first_mp = mp;
13231 	}
13232 
13233 	/* Now we have a complete datagram, destined for this machine. */
13234 	u1 = IPH_HDR_LENGTH(ipha);
13235 	goto find_sctp_client;
13236 #undef  iphs
13237 #undef  rptr
13238 
13239 error:
13240 	freemsg(first_mp);
13241 slow_done:
13242 	IRE_REFRELE(ire);
13243 }
13244 
13245 #define	VER_BITS	0xF0
13246 #define	VERSION_6	0x60
13247 
13248 static boolean_t
13249 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
13250     ipaddr_t *dstp)
13251 {
13252 	uint_t	opt_len;
13253 	ipha_t *ipha;
13254 	ssize_t len;
13255 	uint_t	pkt_len;
13256 
13257 	IP_STAT(ip_ipoptions);
13258 	ipha = *iphapp;
13259 
13260 #define	rptr    ((uchar_t *)ipha)
13261 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13262 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13263 		BUMP_MIB(&ip_mib, ipInIPv6);
13264 		freemsg(mp);
13265 		return (B_FALSE);
13266 	}
13267 
13268 	/* multiple mblk or too short */
13269 	pkt_len = ntohs(ipha->ipha_length);
13270 
13271 	/* Get the number of words of IP options in the IP header. */
13272 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13273 	if (opt_len) {
13274 		/* IP Options present!  Validate and process. */
13275 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13276 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13277 			goto done;
13278 		}
13279 		/*
13280 		 * Recompute complete header length and make sure we
13281 		 * have access to all of it.
13282 		 */
13283 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13284 		if (len > (mp->b_wptr - rptr)) {
13285 			if (len > pkt_len) {
13286 				BUMP_MIB(&ip_mib, ipInHdrErrors);
13287 				goto done;
13288 			}
13289 			if (!pullupmsg(mp, len)) {
13290 				BUMP_MIB(&ip_mib, ipInDiscards);
13291 				goto done;
13292 			}
13293 			ipha = (ipha_t *)mp->b_rptr;
13294 		}
13295 		/*
13296 		 * Go off to ip_rput_options which returns the next hop
13297 		 * destination address, which may have been affected
13298 		 * by source routing.
13299 		 */
13300 		IP_STAT(ip_opt);
13301 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13302 			return (B_FALSE);
13303 		}
13304 	}
13305 	*iphapp = ipha;
13306 	return (B_TRUE);
13307 done:
13308 	/* clear b_prev - used by ip_mroute_decap */
13309 	mp->b_prev = NULL;
13310 	freemsg(mp);
13311 	return (B_FALSE);
13312 #undef  rptr
13313 }
13314 
13315 /*
13316  * Deal with the fact that there is no ire for the destination.
13317  * The incoming ill (in_ill) is passed in to ip_newroute only
13318  * in the case of packets coming from mobile ip forward tunnel.
13319  * It must be null otherwise.
13320  */
13321 static ire_t *
13322 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13323     ipaddr_t dst)
13324 {
13325 	ipha_t	*ipha;
13326 	ill_t	*ill;
13327 	ire_t	*ire;
13328 	boolean_t	check_multirt = B_FALSE;
13329 
13330 	ipha = (ipha_t *)mp->b_rptr;
13331 	ill = (ill_t *)q->q_ptr;
13332 
13333 	ASSERT(ill != NULL);
13334 	/*
13335 	 * No IRE for this destination, so it can't be for us.
13336 	 * Unless we are forwarding, drop the packet.
13337 	 * We have to let source routed packets through
13338 	 * since we don't yet know if they are 'ping -l'
13339 	 * packets i.e. if they will go out over the
13340 	 * same interface as they came in on.
13341 	 */
13342 	if (ll_multicast) {
13343 		freemsg(mp);
13344 		return (NULL);
13345 	}
13346 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13347 		BUMP_MIB(&ip_mib, ipForwProhibits);
13348 		freemsg(mp);
13349 		return (NULL);
13350 	}
13351 
13352 	/*
13353 	 * Mark this packet as having originated externally.
13354 	 *
13355 	 * For non-forwarding code path, ire_send later double
13356 	 * checks this interface to see if it is still exists
13357 	 * post-ARP resolution.
13358 	 *
13359 	 * Also, IPQOS uses this to differentiate between
13360 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13361 	 * QOS packet processing in ip_wput_attach_llhdr().
13362 	 * The QoS module can mark the b_band for a fastpath message
13363 	 * or the dl_priority field in a unitdata_req header for
13364 	 * CoS marking. This info can only be found in
13365 	 * ip_wput_attach_llhdr().
13366 	 */
13367 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13368 	/*
13369 	 * Clear the indication that this may have a hardware checksum
13370 	 * as we are not using it
13371 	 */
13372 	DB_CKSUMFLAGS(mp) = 0;
13373 
13374 	if (in_ill != NULL) {
13375 		/*
13376 		 * Now hand the packet to ip_newroute.
13377 		 */
13378 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13379 		return (NULL);
13380 	}
13381 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13382 	    MBLK_GETLABEL(mp));
13383 
13384 	if (ire == NULL && check_multirt) {
13385 		/* Let ip_newroute handle CGTP  */
13386 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13387 		return (NULL);
13388 	}
13389 
13390 	if (ire != NULL)
13391 		return (ire);
13392 
13393 	mp->b_prev = mp->b_next = 0;
13394 	/* send icmp unreachable */
13395 	q = WR(q);
13396 	/* Sent by forwarding path, and router is global zone */
13397 	if (ip_source_routed(ipha)) {
13398 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13399 		    GLOBAL_ZONEID);
13400 	} else {
13401 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13402 	}
13403 
13404 	return (NULL);
13405 
13406 }
13407 
13408 /*
13409  * check ip header length and align it.
13410  */
13411 static boolean_t
13412 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13413 {
13414 	ssize_t len;
13415 	ill_t *ill;
13416 	ipha_t	*ipha;
13417 
13418 	len = MBLKL(mp);
13419 
13420 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13421 		if (!OK_32PTR(mp->b_rptr))
13422 			IP_STAT(ip_notaligned1);
13423 		else
13424 			IP_STAT(ip_notaligned2);
13425 		/* Guard against bogus device drivers */
13426 		if (len < 0) {
13427 			/* clear b_prev - used by ip_mroute_decap */
13428 			mp->b_prev = NULL;
13429 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13430 			freemsg(mp);
13431 			return (B_FALSE);
13432 		}
13433 
13434 		if (ip_rput_pullups++ == 0) {
13435 			ill = (ill_t *)q->q_ptr;
13436 			ipha = (ipha_t *)mp->b_rptr;
13437 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13438 			    "ip_check_and_align_header: %s forced us to "
13439 			    " pullup pkt, hdr len %ld, hdr addr %p",
13440 			    ill->ill_name, len, ipha);
13441 		}
13442 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13443 			/* clear b_prev - used by ip_mroute_decap */
13444 			mp->b_prev = NULL;
13445 			BUMP_MIB(&ip_mib, ipInDiscards);
13446 			freemsg(mp);
13447 			return (B_FALSE);
13448 		}
13449 	}
13450 	return (B_TRUE);
13451 }
13452 
13453 static boolean_t
13454 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13455 {
13456 	ill_group_t	*ill_group;
13457 	ill_group_t	*ire_group;
13458 	queue_t 	*q;
13459 	ill_t		*ire_ill;
13460 	uint_t		ill_ifindex;
13461 
13462 	q = *qp;
13463 	/*
13464 	 * We need to check to make sure the packet came in
13465 	 * on the queue associated with the destination IRE.
13466 	 * Note that for multicast packets and broadcast packets sent to
13467 	 * a broadcast address which is shared between multiple interfaces
13468 	 * we should not do this since we just got a random broadcast ire.
13469 	 */
13470 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13471 		boolean_t check_multi = B_TRUE;
13472 
13473 		/*
13474 		 * This packet came in on an interface other than the
13475 		 * one associated with the destination address.
13476 		 * "Gateway" it to the appropriate interface here.
13477 		 * As long as the ills belong to the same group,
13478 		 * we don't consider them to arriving on the wrong
13479 		 * interface. Thus, when the switch is doing inbound
13480 		 * load spreading, we won't drop packets when we
13481 		 * are doing strict multihoming checks. Note, the
13482 		 * same holds true for 'usesrc groups' where the
13483 		 * destination address may belong to another interface
13484 		 * to allow multipathing to happen
13485 		 */
13486 		ill_group = ill->ill_group;
13487 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13488 		ill_ifindex = ill->ill_usesrc_ifindex;
13489 		ire_group = ire_ill->ill_group;
13490 
13491 		/*
13492 		 * If it's part of the same IPMP group, or if it's a legal
13493 		 * address on the 'usesrc' interface, then bypass strict
13494 		 * checks.
13495 		 */
13496 		if (ill_group != NULL && ill_group == ire_group) {
13497 			check_multi = B_FALSE;
13498 		} else if (ill_ifindex != 0 &&
13499 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13500 			check_multi = B_FALSE;
13501 		}
13502 
13503 		if (check_multi &&
13504 		    ip_strict_dst_multihoming &&
13505 		    ((ill->ill_flags &
13506 		    ire->ire_ipif->ipif_ill->ill_flags &
13507 		    ILLF_ROUTER) == 0)) {
13508 			/* Drop packet */
13509 			BUMP_MIB(&ip_mib, ipForwProhibits);
13510 			freemsg(mp);
13511 			return (B_TRUE);
13512 		}
13513 
13514 		/*
13515 		 * Change the queue (for non-virtual destination network
13516 		 * interfaces) and ip_rput_local will be called with the right
13517 		 * queue
13518 		 */
13519 		q = ire->ire_rfq;
13520 	}
13521 	/* Must be broadcast.  We'll take it. */
13522 	*qp = q;
13523 	return (B_FALSE);
13524 }
13525 
13526 #define	SEND_PKT(ire, mp)			\
13527 {						\
13528 	UPDATE_IB_PKT_COUNT(ire);		\
13529 	(ire)->ire_last_used_time = lbolt;	\
13530 	BUMP_MIB(&ip_mib, ipForwDatagrams);	\
13531 	putnext((ire)->ire_stq, mp);		\
13532 }
13533 
13534 ire_t *
13535 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13536 {
13537 	ipha_t	*ipha;
13538 	ipaddr_t ip_dst, ip_src;
13539 	ire_t	*src_ire = NULL;
13540 	ill_t	*stq_ill;
13541 	uint_t	hlen;
13542 	uint32_t sum;
13543 	queue_t	*dev_q;
13544 	boolean_t check_multirt = B_FALSE;
13545 
13546 
13547 	ipha = (ipha_t *)mp->b_rptr;
13548 
13549 	/*
13550 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13551 	 * The loopback address check for both src and dst has already
13552 	 * been checked in ip_input
13553 	 */
13554 	ip_dst = ntohl(dst);
13555 	ip_src = ntohl(ipha->ipha_src);
13556 
13557 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13558 	    IN_CLASSD(ip_src)) {
13559 		BUMP_MIB(&ip_mib, ipForwProhibits);
13560 		goto drop;
13561 	}
13562 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13563 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13564 
13565 	if (src_ire != NULL) {
13566 		BUMP_MIB(&ip_mib, ipForwProhibits);
13567 		goto drop;
13568 	}
13569 
13570 	/* No ire cache of nexthop. So first create one  */
13571 	if (ire == NULL) {
13572 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13573 		/*
13574 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13575 		 * is not set. So upon return from ire_forward
13576 		 * check_multirt should remain as false.
13577 		 */
13578 		ASSERT(!check_multirt);
13579 		if (ire == NULL) {
13580 			BUMP_MIB(&ip_mib, ipInDiscards);
13581 			mp->b_prev = mp->b_next = 0;
13582 			/* send icmp unreachable */
13583 			/* Sent by forwarding path, and router is global zone */
13584 			if (ip_source_routed(ipha)) {
13585 				icmp_unreachable(ill->ill_wq, mp,
13586 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13587 			} else {
13588 				icmp_unreachable(ill->ill_wq, mp,
13589 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13590 			}
13591 			return (ire);
13592 		}
13593 	}
13594 
13595 	/*
13596 	 * Forwarding fastpath exception case:
13597 	 * If either of the follwoing case is true, we take
13598 	 * the slowpath
13599 	 *	o forwarding is not enabled
13600 	 *	o IPMP is enabled
13601 	 *	o corresponding ire is in incomplete state
13602 	 *	o packet needs fragmentation
13603 	 *
13604 	 * The codeflow from here on is thus:
13605 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13606 	 */
13607 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13608 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13609 	    !(ill->ill_flags & ILLF_ROUTER) || SAME_IPMP_GROUP(ill, stq_ill) ||
13610 	    (ire->ire_nce == NULL) ||
13611 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13612 	    (ntohs(ipha->ipha_length) > ire->ire_max_frag) ||
13613 	    ipha->ipha_ttl <= 1) {
13614 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13615 		    ipha, ill, B_FALSE);
13616 		return (ire);
13617 	}
13618 
13619 	mp->b_datap->db_struioun.cksum.flags = 0;
13620 	/* Adjust the checksum to reflect the ttl decrement. */
13621 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13622 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13623 	ipha->ipha_ttl--;
13624 
13625 	dev_q = ire->ire_stq->q_next;
13626 	if ((dev_q->q_next != NULL ||
13627 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13628 		goto indiscard;
13629 	}
13630 
13631 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13632 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13633 
13634 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13635 		mp = ip_wput_attach_llhdr(mp, ire, 0, 0);
13636 		if (mp != NULL) {
13637 			SEND_PKT(ire, mp);
13638 			return (ire);
13639 		}
13640 	}
13641 
13642 indiscard:
13643 	BUMP_MIB(&ip_mib, ipInDiscards);
13644 drop:
13645 	if (mp != NULL)
13646 		freemsg(mp);
13647 	if (src_ire != NULL)
13648 		ire_refrele(src_ire);
13649 	return (ire);
13650 
13651 }
13652 
13653 /*
13654  * This function is called in the forwarding slowpath, when
13655  * either the ire lacks the link-layer address, or the packet needs
13656  * further processing(eg. fragmentation), before transmission.
13657  */
13658 static void
13659 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13660     ill_t *ill, boolean_t ll_multicast)
13661 {
13662 	ill_group_t	*ill_group;
13663 	ill_group_t	*ire_group;
13664 	queue_t		*dev_q;
13665 	ire_t		*src_ire;
13666 
13667 	ASSERT(ire->ire_stq != NULL);
13668 
13669 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13670 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13671 
13672 	if (ll_multicast != 0)
13673 		goto drop_pkt;
13674 
13675 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13676 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13677 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13678 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13679 		if (src_ire != NULL)
13680 			ire_refrele(src_ire);
13681 		BUMP_MIB(&ip_mib, ipForwProhibits);
13682 		ip2dbg(("ip_rput_process_forward: Received packet with"
13683 		    " bad src/dst address on %s\n", ill->ill_name));
13684 	}
13685 
13686 	ill_group = ill->ill_group;
13687 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13688 	/*
13689 	 * Check if we want to forward this one at this time.
13690 	 * We allow source routed packets on a host provided that
13691 	 * they go out the same interface or same interface group
13692 	 * as they came in on.
13693 	 *
13694 	 * XXX To be quicker, we may wish to not chase pointers to
13695 	 * get the ILLF_ROUTER flag and instead store the
13696 	 * forwarding policy in the ire.  An unfortunate
13697 	 * side-effect of that would be requiring an ire flush
13698 	 * whenever the ILLF_ROUTER flag changes.
13699 	 */
13700 	if (((ill->ill_flags &
13701 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13702 	    ILLF_ROUTER) == 0) &&
13703 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13704 	    (ill_group != NULL && ill_group == ire_group)))) {
13705 		BUMP_MIB(&ip_mib, ipForwProhibits);
13706 		if (ip_source_routed(ipha)) {
13707 			q = WR(q);
13708 			/*
13709 			 * Clear the indication that this may have
13710 			 * hardware checksum as we are not using it.
13711 			 */
13712 			DB_CKSUMFLAGS(mp) = 0;
13713 			/* Sent by forwarding path, and router is global zone */
13714 			icmp_unreachable(q, mp,
13715 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13716 			return;
13717 		}
13718 		goto drop_pkt;
13719 	}
13720 
13721 	/* Packet is being forwarded. Turning off hwcksum flag. */
13722 	DB_CKSUMFLAGS(mp) = 0;
13723 	if (ip_g_send_redirects) {
13724 		/*
13725 		 * Check whether the incoming interface and outgoing
13726 		 * interface is part of the same group. If so,
13727 		 * send redirects.
13728 		 *
13729 		 * Check the source address to see if it originated
13730 		 * on the same logical subnet it is going back out on.
13731 		 * If so, we should be able to send it a redirect.
13732 		 * Avoid sending a redirect if the destination
13733 		 * is directly connected (gw_addr == 0),
13734 		 * or if the packet was source routed out this
13735 		 * interface.
13736 		 */
13737 		ipaddr_t src;
13738 		mblk_t	*mp1;
13739 		ire_t	*src_ire = NULL;
13740 
13741 		/*
13742 		 * Check whether ire_rfq and q are from the same ill
13743 		 * or if they are not same, they at least belong
13744 		 * to the same group. If so, send redirects.
13745 		 */
13746 		if ((ire->ire_rfq == q ||
13747 		    (ill_group != NULL && ill_group == ire_group)) &&
13748 		    (ire->ire_gateway_addr != 0) &&
13749 		    !ip_source_routed(ipha)) {
13750 
13751 			src = ipha->ipha_src;
13752 			src_ire = ire_ftable_lookup(src, 0, 0,
13753 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
13754 			    0, NULL, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
13755 
13756 			if (src_ire != NULL) {
13757 				/*
13758 				 * The source is directly connected.
13759 				 * Just copy the ip header (which is
13760 				 * in the first mblk)
13761 				 */
13762 				mp1 = copyb(mp);
13763 				if (mp1 != NULL) {
13764 					icmp_send_redirect(WR(q), mp1,
13765 					    ire->ire_gateway_addr);
13766 				}
13767 				ire_refrele(src_ire);
13768 			}
13769 		}
13770 	}
13771 
13772 	dev_q = ire->ire_stq->q_next;
13773 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13774 		BUMP_MIB(&ip_mib, ipInDiscards);
13775 		freemsg(mp);
13776 		return;
13777 	}
13778 
13779 	ip_rput_forward(ire, ipha, mp, ill);
13780 	return;
13781 
13782 drop_pkt:
13783 	ip2dbg(("ip_rput_forward: drop pkt\n"));
13784 	freemsg(mp);
13785 }
13786 
13787 ire_t *
13788 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13789     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13790 {
13791 	queue_t		*q;
13792 	uint16_t	hcksumflags;
13793 
13794 	q = *qp;
13795 
13796 	/*
13797 	 * Clear the indication that this may have hardware
13798 	 * checksum as we are not using it for forwarding.
13799 	 */
13800 	hcksumflags = DB_CKSUMFLAGS(mp);
13801 	DB_CKSUMFLAGS(mp) = 0;
13802 
13803 	/*
13804 	 * Directed broadcast forwarding: if the packet came in over a
13805 	 * different interface then it is routed out over we can forward it.
13806 	 */
13807 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13808 		ire_refrele(ire);
13809 		freemsg(mp);
13810 		BUMP_MIB(&ip_mib, ipInDiscards);
13811 		return (NULL);
13812 	}
13813 	/*
13814 	 * For multicast we have set dst to be INADDR_BROADCAST
13815 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13816 	 * only for broadcast packets.
13817 	 */
13818 	if (!CLASSD(ipha->ipha_dst)) {
13819 		ire_t *new_ire;
13820 		ipif_t *ipif;
13821 		/*
13822 		 * For ill groups, as the switch duplicates broadcasts
13823 		 * across all the ports, we need to filter out and
13824 		 * send up only one copy. There is one copy for every
13825 		 * broadcast address on each ill. Thus, we look for a
13826 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13827 		 * later to see whether this ill is eligible to receive
13828 		 * them or not. ill_nominate_bcast_rcv() nominates only
13829 		 * one set of IREs for receiving.
13830 		 */
13831 
13832 		ipif = ipif_get_next_ipif(NULL, ill);
13833 		if (ipif == NULL) {
13834 			ire_refrele(ire);
13835 			freemsg(mp);
13836 			BUMP_MIB(&ip_mib, ipInDiscards);
13837 			return (NULL);
13838 		}
13839 		new_ire = ire_ctable_lookup(dst, 0, 0,
13840 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13841 		ipif_refrele(ipif);
13842 
13843 		if (new_ire != NULL) {
13844 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13845 				ire_refrele(ire);
13846 				ire_refrele(new_ire);
13847 				freemsg(mp);
13848 				BUMP_MIB(&ip_mib, ipInDiscards);
13849 				return (NULL);
13850 			}
13851 			/*
13852 			 * In the special case of multirouted broadcast
13853 			 * packets, we unconditionally need to "gateway"
13854 			 * them to the appropriate interface here.
13855 			 * In the normal case, this cannot happen, because
13856 			 * there is no broadcast IRE tagged with the
13857 			 * RTF_MULTIRT flag.
13858 			 */
13859 			if (new_ire->ire_flags & RTF_MULTIRT) {
13860 				ire_refrele(new_ire);
13861 				if (ire->ire_rfq != NULL) {
13862 					q = ire->ire_rfq;
13863 					*qp = q;
13864 				}
13865 			} else {
13866 				ire_refrele(ire);
13867 				ire = new_ire;
13868 			}
13869 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
13870 			if (!ip_g_forward_directed_bcast) {
13871 				/*
13872 				 * Free the message if
13873 				 * ip_g_forward_directed_bcast is turned
13874 				 * off for non-local broadcast.
13875 				 */
13876 				ire_refrele(ire);
13877 				freemsg(mp);
13878 				BUMP_MIB(&ip_mib, ipInDiscards);
13879 				return (NULL);
13880 			}
13881 		} else {
13882 			/*
13883 			 * This CGTP packet successfully passed the
13884 			 * CGTP filter, but the related CGTP
13885 			 * broadcast IRE has not been found,
13886 			 * meaning that the redundant ipif is
13887 			 * probably down. However, if we discarded
13888 			 * this packet, its duplicate would be
13889 			 * filtered out by the CGTP filter so none
13890 			 * of them would get through. So we keep
13891 			 * going with this one.
13892 			 */
13893 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
13894 			if (ire->ire_rfq != NULL) {
13895 				q = ire->ire_rfq;
13896 				*qp = q;
13897 			}
13898 		}
13899 	}
13900 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
13901 		/*
13902 		 * Verify that there are not more then one
13903 		 * IRE_BROADCAST with this broadcast address which
13904 		 * has ire_stq set.
13905 		 * TODO: simplify, loop over all IRE's
13906 		 */
13907 		ire_t	*ire1;
13908 		int	num_stq = 0;
13909 		mblk_t	*mp1;
13910 
13911 		/* Find the first one with ire_stq set */
13912 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
13913 		for (ire1 = ire; ire1 &&
13914 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
13915 		    ire1 = ire1->ire_next)
13916 			;
13917 		if (ire1) {
13918 			ire_refrele(ire);
13919 			ire = ire1;
13920 			IRE_REFHOLD(ire);
13921 		}
13922 
13923 		/* Check if there are additional ones with stq set */
13924 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
13925 			if (ire->ire_addr != ire1->ire_addr)
13926 				break;
13927 			if (ire1->ire_stq) {
13928 				num_stq++;
13929 				break;
13930 			}
13931 		}
13932 		rw_exit(&ire->ire_bucket->irb_lock);
13933 		if (num_stq == 1 && ire->ire_stq != NULL) {
13934 			ip1dbg(("ip_rput_process_broadcast: directed "
13935 			    "broadcast to 0x%x\n",
13936 			    ntohl(ire->ire_addr)));
13937 			mp1 = copymsg(mp);
13938 			if (mp1) {
13939 				switch (ipha->ipha_protocol) {
13940 				case IPPROTO_UDP:
13941 					ip_udp_input(q, mp1, ipha, ire, ill);
13942 					break;
13943 				default:
13944 					ip_proto_input(q, mp1, ipha, ire, ill);
13945 					break;
13946 				}
13947 			}
13948 			/*
13949 			 * Adjust ttl to 2 (1+1 - the forward engine
13950 			 * will decrement it by one.
13951 			 */
13952 			if (ip_csum_hdr(ipha)) {
13953 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13954 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
13955 				freemsg(mp);
13956 				ire_refrele(ire);
13957 				return (NULL);
13958 			}
13959 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
13960 			ipha->ipha_hdr_checksum = 0;
13961 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
13962 			ip_rput_process_forward(q, mp, ire, ipha,
13963 			    ill, ll_multicast);
13964 			ire_refrele(ire);
13965 			return (NULL);
13966 		}
13967 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
13968 		    ntohl(ire->ire_addr)));
13969 	}
13970 
13971 
13972 	/* Restore any hardware checksum flags */
13973 	DB_CKSUMFLAGS(mp) = hcksumflags;
13974 	return (ire);
13975 }
13976 
13977 /* ARGSUSED */
13978 static boolean_t
13979 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
13980     int *ll_multicast, ipaddr_t *dstp)
13981 {
13982 	/*
13983 	 * Forward packets only if we have joined the allmulti
13984 	 * group on this interface.
13985 	 */
13986 	if (ip_g_mrouter && ill->ill_join_allmulti) {
13987 		int retval;
13988 
13989 		/*
13990 		 * Clear the indication that this may have hardware
13991 		 * checksum as we are not using it.
13992 		 */
13993 		DB_CKSUMFLAGS(mp) = 0;
13994 		retval = ip_mforward(ill, ipha, mp);
13995 		/* ip_mforward updates mib variables if needed */
13996 		/* clear b_prev - used by ip_mroute_decap */
13997 		mp->b_prev = NULL;
13998 
13999 		switch (retval) {
14000 		case 0:
14001 			/*
14002 			 * pkt is okay and arrived on phyint.
14003 			 *
14004 			 * If we are running as a multicast router
14005 			 * we need to see all IGMP and/or PIM packets.
14006 			 */
14007 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14008 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14009 				goto done;
14010 			}
14011 			break;
14012 		case -1:
14013 			/* pkt is mal-formed, toss it */
14014 			goto drop_pkt;
14015 		case 1:
14016 			/* pkt is okay and arrived on a tunnel */
14017 			/*
14018 			 * If we are running a multicast router
14019 			 *  we need to see all igmp packets.
14020 			 */
14021 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14022 				*dstp = INADDR_BROADCAST;
14023 				*ll_multicast = 1;
14024 				return (B_FALSE);
14025 			}
14026 
14027 			goto drop_pkt;
14028 		}
14029 	}
14030 
14031 	ILM_WALKER_HOLD(ill);
14032 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14033 		/*
14034 		 * This might just be caused by the fact that
14035 		 * multiple IP Multicast addresses map to the same
14036 		 * link layer multicast - no need to increment counter!
14037 		 */
14038 		ILM_WALKER_RELE(ill);
14039 		freemsg(mp);
14040 		return (B_TRUE);
14041 	}
14042 	ILM_WALKER_RELE(ill);
14043 done:
14044 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14045 	/*
14046 	 * This assumes the we deliver to all streams for multicast
14047 	 * and broadcast packets.
14048 	 */
14049 	*dstp = INADDR_BROADCAST;
14050 	*ll_multicast = 1;
14051 	return (B_FALSE);
14052 drop_pkt:
14053 	ip2dbg(("ip_rput: drop pkt\n"));
14054 	freemsg(mp);
14055 	return (B_TRUE);
14056 }
14057 
14058 static boolean_t
14059 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14060     int *ll_multicast, mblk_t **mpp)
14061 {
14062 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14063 	boolean_t must_copy = B_FALSE;
14064 	struct iocblk   *iocp;
14065 	ipha_t		*ipha;
14066 
14067 #define	rptr    ((uchar_t *)ipha)
14068 
14069 	first_mp = *first_mpp;
14070 	mp = *mpp;
14071 
14072 	ASSERT(first_mp == mp);
14073 
14074 	/*
14075 	 * if db_ref > 1 then copymsg and free original. Packet may be
14076 	 * changed and do not want other entity who has a reference to this
14077 	 * message to trip over the changes. This is a blind change because
14078 	 * trying to catch all places that might change packet is too
14079 	 * difficult (since it may be a module above this one)
14080 	 *
14081 	 * This corresponds to the non-fast path case. We walk down the full
14082 	 * chain in this case, and check the db_ref count of all the dblks,
14083 	 * and do a copymsg if required. It is possible that the db_ref counts
14084 	 * of the data blocks in the mblk chain can be different.
14085 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14086 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14087 	 * 'snoop' is running.
14088 	 */
14089 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14090 		if (mp1->b_datap->db_ref > 1) {
14091 			must_copy = B_TRUE;
14092 			break;
14093 		}
14094 	}
14095 
14096 	if (must_copy) {
14097 		mp1 = copymsg(mp);
14098 		if (mp1 == NULL) {
14099 			for (mp1 = mp; mp1 != NULL;
14100 			    mp1 = mp1->b_cont) {
14101 				mp1->b_next = NULL;
14102 				mp1->b_prev = NULL;
14103 			}
14104 			freemsg(mp);
14105 			BUMP_MIB(&ip_mib, ipInDiscards);
14106 			return (B_TRUE);
14107 		}
14108 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14109 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14110 			/* Copy b_prev - used by ip_mroute_decap */
14111 			to_mp->b_prev = from_mp->b_prev;
14112 			from_mp->b_prev = NULL;
14113 		}
14114 		*first_mpp = first_mp = mp1;
14115 		freemsg(mp);
14116 		mp = mp1;
14117 		*mpp = mp1;
14118 	}
14119 
14120 	ipha = (ipha_t *)mp->b_rptr;
14121 
14122 	/*
14123 	 * previous code has a case for M_DATA.
14124 	 * We want to check how that happens.
14125 	 */
14126 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14127 	switch (first_mp->b_datap->db_type) {
14128 	case M_PROTO:
14129 	case M_PCPROTO:
14130 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14131 		    DL_UNITDATA_IND) {
14132 			/* Go handle anything other than data elsewhere. */
14133 			ip_rput_dlpi(q, mp);
14134 			return (B_TRUE);
14135 		}
14136 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14137 		/* Ditch the DLPI header. */
14138 		mp1 = mp->b_cont;
14139 		ASSERT(first_mp == mp);
14140 		*first_mpp = mp1;
14141 		freeb(mp);
14142 		*mpp = mp1;
14143 		return (B_FALSE);
14144 	case M_IOCACK:
14145 		ip1dbg(("got iocack "));
14146 		iocp = (struct iocblk *)mp->b_rptr;
14147 		switch (iocp->ioc_cmd) {
14148 		case DL_IOC_HDR_INFO:
14149 			ill = (ill_t *)q->q_ptr;
14150 			ill_fastpath_ack(ill, mp);
14151 			return (B_TRUE);
14152 		case SIOCSTUNPARAM:
14153 		case OSIOCSTUNPARAM:
14154 			/* Go through qwriter_ip */
14155 			break;
14156 		case SIOCGTUNPARAM:
14157 		case OSIOCGTUNPARAM:
14158 			ip_rput_other(NULL, q, mp, NULL);
14159 			return (B_TRUE);
14160 		default:
14161 			putnext(q, mp);
14162 			return (B_TRUE);
14163 		}
14164 		/* FALLTHRU */
14165 	case M_ERROR:
14166 	case M_HANGUP:
14167 		/*
14168 		 * Since this is on the ill stream we unconditionally
14169 		 * bump up the refcount
14170 		 */
14171 		ill_refhold(ill);
14172 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14173 		    B_FALSE);
14174 		return (B_TRUE);
14175 	case M_CTL:
14176 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14177 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14178 			IPHADA_M_CTL)) {
14179 			/*
14180 			 * It's an IPsec accelerated packet.
14181 			 * Make sure that the ill from which we received the
14182 			 * packet has enabled IPsec hardware acceleration.
14183 			 */
14184 			if (!(ill->ill_capabilities &
14185 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14186 				/* IPsec kstats: bean counter */
14187 				freemsg(mp);
14188 				return (B_TRUE);
14189 			}
14190 
14191 			/*
14192 			 * Make mp point to the mblk following the M_CTL,
14193 			 * then process according to type of mp.
14194 			 * After this processing, first_mp will point to
14195 			 * the data-attributes and mp to the pkt following
14196 			 * the M_CTL.
14197 			 */
14198 			mp = first_mp->b_cont;
14199 			if (mp == NULL) {
14200 				freemsg(first_mp);
14201 				return (B_TRUE);
14202 			}
14203 			/*
14204 			 * A Hardware Accelerated packet can only be M_DATA
14205 			 * ESP or AH packet.
14206 			 */
14207 			if (mp->b_datap->db_type != M_DATA) {
14208 				/* non-M_DATA IPsec accelerated packet */
14209 				IPSECHW_DEBUG(IPSECHW_PKT,
14210 				    ("non-M_DATA IPsec accelerated pkt\n"));
14211 				freemsg(first_mp);
14212 				return (B_TRUE);
14213 			}
14214 			ipha = (ipha_t *)mp->b_rptr;
14215 			if (ipha->ipha_protocol != IPPROTO_AH &&
14216 			    ipha->ipha_protocol != IPPROTO_ESP) {
14217 				IPSECHW_DEBUG(IPSECHW_PKT,
14218 				    ("non-M_DATA IPsec accelerated pkt\n"));
14219 				freemsg(first_mp);
14220 				return (B_TRUE);
14221 			}
14222 			*mpp = mp;
14223 			return (B_FALSE);
14224 		}
14225 		putnext(q, mp);
14226 		return (B_TRUE);
14227 	case M_FLUSH:
14228 		if (*mp->b_rptr & FLUSHW) {
14229 			*mp->b_rptr &= ~FLUSHR;
14230 			qreply(q, mp);
14231 			return (B_TRUE);
14232 		}
14233 		freemsg(mp);
14234 		return (B_TRUE);
14235 	case M_IOCNAK:
14236 		ip1dbg(("got iocnak "));
14237 		iocp = (struct iocblk *)mp->b_rptr;
14238 		switch (iocp->ioc_cmd) {
14239 		case DL_IOC_HDR_INFO:
14240 		case SIOCSTUNPARAM:
14241 		case OSIOCSTUNPARAM:
14242 			/*
14243 			 * Since this is on the ill stream we unconditionally
14244 			 * bump up the refcount
14245 			 */
14246 			ill_refhold(ill);
14247 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14248 			    CUR_OP, B_FALSE);
14249 			return (B_TRUE);
14250 		case SIOCGTUNPARAM:
14251 		case OSIOCGTUNPARAM:
14252 			ip_rput_other(NULL, q, mp, NULL);
14253 			return (B_TRUE);
14254 		default:
14255 			break;
14256 		}
14257 		/* FALLTHRU */
14258 	default:
14259 		putnext(q, mp);
14260 		return (B_TRUE);
14261 	}
14262 }
14263 
14264 /* Read side put procedure.  Packets coming from the wire arrive here. */
14265 void
14266 ip_rput(queue_t *q, mblk_t *mp)
14267 {
14268 	ill_t	*ill;
14269 	mblk_t	 *dmp = NULL;
14270 
14271 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14272 
14273 	ill = (ill_t *)q->q_ptr;
14274 
14275 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14276 		union DL_primitives *dl;
14277 
14278 		/*
14279 		 * Things are opening or closing. Only accept DLPI control
14280 		 * messages. In the open case, the ill->ill_ipif has not yet
14281 		 * been created. In the close case, things hanging off the
14282 		 * ill could have been freed already. In either case it
14283 		 * may not be safe to proceed further.
14284 		 */
14285 
14286 		dl = (union DL_primitives *)mp->b_rptr;
14287 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14288 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14289 			/*
14290 			 * Also SIOC[GS]TUN* ioctls can come here.
14291 			 */
14292 			inet_freemsg(mp);
14293 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14294 			    "ip_input_end: q %p (%S)", q, "uninit");
14295 			return;
14296 		}
14297 	}
14298 
14299 	/*
14300 	 * if db_ref > 1 then copymsg and free original. Packet may be
14301 	 * changed and we do not want the other entity who has a reference to
14302 	 * this message to trip over the changes. This is a blind change because
14303 	 * trying to catch all places that might change the packet is too
14304 	 * difficult.
14305 	 *
14306 	 * This corresponds to the fast path case, where we have a chain of
14307 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14308 	 * in the mblk chain. There doesn't seem to be a reason why a device
14309 	 * driver would send up data with varying db_ref counts in the mblk
14310 	 * chain. In any case the Fast path is a private interface, and our
14311 	 * drivers don't do such a thing. Given the above assumption, there is
14312 	 * no need to walk down the entire mblk chain (which could have a
14313 	 * potential performance problem)
14314 	 */
14315 	if (mp->b_datap->db_ref > 1) {
14316 		mblk_t  *mp1;
14317 		boolean_t adjusted = B_FALSE;
14318 		IP_STAT(ip_db_ref);
14319 
14320 		/*
14321 		 * The IP_RECVSLLA option depends on having the link layer
14322 		 * header. First check that:
14323 		 * a> the underlying device is of type ether, since this
14324 		 * option is currently supported only over ethernet.
14325 		 * b> there is enough room to copy over the link layer header.
14326 		 *
14327 		 * Once the checks are done, adjust rptr so that the link layer
14328 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14329 		 * be returned by some non-ethernet drivers but in this case the
14330 		 * second check will fail.
14331 		 */
14332 		if (ill->ill_type == IFT_ETHER &&
14333 		    (mp->b_rptr - mp->b_datap->db_base) >=
14334 		    sizeof (struct ether_header)) {
14335 			mp->b_rptr -= sizeof (struct ether_header);
14336 			adjusted = B_TRUE;
14337 		}
14338 		mp1 = copymsg(mp);
14339 		if (mp1 == NULL) {
14340 			mp->b_next = NULL;
14341 			/* clear b_prev - used by ip_mroute_decap */
14342 			mp->b_prev = NULL;
14343 			freemsg(mp);
14344 			BUMP_MIB(&ip_mib, ipInDiscards);
14345 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14346 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14347 			return;
14348 		}
14349 		if (adjusted) {
14350 			/*
14351 			 * Copy is done. Restore the pointer in the _new_ mblk
14352 			 */
14353 			mp1->b_rptr += sizeof (struct ether_header);
14354 		}
14355 		/* Copy b_prev - used by ip_mroute_decap */
14356 		mp1->b_prev = mp->b_prev;
14357 		mp->b_prev = NULL;
14358 		freemsg(mp);
14359 		mp = mp1;
14360 	}
14361 	if (DB_TYPE(mp) == M_DATA) {
14362 		dmp = mp;
14363 	} else if (DB_TYPE(mp) == M_PROTO &&
14364 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14365 		dmp = mp->b_cont;
14366 	}
14367 	if (dmp != NULL) {
14368 		/*
14369 		 * IP header ptr not aligned?
14370 		 * OR IP header not complete in first mblk
14371 		 */
14372 		if (!OK_32PTR(dmp->b_rptr) ||
14373 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14374 			if (!ip_check_and_align_header(q, dmp))
14375 				return;
14376 		}
14377 	}
14378 
14379 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14380 	    "ip_rput_end: q %p (%S)", q, "end");
14381 
14382 	ip_input(ill, NULL, mp, NULL);
14383 }
14384 
14385 /*
14386  * Direct read side procedure capable of dealing with chains. GLDv3 based
14387  * drivers call this function directly with mblk chains while STREAMS
14388  * read side procedure ip_rput() calls this for single packet with ip_ring
14389  * set to NULL to process one packet at a time.
14390  *
14391  * The ill will always be valid if this function is called directly from
14392  * the driver.
14393  *
14394  * If ip_input() is called from GLDv3:
14395  *
14396  *   - This must be a non-VLAN IP stream.
14397  *   - 'mp' is either an untagged or a special priority-tagged packet.
14398  *   - Any VLAN tag that was in the MAC header has been stripped.
14399  *
14400  * Thus, there is no need to adjust b_rptr in this function.
14401  */
14402 /* ARGSUSED */
14403 void
14404 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14405     struct mac_header_info_s *mhip)
14406 {
14407 	ipaddr_t		dst = NULL;
14408 	ipaddr_t		prev_dst;
14409 	ire_t			*ire = NULL;
14410 	ipha_t			*ipha;
14411 	uint_t			pkt_len;
14412 	ssize_t			len;
14413 	uint_t			opt_len;
14414 	int			ll_multicast;
14415 	int			cgtp_flt_pkt;
14416 	queue_t			*q = ill->ill_rq;
14417 	squeue_t		*curr_sqp = NULL;
14418 	mblk_t 			*head = NULL;
14419 	mblk_t			*tail = NULL;
14420 	mblk_t			*first_mp;
14421 	mblk_t 			*mp;
14422 	int			cnt = 0;
14423 
14424 	ASSERT(mp_chain != NULL);
14425 	ASSERT(ill != NULL);
14426 
14427 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14428 
14429 #define	rptr	((uchar_t *)ipha)
14430 
14431 	while (mp_chain != NULL) {
14432 		first_mp = mp = mp_chain;
14433 		mp_chain = mp_chain->b_next;
14434 		mp->b_next = NULL;
14435 		ll_multicast = 0;
14436 
14437 		/*
14438 		 * We do ire caching from one iteration to
14439 		 * another. In the event the packet chain contains
14440 		 * all packets from the same dst, this caching saves
14441 		 * an ire_cache_lookup for each of the succeeding
14442 		 * packets in a packet chain.
14443 		 */
14444 		prev_dst = dst;
14445 
14446 		/*
14447 		 * ip_input fast path
14448 		 */
14449 
14450 		/* mblk type is not M_DATA */
14451 		if (mp->b_datap->db_type != M_DATA) {
14452 			if (ip_rput_process_notdata(q, &first_mp, ill,
14453 			    &ll_multicast, &mp))
14454 				continue;
14455 		}
14456 
14457 		/* Make sure its an M_DATA and that its aligned */
14458 		ASSERT(mp->b_datap->db_type == M_DATA);
14459 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14460 
14461 		ipha = (ipha_t *)mp->b_rptr;
14462 		len = mp->b_wptr - rptr;
14463 
14464 		BUMP_MIB(&ip_mib, ipInReceives);
14465 
14466 
14467 		/* multiple mblk or too short */
14468 		pkt_len = ntohs(ipha->ipha_length);
14469 		len -= pkt_len;
14470 		if (len != 0) {
14471 			/*
14472 			 * Make sure we have data length consistent
14473 			 * with the IP header.
14474 			 */
14475 			if (mp->b_cont == NULL) {
14476 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14477 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14478 					ip2dbg(("ip_input: drop pkt\n"));
14479 					freemsg(mp);
14480 					continue;
14481 				}
14482 				mp->b_wptr = rptr + pkt_len;
14483 			} else if (len += msgdsize(mp->b_cont)) {
14484 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14485 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14486 					ip2dbg(("ip_input: drop pkt\n"));
14487 					freemsg(mp);
14488 					continue;
14489 				}
14490 				(void) adjmsg(mp, -len);
14491 				IP_STAT(ip_multimblk3);
14492 			}
14493 		}
14494 
14495 		/* Obtain the dst of the current packet */
14496 		dst = ipha->ipha_dst;
14497 
14498 		if (IP_LOOPBACK_ADDR(dst) ||
14499 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14500 			BUMP_MIB(&ip_mib, ipInAddrErrors);
14501 			cmn_err(CE_CONT, "dst %X src %X\n",
14502 			    dst, ipha->ipha_src);
14503 			freemsg(mp);
14504 			continue;
14505 		}
14506 
14507 		/*
14508 		 * Attach any necessary label information to
14509 		 * this packet
14510 		 */
14511 		if (is_system_labeled() &&
14512 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14513 			BUMP_MIB(&ip_mib, ipInDiscards);
14514 			freemsg(mp);
14515 			continue;
14516 		}
14517 
14518 		/*
14519 		 * Reuse the cached ire only if the ipha_dst of the previous
14520 		 * packet is the same as the current packet AND it is not
14521 		 * INADDR_ANY.
14522 		 */
14523 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14524 		    (ire != NULL)) {
14525 			ire_refrele(ire);
14526 			ire = NULL;
14527 		}
14528 		opt_len = ipha->ipha_version_and_hdr_length -
14529 		    IP_SIMPLE_HDR_VERSION;
14530 
14531 		/*
14532 		 * Check to see if we can take the fastpath.
14533 		 * That is possible if the following conditions are met
14534 		 *	o Tsol disabled
14535 		 *	o CGTP disabled
14536 		 *	o ipp_action_count is 0
14537 		 *	o Mobile IP not running
14538 		 *	o no options in the packet
14539 		 *	o not a RSVP packet
14540 		 * 	o not a multicast packet
14541 		 */
14542 		if (!is_system_labeled() &&
14543 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14544 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14545 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14546 		    !ll_multicast && !CLASSD(dst)) {
14547 			if (ire == NULL)
14548 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14549 
14550 			/* incoming packet is for forwarding */
14551 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14552 				ire = ip_fast_forward(ire, dst, ill, mp);
14553 				continue;
14554 			}
14555 			/* incoming packet is for local consumption */
14556 			if (ire->ire_type & IRE_LOCAL)
14557 				goto local;
14558 		}
14559 
14560 		/*
14561 		 * Disable ire caching for anything more complex
14562 		 * than the simple fast path case we checked for above.
14563 		 */
14564 		if (ire != NULL) {
14565 			ire_refrele(ire);
14566 			ire = NULL;
14567 		}
14568 
14569 		/* Full-blown slow path */
14570 		if (opt_len != 0) {
14571 			if (len != 0)
14572 				IP_STAT(ip_multimblk4);
14573 			else
14574 				IP_STAT(ip_ipoptions);
14575 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
14576 				continue;
14577 		}
14578 
14579 		/*
14580 		 * Invoke the CGTP (multirouting) filtering module to process
14581 		 * the incoming packet. Packets identified as duplicates
14582 		 * must be discarded. Filtering is active only if the
14583 		 * the ip_cgtp_filter ndd variable is non-zero.
14584 		 */
14585 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14586 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
14587 			cgtp_flt_pkt =
14588 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14589 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14590 				freemsg(first_mp);
14591 				continue;
14592 			}
14593 		}
14594 
14595 		/*
14596 		 * If rsvpd is running, let RSVP daemon handle its processing
14597 		 * and forwarding of RSVP multicast/unicast packets.
14598 		 * If rsvpd is not running but mrouted is running, RSVP
14599 		 * multicast packets are forwarded as multicast traffic
14600 		 * and RSVP unicast packets are forwarded by unicast router.
14601 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14602 		 * packets are not forwarded, but the unicast packets are
14603 		 * forwarded like unicast traffic.
14604 		 */
14605 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14606 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
14607 			/* RSVP packet and rsvpd running. Treat as ours */
14608 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14609 			/*
14610 			 * This assumes that we deliver to all streams for
14611 			 * multicast and broadcast packets.
14612 			 * We have to force ll_multicast to 1 to handle the
14613 			 * M_DATA messages passed in from ip_mroute_decap.
14614 			 */
14615 			dst = INADDR_BROADCAST;
14616 			ll_multicast = 1;
14617 		} else if (CLASSD(dst)) {
14618 			/* packet is multicast */
14619 			mp->b_next = NULL;
14620 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14621 			    &ll_multicast, &dst))
14622 				continue;
14623 		}
14624 
14625 
14626 		/*
14627 		 * Check if the packet is coming from the Mobile IP
14628 		 * forward tunnel interface
14629 		 */
14630 		if (ill->ill_srcif_refcnt > 0) {
14631 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
14632 			    NULL, ill, MATCH_IRE_TYPE);
14633 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
14634 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
14635 
14636 				/* We need to resolve the link layer info */
14637 				ire_refrele(ire);
14638 				ire = NULL;
14639 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
14640 				    ll_multicast, dst);
14641 				continue;
14642 			}
14643 		}
14644 
14645 		if (ire == NULL) {
14646 			ire = ire_cache_lookup(dst, ALL_ZONES,
14647 			    MBLK_GETLABEL(mp));
14648 		}
14649 
14650 		/*
14651 		 * If mipagent is running and reverse tunnel is created as per
14652 		 * mobile node request, then any packet coming through the
14653 		 * incoming interface from the mobile-node, should be reverse
14654 		 * tunneled to it's home agent except those that are destined
14655 		 * to foreign agent only.
14656 		 * This needs source address based ire lookup. The routing
14657 		 * entries for source address based lookup are only created by
14658 		 * mipagent program only when a reverse tunnel is created.
14659 		 * Reference : RFC2002, RFC2344
14660 		 */
14661 		if (ill->ill_mrtun_refcnt > 0) {
14662 			ipaddr_t	srcaddr;
14663 			ire_t		*tmp_ire;
14664 
14665 			tmp_ire = ire;	/* Save, we might need it later */
14666 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14667 			    ire->ire_type != IRE_BROADCAST)) {
14668 				srcaddr = ipha->ipha_src;
14669 				ire = ire_mrtun_lookup(srcaddr, ill);
14670 				if (ire != NULL) {
14671 					/*
14672 					 * Should not be getting iphada packet
14673 					 * here. we should only get those for
14674 					 * IRE_LOCAL traffic, excluded above.
14675 					 * Fail-safe (drop packet) in the event
14676 					 * hardware is misbehaving.
14677 					 */
14678 					if (first_mp != mp) {
14679 						/* IPsec KSTATS: beancount me */
14680 						freemsg(first_mp);
14681 					} else {
14682 						/*
14683 						 * This packet must be forwarded
14684 						 * to Reverse Tunnel
14685 						 */
14686 						ip_mrtun_forward(ire, ill, mp);
14687 					}
14688 					ire_refrele(ire);
14689 					ire = NULL;
14690 					if (tmp_ire != NULL) {
14691 						ire_refrele(tmp_ire);
14692 						tmp_ire = NULL;
14693 					}
14694 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14695 					    "ip_input_end: q %p (%S)",
14696 					    q, "uninit");
14697 					continue;
14698 				}
14699 			}
14700 			/*
14701 			 * If this packet is from a non-mobilenode  or a
14702 			 * mobile-node which does not request reverse
14703 			 * tunnel service
14704 			 */
14705 			ire = tmp_ire;
14706 		}
14707 
14708 
14709 		/*
14710 		 * If we reach here that means the incoming packet satisfies
14711 		 * one of the following conditions:
14712 		 *   - packet is from a mobile node which does not request
14713 		 *	reverse tunnel
14714 		 *   - packet is from a non-mobile node, which is the most
14715 		 *	common case
14716 		 *   - packet is from a reverse tunnel enabled mobile node
14717 		 *	and destined to foreign agent only
14718 		 */
14719 
14720 		if (ire == NULL) {
14721 			/*
14722 			 * No IRE for this destination, so it can't be for us.
14723 			 * Unless we are forwarding, drop the packet.
14724 			 * We have to let source routed packets through
14725 			 * since we don't yet know if they are 'ping -l'
14726 			 * packets i.e. if they will go out over the
14727 			 * same interface as they came in on.
14728 			 */
14729 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14730 			if (ire == NULL)
14731 				continue;
14732 		}
14733 
14734 		/*
14735 		 * Broadcast IRE may indicate either broadcast or
14736 		 * multicast packet
14737 		 */
14738 		if (ire->ire_type == IRE_BROADCAST) {
14739 			/*
14740 			 * Skip broadcast checks if packet is UDP multicast;
14741 			 * we'd rather not enter ip_rput_process_broadcast()
14742 			 * unless the packet is broadcast for real, since
14743 			 * that routine is a no-op for multicast.
14744 			 */
14745 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14746 			    !CLASSD(ipha->ipha_dst)) {
14747 				ire = ip_rput_process_broadcast(&q, mp,
14748 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14749 				    ll_multicast);
14750 				if (ire == NULL)
14751 					continue;
14752 			}
14753 		} else if (ire->ire_stq != NULL) {
14754 			/* fowarding? */
14755 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14756 			    ll_multicast);
14757 			/* ip_rput_process_forward consumed the packet */
14758 			continue;
14759 		}
14760 
14761 local:
14762 		/* packet not for us */
14763 		if (ire->ire_rfq != q) {
14764 			if (ip_rput_notforus(&q, mp, ire, ill))
14765 				continue;
14766 		}
14767 
14768 		switch (ipha->ipha_protocol) {
14769 		case IPPROTO_TCP:
14770 			ASSERT(first_mp == mp);
14771 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14772 				mp, 0, q, ip_ring)) != NULL) {
14773 				if (curr_sqp == NULL) {
14774 					curr_sqp = GET_SQUEUE(mp);
14775 					ASSERT(cnt == 0);
14776 					cnt++;
14777 					head = tail = mp;
14778 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14779 					ASSERT(tail != NULL);
14780 					cnt++;
14781 					tail->b_next = mp;
14782 					tail = mp;
14783 				} else {
14784 					/*
14785 					 * A different squeue. Send the
14786 					 * chain for the previous squeue on
14787 					 * its way. This shouldn't happen
14788 					 * often unless interrupt binding
14789 					 * changes.
14790 					 */
14791 					IP_STAT(ip_input_multi_squeue);
14792 					squeue_enter_chain(curr_sqp, head,
14793 					    tail, cnt, SQTAG_IP_INPUT);
14794 					curr_sqp = GET_SQUEUE(mp);
14795 					head = mp;
14796 					tail = mp;
14797 					cnt = 1;
14798 				}
14799 			}
14800 			continue;
14801 		case IPPROTO_UDP:
14802 			ASSERT(first_mp == mp);
14803 			ip_udp_input(q, mp, ipha, ire, ill);
14804 			continue;
14805 		case IPPROTO_SCTP:
14806 			ASSERT(first_mp == mp);
14807 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14808 			    q, dst);
14809 			/* ire has been released by ip_sctp_input */
14810 			ire = NULL;
14811 			continue;
14812 		default:
14813 			ip_proto_input(q, first_mp, ipha, ire, ill);
14814 			continue;
14815 		}
14816 	}
14817 
14818 	if (ire != NULL)
14819 		ire_refrele(ire);
14820 
14821 	if (head != NULL)
14822 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14823 
14824 	/*
14825 	 * This code is there just to make netperf/ttcp look good.
14826 	 *
14827 	 * Its possible that after being in polling mode (and having cleared
14828 	 * the backlog), squeues have turned the interrupt frequency higher
14829 	 * to improve latency at the expense of more CPU utilization (less
14830 	 * packets per interrupts or more number of interrupts). Workloads
14831 	 * like ttcp/netperf do manage to tickle polling once in a while
14832 	 * but for the remaining time, stay in higher interrupt mode since
14833 	 * their packet arrival rate is pretty uniform and this shows up
14834 	 * as higher CPU utilization. Since people care about CPU utilization
14835 	 * while running netperf/ttcp, turn the interrupt frequency back to
14836 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14837 	 */
14838 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14839 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14840 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14841 			ip_ring->rr_blank(ip_ring->rr_handle,
14842 			    ip_ring->rr_normal_blank_time,
14843 			    ip_ring->rr_normal_pkt_cnt);
14844 		}
14845 	}
14846 
14847 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14848 	    "ip_input_end: q %p (%S)", q, "end");
14849 #undef	rptr
14850 }
14851 
14852 static void
14853 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
14854     t_uscalar_t err)
14855 {
14856 	if (dl_err == DL_SYSERR) {
14857 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14858 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
14859 		    ill->ill_name, dlpi_prim_str(prim), err);
14860 		return;
14861 	}
14862 
14863 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14864 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
14865 	    dlpi_err_str(dl_err));
14866 }
14867 
14868 /*
14869  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
14870  * than DL_UNITDATA_IND messages. If we need to process this message
14871  * exclusively, we call qwriter_ip, in which case we also need to call
14872  * ill_refhold before that, since qwriter_ip does an ill_refrele.
14873  */
14874 void
14875 ip_rput_dlpi(queue_t *q, mblk_t *mp)
14876 {
14877 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14878 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14879 	ill_t		*ill;
14880 
14881 	ip1dbg(("ip_rput_dlpi"));
14882 	ill = (ill_t *)q->q_ptr;
14883 	switch (dloa->dl_primitive) {
14884 	case DL_ERROR_ACK:
14885 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
14886 		    "%s (0x%x), unix %u\n", ill->ill_name,
14887 		    dlpi_prim_str(dlea->dl_error_primitive),
14888 		    dlea->dl_error_primitive,
14889 		    dlpi_err_str(dlea->dl_errno),
14890 		    dlea->dl_errno,
14891 		    dlea->dl_unix_errno));
14892 		switch (dlea->dl_error_primitive) {
14893 		case DL_UNBIND_REQ:
14894 			mutex_enter(&ill->ill_lock);
14895 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14896 			cv_signal(&ill->ill_cv);
14897 			mutex_exit(&ill->ill_lock);
14898 			/* FALLTHRU */
14899 		case DL_NOTIFY_REQ:
14900 		case DL_ATTACH_REQ:
14901 		case DL_DETACH_REQ:
14902 		case DL_INFO_REQ:
14903 		case DL_BIND_REQ:
14904 		case DL_ENABMULTI_REQ:
14905 		case DL_PHYS_ADDR_REQ:
14906 		case DL_CAPABILITY_REQ:
14907 		case DL_CONTROL_REQ:
14908 			/*
14909 			 * Refhold the ill to match qwriter_ip which does a
14910 			 * refrele. Since this is on the ill stream we
14911 			 * unconditionally bump up the refcount without
14912 			 * checking for ILL_CAN_LOOKUP
14913 			 */
14914 			ill_refhold(ill);
14915 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14916 			    CUR_OP, B_FALSE);
14917 			return;
14918 		case DL_DISABMULTI_REQ:
14919 			freemsg(mp);	/* Don't want to pass this up */
14920 			return;
14921 		default:
14922 			break;
14923 		}
14924 		ip_dlpi_error(ill, dlea->dl_error_primitive,
14925 		    dlea->dl_errno, dlea->dl_unix_errno);
14926 		freemsg(mp);
14927 		return;
14928 	case DL_INFO_ACK:
14929 	case DL_BIND_ACK:
14930 	case DL_PHYS_ADDR_ACK:
14931 	case DL_NOTIFY_ACK:
14932 	case DL_CAPABILITY_ACK:
14933 	case DL_CONTROL_ACK:
14934 		/*
14935 		 * Refhold the ill to match qwriter_ip which does a refrele
14936 		 * Since this is on the ill stream we unconditionally
14937 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
14938 		 */
14939 		ill_refhold(ill);
14940 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14941 		    CUR_OP, B_FALSE);
14942 		return;
14943 	case DL_NOTIFY_IND:
14944 		ill_refhold(ill);
14945 		/*
14946 		 * The DL_NOTIFY_IND is an asynchronous message that has no
14947 		 * relation to the current ioctl in progress (if any). Hence we
14948 		 * pass in NEW_OP in this case.
14949 		 */
14950 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14951 		    NEW_OP, B_FALSE);
14952 		return;
14953 	case DL_OK_ACK:
14954 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
14955 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
14956 		switch (dloa->dl_correct_primitive) {
14957 		case DL_UNBIND_REQ:
14958 			mutex_enter(&ill->ill_lock);
14959 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14960 			cv_signal(&ill->ill_cv);
14961 			mutex_exit(&ill->ill_lock);
14962 			/* FALLTHRU */
14963 		case DL_ATTACH_REQ:
14964 		case DL_DETACH_REQ:
14965 			/*
14966 			 * Refhold the ill to match qwriter_ip which does a
14967 			 * refrele. Since this is on the ill stream we
14968 			 * unconditionally bump up the refcount
14969 			 */
14970 			ill_refhold(ill);
14971 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14972 			    CUR_OP, B_FALSE);
14973 			return;
14974 		case DL_ENABMULTI_REQ:
14975 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
14976 				ill->ill_dlpi_multicast_state = IDS_OK;
14977 			break;
14978 
14979 		}
14980 		break;
14981 	default:
14982 		break;
14983 	}
14984 	freemsg(mp);
14985 }
14986 
14987 /*
14988  * Handling of DLPI messages that require exclusive access to the ipsq.
14989  *
14990  * Need to do ill_pending_mp_release on ioctl completion, which could
14991  * happen here. (along with mi_copy_done)
14992  */
14993 /* ARGSUSED */
14994 static void
14995 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14996 {
14997 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14998 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14999 	int		err = 0;
15000 	ill_t		*ill;
15001 	ipif_t		*ipif = NULL;
15002 	mblk_t		*mp1 = NULL;
15003 	conn_t		*connp = NULL;
15004 	t_uscalar_t	physaddr_req;
15005 	mblk_t		*mp_hw;
15006 	union DL_primitives *dlp;
15007 	boolean_t	success;
15008 	boolean_t	ioctl_aborted = B_FALSE;
15009 	boolean_t	log = B_TRUE;
15010 
15011 	ip1dbg(("ip_rput_dlpi_writer .."));
15012 	ill = (ill_t *)q->q_ptr;
15013 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15014 
15015 	ASSERT(IAM_WRITER_ILL(ill));
15016 
15017 	/*
15018 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15019 	 * both are null or non-null. However we can assert that only
15020 	 * after grabbing the ipsq_lock. So we don't make any assertion
15021 	 * here and in other places in the code.
15022 	 */
15023 	ipif = ipsq->ipsq_pending_ipif;
15024 	/*
15025 	 * The current ioctl could have been aborted by the user and a new
15026 	 * ioctl to bring up another ill could have started. We could still
15027 	 * get a response from the driver later.
15028 	 */
15029 	if (ipif != NULL && ipif->ipif_ill != ill)
15030 		ioctl_aborted = B_TRUE;
15031 
15032 	switch (dloa->dl_primitive) {
15033 	case DL_ERROR_ACK:
15034 		switch (dlea->dl_error_primitive) {
15035 		case DL_UNBIND_REQ:
15036 		case DL_ATTACH_REQ:
15037 		case DL_DETACH_REQ:
15038 		case DL_INFO_REQ:
15039 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15040 			break;
15041 		case DL_NOTIFY_REQ:
15042 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15043 			log = B_FALSE;
15044 			break;
15045 		case DL_PHYS_ADDR_REQ:
15046 			/*
15047 			 * For IPv6 only, there are two additional
15048 			 * phys_addr_req's sent to the driver to get the
15049 			 * IPv6 token and lla. This allows IP to acquire
15050 			 * the hardware address format for a given interface
15051 			 * without having built in knowledge of the hardware
15052 			 * address. ill_phys_addr_pend keeps track of the last
15053 			 * DL_PAR sent so we know which response we are
15054 			 * dealing with. ill_dlpi_done will update
15055 			 * ill_phys_addr_pend when it sends the next req.
15056 			 * We don't complete the IOCTL until all three DL_PARs
15057 			 * have been attempted, so set *_len to 0 and break.
15058 			 */
15059 			physaddr_req = ill->ill_phys_addr_pend;
15060 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15061 			if (physaddr_req == DL_IPV6_TOKEN) {
15062 				ill->ill_token_length = 0;
15063 				log = B_FALSE;
15064 				break;
15065 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15066 				ill->ill_nd_lla_len = 0;
15067 				log = B_FALSE;
15068 				break;
15069 			}
15070 			/*
15071 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15072 			 * We presumably have an IOCTL hanging out waiting
15073 			 * for completion. Find it and complete the IOCTL
15074 			 * with the error noted.
15075 			 * However, ill_dl_phys was called on an ill queue
15076 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15077 			 * set. But the ioctl is known to be pending on ill_wq.
15078 			 */
15079 			if (!ill->ill_ifname_pending)
15080 				break;
15081 			ill->ill_ifname_pending = 0;
15082 			if (!ioctl_aborted)
15083 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15084 			if (mp1 != NULL) {
15085 				/*
15086 				 * This operation (SIOCSLIFNAME) must have
15087 				 * happened on the ill. Assert there is no conn
15088 				 */
15089 				ASSERT(connp == NULL);
15090 				q = ill->ill_wq;
15091 			}
15092 			break;
15093 		case DL_BIND_REQ:
15094 			ill_dlpi_done(ill, DL_BIND_REQ);
15095 			if (ill->ill_ifname_pending)
15096 				break;
15097 			/*
15098 			 * Something went wrong with the bind.  We presumably
15099 			 * have an IOCTL hanging out waiting for completion.
15100 			 * Find it, take down the interface that was coming
15101 			 * up, and complete the IOCTL with the error noted.
15102 			 */
15103 			if (!ioctl_aborted)
15104 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15105 			if (mp1 != NULL) {
15106 				/*
15107 				 * This operation (SIOCSLIFFLAGS) must have
15108 				 * happened from a conn.
15109 				 */
15110 				ASSERT(connp != NULL);
15111 				q = CONNP_TO_WQ(connp);
15112 				if (ill->ill_move_in_progress) {
15113 					ILL_CLEAR_MOVE(ill);
15114 				}
15115 				(void) ipif_down(ipif, NULL, NULL);
15116 				/* error is set below the switch */
15117 			}
15118 			break;
15119 		case DL_ENABMULTI_REQ:
15120 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15121 
15122 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15123 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15124 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15125 				ipif_t *ipif;
15126 
15127 				log = B_FALSE;
15128 				printf("ip: joining multicasts failed (%d)"
15129 				    " on %s - will use link layer "
15130 				    "broadcasts for multicast\n",
15131 				    dlea->dl_errno, ill->ill_name);
15132 
15133 				/*
15134 				 * Set up the multicast mapping alone.
15135 				 * writer, so ok to access ill->ill_ipif
15136 				 * without any lock.
15137 				 */
15138 				ipif = ill->ill_ipif;
15139 				mutex_enter(&ill->ill_phyint->phyint_lock);
15140 				ill->ill_phyint->phyint_flags |=
15141 				    PHYI_MULTI_BCAST;
15142 				mutex_exit(&ill->ill_phyint->phyint_lock);
15143 
15144 				if (!ill->ill_isv6) {
15145 					(void) ipif_arp_setup_multicast(ipif,
15146 					    NULL);
15147 				} else {
15148 					(void) ipif_ndp_setup_multicast(ipif,
15149 					    NULL);
15150 				}
15151 			}
15152 			freemsg(mp);	/* Don't want to pass this up */
15153 			return;
15154 		case DL_CAPABILITY_REQ:
15155 		case DL_CONTROL_REQ:
15156 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15157 			    "DL_CAPABILITY/CONTROL REQ\n"));
15158 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15159 			ill->ill_dlpi_capab_state = IDS_FAILED;
15160 			freemsg(mp);
15161 			return;
15162 		}
15163 		/*
15164 		 * Note the error for IOCTL completion (mp1 is set when
15165 		 * ready to complete ioctl). If ill_ifname_pending_err is
15166 		 * set, an error occured during plumbing (ill_ifname_pending),
15167 		 * so we want to report that error.
15168 		 *
15169 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15170 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15171 		 * expected to get errack'd if the driver doesn't support
15172 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15173 		 * if these error conditions are encountered.
15174 		 */
15175 		if (mp1 != NULL) {
15176 			if (ill->ill_ifname_pending_err != 0)  {
15177 				err = ill->ill_ifname_pending_err;
15178 				ill->ill_ifname_pending_err = 0;
15179 			} else {
15180 				err = dlea->dl_unix_errno ?
15181 				    dlea->dl_unix_errno : ENXIO;
15182 			}
15183 		/*
15184 		 * If we're plumbing an interface and an error hasn't already
15185 		 * been saved, set ill_ifname_pending_err to the error passed
15186 		 * up. Ignore the error if log is B_FALSE (see comment above).
15187 		 */
15188 		} else if (log && ill->ill_ifname_pending &&
15189 		    ill->ill_ifname_pending_err == 0) {
15190 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15191 			dlea->dl_unix_errno : ENXIO;
15192 		}
15193 
15194 		if (log)
15195 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15196 			    dlea->dl_errno, dlea->dl_unix_errno);
15197 		break;
15198 	case DL_CAPABILITY_ACK: {
15199 		boolean_t reneg_flag = B_FALSE;
15200 		/* Call a routine to handle this one. */
15201 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15202 		/*
15203 		 * Check if the ACK is due to renegotiation case since we
15204 		 * will need to send a new CAPABILITY_REQ later.
15205 		 */
15206 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15207 			/* This is the ack for a renogiation case */
15208 			reneg_flag = B_TRUE;
15209 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15210 		}
15211 		ill_capability_ack(ill, mp);
15212 		if (reneg_flag)
15213 			ill_capability_probe(ill);
15214 		break;
15215 	}
15216 	case DL_CONTROL_ACK:
15217 		/* We treat all of these as "fire and forget" */
15218 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15219 		break;
15220 	case DL_INFO_ACK:
15221 		/* Call a routine to handle this one. */
15222 		ill_dlpi_done(ill, DL_INFO_REQ);
15223 		ip_ll_subnet_defaults(ill, mp);
15224 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15225 		return;
15226 	case DL_BIND_ACK:
15227 		/*
15228 		 * We should have an IOCTL waiting on this unless
15229 		 * sent by ill_dl_phys, in which case just return
15230 		 */
15231 		ill_dlpi_done(ill, DL_BIND_REQ);
15232 		if (ill->ill_ifname_pending)
15233 			break;
15234 
15235 		if (!ioctl_aborted)
15236 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15237 		if (mp1 == NULL)
15238 			break;
15239 		ASSERT(connp != NULL);
15240 		q = CONNP_TO_WQ(connp);
15241 
15242 		/*
15243 		 * We are exclusive. So nothing can change even after
15244 		 * we get the pending mp. If need be we can put it back
15245 		 * and restart, as in calling ipif_arp_up()  below.
15246 		 */
15247 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15248 
15249 		mutex_enter(&ill->ill_lock);
15250 		ill->ill_dl_up = 1;
15251 		mutex_exit(&ill->ill_lock);
15252 
15253 		/*
15254 		 * Now bring up the resolver; when that is complete, we'll
15255 		 * create IREs.  Note that we intentionally mirror what
15256 		 * ipif_up() would have done, because we got here by way of
15257 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15258 		 */
15259 		if (ill->ill_isv6) {
15260 			/*
15261 			 * v6 interfaces.
15262 			 * Unlike ARP which has to do another bind
15263 			 * and attach, once we get here we are
15264 			 * done with NDP. Except in the case of
15265 			 * ILLF_XRESOLV, in which case we send an
15266 			 * AR_INTERFACE_UP to the external resolver.
15267 			 * If all goes well, the ioctl will complete
15268 			 * in ip_rput(). If there's an error, we
15269 			 * complete it here.
15270 			 */
15271 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15272 			    B_FALSE);
15273 			if (err == 0) {
15274 				if (ill->ill_flags & ILLF_XRESOLV) {
15275 					mutex_enter(&connp->conn_lock);
15276 					mutex_enter(&ill->ill_lock);
15277 					success = ipsq_pending_mp_add(
15278 					    connp, ipif, q, mp1, 0);
15279 					mutex_exit(&ill->ill_lock);
15280 					mutex_exit(&connp->conn_lock);
15281 					if (success) {
15282 						err = ipif_resolver_up(ipif,
15283 						    Res_act_initial);
15284 						if (err == EINPROGRESS) {
15285 							freemsg(mp);
15286 							return;
15287 						}
15288 						ASSERT(err != 0);
15289 						mp1 = ipsq_pending_mp_get(ipsq,
15290 						    &connp);
15291 						ASSERT(mp1 != NULL);
15292 					} else {
15293 						/* conn has started closing */
15294 						err = EINTR;
15295 					}
15296 				} else { /* Non XRESOLV interface */
15297 					(void) ipif_resolver_up(ipif,
15298 					    Res_act_initial);
15299 					err = ipif_up_done_v6(ipif);
15300 				}
15301 			}
15302 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15303 			/*
15304 			 * ARP and other v4 external resolvers.
15305 			 * Leave the pending mblk intact so that
15306 			 * the ioctl completes in ip_rput().
15307 			 */
15308 			mutex_enter(&connp->conn_lock);
15309 			mutex_enter(&ill->ill_lock);
15310 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15311 			mutex_exit(&ill->ill_lock);
15312 			mutex_exit(&connp->conn_lock);
15313 			if (success) {
15314 				err = ipif_resolver_up(ipif, Res_act_initial);
15315 				if (err == EINPROGRESS) {
15316 					freemsg(mp);
15317 					return;
15318 				}
15319 				ASSERT(err != 0);
15320 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15321 			} else {
15322 				/* The conn has started closing */
15323 				err = EINTR;
15324 			}
15325 		} else {
15326 			/*
15327 			 * This one is complete. Reply to pending ioctl.
15328 			 */
15329 			(void) ipif_resolver_up(ipif, Res_act_initial);
15330 			err = ipif_up_done(ipif);
15331 		}
15332 
15333 		if ((err == 0) && (ill->ill_up_ipifs)) {
15334 			err = ill_up_ipifs(ill, q, mp1);
15335 			if (err == EINPROGRESS) {
15336 				freemsg(mp);
15337 				return;
15338 			}
15339 		}
15340 
15341 		if (ill->ill_up_ipifs) {
15342 			ill_group_cleanup(ill);
15343 		}
15344 
15345 		break;
15346 	case DL_NOTIFY_IND: {
15347 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15348 		ire_t *ire;
15349 		boolean_t need_ire_walk_v4 = B_FALSE;
15350 		boolean_t need_ire_walk_v6 = B_FALSE;
15351 
15352 		/*
15353 		 * Change the address everywhere we need to.
15354 		 * What we're getting here is a link-level addr or phys addr.
15355 		 * The new addr is at notify + notify->dl_addr_offset
15356 		 * The address length is notify->dl_addr_length;
15357 		 */
15358 		switch (notify->dl_notification) {
15359 		case DL_NOTE_PHYS_ADDR:
15360 			mp_hw = copyb(mp);
15361 			if (mp_hw == NULL) {
15362 				err = ENOMEM;
15363 				break;
15364 			}
15365 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15366 			/*
15367 			 * We currently don't support changing
15368 			 * the token via DL_NOTIFY_IND.
15369 			 * When we do support it, we have to consider
15370 			 * what the implications are with respect to
15371 			 * the token and the link local address.
15372 			 */
15373 			mutex_enter(&ill->ill_lock);
15374 			if (dlp->notify_ind.dl_data ==
15375 			    DL_IPV6_LINK_LAYER_ADDR) {
15376 				if (ill->ill_nd_lla_mp != NULL)
15377 					freemsg(ill->ill_nd_lla_mp);
15378 				ill->ill_nd_lla_mp = mp_hw;
15379 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15380 				    dlp->notify_ind.dl_addr_offset;
15381 				ill->ill_nd_lla_len =
15382 				    dlp->notify_ind.dl_addr_length -
15383 				    ABS(ill->ill_sap_length);
15384 				mutex_exit(&ill->ill_lock);
15385 				break;
15386 			} else if (dlp->notify_ind.dl_data ==
15387 			    DL_CURR_PHYS_ADDR) {
15388 				if (ill->ill_phys_addr_mp != NULL)
15389 					freemsg(ill->ill_phys_addr_mp);
15390 				ill->ill_phys_addr_mp = mp_hw;
15391 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15392 				    dlp->notify_ind.dl_addr_offset;
15393 				ill->ill_phys_addr_length =
15394 				    dlp->notify_ind.dl_addr_length -
15395 				    ABS(ill->ill_sap_length);
15396 				if (ill->ill_isv6 &&
15397 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15398 					if (ill->ill_nd_lla_mp != NULL)
15399 						freemsg(ill->ill_nd_lla_mp);
15400 					ill->ill_nd_lla_mp = copyb(mp_hw);
15401 					ill->ill_nd_lla = (uchar_t *)
15402 					    ill->ill_nd_lla_mp->b_rptr +
15403 					    dlp->notify_ind.dl_addr_offset;
15404 					ill->ill_nd_lla_len =
15405 					    ill->ill_phys_addr_length;
15406 				}
15407 			}
15408 			mutex_exit(&ill->ill_lock);
15409 			/*
15410 			 * Send out gratuitous arp request for our new
15411 			 * hardware address.
15412 			 */
15413 			for (ipif = ill->ill_ipif; ipif != NULL;
15414 			    ipif = ipif->ipif_next) {
15415 				if (!(ipif->ipif_flags & IPIF_UP))
15416 					continue;
15417 				if (ill->ill_isv6) {
15418 					ipif_ndp_down(ipif);
15419 					/*
15420 					 * Set B_TRUE to enable
15421 					 * ipif_ndp_up() to send out
15422 					 * unsolicited advertisements.
15423 					 */
15424 					err = ipif_ndp_up(ipif,
15425 					    &ipif->ipif_v6lcl_addr,
15426 					    B_TRUE);
15427 					if (err) {
15428 						ip1dbg((
15429 						    "ip_rput_dlpi_writer: "
15430 						    "Failed to update ndp "
15431 						    "err %d\n", err));
15432 					}
15433 				} else {
15434 					/*
15435 					 * IPv4 ARP case
15436 					 *
15437 					 * Set Res_act_move, as we only want
15438 					 * ipif_resolver_up to send an
15439 					 * AR_ENTRY_ADD request up to
15440 					 * ARP.
15441 					 */
15442 					err = ipif_resolver_up(ipif,
15443 					    Res_act_move);
15444 					if (err) {
15445 						ip1dbg((
15446 						    "ip_rput_dlpi_writer: "
15447 						    "Failed to update arp "
15448 						    "err %d\n", err));
15449 					}
15450 				}
15451 			}
15452 			/*
15453 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15454 			 * case so that all old fastpath information can be
15455 			 * purged from IRE caches.
15456 			 */
15457 		/* FALLTHRU */
15458 		case DL_NOTE_FASTPATH_FLUSH:
15459 			/*
15460 			 * Any fastpath probe sent henceforth will get the
15461 			 * new fp mp. So we first delete any ires that are
15462 			 * waiting for the fastpath. Then walk all ires and
15463 			 * delete the ire or delete the fp mp. In the case of
15464 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15465 			 * recreate the ire's without going through a complex
15466 			 * ipif up/down dance. So we don't delete the ire
15467 			 * itself, but just the nce_fp_mp for these 2 ire's
15468 			 * In the case of the other ire's we delete the ire's
15469 			 * themselves. Access to nce_fp_mp is completely
15470 			 * protected by ire_lock for IRE_MIPRTUN and
15471 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15472 			 * other cases for performance.
15473 			 */
15474 			if (ill->ill_isv6) {
15475 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15476 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15477 				    NULL);
15478 			} else {
15479 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15480 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15481 				    IRE_CACHE | IRE_BROADCAST,
15482 				    ire_fastpath_flush, NULL, ill);
15483 				mutex_enter(&ire_mrtun_lock);
15484 				if (ire_mrtun_count != 0) {
15485 					mutex_exit(&ire_mrtun_lock);
15486 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15487 					    IRE_MIPRTUN, ire_fastpath_flush,
15488 					    NULL, ill);
15489 				} else {
15490 					mutex_exit(&ire_mrtun_lock);
15491 				}
15492 			}
15493 			break;
15494 		case DL_NOTE_SDU_SIZE:
15495 			/*
15496 			 * Change the MTU size of the interface, of all
15497 			 * attached ipif's, and of all relevant ire's.  The
15498 			 * new value's a uint32_t at notify->dl_data.
15499 			 * Mtu change Vs. new ire creation - protocol below.
15500 			 *
15501 			 * a Mark the ipif as IPIF_CHANGING.
15502 			 * b Set the new mtu in the ipif.
15503 			 * c Change the ire_max_frag on all affected ires
15504 			 * d Unmark the IPIF_CHANGING
15505 			 *
15506 			 * To see how the protocol works, assume an interface
15507 			 * route is also being added simultaneously by
15508 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15509 			 * the ire. If the ire is created before step a,
15510 			 * it will be cleaned up by step c. If the ire is
15511 			 * created after step d, it will see the new value of
15512 			 * ipif_mtu. Any attempt to create the ire between
15513 			 * steps a to d will fail because of the IPIF_CHANGING
15514 			 * flag. Note that ire_create() is passed a pointer to
15515 			 * the ipif_mtu, and not the value. During ire_add
15516 			 * under the bucket lock, the ire_max_frag of the
15517 			 * new ire being created is set from the ipif/ire from
15518 			 * which it is being derived.
15519 			 */
15520 			mutex_enter(&ill->ill_lock);
15521 			ill->ill_max_frag = (uint_t)notify->dl_data;
15522 
15523 			/*
15524 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15525 			 * leave it alone
15526 			 */
15527 			if (ill->ill_mtu_userspecified) {
15528 				mutex_exit(&ill->ill_lock);
15529 				break;
15530 			}
15531 			ill->ill_max_mtu = ill->ill_max_frag;
15532 			if (ill->ill_isv6) {
15533 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15534 					ill->ill_max_mtu = IPV6_MIN_MTU;
15535 			} else {
15536 				if (ill->ill_max_mtu < IP_MIN_MTU)
15537 					ill->ill_max_mtu = IP_MIN_MTU;
15538 			}
15539 			for (ipif = ill->ill_ipif; ipif != NULL;
15540 			    ipif = ipif->ipif_next) {
15541 				/*
15542 				 * Don't override the mtu if the user
15543 				 * has explicitly set it.
15544 				 */
15545 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15546 					continue;
15547 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15548 				if (ipif->ipif_isv6)
15549 					ire = ipif_to_ire_v6(ipif);
15550 				else
15551 					ire = ipif_to_ire(ipif);
15552 				if (ire != NULL) {
15553 					ire->ire_max_frag = ipif->ipif_mtu;
15554 					ire_refrele(ire);
15555 				}
15556 				if (ipif->ipif_flags & IPIF_UP) {
15557 					if (ill->ill_isv6)
15558 						need_ire_walk_v6 = B_TRUE;
15559 					else
15560 						need_ire_walk_v4 = B_TRUE;
15561 				}
15562 			}
15563 			mutex_exit(&ill->ill_lock);
15564 			if (need_ire_walk_v4)
15565 				ire_walk_v4(ill_mtu_change, (char *)ill,
15566 				    ALL_ZONES);
15567 			if (need_ire_walk_v6)
15568 				ire_walk_v6(ill_mtu_change, (char *)ill,
15569 				    ALL_ZONES);
15570 			break;
15571 		case DL_NOTE_LINK_UP:
15572 		case DL_NOTE_LINK_DOWN: {
15573 			/*
15574 			 * We are writer. ill / phyint / ipsq assocs stable.
15575 			 * The RUNNING flag reflects the state of the link.
15576 			 */
15577 			phyint_t *phyint = ill->ill_phyint;
15578 			uint64_t new_phyint_flags;
15579 			boolean_t changed = B_FALSE;
15580 			boolean_t went_up;
15581 
15582 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15583 			mutex_enter(&phyint->phyint_lock);
15584 			new_phyint_flags = went_up ?
15585 			    phyint->phyint_flags | PHYI_RUNNING :
15586 			    phyint->phyint_flags & ~PHYI_RUNNING;
15587 			if (new_phyint_flags != phyint->phyint_flags) {
15588 				phyint->phyint_flags = new_phyint_flags;
15589 				changed = B_TRUE;
15590 			}
15591 			mutex_exit(&phyint->phyint_lock);
15592 			/*
15593 			 * ill_restart_dad handles the DAD restart and routing
15594 			 * socket notification logic.
15595 			 */
15596 			if (changed) {
15597 				ill_restart_dad(phyint->phyint_illv4, went_up);
15598 				ill_restart_dad(phyint->phyint_illv6, went_up);
15599 			}
15600 			break;
15601 		}
15602 		case DL_NOTE_PROMISC_ON_PHYS:
15603 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15604 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15605 			mutex_enter(&ill->ill_lock);
15606 			ill->ill_promisc_on_phys = B_TRUE;
15607 			mutex_exit(&ill->ill_lock);
15608 			break;
15609 		case DL_NOTE_PROMISC_OFF_PHYS:
15610 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15611 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15612 			mutex_enter(&ill->ill_lock);
15613 			ill->ill_promisc_on_phys = B_FALSE;
15614 			mutex_exit(&ill->ill_lock);
15615 			break;
15616 		case DL_NOTE_CAPAB_RENEG:
15617 			/*
15618 			 * Something changed on the driver side.
15619 			 * It wants us to renegotiate the capabilities
15620 			 * on this ill. The most likely cause is the
15621 			 * aggregation interface under us where a
15622 			 * port got added or went away.
15623 			 *
15624 			 * We reset the capabilities and set the
15625 			 * state to IDS_RENG so that when the ack
15626 			 * comes back, we can start the
15627 			 * renegotiation process.
15628 			 */
15629 			ill_capability_reset(ill);
15630 			ill->ill_dlpi_capab_state = IDS_RENEG;
15631 			break;
15632 		default:
15633 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15634 			    "type 0x%x for DL_NOTIFY_IND\n",
15635 			    notify->dl_notification));
15636 			break;
15637 		}
15638 
15639 		/*
15640 		 * As this is an asynchronous operation, we
15641 		 * should not call ill_dlpi_done
15642 		 */
15643 		break;
15644 	}
15645 	case DL_NOTIFY_ACK: {
15646 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15647 
15648 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15649 			ill->ill_note_link = 1;
15650 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15651 		break;
15652 	}
15653 	case DL_PHYS_ADDR_ACK: {
15654 		/*
15655 		 * We should have an IOCTL waiting on this when request
15656 		 * sent by ill_dl_phys.
15657 		 * However, ill_dl_phys was called on an ill queue (from
15658 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15659 		 * ioctl is known to be pending on ill_wq.
15660 		 * There are two additional phys_addr_req's sent to the
15661 		 * driver to get the token and lla. ill_phys_addr_pend
15662 		 * keeps track of the last one sent so we know which
15663 		 * response we are dealing with. ill_dlpi_done will
15664 		 * update ill_phys_addr_pend when it sends the next req.
15665 		 * We don't complete the IOCTL until all three DL_PARs
15666 		 * have been attempted.
15667 		 *
15668 		 * We don't need any lock to update ill_nd_lla* fields,
15669 		 * since the ill is not yet up, We grab the lock just
15670 		 * for uniformity with other code that accesses ill_nd_lla.
15671 		 */
15672 		physaddr_req = ill->ill_phys_addr_pend;
15673 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15674 		if (physaddr_req == DL_IPV6_TOKEN ||
15675 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15676 			if (physaddr_req == DL_IPV6_TOKEN) {
15677 				/*
15678 				 * bcopy to low-order bits of ill_token
15679 				 *
15680 				 * XXX Temporary hack - currently,
15681 				 * all known tokens are 64 bits,
15682 				 * so I'll cheat for the moment.
15683 				 */
15684 				dlp = (union DL_primitives *)mp->b_rptr;
15685 
15686 				mutex_enter(&ill->ill_lock);
15687 				bcopy((uchar_t *)(mp->b_rptr +
15688 				dlp->physaddr_ack.dl_addr_offset),
15689 				(void *)&ill->ill_token.s6_addr32[2],
15690 				dlp->physaddr_ack.dl_addr_length);
15691 				ill->ill_token_length =
15692 					dlp->physaddr_ack.dl_addr_length;
15693 				mutex_exit(&ill->ill_lock);
15694 			} else {
15695 				ASSERT(ill->ill_nd_lla_mp == NULL);
15696 				mp_hw = copyb(mp);
15697 				if (mp_hw == NULL) {
15698 					err = ENOMEM;
15699 					break;
15700 				}
15701 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15702 				mutex_enter(&ill->ill_lock);
15703 				ill->ill_nd_lla_mp = mp_hw;
15704 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15705 				dlp->physaddr_ack.dl_addr_offset;
15706 				ill->ill_nd_lla_len =
15707 					dlp->physaddr_ack.dl_addr_length;
15708 				mutex_exit(&ill->ill_lock);
15709 			}
15710 			break;
15711 		}
15712 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15713 		ASSERT(ill->ill_phys_addr_mp == NULL);
15714 		if (!ill->ill_ifname_pending)
15715 			break;
15716 		ill->ill_ifname_pending = 0;
15717 		if (!ioctl_aborted)
15718 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15719 		if (mp1 != NULL) {
15720 			ASSERT(connp == NULL);
15721 			q = ill->ill_wq;
15722 		}
15723 		/*
15724 		 * If any error acks received during the plumbing sequence,
15725 		 * ill_ifname_pending_err will be set. Break out and send up
15726 		 * the error to the pending ioctl.
15727 		 */
15728 		if (ill->ill_ifname_pending_err != 0) {
15729 			err = ill->ill_ifname_pending_err;
15730 			ill->ill_ifname_pending_err = 0;
15731 			break;
15732 		}
15733 		/*
15734 		 * Get the interface token.  If the zeroth interface
15735 		 * address is zero then set the address to the link local
15736 		 * address
15737 		 */
15738 		mp_hw = copyb(mp);
15739 		if (mp_hw == NULL) {
15740 			err = ENOMEM;
15741 			break;
15742 		}
15743 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15744 		ill->ill_phys_addr_mp = mp_hw;
15745 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15746 				dlp->physaddr_ack.dl_addr_offset;
15747 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15748 		    ill->ill_phys_addr_length == 0 ||
15749 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15750 			/*
15751 			 * Compatibility: atun driver returns a length of 0.
15752 			 * ipdptp has an ill_phys_addr_length of zero(from
15753 			 * DL_BIND_ACK) but a non-zero length here.
15754 			 * ipd has an ill_phys_addr_length of 4(from
15755 			 * DL_BIND_ACK) but a non-zero length here.
15756 			 */
15757 			ill->ill_phys_addr = NULL;
15758 		} else if (dlp->physaddr_ack.dl_addr_length !=
15759 		    ill->ill_phys_addr_length) {
15760 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15761 			    "Address length mismatch %d %d\n",
15762 			    dlp->physaddr_ack.dl_addr_length,
15763 			    ill->ill_phys_addr_length));
15764 			err = EINVAL;
15765 			break;
15766 		}
15767 		mutex_enter(&ill->ill_lock);
15768 		if (ill->ill_nd_lla_mp == NULL) {
15769 			ill->ill_nd_lla_mp = copyb(mp_hw);
15770 			if (ill->ill_nd_lla_mp == NULL) {
15771 				err = ENOMEM;
15772 				mutex_exit(&ill->ill_lock);
15773 				break;
15774 			}
15775 			ill->ill_nd_lla =
15776 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15777 			    dlp->physaddr_ack.dl_addr_offset;
15778 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15779 		}
15780 		mutex_exit(&ill->ill_lock);
15781 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15782 			(void) ill_setdefaulttoken(ill);
15783 
15784 		/*
15785 		 * If the ill zero interface has a zero address assign
15786 		 * it the proper link local address.
15787 		 */
15788 		ASSERT(ill->ill_ipif->ipif_id == 0);
15789 		if (ipif != NULL &&
15790 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15791 			(void) ipif_setlinklocal(ipif);
15792 		break;
15793 	}
15794 	case DL_OK_ACK:
15795 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15796 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15797 		    dloa->dl_correct_primitive));
15798 		switch (dloa->dl_correct_primitive) {
15799 		case DL_UNBIND_REQ:
15800 		case DL_ATTACH_REQ:
15801 		case DL_DETACH_REQ:
15802 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15803 			break;
15804 		}
15805 		break;
15806 	default:
15807 		break;
15808 	}
15809 
15810 	freemsg(mp);
15811 	if (mp1) {
15812 		struct iocblk *iocp;
15813 		int mode;
15814 
15815 		/*
15816 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15817 		 * SIOCSLIFNAME do a copyout.
15818 		 */
15819 		iocp = (struct iocblk *)mp1->b_rptr;
15820 
15821 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
15822 		    iocp->ioc_cmd == SIOCSLIFNAME)
15823 			mode = COPYOUT;
15824 		else
15825 			mode = NO_COPYOUT;
15826 		/*
15827 		 * The ioctl must complete now without EINPROGRESS
15828 		 * since ipsq_pending_mp_get has removed the ioctl mblk
15829 		 * from ipsq_pending_mp. Otherwise the ioctl will be
15830 		 * stuck for ever in the ipsq.
15831 		 */
15832 		ASSERT(err != EINPROGRESS);
15833 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
15834 
15835 	}
15836 }
15837 
15838 /*
15839  * ip_rput_other is called by ip_rput to handle messages modifying the global
15840  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15841  */
15842 /* ARGSUSED */
15843 void
15844 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15845 {
15846 	ill_t		*ill;
15847 	struct iocblk	*iocp;
15848 	mblk_t		*mp1;
15849 	conn_t		*connp = NULL;
15850 
15851 	ip1dbg(("ip_rput_other "));
15852 	ill = (ill_t *)q->q_ptr;
15853 	/*
15854 	 * This routine is not a writer in the case of SIOCGTUNPARAM
15855 	 * in which case ipsq is NULL.
15856 	 */
15857 	if (ipsq != NULL) {
15858 		ASSERT(IAM_WRITER_IPSQ(ipsq));
15859 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15860 	}
15861 
15862 	switch (mp->b_datap->db_type) {
15863 	case M_ERROR:
15864 	case M_HANGUP:
15865 		/*
15866 		 * The device has a problem.  We force the ILL down.  It can
15867 		 * be brought up again manually using SIOCSIFFLAGS (via
15868 		 * ifconfig or equivalent).
15869 		 */
15870 		ASSERT(ipsq != NULL);
15871 		if (mp->b_rptr < mp->b_wptr)
15872 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
15873 		if (ill->ill_error == 0)
15874 			ill->ill_error = ENXIO;
15875 		if (!ill_down_start(q, mp))
15876 			return;
15877 		ipif_all_down_tail(ipsq, q, mp, NULL);
15878 		break;
15879 	case M_IOCACK:
15880 		iocp = (struct iocblk *)mp->b_rptr;
15881 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
15882 		switch (iocp->ioc_cmd) {
15883 		case SIOCSTUNPARAM:
15884 		case OSIOCSTUNPARAM:
15885 			ASSERT(ipsq != NULL);
15886 			/*
15887 			 * Finish socket ioctl passed through to tun.
15888 			 * We should have an IOCTL waiting on this.
15889 			 */
15890 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15891 			if (ill->ill_isv6) {
15892 				struct iftun_req *ta;
15893 
15894 				/*
15895 				 * if a source or destination is
15896 				 * being set, try and set the link
15897 				 * local address for the tunnel
15898 				 */
15899 				ta = (struct iftun_req *)mp->b_cont->
15900 				    b_cont->b_rptr;
15901 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
15902 					ipif_set_tun_llink(ill, ta);
15903 				}
15904 
15905 			}
15906 			if (mp1 != NULL) {
15907 				/*
15908 				 * Now copy back the b_next/b_prev used by
15909 				 * mi code for the mi_copy* functions.
15910 				 * See ip_sioctl_tunparam() for the reason.
15911 				 * Also protect against missing b_cont.
15912 				 */
15913 				if (mp->b_cont != NULL) {
15914 					mp->b_cont->b_next =
15915 					    mp1->b_cont->b_next;
15916 					mp->b_cont->b_prev =
15917 					    mp1->b_cont->b_prev;
15918 				}
15919 				inet_freemsg(mp1);
15920 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15921 				ASSERT(connp != NULL);
15922 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15923 				    iocp->ioc_error, NO_COPYOUT,
15924 				    ipsq->ipsq_current_ipif, ipsq);
15925 			} else {
15926 				ASSERT(connp == NULL);
15927 				putnext(q, mp);
15928 			}
15929 			break;
15930 		case SIOCGTUNPARAM:
15931 		case OSIOCGTUNPARAM:
15932 			/*
15933 			 * This is really M_IOCDATA from the tunnel driver.
15934 			 * convert back and complete the ioctl.
15935 			 * We should have an IOCTL waiting on this.
15936 			 */
15937 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
15938 			if (mp1) {
15939 				/*
15940 				 * Now copy back the b_next/b_prev used by
15941 				 * mi code for the mi_copy* functions.
15942 				 * See ip_sioctl_tunparam() for the reason.
15943 				 * Also protect against missing b_cont.
15944 				 */
15945 				if (mp->b_cont != NULL) {
15946 					mp->b_cont->b_next =
15947 					    mp1->b_cont->b_next;
15948 					mp->b_cont->b_prev =
15949 					    mp1->b_cont->b_prev;
15950 				}
15951 				inet_freemsg(mp1);
15952 				if (iocp->ioc_error == 0)
15953 					mp->b_datap->db_type = M_IOCDATA;
15954 				ASSERT(connp != NULL);
15955 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15956 				    iocp->ioc_error, COPYOUT, NULL, NULL);
15957 			} else {
15958 				ASSERT(connp == NULL);
15959 				putnext(q, mp);
15960 			}
15961 			break;
15962 		default:
15963 			break;
15964 		}
15965 		break;
15966 	case M_IOCNAK:
15967 		iocp = (struct iocblk *)mp->b_rptr;
15968 
15969 		switch (iocp->ioc_cmd) {
15970 		int mode;
15971 		ipif_t	*ipif;
15972 
15973 		case DL_IOC_HDR_INFO:
15974 			/*
15975 			 * If this was the first attempt turn of the
15976 			 * fastpath probing.
15977 			 */
15978 			mutex_enter(&ill->ill_lock);
15979 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
15980 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
15981 				mutex_exit(&ill->ill_lock);
15982 				ill_fastpath_nack(ill);
15983 				ip1dbg(("ip_rput: DLPI fastpath off on "
15984 				    "interface %s\n",
15985 				    ill->ill_name));
15986 			} else {
15987 				mutex_exit(&ill->ill_lock);
15988 			}
15989 			freemsg(mp);
15990 			break;
15991 		case SIOCSTUNPARAM:
15992 		case OSIOCSTUNPARAM:
15993 			ASSERT(ipsq != NULL);
15994 			/*
15995 			 * Finish socket ioctl passed through to tun
15996 			 * We should have an IOCTL waiting on this.
15997 			 */
15998 			/* FALLTHRU */
15999 		case SIOCGTUNPARAM:
16000 		case OSIOCGTUNPARAM:
16001 			/*
16002 			 * This is really M_IOCDATA from the tunnel driver.
16003 			 * convert back and complete the ioctl.
16004 			 * We should have an IOCTL waiting on this.
16005 			 */
16006 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16007 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16008 				mp1 = ill_pending_mp_get(ill, &connp,
16009 				    iocp->ioc_id);
16010 				mode = COPYOUT;
16011 				ipsq = NULL;
16012 				ipif = NULL;
16013 			} else {
16014 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16015 				mode = NO_COPYOUT;
16016 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16017 				ipif = ipsq->ipsq_current_ipif;
16018 			}
16019 			if (mp1 != NULL) {
16020 				/*
16021 				 * Now copy back the b_next/b_prev used by
16022 				 * mi code for the mi_copy* functions.
16023 				 * See ip_sioctl_tunparam() for the reason.
16024 				 * Also protect against missing b_cont.
16025 				 */
16026 				if (mp->b_cont != NULL) {
16027 					mp->b_cont->b_next =
16028 					    mp1->b_cont->b_next;
16029 					mp->b_cont->b_prev =
16030 					    mp1->b_cont->b_prev;
16031 				}
16032 				inet_freemsg(mp1);
16033 				if (iocp->ioc_error == 0)
16034 					iocp->ioc_error = EINVAL;
16035 				ASSERT(connp != NULL);
16036 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16037 				    iocp->ioc_error, mode, ipif, ipsq);
16038 			} else {
16039 				ASSERT(connp == NULL);
16040 				putnext(q, mp);
16041 			}
16042 			break;
16043 		default:
16044 			break;
16045 		}
16046 	default:
16047 		break;
16048 	}
16049 }
16050 
16051 /*
16052  * NOTE : This function does not ire_refrele the ire argument passed in.
16053  *
16054  * IPQoS notes
16055  * IP policy is invoked twice for a forwarded packet, once on the read side
16056  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16057  * enabled. An additional parameter, in_ill, has been added for this purpose.
16058  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16059  * because ip_mroute drops this information.
16060  *
16061  */
16062 void
16063 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16064 {
16065 	uint32_t	pkt_len;
16066 	queue_t	*q;
16067 	uint32_t	sum;
16068 #define	rptr	((uchar_t *)ipha)
16069 	uint32_t	max_frag;
16070 	uint32_t	ill_index;
16071 
16072 	/* Get the ill_index of the incoming ILL */
16073 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16074 
16075 	/* Initiate Read side IPPF processing */
16076 	if (IPP_ENABLED(IPP_FWD_IN)) {
16077 		ip_process(IPP_FWD_IN, &mp, ill_index);
16078 		if (mp == NULL) {
16079 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16080 			    "during IPPF processing\n"));
16081 			return;
16082 		}
16083 	}
16084 
16085 	pkt_len = ntohs(ipha->ipha_length);
16086 
16087 	/* Adjust the checksum to reflect the ttl decrement. */
16088 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16089 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16090 
16091 	if (ipha->ipha_ttl-- <= 1) {
16092 		if (ip_csum_hdr(ipha)) {
16093 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16094 			goto drop_pkt;
16095 		}
16096 		/*
16097 		 * Note: ire_stq this will be NULL for multicast
16098 		 * datagrams using the long path through arp (the IRE
16099 		 * is not an IRE_CACHE). This should not cause
16100 		 * problems since we don't generate ICMP errors for
16101 		 * multicast packets.
16102 		 */
16103 		q = ire->ire_stq;
16104 		if (q != NULL) {
16105 			/* Sent by forwarding path, and router is global zone */
16106 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16107 			    GLOBAL_ZONEID);
16108 		} else
16109 			freemsg(mp);
16110 		return;
16111 	}
16112 
16113 	/*
16114 	 * Don't forward if the interface is down
16115 	 */
16116 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16117 		BUMP_MIB(&ip_mib, ipInDiscards);
16118 		ip2dbg(("ip_rput_forward:interface is down\n"));
16119 		goto drop_pkt;
16120 	}
16121 
16122 	/* Get the ill_index of the outgoing ILL */
16123 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16124 
16125 	if (is_system_labeled()) {
16126 		mblk_t *mp1;
16127 
16128 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16129 			BUMP_MIB(&ip_mib, ipForwProhibits);
16130 			goto drop_pkt;
16131 		}
16132 		/* Size may have changed */
16133 		mp = mp1;
16134 		ipha = (ipha_t *)mp->b_rptr;
16135 		pkt_len = ntohs(ipha->ipha_length);
16136 	}
16137 
16138 	/* Check if there are options to update */
16139 	if (!IS_SIMPLE_IPH(ipha)) {
16140 		if (ip_csum_hdr(ipha)) {
16141 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16142 			goto drop_pkt;
16143 		}
16144 		if (ip_rput_forward_options(mp, ipha, ire)) {
16145 			return;
16146 		}
16147 
16148 		ipha->ipha_hdr_checksum = 0;
16149 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16150 	}
16151 	max_frag = ire->ire_max_frag;
16152 	if (pkt_len > max_frag) {
16153 		/*
16154 		 * It needs fragging on its way out.  We haven't
16155 		 * verified the header checksum yet.  Since we
16156 		 * are going to put a surely good checksum in the
16157 		 * outgoing header, we have to make sure that it
16158 		 * was good coming in.
16159 		 */
16160 		if (ip_csum_hdr(ipha)) {
16161 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16162 			goto drop_pkt;
16163 		}
16164 		/* Initiate Write side IPPF processing */
16165 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16166 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16167 			if (mp == NULL) {
16168 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16169 				    " during IPPF processing\n"));
16170 				return;
16171 			}
16172 		}
16173 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
16174 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16175 		return;
16176 	}
16177 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16178 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16179 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16180 	/* ip_xmit_v4 always consumes the packet */
16181 	return;
16182 
16183 drop_pkt:;
16184 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16185 	freemsg(mp);
16186 #undef	rptr
16187 }
16188 
16189 void
16190 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16191 {
16192 	ire_t	*ire;
16193 
16194 	ASSERT(!ipif->ipif_isv6);
16195 	/*
16196 	 * Find an IRE which matches the destination and the outgoing
16197 	 * queue in the cache table. All we need is an IRE_CACHE which
16198 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16199 	 * then it is enough to have some IRE_CACHE in the group.
16200 	 */
16201 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16202 		dst = ipif->ipif_pp_dst_addr;
16203 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16204 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16205 	if (ire == NULL) {
16206 		/*
16207 		 * Mark this packet to make it be delivered to
16208 		 * ip_rput_forward after the new ire has been
16209 		 * created.
16210 		 */
16211 		mp->b_prev = NULL;
16212 		mp->b_next = mp;
16213 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16214 		    NULL, 0, GLOBAL_ZONEID);
16215 	} else {
16216 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16217 		IRE_REFRELE(ire);
16218 	}
16219 }
16220 
16221 /* Update any source route, record route or timestamp options */
16222 static int
16223 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16224 {
16225 	ipoptp_t	opts;
16226 	uchar_t		*opt;
16227 	uint8_t		optval;
16228 	uint8_t		optlen;
16229 	ipaddr_t	dst;
16230 	uint32_t	ts;
16231 	ire_t		*dst_ire = NULL;
16232 	ire_t		*tmp_ire = NULL;
16233 	timestruc_t	now;
16234 
16235 	ip2dbg(("ip_rput_forward_options\n"));
16236 	dst = ipha->ipha_dst;
16237 	for (optval = ipoptp_first(&opts, ipha);
16238 	    optval != IPOPT_EOL;
16239 	    optval = ipoptp_next(&opts)) {
16240 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16241 		opt = opts.ipoptp_cur;
16242 		optlen = opts.ipoptp_len;
16243 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16244 		    optval, opts.ipoptp_len));
16245 		switch (optval) {
16246 			uint32_t off;
16247 		case IPOPT_SSRR:
16248 		case IPOPT_LSRR:
16249 			/* Check if adminstratively disabled */
16250 			if (!ip_forward_src_routed) {
16251 				BUMP_MIB(&ip_mib, ipForwProhibits);
16252 				if (ire->ire_stq != NULL) {
16253 					/*
16254 					 * Sent by forwarding path, and router
16255 					 * is global zone
16256 					 */
16257 					icmp_unreachable(ire->ire_stq, mp,
16258 					    ICMP_SOURCE_ROUTE_FAILED,
16259 					    GLOBAL_ZONEID);
16260 				} else {
16261 					ip0dbg(("ip_rput_forward_options: "
16262 					    "unable to send unreach\n"));
16263 					freemsg(mp);
16264 				}
16265 				return (-1);
16266 			}
16267 
16268 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16269 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16270 			if (dst_ire == NULL) {
16271 				/*
16272 				 * Must be partial since ip_rput_options
16273 				 * checked for strict.
16274 				 */
16275 				break;
16276 			}
16277 			off = opt[IPOPT_OFFSET];
16278 			off--;
16279 		redo_srr:
16280 			if (optlen < IP_ADDR_LEN ||
16281 			    off > optlen - IP_ADDR_LEN) {
16282 				/* End of source route */
16283 				ip1dbg((
16284 				    "ip_rput_forward_options: end of SR\n"));
16285 				ire_refrele(dst_ire);
16286 				break;
16287 			}
16288 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16289 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16290 			    IP_ADDR_LEN);
16291 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16292 			    ntohl(dst)));
16293 
16294 			/*
16295 			 * Check if our address is present more than
16296 			 * once as consecutive hops in source route.
16297 			 */
16298 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16299 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16300 			if (tmp_ire != NULL) {
16301 				ire_refrele(tmp_ire);
16302 				off += IP_ADDR_LEN;
16303 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16304 				goto redo_srr;
16305 			}
16306 			ipha->ipha_dst = dst;
16307 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16308 			ire_refrele(dst_ire);
16309 			break;
16310 		case IPOPT_RR:
16311 			off = opt[IPOPT_OFFSET];
16312 			off--;
16313 			if (optlen < IP_ADDR_LEN ||
16314 			    off > optlen - IP_ADDR_LEN) {
16315 				/* No more room - ignore */
16316 				ip1dbg((
16317 				    "ip_rput_forward_options: end of RR\n"));
16318 				break;
16319 			}
16320 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16321 			    IP_ADDR_LEN);
16322 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16323 			break;
16324 		case IPOPT_TS:
16325 			/* Insert timestamp if there is room */
16326 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16327 			case IPOPT_TS_TSONLY:
16328 				off = IPOPT_TS_TIMELEN;
16329 				break;
16330 			case IPOPT_TS_PRESPEC:
16331 			case IPOPT_TS_PRESPEC_RFC791:
16332 				/* Verify that the address matched */
16333 				off = opt[IPOPT_OFFSET] - 1;
16334 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16335 				dst_ire = ire_ctable_lookup(dst, 0,
16336 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16337 				    MATCH_IRE_TYPE);
16338 
16339 				if (dst_ire == NULL) {
16340 					/* Not for us */
16341 					break;
16342 				}
16343 				ire_refrele(dst_ire);
16344 				/* FALLTHRU */
16345 			case IPOPT_TS_TSANDADDR:
16346 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16347 				break;
16348 			default:
16349 				/*
16350 				 * ip_*put_options should have already
16351 				 * dropped this packet.
16352 				 */
16353 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16354 				    "unknown IT - bug in ip_rput_options?\n");
16355 				return (0);	/* Keep "lint" happy */
16356 			}
16357 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16358 				/* Increase overflow counter */
16359 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16360 				opt[IPOPT_POS_OV_FLG] =
16361 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16362 				    (off << 4));
16363 				break;
16364 			}
16365 			off = opt[IPOPT_OFFSET] - 1;
16366 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16367 			case IPOPT_TS_PRESPEC:
16368 			case IPOPT_TS_PRESPEC_RFC791:
16369 			case IPOPT_TS_TSANDADDR:
16370 				bcopy(&ire->ire_src_addr,
16371 				    (char *)opt + off, IP_ADDR_LEN);
16372 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16373 				/* FALLTHRU */
16374 			case IPOPT_TS_TSONLY:
16375 				off = opt[IPOPT_OFFSET] - 1;
16376 				/* Compute # of milliseconds since midnight */
16377 				gethrestime(&now);
16378 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16379 				    now.tv_nsec / (NANOSEC / MILLISEC);
16380 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16381 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16382 				break;
16383 			}
16384 			break;
16385 		}
16386 	}
16387 	return (0);
16388 }
16389 
16390 /*
16391  * This is called after processing at least one of AH/ESP headers.
16392  *
16393  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16394  * the actual, physical interface on which the packet was received,
16395  * but, when ip_strict_dst_multihoming is set to 1, could be the
16396  * interface which had the ipha_dst configured when the packet went
16397  * through ip_rput. The ill_index corresponding to the recv_ill
16398  * is saved in ipsec_in_rill_index
16399  */
16400 void
16401 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16402 {
16403 	mblk_t *mp;
16404 	ipaddr_t dst;
16405 	in6_addr_t *v6dstp;
16406 	ipha_t *ipha;
16407 	ip6_t *ip6h;
16408 	ipsec_in_t *ii;
16409 	boolean_t ill_need_rele = B_FALSE;
16410 	boolean_t rill_need_rele = B_FALSE;
16411 	boolean_t ire_need_rele = B_FALSE;
16412 
16413 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16414 	ASSERT(ii->ipsec_in_ill_index != 0);
16415 
16416 	mp = ipsec_mp->b_cont;
16417 	ASSERT(mp != NULL);
16418 
16419 
16420 	if (ill == NULL) {
16421 		ASSERT(recv_ill == NULL);
16422 		/*
16423 		 * We need to get the original queue on which ip_rput_local
16424 		 * or ip_rput_data_v6 was called.
16425 		 */
16426 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16427 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16428 		ill_need_rele = B_TRUE;
16429 
16430 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16431 			recv_ill = ill_lookup_on_ifindex(
16432 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16433 			    NULL, NULL, NULL, NULL);
16434 			rill_need_rele = B_TRUE;
16435 		} else {
16436 			recv_ill = ill;
16437 		}
16438 
16439 		if ((ill == NULL) || (recv_ill == NULL)) {
16440 			ip0dbg(("ip_fanout_proto_again: interface "
16441 			    "disappeared\n"));
16442 			if (ill != NULL)
16443 				ill_refrele(ill);
16444 			if (recv_ill != NULL)
16445 				ill_refrele(recv_ill);
16446 			freemsg(ipsec_mp);
16447 			return;
16448 		}
16449 	}
16450 
16451 	ASSERT(ill != NULL && recv_ill != NULL);
16452 
16453 	if (mp->b_datap->db_type == M_CTL) {
16454 		/*
16455 		 * AH/ESP is returning the ICMP message after
16456 		 * removing their headers. Fanout again till
16457 		 * it gets to the right protocol.
16458 		 */
16459 		if (ii->ipsec_in_v4) {
16460 			icmph_t *icmph;
16461 			int iph_hdr_length;
16462 			int hdr_length;
16463 
16464 			ipha = (ipha_t *)mp->b_rptr;
16465 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16466 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16467 			ipha = (ipha_t *)&icmph[1];
16468 			hdr_length = IPH_HDR_LENGTH(ipha);
16469 			/*
16470 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16471 			 * Reset the type to M_DATA.
16472 			 */
16473 			mp->b_datap->db_type = M_DATA;
16474 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16475 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16476 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16477 		} else {
16478 			icmp6_t *icmp6;
16479 			int hdr_length;
16480 
16481 			ip6h = (ip6_t *)mp->b_rptr;
16482 			/* Don't call hdr_length_v6() unless you have to. */
16483 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16484 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16485 			else
16486 				hdr_length = IPV6_HDR_LEN;
16487 
16488 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16489 			/*
16490 			 * icmp_inbound_error_fanout_v6 may need to do
16491 			 * pullupmsg.  Reset the type to M_DATA.
16492 			 */
16493 			mp->b_datap->db_type = M_DATA;
16494 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16495 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16496 		}
16497 		if (ill_need_rele)
16498 			ill_refrele(ill);
16499 		if (rill_need_rele)
16500 			ill_refrele(recv_ill);
16501 		return;
16502 	}
16503 
16504 	if (ii->ipsec_in_v4) {
16505 		ipha = (ipha_t *)mp->b_rptr;
16506 		dst = ipha->ipha_dst;
16507 		if (CLASSD(dst)) {
16508 			/*
16509 			 * Multicast has to be delivered to all streams.
16510 			 */
16511 			dst = INADDR_BROADCAST;
16512 		}
16513 
16514 		if (ire == NULL) {
16515 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16516 			    MBLK_GETLABEL(mp));
16517 			if (ire == NULL) {
16518 				if (ill_need_rele)
16519 					ill_refrele(ill);
16520 				if (rill_need_rele)
16521 					ill_refrele(recv_ill);
16522 				ip1dbg(("ip_fanout_proto_again: "
16523 				    "IRE not found"));
16524 				freemsg(ipsec_mp);
16525 				return;
16526 			}
16527 			ire_need_rele = B_TRUE;
16528 		}
16529 
16530 		switch (ipha->ipha_protocol) {
16531 			case IPPROTO_UDP:
16532 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16533 				    recv_ill);
16534 				if (ire_need_rele)
16535 					ire_refrele(ire);
16536 				break;
16537 			case IPPROTO_TCP:
16538 				if (!ire_need_rele)
16539 					IRE_REFHOLD(ire);
16540 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16541 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16542 				IRE_REFRELE(ire);
16543 				if (mp != NULL)
16544 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16545 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16546 				break;
16547 			case IPPROTO_SCTP:
16548 				if (!ire_need_rele)
16549 					IRE_REFHOLD(ire);
16550 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16551 				    ipsec_mp, 0, ill->ill_rq, dst);
16552 				break;
16553 			default:
16554 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16555 				    recv_ill);
16556 				if (ire_need_rele)
16557 					ire_refrele(ire);
16558 				break;
16559 		}
16560 	} else {
16561 		uint32_t rput_flags = 0;
16562 
16563 		ip6h = (ip6_t *)mp->b_rptr;
16564 		v6dstp = &ip6h->ip6_dst;
16565 		/*
16566 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16567 		 * address.
16568 		 *
16569 		 * Currently, we don't store that state in the IPSEC_IN
16570 		 * message, and we may need to.
16571 		 */
16572 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16573 		    IP6_IN_LLMCAST : 0);
16574 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16575 		    NULL, NULL);
16576 	}
16577 	if (ill_need_rele)
16578 		ill_refrele(ill);
16579 	if (rill_need_rele)
16580 		ill_refrele(recv_ill);
16581 }
16582 
16583 /*
16584  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16585  * returns 'true' if there are still fragments left on the queue, in
16586  * which case we restart the timer.
16587  */
16588 void
16589 ill_frag_timer(void *arg)
16590 {
16591 	ill_t	*ill = (ill_t *)arg;
16592 	boolean_t frag_pending;
16593 
16594 	mutex_enter(&ill->ill_lock);
16595 	ASSERT(!ill->ill_fragtimer_executing);
16596 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16597 		ill->ill_frag_timer_id = 0;
16598 		mutex_exit(&ill->ill_lock);
16599 		return;
16600 	}
16601 	ill->ill_fragtimer_executing = 1;
16602 	mutex_exit(&ill->ill_lock);
16603 
16604 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16605 
16606 	/*
16607 	 * Restart the timer, if we have fragments pending or if someone
16608 	 * wanted us to be scheduled again.
16609 	 */
16610 	mutex_enter(&ill->ill_lock);
16611 	ill->ill_fragtimer_executing = 0;
16612 	ill->ill_frag_timer_id = 0;
16613 	if (frag_pending || ill->ill_fragtimer_needrestart)
16614 		ill_frag_timer_start(ill);
16615 	mutex_exit(&ill->ill_lock);
16616 }
16617 
16618 void
16619 ill_frag_timer_start(ill_t *ill)
16620 {
16621 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16622 
16623 	/* If the ill is closing or opening don't proceed */
16624 	if (ill->ill_state_flags & ILL_CONDEMNED)
16625 		return;
16626 
16627 	if (ill->ill_fragtimer_executing) {
16628 		/*
16629 		 * ill_frag_timer is currently executing. Just record the
16630 		 * the fact that we want the timer to be restarted.
16631 		 * ill_frag_timer will post a timeout before it returns,
16632 		 * ensuring it will be called again.
16633 		 */
16634 		ill->ill_fragtimer_needrestart = 1;
16635 		return;
16636 	}
16637 
16638 	if (ill->ill_frag_timer_id == 0) {
16639 		/*
16640 		 * The timer is neither running nor is the timeout handler
16641 		 * executing. Post a timeout so that ill_frag_timer will be
16642 		 * called
16643 		 */
16644 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16645 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16646 		ill->ill_fragtimer_needrestart = 0;
16647 	}
16648 }
16649 
16650 /*
16651  * This routine is needed for loopback when forwarding multicasts.
16652  *
16653  * IPQoS Notes:
16654  * IPPF processing is done in fanout routines.
16655  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16656  * processing for IPSec packets is done when it comes back in clear.
16657  * NOTE : The callers of this function need to do the ire_refrele for the
16658  *	  ire that is being passed in.
16659  */
16660 void
16661 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16662     ill_t *recv_ill)
16663 {
16664 	ill_t	*ill = (ill_t *)q->q_ptr;
16665 	uint32_t	sum;
16666 	uint32_t	u1;
16667 	uint32_t	u2;
16668 	int		hdr_length;
16669 	boolean_t	mctl_present;
16670 	mblk_t		*first_mp = mp;
16671 	mblk_t		*hada_mp = NULL;
16672 	ipha_t		*inner_ipha;
16673 
16674 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16675 	    "ip_rput_locl_start: q %p", q);
16676 
16677 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16678 
16679 
16680 #define	rptr	((uchar_t *)ipha)
16681 #define	iphs	((uint16_t *)ipha)
16682 
16683 	/*
16684 	 * no UDP or TCP packet should come here anymore.
16685 	 */
16686 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16687 	    (ipha->ipha_protocol != IPPROTO_UDP));
16688 
16689 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16690 	if (mctl_present &&
16691 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16692 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16693 
16694 		/*
16695 		 * It's an IPsec accelerated packet.
16696 		 * Keep a pointer to the data attributes around until
16697 		 * we allocate the ipsec_info_t.
16698 		 */
16699 		IPSECHW_DEBUG(IPSECHW_PKT,
16700 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16701 		hada_mp = first_mp;
16702 		hada_mp->b_cont = NULL;
16703 		/*
16704 		 * Since it is accelerated, it comes directly from
16705 		 * the ill and the data attributes is followed by
16706 		 * the packet data.
16707 		 */
16708 		ASSERT(mp->b_datap->db_type != M_CTL);
16709 		first_mp = mp;
16710 		mctl_present = B_FALSE;
16711 	}
16712 
16713 	/*
16714 	 * IF M_CTL is not present, then ipsec_in_is_secure
16715 	 * should return B_TRUE. There is a case where loopback
16716 	 * packets has an M_CTL in the front with all the
16717 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16718 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16719 	 * packets never comes here, it is safe to ASSERT the
16720 	 * following.
16721 	 */
16722 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16723 
16724 
16725 	/* u1 is # words of IP options */
16726 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16727 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16728 
16729 	if (u1) {
16730 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16731 			if (hada_mp != NULL)
16732 				freemsg(hada_mp);
16733 			return;
16734 		}
16735 	} else {
16736 		/* Check the IP header checksum.  */
16737 #define	uph	((uint16_t *)ipha)
16738 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16739 		    uph[6] + uph[7] + uph[8] + uph[9];
16740 #undef  uph
16741 		/* finish doing IP checksum */
16742 		sum = (sum & 0xFFFF) + (sum >> 16);
16743 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16744 		/*
16745 		 * Don't verify header checksum if this packet is coming
16746 		 * back from AH/ESP as we already did it.
16747 		 */
16748 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16749 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16750 			goto drop_pkt;
16751 		}
16752 	}
16753 
16754 	/*
16755 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16756 	 * might be called more than once for secure packets, count only
16757 	 * the first time.
16758 	 */
16759 	if (!mctl_present) {
16760 		UPDATE_IB_PKT_COUNT(ire);
16761 		ire->ire_last_used_time = lbolt;
16762 	}
16763 
16764 	/* Check for fragmentation offset. */
16765 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16766 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16767 	if (u1) {
16768 		/*
16769 		 * We re-assemble fragments before we do the AH/ESP
16770 		 * processing. Thus, M_CTL should not be present
16771 		 * while we are re-assembling.
16772 		 */
16773 		ASSERT(!mctl_present);
16774 		ASSERT(first_mp == mp);
16775 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16776 			return;
16777 		}
16778 		/*
16779 		 * Make sure that first_mp points back to mp as
16780 		 * the mp we came in with could have changed in
16781 		 * ip_rput_fragment().
16782 		 */
16783 		ipha = (ipha_t *)mp->b_rptr;
16784 		first_mp = mp;
16785 	}
16786 
16787 	/*
16788 	 * Clear hardware checksumming flag as it is currently only
16789 	 * used by TCP and UDP.
16790 	 */
16791 	DB_CKSUMFLAGS(mp) = 0;
16792 
16793 	/* Now we have a complete datagram, destined for this machine. */
16794 	u1 = IPH_HDR_LENGTH(ipha);
16795 	switch (ipha->ipha_protocol) {
16796 	case IPPROTO_ICMP: {
16797 		ire_t		*ire_zone;
16798 		ilm_t		*ilm;
16799 		mblk_t		*mp1;
16800 		zoneid_t	last_zoneid;
16801 
16802 		if (CLASSD(ipha->ipha_dst) &&
16803 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
16804 			ASSERT(ire->ire_type == IRE_BROADCAST);
16805 			/*
16806 			 * In the multicast case, applications may have joined
16807 			 * the group from different zones, so we need to deliver
16808 			 * the packet to each of them. Loop through the
16809 			 * multicast memberships structures (ilm) on the receive
16810 			 * ill and send a copy of the packet up each matching
16811 			 * one. However, we don't do this for multicasts sent on
16812 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16813 			 * they must stay in the sender's zone.
16814 			 *
16815 			 * ilm_add_v6() ensures that ilms in the same zone are
16816 			 * contiguous in the ill_ilm list. We use this property
16817 			 * to avoid sending duplicates needed when two
16818 			 * applications in the same zone join the same group on
16819 			 * different logical interfaces: we ignore the ilm if
16820 			 * its zoneid is the same as the last matching one.
16821 			 * In addition, the sending of the packet for
16822 			 * ire_zoneid is delayed until all of the other ilms
16823 			 * have been exhausted.
16824 			 */
16825 			last_zoneid = -1;
16826 			ILM_WALKER_HOLD(recv_ill);
16827 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
16828 			    ilm = ilm->ilm_next) {
16829 				if ((ilm->ilm_flags & ILM_DELETED) ||
16830 				    ipha->ipha_dst != ilm->ilm_addr ||
16831 				    ilm->ilm_zoneid == last_zoneid ||
16832 				    ilm->ilm_zoneid == ire->ire_zoneid ||
16833 				    ilm->ilm_zoneid == ALL_ZONES ||
16834 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
16835 					continue;
16836 				mp1 = ip_copymsg(first_mp);
16837 				if (mp1 == NULL)
16838 					continue;
16839 				icmp_inbound(q, mp1, B_TRUE, ill,
16840 				    0, sum, mctl_present, B_TRUE,
16841 				    recv_ill, ilm->ilm_zoneid);
16842 				last_zoneid = ilm->ilm_zoneid;
16843 			}
16844 			ILM_WALKER_RELE(recv_ill);
16845 		} else if (ire->ire_type == IRE_BROADCAST) {
16846 			/*
16847 			 * In the broadcast case, there may be many zones
16848 			 * which need a copy of the packet delivered to them.
16849 			 * There is one IRE_BROADCAST per broadcast address
16850 			 * and per zone; we walk those using a helper function.
16851 			 * In addition, the sending of the packet for ire is
16852 			 * delayed until all of the other ires have been
16853 			 * processed.
16854 			 */
16855 			IRB_REFHOLD(ire->ire_bucket);
16856 			ire_zone = NULL;
16857 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
16858 			    ire)) != NULL) {
16859 				mp1 = ip_copymsg(first_mp);
16860 				if (mp1 == NULL)
16861 					continue;
16862 
16863 				UPDATE_IB_PKT_COUNT(ire_zone);
16864 				ire_zone->ire_last_used_time = lbolt;
16865 				icmp_inbound(q, mp1, B_TRUE, ill,
16866 				    0, sum, mctl_present, B_TRUE,
16867 				    recv_ill, ire_zone->ire_zoneid);
16868 			}
16869 			IRB_REFRELE(ire->ire_bucket);
16870 		}
16871 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
16872 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
16873 		    ire->ire_zoneid);
16874 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16875 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
16876 		return;
16877 	}
16878 	case IPPROTO_IGMP:
16879 		/*
16880 		 * If we are not willing to accept IGMP packets in clear,
16881 		 * then check with global policy.
16882 		 */
16883 		if (igmp_accept_clear_messages == 0) {
16884 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16885 			    ipha, NULL, mctl_present);
16886 			if (first_mp == NULL)
16887 				return;
16888 		}
16889 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16890 			freemsg(first_mp);
16891 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
16892 			BUMP_MIB(&ip_mib, ipInDiscards);
16893 			return;
16894 		}
16895 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
16896 			/* Bad packet - discarded by igmp_input */
16897 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16898 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
16899 			if (mctl_present)
16900 				freeb(first_mp);
16901 			return;
16902 		}
16903 		/*
16904 		 * igmp_input() may have returned the pulled up message.
16905 		 * So first_mp and ipha need to be reinitialized.
16906 		 */
16907 		ipha = (ipha_t *)mp->b_rptr;
16908 		if (mctl_present)
16909 			first_mp->b_cont = mp;
16910 		else
16911 			first_mp = mp;
16912 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16913 			/* No user-level listener for IGMP packets */
16914 			goto drop_pkt;
16915 		}
16916 		/* deliver to local raw users */
16917 		break;
16918 	case IPPROTO_PIM:
16919 		/*
16920 		 * If we are not willing to accept PIM packets in clear,
16921 		 * then check with global policy.
16922 		 */
16923 		if (pim_accept_clear_messages == 0) {
16924 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16925 			    ipha, NULL, mctl_present);
16926 			if (first_mp == NULL)
16927 				return;
16928 		}
16929 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16930 			freemsg(first_mp);
16931 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
16932 			BUMP_MIB(&ip_mib, ipInDiscards);
16933 			return;
16934 		}
16935 		if (pim_input(q, mp) != 0) {
16936 			/* Bad packet - discarded by pim_input */
16937 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16938 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
16939 			if (mctl_present)
16940 				freeb(first_mp);
16941 			return;
16942 		}
16943 
16944 		/*
16945 		 * pim_input() may have pulled up the message so ipha needs to
16946 		 * be reinitialized.
16947 		 */
16948 		ipha = (ipha_t *)mp->b_rptr;
16949 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16950 			/* No user-level listener for PIM packets */
16951 			goto drop_pkt;
16952 		}
16953 		/* deliver to local raw users */
16954 		break;
16955 	case IPPROTO_ENCAP:
16956 		/*
16957 		 * Handle self-encapsulated packets (IP-in-IP where
16958 		 * the inner addresses == the outer addresses).
16959 		 */
16960 		hdr_length = IPH_HDR_LENGTH(ipha);
16961 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
16962 		    mp->b_wptr) {
16963 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
16964 			    sizeof (ipha_t) - mp->b_rptr)) {
16965 				BUMP_MIB(&ip_mib, ipInDiscards);
16966 				freemsg(first_mp);
16967 				return;
16968 			}
16969 			ipha = (ipha_t *)mp->b_rptr;
16970 		}
16971 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
16972 		/*
16973 		 * Check the sanity of the inner IP header.
16974 		 */
16975 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
16976 			BUMP_MIB(&ip_mib, ipInDiscards);
16977 			freemsg(first_mp);
16978 			return;
16979 		}
16980 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
16981 			BUMP_MIB(&ip_mib, ipInDiscards);
16982 			freemsg(first_mp);
16983 			return;
16984 		}
16985 		if (inner_ipha->ipha_src == ipha->ipha_src &&
16986 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
16987 			ipsec_in_t *ii;
16988 
16989 			/*
16990 			 * Self-encapsulated tunnel packet. Remove
16991 			 * the outer IP header and fanout again.
16992 			 * We also need to make sure that the inner
16993 			 * header is pulled up until options.
16994 			 */
16995 			mp->b_rptr = (uchar_t *)inner_ipha;
16996 			ipha = inner_ipha;
16997 			hdr_length = IPH_HDR_LENGTH(ipha);
16998 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
16999 				if (!pullupmsg(mp, (uchar_t *)ipha +
17000 				    + hdr_length - mp->b_rptr)) {
17001 					freemsg(first_mp);
17002 					return;
17003 				}
17004 				ipha = (ipha_t *)mp->b_rptr;
17005 			}
17006 			if (!mctl_present) {
17007 				ASSERT(first_mp == mp);
17008 				/*
17009 				 * This means that somebody is sending
17010 				 * Self-encapsualted packets without AH/ESP.
17011 				 * If AH/ESP was present, we would have already
17012 				 * allocated the first_mp.
17013 				 */
17014 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
17015 				    NULL) {
17016 					ip1dbg(("ip_proto_input: IPSEC_IN "
17017 					    "allocation failure.\n"));
17018 					BUMP_MIB(&ip_mib, ipInDiscards);
17019 					freemsg(mp);
17020 					return;
17021 				}
17022 				first_mp->b_cont = mp;
17023 			}
17024 			/*
17025 			 * We generally store the ill_index if we need to
17026 			 * do IPSEC processing as we lose the ill queue when
17027 			 * we come back. But in this case, we never should
17028 			 * have to store the ill_index here as it should have
17029 			 * been stored previously when we processed the
17030 			 * AH/ESP header in this routine or for non-ipsec
17031 			 * cases, we still have the queue. But for some bad
17032 			 * packets from the wire, we can get to IPSEC after
17033 			 * this and we better store the index for that case.
17034 			 */
17035 			ill = (ill_t *)q->q_ptr;
17036 			ii = (ipsec_in_t *)first_mp->b_rptr;
17037 			ii->ipsec_in_ill_index =
17038 			    ill->ill_phyint->phyint_ifindex;
17039 			ii->ipsec_in_rill_index =
17040 			    recv_ill->ill_phyint->phyint_ifindex;
17041 			if (ii->ipsec_in_decaps) {
17042 				/*
17043 				 * This packet is self-encapsulated multiple
17044 				 * times. We don't want to recurse infinitely.
17045 				 * To keep it simple, drop the packet.
17046 				 */
17047 				BUMP_MIB(&ip_mib, ipInDiscards);
17048 				freemsg(first_mp);
17049 				return;
17050 			}
17051 			ii->ipsec_in_decaps = B_TRUE;
17052 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
17053 			return;
17054 		}
17055 		break;
17056 	case IPPROTO_AH:
17057 	case IPPROTO_ESP: {
17058 		/*
17059 		 * Fast path for AH/ESP. If this is the first time
17060 		 * we are sending a datagram to AH/ESP, allocate
17061 		 * a IPSEC_IN message and prepend it. Otherwise,
17062 		 * just fanout.
17063 		 */
17064 
17065 		int ipsec_rc;
17066 		ipsec_in_t *ii;
17067 
17068 		IP_STAT(ipsec_proto_ahesp);
17069 		if (!mctl_present) {
17070 			ASSERT(first_mp == mp);
17071 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
17072 				ip1dbg(("ip_proto_input: IPSEC_IN "
17073 				    "allocation failure.\n"));
17074 				freemsg(hada_mp); /* okay ifnull */
17075 				BUMP_MIB(&ip_mib, ipInDiscards);
17076 				freemsg(mp);
17077 				return;
17078 			}
17079 			/*
17080 			 * Store the ill_index so that when we come back
17081 			 * from IPSEC we ride on the same queue.
17082 			 */
17083 			ill = (ill_t *)q->q_ptr;
17084 			ii = (ipsec_in_t *)first_mp->b_rptr;
17085 			ii->ipsec_in_ill_index =
17086 			    ill->ill_phyint->phyint_ifindex;
17087 			ii->ipsec_in_rill_index =
17088 			    recv_ill->ill_phyint->phyint_ifindex;
17089 			first_mp->b_cont = mp;
17090 			/*
17091 			 * Cache hardware acceleration info.
17092 			 */
17093 			if (hada_mp != NULL) {
17094 				IPSECHW_DEBUG(IPSECHW_PKT,
17095 				    ("ip_rput_local: caching data attr.\n"));
17096 				ii->ipsec_in_accelerated = B_TRUE;
17097 				ii->ipsec_in_da = hada_mp;
17098 				hada_mp = NULL;
17099 			}
17100 		} else {
17101 			ii = (ipsec_in_t *)first_mp->b_rptr;
17102 		}
17103 
17104 		if (!ipsec_loaded()) {
17105 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17106 			    ire->ire_zoneid);
17107 			return;
17108 		}
17109 
17110 		/* select inbound SA and have IPsec process the pkt */
17111 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17112 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17113 			if (esph == NULL)
17114 				return;
17115 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17116 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17117 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17118 			    first_mp, esph);
17119 		} else {
17120 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17121 			if (ah == NULL)
17122 				return;
17123 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17124 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17125 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17126 			    first_mp, ah);
17127 		}
17128 
17129 		switch (ipsec_rc) {
17130 		case IPSEC_STATUS_SUCCESS:
17131 			break;
17132 		case IPSEC_STATUS_FAILED:
17133 			BUMP_MIB(&ip_mib, ipInDiscards);
17134 			/* FALLTHRU */
17135 		case IPSEC_STATUS_PENDING:
17136 			return;
17137 		}
17138 		/* we're done with IPsec processing, send it up */
17139 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17140 		return;
17141 	}
17142 	default:
17143 		break;
17144 	}
17145 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17146 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17147 		    ire->ire_zoneid));
17148 		goto drop_pkt;
17149 	}
17150 	/*
17151 	 * Handle protocols with which IP is less intimate.  There
17152 	 * can be more than one stream bound to a particular
17153 	 * protocol.  When this is the case, each one gets a copy
17154 	 * of any incoming packets.
17155 	 */
17156 	ip_fanout_proto(q, first_mp, ill, ipha,
17157 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17158 	    B_TRUE, recv_ill, ire->ire_zoneid);
17159 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17160 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17161 	return;
17162 
17163 drop_pkt:
17164 	freemsg(first_mp);
17165 	if (hada_mp != NULL)
17166 		freeb(hada_mp);
17167 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17168 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17169 #undef	rptr
17170 #undef  iphs
17171 
17172 }
17173 
17174 /*
17175  * Update any source route, record route or timestamp options.
17176  * Check that we are at end of strict source route.
17177  * The options have already been checked for sanity in ip_rput_options().
17178  */
17179 static boolean_t
17180 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17181 {
17182 	ipoptp_t	opts;
17183 	uchar_t		*opt;
17184 	uint8_t		optval;
17185 	uint8_t		optlen;
17186 	ipaddr_t	dst;
17187 	uint32_t	ts;
17188 	ire_t		*dst_ire;
17189 	timestruc_t	now;
17190 	zoneid_t	zoneid;
17191 	ill_t		*ill;
17192 
17193 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17194 
17195 	ip2dbg(("ip_rput_local_options\n"));
17196 
17197 	for (optval = ipoptp_first(&opts, ipha);
17198 	    optval != IPOPT_EOL;
17199 	    optval = ipoptp_next(&opts)) {
17200 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17201 		opt = opts.ipoptp_cur;
17202 		optlen = opts.ipoptp_len;
17203 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17204 		    optval, optlen));
17205 		switch (optval) {
17206 			uint32_t off;
17207 		case IPOPT_SSRR:
17208 		case IPOPT_LSRR:
17209 			off = opt[IPOPT_OFFSET];
17210 			off--;
17211 			if (optlen < IP_ADDR_LEN ||
17212 			    off > optlen - IP_ADDR_LEN) {
17213 				/* End of source route */
17214 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17215 				break;
17216 			}
17217 			/*
17218 			 * This will only happen if two consecutive entries
17219 			 * in the source route contains our address or if
17220 			 * it is a packet with a loose source route which
17221 			 * reaches us before consuming the whole source route
17222 			 */
17223 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17224 			if (optval == IPOPT_SSRR) {
17225 				goto bad_src_route;
17226 			}
17227 			/*
17228 			 * Hack: instead of dropping the packet truncate the
17229 			 * source route to what has been used by filling the
17230 			 * rest with IPOPT_NOP.
17231 			 */
17232 			opt[IPOPT_OLEN] = (uint8_t)off;
17233 			while (off < optlen) {
17234 				opt[off++] = IPOPT_NOP;
17235 			}
17236 			break;
17237 		case IPOPT_RR:
17238 			off = opt[IPOPT_OFFSET];
17239 			off--;
17240 			if (optlen < IP_ADDR_LEN ||
17241 			    off > optlen - IP_ADDR_LEN) {
17242 				/* No more room - ignore */
17243 				ip1dbg((
17244 				    "ip_rput_local_options: end of RR\n"));
17245 				break;
17246 			}
17247 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17248 			    IP_ADDR_LEN);
17249 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17250 			break;
17251 		case IPOPT_TS:
17252 			/* Insert timestamp if there is romm */
17253 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17254 			case IPOPT_TS_TSONLY:
17255 				off = IPOPT_TS_TIMELEN;
17256 				break;
17257 			case IPOPT_TS_PRESPEC:
17258 			case IPOPT_TS_PRESPEC_RFC791:
17259 				/* Verify that the address matched */
17260 				off = opt[IPOPT_OFFSET] - 1;
17261 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17262 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17263 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17264 				if (dst_ire == NULL) {
17265 					/* Not for us */
17266 					break;
17267 				}
17268 				ire_refrele(dst_ire);
17269 				/* FALLTHRU */
17270 			case IPOPT_TS_TSANDADDR:
17271 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17272 				break;
17273 			default:
17274 				/*
17275 				 * ip_*put_options should have already
17276 				 * dropped this packet.
17277 				 */
17278 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17279 				    "unknown IT - bug in ip_rput_options?\n");
17280 				return (B_TRUE);	/* Keep "lint" happy */
17281 			}
17282 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17283 				/* Increase overflow counter */
17284 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17285 				opt[IPOPT_POS_OV_FLG] =
17286 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17287 				    (off << 4));
17288 				break;
17289 			}
17290 			off = opt[IPOPT_OFFSET] - 1;
17291 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17292 			case IPOPT_TS_PRESPEC:
17293 			case IPOPT_TS_PRESPEC_RFC791:
17294 			case IPOPT_TS_TSANDADDR:
17295 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17296 				    IP_ADDR_LEN);
17297 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17298 				/* FALLTHRU */
17299 			case IPOPT_TS_TSONLY:
17300 				off = opt[IPOPT_OFFSET] - 1;
17301 				/* Compute # of milliseconds since midnight */
17302 				gethrestime(&now);
17303 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17304 				    now.tv_nsec / (NANOSEC / MILLISEC);
17305 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17306 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17307 				break;
17308 			}
17309 			break;
17310 		}
17311 	}
17312 	return (B_TRUE);
17313 
17314 bad_src_route:
17315 	q = WR(q);
17316 	if (q->q_next != NULL)
17317 		ill = q->q_ptr;
17318 	else
17319 		ill = NULL;
17320 
17321 	/* make sure we clear any indication of a hardware checksum */
17322 	DB_CKSUMFLAGS(mp) = 0;
17323 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill);
17324 	if (zoneid == ALL_ZONES)
17325 		freemsg(mp);
17326 	else
17327 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17328 	return (B_FALSE);
17329 
17330 }
17331 
17332 /*
17333  * Process IP options in an inbound packet.  If an option affects the
17334  * effective destination address, return the next hop address via dstp.
17335  * Returns -1 if something fails in which case an ICMP error has been sent
17336  * and mp freed.
17337  */
17338 static int
17339 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17340 {
17341 	ipoptp_t	opts;
17342 	uchar_t		*opt;
17343 	uint8_t		optval;
17344 	uint8_t		optlen;
17345 	ipaddr_t	dst;
17346 	intptr_t	code = 0;
17347 	ire_t		*ire = NULL;
17348 	zoneid_t	zoneid;
17349 	ill_t		*ill;
17350 
17351 	ip2dbg(("ip_rput_options\n"));
17352 	dst = ipha->ipha_dst;
17353 	for (optval = ipoptp_first(&opts, ipha);
17354 	    optval != IPOPT_EOL;
17355 	    optval = ipoptp_next(&opts)) {
17356 		opt = opts.ipoptp_cur;
17357 		optlen = opts.ipoptp_len;
17358 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17359 		    optval, optlen));
17360 		/*
17361 		 * Note: we need to verify the checksum before we
17362 		 * modify anything thus this routine only extracts the next
17363 		 * hop dst from any source route.
17364 		 */
17365 		switch (optval) {
17366 			uint32_t off;
17367 		case IPOPT_SSRR:
17368 		case IPOPT_LSRR:
17369 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17370 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17371 			if (ire == NULL) {
17372 				if (optval == IPOPT_SSRR) {
17373 					ip1dbg(("ip_rput_options: not next"
17374 					    " strict source route 0x%x\n",
17375 					    ntohl(dst)));
17376 					code = (char *)&ipha->ipha_dst -
17377 					    (char *)ipha;
17378 					goto param_prob; /* RouterReq's */
17379 				}
17380 				ip2dbg(("ip_rput_options: "
17381 				    "not next source route 0x%x\n",
17382 				    ntohl(dst)));
17383 				break;
17384 			}
17385 			ire_refrele(ire);
17386 
17387 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17388 				ip1dbg((
17389 				    "ip_rput_options: bad option offset\n"));
17390 				code = (char *)&opt[IPOPT_OLEN] -
17391 				    (char *)ipha;
17392 				goto param_prob;
17393 			}
17394 			off = opt[IPOPT_OFFSET];
17395 			off--;
17396 		redo_srr:
17397 			if (optlen < IP_ADDR_LEN ||
17398 			    off > optlen - IP_ADDR_LEN) {
17399 				/* End of source route */
17400 				ip1dbg(("ip_rput_options: end of SR\n"));
17401 				break;
17402 			}
17403 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17404 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17405 			    ntohl(dst)));
17406 
17407 			/*
17408 			 * Check if our address is present more than
17409 			 * once as consecutive hops in source route.
17410 			 * XXX verify per-interface ip_forwarding
17411 			 * for source route?
17412 			 */
17413 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17414 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17415 
17416 			if (ire != NULL) {
17417 				ire_refrele(ire);
17418 				off += IP_ADDR_LEN;
17419 				goto redo_srr;
17420 			}
17421 
17422 			if (dst == htonl(INADDR_LOOPBACK)) {
17423 				ip1dbg(("ip_rput_options: loopback addr in "
17424 				    "source route!\n"));
17425 				goto bad_src_route;
17426 			}
17427 			/*
17428 			 * For strict: verify that dst is directly
17429 			 * reachable.
17430 			 */
17431 			if (optval == IPOPT_SSRR) {
17432 				ire = ire_ftable_lookup(dst, 0, 0,
17433 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17434 				    MBLK_GETLABEL(mp),
17435 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17436 				if (ire == NULL) {
17437 					ip1dbg(("ip_rput_options: SSRR not "
17438 					    "directly reachable: 0x%x\n",
17439 					    ntohl(dst)));
17440 					goto bad_src_route;
17441 				}
17442 				ire_refrele(ire);
17443 			}
17444 			/*
17445 			 * Defer update of the offset and the record route
17446 			 * until the packet is forwarded.
17447 			 */
17448 			break;
17449 		case IPOPT_RR:
17450 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17451 				ip1dbg((
17452 				    "ip_rput_options: bad option offset\n"));
17453 				code = (char *)&opt[IPOPT_OLEN] -
17454 				    (char *)ipha;
17455 				goto param_prob;
17456 			}
17457 			break;
17458 		case IPOPT_TS:
17459 			/*
17460 			 * Verify that length >= 5 and that there is either
17461 			 * room for another timestamp or that the overflow
17462 			 * counter is not maxed out.
17463 			 */
17464 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17465 			if (optlen < IPOPT_MINLEN_IT) {
17466 				goto param_prob;
17467 			}
17468 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17469 				ip1dbg((
17470 				    "ip_rput_options: bad option offset\n"));
17471 				code = (char *)&opt[IPOPT_OFFSET] -
17472 				    (char *)ipha;
17473 				goto param_prob;
17474 			}
17475 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17476 			case IPOPT_TS_TSONLY:
17477 				off = IPOPT_TS_TIMELEN;
17478 				break;
17479 			case IPOPT_TS_TSANDADDR:
17480 			case IPOPT_TS_PRESPEC:
17481 			case IPOPT_TS_PRESPEC_RFC791:
17482 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17483 				break;
17484 			default:
17485 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17486 				    (char *)ipha;
17487 				goto param_prob;
17488 			}
17489 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17490 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17491 				/*
17492 				 * No room and the overflow counter is 15
17493 				 * already.
17494 				 */
17495 				goto param_prob;
17496 			}
17497 			break;
17498 		}
17499 	}
17500 
17501 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17502 		*dstp = dst;
17503 		return (0);
17504 	}
17505 
17506 	ip1dbg(("ip_rput_options: error processing IP options."));
17507 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17508 
17509 param_prob:
17510 	q = WR(q);
17511 	if (q->q_next != NULL)
17512 		ill = q->q_ptr;
17513 	else
17514 		ill = NULL;
17515 
17516 	/* make sure we clear any indication of a hardware checksum */
17517 	DB_CKSUMFLAGS(mp) = 0;
17518 	/* Don't know whether this is for non-global or global/forwarding */
17519 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17520 	if (zoneid == ALL_ZONES)
17521 		freemsg(mp);
17522 	else
17523 		icmp_param_problem(q, mp, (uint8_t)code, zoneid);
17524 	return (-1);
17525 
17526 bad_src_route:
17527 	q = WR(q);
17528 	if (q->q_next != NULL)
17529 		ill = q->q_ptr;
17530 	else
17531 		ill = NULL;
17532 
17533 	/* make sure we clear any indication of a hardware checksum */
17534 	DB_CKSUMFLAGS(mp) = 0;
17535 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17536 	if (zoneid == ALL_ZONES)
17537 		freemsg(mp);
17538 	else
17539 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17540 	return (-1);
17541 }
17542 
17543 /*
17544  * IP & ICMP info in >=14 msg's ...
17545  *  - ip fixed part (mib2_ip_t)
17546  *  - icmp fixed part (mib2_icmp_t)
17547  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17548  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17549  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
17550  *  - ipRouteAttributeTable (ip 102)	labeled routes
17551  *  - ip multicast membership (ip_member_t)
17552  *  - ip multicast source filtering (ip_grpsrc_t)
17553  *  - igmp fixed part (struct igmpstat)
17554  *  - multicast routing stats (struct mrtstat)
17555  *  - multicast routing vifs (array of struct vifctl)
17556  *  - multicast routing routes (array of struct mfcctl)
17557  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17558  *					One per ill plus one generic
17559  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17560  *					One per ill plus one generic
17561  *  - ipv6RouteEntry			all IPv6 IREs
17562  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17563  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17564  *  - ipv6AddrEntry			all IPv6 ipifs
17565  *  - ipv6 multicast membership (ipv6_member_t)
17566  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17567  *
17568  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
17569  * already present.
17570  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17571  * already filled in by the caller.
17572  * Return value of 0 indicates that no messages were sent and caller
17573  * should free mpctl.
17574  */
17575 int
17576 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17577 {
17578 
17579 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17580 		return (0);
17581 	}
17582 
17583 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
17584 		return (1);
17585 	}
17586 
17587 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17588 		return (1);
17589 	}
17590 
17591 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17592 		return (1);
17593 	}
17594 
17595 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17596 		return (1);
17597 	}
17598 
17599 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17600 		return (1);
17601 	}
17602 
17603 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17604 		return (1);
17605 	}
17606 
17607 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17608 		return (1);
17609 	}
17610 
17611 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17612 		return (1);
17613 	}
17614 
17615 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17616 		return (1);
17617 	}
17618 
17619 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17620 		return (1);
17621 	}
17622 
17623 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17624 		return (1);
17625 	}
17626 
17627 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17628 		return (1);
17629 	}
17630 
17631 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17632 		return (1);
17633 	}
17634 
17635 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17636 		return (1);
17637 	}
17638 
17639 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17640 		return (1);
17641 	}
17642 
17643 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17644 		return (1);
17645 	}
17646 
17647 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17648 		return (1);
17649 	}
17650 	freemsg(mpctl);
17651 	return (1);
17652 }
17653 
17654 
17655 /* Get global IPv4 statistics */
17656 static mblk_t *
17657 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
17658 {
17659 	struct opthdr		*optp;
17660 	mblk_t			*mp2ctl;
17661 
17662 	/*
17663 	 * make a copy of the original message
17664 	 */
17665 	mp2ctl = copymsg(mpctl);
17666 
17667 	/* fixed length IP structure... */
17668 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17669 	optp->level = MIB2_IP;
17670 	optp->name = 0;
17671 	SET_MIB(ip_mib.ipForwarding,
17672 	    (WE_ARE_FORWARDING ? 1 : 2));
17673 	SET_MIB(ip_mib.ipDefaultTTL,
17674 	    (uint32_t)ip_def_ttl);
17675 	SET_MIB(ip_mib.ipReasmTimeout,
17676 	    ip_g_frag_timeout);
17677 	SET_MIB(ip_mib.ipAddrEntrySize,
17678 	    sizeof (mib2_ipAddrEntry_t));
17679 	SET_MIB(ip_mib.ipRouteEntrySize,
17680 	    sizeof (mib2_ipRouteEntry_t));
17681 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
17682 	    sizeof (mib2_ipNetToMediaEntry_t));
17683 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17684 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17685 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
17686 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17687 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
17688 	    (int)sizeof (ip_mib))) {
17689 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17690 		    (uint_t)sizeof (ip_mib)));
17691 	}
17692 
17693 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17694 	ip3dbg(("ip_snmp_get_mib2_ip: 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 ICMP statistics */
17701 static mblk_t *
17702 ip_snmp_get_mib2_icmp(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 = MIB2_ICMP;
17714 	optp->name = 0;
17715 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17716 	    (int)sizeof (icmp_mib))) {
17717 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17718 		    (uint_t)sizeof (icmp_mib)));
17719 	}
17720 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17721 	ip3dbg(("ip_snmp_get_mib2_icmp: 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 IGMP statistics */
17728 static mblk_t *
17729 ip_snmp_get_mib2_igmp(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_IGMP;
17741 	optp->name = 0;
17742 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17743 	    (int)sizeof (igmpstat))) {
17744 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17745 		    (uint_t)sizeof (igmpstat)));
17746 	}
17747 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17748 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17749 	    (int)optp->level, (int)optp->name, (int)optp->len));
17750 	qreply(q, mpctl);
17751 	return (mp2ctl);
17752 }
17753 
17754 /* Global IPv4 Multicast Routing statistics */
17755 static mblk_t *
17756 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17757 {
17758 	struct opthdr		*optp;
17759 	mblk_t			*mp2ctl;
17760 
17761 	/*
17762 	 * make a copy of the original message
17763 	 */
17764 	mp2ctl = copymsg(mpctl);
17765 
17766 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17767 	optp->level = EXPER_DVMRP;
17768 	optp->name = 0;
17769 	if (!ip_mroute_stats(mpctl->b_cont)) {
17770 		ip0dbg(("ip_mroute_stats: failed\n"));
17771 	}
17772 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17773 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17774 	    (int)optp->level, (int)optp->name, (int)optp->len));
17775 	qreply(q, mpctl);
17776 	return (mp2ctl);
17777 }
17778 
17779 /* IPv4 address information */
17780 static mblk_t *
17781 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17782 {
17783 	struct opthdr		*optp;
17784 	mblk_t			*mp2ctl;
17785 	mblk_t			*mp_tail = NULL;
17786 	ill_t			*ill;
17787 	ipif_t			*ipif;
17788 	uint_t			bitval;
17789 	mib2_ipAddrEntry_t	mae;
17790 	zoneid_t		zoneid;
17791 	ill_walk_context_t ctx;
17792 
17793 	/*
17794 	 * make a copy of the original message
17795 	 */
17796 	mp2ctl = copymsg(mpctl);
17797 
17798 	/* ipAddrEntryTable */
17799 
17800 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17801 	optp->level = MIB2_IP;
17802 	optp->name = MIB2_IP_ADDR;
17803 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17804 
17805 	rw_enter(&ill_g_lock, RW_READER);
17806 	ill = ILL_START_WALK_V4(&ctx);
17807 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17808 		for (ipif = ill->ill_ipif; ipif != NULL;
17809 		    ipif = ipif->ipif_next) {
17810 			if (ipif->ipif_zoneid != zoneid &&
17811 			    ipif->ipif_zoneid != ALL_ZONES)
17812 				continue;
17813 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17814 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17815 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17816 
17817 			(void) ipif_get_name(ipif,
17818 			    mae.ipAdEntIfIndex.o_bytes,
17819 			    OCTET_LENGTH);
17820 			mae.ipAdEntIfIndex.o_length =
17821 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
17822 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
17823 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
17824 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
17825 			mae.ipAdEntInfo.ae_subnet_len =
17826 			    ip_mask_to_plen(ipif->ipif_net_mask);
17827 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
17828 			for (bitval = 1;
17829 			    bitval &&
17830 			    !(bitval & ipif->ipif_brd_addr);
17831 			    bitval <<= 1)
17832 				noop;
17833 			mae.ipAdEntBcastAddr = bitval;
17834 			mae.ipAdEntReasmMaxSize = 65535;
17835 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
17836 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
17837 			mae.ipAdEntInfo.ae_broadcast_addr =
17838 			    ipif->ipif_brd_addr;
17839 			mae.ipAdEntInfo.ae_pp_dst_addr =
17840 			    ipif->ipif_pp_dst_addr;
17841 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
17842 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17843 
17844 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17845 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
17846 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
17847 				    "allocate %u bytes\n",
17848 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
17849 			}
17850 		}
17851 	}
17852 	rw_exit(&ill_g_lock);
17853 
17854 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17855 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
17856 	    (int)optp->level, (int)optp->name, (int)optp->len));
17857 	qreply(q, mpctl);
17858 	return (mp2ctl);
17859 }
17860 
17861 /* IPv6 address information */
17862 static mblk_t *
17863 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
17864 {
17865 	struct opthdr		*optp;
17866 	mblk_t			*mp2ctl;
17867 	mblk_t			*mp_tail = NULL;
17868 	ill_t			*ill;
17869 	ipif_t			*ipif;
17870 	mib2_ipv6AddrEntry_t	mae6;
17871 	zoneid_t		zoneid;
17872 	ill_walk_context_t	ctx;
17873 
17874 	/*
17875 	 * make a copy of the original message
17876 	 */
17877 	mp2ctl = copymsg(mpctl);
17878 
17879 	/* ipv6AddrEntryTable */
17880 
17881 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17882 	optp->level = MIB2_IP6;
17883 	optp->name = MIB2_IP6_ADDR;
17884 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17885 
17886 	rw_enter(&ill_g_lock, RW_READER);
17887 	ill = ILL_START_WALK_V6(&ctx);
17888 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17889 		for (ipif = ill->ill_ipif; ipif != NULL;
17890 		    ipif = ipif->ipif_next) {
17891 			if (ipif->ipif_zoneid != zoneid &&
17892 			    ipif->ipif_zoneid != ALL_ZONES)
17893 				continue;
17894 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17895 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17896 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17897 
17898 			(void) ipif_get_name(ipif,
17899 			    mae6.ipv6AddrIfIndex.o_bytes,
17900 			    OCTET_LENGTH);
17901 			mae6.ipv6AddrIfIndex.o_length =
17902 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
17903 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
17904 			mae6.ipv6AddrPfxLength =
17905 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
17906 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
17907 			mae6.ipv6AddrInfo.ae_subnet_len =
17908 			    mae6.ipv6AddrPfxLength;
17909 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
17910 
17911 			/* Type: stateless(1), stateful(2), unknown(3) */
17912 			if (ipif->ipif_flags & IPIF_ADDRCONF)
17913 				mae6.ipv6AddrType = 1;
17914 			else
17915 				mae6.ipv6AddrType = 2;
17916 			/* Anycast: true(1), false(2) */
17917 			if (ipif->ipif_flags & IPIF_ANYCAST)
17918 				mae6.ipv6AddrAnycastFlag = 1;
17919 			else
17920 				mae6.ipv6AddrAnycastFlag = 2;
17921 
17922 			/*
17923 			 * Address status: preferred(1), deprecated(2),
17924 			 * invalid(3), inaccessible(4), unknown(5)
17925 			 */
17926 			if (ipif->ipif_flags & IPIF_NOLOCAL)
17927 				mae6.ipv6AddrStatus = 3;
17928 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
17929 				mae6.ipv6AddrStatus = 2;
17930 			else
17931 				mae6.ipv6AddrStatus = 1;
17932 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
17933 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
17934 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
17935 						ipif->ipif_v6pp_dst_addr;
17936 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
17937 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17938 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17939 				(char *)&mae6,
17940 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
17941 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
17942 				    "allocate %u bytes\n",
17943 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
17944 			}
17945 		}
17946 	}
17947 	rw_exit(&ill_g_lock);
17948 
17949 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17950 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
17951 	    (int)optp->level, (int)optp->name, (int)optp->len));
17952 	qreply(q, mpctl);
17953 	return (mp2ctl);
17954 }
17955 
17956 /* IPv4 multicast group membership. */
17957 static mblk_t *
17958 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
17959 {
17960 	struct opthdr		*optp;
17961 	mblk_t			*mp2ctl;
17962 	ill_t			*ill;
17963 	ipif_t			*ipif;
17964 	ilm_t			*ilm;
17965 	ip_member_t		ipm;
17966 	mblk_t			*mp_tail = NULL;
17967 	ill_walk_context_t	ctx;
17968 	zoneid_t		zoneid;
17969 
17970 	/*
17971 	 * make a copy of the original message
17972 	 */
17973 	mp2ctl = copymsg(mpctl);
17974 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17975 
17976 	/* ipGroupMember table */
17977 	optp = (struct opthdr *)&mpctl->b_rptr[
17978 	    sizeof (struct T_optmgmt_ack)];
17979 	optp->level = MIB2_IP;
17980 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
17981 
17982 	rw_enter(&ill_g_lock, RW_READER);
17983 	ill = ILL_START_WALK_V4(&ctx);
17984 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17985 		ILM_WALKER_HOLD(ill);
17986 		for (ipif = ill->ill_ipif; ipif != NULL;
17987 		    ipif = ipif->ipif_next) {
17988 			if (ipif->ipif_zoneid != zoneid &&
17989 			    ipif->ipif_zoneid != ALL_ZONES)
17990 				continue;	/* not this zone */
17991 			(void) ipif_get_name(ipif,
17992 			    ipm.ipGroupMemberIfIndex.o_bytes,
17993 			    OCTET_LENGTH);
17994 			ipm.ipGroupMemberIfIndex.o_length =
17995 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
17996 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17997 				ASSERT(ilm->ilm_ipif != NULL);
17998 				ASSERT(ilm->ilm_ill == NULL);
17999 				if (ilm->ilm_ipif != ipif)
18000 					continue;
18001 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18002 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18003 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18004 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18005 				    (char *)&ipm, (int)sizeof (ipm))) {
18006 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18007 					    "failed to allocate %u bytes\n",
18008 						(uint_t)sizeof (ipm)));
18009 				}
18010 			}
18011 		}
18012 		ILM_WALKER_RELE(ill);
18013 	}
18014 	rw_exit(&ill_g_lock);
18015 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18016 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18017 	    (int)optp->level, (int)optp->name, (int)optp->len));
18018 	qreply(q, mpctl);
18019 	return (mp2ctl);
18020 }
18021 
18022 /* IPv6 multicast group membership. */
18023 static mblk_t *
18024 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
18025 {
18026 	struct opthdr		*optp;
18027 	mblk_t			*mp2ctl;
18028 	ill_t			*ill;
18029 	ilm_t			*ilm;
18030 	ipv6_member_t		ipm6;
18031 	mblk_t			*mp_tail = NULL;
18032 	ill_walk_context_t	ctx;
18033 	zoneid_t		zoneid;
18034 
18035 	/*
18036 	 * make a copy of the original message
18037 	 */
18038 	mp2ctl = copymsg(mpctl);
18039 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18040 
18041 	/* ip6GroupMember table */
18042 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18043 	optp->level = MIB2_IP6;
18044 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18045 
18046 	rw_enter(&ill_g_lock, RW_READER);
18047 	ill = ILL_START_WALK_V6(&ctx);
18048 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18049 		ILM_WALKER_HOLD(ill);
18050 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18051 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18052 			ASSERT(ilm->ilm_ipif == NULL);
18053 			ASSERT(ilm->ilm_ill != NULL);
18054 			if (ilm->ilm_zoneid != zoneid)
18055 				continue;	/* not this zone */
18056 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18057 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18058 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18059 			if (!snmp_append_data2(mpctl->b_cont,
18060 			    &mp_tail,
18061 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18062 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18063 				    "failed to allocate %u bytes\n",
18064 				    (uint_t)sizeof (ipm6)));
18065 			}
18066 		}
18067 		ILM_WALKER_RELE(ill);
18068 	}
18069 	rw_exit(&ill_g_lock);
18070 
18071 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18072 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18073 	    (int)optp->level, (int)optp->name, (int)optp->len));
18074 	qreply(q, mpctl);
18075 	return (mp2ctl);
18076 }
18077 
18078 /* IP multicast filtered sources */
18079 static mblk_t *
18080 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
18081 {
18082 	struct opthdr		*optp;
18083 	mblk_t			*mp2ctl;
18084 	ill_t			*ill;
18085 	ipif_t			*ipif;
18086 	ilm_t			*ilm;
18087 	ip_grpsrc_t		ips;
18088 	mblk_t			*mp_tail = NULL;
18089 	ill_walk_context_t	ctx;
18090 	zoneid_t		zoneid;
18091 	int			i;
18092 	slist_t			*sl;
18093 
18094 	/*
18095 	 * make a copy of the original message
18096 	 */
18097 	mp2ctl = copymsg(mpctl);
18098 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18099 
18100 	/* ipGroupSource table */
18101 	optp = (struct opthdr *)&mpctl->b_rptr[
18102 	    sizeof (struct T_optmgmt_ack)];
18103 	optp->level = MIB2_IP;
18104 	optp->name = EXPER_IP_GROUP_SOURCES;
18105 
18106 	rw_enter(&ill_g_lock, RW_READER);
18107 	ill = ILL_START_WALK_V4(&ctx);
18108 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18109 		ILM_WALKER_HOLD(ill);
18110 		for (ipif = ill->ill_ipif; ipif != NULL;
18111 		    ipif = ipif->ipif_next) {
18112 			if (ipif->ipif_zoneid != zoneid)
18113 				continue;	/* not this zone */
18114 			(void) ipif_get_name(ipif,
18115 			    ips.ipGroupSourceIfIndex.o_bytes,
18116 			    OCTET_LENGTH);
18117 			ips.ipGroupSourceIfIndex.o_length =
18118 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18119 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18120 				ASSERT(ilm->ilm_ipif != NULL);
18121 				ASSERT(ilm->ilm_ill == NULL);
18122 				sl = ilm->ilm_filter;
18123 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18124 					continue;
18125 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18126 				for (i = 0; i < sl->sl_numsrc; i++) {
18127 					if (!IN6_IS_ADDR_V4MAPPED(
18128 					    &sl->sl_addr[i]))
18129 						continue;
18130 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18131 					    ips.ipGroupSourceAddress);
18132 					if (snmp_append_data2(mpctl->b_cont,
18133 					    &mp_tail, (char *)&ips,
18134 					    (int)sizeof (ips)) == 0) {
18135 						ip1dbg(("ip_snmp_get_mib2_"
18136 						    "ip_group_src: failed to "
18137 						    "allocate %u bytes\n",
18138 						    (uint_t)sizeof (ips)));
18139 					}
18140 				}
18141 			}
18142 		}
18143 		ILM_WALKER_RELE(ill);
18144 	}
18145 	rw_exit(&ill_g_lock);
18146 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18147 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18148 	    (int)optp->level, (int)optp->name, (int)optp->len));
18149 	qreply(q, mpctl);
18150 	return (mp2ctl);
18151 }
18152 
18153 /* IPv6 multicast filtered sources. */
18154 static mblk_t *
18155 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18156 {
18157 	struct opthdr		*optp;
18158 	mblk_t			*mp2ctl;
18159 	ill_t			*ill;
18160 	ilm_t			*ilm;
18161 	ipv6_grpsrc_t		ips6;
18162 	mblk_t			*mp_tail = NULL;
18163 	ill_walk_context_t	ctx;
18164 	zoneid_t		zoneid;
18165 	int			i;
18166 	slist_t			*sl;
18167 
18168 	/*
18169 	 * make a copy of the original message
18170 	 */
18171 	mp2ctl = copymsg(mpctl);
18172 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18173 
18174 	/* ip6GroupMember table */
18175 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18176 	optp->level = MIB2_IP6;
18177 	optp->name = EXPER_IP6_GROUP_SOURCES;
18178 
18179 	rw_enter(&ill_g_lock, RW_READER);
18180 	ill = ILL_START_WALK_V6(&ctx);
18181 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18182 		ILM_WALKER_HOLD(ill);
18183 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18184 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18185 			ASSERT(ilm->ilm_ipif == NULL);
18186 			ASSERT(ilm->ilm_ill != NULL);
18187 			sl = ilm->ilm_filter;
18188 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18189 				continue;
18190 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18191 			for (i = 0; i < sl->sl_numsrc; i++) {
18192 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18193 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18194 				    (char *)&ips6, (int)sizeof (ips6))) {
18195 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18196 					    "group_src: failed to allocate "
18197 					    "%u bytes\n",
18198 					    (uint_t)sizeof (ips6)));
18199 				}
18200 			}
18201 		}
18202 		ILM_WALKER_RELE(ill);
18203 	}
18204 	rw_exit(&ill_g_lock);
18205 
18206 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18207 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18208 	    (int)optp->level, (int)optp->name, (int)optp->len));
18209 	qreply(q, mpctl);
18210 	return (mp2ctl);
18211 }
18212 
18213 /* Multicast routing virtual interface table. */
18214 static mblk_t *
18215 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18216 {
18217 	struct opthdr		*optp;
18218 	mblk_t			*mp2ctl;
18219 
18220 	/*
18221 	 * make a copy of the original message
18222 	 */
18223 	mp2ctl = copymsg(mpctl);
18224 
18225 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18226 	optp->level = EXPER_DVMRP;
18227 	optp->name = EXPER_DVMRP_VIF;
18228 	if (!ip_mroute_vif(mpctl->b_cont)) {
18229 		ip0dbg(("ip_mroute_vif: failed\n"));
18230 	}
18231 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18232 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18233 	    (int)optp->level, (int)optp->name, (int)optp->len));
18234 	qreply(q, mpctl);
18235 	return (mp2ctl);
18236 }
18237 
18238 /* Multicast routing table. */
18239 static mblk_t *
18240 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18241 {
18242 	struct opthdr		*optp;
18243 	mblk_t			*mp2ctl;
18244 
18245 	/*
18246 	 * make a copy of the original message
18247 	 */
18248 	mp2ctl = copymsg(mpctl);
18249 
18250 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18251 	optp->level = EXPER_DVMRP;
18252 	optp->name = EXPER_DVMRP_MRT;
18253 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18254 		ip0dbg(("ip_mroute_mrt: failed\n"));
18255 	}
18256 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18257 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18258 	    (int)optp->level, (int)optp->name, (int)optp->len));
18259 	qreply(q, mpctl);
18260 	return (mp2ctl);
18261 }
18262 
18263 /*
18264  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18265  * in one IRE walk.
18266  */
18267 static mblk_t *
18268 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18269 {
18270 	struct opthdr	*optp;
18271 	mblk_t		*mp2ctl;	/* Returned */
18272 	mblk_t		*mp3ctl;	/* nettomedia */
18273 	mblk_t		*mp4ctl;	/* routeattrs */
18274 	iproutedata_t	ird;
18275 	zoneid_t	zoneid;
18276 
18277 	/*
18278 	 * make copies of the original message
18279 	 *	- mp2ctl is returned unchanged to the caller for his use
18280 	 *	- mpctl is sent upstream as ipRouteEntryTable
18281 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18282 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18283 	 */
18284 	mp2ctl = copymsg(mpctl);
18285 	mp3ctl = copymsg(mpctl);
18286 	mp4ctl = copymsg(mpctl);
18287 	if (mp3ctl == NULL || mp4ctl == NULL) {
18288 		freemsg(mp4ctl);
18289 		freemsg(mp3ctl);
18290 		freemsg(mp2ctl);
18291 		freemsg(mpctl);
18292 		return (NULL);
18293 	}
18294 
18295 	bzero(&ird, sizeof (ird));
18296 
18297 	ird.ird_route.lp_head = mpctl->b_cont;
18298 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18299 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18300 
18301 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18302 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18303 	if (zoneid == GLOBAL_ZONEID) {
18304 		/*
18305 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18306 		 * the sys_net_config privilege, it can only run in the global
18307 		 * zone, so we don't display these IREs in the other zones.
18308 		 */
18309 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18310 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18311 	}
18312 
18313 	/* ipRouteEntryTable in mpctl */
18314 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18315 	optp->level = MIB2_IP;
18316 	optp->name = MIB2_IP_ROUTE;
18317 	optp->len = msgdsize(ird.ird_route.lp_head);
18318 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18319 	    (int)optp->level, (int)optp->name, (int)optp->len));
18320 	qreply(q, mpctl);
18321 
18322 	/* ipNetToMediaEntryTable in mp3ctl */
18323 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18324 	optp->level = MIB2_IP;
18325 	optp->name = MIB2_IP_MEDIA;
18326 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18327 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18328 	    (int)optp->level, (int)optp->name, (int)optp->len));
18329 	qreply(q, mp3ctl);
18330 
18331 	/* ipRouteAttributeTable in mp4ctl */
18332 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18333 	optp->level = MIB2_IP;
18334 	optp->name = EXPER_IP_RTATTR;
18335 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18336 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18337 	    (int)optp->level, (int)optp->name, (int)optp->len));
18338 	if (optp->len == 0)
18339 		freemsg(mp4ctl);
18340 	else
18341 		qreply(q, mp4ctl);
18342 
18343 	return (mp2ctl);
18344 }
18345 
18346 /*
18347  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18348  * ipv6NetToMediaEntryTable in an NDP walk.
18349  */
18350 static mblk_t *
18351 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18352 {
18353 	struct opthdr	*optp;
18354 	mblk_t		*mp2ctl;	/* Returned */
18355 	mblk_t		*mp3ctl;	/* nettomedia */
18356 	mblk_t		*mp4ctl;	/* routeattrs */
18357 	iproutedata_t	ird;
18358 	zoneid_t	zoneid;
18359 
18360 	/*
18361 	 * make copies of the original message
18362 	 *	- mp2ctl is returned unchanged to the caller for his use
18363 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18364 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18365 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18366 	 */
18367 	mp2ctl = copymsg(mpctl);
18368 	mp3ctl = copymsg(mpctl);
18369 	mp4ctl = copymsg(mpctl);
18370 	if (mp3ctl == NULL || mp4ctl == NULL) {
18371 		freemsg(mp4ctl);
18372 		freemsg(mp3ctl);
18373 		freemsg(mp2ctl);
18374 		freemsg(mpctl);
18375 		return (NULL);
18376 	}
18377 
18378 	bzero(&ird, sizeof (ird));
18379 
18380 	ird.ird_route.lp_head = mpctl->b_cont;
18381 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18382 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18383 
18384 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18385 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18386 
18387 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18388 	optp->level = MIB2_IP6;
18389 	optp->name = MIB2_IP6_ROUTE;
18390 	optp->len = msgdsize(ird.ird_route.lp_head);
18391 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18392 	    (int)optp->level, (int)optp->name, (int)optp->len));
18393 	qreply(q, mpctl);
18394 
18395 	/* ipv6NetToMediaEntryTable in mp3ctl */
18396 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18397 
18398 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18399 	optp->level = MIB2_IP6;
18400 	optp->name = MIB2_IP6_MEDIA;
18401 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18402 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18403 	    (int)optp->level, (int)optp->name, (int)optp->len));
18404 	qreply(q, mp3ctl);
18405 
18406 	/* ipv6RouteAttributeTable in mp4ctl */
18407 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18408 	optp->level = MIB2_IP6;
18409 	optp->name = EXPER_IP_RTATTR;
18410 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18411 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18412 	    (int)optp->level, (int)optp->name, (int)optp->len));
18413 	if (optp->len == 0)
18414 		freemsg(mp4ctl);
18415 	else
18416 		qreply(q, mp4ctl);
18417 
18418 	return (mp2ctl);
18419 }
18420 
18421 /*
18422  * ICMPv6 mib: One per ill
18423  */
18424 static mblk_t *
18425 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18426 {
18427 	struct opthdr		*optp;
18428 	mblk_t			*mp2ctl;
18429 	ill_t			*ill;
18430 	ill_walk_context_t	ctx;
18431 	mblk_t			*mp_tail = NULL;
18432 
18433 	/*
18434 	 * Make a copy of the original message
18435 	 */
18436 	mp2ctl = copymsg(mpctl);
18437 
18438 	/* fixed length IPv6 structure ... */
18439 
18440 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18441 	optp->level = MIB2_IP6;
18442 	optp->name = 0;
18443 	/* Include "unknown interface" ip6_mib */
18444 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
18445 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
18446 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
18447 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
18448 	    sizeof (mib2_ipv6IfStatsEntry_t));
18449 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18450 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
18451 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
18452 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18453 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
18454 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18455 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18456 	    (int)sizeof (ip6_mib))) {
18457 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18458 		    (uint_t)sizeof (ip6_mib)));
18459 	}
18460 
18461 	rw_enter(&ill_g_lock, RW_READER);
18462 	ill = ILL_START_WALK_V6(&ctx);
18463 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18464 		ill->ill_ip6_mib->ipv6IfIndex =
18465 		    ill->ill_phyint->phyint_ifindex;
18466 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
18467 		    ipv6_forward ? 1 : 2);
18468 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
18469 		    ill->ill_max_hops);
18470 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
18471 		    sizeof (mib2_ipv6IfStatsEntry_t));
18472 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
18473 		    sizeof (mib2_ipv6AddrEntry_t));
18474 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
18475 		    sizeof (mib2_ipv6RouteEntry_t));
18476 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
18477 		    sizeof (mib2_ipv6NetToMediaEntry_t));
18478 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
18479 		    sizeof (ipv6_member_t));
18480 
18481 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18482 		    (char *)ill->ill_ip6_mib,
18483 		    (int)sizeof (*ill->ill_ip6_mib))) {
18484 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18485 				"%u bytes\n",
18486 				(uint_t)sizeof (*ill->ill_ip6_mib)));
18487 		}
18488 	}
18489 	rw_exit(&ill_g_lock);
18490 
18491 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18492 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18493 	    (int)optp->level, (int)optp->name, (int)optp->len));
18494 	qreply(q, mpctl);
18495 	return (mp2ctl);
18496 }
18497 
18498 /*
18499  * ICMPv6 mib: One per ill
18500  */
18501 static mblk_t *
18502 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18503 {
18504 	struct opthdr		*optp;
18505 	mblk_t			*mp2ctl;
18506 	ill_t			*ill;
18507 	ill_walk_context_t	ctx;
18508 	mblk_t			*mp_tail = NULL;
18509 	/*
18510 	 * Make a copy of the original message
18511 	 */
18512 	mp2ctl = copymsg(mpctl);
18513 
18514 	/* fixed length ICMPv6 structure ... */
18515 
18516 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18517 	optp->level = MIB2_ICMP6;
18518 	optp->name = 0;
18519 	/* Include "unknown interface" icmp6_mib */
18520 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
18521 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18522 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18523 	    (int)sizeof (icmp6_mib))) {
18524 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18525 		    (uint_t)sizeof (icmp6_mib)));
18526 	}
18527 
18528 	rw_enter(&ill_g_lock, RW_READER);
18529 	ill = ILL_START_WALK_V6(&ctx);
18530 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18531 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18532 		    ill->ill_phyint->phyint_ifindex;
18533 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
18534 		    sizeof (mib2_ipv6IfIcmpEntry_t);
18535 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18536 		    (char *)ill->ill_icmp6_mib,
18537 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18538 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18539 			    "%u bytes\n",
18540 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18541 		}
18542 	}
18543 	rw_exit(&ill_g_lock);
18544 
18545 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18546 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18547 	    (int)optp->level, (int)optp->name, (int)optp->len));
18548 	qreply(q, mpctl);
18549 	return (mp2ctl);
18550 }
18551 
18552 /*
18553  * ire_walk routine to create both ipRouteEntryTable and
18554  * ipNetToMediaEntryTable in one IRE walk
18555  */
18556 static void
18557 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18558 {
18559 	ill_t				*ill;
18560 	ipif_t				*ipif;
18561 	mblk_t				*llmp;
18562 	dl_unitdata_req_t		*dlup;
18563 	mib2_ipRouteEntry_t		*re;
18564 	mib2_ipNetToMediaEntry_t	ntme;
18565 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18566 	ipaddr_t			gw_addr;
18567 	tsol_ire_gw_secattr_t		*attrp;
18568 	tsol_gc_t			*gc = NULL;
18569 	tsol_gcgrp_t			*gcgrp = NULL;
18570 	uint_t				sacnt = 0;
18571 	int				i;
18572 
18573 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18574 
18575 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18576 		return;
18577 
18578 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18579 		mutex_enter(&attrp->igsa_lock);
18580 		if ((gc = attrp->igsa_gc) != NULL) {
18581 			gcgrp = gc->gc_grp;
18582 			ASSERT(gcgrp != NULL);
18583 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18584 			sacnt = 1;
18585 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18586 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18587 			gc = gcgrp->gcgrp_head;
18588 			sacnt = gcgrp->gcgrp_count;
18589 		}
18590 		mutex_exit(&attrp->igsa_lock);
18591 
18592 		/* do nothing if there's no gc to report */
18593 		if (gc == NULL) {
18594 			ASSERT(sacnt == 0);
18595 			if (gcgrp != NULL) {
18596 				/* we might as well drop the lock now */
18597 				rw_exit(&gcgrp->gcgrp_rwlock);
18598 				gcgrp = NULL;
18599 			}
18600 			attrp = NULL;
18601 		}
18602 
18603 		ASSERT(gc == NULL || (gcgrp != NULL &&
18604 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18605 	}
18606 	ASSERT(sacnt == 0 || gc != NULL);
18607 
18608 	if (sacnt != 0 &&
18609 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18610 		kmem_free(re, sizeof (*re));
18611 		rw_exit(&gcgrp->gcgrp_rwlock);
18612 		return;
18613 	}
18614 
18615 	/*
18616 	 * Return all IRE types for route table... let caller pick and choose
18617 	 */
18618 	re->ipRouteDest = ire->ire_addr;
18619 	ipif = ire->ire_ipif;
18620 	re->ipRouteIfIndex.o_length = 0;
18621 	if (ire->ire_type == IRE_CACHE) {
18622 		ill = (ill_t *)ire->ire_stq->q_ptr;
18623 		re->ipRouteIfIndex.o_length =
18624 		    ill->ill_name_length == 0 ? 0 :
18625 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18626 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18627 		    re->ipRouteIfIndex.o_length);
18628 	} else if (ipif != NULL) {
18629 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18630 		    OCTET_LENGTH);
18631 		re->ipRouteIfIndex.o_length =
18632 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18633 	}
18634 	re->ipRouteMetric1 = -1;
18635 	re->ipRouteMetric2 = -1;
18636 	re->ipRouteMetric3 = -1;
18637 	re->ipRouteMetric4 = -1;
18638 
18639 	gw_addr = ire->ire_gateway_addr;
18640 
18641 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18642 		re->ipRouteNextHop = ire->ire_src_addr;
18643 	else
18644 		re->ipRouteNextHop = gw_addr;
18645 	/* indirect(4), direct(3), or invalid(2) */
18646 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18647 		re->ipRouteType = 2;
18648 	else
18649 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18650 	re->ipRouteProto = -1;
18651 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18652 	re->ipRouteMask = ire->ire_mask;
18653 	re->ipRouteMetric5 = -1;
18654 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
18655 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
18656 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
18657 	if (ire->ire_nce &&
18658 	    ire->ire_nce->nce_state == ND_REACHABLE)
18659 		llmp = ire->ire_nce->nce_res_mp;
18660 	else
18661 		llmp = NULL;
18662 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
18663 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
18664 	re->ipRouteInfo.re_ire_type	= ire->ire_type;
18665 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18666 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18667 	re->ipRouteInfo.re_flags	= ire->ire_flags;
18668 	re->ipRouteInfo.re_in_ill.o_length = 0;
18669 	if (ire->ire_in_ill != NULL) {
18670 		re->ipRouteInfo.re_in_ill.o_length =
18671 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
18672 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
18673 		bcopy(ire->ire_in_ill->ill_name,
18674 		    re->ipRouteInfo.re_in_ill.o_bytes,
18675 		    re->ipRouteInfo.re_in_ill.o_length);
18676 	}
18677 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
18678 
18679 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18680 	    (char *)re, (int)sizeof (*re))) {
18681 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18682 		    (uint_t)sizeof (*re)));
18683 	}
18684 
18685 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18686 		iaeptr->iae_routeidx = ird->ird_idx;
18687 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18688 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18689 	}
18690 
18691 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18692 	    (char *)iae, sacnt * sizeof (*iae))) {
18693 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18694 		    (unsigned)(sacnt * sizeof (*iae))));
18695 	}
18696 
18697 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
18698 		goto done;
18699 	/*
18700 	 * only IRE_CACHE entries that are for a directly connected subnet
18701 	 * get appended to net -> phys addr table
18702 	 * (others in arp)
18703 	 */
18704 	ntme.ipNetToMediaIfIndex.o_length = 0;
18705 	ill = ire_to_ill(ire);
18706 	ASSERT(ill != NULL);
18707 	ntme.ipNetToMediaIfIndex.o_length =
18708 	    ill->ill_name_length == 0 ? 0 :
18709 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18710 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
18711 		    ntme.ipNetToMediaIfIndex.o_length);
18712 
18713 	ntme.ipNetToMediaPhysAddress.o_length = 0;
18714 	if (llmp) {
18715 		uchar_t *addr;
18716 
18717 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
18718 		/* Remove sap from  address */
18719 		if (ill->ill_sap_length < 0)
18720 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
18721 		else
18722 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
18723 			    ill->ill_sap_length;
18724 
18725 		ntme.ipNetToMediaPhysAddress.o_length =
18726 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18727 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18728 		    ntme.ipNetToMediaPhysAddress.o_length);
18729 	}
18730 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18731 	/* assume dynamic (may be changed in arp) */
18732 	ntme.ipNetToMediaType = 3;
18733 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18734 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18735 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18736 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18737 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18738 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18739 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18740 		    (uint_t)sizeof (ntme)));
18741 	}
18742 done:
18743 	/* bump route index for next pass */
18744 	ird->ird_idx++;
18745 
18746 	kmem_free(re, sizeof (*re));
18747 	if (sacnt != 0)
18748 		kmem_free(iae, sacnt * sizeof (*iae));
18749 
18750 	if (gcgrp != NULL)
18751 		rw_exit(&gcgrp->gcgrp_rwlock);
18752 }
18753 
18754 /*
18755  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18756  */
18757 static void
18758 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18759 {
18760 	ill_t				*ill;
18761 	ipif_t				*ipif;
18762 	mib2_ipv6RouteEntry_t		*re;
18763 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18764 	in6_addr_t			gw_addr_v6;
18765 	tsol_ire_gw_secattr_t		*attrp;
18766 	tsol_gc_t			*gc = NULL;
18767 	tsol_gcgrp_t			*gcgrp = NULL;
18768 	uint_t				sacnt = 0;
18769 	int				i;
18770 
18771 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18772 
18773 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18774 		return;
18775 
18776 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18777 		mutex_enter(&attrp->igsa_lock);
18778 		if ((gc = attrp->igsa_gc) != NULL) {
18779 			gcgrp = gc->gc_grp;
18780 			ASSERT(gcgrp != NULL);
18781 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18782 			sacnt = 1;
18783 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18784 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18785 			gc = gcgrp->gcgrp_head;
18786 			sacnt = gcgrp->gcgrp_count;
18787 		}
18788 		mutex_exit(&attrp->igsa_lock);
18789 
18790 		/* do nothing if there's no gc to report */
18791 		if (gc == NULL) {
18792 			ASSERT(sacnt == 0);
18793 			if (gcgrp != NULL) {
18794 				/* we might as well drop the lock now */
18795 				rw_exit(&gcgrp->gcgrp_rwlock);
18796 				gcgrp = NULL;
18797 			}
18798 			attrp = NULL;
18799 		}
18800 
18801 		ASSERT(gc == NULL || (gcgrp != NULL &&
18802 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18803 	}
18804 	ASSERT(sacnt == 0 || gc != NULL);
18805 
18806 	if (sacnt != 0 &&
18807 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18808 		kmem_free(re, sizeof (*re));
18809 		rw_exit(&gcgrp->gcgrp_rwlock);
18810 		return;
18811 	}
18812 
18813 	/*
18814 	 * Return all IRE types for route table... let caller pick and choose
18815 	 */
18816 	re->ipv6RouteDest = ire->ire_addr_v6;
18817 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18818 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18819 	re->ipv6RouteIfIndex.o_length = 0;
18820 	ipif = ire->ire_ipif;
18821 	if (ire->ire_type == IRE_CACHE) {
18822 		ill = (ill_t *)ire->ire_stq->q_ptr;
18823 		re->ipv6RouteIfIndex.o_length =
18824 		    ill->ill_name_length == 0 ? 0 :
18825 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18826 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
18827 		    re->ipv6RouteIfIndex.o_length);
18828 	} else if (ipif != NULL) {
18829 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
18830 		    OCTET_LENGTH);
18831 		re->ipv6RouteIfIndex.o_length =
18832 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
18833 	}
18834 
18835 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18836 
18837 	mutex_enter(&ire->ire_lock);
18838 	gw_addr_v6 = ire->ire_gateway_addr_v6;
18839 	mutex_exit(&ire->ire_lock);
18840 
18841 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
18842 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
18843 	else
18844 		re->ipv6RouteNextHop = gw_addr_v6;
18845 
18846 	/* remote(4), local(3), or discard(2) */
18847 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18848 		re->ipv6RouteType = 2;
18849 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
18850 		re->ipv6RouteType = 3;
18851 	else
18852 		re->ipv6RouteType = 4;
18853 
18854 	re->ipv6RouteProtocol	= -1;
18855 	re->ipv6RoutePolicy	= 0;
18856 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
18857 	re->ipv6RouteNextHopRDI	= 0;
18858 	re->ipv6RouteWeight	= 0;
18859 	re->ipv6RouteMetric	= 0;
18860 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
18861 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
18862 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
18863 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
18864 	re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
18865 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18866 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18867 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
18868 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
18869 
18870 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18871 	    (char *)re, (int)sizeof (*re))) {
18872 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18873 		    (uint_t)sizeof (*re)));
18874 	}
18875 
18876 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18877 		iaeptr->iae_routeidx = ird->ird_idx;
18878 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18879 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18880 	}
18881 
18882 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18883 	    (char *)iae, sacnt * sizeof (*iae))) {
18884 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18885 		    (unsigned)(sacnt * sizeof (*iae))));
18886 	}
18887 
18888 	/* bump route index for next pass */
18889 	ird->ird_idx++;
18890 
18891 	kmem_free(re, sizeof (*re));
18892 	if (sacnt != 0)
18893 		kmem_free(iae, sacnt * sizeof (*iae));
18894 
18895 	if (gcgrp != NULL)
18896 		rw_exit(&gcgrp->gcgrp_rwlock);
18897 }
18898 
18899 /*
18900  * ndp_walk routine to create ipv6NetToMediaEntryTable
18901  */
18902 static int
18903 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
18904 {
18905 	ill_t				*ill;
18906 	mib2_ipv6NetToMediaEntry_t	ntme;
18907 	dl_unitdata_req_t		*dl;
18908 
18909 	ill = nce->nce_ill;
18910 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
18911 		return (0);
18912 
18913 	/*
18914 	 * Neighbor cache entry attached to IRE with on-link
18915 	 * destination.
18916 	 */
18917 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
18918 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
18919 	if ((ill->ill_flags & ILLF_XRESOLV) &&
18920 	    (nce->nce_res_mp != NULL)) {
18921 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
18922 		ntme.ipv6NetToMediaPhysAddress.o_length =
18923 		    dl->dl_dest_addr_length;
18924 	} else {
18925 		ntme.ipv6NetToMediaPhysAddress.o_length =
18926 		    ill->ill_phys_addr_length;
18927 	}
18928 	if (nce->nce_res_mp != NULL) {
18929 		bcopy((char *)nce->nce_res_mp->b_rptr +
18930 		    NCE_LL_ADDR_OFFSET(ill),
18931 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
18932 		    ntme.ipv6NetToMediaPhysAddress.o_length);
18933 	} else {
18934 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
18935 		    ill->ill_phys_addr_length);
18936 	}
18937 	/*
18938 	 * Note: Returns ND_* states. Should be:
18939 	 * reachable(1), stale(2), delay(3), probe(4),
18940 	 * invalid(5), unknown(6)
18941 	 */
18942 	ntme.ipv6NetToMediaState = nce->nce_state;
18943 	ntme.ipv6NetToMediaLastUpdated = 0;
18944 
18945 	/* other(1), dynamic(2), static(3), local(4) */
18946 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
18947 		ntme.ipv6NetToMediaType = 4;
18948 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
18949 		ntme.ipv6NetToMediaType = 1;
18950 	} else {
18951 		ntme.ipv6NetToMediaType = 2;
18952 	}
18953 
18954 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18955 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18956 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
18957 		    (uint_t)sizeof (ntme)));
18958 	}
18959 	return (0);
18960 }
18961 
18962 /*
18963  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
18964  */
18965 /* ARGSUSED */
18966 int
18967 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
18968 {
18969 	switch (level) {
18970 	case MIB2_IP:
18971 	case MIB2_ICMP:
18972 		switch (name) {
18973 		default:
18974 			break;
18975 		}
18976 		return (1);
18977 	default:
18978 		return (1);
18979 	}
18980 }
18981 
18982 /*
18983  * Called before the options are updated to check if this packet will
18984  * be source routed from here.
18985  * This routine assumes that the options are well formed i.e. that they
18986  * have already been checked.
18987  */
18988 static boolean_t
18989 ip_source_routed(ipha_t *ipha)
18990 {
18991 	ipoptp_t	opts;
18992 	uchar_t		*opt;
18993 	uint8_t		optval;
18994 	uint8_t		optlen;
18995 	ipaddr_t	dst;
18996 	ire_t		*ire;
18997 
18998 	if (IS_SIMPLE_IPH(ipha)) {
18999 		ip2dbg(("not source routed\n"));
19000 		return (B_FALSE);
19001 	}
19002 	dst = ipha->ipha_dst;
19003 	for (optval = ipoptp_first(&opts, ipha);
19004 	    optval != IPOPT_EOL;
19005 	    optval = ipoptp_next(&opts)) {
19006 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19007 		opt = opts.ipoptp_cur;
19008 		optlen = opts.ipoptp_len;
19009 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19010 		    optval, optlen));
19011 		switch (optval) {
19012 			uint32_t off;
19013 		case IPOPT_SSRR:
19014 		case IPOPT_LSRR:
19015 			/*
19016 			 * If dst is one of our addresses and there are some
19017 			 * entries left in the source route return (true).
19018 			 */
19019 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19020 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
19021 			if (ire == NULL) {
19022 				ip2dbg(("ip_source_routed: not next"
19023 				    " source route 0x%x\n",
19024 				    ntohl(dst)));
19025 				return (B_FALSE);
19026 			}
19027 			ire_refrele(ire);
19028 			off = opt[IPOPT_OFFSET];
19029 			off--;
19030 			if (optlen < IP_ADDR_LEN ||
19031 			    off > optlen - IP_ADDR_LEN) {
19032 				/* End of source route */
19033 				ip1dbg(("ip_source_routed: end of SR\n"));
19034 				return (B_FALSE);
19035 			}
19036 			return (B_TRUE);
19037 		}
19038 	}
19039 	ip2dbg(("not source routed\n"));
19040 	return (B_FALSE);
19041 }
19042 
19043 /*
19044  * Check if the packet contains any source route.
19045  */
19046 static boolean_t
19047 ip_source_route_included(ipha_t *ipha)
19048 {
19049 	ipoptp_t	opts;
19050 	uint8_t		optval;
19051 
19052 	if (IS_SIMPLE_IPH(ipha))
19053 		return (B_FALSE);
19054 	for (optval = ipoptp_first(&opts, ipha);
19055 	    optval != IPOPT_EOL;
19056 	    optval = ipoptp_next(&opts)) {
19057 		switch (optval) {
19058 		case IPOPT_SSRR:
19059 		case IPOPT_LSRR:
19060 			return (B_TRUE);
19061 		}
19062 	}
19063 	return (B_FALSE);
19064 }
19065 
19066 /*
19067  * Called when the IRE expiration timer fires.
19068  */
19069 /* ARGSUSED */
19070 void
19071 ip_trash_timer_expire(void *args)
19072 {
19073 	int	flush_flag = 0;
19074 
19075 	/*
19076 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19077 	 * This lock makes sure that a new invocation of this function
19078 	 * that occurs due to an almost immediate timer firing will not
19079 	 * progress beyond this point until the current invocation is done
19080 	 */
19081 	mutex_enter(&ip_trash_timer_lock);
19082 	ip_ire_expire_id = 0;
19083 	mutex_exit(&ip_trash_timer_lock);
19084 
19085 	/* Periodic timer */
19086 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
19087 		/*
19088 		 * Remove all IRE_CACHE entries since they might
19089 		 * contain arp information.
19090 		 */
19091 		flush_flag |= FLUSH_ARP_TIME;
19092 		ip_ire_arp_time_elapsed = 0;
19093 		IP_STAT(ip_ire_arp_timer_expired);
19094 	}
19095 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
19096 		/* Remove all redirects */
19097 		flush_flag |= FLUSH_REDIRECT_TIME;
19098 		ip_ire_rd_time_elapsed = 0;
19099 		IP_STAT(ip_ire_redirect_timer_expired);
19100 	}
19101 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
19102 		/* Increase path mtu */
19103 		flush_flag |= FLUSH_MTU_TIME;
19104 		ip_ire_pmtu_time_elapsed = 0;
19105 		IP_STAT(ip_ire_pmtu_timer_expired);
19106 	}
19107 
19108 	/*
19109 	 * Optimize for the case when there are no redirects in the
19110 	 * ftable, that is, no need to walk the ftable in that case.
19111 	 */
19112 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19113 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19114 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
19115 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
19116 	}
19117 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
19118 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19119 		    ire_expire, (char *)(uintptr_t)flush_flag,
19120 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
19121 	}
19122 	if (flush_flag & FLUSH_MTU_TIME) {
19123 		/*
19124 		 * Walk all IPv6 IRE's and update them
19125 		 * Note that ARP and redirect timers are not
19126 		 * needed since NUD handles stale entries.
19127 		 */
19128 		flush_flag = FLUSH_MTU_TIME;
19129 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
19130 		    ALL_ZONES);
19131 	}
19132 
19133 	ip_ire_arp_time_elapsed += ip_timer_interval;
19134 	ip_ire_rd_time_elapsed += ip_timer_interval;
19135 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19136 
19137 	/*
19138 	 * Hold the lock to serialize timeout calls and prevent
19139 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19140 	 * for the timer to fire and a new invocation of this function
19141 	 * to start before the return value of timeout has been stored
19142 	 * in ip_ire_expire_id by the current invocation.
19143 	 */
19144 	mutex_enter(&ip_trash_timer_lock);
19145 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19146 	    MSEC_TO_TICK(ip_timer_interval));
19147 	mutex_exit(&ip_trash_timer_lock);
19148 }
19149 
19150 /*
19151  * Called by the memory allocator subsystem directly, when the system
19152  * is running low on memory.
19153  */
19154 /* ARGSUSED */
19155 void
19156 ip_trash_ire_reclaim(void *args)
19157 {
19158 	ire_cache_count_t icc;
19159 	ire_cache_reclaim_t icr;
19160 	ncc_cache_count_t ncc;
19161 	nce_cache_reclaim_t ncr;
19162 	uint_t delete_cnt;
19163 	/*
19164 	 * Memory reclaim call back.
19165 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19166 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19167 	 * entries, determine what fraction to free for
19168 	 * each category of IRE_CACHE entries giving absolute priority
19169 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19170 	 * entry will be freed unless all offlink entries are freed).
19171 	 */
19172 	icc.icc_total = 0;
19173 	icc.icc_unused = 0;
19174 	icc.icc_offlink = 0;
19175 	icc.icc_pmtu = 0;
19176 	icc.icc_onlink = 0;
19177 	ire_walk(ire_cache_count, (char *)&icc);
19178 
19179 	/*
19180 	 * Free NCEs for IPv6 like the onlink ires.
19181 	 */
19182 	ncc.ncc_total = 0;
19183 	ncc.ncc_host = 0;
19184 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19185 
19186 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19187 	    icc.icc_pmtu + icc.icc_onlink);
19188 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19189 	IP_STAT(ip_trash_ire_reclaim_calls);
19190 	if (delete_cnt == 0)
19191 		return;
19192 	IP_STAT(ip_trash_ire_reclaim_success);
19193 	/* Always delete all unused offlink entries */
19194 	icr.icr_unused = 1;
19195 	if (delete_cnt <= icc.icc_unused) {
19196 		/*
19197 		 * Only need to free unused entries.  In other words,
19198 		 * there are enough unused entries to free to meet our
19199 		 * target number of freed ire cache entries.
19200 		 */
19201 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19202 		ncr.ncr_host = 0;
19203 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19204 		/*
19205 		 * Only need to free unused entries, plus a fraction of offlink
19206 		 * entries.  It follows from the first if statement that
19207 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19208 		 */
19209 		delete_cnt -= icc.icc_unused;
19210 		/* Round up # deleted by truncating fraction */
19211 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19212 		icr.icr_pmtu = icr.icr_onlink = 0;
19213 		ncr.ncr_host = 0;
19214 	} else if (delete_cnt <=
19215 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19216 		/*
19217 		 * Free all unused and offlink entries, plus a fraction of
19218 		 * pmtu entries.  It follows from the previous if statement
19219 		 * that icc_pmtu is non-zero, and that
19220 		 * delete_cnt != icc_unused + icc_offlink.
19221 		 */
19222 		icr.icr_offlink = 1;
19223 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19224 		/* Round up # deleted by truncating fraction */
19225 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19226 		icr.icr_onlink = 0;
19227 		ncr.ncr_host = 0;
19228 	} else {
19229 		/*
19230 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19231 		 * of onlink entries.  If we're here, then we know that
19232 		 * icc_onlink is non-zero, and that
19233 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19234 		 */
19235 		icr.icr_offlink = icr.icr_pmtu = 1;
19236 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19237 		    icc.icc_pmtu;
19238 		/* Round up # deleted by truncating fraction */
19239 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19240 		/* Using the same delete fraction as for onlink IREs */
19241 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19242 	}
19243 #ifdef DEBUG
19244 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19245 	    "fractions %d/%d/%d/%d\n",
19246 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19247 	    icc.icc_unused, icc.icc_offlink,
19248 	    icc.icc_pmtu, icc.icc_onlink,
19249 	    icr.icr_unused, icr.icr_offlink,
19250 	    icr.icr_pmtu, icr.icr_onlink));
19251 #endif
19252 	ire_walk(ire_cache_reclaim, (char *)&icr);
19253 	if (ncr.ncr_host != 0)
19254 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19255 		    (uchar_t *)&ncr);
19256 #ifdef DEBUG
19257 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19258 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19259 	ire_walk(ire_cache_count, (char *)&icc);
19260 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19261 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19262 	    icc.icc_pmtu, icc.icc_onlink));
19263 #endif
19264 }
19265 
19266 /*
19267  * ip_unbind is called when a copy of an unbind request is received from the
19268  * upper level protocol.  We remove this conn from any fanout hash list it is
19269  * on, and zero out the bind information.  No reply is expected up above.
19270  */
19271 mblk_t *
19272 ip_unbind(queue_t *q, mblk_t *mp)
19273 {
19274 	conn_t	*connp = Q_TO_CONN(q);
19275 
19276 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19277 
19278 	if (is_system_labeled() && connp->conn_anon_port) {
19279 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19280 		    connp->conn_mlp_type, connp->conn_ulp,
19281 		    ntohs(connp->conn_lport), B_FALSE);
19282 		connp->conn_anon_port = 0;
19283 	}
19284 	connp->conn_mlp_type = mlptSingle;
19285 
19286 	ipcl_hash_remove(connp);
19287 
19288 	ASSERT(mp->b_cont == NULL);
19289 	/*
19290 	 * Convert mp into a T_OK_ACK
19291 	 */
19292 	mp = mi_tpi_ok_ack_alloc(mp);
19293 
19294 	/*
19295 	 * should not happen in practice... T_OK_ACK is smaller than the
19296 	 * original message.
19297 	 */
19298 	if (mp == NULL)
19299 		return (NULL);
19300 
19301 	/*
19302 	 * Don't bzero the ports if its TCP since TCP still needs the
19303 	 * lport to remove it from its own bind hash. TCP will do the
19304 	 * cleanup.
19305 	 */
19306 	if (!IPCL_IS_TCP(connp))
19307 		bzero(&connp->u_port, sizeof (connp->u_port));
19308 
19309 	return (mp);
19310 }
19311 
19312 /*
19313  * Write side put procedure.  Outbound data, IOCTLs, responses from
19314  * resolvers, etc, come down through here.
19315  *
19316  * arg2 is always a queue_t *.
19317  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19318  * the zoneid.
19319  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19320  */
19321 void
19322 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19323 {
19324 	conn_t		*connp = NULL;
19325 	queue_t		*q = (queue_t *)arg2;
19326 	ipha_t		*ipha;
19327 #define	rptr	((uchar_t *)ipha)
19328 	ire_t		*ire = NULL;
19329 	ire_t		*sctp_ire = NULL;
19330 	uint32_t	v_hlen_tos_len;
19331 	ipaddr_t	dst;
19332 	mblk_t		*first_mp = NULL;
19333 	boolean_t	mctl_present;
19334 	ipsec_out_t	*io;
19335 	int		match_flags;
19336 	ill_t		*attach_ill = NULL;
19337 					/* Bind to IPIF_NOFAILOVER ill etc. */
19338 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19339 	ipif_t		*dst_ipif;
19340 	boolean_t	multirt_need_resolve = B_FALSE;
19341 	mblk_t		*copy_mp = NULL;
19342 	int		err;
19343 	zoneid_t	zoneid;
19344 	int	adjust;
19345 	uint16_t iplen;
19346 	boolean_t	need_decref = B_FALSE;
19347 	boolean_t	ignore_dontroute = B_FALSE;
19348 	boolean_t	ignore_nexthop = B_FALSE;
19349 	boolean_t	ip_nexthop = B_FALSE;
19350 	ipaddr_t	nexthop_addr;
19351 
19352 #ifdef	_BIG_ENDIAN
19353 #define	V_HLEN	(v_hlen_tos_len >> 24)
19354 #else
19355 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19356 #endif
19357 
19358 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19359 	    "ip_wput_start: q %p", q);
19360 
19361 	/*
19362 	 * ip_wput fast path
19363 	 */
19364 
19365 	/* is packet from ARP ? */
19366 	if (q->q_next != NULL) {
19367 		zoneid = (zoneid_t)(uintptr_t)arg;
19368 		goto qnext;
19369 	}
19370 
19371 	connp = (conn_t *)arg;
19372 	ASSERT(connp != NULL);
19373 	zoneid = connp->conn_zoneid;
19374 
19375 	/* is queue flow controlled? */
19376 	if ((q->q_first != NULL || connp->conn_draining) &&
19377 	    (caller == IP_WPUT)) {
19378 		ASSERT(!need_decref);
19379 		(void) putq(q, mp);
19380 		return;
19381 	}
19382 
19383 	/* Multidata transmit? */
19384 	if (DB_TYPE(mp) == M_MULTIDATA) {
19385 		/*
19386 		 * We should never get here, since all Multidata messages
19387 		 * originating from tcp should have been directed over to
19388 		 * tcp_multisend() in the first place.
19389 		 */
19390 		BUMP_MIB(&ip_mib, ipOutDiscards);
19391 		freemsg(mp);
19392 		return;
19393 	} else if (DB_TYPE(mp) != M_DATA)
19394 		goto notdata;
19395 
19396 	if (mp->b_flag & MSGHASREF) {
19397 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19398 		mp->b_flag &= ~MSGHASREF;
19399 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19400 		need_decref = B_TRUE;
19401 	}
19402 	ipha = (ipha_t *)mp->b_rptr;
19403 
19404 	/* is IP header non-aligned or mblk smaller than basic IP header */
19405 #ifndef SAFETY_BEFORE_SPEED
19406 	if (!OK_32PTR(rptr) ||
19407 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19408 		goto hdrtoosmall;
19409 #endif
19410 
19411 	ASSERT(OK_32PTR(ipha));
19412 
19413 	/*
19414 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19415 	 * wrong version, we'll catch it again in ip_output_v6.
19416 	 *
19417 	 * Note that this is *only* locally-generated output here, and never
19418 	 * forwarded data, and that we need to deal only with transports that
19419 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19420 	 * label.)
19421 	 */
19422 	if (is_system_labeled() &&
19423 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19424 	    !connp->conn_ulp_labeled) {
19425 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19426 		    connp->conn_mac_exempt);
19427 		ipha = (ipha_t *)mp->b_rptr;
19428 		if (err != 0) {
19429 			first_mp = mp;
19430 			if (err == EINVAL)
19431 				goto icmp_parameter_problem;
19432 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19433 			goto drop_pkt;
19434 		}
19435 		iplen = ntohs(ipha->ipha_length) + adjust;
19436 		ipha->ipha_length = htons(iplen);
19437 	}
19438 
19439 	/*
19440 	 * If there is a policy, try to attach an ipsec_out in
19441 	 * the front. At the end, first_mp either points to a
19442 	 * M_DATA message or IPSEC_OUT message linked to a
19443 	 * M_DATA message. We have to do it now as we might
19444 	 * lose the "conn" if we go through ip_newroute.
19445 	 */
19446 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19447 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
19448 		    ipha->ipha_protocol)) == NULL)) {
19449 			if (need_decref)
19450 				CONN_DEC_REF(connp);
19451 			return;
19452 		} else {
19453 			ASSERT(mp->b_datap->db_type == M_CTL);
19454 			first_mp = mp;
19455 			mp = mp->b_cont;
19456 			mctl_present = B_TRUE;
19457 		}
19458 	} else {
19459 		first_mp = mp;
19460 		mctl_present = B_FALSE;
19461 	}
19462 
19463 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19464 
19465 	/* is wrong version or IP options present */
19466 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19467 		goto version_hdrlen_check;
19468 	dst = ipha->ipha_dst;
19469 
19470 	if (connp->conn_nofailover_ill != NULL) {
19471 		attach_ill = conn_get_held_ill(connp,
19472 		    &connp->conn_nofailover_ill, &err);
19473 		if (err == ILL_LOOKUP_FAILED) {
19474 			if (need_decref)
19475 				CONN_DEC_REF(connp);
19476 			freemsg(first_mp);
19477 			return;
19478 		}
19479 	}
19480 
19481 	/* is packet multicast? */
19482 	if (CLASSD(dst))
19483 		goto multicast;
19484 
19485 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19486 	    (connp->conn_nexthop_set)) {
19487 		/*
19488 		 * If the destination is a broadcast or a loopback
19489 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
19490 		 * through the standard path. But in the case of local
19491 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
19492 		 * the standard path not IP_XMIT_IF.
19493 		 */
19494 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19495 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
19496 		    (ire->ire_type != IRE_LOOPBACK))) {
19497 			if ((connp->conn_dontroute ||
19498 			    connp->conn_nexthop_set) && (ire != NULL) &&
19499 			    (ire->ire_type == IRE_LOCAL))
19500 				goto standard_path;
19501 
19502 			if (ire != NULL) {
19503 				ire_refrele(ire);
19504 				/* No more access to ire */
19505 				ire = NULL;
19506 			}
19507 			/*
19508 			 * bypass routing checks and go directly to
19509 			 * interface.
19510 			 */
19511 			if (connp->conn_dontroute) {
19512 				goto dontroute;
19513 			} else if (connp->conn_nexthop_set) {
19514 				ip_nexthop = B_TRUE;
19515 				nexthop_addr = connp->conn_nexthop_v4;
19516 				goto send_from_ill;
19517 			}
19518 
19519 			/*
19520 			 * If IP_XMIT_IF socket option is set,
19521 			 * then we allow unicast and multicast
19522 			 * packets to go through the ill. It is
19523 			 * quite possible that the destination
19524 			 * is not in the ire cache table and we
19525 			 * do not want to go to ip_newroute()
19526 			 * instead we call ip_newroute_ipif.
19527 			 */
19528 			xmit_ill = conn_get_held_ill(connp,
19529 			    &connp->conn_xmit_if_ill, &err);
19530 			if (err == ILL_LOOKUP_FAILED) {
19531 				if (attach_ill != NULL)
19532 					ill_refrele(attach_ill);
19533 				if (need_decref)
19534 					CONN_DEC_REF(connp);
19535 				freemsg(first_mp);
19536 				return;
19537 			}
19538 			goto send_from_ill;
19539 		}
19540 standard_path:
19541 		/* Must be a broadcast, a loopback or a local ire */
19542 		if (ire != NULL) {
19543 			ire_refrele(ire);
19544 			/* No more access to ire */
19545 			ire = NULL;
19546 		}
19547 	}
19548 
19549 	if (attach_ill != NULL)
19550 		goto send_from_ill;
19551 
19552 	/*
19553 	 * We cache IRE_CACHEs to avoid lookups. We don't do
19554 	 * this for the tcp global queue and listen end point
19555 	 * as it does not really have a real destination to
19556 	 * talk to.  This is also true for SCTP.
19557 	 */
19558 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
19559 	    !connp->conn_fully_bound) {
19560 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19561 		if (ire == NULL)
19562 			goto noirefound;
19563 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19564 		    "ip_wput_end: q %p (%S)", q, "end");
19565 
19566 		/*
19567 		 * Check if the ire has the RTF_MULTIRT flag, inherited
19568 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19569 		 */
19570 		if (ire->ire_flags & RTF_MULTIRT) {
19571 
19572 			/*
19573 			 * Force the TTL of multirouted packets if required.
19574 			 * The TTL of such packets is bounded by the
19575 			 * ip_multirt_ttl ndd variable.
19576 			 */
19577 			if ((ip_multirt_ttl > 0) &&
19578 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
19579 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
19580 				    "(was %d), dst 0x%08x\n",
19581 				    ip_multirt_ttl, ipha->ipha_ttl,
19582 				    ntohl(ire->ire_addr)));
19583 				ipha->ipha_ttl = ip_multirt_ttl;
19584 			}
19585 			/*
19586 			 * We look at this point if there are pending
19587 			 * unresolved routes. ire_multirt_resolvable()
19588 			 * checks in O(n) that all IRE_OFFSUBNET ire
19589 			 * entries for the packet's destination and
19590 			 * flagged RTF_MULTIRT are currently resolved.
19591 			 * If some remain unresolved, we make a copy
19592 			 * of the current message. It will be used
19593 			 * to initiate additional route resolutions.
19594 			 */
19595 			multirt_need_resolve =
19596 			    ire_multirt_need_resolve(ire->ire_addr,
19597 			    MBLK_GETLABEL(first_mp));
19598 			ip2dbg(("ip_wput[TCP]: ire %p, "
19599 			    "multirt_need_resolve %d, first_mp %p\n",
19600 			    (void *)ire, multirt_need_resolve,
19601 			    (void *)first_mp));
19602 			if (multirt_need_resolve) {
19603 				copy_mp = copymsg(first_mp);
19604 				if (copy_mp != NULL) {
19605 					MULTIRT_DEBUG_TAG(copy_mp);
19606 				}
19607 			}
19608 		}
19609 
19610 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19611 
19612 		/*
19613 		 * Try to resolve another multiroute if
19614 		 * ire_multirt_need_resolve() deemed it necessary.
19615 		 */
19616 		if (copy_mp != NULL) {
19617 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19618 		}
19619 		if (need_decref)
19620 			CONN_DEC_REF(connp);
19621 		return;
19622 	}
19623 
19624 	/*
19625 	 * Access to conn_ire_cache. (protected by conn_lock)
19626 	 *
19627 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
19628 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
19629 	 * send a packet or two with the IRE_CACHE that is going away.
19630 	 * Access to the ire requires an ire refhold on the ire prior to
19631 	 * its use since an interface unplumb thread may delete the cached
19632 	 * ire and release the refhold at any time.
19633 	 *
19634 	 * Caching an ire in the conn_ire_cache
19635 	 *
19636 	 * o Caching an ire pointer in the conn requires a strict check for
19637 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
19638 	 * ires  before cleaning up the conns. So the caching of an ire pointer
19639 	 * in the conn is done after making sure under the bucket lock that the
19640 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
19641 	 * caching an ire after the unplumb thread has cleaned up the conn.
19642 	 * If the conn does not send a packet subsequently the unplumb thread
19643 	 * will be hanging waiting for the ire count to drop to zero.
19644 	 *
19645 	 * o We also need to atomically test for a null conn_ire_cache and
19646 	 * set the conn_ire_cache under the the protection of the conn_lock
19647 	 * to avoid races among concurrent threads trying to simultaneously
19648 	 * cache an ire in the conn_ire_cache.
19649 	 */
19650 	mutex_enter(&connp->conn_lock);
19651 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
19652 
19653 	if (ire != NULL && ire->ire_addr == dst &&
19654 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19655 
19656 		IRE_REFHOLD(ire);
19657 		mutex_exit(&connp->conn_lock);
19658 
19659 	} else {
19660 		boolean_t cached = B_FALSE;
19661 		connp->conn_ire_cache = NULL;
19662 		mutex_exit(&connp->conn_lock);
19663 		/* Release the old ire */
19664 		if (ire != NULL && sctp_ire == NULL)
19665 			IRE_REFRELE_NOTR(ire);
19666 
19667 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19668 		if (ire == NULL)
19669 			goto noirefound;
19670 		IRE_REFHOLD_NOTR(ire);
19671 
19672 		mutex_enter(&connp->conn_lock);
19673 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
19674 		    connp->conn_ire_cache == NULL) {
19675 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19676 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19677 				connp->conn_ire_cache = ire;
19678 				cached = B_TRUE;
19679 			}
19680 			rw_exit(&ire->ire_bucket->irb_lock);
19681 		}
19682 		mutex_exit(&connp->conn_lock);
19683 
19684 		/*
19685 		 * We can continue to use the ire but since it was
19686 		 * not cached, we should drop the extra reference.
19687 		 */
19688 		if (!cached)
19689 			IRE_REFRELE_NOTR(ire);
19690 	}
19691 
19692 
19693 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19694 	    "ip_wput_end: q %p (%S)", q, "end");
19695 
19696 	/*
19697 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19698 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19699 	 */
19700 	if (ire->ire_flags & RTF_MULTIRT) {
19701 
19702 		/*
19703 		 * Force the TTL of multirouted packets if required.
19704 		 * The TTL of such packets is bounded by the
19705 		 * ip_multirt_ttl ndd variable.
19706 		 */
19707 		if ((ip_multirt_ttl > 0) &&
19708 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19709 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19710 			    "(was %d), dst 0x%08x\n",
19711 			    ip_multirt_ttl, ipha->ipha_ttl,
19712 			    ntohl(ire->ire_addr)));
19713 			ipha->ipha_ttl = ip_multirt_ttl;
19714 		}
19715 
19716 		/*
19717 		 * At this point, we check to see if there are any pending
19718 		 * unresolved routes. ire_multirt_resolvable()
19719 		 * checks in O(n) that all IRE_OFFSUBNET ire
19720 		 * entries for the packet's destination and
19721 		 * flagged RTF_MULTIRT are currently resolved.
19722 		 * If some remain unresolved, we make a copy
19723 		 * of the current message. It will be used
19724 		 * to initiate additional route resolutions.
19725 		 */
19726 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19727 		    MBLK_GETLABEL(first_mp));
19728 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19729 		    "multirt_need_resolve %d, first_mp %p\n",
19730 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19731 		if (multirt_need_resolve) {
19732 			copy_mp = copymsg(first_mp);
19733 			if (copy_mp != NULL) {
19734 				MULTIRT_DEBUG_TAG(copy_mp);
19735 			}
19736 		}
19737 	}
19738 
19739 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19740 
19741 	/*
19742 	 * Try to resolve another multiroute if
19743 	 * ire_multirt_resolvable() deemed it necessary
19744 	 */
19745 	if (copy_mp != NULL) {
19746 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19747 	}
19748 	if (need_decref)
19749 		CONN_DEC_REF(connp);
19750 	return;
19751 
19752 qnext:
19753 	/*
19754 	 * Upper Level Protocols pass down complete IP datagrams
19755 	 * as M_DATA messages.	Everything else is a sideshow.
19756 	 *
19757 	 * 1) We could be re-entering ip_wput because of ip_neworute
19758 	 *    in which case we could have a IPSEC_OUT message. We
19759 	 *    need to pass through ip_wput like other datagrams and
19760 	 *    hence cannot branch to ip_wput_nondata.
19761 	 *
19762 	 * 2) ARP, AH, ESP, and other clients who are on the module
19763 	 *    instance of IP stream, give us something to deal with.
19764 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19765 	 *
19766 	 * 3) ICMP replies also could come here.
19767 	 */
19768 	if (DB_TYPE(mp) != M_DATA) {
19769 	    notdata:
19770 		if (DB_TYPE(mp) == M_CTL) {
19771 			/*
19772 			 * M_CTL messages are used by ARP, AH and ESP to
19773 			 * communicate with IP. We deal with IPSEC_IN and
19774 			 * IPSEC_OUT here. ip_wput_nondata handles other
19775 			 * cases.
19776 			 */
19777 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19778 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19779 				first_mp = mp->b_cont;
19780 				first_mp->b_flag &= ~MSGHASREF;
19781 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19782 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19783 				CONN_DEC_REF(connp);
19784 				connp = NULL;
19785 			}
19786 			if (ii->ipsec_info_type == IPSEC_IN) {
19787 				/*
19788 				 * Either this message goes back to
19789 				 * IPSEC for further processing or to
19790 				 * ULP after policy checks.
19791 				 */
19792 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19793 				return;
19794 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19795 				io = (ipsec_out_t *)ii;
19796 				if (io->ipsec_out_proc_begin) {
19797 					/*
19798 					 * IPSEC processing has already started.
19799 					 * Complete it.
19800 					 * IPQoS notes: We don't care what is
19801 					 * in ipsec_out_ill_index since this
19802 					 * won't be processed for IPQoS policies
19803 					 * in ipsec_out_process.
19804 					 */
19805 					ipsec_out_process(q, mp, NULL,
19806 					    io->ipsec_out_ill_index);
19807 					return;
19808 				} else {
19809 					connp = (q->q_next != NULL) ?
19810 					    NULL : Q_TO_CONN(q);
19811 					first_mp = mp;
19812 					mp = mp->b_cont;
19813 					mctl_present = B_TRUE;
19814 				}
19815 				zoneid = io->ipsec_out_zoneid;
19816 				ASSERT(zoneid != ALL_ZONES);
19817 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
19818 				/*
19819 				 * It's an IPsec control message requesting
19820 				 * an SADB update to be sent to the IPsec
19821 				 * hardware acceleration capable ills.
19822 				 */
19823 				ipsec_ctl_t *ipsec_ctl =
19824 				    (ipsec_ctl_t *)mp->b_rptr;
19825 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
19826 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
19827 				mblk_t *cmp = mp->b_cont;
19828 
19829 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
19830 				ASSERT(cmp != NULL);
19831 
19832 				freeb(mp);
19833 				ill_ipsec_capab_send_all(satype, cmp, sa);
19834 				return;
19835 			} else {
19836 				/*
19837 				 * This must be ARP or special TSOL signaling.
19838 				 */
19839 				ip_wput_nondata(NULL, q, mp, NULL);
19840 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19841 				    "ip_wput_end: q %p (%S)", q, "nondata");
19842 				return;
19843 			}
19844 		} else {
19845 			/*
19846 			 * This must be non-(ARP/AH/ESP) messages.
19847 			 */
19848 			ASSERT(!need_decref);
19849 			ip_wput_nondata(NULL, q, mp, NULL);
19850 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19851 			    "ip_wput_end: q %p (%S)", q, "nondata");
19852 			return;
19853 		}
19854 	} else {
19855 		first_mp = mp;
19856 		mctl_present = B_FALSE;
19857 	}
19858 
19859 	ASSERT(first_mp != NULL);
19860 	/*
19861 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
19862 	 * to make sure that this packet goes out on the same interface it
19863 	 * came in. We handle that here.
19864 	 */
19865 	if (mctl_present) {
19866 		uint_t ifindex;
19867 
19868 		io = (ipsec_out_t *)first_mp->b_rptr;
19869 		if (io->ipsec_out_attach_if ||
19870 		    io->ipsec_out_xmit_if ||
19871 		    io->ipsec_out_ip_nexthop) {
19872 			ill_t	*ill;
19873 
19874 			/*
19875 			 * We may have lost the conn context if we are
19876 			 * coming here from ip_newroute(). Copy the
19877 			 * nexthop information.
19878 			 */
19879 			if (io->ipsec_out_ip_nexthop) {
19880 				ip_nexthop = B_TRUE;
19881 				nexthop_addr = io->ipsec_out_nexthop_addr;
19882 
19883 				ipha = (ipha_t *)mp->b_rptr;
19884 				dst = ipha->ipha_dst;
19885 				goto send_from_ill;
19886 			} else {
19887 				ASSERT(io->ipsec_out_ill_index != 0);
19888 				ifindex = io->ipsec_out_ill_index;
19889 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
19890 				    NULL, NULL, NULL, NULL);
19891 				/*
19892 				 * ipsec_out_xmit_if bit is used to tell
19893 				 * ip_wput to use the ill to send outgoing data
19894 				 * as we have no conn when data comes from ICMP
19895 				 * error msg routines. Currently this feature is
19896 				 * only used by ip_mrtun_forward routine.
19897 				 */
19898 				if (io->ipsec_out_xmit_if) {
19899 					xmit_ill = ill;
19900 					if (xmit_ill == NULL) {
19901 						ip1dbg(("ip_output:bad ifindex "
19902 						    "for xmit_ill %d\n",
19903 						    ifindex));
19904 						freemsg(first_mp);
19905 						BUMP_MIB(&ip_mib,
19906 						    ipOutDiscards);
19907 						ASSERT(!need_decref);
19908 						return;
19909 					}
19910 					/* Free up the ipsec_out_t mblk */
19911 					ASSERT(first_mp->b_cont == mp);
19912 					first_mp->b_cont = NULL;
19913 					freeb(first_mp);
19914 					/* Just send the IP header+ICMP+data */
19915 					first_mp = mp;
19916 					ipha = (ipha_t *)mp->b_rptr;
19917 					dst = ipha->ipha_dst;
19918 					goto send_from_ill;
19919 				} else {
19920 					attach_ill = ill;
19921 				}
19922 
19923 				if (attach_ill == NULL) {
19924 					ASSERT(xmit_ill == NULL);
19925 					ip1dbg(("ip_output: bad ifindex for "
19926 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
19927 					    ifindex));
19928 					freemsg(first_mp);
19929 					BUMP_MIB(&ip_mib, ipOutDiscards);
19930 					ASSERT(!need_decref);
19931 					return;
19932 				}
19933 			}
19934 		}
19935 	}
19936 
19937 	ASSERT(xmit_ill == NULL);
19938 
19939 	/* We have a complete IP datagram heading outbound. */
19940 	ipha = (ipha_t *)mp->b_rptr;
19941 
19942 #ifndef SPEED_BEFORE_SAFETY
19943 	/*
19944 	 * Make sure we have a full-word aligned message and that at least
19945 	 * a simple IP header is accessible in the first message.  If not,
19946 	 * try a pullup.
19947 	 */
19948 	if (!OK_32PTR(rptr) ||
19949 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
19950 	    hdrtoosmall:
19951 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
19952 			BUMP_MIB(&ip_mib, ipOutDiscards);
19953 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19954 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
19955 			if (first_mp == NULL)
19956 				first_mp = mp;
19957 			goto drop_pkt;
19958 		}
19959 
19960 		/* This function assumes that mp points to an IPv4 packet. */
19961 		if (is_system_labeled() && q->q_next == NULL &&
19962 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
19963 		    !connp->conn_ulp_labeled) {
19964 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
19965 			    &adjust, connp->conn_mac_exempt);
19966 			ipha = (ipha_t *)mp->b_rptr;
19967 			if (first_mp != NULL)
19968 				first_mp->b_cont = mp;
19969 			if (err != 0) {
19970 				if (first_mp == NULL)
19971 					first_mp = mp;
19972 				if (err == EINVAL)
19973 					goto icmp_parameter_problem;
19974 				ip2dbg(("ip_wput: label check failed (%d)\n",
19975 				    err));
19976 				goto drop_pkt;
19977 			}
19978 			iplen = ntohs(ipha->ipha_length) + adjust;
19979 			ipha->ipha_length = htons(iplen);
19980 		}
19981 
19982 		ipha = (ipha_t *)mp->b_rptr;
19983 		if (first_mp == NULL) {
19984 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
19985 			/*
19986 			 * If we got here because of "goto hdrtoosmall"
19987 			 * We need to attach a IPSEC_OUT.
19988 			 */
19989 			if (connp->conn_out_enforce_policy) {
19990 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
19991 				    NULL, ipha->ipha_protocol)) == NULL)) {
19992 					if (need_decref)
19993 						CONN_DEC_REF(connp);
19994 					return;
19995 				} else {
19996 					ASSERT(mp->b_datap->db_type == M_CTL);
19997 					first_mp = mp;
19998 					mp = mp->b_cont;
19999 					mctl_present = B_TRUE;
20000 				}
20001 			} else {
20002 				first_mp = mp;
20003 				mctl_present = B_FALSE;
20004 			}
20005 		}
20006 	}
20007 #endif
20008 
20009 	/* Most of the code below is written for speed, not readability */
20010 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20011 
20012 	/*
20013 	 * If ip_newroute() fails, we're going to need a full
20014 	 * header for the icmp wraparound.
20015 	 */
20016 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20017 		uint_t	v_hlen;
20018 	    version_hdrlen_check:
20019 		ASSERT(first_mp != NULL);
20020 		v_hlen = V_HLEN;
20021 		/*
20022 		 * siphon off IPv6 packets coming down from transport
20023 		 * layer modules here.
20024 		 * Note: high-order bit carries NUD reachability confirmation
20025 		 */
20026 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20027 			/*
20028 			 * XXX implement a IPv4 and IPv6 packet counter per
20029 			 * conn and switch when ratio exceeds e.g. 10:1
20030 			 */
20031 #ifdef notyet
20032 			if (q->q_next == NULL) /* Avoid ill queue */
20033 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
20034 #endif
20035 			BUMP_MIB(&ip_mib, ipOutIPv6);
20036 			ASSERT(xmit_ill == NULL);
20037 			if (attach_ill != NULL)
20038 				ill_refrele(attach_ill);
20039 			if (need_decref)
20040 				mp->b_flag |= MSGHASREF;
20041 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20042 			return;
20043 		}
20044 
20045 		if ((v_hlen >> 4) != IP_VERSION) {
20046 			BUMP_MIB(&ip_mib, ipOutDiscards);
20047 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20048 			    "ip_wput_end: q %p (%S)", q, "badvers");
20049 			goto drop_pkt;
20050 		}
20051 		/*
20052 		 * Is the header length at least 20 bytes?
20053 		 *
20054 		 * Are there enough bytes accessible in the header?  If
20055 		 * not, try a pullup.
20056 		 */
20057 		v_hlen &= 0xF;
20058 		v_hlen <<= 2;
20059 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20060 			BUMP_MIB(&ip_mib, ipOutDiscards);
20061 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20062 			    "ip_wput_end: q %p (%S)", q, "badlen");
20063 			goto drop_pkt;
20064 		}
20065 		if (v_hlen > (mp->b_wptr - rptr)) {
20066 			if (!pullupmsg(mp, v_hlen)) {
20067 				BUMP_MIB(&ip_mib, ipOutDiscards);
20068 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20069 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20070 				goto drop_pkt;
20071 			}
20072 			ipha = (ipha_t *)mp->b_rptr;
20073 		}
20074 		/*
20075 		 * Move first entry from any source route into ipha_dst and
20076 		 * verify the options
20077 		 */
20078 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
20079 			ASSERT(xmit_ill == NULL);
20080 			if (attach_ill != NULL)
20081 				ill_refrele(attach_ill);
20082 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20083 			    "ip_wput_end: q %p (%S)", q, "badopts");
20084 			if (need_decref)
20085 				CONN_DEC_REF(connp);
20086 			return;
20087 		}
20088 	}
20089 	dst = ipha->ipha_dst;
20090 
20091 	/*
20092 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20093 	 * we have to run the packet through ip_newroute which will take
20094 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20095 	 * a resolver, or assigning a default gateway, etc.
20096 	 */
20097 	if (CLASSD(dst)) {
20098 		ipif_t	*ipif;
20099 		uint32_t setsrc = 0;
20100 
20101 	    multicast:
20102 		ASSERT(first_mp != NULL);
20103 		ASSERT(xmit_ill == NULL);
20104 		ip2dbg(("ip_wput: CLASSD\n"));
20105 		if (connp == NULL) {
20106 			/*
20107 			 * Use the first good ipif on the ill.
20108 			 * XXX Should this ever happen? (Appears
20109 			 * to show up with just ppp and no ethernet due
20110 			 * to in.rdisc.)
20111 			 * However, ire_send should be able to
20112 			 * call ip_wput_ire directly.
20113 			 *
20114 			 * XXX Also, this can happen for ICMP and other packets
20115 			 * with multicast source addresses.  Perhaps we should
20116 			 * fix things so that we drop the packet in question,
20117 			 * but for now, just run with it.
20118 			 */
20119 			ill_t *ill = (ill_t *)q->q_ptr;
20120 
20121 			/*
20122 			 * Don't honor attach_if for this case. If ill
20123 			 * is part of the group, ipif could belong to
20124 			 * any ill and we cannot maintain attach_ill
20125 			 * and ipif_ill same anymore and the assert
20126 			 * below would fail.
20127 			 */
20128 			if (mctl_present && io->ipsec_out_attach_if) {
20129 				io->ipsec_out_ill_index = 0;
20130 				io->ipsec_out_attach_if = B_FALSE;
20131 				ASSERT(attach_ill != NULL);
20132 				ill_refrele(attach_ill);
20133 				attach_ill = NULL;
20134 			}
20135 
20136 			ASSERT(attach_ill == NULL);
20137 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20138 			if (ipif == NULL) {
20139 				if (need_decref)
20140 					CONN_DEC_REF(connp);
20141 				freemsg(first_mp);
20142 				return;
20143 			}
20144 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20145 			    ntohl(dst), ill->ill_name));
20146 		} else {
20147 			/*
20148 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
20149 			 * IP_XMIT_IF is honoured.
20150 			 * Block comment above this function explains the
20151 			 * locking mechanism used here
20152 			 */
20153 			xmit_ill = conn_get_held_ill(connp,
20154 			    &connp->conn_xmit_if_ill, &err);
20155 			if (err == ILL_LOOKUP_FAILED) {
20156 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
20157 				goto drop_pkt;
20158 			}
20159 			if (xmit_ill == NULL) {
20160 				ipif = conn_get_held_ipif(connp,
20161 				    &connp->conn_multicast_ipif, &err);
20162 				if (err == IPIF_LOOKUP_FAILED) {
20163 					ip1dbg(("ip_wput: No ipif for "
20164 					    "multicast\n"));
20165 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20166 					goto drop_pkt;
20167 				}
20168 			}
20169 			if (xmit_ill != NULL) {
20170 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20171 				if (ipif == NULL) {
20172 					ip1dbg(("ip_wput: No ipif for "
20173 					    "IP_XMIT_IF\n"));
20174 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20175 					goto drop_pkt;
20176 				}
20177 			} else if (ipif == NULL || ipif->ipif_isv6) {
20178 				/*
20179 				 * We must do this ipif determination here
20180 				 * else we could pass through ip_newroute
20181 				 * and come back here without the conn context.
20182 				 *
20183 				 * Note: we do late binding i.e. we bind to
20184 				 * the interface when the first packet is sent.
20185 				 * For performance reasons we do not rebind on
20186 				 * each packet but keep the binding until the
20187 				 * next IP_MULTICAST_IF option.
20188 				 *
20189 				 * conn_multicast_{ipif,ill} are shared between
20190 				 * IPv4 and IPv6 and AF_INET6 sockets can
20191 				 * send both IPv4 and IPv6 packets. Hence
20192 				 * we have to check that "isv6" matches above.
20193 				 */
20194 				if (ipif != NULL)
20195 					ipif_refrele(ipif);
20196 				ipif = ipif_lookup_group(dst, zoneid);
20197 				if (ipif == NULL) {
20198 					ip1dbg(("ip_wput: No ipif for "
20199 					    "multicast\n"));
20200 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20201 					goto drop_pkt;
20202 				}
20203 				err = conn_set_held_ipif(connp,
20204 				    &connp->conn_multicast_ipif, ipif);
20205 				if (err == IPIF_LOOKUP_FAILED) {
20206 					ipif_refrele(ipif);
20207 					ip1dbg(("ip_wput: No ipif for "
20208 					    "multicast\n"));
20209 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20210 					goto drop_pkt;
20211 				}
20212 			}
20213 		}
20214 		ASSERT(!ipif->ipif_isv6);
20215 		/*
20216 		 * As we may lose the conn by the time we reach ip_wput_ire,
20217 		 * we copy conn_multicast_loop and conn_dontroute on to an
20218 		 * ipsec_out. In case if this datagram goes out secure,
20219 		 * we need the ill_index also. Copy that also into the
20220 		 * ipsec_out.
20221 		 */
20222 		if (mctl_present) {
20223 			io = (ipsec_out_t *)first_mp->b_rptr;
20224 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20225 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20226 		} else {
20227 			ASSERT(mp == first_mp);
20228 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20229 			    BPRI_HI)) == NULL) {
20230 				ipif_refrele(ipif);
20231 				first_mp = mp;
20232 				goto drop_pkt;
20233 			}
20234 			first_mp->b_datap->db_type = M_CTL;
20235 			first_mp->b_wptr += sizeof (ipsec_info_t);
20236 			/* ipsec_out_secure is B_FALSE now */
20237 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20238 			io = (ipsec_out_t *)first_mp->b_rptr;
20239 			io->ipsec_out_type = IPSEC_OUT;
20240 			io->ipsec_out_len = sizeof (ipsec_out_t);
20241 			io->ipsec_out_use_global_policy = B_TRUE;
20242 			first_mp->b_cont = mp;
20243 			mctl_present = B_TRUE;
20244 		}
20245 		if (attach_ill != NULL) {
20246 			ASSERT(attach_ill == ipif->ipif_ill);
20247 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20248 
20249 			/*
20250 			 * Check if we need an ire that will not be
20251 			 * looked up by anybody else i.e. HIDDEN.
20252 			 */
20253 			if (ill_is_probeonly(attach_ill)) {
20254 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20255 			}
20256 			io->ipsec_out_ill_index =
20257 			    attach_ill->ill_phyint->phyint_ifindex;
20258 			io->ipsec_out_attach_if = B_TRUE;
20259 		} else {
20260 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20261 			io->ipsec_out_ill_index =
20262 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20263 		}
20264 		if (connp != NULL) {
20265 			io->ipsec_out_multicast_loop =
20266 			    connp->conn_multicast_loop;
20267 			io->ipsec_out_dontroute = connp->conn_dontroute;
20268 			io->ipsec_out_zoneid = connp->conn_zoneid;
20269 		}
20270 		/*
20271 		 * If the application uses IP_MULTICAST_IF with
20272 		 * different logical addresses of the same ILL, we
20273 		 * need to make sure that the soruce address of
20274 		 * the packet matches the logical IP address used
20275 		 * in the option. We do it by initializing ipha_src
20276 		 * here. This should keep IPSEC also happy as
20277 		 * when we return from IPSEC processing, we don't
20278 		 * have to worry about getting the right address on
20279 		 * the packet. Thus it is sufficient to look for
20280 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20281 		 * MATCH_IRE_IPIF.
20282 		 *
20283 		 * NOTE : We need to do it for non-secure case also as
20284 		 * this might go out secure if there is a global policy
20285 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20286 		 * address, the source should be initialized already and
20287 		 * hence we won't be initializing here.
20288 		 *
20289 		 * As we do not have the ire yet, it is possible that
20290 		 * we set the source address here and then later discover
20291 		 * that the ire implies the source address to be assigned
20292 		 * through the RTF_SETSRC flag.
20293 		 * In that case, the setsrc variable will remind us
20294 		 * that overwritting the source address by the one
20295 		 * of the RTF_SETSRC-flagged ire is allowed.
20296 		 */
20297 		if (ipha->ipha_src == INADDR_ANY &&
20298 		    (connp == NULL || !connp->conn_unspec_src)) {
20299 			ipha->ipha_src = ipif->ipif_src_addr;
20300 			setsrc = RTF_SETSRC;
20301 		}
20302 		/*
20303 		 * Find an IRE which matches the destination and the outgoing
20304 		 * queue (i.e. the outgoing interface.)
20305 		 * For loopback use a unicast IP address for
20306 		 * the ire lookup.
20307 		 */
20308 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20309 		    PHYI_LOOPBACK) {
20310 			dst = ipif->ipif_lcl_addr;
20311 		}
20312 		/*
20313 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20314 		 * We don't need to lookup ire in ctable as the packet
20315 		 * needs to be sent to the destination through the specified
20316 		 * ill irrespective of ires in the cache table.
20317 		 */
20318 		ire = NULL;
20319 		if (xmit_ill == NULL) {
20320 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20321 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20322 		}
20323 
20324 		/*
20325 		 * refrele attach_ill as its not needed anymore.
20326 		 */
20327 		if (attach_ill != NULL) {
20328 			ill_refrele(attach_ill);
20329 			attach_ill = NULL;
20330 		}
20331 
20332 		if (ire == NULL) {
20333 			/*
20334 			 * Multicast loopback and multicast forwarding is
20335 			 * done in ip_wput_ire.
20336 			 *
20337 			 * Mark this packet to make it be delivered to
20338 			 * ip_wput_ire after the new ire has been
20339 			 * created.
20340 			 *
20341 			 * The call to ip_newroute_ipif takes into account
20342 			 * the setsrc reminder. In any case, we take care
20343 			 * of the RTF_MULTIRT flag.
20344 			 */
20345 			mp->b_prev = mp->b_next = NULL;
20346 			if (xmit_ill == NULL ||
20347 			    xmit_ill->ill_ipif_up_count > 0) {
20348 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20349 				    setsrc | RTF_MULTIRT, zoneid);
20350 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20351 				    "ip_wput_end: q %p (%S)", q, "noire");
20352 			} else {
20353 				freemsg(first_mp);
20354 			}
20355 			ipif_refrele(ipif);
20356 			if (xmit_ill != NULL)
20357 				ill_refrele(xmit_ill);
20358 			if (need_decref)
20359 				CONN_DEC_REF(connp);
20360 			return;
20361 		}
20362 
20363 		ipif_refrele(ipif);
20364 		ipif = NULL;
20365 		ASSERT(xmit_ill == NULL);
20366 
20367 		/*
20368 		 * Honor the RTF_SETSRC flag for multicast packets,
20369 		 * if allowed by the setsrc reminder.
20370 		 */
20371 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20372 			ipha->ipha_src = ire->ire_src_addr;
20373 		}
20374 
20375 		/*
20376 		 * Unconditionally force the TTL to 1 for
20377 		 * multirouted multicast packets:
20378 		 * multirouted multicast should not cross
20379 		 * multicast routers.
20380 		 */
20381 		if (ire->ire_flags & RTF_MULTIRT) {
20382 			if (ipha->ipha_ttl > 1) {
20383 				ip2dbg(("ip_wput: forcing multicast "
20384 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20385 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20386 				ipha->ipha_ttl = 1;
20387 			}
20388 		}
20389 	} else {
20390 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20391 		if ((ire != NULL) && (ire->ire_type &
20392 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20393 			ignore_dontroute = B_TRUE;
20394 			ignore_nexthop = B_TRUE;
20395 		}
20396 		if (ire != NULL) {
20397 			ire_refrele(ire);
20398 			ire = NULL;
20399 		}
20400 		/*
20401 		 * Guard against coming in from arp in which case conn is NULL.
20402 		 * Also guard against non M_DATA with dontroute set but
20403 		 * destined to local, loopback or broadcast addresses.
20404 		 */
20405 		if (connp != NULL && connp->conn_dontroute &&
20406 		    !ignore_dontroute) {
20407 dontroute:
20408 			/*
20409 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20410 			 * routing protocols from seeing false direct
20411 			 * connectivity.
20412 			 */
20413 			ipha->ipha_ttl = 1;
20414 			/*
20415 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20416 			 * along with SO_DONTROUTE, higher precedence is
20417 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20418 			 */
20419 			if (connp->conn_xmit_if_ill == NULL) {
20420 				/* If suitable ipif not found, drop packet */
20421 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20422 				if (dst_ipif == NULL) {
20423 					ip1dbg(("ip_wput: no route for "
20424 					    "dst using SO_DONTROUTE\n"));
20425 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20426 					mp->b_prev = mp->b_next = NULL;
20427 					if (first_mp == NULL)
20428 						first_mp = mp;
20429 					goto drop_pkt;
20430 				} else {
20431 					/*
20432 					 * If suitable ipif has been found, set
20433 					 * xmit_ill to the corresponding
20434 					 * ipif_ill because we'll be following
20435 					 * the IP_XMIT_IF logic.
20436 					 */
20437 					ASSERT(xmit_ill == NULL);
20438 					xmit_ill = dst_ipif->ipif_ill;
20439 					mutex_enter(&xmit_ill->ill_lock);
20440 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20441 						mutex_exit(&xmit_ill->ill_lock);
20442 						xmit_ill = NULL;
20443 						ipif_refrele(dst_ipif);
20444 						ip1dbg(("ip_wput: no route for"
20445 						    " dst using"
20446 						    " SO_DONTROUTE\n"));
20447 						BUMP_MIB(&ip_mib,
20448 						    ipOutNoRoutes);
20449 						mp->b_prev = mp->b_next = NULL;
20450 						if (first_mp == NULL)
20451 							first_mp = mp;
20452 						goto drop_pkt;
20453 					}
20454 					ill_refhold_locked(xmit_ill);
20455 					mutex_exit(&xmit_ill->ill_lock);
20456 					ipif_refrele(dst_ipif);
20457 				}
20458 			}
20459 
20460 		}
20461 		/*
20462 		 * If we are bound to IPIF_NOFAILOVER address, look for
20463 		 * an IRE_CACHE matching the ill.
20464 		 */
20465 send_from_ill:
20466 		if (attach_ill != NULL) {
20467 			ipif_t	*attach_ipif;
20468 
20469 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20470 
20471 			/*
20472 			 * Check if we need an ire that will not be
20473 			 * looked up by anybody else i.e. HIDDEN.
20474 			 */
20475 			if (ill_is_probeonly(attach_ill)) {
20476 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20477 			}
20478 
20479 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20480 			if (attach_ipif == NULL) {
20481 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20482 				goto drop_pkt;
20483 			}
20484 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20485 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20486 			ipif_refrele(attach_ipif);
20487 		} else if (xmit_ill != NULL || (connp != NULL &&
20488 			    connp->conn_xmit_if_ill != NULL)) {
20489 			/*
20490 			 * Mark this packet as originated locally
20491 			 */
20492 			mp->b_prev = mp->b_next = NULL;
20493 			/*
20494 			 * xmit_ill could be NULL if SO_DONTROUTE
20495 			 * is also set.
20496 			 */
20497 			if (xmit_ill == NULL) {
20498 				xmit_ill = conn_get_held_ill(connp,
20499 				    &connp->conn_xmit_if_ill, &err);
20500 				if (err == ILL_LOOKUP_FAILED) {
20501 					if (need_decref)
20502 						CONN_DEC_REF(connp);
20503 					freemsg(first_mp);
20504 					return;
20505 				}
20506 				if (xmit_ill == NULL) {
20507 					if (connp->conn_dontroute)
20508 						goto dontroute;
20509 					goto send_from_ill;
20510 				}
20511 			}
20512 			/*
20513 			 * could be SO_DONTROUTE case also.
20514 			 * check at least one interface is UP as
20515 			 * spcified by this ILL, and then call
20516 			 * ip_newroute_ipif()
20517 			 */
20518 			if (xmit_ill->ill_ipif_up_count > 0) {
20519 				ipif_t *ipif;
20520 
20521 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20522 				if (ipif != NULL) {
20523 					ip_newroute_ipif(q, first_mp, ipif,
20524 					    dst, connp, 0, zoneid);
20525 					ipif_refrele(ipif);
20526 					ip1dbg(("ip_wput: ip_unicast_if\n"));
20527 				}
20528 			} else {
20529 				freemsg(first_mp);
20530 			}
20531 			ill_refrele(xmit_ill);
20532 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20533 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
20534 			if (need_decref)
20535 				CONN_DEC_REF(connp);
20536 			return;
20537 		} else if (ip_nexthop || (connp != NULL &&
20538 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
20539 			if (!ip_nexthop) {
20540 				ip_nexthop = B_TRUE;
20541 				nexthop_addr = connp->conn_nexthop_v4;
20542 			}
20543 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
20544 			    MATCH_IRE_GW;
20545 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
20546 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
20547 		} else {
20548 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20549 		}
20550 		if (!ire) {
20551 			/*
20552 			 * Make sure we don't load spread if this
20553 			 * is IPIF_NOFAILOVER case.
20554 			 */
20555 			if ((attach_ill != NULL) ||
20556 			    (ip_nexthop && !ignore_nexthop)) {
20557 				if (mctl_present) {
20558 					io = (ipsec_out_t *)first_mp->b_rptr;
20559 					ASSERT(first_mp->b_datap->db_type ==
20560 					    M_CTL);
20561 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
20562 				} else {
20563 					ASSERT(mp == first_mp);
20564 					first_mp = allocb(
20565 					    sizeof (ipsec_info_t), BPRI_HI);
20566 					if (first_mp == NULL) {
20567 						first_mp = mp;
20568 						goto drop_pkt;
20569 					}
20570 					first_mp->b_datap->db_type = M_CTL;
20571 					first_mp->b_wptr +=
20572 					    sizeof (ipsec_info_t);
20573 					/* ipsec_out_secure is B_FALSE now */
20574 					bzero(first_mp->b_rptr,
20575 					    sizeof (ipsec_info_t));
20576 					io = (ipsec_out_t *)first_mp->b_rptr;
20577 					io->ipsec_out_type = IPSEC_OUT;
20578 					io->ipsec_out_len =
20579 					    sizeof (ipsec_out_t);
20580 					io->ipsec_out_use_global_policy =
20581 					    B_TRUE;
20582 					first_mp->b_cont = mp;
20583 					mctl_present = B_TRUE;
20584 				}
20585 				if (attach_ill != NULL) {
20586 					io->ipsec_out_ill_index = attach_ill->
20587 					    ill_phyint->phyint_ifindex;
20588 					io->ipsec_out_attach_if = B_TRUE;
20589 				} else {
20590 					io->ipsec_out_ip_nexthop = ip_nexthop;
20591 					io->ipsec_out_nexthop_addr =
20592 					    nexthop_addr;
20593 				}
20594 			}
20595 noirefound:
20596 			/*
20597 			 * Mark this packet as having originated on
20598 			 * this machine.  This will be noted in
20599 			 * ire_add_then_send, which needs to know
20600 			 * whether to run it back through ip_wput or
20601 			 * ip_rput following successful resolution.
20602 			 */
20603 			mp->b_prev = NULL;
20604 			mp->b_next = NULL;
20605 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid);
20606 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20607 			    "ip_wput_end: q %p (%S)", q, "newroute");
20608 			if (attach_ill != NULL)
20609 				ill_refrele(attach_ill);
20610 			if (xmit_ill != NULL)
20611 				ill_refrele(xmit_ill);
20612 			if (need_decref)
20613 				CONN_DEC_REF(connp);
20614 			return;
20615 		}
20616 	}
20617 
20618 	/* We now know where we are going with it. */
20619 
20620 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20621 	    "ip_wput_end: q %p (%S)", q, "end");
20622 
20623 	/*
20624 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20625 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
20626 	 */
20627 	if (ire->ire_flags & RTF_MULTIRT) {
20628 		/*
20629 		 * Force the TTL of multirouted packets if required.
20630 		 * The TTL of such packets is bounded by the
20631 		 * ip_multirt_ttl ndd variable.
20632 		 */
20633 		if ((ip_multirt_ttl > 0) &&
20634 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20635 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20636 			    "(was %d), dst 0x%08x\n",
20637 			    ip_multirt_ttl, ipha->ipha_ttl,
20638 			    ntohl(ire->ire_addr)));
20639 			ipha->ipha_ttl = ip_multirt_ttl;
20640 		}
20641 		/*
20642 		 * At this point, we check to see if there are any pending
20643 		 * unresolved routes. ire_multirt_resolvable()
20644 		 * checks in O(n) that all IRE_OFFSUBNET ire
20645 		 * entries for the packet's destination and
20646 		 * flagged RTF_MULTIRT are currently resolved.
20647 		 * If some remain unresolved, we make a copy
20648 		 * of the current message. It will be used
20649 		 * to initiate additional route resolutions.
20650 		 */
20651 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20652 		    MBLK_GETLABEL(first_mp));
20653 		ip2dbg(("ip_wput[noirefound]: ire %p, "
20654 		    "multirt_need_resolve %d, first_mp %p\n",
20655 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20656 		if (multirt_need_resolve) {
20657 			copy_mp = copymsg(first_mp);
20658 			if (copy_mp != NULL) {
20659 				MULTIRT_DEBUG_TAG(copy_mp);
20660 			}
20661 		}
20662 	}
20663 
20664 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20665 	/*
20666 	 * Try to resolve another multiroute if
20667 	 * ire_multirt_resolvable() deemed it necessary.
20668 	 * At this point, we need to distinguish
20669 	 * multicasts from other packets. For multicasts,
20670 	 * we call ip_newroute_ipif() and request that both
20671 	 * multirouting and setsrc flags are checked.
20672 	 */
20673 	if (copy_mp != NULL) {
20674 		if (CLASSD(dst)) {
20675 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
20676 			if (ipif) {
20677 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
20678 				    RTF_SETSRC | RTF_MULTIRT, zoneid);
20679 				ipif_refrele(ipif);
20680 			} else {
20681 				MULTIRT_DEBUG_UNTAG(copy_mp);
20682 				freemsg(copy_mp);
20683 				copy_mp = NULL;
20684 			}
20685 		} else {
20686 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20687 		}
20688 	}
20689 	if (attach_ill != NULL)
20690 		ill_refrele(attach_ill);
20691 	if (xmit_ill != NULL)
20692 		ill_refrele(xmit_ill);
20693 	if (need_decref)
20694 		CONN_DEC_REF(connp);
20695 	return;
20696 
20697 icmp_parameter_problem:
20698 	/* could not have originated externally */
20699 	ASSERT(mp->b_prev == NULL);
20700 	if (ip_hdr_complete(ipha, zoneid) == 0) {
20701 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
20702 		/* it's the IP header length that's in trouble */
20703 		icmp_param_problem(q, first_mp, 0, zoneid);
20704 		first_mp = NULL;
20705 	}
20706 
20707 drop_pkt:
20708 	ip1dbg(("ip_wput: dropped packet\n"));
20709 	if (ire != NULL)
20710 		ire_refrele(ire);
20711 	if (need_decref)
20712 		CONN_DEC_REF(connp);
20713 	freemsg(first_mp);
20714 	if (attach_ill != NULL)
20715 		ill_refrele(attach_ill);
20716 	if (xmit_ill != NULL)
20717 		ill_refrele(xmit_ill);
20718 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20719 	    "ip_wput_end: q %p (%S)", q, "droppkt");
20720 }
20721 
20722 /*
20723  * If this is a conn_t queue, then we pass in the conn. This includes the
20724  * zoneid.
20725  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
20726  * in which case we use the global zoneid since those are all part of
20727  * the global zone.
20728  */
20729 void
20730 ip_wput(queue_t *q, mblk_t *mp)
20731 {
20732 	if (CONN_Q(q))
20733 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20734 	else
20735 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
20736 }
20737 
20738 /*
20739  *
20740  * The following rules must be observed when accessing any ipif or ill
20741  * that has been cached in the conn. Typically conn_nofailover_ill,
20742  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20743  *
20744  * Access: The ipif or ill pointed to from the conn can be accessed under
20745  * the protection of the conn_lock or after it has been refheld under the
20746  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20747  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20748  * The reason for this is that a concurrent unplumb could actually be
20749  * cleaning up these cached pointers by walking the conns and might have
20750  * finished cleaning up the conn in question. The macros check that an
20751  * unplumb has not yet started on the ipif or ill.
20752  *
20753  * Caching: An ipif or ill pointer may be cached in the conn only after
20754  * making sure that an unplumb has not started. So the caching is done
20755  * while holding both the conn_lock and the ill_lock and after using the
20756  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20757  * flag before starting the cleanup of conns.
20758  *
20759  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20760  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20761  * or a reference to the ipif or a reference to an ire that references the
20762  * ipif. An ipif does not change its ill except for failover/failback. Since
20763  * failover/failback happens only after bringing down the ipif and making sure
20764  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20765  * the above holds.
20766  */
20767 ipif_t *
20768 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20769 {
20770 	ipif_t	*ipif;
20771 	ill_t	*ill;
20772 
20773 	*err = 0;
20774 	rw_enter(&ill_g_lock, RW_READER);
20775 	mutex_enter(&connp->conn_lock);
20776 	ipif = *ipifp;
20777 	if (ipif != NULL) {
20778 		ill = ipif->ipif_ill;
20779 		mutex_enter(&ill->ill_lock);
20780 		if (IPIF_CAN_LOOKUP(ipif)) {
20781 			ipif_refhold_locked(ipif);
20782 			mutex_exit(&ill->ill_lock);
20783 			mutex_exit(&connp->conn_lock);
20784 			rw_exit(&ill_g_lock);
20785 			return (ipif);
20786 		} else {
20787 			*err = IPIF_LOOKUP_FAILED;
20788 		}
20789 		mutex_exit(&ill->ill_lock);
20790 	}
20791 	mutex_exit(&connp->conn_lock);
20792 	rw_exit(&ill_g_lock);
20793 	return (NULL);
20794 }
20795 
20796 ill_t *
20797 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20798 {
20799 	ill_t	*ill;
20800 
20801 	*err = 0;
20802 	mutex_enter(&connp->conn_lock);
20803 	ill = *illp;
20804 	if (ill != NULL) {
20805 		mutex_enter(&ill->ill_lock);
20806 		if (ILL_CAN_LOOKUP(ill)) {
20807 			ill_refhold_locked(ill);
20808 			mutex_exit(&ill->ill_lock);
20809 			mutex_exit(&connp->conn_lock);
20810 			return (ill);
20811 		} else {
20812 			*err = ILL_LOOKUP_FAILED;
20813 		}
20814 		mutex_exit(&ill->ill_lock);
20815 	}
20816 	mutex_exit(&connp->conn_lock);
20817 	return (NULL);
20818 }
20819 
20820 static int
20821 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
20822 {
20823 	ill_t	*ill;
20824 
20825 	ill = ipif->ipif_ill;
20826 	mutex_enter(&connp->conn_lock);
20827 	mutex_enter(&ill->ill_lock);
20828 	if (IPIF_CAN_LOOKUP(ipif)) {
20829 		*ipifp = ipif;
20830 		mutex_exit(&ill->ill_lock);
20831 		mutex_exit(&connp->conn_lock);
20832 		return (0);
20833 	}
20834 	mutex_exit(&ill->ill_lock);
20835 	mutex_exit(&connp->conn_lock);
20836 	return (IPIF_LOOKUP_FAILED);
20837 }
20838 
20839 /*
20840  * This is called if the outbound datagram needs fragmentation.
20841  *
20842  * NOTE : This function does not ire_refrele the ire argument passed in.
20843  */
20844 static void
20845 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid)
20846 {
20847 	ipha_t		*ipha;
20848 	mblk_t		*mp;
20849 	uint32_t	v_hlen_tos_len;
20850 	uint32_t	max_frag;
20851 	uint32_t	frag_flag;
20852 	boolean_t	dont_use;
20853 
20854 	if (ipsec_mp->b_datap->db_type == M_CTL) {
20855 		mp = ipsec_mp->b_cont;
20856 	} else {
20857 		mp = ipsec_mp;
20858 	}
20859 
20860 	ipha = (ipha_t *)mp->b_rptr;
20861 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20862 
20863 #ifdef	_BIG_ENDIAN
20864 #define	V_HLEN	(v_hlen_tos_len >> 24)
20865 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20866 #else
20867 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20868 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20869 #endif
20870 
20871 #ifndef SPEED_BEFORE_SAFETY
20872 	/*
20873 	 * Check that ipha_length is consistent with
20874 	 * the mblk length
20875 	 */
20876 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
20877 		ip0dbg(("Packet length mismatch: %d, %ld\n",
20878 		    LENGTH, msgdsize(mp)));
20879 		freemsg(ipsec_mp);
20880 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20881 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
20882 		    "packet length mismatch");
20883 		return;
20884 	}
20885 #endif
20886 	/*
20887 	 * Don't use frag_flag if pre-built packet or source
20888 	 * routed or if multicast (since multicast packets do not solicit
20889 	 * ICMP "packet too big" messages). Get the values of
20890 	 * max_frag and frag_flag atomically by acquiring the
20891 	 * ire_lock.
20892 	 */
20893 	mutex_enter(&ire->ire_lock);
20894 	max_frag = ire->ire_max_frag;
20895 	frag_flag = ire->ire_frag_flag;
20896 	mutex_exit(&ire->ire_lock);
20897 
20898 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
20899 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
20900 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
20901 
20902 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
20903 	    (dont_use ? 0 : frag_flag), zoneid);
20904 }
20905 
20906 /*
20907  * Used for deciding the MSS size for the upper layer. Thus
20908  * we need to check the outbound policy values in the conn.
20909  */
20910 int
20911 conn_ipsec_length(conn_t *connp)
20912 {
20913 	ipsec_latch_t *ipl;
20914 
20915 	ipl = connp->conn_latch;
20916 	if (ipl == NULL)
20917 		return (0);
20918 
20919 	if (ipl->ipl_out_policy == NULL)
20920 		return (0);
20921 
20922 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
20923 }
20924 
20925 /*
20926  * Returns an estimate of the IPSEC headers size. This is used if
20927  * we don't want to call into IPSEC to get the exact size.
20928  */
20929 int
20930 ipsec_out_extra_length(mblk_t *ipsec_mp)
20931 {
20932 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
20933 	ipsec_action_t *a;
20934 
20935 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
20936 	if (!io->ipsec_out_secure)
20937 		return (0);
20938 
20939 	a = io->ipsec_out_act;
20940 
20941 	if (a == NULL) {
20942 		ASSERT(io->ipsec_out_policy != NULL);
20943 		a = io->ipsec_out_policy->ipsp_act;
20944 	}
20945 	ASSERT(a != NULL);
20946 
20947 	return (a->ipa_ovhd);
20948 }
20949 
20950 /*
20951  * Returns an estimate of the IPSEC headers size. This is used if
20952  * we don't want to call into IPSEC to get the exact size.
20953  */
20954 int
20955 ipsec_in_extra_length(mblk_t *ipsec_mp)
20956 {
20957 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
20958 	ipsec_action_t *a;
20959 
20960 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
20961 
20962 	a = ii->ipsec_in_action;
20963 	return (a == NULL ? 0 : a->ipa_ovhd);
20964 }
20965 
20966 /*
20967  * If there are any source route options, return the true final
20968  * destination. Otherwise, return the destination.
20969  */
20970 ipaddr_t
20971 ip_get_dst(ipha_t *ipha)
20972 {
20973 	ipoptp_t	opts;
20974 	uchar_t		*opt;
20975 	uint8_t		optval;
20976 	uint8_t		optlen;
20977 	ipaddr_t	dst;
20978 	uint32_t off;
20979 
20980 	dst = ipha->ipha_dst;
20981 
20982 	if (IS_SIMPLE_IPH(ipha))
20983 		return (dst);
20984 
20985 	for (optval = ipoptp_first(&opts, ipha);
20986 	    optval != IPOPT_EOL;
20987 	    optval = ipoptp_next(&opts)) {
20988 		opt = opts.ipoptp_cur;
20989 		optlen = opts.ipoptp_len;
20990 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20991 		switch (optval) {
20992 		case IPOPT_SSRR:
20993 		case IPOPT_LSRR:
20994 			off = opt[IPOPT_OFFSET];
20995 			/*
20996 			 * If one of the conditions is true, it means
20997 			 * end of options and dst already has the right
20998 			 * value.
20999 			 */
21000 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21001 				off = optlen - IP_ADDR_LEN;
21002 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21003 			}
21004 			return (dst);
21005 		default:
21006 			break;
21007 		}
21008 	}
21009 
21010 	return (dst);
21011 }
21012 
21013 mblk_t *
21014 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21015     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21016 {
21017 	ipsec_out_t	*io;
21018 	mblk_t		*first_mp;
21019 	boolean_t policy_present;
21020 
21021 	first_mp = mp;
21022 	if (mp->b_datap->db_type == M_CTL) {
21023 		io = (ipsec_out_t *)first_mp->b_rptr;
21024 		/*
21025 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21026 		 *
21027 		 * 1) There is per-socket policy (including cached global
21028 		 *    policy).
21029 		 * 2) There is no per-socket policy, but it is
21030 		 *    a multicast packet that needs to go out
21031 		 *    on a specific interface. This is the case
21032 		 *    where (ip_wput and ip_wput_multicast) attaches
21033 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21034 		 *
21035 		 * In case (2) we check with global policy to
21036 		 * see if there is a match and set the ill_index
21037 		 * appropriately so that we can lookup the ire
21038 		 * properly in ip_wput_ipsec_out.
21039 		 */
21040 
21041 		/*
21042 		 * ipsec_out_use_global_policy is set to B_FALSE
21043 		 * in ipsec_in_to_out(). Refer to that function for
21044 		 * details.
21045 		 */
21046 		if ((io->ipsec_out_latch == NULL) &&
21047 		    (io->ipsec_out_use_global_policy)) {
21048 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21049 				    ire, connp, unspec_src, zoneid));
21050 		}
21051 		if (!io->ipsec_out_secure) {
21052 			/*
21053 			 * If this is not a secure packet, drop
21054 			 * the IPSEC_OUT mp and treat it as a clear
21055 			 * packet. This happens when we are sending
21056 			 * a ICMP reply back to a clear packet. See
21057 			 * ipsec_in_to_out() for details.
21058 			 */
21059 			mp = first_mp->b_cont;
21060 			freeb(first_mp);
21061 		}
21062 		return (mp);
21063 	}
21064 	/*
21065 	 * See whether we need to attach a global policy here. We
21066 	 * don't depend on the conn (as it could be null) for deciding
21067 	 * what policy this datagram should go through because it
21068 	 * should have happened in ip_wput if there was some
21069 	 * policy. This normally happens for connections which are not
21070 	 * fully bound preventing us from caching policies in
21071 	 * ip_bind. Packets coming from the TCP listener/global queue
21072 	 * - which are non-hard_bound - could also be affected by
21073 	 * applying policy here.
21074 	 *
21075 	 * If this packet is coming from tcp global queue or listener,
21076 	 * we will be applying policy here.  This may not be *right*
21077 	 * if these packets are coming from the detached connection as
21078 	 * it could have gone in clear before. This happens only if a
21079 	 * TCP connection started when there is no policy and somebody
21080 	 * added policy before it became detached. Thus packets of the
21081 	 * detached connection could go out secure and the other end
21082 	 * would drop it because it will be expecting in clear. The
21083 	 * converse is not true i.e if somebody starts a TCP
21084 	 * connection and deletes the policy, all the packets will
21085 	 * still go out with the policy that existed before deleting
21086 	 * because ip_unbind sends up policy information which is used
21087 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21088 	 * TCP to attach a dummy IPSEC_OUT and set
21089 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21090 	 * affect performance for normal cases, we are not doing it.
21091 	 * Thus, set policy before starting any TCP connections.
21092 	 *
21093 	 * NOTE - We might apply policy even for a hard bound connection
21094 	 * - for which we cached policy in ip_bind - if somebody added
21095 	 * global policy after we inherited the policy in ip_bind.
21096 	 * This means that the packets that were going out in clear
21097 	 * previously would start going secure and hence get dropped
21098 	 * on the other side. To fix this, TCP attaches a dummy
21099 	 * ipsec_out and make sure that we don't apply global policy.
21100 	 */
21101 	if (ipha != NULL)
21102 		policy_present = ipsec_outbound_v4_policy_present;
21103 	else
21104 		policy_present = ipsec_outbound_v6_policy_present;
21105 	if (!policy_present)
21106 		return (mp);
21107 
21108 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21109 		    zoneid));
21110 }
21111 
21112 ire_t *
21113 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21114 {
21115 	ipaddr_t addr;
21116 	ire_t *save_ire;
21117 	irb_t *irb;
21118 	ill_group_t *illgrp;
21119 	int	err;
21120 
21121 	save_ire = ire;
21122 	addr = ire->ire_addr;
21123 
21124 	ASSERT(ire->ire_type == IRE_BROADCAST);
21125 
21126 	illgrp = connp->conn_outgoing_ill->ill_group;
21127 	if (illgrp == NULL) {
21128 		*conn_outgoing_ill = conn_get_held_ill(connp,
21129 		    &connp->conn_outgoing_ill, &err);
21130 		if (err == ILL_LOOKUP_FAILED) {
21131 			ire_refrele(save_ire);
21132 			return (NULL);
21133 		}
21134 		return (save_ire);
21135 	}
21136 	/*
21137 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21138 	 * If it is part of the group, we need to send on the ire
21139 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21140 	 * to this group. This is okay as IP_BOUND_IF really means
21141 	 * any ill in the group. We depend on the fact that the
21142 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21143 	 * if such an ire exists. This is possible only if you have
21144 	 * at least one ill in the group that has not failed.
21145 	 *
21146 	 * First get to the ire that matches the address and group.
21147 	 *
21148 	 * We don't look for an ire with a matching zoneid because a given zone
21149 	 * won't always have broadcast ires on all ills in the group.
21150 	 */
21151 	irb = ire->ire_bucket;
21152 	rw_enter(&irb->irb_lock, RW_READER);
21153 	if (ire->ire_marks & IRE_MARK_NORECV) {
21154 		/*
21155 		 * If the current zone only has an ire broadcast for this
21156 		 * address marked NORECV, the ire we want is ahead in the
21157 		 * bucket, so we look it up deliberately ignoring the zoneid.
21158 		 */
21159 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21160 			if (ire->ire_addr != addr)
21161 				continue;
21162 			/* skip over deleted ires */
21163 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21164 				continue;
21165 		}
21166 	}
21167 	while (ire != NULL) {
21168 		/*
21169 		 * If a new interface is coming up, we could end up
21170 		 * seeing the loopback ire and the non-loopback ire
21171 		 * may not have been added yet. So check for ire_stq
21172 		 */
21173 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21174 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21175 			break;
21176 		}
21177 		ire = ire->ire_next;
21178 	}
21179 	if (ire != NULL && ire->ire_addr == addr &&
21180 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21181 		IRE_REFHOLD(ire);
21182 		rw_exit(&irb->irb_lock);
21183 		ire_refrele(save_ire);
21184 		*conn_outgoing_ill = ire_to_ill(ire);
21185 		/*
21186 		 * Refhold the ill to make the conn_outgoing_ill
21187 		 * independent of the ire. ip_wput_ire goes in a loop
21188 		 * and may refrele the ire. Since we have an ire at this
21189 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21190 		 */
21191 		ill_refhold(*conn_outgoing_ill);
21192 		return (ire);
21193 	}
21194 	rw_exit(&irb->irb_lock);
21195 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21196 	/*
21197 	 * If we can't find a suitable ire, return the original ire.
21198 	 */
21199 	return (save_ire);
21200 }
21201 
21202 /*
21203  * This function does the ire_refrele of the ire passed in as the
21204  * argument. As this function looks up more ires i.e broadcast ires,
21205  * it needs to REFRELE them. Currently, for simplicity we don't
21206  * differentiate the one passed in and looked up here. We always
21207  * REFRELE.
21208  * IPQoS Notes:
21209  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21210  * IPSec packets are done in ipsec_out_process.
21211  *
21212  */
21213 void
21214 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21215     zoneid_t zoneid)
21216 {
21217 	ipha_t		*ipha;
21218 #define	rptr	((uchar_t *)ipha)
21219 	queue_t		*stq;
21220 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21221 	uint32_t	v_hlen_tos_len;
21222 	uint32_t	ttl_protocol;
21223 	ipaddr_t	src;
21224 	ipaddr_t	dst;
21225 	uint32_t	cksum;
21226 	ipaddr_t	orig_src;
21227 	ire_t		*ire1;
21228 	mblk_t		*next_mp;
21229 	uint_t		hlen;
21230 	uint16_t	*up;
21231 	uint32_t	max_frag = ire->ire_max_frag;
21232 	ill_t		*ill = ire_to_ill(ire);
21233 	int		clusterwide;
21234 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21235 	int		ipsec_len;
21236 	mblk_t		*first_mp;
21237 	ipsec_out_t	*io;
21238 	boolean_t	conn_dontroute;		/* conn value for multicast */
21239 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21240 	boolean_t	multicast_forward;	/* Should we forward ? */
21241 	boolean_t	unspec_src;
21242 	ill_t		*conn_outgoing_ill = NULL;
21243 	ill_t		*ire_ill;
21244 	ill_t		*ire1_ill;
21245 	uint32_t 	ill_index = 0;
21246 	boolean_t	multirt_send = B_FALSE;
21247 	int		err;
21248 	ipxmit_state_t	pktxmit_state;
21249 
21250 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21251 	    "ip_wput_ire_start: q %p", q);
21252 
21253 	multicast_forward = B_FALSE;
21254 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21255 
21256 	if (ire->ire_flags & RTF_MULTIRT) {
21257 		/*
21258 		 * Multirouting case. The bucket where ire is stored
21259 		 * probably holds other RTF_MULTIRT flagged ire
21260 		 * to the destination. In this call to ip_wput_ire,
21261 		 * we attempt to send the packet through all
21262 		 * those ires. Thus, we first ensure that ire is the
21263 		 * first RTF_MULTIRT ire in the bucket,
21264 		 * before walking the ire list.
21265 		 */
21266 		ire_t *first_ire;
21267 		irb_t *irb = ire->ire_bucket;
21268 		ASSERT(irb != NULL);
21269 
21270 		/* Make sure we do not omit any multiroute ire. */
21271 		IRB_REFHOLD(irb);
21272 		for (first_ire = irb->irb_ire;
21273 		    first_ire != NULL;
21274 		    first_ire = first_ire->ire_next) {
21275 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21276 			    (first_ire->ire_addr == ire->ire_addr) &&
21277 			    !(first_ire->ire_marks &
21278 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21279 				break;
21280 		}
21281 
21282 		if ((first_ire != NULL) && (first_ire != ire)) {
21283 			IRE_REFHOLD(first_ire);
21284 			ire_refrele(ire);
21285 			ire = first_ire;
21286 			ill = ire_to_ill(ire);
21287 		}
21288 		IRB_REFRELE(irb);
21289 	}
21290 
21291 	/*
21292 	 * conn_outgoing_ill is used only in the broadcast loop.
21293 	 * for performance we don't grab the mutexs in the fastpath
21294 	 */
21295 	if ((connp != NULL) &&
21296 	    (connp->conn_xmit_if_ill == NULL) &&
21297 	    (ire->ire_type == IRE_BROADCAST) &&
21298 	    ((connp->conn_nofailover_ill != NULL) ||
21299 	    (connp->conn_outgoing_ill != NULL))) {
21300 		/*
21301 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21302 		 * option. So, see if this endpoint is bound to a
21303 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21304 		 * that if the interface is failed, we will still send
21305 		 * the packet on the same ill which is what we want.
21306 		 */
21307 		conn_outgoing_ill = conn_get_held_ill(connp,
21308 		    &connp->conn_nofailover_ill, &err);
21309 		if (err == ILL_LOOKUP_FAILED) {
21310 			ire_refrele(ire);
21311 			freemsg(mp);
21312 			return;
21313 		}
21314 		if (conn_outgoing_ill == NULL) {
21315 			/*
21316 			 * Choose a good ill in the group to send the
21317 			 * packets on.
21318 			 */
21319 			ire = conn_set_outgoing_ill(connp, ire,
21320 			    &conn_outgoing_ill);
21321 			if (ire == NULL) {
21322 				freemsg(mp);
21323 				return;
21324 			}
21325 		}
21326 	}
21327 
21328 	if (mp->b_datap->db_type != M_CTL) {
21329 		ipha = (ipha_t *)mp->b_rptr;
21330 	} else {
21331 		io = (ipsec_out_t *)mp->b_rptr;
21332 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21333 		ASSERT(zoneid == io->ipsec_out_zoneid);
21334 		ASSERT(zoneid != ALL_ZONES);
21335 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21336 		dst = ipha->ipha_dst;
21337 		/*
21338 		 * For the multicast case, ipsec_out carries conn_dontroute and
21339 		 * conn_multicast_loop as conn may not be available here. We
21340 		 * need this for multicast loopback and forwarding which is done
21341 		 * later in the code.
21342 		 */
21343 		if (CLASSD(dst)) {
21344 			conn_dontroute = io->ipsec_out_dontroute;
21345 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21346 			/*
21347 			 * If conn_dontroute is not set or conn_multicast_loop
21348 			 * is set, we need to do forwarding/loopback. For
21349 			 * datagrams from ip_wput_multicast, conn_dontroute is
21350 			 * set to B_TRUE and conn_multicast_loop is set to
21351 			 * B_FALSE so that we neither do forwarding nor
21352 			 * loopback.
21353 			 */
21354 			if (!conn_dontroute || conn_multicast_loop)
21355 				multicast_forward = B_TRUE;
21356 		}
21357 	}
21358 
21359 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21360 	    ire->ire_zoneid != ALL_ZONES) {
21361 		/*
21362 		 * When a zone sends a packet to another zone, we try to deliver
21363 		 * the packet under the same conditions as if the destination
21364 		 * was a real node on the network. To do so, we look for a
21365 		 * matching route in the forwarding table.
21366 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21367 		 * ip_newroute() does.
21368 		 * Note that IRE_LOCAL are special, since they are used
21369 		 * when the zoneid doesn't match in some cases. This means that
21370 		 * we need to handle ipha_src differently since ire_src_addr
21371 		 * belongs to the receiving zone instead of the sending zone.
21372 		 * When ip_restrict_interzone_loopback is set, then
21373 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
21374 		 * for loopback between zones when the logical "Ethernet" would
21375 		 * have looped them back.
21376 		 */
21377 		ire_t *src_ire;
21378 
21379 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21380 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21381 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
21382 		if (src_ire != NULL &&
21383 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
21384 		    (!ip_restrict_interzone_loopback ||
21385 		    ire_local_same_ill_group(ire, src_ire))) {
21386 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21387 				ipha->ipha_src = src_ire->ire_src_addr;
21388 			ire_refrele(src_ire);
21389 		} else {
21390 			ire_refrele(ire);
21391 			if (conn_outgoing_ill != NULL)
21392 				ill_refrele(conn_outgoing_ill);
21393 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
21394 			if (src_ire != NULL) {
21395 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21396 					ire_refrele(src_ire);
21397 					freemsg(mp);
21398 					return;
21399 				}
21400 				ire_refrele(src_ire);
21401 			}
21402 			if (ip_hdr_complete(ipha, zoneid)) {
21403 				/* Failed */
21404 				freemsg(mp);
21405 				return;
21406 			}
21407 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid);
21408 			return;
21409 		}
21410 	}
21411 
21412 	if (mp->b_datap->db_type == M_CTL ||
21413 	    ipsec_outbound_v4_policy_present) {
21414 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21415 		    unspec_src, zoneid);
21416 		if (mp == NULL) {
21417 			ire_refrele(ire);
21418 			if (conn_outgoing_ill != NULL)
21419 				ill_refrele(conn_outgoing_ill);
21420 			return;
21421 		}
21422 	}
21423 
21424 	first_mp = mp;
21425 	ipsec_len = 0;
21426 
21427 	if (first_mp->b_datap->db_type == M_CTL) {
21428 		io = (ipsec_out_t *)first_mp->b_rptr;
21429 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21430 		mp = first_mp->b_cont;
21431 		ipsec_len = ipsec_out_extra_length(first_mp);
21432 		ASSERT(ipsec_len >= 0);
21433 		/* We already picked up the zoneid from the M_CTL above */
21434 		ASSERT(zoneid == io->ipsec_out_zoneid);
21435 		ASSERT(zoneid != ALL_ZONES);
21436 
21437 		/*
21438 		 * Drop M_CTL here if IPsec processing is not needed.
21439 		 * (Non-IPsec use of M_CTL extracted any information it
21440 		 * needed above).
21441 		 */
21442 		if (ipsec_len == 0) {
21443 			freeb(first_mp);
21444 			first_mp = mp;
21445 		}
21446 	}
21447 
21448 	/*
21449 	 * Fast path for ip_wput_ire
21450 	 */
21451 
21452 	ipha = (ipha_t *)mp->b_rptr;
21453 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21454 	dst = ipha->ipha_dst;
21455 
21456 	/*
21457 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21458 	 * if the socket is a SOCK_RAW type. The transport checksum should
21459 	 * be provided in the pre-built packet, so we don't need to compute it.
21460 	 * Also, other application set flags, like DF, should not be altered.
21461 	 * Other transport MUST pass down zero.
21462 	 */
21463 	ip_hdr_included = ipha->ipha_ident;
21464 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21465 
21466 	if (CLASSD(dst)) {
21467 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
21468 		    ntohl(dst),
21469 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
21470 		    ntohl(ire->ire_addr)));
21471 	}
21472 
21473 /* Macros to extract header fields from data already in registers */
21474 #ifdef	_BIG_ENDIAN
21475 #define	V_HLEN	(v_hlen_tos_len >> 24)
21476 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21477 #define	PROTO	(ttl_protocol & 0xFF)
21478 #else
21479 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21480 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21481 #define	PROTO	(ttl_protocol >> 8)
21482 #endif
21483 
21484 
21485 	orig_src = src = ipha->ipha_src;
21486 	/* (The loop back to "another" is explained down below.) */
21487 another:;
21488 	/*
21489 	 * Assign an ident value for this packet.  We assign idents on
21490 	 * a per destination basis out of the IRE.  There could be
21491 	 * other threads targeting the same destination, so we have to
21492 	 * arrange for a atomic increment.  Note that we use a 32-bit
21493 	 * atomic add because it has better performance than its
21494 	 * 16-bit sibling.
21495 	 *
21496 	 * If running in cluster mode and if the source address
21497 	 * belongs to a replicated service then vector through
21498 	 * cl_inet_ipident vector to allocate ip identifier
21499 	 * NOTE: This is a contract private interface with the
21500 	 * clustering group.
21501 	 */
21502 	clusterwide = 0;
21503 	if (cl_inet_ipident) {
21504 		ASSERT(cl_inet_isclusterwide);
21505 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21506 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
21507 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
21508 			    AF_INET, (uint8_t *)(uintptr_t)src,
21509 			    (uint8_t *)(uintptr_t)dst);
21510 			clusterwide = 1;
21511 		}
21512 	}
21513 	if (!clusterwide) {
21514 		ipha->ipha_ident =
21515 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
21516 	}
21517 
21518 #ifndef _BIG_ENDIAN
21519 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21520 #endif
21521 
21522 	/*
21523 	 * Set source address unless sent on an ill or conn_unspec_src is set.
21524 	 * This is needed to obey conn_unspec_src when packets go through
21525 	 * ip_newroute + arp.
21526 	 * Assumes ip_newroute{,_multi} sets the source address as well.
21527 	 */
21528 	if (src == INADDR_ANY && !unspec_src) {
21529 		/*
21530 		 * Assign the appropriate source address from the IRE if none
21531 		 * was specified.
21532 		 */
21533 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
21534 
21535 		/*
21536 		 * With IP multipathing, broadcast packets are sent on the ire
21537 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
21538 		 * the group. However, this ire might not be in the same zone so
21539 		 * we can't always use its source address. We look for a
21540 		 * broadcast ire in the same group and in the right zone.
21541 		 */
21542 		if (ire->ire_type == IRE_BROADCAST &&
21543 		    ire->ire_zoneid != zoneid) {
21544 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
21545 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
21546 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
21547 			if (src_ire != NULL) {
21548 				src = src_ire->ire_src_addr;
21549 				ire_refrele(src_ire);
21550 			} else {
21551 				ire_refrele(ire);
21552 				if (conn_outgoing_ill != NULL)
21553 					ill_refrele(conn_outgoing_ill);
21554 				freemsg(first_mp);
21555 				BUMP_MIB(&ip_mib, ipOutDiscards);
21556 				return;
21557 			}
21558 		} else {
21559 			src = ire->ire_src_addr;
21560 		}
21561 
21562 		if (connp == NULL) {
21563 			ip1dbg(("ip_wput_ire: no connp and no src "
21564 			    "address for dst 0x%x, using src 0x%x\n",
21565 			    ntohl(dst),
21566 			    ntohl(src)));
21567 		}
21568 		ipha->ipha_src = src;
21569 	}
21570 	stq = ire->ire_stq;
21571 
21572 	/*
21573 	 * We only allow ire chains for broadcasts since there will
21574 	 * be multiple IRE_CACHE entries for the same multicast
21575 	 * address (one per ipif).
21576 	 */
21577 	next_mp = NULL;
21578 
21579 	/* broadcast packet */
21580 	if (ire->ire_type == IRE_BROADCAST)
21581 		goto broadcast;
21582 
21583 	/* loopback ? */
21584 	if (stq == NULL)
21585 		goto nullstq;
21586 
21587 	/* The ill_index for outbound ILL */
21588 	ill_index = Q_TO_INDEX(stq);
21589 
21590 	BUMP_MIB(&ip_mib, ipOutRequests);
21591 	ttl_protocol = ((uint16_t *)ipha)[4];
21592 
21593 	/* pseudo checksum (do it in parts for IP header checksum) */
21594 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21595 
21596 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
21597 		queue_t *dev_q = stq->q_next;
21598 
21599 		/* flow controlled */
21600 		if ((dev_q->q_next || dev_q->q_first) &&
21601 		    !canput(dev_q))
21602 			goto blocked;
21603 		if ((PROTO == IPPROTO_UDP) &&
21604 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21605 			hlen = (V_HLEN & 0xF) << 2;
21606 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21607 			if (*up != 0) {
21608 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
21609 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
21610 				/* Software checksum? */
21611 				if (DB_CKSUMFLAGS(mp) == 0) {
21612 					IP_STAT(ip_out_sw_cksum);
21613 					IP_STAT_UPDATE(
21614 					    ip_udp_out_sw_cksum_bytes,
21615 					    LENGTH - hlen);
21616 				}
21617 			}
21618 		}
21619 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
21620 		hlen = (V_HLEN & 0xF) << 2;
21621 		if (PROTO == IPPROTO_TCP) {
21622 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21623 			/*
21624 			 * The packet header is processed once and for all, even
21625 			 * in the multirouting case. We disable hardware
21626 			 * checksum if the packet is multirouted, as it will be
21627 			 * replicated via several interfaces, and not all of
21628 			 * them may have this capability.
21629 			 */
21630 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
21631 			    LENGTH, max_frag, ipsec_len, cksum);
21632 			/* Software checksum? */
21633 			if (DB_CKSUMFLAGS(mp) == 0) {
21634 				IP_STAT(ip_out_sw_cksum);
21635 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21636 				    LENGTH - hlen);
21637 			}
21638 		} else {
21639 			sctp_hdr_t	*sctph;
21640 
21641 			ASSERT(PROTO == IPPROTO_SCTP);
21642 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21643 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21644 			/*
21645 			 * Zero out the checksum field to ensure proper
21646 			 * checksum calculation.
21647 			 */
21648 			sctph->sh_chksum = 0;
21649 #ifdef	DEBUG
21650 			if (!skip_sctp_cksum)
21651 #endif
21652 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21653 		}
21654 	}
21655 
21656 	/*
21657 	 * If this is a multicast packet and originated from ip_wput
21658 	 * we need to do loopback and forwarding checks. If it comes
21659 	 * from ip_wput_multicast, we SHOULD not do this.
21660 	 */
21661 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
21662 
21663 	/* checksum */
21664 	cksum += ttl_protocol;
21665 
21666 	/* fragment the packet */
21667 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
21668 		goto fragmentit;
21669 	/*
21670 	 * Don't use frag_flag if packet is pre-built or source
21671 	 * routed or if multicast (since multicast packets do
21672 	 * not solicit ICMP "packet too big" messages).
21673 	 */
21674 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21675 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21676 	    !ip_source_route_included(ipha)) &&
21677 	    !CLASSD(ipha->ipha_dst))
21678 		ipha->ipha_fragment_offset_and_flags |=
21679 		    htons(ire->ire_frag_flag);
21680 
21681 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21682 		/* calculate IP header checksum */
21683 		cksum += ipha->ipha_ident;
21684 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
21685 		cksum += ipha->ipha_fragment_offset_and_flags;
21686 
21687 		/* IP options present */
21688 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21689 		if (hlen)
21690 			goto checksumoptions;
21691 
21692 		/* calculate hdr checksum */
21693 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21694 		cksum = ~(cksum + (cksum >> 16));
21695 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
21696 	}
21697 	if (ipsec_len != 0) {
21698 		/*
21699 		 * We will do the rest of the processing after
21700 		 * we come back from IPSEC in ip_wput_ipsec_out().
21701 		 */
21702 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
21703 
21704 		io = (ipsec_out_t *)first_mp->b_rptr;
21705 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
21706 				ill_phyint->phyint_ifindex;
21707 
21708 		ipsec_out_process(q, first_mp, ire, ill_index);
21709 		ire_refrele(ire);
21710 		if (conn_outgoing_ill != NULL)
21711 			ill_refrele(conn_outgoing_ill);
21712 		return;
21713 	}
21714 
21715 	/*
21716 	 * In most cases, the emission loop below is entered only
21717 	 * once. Only in the case where the ire holds the
21718 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
21719 	 * flagged ires in the bucket, and send the packet
21720 	 * through all crossed RTF_MULTIRT routes.
21721 	 */
21722 	if (ire->ire_flags & RTF_MULTIRT) {
21723 		multirt_send = B_TRUE;
21724 	}
21725 	do {
21726 		if (multirt_send) {
21727 			irb_t *irb;
21728 			/*
21729 			 * We are in a multiple send case, need to get
21730 			 * the next ire and make a duplicate of the packet.
21731 			 * ire1 holds here the next ire to process in the
21732 			 * bucket. If multirouting is expected,
21733 			 * any non-RTF_MULTIRT ire that has the
21734 			 * right destination address is ignored.
21735 			 */
21736 			irb = ire->ire_bucket;
21737 			ASSERT(irb != NULL);
21738 
21739 			IRB_REFHOLD(irb);
21740 			for (ire1 = ire->ire_next;
21741 			    ire1 != NULL;
21742 			    ire1 = ire1->ire_next) {
21743 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21744 					continue;
21745 				if (ire1->ire_addr != ire->ire_addr)
21746 					continue;
21747 				if (ire1->ire_marks &
21748 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21749 					continue;
21750 
21751 				/* Got one */
21752 				IRE_REFHOLD(ire1);
21753 				break;
21754 			}
21755 			IRB_REFRELE(irb);
21756 
21757 			if (ire1 != NULL) {
21758 				next_mp = copyb(mp);
21759 				if ((next_mp == NULL) ||
21760 				    ((mp->b_cont != NULL) &&
21761 				    ((next_mp->b_cont =
21762 				    dupmsg(mp->b_cont)) == NULL))) {
21763 					freemsg(next_mp);
21764 					next_mp = NULL;
21765 					ire_refrele(ire1);
21766 					ire1 = NULL;
21767 				}
21768 			}
21769 
21770 			/* Last multiroute ire; don't loop anymore. */
21771 			if (ire1 == NULL) {
21772 				multirt_send = B_FALSE;
21773 			}
21774 		}
21775 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
21776 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
21777 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
21778 		if ((pktxmit_state == SEND_FAILED) ||
21779 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
21780 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
21781 			    "- packet dropped\n"));
21782 			ire_refrele(ire);
21783 			if (next_mp != NULL) {
21784 				freemsg(next_mp);
21785 				ire_refrele(ire1);
21786 			}
21787 			if (conn_outgoing_ill != NULL)
21788 				ill_refrele(conn_outgoing_ill);
21789 			return;
21790 		}
21791 
21792 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21793 		    "ip_wput_ire_end: q %p (%S)",
21794 		    q, "last copy out");
21795 		IRE_REFRELE(ire);
21796 
21797 		if (multirt_send) {
21798 			ASSERT(ire1);
21799 			/*
21800 			 * Proceed with the next RTF_MULTIRT ire,
21801 			 * Also set up the send-to queue accordingly.
21802 			 */
21803 			ire = ire1;
21804 			ire1 = NULL;
21805 			stq = ire->ire_stq;
21806 			mp = next_mp;
21807 			next_mp = NULL;
21808 			ipha = (ipha_t *)mp->b_rptr;
21809 			ill_index = Q_TO_INDEX(stq);
21810 		}
21811 	} while (multirt_send);
21812 	if (conn_outgoing_ill != NULL)
21813 		ill_refrele(conn_outgoing_ill);
21814 	return;
21815 
21816 	/*
21817 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
21818 	 */
21819 broadcast:
21820 	{
21821 		/*
21822 		 * Avoid broadcast storms by setting the ttl to 1
21823 		 * for broadcasts. This parameter can be set
21824 		 * via ndd, so make sure that for the SO_DONTROUTE
21825 		 * case that ipha_ttl is always set to 1.
21826 		 * In the event that we are replying to incoming
21827 		 * ICMP packets, conn could be NULL.
21828 		 */
21829 		if ((connp != NULL) && connp->conn_dontroute)
21830 			ipha->ipha_ttl = 1;
21831 		else
21832 			ipha->ipha_ttl = ip_broadcast_ttl;
21833 
21834 		/*
21835 		 * Note that we are not doing a IRB_REFHOLD here.
21836 		 * Actually we don't care if the list changes i.e
21837 		 * if somebody deletes an IRE from the list while
21838 		 * we drop the lock, the next time we come around
21839 		 * ire_next will be NULL and hence we won't send
21840 		 * out multiple copies which is fine.
21841 		 */
21842 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
21843 		ire1 = ire->ire_next;
21844 		if (conn_outgoing_ill != NULL) {
21845 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
21846 				ASSERT(ire1 == ire->ire_next);
21847 				if (ire1 != NULL && ire1->ire_addr == dst) {
21848 					ire_refrele(ire);
21849 					ire = ire1;
21850 					IRE_REFHOLD(ire);
21851 					ire1 = ire->ire_next;
21852 					continue;
21853 				}
21854 				rw_exit(&ire->ire_bucket->irb_lock);
21855 				/* Did not find a matching ill */
21856 				ip1dbg(("ip_wput_ire: broadcast with no "
21857 				    "matching IP_BOUND_IF ill %s\n",
21858 				    conn_outgoing_ill->ill_name));
21859 				freemsg(first_mp);
21860 				if (ire != NULL)
21861 					ire_refrele(ire);
21862 				ill_refrele(conn_outgoing_ill);
21863 				return;
21864 			}
21865 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
21866 			/*
21867 			 * If the next IRE has the same address and is not one
21868 			 * of the two copies that we need to send, try to see
21869 			 * whether this copy should be sent at all. This
21870 			 * assumes that we insert loopbacks first and then
21871 			 * non-loopbacks. This is acheived by inserting the
21872 			 * loopback always before non-loopback.
21873 			 * This is used to send a single copy of a broadcast
21874 			 * packet out all physical interfaces that have an
21875 			 * matching IRE_BROADCAST while also looping
21876 			 * back one copy (to ip_wput_local) for each
21877 			 * matching physical interface. However, we avoid
21878 			 * sending packets out different logical that match by
21879 			 * having ipif_up/ipif_down supress duplicate
21880 			 * IRE_BROADCASTS.
21881 			 *
21882 			 * This feature is currently used to get broadcasts
21883 			 * sent to multiple interfaces, when the broadcast
21884 			 * address being used applies to multiple interfaces.
21885 			 * For example, a whole net broadcast will be
21886 			 * replicated on every connected subnet of
21887 			 * the target net.
21888 			 *
21889 			 * Each zone has its own set of IRE_BROADCASTs, so that
21890 			 * we're able to distribute inbound packets to multiple
21891 			 * zones who share a broadcast address. We avoid looping
21892 			 * back outbound packets in different zones but on the
21893 			 * same ill, as the application would see duplicates.
21894 			 *
21895 			 * If the interfaces are part of the same group,
21896 			 * we would want to send only one copy out for
21897 			 * whole group.
21898 			 *
21899 			 * This logic assumes that ire_add_v4() groups the
21900 			 * IRE_BROADCAST entries so that those with the same
21901 			 * ire_addr and ill_group are kept together.
21902 			 */
21903 			ire_ill = ire->ire_ipif->ipif_ill;
21904 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
21905 				if (ire_ill->ill_group != NULL &&
21906 				    (ire->ire_marks & IRE_MARK_NORECV)) {
21907 					/*
21908 					 * If the current zone only has an ire
21909 					 * broadcast for this address marked
21910 					 * NORECV, the ire we want is ahead in
21911 					 * the bucket, so we look it up
21912 					 * deliberately ignoring the zoneid.
21913 					 */
21914 					for (ire1 = ire->ire_bucket->irb_ire;
21915 					    ire1 != NULL;
21916 					    ire1 = ire1->ire_next) {
21917 						ire1_ill =
21918 						    ire1->ire_ipif->ipif_ill;
21919 						if (ire1->ire_addr != dst)
21920 							continue;
21921 						/* skip over the current ire */
21922 						if (ire1 == ire)
21923 							continue;
21924 						/* skip over deleted ires */
21925 						if (ire1->ire_marks &
21926 						    IRE_MARK_CONDEMNED)
21927 							continue;
21928 						/*
21929 						 * non-loopback ire in our
21930 						 * group: use it for the next
21931 						 * pass in the loop
21932 						 */
21933 						if (ire1->ire_stq != NULL &&
21934 						    ire1_ill->ill_group ==
21935 						    ire_ill->ill_group)
21936 							break;
21937 					}
21938 				}
21939 			} else {
21940 				while (ire1 != NULL && ire1->ire_addr == dst) {
21941 					ire1_ill = ire1->ire_ipif->ipif_ill;
21942 					/*
21943 					 * We can have two broadcast ires on the
21944 					 * same ill in different zones; here
21945 					 * we'll send a copy of the packet on
21946 					 * each ill and the fanout code will
21947 					 * call conn_wantpacket() to check that
21948 					 * the zone has the broadcast address
21949 					 * configured on the ill. If the two
21950 					 * ires are in the same group we only
21951 					 * send one copy up.
21952 					 */
21953 					if (ire1_ill != ire_ill &&
21954 					    (ire1_ill->ill_group == NULL ||
21955 					    ire_ill->ill_group == NULL ||
21956 					    ire1_ill->ill_group !=
21957 					    ire_ill->ill_group)) {
21958 						break;
21959 					}
21960 					ire1 = ire1->ire_next;
21961 				}
21962 			}
21963 		}
21964 		ASSERT(multirt_send == B_FALSE);
21965 		if (ire1 != NULL && ire1->ire_addr == dst) {
21966 			if ((ire->ire_flags & RTF_MULTIRT) &&
21967 			    (ire1->ire_flags & RTF_MULTIRT)) {
21968 				/*
21969 				 * We are in the multirouting case.
21970 				 * The message must be sent at least
21971 				 * on both ires. These ires have been
21972 				 * inserted AFTER the standard ones
21973 				 * in ip_rt_add(). There are thus no
21974 				 * other ire entries for the destination
21975 				 * address in the rest of the bucket
21976 				 * that do not have the RTF_MULTIRT
21977 				 * flag. We don't process a copy
21978 				 * of the message here. This will be
21979 				 * done in the final sending loop.
21980 				 */
21981 				multirt_send = B_TRUE;
21982 			} else {
21983 				next_mp = ip_copymsg(first_mp);
21984 				if (next_mp != NULL)
21985 					IRE_REFHOLD(ire1);
21986 			}
21987 		}
21988 		rw_exit(&ire->ire_bucket->irb_lock);
21989 	}
21990 
21991 	if (stq) {
21992 		/*
21993 		 * A non-NULL send-to queue means this packet is going
21994 		 * out of this machine.
21995 		 */
21996 
21997 		BUMP_MIB(&ip_mib, ipOutRequests);
21998 		ttl_protocol = ((uint16_t *)ipha)[4];
21999 		/*
22000 		 * We accumulate the pseudo header checksum in cksum.
22001 		 * This is pretty hairy code, so watch close.  One
22002 		 * thing to keep in mind is that UDP and TCP have
22003 		 * stored their respective datagram lengths in their
22004 		 * checksum fields.  This lines things up real nice.
22005 		 */
22006 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22007 		    (src >> 16) + (src & 0xFFFF);
22008 		/*
22009 		 * We assume the udp checksum field contains the
22010 		 * length, so to compute the pseudo header checksum,
22011 		 * all we need is the protocol number and src/dst.
22012 		 */
22013 		/* Provide the checksums for UDP and TCP. */
22014 		if ((PROTO == IPPROTO_TCP) &&
22015 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22016 			/* hlen gets the number of uchar_ts in the IP header */
22017 			hlen = (V_HLEN & 0xF) << 2;
22018 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22019 			IP_STAT(ip_out_sw_cksum);
22020 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22021 			    LENGTH - hlen);
22022 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22023 			if (*up == 0)
22024 				*up = 0xFFFF;
22025 		} else if (PROTO == IPPROTO_SCTP &&
22026 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22027 			sctp_hdr_t	*sctph;
22028 
22029 			hlen = (V_HLEN & 0xF) << 2;
22030 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22031 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22032 			sctph->sh_chksum = 0;
22033 #ifdef	DEBUG
22034 			if (!skip_sctp_cksum)
22035 #endif
22036 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22037 		} else {
22038 			queue_t *dev_q = stq->q_next;
22039 
22040 			if ((dev_q->q_next || dev_q->q_first) &&
22041 			    !canput(dev_q)) {
22042 			    blocked:
22043 				ipha->ipha_ident = ip_hdr_included;
22044 				/*
22045 				 * If we don't have a conn to apply
22046 				 * backpressure, free the message.
22047 				 * In the ire_send path, we don't know
22048 				 * the position to requeue the packet. Rather
22049 				 * than reorder packets, we just drop this
22050 				 * packet.
22051 				 */
22052 				if (ip_output_queue && connp != NULL &&
22053 				    caller != IRE_SEND) {
22054 					if (caller == IP_WSRV) {
22055 						connp->conn_did_putbq = 1;
22056 						(void) putbq(connp->conn_wq,
22057 						    first_mp);
22058 						conn_drain_insert(connp);
22059 						/*
22060 						 * This is the service thread,
22061 						 * and the queue is already
22062 						 * noenabled. The check for
22063 						 * canput and the putbq is not
22064 						 * atomic. So we need to check
22065 						 * again.
22066 						 */
22067 						if (canput(stq->q_next))
22068 							connp->conn_did_putbq
22069 							    = 0;
22070 						IP_STAT(ip_conn_flputbq);
22071 					} else {
22072 						/*
22073 						 * We are not the service proc.
22074 						 * ip_wsrv will be scheduled or
22075 						 * is already running.
22076 						 */
22077 						(void) putq(connp->conn_wq,
22078 						    first_mp);
22079 					}
22080 				} else {
22081 					BUMP_MIB(&ip_mib, ipOutDiscards);
22082 					freemsg(first_mp);
22083 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22084 					    "ip_wput_ire_end: q %p (%S)",
22085 					    q, "discard");
22086 				}
22087 				ire_refrele(ire);
22088 				if (next_mp) {
22089 					ire_refrele(ire1);
22090 					freemsg(next_mp);
22091 				}
22092 				if (conn_outgoing_ill != NULL)
22093 					ill_refrele(conn_outgoing_ill);
22094 				return;
22095 			}
22096 			if ((PROTO == IPPROTO_UDP) &&
22097 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22098 				/*
22099 				 * hlen gets the number of uchar_ts in the
22100 				 * IP header
22101 				 */
22102 				hlen = (V_HLEN & 0xF) << 2;
22103 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22104 				max_frag = ire->ire_max_frag;
22105 				if (*up != 0) {
22106 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22107 					    up, PROTO, hlen, LENGTH, max_frag,
22108 					    ipsec_len, cksum);
22109 					/* Software checksum? */
22110 					if (DB_CKSUMFLAGS(mp) == 0) {
22111 						IP_STAT(ip_out_sw_cksum);
22112 						IP_STAT_UPDATE(
22113 						    ip_udp_out_sw_cksum_bytes,
22114 						    LENGTH - hlen);
22115 					}
22116 				}
22117 			}
22118 		}
22119 		/*
22120 		 * Need to do this even when fragmenting. The local
22121 		 * loopback can be done without computing checksums
22122 		 * but forwarding out other interface must be done
22123 		 * after the IP checksum (and ULP checksums) have been
22124 		 * computed.
22125 		 *
22126 		 * NOTE : multicast_forward is set only if this packet
22127 		 * originated from ip_wput. For packets originating from
22128 		 * ip_wput_multicast, it is not set.
22129 		 */
22130 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22131 		    multi_loopback:
22132 			ip2dbg(("ip_wput: multicast, loop %d\n",
22133 			    conn_multicast_loop));
22134 
22135 			/*  Forget header checksum offload */
22136 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22137 
22138 			/*
22139 			 * Local loopback of multicasts?  Check the
22140 			 * ill.
22141 			 *
22142 			 * Note that the loopback function will not come
22143 			 * in through ip_rput - it will only do the
22144 			 * client fanout thus we need to do an mforward
22145 			 * as well.  The is different from the BSD
22146 			 * logic.
22147 			 */
22148 			if (ill != NULL) {
22149 				ilm_t	*ilm;
22150 
22151 				ILM_WALKER_HOLD(ill);
22152 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22153 				    ALL_ZONES);
22154 				ILM_WALKER_RELE(ill);
22155 				if (ilm != NULL) {
22156 					/*
22157 					 * Pass along the virtual output q.
22158 					 * ip_wput_local() will distribute the
22159 					 * packet to all the matching zones,
22160 					 * except the sending zone when
22161 					 * IP_MULTICAST_LOOP is false.
22162 					 */
22163 					ip_multicast_loopback(q, ill, first_mp,
22164 					    conn_multicast_loop ? 0 :
22165 					    IP_FF_NO_MCAST_LOOP, zoneid);
22166 				}
22167 			}
22168 			if (ipha->ipha_ttl == 0) {
22169 				/*
22170 				 * 0 => only to this host i.e. we are
22171 				 * done. We are also done if this was the
22172 				 * loopback interface since it is sufficient
22173 				 * to loopback one copy of a multicast packet.
22174 				 */
22175 				freemsg(first_mp);
22176 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22177 				    "ip_wput_ire_end: q %p (%S)",
22178 				    q, "loopback");
22179 				ire_refrele(ire);
22180 				if (conn_outgoing_ill != NULL)
22181 					ill_refrele(conn_outgoing_ill);
22182 				return;
22183 			}
22184 			/*
22185 			 * ILLF_MULTICAST is checked in ip_newroute
22186 			 * i.e. we don't need to check it here since
22187 			 * all IRE_CACHEs come from ip_newroute.
22188 			 * For multicast traffic, SO_DONTROUTE is interpreted
22189 			 * to mean only send the packet out the interface
22190 			 * (optionally specified with IP_MULTICAST_IF)
22191 			 * and do not forward it out additional interfaces.
22192 			 * RSVP and the rsvp daemon is an example of a
22193 			 * protocol and user level process that
22194 			 * handles it's own routing. Hence, it uses the
22195 			 * SO_DONTROUTE option to accomplish this.
22196 			 */
22197 
22198 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22199 				/* Unconditionally redo the checksum */
22200 				ipha->ipha_hdr_checksum = 0;
22201 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22202 
22203 				/*
22204 				 * If this needs to go out secure, we need
22205 				 * to wait till we finish the IPSEC
22206 				 * processing.
22207 				 */
22208 				if (ipsec_len == 0 &&
22209 				    ip_mforward(ill, ipha, mp)) {
22210 					freemsg(first_mp);
22211 					ip1dbg(("ip_wput: mforward failed\n"));
22212 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22213 					    "ip_wput_ire_end: q %p (%S)",
22214 					    q, "mforward failed");
22215 					ire_refrele(ire);
22216 					if (conn_outgoing_ill != NULL)
22217 						ill_refrele(conn_outgoing_ill);
22218 					return;
22219 				}
22220 			}
22221 		}
22222 		max_frag = ire->ire_max_frag;
22223 		cksum += ttl_protocol;
22224 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22225 			/* No fragmentation required for this one. */
22226 			/*
22227 			 * Don't use frag_flag if packet is pre-built or source
22228 			 * routed or if multicast (since multicast packets do
22229 			 * not solicit ICMP "packet too big" messages).
22230 			 */
22231 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22232 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22233 			    !ip_source_route_included(ipha)) &&
22234 			    !CLASSD(ipha->ipha_dst))
22235 				ipha->ipha_fragment_offset_and_flags |=
22236 				    htons(ire->ire_frag_flag);
22237 
22238 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22239 				/* Complete the IP header checksum. */
22240 				cksum += ipha->ipha_ident;
22241 				cksum += (v_hlen_tos_len >> 16)+
22242 				    (v_hlen_tos_len & 0xFFFF);
22243 				cksum += ipha->ipha_fragment_offset_and_flags;
22244 				hlen = (V_HLEN & 0xF) -
22245 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22246 				if (hlen) {
22247 				    checksumoptions:
22248 					/*
22249 					 * Account for the IP Options in the IP
22250 					 * header checksum.
22251 					 */
22252 					up = (uint16_t *)(rptr+
22253 					    IP_SIMPLE_HDR_LENGTH);
22254 					do {
22255 						cksum += up[0];
22256 						cksum += up[1];
22257 						up += 2;
22258 					} while (--hlen);
22259 				}
22260 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22261 				cksum = ~(cksum + (cksum >> 16));
22262 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22263 			}
22264 			if (ipsec_len != 0) {
22265 				ipsec_out_process(q, first_mp, ire, ill_index);
22266 				if (!next_mp) {
22267 					ire_refrele(ire);
22268 					if (conn_outgoing_ill != NULL)
22269 						ill_refrele(conn_outgoing_ill);
22270 					return;
22271 				}
22272 				goto next;
22273 			}
22274 
22275 			/*
22276 			 * multirt_send has already been handled
22277 			 * for broadcast, but not yet for multicast
22278 			 * or IP options.
22279 			 */
22280 			if (next_mp == NULL) {
22281 				if (ire->ire_flags & RTF_MULTIRT) {
22282 					multirt_send = B_TRUE;
22283 				}
22284 			}
22285 
22286 			/*
22287 			 * In most cases, the emission loop below is
22288 			 * entered only once. Only in the case where
22289 			 * the ire holds the RTF_MULTIRT flag, do we loop
22290 			 * to process all RTF_MULTIRT ires in the bucket,
22291 			 * and send the packet through all crossed
22292 			 * RTF_MULTIRT routes.
22293 			 */
22294 			do {
22295 				if (multirt_send) {
22296 					irb_t *irb;
22297 
22298 					irb = ire->ire_bucket;
22299 					ASSERT(irb != NULL);
22300 					/*
22301 					 * We are in a multiple send case,
22302 					 * need to get the next IRE and make
22303 					 * a duplicate of the packet.
22304 					 */
22305 					IRB_REFHOLD(irb);
22306 					for (ire1 = ire->ire_next;
22307 					    ire1 != NULL;
22308 					    ire1 = ire1->ire_next) {
22309 						if (!(ire1->ire_flags &
22310 						    RTF_MULTIRT))
22311 							continue;
22312 						if (ire1->ire_addr !=
22313 						    ire->ire_addr)
22314 							continue;
22315 						if (ire1->ire_marks &
22316 						    (IRE_MARK_CONDEMNED|
22317 							IRE_MARK_HIDDEN))
22318 							continue;
22319 
22320 						/* Got one */
22321 						IRE_REFHOLD(ire1);
22322 						break;
22323 					}
22324 					IRB_REFRELE(irb);
22325 
22326 					if (ire1 != NULL) {
22327 						next_mp = copyb(mp);
22328 						if ((next_mp == NULL) ||
22329 						    ((mp->b_cont != NULL) &&
22330 						    ((next_mp->b_cont =
22331 						    dupmsg(mp->b_cont))
22332 						    == NULL))) {
22333 							freemsg(next_mp);
22334 							next_mp = NULL;
22335 							ire_refrele(ire1);
22336 							ire1 = NULL;
22337 						}
22338 					}
22339 
22340 					/*
22341 					 * Last multiroute ire; don't loop
22342 					 * anymore. The emission is over
22343 					 * and next_mp is NULL.
22344 					 */
22345 					if (ire1 == NULL) {
22346 						multirt_send = B_FALSE;
22347 					}
22348 				}
22349 
22350 				ASSERT(ipsec_len == 0);
22351 				mp->b_prev =
22352 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22353 				DTRACE_PROBE2(ip__xmit__2,
22354 				    mblk_t *, mp, ire_t *, ire);
22355 				pktxmit_state = ip_xmit_v4(mp, ire,
22356 				    NULL, B_TRUE);
22357 				if ((pktxmit_state == SEND_FAILED) ||
22358 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22359 					if (next_mp) {
22360 						freemsg(next_mp);
22361 						ire_refrele(ire1);
22362 					}
22363 					ire_refrele(ire);
22364 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22365 					    "ip_wput_ire_end: q %p (%S)",
22366 					    q, "discard MDATA");
22367 					if (conn_outgoing_ill != NULL)
22368 						ill_refrele(conn_outgoing_ill);
22369 					return;
22370 				}
22371 
22372 				if (multirt_send) {
22373 					/*
22374 					 * We are in a multiple send case,
22375 					 * need to re-enter the sending loop
22376 					 * using the next ire.
22377 					 */
22378 					ire_refrele(ire);
22379 					ire = ire1;
22380 					stq = ire->ire_stq;
22381 					mp = next_mp;
22382 					next_mp = NULL;
22383 					ipha = (ipha_t *)mp->b_rptr;
22384 					ill_index = Q_TO_INDEX(stq);
22385 				}
22386 			} while (multirt_send);
22387 
22388 			if (!next_mp) {
22389 				/*
22390 				 * Last copy going out (the ultra-common
22391 				 * case).  Note that we intentionally replicate
22392 				 * the putnext rather than calling it before
22393 				 * the next_mp check in hopes of a little
22394 				 * tail-call action out of the compiler.
22395 				 */
22396 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22397 				    "ip_wput_ire_end: q %p (%S)",
22398 				    q, "last copy out(1)");
22399 				ire_refrele(ire);
22400 				if (conn_outgoing_ill != NULL)
22401 					ill_refrele(conn_outgoing_ill);
22402 				return;
22403 			}
22404 			/* More copies going out below. */
22405 		} else {
22406 			int offset;
22407 		    fragmentit:
22408 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22409 			/*
22410 			 * If this would generate a icmp_frag_needed message,
22411 			 * we need to handle it before we do the IPSEC
22412 			 * processing. Otherwise, we need to strip the IPSEC
22413 			 * headers before we send up the message to the ULPs
22414 			 * which becomes messy and difficult.
22415 			 */
22416 			if (ipsec_len != 0) {
22417 				if ((max_frag < (unsigned int)(LENGTH +
22418 				    ipsec_len)) && (offset & IPH_DF)) {
22419 
22420 					BUMP_MIB(&ip_mib, ipFragFails);
22421 					ipha->ipha_hdr_checksum = 0;
22422 					ipha->ipha_hdr_checksum =
22423 					    (uint16_t)ip_csum_hdr(ipha);
22424 					icmp_frag_needed(ire->ire_stq, first_mp,
22425 					    max_frag, zoneid);
22426 					if (!next_mp) {
22427 						ire_refrele(ire);
22428 						if (conn_outgoing_ill != NULL) {
22429 							ill_refrele(
22430 							    conn_outgoing_ill);
22431 						}
22432 						return;
22433 					}
22434 				} else {
22435 					/*
22436 					 * This won't cause a icmp_frag_needed
22437 					 * message. to be gnerated. Send it on
22438 					 * the wire. Note that this could still
22439 					 * cause fragmentation and all we
22440 					 * do is the generation of the message
22441 					 * to the ULP if needed before IPSEC.
22442 					 */
22443 					if (!next_mp) {
22444 						ipsec_out_process(q, first_mp,
22445 						    ire, ill_index);
22446 						TRACE_2(TR_FAC_IP,
22447 						    TR_IP_WPUT_IRE_END,
22448 						    "ip_wput_ire_end: q %p "
22449 						    "(%S)", q,
22450 						    "last ipsec_out_process");
22451 						ire_refrele(ire);
22452 						if (conn_outgoing_ill != NULL) {
22453 							ill_refrele(
22454 							    conn_outgoing_ill);
22455 						}
22456 						return;
22457 					}
22458 					ipsec_out_process(q, first_mp,
22459 					    ire, ill_index);
22460 				}
22461 			} else {
22462 				/*
22463 				 * Initiate IPPF processing. For
22464 				 * fragmentable packets we finish
22465 				 * all QOS packet processing before
22466 				 * calling:
22467 				 * ip_wput_ire_fragmentit->ip_wput_frag
22468 				 */
22469 
22470 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22471 					ip_process(IPP_LOCAL_OUT, &mp,
22472 					    ill_index);
22473 					if (mp == NULL) {
22474 						BUMP_MIB(&ip_mib,
22475 						    ipOutDiscards);
22476 						if (next_mp != NULL) {
22477 							freemsg(next_mp);
22478 							ire_refrele(ire1);
22479 						}
22480 						ire_refrele(ire);
22481 						TRACE_2(TR_FAC_IP,
22482 						    TR_IP_WPUT_IRE_END,
22483 						    "ip_wput_ire: q %p (%S)",
22484 						    q, "discard MDATA");
22485 						if (conn_outgoing_ill != NULL) {
22486 							ill_refrele(
22487 							    conn_outgoing_ill);
22488 						}
22489 						return;
22490 					}
22491 				}
22492 				if (!next_mp) {
22493 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22494 					    "ip_wput_ire_end: q %p (%S)",
22495 					    q, "last fragmentation");
22496 					ip_wput_ire_fragmentit(mp, ire,
22497 					    zoneid);
22498 					ire_refrele(ire);
22499 					if (conn_outgoing_ill != NULL)
22500 						ill_refrele(conn_outgoing_ill);
22501 					return;
22502 				}
22503 				ip_wput_ire_fragmentit(mp, ire, zoneid);
22504 			}
22505 		}
22506 	} else {
22507 	    nullstq:
22508 		/* A NULL stq means the destination address is local. */
22509 		UPDATE_OB_PKT_COUNT(ire);
22510 		ire->ire_last_used_time = lbolt;
22511 		ASSERT(ire->ire_ipif != NULL);
22512 		if (!next_mp) {
22513 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22514 			    "ip_wput_ire_end: q %p (%S)",
22515 			    q, "local address");
22516 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
22517 			    first_mp, ire, 0, ire->ire_zoneid);
22518 			ire_refrele(ire);
22519 			if (conn_outgoing_ill != NULL)
22520 				ill_refrele(conn_outgoing_ill);
22521 			return;
22522 		}
22523 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
22524 		    ire, 0, ire->ire_zoneid);
22525 	}
22526 next:
22527 	/*
22528 	 * More copies going out to additional interfaces.
22529 	 * ire1 has already been held. We don't need the
22530 	 * "ire" anymore.
22531 	 */
22532 	ire_refrele(ire);
22533 	ire = ire1;
22534 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
22535 	mp = next_mp;
22536 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
22537 	ill = ire_to_ill(ire);
22538 	first_mp = mp;
22539 	if (ipsec_len != 0) {
22540 		ASSERT(first_mp->b_datap->db_type == M_CTL);
22541 		mp = mp->b_cont;
22542 	}
22543 	dst = ire->ire_addr;
22544 	ipha = (ipha_t *)mp->b_rptr;
22545 	/*
22546 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
22547 	 * Restore ipha_ident "no checksum" flag.
22548 	 */
22549 	src = orig_src;
22550 	ipha->ipha_ident = ip_hdr_included;
22551 	goto another;
22552 
22553 #undef	rptr
22554 #undef	Q_TO_INDEX
22555 }
22556 
22557 /*
22558  * Routine to allocate a message that is used to notify the ULP about MDT.
22559  * The caller may provide a pointer to the link-layer MDT capabilities,
22560  * or NULL if MDT is to be disabled on the stream.
22561  */
22562 mblk_t *
22563 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
22564 {
22565 	mblk_t *mp;
22566 	ip_mdt_info_t *mdti;
22567 	ill_mdt_capab_t *idst;
22568 
22569 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
22570 		DB_TYPE(mp) = M_CTL;
22571 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
22572 		mdti = (ip_mdt_info_t *)mp->b_rptr;
22573 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
22574 		idst = &(mdti->mdt_capab);
22575 
22576 		/*
22577 		 * If the caller provides us with the capability, copy
22578 		 * it over into our notification message; otherwise
22579 		 * we zero out the capability portion.
22580 		 */
22581 		if (isrc != NULL)
22582 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22583 		else
22584 			bzero((caddr_t)idst, sizeof (*idst));
22585 	}
22586 	return (mp);
22587 }
22588 
22589 /*
22590  * Routine which determines whether MDT can be enabled on the destination
22591  * IRE and IPC combination, and if so, allocates and returns the MDT
22592  * notification mblk that may be used by ULP.  We also check if we need to
22593  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
22594  * MDT usage in the past have been lifted.  This gets called during IP
22595  * and ULP binding.
22596  */
22597 mblk_t *
22598 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22599     ill_mdt_capab_t *mdt_cap)
22600 {
22601 	mblk_t *mp;
22602 	boolean_t rc = B_FALSE;
22603 
22604 	ASSERT(dst_ire != NULL);
22605 	ASSERT(connp != NULL);
22606 	ASSERT(mdt_cap != NULL);
22607 
22608 	/*
22609 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
22610 	 * Multidata, which is handled in tcp_multisend().  This
22611 	 * is the reason why we do all these checks here, to ensure
22612 	 * that we don't enable Multidata for the cases which we
22613 	 * can't handle at the moment.
22614 	 */
22615 	do {
22616 		/* Only do TCP at the moment */
22617 		if (connp->conn_ulp != IPPROTO_TCP)
22618 			break;
22619 
22620 		/*
22621 		 * IPSEC outbound policy present?  Note that we get here
22622 		 * after calling ipsec_conn_cache_policy() where the global
22623 		 * policy checking is performed.  conn_latch will be
22624 		 * non-NULL as long as there's a policy defined,
22625 		 * i.e. conn_out_enforce_policy may be NULL in such case
22626 		 * when the connection is non-secure, and hence we check
22627 		 * further if the latch refers to an outbound policy.
22628 		 */
22629 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
22630 			break;
22631 
22632 		/* CGTP (multiroute) is enabled? */
22633 		if (dst_ire->ire_flags & RTF_MULTIRT)
22634 			break;
22635 
22636 		/* Outbound IPQoS enabled? */
22637 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22638 			/*
22639 			 * In this case, we disable MDT for this and all
22640 			 * future connections going over the interface.
22641 			 */
22642 			mdt_cap->ill_mdt_on = 0;
22643 			break;
22644 		}
22645 
22646 		/* socket option(s) present? */
22647 		if (!CONN_IS_MD_FASTPATH(connp))
22648 			break;
22649 
22650 		rc = B_TRUE;
22651 	/* CONSTCOND */
22652 	} while (0);
22653 
22654 	/* Remember the result */
22655 	connp->conn_mdt_ok = rc;
22656 
22657 	if (!rc)
22658 		return (NULL);
22659 	else if (!mdt_cap->ill_mdt_on) {
22660 		/*
22661 		 * If MDT has been previously turned off in the past, and we
22662 		 * currently can do MDT (due to IPQoS policy removal, etc.)
22663 		 * then enable it for this interface.
22664 		 */
22665 		mdt_cap->ill_mdt_on = 1;
22666 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
22667 		    "interface %s\n", ill_name));
22668 	}
22669 
22670 	/* Allocate the MDT info mblk */
22671 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
22672 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
22673 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
22674 		return (NULL);
22675 	}
22676 	return (mp);
22677 }
22678 
22679 /*
22680  * Create destination address attribute, and fill it with the physical
22681  * destination address and SAP taken from the template DL_UNITDATA_REQ
22682  * message block.
22683  */
22684 boolean_t
22685 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
22686 {
22687 	dl_unitdata_req_t *dlurp;
22688 	pattr_t *pa;
22689 	pattrinfo_t pa_info;
22690 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
22691 	uint_t das_len, das_off;
22692 
22693 	ASSERT(dlmp != NULL);
22694 
22695 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
22696 	das_len = dlurp->dl_dest_addr_length;
22697 	das_off = dlurp->dl_dest_addr_offset;
22698 
22699 	pa_info.type = PATTR_DSTADDRSAP;
22700 	pa_info.len = sizeof (**das) + das_len - 1;
22701 
22702 	/* create and associate the attribute */
22703 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22704 	if (pa != NULL) {
22705 		ASSERT(*das != NULL);
22706 		(*das)->addr_is_group = 0;
22707 		(*das)->addr_len = (uint8_t)das_len;
22708 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
22709 	}
22710 
22711 	return (pa != NULL);
22712 }
22713 
22714 /*
22715  * Create hardware checksum attribute and fill it with the values passed.
22716  */
22717 boolean_t
22718 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
22719     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
22720 {
22721 	pattr_t *pa;
22722 	pattrinfo_t pa_info;
22723 
22724 	ASSERT(mmd != NULL);
22725 
22726 	pa_info.type = PATTR_HCKSUM;
22727 	pa_info.len = sizeof (pattr_hcksum_t);
22728 
22729 	/* create and associate the attribute */
22730 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22731 	if (pa != NULL) {
22732 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
22733 
22734 		hck->hcksum_start_offset = start_offset;
22735 		hck->hcksum_stuff_offset = stuff_offset;
22736 		hck->hcksum_end_offset = end_offset;
22737 		hck->hcksum_flags = flags;
22738 	}
22739 	return (pa != NULL);
22740 }
22741 
22742 /*
22743  * Create zerocopy attribute and fill it with the specified flags
22744  */
22745 boolean_t
22746 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
22747 {
22748 	pattr_t *pa;
22749 	pattrinfo_t pa_info;
22750 
22751 	ASSERT(mmd != NULL);
22752 	pa_info.type = PATTR_ZCOPY;
22753 	pa_info.len = sizeof (pattr_zcopy_t);
22754 
22755 	/* create and associate the attribute */
22756 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22757 	if (pa != NULL) {
22758 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
22759 
22760 		zcopy->zcopy_flags = flags;
22761 	}
22762 	return (pa != NULL);
22763 }
22764 
22765 /*
22766  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
22767  * block chain. We could rewrite to handle arbitrary message block chains but
22768  * that would make the code complicated and slow. Right now there three
22769  * restrictions:
22770  *
22771  *   1. The first message block must contain the complete IP header and
22772  *	at least 1 byte of payload data.
22773  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
22774  *	so that we can use a single Multidata message.
22775  *   3. No frag must be distributed over two or more message blocks so
22776  *	that we don't need more than two packet descriptors per frag.
22777  *
22778  * The above restrictions allow us to support userland applications (which
22779  * will send down a single message block) and NFS over UDP (which will
22780  * send down a chain of at most three message blocks).
22781  *
22782  * We also don't use MDT for payloads with less than or equal to
22783  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
22784  */
22785 boolean_t
22786 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
22787 {
22788 	int	blocks;
22789 	ssize_t	total, missing, size;
22790 
22791 	ASSERT(mp != NULL);
22792 	ASSERT(hdr_len > 0);
22793 
22794 	size = MBLKL(mp) - hdr_len;
22795 	if (size <= 0)
22796 		return (B_FALSE);
22797 
22798 	/* The first mblk contains the header and some payload. */
22799 	blocks = 1;
22800 	total = size;
22801 	size %= len;
22802 	missing = (size == 0) ? 0 : (len - size);
22803 	mp = mp->b_cont;
22804 
22805 	while (mp != NULL) {
22806 		/*
22807 		 * Give up if we encounter a zero length message block.
22808 		 * In practice, this should rarely happen and therefore
22809 		 * not worth the trouble of freeing and re-linking the
22810 		 * mblk from the chain to handle such case.
22811 		 */
22812 		if ((size = MBLKL(mp)) == 0)
22813 			return (B_FALSE);
22814 
22815 		/* Too many payload buffers for a single Multidata message? */
22816 		if (++blocks > MULTIDATA_MAX_PBUFS)
22817 			return (B_FALSE);
22818 
22819 		total += size;
22820 		/* Is a frag distributed over two or more message blocks? */
22821 		if (missing > size)
22822 			return (B_FALSE);
22823 		size -= missing;
22824 
22825 		size %= len;
22826 		missing = (size == 0) ? 0 : (len - size);
22827 
22828 		mp = mp->b_cont;
22829 	}
22830 
22831 	return (total > ip_wput_frag_mdt_min);
22832 }
22833 
22834 /*
22835  * Outbound IPv4 fragmentation routine using MDT.
22836  */
22837 static void
22838 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
22839     uint32_t frag_flag, int offset)
22840 {
22841 	ipha_t		*ipha_orig;
22842 	int		i1, ip_data_end;
22843 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
22844 	mblk_t		*hdr_mp, *md_mp = NULL;
22845 	unsigned char	*hdr_ptr, *pld_ptr;
22846 	multidata_t	*mmd;
22847 	ip_pdescinfo_t	pdi;
22848 
22849 	ASSERT(DB_TYPE(mp) == M_DATA);
22850 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
22851 
22852 	ipha_orig = (ipha_t *)mp->b_rptr;
22853 	mp->b_rptr += sizeof (ipha_t);
22854 
22855 	/* Calculate how many packets we will send out */
22856 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
22857 	pkts = (i1 + len - 1) / len;
22858 	ASSERT(pkts > 1);
22859 
22860 	/* Allocate a message block which will hold all the IP Headers. */
22861 	wroff = ip_wroff_extra;
22862 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
22863 
22864 	i1 = pkts * hdr_chunk_len;
22865 	/*
22866 	 * Create the header buffer, Multidata and destination address
22867 	 * and SAP attribute that should be associated with it.
22868 	 */
22869 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
22870 	    ((hdr_mp->b_wptr += i1),
22871 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
22872 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
22873 		freemsg(mp);
22874 		if (md_mp == NULL) {
22875 			freemsg(hdr_mp);
22876 		} else {
22877 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
22878 			freemsg(md_mp);
22879 		}
22880 		IP_STAT(ip_frag_mdt_allocfail);
22881 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
22882 		return;
22883 	}
22884 	IP_STAT(ip_frag_mdt_allocd);
22885 
22886 	/*
22887 	 * Add a payload buffer to the Multidata; this operation must not
22888 	 * fail, or otherwise our logic in this routine is broken.  There
22889 	 * is no memory allocation done by the routine, so any returned
22890 	 * failure simply tells us that we've done something wrong.
22891 	 *
22892 	 * A failure tells us that either we're adding the same payload
22893 	 * buffer more than once, or we're trying to add more buffers than
22894 	 * allowed.  None of the above cases should happen, and we panic
22895 	 * because either there's horrible heap corruption, and/or
22896 	 * programming mistake.
22897 	 */
22898 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22899 		goto pbuf_panic;
22900 
22901 	hdr_ptr = hdr_mp->b_rptr;
22902 	pld_ptr = mp->b_rptr;
22903 
22904 	/* Establish the ending byte offset, based on the starting offset. */
22905 	offset <<= 3;
22906 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
22907 	    IP_SIMPLE_HDR_LENGTH;
22908 
22909 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
22910 
22911 	while (pld_ptr < mp->b_wptr) {
22912 		ipha_t		*ipha;
22913 		uint16_t	offset_and_flags;
22914 		uint16_t	ip_len;
22915 		int		error;
22916 
22917 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
22918 		ipha = (ipha_t *)(hdr_ptr + wroff);
22919 		ASSERT(OK_32PTR(ipha));
22920 		*ipha = *ipha_orig;
22921 
22922 		if (ip_data_end - offset > len) {
22923 			offset_and_flags = IPH_MF;
22924 		} else {
22925 			/*
22926 			 * Last frag. Set len to the length of this last piece.
22927 			 */
22928 			len = ip_data_end - offset;
22929 			/* A frag of a frag might have IPH_MF non-zero */
22930 			offset_and_flags =
22931 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22932 			    IPH_MF;
22933 		}
22934 		offset_and_flags |= (uint16_t)(offset >> 3);
22935 		offset_and_flags |= (uint16_t)frag_flag;
22936 		/* Store the offset and flags in the IP header. */
22937 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22938 
22939 		/* Store the length in the IP header. */
22940 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
22941 		ipha->ipha_length = htons(ip_len);
22942 
22943 		/*
22944 		 * Set the IP header checksum.  Note that mp is just
22945 		 * the header, so this is easy to pass to ip_csum.
22946 		 */
22947 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22948 
22949 		/*
22950 		 * Record offset and size of header and data of the next packet
22951 		 * in the multidata message.
22952 		 */
22953 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
22954 		PDESC_PLD_INIT(&pdi);
22955 		i1 = MIN(mp->b_wptr - pld_ptr, len);
22956 		ASSERT(i1 > 0);
22957 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
22958 		if (i1 == len) {
22959 			pld_ptr += len;
22960 		} else {
22961 			i1 = len - i1;
22962 			mp = mp->b_cont;
22963 			ASSERT(mp != NULL);
22964 			ASSERT(MBLKL(mp) >= i1);
22965 			/*
22966 			 * Attach the next payload message block to the
22967 			 * multidata message.
22968 			 */
22969 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22970 				goto pbuf_panic;
22971 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
22972 			pld_ptr = mp->b_rptr + i1;
22973 		}
22974 
22975 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
22976 		    KM_NOSLEEP)) == NULL) {
22977 			/*
22978 			 * Any failure other than ENOMEM indicates that we
22979 			 * have passed in invalid pdesc info or parameters
22980 			 * to mmd_addpdesc, which must not happen.
22981 			 *
22982 			 * EINVAL is a result of failure on boundary checks
22983 			 * against the pdesc info contents.  It should not
22984 			 * happen, and we panic because either there's
22985 			 * horrible heap corruption, and/or programming
22986 			 * mistake.
22987 			 */
22988 			if (error != ENOMEM) {
22989 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
22990 				    "pdesc logic error detected for "
22991 				    "mmd %p pinfo %p (%d)\n",
22992 				    (void *)mmd, (void *)&pdi, error);
22993 				/* NOTREACHED */
22994 			}
22995 			IP_STAT(ip_frag_mdt_addpdescfail);
22996 			/* Free unattached payload message blocks as well */
22997 			md_mp->b_cont = mp->b_cont;
22998 			goto free_mmd;
22999 		}
23000 
23001 		/* Advance fragment offset. */
23002 		offset += len;
23003 
23004 		/* Advance to location for next header in the buffer. */
23005 		hdr_ptr += hdr_chunk_len;
23006 
23007 		/* Did we reach the next payload message block? */
23008 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23009 			mp = mp->b_cont;
23010 			/*
23011 			 * Attach the next message block with payload
23012 			 * data to the multidata message.
23013 			 */
23014 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23015 				goto pbuf_panic;
23016 			pld_ptr = mp->b_rptr;
23017 		}
23018 	}
23019 
23020 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23021 	ASSERT(mp->b_wptr == pld_ptr);
23022 
23023 	/* Update IP statistics */
23024 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
23025 	BUMP_MIB(&ip_mib, ipFragOKs);
23026 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
23027 
23028 	if (pkt_type == OB_PKT) {
23029 		ire->ire_ob_pkt_count += pkts;
23030 		if (ire->ire_ipif != NULL)
23031 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23032 	} else {
23033 		/*
23034 		 * The type is IB_PKT in the forwarding path and in
23035 		 * the mobile IP case when the packet is being reverse-
23036 		 * tunneled to the home agent.
23037 		 */
23038 		ire->ire_ib_pkt_count += pkts;
23039 		ASSERT(!IRE_IS_LOCAL(ire));
23040 		if (ire->ire_type & IRE_BROADCAST)
23041 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23042 		else
23043 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23044 	}
23045 	ire->ire_last_used_time = lbolt;
23046 	/* Send it down */
23047 	putnext(ire->ire_stq, md_mp);
23048 	return;
23049 
23050 pbuf_panic:
23051 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23052 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23053 	    pbuf_idx);
23054 	/* NOTREACHED */
23055 }
23056 
23057 /*
23058  * Outbound IP fragmentation routine.
23059  *
23060  * NOTE : This routine does not ire_refrele the ire that is passed in
23061  * as the argument.
23062  */
23063 static void
23064 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23065     uint32_t frag_flag, zoneid_t zoneid)
23066 {
23067 	int		i1;
23068 	mblk_t		*ll_hdr_mp;
23069 	int 		ll_hdr_len;
23070 	int		hdr_len;
23071 	mblk_t		*hdr_mp;
23072 	ipha_t		*ipha;
23073 	int		ip_data_end;
23074 	int		len;
23075 	mblk_t		*mp = mp_orig;
23076 	int		offset;
23077 	queue_t		*q;
23078 	uint32_t	v_hlen_tos_len;
23079 	mblk_t		*first_mp;
23080 	boolean_t	mctl_present;
23081 	ill_t		*ill;
23082 	mblk_t		*xmit_mp;
23083 	mblk_t		*carve_mp;
23084 	ire_t		*ire1 = NULL;
23085 	ire_t		*save_ire = NULL;
23086 	mblk_t  	*next_mp = NULL;
23087 	boolean_t	last_frag = B_FALSE;
23088 	boolean_t	multirt_send = B_FALSE;
23089 	ire_t		*first_ire = NULL;
23090 	irb_t		*irb = NULL;
23091 
23092 	/*
23093 	 * IPSEC does not allow hw accelerated packets to be fragmented
23094 	 * This check is made in ip_wput_ipsec_out prior to coming here
23095 	 * via ip_wput_ire_fragmentit.
23096 	 *
23097 	 * If at this point we have an ire whose ARP request has not
23098 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23099 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23100 	 * This packet and all fragmentable packets for this ire will
23101 	 * continue to get dropped while ire_nce->nce_state remains in
23102 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23103 	 * ND_REACHABLE, all subsquent large packets for this ire will
23104 	 * get fragemented and sent out by this function.
23105 	 */
23106 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23107 		/* If nce_state is ND_INITIAL, trigger ARP query */
23108 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23109 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23110 		    " -  dropping packet\n"));
23111 		BUMP_MIB(&ip_mib, ipFragFails);
23112 		freemsg(mp);
23113 		return;
23114 	}
23115 
23116 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23117 	    "ip_wput_frag_start:");
23118 
23119 	if (mp->b_datap->db_type == M_CTL) {
23120 		first_mp = mp;
23121 		mp_orig = mp = mp->b_cont;
23122 		mctl_present = B_TRUE;
23123 	} else {
23124 		first_mp = mp;
23125 		mctl_present = B_FALSE;
23126 	}
23127 
23128 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23129 	ipha = (ipha_t *)mp->b_rptr;
23130 
23131 	/*
23132 	 * If the Don't Fragment flag is on, generate an ICMP destination
23133 	 * unreachable, fragmentation needed.
23134 	 */
23135 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23136 	if (offset & IPH_DF) {
23137 		BUMP_MIB(&ip_mib, ipFragFails);
23138 		/*
23139 		 * Need to compute hdr checksum if called from ip_wput_ire.
23140 		 * Note that ip_rput_forward verifies the checksum before
23141 		 * calling this routine so in that case this is a noop.
23142 		 */
23143 		ipha->ipha_hdr_checksum = 0;
23144 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23145 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid);
23146 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23147 		    "ip_wput_frag_end:(%S)",
23148 		    "don't fragment");
23149 		return;
23150 	}
23151 	if (mctl_present)
23152 		freeb(first_mp);
23153 	/*
23154 	 * Establish the starting offset.  May not be zero if we are fragging
23155 	 * a fragment that is being forwarded.
23156 	 */
23157 	offset = offset & IPH_OFFSET;
23158 
23159 	/* TODO why is this test needed? */
23160 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23161 	if (((max_frag - LENGTH) & ~7) < 8) {
23162 		/* TODO: notify ulp somehow */
23163 		BUMP_MIB(&ip_mib, ipFragFails);
23164 		freemsg(mp);
23165 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23166 		    "ip_wput_frag_end:(%S)",
23167 		    "len < 8");
23168 		return;
23169 	}
23170 
23171 	hdr_len = (V_HLEN & 0xF) << 2;
23172 
23173 	ipha->ipha_hdr_checksum = 0;
23174 
23175 	/*
23176 	 * Establish the number of bytes maximum per frag, after putting
23177 	 * in the header.
23178 	 */
23179 	len = (max_frag - hdr_len) & ~7;
23180 
23181 	/* Check if we can use MDT to send out the frags. */
23182 	ASSERT(!IRE_IS_LOCAL(ire));
23183 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
23184 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
23185 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
23186 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23187 		ASSERT(ill->ill_mdt_capab != NULL);
23188 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23189 			/*
23190 			 * If MDT has been previously turned off in the past,
23191 			 * and we currently can do MDT (due to IPQoS policy
23192 			 * removal, etc.) then enable it for this interface.
23193 			 */
23194 			ill->ill_mdt_capab->ill_mdt_on = 1;
23195 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23196 			    ill->ill_name));
23197 		}
23198 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23199 		    offset);
23200 		return;
23201 	}
23202 
23203 	/* Get a copy of the header for the trailing frags */
23204 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
23205 	if (!hdr_mp) {
23206 		BUMP_MIB(&ip_mib, ipOutDiscards);
23207 		freemsg(mp);
23208 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23209 		    "ip_wput_frag_end:(%S)",
23210 		    "couldn't copy hdr");
23211 		return;
23212 	}
23213 	if (DB_CRED(mp) != NULL)
23214 		mblk_setcred(hdr_mp, DB_CRED(mp));
23215 
23216 	/* Store the starting offset, with the MoreFrags flag. */
23217 	i1 = offset | IPH_MF | frag_flag;
23218 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23219 
23220 	/* Establish the ending byte offset, based on the starting offset. */
23221 	offset <<= 3;
23222 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23223 
23224 	/* Store the length of the first fragment in the IP header. */
23225 	i1 = len + hdr_len;
23226 	ASSERT(i1 <= IP_MAXPACKET);
23227 	ipha->ipha_length = htons((uint16_t)i1);
23228 
23229 	/*
23230 	 * Compute the IP header checksum for the first frag.  We have to
23231 	 * watch out that we stop at the end of the header.
23232 	 */
23233 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23234 
23235 	/*
23236 	 * Now carve off the first frag.  Note that this will include the
23237 	 * original IP header.
23238 	 */
23239 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
23240 		BUMP_MIB(&ip_mib, ipOutDiscards);
23241 		freeb(hdr_mp);
23242 		freemsg(mp_orig);
23243 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23244 		    "ip_wput_frag_end:(%S)",
23245 		    "couldn't carve first");
23246 		return;
23247 	}
23248 
23249 	/*
23250 	 * Multirouting case. Each fragment is replicated
23251 	 * via all non-condemned RTF_MULTIRT routes
23252 	 * currently resolved.
23253 	 * We ensure that first_ire is the first RTF_MULTIRT
23254 	 * ire in the bucket.
23255 	 */
23256 	if (ire->ire_flags & RTF_MULTIRT) {
23257 		irb = ire->ire_bucket;
23258 		ASSERT(irb != NULL);
23259 
23260 		multirt_send = B_TRUE;
23261 
23262 		/* Make sure we do not omit any multiroute ire. */
23263 		IRB_REFHOLD(irb);
23264 		for (first_ire = irb->irb_ire;
23265 		    first_ire != NULL;
23266 		    first_ire = first_ire->ire_next) {
23267 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23268 			    (first_ire->ire_addr == ire->ire_addr) &&
23269 			    !(first_ire->ire_marks &
23270 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23271 				break;
23272 		}
23273 
23274 		if (first_ire != NULL) {
23275 			if (first_ire != ire) {
23276 				IRE_REFHOLD(first_ire);
23277 				/*
23278 				 * Do not release the ire passed in
23279 				 * as the argument.
23280 				 */
23281 				ire = first_ire;
23282 			} else {
23283 				first_ire = NULL;
23284 			}
23285 		}
23286 		IRB_REFRELE(irb);
23287 
23288 		/*
23289 		 * Save the first ire; we will need to restore it
23290 		 * for the trailing frags.
23291 		 * We REFHOLD save_ire, as each iterated ire will be
23292 		 * REFRELEd.
23293 		 */
23294 		save_ire = ire;
23295 		IRE_REFHOLD(save_ire);
23296 	}
23297 
23298 	/*
23299 	 * First fragment emission loop.
23300 	 * In most cases, the emission loop below is entered only
23301 	 * once. Only in the case where the ire holds the RTF_MULTIRT
23302 	 * flag, do we loop to process all RTF_MULTIRT ires in the
23303 	 * bucket, and send the fragment through all crossed
23304 	 * RTF_MULTIRT routes.
23305 	 */
23306 	do {
23307 		if (ire->ire_flags & RTF_MULTIRT) {
23308 			/*
23309 			 * We are in a multiple send case, need to get
23310 			 * the next ire and make a copy of the packet.
23311 			 * ire1 holds here the next ire to process in the
23312 			 * bucket. If multirouting is expected,
23313 			 * any non-RTF_MULTIRT ire that has the
23314 			 * right destination address is ignored.
23315 			 *
23316 			 * We have to take into account the MTU of
23317 			 * each walked ire. max_frag is set by the
23318 			 * the caller and generally refers to
23319 			 * the primary ire entry. Here we ensure that
23320 			 * no route with a lower MTU will be used, as
23321 			 * fragments are carved once for all ires,
23322 			 * then replicated.
23323 			 */
23324 			ASSERT(irb != NULL);
23325 			IRB_REFHOLD(irb);
23326 			for (ire1 = ire->ire_next;
23327 			    ire1 != NULL;
23328 			    ire1 = ire1->ire_next) {
23329 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23330 					continue;
23331 				if (ire1->ire_addr != ire->ire_addr)
23332 					continue;
23333 				if (ire1->ire_marks &
23334 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23335 					continue;
23336 				/*
23337 				 * Ensure we do not exceed the MTU
23338 				 * of the next route.
23339 				 */
23340 				if (ire1->ire_max_frag < max_frag) {
23341 					ip_multirt_bad_mtu(ire1, max_frag);
23342 					continue;
23343 				}
23344 
23345 				/* Got one. */
23346 				IRE_REFHOLD(ire1);
23347 				break;
23348 			}
23349 			IRB_REFRELE(irb);
23350 
23351 			if (ire1 != NULL) {
23352 				next_mp = copyb(mp);
23353 				if ((next_mp == NULL) ||
23354 				    ((mp->b_cont != NULL) &&
23355 				    ((next_mp->b_cont =
23356 				    dupmsg(mp->b_cont)) == NULL))) {
23357 					freemsg(next_mp);
23358 					next_mp = NULL;
23359 					ire_refrele(ire1);
23360 					ire1 = NULL;
23361 				}
23362 			}
23363 
23364 			/* Last multiroute ire; don't loop anymore. */
23365 			if (ire1 == NULL) {
23366 				multirt_send = B_FALSE;
23367 			}
23368 		}
23369 
23370 		ll_hdr_len = 0;
23371 		LOCK_IRE_FP_MP(ire);
23372 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23373 		if (ll_hdr_mp != NULL) {
23374 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23375 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
23376 		} else {
23377 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
23378 		}
23379 
23380 		/* If there is a transmit header, get a copy for this frag. */
23381 		/*
23382 		 * TODO: should check db_ref before calling ip_carve_mp since
23383 		 * it might give us a dup.
23384 		 */
23385 		if (!ll_hdr_mp) {
23386 			/* No xmit header. */
23387 			xmit_mp = mp;
23388 
23389 		/* We have a link-layer header that can fit in our mblk. */
23390 		} else if (mp->b_datap->db_ref == 1 &&
23391 		    ll_hdr_len != 0 &&
23392 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23393 			/* M_DATA fastpath */
23394 			mp->b_rptr -= ll_hdr_len;
23395 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
23396 			xmit_mp = mp;
23397 
23398 		/* Corner case if copyb has failed */
23399 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
23400 			UNLOCK_IRE_FP_MP(ire);
23401 			BUMP_MIB(&ip_mib, ipOutDiscards);
23402 			freeb(hdr_mp);
23403 			freemsg(mp);
23404 			freemsg(mp_orig);
23405 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23406 			    "ip_wput_frag_end:(%S)",
23407 			    "discard");
23408 
23409 			if (multirt_send) {
23410 				ASSERT(ire1);
23411 				ASSERT(next_mp);
23412 
23413 				freemsg(next_mp);
23414 				ire_refrele(ire1);
23415 			}
23416 			if (save_ire != NULL)
23417 				IRE_REFRELE(save_ire);
23418 
23419 			if (first_ire != NULL)
23420 				ire_refrele(first_ire);
23421 			return;
23422 
23423 		/*
23424 		 * Case of res_mp OR the fastpath mp can't fit
23425 		 * in the mblk
23426 		 */
23427 		} else {
23428 			xmit_mp->b_cont = mp;
23429 			if (DB_CRED(mp) != NULL)
23430 				mblk_setcred(xmit_mp, DB_CRED(mp));
23431 			/*
23432 			 * Get priority marking, if any.
23433 			 * We propagate the CoS marking from the
23434 			 * original packet that went to QoS processing
23435 			 * in ip_wput_ire to the newly carved mp.
23436 			 */
23437 			if (DB_TYPE(xmit_mp) == M_DATA)
23438 				xmit_mp->b_band = mp->b_band;
23439 		}
23440 		UNLOCK_IRE_FP_MP(ire);
23441 		q = ire->ire_stq;
23442 		BUMP_MIB(&ip_mib, ipFragCreates);
23443 		putnext(q, xmit_mp);
23444 		if (pkt_type != OB_PKT) {
23445 			/*
23446 			 * Update the packet count of trailing
23447 			 * RTF_MULTIRT ires.
23448 			 */
23449 			UPDATE_OB_PKT_COUNT(ire);
23450 		}
23451 
23452 		if (multirt_send) {
23453 			/*
23454 			 * We are in a multiple send case; look for
23455 			 * the next ire and re-enter the loop.
23456 			 */
23457 			ASSERT(ire1);
23458 			ASSERT(next_mp);
23459 			/* REFRELE the current ire before looping */
23460 			ire_refrele(ire);
23461 			ire = ire1;
23462 			ire1 = NULL;
23463 			mp = next_mp;
23464 			next_mp = NULL;
23465 		}
23466 	} while (multirt_send);
23467 
23468 	ASSERT(ire1 == NULL);
23469 
23470 	/* Restore the original ire; we need it for the trailing frags */
23471 	if (save_ire != NULL) {
23472 		/* REFRELE the last iterated ire */
23473 		ire_refrele(ire);
23474 		/* save_ire has been REFHOLDed */
23475 		ire = save_ire;
23476 		save_ire = NULL;
23477 		q = ire->ire_stq;
23478 	}
23479 
23480 	if (pkt_type == OB_PKT) {
23481 		UPDATE_OB_PKT_COUNT(ire);
23482 	} else {
23483 		UPDATE_IB_PKT_COUNT(ire);
23484 	}
23485 
23486 	/* Advance the offset to the second frag starting point. */
23487 	offset += len;
23488 	/*
23489 	 * Update hdr_len from the copied header - there might be less options
23490 	 * in the later fragments.
23491 	 */
23492 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
23493 	/* Loop until done. */
23494 	for (;;) {
23495 		uint16_t	offset_and_flags;
23496 		uint16_t	ip_len;
23497 
23498 		if (ip_data_end - offset > len) {
23499 			/*
23500 			 * Carve off the appropriate amount from the original
23501 			 * datagram.
23502 			 */
23503 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23504 				mp = NULL;
23505 				break;
23506 			}
23507 			/*
23508 			 * More frags after this one.  Get another copy
23509 			 * of the header.
23510 			 */
23511 			if (carve_mp->b_datap->db_ref == 1 &&
23512 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23513 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23514 				/* Inline IP header */
23515 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23516 				    hdr_mp->b_rptr;
23517 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23518 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23519 				mp = carve_mp;
23520 			} else {
23521 				if (!(mp = copyb(hdr_mp))) {
23522 					freemsg(carve_mp);
23523 					break;
23524 				}
23525 				/* Get priority marking, if any. */
23526 				mp->b_band = carve_mp->b_band;
23527 				mp->b_cont = carve_mp;
23528 			}
23529 			ipha = (ipha_t *)mp->b_rptr;
23530 			offset_and_flags = IPH_MF;
23531 		} else {
23532 			/*
23533 			 * Last frag.  Consume the header. Set len to
23534 			 * the length of this last piece.
23535 			 */
23536 			len = ip_data_end - offset;
23537 
23538 			/*
23539 			 * Carve off the appropriate amount from the original
23540 			 * datagram.
23541 			 */
23542 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23543 				mp = NULL;
23544 				break;
23545 			}
23546 			if (carve_mp->b_datap->db_ref == 1 &&
23547 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23548 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23549 				/* Inline IP header */
23550 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23551 				    hdr_mp->b_rptr;
23552 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23553 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23554 				mp = carve_mp;
23555 				freeb(hdr_mp);
23556 				hdr_mp = mp;
23557 			} else {
23558 				mp = hdr_mp;
23559 				/* Get priority marking, if any. */
23560 				mp->b_band = carve_mp->b_band;
23561 				mp->b_cont = carve_mp;
23562 			}
23563 			ipha = (ipha_t *)mp->b_rptr;
23564 			/* A frag of a frag might have IPH_MF non-zero */
23565 			offset_and_flags =
23566 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23567 			    IPH_MF;
23568 		}
23569 		offset_and_flags |= (uint16_t)(offset >> 3);
23570 		offset_and_flags |= (uint16_t)frag_flag;
23571 		/* Store the offset and flags in the IP header. */
23572 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23573 
23574 		/* Store the length in the IP header. */
23575 		ip_len = (uint16_t)(len + hdr_len);
23576 		ipha->ipha_length = htons(ip_len);
23577 
23578 		/*
23579 		 * Set the IP header checksum.	Note that mp is just
23580 		 * the header, so this is easy to pass to ip_csum.
23581 		 */
23582 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23583 
23584 		/* Attach a transmit header, if any, and ship it. */
23585 		if (pkt_type == OB_PKT) {
23586 			UPDATE_OB_PKT_COUNT(ire);
23587 		} else {
23588 			UPDATE_IB_PKT_COUNT(ire);
23589 		}
23590 
23591 		if (ire->ire_flags & RTF_MULTIRT) {
23592 			irb = ire->ire_bucket;
23593 			ASSERT(irb != NULL);
23594 
23595 			multirt_send = B_TRUE;
23596 
23597 			/*
23598 			 * Save the original ire; we will need to restore it
23599 			 * for the tailing frags.
23600 			 */
23601 			save_ire = ire;
23602 			IRE_REFHOLD(save_ire);
23603 		}
23604 		/*
23605 		 * Emission loop for this fragment, similar
23606 		 * to what is done for the first fragment.
23607 		 */
23608 		do {
23609 			if (multirt_send) {
23610 				/*
23611 				 * We are in a multiple send case, need to get
23612 				 * the next ire and make a copy of the packet.
23613 				 */
23614 				ASSERT(irb != NULL);
23615 				IRB_REFHOLD(irb);
23616 				for (ire1 = ire->ire_next;
23617 				    ire1 != NULL;
23618 				    ire1 = ire1->ire_next) {
23619 					if (!(ire1->ire_flags & RTF_MULTIRT))
23620 						continue;
23621 					if (ire1->ire_addr != ire->ire_addr)
23622 						continue;
23623 					if (ire1->ire_marks &
23624 					    (IRE_MARK_CONDEMNED|
23625 						IRE_MARK_HIDDEN))
23626 						continue;
23627 					/*
23628 					 * Ensure we do not exceed the MTU
23629 					 * of the next route.
23630 					 */
23631 					if (ire1->ire_max_frag < max_frag) {
23632 						ip_multirt_bad_mtu(ire1,
23633 						    max_frag);
23634 						continue;
23635 					}
23636 
23637 					/* Got one. */
23638 					IRE_REFHOLD(ire1);
23639 					break;
23640 				}
23641 				IRB_REFRELE(irb);
23642 
23643 				if (ire1 != NULL) {
23644 					next_mp = copyb(mp);
23645 					if ((next_mp == NULL) ||
23646 					    ((mp->b_cont != NULL) &&
23647 					    ((next_mp->b_cont =
23648 					    dupmsg(mp->b_cont)) == NULL))) {
23649 						freemsg(next_mp);
23650 						next_mp = NULL;
23651 						ire_refrele(ire1);
23652 						ire1 = NULL;
23653 					}
23654 				}
23655 
23656 				/* Last multiroute ire; don't loop anymore. */
23657 				if (ire1 == NULL) {
23658 					multirt_send = B_FALSE;
23659 				}
23660 			}
23661 
23662 			/* Update transmit header */
23663 			ll_hdr_len = 0;
23664 			LOCK_IRE_FP_MP(ire);
23665 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23666 			if (ll_hdr_mp != NULL) {
23667 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23668 				ll_hdr_len = MBLKL(ll_hdr_mp);
23669 			} else {
23670 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
23671 			}
23672 
23673 			if (!ll_hdr_mp) {
23674 				xmit_mp = mp;
23675 
23676 			/*
23677 			 * We have link-layer header that can fit in
23678 			 * our mblk.
23679 			 */
23680 			} else if (mp->b_datap->db_ref == 1 &&
23681 			    ll_hdr_len != 0 &&
23682 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23683 				/* M_DATA fastpath */
23684 				mp->b_rptr -= ll_hdr_len;
23685 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
23686 				    ll_hdr_len);
23687 				xmit_mp = mp;
23688 
23689 			/*
23690 			 * Case of res_mp OR the fastpath mp can't fit
23691 			 * in the mblk
23692 			 */
23693 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
23694 				xmit_mp->b_cont = mp;
23695 				if (DB_CRED(mp) != NULL)
23696 					mblk_setcred(xmit_mp, DB_CRED(mp));
23697 				/* Get priority marking, if any. */
23698 				if (DB_TYPE(xmit_mp) == M_DATA)
23699 					xmit_mp->b_band = mp->b_band;
23700 
23701 			/* Corner case if copyb failed */
23702 			} else {
23703 				/*
23704 				 * Exit both the replication and
23705 				 * fragmentation loops.
23706 				 */
23707 				UNLOCK_IRE_FP_MP(ire);
23708 				goto drop_pkt;
23709 			}
23710 			UNLOCK_IRE_FP_MP(ire);
23711 			BUMP_MIB(&ip_mib, ipFragCreates);
23712 			putnext(q, xmit_mp);
23713 
23714 			if (pkt_type != OB_PKT) {
23715 				/*
23716 				 * Update the packet count of trailing
23717 				 * RTF_MULTIRT ires.
23718 				 */
23719 				UPDATE_OB_PKT_COUNT(ire);
23720 			}
23721 
23722 			/* All done if we just consumed the hdr_mp. */
23723 			if (mp == hdr_mp) {
23724 				last_frag = B_TRUE;
23725 			}
23726 
23727 			if (multirt_send) {
23728 				/*
23729 				 * We are in a multiple send case; look for
23730 				 * the next ire and re-enter the loop.
23731 				 */
23732 				ASSERT(ire1);
23733 				ASSERT(next_mp);
23734 				/* REFRELE the current ire before looping */
23735 				ire_refrele(ire);
23736 				ire = ire1;
23737 				ire1 = NULL;
23738 				q = ire->ire_stq;
23739 				mp = next_mp;
23740 				next_mp = NULL;
23741 			}
23742 		} while (multirt_send);
23743 		/*
23744 		 * Restore the original ire; we need it for the
23745 		 * trailing frags
23746 		 */
23747 		if (save_ire != NULL) {
23748 			ASSERT(ire1 == NULL);
23749 			/* REFRELE the last iterated ire */
23750 			ire_refrele(ire);
23751 			/* save_ire has been REFHOLDed */
23752 			ire = save_ire;
23753 			q = ire->ire_stq;
23754 			save_ire = NULL;
23755 		}
23756 
23757 		if (last_frag) {
23758 			BUMP_MIB(&ip_mib, ipFragOKs);
23759 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23760 			    "ip_wput_frag_end:(%S)",
23761 			    "consumed hdr_mp");
23762 
23763 			if (first_ire != NULL)
23764 				ire_refrele(first_ire);
23765 			return;
23766 		}
23767 		/* Otherwise, advance and loop. */
23768 		offset += len;
23769 	}
23770 
23771 drop_pkt:
23772 	/* Clean up following allocation failure. */
23773 	BUMP_MIB(&ip_mib, ipOutDiscards);
23774 	freemsg(mp);
23775 	if (mp != hdr_mp)
23776 		freeb(hdr_mp);
23777 	if (mp != mp_orig)
23778 		freemsg(mp_orig);
23779 
23780 	if (save_ire != NULL)
23781 		IRE_REFRELE(save_ire);
23782 	if (first_ire != NULL)
23783 		ire_refrele(first_ire);
23784 
23785 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23786 	    "ip_wput_frag_end:(%S)",
23787 	    "end--alloc failure");
23788 }
23789 
23790 /*
23791  * Copy the header plus those options which have the copy bit set
23792  */
23793 static mblk_t *
23794 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
23795 {
23796 	mblk_t	*mp;
23797 	uchar_t	*up;
23798 
23799 	/*
23800 	 * Quick check if we need to look for options without the copy bit
23801 	 * set
23802 	 */
23803 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
23804 	if (!mp)
23805 		return (mp);
23806 	mp->b_rptr += ip_wroff_extra;
23807 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
23808 		bcopy(rptr, mp->b_rptr, hdr_len);
23809 		mp->b_wptr += hdr_len + ip_wroff_extra;
23810 		return (mp);
23811 	}
23812 	up  = mp->b_rptr;
23813 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
23814 	up += IP_SIMPLE_HDR_LENGTH;
23815 	rptr += IP_SIMPLE_HDR_LENGTH;
23816 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
23817 	while (hdr_len > 0) {
23818 		uint32_t optval;
23819 		uint32_t optlen;
23820 
23821 		optval = *rptr;
23822 		if (optval == IPOPT_EOL)
23823 			break;
23824 		if (optval == IPOPT_NOP)
23825 			optlen = 1;
23826 		else
23827 			optlen = rptr[1];
23828 		if (optval & IPOPT_COPY) {
23829 			bcopy(rptr, up, optlen);
23830 			up += optlen;
23831 		}
23832 		rptr += optlen;
23833 		hdr_len -= optlen;
23834 	}
23835 	/*
23836 	 * Make sure that we drop an even number of words by filling
23837 	 * with EOL to the next word boundary.
23838 	 */
23839 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
23840 	    hdr_len & 0x3; hdr_len++)
23841 		*up++ = IPOPT_EOL;
23842 	mp->b_wptr = up;
23843 	/* Update header length */
23844 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
23845 	return (mp);
23846 }
23847 
23848 /*
23849  * Delivery to local recipients including fanout to multiple recipients.
23850  * Does not do checksumming of UDP/TCP.
23851  * Note: q should be the read side queue for either the ill or conn.
23852  * Note: rq should be the read side q for the lower (ill) stream.
23853  * We don't send packets to IPPF processing, thus the last argument
23854  * to all the fanout calls are B_FALSE.
23855  */
23856 void
23857 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
23858     int fanout_flags, zoneid_t zoneid)
23859 {
23860 	uint32_t	protocol;
23861 	mblk_t		*first_mp;
23862 	boolean_t	mctl_present;
23863 	int		ire_type;
23864 #define	rptr	((uchar_t *)ipha)
23865 
23866 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
23867 	    "ip_wput_local_start: q %p", q);
23868 
23869 	if (ire != NULL) {
23870 		ire_type = ire->ire_type;
23871 	} else {
23872 		/*
23873 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
23874 		 * packet is not multicast, we can't tell the ire type.
23875 		 */
23876 		ASSERT(CLASSD(ipha->ipha_dst));
23877 		ire_type = IRE_BROADCAST;
23878 	}
23879 
23880 	first_mp = mp;
23881 	if (first_mp->b_datap->db_type == M_CTL) {
23882 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
23883 		if (!io->ipsec_out_secure) {
23884 			/*
23885 			 * This ipsec_out_t was allocated in ip_wput
23886 			 * for multicast packets to store the ill_index.
23887 			 * As this is being delivered locally, we don't
23888 			 * need this anymore.
23889 			 */
23890 			mp = first_mp->b_cont;
23891 			freeb(first_mp);
23892 			first_mp = mp;
23893 			mctl_present = B_FALSE;
23894 		} else {
23895 			mctl_present = B_TRUE;
23896 			mp = first_mp->b_cont;
23897 			ASSERT(mp != NULL);
23898 			ipsec_out_to_in(first_mp);
23899 		}
23900 	} else {
23901 		mctl_present = B_FALSE;
23902 	}
23903 
23904 	loopback_packets++;
23905 
23906 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
23907 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
23908 	if (!IS_SIMPLE_IPH(ipha)) {
23909 		ip_wput_local_options(ipha);
23910 	}
23911 
23912 	protocol = ipha->ipha_protocol;
23913 	switch (protocol) {
23914 	case IPPROTO_ICMP: {
23915 		ire_t		*ire_zone;
23916 		ilm_t		*ilm;
23917 		mblk_t		*mp1;
23918 		zoneid_t	last_zoneid;
23919 
23920 		if (CLASSD(ipha->ipha_dst) &&
23921 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
23922 			ASSERT(ire_type == IRE_BROADCAST);
23923 			/*
23924 			 * In the multicast case, applications may have joined
23925 			 * the group from different zones, so we need to deliver
23926 			 * the packet to each of them. Loop through the
23927 			 * multicast memberships structures (ilm) on the receive
23928 			 * ill and send a copy of the packet up each matching
23929 			 * one. However, we don't do this for multicasts sent on
23930 			 * the loopback interface (PHYI_LOOPBACK flag set) as
23931 			 * they must stay in the sender's zone.
23932 			 *
23933 			 * ilm_add_v6() ensures that ilms in the same zone are
23934 			 * contiguous in the ill_ilm list. We use this property
23935 			 * to avoid sending duplicates needed when two
23936 			 * applications in the same zone join the same group on
23937 			 * different logical interfaces: we ignore the ilm if
23938 			 * it's zoneid is the same as the last matching one.
23939 			 * In addition, the sending of the packet for
23940 			 * ire_zoneid is delayed until all of the other ilms
23941 			 * have been exhausted.
23942 			 */
23943 			last_zoneid = -1;
23944 			ILM_WALKER_HOLD(ill);
23945 			for (ilm = ill->ill_ilm; ilm != NULL;
23946 			    ilm = ilm->ilm_next) {
23947 				if ((ilm->ilm_flags & ILM_DELETED) ||
23948 				    ipha->ipha_dst != ilm->ilm_addr ||
23949 				    ilm->ilm_zoneid == last_zoneid ||
23950 				    ilm->ilm_zoneid == zoneid ||
23951 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
23952 					continue;
23953 				mp1 = ip_copymsg(first_mp);
23954 				if (mp1 == NULL)
23955 					continue;
23956 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23957 				    mctl_present, B_FALSE, ill,
23958 				    ilm->ilm_zoneid);
23959 				last_zoneid = ilm->ilm_zoneid;
23960 			}
23961 			ILM_WALKER_RELE(ill);
23962 			/*
23963 			 * Loopback case: the sending endpoint has
23964 			 * IP_MULTICAST_LOOP disabled, therefore we don't
23965 			 * dispatch the multicast packet to the sending zone.
23966 			 */
23967 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
23968 				freemsg(first_mp);
23969 				return;
23970 			}
23971 		} else if (ire_type == IRE_BROADCAST) {
23972 			/*
23973 			 * In the broadcast case, there may be many zones
23974 			 * which need a copy of the packet delivered to them.
23975 			 * There is one IRE_BROADCAST per broadcast address
23976 			 * and per zone; we walk those using a helper function.
23977 			 * In addition, the sending of the packet for zoneid is
23978 			 * delayed until all of the other ires have been
23979 			 * processed.
23980 			 */
23981 			IRB_REFHOLD(ire->ire_bucket);
23982 			ire_zone = NULL;
23983 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
23984 			    ire)) != NULL) {
23985 				mp1 = ip_copymsg(first_mp);
23986 				if (mp1 == NULL)
23987 					continue;
23988 
23989 				UPDATE_IB_PKT_COUNT(ire_zone);
23990 				ire_zone->ire_last_used_time = lbolt;
23991 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23992 				    mctl_present, B_FALSE, ill,
23993 				    ire_zone->ire_zoneid);
23994 			}
23995 			IRB_REFRELE(ire->ire_bucket);
23996 		}
23997 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
23998 		    0, mctl_present, B_FALSE, ill, zoneid);
23999 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24000 		    "ip_wput_local_end: q %p (%S)",
24001 		    q, "icmp");
24002 		return;
24003 	}
24004 	case IPPROTO_IGMP:
24005 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
24006 			/* Bad packet - discarded by igmp_input */
24007 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24008 			    "ip_wput_local_end: q %p (%S)",
24009 			    q, "igmp_input--bad packet");
24010 			if (mctl_present)
24011 				freeb(first_mp);
24012 			return;
24013 		}
24014 		/*
24015 		 * igmp_input() may have returned the pulled up message.
24016 		 * So first_mp and ipha need to be reinitialized.
24017 		 */
24018 		ipha = (ipha_t *)mp->b_rptr;
24019 		if (mctl_present)
24020 			first_mp->b_cont = mp;
24021 		else
24022 			first_mp = mp;
24023 		/* deliver to local raw users */
24024 		break;
24025 	case IPPROTO_ENCAP:
24026 		/*
24027 		 * This case is covered by either ip_fanout_proto, or by
24028 		 * the above security processing for self-tunneled packets.
24029 		 */
24030 		break;
24031 	case IPPROTO_UDP: {
24032 		uint16_t	*up;
24033 		uint32_t	ports;
24034 
24035 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
24036 		    UDP_PORTS_OFFSET);
24037 		/* Force a 'valid' checksum. */
24038 		up[3] = 0;
24039 
24040 		ports = *(uint32_t *)up;
24041 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24042 		    (ire_type == IRE_BROADCAST),
24043 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24044 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
24045 		    ill, zoneid);
24046 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24047 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24048 		return;
24049 	}
24050 	case IPPROTO_TCP: {
24051 
24052 		/*
24053 		 * For TCP, discard broadcast packets.
24054 		 */
24055 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24056 			freemsg(first_mp);
24057 			BUMP_MIB(&ip_mib, ipInDiscards);
24058 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24059 			return;
24060 		}
24061 
24062 		if (mp->b_datap->db_type == M_DATA) {
24063 			/*
24064 			 * M_DATA mblk, so init mblk (chain) for no struio().
24065 			 */
24066 			mblk_t	*mp1 = mp;
24067 
24068 			do
24069 				mp1->b_datap->db_struioflag = 0;
24070 			while ((mp1 = mp1->b_cont) != NULL);
24071 		}
24072 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24073 		    <= mp->b_wptr);
24074 		ip_fanout_tcp(q, first_mp, ill, ipha,
24075 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24076 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
24077 		    mctl_present, B_FALSE, zoneid);
24078 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24079 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24080 		return;
24081 	}
24082 	case IPPROTO_SCTP:
24083 	{
24084 		uint32_t	ports;
24085 
24086 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24087 		ip_fanout_sctp(first_mp, ill, ipha, ports,
24088 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24089 		    IP_FF_IP6INFO,
24090 		    mctl_present, B_FALSE, 0, zoneid);
24091 		return;
24092 	}
24093 
24094 	default:
24095 		break;
24096 	}
24097 	/*
24098 	 * Find a client for some other protocol.  We give
24099 	 * copies to multiple clients, if more than one is
24100 	 * bound.
24101 	 */
24102 	ip_fanout_proto(q, first_mp, ill, ipha,
24103 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
24104 	    mctl_present, B_FALSE, ill, zoneid);
24105 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24106 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
24107 #undef	rptr
24108 }
24109 
24110 /*
24111  * Update any source route, record route, or timestamp options.
24112  * Check that we are at end of strict source route.
24113  * The options have been sanity checked by ip_wput_options().
24114  */
24115 static void
24116 ip_wput_local_options(ipha_t *ipha)
24117 {
24118 	ipoptp_t	opts;
24119 	uchar_t		*opt;
24120 	uint8_t		optval;
24121 	uint8_t		optlen;
24122 	ipaddr_t	dst;
24123 	uint32_t	ts;
24124 	ire_t		*ire;
24125 	timestruc_t	now;
24126 
24127 	ip2dbg(("ip_wput_local_options\n"));
24128 	for (optval = ipoptp_first(&opts, ipha);
24129 	    optval != IPOPT_EOL;
24130 	    optval = ipoptp_next(&opts)) {
24131 		opt = opts.ipoptp_cur;
24132 		optlen = opts.ipoptp_len;
24133 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
24134 		switch (optval) {
24135 			uint32_t off;
24136 		case IPOPT_SSRR:
24137 		case IPOPT_LSRR:
24138 			off = opt[IPOPT_OFFSET];
24139 			off--;
24140 			if (optlen < IP_ADDR_LEN ||
24141 			    off > optlen - IP_ADDR_LEN) {
24142 				/* End of source route */
24143 				break;
24144 			}
24145 			/*
24146 			 * This will only happen if two consecutive entries
24147 			 * in the source route contains our address or if
24148 			 * it is a packet with a loose source route which
24149 			 * reaches us before consuming the whole source route
24150 			 */
24151 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
24152 			if (optval == IPOPT_SSRR) {
24153 				return;
24154 			}
24155 			/*
24156 			 * Hack: instead of dropping the packet truncate the
24157 			 * source route to what has been used by filling the
24158 			 * rest with IPOPT_NOP.
24159 			 */
24160 			opt[IPOPT_OLEN] = (uint8_t)off;
24161 			while (off < optlen) {
24162 				opt[off++] = IPOPT_NOP;
24163 			}
24164 			break;
24165 		case IPOPT_RR:
24166 			off = opt[IPOPT_OFFSET];
24167 			off--;
24168 			if (optlen < IP_ADDR_LEN ||
24169 			    off > optlen - IP_ADDR_LEN) {
24170 				/* No more room - ignore */
24171 				ip1dbg((
24172 				    "ip_wput_forward_options: end of RR\n"));
24173 				break;
24174 			}
24175 			dst = htonl(INADDR_LOOPBACK);
24176 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24177 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24178 			break;
24179 		case IPOPT_TS:
24180 			/* Insert timestamp if there is romm */
24181 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24182 			case IPOPT_TS_TSONLY:
24183 				off = IPOPT_TS_TIMELEN;
24184 				break;
24185 			case IPOPT_TS_PRESPEC:
24186 			case IPOPT_TS_PRESPEC_RFC791:
24187 				/* Verify that the address matched */
24188 				off = opt[IPOPT_OFFSET] - 1;
24189 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
24190 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
24191 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
24192 				if (ire == NULL) {
24193 					/* Not for us */
24194 					break;
24195 				}
24196 				ire_refrele(ire);
24197 				/* FALLTHRU */
24198 			case IPOPT_TS_TSANDADDR:
24199 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24200 				break;
24201 			default:
24202 				/*
24203 				 * ip_*put_options should have already
24204 				 * dropped this packet.
24205 				 */
24206 				cmn_err(CE_PANIC, "ip_wput_local_options: "
24207 				    "unknown IT - bug in ip_wput_options?\n");
24208 				return;	/* Keep "lint" happy */
24209 			}
24210 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
24211 				/* Increase overflow counter */
24212 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
24213 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
24214 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
24215 				    (off << 4);
24216 				break;
24217 			}
24218 			off = opt[IPOPT_OFFSET] - 1;
24219 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24220 			case IPOPT_TS_PRESPEC:
24221 			case IPOPT_TS_PRESPEC_RFC791:
24222 			case IPOPT_TS_TSANDADDR:
24223 				dst = htonl(INADDR_LOOPBACK);
24224 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24225 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24226 				/* FALLTHRU */
24227 			case IPOPT_TS_TSONLY:
24228 				off = opt[IPOPT_OFFSET] - 1;
24229 				/* Compute # of milliseconds since midnight */
24230 				gethrestime(&now);
24231 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
24232 				    now.tv_nsec / (NANOSEC / MILLISEC);
24233 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
24234 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
24235 				break;
24236 			}
24237 			break;
24238 		}
24239 	}
24240 }
24241 
24242 /*
24243  * Send out a multicast packet on interface ipif.
24244  * The sender does not have an conn.
24245  * Caller verifies that this isn't a PHYI_LOOPBACK.
24246  */
24247 void
24248 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
24249 {
24250 	ipha_t	*ipha;
24251 	ire_t	*ire;
24252 	ipaddr_t	dst;
24253 	mblk_t		*first_mp;
24254 
24255 	/* igmp_sendpkt always allocates a ipsec_out_t */
24256 	ASSERT(mp->b_datap->db_type == M_CTL);
24257 	ASSERT(!ipif->ipif_isv6);
24258 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
24259 
24260 	first_mp = mp;
24261 	mp = first_mp->b_cont;
24262 	ASSERT(mp->b_datap->db_type == M_DATA);
24263 	ipha = (ipha_t *)mp->b_rptr;
24264 
24265 	/*
24266 	 * Find an IRE which matches the destination and the outgoing
24267 	 * queue (i.e. the outgoing interface.)
24268 	 */
24269 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
24270 		dst = ipif->ipif_pp_dst_addr;
24271 	else
24272 		dst = ipha->ipha_dst;
24273 	/*
24274 	 * The source address has already been initialized by the
24275 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
24276 	 * be sufficient rather than MATCH_IRE_IPIF.
24277 	 *
24278 	 * This function is used for sending IGMP packets. We need
24279 	 * to make sure that we send the packet out of the interface
24280 	 * (ipif->ipif_ill) where we joined the group. This is to
24281 	 * prevent from switches doing IGMP snooping to send us multicast
24282 	 * packets for a given group on the interface we have joined.
24283 	 * If we can't find an ire, igmp_sendpkt has already initialized
24284 	 * ipsec_out_attach_if so that this will not be load spread in
24285 	 * ip_newroute_ipif.
24286 	 */
24287 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
24288 	    MATCH_IRE_ILL);
24289 	if (!ire) {
24290 		/*
24291 		 * Mark this packet to make it be delivered to
24292 		 * ip_wput_ire after the new ire has been
24293 		 * created.
24294 		 */
24295 		mp->b_prev = NULL;
24296 		mp->b_next = NULL;
24297 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
24298 		    zoneid);
24299 		return;
24300 	}
24301 
24302 	/*
24303 	 * Honor the RTF_SETSRC flag; this is the only case
24304 	 * where we force this addr whatever the current src addr is,
24305 	 * because this address is set by igmp_sendpkt(), and
24306 	 * cannot be specified by any user.
24307 	 */
24308 	if (ire->ire_flags & RTF_SETSRC) {
24309 		ipha->ipha_src = ire->ire_src_addr;
24310 	}
24311 
24312 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
24313 }
24314 
24315 /*
24316  * NOTE : This function does not ire_refrele the ire argument passed in.
24317  *
24318  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
24319  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
24320  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
24321  * the ire_lock to access the nce_fp_mp in this case.
24322  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
24323  * prepending a fastpath message IPQoS processing must precede it, we also set
24324  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
24325  * (IPQoS might have set the b_band for CoS marking).
24326  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
24327  * must follow it so that IPQoS can mark the dl_priority field for CoS
24328  * marking, if needed.
24329  */
24330 static mblk_t *
24331 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
24332 {
24333 	uint_t	hlen;
24334 	ipha_t *ipha;
24335 	mblk_t *mp1;
24336 	boolean_t qos_done = B_FALSE;
24337 	uchar_t	*ll_hdr;
24338 
24339 #define	rptr	((uchar_t *)ipha)
24340 
24341 	ipha = (ipha_t *)mp->b_rptr;
24342 	hlen = 0;
24343 	LOCK_IRE_FP_MP(ire);
24344 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
24345 		ASSERT(DB_TYPE(mp1) == M_DATA);
24346 		/* Initiate IPPF processing */
24347 		if ((proc != 0) && IPP_ENABLED(proc)) {
24348 			UNLOCK_IRE_FP_MP(ire);
24349 			ip_process(proc, &mp, ill_index);
24350 			if (mp == NULL)
24351 				return (NULL);
24352 
24353 			ipha = (ipha_t *)mp->b_rptr;
24354 			LOCK_IRE_FP_MP(ire);
24355 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
24356 				qos_done = B_TRUE;
24357 				goto no_fp_mp;
24358 			}
24359 			ASSERT(DB_TYPE(mp1) == M_DATA);
24360 		}
24361 		hlen = MBLKL(mp1);
24362 		/*
24363 		 * Check if we have enough room to prepend fastpath
24364 		 * header
24365 		 */
24366 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
24367 			ll_hdr = rptr - hlen;
24368 			bcopy(mp1->b_rptr, ll_hdr, hlen);
24369 			/*
24370 			 * Set the b_rptr to the start of the link layer
24371 			 * header
24372 			 */
24373 			mp->b_rptr = ll_hdr;
24374 			mp1 = mp;
24375 		} else {
24376 			mp1 = copyb(mp1);
24377 			if (mp1 == NULL)
24378 				goto unlock_err;
24379 			mp1->b_band = mp->b_band;
24380 			mp1->b_cont = mp;
24381 			/*
24382 			 * certain system generated traffic may not
24383 			 * have cred/label in ip header block. This
24384 			 * is true even for a labeled system. But for
24385 			 * labeled traffic, inherit the label in the
24386 			 * new header.
24387 			 */
24388 			if (DB_CRED(mp) != NULL)
24389 				mblk_setcred(mp1, DB_CRED(mp));
24390 			/*
24391 			 * XXX disable ICK_VALID and compute checksum
24392 			 * here; can happen if nce_fp_mp changes and
24393 			 * it can't be copied now due to insufficient
24394 			 * space. (unlikely, fp mp can change, but it
24395 			 * does not increase in length)
24396 			 */
24397 		}
24398 		UNLOCK_IRE_FP_MP(ire);
24399 	} else {
24400 no_fp_mp:
24401 		mp1 = copyb(ire->ire_nce->nce_res_mp);
24402 		if (mp1 == NULL) {
24403 unlock_err:
24404 			UNLOCK_IRE_FP_MP(ire);
24405 			freemsg(mp);
24406 			return (NULL);
24407 		}
24408 		UNLOCK_IRE_FP_MP(ire);
24409 		mp1->b_cont = mp;
24410 		/*
24411 		 * certain system generated traffic may not
24412 		 * have cred/label in ip header block. This
24413 		 * is true even for a labeled system. But for
24414 		 * labeled traffic, inherit the label in the
24415 		 * new header.
24416 		 */
24417 		if (DB_CRED(mp) != NULL)
24418 			mblk_setcred(mp1, DB_CRED(mp));
24419 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
24420 			ip_process(proc, &mp1, ill_index);
24421 			if (mp1 == NULL)
24422 				return (NULL);
24423 		}
24424 	}
24425 	return (mp1);
24426 #undef rptr
24427 }
24428 
24429 /*
24430  * Finish the outbound IPsec processing for an IPv6 packet. This function
24431  * is called from ipsec_out_process() if the IPsec packet was processed
24432  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24433  * asynchronously.
24434  */
24435 void
24436 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
24437     ire_t *ire_arg)
24438 {
24439 	in6_addr_t *v6dstp;
24440 	ire_t *ire;
24441 	mblk_t *mp;
24442 	uint_t	ill_index;
24443 	ipsec_out_t *io;
24444 	boolean_t attach_if, hwaccel;
24445 	uint32_t flags = IP6_NO_IPPOLICY;
24446 	int match_flags;
24447 	zoneid_t zoneid;
24448 	boolean_t ill_need_rele = B_FALSE;
24449 	boolean_t ire_need_rele = B_FALSE;
24450 
24451 	mp = ipsec_mp->b_cont;
24452 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24453 	ill_index = io->ipsec_out_ill_index;
24454 	if (io->ipsec_out_reachable) {
24455 		flags |= IPV6_REACHABILITY_CONFIRMATION;
24456 	}
24457 	attach_if = io->ipsec_out_attach_if;
24458 	hwaccel = io->ipsec_out_accelerated;
24459 	zoneid = io->ipsec_out_zoneid;
24460 	ASSERT(zoneid != ALL_ZONES);
24461 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24462 	/* Multicast addresses should have non-zero ill_index. */
24463 	v6dstp = &ip6h->ip6_dst;
24464 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
24465 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
24466 	ASSERT(!attach_if || ill_index != 0);
24467 	if (ill_index != 0) {
24468 		if (ill == NULL) {
24469 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
24470 			    B_TRUE);
24471 
24472 			/* Failure case frees things for us. */
24473 			if (ill == NULL)
24474 				return;
24475 
24476 			ill_need_rele = B_TRUE;
24477 		}
24478 		/*
24479 		 * If this packet needs to go out on a particular interface
24480 		 * honor it.
24481 		 */
24482 		if (attach_if) {
24483 			match_flags = MATCH_IRE_ILL;
24484 
24485 			/*
24486 			 * Check if we need an ire that will not be
24487 			 * looked up by anybody else i.e. HIDDEN.
24488 			 */
24489 			if (ill_is_probeonly(ill)) {
24490 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24491 			}
24492 		}
24493 	}
24494 	ASSERT(mp != NULL);
24495 
24496 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
24497 		boolean_t unspec_src;
24498 		ipif_t	*ipif;
24499 
24500 		/*
24501 		 * Use the ill_index to get the right ill.
24502 		 */
24503 		unspec_src = io->ipsec_out_unspec_src;
24504 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24505 		if (ipif == NULL) {
24506 			if (ill_need_rele)
24507 				ill_refrele(ill);
24508 			freemsg(ipsec_mp);
24509 			return;
24510 		}
24511 
24512 		if (ire_arg != NULL) {
24513 			ire = ire_arg;
24514 		} else {
24515 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24516 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24517 			ire_need_rele = B_TRUE;
24518 		}
24519 		if (ire != NULL) {
24520 			ipif_refrele(ipif);
24521 			/*
24522 			 * XXX Do the multicast forwarding now, as the IPSEC
24523 			 * processing has been done.
24524 			 */
24525 			goto send;
24526 		}
24527 
24528 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
24529 		mp->b_prev = NULL;
24530 		mp->b_next = NULL;
24531 
24532 		/*
24533 		 * If the IPsec packet was processed asynchronously,
24534 		 * drop it now.
24535 		 */
24536 		if (q == NULL) {
24537 			if (ill_need_rele)
24538 				ill_refrele(ill);
24539 			freemsg(ipsec_mp);
24540 			return;
24541 		}
24542 
24543 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
24544 		    unspec_src, zoneid);
24545 		ipif_refrele(ipif);
24546 	} else {
24547 		if (attach_if) {
24548 			ipif_t	*ipif;
24549 
24550 			ipif = ipif_get_next_ipif(NULL, ill);
24551 			if (ipif == NULL) {
24552 				if (ill_need_rele)
24553 					ill_refrele(ill);
24554 				freemsg(ipsec_mp);
24555 				return;
24556 			}
24557 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24558 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24559 			ire_need_rele = B_TRUE;
24560 			ipif_refrele(ipif);
24561 		} else {
24562 			if (ire_arg != NULL) {
24563 				ire = ire_arg;
24564 			} else {
24565 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
24566 				ire_need_rele = B_TRUE;
24567 			}
24568 		}
24569 		if (ire != NULL)
24570 			goto send;
24571 		/*
24572 		 * ire disappeared underneath.
24573 		 *
24574 		 * What we need to do here is the ip_newroute
24575 		 * logic to get the ire without doing the IPSEC
24576 		 * processing. Follow the same old path. But this
24577 		 * time, ip_wput or ire_add_then_send will call us
24578 		 * directly as all the IPSEC operations are done.
24579 		 */
24580 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
24581 		mp->b_prev = NULL;
24582 		mp->b_next = NULL;
24583 
24584 		/*
24585 		 * If the IPsec packet was processed asynchronously,
24586 		 * drop it now.
24587 		 */
24588 		if (q == NULL) {
24589 			if (ill_need_rele)
24590 				ill_refrele(ill);
24591 			freemsg(ipsec_mp);
24592 			return;
24593 		}
24594 
24595 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
24596 		    zoneid);
24597 	}
24598 	if (ill != NULL && ill_need_rele)
24599 		ill_refrele(ill);
24600 	return;
24601 send:
24602 	if (ill != NULL && ill_need_rele)
24603 		ill_refrele(ill);
24604 
24605 	/* Local delivery */
24606 	if (ire->ire_stq == NULL) {
24607 		ASSERT(q != NULL);
24608 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
24609 		    ire, 0);
24610 		if (ire_need_rele)
24611 			ire_refrele(ire);
24612 		return;
24613 	}
24614 	/*
24615 	 * Everything is done. Send it out on the wire.
24616 	 * We force the insertion of a fragment header using the
24617 	 * IPH_FRAG_HDR flag in two cases:
24618 	 * - after reception of an ICMPv6 "packet too big" message
24619 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
24620 	 * - for multirouted IPv6 packets, so that the receiver can
24621 	 *   discard duplicates according to their fragment identifier
24622 	 */
24623 	/* XXX fix flow control problems. */
24624 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
24625 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
24626 		if (hwaccel) {
24627 			/*
24628 			 * hardware acceleration does not handle these
24629 			 * "slow path" cases.
24630 			 */
24631 			/* IPsec KSTATS: should bump bean counter here. */
24632 			if (ire_need_rele)
24633 				ire_refrele(ire);
24634 			freemsg(ipsec_mp);
24635 			return;
24636 		}
24637 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
24638 		    (mp->b_cont ? msgdsize(mp) :
24639 		    mp->b_wptr - (uchar_t *)ip6h)) {
24640 			/* IPsec KSTATS: should bump bean counter here. */
24641 			ip0dbg(("Packet length mismatch: %d, %ld\n",
24642 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
24643 			    msgdsize(mp)));
24644 			if (ire_need_rele)
24645 				ire_refrele(ire);
24646 			freemsg(ipsec_mp);
24647 			return;
24648 		}
24649 		ASSERT(mp->b_prev == NULL);
24650 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
24651 		    ntohs(ip6h->ip6_plen) +
24652 		    IPV6_HDR_LEN, ire->ire_max_frag));
24653 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
24654 		    ire->ire_max_frag);
24655 	} else {
24656 		UPDATE_OB_PKT_COUNT(ire);
24657 		ire->ire_last_used_time = lbolt;
24658 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
24659 	}
24660 	if (ire_need_rele)
24661 		ire_refrele(ire);
24662 	freeb(ipsec_mp);
24663 }
24664 
24665 void
24666 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
24667 {
24668 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
24669 	da_ipsec_t *hada;	/* data attributes */
24670 	ill_t *ill = (ill_t *)q->q_ptr;
24671 
24672 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
24673 
24674 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
24675 		/* IPsec KSTATS: Bump lose counter here! */
24676 		freemsg(mp);
24677 		return;
24678 	}
24679 
24680 	/*
24681 	 * It's an IPsec packet that must be
24682 	 * accelerated by the Provider, and the
24683 	 * outbound ill is IPsec acceleration capable.
24684 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
24685 	 * to the ill.
24686 	 * IPsec KSTATS: should bump packet counter here.
24687 	 */
24688 
24689 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
24690 	if (hada_mp == NULL) {
24691 		/* IPsec KSTATS: should bump packet counter here. */
24692 		freemsg(mp);
24693 		return;
24694 	}
24695 
24696 	hada_mp->b_datap->db_type = M_CTL;
24697 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
24698 	hada_mp->b_cont = mp;
24699 
24700 	hada = (da_ipsec_t *)hada_mp->b_rptr;
24701 	bzero(hada, sizeof (da_ipsec_t));
24702 	hada->da_type = IPHADA_M_CTL;
24703 
24704 	putnext(q, hada_mp);
24705 }
24706 
24707 /*
24708  * Finish the outbound IPsec processing. This function is called from
24709  * ipsec_out_process() if the IPsec packet was processed
24710  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24711  * asynchronously.
24712  */
24713 void
24714 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
24715     ire_t *ire_arg)
24716 {
24717 	uint32_t v_hlen_tos_len;
24718 	ipaddr_t	dst;
24719 	ipif_t	*ipif = NULL;
24720 	ire_t *ire;
24721 	ire_t *ire1 = NULL;
24722 	mblk_t *next_mp = NULL;
24723 	uint32_t max_frag;
24724 	boolean_t multirt_send = B_FALSE;
24725 	mblk_t *mp;
24726 	mblk_t *mp1;
24727 	uint_t	ill_index;
24728 	ipsec_out_t *io;
24729 	boolean_t attach_if;
24730 	int match_flags, offset;
24731 	irb_t *irb = NULL;
24732 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
24733 	zoneid_t zoneid;
24734 	uint32_t cksum;
24735 	uint16_t *up;
24736 	ipxmit_state_t	pktxmit_state;
24737 #ifdef	_BIG_ENDIAN
24738 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
24739 #else
24740 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
24741 #endif
24742 
24743 	mp = ipsec_mp->b_cont;
24744 	ASSERT(mp != NULL);
24745 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24746 	dst = ipha->ipha_dst;
24747 
24748 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24749 	ill_index = io->ipsec_out_ill_index;
24750 	attach_if = io->ipsec_out_attach_if;
24751 	zoneid = io->ipsec_out_zoneid;
24752 	ASSERT(zoneid != ALL_ZONES);
24753 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24754 	if (ill_index != 0) {
24755 		if (ill == NULL) {
24756 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
24757 			    ill_index, B_FALSE);
24758 
24759 			/* Failure case frees things for us. */
24760 			if (ill == NULL)
24761 				return;
24762 
24763 			ill_need_rele = B_TRUE;
24764 		}
24765 		/*
24766 		 * If this packet needs to go out on a particular interface
24767 		 * honor it.
24768 		 */
24769 		if (attach_if) {
24770 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
24771 
24772 			/*
24773 			 * Check if we need an ire that will not be
24774 			 * looked up by anybody else i.e. HIDDEN.
24775 			 */
24776 			if (ill_is_probeonly(ill)) {
24777 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24778 			}
24779 		}
24780 	}
24781 
24782 	if (CLASSD(dst)) {
24783 		boolean_t conn_dontroute;
24784 		/*
24785 		 * Use the ill_index to get the right ipif.
24786 		 */
24787 		conn_dontroute = io->ipsec_out_dontroute;
24788 		if (ill_index == 0)
24789 			ipif = ipif_lookup_group(dst, zoneid);
24790 		else
24791 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24792 		if (ipif == NULL) {
24793 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
24794 			    " multicast\n"));
24795 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
24796 			freemsg(ipsec_mp);
24797 			goto done;
24798 		}
24799 		/*
24800 		 * ipha_src has already been intialized with the
24801 		 * value of the ipif in ip_wput. All we need now is
24802 		 * an ire to send this downstream.
24803 		 */
24804 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
24805 		    MBLK_GETLABEL(mp), match_flags);
24806 		if (ire != NULL) {
24807 			ill_t *ill1;
24808 			/*
24809 			 * Do the multicast forwarding now, as the IPSEC
24810 			 * processing has been done.
24811 			 */
24812 			if (ip_g_mrouter && !conn_dontroute &&
24813 			    (ill1 = ire_to_ill(ire))) {
24814 				if (ip_mforward(ill1, ipha, mp)) {
24815 					freemsg(ipsec_mp);
24816 					ip1dbg(("ip_wput_ipsec_out: mforward "
24817 					    "failed\n"));
24818 					ire_refrele(ire);
24819 					goto done;
24820 				}
24821 			}
24822 			goto send;
24823 		}
24824 
24825 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
24826 		mp->b_prev = NULL;
24827 		mp->b_next = NULL;
24828 
24829 		/*
24830 		 * If the IPsec packet was processed asynchronously,
24831 		 * drop it now.
24832 		 */
24833 		if (q == NULL) {
24834 			freemsg(ipsec_mp);
24835 			goto done;
24836 		}
24837 
24838 		/*
24839 		 * We may be using a wrong ipif to create the ire.
24840 		 * But it is okay as the source address is assigned
24841 		 * for the packet already. Next outbound packet would
24842 		 * create the IRE with the right IPIF in ip_wput.
24843 		 *
24844 		 * Also handle RTF_MULTIRT routes.
24845 		 */
24846 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
24847 		    zoneid);
24848 	} else {
24849 		if (attach_if) {
24850 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
24851 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24852 		} else {
24853 			if (ire_arg != NULL) {
24854 				ire = ire_arg;
24855 				ire_need_rele = B_FALSE;
24856 			} else {
24857 				ire = ire_cache_lookup(dst, zoneid,
24858 				    MBLK_GETLABEL(mp));
24859 			}
24860 		}
24861 		if (ire != NULL) {
24862 			goto send;
24863 		}
24864 
24865 		/*
24866 		 * ire disappeared underneath.
24867 		 *
24868 		 * What we need to do here is the ip_newroute
24869 		 * logic to get the ire without doing the IPSEC
24870 		 * processing. Follow the same old path. But this
24871 		 * time, ip_wput or ire_add_then_put will call us
24872 		 * directly as all the IPSEC operations are done.
24873 		 */
24874 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
24875 		mp->b_prev = NULL;
24876 		mp->b_next = NULL;
24877 
24878 		/*
24879 		 * If the IPsec packet was processed asynchronously,
24880 		 * drop it now.
24881 		 */
24882 		if (q == NULL) {
24883 			freemsg(ipsec_mp);
24884 			goto done;
24885 		}
24886 
24887 		/*
24888 		 * Since we're going through ip_newroute() again, we
24889 		 * need to make sure we don't:
24890 		 *
24891 		 *	1.) Trigger the ASSERT() with the ipha_ident
24892 		 *	    overloading.
24893 		 *	2.) Redo transport-layer checksumming, since we've
24894 		 *	    already done all that to get this far.
24895 		 *
24896 		 * The easiest way not do either of the above is to set
24897 		 * the ipha_ident field to IP_HDR_INCLUDED.
24898 		 */
24899 		ipha->ipha_ident = IP_HDR_INCLUDED;
24900 		ip_newroute(q, ipsec_mp, dst, NULL,
24901 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid);
24902 	}
24903 	goto done;
24904 send:
24905 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
24906 		/*
24907 		 * ESP NAT-Traversal packet.
24908 		 *
24909 		 * Just do software checksum for now.
24910 		 */
24911 
24912 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
24913 		IP_STAT(ip_out_sw_cksum);
24914 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
24915 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
24916 #define	iphs	((uint16_t *)ipha)
24917 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
24918 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
24919 		    IP_SIMPLE_HDR_LENGTH);
24920 #undef iphs
24921 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
24922 			cksum = 0xFFFF;
24923 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
24924 			if (mp1->b_wptr - mp1->b_rptr >=
24925 			    offset + sizeof (uint16_t)) {
24926 				up = (uint16_t *)(mp1->b_rptr + offset);
24927 				*up = cksum;
24928 				break;	/* out of for loop */
24929 			} else {
24930 				offset -= (mp->b_wptr - mp->b_rptr);
24931 			}
24932 	} /* Otherwise, just keep the all-zero checksum. */
24933 
24934 	if (ire->ire_stq == NULL) {
24935 		/*
24936 		 * Loopbacks go through ip_wput_local except for one case.
24937 		 * We come here if we generate a icmp_frag_needed message
24938 		 * after IPSEC processing is over. When this function calls
24939 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
24940 		 * icmp_frag_needed. The message generated comes back here
24941 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
24942 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
24943 		 * source address as it is usually set in ip_wput_ire. As
24944 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
24945 		 * and we end up here. We can't enter ip_wput_ire once the
24946 		 * IPSEC processing is over and hence we need to do it here.
24947 		 */
24948 		ASSERT(q != NULL);
24949 		UPDATE_OB_PKT_COUNT(ire);
24950 		ire->ire_last_used_time = lbolt;
24951 		if (ipha->ipha_src == 0)
24952 			ipha->ipha_src = ire->ire_src_addr;
24953 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
24954 		    ire, 0, zoneid);
24955 		if (ire_need_rele)
24956 			ire_refrele(ire);
24957 		goto done;
24958 	}
24959 
24960 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
24961 		/*
24962 		 * We are through with IPSEC processing.
24963 		 * Fragment this and send it on the wire.
24964 		 */
24965 		if (io->ipsec_out_accelerated) {
24966 			/*
24967 			 * The packet has been accelerated but must
24968 			 * be fragmented. This should not happen
24969 			 * since AH and ESP must not accelerate
24970 			 * packets that need fragmentation, however
24971 			 * the configuration could have changed
24972 			 * since the AH or ESP processing.
24973 			 * Drop packet.
24974 			 * IPsec KSTATS: bump bean counter here.
24975 			 */
24976 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
24977 			    "fragmented accelerated packet!\n"));
24978 			freemsg(ipsec_mp);
24979 		} else {
24980 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid);
24981 		}
24982 		if (ire_need_rele)
24983 			ire_refrele(ire);
24984 		goto done;
24985 	}
24986 
24987 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
24988 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
24989 	    (void *)ire->ire_ipif, (void *)ipif));
24990 
24991 	/*
24992 	 * Multiroute the secured packet, unless IPsec really
24993 	 * requires the packet to go out only through a particular
24994 	 * interface.
24995 	 */
24996 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
24997 		ire_t *first_ire;
24998 		irb = ire->ire_bucket;
24999 		ASSERT(irb != NULL);
25000 		/*
25001 		 * This ire has been looked up as the one that
25002 		 * goes through the given ipif;
25003 		 * make sure we do not omit any other multiroute ire
25004 		 * that may be present in the bucket before this one.
25005 		 */
25006 		IRB_REFHOLD(irb);
25007 		for (first_ire = irb->irb_ire;
25008 		    first_ire != NULL;
25009 		    first_ire = first_ire->ire_next) {
25010 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25011 			    (first_ire->ire_addr == ire->ire_addr) &&
25012 			    !(first_ire->ire_marks &
25013 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
25014 				break;
25015 		}
25016 
25017 		if ((first_ire != NULL) && (first_ire != ire)) {
25018 			/*
25019 			 * Don't change the ire if the packet must
25020 			 * be fragmented if sent via this new one.
25021 			 */
25022 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25023 				IRE_REFHOLD(first_ire);
25024 				if (ire_need_rele)
25025 					ire_refrele(ire);
25026 				else
25027 					ire_need_rele = B_TRUE;
25028 				ire = first_ire;
25029 			}
25030 		}
25031 		IRB_REFRELE(irb);
25032 
25033 		multirt_send = B_TRUE;
25034 		max_frag = ire->ire_max_frag;
25035 	} else {
25036 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
25037 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25038 			    "flag, attach_if %d\n", attach_if));
25039 		}
25040 	}
25041 
25042 	/*
25043 	 * In most cases, the emission loop below is entered only once.
25044 	 * Only in the case where the ire holds the RTF_MULTIRT
25045 	 * flag, we loop to process all RTF_MULTIRT ires in the
25046 	 * bucket, and send the packet through all crossed
25047 	 * RTF_MULTIRT routes.
25048 	 */
25049 	do {
25050 		if (multirt_send) {
25051 			/*
25052 			 * ire1 holds here the next ire to process in the
25053 			 * bucket. If multirouting is expected,
25054 			 * any non-RTF_MULTIRT ire that has the
25055 			 * right destination address is ignored.
25056 			 */
25057 			ASSERT(irb != NULL);
25058 			IRB_REFHOLD(irb);
25059 			for (ire1 = ire->ire_next;
25060 			    ire1 != NULL;
25061 			    ire1 = ire1->ire_next) {
25062 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
25063 					continue;
25064 				if (ire1->ire_addr != ire->ire_addr)
25065 					continue;
25066 				if (ire1->ire_marks &
25067 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
25068 					continue;
25069 				/* No loopback here */
25070 				if (ire1->ire_stq == NULL)
25071 					continue;
25072 				/*
25073 				 * Ensure we do not exceed the MTU
25074 				 * of the next route.
25075 				 */
25076 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
25077 					ip_multirt_bad_mtu(ire1, max_frag);
25078 					continue;
25079 				}
25080 
25081 				IRE_REFHOLD(ire1);
25082 				break;
25083 			}
25084 			IRB_REFRELE(irb);
25085 			if (ire1 != NULL) {
25086 				/*
25087 				 * We are in a multiple send case, need to
25088 				 * make a copy of the packet.
25089 				 */
25090 				next_mp = copymsg(ipsec_mp);
25091 				if (next_mp == NULL) {
25092 					ire_refrele(ire1);
25093 					ire1 = NULL;
25094 				}
25095 			}
25096 		}
25097 		/*
25098 		 * Everything is done. Send it out on the wire
25099 		 *
25100 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
25101 		 * either send it on the wire or, in the case of
25102 		 * HW acceleration, call ipsec_hw_putnext.
25103 		 */
25104 		if (ire->ire_nce &&
25105 		    ire->ire_nce->nce_state != ND_REACHABLE) {
25106 			DTRACE_PROBE2(ip__wput__ipsec__bail,
25107 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
25108 			/*
25109 			 * If ire's link-layer is unresolved (this
25110 			 * would only happen if the incomplete ire
25111 			 * was added to cachetable via forwarding path)
25112 			 * don't bother going to ip_xmit_v4. Just drop the
25113 			 * packet.
25114 			 * There is a slight risk here, in that, if we
25115 			 * have the forwarding path create an incomplete
25116 			 * IRE, then until the IRE is completed, any
25117 			 * transmitted IPSEC packets will be dropped
25118 			 * instead of being queued waiting for resolution.
25119 			 *
25120 			 * But the likelihood of a forwarding packet and a wput
25121 			 * packet sending to the same dst at the same time
25122 			 * and there not yet be an ARP entry for it is small.
25123 			 * Furthermore, if this actually happens, it might
25124 			 * be likely that wput would generate multiple
25125 			 * packets (and forwarding would also have a train
25126 			 * of packets) for that destination. If this is
25127 			 * the case, some of them would have been dropped
25128 			 * anyway, since ARP only queues a few packets while
25129 			 * waiting for resolution
25130 			 *
25131 			 * NOTE: We should really call ip_xmit_v4,
25132 			 * and let it queue the packet and send the
25133 			 * ARP query and have ARP come back thus:
25134 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
25135 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
25136 			 * hw accel work. But it's too complex to get
25137 			 * the IPsec hw  acceleration approach to fit
25138 			 * well with ip_xmit_v4 doing ARP without
25139 			 * doing IPSEC simplification. For now, we just
25140 			 * poke ip_xmit_v4 to trigger the arp resolve, so
25141 			 * that we can continue with the send on the next
25142 			 * attempt.
25143 			 *
25144 			 * XXX THis should be revisited, when
25145 			 * the IPsec/IP interaction is cleaned up
25146 			 */
25147 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
25148 			    " - dropping packet\n"));
25149 			freemsg(ipsec_mp);
25150 			/*
25151 			 * Call ip_xmit_v4() to trigger ARP query
25152 			 * in case the nce_state is ND_INITIAL
25153 			 */
25154 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
25155 			goto drop_pkt;
25156 		}
25157 
25158 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
25159 		pktxmit_state = ip_xmit_v4(mp, ire,
25160 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
25161 
25162 		if ((pktxmit_state ==  SEND_FAILED) ||
25163 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
25164 
25165 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
25166 drop_pkt:
25167 			BUMP_MIB(&ip_mib, ipOutDiscards);
25168 			if (ire_need_rele)
25169 				ire_refrele(ire);
25170 			if (ire1 != NULL) {
25171 				ire_refrele(ire1);
25172 				freemsg(next_mp);
25173 			}
25174 			goto done;
25175 		}
25176 
25177 		freeb(ipsec_mp);
25178 		if (ire_need_rele)
25179 			ire_refrele(ire);
25180 
25181 		if (ire1 != NULL) {
25182 			ire = ire1;
25183 			ire_need_rele = B_TRUE;
25184 			ASSERT(next_mp);
25185 			ipsec_mp = next_mp;
25186 			mp = ipsec_mp->b_cont;
25187 			ire1 = NULL;
25188 			next_mp = NULL;
25189 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
25190 		} else {
25191 			multirt_send = B_FALSE;
25192 		}
25193 	} while (multirt_send);
25194 done:
25195 	if (ill != NULL && ill_need_rele)
25196 		ill_refrele(ill);
25197 	if (ipif != NULL)
25198 		ipif_refrele(ipif);
25199 }
25200 
25201 /*
25202  * Get the ill corresponding to the specified ire, and compare its
25203  * capabilities with the protocol and algorithms specified by the
25204  * the SA obtained from ipsec_out. If they match, annotate the
25205  * ipsec_out structure to indicate that the packet needs acceleration.
25206  *
25207  *
25208  * A packet is eligible for outbound hardware acceleration if the
25209  * following conditions are satisfied:
25210  *
25211  * 1. the packet will not be fragmented
25212  * 2. the provider supports the algorithm
25213  * 3. there is no pending control message being exchanged
25214  * 4. snoop is not attached
25215  * 5. the destination address is not a broadcast or multicast address.
25216  *
25217  * Rationale:
25218  *	- Hardware drivers do not support fragmentation with
25219  *	  the current interface.
25220  *	- snoop, multicast, and broadcast may result in exposure of
25221  *	  a cleartext datagram.
25222  * We check all five of these conditions here.
25223  *
25224  * XXX would like to nuke "ire_t *" parameter here; problem is that
25225  * IRE is only way to figure out if a v4 address is a broadcast and
25226  * thus ineligible for acceleration...
25227  */
25228 static void
25229 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
25230 {
25231 	ipsec_out_t *io;
25232 	mblk_t *data_mp;
25233 	uint_t plen, overhead;
25234 
25235 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
25236 		return;
25237 
25238 	if (ill == NULL)
25239 		return;
25240 
25241 	/*
25242 	 * Destination address is a broadcast or multicast.  Punt.
25243 	 */
25244 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
25245 	    IRE_LOCAL)))
25246 		return;
25247 
25248 	data_mp = ipsec_mp->b_cont;
25249 
25250 	if (ill->ill_isv6) {
25251 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
25252 
25253 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
25254 			return;
25255 
25256 		plen = ip6h->ip6_plen;
25257 	} else {
25258 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
25259 
25260 		if (CLASSD(ipha->ipha_dst))
25261 			return;
25262 
25263 		plen = ipha->ipha_length;
25264 	}
25265 	/*
25266 	 * Is there a pending DLPI control message being exchanged
25267 	 * between IP/IPsec and the DLS Provider? If there is, it
25268 	 * could be a SADB update, and the state of the DLS Provider
25269 	 * SADB might not be in sync with the SADB maintained by
25270 	 * IPsec. To avoid dropping packets or using the wrong keying
25271 	 * material, we do not accelerate this packet.
25272 	 */
25273 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
25274 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25275 		    "ill_dlpi_pending! don't accelerate packet\n"));
25276 		return;
25277 	}
25278 
25279 	/*
25280 	 * Is the Provider in promiscous mode? If it does, we don't
25281 	 * accelerate the packet since it will bounce back up to the
25282 	 * listeners in the clear.
25283 	 */
25284 	if (ill->ill_promisc_on_phys) {
25285 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25286 		    "ill in promiscous mode, don't accelerate packet\n"));
25287 		return;
25288 	}
25289 
25290 	/*
25291 	 * Will the packet require fragmentation?
25292 	 */
25293 
25294 	/*
25295 	 * IPsec ESP note: this is a pessimistic estimate, but the same
25296 	 * as is used elsewhere.
25297 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
25298 	 *	+ 2-byte trailer
25299 	 */
25300 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
25301 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
25302 
25303 	if ((plen + overhead) > ill->ill_max_mtu)
25304 		return;
25305 
25306 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25307 
25308 	/*
25309 	 * Can the ill accelerate this IPsec protocol and algorithm
25310 	 * specified by the SA?
25311 	 */
25312 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
25313 	    ill->ill_isv6, sa)) {
25314 		return;
25315 	}
25316 
25317 	/*
25318 	 * Tell AH or ESP that the outbound ill is capable of
25319 	 * accelerating this packet.
25320 	 */
25321 	io->ipsec_out_is_capab_ill = B_TRUE;
25322 }
25323 
25324 /*
25325  * Select which AH & ESP SA's to use (if any) for the outbound packet.
25326  *
25327  * If this function returns B_TRUE, the requested SA's have been filled
25328  * into the ipsec_out_*_sa pointers.
25329  *
25330  * If the function returns B_FALSE, the packet has been "consumed", most
25331  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
25332  *
25333  * The SA references created by the protocol-specific "select"
25334  * function will be released when the ipsec_mp is freed, thanks to the
25335  * ipsec_out_free destructor -- see spd.c.
25336  */
25337 static boolean_t
25338 ipsec_out_select_sa(mblk_t *ipsec_mp)
25339 {
25340 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
25341 	ipsec_out_t *io;
25342 	ipsec_policy_t *pp;
25343 	ipsec_action_t *ap;
25344 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25345 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25346 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25347 
25348 	if (!io->ipsec_out_secure) {
25349 		/*
25350 		 * We came here by mistake.
25351 		 * Don't bother with ipsec processing
25352 		 * We should "discourage" this path in the future.
25353 		 */
25354 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25355 		return (B_FALSE);
25356 	}
25357 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25358 	ASSERT((io->ipsec_out_policy != NULL) ||
25359 	    (io->ipsec_out_act != NULL));
25360 
25361 	ASSERT(io->ipsec_out_failed == B_FALSE);
25362 
25363 	/*
25364 	 * IPSEC processing has started.
25365 	 */
25366 	io->ipsec_out_proc_begin = B_TRUE;
25367 	ap = io->ipsec_out_act;
25368 	if (ap == NULL) {
25369 		pp = io->ipsec_out_policy;
25370 		ASSERT(pp != NULL);
25371 		ap = pp->ipsp_act;
25372 		ASSERT(ap != NULL);
25373 	}
25374 
25375 	/*
25376 	 * We have an action.  now, let's select SA's.
25377 	 * (In the future, we can cache this in the conn_t..)
25378 	 */
25379 	if (ap->ipa_want_esp) {
25380 		if (io->ipsec_out_esp_sa == NULL) {
25381 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
25382 			    IPPROTO_ESP);
25383 		}
25384 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
25385 	}
25386 
25387 	if (ap->ipa_want_ah) {
25388 		if (io->ipsec_out_ah_sa == NULL) {
25389 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
25390 			    IPPROTO_AH);
25391 		}
25392 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
25393 		/*
25394 		 * The ESP and AH processing order needs to be preserved
25395 		 * when both protocols are required (ESP should be applied
25396 		 * before AH for an outbound packet). Force an ESP ACQUIRE
25397 		 * when both ESP and AH are required, and an AH ACQUIRE
25398 		 * is needed.
25399 		 */
25400 		if (ap->ipa_want_esp && need_ah_acquire)
25401 			need_esp_acquire = B_TRUE;
25402 	}
25403 
25404 	/*
25405 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
25406 	 * Release SAs that got referenced, but will not be used until we
25407 	 * acquire _all_ of the SAs we need.
25408 	 */
25409 	if (need_ah_acquire || need_esp_acquire) {
25410 		if (io->ipsec_out_ah_sa != NULL) {
25411 			IPSA_REFRELE(io->ipsec_out_ah_sa);
25412 			io->ipsec_out_ah_sa = NULL;
25413 		}
25414 		if (io->ipsec_out_esp_sa != NULL) {
25415 			IPSA_REFRELE(io->ipsec_out_esp_sa);
25416 			io->ipsec_out_esp_sa = NULL;
25417 		}
25418 
25419 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
25420 		return (B_FALSE);
25421 	}
25422 
25423 	return (B_TRUE);
25424 }
25425 
25426 /*
25427  * Process an IPSEC_OUT message and see what you can
25428  * do with it.
25429  * IPQoS Notes:
25430  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
25431  * IPSec.
25432  * XXX would like to nuke ire_t.
25433  * XXX ill_index better be "real"
25434  */
25435 void
25436 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
25437 {
25438 	ipsec_out_t *io;
25439 	ipsec_policy_t *pp;
25440 	ipsec_action_t *ap;
25441 	ipha_t *ipha;
25442 	ip6_t *ip6h;
25443 	mblk_t *mp;
25444 	ill_t *ill;
25445 	zoneid_t zoneid;
25446 	ipsec_status_t ipsec_rc;
25447 	boolean_t ill_need_rele = B_FALSE;
25448 
25449 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25450 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25451 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25452 	mp = ipsec_mp->b_cont;
25453 
25454 	/*
25455 	 * Initiate IPPF processing. We do it here to account for packets
25456 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
25457 	 * We can check for ipsec_out_proc_begin even for such packets, as
25458 	 * they will always be false (asserted below).
25459 	 */
25460 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
25461 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
25462 		    io->ipsec_out_ill_index : ill_index);
25463 		if (mp == NULL) {
25464 			ip2dbg(("ipsec_out_process: packet dropped "\
25465 			    "during IPPF processing\n"));
25466 			freeb(ipsec_mp);
25467 			BUMP_MIB(&ip_mib, ipOutDiscards);
25468 			return;
25469 		}
25470 	}
25471 
25472 	if (!io->ipsec_out_secure) {
25473 		/*
25474 		 * We came here by mistake.
25475 		 * Don't bother with ipsec processing
25476 		 * Should "discourage" this path in the future.
25477 		 */
25478 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25479 		goto done;
25480 	}
25481 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25482 	ASSERT((io->ipsec_out_policy != NULL) ||
25483 	    (io->ipsec_out_act != NULL));
25484 	ASSERT(io->ipsec_out_failed == B_FALSE);
25485 
25486 	if (!ipsec_loaded()) {
25487 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
25488 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25489 			BUMP_MIB(&ip_mib, ipOutDiscards);
25490 		} else {
25491 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
25492 		}
25493 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
25494 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
25495 		return;
25496 	}
25497 
25498 	/*
25499 	 * IPSEC processing has started.
25500 	 */
25501 	io->ipsec_out_proc_begin = B_TRUE;
25502 	ap = io->ipsec_out_act;
25503 	if (ap == NULL) {
25504 		pp = io->ipsec_out_policy;
25505 		ASSERT(pp != NULL);
25506 		ap = pp->ipsp_act;
25507 		ASSERT(ap != NULL);
25508 	}
25509 
25510 	/*
25511 	 * Save the outbound ill index. When the packet comes back
25512 	 * from IPsec, we make sure the ill hasn't changed or disappeared
25513 	 * before sending it the accelerated packet.
25514 	 */
25515 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
25516 		int ifindex;
25517 		ill = ire_to_ill(ire);
25518 		ifindex = ill->ill_phyint->phyint_ifindex;
25519 		io->ipsec_out_capab_ill_index = ifindex;
25520 	}
25521 
25522 	/*
25523 	 * The order of processing is first insert a IP header if needed.
25524 	 * Then insert the ESP header and then the AH header.
25525 	 */
25526 	if ((io->ipsec_out_se_done == B_FALSE) &&
25527 	    (ap->ipa_want_se)) {
25528 		/*
25529 		 * First get the outer IP header before sending
25530 		 * it to ESP.
25531 		 */
25532 		ipha_t *oipha, *iipha;
25533 		mblk_t *outer_mp, *inner_mp;
25534 
25535 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
25536 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
25537 			    "ipsec_out_process: "
25538 			    "Self-Encapsulation failed: Out of memory\n");
25539 			freemsg(ipsec_mp);
25540 			BUMP_MIB(&ip_mib, ipOutDiscards);
25541 			return;
25542 		}
25543 		inner_mp = ipsec_mp->b_cont;
25544 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
25545 		oipha = (ipha_t *)outer_mp->b_rptr;
25546 		iipha = (ipha_t *)inner_mp->b_rptr;
25547 		*oipha = *iipha;
25548 		outer_mp->b_wptr += sizeof (ipha_t);
25549 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
25550 		    sizeof (ipha_t));
25551 		oipha->ipha_protocol = IPPROTO_ENCAP;
25552 		oipha->ipha_version_and_hdr_length =
25553 		    IP_SIMPLE_HDR_VERSION;
25554 		oipha->ipha_hdr_checksum = 0;
25555 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
25556 		outer_mp->b_cont = inner_mp;
25557 		ipsec_mp->b_cont = outer_mp;
25558 
25559 		io->ipsec_out_se_done = B_TRUE;
25560 		io->ipsec_out_encaps = B_TRUE;
25561 	}
25562 
25563 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
25564 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
25565 	    !ipsec_out_select_sa(ipsec_mp))
25566 		return;
25567 
25568 	/*
25569 	 * By now, we know what SA's to use.  Toss over to ESP & AH
25570 	 * to do the heavy lifting.
25571 	 */
25572 	zoneid = io->ipsec_out_zoneid;
25573 	ASSERT(zoneid != ALL_ZONES);
25574 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
25575 		ASSERT(io->ipsec_out_esp_sa != NULL);
25576 		io->ipsec_out_esp_done = B_TRUE;
25577 		/*
25578 		 * Note that since hw accel can only apply one transform,
25579 		 * not two, we skip hw accel for ESP if we also have AH
25580 		 * This is an design limitation of the interface
25581 		 * which should be revisited.
25582 		 */
25583 		ASSERT(ire != NULL);
25584 		if (io->ipsec_out_ah_sa == NULL) {
25585 			ill = (ill_t *)ire->ire_stq->q_ptr;
25586 			ipsec_out_is_accelerated(ipsec_mp,
25587 			    io->ipsec_out_esp_sa, ill, ire);
25588 		}
25589 
25590 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
25591 		switch (ipsec_rc) {
25592 		case IPSEC_STATUS_SUCCESS:
25593 			break;
25594 		case IPSEC_STATUS_FAILED:
25595 			BUMP_MIB(&ip_mib, ipOutDiscards);
25596 			/* FALLTHRU */
25597 		case IPSEC_STATUS_PENDING:
25598 			return;
25599 		}
25600 	}
25601 
25602 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
25603 		ASSERT(io->ipsec_out_ah_sa != NULL);
25604 		io->ipsec_out_ah_done = B_TRUE;
25605 		if (ire == NULL) {
25606 			int idx = io->ipsec_out_capab_ill_index;
25607 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
25608 			    NULL, NULL, NULL, NULL);
25609 			ill_need_rele = B_TRUE;
25610 		} else {
25611 			ill = (ill_t *)ire->ire_stq->q_ptr;
25612 		}
25613 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
25614 		    ire);
25615 
25616 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
25617 		switch (ipsec_rc) {
25618 		case IPSEC_STATUS_SUCCESS:
25619 			break;
25620 		case IPSEC_STATUS_FAILED:
25621 			BUMP_MIB(&ip_mib, ipOutDiscards);
25622 			/* FALLTHRU */
25623 		case IPSEC_STATUS_PENDING:
25624 			if (ill != NULL && ill_need_rele)
25625 				ill_refrele(ill);
25626 			return;
25627 		}
25628 	}
25629 	/*
25630 	 * We are done with IPSEC processing. Send it over
25631 	 * the wire.
25632 	 */
25633 done:
25634 	mp = ipsec_mp->b_cont;
25635 	ipha = (ipha_t *)mp->b_rptr;
25636 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25637 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
25638 	} else {
25639 		ip6h = (ip6_t *)ipha;
25640 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
25641 	}
25642 	if (ill != NULL && ill_need_rele)
25643 		ill_refrele(ill);
25644 }
25645 
25646 /* ARGSUSED */
25647 void
25648 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
25649 {
25650 	opt_restart_t	*or;
25651 	int	err;
25652 	conn_t	*connp;
25653 
25654 	ASSERT(CONN_Q(q));
25655 	connp = Q_TO_CONN(q);
25656 
25657 	ASSERT(first_mp->b_datap->db_type == M_CTL);
25658 	or = (opt_restart_t *)first_mp->b_rptr;
25659 	/*
25660 	 * We don't need to pass any credentials here since this is just
25661 	 * a restart. The credentials are passed in when svr4_optcom_req
25662 	 * is called the first time (from ip_wput_nondata).
25663 	 */
25664 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
25665 		err = svr4_optcom_req(q, first_mp, NULL,
25666 		    &ip_opt_obj);
25667 	} else {
25668 		ASSERT(or->or_type == T_OPTMGMT_REQ);
25669 		err = tpi_optcom_req(q, first_mp, NULL,
25670 		    &ip_opt_obj);
25671 	}
25672 	if (err != EINPROGRESS) {
25673 		/* operation is done */
25674 		CONN_OPER_PENDING_DONE(connp);
25675 	}
25676 }
25677 
25678 /*
25679  * ioctls that go through a down/up sequence may need to wait for the down
25680  * to complete. This involves waiting for the ire and ipif refcnts to go down
25681  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
25682  */
25683 /* ARGSUSED */
25684 void
25685 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25686 {
25687 	struct iocblk *iocp;
25688 	mblk_t *mp1;
25689 	ipif_t	*ipif;
25690 	ip_ioctl_cmd_t *ipip;
25691 	int err;
25692 	sin_t	*sin;
25693 	struct lifreq *lifr;
25694 	struct ifreq *ifr;
25695 
25696 	iocp = (struct iocblk *)mp->b_rptr;
25697 	ASSERT(ipsq != NULL);
25698 	/* Existence of mp1 verified in ip_wput_nondata */
25699 	mp1 = mp->b_cont->b_cont;
25700 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25701 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
25702 		ill_t *ill;
25703 		/*
25704 		 * Special case where ipsq_current_ipif may not be set.
25705 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
25706 		 * ill could also have become part of a ipmp group in the
25707 		 * process, we are here as were not able to complete the
25708 		 * operation in ipif_set_values because we could not become
25709 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
25710 		 * will not be set so we need to set it.
25711 		 */
25712 		ill = (ill_t *)q->q_ptr;
25713 		ipsq->ipsq_current_ipif = ill->ill_ipif;
25714 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25715 	}
25716 
25717 	ipif = ipsq->ipsq_current_ipif;
25718 	ASSERT(ipif != NULL);
25719 	if (ipip->ipi_cmd_type == IF_CMD) {
25720 		/* This a old style SIOC[GS]IF* command */
25721 		ifr = (struct ifreq *)mp1->b_rptr;
25722 		sin = (sin_t *)&ifr->ifr_addr;
25723 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
25724 		/* This a new style SIOC[GS]LIF* command */
25725 		lifr = (struct lifreq *)mp1->b_rptr;
25726 		sin = (sin_t *)&lifr->lifr_addr;
25727 	} else {
25728 		sin = NULL;
25729 	}
25730 
25731 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
25732 	    (void *)mp1->b_rptr);
25733 
25734 	/* SIOCLIFREMOVEIF could have removed the ipif */
25735 	ip_ioctl_finish(q, mp, err,
25736 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25737 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
25738 }
25739 
25740 /*
25741  * ioctl processing
25742  *
25743  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
25744  * the ioctl command in the ioctl tables and determines the copyin data size
25745  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
25746  * size.
25747  *
25748  * ioctl processing then continues when the M_IOCDATA makes its way down.
25749  * Now the ioctl is looked up again in the ioctl table, and its properties are
25750  * extracted. The associated 'conn' is then refheld till the end of the ioctl
25751  * and the general ioctl processing function ip_process_ioctl is called.
25752  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
25753  * so goes thru the serialization primitive ipsq_try_enter. Then the
25754  * appropriate function to handle the ioctl is called based on the entry in
25755  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
25756  * which also refreleases the 'conn' that was refheld at the start of the
25757  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
25758  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
25759  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
25760  *
25761  * Many exclusive ioctls go thru an internal down up sequence as part of
25762  * the operation. For example an attempt to change the IP address of an
25763  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
25764  * does all the cleanup such as deleting all ires that use this address.
25765  * Then we need to wait till all references to the interface go away.
25766  */
25767 void
25768 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
25769 {
25770 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
25771 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
25772 	cmd_info_t ci;
25773 	int err;
25774 	boolean_t entered_ipsq = B_FALSE;
25775 
25776 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
25777 
25778 	if (ipip == NULL)
25779 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25780 
25781 	/*
25782 	 * SIOCLIFADDIF needs to go thru a special path since the
25783 	 * ill may not exist yet. This happens in the case of lo0
25784 	 * which is created using this ioctl.
25785 	 */
25786 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
25787 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
25788 		ip_ioctl_finish(q, mp, err,
25789 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25790 		    NULL, NULL);
25791 		return;
25792 	}
25793 
25794 	ci.ci_ipif = NULL;
25795 	switch (ipip->ipi_cmd_type) {
25796 	case IF_CMD:
25797 	case LIF_CMD:
25798 		/*
25799 		 * ioctls that pass in a [l]ifreq appear here.
25800 		 * ip_extract_lifreq_cmn returns a refheld ipif in
25801 		 * ci.ci_ipif
25802 		 */
25803 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
25804 		    ipip->ipi_flags, &ci, ip_process_ioctl);
25805 		if (err != 0) {
25806 			ip_ioctl_finish(q, mp, err,
25807 			    ipip->ipi_flags & IPI_GET_CMD ?
25808 			    COPYOUT : NO_COPYOUT, NULL, NULL);
25809 			return;
25810 		}
25811 		ASSERT(ci.ci_ipif != NULL);
25812 		break;
25813 
25814 	case TUN_CMD:
25815 		/*
25816 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
25817 		 * a refheld ipif in ci.ci_ipif
25818 		 */
25819 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
25820 		if (err != 0) {
25821 			ip_ioctl_finish(q, mp, err,
25822 			    ipip->ipi_flags & IPI_GET_CMD ?
25823 			    COPYOUT : NO_COPYOUT, NULL, NULL);
25824 			return;
25825 		}
25826 		ASSERT(ci.ci_ipif != NULL);
25827 		break;
25828 
25829 	case MISC_CMD:
25830 		/*
25831 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
25832 		 * For eg. SIOCGLIFCONF will appear here.
25833 		 */
25834 		switch (ipip->ipi_cmd) {
25835 		case IF_UNITSEL:
25836 			/* ioctl comes down the ill */
25837 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
25838 			ipif_refhold(ci.ci_ipif);
25839 			break;
25840 		case SIOCGMSFILTER:
25841 		case SIOCSMSFILTER:
25842 		case SIOCGIPMSFILTER:
25843 		case SIOCSIPMSFILTER:
25844 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
25845 			    ip_process_ioctl);
25846 			if (err != 0) {
25847 				ip_ioctl_finish(q, mp, err,
25848 				    ipip->ipi_flags & IPI_GET_CMD ?
25849 				    COPYOUT : NO_COPYOUT, NULL, NULL);
25850 				return;
25851 			}
25852 			break;
25853 		}
25854 		err = 0;
25855 		ci.ci_sin = NULL;
25856 		ci.ci_sin6 = NULL;
25857 		ci.ci_lifr = NULL;
25858 		break;
25859 	}
25860 
25861 	/*
25862 	 * If ipsq is non-null, we are already being called exclusively
25863 	 */
25864 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
25865 	if (!(ipip->ipi_flags & IPI_WR)) {
25866 		/*
25867 		 * A return value of EINPROGRESS means the ioctl is
25868 		 * either queued and waiting for some reason or has
25869 		 * already completed.
25870 		 */
25871 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25872 		    ci.ci_lifr);
25873 		if (ci.ci_ipif != NULL)
25874 			ipif_refrele(ci.ci_ipif);
25875 		ip_ioctl_finish(q, mp, err,
25876 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25877 		    NULL, NULL);
25878 		return;
25879 	}
25880 
25881 	ASSERT(ci.ci_ipif != NULL);
25882 
25883 	if (ipsq == NULL) {
25884 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
25885 		    ip_process_ioctl, NEW_OP, B_TRUE);
25886 		entered_ipsq = B_TRUE;
25887 	}
25888 	/*
25889 	 * Release the ipif so that ipif_down and friends that wait for
25890 	 * references to go away are not misled about the current ipif_refcnt
25891 	 * values. We are writer so we can access the ipif even after releasing
25892 	 * the ipif.
25893 	 */
25894 	ipif_refrele(ci.ci_ipif);
25895 	if (ipsq == NULL)
25896 		return;
25897 
25898 	mutex_enter(&ipsq->ipsq_lock);
25899 	ASSERT(ipsq->ipsq_current_ipif == NULL);
25900 	ipsq->ipsq_current_ipif = ci.ci_ipif;
25901 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25902 	mutex_exit(&ipsq->ipsq_lock);
25903 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
25904 	/*
25905 	 * For most set ioctls that come here, this serves as a single point
25906 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
25907 	 * be any new references to the ipif. This helps functions that go
25908 	 * through this path and end up trying to wait for the refcnts
25909 	 * associated with the ipif to go down to zero. Some exceptions are
25910 	 * Failover, Failback, and Groupname commands that operate on more than
25911 	 * just the ci.ci_ipif. These commands internally determine the
25912 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
25913 	 * flags on that set. Another exception is the Removeif command that
25914 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
25915 	 * ipif to operate on.
25916 	 */
25917 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
25918 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
25919 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
25920 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
25921 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
25922 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
25923 
25924 	/*
25925 	 * A return value of EINPROGRESS means the ioctl is
25926 	 * either queued and waiting for some reason or has
25927 	 * already completed.
25928 	 */
25929 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25930 	    ci.ci_lifr);
25931 
25932 	/* SIOCLIFREMOVEIF could have removed the ipif */
25933 	ip_ioctl_finish(q, mp, err,
25934 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25935 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
25936 
25937 	if (entered_ipsq)
25938 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
25939 }
25940 
25941 /*
25942  * Complete the ioctl. Typically ioctls use the mi package and need to
25943  * do mi_copyout/mi_copy_done.
25944  */
25945 void
25946 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
25947     ipif_t *ipif, ipsq_t *ipsq)
25948 {
25949 	conn_t	*connp = NULL;
25950 
25951 	if (err == EINPROGRESS)
25952 		return;
25953 
25954 	if (CONN_Q(q)) {
25955 		connp = Q_TO_CONN(q);
25956 		ASSERT(connp->conn_ref >= 2);
25957 	}
25958 
25959 	switch (mode) {
25960 	case COPYOUT:
25961 		if (err == 0)
25962 			mi_copyout(q, mp);
25963 		else
25964 			mi_copy_done(q, mp, err);
25965 		break;
25966 
25967 	case NO_COPYOUT:
25968 		mi_copy_done(q, mp, err);
25969 		break;
25970 
25971 	default:
25972 		/* An ioctl aborted through a conn close would take this path */
25973 		break;
25974 	}
25975 
25976 	/*
25977 	 * The refhold placed at the start of the ioctl is released here.
25978 	 */
25979 	if (connp != NULL)
25980 		CONN_OPER_PENDING_DONE(connp);
25981 
25982 	/*
25983 	 * If the ioctl were an exclusive ioctl it would have set
25984 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
25985 	 */
25986 	if (ipif != NULL) {
25987 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
25988 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
25989 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
25990 	}
25991 
25992 	/*
25993 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
25994 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
25995 	 * entering the ipsq
25996 	 */
25997 	if (ipsq != NULL) {
25998 		mutex_enter(&ipsq->ipsq_lock);
25999 		ipsq->ipsq_current_ipif = NULL;
26000 		mutex_exit(&ipsq->ipsq_lock);
26001 	}
26002 }
26003 
26004 /*
26005  * This is called from ip_wput_nondata to resume a deferred TCP bind.
26006  */
26007 /* ARGSUSED */
26008 void
26009 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
26010 {
26011 	conn_t *connp = arg;
26012 	tcp_t	*tcp;
26013 
26014 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
26015 	tcp = connp->conn_tcp;
26016 
26017 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
26018 		freemsg(mp);
26019 	else
26020 		tcp_rput_other(tcp, mp);
26021 	CONN_OPER_PENDING_DONE(connp);
26022 }
26023 
26024 /* Called from ip_wput for all non data messages */
26025 /* ARGSUSED */
26026 void
26027 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26028 {
26029 	mblk_t		*mp1;
26030 	ire_t		*ire, *fake_ire;
26031 	ill_t		*ill;
26032 	struct iocblk	*iocp;
26033 	ip_ioctl_cmd_t	*ipip;
26034 	cred_t		*cr;
26035 	conn_t		*connp = NULL;
26036 	int		cmd, err;
26037 	nce_t		*nce;
26038 	ipif_t		*ipif;
26039 
26040 	if (CONN_Q(q))
26041 		connp = Q_TO_CONN(q);
26042 
26043 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26044 
26045 	/* Check if it is a queue to /dev/sctp. */
26046 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26047 	    connp->conn_rq == NULL) {
26048 		sctp_wput(q, mp);
26049 		return;
26050 	}
26051 
26052 	switch (DB_TYPE(mp)) {
26053 	case M_IOCTL:
26054 		/*
26055 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26056 		 * will arrange to copy in associated control structures.
26057 		 */
26058 		ip_sioctl_copyin_setup(q, mp);
26059 		return;
26060 	case M_IOCDATA:
26061 		/*
26062 		 * Ensure that this is associated with one of our trans-
26063 		 * parent ioctls.  If it's not ours, discard it if we're
26064 		 * running as a driver, or pass it on if we're a module.
26065 		 */
26066 		iocp = (struct iocblk *)mp->b_rptr;
26067 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26068 		if (ipip == NULL) {
26069 			if (q->q_next == NULL) {
26070 				goto nak;
26071 			} else {
26072 				putnext(q, mp);
26073 			}
26074 			return;
26075 		} else if ((q->q_next != NULL) &&
26076 		    !(ipip->ipi_flags & IPI_MODOK)) {
26077 			/*
26078 			 * the ioctl is one we recognise, but is not
26079 			 * consumed by IP as a module, pass M_IOCDATA
26080 			 * for processing downstream, but only for
26081 			 * common Streams ioctls.
26082 			 */
26083 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26084 				putnext(q, mp);
26085 				return;
26086 			} else {
26087 				goto nak;
26088 			}
26089 		}
26090 
26091 		/* IOCTL continuation following copyin or copyout. */
26092 		if (mi_copy_state(q, mp, NULL) == -1) {
26093 			/*
26094 			 * The copy operation failed.  mi_copy_state already
26095 			 * cleaned up, so we're out of here.
26096 			 */
26097 			return;
26098 		}
26099 		/*
26100 		 * If we just completed a copy in, we become writer and
26101 		 * continue processing in ip_sioctl_copyin_done.  If it
26102 		 * was a copy out, we call mi_copyout again.  If there is
26103 		 * nothing more to copy out, it will complete the IOCTL.
26104 		 */
26105 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
26106 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
26107 				mi_copy_done(q, mp, EPROTO);
26108 				return;
26109 			}
26110 			/*
26111 			 * Check for cases that need more copying.  A return
26112 			 * value of 0 means a second copyin has been started,
26113 			 * so we return; a return value of 1 means no more
26114 			 * copying is needed, so we continue.
26115 			 */
26116 			cmd = iocp->ioc_cmd;
26117 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
26118 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
26119 			    MI_COPY_COUNT(mp) == 1) {
26120 				if (ip_copyin_msfilter(q, mp) == 0)
26121 					return;
26122 			}
26123 			/*
26124 			 * Refhold the conn, till the ioctl completes. This is
26125 			 * needed in case the ioctl ends up in the pending mp
26126 			 * list. Every mp in the ill_pending_mp list and
26127 			 * the ipsq_pending_mp must have a refhold on the conn
26128 			 * to resume processing. The refhold is released when
26129 			 * the ioctl completes. (normally or abnormally)
26130 			 * In all cases ip_ioctl_finish is called to finish
26131 			 * the ioctl.
26132 			 */
26133 			if (connp != NULL) {
26134 				/* This is not a reentry */
26135 				ASSERT(ipsq == NULL);
26136 				CONN_INC_REF(connp);
26137 			} else {
26138 				if (!(ipip->ipi_flags & IPI_MODOK)) {
26139 					mi_copy_done(q, mp, EINVAL);
26140 					return;
26141 				}
26142 			}
26143 
26144 			ip_process_ioctl(ipsq, q, mp, ipip);
26145 
26146 		} else {
26147 			mi_copyout(q, mp);
26148 		}
26149 		return;
26150 nak:
26151 		iocp->ioc_error = EINVAL;
26152 		mp->b_datap->db_type = M_IOCNAK;
26153 		iocp->ioc_count = 0;
26154 		qreply(q, mp);
26155 		return;
26156 
26157 	case M_IOCNAK:
26158 		/*
26159 		 * The only way we could get here is if a resolver didn't like
26160 		 * an IOCTL we sent it.	 This shouldn't happen.
26161 		 */
26162 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
26163 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
26164 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
26165 		freemsg(mp);
26166 		return;
26167 	case M_IOCACK:
26168 		/* Finish socket ioctls passed through to ARP. */
26169 		ip_sioctl_iocack(q, mp);
26170 		return;
26171 	case M_FLUSH:
26172 		if (*mp->b_rptr & FLUSHW)
26173 			flushq(q, FLUSHALL);
26174 		if (q->q_next) {
26175 			/*
26176 			 * M_FLUSH is sent up to IP by some drivers during
26177 			 * unbind. ip_rput has already replied to it. We are
26178 			 * here for the M_FLUSH that we originated in IP
26179 			 * before sending the unbind request to the driver.
26180 			 * Just free it as we don't queue packets in IP
26181 			 * on the write side of the device instance.
26182 			 */
26183 			freemsg(mp);
26184 			return;
26185 		}
26186 		if (*mp->b_rptr & FLUSHR) {
26187 			*mp->b_rptr &= ~FLUSHW;
26188 			qreply(q, mp);
26189 			return;
26190 		}
26191 		freemsg(mp);
26192 		return;
26193 	case IRE_DB_REQ_TYPE:
26194 		/* An Upper Level Protocol wants a copy of an IRE. */
26195 		ip_ire_req(q, mp);
26196 		return;
26197 	case M_CTL:
26198 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
26199 			break;
26200 
26201 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
26202 		    IP_ULP_OUT_LABELED) {
26203 			out_labeled_t *olp;
26204 
26205 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
26206 				break;
26207 			olp = (out_labeled_t *)mp->b_rptr;
26208 			connp->conn_ulp_labeled = olp->out_qnext == q;
26209 			freemsg(mp);
26210 			return;
26211 		}
26212 
26213 		/* M_CTL messages are used by ARP to tell us things. */
26214 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
26215 			break;
26216 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
26217 		case AR_ENTRY_SQUERY:
26218 			ip_wput_ctl(q, mp);
26219 			return;
26220 		case AR_CLIENT_NOTIFY:
26221 			ip_arp_news(q, mp);
26222 			return;
26223 		case AR_DLPIOP_DONE:
26224 			ASSERT(q->q_next != NULL);
26225 			ill = (ill_t *)q->q_ptr;
26226 			/* qwriter_ip releases the refhold */
26227 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
26228 			ill_refhold(ill);
26229 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
26230 			    CUR_OP, B_FALSE);
26231 			return;
26232 		case AR_ARP_CLOSING:
26233 			/*
26234 			 * ARP (above us) is closing. If no ARP bringup is
26235 			 * currently pending, ack the message so that ARP
26236 			 * can complete its close. Also mark ill_arp_closing
26237 			 * so that new ARP bringups will fail. If any
26238 			 * ARP bringup is currently in progress, we will
26239 			 * ack this when the current ARP bringup completes.
26240 			 */
26241 			ASSERT(q->q_next != NULL);
26242 			ill = (ill_t *)q->q_ptr;
26243 			mutex_enter(&ill->ill_lock);
26244 			ill->ill_arp_closing = 1;
26245 			if (!ill->ill_arp_bringup_pending) {
26246 				mutex_exit(&ill->ill_lock);
26247 				qreply(q, mp);
26248 			} else {
26249 				mutex_exit(&ill->ill_lock);
26250 				freemsg(mp);
26251 			}
26252 			return;
26253 		case AR_ARP_EXTEND:
26254 			/*
26255 			 * The ARP module above us is capable of duplicate
26256 			 * address detection.  Old ATM drivers will not send
26257 			 * this message.
26258 			 */
26259 			ASSERT(q->q_next != NULL);
26260 			ill = (ill_t *)q->q_ptr;
26261 			ill->ill_arp_extend = B_TRUE;
26262 			freemsg(mp);
26263 			return;
26264 		default:
26265 			break;
26266 		}
26267 		break;
26268 	case M_PROTO:
26269 	case M_PCPROTO:
26270 		/*
26271 		 * The only PROTO messages we expect are ULP binds and
26272 		 * copies of option negotiation acknowledgements.
26273 		 */
26274 		switch (((union T_primitives *)mp->b_rptr)->type) {
26275 		case O_T_BIND_REQ:
26276 		case T_BIND_REQ: {
26277 			/* Request can get queued in bind */
26278 			ASSERT(connp != NULL);
26279 			/*
26280 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
26281 			 * instead of going through this path.  We only get
26282 			 * here in the following cases:
26283 			 *
26284 			 * a. Bind retries, where ipsq is non-NULL.
26285 			 * b. T_BIND_REQ is issued from non TCP/UDP
26286 			 *    transport, e.g. icmp for raw socket,
26287 			 *    in which case ipsq will be NULL.
26288 			 */
26289 			ASSERT(ipsq != NULL ||
26290 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
26291 
26292 			/* Don't increment refcnt if this is a re-entry */
26293 			if (ipsq == NULL)
26294 				CONN_INC_REF(connp);
26295 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
26296 			    connp, NULL) : ip_bind_v4(q, mp, connp);
26297 			if (mp == NULL)
26298 				return;
26299 			if (IPCL_IS_TCP(connp)) {
26300 				/*
26301 				 * In the case of TCP endpoint we
26302 				 * come here only for bind retries
26303 				 */
26304 				ASSERT(ipsq != NULL);
26305 				CONN_INC_REF(connp);
26306 				squeue_fill(connp->conn_sqp, mp,
26307 				    ip_resume_tcp_bind, connp,
26308 				    SQTAG_BIND_RETRY);
26309 				return;
26310 			} else if (IPCL_IS_UDP(connp)) {
26311 				/*
26312 				 * In the case of UDP endpoint we
26313 				 * come here only for bind retries
26314 				 */
26315 				ASSERT(ipsq != NULL);
26316 				udp_resume_bind(connp, mp);
26317 				return;
26318 			}
26319 			qreply(q, mp);
26320 			CONN_OPER_PENDING_DONE(connp);
26321 			return;
26322 		}
26323 		case T_SVR4_OPTMGMT_REQ:
26324 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
26325 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
26326 
26327 			ASSERT(connp != NULL);
26328 			if (!snmpcom_req(q, mp, ip_snmp_set,
26329 			    ip_snmp_get, cr)) {
26330 				/*
26331 				 * Call svr4_optcom_req so that it can
26332 				 * generate the ack. We don't come here
26333 				 * if this operation is being restarted.
26334 				 * ip_restart_optmgmt will drop the conn ref.
26335 				 * In the case of ipsec option after the ipsec
26336 				 * load is complete conn_restart_ipsec_waiter
26337 				 * drops the conn ref.
26338 				 */
26339 				ASSERT(ipsq == NULL);
26340 				CONN_INC_REF(connp);
26341 				if (ip_check_for_ipsec_opt(q, mp))
26342 					return;
26343 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
26344 				if (err != EINPROGRESS) {
26345 					/* Operation is done */
26346 					CONN_OPER_PENDING_DONE(connp);
26347 				}
26348 			}
26349 			return;
26350 		case T_OPTMGMT_REQ:
26351 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
26352 			/*
26353 			 * Note: No snmpcom_req support through new
26354 			 * T_OPTMGMT_REQ.
26355 			 * Call tpi_optcom_req so that it can
26356 			 * generate the ack.
26357 			 */
26358 			ASSERT(connp != NULL);
26359 			ASSERT(ipsq == NULL);
26360 			/*
26361 			 * We don't come here for restart. ip_restart_optmgmt
26362 			 * will drop the conn ref. In the case of ipsec option
26363 			 * after the ipsec load is complete
26364 			 * conn_restart_ipsec_waiter drops the conn ref.
26365 			 */
26366 			CONN_INC_REF(connp);
26367 			if (ip_check_for_ipsec_opt(q, mp))
26368 				return;
26369 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
26370 			if (err != EINPROGRESS) {
26371 				/* Operation is done */
26372 				CONN_OPER_PENDING_DONE(connp);
26373 			}
26374 			return;
26375 		case T_UNBIND_REQ:
26376 			mp = ip_unbind(q, mp);
26377 			qreply(q, mp);
26378 			return;
26379 		default:
26380 			/*
26381 			 * Have to drop any DLPI messages coming down from
26382 			 * arp (such as an info_req which would cause ip
26383 			 * to receive an extra info_ack if it was passed
26384 			 * through.
26385 			 */
26386 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
26387 			    (int)*(uint_t *)mp->b_rptr));
26388 			freemsg(mp);
26389 			return;
26390 		}
26391 		/* NOTREACHED */
26392 	case IRE_DB_TYPE: {
26393 		nce_t		*nce;
26394 		ill_t		*ill;
26395 		in6_addr_t	gw_addr_v6;
26396 
26397 
26398 		/*
26399 		 * This is a response back from a resolver.  It
26400 		 * consists of a message chain containing:
26401 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
26402 		 * The IRE_MBLK is the one we allocated in ip_newroute.
26403 		 * The LL_HDR_MBLK is the DLPI header to use to get
26404 		 * the attached packet, and subsequent ones for the
26405 		 * same destination, transmitted.
26406 		 */
26407 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
26408 			break;
26409 		/*
26410 		 * First, check to make sure the resolution succeeded.
26411 		 * If it failed, the second mblk will be empty.
26412 		 * If it is, free the chain, dropping the packet.
26413 		 * (We must ire_delete the ire; that frees the ire mblk)
26414 		 * We're doing this now to support PVCs for ATM; it's
26415 		 * a partial xresolv implementation. When we fully implement
26416 		 * xresolv interfaces, instead of freeing everything here
26417 		 * we'll initiate neighbor discovery.
26418 		 *
26419 		 * For v4 (ARP and other external resolvers) the resolver
26420 		 * frees the message, so no check is needed. This check
26421 		 * is required, though, for a full xresolve implementation.
26422 		 * Including this code here now both shows how external
26423 		 * resolvers can NACK a resolution request using an
26424 		 * existing design that has no specific provisions for NACKs,
26425 		 * and also takes into account that the current non-ARP
26426 		 * external resolver has been coded to use this method of
26427 		 * NACKing for all IPv6 (xresolv) cases,
26428 		 * whether our xresolv implementation is complete or not.
26429 		 *
26430 		 */
26431 		ire = (ire_t *)mp->b_rptr;
26432 		ill = ire_to_ill(ire);
26433 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26434 		if (mp1->b_rptr == mp1->b_wptr) {
26435 			if (ire->ire_ipversion == IPV6_VERSION) {
26436 				/*
26437 				 * XRESOLV interface.
26438 				 */
26439 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
26440 				mutex_enter(&ire->ire_lock);
26441 				gw_addr_v6 = ire->ire_gateway_addr_v6;
26442 				mutex_exit(&ire->ire_lock);
26443 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26444 					nce = ndp_lookup_v6(ill,
26445 					    &ire->ire_addr_v6, B_FALSE);
26446 				} else {
26447 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
26448 					    B_FALSE);
26449 				}
26450 				if (nce != NULL) {
26451 					nce_resolv_failed(nce);
26452 					ndp_delete(nce);
26453 					NCE_REFRELE(nce);
26454 				}
26455 			}
26456 			mp->b_cont = NULL;
26457 			freemsg(mp1);		/* frees the pkt as well */
26458 			ASSERT(ire->ire_nce == NULL);
26459 			ire_delete((ire_t *)mp->b_rptr);
26460 			return;
26461 		}
26462 
26463 		/*
26464 		 * Split them into IRE_MBLK and pkt and feed it into
26465 		 * ire_add_then_send. Then in ire_add_then_send
26466 		 * the IRE will be added, and then the packet will be
26467 		 * run back through ip_wput. This time it will make
26468 		 * it to the wire.
26469 		 */
26470 		mp->b_cont = NULL;
26471 		mp = mp1->b_cont;		/* now, mp points to pkt */
26472 		mp1->b_cont = NULL;
26473 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
26474 		if (ire->ire_ipversion == IPV6_VERSION) {
26475 			/*
26476 			 * XRESOLV interface. Find the nce and put a copy
26477 			 * of the dl_unitdata_req in nce_res_mp
26478 			 */
26479 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
26480 			mutex_enter(&ire->ire_lock);
26481 			gw_addr_v6 = ire->ire_gateway_addr_v6;
26482 			mutex_exit(&ire->ire_lock);
26483 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26484 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
26485 				    B_FALSE);
26486 			} else {
26487 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
26488 			}
26489 			if (nce != NULL) {
26490 				/*
26491 				 * We have to protect nce_res_mp here
26492 				 * from being accessed by other threads
26493 				 * while we change the mblk pointer.
26494 				 * Other functions will also lock the nce when
26495 				 * accessing nce_res_mp.
26496 				 *
26497 				 * The reason we change the mblk pointer
26498 				 * here rather than copying the resolved address
26499 				 * into the template is that, unlike with
26500 				 * ethernet, we have no guarantee that the
26501 				 * resolved address length will be
26502 				 * smaller than or equal to the lla length
26503 				 * with which the template was allocated,
26504 				 * (for ethernet, they're equal)
26505 				 * so we have to use the actual resolved
26506 				 * address mblk - which holds the real
26507 				 * dl_unitdata_req with the resolved address.
26508 				 *
26509 				 * Doing this is the same behavior as was
26510 				 * previously used in the v4 ARP case.
26511 				 */
26512 				mutex_enter(&nce->nce_lock);
26513 				if (nce->nce_res_mp != NULL)
26514 					freemsg(nce->nce_res_mp);
26515 				nce->nce_res_mp = mp1;
26516 				mutex_exit(&nce->nce_lock);
26517 				/*
26518 				 * We do a fastpath probe here because
26519 				 * we have resolved the address without
26520 				 * using Neighbor Discovery.
26521 				 * In the non-XRESOLV v6 case, the fastpath
26522 				 * probe is done right after neighbor
26523 				 * discovery completes.
26524 				 */
26525 				if (nce->nce_res_mp != NULL) {
26526 					int res;
26527 					nce_fastpath_list_add(nce);
26528 					res = ill_fastpath_probe(ill,
26529 					    nce->nce_res_mp);
26530 					if (res != 0 && res != EAGAIN)
26531 						nce_fastpath_list_delete(nce);
26532 				}
26533 
26534 				ire_add_then_send(q, ire, mp);
26535 				/*
26536 				 * Now we have to clean out any packets
26537 				 * that may have been queued on the nce
26538 				 * while it was waiting for address resolution
26539 				 * to complete.
26540 				 */
26541 				mutex_enter(&nce->nce_lock);
26542 				mp1 = nce->nce_qd_mp;
26543 				nce->nce_qd_mp = NULL;
26544 				mutex_exit(&nce->nce_lock);
26545 				while (mp1 != NULL) {
26546 					mblk_t *nxt_mp;
26547 					queue_t *fwdq = NULL;
26548 					ill_t   *inbound_ill;
26549 					uint_t ifindex;
26550 
26551 					nxt_mp = mp1->b_next;
26552 					mp1->b_next = NULL;
26553 					/*
26554 					 * Retrieve ifindex stored in
26555 					 * ip_rput_data_v6()
26556 					 */
26557 					ifindex =
26558 					    (uint_t)(uintptr_t)mp1->b_prev;
26559 					inbound_ill =
26560 						ill_lookup_on_ifindex(ifindex,
26561 						    B_TRUE, NULL, NULL, NULL,
26562 						    NULL);
26563 					mp1->b_prev = NULL;
26564 					if (inbound_ill != NULL)
26565 						fwdq = inbound_ill->ill_rq;
26566 
26567 					if (fwdq != NULL) {
26568 						put(fwdq, mp1);
26569 						ill_refrele(inbound_ill);
26570 					} else
26571 						put(WR(ill->ill_rq), mp1);
26572 					mp1 = nxt_mp;
26573 				}
26574 				NCE_REFRELE(nce);
26575 			} else {	/* nce is NULL; clean up */
26576 				ire_delete(ire);
26577 				freemsg(mp);
26578 				freemsg(mp1);
26579 				return;
26580 			}
26581 		} else {
26582 			nce_t *arpce;
26583 			/*
26584 			 * Link layer resolution succeeded. Recompute the
26585 			 * ire_nce.
26586 			 */
26587 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
26588 			if ((arpce = ndp_lookup_v4(ill,
26589 			    (ire->ire_gateway_addr != INADDR_ANY ?
26590 			    &ire->ire_gateway_addr : &ire->ire_addr),
26591 			    B_FALSE)) == NULL) {
26592 				freeb(ire->ire_mp);
26593 				freeb(mp1);
26594 				freemsg(mp);
26595 				return;
26596 			}
26597 			mutex_enter(&arpce->nce_lock);
26598 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
26599 			if (arpce->nce_state == ND_REACHABLE) {
26600 				/*
26601 				 * Someone resolved this before us;
26602 				 * cleanup the res_mp. Since ire has
26603 				 * not been added yet, the call to ire_add_v4
26604 				 * from ire_add_then_send (when a dup is
26605 				 * detected) will clean up the ire.
26606 				 */
26607 				freeb(mp1);
26608 			} else {
26609 				if (arpce->nce_res_mp != NULL)
26610 					freemsg(arpce->nce_res_mp);
26611 				arpce->nce_res_mp = mp1;
26612 				arpce->nce_state = ND_REACHABLE;
26613 			}
26614 			mutex_exit(&arpce->nce_lock);
26615 			if (ire->ire_marks & IRE_MARK_NOADD) {
26616 				/*
26617 				 * this ire will not be added to the ire
26618 				 * cache table, so we can set the ire_nce
26619 				 * here, as there are no atomicity constraints.
26620 				 */
26621 				ire->ire_nce = arpce;
26622 				/*
26623 				 * We are associating this nce with the ire
26624 				 * so change the nce ref taken in
26625 				 * ndp_lookup_v4() from
26626 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
26627 				 */
26628 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
26629 			} else {
26630 				NCE_REFRELE(arpce);
26631 			}
26632 			ire_add_then_send(q, ire, mp);
26633 		}
26634 		return;	/* All is well, the packet has been sent. */
26635 	}
26636 	case IRE_ARPRESOLVE_TYPE: {
26637 
26638 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
26639 			break;
26640 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26641 		mp->b_cont = NULL;
26642 		/*
26643 		 * First, check to make sure the resolution succeeded.
26644 		 * If it failed, the second mblk will be empty.
26645 		 */
26646 		if (mp1->b_rptr == mp1->b_wptr) {
26647 			/* cleanup  the incomplete ire, free queued packets */
26648 			freemsg(mp); /* fake ire */
26649 			freeb(mp1);  /* dl_unitdata response */
26650 			return;
26651 		}
26652 
26653 		/*
26654 		 * update any incomplete nce_t found. we lookup the ctable
26655 		 * and find the nce from the ire->ire_nce because we need
26656 		 * to pass the ire to ip_xmit_v4 later, and can find both
26657 		 * ire and nce in one lookup from the ctable.
26658 		 */
26659 		fake_ire = (ire_t *)mp->b_rptr;
26660 		/*
26661 		 * By the time we come back here from ARP
26662 		 * the logical outgoing interface  of the incomplete ire
26663 		 * we added in ire_forward could have disappeared,
26664 		 * causing the incomplete ire to also have
26665 		 * dissapeared. So we need to retreive the
26666 		 * proper ipif for the ire  before looking
26667 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
26668 		 */
26669 		ill = q->q_ptr;
26670 
26671 		/* Get the outgoing ipif */
26672 		mutex_enter(&ill->ill_lock);
26673 		if (ill->ill_state_flags & ILL_CONDEMNED) {
26674 			mutex_exit(&ill->ill_lock);
26675 			freemsg(mp); /* fake ire */
26676 			freeb(mp1);  /* dl_unitdata response */
26677 			return;
26678 		}
26679 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
26680 
26681 		if (ipif == NULL) {
26682 			mutex_exit(&ill->ill_lock);
26683 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
26684 			freemsg(mp);
26685 			freeb(mp1);
26686 			return;
26687 		}
26688 		ipif_refhold_locked(ipif);
26689 		mutex_exit(&ill->ill_lock);
26690 		ire = ire_ctable_lookup(fake_ire->ire_addr,
26691 		    fake_ire->ire_gateway_addr, IRE_CACHE,
26692 		    ipif, fake_ire->ire_zoneid, NULL,
26693 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
26694 		ipif_refrele(ipif);
26695 		if (ire == NULL) {
26696 			/*
26697 			 * no ire was found; check if there is an nce
26698 			 * for this lookup; if it has no ire's pointing at it
26699 			 * cleanup.
26700 			 */
26701 			if ((nce = ndp_lookup_v4(ill,
26702 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
26703 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
26704 			    B_FALSE)) != NULL) {
26705 				/*
26706 				 * cleanup: just reset nce.
26707 				 * We check for refcnt 2 (one for the nce
26708 				 * hash list + 1 for the ref taken by
26709 				 * ndp_lookup_v4) to ensure that there are
26710 				 * no ire's pointing at the nce.
26711 				 */
26712 				if (nce->nce_refcnt == 2) {
26713 					nce = nce_reinit(nce);
26714 				}
26715 				if (nce != NULL)
26716 					NCE_REFRELE(nce);
26717 			}
26718 			freeb(mp1);  /* dl_unitdata response */
26719 			freemsg(mp); /* fake ire */
26720 			return;
26721 		}
26722 		nce = ire->ire_nce;
26723 		DTRACE_PROBE2(ire__arpresolve__type,
26724 		    ire_t *, ire, nce_t *, nce);
26725 		ASSERT(nce->nce_state != ND_INITIAL);
26726 		mutex_enter(&nce->nce_lock);
26727 		nce->nce_last = TICK_TO_MSEC(lbolt64);
26728 		if (nce->nce_state == ND_REACHABLE) {
26729 			/*
26730 			 * Someone resolved this before us;
26731 			 * our response is not needed any more.
26732 			 */
26733 			mutex_exit(&nce->nce_lock);
26734 			freeb(mp1);  /* dl_unitdata response */
26735 		} else {
26736 			if (nce->nce_res_mp != NULL) {
26737 				freemsg(nce->nce_res_mp);
26738 				/* existing dl_unitdata template */
26739 			}
26740 			nce->nce_res_mp = mp1;
26741 			nce->nce_state = ND_REACHABLE;
26742 			mutex_exit(&nce->nce_lock);
26743 			ire_fastpath(ire);
26744 		}
26745 		/*
26746 		 * The cached nce_t has been updated to be reachable;
26747 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
26748 		 */
26749 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
26750 		freemsg(mp);
26751 		/*
26752 		 * send out queued packets.
26753 		 */
26754 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26755 
26756 		IRE_REFRELE(ire);
26757 		return;
26758 	}
26759 	default:
26760 		break;
26761 	}
26762 	if (q->q_next) {
26763 		putnext(q, mp);
26764 	} else
26765 		freemsg(mp);
26766 }
26767 
26768 /*
26769  * Process IP options in an outbound packet.  Modify the destination if there
26770  * is a source route option.
26771  * Returns non-zero if something fails in which case an ICMP error has been
26772  * sent and mp freed.
26773  */
26774 static int
26775 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
26776     boolean_t mctl_present, zoneid_t zoneid)
26777 {
26778 	ipoptp_t	opts;
26779 	uchar_t		*opt;
26780 	uint8_t		optval;
26781 	uint8_t		optlen;
26782 	ipaddr_t	dst;
26783 	intptr_t	code = 0;
26784 	mblk_t		*mp;
26785 	ire_t		*ire = NULL;
26786 
26787 	ip2dbg(("ip_wput_options\n"));
26788 	mp = ipsec_mp;
26789 	if (mctl_present) {
26790 		mp = ipsec_mp->b_cont;
26791 	}
26792 
26793 	dst = ipha->ipha_dst;
26794 	for (optval = ipoptp_first(&opts, ipha);
26795 	    optval != IPOPT_EOL;
26796 	    optval = ipoptp_next(&opts)) {
26797 		opt = opts.ipoptp_cur;
26798 		optlen = opts.ipoptp_len;
26799 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
26800 		    optval, optlen));
26801 		switch (optval) {
26802 			uint32_t off;
26803 		case IPOPT_SSRR:
26804 		case IPOPT_LSRR:
26805 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26806 				ip1dbg((
26807 				    "ip_wput_options: bad option offset\n"));
26808 				code = (char *)&opt[IPOPT_OLEN] -
26809 				    (char *)ipha;
26810 				goto param_prob;
26811 			}
26812 			off = opt[IPOPT_OFFSET];
26813 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
26814 			    ntohl(dst)));
26815 			/*
26816 			 * For strict: verify that dst is directly
26817 			 * reachable.
26818 			 */
26819 			if (optval == IPOPT_SSRR) {
26820 				ire = ire_ftable_lookup(dst, 0, 0,
26821 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
26822 				    MBLK_GETLABEL(mp),
26823 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
26824 				if (ire == NULL) {
26825 					ip1dbg(("ip_wput_options: SSRR not"
26826 					    " directly reachable: 0x%x\n",
26827 					    ntohl(dst)));
26828 					goto bad_src_route;
26829 				}
26830 				ire_refrele(ire);
26831 			}
26832 			break;
26833 		case IPOPT_RR:
26834 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26835 				ip1dbg((
26836 				    "ip_wput_options: bad option offset\n"));
26837 				code = (char *)&opt[IPOPT_OLEN] -
26838 				    (char *)ipha;
26839 				goto param_prob;
26840 			}
26841 			break;
26842 		case IPOPT_TS:
26843 			/*
26844 			 * Verify that length >=5 and that there is either
26845 			 * room for another timestamp or that the overflow
26846 			 * counter is not maxed out.
26847 			 */
26848 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
26849 			if (optlen < IPOPT_MINLEN_IT) {
26850 				goto param_prob;
26851 			}
26852 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26853 				ip1dbg((
26854 				    "ip_wput_options: bad option offset\n"));
26855 				code = (char *)&opt[IPOPT_OFFSET] -
26856 				    (char *)ipha;
26857 				goto param_prob;
26858 			}
26859 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
26860 			case IPOPT_TS_TSONLY:
26861 				off = IPOPT_TS_TIMELEN;
26862 				break;
26863 			case IPOPT_TS_TSANDADDR:
26864 			case IPOPT_TS_PRESPEC:
26865 			case IPOPT_TS_PRESPEC_RFC791:
26866 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
26867 				break;
26868 			default:
26869 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
26870 				    (char *)ipha;
26871 				goto param_prob;
26872 			}
26873 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
26874 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
26875 				/*
26876 				 * No room and the overflow counter is 15
26877 				 * already.
26878 				 */
26879 				goto param_prob;
26880 			}
26881 			break;
26882 		}
26883 	}
26884 
26885 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
26886 		return (0);
26887 
26888 	ip1dbg(("ip_wput_options: error processing IP options."));
26889 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
26890 
26891 param_prob:
26892 	/*
26893 	 * Since ip_wput() isn't close to finished, we fill
26894 	 * in enough of the header for credible error reporting.
26895 	 */
26896 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
26897 		/* Failed */
26898 		freemsg(ipsec_mp);
26899 		return (-1);
26900 	}
26901 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid);
26902 	return (-1);
26903 
26904 bad_src_route:
26905 	/*
26906 	 * Since ip_wput() isn't close to finished, we fill
26907 	 * in enough of the header for credible error reporting.
26908 	 */
26909 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
26910 		/* Failed */
26911 		freemsg(ipsec_mp);
26912 		return (-1);
26913 	}
26914 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
26915 	return (-1);
26916 }
26917 
26918 /*
26919  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
26920  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
26921  * thru /etc/system.
26922  */
26923 #define	CONN_MAXDRAINCNT	64
26924 
26925 static void
26926 conn_drain_init(void)
26927 {
26928 	int i;
26929 
26930 	conn_drain_list_cnt = conn_drain_nthreads;
26931 
26932 	if ((conn_drain_list_cnt == 0) ||
26933 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
26934 		/*
26935 		 * Default value of the number of drainers is the
26936 		 * number of cpus, subject to maximum of 8 drainers.
26937 		 */
26938 		if (boot_max_ncpus != -1)
26939 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
26940 		else
26941 			conn_drain_list_cnt = MIN(max_ncpus, 8);
26942 	}
26943 
26944 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
26945 	    KM_SLEEP);
26946 
26947 	for (i = 0; i < conn_drain_list_cnt; i++) {
26948 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
26949 		    MUTEX_DEFAULT, NULL);
26950 	}
26951 }
26952 
26953 static void
26954 conn_drain_fini(void)
26955 {
26956 	int i;
26957 
26958 	for (i = 0; i < conn_drain_list_cnt; i++)
26959 		mutex_destroy(&conn_drain_list[i].idl_lock);
26960 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
26961 	conn_drain_list = NULL;
26962 }
26963 
26964 /*
26965  * Note: For an overview of how flowcontrol is handled in IP please see the
26966  * IP Flowcontrol notes at the top of this file.
26967  *
26968  * Flow control has blocked us from proceeding. Insert the given conn in one
26969  * of the conn drain lists. These conn wq's will be qenabled later on when
26970  * STREAMS flow control does a backenable. conn_walk_drain will enable
26971  * the first conn in each of these drain lists. Each of these qenabled conns
26972  * in turn enables the next in the list, after it runs, or when it closes,
26973  * thus sustaining the drain process.
26974  *
26975  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
26976  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
26977  * running at any time, on a given conn, since there can be only 1 service proc
26978  * running on a queue at any time.
26979  */
26980 void
26981 conn_drain_insert(conn_t *connp)
26982 {
26983 	idl_t	*idl;
26984 	uint_t	index;
26985 
26986 	mutex_enter(&connp->conn_lock);
26987 	if (connp->conn_state_flags & CONN_CLOSING) {
26988 		/*
26989 		 * The conn is closing as a result of which CONN_CLOSING
26990 		 * is set. Return.
26991 		 */
26992 		mutex_exit(&connp->conn_lock);
26993 		return;
26994 	} else if (connp->conn_idl == NULL) {
26995 		/*
26996 		 * Assign the next drain list round robin. We dont' use
26997 		 * a lock, and thus it may not be strictly round robin.
26998 		 * Atomicity of load/stores is enough to make sure that
26999 		 * conn_drain_list_index is always within bounds.
27000 		 */
27001 		index = conn_drain_list_index;
27002 		ASSERT(index < conn_drain_list_cnt);
27003 		connp->conn_idl = &conn_drain_list[index];
27004 		index++;
27005 		if (index == conn_drain_list_cnt)
27006 			index = 0;
27007 		conn_drain_list_index = index;
27008 	}
27009 	mutex_exit(&connp->conn_lock);
27010 
27011 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27012 	if ((connp->conn_drain_prev != NULL) ||
27013 	    (connp->conn_state_flags & CONN_CLOSING)) {
27014 		/*
27015 		 * The conn is already in the drain list, OR
27016 		 * the conn is closing. We need to check again for
27017 		 * the closing case again since close can happen
27018 		 * after we drop the conn_lock, and before we
27019 		 * acquire the CONN_DRAIN_LIST_LOCK.
27020 		 */
27021 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27022 		return;
27023 	} else {
27024 		idl = connp->conn_idl;
27025 	}
27026 
27027 	/*
27028 	 * The conn is not in the drain list. Insert it at the
27029 	 * tail of the drain list. The drain list is circular
27030 	 * and doubly linked. idl_conn points to the 1st element
27031 	 * in the list.
27032 	 */
27033 	if (idl->idl_conn == NULL) {
27034 		idl->idl_conn = connp;
27035 		connp->conn_drain_next = connp;
27036 		connp->conn_drain_prev = connp;
27037 	} else {
27038 		conn_t *head = idl->idl_conn;
27039 
27040 		connp->conn_drain_next = head;
27041 		connp->conn_drain_prev = head->conn_drain_prev;
27042 		head->conn_drain_prev->conn_drain_next = connp;
27043 		head->conn_drain_prev = connp;
27044 	}
27045 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27046 }
27047 
27048 /*
27049  * This conn is closing, and we are called from ip_close. OR
27050  * This conn has been serviced by ip_wsrv, and we need to do the tail
27051  * processing.
27052  * If this conn is part of the drain list, we may need to sustain the drain
27053  * process by qenabling the next conn in the drain list. We may also need to
27054  * remove this conn from the list, if it is done.
27055  */
27056 static void
27057 conn_drain_tail(conn_t *connp, boolean_t closing)
27058 {
27059 	idl_t *idl;
27060 
27061 	/*
27062 	 * connp->conn_idl is stable at this point, and no lock is needed
27063 	 * to check it. If we are called from ip_close, close has already
27064 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27065 	 * called us only because conn_idl is non-null. If we are called thru
27066 	 * service, conn_idl could be null, but it cannot change because
27067 	 * service is single-threaded per queue, and there cannot be another
27068 	 * instance of service trying to call conn_drain_insert on this conn
27069 	 * now.
27070 	 */
27071 	ASSERT(!closing || (connp->conn_idl != NULL));
27072 
27073 	/*
27074 	 * If connp->conn_idl is null, the conn has not been inserted into any
27075 	 * drain list even once since creation of the conn. Just return.
27076 	 */
27077 	if (connp->conn_idl == NULL)
27078 		return;
27079 
27080 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27081 
27082 	if (connp->conn_drain_prev == NULL) {
27083 		/* This conn is currently not in the drain list.  */
27084 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27085 		return;
27086 	}
27087 	idl = connp->conn_idl;
27088 	if (idl->idl_conn_draining == connp) {
27089 		/*
27090 		 * This conn is the current drainer. If this is the last conn
27091 		 * in the drain list, we need to do more checks, in the 'if'
27092 		 * below. Otherwwise we need to just qenable the next conn,
27093 		 * to sustain the draining, and is handled in the 'else'
27094 		 * below.
27095 		 */
27096 		if (connp->conn_drain_next == idl->idl_conn) {
27097 			/*
27098 			 * This conn is the last in this list. This round
27099 			 * of draining is complete. If idl_repeat is set,
27100 			 * it means another flow enabling has happened from
27101 			 * the driver/streams and we need to another round
27102 			 * of draining.
27103 			 * If there are more than 2 conns in the drain list,
27104 			 * do a left rotate by 1, so that all conns except the
27105 			 * conn at the head move towards the head by 1, and the
27106 			 * the conn at the head goes to the tail. This attempts
27107 			 * a more even share for all queues that are being
27108 			 * drained.
27109 			 */
27110 			if ((connp->conn_drain_next != connp) &&
27111 			    (idl->idl_conn->conn_drain_next != connp)) {
27112 				idl->idl_conn = idl->idl_conn->conn_drain_next;
27113 			}
27114 			if (idl->idl_repeat) {
27115 				qenable(idl->idl_conn->conn_wq);
27116 				idl->idl_conn_draining = idl->idl_conn;
27117 				idl->idl_repeat = 0;
27118 			} else {
27119 				idl->idl_conn_draining = NULL;
27120 			}
27121 		} else {
27122 			/*
27123 			 * If the next queue that we are now qenable'ing,
27124 			 * is closing, it will remove itself from this list
27125 			 * and qenable the subsequent queue in ip_close().
27126 			 * Serialization is acheived thru idl_lock.
27127 			 */
27128 			qenable(connp->conn_drain_next->conn_wq);
27129 			idl->idl_conn_draining = connp->conn_drain_next;
27130 		}
27131 	}
27132 	if (!connp->conn_did_putbq || closing) {
27133 		/*
27134 		 * Remove ourself from the drain list, if we did not do
27135 		 * a putbq, or if the conn is closing.
27136 		 * Note: It is possible that q->q_first is non-null. It means
27137 		 * that these messages landed after we did a enableok() in
27138 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
27139 		 * service them.
27140 		 */
27141 		if (connp->conn_drain_next == connp) {
27142 			/* Singleton in the list */
27143 			ASSERT(connp->conn_drain_prev == connp);
27144 			idl->idl_conn = NULL;
27145 			idl->idl_conn_draining = NULL;
27146 		} else {
27147 			connp->conn_drain_prev->conn_drain_next =
27148 			    connp->conn_drain_next;
27149 			connp->conn_drain_next->conn_drain_prev =
27150 			    connp->conn_drain_prev;
27151 			if (idl->idl_conn == connp)
27152 				idl->idl_conn = connp->conn_drain_next;
27153 			ASSERT(idl->idl_conn_draining != connp);
27154 
27155 		}
27156 		connp->conn_drain_next = NULL;
27157 		connp->conn_drain_prev = NULL;
27158 	}
27159 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27160 }
27161 
27162 /*
27163  * Write service routine. Shared perimeter entry point.
27164  * ip_wsrv can be called in any of the following ways.
27165  * 1. The device queue's messages has fallen below the low water mark
27166  *    and STREAMS has backenabled the ill_wq. We walk thru all the
27167  *    the drain lists and backenable the first conn in each list.
27168  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
27169  *    qenabled non-tcp upper layers. We start dequeing messages and call
27170  *    ip_wput for each message.
27171  */
27172 
27173 void
27174 ip_wsrv(queue_t *q)
27175 {
27176 	conn_t	*connp;
27177 	ill_t	*ill;
27178 	mblk_t	*mp;
27179 
27180 	if (q->q_next) {
27181 		ill = (ill_t *)q->q_ptr;
27182 		if (ill->ill_state_flags == 0) {
27183 			/*
27184 			 * The device flow control has opened up.
27185 			 * Walk through conn drain lists and qenable the
27186 			 * first conn in each list. This makes sense only
27187 			 * if the stream is fully plumbed and setup.
27188 			 * Hence the if check above.
27189 			 */
27190 			ip1dbg(("ip_wsrv: walking\n"));
27191 			conn_walk_drain();
27192 		}
27193 		return;
27194 	}
27195 
27196 	connp = Q_TO_CONN(q);
27197 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
27198 
27199 	/*
27200 	 * 1. Set conn_draining flag to signal that service is active.
27201 	 *
27202 	 * 2. ip_output determines whether it has been called from service,
27203 	 *    based on the last parameter. If it is IP_WSRV it concludes it
27204 	 *    has been called from service.
27205 	 *
27206 	 * 3. Message ordering is preserved by the following logic.
27207 	 *    i. A directly called ip_output (i.e. not thru service) will queue
27208 	 *    the message at the tail, if conn_draining is set (i.e. service
27209 	 *    is running) or if q->q_first is non-null.
27210 	 *
27211 	 *    ii. If ip_output is called from service, and if ip_output cannot
27212 	 *    putnext due to flow control, it does a putbq.
27213 	 *
27214 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
27215 	 *    (causing an infinite loop).
27216 	 */
27217 	ASSERT(!connp->conn_did_putbq);
27218 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
27219 		connp->conn_draining = 1;
27220 		noenable(q);
27221 		while ((mp = getq(q)) != NULL) {
27222 			ASSERT(CONN_Q(q));
27223 
27224 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
27225 			if (connp->conn_did_putbq) {
27226 				/* ip_wput did a putbq */
27227 				break;
27228 			}
27229 		}
27230 		/*
27231 		 * At this point, a thread coming down from top, calling
27232 		 * ip_wput, may end up queueing the message. We have not yet
27233 		 * enabled the queue, so ip_wsrv won't be called again.
27234 		 * To avoid this race, check q->q_first again (in the loop)
27235 		 * If the other thread queued the message before we call
27236 		 * enableok(), we will catch it in the q->q_first check.
27237 		 * If the other thread queues the message after we call
27238 		 * enableok(), ip_wsrv will be called again by STREAMS.
27239 		 */
27240 		connp->conn_draining = 0;
27241 		enableok(q);
27242 	}
27243 
27244 	/* Enable the next conn for draining */
27245 	conn_drain_tail(connp, B_FALSE);
27246 
27247 	connp->conn_did_putbq = 0;
27248 }
27249 
27250 /*
27251  * Walk the list of all conn's calling the function provided with the
27252  * specified argument for each.	 Note that this only walks conn's that
27253  * have been bound.
27254  * Applies to both IPv4 and IPv6.
27255  */
27256 static void
27257 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
27258 {
27259 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
27260 	    func, arg, zoneid);
27261 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
27262 	    func, arg, zoneid);
27263 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
27264 	    func, arg, zoneid);
27265 	conn_walk_fanout_table(ipcl_proto_fanout,
27266 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
27267 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
27268 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
27269 }
27270 
27271 /*
27272  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
27273  * of conns that need to be drained, check if drain is already in progress.
27274  * If so set the idl_repeat bit, indicating that the last conn in the list
27275  * needs to reinitiate the drain once again, for the list. If drain is not
27276  * in progress for the list, initiate the draining, by qenabling the 1st
27277  * conn in the list. The drain is self-sustaining, each qenabled conn will
27278  * in turn qenable the next conn, when it is done/blocked/closing.
27279  */
27280 static void
27281 conn_walk_drain(void)
27282 {
27283 	int i;
27284 	idl_t *idl;
27285 
27286 	IP_STAT(ip_conn_walk_drain);
27287 
27288 	for (i = 0; i < conn_drain_list_cnt; i++) {
27289 		idl = &conn_drain_list[i];
27290 		mutex_enter(&idl->idl_lock);
27291 		if (idl->idl_conn == NULL) {
27292 			mutex_exit(&idl->idl_lock);
27293 			continue;
27294 		}
27295 		/*
27296 		 * If this list is not being drained currently by
27297 		 * an ip_wsrv thread, start the process.
27298 		 */
27299 		if (idl->idl_conn_draining == NULL) {
27300 			ASSERT(idl->idl_repeat == 0);
27301 			qenable(idl->idl_conn->conn_wq);
27302 			idl->idl_conn_draining = idl->idl_conn;
27303 		} else {
27304 			idl->idl_repeat = 1;
27305 		}
27306 		mutex_exit(&idl->idl_lock);
27307 	}
27308 }
27309 
27310 /*
27311  * Walk an conn hash table of `count' buckets, calling func for each entry.
27312  */
27313 static void
27314 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
27315     zoneid_t zoneid)
27316 {
27317 	conn_t	*connp;
27318 
27319 	while (count-- > 0) {
27320 		mutex_enter(&connfp->connf_lock);
27321 		for (connp = connfp->connf_head; connp != NULL;
27322 		    connp = connp->conn_next) {
27323 			if (zoneid == GLOBAL_ZONEID ||
27324 			    zoneid == connp->conn_zoneid) {
27325 				CONN_INC_REF(connp);
27326 				mutex_exit(&connfp->connf_lock);
27327 				(*func)(connp, arg);
27328 				mutex_enter(&connfp->connf_lock);
27329 				CONN_DEC_REF(connp);
27330 			}
27331 		}
27332 		mutex_exit(&connfp->connf_lock);
27333 		connfp++;
27334 	}
27335 }
27336 
27337 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
27338 static void
27339 conn_report1(conn_t *connp, void *mp)
27340 {
27341 	char	buf1[INET6_ADDRSTRLEN];
27342 	char	buf2[INET6_ADDRSTRLEN];
27343 	uint_t	print_len, buf_len;
27344 
27345 	ASSERT(connp != NULL);
27346 
27347 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
27348 	if (buf_len <= 0)
27349 		return;
27350 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
27351 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
27352 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
27353 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
27354 	    "%5d %s/%05d %s/%05d\n",
27355 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
27356 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
27357 	    buf1, connp->conn_lport,
27358 	    buf2, connp->conn_fport);
27359 	if (print_len < buf_len) {
27360 		((mblk_t *)mp)->b_wptr += print_len;
27361 	} else {
27362 		((mblk_t *)mp)->b_wptr += buf_len;
27363 	}
27364 }
27365 
27366 /*
27367  * Named Dispatch routine to produce a formatted report on all conns
27368  * that are listed in one of the fanout tables.
27369  * This report is accessed by using the ndd utility to "get" ND variable
27370  * "ip_conn_status".
27371  */
27372 /* ARGSUSED */
27373 static int
27374 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
27375 {
27376 	(void) mi_mpprintf(mp,
27377 	    "CONN      " MI_COL_HDRPAD_STR
27378 	    "rfq      " MI_COL_HDRPAD_STR
27379 	    "stq      " MI_COL_HDRPAD_STR
27380 	    " zone local                 remote");
27381 
27382 	/*
27383 	 * Because of the ndd constraint, at most we can have 64K buffer
27384 	 * to put in all conn info.  So to be more efficient, just
27385 	 * allocate a 64K buffer here, assuming we need that large buffer.
27386 	 * This should be OK as only privileged processes can do ndd /dev/ip.
27387 	 */
27388 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
27389 		/* The following may work even if we cannot get a large buf. */
27390 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
27391 		return (0);
27392 	}
27393 
27394 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
27395 	return (0);
27396 }
27397 
27398 /*
27399  * Determine if the ill and multicast aspects of that packets
27400  * "matches" the conn.
27401  */
27402 boolean_t
27403 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
27404     zoneid_t zoneid)
27405 {
27406 	ill_t *in_ill;
27407 	boolean_t found;
27408 	ipif_t *ipif;
27409 	ire_t *ire;
27410 	ipaddr_t dst, src;
27411 
27412 	dst = ipha->ipha_dst;
27413 	src = ipha->ipha_src;
27414 
27415 	/*
27416 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
27417 	 * unicast, broadcast and multicast reception to
27418 	 * conn_incoming_ill. conn_wantpacket itself is called
27419 	 * only for BROADCAST and multicast.
27420 	 *
27421 	 * 1) ip_rput supresses duplicate broadcasts if the ill
27422 	 *    is part of a group. Hence, we should be receiving
27423 	 *    just one copy of broadcast for the whole group.
27424 	 *    Thus, if it is part of the group the packet could
27425 	 *    come on any ill of the group and hence we need a
27426 	 *    match on the group. Otherwise, match on ill should
27427 	 *    be sufficient.
27428 	 *
27429 	 * 2) ip_rput does not suppress duplicate multicast packets.
27430 	 *    If there are two interfaces in a ill group and we have
27431 	 *    2 applications (conns) joined a multicast group G on
27432 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
27433 	 *    will give us two packets because we join G on both the
27434 	 *    interfaces rather than nominating just one interface
27435 	 *    for receiving multicast like broadcast above. So,
27436 	 *    we have to call ilg_lookup_ill to filter out duplicate
27437 	 *    copies, if ill is part of a group.
27438 	 */
27439 	in_ill = connp->conn_incoming_ill;
27440 	if (in_ill != NULL) {
27441 		if (in_ill->ill_group == NULL) {
27442 			if (in_ill != ill)
27443 				return (B_FALSE);
27444 		} else if (in_ill->ill_group != ill->ill_group) {
27445 			return (B_FALSE);
27446 		}
27447 	}
27448 
27449 	if (!CLASSD(dst)) {
27450 		if (IPCL_ZONE_MATCH(connp, zoneid))
27451 			return (B_TRUE);
27452 		/*
27453 		 * The conn is in a different zone; we need to check that this
27454 		 * broadcast address is configured in the application's zone and
27455 		 * on one ill in the group.
27456 		 */
27457 		ipif = ipif_get_next_ipif(NULL, ill);
27458 		if (ipif == NULL)
27459 			return (B_FALSE);
27460 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
27461 		    connp->conn_zoneid, NULL,
27462 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
27463 		ipif_refrele(ipif);
27464 		if (ire != NULL) {
27465 			ire_refrele(ire);
27466 			return (B_TRUE);
27467 		} else {
27468 			return (B_FALSE);
27469 		}
27470 	}
27471 
27472 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
27473 	    connp->conn_zoneid == zoneid) {
27474 		/*
27475 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
27476 		 * disabled, therefore we don't dispatch the multicast packet to
27477 		 * the sending zone.
27478 		 */
27479 		return (B_FALSE);
27480 	}
27481 
27482 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
27483 	    connp->conn_zoneid != zoneid) {
27484 		/*
27485 		 * Multicast packet on the loopback interface: we only match
27486 		 * conns who joined the group in the specified zone.
27487 		 */
27488 		return (B_FALSE);
27489 	}
27490 
27491 	if (connp->conn_multi_router) {
27492 		/* multicast packet and multicast router socket: send up */
27493 		return (B_TRUE);
27494 	}
27495 
27496 	mutex_enter(&connp->conn_lock);
27497 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
27498 	mutex_exit(&connp->conn_lock);
27499 	return (found);
27500 }
27501 
27502 /*
27503  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
27504  */
27505 /* ARGSUSED */
27506 static void
27507 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
27508 {
27509 	ill_t *ill = (ill_t *)q->q_ptr;
27510 	mblk_t	*mp1, *mp2;
27511 	ipif_t  *ipif;
27512 	int err = 0;
27513 	conn_t *connp = NULL;
27514 	ipsq_t	*ipsq;
27515 	arc_t	*arc;
27516 
27517 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
27518 
27519 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
27520 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
27521 
27522 	ASSERT(IAM_WRITER_ILL(ill));
27523 	mp2 = mp->b_cont;
27524 	mp->b_cont = NULL;
27525 
27526 	/*
27527 	 * We have now received the arp bringup completion message
27528 	 * from ARP. Mark the arp bringup as done. Also if the arp
27529 	 * stream has already started closing, send up the AR_ARP_CLOSING
27530 	 * ack now since ARP is waiting in close for this ack.
27531 	 */
27532 	mutex_enter(&ill->ill_lock);
27533 	ill->ill_arp_bringup_pending = 0;
27534 	if (ill->ill_arp_closing) {
27535 		mutex_exit(&ill->ill_lock);
27536 		/* Let's reuse the mp for sending the ack */
27537 		arc = (arc_t *)mp->b_rptr;
27538 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
27539 		arc->arc_cmd = AR_ARP_CLOSING;
27540 		qreply(q, mp);
27541 	} else {
27542 		mutex_exit(&ill->ill_lock);
27543 		freeb(mp);
27544 	}
27545 
27546 	/* We should have an IOCTL waiting on this. */
27547 	ipsq = ill->ill_phyint->phyint_ipsq;
27548 	ipif = ipsq->ipsq_pending_ipif;
27549 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
27550 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
27551 	if (mp1 == NULL) {
27552 		/* bringup was aborted by the user */
27553 		freemsg(mp2);
27554 		return;
27555 	}
27556 	ASSERT(connp != NULL);
27557 	q = CONNP_TO_WQ(connp);
27558 	/*
27559 	 * If the DL_BIND_REQ fails, it is noted
27560 	 * in arc_name_offset.
27561 	 */
27562 	err = *((int *)mp2->b_rptr);
27563 	if (err == 0) {
27564 		if (ipif->ipif_isv6) {
27565 			if ((err = ipif_up_done_v6(ipif)) != 0)
27566 				ip0dbg(("ip_arp_done: init failed\n"));
27567 		} else {
27568 			if ((err = ipif_up_done(ipif)) != 0)
27569 				ip0dbg(("ip_arp_done: init failed\n"));
27570 		}
27571 	} else {
27572 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
27573 	}
27574 
27575 	freemsg(mp2);
27576 
27577 	if ((err == 0) && (ill->ill_up_ipifs)) {
27578 		err = ill_up_ipifs(ill, q, mp1);
27579 		if (err == EINPROGRESS)
27580 			return;
27581 	}
27582 
27583 	if (ill->ill_up_ipifs) {
27584 		ill_group_cleanup(ill);
27585 	}
27586 
27587 	/*
27588 	 * The ioctl must complete now without EINPROGRESS
27589 	 * since ipsq_pending_mp_get has removed the ioctl mblk
27590 	 * from ipsq_pending_mp. Otherwise the ioctl will be
27591 	 * stuck for ever in the ipsq.
27592 	 */
27593 	ASSERT(err != EINPROGRESS);
27594 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
27595 }
27596 
27597 /* Allocate the private structure */
27598 static int
27599 ip_priv_alloc(void **bufp)
27600 {
27601 	void	*buf;
27602 
27603 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
27604 		return (ENOMEM);
27605 
27606 	*bufp = buf;
27607 	return (0);
27608 }
27609 
27610 /* Function to delete the private structure */
27611 void
27612 ip_priv_free(void *buf)
27613 {
27614 	ASSERT(buf != NULL);
27615 	kmem_free(buf, sizeof (ip_priv_t));
27616 }
27617 
27618 /*
27619  * The entry point for IPPF processing.
27620  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
27621  * routine just returns.
27622  *
27623  * When called, ip_process generates an ipp_packet_t structure
27624  * which holds the state information for this packet and invokes the
27625  * the classifier (via ipp_packet_process). The classification, depending on
27626  * configured filters, results in a list of actions for this packet. Invoking
27627  * an action may cause the packet to be dropped, in which case the resulting
27628  * mblk (*mpp) is NULL. proc indicates the callout position for
27629  * this packet and ill_index is the interface this packet on or will leave
27630  * on (inbound and outbound resp.).
27631  */
27632 void
27633 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
27634 {
27635 	mblk_t		*mp;
27636 	ip_priv_t	*priv;
27637 	ipp_action_id_t	aid;
27638 	int		rc = 0;
27639 	ipp_packet_t	*pp;
27640 #define	IP_CLASS	"ip"
27641 
27642 	/* If the classifier is not loaded, return  */
27643 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
27644 		return;
27645 	}
27646 
27647 	mp = *mpp;
27648 	ASSERT(mp != NULL);
27649 
27650 	/* Allocate the packet structure */
27651 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
27652 	if (rc != 0) {
27653 		*mpp = NULL;
27654 		freemsg(mp);
27655 		return;
27656 	}
27657 
27658 	/* Allocate the private structure */
27659 	rc = ip_priv_alloc((void **)&priv);
27660 	if (rc != 0) {
27661 		*mpp = NULL;
27662 		freemsg(mp);
27663 		ipp_packet_free(pp);
27664 		return;
27665 	}
27666 	priv->proc = proc;
27667 	priv->ill_index = ill_index;
27668 	ipp_packet_set_private(pp, priv, ip_priv_free);
27669 	ipp_packet_set_data(pp, mp);
27670 
27671 	/* Invoke the classifier */
27672 	rc = ipp_packet_process(&pp);
27673 	if (pp != NULL) {
27674 		mp = ipp_packet_get_data(pp);
27675 		ipp_packet_free(pp);
27676 		if (rc != 0) {
27677 			freemsg(mp);
27678 			*mpp = NULL;
27679 		}
27680 	} else {
27681 		*mpp = NULL;
27682 	}
27683 #undef	IP_CLASS
27684 }
27685 
27686 /*
27687  * Propagate a multicast group membership operation (add/drop) on
27688  * all the interfaces crossed by the related multirt routes.
27689  * The call is considered successful if the operation succeeds
27690  * on at least one interface.
27691  */
27692 static int
27693 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
27694     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
27695     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
27696     mblk_t *first_mp)
27697 {
27698 	ire_t		*ire_gw;
27699 	irb_t		*irb;
27700 	int		error = 0;
27701 	opt_restart_t	*or;
27702 
27703 	irb = ire->ire_bucket;
27704 	ASSERT(irb != NULL);
27705 
27706 	ASSERT(DB_TYPE(first_mp) == M_CTL);
27707 
27708 	or = (opt_restart_t *)first_mp->b_rptr;
27709 	IRB_REFHOLD(irb);
27710 	for (; ire != NULL; ire = ire->ire_next) {
27711 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
27712 			continue;
27713 		if (ire->ire_addr != group)
27714 			continue;
27715 
27716 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
27717 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
27718 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
27719 		/* No resolver exists for the gateway; skip this ire. */
27720 		if (ire_gw == NULL)
27721 			continue;
27722 
27723 		/*
27724 		 * This function can return EINPROGRESS. If so the operation
27725 		 * will be restarted from ip_restart_optmgmt which will
27726 		 * call ip_opt_set and option processing will restart for
27727 		 * this option. So we may end up calling 'fn' more than once.
27728 		 * This requires that 'fn' is idempotent except for the
27729 		 * return value. The operation is considered a success if
27730 		 * it succeeds at least once on any one interface.
27731 		 */
27732 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
27733 		    NULL, fmode, src, first_mp);
27734 		if (error == 0)
27735 			or->or_private = CGTP_MCAST_SUCCESS;
27736 
27737 		if (ip_debug > 0) {
27738 			ulong_t	off;
27739 			char	*ksym;
27740 			ksym = kobj_getsymname((uintptr_t)fn, &off);
27741 			ip2dbg(("ip_multirt_apply_membership: "
27742 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
27743 			    "error %d [success %u]\n",
27744 			    ksym ? ksym : "?",
27745 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
27746 			    error, or->or_private));
27747 		}
27748 
27749 		ire_refrele(ire_gw);
27750 		if (error == EINPROGRESS) {
27751 			IRB_REFRELE(irb);
27752 			return (error);
27753 		}
27754 	}
27755 	IRB_REFRELE(irb);
27756 	/*
27757 	 * Consider the call as successful if we succeeded on at least
27758 	 * one interface. Otherwise, return the last encountered error.
27759 	 */
27760 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
27761 }
27762 
27763 
27764 /*
27765  * Issue a warning regarding a route crossing an interface with an
27766  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
27767  * amount of time is logged.
27768  */
27769 static void
27770 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
27771 {
27772 	hrtime_t	current = gethrtime();
27773 	char		buf[INET_ADDRSTRLEN];
27774 
27775 	/* Convert interval in ms to hrtime in ns */
27776 	if (multirt_bad_mtu_last_time +
27777 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
27778 	    current) {
27779 		cmn_err(CE_WARN, "ip: ignoring multiroute "
27780 		    "to %s, incorrect MTU %u (expected %u)\n",
27781 		    ip_dot_addr(ire->ire_addr, buf),
27782 		    ire->ire_max_frag, max_frag);
27783 
27784 		multirt_bad_mtu_last_time = current;
27785 	}
27786 }
27787 
27788 
27789 /*
27790  * Get the CGTP (multirouting) filtering status.
27791  * If 0, the CGTP hooks are transparent.
27792  */
27793 /* ARGSUSED */
27794 static int
27795 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
27796 {
27797 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
27798 
27799 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
27800 	return (0);
27801 }
27802 
27803 
27804 /*
27805  * Set the CGTP (multirouting) filtering status.
27806  * If the status is changed from active to transparent
27807  * or from transparent to active, forward the new status
27808  * to the filtering module (if loaded).
27809  */
27810 /* ARGSUSED */
27811 static int
27812 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
27813     cred_t *ioc_cr)
27814 {
27815 	long		new_value;
27816 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
27817 
27818 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
27819 	    new_value < 0 || new_value > 1) {
27820 		return (EINVAL);
27821 	}
27822 
27823 	/*
27824 	 * Do not enable CGTP filtering - thus preventing the hooks
27825 	 * from being invoked - if the version number of the
27826 	 * filtering module hooks does not match.
27827 	 */
27828 	if ((ip_cgtp_filter_ops != NULL) &&
27829 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
27830 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
27831 		    "(module hooks version %d, expecting %d)\n",
27832 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
27833 		return (ENOTSUP);
27834 	}
27835 
27836 	if ((!*ip_cgtp_filter_value) && new_value) {
27837 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
27838 		    ip_cgtp_filter_ops == NULL ?
27839 		    " (module not loaded)" : "");
27840 	}
27841 	if (*ip_cgtp_filter_value && (!new_value)) {
27842 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
27843 		    ip_cgtp_filter_ops == NULL ?
27844 		    " (module not loaded)" : "");
27845 	}
27846 
27847 	if (ip_cgtp_filter_ops != NULL) {
27848 		int	res;
27849 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
27850 			return (res);
27851 		}
27852 	}
27853 
27854 	*ip_cgtp_filter_value = (boolean_t)new_value;
27855 
27856 	return (0);
27857 }
27858 
27859 
27860 /*
27861  * Return the expected CGTP hooks version number.
27862  */
27863 int
27864 ip_cgtp_filter_supported(void)
27865 {
27866 	return (ip_cgtp_filter_rev);
27867 }
27868 
27869 
27870 /*
27871  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
27872  * or by invoking this function. In the first case, the version number
27873  * of the registered structure is checked at hooks activation time
27874  * in ip_cgtp_filter_set().
27875  */
27876 int
27877 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
27878 {
27879 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
27880 		return (ENOTSUP);
27881 
27882 	ip_cgtp_filter_ops = ops;
27883 	return (0);
27884 }
27885 
27886 static squeue_func_t
27887 ip_squeue_switch(int val)
27888 {
27889 	squeue_func_t rval = squeue_fill;
27890 
27891 	switch (val) {
27892 	case IP_SQUEUE_ENTER_NODRAIN:
27893 		rval = squeue_enter_nodrain;
27894 		break;
27895 	case IP_SQUEUE_ENTER:
27896 		rval = squeue_enter;
27897 		break;
27898 	default:
27899 		break;
27900 	}
27901 	return (rval);
27902 }
27903 
27904 /* ARGSUSED */
27905 static int
27906 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
27907     caddr_t addr, cred_t *cr)
27908 {
27909 	int *v = (int *)addr;
27910 	long new_value;
27911 
27912 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
27913 		return (EINVAL);
27914 
27915 	ip_input_proc = ip_squeue_switch(new_value);
27916 	*v = new_value;
27917 	return (0);
27918 }
27919 
27920 /* ARGSUSED */
27921 static int
27922 ip_int_set(queue_t *q, mblk_t *mp, char *value,
27923     caddr_t addr, cred_t *cr)
27924 {
27925 	int *v = (int *)addr;
27926 	long new_value;
27927 
27928 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
27929 		return (EINVAL);
27930 
27931 	*v = new_value;
27932 	return (0);
27933 }
27934 
27935 static void
27936 ip_kstat_init(void)
27937 {
27938 	ip_named_kstat_t template = {
27939 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
27940 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
27941 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
27942 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
27943 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
27944 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
27945 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
27946 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
27947 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
27948 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
27949 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
27950 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
27951 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
27952 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
27953 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
27954 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
27955 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
27956 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
27957 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
27958 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
27959 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
27960 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
27961 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
27962 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
27963 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
27964 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
27965 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
27966 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
27967 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
27968 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
27969 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
27970 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
27971 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
27972 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
27973 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
27974 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
27975 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
27976 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
27977 	};
27978 
27979 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
27980 					NUM_OF_FIELDS(ip_named_kstat_t),
27981 					0);
27982 	if (!ip_mibkp)
27983 		return;
27984 
27985 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
27986 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
27987 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
27988 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
27989 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
27990 
27991 	template.netToMediaEntrySize.value.i32 =
27992 		sizeof (mib2_ipNetToMediaEntry_t);
27993 
27994 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
27995 
27996 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
27997 
27998 	ip_mibkp->ks_update = ip_kstat_update;
27999 
28000 	kstat_install(ip_mibkp);
28001 }
28002 
28003 static void
28004 ip_kstat_fini(void)
28005 {
28006 
28007 	if (ip_mibkp != NULL) {
28008 		kstat_delete(ip_mibkp);
28009 		ip_mibkp = NULL;
28010 	}
28011 }
28012 
28013 static int
28014 ip_kstat_update(kstat_t *kp, int rw)
28015 {
28016 	ip_named_kstat_t *ipkp;
28017 
28018 	if (!kp || !kp->ks_data)
28019 		return (EIO);
28020 
28021 	if (rw == KSTAT_WRITE)
28022 		return (EACCES);
28023 
28024 	ipkp = (ip_named_kstat_t *)kp->ks_data;
28025 
28026 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
28027 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
28028 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
28029 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
28030 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
28031 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
28032 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
28033 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
28034 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
28035 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
28036 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
28037 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
28038 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
28039 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
28040 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
28041 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
28042 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
28043 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
28044 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
28045 
28046 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
28047 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
28048 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
28049 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
28050 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
28051 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
28052 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
28053 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
28054 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
28055 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
28056 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
28057 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
28058 
28059 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
28060 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
28061 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
28062 
28063 	return (0);
28064 }
28065 
28066 static void
28067 icmp_kstat_init(void)
28068 {
28069 	icmp_named_kstat_t template = {
28070 		{ "inMsgs",		KSTAT_DATA_UINT32 },
28071 		{ "inErrors",		KSTAT_DATA_UINT32 },
28072 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
28073 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
28074 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
28075 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
28076 		{ "inRedirects",	KSTAT_DATA_UINT32 },
28077 		{ "inEchos",		KSTAT_DATA_UINT32 },
28078 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
28079 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
28080 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
28081 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
28082 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
28083 		{ "outMsgs",		KSTAT_DATA_UINT32 },
28084 		{ "outErrors",		KSTAT_DATA_UINT32 },
28085 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
28086 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
28087 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
28088 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
28089 		{ "outRedirects",	KSTAT_DATA_UINT32 },
28090 		{ "outEchos",		KSTAT_DATA_UINT32 },
28091 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
28092 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
28093 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
28094 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
28095 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
28096 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
28097 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
28098 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
28099 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
28100 		{ "outDrops",		KSTAT_DATA_UINT32 },
28101 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
28102 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
28103 	};
28104 
28105 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
28106 					NUM_OF_FIELDS(icmp_named_kstat_t),
28107 					0);
28108 	if (icmp_mibkp == NULL)
28109 		return;
28110 
28111 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
28112 
28113 	icmp_mibkp->ks_update = icmp_kstat_update;
28114 
28115 	kstat_install(icmp_mibkp);
28116 }
28117 
28118 static void
28119 icmp_kstat_fini(void)
28120 {
28121 
28122 	if (icmp_mibkp != NULL) {
28123 		kstat_delete(icmp_mibkp);
28124 		icmp_mibkp = NULL;
28125 	}
28126 }
28127 
28128 static int
28129 icmp_kstat_update(kstat_t *kp, int rw)
28130 {
28131 	icmp_named_kstat_t *icmpkp;
28132 
28133 	if ((kp == NULL) || (kp->ks_data == NULL))
28134 		return (EIO);
28135 
28136 	if (rw == KSTAT_WRITE)
28137 		return (EACCES);
28138 
28139 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
28140 
28141 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
28142 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
28143 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
28144 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
28145 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
28146 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
28147 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
28148 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
28149 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
28150 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
28151 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
28152 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
28153 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
28154 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
28155 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
28156 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
28157 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
28158 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
28159 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
28160 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
28161 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
28162 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
28163 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
28164 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
28165 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
28166 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
28167 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
28168 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
28169 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
28170 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
28171 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
28172 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
28173 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
28174 
28175 	return (0);
28176 }
28177 
28178 /*
28179  * This is the fanout function for raw socket opened for SCTP.  Note
28180  * that it is called after SCTP checks that there is no socket which
28181  * wants a packet.  Then before SCTP handles this out of the blue packet,
28182  * this function is called to see if there is any raw socket for SCTP.
28183  * If there is and it is bound to the correct address, the packet will
28184  * be sent to that socket.  Note that only one raw socket can be bound to
28185  * a port.  This is assured in ipcl_sctp_hash_insert();
28186  */
28187 void
28188 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
28189     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
28190     uint_t ipif_seqid, zoneid_t zoneid)
28191 {
28192 	conn_t		*connp;
28193 	queue_t		*rq;
28194 	mblk_t		*first_mp;
28195 	boolean_t	secure;
28196 	ip6_t		*ip6h;
28197 
28198 	first_mp = mp;
28199 	if (mctl_present) {
28200 		mp = first_mp->b_cont;
28201 		secure = ipsec_in_is_secure(first_mp);
28202 		ASSERT(mp != NULL);
28203 	} else {
28204 		secure = B_FALSE;
28205 	}
28206 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
28207 
28208 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
28209 	if (connp == NULL) {
28210 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
28211 		    mctl_present);
28212 		return;
28213 	}
28214 	rq = connp->conn_rq;
28215 	if (!canputnext(rq)) {
28216 		CONN_DEC_REF(connp);
28217 		BUMP_MIB(&ip_mib, rawipInOverflows);
28218 		freemsg(first_mp);
28219 		return;
28220 	}
28221 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
28222 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
28223 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
28224 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
28225 		if (first_mp == NULL) {
28226 			CONN_DEC_REF(connp);
28227 			return;
28228 		}
28229 	}
28230 	/*
28231 	 * We probably should not send M_CTL message up to
28232 	 * raw socket.
28233 	 */
28234 	if (mctl_present)
28235 		freeb(first_mp);
28236 
28237 	/* Initiate IPPF processing here if needed. */
28238 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
28239 	    (!isv4 && IP6_IN_IPP(flags))) {
28240 		ip_process(IPP_LOCAL_IN, &mp,
28241 		    recv_ill->ill_phyint->phyint_ifindex);
28242 		if (mp == NULL) {
28243 			CONN_DEC_REF(connp);
28244 			return;
28245 		}
28246 	}
28247 
28248 	if (connp->conn_recvif || connp->conn_recvslla ||
28249 	    ((connp->conn_ipv6_recvpktinfo ||
28250 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
28251 	    (flags & IP_FF_IP6INFO))) {
28252 		int in_flags = 0;
28253 
28254 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
28255 			in_flags = IPF_RECVIF;
28256 		}
28257 		if (connp->conn_recvslla) {
28258 			in_flags |= IPF_RECVSLLA;
28259 		}
28260 		if (isv4) {
28261 			mp = ip_add_info(mp, recv_ill, in_flags);
28262 		} else {
28263 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
28264 			if (mp == NULL) {
28265 				CONN_DEC_REF(connp);
28266 				return;
28267 			}
28268 		}
28269 	}
28270 
28271 	BUMP_MIB(&ip_mib, ipInDelivers);
28272 	/*
28273 	 * We are sending the IPSEC_IN message also up. Refer
28274 	 * to comments above this function.
28275 	 */
28276 	putnext(rq, mp);
28277 	CONN_DEC_REF(connp);
28278 }
28279 
28280 /*
28281  * This function should be called only if all packet processing
28282  * including fragmentation is complete. Callers of this function
28283  * must set mp->b_prev to one of these values:
28284  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
28285  * prior to handing over the mp as first argument to this function.
28286  *
28287  * If the ire passed by caller is incomplete, this function
28288  * queues the packet and if necessary, sends ARP request and bails.
28289  * If the ire passed is fully resolved, we simply prepend
28290  * the link-layer header to the packet, do ipsec hw acceleration
28291  * work if necessary, and send the packet out on the wire.
28292  *
28293  * NOTE: IPSEC will only call this function with fully resolved
28294  * ires if hw acceleration is involved.
28295  * TODO list :
28296  * 	a Handle M_MULTIDATA so that
28297  *	  tcp_multisend->tcp_multisend_data can
28298  *	  call ip_xmit_v4 directly
28299  *	b Handle post-ARP work for fragments so that
28300  *	  ip_wput_frag can call this function.
28301  */
28302 ipxmit_state_t
28303 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
28304 {
28305 	nce_t		*arpce;
28306 	queue_t		*q;
28307 	int		ill_index;
28308 	mblk_t		*nxt_mp;
28309 	boolean_t	xmit_drop = B_FALSE;
28310 	ip_proc_t	proc;
28311 
28312 	arpce = ire->ire_nce;
28313 	ASSERT(arpce != NULL);
28314 
28315 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
28316 
28317 	mutex_enter(&arpce->nce_lock);
28318 	switch (arpce->nce_state) {
28319 	case ND_REACHABLE:
28320 		/* If there are other queued packets, queue this packet */
28321 		if (arpce->nce_qd_mp != NULL) {
28322 			if (mp != NULL)
28323 				nce_queue_mp_common(arpce, mp, B_FALSE);
28324 			mp = arpce->nce_qd_mp;
28325 		}
28326 		arpce->nce_qd_mp = NULL;
28327 		mutex_exit(&arpce->nce_lock);
28328 
28329 		/*
28330 		 * Flush the queue.  In the common case, where the
28331 		 * ARP is already resolved,  it will go through the
28332 		 * while loop only once.
28333 		 */
28334 		while (mp != NULL) {
28335 
28336 			nxt_mp = mp->b_next;
28337 			mp->b_next = NULL;
28338 			/*
28339 			 * This info is needed for IPQOS to do COS marking
28340 			 * in ip_wput_attach_llhdr->ip_process.
28341 			 */
28342 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
28343 			mp->b_prev = NULL;
28344 
28345 			/* set up ill index for outbound qos processing */
28346 			ill_index =
28347 			    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
28348 			mp = ip_wput_attach_llhdr(mp, ire, proc, ill_index);
28349 			if (mp == NULL) {
28350 				xmit_drop = B_TRUE;
28351 				if (proc == IPP_FWD_OUT) {
28352 					BUMP_MIB(&ip_mib, ipInDiscards);
28353 				} else {
28354 					BUMP_MIB(&ip_mib, ipOutDiscards);
28355 				}
28356 				goto next_mp;
28357 			}
28358 			/* non-ipsec hw accel case */
28359 			if (io == NULL || !io->ipsec_out_accelerated) {
28360 				/* send it */
28361 				q = ire->ire_stq;
28362 				if (proc == IPP_FWD_OUT) {
28363 					UPDATE_IB_PKT_COUNT(ire);
28364 				} else {
28365 					UPDATE_OB_PKT_COUNT(ire);
28366 				}
28367 				ire->ire_last_used_time = lbolt;
28368 
28369 				if (flow_ctl_enabled) {
28370 					/*
28371 					 * We are here from ip_wout_ire
28372 					 * which has already done canput
28373 					 * check and has enabled flow
28374 					 * control, so skip the canputnext
28375 					 * check.
28376 					 */
28377 					putnext(q, mp);
28378 					goto next_mp;
28379 				}
28380 				if (canputnext(q))  {
28381 					if (proc == IPP_FWD_OUT) {
28382 						BUMP_MIB(&ip_mib,
28383 						    ipForwDatagrams);
28384 					}
28385 					putnext(q, mp);
28386 				} else {
28387 					BUMP_MIB(&ip_mib,
28388 					    ipOutDiscards);
28389 					xmit_drop = B_TRUE;
28390 					freemsg(mp);
28391 				}
28392 			} else {
28393 				/*
28394 				 * Safety Pup says: make sure this
28395 				 *  is going to the right interface!
28396 				 */
28397 				ill_t *ill1 =
28398 				    (ill_t *)ire->ire_stq->q_ptr;
28399 				int ifindex =
28400 				    ill1->ill_phyint->phyint_ifindex;
28401 				if (ifindex !=
28402 				    io->ipsec_out_capab_ill_index) {
28403 					xmit_drop = B_TRUE;
28404 					freemsg(mp);
28405 				} else {
28406 					ipsec_hw_putnext(ire->ire_stq,
28407 					    mp);
28408 				}
28409 			}
28410 next_mp:
28411 			mp = nxt_mp;
28412 		} /* while (mp != NULL) */
28413 		if (xmit_drop)
28414 			return (SEND_FAILED);
28415 		else
28416 			return (SEND_PASSED);
28417 
28418 	case ND_INITIAL:
28419 	case ND_INCOMPLETE:
28420 
28421 		/*
28422 		 * While we do send off packets to dests that
28423 		 * use fully-resolved CGTP routes, we do not
28424 		 * handle unresolved CGTP routes.
28425 		 */
28426 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
28427 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
28428 
28429 		if (mp != NULL) {
28430 			/* queue the packet */
28431 			nce_queue_mp_common(arpce, mp, B_FALSE);
28432 		}
28433 
28434 		if (arpce->nce_state == ND_INCOMPLETE) {
28435 			mutex_exit(&arpce->nce_lock);
28436 			DTRACE_PROBE3(ip__xmit__incomplete,
28437 			    (ire_t *), ire, (mblk_t *), mp,
28438 			    (ipsec_out_t *), io);
28439 			return (LOOKUP_IN_PROGRESS);
28440 		}
28441 
28442 		arpce->nce_state = ND_INCOMPLETE;
28443 		mutex_exit(&arpce->nce_lock);
28444 		/*
28445 		 * Note that ire_add() (called from ire_forward())
28446 		 * holds a ref on the ire until ARP is completed.
28447 		 */
28448 
28449 		ire_arpresolve(ire, ire_to_ill(ire));
28450 		return (LOOKUP_IN_PROGRESS);
28451 	default:
28452 		ASSERT(0);
28453 		mutex_exit(&arpce->nce_lock);
28454 		return (LLHDR_RESLV_FAILED);
28455 	}
28456 }
28457 
28458 /*
28459  * Return B_TRUE if the buffers differ in length or content.
28460  * This is used for comparing extension header buffers.
28461  * Note that an extension header would be declared different
28462  * even if all that changed was the next header value in that header i.e.
28463  * what really changed is the next extension header.
28464  */
28465 boolean_t
28466 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
28467     uint_t blen)
28468 {
28469 	if (!b_valid)
28470 		blen = 0;
28471 
28472 	if (alen != blen)
28473 		return (B_TRUE);
28474 	if (alen == 0)
28475 		return (B_FALSE);	/* Both zero length */
28476 	return (bcmp(abuf, bbuf, alen));
28477 }
28478 
28479 /*
28480  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
28481  * Return B_FALSE if memory allocation fails - don't change any state!
28482  */
28483 boolean_t
28484 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28485     const void *src, uint_t srclen)
28486 {
28487 	void *dst;
28488 
28489 	if (!src_valid)
28490 		srclen = 0;
28491 
28492 	ASSERT(*dstlenp == 0);
28493 	if (src != NULL && srclen != 0) {
28494 		dst = mi_alloc(srclen, BPRI_MED);
28495 		if (dst == NULL)
28496 			return (B_FALSE);
28497 	} else {
28498 		dst = NULL;
28499 	}
28500 	if (*dstp != NULL)
28501 		mi_free(*dstp);
28502 	*dstp = dst;
28503 	*dstlenp = dst == NULL ? 0 : srclen;
28504 	return (B_TRUE);
28505 }
28506 
28507 /*
28508  * Replace what is in *dst, *dstlen with the source.
28509  * Assumes ip_allocbuf has already been called.
28510  */
28511 void
28512 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28513     const void *src, uint_t srclen)
28514 {
28515 	if (!src_valid)
28516 		srclen = 0;
28517 
28518 	ASSERT(*dstlenp == srclen);
28519 	if (src != NULL && srclen != 0)
28520 		bcopy(src, *dstp, srclen);
28521 }
28522 
28523 /*
28524  * Free the storage pointed to by the members of an ip6_pkt_t.
28525  */
28526 void
28527 ip6_pkt_free(ip6_pkt_t *ipp)
28528 {
28529 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
28530 
28531 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
28532 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
28533 		ipp->ipp_hopopts = NULL;
28534 		ipp->ipp_hopoptslen = 0;
28535 	}
28536 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
28537 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
28538 		ipp->ipp_rtdstopts = NULL;
28539 		ipp->ipp_rtdstoptslen = 0;
28540 	}
28541 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
28542 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
28543 		ipp->ipp_dstopts = NULL;
28544 		ipp->ipp_dstoptslen = 0;
28545 	}
28546 	if (ipp->ipp_fields & IPPF_RTHDR) {
28547 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
28548 		ipp->ipp_rthdr = NULL;
28549 		ipp->ipp_rthdrlen = 0;
28550 	}
28551 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
28552 	    IPPF_RTHDR);
28553 }
28554