xref: /titanic_41/usr/src/uts/common/inet/ip/ip.c (revision 752ec50eb29a9f48e3047116b6c8ceb8dedaefb3)
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
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  * Multiple zones can share a common broadcast address; typically all zones
648  * share the 255.255.255.255 address. Incoming as well as locally originated
649  * broadcast packets must be dispatched to all the zones on the broadcast
650  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
651  * since some zones may not be on the 10.16.72/24 network. To handle this, each
652  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
653  * sent to every zone that has an IRE_BROADCAST entry for the destination
654  * address on the input ill, see conn_wantpacket().
655  *
656  * Applications in different zones can join the same multicast group address.
657  * For IPv4, group memberships are per-logical interface, so they're already
658  * inherently part of a zone. For IPv6, group memberships are per-physical
659  * interface, so we distinguish IPv6 group memberships based on group address,
660  * interface and zoneid. In both cases, received multicast packets are sent to
661  * every zone for which a group membership entry exists. On IPv6 we need to
662  * check that the target zone still has an address on the receiving physical
663  * interface; it could have been removed since the application issued the
664  * IPV6_JOIN_GROUP.
665  */
666 
667 /*
668  * Squeue Fanout flags:
669  *	0: No fanout.
670  *	1: Fanout across all squeues
671  */
672 boolean_t	ip_squeue_fanout = 0;
673 
674 /*
675  * Maximum dups allowed per packet.
676  */
677 uint_t ip_max_frag_dups = 10;
678 
679 #define	IS_SIMPLE_IPH(ipha)						\
680 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
681 
682 /* RFC1122 Conformance */
683 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
684 
685 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
686 
687 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
688 
689 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
690 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
691 
692 static void	icmp_frag_needed(queue_t *, mblk_t *, int);
693 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
694     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
695 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
696 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
697 		    mblk_t *, int);
698 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
699 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
700 		    ill_t *, zoneid_t);
701 static void	icmp_options_update(ipha_t *);
702 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t);
703 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t);
704 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
705 static void	icmp_redirect(mblk_t *);
706 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
707 
708 static void	ip_arp_news(queue_t *, mblk_t *);
709 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
710 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
711 char		*ip_dot_addr(ipaddr_t, char *);
712 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
713 int		ip_close(queue_t *, int);
714 static char	*ip_dot_saddr(uchar_t *, char *);
715 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
716 		    boolean_t, boolean_t, ill_t *, zoneid_t);
717 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
718 		    boolean_t, boolean_t, zoneid_t);
719 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
720 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
721 static void	ip_lrput(queue_t *, mblk_t *);
722 ipaddr_t	ip_massage_options(ipha_t *);
723 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
724 ipaddr_t	ip_net_mask(ipaddr_t);
725 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *);
726 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
727 		    conn_t *, uint32_t);
728 char		*ip_nv_lookup(nv_t *, int);
729 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
730 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
731 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
732 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
733 			    size_t);
734 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
735 void	ip_rput(queue_t *, mblk_t *);
736 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
737 		    void *dummy_arg);
738 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
739 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
740 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
741 			    ire_t *);
742 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
743 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
744 		    uint16_t *);
745 int		ip_snmp_get(queue_t *, mblk_t *);
746 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
747 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
748 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
749 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
750 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
751 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
752 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
753 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
754 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
755 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
756 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
757 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
758 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
759 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
760 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
761 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
762 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
763 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
764 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
765 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
766 static boolean_t	ip_source_routed(ipha_t *);
767 static boolean_t	ip_source_route_included(ipha_t *);
768 
769 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t);
770 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
771 static void	ip_wput_local_options(ipha_t *);
772 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
773     zoneid_t);
774 
775 static void	conn_drain_init(void);
776 static void	conn_drain_fini(void);
777 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
778 
779 static void	conn_walk_drain(void);
780 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
781     zoneid_t);
782 
783 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
784     zoneid_t);
785 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
786     void *dummy_arg);
787 
788 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
789 
790 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
791     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
792     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
793 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
794 
795 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
796 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
797     caddr_t, cred_t *);
798 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
799     caddr_t cp, cred_t *cr);
800 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
801     cred_t *);
802 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
803     caddr_t cp, cred_t *cr);
804 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
805     cred_t *);
806 static squeue_func_t ip_squeue_switch(int);
807 
808 static void	ip_kstat_init(void);
809 static void	ip_kstat_fini(void);
810 static int	ip_kstat_update(kstat_t *kp, int rw);
811 static void	icmp_kstat_init(void);
812 static void	icmp_kstat_fini(void);
813 static int	icmp_kstat_update(kstat_t *kp, int rw);
814 
815 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
816 
817 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
818     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
819 
820 void	ip_input(ill_t *, ill_rx_ring_t *, mblk_t *, size_t);
821 
822 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
823     ipha_t *, ill_t *, boolean_t);
824 
825 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
826 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
827 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
828 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
829 
830 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
831 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
832 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
833 
834 /* How long, in seconds, we allow frags to hang around. */
835 #define	IP_FRAG_TIMEOUT	60
836 
837 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
838 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
839 
840 /*
841  * Threshold which determines whether MDT should be used when
842  * generating IP fragments; payload size must be greater than
843  * this threshold for MDT to take place.
844  */
845 #define	IP_WPUT_FRAG_MDT_MIN	32768
846 
847 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
848 
849 /* Protected by ip_mi_lock */
850 static void	*ip_g_head;		/* Instance Data List Head */
851 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
852 
853 /* Only modified during _init and _fini thus no locking is needed. */
854 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
855 
856 
857 static long ip_rput_pullups;
858 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
859 
860 vmem_t *ip_minor_arena;
861 
862 /*
863  * MIB-2 stuff for SNMP (both IP and ICMP)
864  */
865 mib2_ip_t	ip_mib;
866 mib2_icmp_t	icmp_mib;
867 
868 #ifdef DEBUG
869 uint32_t ipsechw_debug = 0;
870 #endif
871 
872 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
873 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
874 
875 uint_t	loopback_packets = 0;
876 
877 /*
878  * Multirouting/CGTP stuff
879  */
880 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
881 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
882 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
883 /* Interval (in ms) between consecutive 'bad MTU' warnings */
884 hrtime_t ip_multirt_log_interval = 1000;
885 /* Time since last warning issued. */
886 static hrtime_t	multirt_bad_mtu_last_time = 0;
887 
888 kmutex_t ip_trash_timer_lock;
889 krwlock_t ip_g_nd_lock;
890 
891 /*
892  * XXX following really should only be in a header. Would need more
893  * header and .c clean up first.
894  */
895 extern optdb_obj_t	ip_opt_obj;
896 
897 ulong_t ip_squeue_enter_unbound = 0;
898 
899 /*
900  * Named Dispatch Parameter Table.
901  * All of these are alterable, within the min/max values given, at run time.
902  */
903 static ipparam_t	lcl_param_arr[] = {
904 	/* min	max	value	name */
905 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
906 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
907 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
908 	{  0,	1,	0,	"ip_respond_to_timestamp"},
909 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
910 	{  0,	1,	1,	"ip_send_redirects"},
911 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
912 	{  0,	10,	0,	"ip_debug"},
913 	{  0,	10,	0,	"ip_mrtdebug"},
914 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
915 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
916 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
917 	{  1,	255,	255,	"ip_def_ttl" },
918 	{  0,	1,	0,	"ip_forward_src_routed"},
919 	{  0,	256,	32,	"ip_wroff_extra" },
920 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
921 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
922 	{  0,	1,	1,	"ip_path_mtu_discovery" },
923 	{  0,	240,	30,	"ip_ignore_delete_time" },
924 	{  0,	1,	0,	"ip_ignore_redirect" },
925 	{  0,	1,	1,	"ip_output_queue" },
926 	{  1,	254,	1,	"ip_broadcast_ttl" },
927 	{  0,	99999,	100,	"ip_icmp_err_interval" },
928 	{  1,	99999,	10,	"ip_icmp_err_burst" },
929 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
930 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
931 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
932 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
933 	{  0,	1,	1,	"icmp_accept_clear_messages" },
934 	{  0,	1,	1,	"igmp_accept_clear_messages" },
935 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
936 				"ip_ndp_delay_first_probe_time"},
937 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
938 				"ip_ndp_max_unicast_solicit"},
939 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
940 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
941 	{  0,	1,	0,	"ip6_forward_src_routed"},
942 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
943 	{  0,	1,	1,	"ip6_send_redirects"},
944 	{  0,	1,	0,	"ip6_ignore_redirect" },
945 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
946 
947 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
948 
949 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
950 
951 	{  0,	1,	1,	"pim_accept_clear_messages" },
952 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
953 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
954 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
955 	{  0,	15,	0,	"ip_policy_mask" },
956 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
957 	{  0,	255,	1,	"ip_multirt_ttl" },
958 	{  0,	1,	1,	"ip_multidata_outbound" },
959 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
960 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
961 	{  0,	1000,	1,	"ip_max_temp_defend" },
962 	{  0,	1000,	3,	"ip_max_defend" },
963 	{  0,	999999,	30,	"ip_defend_interval" },
964 	{  0,	3600000, 300000, "ip_dup_recovery" },
965 #ifdef DEBUG
966 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
967 #endif
968 };
969 
970 ipparam_t	*ip_param_arr = lcl_param_arr;
971 
972 /* Extended NDP table */
973 static ipndp_t	lcl_ndp_arr[] = {
974 	/* getf			setf		data			name */
975 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
976 	    "ip_forwarding" },
977 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
978 	    "ip6_forwarding" },
979 	{  ip_ill_report,	NULL,		NULL,
980 	    "ip_ill_status" },
981 	{  ip_ipif_report,	NULL,		NULL,
982 	    "ip_ipif_status" },
983 	{  ip_ire_report,	NULL,		NULL,
984 	    "ipv4_ire_status" },
985 	{  ip_ire_report_mrtun,	NULL,		NULL,
986 	    "ipv4_mrtun_ire_status" },
987 	{  ip_ire_report_srcif,	NULL,		NULL,
988 	    "ipv4_srcif_ire_status" },
989 	{  ip_ire_report_v6,	NULL,		NULL,
990 	    "ipv6_ire_status" },
991 	{  ip_conn_report,	NULL,		NULL,
992 	    "ip_conn_status" },
993 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
994 	    "ip_rput_pullups" },
995 	{  ndp_report,		NULL,		NULL,
996 	    "ip_ndp_cache_report" },
997 	{  ip_srcid_report,	NULL,		NULL,
998 	    "ip_srcid_status" },
999 	{ ip_param_generic_get, ip_squeue_profile_set,
1000 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
1001 	{ ip_param_generic_get, ip_squeue_bind_set,
1002 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
1003 	{ ip_param_generic_get, ip_input_proc_set,
1004 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1005 	{ ip_param_generic_get, ip_int_set,
1006 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1007 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
1008 	    "ip_cgtp_filter" },
1009 	{ ip_param_generic_get, ip_int_set,
1010 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
1011 };
1012 
1013 /*
1014  * ip_g_forward controls IP forwarding.  It takes two values:
1015  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
1016  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
1017  *
1018  * RFC1122 says there must be a configuration switch to control forwarding,
1019  * but that the default MUST be to not forward packets ever.  Implicit
1020  * control based on configuration of multiple interfaces MUST NOT be
1021  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
1022  * and, in fact, it was the default.  That capability is now provided in the
1023  * /etc/rc2.d/S69inet script.
1024  */
1025 int ip_g_forward = IP_FORWARD_DEFAULT;
1026 
1027 /* It also has an IPv6 counterpart. */
1028 
1029 int ipv6_forward = IP_FORWARD_DEFAULT;
1030 
1031 /*
1032  * Table of IP ioctls encoding the various properties of the ioctl and
1033  * indexed based on the last byte of the ioctl command. Occasionally there
1034  * is a clash, and there is more than 1 ioctl with the same last byte.
1035  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1036  * ioctls are encoded in the misc table. An entry in the ndx table is
1037  * retrieved by indexing on the last byte of the ioctl command and comparing
1038  * the ioctl command with the value in the ndx table. In the event of a
1039  * mismatch the misc table is then searched sequentially for the desired
1040  * ioctl command.
1041  *
1042  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1043  */
1044 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1045 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 
1056 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1057 			MISC_CMD, ip_siocaddrt, NULL },
1058 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1059 			MISC_CMD, ip_siocdelrt, NULL },
1060 
1061 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1062 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1063 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1064 			IF_CMD, ip_sioctl_get_addr, NULL },
1065 
1066 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1067 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1068 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1069 			IPI_GET_CMD | IPI_REPL,
1070 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1071 
1072 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1073 			IPI_PRIV | IPI_WR | IPI_REPL,
1074 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1075 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1076 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1077 			IF_CMD, ip_sioctl_get_flags, NULL },
1078 
1079 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 
1082 	/* copyin size cannot be coded for SIOCGIFCONF */
1083 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1084 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1085 
1086 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1087 			IF_CMD, ip_sioctl_mtu, NULL },
1088 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1089 			IF_CMD, ip_sioctl_get_mtu, NULL },
1090 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1091 			IPI_GET_CMD | IPI_REPL,
1092 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1093 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1094 			IF_CMD, ip_sioctl_brdaddr, NULL },
1095 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1096 			IPI_GET_CMD | IPI_REPL,
1097 			IF_CMD, ip_sioctl_get_netmask, NULL },
1098 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1099 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1100 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1101 			IPI_GET_CMD | IPI_REPL,
1102 			IF_CMD, ip_sioctl_get_metric, NULL },
1103 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1104 			IF_CMD, ip_sioctl_metric, NULL },
1105 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 
1107 	/* See 166-168 below for extended SIOC*XARP ioctls */
1108 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1109 			MISC_CMD, ip_sioctl_arp, NULL },
1110 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1111 			MISC_CMD, ip_sioctl_arp, NULL },
1112 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1113 			MISC_CMD, ip_sioctl_arp, NULL },
1114 
1115 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1135 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1136 
1137 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1138 			MISC_CMD, if_unitsel, if_unitsel_restart },
1139 
1140 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1158 
1159 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1160 			IPI_PRIV | IPI_WR | IPI_MODOK,
1161 			IF_CMD, ip_sioctl_sifname, NULL },
1162 
1163 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 
1177 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1178 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1179 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1180 			IF_CMD, ip_sioctl_get_muxid, NULL },
1181 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1182 			IPI_PRIV | IPI_WR | IPI_REPL,
1183 			IF_CMD, ip_sioctl_muxid, NULL },
1184 
1185 	/* Both if and lif variants share same func */
1186 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1187 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1188 	/* Both if and lif variants share same func */
1189 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1190 			IPI_PRIV | IPI_WR | IPI_REPL,
1191 			IF_CMD, ip_sioctl_slifindex, NULL },
1192 
1193 	/* copyin size cannot be coded for SIOCGIFCONF */
1194 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1195 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1196 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1200 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1201 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1202 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1203 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1204 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1205 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1206 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1207 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1208 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1209 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1210 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1211 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1212 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1213 
1214 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1215 			IPI_PRIV | IPI_WR | IPI_REPL,
1216 			LIF_CMD, ip_sioctl_removeif,
1217 			ip_sioctl_removeif_restart },
1218 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1219 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1220 			LIF_CMD, ip_sioctl_addif, NULL },
1221 #define	SIOCLIFADDR_NDX 112
1222 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1223 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1224 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1225 			IPI_GET_CMD | IPI_REPL,
1226 			LIF_CMD, ip_sioctl_get_addr, NULL },
1227 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1228 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1229 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1230 			IPI_GET_CMD | IPI_REPL,
1231 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1232 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1233 			IPI_PRIV | IPI_WR | IPI_REPL,
1234 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1235 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1236 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1237 			LIF_CMD, ip_sioctl_get_flags, NULL },
1238 
1239 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1240 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1241 
1242 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1243 			ip_sioctl_get_lifconf, NULL },
1244 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1245 			LIF_CMD, ip_sioctl_mtu, NULL },
1246 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1247 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1248 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1249 			IPI_GET_CMD | IPI_REPL,
1250 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1251 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1252 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1253 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1254 			IPI_GET_CMD | IPI_REPL,
1255 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1256 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1257 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1258 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1259 			IPI_GET_CMD | IPI_REPL,
1260 			LIF_CMD, ip_sioctl_get_metric, NULL },
1261 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1262 			LIF_CMD, ip_sioctl_metric, NULL },
1263 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1264 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1265 			LIF_CMD, ip_sioctl_slifname,
1266 			ip_sioctl_slifname_restart },
1267 
1268 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1269 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1270 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1271 			IPI_GET_CMD | IPI_REPL,
1272 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1273 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1274 			IPI_PRIV | IPI_WR | IPI_REPL,
1275 			LIF_CMD, ip_sioctl_muxid, NULL },
1276 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1277 			IPI_GET_CMD | IPI_REPL,
1278 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1279 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1280 			IPI_PRIV | IPI_WR | IPI_REPL,
1281 			LIF_CMD, ip_sioctl_slifindex, 0 },
1282 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1283 			LIF_CMD, ip_sioctl_token, NULL },
1284 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1285 			IPI_GET_CMD | IPI_REPL,
1286 			LIF_CMD, ip_sioctl_get_token, NULL },
1287 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1288 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1289 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1290 			IPI_GET_CMD | IPI_REPL,
1291 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1292 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1293 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1294 
1295 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1296 			IPI_GET_CMD | IPI_REPL,
1297 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1298 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1299 			LIF_CMD, ip_siocdelndp_v6, NULL },
1300 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1301 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1302 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1303 			LIF_CMD, ip_siocsetndp_v6, NULL },
1304 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1305 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1306 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1307 			MISC_CMD, ip_sioctl_tonlink, NULL },
1308 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1309 			MISC_CMD, ip_sioctl_tmysite, NULL },
1310 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1311 			TUN_CMD, ip_sioctl_tunparam, NULL },
1312 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1313 			IPI_PRIV | IPI_WR,
1314 			TUN_CMD, ip_sioctl_tunparam, NULL },
1315 
1316 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1317 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1318 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1319 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1320 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1321 
1322 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1323 			IPI_PRIV | IPI_WR | IPI_REPL,
1324 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1325 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1326 			IPI_PRIV | IPI_WR | IPI_REPL,
1327 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1328 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1329 			IPI_PRIV | IPI_WR,
1330 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1331 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1332 			IPI_GET_CMD | IPI_REPL,
1333 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1334 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1335 			IPI_GET_CMD | IPI_REPL,
1336 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1337 
1338 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1339 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1340 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1341 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1342 
1343 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1344 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1345 
1346 	/* These are handled in ip_sioctl_copyin_setup itself */
1347 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1348 			MISC_CMD, NULL, NULL },
1349 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1350 			MISC_CMD, NULL, NULL },
1351 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1352 
1353 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1354 			ip_sioctl_get_lifconf, NULL },
1355 
1356 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1357 			MISC_CMD, ip_sioctl_xarp, NULL },
1358 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1359 			MISC_CMD, ip_sioctl_xarp, NULL },
1360 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1361 			MISC_CMD, ip_sioctl_xarp, NULL },
1362 
1363 	/* SIOCPOPSOCKFS is not handled by IP */
1364 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1365 
1366 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1367 			IPI_GET_CMD | IPI_REPL,
1368 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1369 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1370 			IPI_PRIV | IPI_WR | IPI_REPL,
1371 			LIF_CMD, ip_sioctl_slifzone,
1372 			ip_sioctl_slifzone_restart },
1373 	/* 172-174 are SCTP ioctls and not handled by IP */
1374 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1375 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1376 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1377 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1378 			IPI_GET_CMD, LIF_CMD,
1379 			ip_sioctl_get_lifusesrc, 0 },
1380 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1381 			IPI_PRIV | IPI_WR,
1382 			LIF_CMD, ip_sioctl_slifusesrc,
1383 			NULL },
1384 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1385 			ip_sioctl_get_lifsrcof, NULL },
1386 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1387 			MISC_CMD, ip_sioctl_msfilter, NULL },
1388 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1389 			MISC_CMD, ip_sioctl_msfilter, NULL },
1390 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1391 			MISC_CMD, ip_sioctl_msfilter, NULL },
1392 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1393 			MISC_CMD, ip_sioctl_msfilter, NULL },
1394 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1395 			ip_sioctl_set_ipmpfailback, NULL }
1396 };
1397 
1398 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1399 
1400 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1401 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1402 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1403 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1404 		TUN_CMD, ip_sioctl_tunparam, NULL },
1405 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1406 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1407 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1408 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1409 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1410 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1411 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1412 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1413 		MISC_CMD, mrt_ioctl},
1414 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1415 		MISC_CMD, mrt_ioctl},
1416 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1417 		MISC_CMD, mrt_ioctl}
1418 };
1419 
1420 int ip_misc_ioctl_count =
1421     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1422 
1423 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1424 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1425 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1426 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1427 					/* Settable in /etc/system */
1428 uint_t	ip_redirect_cnt;		/* Num of redirect routes in ftable */
1429 
1430 /* Defined in ip_ire.c */
1431 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1432 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1433 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1434 
1435 static nv_t	ire_nv_arr[] = {
1436 	{ IRE_BROADCAST, "BROADCAST" },
1437 	{ IRE_LOCAL, "LOCAL" },
1438 	{ IRE_LOOPBACK, "LOOPBACK" },
1439 	{ IRE_CACHE, "CACHE" },
1440 	{ IRE_DEFAULT, "DEFAULT" },
1441 	{ IRE_PREFIX, "PREFIX" },
1442 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1443 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1444 	{ IRE_HOST, "HOST" },
1445 	{ IRE_HOST_REDIRECT, "HOST_REDIRECT" },
1446 	{ 0 }
1447 };
1448 
1449 nv_t	*ire_nv_tbl = ire_nv_arr;
1450 
1451 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1452 extern krwlock_t ipsec_capab_ills_lock;
1453 
1454 /* Packet dropper for IP IPsec processing failures */
1455 ipdropper_t ip_dropper;
1456 
1457 /* Simple ICMP IP Header Template */
1458 static ipha_t icmp_ipha = {
1459 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1460 };
1461 
1462 struct module_info ip_mod_info = {
1463 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1464 };
1465 
1466 /*
1467  * Duplicate static symbols within a module confuses mdb; so we avoid the
1468  * problem by making the symbols here distinct from those in udp.c.
1469  */
1470 
1471 static struct qinit iprinit = {
1472 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1473 	&ip_mod_info
1474 };
1475 
1476 static struct qinit ipwinit = {
1477 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1478 	&ip_mod_info
1479 };
1480 
1481 static struct qinit iplrinit = {
1482 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1483 	&ip_mod_info
1484 };
1485 
1486 static struct qinit iplwinit = {
1487 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1488 	&ip_mod_info
1489 };
1490 
1491 struct streamtab ipinfo = {
1492 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1493 };
1494 
1495 #ifdef	DEBUG
1496 static boolean_t skip_sctp_cksum = B_FALSE;
1497 #endif
1498 /*
1499  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1500  */
1501 mblk_t *
1502 ip_copymsg(mblk_t *mp)
1503 {
1504 	mblk_t *nmp;
1505 	ipsec_info_t *in;
1506 
1507 	if (mp->b_datap->db_type != M_CTL)
1508 		return (copymsg(mp));
1509 
1510 	in = (ipsec_info_t *)mp->b_rptr;
1511 
1512 	/*
1513 	 * Note that M_CTL is also used for delivering ICMP error messages
1514 	 * upstream to transport layers.
1515 	 */
1516 	if (in->ipsec_info_type != IPSEC_OUT &&
1517 	    in->ipsec_info_type != IPSEC_IN)
1518 		return (copymsg(mp));
1519 
1520 	nmp = copymsg(mp->b_cont);
1521 
1522 	if (in->ipsec_info_type == IPSEC_OUT)
1523 		return (ipsec_out_tag(mp, nmp));
1524 	else
1525 		return (ipsec_in_tag(mp, nmp));
1526 }
1527 
1528 /* Generate an ICMP fragmentation needed message. */
1529 static void
1530 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu)
1531 {
1532 	icmph_t	icmph;
1533 	mblk_t *first_mp;
1534 	boolean_t mctl_present;
1535 
1536 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1537 
1538 	if (!(mp = icmp_pkt_err_ok(mp))) {
1539 		if (mctl_present)
1540 			freeb(first_mp);
1541 		return;
1542 	}
1543 
1544 	bzero(&icmph, sizeof (icmph_t));
1545 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1546 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1547 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1548 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1549 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1550 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
1551 }
1552 
1553 /*
1554  * icmp_inbound deals with ICMP messages in the following ways.
1555  *
1556  * 1) It needs to send a reply back and possibly delivering it
1557  *    to the "interested" upper clients.
1558  * 2) It needs to send it to the upper clients only.
1559  * 3) It needs to change some values in IP only.
1560  * 4) It needs to change some values in IP and upper layers e.g TCP.
1561  *
1562  * We need to accomodate icmp messages coming in clear until we get
1563  * everything secure from the wire. If icmp_accept_clear_messages
1564  * is zero we check with the global policy and act accordingly. If
1565  * it is non-zero, we accept the message without any checks. But
1566  * *this does not mean* that this will be delivered to the upper
1567  * clients. By accepting we might send replies back, change our MTU
1568  * value etc. but delivery to the ULP/clients depends on their policy
1569  * dispositions.
1570  *
1571  * We handle the above 4 cases in the context of IPSEC in the
1572  * following way :
1573  *
1574  * 1) Send the reply back in the same way as the request came in.
1575  *    If it came in encrypted, it goes out encrypted. If it came in
1576  *    clear, it goes out in clear. Thus, this will prevent chosen
1577  *    plain text attack.
1578  * 2) The client may or may not expect things to come in secure.
1579  *    If it comes in secure, the policy constraints are checked
1580  *    before delivering it to the upper layers. If it comes in
1581  *    clear, ipsec_inbound_accept_clear will decide whether to
1582  *    accept this in clear or not. In both the cases, if the returned
1583  *    message (IP header + 8 bytes) that caused the icmp message has
1584  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1585  *    sending up. If there are only 8 bytes of returned message, then
1586  *    upper client will not be notified.
1587  * 3) Check with global policy to see whether it matches the constaints.
1588  *    But this will be done only if icmp_accept_messages_in_clear is
1589  *    zero.
1590  * 4) If we need to change both in IP and ULP, then the decision taken
1591  *    while affecting the values in IP and while delivering up to TCP
1592  *    should be the same.
1593  *
1594  * 	There are two cases.
1595  *
1596  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1597  *	   failed), we will not deliver it to the ULP, even though they
1598  *	   are *willing* to accept in *clear*. This is fine as our global
1599  *	   disposition to icmp messages asks us reject the datagram.
1600  *
1601  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1602  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1603  *	   to deliver it to ULP (policy failed), it can lead to
1604  *	   consistency problems. The cases known at this time are
1605  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1606  *	   values :
1607  *
1608  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1609  *	     and Upper layer rejects. Then the communication will
1610  *	     come to a stop. This is solved by making similar decisions
1611  *	     at both levels. Currently, when we are unable to deliver
1612  *	     to the Upper Layer (due to policy failures) while IP has
1613  *	     adjusted ire_max_frag, the next outbound datagram would
1614  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1615  *	     will be with the right level of protection. Thus the right
1616  *	     value will be communicated even if we are not able to
1617  *	     communicate when we get from the wire initially. But this
1618  *	     assumes there would be at least one outbound datagram after
1619  *	     IP has adjusted its ire_max_frag value. To make things
1620  *	     simpler, we accept in clear after the validation of
1621  *	     AH/ESP headers.
1622  *
1623  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1624  *	     upper layer depending on the level of protection the upper
1625  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1626  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1627  *	     should be accepted in clear when the Upper layer expects secure.
1628  *	     Thus the communication may get aborted by some bad ICMP
1629  *	     packets.
1630  *
1631  * IPQoS Notes:
1632  * The only instance when a packet is sent for processing is when there
1633  * isn't an ICMP client and if we are interested in it.
1634  * If there is a client, IPPF processing will take place in the
1635  * ip_fanout_proto routine.
1636  *
1637  * Zones notes:
1638  * The packet is only processed in the context of the specified zone: typically
1639  * only this zone will reply to an echo request, and only interested clients in
1640  * this zone will receive a copy of the packet. This means that the caller must
1641  * call icmp_inbound() for each relevant zone.
1642  */
1643 static void
1644 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1645     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1646     ill_t *recv_ill, zoneid_t zoneid)
1647 {
1648 	icmph_t	*icmph;
1649 	ipha_t	*ipha;
1650 	int	iph_hdr_length;
1651 	int	hdr_length;
1652 	boolean_t	interested;
1653 	uint32_t	ts;
1654 	uchar_t	*wptr;
1655 	ipif_t	*ipif;
1656 	mblk_t *first_mp;
1657 	ipsec_in_t *ii;
1658 	ire_t *src_ire;
1659 	boolean_t onlink;
1660 	timestruc_t now;
1661 	uint32_t ill_index;
1662 
1663 	ASSERT(ill != NULL);
1664 
1665 	first_mp = mp;
1666 	if (mctl_present) {
1667 		mp = first_mp->b_cont;
1668 		ASSERT(mp != NULL);
1669 	}
1670 
1671 	ipha = (ipha_t *)mp->b_rptr;
1672 	if (icmp_accept_clear_messages == 0) {
1673 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1674 		    ipha, NULL, mctl_present);
1675 		if (first_mp == NULL)
1676 			return;
1677 	}
1678 
1679 	/*
1680 	 * On a labeled system, we have to check whether the zone itself is
1681 	 * permitted to receive raw traffic.
1682 	 */
1683 	if (is_system_labeled()) {
1684 		if (zoneid == ALL_ZONES)
1685 			zoneid = tsol_packet_to_zoneid(mp);
1686 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1687 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1688 			    zoneid));
1689 			BUMP_MIB(&icmp_mib, icmpInErrors);
1690 			freemsg(first_mp);
1691 			return;
1692 		}
1693 	}
1694 
1695 	/*
1696 	 * We have accepted the ICMP message. It means that we will
1697 	 * respond to the packet if needed. It may not be delivered
1698 	 * to the upper client depending on the policy constraints
1699 	 * and the disposition in ipsec_inbound_accept_clear.
1700 	 */
1701 
1702 	ASSERT(ill != NULL);
1703 
1704 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1705 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1706 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1707 		/* Last chance to get real. */
1708 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1709 			BUMP_MIB(&icmp_mib, icmpInErrors);
1710 			freemsg(first_mp);
1711 			return;
1712 		}
1713 		/* Refresh iph following the pullup. */
1714 		ipha = (ipha_t *)mp->b_rptr;
1715 	}
1716 	/* ICMP header checksum, including checksum field, should be zero. */
1717 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1718 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1719 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1720 		freemsg(first_mp);
1721 		return;
1722 	}
1723 	/* The IP header will always be a multiple of four bytes */
1724 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1725 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1726 	    icmph->icmph_code));
1727 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1728 	/* We will set "interested" to "true" if we want a copy */
1729 	interested = B_FALSE;
1730 	switch (icmph->icmph_type) {
1731 	case ICMP_ECHO_REPLY:
1732 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1733 		break;
1734 	case ICMP_DEST_UNREACHABLE:
1735 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1736 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1737 		interested = B_TRUE;	/* Pass up to transport */
1738 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1739 		break;
1740 	case ICMP_SOURCE_QUENCH:
1741 		interested = B_TRUE;	/* Pass up to transport */
1742 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1743 		break;
1744 	case ICMP_REDIRECT:
1745 		if (!ip_ignore_redirect)
1746 			interested = B_TRUE;
1747 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1748 		break;
1749 	case ICMP_ECHO_REQUEST:
1750 		/*
1751 		 * Whether to respond to echo requests that come in as IP
1752 		 * broadcasts or as IP multicast is subject to debate
1753 		 * (what isn't?).  We aim to please, you pick it.
1754 		 * Default is do it.
1755 		 */
1756 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1757 			/* unicast: always respond */
1758 			interested = B_TRUE;
1759 		} else if (CLASSD(ipha->ipha_dst)) {
1760 			/* multicast: respond based on tunable */
1761 			interested = ip_g_resp_to_echo_mcast;
1762 		} else if (broadcast) {
1763 			/* broadcast: respond based on tunable */
1764 			interested = ip_g_resp_to_echo_bcast;
1765 		}
1766 		BUMP_MIB(&icmp_mib, icmpInEchos);
1767 		break;
1768 	case ICMP_ROUTER_ADVERTISEMENT:
1769 	case ICMP_ROUTER_SOLICITATION:
1770 		break;
1771 	case ICMP_TIME_EXCEEDED:
1772 		interested = B_TRUE;	/* Pass up to transport */
1773 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1774 		break;
1775 	case ICMP_PARAM_PROBLEM:
1776 		interested = B_TRUE;	/* Pass up to transport */
1777 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1778 		break;
1779 	case ICMP_TIME_STAMP_REQUEST:
1780 		/* Response to Time Stamp Requests is local policy. */
1781 		if (ip_g_resp_to_timestamp &&
1782 		    /* So is whether to respond if it was an IP broadcast. */
1783 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1784 			int tstamp_len = 3 * sizeof (uint32_t);
1785 
1786 			if (wptr +  tstamp_len > mp->b_wptr) {
1787 				if (!pullupmsg(mp, wptr + tstamp_len -
1788 				    mp->b_rptr)) {
1789 					BUMP_MIB(&ip_mib, ipInDiscards);
1790 					freemsg(first_mp);
1791 					return;
1792 				}
1793 				/* Refresh ipha following the pullup. */
1794 				ipha = (ipha_t *)mp->b_rptr;
1795 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1796 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1797 			}
1798 			interested = B_TRUE;
1799 		}
1800 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1801 		break;
1802 	case ICMP_TIME_STAMP_REPLY:
1803 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1804 		break;
1805 	case ICMP_INFO_REQUEST:
1806 		/* Per RFC 1122 3.2.2.7, ignore this. */
1807 	case ICMP_INFO_REPLY:
1808 		break;
1809 	case ICMP_ADDRESS_MASK_REQUEST:
1810 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1811 		    /* TODO m_pullup of complete header? */
1812 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1813 			interested = B_TRUE;
1814 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1815 		break;
1816 	case ICMP_ADDRESS_MASK_REPLY:
1817 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1818 		break;
1819 	default:
1820 		interested = B_TRUE;	/* Pass up to transport */
1821 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1822 		break;
1823 	}
1824 	/* See if there is an ICMP client. */
1825 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1826 		/* If there is an ICMP client and we want one too, copy it. */
1827 		mblk_t *first_mp1;
1828 
1829 		if (!interested) {
1830 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1831 			    ip_policy, recv_ill, zoneid);
1832 			return;
1833 		}
1834 		first_mp1 = ip_copymsg(first_mp);
1835 		if (first_mp1 != NULL) {
1836 			ip_fanout_proto(q, first_mp1, ill, ipha,
1837 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1838 		}
1839 	} else if (!interested) {
1840 		freemsg(first_mp);
1841 		return;
1842 	} else {
1843 		/*
1844 		 * Initiate policy processing for this packet if ip_policy
1845 		 * is true.
1846 		 */
1847 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1848 			ill_index = ill->ill_phyint->phyint_ifindex;
1849 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1850 			if (mp == NULL) {
1851 				if (mctl_present) {
1852 					freeb(first_mp);
1853 				}
1854 				BUMP_MIB(&icmp_mib, icmpInErrors);
1855 				return;
1856 			}
1857 		}
1858 	}
1859 	/* We want to do something with it. */
1860 	/* Check db_ref to make sure we can modify the packet. */
1861 	if (mp->b_datap->db_ref > 1) {
1862 		mblk_t	*first_mp1;
1863 
1864 		first_mp1 = ip_copymsg(first_mp);
1865 		freemsg(first_mp);
1866 		if (!first_mp1) {
1867 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1868 			return;
1869 		}
1870 		first_mp = first_mp1;
1871 		if (mctl_present) {
1872 			mp = first_mp->b_cont;
1873 			ASSERT(mp != NULL);
1874 		} else {
1875 			mp = first_mp;
1876 		}
1877 		ipha = (ipha_t *)mp->b_rptr;
1878 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1879 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1880 	}
1881 	switch (icmph->icmph_type) {
1882 	case ICMP_ADDRESS_MASK_REQUEST:
1883 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1884 		if (ipif == NULL) {
1885 			freemsg(first_mp);
1886 			return;
1887 		}
1888 		/*
1889 		 * outging interface must be IPv4
1890 		 */
1891 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1892 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1893 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1894 		ipif_refrele(ipif);
1895 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1896 		break;
1897 	case ICMP_ECHO_REQUEST:
1898 		icmph->icmph_type = ICMP_ECHO_REPLY;
1899 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1900 		break;
1901 	case ICMP_TIME_STAMP_REQUEST: {
1902 		uint32_t *tsp;
1903 
1904 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1905 		tsp = (uint32_t *)wptr;
1906 		tsp++;		/* Skip past 'originate time' */
1907 		/* Compute # of milliseconds since midnight */
1908 		gethrestime(&now);
1909 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1910 		    now.tv_nsec / (NANOSEC / MILLISEC);
1911 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1912 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1913 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1914 		break;
1915 	}
1916 	default:
1917 		ipha = (ipha_t *)&icmph[1];
1918 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1919 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1920 				BUMP_MIB(&ip_mib, ipInDiscards);
1921 				freemsg(first_mp);
1922 				return;
1923 			}
1924 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1925 			ipha = (ipha_t *)&icmph[1];
1926 		}
1927 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1928 			BUMP_MIB(&ip_mib, ipInDiscards);
1929 			freemsg(first_mp);
1930 			return;
1931 		}
1932 		hdr_length = IPH_HDR_LENGTH(ipha);
1933 		if (hdr_length < sizeof (ipha_t)) {
1934 			BUMP_MIB(&ip_mib, ipInDiscards);
1935 			freemsg(first_mp);
1936 			return;
1937 		}
1938 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1939 			if (!pullupmsg(mp,
1940 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1941 				BUMP_MIB(&ip_mib, ipInDiscards);
1942 				freemsg(first_mp);
1943 				return;
1944 			}
1945 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1946 			ipha = (ipha_t *)&icmph[1];
1947 		}
1948 		switch (icmph->icmph_type) {
1949 		case ICMP_REDIRECT:
1950 			/*
1951 			 * As there is no upper client to deliver, we don't
1952 			 * need the first_mp any more.
1953 			 */
1954 			if (mctl_present) {
1955 				freeb(first_mp);
1956 			}
1957 			icmp_redirect(mp);
1958 			return;
1959 		case ICMP_DEST_UNREACHABLE:
1960 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1961 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1962 				    zoneid, mp, iph_hdr_length)) {
1963 					freemsg(first_mp);
1964 					return;
1965 				}
1966 				/*
1967 				 * icmp_inbound_too_big() may alter mp.
1968 				 * Resynch ipha and icmph accordingly.
1969 				 */
1970 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1971 				ipha = (ipha_t *)&icmph[1];
1972 			}
1973 			/* FALLTHRU */
1974 		default :
1975 			/*
1976 			 * IPQoS notes: Since we have already done IPQoS
1977 			 * processing we don't want to do it again in
1978 			 * the fanout routines called by
1979 			 * icmp_inbound_error_fanout, hence the last
1980 			 * argument, ip_policy, is B_FALSE.
1981 			 */
1982 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1983 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1984 			    B_FALSE, recv_ill, zoneid);
1985 		}
1986 		return;
1987 	}
1988 	/* Send out an ICMP packet */
1989 	icmph->icmph_checksum = 0;
1990 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1991 	if (icmph->icmph_checksum == 0)
1992 		icmph->icmph_checksum = 0xFFFF;
1993 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1994 		ipif_t	*ipif_chosen;
1995 		/*
1996 		 * Make it look like it was directed to us, so we don't look
1997 		 * like a fool with a broadcast or multicast source address.
1998 		 */
1999 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2000 		/*
2001 		 * Make sure that we haven't grabbed an interface that's DOWN.
2002 		 */
2003 		if (ipif != NULL) {
2004 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2005 			    ipha->ipha_src, zoneid);
2006 			if (ipif_chosen != NULL) {
2007 				ipif_refrele(ipif);
2008 				ipif = ipif_chosen;
2009 			}
2010 		}
2011 		if (ipif == NULL) {
2012 			ip0dbg(("icmp_inbound: "
2013 			    "No source for broadcast/multicast:\n"
2014 			    "\tsrc 0x%x dst 0x%x ill %p "
2015 			    "ipif_lcl_addr 0x%x\n",
2016 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2017 			    (void *)ill,
2018 			    ill->ill_ipif->ipif_lcl_addr));
2019 			freemsg(first_mp);
2020 			return;
2021 		}
2022 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2023 		ipha->ipha_dst = ipif->ipif_src_addr;
2024 		ipif_refrele(ipif);
2025 	}
2026 	/* Reset time to live. */
2027 	ipha->ipha_ttl = ip_def_ttl;
2028 	{
2029 		/* Swap source and destination addresses */
2030 		ipaddr_t tmp;
2031 
2032 		tmp = ipha->ipha_src;
2033 		ipha->ipha_src = ipha->ipha_dst;
2034 		ipha->ipha_dst = tmp;
2035 	}
2036 	ipha->ipha_ident = 0;
2037 	if (!IS_SIMPLE_IPH(ipha))
2038 		icmp_options_update(ipha);
2039 
2040 	/*
2041 	 * ICMP echo replies should go out on the same interface
2042 	 * the request came on as probes used by in.mpathd for detecting
2043 	 * NIC failures are ECHO packets. We turn-off load spreading
2044 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2045 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2046 	 * function. This is in turn handled by ip_wput and ip_newroute
2047 	 * to make sure that the packet goes out on the interface it came
2048 	 * in on. If we don't turnoff load spreading, the packets might get
2049 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2050 	 * to go out and in.mpathd would wrongly detect a failure or
2051 	 * mis-detect a NIC failure for link failure. As load spreading
2052 	 * can happen only if ill_group is not NULL, we do only for
2053 	 * that case and this does not affect the normal case.
2054 	 *
2055 	 * We turn off load spreading only on echo packets that came from
2056 	 * on-link hosts. If the interface route has been deleted, this will
2057 	 * not be enforced as we can't do much. For off-link hosts, as the
2058 	 * default routes in IPv4 does not typically have an ire_ipif
2059 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2060 	 * Moreover, expecting a default route through this interface may
2061 	 * not be correct. We use ipha_dst because of the swap above.
2062 	 */
2063 	onlink = B_FALSE;
2064 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2065 		/*
2066 		 * First, we need to make sure that it is not one of our
2067 		 * local addresses. If we set onlink when it is one of
2068 		 * our local addresses, we will end up creating IRE_CACHES
2069 		 * for one of our local addresses. Then, we will never
2070 		 * accept packets for them afterwards.
2071 		 */
2072 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2073 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2074 		if (src_ire == NULL) {
2075 			ipif = ipif_get_next_ipif(NULL, ill);
2076 			if (ipif == NULL) {
2077 				BUMP_MIB(&ip_mib, ipInDiscards);
2078 				freemsg(mp);
2079 				return;
2080 			}
2081 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2082 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2083 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2084 			ipif_refrele(ipif);
2085 			if (src_ire != NULL) {
2086 				onlink = B_TRUE;
2087 				ire_refrele(src_ire);
2088 			}
2089 		} else {
2090 			ire_refrele(src_ire);
2091 		}
2092 	}
2093 	if (!mctl_present) {
2094 		/*
2095 		 * This packet should go out the same way as it
2096 		 * came in i.e in clear. To make sure that global
2097 		 * policy will not be applied to this in ip_wput_ire,
2098 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2099 		 */
2100 		ASSERT(first_mp == mp);
2101 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2102 			BUMP_MIB(&ip_mib, ipInDiscards);
2103 			freemsg(mp);
2104 			return;
2105 		}
2106 		ii = (ipsec_in_t *)first_mp->b_rptr;
2107 
2108 		/* This is not a secure packet */
2109 		ii->ipsec_in_secure = B_FALSE;
2110 		if (onlink) {
2111 			ii->ipsec_in_attach_if = B_TRUE;
2112 			ii->ipsec_in_ill_index =
2113 			    ill->ill_phyint->phyint_ifindex;
2114 			ii->ipsec_in_rill_index =
2115 			    recv_ill->ill_phyint->phyint_ifindex;
2116 		}
2117 		first_mp->b_cont = mp;
2118 	} else if (onlink) {
2119 		ii = (ipsec_in_t *)first_mp->b_rptr;
2120 		ii->ipsec_in_attach_if = B_TRUE;
2121 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2122 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2123 	} else {
2124 		ii = (ipsec_in_t *)first_mp->b_rptr;
2125 	}
2126 	ii->ipsec_in_zoneid = zoneid;
2127 	ASSERT(zoneid != ALL_ZONES);
2128 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2129 		BUMP_MIB(&ip_mib, ipInDiscards);
2130 		return;
2131 	}
2132 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2133 	put(WR(q), first_mp);
2134 }
2135 
2136 static ipaddr_t
2137 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2138 {
2139 	conn_t *connp;
2140 	connf_t *connfp;
2141 	ipaddr_t nexthop_addr = INADDR_ANY;
2142 	int hdr_length = IPH_HDR_LENGTH(ipha);
2143 	uint16_t *up;
2144 	uint32_t ports;
2145 
2146 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2147 	switch (ipha->ipha_protocol) {
2148 		case IPPROTO_TCP:
2149 		{
2150 			tcph_t *tcph;
2151 
2152 			/* do a reverse lookup */
2153 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2154 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2155 			    TCPS_LISTEN);
2156 			break;
2157 		}
2158 		case IPPROTO_UDP:
2159 		{
2160 			uint32_t dstport, srcport;
2161 
2162 			((uint16_t *)&ports)[0] = up[1];
2163 			((uint16_t *)&ports)[1] = up[0];
2164 
2165 			/* Extract ports in net byte order */
2166 			dstport = htons(ntohl(ports) & 0xFFFF);
2167 			srcport = htons(ntohl(ports) >> 16);
2168 
2169 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2170 			mutex_enter(&connfp->connf_lock);
2171 			connp = connfp->connf_head;
2172 
2173 			/* do a reverse lookup */
2174 			while ((connp != NULL) &&
2175 			    (!IPCL_UDP_MATCH(connp, dstport,
2176 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2177 			    connp->conn_zoneid != zoneid)) {
2178 				connp = connp->conn_next;
2179 			}
2180 			if (connp != NULL)
2181 				CONN_INC_REF(connp);
2182 			mutex_exit(&connfp->connf_lock);
2183 			break;
2184 		}
2185 		case IPPROTO_SCTP:
2186 		{
2187 			in6_addr_t map_src, map_dst;
2188 
2189 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2190 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2191 			((uint16_t *)&ports)[0] = up[1];
2192 			((uint16_t *)&ports)[1] = up[0];
2193 
2194 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2195 			    0, zoneid)) == NULL) {
2196 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2197 				    zoneid, ports, ipha);
2198 			} else {
2199 				CONN_INC_REF(connp);
2200 				SCTP_REFRELE(CONN2SCTP(connp));
2201 			}
2202 			break;
2203 		}
2204 		default:
2205 		{
2206 			ipha_t ripha;
2207 
2208 			ripha.ipha_src = ipha->ipha_dst;
2209 			ripha.ipha_dst = ipha->ipha_src;
2210 			ripha.ipha_protocol = ipha->ipha_protocol;
2211 
2212 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2213 			mutex_enter(&connfp->connf_lock);
2214 			connp = connfp->connf_head;
2215 			for (connp = connfp->connf_head; connp != NULL;
2216 			    connp = connp->conn_next) {
2217 				if (IPCL_PROTO_MATCH(connp,
2218 				    ipha->ipha_protocol, &ripha, ill,
2219 				    0, zoneid)) {
2220 					CONN_INC_REF(connp);
2221 					break;
2222 				}
2223 			}
2224 			mutex_exit(&connfp->connf_lock);
2225 		}
2226 	}
2227 	if (connp != NULL) {
2228 		if (connp->conn_nexthop_set)
2229 			nexthop_addr = connp->conn_nexthop_v4;
2230 		CONN_DEC_REF(connp);
2231 	}
2232 	return (nexthop_addr);
2233 }
2234 
2235 /* Table from RFC 1191 */
2236 static int icmp_frag_size_table[] =
2237 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2238 
2239 /*
2240  * Process received ICMP Packet too big.
2241  * After updating any IRE it does the fanout to any matching transport streams.
2242  * Assumes the message has been pulled up till the IP header that caused
2243  * the error.
2244  *
2245  * Returns B_FALSE on failure and B_TRUE on success.
2246  */
2247 static boolean_t
2248 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2249     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2250 {
2251 	ire_t	*ire, *first_ire;
2252 	int	mtu;
2253 	int	hdr_length;
2254 	ipaddr_t nexthop_addr;
2255 
2256 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2257 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2258 
2259 	hdr_length = IPH_HDR_LENGTH(ipha);
2260 
2261 	/* Drop if the original packet contained a source route */
2262 	if (ip_source_route_included(ipha)) {
2263 		return (B_FALSE);
2264 	}
2265 	/*
2266 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2267 	 * header.
2268 	 */
2269 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2270 	    mp->b_wptr) {
2271 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2272 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2273 			BUMP_MIB(&ip_mib, ipInDiscards);
2274 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2275 			return (B_FALSE);
2276 		}
2277 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2278 		ipha = (ipha_t *)&icmph[1];
2279 	}
2280 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2281 	if (nexthop_addr != INADDR_ANY) {
2282 		/* nexthop set */
2283 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2284 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2285 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2286 	} else {
2287 		/* nexthop not set */
2288 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2289 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2290 	}
2291 
2292 	if (!first_ire) {
2293 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2294 		    ntohl(ipha->ipha_dst)));
2295 		return (B_FALSE);
2296 	}
2297 	/* Check for MTU discovery advice as described in RFC 1191 */
2298 	mtu = ntohs(icmph->icmph_du_mtu);
2299 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2300 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2301 	    ire = ire->ire_next) {
2302 		/*
2303 		 * Look for the connection to which this ICMP message is
2304 		 * directed. If it has the IP_NEXTHOP option set, then the
2305 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2306 		 * option. Else the search is limited to regular IREs.
2307 		 */
2308 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2309 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2310 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2311 		    (nexthop_addr != INADDR_ANY)))
2312 			continue;
2313 
2314 		mutex_enter(&ire->ire_lock);
2315 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2316 			/* Reduce the IRE max frag value as advised. */
2317 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2318 			    mtu, ire->ire_max_frag));
2319 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2320 		} else {
2321 			uint32_t length;
2322 			int	i;
2323 
2324 			/*
2325 			 * Use the table from RFC 1191 to figure out
2326 			 * the next "plateau" based on the length in
2327 			 * the original IP packet.
2328 			 */
2329 			length = ntohs(ipha->ipha_length);
2330 			if (ire->ire_max_frag <= length &&
2331 			    ire->ire_max_frag >= length - hdr_length) {
2332 				/*
2333 				 * Handle broken BSD 4.2 systems that
2334 				 * return the wrong iph_length in ICMP
2335 				 * errors.
2336 				 */
2337 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2338 				    length, ire->ire_max_frag));
2339 				length -= hdr_length;
2340 			}
2341 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2342 				if (length > icmp_frag_size_table[i])
2343 					break;
2344 			}
2345 			if (i == A_CNT(icmp_frag_size_table)) {
2346 				/* Smaller than 68! */
2347 				ip1dbg(("Too big for packet size %d\n",
2348 				    length));
2349 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2350 				ire->ire_frag_flag = 0;
2351 			} else {
2352 				mtu = icmp_frag_size_table[i];
2353 				ip1dbg(("Calculated mtu %d, packet size %d, "
2354 				    "before %d", mtu, length,
2355 				    ire->ire_max_frag));
2356 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2357 				ip1dbg((", after %d\n", ire->ire_max_frag));
2358 			}
2359 			/* Record the new max frag size for the ULP. */
2360 			icmph->icmph_du_zero = 0;
2361 			icmph->icmph_du_mtu =
2362 			    htons((uint16_t)ire->ire_max_frag);
2363 		}
2364 		mutex_exit(&ire->ire_lock);
2365 	}
2366 	rw_exit(&first_ire->ire_bucket->irb_lock);
2367 	ire_refrele(first_ire);
2368 	return (B_TRUE);
2369 }
2370 
2371 /*
2372  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2373  * calls this function.
2374  */
2375 static mblk_t *
2376 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2377 {
2378 	ipha_t *ipha;
2379 	icmph_t *icmph;
2380 	ipha_t *in_ipha;
2381 	int length;
2382 
2383 	ASSERT(mp->b_datap->db_type == M_DATA);
2384 
2385 	/*
2386 	 * For Self-encapsulated packets, we added an extra IP header
2387 	 * without the options. Inner IP header is the one from which
2388 	 * the outer IP header was formed. Thus, we need to remove the
2389 	 * outer IP header. To do this, we pullup the whole message
2390 	 * and overlay whatever follows the outer IP header over the
2391 	 * outer IP header.
2392 	 */
2393 
2394 	if (!pullupmsg(mp, -1)) {
2395 		BUMP_MIB(&ip_mib, ipInDiscards);
2396 		return (NULL);
2397 	}
2398 
2399 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2400 	ipha = (ipha_t *)&icmph[1];
2401 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2402 
2403 	/*
2404 	 * The length that we want to overlay is following the inner
2405 	 * IP header. Subtracting the IP header + icmp header + outer
2406 	 * IP header's length should give us the length that we want to
2407 	 * overlay.
2408 	 */
2409 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2410 	    hdr_length;
2411 	/*
2412 	 * Overlay whatever follows the inner header over the
2413 	 * outer header.
2414 	 */
2415 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2416 
2417 	/* Set the wptr to account for the outer header */
2418 	mp->b_wptr -= hdr_length;
2419 	return (mp);
2420 }
2421 
2422 /*
2423  * Try to pass the ICMP message upstream in case the ULP cares.
2424  *
2425  * If the packet that caused the ICMP error is secure, we send
2426  * it to AH/ESP to make sure that the attached packet has a
2427  * valid association. ipha in the code below points to the
2428  * IP header of the packet that caused the error.
2429  *
2430  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2431  * in the context of IPSEC. Normally we tell the upper layer
2432  * whenever we send the ire (including ip_bind), the IPSEC header
2433  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2434  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2435  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2436  * same thing. As TCP has the IPSEC options size that needs to be
2437  * adjusted, we just pass the MTU unchanged.
2438  *
2439  * IFN could have been generated locally or by some router.
2440  *
2441  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2442  *	    This happens because IP adjusted its value of MTU on an
2443  *	    earlier IFN message and could not tell the upper layer,
2444  *	    the new adjusted value of MTU e.g. Packet was encrypted
2445  *	    or there was not enough information to fanout to upper
2446  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2447  *	    generates the IFN, where IPSEC processing has *not* been
2448  *	    done.
2449  *
2450  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2451  *	    could have generated this. This happens because ire_max_frag
2452  *	    value in IP was set to a new value, while the IPSEC processing
2453  *	    was being done and after we made the fragmentation check in
2454  *	    ip_wput_ire. Thus on return from IPSEC processing,
2455  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2456  *	    and generates the IFN. As IPSEC processing is over, we fanout
2457  *	    to AH/ESP to remove the header.
2458  *
2459  *	    In both these cases, ipsec_in_loopback will be set indicating
2460  *	    that IFN was generated locally.
2461  *
2462  * ROUTER : IFN could be secure or non-secure.
2463  *
2464  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2465  *	      packet in error has AH/ESP headers to validate the AH/ESP
2466  *	      headers. AH/ESP will verify whether there is a valid SA or
2467  *	      not and send it back. We will fanout again if we have more
2468  *	      data in the packet.
2469  *
2470  *	      If the packet in error does not have AH/ESP, we handle it
2471  *	      like any other case.
2472  *
2473  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2474  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2475  *	      for validation. AH/ESP will verify whether there is a
2476  *	      valid SA or not and send it back. We will fanout again if
2477  *	      we have more data in the packet.
2478  *
2479  *	      If the packet in error does not have AH/ESP, we handle it
2480  *	      like any other case.
2481  */
2482 static void
2483 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2484     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2485     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2486     zoneid_t zoneid)
2487 {
2488 	uint16_t *up;	/* Pointer to ports in ULP header */
2489 	uint32_t ports;	/* reversed ports for fanout */
2490 	ipha_t ripha;	/* With reversed addresses */
2491 	mblk_t *first_mp;
2492 	ipsec_in_t *ii;
2493 	tcph_t	*tcph;
2494 	conn_t	*connp;
2495 
2496 	first_mp = mp;
2497 	if (mctl_present) {
2498 		mp = first_mp->b_cont;
2499 		ASSERT(mp != NULL);
2500 
2501 		ii = (ipsec_in_t *)first_mp->b_rptr;
2502 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2503 	} else {
2504 		ii = NULL;
2505 	}
2506 
2507 	switch (ipha->ipha_protocol) {
2508 	case IPPROTO_UDP:
2509 		/*
2510 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2511 		 * transport header.
2512 		 */
2513 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2514 		    mp->b_wptr) {
2515 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2516 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2517 				BUMP_MIB(&ip_mib, ipInDiscards);
2518 				goto drop_pkt;
2519 			}
2520 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2521 			ipha = (ipha_t *)&icmph[1];
2522 		}
2523 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2524 
2525 		/*
2526 		 * Attempt to find a client stream based on port.
2527 		 * Note that we do a reverse lookup since the header is
2528 		 * in the form we sent it out.
2529 		 * The ripha header is only used for the IP_UDP_MATCH and we
2530 		 * only set the src and dst addresses and protocol.
2531 		 */
2532 		ripha.ipha_src = ipha->ipha_dst;
2533 		ripha.ipha_dst = ipha->ipha_src;
2534 		ripha.ipha_protocol = ipha->ipha_protocol;
2535 		((uint16_t *)&ports)[0] = up[1];
2536 		((uint16_t *)&ports)[1] = up[0];
2537 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2538 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2539 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2540 		    icmph->icmph_type, icmph->icmph_code));
2541 
2542 		/* Have to change db_type after any pullupmsg */
2543 		DB_TYPE(mp) = M_CTL;
2544 
2545 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2546 		    mctl_present, ip_policy, recv_ill, zoneid);
2547 		return;
2548 
2549 	case IPPROTO_TCP:
2550 		/*
2551 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2552 		 * transport header.
2553 		 */
2554 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2555 		    mp->b_wptr) {
2556 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2557 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2558 				BUMP_MIB(&ip_mib, ipInDiscards);
2559 				goto drop_pkt;
2560 			}
2561 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2562 			ipha = (ipha_t *)&icmph[1];
2563 		}
2564 		/*
2565 		 * Find a TCP client stream for this packet.
2566 		 * Note that we do a reverse lookup since the header is
2567 		 * in the form we sent it out.
2568 		 */
2569 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2570 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2571 		if (connp == NULL) {
2572 			BUMP_MIB(&ip_mib, ipInDiscards);
2573 			goto drop_pkt;
2574 		}
2575 
2576 		/* Have to change db_type after any pullupmsg */
2577 		DB_TYPE(mp) = M_CTL;
2578 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2579 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2580 		return;
2581 
2582 	case IPPROTO_SCTP:
2583 		/*
2584 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2585 		 * transport header.
2586 		 */
2587 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2588 		    mp->b_wptr) {
2589 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2590 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2591 				BUMP_MIB(&ip_mib, ipInDiscards);
2592 				goto drop_pkt;
2593 			}
2594 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2595 			ipha = (ipha_t *)&icmph[1];
2596 		}
2597 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2598 		/*
2599 		 * Find a SCTP client stream for this packet.
2600 		 * Note that we do a reverse lookup since the header is
2601 		 * in the form we sent it out.
2602 		 * The ripha header is only used for the matching and we
2603 		 * only set the src and dst addresses, protocol, and version.
2604 		 */
2605 		ripha.ipha_src = ipha->ipha_dst;
2606 		ripha.ipha_dst = ipha->ipha_src;
2607 		ripha.ipha_protocol = ipha->ipha_protocol;
2608 		ripha.ipha_version_and_hdr_length =
2609 		    ipha->ipha_version_and_hdr_length;
2610 		((uint16_t *)&ports)[0] = up[1];
2611 		((uint16_t *)&ports)[1] = up[0];
2612 
2613 		/* Have to change db_type after any pullupmsg */
2614 		DB_TYPE(mp) = M_CTL;
2615 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2616 		    mctl_present, ip_policy, 0, zoneid);
2617 		return;
2618 
2619 	case IPPROTO_ESP:
2620 	case IPPROTO_AH: {
2621 		int ipsec_rc;
2622 
2623 		/*
2624 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2625 		 * We will re-use the IPSEC_IN if it is already present as
2626 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2627 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2628 		 * one and attach it in the front.
2629 		 */
2630 		if (ii != NULL) {
2631 			/*
2632 			 * ip_fanout_proto_again converts the ICMP errors
2633 			 * that come back from AH/ESP to M_DATA so that
2634 			 * if it is non-AH/ESP and we do a pullupmsg in
2635 			 * this function, it would work. Convert it back
2636 			 * to M_CTL before we send up as this is a ICMP
2637 			 * error. This could have been generated locally or
2638 			 * by some router. Validate the inner IPSEC
2639 			 * headers.
2640 			 *
2641 			 * NOTE : ill_index is used by ip_fanout_proto_again
2642 			 * to locate the ill.
2643 			 */
2644 			ASSERT(ill != NULL);
2645 			ii->ipsec_in_ill_index =
2646 			    ill->ill_phyint->phyint_ifindex;
2647 			ii->ipsec_in_rill_index =
2648 			    recv_ill->ill_phyint->phyint_ifindex;
2649 			DB_TYPE(first_mp->b_cont) = M_CTL;
2650 		} else {
2651 			/*
2652 			 * IPSEC_IN is not present. We attach a ipsec_in
2653 			 * message and send up to IPSEC for validating
2654 			 * and removing the IPSEC headers. Clear
2655 			 * ipsec_in_secure so that when we return
2656 			 * from IPSEC, we don't mistakenly think that this
2657 			 * is a secure packet came from the network.
2658 			 *
2659 			 * NOTE : ill_index is used by ip_fanout_proto_again
2660 			 * to locate the ill.
2661 			 */
2662 			ASSERT(first_mp == mp);
2663 			first_mp = ipsec_in_alloc(B_TRUE);
2664 			if (first_mp == NULL) {
2665 				freemsg(mp);
2666 				BUMP_MIB(&ip_mib, ipInDiscards);
2667 				return;
2668 			}
2669 			ii = (ipsec_in_t *)first_mp->b_rptr;
2670 
2671 			/* This is not a secure packet */
2672 			ii->ipsec_in_secure = B_FALSE;
2673 			first_mp->b_cont = mp;
2674 			DB_TYPE(mp) = M_CTL;
2675 			ASSERT(ill != NULL);
2676 			ii->ipsec_in_ill_index =
2677 			    ill->ill_phyint->phyint_ifindex;
2678 			ii->ipsec_in_rill_index =
2679 			    recv_ill->ill_phyint->phyint_ifindex;
2680 		}
2681 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2682 
2683 		if (!ipsec_loaded()) {
2684 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2685 			return;
2686 		}
2687 
2688 		if (ipha->ipha_protocol == IPPROTO_ESP)
2689 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2690 		else
2691 			ipsec_rc = ipsecah_icmp_error(first_mp);
2692 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2693 			return;
2694 
2695 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2696 		return;
2697 	}
2698 	default:
2699 		/*
2700 		 * The ripha header is only used for the lookup and we
2701 		 * only set the src and dst addresses and protocol.
2702 		 */
2703 		ripha.ipha_src = ipha->ipha_dst;
2704 		ripha.ipha_dst = ipha->ipha_src;
2705 		ripha.ipha_protocol = ipha->ipha_protocol;
2706 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2707 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2708 		    ntohl(ipha->ipha_dst),
2709 		    icmph->icmph_type, icmph->icmph_code));
2710 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2711 			ipha_t *in_ipha;
2712 
2713 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2714 			    mp->b_wptr) {
2715 				if (!pullupmsg(mp, (uchar_t *)ipha +
2716 				    hdr_length + sizeof (ipha_t) -
2717 				    mp->b_rptr)) {
2718 
2719 					BUMP_MIB(&ip_mib, ipInDiscards);
2720 					goto drop_pkt;
2721 				}
2722 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2723 				ipha = (ipha_t *)&icmph[1];
2724 			}
2725 			/*
2726 			 * Caller has verified that length has to be
2727 			 * at least the size of IP header.
2728 			 */
2729 			ASSERT(hdr_length >= sizeof (ipha_t));
2730 			/*
2731 			 * Check the sanity of the inner IP header like
2732 			 * we did for the outer header.
2733 			 */
2734 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2735 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2736 				BUMP_MIB(&ip_mib, ipInDiscards);
2737 				goto drop_pkt;
2738 			}
2739 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2740 				BUMP_MIB(&ip_mib, ipInDiscards);
2741 				goto drop_pkt;
2742 			}
2743 			/* Check for Self-encapsulated tunnels */
2744 			if (in_ipha->ipha_src == ipha->ipha_src &&
2745 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2746 
2747 				mp = icmp_inbound_self_encap_error(mp,
2748 				    iph_hdr_length, hdr_length);
2749 				if (mp == NULL)
2750 					goto drop_pkt;
2751 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2752 				ipha = (ipha_t *)&icmph[1];
2753 				hdr_length = IPH_HDR_LENGTH(ipha);
2754 				/*
2755 				 * The packet in error is self-encapsualted.
2756 				 * And we are finding it further encapsulated
2757 				 * which we could not have possibly generated.
2758 				 */
2759 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2760 					BUMP_MIB(&ip_mib, ipInDiscards);
2761 					goto drop_pkt;
2762 				}
2763 				icmp_inbound_error_fanout(q, ill, first_mp,
2764 				    icmph, ipha, iph_hdr_length, hdr_length,
2765 				    mctl_present, ip_policy, recv_ill, zoneid);
2766 				return;
2767 			}
2768 		}
2769 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2770 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2771 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2772 		    ii != NULL &&
2773 		    ii->ipsec_in_loopback &&
2774 		    ii->ipsec_in_secure) {
2775 			/*
2776 			 * For IP tunnels that get a looped-back
2777 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2778 			 * reported new MTU to take into account the IPsec
2779 			 * headers protecting this configured tunnel.
2780 			 *
2781 			 * This allows the tunnel module (tun.c) to blindly
2782 			 * accept the MTU reported in an ICMP "too big"
2783 			 * message.
2784 			 *
2785 			 * Non-looped back ICMP messages will just be
2786 			 * handled by the security protocols (if needed),
2787 			 * and the first subsequent packet will hit this
2788 			 * path.
2789 			 */
2790 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2791 			    ipsec_in_extra_length(first_mp));
2792 		}
2793 		/* Have to change db_type after any pullupmsg */
2794 		DB_TYPE(mp) = M_CTL;
2795 
2796 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2797 		    ip_policy, recv_ill, zoneid);
2798 		return;
2799 	}
2800 	/* NOTREACHED */
2801 drop_pkt:;
2802 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2803 	freemsg(first_mp);
2804 }
2805 
2806 /*
2807  * Common IP options parser.
2808  *
2809  * Setup routine: fill in *optp with options-parsing state, then
2810  * tail-call ipoptp_next to return the first option.
2811  */
2812 uint8_t
2813 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2814 {
2815 	uint32_t totallen; /* total length of all options */
2816 
2817 	totallen = ipha->ipha_version_and_hdr_length -
2818 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2819 	totallen <<= 2;
2820 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2821 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2822 	optp->ipoptp_flags = 0;
2823 	return (ipoptp_next(optp));
2824 }
2825 
2826 /*
2827  * Common IP options parser: extract next option.
2828  */
2829 uint8_t
2830 ipoptp_next(ipoptp_t *optp)
2831 {
2832 	uint8_t *end = optp->ipoptp_end;
2833 	uint8_t *cur = optp->ipoptp_next;
2834 	uint8_t opt, len, pointer;
2835 
2836 	/*
2837 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2838 	 * has been corrupted.
2839 	 */
2840 	ASSERT(cur <= end);
2841 
2842 	if (cur == end)
2843 		return (IPOPT_EOL);
2844 
2845 	opt = cur[IPOPT_OPTVAL];
2846 
2847 	/*
2848 	 * Skip any NOP options.
2849 	 */
2850 	while (opt == IPOPT_NOP) {
2851 		cur++;
2852 		if (cur == end)
2853 			return (IPOPT_EOL);
2854 		opt = cur[IPOPT_OPTVAL];
2855 	}
2856 
2857 	if (opt == IPOPT_EOL)
2858 		return (IPOPT_EOL);
2859 
2860 	/*
2861 	 * Option requiring a length.
2862 	 */
2863 	if ((cur + 1) >= end) {
2864 		optp->ipoptp_flags |= IPOPTP_ERROR;
2865 		return (IPOPT_EOL);
2866 	}
2867 	len = cur[IPOPT_OLEN];
2868 	if (len < 2) {
2869 		optp->ipoptp_flags |= IPOPTP_ERROR;
2870 		return (IPOPT_EOL);
2871 	}
2872 	optp->ipoptp_cur = cur;
2873 	optp->ipoptp_len = len;
2874 	optp->ipoptp_next = cur + len;
2875 	if (cur + len > end) {
2876 		optp->ipoptp_flags |= IPOPTP_ERROR;
2877 		return (IPOPT_EOL);
2878 	}
2879 
2880 	/*
2881 	 * For the options which require a pointer field, make sure
2882 	 * its there, and make sure it points to either something
2883 	 * inside this option, or the end of the option.
2884 	 */
2885 	switch (opt) {
2886 	case IPOPT_RR:
2887 	case IPOPT_TS:
2888 	case IPOPT_LSRR:
2889 	case IPOPT_SSRR:
2890 		if (len <= IPOPT_OFFSET) {
2891 			optp->ipoptp_flags |= IPOPTP_ERROR;
2892 			return (opt);
2893 		}
2894 		pointer = cur[IPOPT_OFFSET];
2895 		if (pointer - 1 > len) {
2896 			optp->ipoptp_flags |= IPOPTP_ERROR;
2897 			return (opt);
2898 		}
2899 		break;
2900 	}
2901 
2902 	/*
2903 	 * Sanity check the pointer field based on the type of the
2904 	 * option.
2905 	 */
2906 	switch (opt) {
2907 	case IPOPT_RR:
2908 	case IPOPT_SSRR:
2909 	case IPOPT_LSRR:
2910 		if (pointer < IPOPT_MINOFF_SR)
2911 			optp->ipoptp_flags |= IPOPTP_ERROR;
2912 		break;
2913 	case IPOPT_TS:
2914 		if (pointer < IPOPT_MINOFF_IT)
2915 			optp->ipoptp_flags |= IPOPTP_ERROR;
2916 		/*
2917 		 * Note that the Internet Timestamp option also
2918 		 * contains two four bit fields (the Overflow field,
2919 		 * and the Flag field), which follow the pointer
2920 		 * field.  We don't need to check that these fields
2921 		 * fall within the length of the option because this
2922 		 * was implicitely done above.  We've checked that the
2923 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2924 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2925 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2926 		 */
2927 		ASSERT(len > IPOPT_POS_OV_FLG);
2928 		break;
2929 	}
2930 
2931 	return (opt);
2932 }
2933 
2934 /*
2935  * Use the outgoing IP header to create an IP_OPTIONS option the way
2936  * it was passed down from the application.
2937  */
2938 int
2939 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2940 {
2941 	ipoptp_t	opts;
2942 	const uchar_t	*opt;
2943 	uint8_t		optval;
2944 	uint8_t		optlen;
2945 	uint32_t	len = 0;
2946 	uchar_t	*buf1 = buf;
2947 
2948 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2949 	len += IP_ADDR_LEN;
2950 	bzero(buf1, IP_ADDR_LEN);
2951 
2952 	/*
2953 	 * OK to cast away const here, as we don't store through the returned
2954 	 * opts.ipoptp_cur pointer.
2955 	 */
2956 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2957 	    optval != IPOPT_EOL;
2958 	    optval = ipoptp_next(&opts)) {
2959 		int	off;
2960 
2961 		opt = opts.ipoptp_cur;
2962 		optlen = opts.ipoptp_len;
2963 		switch (optval) {
2964 		case IPOPT_SSRR:
2965 		case IPOPT_LSRR:
2966 
2967 			/*
2968 			 * Insert ipha_dst as the first entry in the source
2969 			 * route and move down the entries on step.
2970 			 * The last entry gets placed at buf1.
2971 			 */
2972 			buf[IPOPT_OPTVAL] = optval;
2973 			buf[IPOPT_OLEN] = optlen;
2974 			buf[IPOPT_OFFSET] = optlen;
2975 
2976 			off = optlen - IP_ADDR_LEN;
2977 			if (off < 0) {
2978 				/* No entries in source route */
2979 				break;
2980 			}
2981 			/* Last entry in source route */
2982 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2983 			off -= IP_ADDR_LEN;
2984 
2985 			while (off > 0) {
2986 				bcopy(opt + off,
2987 				    buf + off + IP_ADDR_LEN,
2988 				    IP_ADDR_LEN);
2989 				off -= IP_ADDR_LEN;
2990 			}
2991 			/* ipha_dst into first slot */
2992 			bcopy(&ipha->ipha_dst,
2993 			    buf + off + IP_ADDR_LEN,
2994 			    IP_ADDR_LEN);
2995 			buf += optlen;
2996 			len += optlen;
2997 			break;
2998 
2999 		case IPOPT_COMSEC:
3000 		case IPOPT_SECURITY:
3001 			/* if passing up a label is not ok, then remove */
3002 			if (is_system_labeled())
3003 				break;
3004 			/* FALLTHROUGH */
3005 		default:
3006 			bcopy(opt, buf, optlen);
3007 			buf += optlen;
3008 			len += optlen;
3009 			break;
3010 		}
3011 	}
3012 done:
3013 	/* Pad the resulting options */
3014 	while (len & 0x3) {
3015 		*buf++ = IPOPT_EOL;
3016 		len++;
3017 	}
3018 	return (len);
3019 }
3020 
3021 /*
3022  * Update any record route or timestamp options to include this host.
3023  * Reverse any source route option.
3024  * This routine assumes that the options are well formed i.e. that they
3025  * have already been checked.
3026  */
3027 static void
3028 icmp_options_update(ipha_t *ipha)
3029 {
3030 	ipoptp_t	opts;
3031 	uchar_t		*opt;
3032 	uint8_t		optval;
3033 	ipaddr_t	src;		/* Our local address */
3034 	ipaddr_t	dst;
3035 
3036 	ip2dbg(("icmp_options_update\n"));
3037 	src = ipha->ipha_src;
3038 	dst = ipha->ipha_dst;
3039 
3040 	for (optval = ipoptp_first(&opts, ipha);
3041 	    optval != IPOPT_EOL;
3042 	    optval = ipoptp_next(&opts)) {
3043 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3044 		opt = opts.ipoptp_cur;
3045 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3046 		    optval, opts.ipoptp_len));
3047 		switch (optval) {
3048 			int off1, off2;
3049 		case IPOPT_SSRR:
3050 		case IPOPT_LSRR:
3051 			/*
3052 			 * Reverse the source route.  The first entry
3053 			 * should be the next to last one in the current
3054 			 * source route (the last entry is our address).
3055 			 * The last entry should be the final destination.
3056 			 */
3057 			off1 = IPOPT_MINOFF_SR - 1;
3058 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3059 			if (off2 < 0) {
3060 				/* No entries in source route */
3061 				ip1dbg((
3062 				    "icmp_options_update: bad src route\n"));
3063 				break;
3064 			}
3065 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3066 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3067 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3068 			off2 -= IP_ADDR_LEN;
3069 
3070 			while (off1 < off2) {
3071 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3072 				bcopy((char *)opt + off2, (char *)opt + off1,
3073 				    IP_ADDR_LEN);
3074 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3075 				off1 += IP_ADDR_LEN;
3076 				off2 -= IP_ADDR_LEN;
3077 			}
3078 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3079 			break;
3080 		}
3081 	}
3082 }
3083 
3084 /*
3085  * Process received ICMP Redirect messages.
3086  */
3087 /* ARGSUSED */
3088 static void
3089 icmp_redirect(mblk_t *mp)
3090 {
3091 	ipha_t	*ipha;
3092 	int	iph_hdr_length;
3093 	icmph_t	*icmph;
3094 	ipha_t	*ipha_err;
3095 	ire_t	*ire;
3096 	ire_t	*prev_ire;
3097 	ire_t	*save_ire;
3098 	ipaddr_t  src, dst, gateway;
3099 	iulp_t	ulp_info = { 0 };
3100 	int	error;
3101 
3102 	ipha = (ipha_t *)mp->b_rptr;
3103 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3104 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3105 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3106 		BUMP_MIB(&icmp_mib, icmpInErrors);
3107 		freemsg(mp);
3108 		return;
3109 	}
3110 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3111 	ipha_err = (ipha_t *)&icmph[1];
3112 	src = ipha->ipha_src;
3113 	dst = ipha_err->ipha_dst;
3114 	gateway = icmph->icmph_rd_gateway;
3115 	/* Make sure the new gateway is reachable somehow. */
3116 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3117 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3118 	/*
3119 	 * Make sure we had a route for the dest in question and that
3120 	 * that route was pointing to the old gateway (the source of the
3121 	 * redirect packet.)
3122 	 */
3123 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3124 	    NULL, MATCH_IRE_GW);
3125 	/*
3126 	 * Check that
3127 	 *	the redirect was not from ourselves
3128 	 *	the new gateway and the old gateway are directly reachable
3129 	 */
3130 	if (!prev_ire ||
3131 	    !ire ||
3132 	    ire->ire_type == IRE_LOCAL) {
3133 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3134 		freemsg(mp);
3135 		if (ire != NULL)
3136 			ire_refrele(ire);
3137 		if (prev_ire != NULL)
3138 			ire_refrele(prev_ire);
3139 		return;
3140 	}
3141 
3142 	/*
3143 	 * Should we use the old ULP info to create the new gateway?  From
3144 	 * a user's perspective, we should inherit the info so that it
3145 	 * is a "smooth" transition.  If we do not do that, then new
3146 	 * connections going thru the new gateway will have no route metrics,
3147 	 * which is counter-intuitive to user.  From a network point of
3148 	 * view, this may or may not make sense even though the new gateway
3149 	 * is still directly connected to us so the route metrics should not
3150 	 * change much.
3151 	 *
3152 	 * But if the old ire_uinfo is not initialized, we do another
3153 	 * recursive lookup on the dest using the new gateway.  There may
3154 	 * be a route to that.  If so, use it to initialize the redirect
3155 	 * route.
3156 	 */
3157 	if (prev_ire->ire_uinfo.iulp_set) {
3158 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3159 	} else {
3160 		ire_t *tmp_ire;
3161 		ire_t *sire;
3162 
3163 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3164 		    ALL_ZONES, 0, NULL,
3165 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3166 		if (sire != NULL) {
3167 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3168 			/*
3169 			 * If sire != NULL, ire_ftable_lookup() should not
3170 			 * return a NULL value.
3171 			 */
3172 			ASSERT(tmp_ire != NULL);
3173 			ire_refrele(tmp_ire);
3174 			ire_refrele(sire);
3175 		} else if (tmp_ire != NULL) {
3176 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3177 			    sizeof (iulp_t));
3178 			ire_refrele(tmp_ire);
3179 		}
3180 	}
3181 	if (prev_ire->ire_type == IRE_CACHE)
3182 		ire_delete(prev_ire);
3183 	ire_refrele(prev_ire);
3184 	/*
3185 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3186 	 * require TOS routing
3187 	 */
3188 	switch (icmph->icmph_code) {
3189 	case 0:
3190 	case 1:
3191 		/* TODO: TOS specificity for cases 2 and 3 */
3192 	case 2:
3193 	case 3:
3194 		break;
3195 	default:
3196 		freemsg(mp);
3197 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3198 		ire_refrele(ire);
3199 		return;
3200 	}
3201 	/*
3202 	 * Create a Route Association.  This will allow us to remember that
3203 	 * someone we believe told us to use the particular gateway.
3204 	 */
3205 	save_ire = ire;
3206 	ire = ire_create(
3207 		(uchar_t *)&dst,			/* dest addr */
3208 		(uchar_t *)&ip_g_all_ones,		/* mask */
3209 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3210 		(uchar_t *)&gateway,			/* gateway addr */
3211 		NULL,					/* no in_srcaddr */
3212 		&save_ire->ire_max_frag,		/* max frag */
3213 		NULL,					/* Fast Path header */
3214 		NULL,					/* no rfq */
3215 		NULL,					/* no stq */
3216 		IRE_HOST_REDIRECT,
3217 		NULL,
3218 		NULL,
3219 		NULL,
3220 		0,
3221 		0,
3222 		0,
3223 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3224 		&ulp_info,
3225 		NULL,
3226 		NULL);
3227 
3228 	if (ire == NULL) {
3229 		freemsg(mp);
3230 		ire_refrele(save_ire);
3231 		return;
3232 	}
3233 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3234 	ire_refrele(save_ire);
3235 	atomic_inc_32(&ip_redirect_cnt);
3236 
3237 	if (error == 0) {
3238 		ire_refrele(ire);		/* Held in ire_add_v4 */
3239 		/* tell routing sockets that we received a redirect */
3240 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3241 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3242 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3243 	}
3244 
3245 	/*
3246 	 * Delete any existing IRE_HOST_REDIRECT for this destination.
3247 	 * This together with the added IRE has the effect of
3248 	 * modifying an existing redirect.
3249 	 */
3250 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST_REDIRECT, NULL, NULL,
3251 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3252 	if (prev_ire) {
3253 		ire_delete(prev_ire);
3254 		ire_refrele(prev_ire);
3255 	}
3256 
3257 	freemsg(mp);
3258 }
3259 
3260 /*
3261  * Generate an ICMP parameter problem message.
3262  */
3263 static void
3264 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr)
3265 {
3266 	icmph_t	icmph;
3267 	boolean_t mctl_present;
3268 	mblk_t *first_mp;
3269 
3270 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3271 
3272 	if (!(mp = icmp_pkt_err_ok(mp))) {
3273 		if (mctl_present)
3274 			freeb(first_mp);
3275 		return;
3276 	}
3277 
3278 	bzero(&icmph, sizeof (icmph_t));
3279 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3280 	icmph.icmph_pp_ptr = ptr;
3281 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3282 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3283 }
3284 
3285 /*
3286  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3287  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3288  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3289  * an icmp error packet can be sent.
3290  * Assigns an appropriate source address to the packet. If ipha_dst is
3291  * one of our addresses use it for source. Otherwise pick a source based
3292  * on a route lookup back to ipha_src.
3293  * Note that ipha_src must be set here since the
3294  * packet is likely to arrive on an ill queue in ip_wput() which will
3295  * not set a source address.
3296  */
3297 static void
3298 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3299     boolean_t mctl_present)
3300 {
3301 	ipaddr_t dst;
3302 	icmph_t	*icmph;
3303 	ipha_t	*ipha;
3304 	uint_t	len_needed;
3305 	size_t	msg_len;
3306 	mblk_t	*mp1;
3307 	ipaddr_t src;
3308 	ire_t	*ire;
3309 	mblk_t *ipsec_mp;
3310 	ipsec_out_t	*io = NULL;
3311 	boolean_t xmit_if_on = B_FALSE;
3312 	zoneid_t	zoneid;
3313 
3314 	if (mctl_present) {
3315 		/*
3316 		 * If it is :
3317 		 *
3318 		 * 1) a IPSEC_OUT, then this is caused by outbound
3319 		 *    datagram originating on this host. IPSEC processing
3320 		 *    may or may not have been done. Refer to comments above
3321 		 *    icmp_inbound_error_fanout for details.
3322 		 *
3323 		 * 2) a IPSEC_IN if we are generating a icmp_message
3324 		 *    for an incoming datagram destined for us i.e called
3325 		 *    from ip_fanout_send_icmp.
3326 		 */
3327 		ipsec_info_t *in;
3328 		ipsec_mp = mp;
3329 		mp = ipsec_mp->b_cont;
3330 
3331 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3332 		ipha = (ipha_t *)mp->b_rptr;
3333 
3334 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3335 		    in->ipsec_info_type == IPSEC_IN);
3336 
3337 		if (in->ipsec_info_type == IPSEC_IN) {
3338 			/*
3339 			 * Convert the IPSEC_IN to IPSEC_OUT.
3340 			 */
3341 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3342 				BUMP_MIB(&ip_mib, ipOutDiscards);
3343 				return;
3344 			}
3345 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3346 		} else {
3347 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3348 			io = (ipsec_out_t *)in;
3349 			if (io->ipsec_out_xmit_if)
3350 				xmit_if_on = B_TRUE;
3351 			/*
3352 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3353 			 * ire lookup.
3354 			 */
3355 			io->ipsec_out_proc_begin = B_FALSE;
3356 		}
3357 		zoneid = io->ipsec_out_zoneid;
3358 		ASSERT(zoneid != ALL_ZONES);
3359 	} else {
3360 		/*
3361 		 * This is in clear. The icmp message we are building
3362 		 * here should go out in clear.
3363 		 *
3364 		 * Pardon the convolution of it all, but it's easier to
3365 		 * allocate a "use cleartext" IPSEC_IN message and convert
3366 		 * it than it is to allocate a new one.
3367 		 */
3368 		ipsec_in_t *ii;
3369 		ASSERT(DB_TYPE(mp) == M_DATA);
3370 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3371 			freemsg(mp);
3372 			BUMP_MIB(&ip_mib, ipOutDiscards);
3373 			return;
3374 		}
3375 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3376 
3377 		/* This is not a secure packet */
3378 		ii->ipsec_in_secure = B_FALSE;
3379 		if (CONN_Q(q)) {
3380 			zoneid = Q_TO_CONN(q)->conn_zoneid;
3381 		} else {
3382 			zoneid = GLOBAL_ZONEID;
3383 		}
3384 		ii->ipsec_in_zoneid = zoneid;
3385 		ASSERT(zoneid != ALL_ZONES);
3386 		ipsec_mp->b_cont = mp;
3387 		ipha = (ipha_t *)mp->b_rptr;
3388 		/*
3389 		 * Convert the IPSEC_IN to IPSEC_OUT.
3390 		 */
3391 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3392 			BUMP_MIB(&ip_mib, ipOutDiscards);
3393 			return;
3394 		}
3395 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3396 	}
3397 
3398 	/* Remember our eventual destination */
3399 	dst = ipha->ipha_src;
3400 
3401 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3402 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3403 	if (ire != NULL &&
3404 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3405 		src = ipha->ipha_dst;
3406 	} else if (!xmit_if_on) {
3407 		if (ire != NULL)
3408 			ire_refrele(ire);
3409 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3410 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3411 		if (ire == NULL) {
3412 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3413 			freemsg(ipsec_mp);
3414 			return;
3415 		}
3416 		src = ire->ire_src_addr;
3417 	} else {
3418 		ipif_t	*ipif = NULL;
3419 		ill_t	*ill;
3420 		/*
3421 		 * This must be an ICMP error coming from
3422 		 * ip_mrtun_forward(). The src addr should
3423 		 * be equal to the IP-addr of the outgoing
3424 		 * interface.
3425 		 */
3426 		if (io == NULL) {
3427 			/* This is not a IPSEC_OUT type control msg */
3428 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3429 			freemsg(ipsec_mp);
3430 			return;
3431 		}
3432 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3433 		    NULL, NULL, NULL, NULL);
3434 		if (ill != NULL) {
3435 			ipif = ipif_get_next_ipif(NULL, ill);
3436 			ill_refrele(ill);
3437 		}
3438 		if (ipif == NULL) {
3439 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3440 			freemsg(ipsec_mp);
3441 			return;
3442 		}
3443 		src = ipif->ipif_src_addr;
3444 		ipif_refrele(ipif);
3445 	}
3446 
3447 	if (ire != NULL)
3448 		ire_refrele(ire);
3449 
3450 	/*
3451 	 * Check if we can send back more then 8 bytes in addition
3452 	 * to the IP header. We will include as much as 64 bytes.
3453 	 */
3454 	len_needed = IPH_HDR_LENGTH(ipha);
3455 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3456 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3457 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3458 	}
3459 	len_needed += ip_icmp_return;
3460 	msg_len = msgdsize(mp);
3461 	if (msg_len > len_needed) {
3462 		(void) adjmsg(mp, len_needed - msg_len);
3463 		msg_len = len_needed;
3464 	}
3465 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3466 	if (mp1 == NULL) {
3467 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3468 		freemsg(ipsec_mp);
3469 		return;
3470 	}
3471 	/*
3472 	 * On an unlabeled system, dblks don't necessarily have creds.
3473 	 */
3474 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3475 	if (DB_CRED(mp) != NULL)
3476 		mblk_setcred(mp1, DB_CRED(mp));
3477 	mp1->b_cont = mp;
3478 	mp = mp1;
3479 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3480 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3481 	    io->ipsec_out_type == IPSEC_OUT);
3482 	ipsec_mp->b_cont = mp;
3483 
3484 	/*
3485 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3486 	 * node generates be accepted in peace by all on-host destinations.
3487 	 * If we do NOT assume that all on-host destinations trust
3488 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3489 	 * (Look for ipsec_out_icmp_loopback).
3490 	 */
3491 	io->ipsec_out_icmp_loopback = B_TRUE;
3492 
3493 	ipha = (ipha_t *)mp->b_rptr;
3494 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3495 	*ipha = icmp_ipha;
3496 	ipha->ipha_src = src;
3497 	ipha->ipha_dst = dst;
3498 	ipha->ipha_ttl = ip_def_ttl;
3499 	msg_len += sizeof (icmp_ipha) + len;
3500 	if (msg_len > IP_MAXPACKET) {
3501 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3502 		msg_len = IP_MAXPACKET;
3503 	}
3504 	ipha->ipha_length = htons((uint16_t)msg_len);
3505 	icmph = (icmph_t *)&ipha[1];
3506 	bcopy(stuff, icmph, len);
3507 	icmph->icmph_checksum = 0;
3508 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3509 	if (icmph->icmph_checksum == 0)
3510 		icmph->icmph_checksum = 0xFFFF;
3511 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3512 	put(q, ipsec_mp);
3513 }
3514 
3515 /*
3516  * Determine if an ICMP error packet can be sent given the rate limit.
3517  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3518  * in milliseconds) and a burst size. Burst size number of packets can
3519  * be sent arbitrarely closely spaced.
3520  * The state is tracked using two variables to implement an approximate
3521  * token bucket filter:
3522  *	icmp_pkt_err_last - lbolt value when the last burst started
3523  *	icmp_pkt_err_sent - number of packets sent in current burst
3524  */
3525 boolean_t
3526 icmp_err_rate_limit(void)
3527 {
3528 	clock_t now = TICK_TO_MSEC(lbolt);
3529 	uint_t refilled; /* Number of packets refilled in tbf since last */
3530 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3531 
3532 	if (err_interval == 0)
3533 		return (B_FALSE);
3534 
3535 	if (icmp_pkt_err_last > now) {
3536 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3537 		icmp_pkt_err_last = 0;
3538 		icmp_pkt_err_sent = 0;
3539 	}
3540 	/*
3541 	 * If we are in a burst update the token bucket filter.
3542 	 * Update the "last" time to be close to "now" but make sure
3543 	 * we don't loose precision.
3544 	 */
3545 	if (icmp_pkt_err_sent != 0) {
3546 		refilled = (now - icmp_pkt_err_last)/err_interval;
3547 		if (refilled > icmp_pkt_err_sent) {
3548 			icmp_pkt_err_sent = 0;
3549 		} else {
3550 			icmp_pkt_err_sent -= refilled;
3551 			icmp_pkt_err_last += refilled * err_interval;
3552 		}
3553 	}
3554 	if (icmp_pkt_err_sent == 0) {
3555 		/* Start of new burst */
3556 		icmp_pkt_err_last = now;
3557 	}
3558 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3559 		icmp_pkt_err_sent++;
3560 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3561 		    icmp_pkt_err_sent));
3562 		return (B_FALSE);
3563 	}
3564 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3565 	return (B_TRUE);
3566 }
3567 
3568 /*
3569  * Check if it is ok to send an IPv4 ICMP error packet in
3570  * response to the IPv4 packet in mp.
3571  * Free the message and return null if no
3572  * ICMP error packet should be sent.
3573  */
3574 static mblk_t *
3575 icmp_pkt_err_ok(mblk_t *mp)
3576 {
3577 	icmph_t	*icmph;
3578 	ipha_t	*ipha;
3579 	uint_t	len_needed;
3580 	ire_t	*src_ire;
3581 	ire_t	*dst_ire;
3582 
3583 	if (!mp)
3584 		return (NULL);
3585 	ipha = (ipha_t *)mp->b_rptr;
3586 	if (ip_csum_hdr(ipha)) {
3587 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3588 		freemsg(mp);
3589 		return (NULL);
3590 	}
3591 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3592 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3593 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3594 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3595 	if (src_ire != NULL || dst_ire != NULL ||
3596 	    CLASSD(ipha->ipha_dst) ||
3597 	    CLASSD(ipha->ipha_src) ||
3598 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3599 		/* Note: only errors to the fragment with offset 0 */
3600 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3601 		freemsg(mp);
3602 		if (src_ire != NULL)
3603 			ire_refrele(src_ire);
3604 		if (dst_ire != NULL)
3605 			ire_refrele(dst_ire);
3606 		return (NULL);
3607 	}
3608 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3609 		/*
3610 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3611 		 * errors in response to any ICMP errors.
3612 		 */
3613 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3614 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3615 			if (!pullupmsg(mp, len_needed)) {
3616 				BUMP_MIB(&icmp_mib, icmpInErrors);
3617 				freemsg(mp);
3618 				return (NULL);
3619 			}
3620 			ipha = (ipha_t *)mp->b_rptr;
3621 		}
3622 		icmph = (icmph_t *)
3623 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3624 		switch (icmph->icmph_type) {
3625 		case ICMP_DEST_UNREACHABLE:
3626 		case ICMP_SOURCE_QUENCH:
3627 		case ICMP_TIME_EXCEEDED:
3628 		case ICMP_PARAM_PROBLEM:
3629 		case ICMP_REDIRECT:
3630 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3631 			freemsg(mp);
3632 			return (NULL);
3633 		default:
3634 			break;
3635 		}
3636 	}
3637 	/*
3638 	 * If this is a labeled system, then check to see if we're allowed to
3639 	 * send a response to this particular sender.  If not, then just drop.
3640 	 */
3641 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3642 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3643 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3644 		freemsg(mp);
3645 		return (NULL);
3646 	}
3647 	if (icmp_err_rate_limit()) {
3648 		/*
3649 		 * Only send ICMP error packets every so often.
3650 		 * This should be done on a per port/source basis,
3651 		 * but for now this will suffice.
3652 		 */
3653 		freemsg(mp);
3654 		return (NULL);
3655 	}
3656 	return (mp);
3657 }
3658 
3659 /*
3660  * Generate an ICMP redirect message.
3661  */
3662 static void
3663 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3664 {
3665 	icmph_t	icmph;
3666 
3667 	/*
3668 	 * We are called from ip_rput where we could
3669 	 * not have attached an IPSEC_IN.
3670 	 */
3671 	ASSERT(mp->b_datap->db_type == M_DATA);
3672 
3673 	if (!(mp = icmp_pkt_err_ok(mp))) {
3674 		return;
3675 	}
3676 
3677 	bzero(&icmph, sizeof (icmph_t));
3678 	icmph.icmph_type = ICMP_REDIRECT;
3679 	icmph.icmph_code = 1;
3680 	icmph.icmph_rd_gateway = gateway;
3681 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3682 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE);
3683 }
3684 
3685 /*
3686  * Generate an ICMP time exceeded message.
3687  */
3688 void
3689 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code)
3690 {
3691 	icmph_t	icmph;
3692 	boolean_t mctl_present;
3693 	mblk_t *first_mp;
3694 
3695 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3696 
3697 	if (!(mp = icmp_pkt_err_ok(mp))) {
3698 		if (mctl_present)
3699 			freeb(first_mp);
3700 		return;
3701 	}
3702 
3703 	bzero(&icmph, sizeof (icmph_t));
3704 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3705 	icmph.icmph_code = code;
3706 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3707 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3708 }
3709 
3710 /*
3711  * Generate an ICMP unreachable message.
3712  */
3713 void
3714 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code)
3715 {
3716 	icmph_t	icmph;
3717 	mblk_t *first_mp;
3718 	boolean_t mctl_present;
3719 
3720 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3721 
3722 	if (!(mp = icmp_pkt_err_ok(mp))) {
3723 		if (mctl_present)
3724 			freeb(first_mp);
3725 		return;
3726 	}
3727 
3728 	bzero(&icmph, sizeof (icmph_t));
3729 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3730 	icmph.icmph_code = code;
3731 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3732 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3733 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present);
3734 }
3735 
3736 /*
3737  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3738  * duplicate.  As long as someone else holds the address, the interface will
3739  * stay down.  When that conflict goes away, the interface is brought back up.
3740  * This is done so that accidental shutdowns of addresses aren't made
3741  * permanent.  Your server will recover from a failure.
3742  *
3743  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3744  * user space process (dhcpagent).
3745  *
3746  * Recovery completes if ARP reports that the address is now ours (via
3747  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3748  *
3749  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3750  */
3751 static void
3752 ipif_dup_recovery(void *arg)
3753 {
3754 	ipif_t *ipif = arg;
3755 	ill_t *ill = ipif->ipif_ill;
3756 	mblk_t *arp_add_mp;
3757 	mblk_t *arp_del_mp;
3758 	area_t *area;
3759 
3760 	ipif->ipif_recovery_id = 0;
3761 
3762 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3763 	    (ipif->ipif_flags & IPIF_POINTOPOINT)) {
3764 		/* No reason to try to bring this address back. */
3765 		return;
3766 	}
3767 
3768 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3769 		goto alloc_fail;
3770 
3771 	if (ipif->ipif_arp_del_mp == NULL) {
3772 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3773 			goto alloc_fail;
3774 		ipif->ipif_arp_del_mp = arp_del_mp;
3775 	}
3776 
3777 	/* Setting the 'unverified' flag restarts DAD */
3778 	area = (area_t *)arp_add_mp->b_rptr;
3779 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3780 	    ACE_F_UNVERIFIED;
3781 	putnext(ill->ill_rq, arp_add_mp);
3782 	return;
3783 
3784 alloc_fail:
3785 	/* On allocation failure, just restart the timer */
3786 	freemsg(arp_add_mp);
3787 	if (ip_dup_recovery > 0) {
3788 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3789 		    MSEC_TO_TICK(ip_dup_recovery));
3790 	}
3791 }
3792 
3793 /*
3794  * This is for exclusive changes due to ARP.  Either tear down an interface due
3795  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3796  */
3797 /* ARGSUSED */
3798 static void
3799 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3800 {
3801 	ill_t	*ill = rq->q_ptr;
3802 	arh_t *arh;
3803 	ipaddr_t src;
3804 	ipif_t	*ipif;
3805 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3806 	char hbuf[MAC_STR_LEN];
3807 	char sbuf[INET_ADDRSTRLEN];
3808 	const char *failtype;
3809 	boolean_t bring_up;
3810 
3811 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3812 	case AR_CN_READY:
3813 		failtype = NULL;
3814 		bring_up = B_TRUE;
3815 		break;
3816 	case AR_CN_FAILED:
3817 		failtype = "in use";
3818 		bring_up = B_FALSE;
3819 		break;
3820 	default:
3821 		failtype = "claimed";
3822 		bring_up = B_FALSE;
3823 		break;
3824 	}
3825 
3826 	arh = (arh_t *)mp->b_cont->b_rptr;
3827 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3828 
3829 	/* Handle failures due to probes */
3830 	if (src == 0) {
3831 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3832 		    IP_ADDR_LEN);
3833 	}
3834 
3835 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3836 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3837 	    sizeof (hbuf));
3838 	(void) ip_dot_addr(src, sbuf);
3839 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3840 
3841 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3842 		    ipif->ipif_lcl_addr != src) {
3843 			continue;
3844 		}
3845 
3846 		/*
3847 		 * If we failed on a recovery probe, then restart the timer to
3848 		 * try again later.
3849 		 */
3850 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3851 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3852 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3853 		    ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0) {
3854 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3855 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3856 			continue;
3857 		}
3858 
3859 		/*
3860 		 * If what we're trying to do has already been done, then do
3861 		 * nothing.
3862 		 */
3863 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3864 			continue;
3865 
3866 		if (ipif->ipif_id != 0) {
3867 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3868 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3869 			    ipif->ipif_id);
3870 		}
3871 		if (failtype == NULL) {
3872 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3873 			    ibuf);
3874 		} else {
3875 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3876 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3877 		}
3878 
3879 		if (bring_up) {
3880 			ASSERT(ill->ill_dl_up);
3881 			/*
3882 			 * Free up the ARP delete message so we can allocate
3883 			 * a fresh one through the normal path.
3884 			 */
3885 			freemsg(ipif->ipif_arp_del_mp);
3886 			ipif->ipif_arp_del_mp = NULL;
3887 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3888 			    EINPROGRESS) {
3889 				ipif->ipif_addr_ready = 1;
3890 				(void) ipif_up_done(ipif);
3891 			}
3892 			continue;
3893 		}
3894 
3895 		mutex_enter(&ill->ill_lock);
3896 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3897 		ipif->ipif_flags |= IPIF_DUPLICATE;
3898 		ill->ill_ipif_dup_count++;
3899 		mutex_exit(&ill->ill_lock);
3900 		/*
3901 		 * Already exclusive on the ill; no need to handle deferred
3902 		 * processing here.
3903 		 */
3904 		(void) ipif_down(ipif, NULL, NULL);
3905 		ipif_down_tail(ipif);
3906 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3907 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3908 		    ip_dup_recovery > 0) {
3909 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3910 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3911 		}
3912 	}
3913 	freemsg(mp);
3914 }
3915 
3916 /* ARGSUSED */
3917 static void
3918 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3919 {
3920 	ill_t	*ill = rq->q_ptr;
3921 	arh_t *arh;
3922 	ipaddr_t src;
3923 	ipif_t	*ipif;
3924 
3925 	arh = (arh_t *)mp->b_cont->b_rptr;
3926 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3927 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3928 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3929 			(void) ipif_resolver_up(ipif, Res_act_defend);
3930 	}
3931 	freemsg(mp);
3932 }
3933 
3934 /*
3935  * News from ARP.  ARP sends notification of interesting events down
3936  * to its clients using M_CTL messages with the interesting ARP packet
3937  * attached via b_cont.
3938  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3939  * queue as opposed to ARP sending the message to all the clients, i.e. all
3940  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3941  * table if a cache IRE is found to delete all the entries for the address in
3942  * the packet.
3943  */
3944 static void
3945 ip_arp_news(queue_t *q, mblk_t *mp)
3946 {
3947 	arcn_t		*arcn;
3948 	arh_t		*arh;
3949 	ire_t		*ire = NULL;
3950 	char		hbuf[MAC_STR_LEN];
3951 	char		sbuf[INET_ADDRSTRLEN];
3952 	ipaddr_t	src;
3953 	in6_addr_t	v6src;
3954 	boolean_t	isv6 = B_FALSE;
3955 	ipif_t		*ipif;
3956 	ill_t		*ill;
3957 
3958 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3959 		if (q->q_next) {
3960 			putnext(q, mp);
3961 		} else
3962 			freemsg(mp);
3963 		return;
3964 	}
3965 	arh = (arh_t *)mp->b_cont->b_rptr;
3966 	/* Is it one we are interested in? */
3967 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3968 		isv6 = B_TRUE;
3969 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3970 		    IPV6_ADDR_LEN);
3971 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3972 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3973 		    IP_ADDR_LEN);
3974 	} else {
3975 		freemsg(mp);
3976 		return;
3977 	}
3978 
3979 	ill = q->q_ptr;
3980 
3981 	arcn = (arcn_t *)mp->b_rptr;
3982 	switch (arcn->arcn_code) {
3983 	case AR_CN_BOGON:
3984 		/*
3985 		 * Someone is sending ARP packets with a source protocol
3986 		 * address that we have published and for which we believe our
3987 		 * entry is authoritative and (when ill_arp_extend is set)
3988 		 * verified to be unique on the network.
3989 		 *
3990 		 * The ARP module internally handles the cases where the sender
3991 		 * is just probing (for DAD) and where the hardware address of
3992 		 * a non-authoritative entry has changed.  Thus, these are the
3993 		 * real conflicts, and we have to do resolution.
3994 		 *
3995 		 * We back away quickly from the address if it's from DHCP or
3996 		 * otherwise temporary and hasn't been used recently (or at
3997 		 * all).  We'd like to include "deprecated" addresses here as
3998 		 * well (as there's no real reason to defend something we're
3999 		 * discarding), but IPMP "reuses" this flag to mean something
4000 		 * other than the standard meaning.
4001 		 *
4002 		 * If the ARP module above is not extended (meaning that it
4003 		 * doesn't know how to defend the address), then we just log
4004 		 * the problem as we always did and continue on.  It's not
4005 		 * right, but there's little else we can do, and those old ATM
4006 		 * users are going away anyway.
4007 		 */
4008 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4009 		    hbuf, sizeof (hbuf));
4010 		(void) ip_dot_addr(src, sbuf);
4011 		if (isv6)
4012 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
4013 		else
4014 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
4015 
4016 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4017 			uint32_t now;
4018 			uint32_t maxage;
4019 			clock_t lused;
4020 			uint_t maxdefense;
4021 			uint_t defs;
4022 
4023 			/*
4024 			 * First, figure out if this address hasn't been used
4025 			 * in a while.  If it hasn't, then it's a better
4026 			 * candidate for abandoning.
4027 			 */
4028 			ipif = ire->ire_ipif;
4029 			ASSERT(ipif != NULL);
4030 			now = gethrestime_sec();
4031 			maxage = now - ire->ire_create_time;
4032 			if (maxage > ip_max_temp_idle)
4033 				maxage = ip_max_temp_idle;
4034 			lused = drv_hztousec(ddi_get_lbolt() -
4035 			    ire->ire_last_used_time) / MICROSEC + 1;
4036 			if (lused >= maxage && (ipif->ipif_flags &
4037 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4038 				maxdefense = ip_max_temp_defend;
4039 			else
4040 				maxdefense = ip_max_defend;
4041 
4042 			/*
4043 			 * Now figure out how many times we've defended
4044 			 * ourselves.  Ignore defenses that happened long in
4045 			 * the past.
4046 			 */
4047 			mutex_enter(&ire->ire_lock);
4048 			if ((defs = ire->ire_defense_count) > 0 &&
4049 			    now - ire->ire_defense_time > ip_defend_interval) {
4050 				ire->ire_defense_count = defs = 0;
4051 			}
4052 			ire->ire_defense_count++;
4053 			ire->ire_defense_time = now;
4054 			mutex_exit(&ire->ire_lock);
4055 			ill_refhold(ill);
4056 			ire_refrele(ire);
4057 
4058 			/*
4059 			 * If we've defended ourselves too many times already,
4060 			 * then give up and tear down the interface(s) using
4061 			 * this address.  Otherwise, defend by sending out a
4062 			 * gratuitous ARP.
4063 			 */
4064 			if (defs >= maxdefense && ill->ill_arp_extend) {
4065 				(void) qwriter_ip(NULL, ill, q, mp,
4066 				    ip_arp_excl, CUR_OP, B_FALSE);
4067 			} else {
4068 				cmn_err(CE_WARN,
4069 				    "node %s is using our IP address %s on %s",
4070 				    hbuf, sbuf, ill->ill_name);
4071 				/*
4072 				 * If this is an old (ATM) ARP module, then
4073 				 * don't try to defend the address.  Remain
4074 				 * compatible with the old behavior.  Defend
4075 				 * only with new ARP.
4076 				 */
4077 				if (ill->ill_arp_extend) {
4078 					(void) qwriter_ip(NULL, ill, q, mp,
4079 					    ip_arp_defend, CUR_OP, B_FALSE);
4080 				} else {
4081 					ill_refrele(ill);
4082 				}
4083 			}
4084 			return;
4085 		}
4086 		cmn_err(CE_WARN,
4087 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4088 		    hbuf, sbuf, ill->ill_name);
4089 		if (ire != NULL)
4090 			ire_refrele(ire);
4091 		break;
4092 	case AR_CN_ANNOUNCE:
4093 		if (isv6) {
4094 			/*
4095 			 * For XRESOLV interfaces.
4096 			 * Delete the IRE cache entry and NCE for this
4097 			 * v6 address
4098 			 */
4099 			ip_ire_clookup_and_delete_v6(&v6src);
4100 			/*
4101 			 * If v6src is a non-zero, it's a router address
4102 			 * as below. Do the same sort of thing to clean
4103 			 * out off-net IRE_CACHE entries that go through
4104 			 * the router.
4105 			 */
4106 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4107 				ire_walk_v6(ire_delete_cache_gw_v6,
4108 				    (char *)&v6src, ALL_ZONES);
4109 			}
4110 		} else {
4111 			nce_hw_map_t hwm;
4112 
4113 			/*
4114 			 * ARP gives us a copy of any packet where it thinks
4115 			 * the address has changed, so that we can update our
4116 			 * caches.  We're responsible for caching known answers
4117 			 * in the current design.  We check whether the
4118 			 * hardware address really has changed in all of our
4119 			 * entries that have cached this mapping, and if so, we
4120 			 * blow them away.  This way we will immediately pick
4121 			 * up the rare case of a host changing hardware
4122 			 * address.
4123 			 */
4124 			if (src == 0)
4125 				break;
4126 			hwm.hwm_addr = src;
4127 			hwm.hwm_hwlen = arh->arh_hlen;
4128 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4129 			ndp_walk_common(&ndp4, NULL,
4130 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4131 		}
4132 		break;
4133 	case AR_CN_READY:
4134 		/* No external v6 resolver has a contract to use this */
4135 		if (isv6)
4136 			break;
4137 		/* If the link is down, we'll retry this later */
4138 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4139 			break;
4140 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4141 		    NULL, NULL);
4142 		if (ipif != NULL) {
4143 			/*
4144 			 * If this is a duplicate recovery, then we now need to
4145 			 * go exclusive to bring this thing back up.
4146 			 */
4147 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4148 			    IPIF_DUPLICATE) {
4149 				ipif_refrele(ipif);
4150 				ill_refhold(ill);
4151 				(void) qwriter_ip(NULL, ill, q, mp,
4152 				    ip_arp_excl, CUR_OP, B_FALSE);
4153 				return;
4154 			}
4155 			/*
4156 			 * If this is the first notice that this address is
4157 			 * ready, then let the user know now.
4158 			 */
4159 			if ((ipif->ipif_flags & IPIF_UP) &&
4160 			    !ipif->ipif_addr_ready) {
4161 				ipif_mask_reply(ipif);
4162 				ip_rts_ifmsg(ipif);
4163 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4164 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4165 			}
4166 			ipif->ipif_addr_ready = 1;
4167 			ipif_refrele(ipif);
4168 		}
4169 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp));
4170 		if (ire != NULL) {
4171 			ire->ire_defense_count = 0;
4172 			ire_refrele(ire);
4173 		}
4174 		break;
4175 	case AR_CN_FAILED:
4176 		/* No external v6 resolver has a contract to use this */
4177 		if (isv6)
4178 			break;
4179 		ill_refhold(ill);
4180 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4181 		    B_FALSE);
4182 		return;
4183 	}
4184 	freemsg(mp);
4185 }
4186 
4187 /*
4188  * Create a mblk suitable for carrying the interface index and/or source link
4189  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4190  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4191  * application.
4192  */
4193 mblk_t *
4194 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
4195 {
4196 	mblk_t		*mp;
4197 	in_pktinfo_t	*pinfo;
4198 	ipha_t *ipha;
4199 	struct ether_header *pether;
4200 
4201 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
4202 	if (mp == NULL) {
4203 		ip1dbg(("ip_add_info: allocation failure.\n"));
4204 		return (data_mp);
4205 	}
4206 
4207 	ipha	= (ipha_t *)data_mp->b_rptr;
4208 	pinfo = (in_pktinfo_t *)mp->b_rptr;
4209 	bzero(pinfo, sizeof (in_pktinfo_t));
4210 	pinfo->in_pkt_flags = (uchar_t)flags;
4211 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4212 
4213 	if (flags & IPF_RECVIF)
4214 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4215 
4216 	pether = (struct ether_header *)((char *)ipha
4217 	    - sizeof (struct ether_header));
4218 	/*
4219 	 * Make sure the interface is an ethernet type, since this option
4220 	 * is currently supported only on this type of interface. Also make
4221 	 * sure we are pointing correctly above db_base.
4222 	 */
4223 
4224 	if ((flags & IPF_RECVSLLA) &&
4225 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4226 	    (ill->ill_type == IFT_ETHER) &&
4227 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4228 
4229 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
4230 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4231 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
4232 	} else {
4233 		/*
4234 		 * Clear the bit. Indicate to upper layer that IP is not
4235 		 * sending this ancillary info.
4236 		 */
4237 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
4238 	}
4239 
4240 	mp->b_datap->db_type = M_CTL;
4241 	mp->b_wptr += sizeof (in_pktinfo_t);
4242 	mp->b_cont = data_mp;
4243 
4244 	return (mp);
4245 }
4246 
4247 /*
4248  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4249  * part of the bind request.
4250  */
4251 
4252 boolean_t
4253 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4254 {
4255 	ipsec_in_t *ii;
4256 
4257 	ASSERT(policy_mp != NULL);
4258 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4259 
4260 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4261 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4262 
4263 	connp->conn_policy = ii->ipsec_in_policy;
4264 	ii->ipsec_in_policy = NULL;
4265 
4266 	if (ii->ipsec_in_action != NULL) {
4267 		if (connp->conn_latch == NULL) {
4268 			connp->conn_latch = iplatch_create();
4269 			if (connp->conn_latch == NULL)
4270 				return (B_FALSE);
4271 		}
4272 		ipsec_latch_inbound(connp->conn_latch, ii);
4273 	}
4274 	return (B_TRUE);
4275 }
4276 
4277 /*
4278  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4279  * and to arrange for power-fanout assist.  The ULP is identified by
4280  * adding a single byte at the end of the original bind message.
4281  * A ULP other than UDP or TCP that wishes to be recognized passes
4282  * down a bind with a zero length address.
4283  *
4284  * The binding works as follows:
4285  * - A zero byte address means just bind to the protocol.
4286  * - A four byte address is treated as a request to validate
4287  *   that the address is a valid local address, appropriate for
4288  *   an application to bind to. This does not affect any fanout
4289  *   information in IP.
4290  * - A sizeof sin_t byte address is used to bind to only the local address
4291  *   and port.
4292  * - A sizeof ipa_conn_t byte address contains complete fanout information
4293  *   consisting of local and remote addresses and ports.  In
4294  *   this case, the addresses are both validated as appropriate
4295  *   for this operation, and, if so, the information is retained
4296  *   for use in the inbound fanout.
4297  *
4298  * The ULP (except in the zero-length bind) can append an
4299  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4300  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4301  * a copy of the source or destination IRE (source for local bind;
4302  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4303  * policy information contained should be copied on to the conn.
4304  *
4305  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4306  */
4307 mblk_t *
4308 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4309 {
4310 	ssize_t		len;
4311 	struct T_bind_req	*tbr;
4312 	sin_t		*sin;
4313 	ipa_conn_t	*ac;
4314 	uchar_t		*ucp;
4315 	mblk_t		*mp1;
4316 	boolean_t	ire_requested;
4317 	boolean_t	ipsec_policy_set = B_FALSE;
4318 	int		error = 0;
4319 	int		protocol;
4320 	ipa_conn_x_t	*acx;
4321 
4322 	ASSERT(!connp->conn_af_isv6);
4323 	connp->conn_pkt_isv6 = B_FALSE;
4324 
4325 	len = MBLKL(mp);
4326 	if (len < (sizeof (*tbr) + 1)) {
4327 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4328 		    "ip_bind: bogus msg, len %ld", len);
4329 		/* XXX: Need to return something better */
4330 		goto bad_addr;
4331 	}
4332 	/* Back up and extract the protocol identifier. */
4333 	mp->b_wptr--;
4334 	protocol = *mp->b_wptr & 0xFF;
4335 	tbr = (struct T_bind_req *)mp->b_rptr;
4336 	/* Reset the message type in preparation for shipping it back. */
4337 	DB_TYPE(mp) = M_PCPROTO;
4338 
4339 	connp->conn_ulp = (uint8_t)protocol;
4340 
4341 	/*
4342 	 * Check for a zero length address.  This is from a protocol that
4343 	 * wants to register to receive all packets of its type.
4344 	 */
4345 	if (tbr->ADDR_length == 0) {
4346 		/*
4347 		 * These protocols are now intercepted in ip_bind_v6().
4348 		 * Reject protocol-level binds here for now.
4349 		 *
4350 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4351 		 * so that the protocol type cannot be SCTP.
4352 		 */
4353 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4354 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4355 			goto bad_addr;
4356 		}
4357 
4358 		/*
4359 		 *
4360 		 * The udp module never sends down a zero-length address,
4361 		 * and allowing this on a labeled system will break MLP
4362 		 * functionality.
4363 		 */
4364 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4365 			goto bad_addr;
4366 
4367 		if (connp->conn_mac_exempt)
4368 			goto bad_addr;
4369 
4370 		/* No hash here really.  The table is big enough. */
4371 		connp->conn_srcv6 = ipv6_all_zeros;
4372 
4373 		ipcl_proto_insert(connp, protocol);
4374 
4375 		tbr->PRIM_type = T_BIND_ACK;
4376 		return (mp);
4377 	}
4378 
4379 	/* Extract the address pointer from the message. */
4380 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4381 	    tbr->ADDR_length);
4382 	if (ucp == NULL) {
4383 		ip1dbg(("ip_bind: no address\n"));
4384 		goto bad_addr;
4385 	}
4386 	if (!OK_32PTR(ucp)) {
4387 		ip1dbg(("ip_bind: unaligned address\n"));
4388 		goto bad_addr;
4389 	}
4390 	/*
4391 	 * Check for trailing mps.
4392 	 */
4393 
4394 	mp1 = mp->b_cont;
4395 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4396 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4397 
4398 	switch (tbr->ADDR_length) {
4399 	default:
4400 		ip1dbg(("ip_bind: bad address length %d\n",
4401 		    (int)tbr->ADDR_length));
4402 		goto bad_addr;
4403 
4404 	case IP_ADDR_LEN:
4405 		/* Verification of local address only */
4406 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4407 		    ire_requested, ipsec_policy_set, B_FALSE);
4408 		break;
4409 
4410 	case sizeof (sin_t):
4411 		sin = (sin_t *)ucp;
4412 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4413 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4414 		if (protocol == IPPROTO_TCP)
4415 			connp->conn_recv = tcp_conn_request;
4416 		break;
4417 
4418 	case sizeof (ipa_conn_t):
4419 		ac = (ipa_conn_t *)ucp;
4420 		/* For raw socket, the local port is not set. */
4421 		if (ac->ac_lport == 0)
4422 			ac->ac_lport = connp->conn_lport;
4423 		/* Always verify destination reachability. */
4424 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4425 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4426 		    ipsec_policy_set, B_TRUE, B_TRUE);
4427 		if (protocol == IPPROTO_TCP)
4428 			connp->conn_recv = tcp_input;
4429 		break;
4430 
4431 	case sizeof (ipa_conn_x_t):
4432 		acx = (ipa_conn_x_t *)ucp;
4433 		/*
4434 		 * Whether or not to verify destination reachability depends
4435 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4436 		 */
4437 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4438 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4439 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4440 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4441 		if (protocol == IPPROTO_TCP)
4442 			connp->conn_recv = tcp_input;
4443 		break;
4444 	}
4445 	if (error == EINPROGRESS)
4446 		return (NULL);
4447 	else if (error != 0)
4448 		goto bad_addr;
4449 	/*
4450 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4451 	 * We can't do this in ip_bind_insert_ire because the policy
4452 	 * may not have been inherited at that point in time and hence
4453 	 * conn_out_enforce_policy may not be set.
4454 	 */
4455 	mp1 = mp->b_cont;
4456 	if (ire_requested && connp->conn_out_enforce_policy &&
4457 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4458 		ire_t *ire = (ire_t *)mp1->b_rptr;
4459 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4460 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4461 	}
4462 
4463 	/* Send it home. */
4464 	mp->b_datap->db_type = M_PCPROTO;
4465 	tbr->PRIM_type = T_BIND_ACK;
4466 	return (mp);
4467 
4468 bad_addr:
4469 	/*
4470 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4471 	 * a unix errno.
4472 	 */
4473 	if (error > 0)
4474 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4475 	else
4476 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4477 	return (mp);
4478 }
4479 
4480 /*
4481  * Here address is verified to be a valid local address.
4482  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4483  * address is also considered a valid local address.
4484  * In the case of a broadcast/multicast address, however, the
4485  * upper protocol is expected to reset the src address
4486  * to 0 if it sees a IRE_BROADCAST type returned so that
4487  * no packets are emitted with broadcast/multicast address as
4488  * source address (that violates hosts requirements RFC1122)
4489  * The addresses valid for bind are:
4490  *	(1) - INADDR_ANY (0)
4491  *	(2) - IP address of an UP interface
4492  *	(3) - IP address of a DOWN interface
4493  *	(4) - valid local IP broadcast addresses. In this case
4494  *	the conn will only receive packets destined to
4495  *	the specified broadcast address.
4496  *	(5) - a multicast address. In this case
4497  *	the conn will only receive packets destined to
4498  *	the specified multicast address. Note: the
4499  *	application still has to issue an
4500  *	IP_ADD_MEMBERSHIP socket option.
4501  *
4502  * On error, return -1 for TBADADDR otherwise pass the
4503  * errno with TSYSERR reply.
4504  *
4505  * In all the above cases, the bound address must be valid in the current zone.
4506  * When the address is loopback, multicast or broadcast, there might be many
4507  * matching IREs so bind has to look up based on the zone.
4508  *
4509  * Note: lport is in network byte order.
4510  */
4511 int
4512 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4513     boolean_t ire_requested, boolean_t ipsec_policy_set,
4514     boolean_t fanout_insert)
4515 {
4516 	int		error = 0;
4517 	ire_t		*src_ire;
4518 	mblk_t		*policy_mp;
4519 	ipif_t		*ipif;
4520 	zoneid_t	zoneid;
4521 
4522 	if (ipsec_policy_set) {
4523 		policy_mp = mp->b_cont;
4524 	}
4525 
4526 	/*
4527 	 * If it was previously connected, conn_fully_bound would have
4528 	 * been set.
4529 	 */
4530 	connp->conn_fully_bound = B_FALSE;
4531 
4532 	src_ire = NULL;
4533 	ipif = NULL;
4534 
4535 	zoneid = IPCL_ZONEID(connp);
4536 
4537 	if (src_addr) {
4538 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4539 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4540 		/*
4541 		 * If an address other than 0.0.0.0 is requested,
4542 		 * we verify that it is a valid address for bind
4543 		 * Note: Following code is in if-else-if form for
4544 		 * readability compared to a condition check.
4545 		 */
4546 		/* LINTED - statement has no consequent */
4547 		if (IRE_IS_LOCAL(src_ire)) {
4548 			/*
4549 			 * (2) Bind to address of local UP interface
4550 			 */
4551 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4552 			/*
4553 			 * (4) Bind to broadcast address
4554 			 * Note: permitted only from transports that
4555 			 * request IRE
4556 			 */
4557 			if (!ire_requested)
4558 				error = EADDRNOTAVAIL;
4559 		} else {
4560 			/*
4561 			 * (3) Bind to address of local DOWN interface
4562 			 * (ipif_lookup_addr() looks up all interfaces
4563 			 * but we do not get here for UP interfaces
4564 			 * - case (2) above)
4565 			 * We put the protocol byte back into the mblk
4566 			 * since we may come back via ip_wput_nondata()
4567 			 * later with this mblk if ipif_lookup_addr chooses
4568 			 * to defer processing.
4569 			 */
4570 			*mp->b_wptr++ = (char)connp->conn_ulp;
4571 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4572 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4573 			    &error)) != NULL) {
4574 				ipif_refrele(ipif);
4575 			} else if (error == EINPROGRESS) {
4576 				if (src_ire != NULL)
4577 					ire_refrele(src_ire);
4578 				return (EINPROGRESS);
4579 			} else if (CLASSD(src_addr)) {
4580 				error = 0;
4581 				if (src_ire != NULL)
4582 					ire_refrele(src_ire);
4583 				/*
4584 				 * (5) bind to multicast address.
4585 				 * Fake out the IRE returned to upper
4586 				 * layer to be a broadcast IRE.
4587 				 */
4588 				src_ire = ire_ctable_lookup(
4589 				    INADDR_BROADCAST, INADDR_ANY,
4590 				    IRE_BROADCAST, NULL, zoneid, NULL,
4591 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4592 				if (src_ire == NULL || !ire_requested)
4593 					error = EADDRNOTAVAIL;
4594 			} else {
4595 				/*
4596 				 * Not a valid address for bind
4597 				 */
4598 				error = EADDRNOTAVAIL;
4599 			}
4600 			/*
4601 			 * Just to keep it consistent with the processing in
4602 			 * ip_bind_v4()
4603 			 */
4604 			mp->b_wptr--;
4605 		}
4606 		if (error) {
4607 			/* Red Alert!  Attempting to be a bogon! */
4608 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4609 			    ntohl(src_addr)));
4610 			goto bad_addr;
4611 		}
4612 	}
4613 
4614 	/*
4615 	 * Allow setting new policies. For example, disconnects come
4616 	 * down as ipa_t bind. As we would have set conn_policy_cached
4617 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4618 	 * can change after the disconnect.
4619 	 */
4620 	connp->conn_policy_cached = B_FALSE;
4621 
4622 	/*
4623 	 * If not fanout_insert this was just an address verification
4624 	 */
4625 	if (fanout_insert) {
4626 		/*
4627 		 * The addresses have been verified. Time to insert in
4628 		 * the correct fanout list.
4629 		 */
4630 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4631 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4632 		connp->conn_lport = lport;
4633 		connp->conn_fport = 0;
4634 		/*
4635 		 * Do we need to add a check to reject Multicast packets
4636 		 */
4637 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4638 	}
4639 
4640 	if (error == 0) {
4641 		if (ire_requested) {
4642 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4643 				error = -1;
4644 				/* Falls through to bad_addr */
4645 			}
4646 		} else if (ipsec_policy_set) {
4647 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4648 				error = -1;
4649 				/* Falls through to bad_addr */
4650 			}
4651 		}
4652 	}
4653 bad_addr:
4654 	if (error != 0) {
4655 		if (connp->conn_anon_port) {
4656 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4657 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4658 			    B_FALSE);
4659 		}
4660 		connp->conn_mlp_type = mlptSingle;
4661 	}
4662 	if (src_ire != NULL)
4663 		IRE_REFRELE(src_ire);
4664 	if (ipsec_policy_set) {
4665 		ASSERT(policy_mp == mp->b_cont);
4666 		ASSERT(policy_mp != NULL);
4667 		freeb(policy_mp);
4668 		/*
4669 		 * As of now assume that nothing else accompanies
4670 		 * IPSEC_POLICY_SET.
4671 		 */
4672 		mp->b_cont = NULL;
4673 	}
4674 	return (error);
4675 }
4676 
4677 /*
4678  * Verify that both the source and destination addresses
4679  * are valid.  If verify_dst is false, then the destination address may be
4680  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4681  * destination reachability, while tunnels do not.
4682  * Note that we allow connect to broadcast and multicast
4683  * addresses when ire_requested is set. Thus the ULP
4684  * has to check for IRE_BROADCAST and multicast.
4685  *
4686  * Returns zero if ok.
4687  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4688  * (for use with TSYSERR reply).
4689  *
4690  * Note: lport and fport are in network byte order.
4691  */
4692 int
4693 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4694     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4695     boolean_t ire_requested, boolean_t ipsec_policy_set,
4696     boolean_t fanout_insert, boolean_t verify_dst)
4697 {
4698 	ire_t		*src_ire;
4699 	ire_t		*dst_ire;
4700 	int		error = 0;
4701 	int 		protocol;
4702 	mblk_t		*policy_mp;
4703 	ire_t		*sire = NULL;
4704 	ire_t		*md_dst_ire = NULL;
4705 	ill_t		*md_ill = NULL;
4706 	zoneid_t	zoneid;
4707 	ipaddr_t	src_addr = *src_addrp;
4708 
4709 	src_ire = dst_ire = NULL;
4710 	protocol = *mp->b_wptr & 0xFF;
4711 
4712 	/*
4713 	 * If we never got a disconnect before, clear it now.
4714 	 */
4715 	connp->conn_fully_bound = B_FALSE;
4716 
4717 	if (ipsec_policy_set) {
4718 		policy_mp = mp->b_cont;
4719 	}
4720 
4721 	zoneid = IPCL_ZONEID(connp);
4722 
4723 	if (CLASSD(dst_addr)) {
4724 		/* Pick up an IRE_BROADCAST */
4725 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4726 		    NULL, zoneid, MBLK_GETLABEL(mp),
4727 		    (MATCH_IRE_RECURSIVE |
4728 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4729 		    MATCH_IRE_SECATTR));
4730 	} else {
4731 		/*
4732 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4733 		 * and onlink ipif is not found set ENETUNREACH error.
4734 		 */
4735 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4736 			ipif_t *ipif;
4737 
4738 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4739 			    dst_addr : connp->conn_nexthop_v4, zoneid);
4740 			if (ipif == NULL) {
4741 				error = ENETUNREACH;
4742 				goto bad_addr;
4743 			}
4744 			ipif_refrele(ipif);
4745 		}
4746 
4747 		if (connp->conn_nexthop_set) {
4748 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4749 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4750 			    MATCH_IRE_SECATTR);
4751 		} else {
4752 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4753 			    &sire, zoneid, MBLK_GETLABEL(mp),
4754 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4755 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4756 			    MATCH_IRE_SECATTR));
4757 		}
4758 	}
4759 	/*
4760 	 * dst_ire can't be a broadcast when not ire_requested.
4761 	 * We also prevent ire's with src address INADDR_ANY to
4762 	 * be used, which are created temporarily for
4763 	 * sending out packets from endpoints that have
4764 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4765 	 * reachable.  If verify_dst is false, the destination needn't be
4766 	 * reachable.
4767 	 *
4768 	 * If we match on a reject or black hole, then we've got a
4769 	 * local failure.  May as well fail out the connect() attempt,
4770 	 * since it's never going to succeed.
4771 	 */
4772 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4773 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4774 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4775 		/*
4776 		 * If we're verifying destination reachability, we always want
4777 		 * to complain here.
4778 		 *
4779 		 * If we're not verifying destination reachability but the
4780 		 * destination has a route, we still want to fail on the
4781 		 * temporary address and broadcast address tests.
4782 		 */
4783 		if (verify_dst || (dst_ire != NULL)) {
4784 			if (ip_debug > 2) {
4785 				pr_addr_dbg("ip_bind_connected: bad connected "
4786 				    "dst %s\n", AF_INET, &dst_addr);
4787 			}
4788 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4789 				error = ENETUNREACH;
4790 			else
4791 				error = EHOSTUNREACH;
4792 			goto bad_addr;
4793 		}
4794 	}
4795 
4796 	/*
4797 	 * We now know that routing will allow us to reach the destination.
4798 	 * Check whether Trusted Solaris policy allows communication with this
4799 	 * host, and pretend that the destination is unreachable if not.
4800 	 *
4801 	 * This is never a problem for TCP, since that transport is known to
4802 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4803 	 * handling.  If the remote is unreachable, it will be detected at that
4804 	 * point, so there's no reason to check it here.
4805 	 *
4806 	 * Note that for sendto (and other datagram-oriented friends), this
4807 	 * check is done as part of the data path label computation instead.
4808 	 * The check here is just to make non-TCP connect() report the right
4809 	 * error.
4810 	 */
4811 	if (dst_ire != NULL && is_system_labeled() &&
4812 	    !IPCL_IS_TCP(connp) &&
4813 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4814 	    connp->conn_mac_exempt) != 0) {
4815 		error = EHOSTUNREACH;
4816 		if (ip_debug > 2) {
4817 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4818 			    AF_INET, &dst_addr);
4819 		}
4820 		goto bad_addr;
4821 	}
4822 
4823 	/*
4824 	 * If the app does a connect(), it means that it will most likely
4825 	 * send more than 1 packet to the destination.  It makes sense
4826 	 * to clear the temporary flag.
4827 	 */
4828 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4829 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4830 		irb_t *irb = dst_ire->ire_bucket;
4831 
4832 		rw_enter(&irb->irb_lock, RW_WRITER);
4833 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4834 		irb->irb_tmp_ire_cnt--;
4835 		rw_exit(&irb->irb_lock);
4836 	}
4837 
4838 	/*
4839 	 * See if we should notify ULP about MDT; we do this whether or not
4840 	 * ire_requested is TRUE, in order to handle active connects; MDT
4841 	 * eligibility tests for passive connects are handled separately
4842 	 * through tcp_adapt_ire().  We do this before the source address
4843 	 * selection, because dst_ire may change after a call to
4844 	 * ipif_select_source().  This is a best-effort check, as the
4845 	 * packet for this connection may not actually go through
4846 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4847 	 * calling ip_newroute().  This is why we further check on the
4848 	 * IRE during Multidata packet transmission in tcp_multisend().
4849 	 */
4850 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4851 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4852 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4853 	    ILL_MDT_CAPABLE(md_ill)) {
4854 		md_dst_ire = dst_ire;
4855 		IRE_REFHOLD(md_dst_ire);
4856 	}
4857 
4858 	if (dst_ire != NULL &&
4859 	    dst_ire->ire_type == IRE_LOCAL &&
4860 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4861 		/*
4862 		 * If the IRE belongs to a different zone, look for a matching
4863 		 * route in the forwarding table and use the source address from
4864 		 * that route.
4865 		 */
4866 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4867 		    zoneid, 0, NULL,
4868 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4869 		    MATCH_IRE_RJ_BHOLE);
4870 		if (src_ire == NULL) {
4871 			error = EHOSTUNREACH;
4872 			goto bad_addr;
4873 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4874 			if (!(src_ire->ire_type & IRE_HOST))
4875 				error = ENETUNREACH;
4876 			else
4877 				error = EHOSTUNREACH;
4878 			goto bad_addr;
4879 		}
4880 		if (src_addr == INADDR_ANY)
4881 			src_addr = src_ire->ire_src_addr;
4882 		ire_refrele(src_ire);
4883 		src_ire = NULL;
4884 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4885 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4886 			src_addr = sire->ire_src_addr;
4887 			ire_refrele(dst_ire);
4888 			dst_ire = sire;
4889 			sire = NULL;
4890 		} else {
4891 			/*
4892 			 * Pick a source address so that a proper inbound
4893 			 * load spreading would happen.
4894 			 */
4895 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4896 			ipif_t *src_ipif = NULL;
4897 			ire_t *ipif_ire;
4898 
4899 			/*
4900 			 * Supply a local source address such that inbound
4901 			 * load spreading happens.
4902 			 *
4903 			 * Determine the best source address on this ill for
4904 			 * the destination.
4905 			 *
4906 			 * 1) For broadcast, we should return a broadcast ire
4907 			 *    found above so that upper layers know that the
4908 			 *    destination address is a broadcast address.
4909 			 *
4910 			 * 2) If this is part of a group, select a better
4911 			 *    source address so that better inbound load
4912 			 *    balancing happens. Do the same if the ipif
4913 			 *    is DEPRECATED.
4914 			 *
4915 			 * 3) If the outgoing interface is part of a usesrc
4916 			 *    group, then try selecting a source address from
4917 			 *    the usesrc ILL.
4918 			 */
4919 			if ((dst_ire->ire_zoneid != zoneid &&
4920 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4921 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4922 			    ((dst_ill->ill_group != NULL) ||
4923 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4924 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4925 				/*
4926 				 * If the destination is reachable via a
4927 				 * given gateway, the selected source address
4928 				 * should be in the same subnet as the gateway.
4929 				 * Otherwise, the destination is not reachable.
4930 				 *
4931 				 * If there are no interfaces on the same subnet
4932 				 * as the destination, ipif_select_source gives
4933 				 * first non-deprecated interface which might be
4934 				 * on a different subnet than the gateway.
4935 				 * This is not desirable. Hence pass the dst_ire
4936 				 * source address to ipif_select_source.
4937 				 * It is sure that the destination is reachable
4938 				 * with the dst_ire source address subnet.
4939 				 * So passing dst_ire source address to
4940 				 * ipif_select_source will make sure that the
4941 				 * selected source will be on the same subnet
4942 				 * as dst_ire source address.
4943 				 */
4944 				ipaddr_t saddr =
4945 				    dst_ire->ire_ipif->ipif_src_addr;
4946 				src_ipif = ipif_select_source(dst_ill,
4947 				    saddr, zoneid);
4948 				if (src_ipif != NULL) {
4949 					if (IS_VNI(src_ipif->ipif_ill)) {
4950 						/*
4951 						 * For VNI there is no
4952 						 * interface route
4953 						 */
4954 						src_addr =
4955 						    src_ipif->ipif_src_addr;
4956 					} else {
4957 						ipif_ire =
4958 						    ipif_to_ire(src_ipif);
4959 						if (ipif_ire != NULL) {
4960 							IRE_REFRELE(dst_ire);
4961 							dst_ire = ipif_ire;
4962 						}
4963 						src_addr =
4964 						    dst_ire->ire_src_addr;
4965 					}
4966 					ipif_refrele(src_ipif);
4967 				} else {
4968 					src_addr = dst_ire->ire_src_addr;
4969 				}
4970 			} else {
4971 				src_addr = dst_ire->ire_src_addr;
4972 			}
4973 		}
4974 	}
4975 
4976 	/*
4977 	 * We do ire_route_lookup() here (and not
4978 	 * interface lookup as we assert that
4979 	 * src_addr should only come from an
4980 	 * UP interface for hard binding.
4981 	 */
4982 	ASSERT(src_ire == NULL);
4983 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
4984 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4985 	/* src_ire must be a local|loopback */
4986 	if (!IRE_IS_LOCAL(src_ire)) {
4987 		if (ip_debug > 2) {
4988 			pr_addr_dbg("ip_bind_connected: bad connected "
4989 			    "src %s\n", AF_INET, &src_addr);
4990 		}
4991 		error = EADDRNOTAVAIL;
4992 		goto bad_addr;
4993 	}
4994 
4995 	/*
4996 	 * If the source address is a loopback address, the
4997 	 * destination had best be local or multicast.
4998 	 * The transports that can't handle multicast will reject
4999 	 * those addresses.
5000 	 */
5001 	if (src_ire->ire_type == IRE_LOOPBACK &&
5002 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5003 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5004 		error = -1;
5005 		goto bad_addr;
5006 	}
5007 
5008 	/*
5009 	 * Allow setting new policies. For example, disconnects come
5010 	 * down as ipa_t bind. As we would have set conn_policy_cached
5011 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5012 	 * can change after the disconnect.
5013 	 */
5014 	connp->conn_policy_cached = B_FALSE;
5015 
5016 	/*
5017 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5018 	 * can handle their passed-in conn's.
5019 	 */
5020 
5021 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5022 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5023 	connp->conn_lport = lport;
5024 	connp->conn_fport = fport;
5025 	*src_addrp = src_addr;
5026 
5027 	ASSERT(!(ipsec_policy_set && ire_requested));
5028 	if (ire_requested) {
5029 		iulp_t *ulp_info = NULL;
5030 
5031 		/*
5032 		 * Note that sire will not be NULL if this is an off-link
5033 		 * connection and there is not cache for that dest yet.
5034 		 *
5035 		 * XXX Because of an existing bug, if there are multiple
5036 		 * default routes, the IRE returned now may not be the actual
5037 		 * default route used (default routes are chosen in a
5038 		 * round robin fashion).  So if the metrics for different
5039 		 * default routes are different, we may return the wrong
5040 		 * metrics.  This will not be a problem if the existing
5041 		 * bug is fixed.
5042 		 */
5043 		if (sire != NULL) {
5044 			ulp_info = &(sire->ire_uinfo);
5045 		}
5046 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5047 			error = -1;
5048 			goto bad_addr;
5049 		}
5050 	} else if (ipsec_policy_set) {
5051 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5052 			error = -1;
5053 			goto bad_addr;
5054 		}
5055 	}
5056 
5057 	/*
5058 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5059 	 * we'll cache that.  If we don't, we'll inherit global policy.
5060 	 *
5061 	 * We can't insert until the conn reflects the policy. Note that
5062 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5063 	 * connections where we don't have a policy. This is to prevent
5064 	 * global policy lookups in the inbound path.
5065 	 *
5066 	 * If we insert before we set conn_policy_cached,
5067 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5068 	 * because global policy cound be non-empty. We normally call
5069 	 * ipsec_check_policy() for conn_policy_cached connections only if
5070 	 * ipc_in_enforce_policy is set. But in this case,
5071 	 * conn_policy_cached can get set anytime since we made the
5072 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5073 	 * called, which will make the above assumption false.  Thus, we
5074 	 * need to insert after we set conn_policy_cached.
5075 	 */
5076 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5077 		goto bad_addr;
5078 
5079 	if (fanout_insert) {
5080 		/*
5081 		 * The addresses have been verified. Time to insert in
5082 		 * the correct fanout list.
5083 		 */
5084 		error = ipcl_conn_insert(connp, protocol, src_addr,
5085 		    dst_addr, connp->conn_ports);
5086 	}
5087 
5088 	if (error == 0) {
5089 		connp->conn_fully_bound = B_TRUE;
5090 		/*
5091 		 * Our initial checks for MDT have passed; the IRE is not
5092 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5093 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
5094 		 * ip_mdinfo_return(), which performs further checks
5095 		 * against them and upon success, returns the MDT info
5096 		 * mblk which we will attach to the bind acknowledgment.
5097 		 */
5098 		if (md_dst_ire != NULL) {
5099 			mblk_t *mdinfo_mp;
5100 
5101 			ASSERT(md_ill != NULL);
5102 			ASSERT(md_ill->ill_mdt_capab != NULL);
5103 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5104 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
5105 				linkb(mp, mdinfo_mp);
5106 		}
5107 	}
5108 bad_addr:
5109 	if (ipsec_policy_set) {
5110 		ASSERT(policy_mp == mp->b_cont);
5111 		ASSERT(policy_mp != NULL);
5112 		freeb(policy_mp);
5113 		/*
5114 		 * As of now assume that nothing else accompanies
5115 		 * IPSEC_POLICY_SET.
5116 		 */
5117 		mp->b_cont = NULL;
5118 	}
5119 	if (src_ire != NULL)
5120 		IRE_REFRELE(src_ire);
5121 	if (dst_ire != NULL)
5122 		IRE_REFRELE(dst_ire);
5123 	if (sire != NULL)
5124 		IRE_REFRELE(sire);
5125 	if (md_dst_ire != NULL)
5126 		IRE_REFRELE(md_dst_ire);
5127 	return (error);
5128 }
5129 
5130 /*
5131  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5132  * Prefers dst_ire over src_ire.
5133  */
5134 static boolean_t
5135 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5136 {
5137 	mblk_t	*mp1;
5138 	ire_t *ret_ire = NULL;
5139 
5140 	mp1 = mp->b_cont;
5141 	ASSERT(mp1 != NULL);
5142 
5143 	if (ire != NULL) {
5144 		/*
5145 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5146 		 * appended mblk. Its <upper protocol>'s
5147 		 * job to make sure there is room.
5148 		 */
5149 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5150 			return (0);
5151 
5152 		mp1->b_datap->db_type = IRE_DB_TYPE;
5153 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5154 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5155 		ret_ire = (ire_t *)mp1->b_rptr;
5156 		/*
5157 		 * Pass the latest setting of the ip_path_mtu_discovery and
5158 		 * copy the ulp info if any.
5159 		 */
5160 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5161 		    IPH_DF : 0;
5162 		if (ulp_info != NULL) {
5163 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5164 			    sizeof (iulp_t));
5165 		}
5166 		ret_ire->ire_mp = mp1;
5167 	} else {
5168 		/*
5169 		 * No IRE was found. Remove IRE mblk.
5170 		 */
5171 		mp->b_cont = mp1->b_cont;
5172 		freeb(mp1);
5173 	}
5174 
5175 	return (1);
5176 }
5177 
5178 /*
5179  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5180  * the final piece where we don't.  Return a pointer to the first mblk in the
5181  * result, and update the pointer to the next mblk to chew on.  If anything
5182  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5183  * NULL pointer.
5184  */
5185 mblk_t *
5186 ip_carve_mp(mblk_t **mpp, ssize_t len)
5187 {
5188 	mblk_t	*mp0;
5189 	mblk_t	*mp1;
5190 	mblk_t	*mp2;
5191 
5192 	if (!len || !mpp || !(mp0 = *mpp))
5193 		return (NULL);
5194 	/* If we aren't going to consume the first mblk, we need a dup. */
5195 	if (mp0->b_wptr - mp0->b_rptr > len) {
5196 		mp1 = dupb(mp0);
5197 		if (mp1) {
5198 			/* Partition the data between the two mblks. */
5199 			mp1->b_wptr = mp1->b_rptr + len;
5200 			mp0->b_rptr = mp1->b_wptr;
5201 			/*
5202 			 * after adjustments if mblk not consumed is now
5203 			 * unaligned, try to align it. If this fails free
5204 			 * all messages and let upper layer recover.
5205 			 */
5206 			if (!OK_32PTR(mp0->b_rptr)) {
5207 				if (!pullupmsg(mp0, -1)) {
5208 					freemsg(mp0);
5209 					freemsg(mp1);
5210 					*mpp = NULL;
5211 					return (NULL);
5212 				}
5213 			}
5214 		}
5215 		return (mp1);
5216 	}
5217 	/* Eat through as many mblks as we need to get len bytes. */
5218 	len -= mp0->b_wptr - mp0->b_rptr;
5219 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5220 		if (mp2->b_wptr - mp2->b_rptr > len) {
5221 			/*
5222 			 * We won't consume the entire last mblk.  Like
5223 			 * above, dup and partition it.
5224 			 */
5225 			mp1->b_cont = dupb(mp2);
5226 			mp1 = mp1->b_cont;
5227 			if (!mp1) {
5228 				/*
5229 				 * Trouble.  Rather than go to a lot of
5230 				 * trouble to clean up, we free the messages.
5231 				 * This won't be any worse than losing it on
5232 				 * the wire.
5233 				 */
5234 				freemsg(mp0);
5235 				freemsg(mp2);
5236 				*mpp = NULL;
5237 				return (NULL);
5238 			}
5239 			mp1->b_wptr = mp1->b_rptr + len;
5240 			mp2->b_rptr = mp1->b_wptr;
5241 			/*
5242 			 * after adjustments if mblk not consumed is now
5243 			 * unaligned, try to align it. If this fails free
5244 			 * all messages and let upper layer recover.
5245 			 */
5246 			if (!OK_32PTR(mp2->b_rptr)) {
5247 				if (!pullupmsg(mp2, -1)) {
5248 					freemsg(mp0);
5249 					freemsg(mp2);
5250 					*mpp = NULL;
5251 					return (NULL);
5252 				}
5253 			}
5254 			*mpp = mp2;
5255 			return (mp0);
5256 		}
5257 		/* Decrement len by the amount we just got. */
5258 		len -= mp2->b_wptr - mp2->b_rptr;
5259 	}
5260 	/*
5261 	 * len should be reduced to zero now.  If not our caller has
5262 	 * screwed up.
5263 	 */
5264 	if (len) {
5265 		/* Shouldn't happen! */
5266 		freemsg(mp0);
5267 		*mpp = NULL;
5268 		return (NULL);
5269 	}
5270 	/*
5271 	 * We consumed up to exactly the end of an mblk.  Detach the part
5272 	 * we are returning from the rest of the chain.
5273 	 */
5274 	mp1->b_cont = NULL;
5275 	*mpp = mp2;
5276 	return (mp0);
5277 }
5278 
5279 /* The ill stream is being unplumbed. Called from ip_close */
5280 int
5281 ip_modclose(ill_t *ill)
5282 {
5283 
5284 	boolean_t success;
5285 	ipsq_t	*ipsq;
5286 	ipif_t	*ipif;
5287 	queue_t	*q = ill->ill_rq;
5288 
5289 	/*
5290 	 * Forcibly enter the ipsq after some delay. This is to take
5291 	 * care of the case when some ioctl does not complete because
5292 	 * we sent a control message to the driver and it did not
5293 	 * send us a reply. We want to be able to at least unplumb
5294 	 * and replumb rather than force the user to reboot the system.
5295 	 */
5296 	success = ipsq_enter(ill, B_FALSE);
5297 
5298 	/*
5299 	 * Open/close/push/pop is guaranteed to be single threaded
5300 	 * per stream by STREAMS. FS guarantees that all references
5301 	 * from top are gone before close is called. So there can't
5302 	 * be another close thread that has set CONDEMNED on this ill.
5303 	 * and cause ipsq_enter to return failure.
5304 	 */
5305 	ASSERT(success);
5306 	ipsq = ill->ill_phyint->phyint_ipsq;
5307 
5308 	/*
5309 	 * Mark it condemned. No new reference will be made to this ill.
5310 	 * Lookup functions will return an error. Threads that try to
5311 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5312 	 * that the refcnt will drop down to zero.
5313 	 */
5314 	mutex_enter(&ill->ill_lock);
5315 	ill->ill_state_flags |= ILL_CONDEMNED;
5316 	for (ipif = ill->ill_ipif; ipif != NULL;
5317 	    ipif = ipif->ipif_next) {
5318 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5319 	}
5320 	/*
5321 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5322 	 * returns  error if ILL_CONDEMNED is set
5323 	 */
5324 	cv_broadcast(&ill->ill_cv);
5325 	mutex_exit(&ill->ill_lock);
5326 
5327 	/*
5328 	 * Shut down fragmentation reassembly.
5329 	 * ill_frag_timer won't start a timer again.
5330 	 * Now cancel any existing timer
5331 	 */
5332 	(void) untimeout(ill->ill_frag_timer_id);
5333 	(void) ill_frag_timeout(ill, 0);
5334 
5335 	/*
5336 	 * If MOVE was in progress, clear the
5337 	 * move_in_progress fields also.
5338 	 */
5339 	if (ill->ill_move_in_progress) {
5340 		ILL_CLEAR_MOVE(ill);
5341 	}
5342 
5343 	/*
5344 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5345 	 * this ill. Then wait for the refcnts to drop to zero.
5346 	 * ill_is_quiescent checks whether the ill is really quiescent.
5347 	 * Then make sure that threads that are waiting to enter the
5348 	 * ipsq have seen the error returned by ipsq_enter and have
5349 	 * gone away. Then we call ill_delete_tail which does the
5350 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5351 	 */
5352 	ill_delete(ill);
5353 	mutex_enter(&ill->ill_lock);
5354 	while (!ill_is_quiescent(ill))
5355 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5356 	while (ill->ill_waiters)
5357 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5358 
5359 	mutex_exit(&ill->ill_lock);
5360 
5361 	/* qprocsoff is called in ill_delete_tail */
5362 	ill_delete_tail(ill);
5363 
5364 	/*
5365 	 * Walk through all upper (conn) streams and qenable
5366 	 * those that have queued data.
5367 	 * close synchronization needs this to
5368 	 * be done to ensure that all upper layers blocked
5369 	 * due to flow control to the closing device
5370 	 * get unblocked.
5371 	 */
5372 	ip1dbg(("ip_wsrv: walking\n"));
5373 	conn_walk_drain();
5374 
5375 	mutex_enter(&ip_mi_lock);
5376 	mi_close_unlink(&ip_g_head, (IDP)ill);
5377 	mutex_exit(&ip_mi_lock);
5378 
5379 	/*
5380 	 * credp could be null if the open didn't succeed and ip_modopen
5381 	 * itself calls ip_close.
5382 	 */
5383 	if (ill->ill_credp != NULL)
5384 		crfree(ill->ill_credp);
5385 
5386 	mi_close_free((IDP)ill);
5387 	q->q_ptr = WR(q)->q_ptr = NULL;
5388 
5389 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5390 
5391 	return (0);
5392 }
5393 
5394 /*
5395  * This is called as part of close() for both IP and UDP
5396  * in order to quiesce the conn.
5397  */
5398 void
5399 ip_quiesce_conn(conn_t *connp)
5400 {
5401 	boolean_t	drain_cleanup_reqd = B_FALSE;
5402 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5403 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5404 
5405 	ASSERT(!IPCL_IS_TCP(connp));
5406 
5407 	/*
5408 	 * Mark the conn as closing, and this conn must not be
5409 	 * inserted in future into any list. Eg. conn_drain_insert(),
5410 	 * won't insert this conn into the conn_drain_list.
5411 	 * Similarly ill_pending_mp_add() will not add any mp to
5412 	 * the pending mp list, after this conn has started closing.
5413 	 *
5414 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5415 	 * cannot get set henceforth.
5416 	 */
5417 	mutex_enter(&connp->conn_lock);
5418 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5419 	connp->conn_state_flags |= CONN_CLOSING;
5420 	if (connp->conn_idl != NULL)
5421 		drain_cleanup_reqd = B_TRUE;
5422 	if (connp->conn_oper_pending_ill != NULL)
5423 		conn_ioctl_cleanup_reqd = B_TRUE;
5424 	if (connp->conn_ilg_inuse != 0)
5425 		ilg_cleanup_reqd = B_TRUE;
5426 	mutex_exit(&connp->conn_lock);
5427 
5428 	if (IPCL_IS_UDP(connp))
5429 		udp_quiesce_conn(connp);
5430 
5431 	if (conn_ioctl_cleanup_reqd)
5432 		conn_ioctl_cleanup(connp);
5433 
5434 	if (is_system_labeled() && connp->conn_anon_port) {
5435 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5436 		    connp->conn_mlp_type, connp->conn_ulp,
5437 		    ntohs(connp->conn_lport), B_FALSE);
5438 		connp->conn_anon_port = 0;
5439 	}
5440 	connp->conn_mlp_type = mlptSingle;
5441 
5442 	/*
5443 	 * Remove this conn from any fanout list it is on.
5444 	 * and then wait for any threads currently operating
5445 	 * on this endpoint to finish
5446 	 */
5447 	ipcl_hash_remove(connp);
5448 
5449 	/*
5450 	 * Remove this conn from the drain list, and do
5451 	 * any other cleanup that may be required.
5452 	 * (Only non-tcp streams may have a non-null conn_idl.
5453 	 * TCP streams are never flow controlled, and
5454 	 * conn_idl will be null)
5455 	 */
5456 	if (drain_cleanup_reqd)
5457 		conn_drain_tail(connp, B_TRUE);
5458 
5459 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5460 		(void) ip_mrouter_done(NULL);
5461 
5462 	if (ilg_cleanup_reqd)
5463 		ilg_delete_all(connp);
5464 
5465 	conn_delete_ire(connp, NULL);
5466 
5467 	/*
5468 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5469 	 * callers from write side can't be there now because close
5470 	 * is in progress. The only other caller is ipcl_walk
5471 	 * which checks for the condemned flag.
5472 	 */
5473 	mutex_enter(&connp->conn_lock);
5474 	connp->conn_state_flags |= CONN_CONDEMNED;
5475 	while (connp->conn_ref != 1)
5476 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5477 	connp->conn_state_flags |= CONN_QUIESCED;
5478 	mutex_exit(&connp->conn_lock);
5479 }
5480 
5481 /* ARGSUSED */
5482 int
5483 ip_close(queue_t *q, int flags)
5484 {
5485 	conn_t		*connp;
5486 
5487 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5488 
5489 	/*
5490 	 * Call the appropriate delete routine depending on whether this is
5491 	 * a module or device.
5492 	 */
5493 	if (WR(q)->q_next != NULL) {
5494 		/* This is a module close */
5495 		return (ip_modclose((ill_t *)q->q_ptr));
5496 	}
5497 
5498 	connp = q->q_ptr;
5499 	ip_quiesce_conn(connp);
5500 
5501 	qprocsoff(q);
5502 
5503 	/*
5504 	 * Now we are truly single threaded on this stream, and can
5505 	 * delete the things hanging off the connp, and finally the connp.
5506 	 * We removed this connp from the fanout list, it cannot be
5507 	 * accessed thru the fanouts, and we already waited for the
5508 	 * conn_ref to drop to 0. We are already in close, so
5509 	 * there cannot be any other thread from the top. qprocsoff
5510 	 * has completed, and service has completed or won't run in
5511 	 * future.
5512 	 */
5513 	ASSERT(connp->conn_ref == 1);
5514 
5515 	/*
5516 	 * A conn which was previously marked as IPCL_UDP cannot
5517 	 * retain the flag because it would have been cleared by
5518 	 * udp_close().
5519 	 */
5520 	ASSERT(!IPCL_IS_UDP(connp));
5521 
5522 	if (connp->conn_latch != NULL) {
5523 		IPLATCH_REFRELE(connp->conn_latch);
5524 		connp->conn_latch = NULL;
5525 	}
5526 	if (connp->conn_policy != NULL) {
5527 		IPPH_REFRELE(connp->conn_policy);
5528 		connp->conn_policy = NULL;
5529 	}
5530 	if (connp->conn_ipsec_opt_mp != NULL) {
5531 		freemsg(connp->conn_ipsec_opt_mp);
5532 		connp->conn_ipsec_opt_mp = NULL;
5533 	}
5534 
5535 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5536 
5537 	connp->conn_ref--;
5538 	ipcl_conn_destroy(connp);
5539 
5540 	q->q_ptr = WR(q)->q_ptr = NULL;
5541 	return (0);
5542 }
5543 
5544 int
5545 ip_snmpmod_close(queue_t *q)
5546 {
5547 	conn_t *connp = Q_TO_CONN(q);
5548 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5549 
5550 	qprocsoff(q);
5551 
5552 	if (connp->conn_flags & IPCL_UDPMOD)
5553 		udp_close_free(connp);
5554 
5555 	if (connp->conn_cred != NULL) {
5556 		crfree(connp->conn_cred);
5557 		connp->conn_cred = NULL;
5558 	}
5559 	CONN_DEC_REF(connp);
5560 	q->q_ptr = WR(q)->q_ptr = NULL;
5561 	return (0);
5562 }
5563 
5564 /*
5565  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5566  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5567  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5568  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5569  * queues as we never enqueue messages there and we don't handle any ioctls.
5570  * Everything else is freed.
5571  */
5572 void
5573 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5574 {
5575 	conn_t	*connp = q->q_ptr;
5576 	pfi_t	setfn;
5577 	pfi_t	getfn;
5578 
5579 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5580 
5581 	switch (DB_TYPE(mp)) {
5582 	case M_PROTO:
5583 	case M_PCPROTO:
5584 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5585 		    ((((union T_primitives *)mp->b_rptr)->type ==
5586 			T_SVR4_OPTMGMT_REQ) ||
5587 		    (((union T_primitives *)mp->b_rptr)->type ==
5588 			T_OPTMGMT_REQ))) {
5589 			/*
5590 			 * This is the only TPI primitive supported. Its
5591 			 * handling does not require tcp_t, but it does require
5592 			 * conn_t to check permissions.
5593 			 */
5594 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5595 
5596 			if (connp->conn_flags & IPCL_TCPMOD) {
5597 				setfn = tcp_snmp_set;
5598 				getfn = tcp_snmp_get;
5599 			} else {
5600 				setfn = udp_snmp_set;
5601 				getfn = udp_snmp_get;
5602 			}
5603 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5604 				freemsg(mp);
5605 				return;
5606 			}
5607 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5608 		    != NULL)
5609 			qreply(q, mp);
5610 		break;
5611 	case M_FLUSH:
5612 	case M_IOCTL:
5613 		putnext(q, mp);
5614 		break;
5615 	default:
5616 		freemsg(mp);
5617 		break;
5618 	}
5619 }
5620 
5621 /* Return the IP checksum for the IP header at "iph". */
5622 uint16_t
5623 ip_csum_hdr(ipha_t *ipha)
5624 {
5625 	uint16_t	*uph;
5626 	uint32_t	sum;
5627 	int		opt_len;
5628 
5629 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5630 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5631 	uph = (uint16_t *)ipha;
5632 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5633 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5634 	if (opt_len > 0) {
5635 		do {
5636 			sum += uph[10];
5637 			sum += uph[11];
5638 			uph += 2;
5639 		} while (--opt_len);
5640 	}
5641 	sum = (sum & 0xFFFF) + (sum >> 16);
5642 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5643 	if (sum == 0xffff)
5644 		sum = 0;
5645 	return ((uint16_t)sum);
5646 }
5647 
5648 void
5649 ip_ddi_destroy(void)
5650 {
5651 	tnet_fini();
5652 	tcp_ddi_destroy();
5653 	sctp_ddi_destroy();
5654 	ipsec_loader_destroy();
5655 	ipsec_policy_destroy();
5656 	ipsec_kstat_destroy();
5657 	nd_free(&ip_g_nd);
5658 	mutex_destroy(&igmp_timer_lock);
5659 	mutex_destroy(&mld_timer_lock);
5660 	mutex_destroy(&igmp_slowtimeout_lock);
5661 	mutex_destroy(&mld_slowtimeout_lock);
5662 	mutex_destroy(&ip_mi_lock);
5663 	mutex_destroy(&rts_clients.connf_lock);
5664 	ip_ire_fini();
5665 	ip6_asp_free();
5666 	conn_drain_fini();
5667 	ipcl_destroy();
5668 	inet_minor_destroy(ip_minor_arena);
5669 	icmp_kstat_fini();
5670 	ip_kstat_fini();
5671 	rw_destroy(&ipsec_capab_ills_lock);
5672 	rw_destroy(&ill_g_usesrc_lock);
5673 	ip_drop_unregister(&ip_dropper);
5674 }
5675 
5676 
5677 void
5678 ip_ddi_init(void)
5679 {
5680 	TCP6_MAJ = ddi_name_to_major(TCP6);
5681 	TCP_MAJ	= ddi_name_to_major(TCP);
5682 	SCTP_MAJ = ddi_name_to_major(SCTP);
5683 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5684 
5685 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5686 
5687 	/* IP's IPsec code calls the packet dropper */
5688 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5689 
5690 	if (!ip_g_nd) {
5691 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5692 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5693 			nd_free(&ip_g_nd);
5694 		}
5695 	}
5696 
5697 	ipsec_loader_init();
5698 	ipsec_policy_init();
5699 	ipsec_kstat_init();
5700 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5701 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5702 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5703 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5704 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5705 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5706 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5707 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5708 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5709 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5710 
5711 	/*
5712 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5713 	 * initial devices: ip, ip6, tcp, tcp6.
5714 	 */
5715 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5716 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5717 		cmn_err(CE_PANIC,
5718 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5719 	}
5720 
5721 	ipcl_init();
5722 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5723 	ip_ire_init();
5724 	ip6_asp_init();
5725 	ipif_init();
5726 	conn_drain_init();
5727 	tcp_ddi_init();
5728 	sctp_ddi_init();
5729 
5730 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5731 
5732 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5733 		"net", KSTAT_TYPE_NAMED,
5734 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5735 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5736 		ip_kstat->ks_data = &ip_statistics;
5737 		kstat_install(ip_kstat);
5738 	}
5739 	ip_kstat_init();
5740 	ip6_kstat_init();
5741 	icmp_kstat_init();
5742 	ipsec_loader_start();
5743 	tnet_init();
5744 }
5745 
5746 /*
5747  * Allocate and initialize a DLPI template of the specified length.  (May be
5748  * called as writer.)
5749  */
5750 mblk_t *
5751 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5752 {
5753 	mblk_t	*mp;
5754 
5755 	mp = allocb(len, BPRI_MED);
5756 	if (!mp)
5757 		return (NULL);
5758 
5759 	/*
5760 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5761 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5762 	 * that other DLPI are M_PROTO.
5763 	 */
5764 	if (prim == DL_INFO_REQ) {
5765 		mp->b_datap->db_type = M_PCPROTO;
5766 	} else {
5767 		mp->b_datap->db_type = M_PROTO;
5768 	}
5769 
5770 	mp->b_wptr = mp->b_rptr + len;
5771 	bzero(mp->b_rptr, len);
5772 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5773 	return (mp);
5774 }
5775 
5776 const char *
5777 dlpi_prim_str(int prim)
5778 {
5779 	switch (prim) {
5780 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5781 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5782 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5783 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5784 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5785 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5786 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5787 	case DL_OK_ACK:		return ("DL_OK_ACK");
5788 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5789 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5790 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5791 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5792 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5793 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5794 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5795 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5796 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5797 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5798 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5799 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5800 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5801 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5802 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5803 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5804 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5805 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5806 	default:		return ("<unknown primitive>");
5807 	}
5808 }
5809 
5810 const char *
5811 dlpi_err_str(int err)
5812 {
5813 	switch (err) {
5814 	case DL_ACCESS:		return ("DL_ACCESS");
5815 	case DL_BADADDR:	return ("DL_BADADDR");
5816 	case DL_BADCORR:	return ("DL_BADCORR");
5817 	case DL_BADDATA:	return ("DL_BADDATA");
5818 	case DL_BADPPA:		return ("DL_BADPPA");
5819 	case DL_BADPRIM:	return ("DL_BADPRIM");
5820 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5821 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5822 	case DL_BADSAP:		return ("DL_BADSAP");
5823 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5824 	case DL_BOUND:		return ("DL_BOUND");
5825 	case DL_INITFAILED:	return ("DL_INITFAILED");
5826 	case DL_NOADDR:		return ("DL_NOADDR");
5827 	case DL_NOTINIT:	return ("DL_NOTINIT");
5828 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5829 	case DL_SYSERR:		return ("DL_SYSERR");
5830 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5831 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5832 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5833 	case DL_TOOMANY:	return ("DL_TOOMANY");
5834 	case DL_NOTENAB:	return ("DL_NOTENAB");
5835 	case DL_BUSY:		return ("DL_BUSY");
5836 	case DL_NOAUTO:		return ("DL_NOAUTO");
5837 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5838 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5839 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5840 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5841 	case DL_PENDING:	return ("DL_PENDING");
5842 	default:		return ("<unknown error>");
5843 	}
5844 }
5845 
5846 /*
5847  * Debug formatting routine.  Returns a character string representation of the
5848  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5849  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5850  *
5851  * Once the ndd table-printing interfaces are removed, this can be changed to
5852  * standard dotted-decimal form.
5853  */
5854 char *
5855 ip_dot_addr(ipaddr_t addr, char *buf)
5856 {
5857 	uint8_t *ap = (uint8_t *)&addr;
5858 
5859 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5860 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
5861 	return (buf);
5862 }
5863 
5864 /*
5865  * Write the given MAC address as a printable string in the usual colon-
5866  * separated format.
5867  */
5868 const char *
5869 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
5870 {
5871 	char *bp;
5872 
5873 	if (alen == 0 || buflen < 4)
5874 		return ("?");
5875 	bp = buf;
5876 	for (;;) {
5877 		/*
5878 		 * If there are more MAC address bytes available, but we won't
5879 		 * have any room to print them, then add "..." to the string
5880 		 * instead.  See below for the 'magic number' explanation.
5881 		 */
5882 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
5883 			(void) strcpy(bp, "...");
5884 			break;
5885 		}
5886 		(void) sprintf(bp, "%02x", *addr++);
5887 		bp += 2;
5888 		if (--alen == 0)
5889 			break;
5890 		*bp++ = ':';
5891 		buflen -= 3;
5892 		/*
5893 		 * At this point, based on the first 'if' statement above,
5894 		 * either alen == 1 and buflen >= 3, or alen > 1 and
5895 		 * buflen >= 4.  The first case leaves room for the final "xx"
5896 		 * number and trailing NUL byte.  The second leaves room for at
5897 		 * least "...".  Thus the apparently 'magic' numbers chosen for
5898 		 * that statement.
5899 		 */
5900 	}
5901 	return (buf);
5902 }
5903 
5904 /*
5905  * Send an ICMP error after patching up the packet appropriately.  Returns
5906  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5907  */
5908 static boolean_t
5909 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5910     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5911 {
5912 	ipha_t *ipha;
5913 	mblk_t *first_mp;
5914 	boolean_t secure;
5915 	unsigned char db_type;
5916 
5917 	first_mp = mp;
5918 	if (mctl_present) {
5919 		mp = mp->b_cont;
5920 		secure = ipsec_in_is_secure(first_mp);
5921 		ASSERT(mp != NULL);
5922 	} else {
5923 		/*
5924 		 * If this is an ICMP error being reported - which goes
5925 		 * up as M_CTLs, we need to convert them to M_DATA till
5926 		 * we finish checking with global policy because
5927 		 * ipsec_check_global_policy() assumes M_DATA as clear
5928 		 * and M_CTL as secure.
5929 		 */
5930 		db_type = DB_TYPE(mp);
5931 		DB_TYPE(mp) = M_DATA;
5932 		secure = B_FALSE;
5933 	}
5934 	/*
5935 	 * We are generating an icmp error for some inbound packet.
5936 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
5937 	 * Before we generate an error, check with global policy
5938 	 * to see whether this is allowed to enter the system. As
5939 	 * there is no "conn", we are checking with global policy.
5940 	 */
5941 	ipha = (ipha_t *)mp->b_rptr;
5942 	if (secure || ipsec_inbound_v4_policy_present) {
5943 		first_mp = ipsec_check_global_policy(first_mp, NULL,
5944 		    ipha, NULL, mctl_present);
5945 		if (first_mp == NULL)
5946 			return (B_FALSE);
5947 	}
5948 
5949 	if (!mctl_present)
5950 		DB_TYPE(mp) = db_type;
5951 
5952 	if (flags & IP_FF_SEND_ICMP) {
5953 		if (flags & IP_FF_HDR_COMPLETE) {
5954 			if (ip_hdr_complete(ipha, zoneid)) {
5955 				freemsg(first_mp);
5956 				return (B_TRUE);
5957 			}
5958 		}
5959 		if (flags & IP_FF_CKSUM) {
5960 			/*
5961 			 * Have to correct checksum since
5962 			 * the packet might have been
5963 			 * fragmented and the reassembly code in ip_rput
5964 			 * does not restore the IP checksum.
5965 			 */
5966 			ipha->ipha_hdr_checksum = 0;
5967 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
5968 		}
5969 		switch (icmp_type) {
5970 		case ICMP_DEST_UNREACHABLE:
5971 			icmp_unreachable(WR(q), first_mp, icmp_code);
5972 			break;
5973 		default:
5974 			freemsg(first_mp);
5975 			break;
5976 		}
5977 	} else {
5978 		freemsg(first_mp);
5979 		return (B_FALSE);
5980 	}
5981 
5982 	return (B_TRUE);
5983 }
5984 
5985 /*
5986  * Used to send an ICMP error message when a packet is received for
5987  * a protocol that is not supported. The mblk passed as argument
5988  * is consumed by this function.
5989  */
5990 void
5991 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
5992 {
5993 	mblk_t *mp;
5994 	ipha_t *ipha;
5995 	ill_t *ill;
5996 	ipsec_in_t *ii;
5997 
5998 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5999 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6000 
6001 	mp = ipsec_mp->b_cont;
6002 	ipsec_mp->b_cont = NULL;
6003 	ipha = (ipha_t *)mp->b_rptr;
6004 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6005 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
6006 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6007 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
6008 		}
6009 	} else {
6010 		/* Get ill from index in ipsec_in_t. */
6011 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6012 		    B_TRUE, NULL, NULL, NULL, NULL);
6013 		if (ill != NULL) {
6014 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6015 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6016 			    0, B_FALSE, zoneid)) {
6017 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
6018 			}
6019 
6020 			ill_refrele(ill);
6021 		} else { /* re-link for the freemsg() below. */
6022 			ipsec_mp->b_cont = mp;
6023 		}
6024 	}
6025 
6026 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6027 	freemsg(ipsec_mp);
6028 }
6029 
6030 /*
6031  * See if the inbound datagram has had IPsec processing applied to it.
6032  */
6033 boolean_t
6034 ipsec_in_is_secure(mblk_t *ipsec_mp)
6035 {
6036 	ipsec_in_t *ii;
6037 
6038 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6039 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6040 
6041 	if (ii->ipsec_in_loopback) {
6042 		return (ii->ipsec_in_secure);
6043 	} else {
6044 		return (ii->ipsec_in_ah_sa != NULL ||
6045 		    ii->ipsec_in_esp_sa != NULL ||
6046 		    ii->ipsec_in_decaps);
6047 	}
6048 }
6049 
6050 /*
6051  * Handle protocols with which IP is less intimate.  There
6052  * can be more than one stream bound to a particular
6053  * protocol.  When this is the case, normally each one gets a copy
6054  * of any incoming packets.
6055  *
6056  * IPSEC NOTE :
6057  *
6058  * Don't allow a secure packet going up a non-secure connection.
6059  * We don't allow this because
6060  *
6061  * 1) Reply might go out in clear which will be dropped at
6062  *    the sending side.
6063  * 2) If the reply goes out in clear it will give the
6064  *    adversary enough information for getting the key in
6065  *    most of the cases.
6066  *
6067  * Moreover getting a secure packet when we expect clear
6068  * implies that SA's were added without checking for
6069  * policy on both ends. This should not happen once ISAKMP
6070  * is used to negotiate SAs as SAs will be added only after
6071  * verifying the policy.
6072  *
6073  * NOTE : If the packet was tunneled and not multicast we only send
6074  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6075  * back to delivering packets to AF_INET6 raw sockets.
6076  *
6077  * IPQoS Notes:
6078  * Once we have determined the client, invoke IPPF processing.
6079  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6080  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6081  * ip_policy will be false.
6082  *
6083  * Zones notes:
6084  * Currently only applications in the global zone can create raw sockets for
6085  * protocols other than ICMP. So unlike the broadcast / multicast case of
6086  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6087  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6088  */
6089 static void
6090 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6091     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6092     zoneid_t zoneid)
6093 {
6094 	queue_t	*rq;
6095 	mblk_t	*mp1, *first_mp1;
6096 	uint_t	protocol = ipha->ipha_protocol;
6097 	ipaddr_t dst;
6098 	boolean_t one_only;
6099 	mblk_t *first_mp = mp;
6100 	boolean_t secure;
6101 	uint32_t ill_index;
6102 	conn_t	*connp, *first_connp, *next_connp;
6103 	connf_t	*connfp;
6104 	boolean_t shared_addr;
6105 
6106 	if (mctl_present) {
6107 		mp = first_mp->b_cont;
6108 		secure = ipsec_in_is_secure(first_mp);
6109 		ASSERT(mp != NULL);
6110 	} else {
6111 		secure = B_FALSE;
6112 	}
6113 	dst = ipha->ipha_dst;
6114 	/*
6115 	 * If the packet was tunneled and not multicast we only send to it
6116 	 * the first match.
6117 	 */
6118 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6119 	    !CLASSD(dst));
6120 
6121 	shared_addr = (zoneid == ALL_ZONES);
6122 	if (shared_addr) {
6123 		/*
6124 		 * We don't allow multilevel ports for raw IP, so no need to
6125 		 * check for that here.
6126 		 */
6127 		zoneid = tsol_packet_to_zoneid(mp);
6128 	}
6129 
6130 	connfp = &ipcl_proto_fanout[protocol];
6131 	mutex_enter(&connfp->connf_lock);
6132 	connp = connfp->connf_head;
6133 	for (connp = connfp->connf_head; connp != NULL;
6134 		connp = connp->conn_next) {
6135 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6136 		    zoneid) &&
6137 		    (!is_system_labeled() ||
6138 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6139 		    connp)))
6140 			break;
6141 	}
6142 
6143 	if (connp == NULL || connp->conn_upq == NULL) {
6144 		/*
6145 		 * No one bound to these addresses.  Is
6146 		 * there a client that wants all
6147 		 * unclaimed datagrams?
6148 		 */
6149 		mutex_exit(&connfp->connf_lock);
6150 		/*
6151 		 * Check for IPPROTO_ENCAP...
6152 		 */
6153 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6154 			/*
6155 			 * XXX If an IPsec mblk is here on a multicast
6156 			 * tunnel (using ip_mroute stuff), what should
6157 			 * I do?
6158 			 *
6159 			 * For now, just free the IPsec mblk before
6160 			 * passing it up to the multicast routing
6161 			 * stuff.
6162 			 *
6163 			 * BTW,  If I match a configured IP-in-IP
6164 			 * tunnel, ip_mroute_decap will never be
6165 			 * called.
6166 			 */
6167 			if (mp != first_mp)
6168 				freeb(first_mp);
6169 			ip_mroute_decap(q, mp);
6170 		} else {
6171 			/*
6172 			 * Otherwise send an ICMP protocol unreachable.
6173 			 */
6174 			if (ip_fanout_send_icmp(q, first_mp, flags,
6175 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6176 			    mctl_present, zoneid)) {
6177 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
6178 			}
6179 		}
6180 		return;
6181 	}
6182 	CONN_INC_REF(connp);
6183 	first_connp = connp;
6184 
6185 	/*
6186 	 * Only send message to one tunnel driver by immediately
6187 	 * terminating the loop.
6188 	 */
6189 	connp = one_only ? NULL : connp->conn_next;
6190 
6191 	for (;;) {
6192 		while (connp != NULL) {
6193 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6194 			    flags, zoneid) &&
6195 			    (!is_system_labeled() ||
6196 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6197 			    shared_addr, connp)))
6198 				break;
6199 			connp = connp->conn_next;
6200 		}
6201 
6202 		/*
6203 		 * Copy the packet.
6204 		 */
6205 		if (connp == NULL || connp->conn_upq == NULL ||
6206 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6207 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6208 			/*
6209 			 * No more interested clients or memory
6210 			 * allocation failed
6211 			 */
6212 			connp = first_connp;
6213 			break;
6214 		}
6215 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6216 		CONN_INC_REF(connp);
6217 		mutex_exit(&connfp->connf_lock);
6218 		rq = connp->conn_rq;
6219 		if (!canputnext(rq)) {
6220 			if (flags & IP_FF_RAWIP) {
6221 				BUMP_MIB(&ip_mib, rawipInOverflows);
6222 			} else {
6223 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6224 			}
6225 
6226 			freemsg(first_mp1);
6227 		} else {
6228 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6229 				first_mp1 = ipsec_check_inbound_policy
6230 				    (first_mp1, connp, ipha, NULL,
6231 				    mctl_present);
6232 			}
6233 			if (first_mp1 != NULL) {
6234 				/*
6235 				 * ip_fanout_proto also gets called from
6236 				 * icmp_inbound_error_fanout, in which case
6237 				 * the msg type is M_CTL.  Don't add info
6238 				 * in this case for the time being. In future
6239 				 * when there is a need for knowing the
6240 				 * inbound iface index for ICMP error msgs,
6241 				 * then this can be changed.
6242 				 */
6243 				if ((connp->conn_recvif != 0) &&
6244 				    (mp->b_datap->db_type != M_CTL)) {
6245 					/*
6246 					 * the actual data will be
6247 					 * contained in b_cont upon
6248 					 * successful return of the
6249 					 * following call else
6250 					 * original mblk is returned
6251 					 */
6252 					ASSERT(recv_ill != NULL);
6253 					mp1 = ip_add_info(mp1, recv_ill,
6254 						IPF_RECVIF);
6255 				}
6256 				BUMP_MIB(&ip_mib, ipInDelivers);
6257 				if (mctl_present)
6258 					freeb(first_mp1);
6259 				putnext(rq, mp1);
6260 			}
6261 		}
6262 		mutex_enter(&connfp->connf_lock);
6263 		/* Follow the next pointer before releasing the conn. */
6264 		next_connp = connp->conn_next;
6265 		CONN_DEC_REF(connp);
6266 		connp = next_connp;
6267 	}
6268 
6269 	/* Last one.  Send it upstream. */
6270 	mutex_exit(&connfp->connf_lock);
6271 
6272 	/*
6273 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6274 	 * will be set to false.
6275 	 */
6276 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6277 		ill_index = ill->ill_phyint->phyint_ifindex;
6278 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6279 		if (mp == NULL) {
6280 			CONN_DEC_REF(connp);
6281 			if (mctl_present) {
6282 				freeb(first_mp);
6283 			}
6284 			return;
6285 		}
6286 	}
6287 
6288 	rq = connp->conn_rq;
6289 	if (!canputnext(rq)) {
6290 		if (flags & IP_FF_RAWIP) {
6291 			BUMP_MIB(&ip_mib, rawipInOverflows);
6292 		} else {
6293 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6294 		}
6295 
6296 		freemsg(first_mp);
6297 	} else {
6298 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6299 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6300 			    ipha, NULL, mctl_present);
6301 		}
6302 		if (first_mp != NULL) {
6303 			/*
6304 			 * ip_fanout_proto also gets called
6305 			 * from icmp_inbound_error_fanout, in
6306 			 * which case the msg type is M_CTL.
6307 			 * Don't add info in this case for time
6308 			 * being. In future when there is a
6309 			 * need for knowing the inbound iface
6310 			 * index for ICMP error msgs, then this
6311 			 * can be changed
6312 			 */
6313 			if ((connp->conn_recvif != 0) &&
6314 			    (mp->b_datap->db_type != M_CTL)) {
6315 				/*
6316 				 * the actual data will be contained in
6317 				 * b_cont upon successful return
6318 				 * of the following call else original
6319 				 * mblk is returned
6320 				 */
6321 				ASSERT(recv_ill != NULL);
6322 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6323 			}
6324 			BUMP_MIB(&ip_mib, ipInDelivers);
6325 			putnext(rq, mp);
6326 			if (mctl_present)
6327 				freeb(first_mp);
6328 		}
6329 	}
6330 	CONN_DEC_REF(connp);
6331 }
6332 
6333 /*
6334  * Fanout for TCP packets
6335  * The caller puts <fport, lport> in the ports parameter.
6336  *
6337  * IPQoS Notes
6338  * Before sending it to the client, invoke IPPF processing.
6339  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6340  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6341  * ip_policy is false.
6342  */
6343 static void
6344 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6345     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6346 {
6347 	mblk_t  *first_mp;
6348 	boolean_t secure;
6349 	uint32_t ill_index;
6350 	int	ip_hdr_len;
6351 	tcph_t	*tcph;
6352 	boolean_t syn_present = B_FALSE;
6353 	conn_t	*connp;
6354 
6355 	first_mp = mp;
6356 	if (mctl_present) {
6357 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6358 		mp = first_mp->b_cont;
6359 		secure = ipsec_in_is_secure(first_mp);
6360 		ASSERT(mp != NULL);
6361 	} else {
6362 		secure = B_FALSE;
6363 	}
6364 
6365 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6366 
6367 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6368 	    NULL) {
6369 		/*
6370 		 * No connected connection or listener. Send a
6371 		 * TH_RST via tcp_xmit_listeners_reset.
6372 		 */
6373 
6374 		/* Initiate IPPf processing, if needed. */
6375 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6376 			uint32_t ill_index;
6377 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6378 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6379 			if (first_mp == NULL)
6380 				return;
6381 		}
6382 		BUMP_MIB(&ip_mib, ipInDelivers);
6383 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6384 		    zoneid));
6385 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
6386 		return;
6387 	}
6388 
6389 	/*
6390 	 * Allocate the SYN for the TCP connection here itself
6391 	 */
6392 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6393 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6394 		if (IPCL_IS_TCP(connp)) {
6395 			squeue_t *sqp;
6396 
6397 			/*
6398 			 * For fused tcp loopback, assign the eager's
6399 			 * squeue to be that of the active connect's.
6400 			 * Note that we don't check for IP_FF_LOOPBACK
6401 			 * here since this routine gets called only
6402 			 * for loopback (unlike the IPv6 counterpart).
6403 			 */
6404 			ASSERT(Q_TO_CONN(q) != NULL);
6405 			if (do_tcp_fusion &&
6406 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6407 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6408 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6409 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6410 				sqp = Q_TO_CONN(q)->conn_sqp;
6411 			} else {
6412 				sqp = IP_SQUEUE_GET(lbolt);
6413 			}
6414 
6415 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6416 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6417 			syn_present = B_TRUE;
6418 		}
6419 	}
6420 
6421 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6422 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6423 		if ((flags & TH_RST) || (flags & TH_URG)) {
6424 			CONN_DEC_REF(connp);
6425 			freemsg(first_mp);
6426 			return;
6427 		}
6428 		if (flags & TH_ACK) {
6429 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
6430 			CONN_DEC_REF(connp);
6431 			return;
6432 		}
6433 
6434 		CONN_DEC_REF(connp);
6435 		freemsg(first_mp);
6436 		return;
6437 	}
6438 
6439 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6440 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6441 		    NULL, mctl_present);
6442 		if (first_mp == NULL) {
6443 			CONN_DEC_REF(connp);
6444 			return;
6445 		}
6446 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6447 			ASSERT(syn_present);
6448 			if (mctl_present) {
6449 				ASSERT(first_mp != mp);
6450 				first_mp->b_datap->db_struioflag |=
6451 				    STRUIO_POLICY;
6452 			} else {
6453 				ASSERT(first_mp == mp);
6454 				mp->b_datap->db_struioflag &=
6455 				    ~STRUIO_EAGER;
6456 				mp->b_datap->db_struioflag |=
6457 				    STRUIO_POLICY;
6458 			}
6459 		} else {
6460 			/*
6461 			 * Discard first_mp early since we're dealing with a
6462 			 * fully-connected conn_t and tcp doesn't do policy in
6463 			 * this case.
6464 			 */
6465 			if (mctl_present) {
6466 				freeb(first_mp);
6467 				mctl_present = B_FALSE;
6468 			}
6469 			first_mp = mp;
6470 		}
6471 	}
6472 
6473 	/*
6474 	 * Initiate policy processing here if needed. If we get here from
6475 	 * icmp_inbound_error_fanout, ip_policy is false.
6476 	 */
6477 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6478 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6479 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6480 		if (mp == NULL) {
6481 			CONN_DEC_REF(connp);
6482 			if (mctl_present)
6483 				freeb(first_mp);
6484 			return;
6485 		} else if (mctl_present) {
6486 			ASSERT(first_mp != mp);
6487 			first_mp->b_cont = mp;
6488 		} else {
6489 			first_mp = mp;
6490 		}
6491 	}
6492 
6493 
6494 
6495 	/* Handle IPv6 socket options. */
6496 	if (!syn_present &&
6497 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6498 		/* Add header */
6499 		ASSERT(recv_ill != NULL);
6500 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6501 		if (mp == NULL) {
6502 			CONN_DEC_REF(connp);
6503 			if (mctl_present)
6504 				freeb(first_mp);
6505 			return;
6506 		} else if (mctl_present) {
6507 			/*
6508 			 * ip_add_info might return a new mp.
6509 			 */
6510 			ASSERT(first_mp != mp);
6511 			first_mp->b_cont = mp;
6512 		} else {
6513 			first_mp = mp;
6514 		}
6515 	}
6516 
6517 	BUMP_MIB(&ip_mib, ipInDelivers);
6518 	if (IPCL_IS_TCP(connp)) {
6519 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6520 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6521 	} else {
6522 		putnext(connp->conn_rq, first_mp);
6523 		CONN_DEC_REF(connp);
6524 	}
6525 }
6526 
6527 /*
6528  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6529  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6530  * Caller is responsible for dropping references to the conn, and freeing
6531  * first_mp.
6532  *
6533  * IPQoS Notes
6534  * Before sending it to the client, invoke IPPF processing. Policy processing
6535  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6536  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6537  * ip_wput_local, ip_policy is false.
6538  */
6539 static void
6540 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6541     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6542     boolean_t ip_policy)
6543 {
6544 	boolean_t	mctl_present = (first_mp != NULL);
6545 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6546 	uint32_t	ill_index;
6547 
6548 	if (mctl_present)
6549 		first_mp->b_cont = mp;
6550 	else
6551 		first_mp = mp;
6552 
6553 	if (CONN_UDP_FLOWCTLD(connp)) {
6554 		BUMP_MIB(&ip_mib, udpInOverflows);
6555 		freemsg(first_mp);
6556 		return;
6557 	}
6558 
6559 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6560 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6561 		    NULL, mctl_present);
6562 		if (first_mp == NULL)
6563 			return;	/* Freed by ipsec_check_inbound_policy(). */
6564 	}
6565 	if (mctl_present)
6566 		freeb(first_mp);
6567 
6568 	if (connp->conn_recvif)
6569 		in_flags = IPF_RECVIF;
6570 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6571 		in_flags |= IPF_RECVSLLA;
6572 
6573 	/* Handle IPv6 options. */
6574 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6575 		in_flags |= IPF_RECVIF;
6576 
6577 	/*
6578 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6579 	 * freed if the packet is dropped. The caller will do so.
6580 	 */
6581 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6582 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6583 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6584 		if (mp == NULL) {
6585 			return;
6586 		}
6587 	}
6588 	if ((in_flags != 0) &&
6589 	    (mp->b_datap->db_type != M_CTL)) {
6590 		/*
6591 		 * The actual data will be contained in b_cont
6592 		 * upon successful return of the following call
6593 		 * else original mblk is returned
6594 		 */
6595 		ASSERT(recv_ill != NULL);
6596 		mp = ip_add_info(mp, recv_ill, in_flags);
6597 	}
6598 	BUMP_MIB(&ip_mib, ipInDelivers);
6599 
6600 	/* Send it upstream */
6601 	CONN_UDP_RECV(connp, mp);
6602 }
6603 
6604 /*
6605  * Fanout for UDP packets.
6606  * The caller puts <fport, lport> in the ports parameter.
6607  *
6608  * If SO_REUSEADDR is set all multicast and broadcast packets
6609  * will be delivered to all streams bound to the same port.
6610  *
6611  * Zones notes:
6612  * Multicast and broadcast packets will be distributed to streams in all zones.
6613  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6614  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6615  * packets. To maintain this behavior with multiple zones, the conns are grouped
6616  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6617  * each zone. If unset, all the following conns in the same zone are skipped.
6618  */
6619 static void
6620 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6621     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6622     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6623 {
6624 	uint32_t	dstport, srcport;
6625 	ipaddr_t	dst;
6626 	mblk_t		*first_mp;
6627 	boolean_t	secure;
6628 	in6_addr_t	v6src;
6629 	conn_t		*connp;
6630 	connf_t		*connfp;
6631 	conn_t		*first_connp;
6632 	conn_t		*next_connp;
6633 	mblk_t		*mp1, *first_mp1;
6634 	ipaddr_t	src;
6635 	zoneid_t	last_zoneid;
6636 	boolean_t	reuseaddr;
6637 	boolean_t	shared_addr;
6638 
6639 	first_mp = mp;
6640 	if (mctl_present) {
6641 		mp = first_mp->b_cont;
6642 		first_mp->b_cont = NULL;
6643 		secure = ipsec_in_is_secure(first_mp);
6644 		ASSERT(mp != NULL);
6645 	} else {
6646 		first_mp = NULL;
6647 		secure = B_FALSE;
6648 	}
6649 
6650 	/* Extract ports in net byte order */
6651 	dstport = htons(ntohl(ports) & 0xFFFF);
6652 	srcport = htons(ntohl(ports) >> 16);
6653 	dst = ipha->ipha_dst;
6654 	src = ipha->ipha_src;
6655 
6656 	shared_addr = (zoneid == ALL_ZONES);
6657 	if (shared_addr) {
6658 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6659 		if (zoneid == ALL_ZONES)
6660 			zoneid = tsol_packet_to_zoneid(mp);
6661 	}
6662 
6663 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6664 	mutex_enter(&connfp->connf_lock);
6665 	connp = connfp->connf_head;
6666 	if (!broadcast && !CLASSD(dst)) {
6667 		/*
6668 		 * Not broadcast or multicast. Send to the one (first)
6669 		 * client we find. No need to check conn_wantpacket()
6670 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6671 		 * IPv4 unicast packets.
6672 		 */
6673 		while ((connp != NULL) &&
6674 		    (!IPCL_UDP_MATCH(connp, dstport, dst,
6675 		    srcport, src) ||
6676 		    (connp->conn_zoneid != zoneid && !connp->conn_allzones))) {
6677 			connp = connp->conn_next;
6678 		}
6679 
6680 		if (connp == NULL || connp->conn_upq == NULL)
6681 			goto notfound;
6682 
6683 		if (is_system_labeled() &&
6684 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6685 		    connp))
6686 			goto notfound;
6687 
6688 		CONN_INC_REF(connp);
6689 		mutex_exit(&connfp->connf_lock);
6690 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6691 		    recv_ill, ip_policy);
6692 		IP_STAT(ip_udp_fannorm);
6693 		CONN_DEC_REF(connp);
6694 		return;
6695 	}
6696 
6697 	/*
6698 	 * Broadcast and multicast case
6699 	 *
6700 	 * Need to check conn_wantpacket().
6701 	 * If SO_REUSEADDR has been set on the first we send the
6702 	 * packet to all clients that have joined the group and
6703 	 * match the port.
6704 	 */
6705 
6706 	while (connp != NULL) {
6707 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6708 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6709 		    (!is_system_labeled() ||
6710 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6711 		    connp)))
6712 			break;
6713 		connp = connp->conn_next;
6714 	}
6715 
6716 	if (connp == NULL || connp->conn_upq == NULL)
6717 		goto notfound;
6718 
6719 	first_connp = connp;
6720 	/*
6721 	 * When SO_REUSEADDR is not set, send the packet only to the first
6722 	 * matching connection in its zone by keeping track of the zoneid.
6723 	 */
6724 	reuseaddr = first_connp->conn_reuseaddr;
6725 	last_zoneid = first_connp->conn_zoneid;
6726 
6727 	CONN_INC_REF(connp);
6728 	connp = connp->conn_next;
6729 	for (;;) {
6730 		while (connp != NULL) {
6731 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6732 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6733 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6734 			    (!is_system_labeled() ||
6735 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6736 			    shared_addr, connp)))
6737 				break;
6738 			connp = connp->conn_next;
6739 		}
6740 		/*
6741 		 * Just copy the data part alone. The mctl part is
6742 		 * needed just for verifying policy and it is never
6743 		 * sent up.
6744 		 */
6745 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6746 		    ((mp1 = copymsg(mp)) == NULL))) {
6747 			/*
6748 			 * No more interested clients or memory
6749 			 * allocation failed
6750 			 */
6751 			connp = first_connp;
6752 			break;
6753 		}
6754 		if (connp->conn_zoneid != last_zoneid) {
6755 			/*
6756 			 * Update the zoneid so that the packet isn't sent to
6757 			 * any more conns in the same zone unless SO_REUSEADDR
6758 			 * is set.
6759 			 */
6760 			reuseaddr = connp->conn_reuseaddr;
6761 			last_zoneid = connp->conn_zoneid;
6762 		}
6763 		if (first_mp != NULL) {
6764 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6765 			    ipsec_info_type == IPSEC_IN);
6766 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6767 			if (first_mp1 == NULL) {
6768 				freemsg(mp1);
6769 				connp = first_connp;
6770 				break;
6771 			}
6772 		} else {
6773 			first_mp1 = NULL;
6774 		}
6775 		CONN_INC_REF(connp);
6776 		mutex_exit(&connfp->connf_lock);
6777 		/*
6778 		 * IPQoS notes: We don't send the packet for policy
6779 		 * processing here, will do it for the last one (below).
6780 		 * i.e. we do it per-packet now, but if we do policy
6781 		 * processing per-conn, then we would need to do it
6782 		 * here too.
6783 		 */
6784 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6785 		    ipha, flags, recv_ill, B_FALSE);
6786 		mutex_enter(&connfp->connf_lock);
6787 		/* Follow the next pointer before releasing the conn. */
6788 		next_connp = connp->conn_next;
6789 		IP_STAT(ip_udp_fanmb);
6790 		CONN_DEC_REF(connp);
6791 		connp = next_connp;
6792 	}
6793 
6794 	/* Last one.  Send it upstream. */
6795 	mutex_exit(&connfp->connf_lock);
6796 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6797 	    ip_policy);
6798 	IP_STAT(ip_udp_fanmb);
6799 	CONN_DEC_REF(connp);
6800 	return;
6801 
6802 notfound:
6803 
6804 	mutex_exit(&connfp->connf_lock);
6805 	IP_STAT(ip_udp_fanothers);
6806 	/*
6807 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6808 	 * have already been matched above, since they live in the IPv4
6809 	 * fanout tables. This implies we only need to
6810 	 * check for IPv6 in6addr_any endpoints here.
6811 	 * Thus we compare using ipv6_all_zeros instead of the destination
6812 	 * address, except for the multicast group membership lookup which
6813 	 * uses the IPv4 destination.
6814 	 */
6815 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6816 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6817 	mutex_enter(&connfp->connf_lock);
6818 	connp = connfp->connf_head;
6819 	if (!broadcast && !CLASSD(dst)) {
6820 		while (connp != NULL) {
6821 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6822 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6823 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6824 			    !connp->conn_ipv6_v6only)
6825 				break;
6826 			connp = connp->conn_next;
6827 		}
6828 
6829 		if (connp != NULL && is_system_labeled() &&
6830 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6831 		    connp))
6832 			connp = NULL;
6833 
6834 		if (connp == NULL || connp->conn_upq == NULL) {
6835 			/*
6836 			 * No one bound to this port.  Is
6837 			 * there a client that wants all
6838 			 * unclaimed datagrams?
6839 			 */
6840 			mutex_exit(&connfp->connf_lock);
6841 
6842 			if (mctl_present)
6843 				first_mp->b_cont = mp;
6844 			else
6845 				first_mp = mp;
6846 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6847 				ip_fanout_proto(q, first_mp, ill, ipha,
6848 				    flags | IP_FF_RAWIP, mctl_present,
6849 				    ip_policy, recv_ill, zoneid);
6850 			} else {
6851 				if (ip_fanout_send_icmp(q, first_mp, flags,
6852 				    ICMP_DEST_UNREACHABLE,
6853 				    ICMP_PORT_UNREACHABLE,
6854 				    mctl_present, zoneid)) {
6855 					BUMP_MIB(&ip_mib, udpNoPorts);
6856 				}
6857 			}
6858 			return;
6859 		}
6860 
6861 		CONN_INC_REF(connp);
6862 		mutex_exit(&connfp->connf_lock);
6863 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6864 		    recv_ill, ip_policy);
6865 		CONN_DEC_REF(connp);
6866 		return;
6867 	}
6868 	/*
6869 	 * IPv4 multicast packet being delivered to an AF_INET6
6870 	 * in6addr_any endpoint.
6871 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6872 	 * and not conn_wantpacket_v6() since any multicast membership is
6873 	 * for an IPv4-mapped multicast address.
6874 	 * The packet is sent to all clients in all zones that have joined the
6875 	 * group and match the port.
6876 	 */
6877 	while (connp != NULL) {
6878 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6879 		    srcport, v6src) &&
6880 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6881 		    (!is_system_labeled() ||
6882 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6883 		    connp)))
6884 			break;
6885 		connp = connp->conn_next;
6886 	}
6887 
6888 	if (connp == NULL || connp->conn_upq == NULL) {
6889 		/*
6890 		 * No one bound to this port.  Is
6891 		 * there a client that wants all
6892 		 * unclaimed datagrams?
6893 		 */
6894 		mutex_exit(&connfp->connf_lock);
6895 
6896 		if (mctl_present)
6897 			first_mp->b_cont = mp;
6898 		else
6899 			first_mp = mp;
6900 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6901 			ip_fanout_proto(q, first_mp, ill, ipha,
6902 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6903 			    recv_ill, zoneid);
6904 		} else {
6905 			/*
6906 			 * We used to attempt to send an icmp error here, but
6907 			 * since this is known to be a multicast packet
6908 			 * and we don't send icmp errors in response to
6909 			 * multicast, just drop the packet and give up sooner.
6910 			 */
6911 			BUMP_MIB(&ip_mib, udpNoPorts);
6912 			freemsg(first_mp);
6913 		}
6914 		return;
6915 	}
6916 
6917 	first_connp = connp;
6918 
6919 	CONN_INC_REF(connp);
6920 	connp = connp->conn_next;
6921 	for (;;) {
6922 		while (connp != NULL) {
6923 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6924 			    ipv6_all_zeros, srcport, v6src) &&
6925 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6926 			    (!is_system_labeled() ||
6927 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6928 			    shared_addr, connp)))
6929 				break;
6930 			connp = connp->conn_next;
6931 		}
6932 		/*
6933 		 * Just copy the data part alone. The mctl part is
6934 		 * needed just for verifying policy and it is never
6935 		 * sent up.
6936 		 */
6937 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6938 		    ((mp1 = copymsg(mp)) == NULL))) {
6939 			/*
6940 			 * No more intested clients or memory
6941 			 * allocation failed
6942 			 */
6943 			connp = first_connp;
6944 			break;
6945 		}
6946 		if (first_mp != NULL) {
6947 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6948 			    ipsec_info_type == IPSEC_IN);
6949 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6950 			if (first_mp1 == NULL) {
6951 				freemsg(mp1);
6952 				connp = first_connp;
6953 				break;
6954 			}
6955 		} else {
6956 			first_mp1 = NULL;
6957 		}
6958 		CONN_INC_REF(connp);
6959 		mutex_exit(&connfp->connf_lock);
6960 		/*
6961 		 * IPQoS notes: We don't send the packet for policy
6962 		 * processing here, will do it for the last one (below).
6963 		 * i.e. we do it per-packet now, but if we do policy
6964 		 * processing per-conn, then we would need to do it
6965 		 * here too.
6966 		 */
6967 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6968 		    ipha, flags, recv_ill, B_FALSE);
6969 		mutex_enter(&connfp->connf_lock);
6970 		/* Follow the next pointer before releasing the conn. */
6971 		next_connp = connp->conn_next;
6972 		CONN_DEC_REF(connp);
6973 		connp = next_connp;
6974 	}
6975 
6976 	/* Last one.  Send it upstream. */
6977 	mutex_exit(&connfp->connf_lock);
6978 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6979 	    ip_policy);
6980 	CONN_DEC_REF(connp);
6981 }
6982 
6983 /*
6984  * Complete the ip_wput header so that it
6985  * is possible to generate ICMP
6986  * errors.
6987  */
6988 int
6989 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
6990 {
6991 	ire_t *ire;
6992 
6993 	if (ipha->ipha_src == INADDR_ANY) {
6994 		ire = ire_lookup_local(zoneid);
6995 		if (ire == NULL) {
6996 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
6997 			return (1);
6998 		}
6999 		ipha->ipha_src = ire->ire_addr;
7000 		ire_refrele(ire);
7001 	}
7002 	ipha->ipha_ttl = ip_def_ttl;
7003 	ipha->ipha_hdr_checksum = 0;
7004 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7005 	return (0);
7006 }
7007 
7008 /*
7009  * Nobody should be sending
7010  * packets up this stream
7011  */
7012 static void
7013 ip_lrput(queue_t *q, mblk_t *mp)
7014 {
7015 	mblk_t *mp1;
7016 
7017 	switch (mp->b_datap->db_type) {
7018 	case M_FLUSH:
7019 		/* Turn around */
7020 		if (*mp->b_rptr & FLUSHW) {
7021 			*mp->b_rptr &= ~FLUSHR;
7022 			qreply(q, mp);
7023 			return;
7024 		}
7025 		break;
7026 	}
7027 	/* Could receive messages that passed through ar_rput */
7028 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7029 		mp1->b_prev = mp1->b_next = NULL;
7030 	freemsg(mp);
7031 }
7032 
7033 /* Nobody should be sending packets down this stream */
7034 /* ARGSUSED */
7035 void
7036 ip_lwput(queue_t *q, mblk_t *mp)
7037 {
7038 	freemsg(mp);
7039 }
7040 
7041 /*
7042  * Move the first hop in any source route to ipha_dst and remove that part of
7043  * the source route.  Called by other protocols.  Errors in option formatting
7044  * are ignored - will be handled by ip_wput_options Return the final
7045  * destination (either ipha_dst or the last entry in a source route.)
7046  */
7047 ipaddr_t
7048 ip_massage_options(ipha_t *ipha)
7049 {
7050 	ipoptp_t	opts;
7051 	uchar_t		*opt;
7052 	uint8_t		optval;
7053 	uint8_t		optlen;
7054 	ipaddr_t	dst;
7055 	int		i;
7056 	ire_t		*ire;
7057 
7058 	ip2dbg(("ip_massage_options\n"));
7059 	dst = ipha->ipha_dst;
7060 	for (optval = ipoptp_first(&opts, ipha);
7061 	    optval != IPOPT_EOL;
7062 	    optval = ipoptp_next(&opts)) {
7063 		opt = opts.ipoptp_cur;
7064 		switch (optval) {
7065 			uint8_t off;
7066 		case IPOPT_SSRR:
7067 		case IPOPT_LSRR:
7068 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7069 				ip1dbg(("ip_massage_options: bad src route\n"));
7070 				break;
7071 			}
7072 			optlen = opts.ipoptp_len;
7073 			off = opt[IPOPT_OFFSET];
7074 			off--;
7075 		redo_srr:
7076 			if (optlen < IP_ADDR_LEN ||
7077 			    off > optlen - IP_ADDR_LEN) {
7078 				/* End of source route */
7079 				ip1dbg(("ip_massage_options: end of SR\n"));
7080 				break;
7081 			}
7082 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7083 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7084 			    ntohl(dst)));
7085 			/*
7086 			 * Check if our address is present more than
7087 			 * once as consecutive hops in source route.
7088 			 * XXX verify per-interface ip_forwarding
7089 			 * for source route?
7090 			 */
7091 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7092 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
7093 			if (ire != NULL) {
7094 				ire_refrele(ire);
7095 				off += IP_ADDR_LEN;
7096 				goto redo_srr;
7097 			}
7098 			if (dst == htonl(INADDR_LOOPBACK)) {
7099 				ip1dbg(("ip_massage_options: loopback addr in "
7100 				    "source route!\n"));
7101 				break;
7102 			}
7103 			/*
7104 			 * Update ipha_dst to be the first hop and remove the
7105 			 * first hop from the source route (by overwriting
7106 			 * part of the option with NOP options).
7107 			 */
7108 			ipha->ipha_dst = dst;
7109 			/* Put the last entry in dst */
7110 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7111 			    3;
7112 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7113 
7114 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7115 			    ntohl(dst)));
7116 			/* Move down and overwrite */
7117 			opt[IP_ADDR_LEN] = opt[0];
7118 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7119 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7120 			for (i = 0; i < IP_ADDR_LEN; i++)
7121 				opt[i] = IPOPT_NOP;
7122 			break;
7123 		}
7124 	}
7125 	return (dst);
7126 }
7127 
7128 /*
7129  * This function's job is to forward data to the reverse tunnel (FA->HA)
7130  * after doing a few checks. It is assumed that the incoming interface
7131  * of the packet is always different than the outgoing interface and the
7132  * ire_type of the found ire has to be a non-resolver type.
7133  *
7134  * IPQoS notes
7135  * IP policy is invoked twice for a forwarded packet, once on the read side
7136  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7137  * enabled.
7138  */
7139 static void
7140 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7141 {
7142 	ipha_t		*ipha;
7143 	queue_t		*q;
7144 	uint32_t 	pkt_len;
7145 #define	rptr    ((uchar_t *)ipha)
7146 	uint32_t 	sum;
7147 	uint32_t 	max_frag;
7148 	mblk_t		*first_mp;
7149 	uint32_t	ill_index;
7150 	ipxmit_state_t	pktxmit_state;
7151 
7152 	ASSERT(ire != NULL);
7153 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7154 	ASSERT(ire->ire_stq != NULL);
7155 
7156 	/* Initiate read side IPPF processing */
7157 	if (IPP_ENABLED(IPP_FWD_IN)) {
7158 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7159 		ip_process(IPP_FWD_IN, &mp, ill_index);
7160 		if (mp == NULL) {
7161 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7162 			    "dropped during IPPF processing\n"));
7163 			return;
7164 		}
7165 	}
7166 
7167 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7168 		ILLF_ROUTER) == 0) ||
7169 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7170 		BUMP_MIB(&ip_mib, ipForwProhibits);
7171 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7172 		    "forwarding is not turned on\n"));
7173 		goto drop_pkt;
7174 	}
7175 
7176 	/*
7177 	 * Don't forward if the interface is down
7178 	 */
7179 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7180 		BUMP_MIB(&ip_mib, ipInDiscards);
7181 		goto drop_pkt;
7182 	}
7183 
7184 	ipha = (ipha_t *)mp->b_rptr;
7185 	pkt_len = ntohs(ipha->ipha_length);
7186 	/* Adjust the checksum to reflect the ttl decrement. */
7187 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7188 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7189 	if (ipha->ipha_ttl-- <= 1) {
7190 		if (ip_csum_hdr(ipha)) {
7191 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7192 			goto drop_pkt;
7193 		}
7194 		q = ire->ire_stq;
7195 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7196 		    BPRI_HI)) == NULL) {
7197 			goto drop_pkt;
7198 		}
7199 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7200 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED);
7201 
7202 		return;
7203 	}
7204 
7205 	/* Get the ill_index of the ILL */
7206 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7207 
7208 	/*
7209 	 * ip_mrtun_forward is only used by foreign agent to reverse
7210 	 * tunnel the incoming packet. So it does not do any option
7211 	 * processing for source routing.
7212 	 */
7213 	max_frag = ire->ire_max_frag;
7214 	if (pkt_len > max_frag) {
7215 		/*
7216 		 * It needs fragging on its way out.  We haven't
7217 		 * verified the header checksum yet.  Since we
7218 		 * are going to put a surely good checksum in the
7219 		 * outgoing header, we have to make sure that it
7220 		 * was good coming in.
7221 		 */
7222 		if (ip_csum_hdr(ipha)) {
7223 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7224 			goto drop_pkt;
7225 		}
7226 
7227 		/* Initiate write side IPPF processing */
7228 		if (IPP_ENABLED(IPP_FWD_OUT)) {
7229 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7230 			if (mp == NULL) {
7231 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7232 				    "dropped/deferred during ip policy "\
7233 				    "processing\n"));
7234 				return;
7235 			}
7236 		}
7237 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7238 		    BPRI_HI)) == NULL) {
7239 			goto drop_pkt;
7240 		}
7241 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7242 		mp = first_mp;
7243 
7244 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
7245 		return;
7246 	}
7247 
7248 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7249 
7250 	ASSERT(ire->ire_ipif != NULL);
7251 
7252 	/* Now send the packet to the tunnel interface */
7253 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7254 	q = ire->ire_stq;
7255 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7256 	if ((pktxmit_state == SEND_FAILED) ||
7257 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7258 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7259 		    q->q_ptr));
7260 	}
7261 
7262 	return;
7263 
7264 drop_pkt:;
7265 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7266 	freemsg(mp);
7267 #undef	rptr
7268 }
7269 
7270 /*
7271  * Fills the ipsec_out_t data structure with appropriate fields and
7272  * prepends it to mp which contains the IP hdr + data that was meant
7273  * to be forwarded. Please note that ipsec_out_info data structure
7274  * is used here to communicate the outgoing ill path at ip_wput()
7275  * for the ICMP error packet. This has nothing to do with ipsec IP
7276  * security. ipsec_out_t is really used to pass the info to the module
7277  * IP where this information cannot be extracted from conn.
7278  * This functions is called by ip_mrtun_forward().
7279  */
7280 void
7281 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7282 {
7283 	ipsec_out_t	*io;
7284 
7285 	ASSERT(xmit_ill != NULL);
7286 	first_mp->b_datap->db_type = M_CTL;
7287 	first_mp->b_wptr += sizeof (ipsec_info_t);
7288 	/*
7289 	 * This is to pass info to ip_wput in absence of conn.
7290 	 * ipsec_out_secure will be B_FALSE because of this.
7291 	 * Thus ipsec_out_secure being B_FALSE indicates that
7292 	 * this is not IPSEC security related information.
7293 	 */
7294 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7295 	io = (ipsec_out_t *)first_mp->b_rptr;
7296 	io->ipsec_out_type = IPSEC_OUT;
7297 	io->ipsec_out_len = sizeof (ipsec_out_t);
7298 	first_mp->b_cont = mp;
7299 	io->ipsec_out_ill_index =
7300 	    xmit_ill->ill_phyint->phyint_ifindex;
7301 	io->ipsec_out_xmit_if = B_TRUE;
7302 }
7303 
7304 /*
7305  * Return the network mask
7306  * associated with the specified address.
7307  */
7308 ipaddr_t
7309 ip_net_mask(ipaddr_t addr)
7310 {
7311 	uchar_t	*up = (uchar_t *)&addr;
7312 	ipaddr_t mask = 0;
7313 	uchar_t	*maskp = (uchar_t *)&mask;
7314 
7315 #if defined(__i386) || defined(__amd64)
7316 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7317 #endif
7318 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7319 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7320 #endif
7321 	if (CLASSD(addr)) {
7322 		maskp[0] = 0xF0;
7323 		return (mask);
7324 	}
7325 	if (addr == 0)
7326 		return (0);
7327 	maskp[0] = 0xFF;
7328 	if ((up[0] & 0x80) == 0)
7329 		return (mask);
7330 
7331 	maskp[1] = 0xFF;
7332 	if ((up[0] & 0xC0) == 0x80)
7333 		return (mask);
7334 
7335 	maskp[2] = 0xFF;
7336 	if ((up[0] & 0xE0) == 0xC0)
7337 		return (mask);
7338 
7339 	/* Must be experimental or multicast, indicate as much */
7340 	return ((ipaddr_t)0);
7341 }
7342 
7343 /*
7344  * Select an ill for the packet by considering load spreading across
7345  * a different ill in the group if dst_ill is part of some group.
7346  */
7347 ill_t *
7348 ip_newroute_get_dst_ill(ill_t *dst_ill)
7349 {
7350 	ill_t *ill;
7351 
7352 	/*
7353 	 * We schedule irrespective of whether the source address is
7354 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7355 	 */
7356 	ill = illgrp_scheduler(dst_ill);
7357 	if (ill == NULL)
7358 		return (NULL);
7359 
7360 	/*
7361 	 * For groups with names ip_sioctl_groupname ensures that all
7362 	 * ills are of same type. For groups without names, ifgrp_insert
7363 	 * ensures this.
7364 	 */
7365 	ASSERT(dst_ill->ill_type == ill->ill_type);
7366 
7367 	return (ill);
7368 }
7369 
7370 /*
7371  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7372  */
7373 ill_t *
7374 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7375 {
7376 	ill_t *ret_ill;
7377 
7378 	ASSERT(ifindex != 0);
7379 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7380 	if (ret_ill == NULL ||
7381 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7382 		if (isv6) {
7383 			if (ill != NULL) {
7384 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7385 			} else {
7386 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7387 			}
7388 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7389 			    "bad ifindex %d.\n", ifindex));
7390 		} else {
7391 			BUMP_MIB(&ip_mib, ipOutDiscards);
7392 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7393 			    "bad ifindex %d.\n", ifindex));
7394 		}
7395 		if (ret_ill != NULL)
7396 			ill_refrele(ret_ill);
7397 		freemsg(first_mp);
7398 		return (NULL);
7399 	}
7400 
7401 	return (ret_ill);
7402 }
7403 
7404 /*
7405  * IPv4 -
7406  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7407  * out a packet to a destination address for which we do not have specific
7408  * (or sufficient) routing information.
7409  *
7410  * NOTE : These are the scopes of some of the variables that point at IRE,
7411  *	  which needs to be followed while making any future modifications
7412  *	  to avoid memory leaks.
7413  *
7414  *	- ire and sire are the entries looked up initially by
7415  *	  ire_ftable_lookup.
7416  *	- ipif_ire is used to hold the interface ire associated with
7417  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7418  *	  it before branching out to error paths.
7419  *	- save_ire is initialized before ire_create, so that ire returned
7420  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7421  *	  before breaking out of the switch.
7422  *
7423  *	Thus on failures, we have to REFRELE only ire and sire, if they
7424  *	are not NULL.
7425  */
7426 void
7427 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp)
7428 {
7429 	areq_t	*areq;
7430 	ipaddr_t gw = 0;
7431 	ire_t	*ire = NULL;
7432 	mblk_t	*res_mp;
7433 	ipaddr_t *addrp;
7434 	ipaddr_t nexthop_addr;
7435 	ipif_t  *src_ipif = NULL;
7436 	ill_t	*dst_ill = NULL;
7437 	ipha_t  *ipha;
7438 	ire_t	*sire = NULL;
7439 	mblk_t	*first_mp;
7440 	ire_t	*save_ire;
7441 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7442 	ushort_t ire_marks = 0;
7443 	boolean_t mctl_present;
7444 	ipsec_out_t *io;
7445 	mblk_t	*saved_mp;
7446 	ire_t	*first_sire = NULL;
7447 	mblk_t	*copy_mp = NULL;
7448 	mblk_t	*xmit_mp = NULL;
7449 	ipaddr_t save_dst;
7450 	uint32_t multirt_flags =
7451 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7452 	boolean_t multirt_is_resolvable;
7453 	boolean_t multirt_resolve_next;
7454 	boolean_t do_attach_ill = B_FALSE;
7455 	boolean_t ip_nexthop = B_FALSE;
7456 	zoneid_t zoneid;
7457 	tsol_ire_gw_secattr_t *attrp = NULL;
7458 	tsol_gcgrp_t *gcgrp = NULL;
7459 	tsol_gcgrp_addr_t ga;
7460 
7461 	if (ip_debug > 2) {
7462 		/* ip1dbg */
7463 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7464 	}
7465 
7466 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7467 	if (mctl_present) {
7468 		io = (ipsec_out_t *)first_mp->b_rptr;
7469 		zoneid = io->ipsec_out_zoneid;
7470 		ASSERT(zoneid != ALL_ZONES);
7471 	} else if (connp != NULL) {
7472 		zoneid = connp->conn_zoneid;
7473 	} else {
7474 		zoneid = GLOBAL_ZONEID;
7475 	}
7476 
7477 	ipha = (ipha_t *)mp->b_rptr;
7478 
7479 	/* All multicast lookups come through ip_newroute_ipif() */
7480 	if (CLASSD(dst)) {
7481 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7482 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7483 		freemsg(first_mp);
7484 		return;
7485 	}
7486 
7487 	if (mctl_present && io->ipsec_out_attach_if) {
7488 		/* ip_grab_attach_ill returns a held ill */
7489 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7490 		    io->ipsec_out_ill_index, B_FALSE);
7491 
7492 		/* Failure case frees things for us. */
7493 		if (attach_ill == NULL)
7494 			return;
7495 
7496 		/*
7497 		 * Check if we need an ire that will not be
7498 		 * looked up by anybody else i.e. HIDDEN.
7499 		 */
7500 		if (ill_is_probeonly(attach_ill))
7501 			ire_marks = IRE_MARK_HIDDEN;
7502 	}
7503 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7504 		ip_nexthop = B_TRUE;
7505 		nexthop_addr = io->ipsec_out_nexthop_addr;
7506 	}
7507 	/*
7508 	 * If this IRE is created for forwarding or it is not for
7509 	 * traffic for congestion controlled protocols, mark it as temporary.
7510 	 */
7511 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7512 		ire_marks |= IRE_MARK_TEMPORARY;
7513 
7514 	/*
7515 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7516 	 * chain until it gets the most specific information available.
7517 	 * For example, we know that there is no IRE_CACHE for this dest,
7518 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7519 	 * ire_ftable_lookup will look up the gateway, etc.
7520 	 * Check if in_ill != NULL. If it is true, the packet must be
7521 	 * from an incoming interface where RTA_SRCIFP is set.
7522 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7523 	 * to the destination, of equal netmask length in the forward table,
7524 	 * will be recursively explored. If no information is available
7525 	 * for the final gateway of that route, we force the returned ire
7526 	 * to be equal to sire using MATCH_IRE_PARENT.
7527 	 * At least, in this case we have a starting point (in the buckets)
7528 	 * to look for other routes to the destination in the forward table.
7529 	 * This is actually used only for multirouting, where a list
7530 	 * of routes has to be processed in sequence.
7531 	 *
7532 	 * In the process of coming up with the most specific information,
7533 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7534 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7535 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7536 	 * Two caveats when handling incomplete ire's in ip_newroute:
7537 	 * - we should be careful when accessing its ire_nce (specifically
7538 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7539 	 * - not all legacy code path callers are prepared to handle
7540 	 *   incomplete ire's, so we should not create/add incomplete
7541 	 *   ire_cache entries here. (See discussion about temporary solution
7542 	 *   further below).
7543 	 *
7544 	 * In order to minimize packet dropping, and to preserve existing
7545 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7546 	 * gateway, and instead use the IF_RESOLVER ire to send out
7547 	 * another request to ARP (this is achieved by passing the
7548 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7549 	 * arp response comes back in ip_wput_nondata, we will create
7550 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7551 	 *
7552 	 * Note that this is a temporary solution; the correct solution is
7553 	 * to create an incomplete  per-dst ire_cache entry, and send the
7554 	 * packet out when the gw's nce is resolved. In order to achieve this,
7555 	 * all packet processing must have been completed prior to calling
7556 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7557 	 * to be modified to accomodate this solution.
7558 	 */
7559 	if (in_ill != NULL) {
7560 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7561 		    in_ill, MATCH_IRE_TYPE);
7562 	} else if (ip_nexthop) {
7563 		/*
7564 		 * The first time we come here, we look for an IRE_INTERFACE
7565 		 * entry for the specified nexthop, set the dst to be the
7566 		 * nexthop address and create an IRE_CACHE entry for the
7567 		 * nexthop. The next time around, we are able to find an
7568 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7569 		 * nexthop address and create an IRE_CACHE entry for the
7570 		 * destination address via the specified nexthop.
7571 		 */
7572 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7573 		    MBLK_GETLABEL(mp));
7574 		if (ire != NULL) {
7575 			gw = nexthop_addr;
7576 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7577 		} else {
7578 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7579 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7580 			    MBLK_GETLABEL(mp),
7581 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7582 			if (ire != NULL) {
7583 				dst = nexthop_addr;
7584 			}
7585 		}
7586 	} else if (attach_ill == NULL) {
7587 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7588 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7589 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7590 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7591 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7592 	} else {
7593 		/*
7594 		 * attach_ill is set only for communicating with
7595 		 * on-link hosts. So, don't look for DEFAULT.
7596 		 */
7597 		ipif_t	*attach_ipif;
7598 
7599 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7600 		if (attach_ipif == NULL) {
7601 			ill_refrele(attach_ill);
7602 			goto icmp_err_ret;
7603 		}
7604 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7605 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7606 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7607 		    MATCH_IRE_SECATTR);
7608 		ipif_refrele(attach_ipif);
7609 	}
7610 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7611 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7612 
7613 	/*
7614 	 * This loop is run only once in most cases.
7615 	 * We loop to resolve further routes only when the destination
7616 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7617 	 */
7618 	do {
7619 		/* Clear the previous iteration's values */
7620 		if (src_ipif != NULL) {
7621 			ipif_refrele(src_ipif);
7622 			src_ipif = NULL;
7623 		}
7624 		if (dst_ill != NULL) {
7625 			ill_refrele(dst_ill);
7626 			dst_ill = NULL;
7627 		}
7628 
7629 		multirt_resolve_next = B_FALSE;
7630 		/*
7631 		 * We check if packets have to be multirouted.
7632 		 * In this case, given the current <ire, sire> couple,
7633 		 * we look for the next suitable <ire, sire>.
7634 		 * This check is done in ire_multirt_lookup(),
7635 		 * which applies various criteria to find the next route
7636 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7637 		 * unchanged if it detects it has not been tried yet.
7638 		 */
7639 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7640 			ip3dbg(("ip_newroute: starting next_resolution "
7641 			    "with first_mp %p, tag %d\n",
7642 			    (void *)first_mp,
7643 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7644 
7645 			ASSERT(sire != NULL);
7646 			multirt_is_resolvable =
7647 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7648 				MBLK_GETLABEL(mp));
7649 
7650 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7651 			    "ire %p, sire %p\n",
7652 			    multirt_is_resolvable,
7653 			    (void *)ire, (void *)sire));
7654 
7655 			if (!multirt_is_resolvable) {
7656 				/*
7657 				 * No more multirt route to resolve; give up
7658 				 * (all routes resolved or no more
7659 				 * resolvable routes).
7660 				 */
7661 				if (ire != NULL) {
7662 					ire_refrele(ire);
7663 					ire = NULL;
7664 				}
7665 			} else {
7666 				ASSERT(sire != NULL);
7667 				ASSERT(ire != NULL);
7668 				/*
7669 				 * We simply use first_sire as a flag that
7670 				 * indicates if a resolvable multirt route
7671 				 * has already been found.
7672 				 * If it is not the case, we may have to send
7673 				 * an ICMP error to report that the
7674 				 * destination is unreachable.
7675 				 * We do not IRE_REFHOLD first_sire.
7676 				 */
7677 				if (first_sire == NULL) {
7678 					first_sire = sire;
7679 				}
7680 			}
7681 		}
7682 		if (ire == NULL) {
7683 			if (ip_debug > 3) {
7684 				/* ip2dbg */
7685 				pr_addr_dbg("ip_newroute: "
7686 				    "can't resolve %s\n", AF_INET, &dst);
7687 			}
7688 			ip3dbg(("ip_newroute: "
7689 			    "ire %p, sire %p, first_sire %p\n",
7690 			    (void *)ire, (void *)sire, (void *)first_sire));
7691 
7692 			if (sire != NULL) {
7693 				ire_refrele(sire);
7694 				sire = NULL;
7695 			}
7696 
7697 			if (first_sire != NULL) {
7698 				/*
7699 				 * At least one multirt route has been found
7700 				 * in the same call to ip_newroute();
7701 				 * there is no need to report an ICMP error.
7702 				 * first_sire was not IRE_REFHOLDed.
7703 				 */
7704 				MULTIRT_DEBUG_UNTAG(first_mp);
7705 				freemsg(first_mp);
7706 				return;
7707 			}
7708 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7709 			    RTA_DST);
7710 			if (attach_ill != NULL)
7711 				ill_refrele(attach_ill);
7712 			goto icmp_err_ret;
7713 		}
7714 
7715 		/*
7716 		 * When RTA_SRCIFP is used to add a route, then an interface
7717 		 * route is added in the source interface's routing table.
7718 		 * If the outgoing interface of this route is of type
7719 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7720 		 * ire_nce->nce_res_mp is set to NULL.
7721 		 * Later, when this route is first used for forwarding
7722 		 * a packet, ip_newroute() is called
7723 		 * to resolve the hardware address of the outgoing ipif.
7724 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7725 		 * source interface based table. We only come here if the
7726 		 * outgoing interface is a resolver interface and we don't
7727 		 * have the ire_nce->nce_res_mp information yet.
7728 		 * If in_ill is not null that means it is called from
7729 		 * ip_rput.
7730 		 */
7731 
7732 		ASSERT(ire->ire_in_ill == NULL ||
7733 		    (ire->ire_type == IRE_IF_RESOLVER &&
7734 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
7735 
7736 		/*
7737 		 * Verify that the returned IRE does not have either
7738 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7739 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7740 		 */
7741 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7742 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7743 			if (attach_ill != NULL)
7744 				ill_refrele(attach_ill);
7745 			goto icmp_err_ret;
7746 		}
7747 		/*
7748 		 * Increment the ire_ob_pkt_count field for ire if it is an
7749 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7750 		 * increment the same for the parent IRE, sire, if it is some
7751 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7752 		 * and HOST_REDIRECT).
7753 		 */
7754 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7755 			UPDATE_OB_PKT_COUNT(ire);
7756 			ire->ire_last_used_time = lbolt;
7757 		}
7758 
7759 		if (sire != NULL) {
7760 			gw = sire->ire_gateway_addr;
7761 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7762 			    IRE_INTERFACE)) == 0);
7763 			UPDATE_OB_PKT_COUNT(sire);
7764 			sire->ire_last_used_time = lbolt;
7765 		}
7766 		/*
7767 		 * We have a route to reach the destination.
7768 		 *
7769 		 * 1) If the interface is part of ill group, try to get a new
7770 		 *    ill taking load spreading into account.
7771 		 *
7772 		 * 2) After selecting the ill, get a source address that
7773 		 *    might create good inbound load spreading.
7774 		 *    ipif_select_source does this for us.
7775 		 *
7776 		 * If the application specified the ill (ifindex), we still
7777 		 * load spread. Only if the packets needs to go out
7778 		 * specifically on a given ill e.g. binding to
7779 		 * IPIF_NOFAILOVER address, then we don't try to use a
7780 		 * different ill for load spreading.
7781 		 */
7782 		if (attach_ill == NULL) {
7783 			/*
7784 			 * Don't perform outbound load spreading in the
7785 			 * case of an RTF_MULTIRT route, as we actually
7786 			 * typically want to replicate outgoing packets
7787 			 * through particular interfaces.
7788 			 */
7789 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7790 				dst_ill = ire->ire_ipif->ipif_ill;
7791 				/* for uniformity */
7792 				ill_refhold(dst_ill);
7793 			} else {
7794 				/*
7795 				 * If we are here trying to create an IRE_CACHE
7796 				 * for an offlink destination and have the
7797 				 * IRE_CACHE for the next hop and the latter is
7798 				 * using virtual IP source address selection i.e
7799 				 * it's ire->ire_ipif is pointing to a virtual
7800 				 * network interface (vni) then
7801 				 * ip_newroute_get_dst_ll() will return the vni
7802 				 * interface as the dst_ill. Since the vni is
7803 				 * virtual i.e not associated with any physical
7804 				 * interface, it cannot be the dst_ill, hence
7805 				 * in such a case call ip_newroute_get_dst_ll()
7806 				 * with the stq_ill instead of the ire_ipif ILL.
7807 				 * The function returns a refheld ill.
7808 				 */
7809 				if ((ire->ire_type == IRE_CACHE) &&
7810 				    IS_VNI(ire->ire_ipif->ipif_ill))
7811 					dst_ill = ip_newroute_get_dst_ill(
7812 						ire->ire_stq->q_ptr);
7813 				else
7814 					dst_ill = ip_newroute_get_dst_ill(
7815 						ire->ire_ipif->ipif_ill);
7816 			}
7817 			if (dst_ill == NULL) {
7818 				if (ip_debug > 2) {
7819 					pr_addr_dbg("ip_newroute: "
7820 					    "no dst ill for dst"
7821 					    " %s\n", AF_INET, &dst);
7822 				}
7823 				goto icmp_err_ret;
7824 			}
7825 		} else {
7826 			dst_ill = ire->ire_ipif->ipif_ill;
7827 			/* for uniformity */
7828 			ill_refhold(dst_ill);
7829 			/*
7830 			 * We should have found a route matching ill as we
7831 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7832 			 * Rather than asserting, when there is a mismatch,
7833 			 * we just drop the packet.
7834 			 */
7835 			if (dst_ill != attach_ill) {
7836 				ip0dbg(("ip_newroute: Packet dropped as "
7837 				    "IPIF_NOFAILOVER ill is %s, "
7838 				    "ire->ire_ipif->ipif_ill is %s\n",
7839 				    attach_ill->ill_name,
7840 				    dst_ill->ill_name));
7841 				ill_refrele(attach_ill);
7842 				goto icmp_err_ret;
7843 			}
7844 		}
7845 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7846 		if (attach_ill != NULL) {
7847 			ill_refrele(attach_ill);
7848 			attach_ill = NULL;
7849 			do_attach_ill = B_TRUE;
7850 		}
7851 		ASSERT(dst_ill != NULL);
7852 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7853 
7854 		/*
7855 		 * Pick the best source address from dst_ill.
7856 		 *
7857 		 * 1) If it is part of a multipathing group, we would
7858 		 *    like to spread the inbound packets across different
7859 		 *    interfaces. ipif_select_source picks a random source
7860 		 *    across the different ills in the group.
7861 		 *
7862 		 * 2) If it is not part of a multipathing group, we try
7863 		 *    to pick the source address from the destination
7864 		 *    route. Clustering assumes that when we have multiple
7865 		 *    prefixes hosted on an interface, the prefix of the
7866 		 *    source address matches the prefix of the destination
7867 		 *    route. We do this only if the address is not
7868 		 *    DEPRECATED.
7869 		 *
7870 		 * 3) If the conn is in a different zone than the ire, we
7871 		 *    need to pick a source address from the right zone.
7872 		 *
7873 		 * NOTE : If we hit case (1) above, the prefix of the source
7874 		 *	  address picked may not match the prefix of the
7875 		 *	  destination routes prefix as ipif_select_source
7876 		 *	  does not look at "dst" while picking a source
7877 		 *	  address.
7878 		 *	  If we want the same behavior as (2), we will need
7879 		 *	  to change the behavior of ipif_select_source.
7880 		 */
7881 		ASSERT(src_ipif == NULL);
7882 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7883 			/*
7884 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7885 			 * Check that the ipif matching the requested source
7886 			 * address still exists.
7887 			 */
7888 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7889 			    zoneid, NULL, NULL, NULL, NULL);
7890 		}
7891 		if (src_ipif == NULL) {
7892 			ire_marks |= IRE_MARK_USESRC_CHECK;
7893 			if ((dst_ill->ill_group != NULL) ||
7894 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
7895 			    (connp != NULL && ire->ire_zoneid != zoneid &&
7896 			    ire->ire_zoneid != ALL_ZONES) ||
7897 			    (dst_ill->ill_usesrc_ifindex != 0)) {
7898 				/*
7899 				 * If the destination is reachable via a
7900 				 * given gateway, the selected source address
7901 				 * should be in the same subnet as the gateway.
7902 				 * Otherwise, the destination is not reachable.
7903 				 *
7904 				 * If there are no interfaces on the same subnet
7905 				 * as the destination, ipif_select_source gives
7906 				 * first non-deprecated interface which might be
7907 				 * on a different subnet than the gateway.
7908 				 * This is not desirable. Hence pass the dst_ire
7909 				 * source address to ipif_select_source.
7910 				 * It is sure that the destination is reachable
7911 				 * with the dst_ire source address subnet.
7912 				 * So passing dst_ire source address to
7913 				 * ipif_select_source will make sure that the
7914 				 * selected source will be on the same subnet
7915 				 * as dst_ire source address.
7916 				 */
7917 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
7918 				src_ipif = ipif_select_source(dst_ill, saddr,
7919 				    zoneid);
7920 				if (src_ipif == NULL) {
7921 					if (ip_debug > 2) {
7922 						pr_addr_dbg("ip_newroute: "
7923 						    "no src for dst %s ",
7924 						    AF_INET, &dst);
7925 						printf("through interface %s\n",
7926 						    dst_ill->ill_name);
7927 					}
7928 					goto icmp_err_ret;
7929 				}
7930 			} else {
7931 				src_ipif = ire->ire_ipif;
7932 				ASSERT(src_ipif != NULL);
7933 				/* hold src_ipif for uniformity */
7934 				ipif_refhold(src_ipif);
7935 			}
7936 		}
7937 
7938 		/*
7939 		 * Assign a source address while we have the conn.
7940 		 * We can't have ip_wput_ire pick a source address when the
7941 		 * packet returns from arp since we need to look at
7942 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7943 		 * going through arp.
7944 		 *
7945 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7946 		 *	  it uses ip6i to store this information.
7947 		 */
7948 		if (ipha->ipha_src == INADDR_ANY &&
7949 		    (connp == NULL || !connp->conn_unspec_src)) {
7950 			ipha->ipha_src = src_ipif->ipif_src_addr;
7951 		}
7952 		if (ip_debug > 3) {
7953 			/* ip2dbg */
7954 			pr_addr_dbg("ip_newroute: first hop %s\n",
7955 			    AF_INET, &gw);
7956 		}
7957 		ip2dbg(("\tire type %s (%d)\n",
7958 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
7959 
7960 		/*
7961 		 * The TTL of multirouted packets is bounded by the
7962 		 * ip_multirt_ttl ndd variable.
7963 		 */
7964 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7965 			/* Force TTL of multirouted packets */
7966 			if ((ip_multirt_ttl > 0) &&
7967 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
7968 				ip2dbg(("ip_newroute: forcing multirt TTL "
7969 				    "to %d (was %d), dst 0x%08x\n",
7970 				    ip_multirt_ttl, ipha->ipha_ttl,
7971 				    ntohl(sire->ire_addr)));
7972 				ipha->ipha_ttl = ip_multirt_ttl;
7973 			}
7974 		}
7975 		/*
7976 		 * At this point in ip_newroute(), ire is either the
7977 		 * IRE_CACHE of the next-hop gateway for an off-subnet
7978 		 * destination or an IRE_INTERFACE type that should be used
7979 		 * to resolve an on-subnet destination or an on-subnet
7980 		 * next-hop gateway.
7981 		 *
7982 		 * In the IRE_CACHE case, we have the following :
7983 		 *
7984 		 * 1) src_ipif - used for getting a source address.
7985 		 *
7986 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7987 		 *    means packets using this IRE_CACHE will go out on
7988 		 *    dst_ill.
7989 		 *
7990 		 * 3) The IRE sire will point to the prefix that is the
7991 		 *    longest  matching route for the destination. These
7992 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
7993 		 *    and IRE_HOST_REDIRECT.
7994 		 *
7995 		 *    The newly created IRE_CACHE entry for the off-subnet
7996 		 *    destination is tied to both the prefix route and the
7997 		 *    interface route used to resolve the next-hop gateway
7998 		 *    via the ire_phandle and ire_ihandle fields,
7999 		 *    respectively.
8000 		 *
8001 		 * In the IRE_INTERFACE case, we have the following :
8002 		 *
8003 		 * 1) src_ipif - used for getting a source address.
8004 		 *
8005 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8006 		 *    means packets using the IRE_CACHE that we will build
8007 		 *    here will go out on dst_ill.
8008 		 *
8009 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8010 		 *    to be created will only be tied to the IRE_INTERFACE
8011 		 *    that was derived from the ire_ihandle field.
8012 		 *
8013 		 *    If sire is non-NULL, it means the destination is
8014 		 *    off-link and we will first create the IRE_CACHE for the
8015 		 *    gateway. Next time through ip_newroute, we will create
8016 		 *    the IRE_CACHE for the final destination as described
8017 		 *    above.
8018 		 *
8019 		 * In both cases, after the current resolution has been
8020 		 * completed (or possibly initialised, in the IRE_INTERFACE
8021 		 * case), the loop may be re-entered to attempt the resolution
8022 		 * of another RTF_MULTIRT route.
8023 		 *
8024 		 * When an IRE_CACHE entry for the off-subnet destination is
8025 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8026 		 * for further processing in emission loops.
8027 		 */
8028 		save_ire = ire;
8029 		switch (ire->ire_type) {
8030 		case IRE_CACHE: {
8031 			ire_t	*ipif_ire;
8032 			mblk_t	*ire_fp_mp;
8033 
8034 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8035 			if (gw == 0)
8036 				gw = ire->ire_gateway_addr;
8037 			/*
8038 			 * We need 3 ire's to create a new cache ire for an
8039 			 * off-link destination from the cache ire of the
8040 			 * gateway.
8041 			 *
8042 			 *	1. The prefix ire 'sire' (Note that this does
8043 			 *	   not apply to the conn_nexthop_set case)
8044 			 *	2. The cache ire of the gateway 'ire'
8045 			 *	3. The interface ire 'ipif_ire'
8046 			 *
8047 			 * We have (1) and (2). We lookup (3) below.
8048 			 *
8049 			 * If there is no interface route to the gateway,
8050 			 * it is a race condition, where we found the cache
8051 			 * but the interface route has been deleted.
8052 			 */
8053 			if (ip_nexthop) {
8054 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8055 			} else {
8056 				ipif_ire =
8057 				    ire_ihandle_lookup_offlink(ire, sire);
8058 			}
8059 			if (ipif_ire == NULL) {
8060 				ip1dbg(("ip_newroute: "
8061 				    "ire_ihandle_lookup_offlink failed\n"));
8062 				goto icmp_err_ret;
8063 			}
8064 			/*
8065 			 * XXX We are using the same res_mp
8066 			 * (DL_UNITDATA_REQ) though the save_ire is not
8067 			 * pointing at the same ill.
8068 			 * This is incorrect. We need to send it up to the
8069 			 * resolver to get the right res_mp. For ethernets
8070 			 * this may be okay (ill_type == DL_ETHER).
8071 			 */
8072 			res_mp = save_ire->ire_nce->nce_res_mp;
8073 			ire_fp_mp = NULL;
8074 			/*
8075 			 * save_ire's nce_fp_mp can't change since it is
8076 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8077 			 * LOCK_IRE_FP_MP does not do any useful work in
8078 			 * the case of IRE_CACHE. So we don't use it below.
8079 			 */
8080 			if (save_ire->ire_stq == dst_ill->ill_wq)
8081 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8082 
8083 			/*
8084 			 * Check cached gateway IRE for any security
8085 			 * attributes; if found, associate the gateway
8086 			 * credentials group to the destination IRE.
8087 			 */
8088 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8089 				mutex_enter(&attrp->igsa_lock);
8090 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8091 					GCGRP_REFHOLD(gcgrp);
8092 				mutex_exit(&attrp->igsa_lock);
8093 			}
8094 
8095 			ire = ire_create(
8096 			    (uchar_t *)&dst,		/* dest address */
8097 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8098 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8099 			    (uchar_t *)&gw,		/* gateway address */
8100 			    NULL,
8101 			    &save_ire->ire_max_frag,
8102 			    ire_fp_mp,			/* Fast Path header */
8103 			    dst_ill->ill_rq,		/* recv-from queue */
8104 			    dst_ill->ill_wq,		/* send-to queue */
8105 			    IRE_CACHE,			/* IRE type */
8106 			    res_mp,
8107 			    src_ipif,
8108 			    in_ill,			/* incoming ill */
8109 			    (sire != NULL) ?
8110 				sire->ire_mask : 0, 	/* Parent mask */
8111 			    (sire != NULL) ?
8112 				sire->ire_phandle : 0,  /* Parent handle */
8113 			    ipif_ire->ire_ihandle,	/* Interface handle */
8114 			    (sire != NULL) ? (sire->ire_flags &
8115 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8116 			    (sire != NULL) ?
8117 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8118 			    NULL,
8119 			    gcgrp);
8120 
8121 			if (ire == NULL) {
8122 				if (gcgrp != NULL) {
8123 					GCGRP_REFRELE(gcgrp);
8124 					gcgrp = NULL;
8125 				}
8126 				ire_refrele(ipif_ire);
8127 				ire_refrele(save_ire);
8128 				break;
8129 			}
8130 
8131 			/* reference now held by IRE */
8132 			gcgrp = NULL;
8133 
8134 			ire->ire_marks |= ire_marks;
8135 
8136 			/*
8137 			 * Prevent sire and ipif_ire from getting deleted.
8138 			 * The newly created ire is tied to both of them via
8139 			 * the phandle and ihandle respectively.
8140 			 */
8141 			if (sire != NULL) {
8142 				IRB_REFHOLD(sire->ire_bucket);
8143 				/* Has it been removed already ? */
8144 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8145 					IRB_REFRELE(sire->ire_bucket);
8146 					ire_refrele(ipif_ire);
8147 					ire_refrele(save_ire);
8148 					break;
8149 				}
8150 			}
8151 
8152 			IRB_REFHOLD(ipif_ire->ire_bucket);
8153 			/* Has it been removed already ? */
8154 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8155 				IRB_REFRELE(ipif_ire->ire_bucket);
8156 				if (sire != NULL)
8157 					IRB_REFRELE(sire->ire_bucket);
8158 				ire_refrele(ipif_ire);
8159 				ire_refrele(save_ire);
8160 				break;
8161 			}
8162 
8163 			xmit_mp = first_mp;
8164 			/*
8165 			 * In the case of multirouting, a copy
8166 			 * of the packet is done before its sending.
8167 			 * The copy is used to attempt another
8168 			 * route resolution, in a next loop.
8169 			 */
8170 			if (ire->ire_flags & RTF_MULTIRT) {
8171 				copy_mp = copymsg(first_mp);
8172 				if (copy_mp != NULL) {
8173 					xmit_mp = copy_mp;
8174 					MULTIRT_DEBUG_TAG(first_mp);
8175 				}
8176 			}
8177 			ire_add_then_send(q, ire, xmit_mp);
8178 			ire_refrele(save_ire);
8179 
8180 			/* Assert that sire is not deleted yet. */
8181 			if (sire != NULL) {
8182 				ASSERT(sire->ire_ptpn != NULL);
8183 				IRB_REFRELE(sire->ire_bucket);
8184 			}
8185 
8186 			/* Assert that ipif_ire is not deleted yet. */
8187 			ASSERT(ipif_ire->ire_ptpn != NULL);
8188 			IRB_REFRELE(ipif_ire->ire_bucket);
8189 			ire_refrele(ipif_ire);
8190 
8191 			/*
8192 			 * If copy_mp is not NULL, multirouting was
8193 			 * requested. We loop to initiate a next
8194 			 * route resolution attempt, starting from sire.
8195 			 */
8196 			if (copy_mp != NULL) {
8197 				/*
8198 				 * Search for the next unresolved
8199 				 * multirt route.
8200 				 */
8201 				copy_mp = NULL;
8202 				ipif_ire = NULL;
8203 				ire = NULL;
8204 				multirt_resolve_next = B_TRUE;
8205 				continue;
8206 			}
8207 			if (sire != NULL)
8208 				ire_refrele(sire);
8209 			ipif_refrele(src_ipif);
8210 			ill_refrele(dst_ill);
8211 			return;
8212 		}
8213 		case IRE_IF_NORESOLVER: {
8214 			/*
8215 			 * We have what we need to build an IRE_CACHE.
8216 			 *
8217 			 * Create a new res_mp with the IP gateway address
8218 			 * in destination address in the DLPI hdr if the
8219 			 * physical length is exactly 4 bytes.
8220 			 */
8221 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8222 				uchar_t *addr;
8223 
8224 				if (gw)
8225 					addr = (uchar_t *)&gw;
8226 				else
8227 					addr = (uchar_t *)&dst;
8228 
8229 				res_mp = ill_dlur_gen(addr,
8230 				    dst_ill->ill_phys_addr_length,
8231 				    dst_ill->ill_sap,
8232 				    dst_ill->ill_sap_length);
8233 
8234 				if (res_mp == NULL) {
8235 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8236 					break;
8237 				}
8238 			} else {
8239 				res_mp = NULL;
8240 			}
8241 
8242 			/*
8243 			 * TSol note: We are creating the ire cache for the
8244 			 * destination 'dst'. If 'dst' is offlink, going
8245 			 * through the first hop 'gw', the security attributes
8246 			 * of 'dst' must be set to point to the gateway
8247 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8248 			 * is possible that 'dst' is a potential gateway that is
8249 			 * referenced by some route that has some security
8250 			 * attributes. Thus in the former case, we need to do a
8251 			 * gcgrp_lookup of 'gw' while in the latter case we
8252 			 * need to do gcgrp_lookup of 'dst' itself.
8253 			 */
8254 			ga.ga_af = AF_INET;
8255 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8256 			    &ga.ga_addr);
8257 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8258 
8259 			ire = ire_create(
8260 			    (uchar_t *)&dst,		/* dest address */
8261 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8262 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8263 			    (uchar_t *)&gw,		/* gateway address */
8264 			    NULL,
8265 			    &save_ire->ire_max_frag,
8266 			    NULL,			/* Fast Path header */
8267 			    dst_ill->ill_rq,		/* recv-from queue */
8268 			    dst_ill->ill_wq,		/* send-to queue */
8269 			    IRE_CACHE,
8270 			    res_mp,
8271 			    src_ipif,
8272 			    in_ill,			/* Incoming ill */
8273 			    save_ire->ire_mask,		/* Parent mask */
8274 			    (sire != NULL) ?		/* Parent handle */
8275 				sire->ire_phandle : 0,
8276 			    save_ire->ire_ihandle,	/* Interface handle */
8277 			    (sire != NULL) ? sire->ire_flags &
8278 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8279 			    &(save_ire->ire_uinfo),
8280 			    NULL,
8281 			    gcgrp);
8282 
8283 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8284 				freeb(res_mp);
8285 
8286 			if (ire == NULL) {
8287 				if (gcgrp != NULL) {
8288 					GCGRP_REFRELE(gcgrp);
8289 					gcgrp = NULL;
8290 				}
8291 				ire_refrele(save_ire);
8292 				break;
8293 			}
8294 
8295 			/* reference now held by IRE */
8296 			gcgrp = NULL;
8297 
8298 			ire->ire_marks |= ire_marks;
8299 
8300 			/* Prevent save_ire from getting deleted */
8301 			IRB_REFHOLD(save_ire->ire_bucket);
8302 			/* Has it been removed already ? */
8303 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8304 				IRB_REFRELE(save_ire->ire_bucket);
8305 				ire_refrele(save_ire);
8306 				break;
8307 			}
8308 
8309 			/*
8310 			 * In the case of multirouting, a copy
8311 			 * of the packet is made before it is sent.
8312 			 * The copy is used in the next
8313 			 * loop to attempt another resolution.
8314 			 */
8315 			xmit_mp = first_mp;
8316 			if ((sire != NULL) &&
8317 			    (sire->ire_flags & RTF_MULTIRT)) {
8318 				copy_mp = copymsg(first_mp);
8319 				if (copy_mp != NULL) {
8320 					xmit_mp = copy_mp;
8321 					MULTIRT_DEBUG_TAG(first_mp);
8322 				}
8323 			}
8324 			ire_add_then_send(q, ire, xmit_mp);
8325 
8326 			/* Assert that it is not deleted yet. */
8327 			ASSERT(save_ire->ire_ptpn != NULL);
8328 			IRB_REFRELE(save_ire->ire_bucket);
8329 			ire_refrele(save_ire);
8330 
8331 			if (copy_mp != NULL) {
8332 				/*
8333 				 * If we found a (no)resolver, we ignore any
8334 				 * trailing top priority IRE_CACHE in further
8335 				 * loops. This ensures that we do not omit any
8336 				 * (no)resolver.
8337 				 * This IRE_CACHE, if any, will be processed
8338 				 * by another thread entering ip_newroute().
8339 				 * IRE_CACHE entries, if any, will be processed
8340 				 * by another thread entering ip_newroute(),
8341 				 * (upon resolver response, for instance).
8342 				 * This aims to force parallel multirt
8343 				 * resolutions as soon as a packet must be sent.
8344 				 * In the best case, after the tx of only one
8345 				 * packet, all reachable routes are resolved.
8346 				 * Otherwise, the resolution of all RTF_MULTIRT
8347 				 * routes would require several emissions.
8348 				 */
8349 				multirt_flags &= ~MULTIRT_CACHEGW;
8350 
8351 				/*
8352 				 * Search for the next unresolved multirt
8353 				 * route.
8354 				 */
8355 				copy_mp = NULL;
8356 				save_ire = NULL;
8357 				ire = NULL;
8358 				multirt_resolve_next = B_TRUE;
8359 				continue;
8360 			}
8361 
8362 			/*
8363 			 * Don't need sire anymore
8364 			 */
8365 			if (sire != NULL)
8366 				ire_refrele(sire);
8367 
8368 			ipif_refrele(src_ipif);
8369 			ill_refrele(dst_ill);
8370 			return;
8371 		}
8372 		case IRE_IF_RESOLVER:
8373 			/*
8374 			 * We can't build an IRE_CACHE yet, but at least we
8375 			 * found a resolver that can help.
8376 			 */
8377 			res_mp = dst_ill->ill_resolver_mp;
8378 			if (!OK_RESOLVER_MP(res_mp))
8379 				break;
8380 
8381 			/*
8382 			 * To be at this point in the code with a non-zero gw
8383 			 * means that dst is reachable through a gateway that
8384 			 * we have never resolved.  By changing dst to the gw
8385 			 * addr we resolve the gateway first.
8386 			 * When ire_add_then_send() tries to put the IP dg
8387 			 * to dst, it will reenter ip_newroute() at which
8388 			 * time we will find the IRE_CACHE for the gw and
8389 			 * create another IRE_CACHE in case IRE_CACHE above.
8390 			 */
8391 			if (gw != INADDR_ANY) {
8392 				/*
8393 				 * The source ipif that was determined above was
8394 				 * relative to the destination address, not the
8395 				 * gateway's. If src_ipif was not taken out of
8396 				 * the IRE_IF_RESOLVER entry, we'll need to call
8397 				 * ipif_select_source() again.
8398 				 */
8399 				if (src_ipif != ire->ire_ipif) {
8400 					ipif_refrele(src_ipif);
8401 					src_ipif = ipif_select_source(dst_ill,
8402 					    gw, zoneid);
8403 					if (src_ipif == NULL) {
8404 						if (ip_debug > 2) {
8405 							pr_addr_dbg(
8406 							    "ip_newroute: no "
8407 							    "src for gw %s ",
8408 							    AF_INET, &gw);
8409 							printf("through "
8410 							    "interface %s\n",
8411 							    dst_ill->ill_name);
8412 						}
8413 						goto icmp_err_ret;
8414 					}
8415 				}
8416 				save_dst = dst;
8417 				dst = gw;
8418 				gw = INADDR_ANY;
8419 			}
8420 
8421 			/*
8422 			 * We obtain a partial IRE_CACHE which we will pass
8423 			 * along with the resolver query.  When the response
8424 			 * comes back it will be there ready for us to add.
8425 			 * The ire_max_frag is atomically set under the
8426 			 * irebucket lock in ire_add_v[46].
8427 			 */
8428 
8429 			ire = ire_create_mp(
8430 			    (uchar_t *)&dst,		/* dest address */
8431 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8432 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8433 			    (uchar_t *)&gw,		/* gateway address */
8434 			    NULL,			/* no in_src_addr */
8435 			    NULL,			/* ire_max_frag */
8436 			    NULL,			/* Fast Path header */
8437 			    dst_ill->ill_rq,		/* recv-from queue */
8438 			    dst_ill->ill_wq,		/* send-to queue */
8439 			    IRE_CACHE,
8440 			    NULL,
8441 			    src_ipif,			/* Interface ipif */
8442 			    in_ill,			/* Incoming ILL */
8443 			    save_ire->ire_mask,		/* Parent mask */
8444 			    0,
8445 			    save_ire->ire_ihandle,	/* Interface handle */
8446 			    0,				/* flags if any */
8447 			    &(save_ire->ire_uinfo),
8448 			    NULL,
8449 			    NULL);
8450 
8451 			if (ire == NULL) {
8452 				ire_refrele(save_ire);
8453 				break;
8454 			}
8455 
8456 			if ((sire != NULL) &&
8457 			    (sire->ire_flags & RTF_MULTIRT)) {
8458 				copy_mp = copymsg(first_mp);
8459 				if (copy_mp != NULL)
8460 					MULTIRT_DEBUG_TAG(copy_mp);
8461 			}
8462 
8463 			ire->ire_marks |= ire_marks;
8464 
8465 			/*
8466 			 * Construct message chain for the resolver
8467 			 * of the form:
8468 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8469 			 * Packet could contain a IPSEC_OUT mp.
8470 			 *
8471 			 * NOTE : ire will be added later when the response
8472 			 * comes back from ARP. If the response does not
8473 			 * come back, ARP frees the packet. For this reason,
8474 			 * we can't REFHOLD the bucket of save_ire to prevent
8475 			 * deletions. We may not be able to REFRELE the bucket
8476 			 * if the response never comes back. Thus, before
8477 			 * adding the ire, ire_add_v4 will make sure that the
8478 			 * interface route does not get deleted. This is the
8479 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8480 			 * where we can always prevent deletions because of
8481 			 * the synchronous nature of adding IRES i.e
8482 			 * ire_add_then_send is called after creating the IRE.
8483 			 */
8484 			ASSERT(ire->ire_mp != NULL);
8485 			ire->ire_mp->b_cont = first_mp;
8486 			/* Have saved_mp handy, for cleanup if canput fails */
8487 			saved_mp = mp;
8488 			mp = copyb(res_mp);
8489 			ASSERT(mp != NULL);
8490 			linkb(mp, ire->ire_mp);
8491 
8492 
8493 			/*
8494 			 * Fill in the source and dest addrs for the resolver.
8495 			 * NOTE: this depends on memory layouts imposed by
8496 			 * ill_init().
8497 			 */
8498 			areq = (areq_t *)mp->b_rptr;
8499 			addrp = (ipaddr_t *)((char *)areq +
8500 			    areq->areq_sender_addr_offset);
8501 			if (do_attach_ill) {
8502 				/*
8503 				 * This is bind to no failover case.
8504 				 * arp packet also must go out on attach_ill.
8505 				 */
8506 				ASSERT(ipha->ipha_src != NULL);
8507 				*addrp = ipha->ipha_src;
8508 			} else {
8509 				*addrp = save_ire->ire_src_addr;
8510 			}
8511 
8512 			ire_refrele(save_ire);
8513 			addrp = (ipaddr_t *)((char *)areq +
8514 			    areq->areq_target_addr_offset);
8515 			*addrp = dst;
8516 			/* Up to the resolver. */
8517 			if (canputnext(dst_ill->ill_rq) &&
8518 			    !(dst_ill->ill_arp_closing)) {
8519 				putnext(dst_ill->ill_rq, mp);
8520 				ire = NULL;
8521 				if (copy_mp != NULL) {
8522 					/*
8523 					 * If we found a resolver, we ignore
8524 					 * any trailing top priority IRE_CACHE
8525 					 * in the further loops. This ensures
8526 					 * that we do not omit any resolver.
8527 					 * IRE_CACHE entries, if any, will be
8528 					 * processed next time we enter
8529 					 * ip_newroute().
8530 					 */
8531 					multirt_flags &= ~MULTIRT_CACHEGW;
8532 					/*
8533 					 * Search for the next unresolved
8534 					 * multirt route.
8535 					 */
8536 					first_mp = copy_mp;
8537 					copy_mp = NULL;
8538 					/* Prepare the next resolution loop. */
8539 					mp = first_mp;
8540 					EXTRACT_PKT_MP(mp, first_mp,
8541 					    mctl_present);
8542 					if (mctl_present)
8543 						io = (ipsec_out_t *)
8544 						    first_mp->b_rptr;
8545 					ipha = (ipha_t *)mp->b_rptr;
8546 
8547 					ASSERT(sire != NULL);
8548 
8549 					dst = save_dst;
8550 					multirt_resolve_next = B_TRUE;
8551 					continue;
8552 				}
8553 
8554 				if (sire != NULL)
8555 					ire_refrele(sire);
8556 
8557 				/*
8558 				 * The response will come back in ip_wput
8559 				 * with db_type IRE_DB_TYPE.
8560 				 */
8561 				ipif_refrele(src_ipif);
8562 				ill_refrele(dst_ill);
8563 				return;
8564 			} else {
8565 				/* Prepare for cleanup */
8566 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8567 				    mp);
8568 				mp->b_cont = NULL;
8569 				freeb(mp); /* areq */
8570 				/*
8571 				 * this is an ire that is not added to the
8572 				 * cache. ire_freemblk will handle the release
8573 				 * of any resources associated with the ire.
8574 				 */
8575 				ire_delete(ire); /* ire_mp */
8576 				mp = saved_mp; /* pkt */
8577 				ire = NULL;
8578 				if (copy_mp != NULL) {
8579 					MULTIRT_DEBUG_UNTAG(copy_mp);
8580 					freemsg(copy_mp);
8581 					copy_mp = NULL;
8582 				}
8583 				break;
8584 			}
8585 		default:
8586 			break;
8587 		}
8588 	} while (multirt_resolve_next);
8589 
8590 	ip1dbg(("ip_newroute: dropped\n"));
8591 	/* Did this packet originate externally? */
8592 	if (mp->b_prev) {
8593 		mp->b_next = NULL;
8594 		mp->b_prev = NULL;
8595 		BUMP_MIB(&ip_mib, ipInDiscards);
8596 	} else {
8597 		BUMP_MIB(&ip_mib, ipOutDiscards);
8598 	}
8599 	ASSERT(copy_mp == NULL);
8600 	MULTIRT_DEBUG_UNTAG(first_mp);
8601 	freemsg(first_mp);
8602 	if (ire != NULL)
8603 		ire_refrele(ire);
8604 	if (sire != NULL)
8605 		ire_refrele(sire);
8606 	if (src_ipif != NULL)
8607 		ipif_refrele(src_ipif);
8608 	if (dst_ill != NULL)
8609 		ill_refrele(dst_ill);
8610 	return;
8611 
8612 icmp_err_ret:
8613 	ip1dbg(("ip_newroute: no route\n"));
8614 	if (src_ipif != NULL)
8615 		ipif_refrele(src_ipif);
8616 	if (dst_ill != NULL)
8617 		ill_refrele(dst_ill);
8618 	if (sire != NULL)
8619 		ire_refrele(sire);
8620 	/* Did this packet originate externally? */
8621 	if (mp->b_prev) {
8622 		mp->b_next = NULL;
8623 		mp->b_prev = NULL;
8624 		/* XXX ipInNoRoutes */
8625 		q = WR(q);
8626 	} else {
8627 		/*
8628 		 * Since ip_wput() isn't close to finished, we fill
8629 		 * in enough of the header for credible error reporting.
8630 		 */
8631 		if (ip_hdr_complete(ipha, zoneid)) {
8632 			/* Failed */
8633 			MULTIRT_DEBUG_UNTAG(first_mp);
8634 			freemsg(first_mp);
8635 			if (ire != NULL)
8636 				ire_refrele(ire);
8637 			return;
8638 		}
8639 	}
8640 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8641 
8642 	/*
8643 	 * At this point we will have ire only if RTF_BLACKHOLE
8644 	 * or RTF_REJECT flags are set on the IRE. It will not
8645 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8646 	 */
8647 	if (ire != NULL) {
8648 		if (ire->ire_flags & RTF_BLACKHOLE) {
8649 			ire_refrele(ire);
8650 			MULTIRT_DEBUG_UNTAG(first_mp);
8651 			freemsg(first_mp);
8652 			return;
8653 		}
8654 		ire_refrele(ire);
8655 	}
8656 	if (ip_source_routed(ipha)) {
8657 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
8658 		return;
8659 	}
8660 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8661 }
8662 
8663 /*
8664  * IPv4 -
8665  * ip_newroute_ipif is called by ip_wput_multicast and
8666  * ip_rput_forward_multicast whenever we need to send
8667  * out a packet to a destination address for which we do not have specific
8668  * routing information. It is used when the packet will be sent out
8669  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8670  * socket option is set or icmp error message wants to go out on a particular
8671  * interface for a unicast packet.
8672  *
8673  * In most cases, the destination address is resolved thanks to the ipif
8674  * intrinsic resolver. However, there are some cases where the call to
8675  * ip_newroute_ipif must take into account the potential presence of
8676  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8677  * that uses the interface. This is specified through flags,
8678  * which can be a combination of:
8679  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8680  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8681  *   and flags. Additionally, the packet source address has to be set to
8682  *   the specified address. The caller is thus expected to set this flag
8683  *   if the packet has no specific source address yet.
8684  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8685  *   flag, the resulting ire will inherit the flag. All unresolved routes
8686  *   to the destination must be explored in the same call to
8687  *   ip_newroute_ipif().
8688  */
8689 static void
8690 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8691     conn_t *connp, uint32_t flags)
8692 {
8693 	areq_t	*areq;
8694 	ire_t	*ire = NULL;
8695 	mblk_t	*res_mp;
8696 	ipaddr_t *addrp;
8697 	mblk_t *first_mp;
8698 	ire_t	*save_ire = NULL;
8699 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8700 	ipif_t	*src_ipif = NULL;
8701 	ushort_t ire_marks = 0;
8702 	ill_t	*dst_ill = NULL;
8703 	boolean_t mctl_present;
8704 	ipsec_out_t *io;
8705 	ipha_t *ipha;
8706 	int	ihandle = 0;
8707 	mblk_t	*saved_mp;
8708 	ire_t   *fire = NULL;
8709 	mblk_t  *copy_mp = NULL;
8710 	boolean_t multirt_resolve_next;
8711 	ipaddr_t ipha_dst;
8712 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
8713 
8714 	/*
8715 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8716 	 * here for uniformity
8717 	 */
8718 	ipif_refhold(ipif);
8719 
8720 	/*
8721 	 * This loop is run only once in most cases.
8722 	 * We loop to resolve further routes only when the destination
8723 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8724 	 */
8725 	do {
8726 		if (dst_ill != NULL) {
8727 			ill_refrele(dst_ill);
8728 			dst_ill = NULL;
8729 		}
8730 		if (src_ipif != NULL) {
8731 			ipif_refrele(src_ipif);
8732 			src_ipif = NULL;
8733 		}
8734 		multirt_resolve_next = B_FALSE;
8735 
8736 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8737 		    ipif->ipif_ill->ill_name));
8738 
8739 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8740 		if (mctl_present)
8741 			io = (ipsec_out_t *)first_mp->b_rptr;
8742 
8743 		ipha = (ipha_t *)mp->b_rptr;
8744 
8745 		/*
8746 		 * Save the packet destination address, we may need it after
8747 		 * the packet has been consumed.
8748 		 */
8749 		ipha_dst = ipha->ipha_dst;
8750 
8751 		/*
8752 		 * If the interface is a pt-pt interface we look for an
8753 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8754 		 * local_address and the pt-pt destination address. Otherwise
8755 		 * we just match the local address.
8756 		 * NOTE: dst could be different than ipha->ipha_dst in case
8757 		 * of sending igmp multicast packets over a point-to-point
8758 		 * connection.
8759 		 * Thus we must be careful enough to check ipha_dst to be a
8760 		 * multicast address, otherwise it will take xmit_if path for
8761 		 * multicast packets resulting into kernel stack overflow by
8762 		 * repeated calls to ip_newroute_ipif from ire_send().
8763 		 */
8764 		if (CLASSD(ipha_dst) &&
8765 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8766 			goto err_ret;
8767 		}
8768 
8769 		/*
8770 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8771 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8772 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8773 		 * propagate its flags to the new ire.
8774 		 */
8775 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8776 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8777 			ip2dbg(("ip_newroute_ipif: "
8778 			    "ipif_lookup_multi_ire("
8779 			    "ipif %p, dst %08x) = fire %p\n",
8780 			    (void *)ipif, ntohl(dst), (void *)fire));
8781 		}
8782 
8783 		if (mctl_present && io->ipsec_out_attach_if) {
8784 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8785 			    io->ipsec_out_ill_index, B_FALSE);
8786 
8787 			/* Failure case frees things for us. */
8788 			if (attach_ill == NULL) {
8789 				ipif_refrele(ipif);
8790 				if (fire != NULL)
8791 					ire_refrele(fire);
8792 				return;
8793 			}
8794 
8795 			/*
8796 			 * Check if we need an ire that will not be
8797 			 * looked up by anybody else i.e. HIDDEN.
8798 			 */
8799 			if (ill_is_probeonly(attach_ill)) {
8800 				ire_marks = IRE_MARK_HIDDEN;
8801 			}
8802 			/*
8803 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8804 			 * case.
8805 			 */
8806 			dst_ill = ipif->ipif_ill;
8807 			/* attach_ill has been refheld by ip_grab_attach_ill */
8808 			ASSERT(dst_ill == attach_ill);
8809 		} else {
8810 			/*
8811 			 * If this is set by IP_XMIT_IF, then make sure that
8812 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8813 			 * specified ill.
8814 			 */
8815 			ASSERT((connp == NULL) ||
8816 			    (connp->conn_xmit_if_ill == NULL) ||
8817 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8818 			/*
8819 			 * If the interface belongs to an interface group,
8820 			 * make sure the next possible interface in the group
8821 			 * is used.  This encourages load spreading among
8822 			 * peers in an interface group.
8823 			 * Note: load spreading is disabled for RTF_MULTIRT
8824 			 * routes.
8825 			 */
8826 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8827 			    (fire->ire_flags & RTF_MULTIRT)) {
8828 				/*
8829 				 * Don't perform outbound load spreading
8830 				 * in the case of an RTF_MULTIRT issued route,
8831 				 * we actually typically want to replicate
8832 				 * outgoing packets through particular
8833 				 * interfaces.
8834 				 */
8835 				dst_ill = ipif->ipif_ill;
8836 				ill_refhold(dst_ill);
8837 			} else {
8838 				dst_ill = ip_newroute_get_dst_ill(
8839 				    ipif->ipif_ill);
8840 			}
8841 			if (dst_ill == NULL) {
8842 				if (ip_debug > 2) {
8843 					pr_addr_dbg("ip_newroute_ipif: "
8844 					    "no dst ill for dst %s\n",
8845 					    AF_INET, &dst);
8846 				}
8847 				goto err_ret;
8848 			}
8849 		}
8850 
8851 		/*
8852 		 * Pick a source address preferring non-deprecated ones.
8853 		 * Unlike ip_newroute, we don't do any source address
8854 		 * selection here since for multicast it really does not help
8855 		 * in inbound load spreading as in the unicast case.
8856 		 */
8857 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8858 		    (fire->ire_flags & RTF_SETSRC)) {
8859 			/*
8860 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8861 			 * on that interface. This ire has RTF_SETSRC flag, so
8862 			 * the source address of the packet must be changed.
8863 			 * Check that the ipif matching the requested source
8864 			 * address still exists.
8865 			 */
8866 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8867 			    zoneid, NULL, NULL, NULL, NULL);
8868 		}
8869 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8870 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
8871 		    ipif->ipif_zoneid != ALL_ZONES)) &&
8872 		    (src_ipif == NULL)) {
8873 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8874 			if (src_ipif == NULL) {
8875 				if (ip_debug > 2) {
8876 					/* ip1dbg */
8877 					pr_addr_dbg("ip_newroute_ipif: "
8878 					    "no src for dst %s",
8879 					    AF_INET, &dst);
8880 				}
8881 				ip1dbg((" through interface %s\n",
8882 				    dst_ill->ill_name));
8883 				goto err_ret;
8884 			}
8885 			ipif_refrele(ipif);
8886 			ipif = src_ipif;
8887 			ipif_refhold(ipif);
8888 		}
8889 		if (src_ipif == NULL) {
8890 			src_ipif = ipif;
8891 			ipif_refhold(src_ipif);
8892 		}
8893 
8894 		/*
8895 		 * Assign a source address while we have the conn.
8896 		 * We can't have ip_wput_ire pick a source address when the
8897 		 * packet returns from arp since conn_unspec_src might be set
8898 		 * and we loose the conn when going through arp.
8899 		 */
8900 		if (ipha->ipha_src == INADDR_ANY &&
8901 		    (connp == NULL || !connp->conn_unspec_src)) {
8902 			ipha->ipha_src = src_ipif->ipif_src_addr;
8903 		}
8904 
8905 		/*
8906 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8907 		 * interface does not have an interface ire.
8908 		 * Example: Thousands of mobileip PPP interfaces to mobile
8909 		 * nodes. We don't want to create interface ires because
8910 		 * packets from other mobile nodes must not take the route
8911 		 * via interface ires to the visiting mobile node without
8912 		 * going through the home agent, in absence of mobileip
8913 		 * route optimization.
8914 		 */
8915 		if (CLASSD(ipha_dst) && (connp == NULL ||
8916 		    connp->conn_xmit_if_ill == NULL)) {
8917 			/* ipif_to_ire returns an held ire */
8918 			ire = ipif_to_ire(ipif);
8919 			if (ire == NULL)
8920 				goto err_ret;
8921 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8922 				goto err_ret;
8923 			/*
8924 			 * ihandle is needed when the ire is added to
8925 			 * cache table.
8926 			 */
8927 			save_ire = ire;
8928 			ihandle = save_ire->ire_ihandle;
8929 
8930 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8931 			    "flags %04x\n",
8932 			    (void *)ire, (void *)ipif, flags));
8933 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8934 			    (fire->ire_flags & RTF_MULTIRT)) {
8935 				/*
8936 				 * As requested by flags, an IRE_OFFSUBNET was
8937 				 * looked up on that interface. This ire has
8938 				 * RTF_MULTIRT flag, so the resolution loop will
8939 				 * be re-entered to resolve additional routes on
8940 				 * other interfaces. For that purpose, a copy of
8941 				 * the packet is performed at this point.
8942 				 */
8943 				fire->ire_last_used_time = lbolt;
8944 				copy_mp = copymsg(first_mp);
8945 				if (copy_mp) {
8946 					MULTIRT_DEBUG_TAG(copy_mp);
8947 				}
8948 			}
8949 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
8950 			    (fire->ire_flags & RTF_SETSRC)) {
8951 				/*
8952 				 * As requested by flags, an IRE_OFFSUBET was
8953 				 * looked up on that interface. This ire has
8954 				 * RTF_SETSRC flag, so the source address of the
8955 				 * packet must be changed.
8956 				 */
8957 				ipha->ipha_src = fire->ire_src_addr;
8958 			}
8959 		} else {
8960 			ASSERT((connp == NULL) ||
8961 			    (connp->conn_xmit_if_ill != NULL) ||
8962 			    (connp->conn_dontroute));
8963 			/*
8964 			 * The only ways we can come here are:
8965 			 * 1) IP_XMIT_IF socket option is set
8966 			 * 2) ICMP error message generated from
8967 			 *    ip_mrtun_forward() routine and it needs
8968 			 *    to go through the specified ill.
8969 			 * 3) SO_DONTROUTE socket option is set
8970 			 * In all cases, the new ire will not be added
8971 			 * into cache table.
8972 			 */
8973 			ire_marks |= IRE_MARK_NOADD;
8974 		}
8975 
8976 		switch (ipif->ipif_net_type) {
8977 		case IRE_IF_NORESOLVER: {
8978 			/* We have what we need to build an IRE_CACHE. */
8979 			mblk_t	*res_mp;
8980 
8981 			/*
8982 			 * Create a new res_mp with the
8983 			 * IP gateway address as destination address in the
8984 			 * DLPI hdr if the physical length is exactly 4 bytes.
8985 			 */
8986 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8987 				res_mp = ill_dlur_gen((uchar_t *)&dst,
8988 				    dst_ill->ill_phys_addr_length,
8989 				    dst_ill->ill_sap,
8990 				    dst_ill->ill_sap_length);
8991 			} else {
8992 				/* use the value set in ip_ll_subnet_defaults */
8993 				res_mp = ill_dlur_gen(NULL,
8994 				    dst_ill->ill_phys_addr_length,
8995 				    dst_ill->ill_sap,
8996 				    dst_ill->ill_sap_length);
8997 			}
8998 
8999 			if (res_mp == NULL)
9000 				break;
9001 			/*
9002 			 * The new ire inherits the IRE_OFFSUBNET flags
9003 			 * and source address, if this was requested.
9004 			 */
9005 			ire = ire_create(
9006 			    (uchar_t *)&dst,		/* dest address */
9007 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9008 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9009 			    NULL,			/* gateway address */
9010 			    NULL,
9011 			    &ipif->ipif_mtu,
9012 			    NULL,			/* Fast Path header */
9013 			    dst_ill->ill_rq,		/* recv-from queue */
9014 			    dst_ill->ill_wq,		/* send-to queue */
9015 			    IRE_CACHE,
9016 			    res_mp,
9017 			    src_ipif,
9018 			    NULL,
9019 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9020 			    (fire != NULL) ?		/* Parent handle */
9021 				fire->ire_phandle : 0,
9022 			    ihandle,			/* Interface handle */
9023 			    (fire != NULL) ?
9024 				(fire->ire_flags &
9025 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9026 			    (save_ire == NULL ? &ire_uinfo_null :
9027 				&save_ire->ire_uinfo),
9028 			    NULL,
9029 			    NULL);
9030 
9031 			freeb(res_mp);
9032 
9033 			if (ire == NULL) {
9034 				if (save_ire != NULL)
9035 					ire_refrele(save_ire);
9036 				break;
9037 			}
9038 
9039 			ire->ire_marks |= ire_marks;
9040 
9041 			/*
9042 			 * If IRE_MARK_NOADD is set then we need to convert
9043 			 * the max_fragp to a useable value now. This is
9044 			 * normally done in ire_add_v[46]. We also need to
9045 			 * associate the ire with an nce (normally would be
9046 			 * done in ip_wput_nondata()).
9047 			 *
9048 			 * Note that IRE_MARK_NOADD packets created here
9049 			 * do not have a non-null ire_mp pointer. The null
9050 			 * value of ire_bucket indicates that they were
9051 			 * never added.
9052 			 */
9053 			if (ire->ire_marks & IRE_MARK_NOADD) {
9054 				uint_t  max_frag;
9055 
9056 				max_frag = *ire->ire_max_fragp;
9057 				ire->ire_max_fragp = NULL;
9058 				ire->ire_max_frag = max_frag;
9059 
9060 				if ((ire->ire_nce = ndp_lookup_v4(
9061 				    ire_to_ill(ire),
9062 				    (ire->ire_gateway_addr != INADDR_ANY ?
9063 				    &ire->ire_gateway_addr : &ire->ire_addr),
9064 				    B_FALSE)) == NULL) {
9065 					if (save_ire != NULL)
9066 						ire_refrele(save_ire);
9067 					break;
9068 				}
9069 				ASSERT(ire->ire_nce->nce_state ==
9070 				    ND_REACHABLE);
9071 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9072 			}
9073 
9074 			/* Prevent save_ire from getting deleted */
9075 			if (save_ire != NULL) {
9076 				IRB_REFHOLD(save_ire->ire_bucket);
9077 				/* Has it been removed already ? */
9078 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9079 					IRB_REFRELE(save_ire->ire_bucket);
9080 					ire_refrele(save_ire);
9081 					break;
9082 				}
9083 			}
9084 
9085 			ire_add_then_send(q, ire, first_mp);
9086 
9087 			/* Assert that save_ire is not deleted yet. */
9088 			if (save_ire != NULL) {
9089 				ASSERT(save_ire->ire_ptpn != NULL);
9090 				IRB_REFRELE(save_ire->ire_bucket);
9091 				ire_refrele(save_ire);
9092 				save_ire = NULL;
9093 			}
9094 			if (fire != NULL) {
9095 				ire_refrele(fire);
9096 				fire = NULL;
9097 			}
9098 
9099 			/*
9100 			 * the resolution loop is re-entered if this
9101 			 * was requested through flags and if we
9102 			 * actually are in a multirouting case.
9103 			 */
9104 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9105 				boolean_t need_resolve =
9106 				    ire_multirt_need_resolve(ipha_dst,
9107 					MBLK_GETLABEL(copy_mp));
9108 				if (!need_resolve) {
9109 					MULTIRT_DEBUG_UNTAG(copy_mp);
9110 					freemsg(copy_mp);
9111 					copy_mp = NULL;
9112 				} else {
9113 					/*
9114 					 * ipif_lookup_group() calls
9115 					 * ire_lookup_multi() that uses
9116 					 * ire_ftable_lookup() to find
9117 					 * an IRE_INTERFACE for the group.
9118 					 * In the multirt case,
9119 					 * ire_lookup_multi() then invokes
9120 					 * ire_multirt_lookup() to find
9121 					 * the next resolvable ire.
9122 					 * As a result, we obtain an new
9123 					 * interface, derived from the
9124 					 * next ire.
9125 					 */
9126 					ipif_refrele(ipif);
9127 					ipif = ipif_lookup_group(ipha_dst,
9128 					    zoneid);
9129 					ip2dbg(("ip_newroute_ipif: "
9130 					    "multirt dst %08x, ipif %p\n",
9131 					    htonl(dst), (void *)ipif));
9132 					if (ipif != NULL) {
9133 						mp = copy_mp;
9134 						copy_mp = NULL;
9135 						multirt_resolve_next = B_TRUE;
9136 						continue;
9137 					} else {
9138 						freemsg(copy_mp);
9139 					}
9140 				}
9141 			}
9142 			if (ipif != NULL)
9143 				ipif_refrele(ipif);
9144 			ill_refrele(dst_ill);
9145 			ipif_refrele(src_ipif);
9146 			return;
9147 		}
9148 		case IRE_IF_RESOLVER:
9149 			/*
9150 			 * We can't build an IRE_CACHE yet, but at least
9151 			 * we found a resolver that can help.
9152 			 */
9153 			res_mp = dst_ill->ill_resolver_mp;
9154 			if (!OK_RESOLVER_MP(res_mp))
9155 				break;
9156 
9157 			/*
9158 			 * We obtain a partial IRE_CACHE which we will pass
9159 			 * along with the resolver query.  When the response
9160 			 * comes back it will be there ready for us to add.
9161 			 * The new ire inherits the IRE_OFFSUBNET flags
9162 			 * and source address, if this was requested.
9163 			 * The ire_max_frag is atomically set under the
9164 			 * irebucket lock in ire_add_v[46]. Only in the
9165 			 * case of IRE_MARK_NOADD, we set it here itself.
9166 			 */
9167 			ire = ire_create_mp(
9168 			    (uchar_t *)&dst,		/* dest address */
9169 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9170 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9171 			    NULL,			/* gateway address */
9172 			    NULL,			/* no in_src_addr */
9173 			    (ire_marks & IRE_MARK_NOADD) ?
9174 				ipif->ipif_mtu : 0,	/* max_frag */
9175 			    NULL,			/* Fast path header */
9176 			    dst_ill->ill_rq,		/* recv-from queue */
9177 			    dst_ill->ill_wq,		/* send-to queue */
9178 			    IRE_CACHE,
9179 			    NULL,	/* let ire_nce_init figure res_mp out */
9180 			    src_ipif,
9181 			    NULL,
9182 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9183 			    (fire != NULL) ?		/* Parent handle */
9184 				fire->ire_phandle : 0,
9185 			    ihandle,			/* Interface handle */
9186 			    (fire != NULL) ?		/* flags if any */
9187 				(fire->ire_flags &
9188 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9189 			    (save_ire == NULL ? &ire_uinfo_null :
9190 				&save_ire->ire_uinfo),
9191 			    NULL,
9192 			    NULL);
9193 
9194 			if (save_ire != NULL) {
9195 				ire_refrele(save_ire);
9196 				save_ire = NULL;
9197 			}
9198 			if (ire == NULL)
9199 				break;
9200 
9201 			ire->ire_marks |= ire_marks;
9202 			/*
9203 			 * Construct message chain for the resolver of the
9204 			 * form:
9205 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9206 			 *
9207 			 * NOTE : ire will be added later when the response
9208 			 * comes back from ARP. If the response does not
9209 			 * come back, ARP frees the packet. For this reason,
9210 			 * we can't REFHOLD the bucket of save_ire to prevent
9211 			 * deletions. We may not be able to REFRELE the
9212 			 * bucket if the response never comes back.
9213 			 * Thus, before adding the ire, ire_add_v4 will make
9214 			 * sure that the interface route does not get deleted.
9215 			 * This is the only case unlike ip_newroute_v6,
9216 			 * ip_newroute_ipif_v6 where we can always prevent
9217 			 * deletions because ire_add_then_send is called after
9218 			 * creating the IRE.
9219 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9220 			 * does not add this IRE into the IRE CACHE.
9221 			 */
9222 			ASSERT(ire->ire_mp != NULL);
9223 			ire->ire_mp->b_cont = first_mp;
9224 			/* Have saved_mp handy, for cleanup if canput fails */
9225 			saved_mp = mp;
9226 			mp = copyb(res_mp);
9227 			ASSERT(mp != NULL);
9228 			linkb(mp, ire->ire_mp);
9229 
9230 			/*
9231 			 * Fill in the source and dest addrs for the resolver.
9232 			 * NOTE: this depends on memory layouts imposed by
9233 			 * ill_init().
9234 			 */
9235 			areq = (areq_t *)mp->b_rptr;
9236 			addrp = (ipaddr_t *)((char *)areq +
9237 			    areq->areq_sender_addr_offset);
9238 			*addrp = ire->ire_src_addr;
9239 			addrp = (ipaddr_t *)((char *)areq +
9240 			    areq->areq_target_addr_offset);
9241 			*addrp = dst;
9242 			/* Up to the resolver. */
9243 			if (canputnext(dst_ill->ill_rq) &&
9244 			    !(dst_ill->ill_arp_closing)) {
9245 				putnext(dst_ill->ill_rq, mp);
9246 				/*
9247 				 * The response will come back in ip_wput
9248 				 * with db_type IRE_DB_TYPE.
9249 				 */
9250 			} else {
9251 				mp->b_cont = NULL;
9252 				freeb(mp); /* areq */
9253 				ire_delete(ire); /* ire_mp */
9254 				saved_mp->b_next = NULL;
9255 				saved_mp->b_prev = NULL;
9256 				freemsg(first_mp); /* pkt */
9257 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9258 			}
9259 
9260 			if (fire != NULL) {
9261 				ire_refrele(fire);
9262 				fire = NULL;
9263 			}
9264 
9265 
9266 			/*
9267 			 * The resolution loop is re-entered if this was
9268 			 * requested through flags and we actually are
9269 			 * in a multirouting case.
9270 			 */
9271 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9272 				boolean_t need_resolve =
9273 				    ire_multirt_need_resolve(ipha_dst,
9274 					MBLK_GETLABEL(copy_mp));
9275 				if (!need_resolve) {
9276 					MULTIRT_DEBUG_UNTAG(copy_mp);
9277 					freemsg(copy_mp);
9278 					copy_mp = NULL;
9279 				} else {
9280 					/*
9281 					 * ipif_lookup_group() calls
9282 					 * ire_lookup_multi() that uses
9283 					 * ire_ftable_lookup() to find
9284 					 * an IRE_INTERFACE for the group.
9285 					 * In the multirt case,
9286 					 * ire_lookup_multi() then invokes
9287 					 * ire_multirt_lookup() to find
9288 					 * the next resolvable ire.
9289 					 * As a result, we obtain an new
9290 					 * interface, derived from the
9291 					 * next ire.
9292 					 */
9293 					ipif_refrele(ipif);
9294 					ipif = ipif_lookup_group(ipha_dst,
9295 					    zoneid);
9296 					if (ipif != NULL) {
9297 						mp = copy_mp;
9298 						copy_mp = NULL;
9299 						multirt_resolve_next = B_TRUE;
9300 						continue;
9301 					} else {
9302 						freemsg(copy_mp);
9303 					}
9304 				}
9305 			}
9306 			if (ipif != NULL)
9307 				ipif_refrele(ipif);
9308 			ill_refrele(dst_ill);
9309 			ipif_refrele(src_ipif);
9310 			return;
9311 		default:
9312 			break;
9313 		}
9314 	} while (multirt_resolve_next);
9315 
9316 err_ret:
9317 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9318 	if (fire != NULL)
9319 		ire_refrele(fire);
9320 	ipif_refrele(ipif);
9321 	/* Did this packet originate externally? */
9322 	if (dst_ill != NULL)
9323 		ill_refrele(dst_ill);
9324 	if (src_ipif != NULL)
9325 		ipif_refrele(src_ipif);
9326 	if (mp->b_prev || mp->b_next) {
9327 		mp->b_next = NULL;
9328 		mp->b_prev = NULL;
9329 	} else {
9330 		/*
9331 		 * Since ip_wput() isn't close to finished, we fill
9332 		 * in enough of the header for credible error reporting.
9333 		 */
9334 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9335 			/* Failed */
9336 			freemsg(first_mp);
9337 			if (ire != NULL)
9338 				ire_refrele(ire);
9339 			return;
9340 		}
9341 	}
9342 	/*
9343 	 * At this point we will have ire only if RTF_BLACKHOLE
9344 	 * or RTF_REJECT flags are set on the IRE. It will not
9345 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9346 	 */
9347 	if (ire != NULL) {
9348 		if (ire->ire_flags & RTF_BLACKHOLE) {
9349 			ire_refrele(ire);
9350 			freemsg(first_mp);
9351 			return;
9352 		}
9353 		ire_refrele(ire);
9354 	}
9355 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
9356 }
9357 
9358 /* Name/Value Table Lookup Routine */
9359 char *
9360 ip_nv_lookup(nv_t *nv, int value)
9361 {
9362 	if (!nv)
9363 		return (NULL);
9364 	for (; nv->nv_name; nv++) {
9365 		if (nv->nv_value == value)
9366 			return (nv->nv_name);
9367 	}
9368 	return ("unknown");
9369 }
9370 
9371 /*
9372  * one day it can be patched to 1 from /etc/system for machines that have few
9373  * fast network interfaces feeding multiple cpus.
9374  */
9375 int ill_stream_putlocks = 0;
9376 
9377 /*
9378  * This is a module open, i.e. this is a control stream for access
9379  * to a DLPI device.  We allocate an ill_t as the instance data in
9380  * this case.
9381  */
9382 int
9383 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9384 {
9385 	uint32_t mem_cnt;
9386 	uint32_t cpu_cnt;
9387 	uint32_t min_cnt;
9388 	pgcnt_t mem_avail;
9389 	ill_t	*ill;
9390 	int	err;
9391 
9392 	/*
9393 	 * Prevent unprivileged processes from pushing IP so that
9394 	 * they can't send raw IP.
9395 	 */
9396 	if (secpolicy_net_rawaccess(credp) != 0)
9397 		return (EPERM);
9398 
9399 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9400 	q->q_ptr = WR(q)->q_ptr = ill;
9401 
9402 	/*
9403 	 * ill_init initializes the ill fields and then sends down
9404 	 * down a DL_INFO_REQ after calling qprocson.
9405 	 */
9406 	err = ill_init(q, ill);
9407 	if (err != 0) {
9408 		mi_free(ill);
9409 		q->q_ptr = NULL;
9410 		WR(q)->q_ptr = NULL;
9411 		return (err);
9412 	}
9413 
9414 	/* ill_init initializes the ipsq marking this thread as writer */
9415 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9416 	/* Wait for the DL_INFO_ACK */
9417 	mutex_enter(&ill->ill_lock);
9418 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9419 		/*
9420 		 * Return value of 0 indicates a pending signal.
9421 		 */
9422 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9423 		if (err == 0) {
9424 			mutex_exit(&ill->ill_lock);
9425 			(void) ip_close(q, 0);
9426 			return (EINTR);
9427 		}
9428 	}
9429 	mutex_exit(&ill->ill_lock);
9430 
9431 	/*
9432 	 * ip_rput_other could have set an error  in ill_error on
9433 	 * receipt of M_ERROR.
9434 	 */
9435 
9436 	err = ill->ill_error;
9437 	if (err != 0) {
9438 		(void) ip_close(q, 0);
9439 		return (err);
9440 	}
9441 
9442 	/*
9443 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9444 	 * size and the cpu speed of the machine. This is upper
9445 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9446 	 * and is lower bounded by the compile time value of
9447 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9448 	 * ip6_ire_max_bucket_cnt.
9449 	 */
9450 	mem_avail = kmem_avail();
9451 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9452 	    ip_cache_table_size / sizeof (ire_t);
9453 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9454 
9455 	min_cnt = MIN(cpu_cnt, mem_cnt);
9456 	if (min_cnt < ip_ire_min_bucket_cnt)
9457 		min_cnt = ip_ire_min_bucket_cnt;
9458 	if (ip_ire_max_bucket_cnt > min_cnt) {
9459 		ip_ire_max_bucket_cnt = min_cnt;
9460 	}
9461 
9462 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9463 	    ip6_cache_table_size / sizeof (ire_t);
9464 	min_cnt = MIN(cpu_cnt, mem_cnt);
9465 	if (min_cnt < ip6_ire_min_bucket_cnt)
9466 		min_cnt = ip6_ire_min_bucket_cnt;
9467 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9468 		ip6_ire_max_bucket_cnt = min_cnt;
9469 	}
9470 
9471 	ill->ill_credp = credp;
9472 	crhold(credp);
9473 
9474 	mutex_enter(&ip_mi_lock);
9475 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9476 	mutex_exit(&ip_mi_lock);
9477 	if (err) {
9478 		(void) ip_close(q, 0);
9479 		return (err);
9480 	}
9481 	return (0);
9482 }
9483 
9484 /* IP open routine. */
9485 int
9486 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9487 {
9488 	conn_t 		*connp;
9489 	major_t		maj;
9490 
9491 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9492 
9493 	/* Allow reopen. */
9494 	if (q->q_ptr != NULL)
9495 		return (0);
9496 
9497 	if (sflag & MODOPEN) {
9498 		/* This is a module open */
9499 		return (ip_modopen(q, devp, flag, sflag, credp));
9500 	}
9501 
9502 	/*
9503 	 * We are opening as a device. This is an IP client stream, and we
9504 	 * allocate an conn_t as the instance data.
9505 	 */
9506 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9507 	connp->conn_upq = q;
9508 	q->q_ptr = WR(q)->q_ptr = connp;
9509 
9510 	if (flag & SO_SOCKSTR)
9511 		connp->conn_flags |= IPCL_SOCKET;
9512 
9513 	/* Minor tells us which /dev entry was opened */
9514 	if (geteminor(*devp) == IPV6_MINOR) {
9515 		connp->conn_flags |= IPCL_ISV6;
9516 		connp->conn_af_isv6 = B_TRUE;
9517 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9518 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9519 	} else {
9520 		connp->conn_af_isv6 = B_FALSE;
9521 		connp->conn_pkt_isv6 = B_FALSE;
9522 	}
9523 
9524 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9525 		q->q_ptr = WR(q)->q_ptr = NULL;
9526 		CONN_DEC_REF(connp);
9527 		return (EBUSY);
9528 	}
9529 
9530 	maj = getemajor(*devp);
9531 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9532 
9533 	/*
9534 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9535 	 */
9536 	connp->conn_cred = credp;
9537 	crhold(connp->conn_cred);
9538 
9539 	/*
9540 	 * If the caller has the process-wide flag set, then default to MAC
9541 	 * exempt mode.  This allows read-down to unlabeled hosts.
9542 	 */
9543 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9544 		connp->conn_mac_exempt = B_TRUE;
9545 
9546 	connp->conn_zoneid = getzoneid();
9547 
9548 	/*
9549 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9550 	 * administrative ops.  In these cases, we just need a normal conn_t
9551 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9552 	 * an error will be returned.
9553 	 */
9554 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9555 		connp->conn_rq = q;
9556 		connp->conn_wq = WR(q);
9557 	} else {
9558 		connp->conn_ulp = IPPROTO_SCTP;
9559 		connp->conn_rq = connp->conn_wq = NULL;
9560 	}
9561 	/* Non-zero default values */
9562 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9563 
9564 	/*
9565 	 * Make the conn globally visible to walkers
9566 	 */
9567 	mutex_enter(&connp->conn_lock);
9568 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9569 	mutex_exit(&connp->conn_lock);
9570 	ASSERT(connp->conn_ref == 1);
9571 
9572 	qprocson(q);
9573 
9574 	return (0);
9575 }
9576 
9577 /*
9578  * Change q_qinfo based on the value of isv6.
9579  * This can not called on an ill queue.
9580  * Note that there is no race since either q_qinfo works for conn queues - it
9581  * is just an optimization to enter the best wput routine directly.
9582  */
9583 void
9584 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9585 {
9586 	ASSERT(q->q_flag & QREADR);
9587 	ASSERT(WR(q)->q_next == NULL);
9588 	ASSERT(q->q_ptr != NULL);
9589 
9590 	if (minor == IPV6_MINOR)  {
9591 		if (bump_mib)
9592 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9593 		q->q_qinfo = &rinit_ipv6;
9594 		WR(q)->q_qinfo = &winit_ipv6;
9595 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9596 	} else {
9597 		if (bump_mib)
9598 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9599 		q->q_qinfo = &iprinit;
9600 		WR(q)->q_qinfo = &ipwinit;
9601 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9602 	}
9603 
9604 }
9605 
9606 /*
9607  * See if IPsec needs loading because of the options in mp.
9608  */
9609 static boolean_t
9610 ipsec_opt_present(mblk_t *mp)
9611 {
9612 	uint8_t *optcp, *next_optcp, *opt_endcp;
9613 	struct opthdr *opt;
9614 	struct T_opthdr *topt;
9615 	int opthdr_len;
9616 	t_uscalar_t optname, optlevel;
9617 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9618 	ipsec_req_t *ipsr;
9619 
9620 	/*
9621 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9622 	 * return TRUE.
9623 	 */
9624 
9625 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9626 	opt_endcp = optcp + tor->OPT_length;
9627 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9628 		opthdr_len = sizeof (struct T_opthdr);
9629 	} else {		/* O_OPTMGMT_REQ */
9630 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9631 		opthdr_len = sizeof (struct opthdr);
9632 	}
9633 	for (; optcp < opt_endcp; optcp = next_optcp) {
9634 		if (optcp + opthdr_len > opt_endcp)
9635 			return (B_FALSE);	/* Not enough option header. */
9636 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9637 			topt = (struct T_opthdr *)optcp;
9638 			optlevel = topt->level;
9639 			optname = topt->name;
9640 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9641 		} else {
9642 			opt = (struct opthdr *)optcp;
9643 			optlevel = opt->level;
9644 			optname = opt->name;
9645 			next_optcp = optcp + opthdr_len +
9646 			    _TPI_ALIGN_OPT(opt->len);
9647 		}
9648 		if ((next_optcp < optcp) || /* wraparound pointer space */
9649 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9650 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9651 			return (B_FALSE); /* bad option buffer */
9652 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9653 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9654 			/*
9655 			 * Check to see if it's an all-bypass or all-zeroes
9656 			 * IPsec request.  Don't bother loading IPsec if
9657 			 * the socket doesn't want to use it.  (A good example
9658 			 * is a bypass request.)
9659 			 *
9660 			 * Basically, if any of the non-NEVER bits are set,
9661 			 * load IPsec.
9662 			 */
9663 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9664 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9665 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9666 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9667 			    != 0)
9668 				return (B_TRUE);
9669 		}
9670 	}
9671 	return (B_FALSE);
9672 }
9673 
9674 /*
9675  * If conn is is waiting for ipsec to finish loading, kick it.
9676  */
9677 /* ARGSUSED */
9678 static void
9679 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9680 {
9681 	t_scalar_t	optreq_prim;
9682 	mblk_t		*mp;
9683 	cred_t		*cr;
9684 	int		err = 0;
9685 
9686 	/*
9687 	 * This function is called, after ipsec loading is complete.
9688 	 * Since IP checks exclusively and atomically (i.e it prevents
9689 	 * ipsec load from completing until ip_optcom_req completes)
9690 	 * whether ipsec load is complete, there cannot be a race with IP
9691 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9692 	 */
9693 	mutex_enter(&connp->conn_lock);
9694 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9695 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9696 		mp = connp->conn_ipsec_opt_mp;
9697 		connp->conn_ipsec_opt_mp = NULL;
9698 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9699 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9700 		mutex_exit(&connp->conn_lock);
9701 
9702 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9703 
9704 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9705 		if (optreq_prim == T_OPTMGMT_REQ) {
9706 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9707 			    &ip_opt_obj);
9708 		} else {
9709 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9710 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9711 			    &ip_opt_obj);
9712 		}
9713 		if (err != EINPROGRESS)
9714 			CONN_OPER_PENDING_DONE(connp);
9715 		return;
9716 	}
9717 	mutex_exit(&connp->conn_lock);
9718 }
9719 
9720 /*
9721  * Called from the ipsec_loader thread, outside any perimeter, to tell
9722  * ip qenable any of the queues waiting for the ipsec loader to
9723  * complete.
9724  *
9725  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9726  * are done with this lock held, so it's guaranteed that none of the
9727  * links will change along the way.
9728  */
9729 void
9730 ip_ipsec_load_complete()
9731 {
9732 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9733 }
9734 
9735 /*
9736  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9737  * determines the grp on which it has to become exclusive, queues the mp
9738  * and sq draining restarts the optmgmt
9739  */
9740 static boolean_t
9741 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9742 {
9743 	conn_t *connp;
9744 
9745 	/*
9746 	 * Take IPsec requests and treat them special.
9747 	 */
9748 	if (ipsec_opt_present(mp)) {
9749 		/* First check if IPsec is loaded. */
9750 		mutex_enter(&ipsec_loader_lock);
9751 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9752 			mutex_exit(&ipsec_loader_lock);
9753 			return (B_FALSE);
9754 		}
9755 		connp = Q_TO_CONN(q);
9756 		mutex_enter(&connp->conn_lock);
9757 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9758 
9759 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9760 		connp->conn_ipsec_opt_mp = mp;
9761 		mutex_exit(&connp->conn_lock);
9762 		mutex_exit(&ipsec_loader_lock);
9763 
9764 		ipsec_loader_loadnow();
9765 		return (B_TRUE);
9766 	}
9767 	return (B_FALSE);
9768 }
9769 
9770 /*
9771  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9772  * all of them are copied to the conn_t. If the req is "zero", the policy is
9773  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9774  * fields.
9775  * We keep only the latest setting of the policy and thus policy setting
9776  * is not incremental/cumulative.
9777  *
9778  * Requests to set policies with multiple alternative actions will
9779  * go through a different API.
9780  */
9781 int
9782 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9783 {
9784 	uint_t ah_req = 0;
9785 	uint_t esp_req = 0;
9786 	uint_t se_req = 0;
9787 	ipsec_selkey_t sel;
9788 	ipsec_act_t *actp = NULL;
9789 	uint_t nact;
9790 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9791 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9792 	ipsec_policy_root_t *pr;
9793 	ipsec_policy_head_t *ph;
9794 	int fam;
9795 	boolean_t is_pol_reset;
9796 	int error = 0;
9797 
9798 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9799 
9800 	/*
9801 	 * The IP_SEC_OPT option does not allow variable length parameters,
9802 	 * hence a request cannot be NULL.
9803 	 */
9804 	if (req == NULL)
9805 		return (EINVAL);
9806 
9807 	ah_req = req->ipsr_ah_req;
9808 	esp_req = req->ipsr_esp_req;
9809 	se_req = req->ipsr_self_encap_req;
9810 
9811 	/*
9812 	 * Are we dealing with a request to reset the policy (i.e.
9813 	 * zero requests).
9814 	 */
9815 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9816 	    (esp_req & REQ_MASK) == 0 &&
9817 	    (se_req & REQ_MASK) == 0);
9818 
9819 	if (!is_pol_reset) {
9820 		/*
9821 		 * If we couldn't load IPsec, fail with "protocol
9822 		 * not supported".
9823 		 * IPsec may not have been loaded for a request with zero
9824 		 * policies, so we don't fail in this case.
9825 		 */
9826 		mutex_enter(&ipsec_loader_lock);
9827 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9828 			mutex_exit(&ipsec_loader_lock);
9829 			return (EPROTONOSUPPORT);
9830 		}
9831 		mutex_exit(&ipsec_loader_lock);
9832 
9833 		/*
9834 		 * Test for valid requests. Invalid algorithms
9835 		 * need to be tested by IPSEC code because new
9836 		 * algorithms can be added dynamically.
9837 		 */
9838 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9839 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9840 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9841 			return (EINVAL);
9842 		}
9843 
9844 		/*
9845 		 * Only privileged users can issue these
9846 		 * requests.
9847 		 */
9848 		if (((ah_req & IPSEC_PREF_NEVER) ||
9849 		    (esp_req & IPSEC_PREF_NEVER) ||
9850 		    (se_req & IPSEC_PREF_NEVER)) &&
9851 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9852 			return (EPERM);
9853 		}
9854 
9855 		/*
9856 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9857 		 * are mutually exclusive.
9858 		 */
9859 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9860 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9861 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9862 			/* Both of them are set */
9863 			return (EINVAL);
9864 		}
9865 	}
9866 
9867 	mutex_enter(&connp->conn_lock);
9868 
9869 	/*
9870 	 * If we have already cached policies in ip_bind_connected*(), don't
9871 	 * let them change now. We cache policies for connections
9872 	 * whose src,dst [addr, port] is known.  The exception to this is
9873 	 * tunnels.  Tunnels are allowed to change policies after having
9874 	 * become fully bound.
9875 	 */
9876 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
9877 		mutex_exit(&connp->conn_lock);
9878 		return (EINVAL);
9879 	}
9880 
9881 	/*
9882 	 * We have a zero policies, reset the connection policy if already
9883 	 * set. This will cause the connection to inherit the
9884 	 * global policy, if any.
9885 	 */
9886 	if (is_pol_reset) {
9887 		if (connp->conn_policy != NULL) {
9888 			IPPH_REFRELE(connp->conn_policy);
9889 			connp->conn_policy = NULL;
9890 		}
9891 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
9892 		connp->conn_in_enforce_policy = B_FALSE;
9893 		connp->conn_out_enforce_policy = B_FALSE;
9894 		mutex_exit(&connp->conn_lock);
9895 		return (0);
9896 	}
9897 
9898 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
9899 	if (ph == NULL)
9900 		goto enomem;
9901 
9902 	ipsec_actvec_from_req(req, &actp, &nact);
9903 	if (actp == NULL)
9904 		goto enomem;
9905 
9906 	/*
9907 	 * Always allocate IPv4 policy entries, since they can also
9908 	 * apply to ipv6 sockets being used in ipv4-compat mode.
9909 	 */
9910 	bzero(&sel, sizeof (sel));
9911 	sel.ipsl_valid = IPSL_IPV4;
9912 
9913 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9914 	if (pin4 == NULL)
9915 		goto enomem;
9916 
9917 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9918 	if (pout4 == NULL)
9919 		goto enomem;
9920 
9921 	if (connp->conn_pkt_isv6) {
9922 		/*
9923 		 * We're looking at a v6 socket, also allocate the
9924 		 * v6-specific entries...
9925 		 */
9926 		sel.ipsl_valid = IPSL_IPV6;
9927 		pin6 = ipsec_policy_create(&sel, actp, nact,
9928 		    IPSEC_PRIO_SOCKET);
9929 		if (pin6 == NULL)
9930 			goto enomem;
9931 
9932 		pout6 = ipsec_policy_create(&sel, actp, nact,
9933 		    IPSEC_PRIO_SOCKET);
9934 		if (pout6 == NULL)
9935 			goto enomem;
9936 
9937 		/*
9938 		 * .. and file them away in the right place.
9939 		 */
9940 		fam = IPSEC_AF_V6;
9941 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9942 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
9943 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
9944 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9945 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
9946 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
9947 	}
9948 
9949 	ipsec_actvec_free(actp, nact);
9950 
9951 	/*
9952 	 * File the v4 policies.
9953 	 */
9954 	fam = IPSEC_AF_V4;
9955 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9956 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
9957 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
9958 
9959 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9960 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
9961 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
9962 
9963 	/*
9964 	 * If the requests need security, set enforce_policy.
9965 	 * If the requests are IPSEC_PREF_NEVER, one should
9966 	 * still set conn_out_enforce_policy so that an ipsec_out
9967 	 * gets attached in ip_wput. This is needed so that
9968 	 * for connections that we don't cache policy in ip_bind,
9969 	 * if global policy matches in ip_wput_attach_policy, we
9970 	 * don't wrongly inherit global policy. Similarly, we need
9971 	 * to set conn_in_enforce_policy also so that we don't verify
9972 	 * policy wrongly.
9973 	 */
9974 	if ((ah_req & REQ_MASK) != 0 ||
9975 	    (esp_req & REQ_MASK) != 0 ||
9976 	    (se_req & REQ_MASK) != 0) {
9977 		connp->conn_in_enforce_policy = B_TRUE;
9978 		connp->conn_out_enforce_policy = B_TRUE;
9979 		connp->conn_flags |= IPCL_CHECK_POLICY;
9980 	}
9981 
9982 	/*
9983 	 * Tunnels are allowed to set policy after having been fully bound.
9984 	 * If that's the case, cache policy here.
9985 	 */
9986 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
9987 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
9988 
9989 	mutex_exit(&connp->conn_lock);
9990 	return (error);
9991 #undef REQ_MASK
9992 
9993 	/*
9994 	 * Common memory-allocation-failure exit path.
9995 	 */
9996 enomem:
9997 	mutex_exit(&connp->conn_lock);
9998 	if (actp != NULL)
9999 		ipsec_actvec_free(actp, nact);
10000 	if (pin4 != NULL)
10001 		IPPOL_REFRELE(pin4);
10002 	if (pout4 != NULL)
10003 		IPPOL_REFRELE(pout4);
10004 	if (pin6 != NULL)
10005 		IPPOL_REFRELE(pin6);
10006 	if (pout6 != NULL)
10007 		IPPOL_REFRELE(pout6);
10008 	return (ENOMEM);
10009 }
10010 
10011 /*
10012  * Only for options that pass in an IP addr. Currently only V4 options
10013  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10014  * So this function assumes level is IPPROTO_IP
10015  */
10016 int
10017 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10018     mblk_t *first_mp)
10019 {
10020 	ipif_t *ipif = NULL;
10021 	int error;
10022 	ill_t *ill;
10023 	int zoneid;
10024 
10025 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10026 
10027 	if (addr != INADDR_ANY || checkonly) {
10028 		ASSERT(connp != NULL);
10029 		zoneid = IPCL_ZONEID(connp);
10030 		if (option == IP_NEXTHOP) {
10031 			ipif = ipif_lookup_onlink_addr(addr, zoneid);
10032 		} else {
10033 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10034 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10035 			    &error);
10036 		}
10037 		if (ipif == NULL) {
10038 			if (error == EINPROGRESS)
10039 				return (error);
10040 			else if ((option == IP_MULTICAST_IF) ||
10041 			    (option == IP_NEXTHOP))
10042 				return (EHOSTUNREACH);
10043 			else
10044 				return (EINVAL);
10045 		} else if (checkonly) {
10046 			if (option == IP_MULTICAST_IF) {
10047 				ill = ipif->ipif_ill;
10048 				/* not supported by the virtual network iface */
10049 				if (IS_VNI(ill)) {
10050 					ipif_refrele(ipif);
10051 					return (EINVAL);
10052 				}
10053 			}
10054 			ipif_refrele(ipif);
10055 			return (0);
10056 		}
10057 		ill = ipif->ipif_ill;
10058 		mutex_enter(&connp->conn_lock);
10059 		mutex_enter(&ill->ill_lock);
10060 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10061 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10062 			mutex_exit(&ill->ill_lock);
10063 			mutex_exit(&connp->conn_lock);
10064 			ipif_refrele(ipif);
10065 			return (option == IP_MULTICAST_IF ?
10066 			    EHOSTUNREACH : EINVAL);
10067 		}
10068 	} else {
10069 		mutex_enter(&connp->conn_lock);
10070 	}
10071 
10072 	/* None of the options below are supported on the VNI */
10073 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10074 		mutex_exit(&ill->ill_lock);
10075 		mutex_exit(&connp->conn_lock);
10076 		ipif_refrele(ipif);
10077 		return (EINVAL);
10078 	}
10079 
10080 	switch (option) {
10081 	case IP_DONTFAILOVER_IF:
10082 		/*
10083 		 * This option is used by in.mpathd to ensure
10084 		 * that IPMP probe packets only go out on the
10085 		 * test interfaces. in.mpathd sets this option
10086 		 * on the non-failover interfaces.
10087 		 * For backward compatibility, this option
10088 		 * implicitly sets IP_MULTICAST_IF, as used
10089 		 * be done in bind(), so that ip_wput gets
10090 		 * this ipif to send mcast packets.
10091 		 */
10092 		if (ipif != NULL) {
10093 			ASSERT(addr != INADDR_ANY);
10094 			connp->conn_nofailover_ill = ipif->ipif_ill;
10095 			connp->conn_multicast_ipif = ipif;
10096 		} else {
10097 			ASSERT(addr == INADDR_ANY);
10098 			connp->conn_nofailover_ill = NULL;
10099 			connp->conn_multicast_ipif = NULL;
10100 		}
10101 		break;
10102 
10103 	case IP_MULTICAST_IF:
10104 		connp->conn_multicast_ipif = ipif;
10105 		break;
10106 	case IP_NEXTHOP:
10107 		connp->conn_nexthop_v4 = addr;
10108 		connp->conn_nexthop_set = B_TRUE;
10109 		break;
10110 	}
10111 
10112 	if (ipif != NULL) {
10113 		mutex_exit(&ill->ill_lock);
10114 		mutex_exit(&connp->conn_lock);
10115 		ipif_refrele(ipif);
10116 		return (0);
10117 	}
10118 	mutex_exit(&connp->conn_lock);
10119 	/* We succeded in cleared the option */
10120 	return (0);
10121 }
10122 
10123 /*
10124  * For options that pass in an ifindex specifying the ill. V6 options always
10125  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10126  */
10127 int
10128 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10129     int level, int option, mblk_t *first_mp)
10130 {
10131 	ill_t *ill = NULL;
10132 	int error = 0;
10133 
10134 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10135 	if (ifindex != 0) {
10136 		ASSERT(connp != NULL);
10137 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10138 		    first_mp, ip_restart_optmgmt, &error);
10139 		if (ill != NULL) {
10140 			if (checkonly) {
10141 				/* not supported by the virtual network iface */
10142 				if (IS_VNI(ill)) {
10143 					ill_refrele(ill);
10144 					return (EINVAL);
10145 				}
10146 				ill_refrele(ill);
10147 				return (0);
10148 			}
10149 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10150 			    0, NULL)) {
10151 				ill_refrele(ill);
10152 				ill = NULL;
10153 				mutex_enter(&connp->conn_lock);
10154 				goto setit;
10155 			}
10156 			mutex_enter(&connp->conn_lock);
10157 			mutex_enter(&ill->ill_lock);
10158 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10159 				mutex_exit(&ill->ill_lock);
10160 				mutex_exit(&connp->conn_lock);
10161 				ill_refrele(ill);
10162 				ill = NULL;
10163 				mutex_enter(&connp->conn_lock);
10164 			}
10165 			goto setit;
10166 		} else if (error == EINPROGRESS) {
10167 			return (error);
10168 		} else {
10169 			error = 0;
10170 		}
10171 	}
10172 	mutex_enter(&connp->conn_lock);
10173 setit:
10174 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10175 
10176 	/*
10177 	 * The options below assume that the ILL (if any) transmits and/or
10178 	 * receives traffic. Neither of which is true for the virtual network
10179 	 * interface, so fail setting these on a VNI.
10180 	 */
10181 	if (IS_VNI(ill)) {
10182 		ASSERT(ill != NULL);
10183 		mutex_exit(&ill->ill_lock);
10184 		mutex_exit(&connp->conn_lock);
10185 		ill_refrele(ill);
10186 		return (EINVAL);
10187 	}
10188 
10189 	if (level == IPPROTO_IP) {
10190 		switch (option) {
10191 		case IP_BOUND_IF:
10192 			connp->conn_incoming_ill = ill;
10193 			connp->conn_outgoing_ill = ill;
10194 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10195 			    0 : ifindex;
10196 			break;
10197 
10198 		case IP_XMIT_IF:
10199 			/*
10200 			 * Similar to IP_BOUND_IF, but this only
10201 			 * determines the outgoing interface for
10202 			 * unicast packets. Also no IRE_CACHE entry
10203 			 * is added for the destination of the
10204 			 * outgoing packets. This feature is needed
10205 			 * for mobile IP.
10206 			 */
10207 			connp->conn_xmit_if_ill = ill;
10208 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10209 			    0 : ifindex;
10210 			break;
10211 
10212 		case IP_MULTICAST_IF:
10213 			/*
10214 			 * This option is an internal special. The socket
10215 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10216 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10217 			 * specifies an ifindex and we try first on V6 ill's.
10218 			 * If we don't find one, we they try using on v4 ill's
10219 			 * intenally and we come here.
10220 			 */
10221 			if (!checkonly && ill != NULL) {
10222 				ipif_t	*ipif;
10223 				ipif = ill->ill_ipif;
10224 
10225 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10226 					mutex_exit(&ill->ill_lock);
10227 					mutex_exit(&connp->conn_lock);
10228 					ill_refrele(ill);
10229 					ill = NULL;
10230 					mutex_enter(&connp->conn_lock);
10231 				} else {
10232 					connp->conn_multicast_ipif = ipif;
10233 				}
10234 			}
10235 			break;
10236 		}
10237 	} else {
10238 		switch (option) {
10239 		case IPV6_BOUND_IF:
10240 			connp->conn_incoming_ill = ill;
10241 			connp->conn_outgoing_ill = ill;
10242 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10243 			    0 : ifindex;
10244 			break;
10245 
10246 		case IPV6_BOUND_PIF:
10247 			/*
10248 			 * Limit all transmit to this ill.
10249 			 * Unlike IPV6_BOUND_IF, using this option
10250 			 * prevents load spreading and failover from
10251 			 * happening when the interface is part of the
10252 			 * group. That's why we don't need to remember
10253 			 * the ifindex in orig_bound_ifindex as in
10254 			 * IPV6_BOUND_IF.
10255 			 */
10256 			connp->conn_outgoing_pill = ill;
10257 			break;
10258 
10259 		case IPV6_DONTFAILOVER_IF:
10260 			/*
10261 			 * This option is used by in.mpathd to ensure
10262 			 * that IPMP probe packets only go out on the
10263 			 * test interfaces. in.mpathd sets this option
10264 			 * on the non-failover interfaces.
10265 			 */
10266 			connp->conn_nofailover_ill = ill;
10267 			/*
10268 			 * For backward compatibility, this option
10269 			 * implicitly sets ip_multicast_ill as used in
10270 			 * IP_MULTICAST_IF so that ip_wput gets
10271 			 * this ipif to send mcast packets.
10272 			 */
10273 			connp->conn_multicast_ill = ill;
10274 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10275 			    0 : ifindex;
10276 			break;
10277 
10278 		case IPV6_MULTICAST_IF:
10279 			/*
10280 			 * Set conn_multicast_ill to be the IPv6 ill.
10281 			 * Set conn_multicast_ipif to be an IPv4 ipif
10282 			 * for ifindex to make IPv4 mapped addresses
10283 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10284 			 * Even if no IPv6 ill exists for the ifindex
10285 			 * we need to check for an IPv4 ifindex in order
10286 			 * for this to work with mapped addresses. In that
10287 			 * case only set conn_multicast_ipif.
10288 			 */
10289 			if (!checkonly) {
10290 				if (ifindex == 0) {
10291 					connp->conn_multicast_ill = NULL;
10292 					connp->conn_orig_multicast_ifindex = 0;
10293 					connp->conn_multicast_ipif = NULL;
10294 				} else if (ill != NULL) {
10295 					connp->conn_multicast_ill = ill;
10296 					connp->conn_orig_multicast_ifindex =
10297 					    ifindex;
10298 				}
10299 			}
10300 			break;
10301 		}
10302 	}
10303 
10304 	if (ill != NULL) {
10305 		mutex_exit(&ill->ill_lock);
10306 		mutex_exit(&connp->conn_lock);
10307 		ill_refrele(ill);
10308 		return (0);
10309 	}
10310 	mutex_exit(&connp->conn_lock);
10311 	/*
10312 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10313 	 * locate the ill and could not set the option (ifindex != 0)
10314 	 */
10315 	return (ifindex == 0 ? 0 : EINVAL);
10316 }
10317 
10318 /* This routine sets socket options. */
10319 /* ARGSUSED */
10320 int
10321 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10322     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10323     void *dummy, cred_t *cr, mblk_t *first_mp)
10324 {
10325 	int		*i1 = (int *)invalp;
10326 	conn_t		*connp = Q_TO_CONN(q);
10327 	int		error = 0;
10328 	boolean_t	checkonly;
10329 	ire_t		*ire;
10330 	boolean_t	found;
10331 
10332 	switch (optset_context) {
10333 
10334 	case SETFN_OPTCOM_CHECKONLY:
10335 		checkonly = B_TRUE;
10336 		/*
10337 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10338 		 * inlen != 0 implies value supplied and
10339 		 * 	we have to "pretend" to set it.
10340 		 * inlen == 0 implies that there is no
10341 		 * 	value part in T_CHECK request and just validation
10342 		 * done elsewhere should be enough, we just return here.
10343 		 */
10344 		if (inlen == 0) {
10345 			*outlenp = 0;
10346 			return (0);
10347 		}
10348 		break;
10349 	case SETFN_OPTCOM_NEGOTIATE:
10350 	case SETFN_UD_NEGOTIATE:
10351 	case SETFN_CONN_NEGOTIATE:
10352 		checkonly = B_FALSE;
10353 		break;
10354 	default:
10355 		/*
10356 		 * We should never get here
10357 		 */
10358 		*outlenp = 0;
10359 		return (EINVAL);
10360 	}
10361 
10362 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10363 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10364 
10365 	/*
10366 	 * For fixed length options, no sanity check
10367 	 * of passed in length is done. It is assumed *_optcom_req()
10368 	 * routines do the right thing.
10369 	 */
10370 
10371 	switch (level) {
10372 	case SOL_SOCKET:
10373 		/*
10374 		 * conn_lock protects the bitfields, and is used to
10375 		 * set the fields atomically.
10376 		 */
10377 		switch (name) {
10378 		case SO_BROADCAST:
10379 			if (!checkonly) {
10380 				/* TODO: use value someplace? */
10381 				mutex_enter(&connp->conn_lock);
10382 				connp->conn_broadcast = *i1 ? 1 : 0;
10383 				mutex_exit(&connp->conn_lock);
10384 			}
10385 			break;	/* goto sizeof (int) option return */
10386 		case SO_USELOOPBACK:
10387 			if (!checkonly) {
10388 				/* TODO: use value someplace? */
10389 				mutex_enter(&connp->conn_lock);
10390 				connp->conn_loopback = *i1 ? 1 : 0;
10391 				mutex_exit(&connp->conn_lock);
10392 			}
10393 			break;	/* goto sizeof (int) option return */
10394 		case SO_DONTROUTE:
10395 			if (!checkonly) {
10396 				mutex_enter(&connp->conn_lock);
10397 				connp->conn_dontroute = *i1 ? 1 : 0;
10398 				mutex_exit(&connp->conn_lock);
10399 			}
10400 			break;	/* goto sizeof (int) option return */
10401 		case SO_REUSEADDR:
10402 			if (!checkonly) {
10403 				mutex_enter(&connp->conn_lock);
10404 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10405 				mutex_exit(&connp->conn_lock);
10406 			}
10407 			break;	/* goto sizeof (int) option return */
10408 		case SO_PROTOTYPE:
10409 			if (!checkonly) {
10410 				mutex_enter(&connp->conn_lock);
10411 				connp->conn_proto = *i1;
10412 				mutex_exit(&connp->conn_lock);
10413 			}
10414 			break;	/* goto sizeof (int) option return */
10415 		case SO_ALLZONES:
10416 			if (!checkonly) {
10417 				mutex_enter(&connp->conn_lock);
10418 				if (IPCL_IS_BOUND(connp)) {
10419 					mutex_exit(&connp->conn_lock);
10420 					return (EINVAL);
10421 				}
10422 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10423 				mutex_exit(&connp->conn_lock);
10424 			}
10425 			break;	/* goto sizeof (int) option return */
10426 		case SO_ANON_MLP:
10427 			if (!checkonly) {
10428 				mutex_enter(&connp->conn_lock);
10429 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10430 				mutex_exit(&connp->conn_lock);
10431 			}
10432 			break;	/* goto sizeof (int) option return */
10433 		case SO_MAC_EXEMPT:
10434 			if (secpolicy_net_mac_aware(cr) != 0 ||
10435 			    IPCL_IS_BOUND(connp))
10436 				return (EACCES);
10437 			if (!checkonly) {
10438 				mutex_enter(&connp->conn_lock);
10439 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10440 				mutex_exit(&connp->conn_lock);
10441 			}
10442 			break;	/* goto sizeof (int) option return */
10443 		default:
10444 			/*
10445 			 * "soft" error (negative)
10446 			 * option not handled at this level
10447 			 * Note: Do not modify *outlenp
10448 			 */
10449 			return (-EINVAL);
10450 		}
10451 		break;
10452 	case IPPROTO_IP:
10453 		switch (name) {
10454 		case IP_NEXTHOP:
10455 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10456 				return (EPERM);
10457 			/* FALLTHRU */
10458 		case IP_MULTICAST_IF:
10459 		case IP_DONTFAILOVER_IF: {
10460 			ipaddr_t addr = *i1;
10461 
10462 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10463 			    first_mp);
10464 			if (error != 0)
10465 				return (error);
10466 			break;	/* goto sizeof (int) option return */
10467 		}
10468 
10469 		case IP_MULTICAST_TTL:
10470 			/* Recorded in transport above IP */
10471 			*outvalp = *invalp;
10472 			*outlenp = sizeof (uchar_t);
10473 			return (0);
10474 		case IP_MULTICAST_LOOP:
10475 			if (!checkonly) {
10476 				mutex_enter(&connp->conn_lock);
10477 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10478 				mutex_exit(&connp->conn_lock);
10479 			}
10480 			*outvalp = *invalp;
10481 			*outlenp = sizeof (uchar_t);
10482 			return (0);
10483 		case IP_ADD_MEMBERSHIP:
10484 		case MCAST_JOIN_GROUP:
10485 		case IP_DROP_MEMBERSHIP:
10486 		case MCAST_LEAVE_GROUP: {
10487 			struct ip_mreq *mreqp;
10488 			struct group_req *greqp;
10489 			ire_t *ire;
10490 			boolean_t done = B_FALSE;
10491 			ipaddr_t group, ifaddr;
10492 			struct sockaddr_in *sin;
10493 			uint32_t *ifindexp;
10494 			boolean_t mcast_opt = B_TRUE;
10495 			mcast_record_t fmode;
10496 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10497 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10498 
10499 			switch (name) {
10500 			case IP_ADD_MEMBERSHIP:
10501 				mcast_opt = B_FALSE;
10502 				/* FALLTHRU */
10503 			case MCAST_JOIN_GROUP:
10504 				fmode = MODE_IS_EXCLUDE;
10505 				optfn = ip_opt_add_group;
10506 				break;
10507 
10508 			case IP_DROP_MEMBERSHIP:
10509 				mcast_opt = B_FALSE;
10510 				/* FALLTHRU */
10511 			case MCAST_LEAVE_GROUP:
10512 				fmode = MODE_IS_INCLUDE;
10513 				optfn = ip_opt_delete_group;
10514 				break;
10515 			}
10516 
10517 			if (mcast_opt) {
10518 				greqp = (struct group_req *)i1;
10519 				sin = (struct sockaddr_in *)&greqp->gr_group;
10520 				if (sin->sin_family != AF_INET) {
10521 					*outlenp = 0;
10522 					return (ENOPROTOOPT);
10523 				}
10524 				group = (ipaddr_t)sin->sin_addr.s_addr;
10525 				ifaddr = INADDR_ANY;
10526 				ifindexp = &greqp->gr_interface;
10527 			} else {
10528 				mreqp = (struct ip_mreq *)i1;
10529 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10530 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10531 				ifindexp = NULL;
10532 			}
10533 
10534 			/*
10535 			 * In the multirouting case, we need to replicate
10536 			 * the request on all interfaces that will take part
10537 			 * in replication.  We do so because multirouting is
10538 			 * reflective, thus we will probably receive multi-
10539 			 * casts on those interfaces.
10540 			 * The ip_multirt_apply_membership() succeeds if the
10541 			 * operation succeeds on at least one interface.
10542 			 */
10543 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10544 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10545 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10546 			if (ire != NULL) {
10547 				if (ire->ire_flags & RTF_MULTIRT) {
10548 					error = ip_multirt_apply_membership(
10549 					    optfn, ire, connp, checkonly, group,
10550 					    fmode, INADDR_ANY, first_mp);
10551 					done = B_TRUE;
10552 				}
10553 				ire_refrele(ire);
10554 			}
10555 			if (!done) {
10556 				error = optfn(connp, checkonly, group, ifaddr,
10557 				    ifindexp, fmode, INADDR_ANY, first_mp);
10558 			}
10559 			if (error) {
10560 				/*
10561 				 * EINPROGRESS is a soft error, needs retry
10562 				 * so don't make *outlenp zero.
10563 				 */
10564 				if (error != EINPROGRESS)
10565 					*outlenp = 0;
10566 				return (error);
10567 			}
10568 			/* OK return - copy input buffer into output buffer */
10569 			if (invalp != outvalp) {
10570 				/* don't trust bcopy for identical src/dst */
10571 				bcopy(invalp, outvalp, inlen);
10572 			}
10573 			*outlenp = inlen;
10574 			return (0);
10575 		}
10576 		case IP_BLOCK_SOURCE:
10577 		case IP_UNBLOCK_SOURCE:
10578 		case IP_ADD_SOURCE_MEMBERSHIP:
10579 		case IP_DROP_SOURCE_MEMBERSHIP:
10580 		case MCAST_BLOCK_SOURCE:
10581 		case MCAST_UNBLOCK_SOURCE:
10582 		case MCAST_JOIN_SOURCE_GROUP:
10583 		case MCAST_LEAVE_SOURCE_GROUP: {
10584 			struct ip_mreq_source *imreqp;
10585 			struct group_source_req *gsreqp;
10586 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10587 			uint32_t ifindex = 0;
10588 			mcast_record_t fmode;
10589 			struct sockaddr_in *sin;
10590 			ire_t *ire;
10591 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10592 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10593 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10594 
10595 			switch (name) {
10596 			case IP_BLOCK_SOURCE:
10597 				mcast_opt = B_FALSE;
10598 				/* FALLTHRU */
10599 			case MCAST_BLOCK_SOURCE:
10600 				fmode = MODE_IS_EXCLUDE;
10601 				optfn = ip_opt_add_group;
10602 				break;
10603 
10604 			case IP_UNBLOCK_SOURCE:
10605 				mcast_opt = B_FALSE;
10606 				/* FALLTHRU */
10607 			case MCAST_UNBLOCK_SOURCE:
10608 				fmode = MODE_IS_EXCLUDE;
10609 				optfn = ip_opt_delete_group;
10610 				break;
10611 
10612 			case IP_ADD_SOURCE_MEMBERSHIP:
10613 				mcast_opt = B_FALSE;
10614 				/* FALLTHRU */
10615 			case MCAST_JOIN_SOURCE_GROUP:
10616 				fmode = MODE_IS_INCLUDE;
10617 				optfn = ip_opt_add_group;
10618 				break;
10619 
10620 			case IP_DROP_SOURCE_MEMBERSHIP:
10621 				mcast_opt = B_FALSE;
10622 				/* FALLTHRU */
10623 			case MCAST_LEAVE_SOURCE_GROUP:
10624 				fmode = MODE_IS_INCLUDE;
10625 				optfn = ip_opt_delete_group;
10626 				break;
10627 			}
10628 
10629 			if (mcast_opt) {
10630 				gsreqp = (struct group_source_req *)i1;
10631 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10632 					*outlenp = 0;
10633 					return (ENOPROTOOPT);
10634 				}
10635 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10636 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10637 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10638 				src = (ipaddr_t)sin->sin_addr.s_addr;
10639 				ifindex = gsreqp->gsr_interface;
10640 			} else {
10641 				imreqp = (struct ip_mreq_source *)i1;
10642 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10643 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10644 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10645 			}
10646 
10647 			/*
10648 			 * In the multirouting case, we need to replicate
10649 			 * the request as noted in the mcast cases above.
10650 			 */
10651 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10652 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10653 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10654 			if (ire != NULL) {
10655 				if (ire->ire_flags & RTF_MULTIRT) {
10656 					error = ip_multirt_apply_membership(
10657 					    optfn, ire, connp, checkonly, grp,
10658 					    fmode, src, first_mp);
10659 					done = B_TRUE;
10660 				}
10661 				ire_refrele(ire);
10662 			}
10663 			if (!done) {
10664 				error = optfn(connp, checkonly, grp, ifaddr,
10665 				    &ifindex, fmode, src, first_mp);
10666 			}
10667 			if (error != 0) {
10668 				/*
10669 				 * EINPROGRESS is a soft error, needs retry
10670 				 * so don't make *outlenp zero.
10671 				 */
10672 				if (error != EINPROGRESS)
10673 					*outlenp = 0;
10674 				return (error);
10675 			}
10676 			/* OK return - copy input buffer into output buffer */
10677 			if (invalp != outvalp) {
10678 				bcopy(invalp, outvalp, inlen);
10679 			}
10680 			*outlenp = inlen;
10681 			return (0);
10682 		}
10683 		case IP_SEC_OPT:
10684 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10685 			if (error != 0) {
10686 				*outlenp = 0;
10687 				return (error);
10688 			}
10689 			break;
10690 		case IP_HDRINCL:
10691 		case IP_OPTIONS:
10692 		case T_IP_OPTIONS:
10693 		case IP_TOS:
10694 		case T_IP_TOS:
10695 		case IP_TTL:
10696 		case IP_RECVDSTADDR:
10697 		case IP_RECVOPTS:
10698 			/* OK return - copy input buffer into output buffer */
10699 			if (invalp != outvalp) {
10700 				/* don't trust bcopy for identical src/dst */
10701 				bcopy(invalp, outvalp, inlen);
10702 			}
10703 			*outlenp = inlen;
10704 			return (0);
10705 		case IP_RECVIF:
10706 			/* Retrieve the inbound interface index */
10707 			if (!checkonly) {
10708 				mutex_enter(&connp->conn_lock);
10709 				connp->conn_recvif = *i1 ? 1 : 0;
10710 				mutex_exit(&connp->conn_lock);
10711 			}
10712 			break;	/* goto sizeof (int) option return */
10713 		case IP_RECVSLLA:
10714 			/* Retrieve the source link layer address */
10715 			if (!checkonly) {
10716 				mutex_enter(&connp->conn_lock);
10717 				connp->conn_recvslla = *i1 ? 1 : 0;
10718 				mutex_exit(&connp->conn_lock);
10719 			}
10720 			break;	/* goto sizeof (int) option return */
10721 		case MRT_INIT:
10722 		case MRT_DONE:
10723 		case MRT_ADD_VIF:
10724 		case MRT_DEL_VIF:
10725 		case MRT_ADD_MFC:
10726 		case MRT_DEL_MFC:
10727 		case MRT_ASSERT:
10728 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10729 				*outlenp = 0;
10730 				return (error);
10731 			}
10732 			error = ip_mrouter_set((int)name, q, checkonly,
10733 			    (uchar_t *)invalp, inlen, first_mp);
10734 			if (error) {
10735 				*outlenp = 0;
10736 				return (error);
10737 			}
10738 			/* OK return - copy input buffer into output buffer */
10739 			if (invalp != outvalp) {
10740 				/* don't trust bcopy for identical src/dst */
10741 				bcopy(invalp, outvalp, inlen);
10742 			}
10743 			*outlenp = inlen;
10744 			return (0);
10745 		case IP_BOUND_IF:
10746 		case IP_XMIT_IF:
10747 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10748 			    level, name, first_mp);
10749 			if (error != 0)
10750 				return (error);
10751 			break; 		/* goto sizeof (int) option return */
10752 
10753 		case IP_UNSPEC_SRC:
10754 			/* Allow sending with a zero source address */
10755 			if (!checkonly) {
10756 				mutex_enter(&connp->conn_lock);
10757 				connp->conn_unspec_src = *i1 ? 1 : 0;
10758 				mutex_exit(&connp->conn_lock);
10759 			}
10760 			break;	/* goto sizeof (int) option return */
10761 		default:
10762 			/*
10763 			 * "soft" error (negative)
10764 			 * option not handled at this level
10765 			 * Note: Do not modify *outlenp
10766 			 */
10767 			return (-EINVAL);
10768 		}
10769 		break;
10770 	case IPPROTO_IPV6:
10771 		switch (name) {
10772 		case IPV6_BOUND_IF:
10773 		case IPV6_BOUND_PIF:
10774 		case IPV6_DONTFAILOVER_IF:
10775 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10776 			    level, name, first_mp);
10777 			if (error != 0)
10778 				return (error);
10779 			break; 		/* goto sizeof (int) option return */
10780 
10781 		case IPV6_MULTICAST_IF:
10782 			/*
10783 			 * The only possible errors are EINPROGRESS and
10784 			 * EINVAL. EINPROGRESS will be restarted and is not
10785 			 * a hard error. We call this option on both V4 and V6
10786 			 * If both return EINVAL, then this call returns
10787 			 * EINVAL. If at least one of them succeeds we
10788 			 * return success.
10789 			 */
10790 			found = B_FALSE;
10791 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10792 			    level, name, first_mp);
10793 			if (error == EINPROGRESS)
10794 				return (error);
10795 			if (error == 0)
10796 				found = B_TRUE;
10797 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10798 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10799 			if (error == 0)
10800 				found = B_TRUE;
10801 			if (!found)
10802 				return (error);
10803 			break; 		/* goto sizeof (int) option return */
10804 
10805 		case IPV6_MULTICAST_HOPS:
10806 			/* Recorded in transport above IP */
10807 			break;	/* goto sizeof (int) option return */
10808 		case IPV6_MULTICAST_LOOP:
10809 			if (!checkonly) {
10810 				mutex_enter(&connp->conn_lock);
10811 				connp->conn_multicast_loop = *i1;
10812 				mutex_exit(&connp->conn_lock);
10813 			}
10814 			break;	/* goto sizeof (int) option return */
10815 		case IPV6_JOIN_GROUP:
10816 		case MCAST_JOIN_GROUP:
10817 		case IPV6_LEAVE_GROUP:
10818 		case MCAST_LEAVE_GROUP: {
10819 			struct ipv6_mreq *ip_mreqp;
10820 			struct group_req *greqp;
10821 			ire_t *ire;
10822 			boolean_t done = B_FALSE;
10823 			in6_addr_t groupv6;
10824 			uint32_t ifindex;
10825 			boolean_t mcast_opt = B_TRUE;
10826 			mcast_record_t fmode;
10827 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10828 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10829 
10830 			switch (name) {
10831 			case IPV6_JOIN_GROUP:
10832 				mcast_opt = B_FALSE;
10833 				/* FALLTHRU */
10834 			case MCAST_JOIN_GROUP:
10835 				fmode = MODE_IS_EXCLUDE;
10836 				optfn = ip_opt_add_group_v6;
10837 				break;
10838 
10839 			case IPV6_LEAVE_GROUP:
10840 				mcast_opt = B_FALSE;
10841 				/* FALLTHRU */
10842 			case MCAST_LEAVE_GROUP:
10843 				fmode = MODE_IS_INCLUDE;
10844 				optfn = ip_opt_delete_group_v6;
10845 				break;
10846 			}
10847 
10848 			if (mcast_opt) {
10849 				struct sockaddr_in *sin;
10850 				struct sockaddr_in6 *sin6;
10851 				greqp = (struct group_req *)i1;
10852 				if (greqp->gr_group.ss_family == AF_INET) {
10853 					sin = (struct sockaddr_in *)
10854 					    &(greqp->gr_group);
10855 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10856 					    &groupv6);
10857 				} else {
10858 					sin6 = (struct sockaddr_in6 *)
10859 					    &(greqp->gr_group);
10860 					groupv6 = sin6->sin6_addr;
10861 				}
10862 				ifindex = greqp->gr_interface;
10863 			} else {
10864 				ip_mreqp = (struct ipv6_mreq *)i1;
10865 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10866 				ifindex = ip_mreqp->ipv6mr_interface;
10867 			}
10868 			/*
10869 			 * In the multirouting case, we need to replicate
10870 			 * the request on all interfaces that will take part
10871 			 * in replication.  We do so because multirouting is
10872 			 * reflective, thus we will probably receive multi-
10873 			 * casts on those interfaces.
10874 			 * The ip_multirt_apply_membership_v6() succeeds if
10875 			 * the operation succeeds on at least one interface.
10876 			 */
10877 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
10878 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10879 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10880 			if (ire != NULL) {
10881 				if (ire->ire_flags & RTF_MULTIRT) {
10882 					error = ip_multirt_apply_membership_v6(
10883 					    optfn, ire, connp, checkonly,
10884 					    &groupv6, fmode, &ipv6_all_zeros,
10885 					    first_mp);
10886 					done = B_TRUE;
10887 				}
10888 				ire_refrele(ire);
10889 			}
10890 			if (!done) {
10891 				error = optfn(connp, checkonly, &groupv6,
10892 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10893 			}
10894 			if (error) {
10895 				/*
10896 				 * EINPROGRESS is a soft error, needs retry
10897 				 * so don't make *outlenp zero.
10898 				 */
10899 				if (error != EINPROGRESS)
10900 					*outlenp = 0;
10901 				return (error);
10902 			}
10903 			/* OK return - copy input buffer into output buffer */
10904 			if (invalp != outvalp) {
10905 				/* don't trust bcopy for identical src/dst */
10906 				bcopy(invalp, outvalp, inlen);
10907 			}
10908 			*outlenp = inlen;
10909 			return (0);
10910 		}
10911 		case MCAST_BLOCK_SOURCE:
10912 		case MCAST_UNBLOCK_SOURCE:
10913 		case MCAST_JOIN_SOURCE_GROUP:
10914 		case MCAST_LEAVE_SOURCE_GROUP: {
10915 			struct group_source_req *gsreqp;
10916 			in6_addr_t v6grp, v6src;
10917 			uint32_t ifindex;
10918 			mcast_record_t fmode;
10919 			ire_t *ire;
10920 			boolean_t done = B_FALSE;
10921 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10922 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10923 
10924 			switch (name) {
10925 			case MCAST_BLOCK_SOURCE:
10926 				fmode = MODE_IS_EXCLUDE;
10927 				optfn = ip_opt_add_group_v6;
10928 				break;
10929 			case MCAST_UNBLOCK_SOURCE:
10930 				fmode = MODE_IS_EXCLUDE;
10931 				optfn = ip_opt_delete_group_v6;
10932 				break;
10933 			case MCAST_JOIN_SOURCE_GROUP:
10934 				fmode = MODE_IS_INCLUDE;
10935 				optfn = ip_opt_add_group_v6;
10936 				break;
10937 			case MCAST_LEAVE_SOURCE_GROUP:
10938 				fmode = MODE_IS_INCLUDE;
10939 				optfn = ip_opt_delete_group_v6;
10940 				break;
10941 			}
10942 
10943 			gsreqp = (struct group_source_req *)i1;
10944 			ifindex = gsreqp->gsr_interface;
10945 			if (gsreqp->gsr_group.ss_family == AF_INET) {
10946 				struct sockaddr_in *s;
10947 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
10948 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
10949 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
10950 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
10951 			} else {
10952 				struct sockaddr_in6 *s6;
10953 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
10954 				v6grp = s6->sin6_addr;
10955 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
10956 				v6src = s6->sin6_addr;
10957 			}
10958 
10959 			/*
10960 			 * In the multirouting case, we need to replicate
10961 			 * the request as noted in the mcast cases above.
10962 			 */
10963 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
10964 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10965 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10966 			if (ire != NULL) {
10967 				if (ire->ire_flags & RTF_MULTIRT) {
10968 					error = ip_multirt_apply_membership_v6(
10969 					    optfn, ire, connp, checkonly,
10970 					    &v6grp, fmode, &v6src, first_mp);
10971 					done = B_TRUE;
10972 				}
10973 				ire_refrele(ire);
10974 			}
10975 			if (!done) {
10976 				error = optfn(connp, checkonly, &v6grp,
10977 				    ifindex, fmode, &v6src, first_mp);
10978 			}
10979 			if (error != 0) {
10980 				/*
10981 				 * EINPROGRESS is a soft error, needs retry
10982 				 * so don't make *outlenp zero.
10983 				 */
10984 				if (error != EINPROGRESS)
10985 					*outlenp = 0;
10986 				return (error);
10987 			}
10988 			/* OK return - copy input buffer into output buffer */
10989 			if (invalp != outvalp) {
10990 				bcopy(invalp, outvalp, inlen);
10991 			}
10992 			*outlenp = inlen;
10993 			return (0);
10994 		}
10995 		case IPV6_UNICAST_HOPS:
10996 			/* Recorded in transport above IP */
10997 			break;	/* goto sizeof (int) option return */
10998 		case IPV6_UNSPEC_SRC:
10999 			/* Allow sending with a zero source address */
11000 			if (!checkonly) {
11001 				mutex_enter(&connp->conn_lock);
11002 				connp->conn_unspec_src = *i1 ? 1 : 0;
11003 				mutex_exit(&connp->conn_lock);
11004 			}
11005 			break;	/* goto sizeof (int) option return */
11006 		case IPV6_RECVPKTINFO:
11007 			if (!checkonly) {
11008 				mutex_enter(&connp->conn_lock);
11009 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
11010 				mutex_exit(&connp->conn_lock);
11011 			}
11012 			break;	/* goto sizeof (int) option return */
11013 		case IPV6_RECVTCLASS:
11014 			if (!checkonly) {
11015 				if (*i1 < 0 || *i1 > 1) {
11016 					return (EINVAL);
11017 				}
11018 				mutex_enter(&connp->conn_lock);
11019 				connp->conn_ipv6_recvtclass = *i1;
11020 				mutex_exit(&connp->conn_lock);
11021 			}
11022 			break;
11023 		case IPV6_RECVPATHMTU:
11024 			if (!checkonly) {
11025 				if (*i1 < 0 || *i1 > 1) {
11026 					return (EINVAL);
11027 				}
11028 				mutex_enter(&connp->conn_lock);
11029 				connp->conn_ipv6_recvpathmtu = *i1;
11030 				mutex_exit(&connp->conn_lock);
11031 			}
11032 			break;
11033 		case IPV6_RECVHOPLIMIT:
11034 			if (!checkonly) {
11035 				mutex_enter(&connp->conn_lock);
11036 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11037 				mutex_exit(&connp->conn_lock);
11038 			}
11039 			break;	/* goto sizeof (int) option return */
11040 		case IPV6_RECVHOPOPTS:
11041 			if (!checkonly) {
11042 				mutex_enter(&connp->conn_lock);
11043 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11044 				mutex_exit(&connp->conn_lock);
11045 			}
11046 			break;	/* goto sizeof (int) option return */
11047 		case IPV6_RECVDSTOPTS:
11048 			if (!checkonly) {
11049 				mutex_enter(&connp->conn_lock);
11050 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11051 				mutex_exit(&connp->conn_lock);
11052 			}
11053 			break;	/* goto sizeof (int) option return */
11054 		case IPV6_RECVRTHDR:
11055 			if (!checkonly) {
11056 				mutex_enter(&connp->conn_lock);
11057 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11058 				mutex_exit(&connp->conn_lock);
11059 			}
11060 			break;	/* goto sizeof (int) option return */
11061 		case IPV6_RECVRTHDRDSTOPTS:
11062 			if (!checkonly) {
11063 				mutex_enter(&connp->conn_lock);
11064 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11065 				mutex_exit(&connp->conn_lock);
11066 			}
11067 			break;	/* goto sizeof (int) option return */
11068 		case IPV6_PKTINFO:
11069 			if (inlen == 0)
11070 				return (-EINVAL);	/* clearing option */
11071 			error = ip6_set_pktinfo(cr, connp,
11072 			    (struct in6_pktinfo *)invalp, first_mp);
11073 			if (error != 0)
11074 				*outlenp = 0;
11075 			else
11076 				*outlenp = inlen;
11077 			return (error);
11078 		case IPV6_NEXTHOP: {
11079 			struct sockaddr_in6 *sin6;
11080 
11081 			/* Verify that the nexthop is reachable */
11082 			if (inlen == 0)
11083 				return (-EINVAL);	/* clearing option */
11084 
11085 			sin6 = (struct sockaddr_in6 *)invalp;
11086 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11087 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11088 			    NULL, MATCH_IRE_DEFAULT);
11089 
11090 			if (ire == NULL) {
11091 				*outlenp = 0;
11092 				return (EHOSTUNREACH);
11093 			}
11094 			ire_refrele(ire);
11095 			return (-EINVAL);
11096 		}
11097 		case IPV6_SEC_OPT:
11098 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11099 			if (error != 0) {
11100 				*outlenp = 0;
11101 				return (error);
11102 			}
11103 			break;
11104 		case IPV6_SRC_PREFERENCES: {
11105 			/*
11106 			 * This is implemented strictly in the ip module
11107 			 * (here and in tcp_opt_*() to accomodate tcp
11108 			 * sockets).  Modules above ip pass this option
11109 			 * down here since ip is the only one that needs to
11110 			 * be aware of source address preferences.
11111 			 *
11112 			 * This socket option only affects connected
11113 			 * sockets that haven't already bound to a specific
11114 			 * IPv6 address.  In other words, sockets that
11115 			 * don't call bind() with an address other than the
11116 			 * unspecified address and that call connect().
11117 			 * ip_bind_connected_v6() passes these preferences
11118 			 * to the ipif_select_source_v6() function.
11119 			 */
11120 			if (inlen != sizeof (uint32_t))
11121 				return (EINVAL);
11122 			error = ip6_set_src_preferences(connp,
11123 			    *(uint32_t *)invalp);
11124 			if (error != 0) {
11125 				*outlenp = 0;
11126 				return (error);
11127 			} else {
11128 				*outlenp = sizeof (uint32_t);
11129 			}
11130 			break;
11131 		}
11132 		case IPV6_V6ONLY:
11133 			if (*i1 < 0 || *i1 > 1) {
11134 				return (EINVAL);
11135 			}
11136 			mutex_enter(&connp->conn_lock);
11137 			connp->conn_ipv6_v6only = *i1;
11138 			mutex_exit(&connp->conn_lock);
11139 			break;
11140 		default:
11141 			return (-EINVAL);
11142 		}
11143 		break;
11144 	default:
11145 		/*
11146 		 * "soft" error (negative)
11147 		 * option not handled at this level
11148 		 * Note: Do not modify *outlenp
11149 		 */
11150 		return (-EINVAL);
11151 	}
11152 	/*
11153 	 * Common case of return from an option that is sizeof (int)
11154 	 */
11155 	*(int *)outvalp = *i1;
11156 	*outlenp = sizeof (int);
11157 	return (0);
11158 }
11159 
11160 /*
11161  * This routine gets default values of certain options whose default
11162  * values are maintained by protocol specific code
11163  */
11164 /* ARGSUSED */
11165 int
11166 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11167 {
11168 	int *i1 = (int *)ptr;
11169 
11170 	switch (level) {
11171 	case IPPROTO_IP:
11172 		switch (name) {
11173 		case IP_MULTICAST_TTL:
11174 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11175 			return (sizeof (uchar_t));
11176 		case IP_MULTICAST_LOOP:
11177 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11178 			return (sizeof (uchar_t));
11179 		default:
11180 			return (-1);
11181 		}
11182 	case IPPROTO_IPV6:
11183 		switch (name) {
11184 		case IPV6_UNICAST_HOPS:
11185 			*i1 = ipv6_def_hops;
11186 			return (sizeof (int));
11187 		case IPV6_MULTICAST_HOPS:
11188 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11189 			return (sizeof (int));
11190 		case IPV6_MULTICAST_LOOP:
11191 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11192 			return (sizeof (int));
11193 		case IPV6_V6ONLY:
11194 			*i1 = 1;
11195 			return (sizeof (int));
11196 		default:
11197 			return (-1);
11198 		}
11199 	default:
11200 		return (-1);
11201 	}
11202 	/* NOTREACHED */
11203 }
11204 
11205 /*
11206  * Given a destination address and a pointer to where to put the information
11207  * this routine fills in the mtuinfo.
11208  */
11209 int
11210 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11211     struct ip6_mtuinfo *mtuinfo)
11212 {
11213 	ire_t *ire;
11214 
11215 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11216 		return (-1);
11217 
11218 	bzero(mtuinfo, sizeof (*mtuinfo));
11219 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11220 	mtuinfo->ip6m_addr.sin6_port = port;
11221 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11222 
11223 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11224 	if (ire != NULL) {
11225 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11226 		ire_refrele(ire);
11227 	} else {
11228 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11229 	}
11230 	return (sizeof (struct ip6_mtuinfo));
11231 }
11232 
11233 /*
11234  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11235  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11236  * isn't.  This doesn't matter as the error checking is done properly for the
11237  * other MRT options coming in through ip_opt_set.
11238  */
11239 int
11240 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11241 {
11242 	conn_t		*connp = Q_TO_CONN(q);
11243 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11244 
11245 	switch (level) {
11246 	case IPPROTO_IP:
11247 		switch (name) {
11248 		case MRT_VERSION:
11249 		case MRT_ASSERT:
11250 			(void) ip_mrouter_get(name, q, ptr);
11251 			return (sizeof (int));
11252 		case IP_SEC_OPT:
11253 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11254 		case IP_NEXTHOP:
11255 			if (connp->conn_nexthop_set) {
11256 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11257 				return (sizeof (ipaddr_t));
11258 			} else
11259 				return (0);
11260 		default:
11261 			break;
11262 		}
11263 		break;
11264 	case IPPROTO_IPV6:
11265 		switch (name) {
11266 		case IPV6_SEC_OPT:
11267 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11268 		case IPV6_SRC_PREFERENCES: {
11269 			return (ip6_get_src_preferences(connp,
11270 			    (uint32_t *)ptr));
11271 		}
11272 		case IPV6_V6ONLY:
11273 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11274 			return (sizeof (int));
11275 		case IPV6_PATHMTU:
11276 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11277 				(struct ip6_mtuinfo *)ptr));
11278 		default:
11279 			break;
11280 		}
11281 		break;
11282 	default:
11283 		break;
11284 	}
11285 	return (-1);
11286 }
11287 
11288 /* Named Dispatch routine to get a current value out of our parameter table. */
11289 /* ARGSUSED */
11290 static int
11291 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11292 {
11293 	ipparam_t *ippa = (ipparam_t *)cp;
11294 
11295 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11296 	return (0);
11297 }
11298 
11299 /* ARGSUSED */
11300 static int
11301 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11302 {
11303 
11304 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11305 	return (0);
11306 }
11307 
11308 /*
11309  * Set ip{,6}_forwarding values.  This means walking through all of the
11310  * ill's and toggling their forwarding values.
11311  */
11312 /* ARGSUSED */
11313 static int
11314 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11315 {
11316 	long new_value;
11317 	int *forwarding_value = (int *)cp;
11318 	ill_t *walker;
11319 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11320 	ill_walk_context_t ctx;
11321 
11322 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11323 	    new_value < 0 || new_value > 1) {
11324 		return (EINVAL);
11325 	}
11326 
11327 	*forwarding_value = new_value;
11328 
11329 	/*
11330 	 * Regardless of the current value of ip_forwarding, set all per-ill
11331 	 * values of ip_forwarding to the value being set.
11332 	 *
11333 	 * Bring all the ill's up to date with the new global value.
11334 	 */
11335 	rw_enter(&ill_g_lock, RW_READER);
11336 
11337 	if (isv6)
11338 		walker = ILL_START_WALK_V6(&ctx);
11339 	else
11340 		walker = ILL_START_WALK_V4(&ctx);
11341 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11342 		(void) ill_forward_set(q, mp, (new_value != 0),
11343 		    (caddr_t)walker);
11344 	}
11345 	rw_exit(&ill_g_lock);
11346 
11347 	return (0);
11348 }
11349 
11350 /*
11351  * Walk through the param array specified registering each element with the
11352  * Named Dispatch handler. This is called only during init. So it is ok
11353  * not to acquire any locks
11354  */
11355 static boolean_t
11356 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11357     ipndp_t *ipnd, size_t ipnd_cnt)
11358 {
11359 	for (; ippa_cnt-- > 0; ippa++) {
11360 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11361 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11362 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11363 				nd_free(&ip_g_nd);
11364 				return (B_FALSE);
11365 			}
11366 		}
11367 	}
11368 
11369 	for (; ipnd_cnt-- > 0; ipnd++) {
11370 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11371 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11372 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11373 			    ipnd->ip_ndp_data)) {
11374 				nd_free(&ip_g_nd);
11375 				return (B_FALSE);
11376 			}
11377 		}
11378 	}
11379 
11380 	return (B_TRUE);
11381 }
11382 
11383 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11384 /* ARGSUSED */
11385 static int
11386 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11387 {
11388 	long		new_value;
11389 	ipparam_t	*ippa = (ipparam_t *)cp;
11390 
11391 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11392 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11393 		return (EINVAL);
11394 	}
11395 	ippa->ip_param_value = new_value;
11396 	return (0);
11397 }
11398 
11399 /*
11400  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11401  * When an ipf is passed here for the first time, if
11402  * we already have in-order fragments on the queue, we convert from the fast-
11403  * path reassembly scheme to the hard-case scheme.  From then on, additional
11404  * fragments are reassembled here.  We keep track of the start and end offsets
11405  * of each piece, and the number of holes in the chain.  When the hole count
11406  * goes to zero, we are done!
11407  *
11408  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11409  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11410  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11411  * after the call to ip_reassemble().
11412  */
11413 int
11414 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11415     size_t msg_len)
11416 {
11417 	uint_t	end;
11418 	mblk_t	*next_mp;
11419 	mblk_t	*mp1;
11420 	uint_t	offset;
11421 	boolean_t incr_dups = B_TRUE;
11422 	boolean_t offset_zero_seen = B_FALSE;
11423 	boolean_t pkt_boundary_checked = B_FALSE;
11424 
11425 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11426 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11427 
11428 	/* Add in byte count */
11429 	ipf->ipf_count += msg_len;
11430 	if (ipf->ipf_end) {
11431 		/*
11432 		 * We were part way through in-order reassembly, but now there
11433 		 * is a hole.  We walk through messages already queued, and
11434 		 * mark them for hard case reassembly.  We know that up till
11435 		 * now they were in order starting from offset zero.
11436 		 */
11437 		offset = 0;
11438 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11439 			IP_REASS_SET_START(mp1, offset);
11440 			if (offset == 0) {
11441 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11442 				offset = -ipf->ipf_nf_hdr_len;
11443 			}
11444 			offset += mp1->b_wptr - mp1->b_rptr;
11445 			IP_REASS_SET_END(mp1, offset);
11446 		}
11447 		/* One hole at the end. */
11448 		ipf->ipf_hole_cnt = 1;
11449 		/* Brand it as a hard case, forever. */
11450 		ipf->ipf_end = 0;
11451 	}
11452 	/* Walk through all the new pieces. */
11453 	do {
11454 		end = start + (mp->b_wptr - mp->b_rptr);
11455 		/*
11456 		 * If start is 0, decrease 'end' only for the first mblk of
11457 		 * the fragment. Otherwise 'end' can get wrong value in the
11458 		 * second pass of the loop if first mblk is exactly the
11459 		 * size of ipf_nf_hdr_len.
11460 		 */
11461 		if (start == 0 && !offset_zero_seen) {
11462 			/* First segment */
11463 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11464 			end -= ipf->ipf_nf_hdr_len;
11465 			offset_zero_seen = B_TRUE;
11466 		}
11467 		next_mp = mp->b_cont;
11468 		/*
11469 		 * We are checking to see if there is any interesing data
11470 		 * to process.  If there isn't and the mblk isn't the
11471 		 * one which carries the unfragmentable header then we
11472 		 * drop it.  It's possible to have just the unfragmentable
11473 		 * header come through without any data.  That needs to be
11474 		 * saved.
11475 		 *
11476 		 * If the assert at the top of this function holds then the
11477 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11478 		 * is infrequently traveled enough that the test is left in
11479 		 * to protect against future code changes which break that
11480 		 * invariant.
11481 		 */
11482 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11483 			/* Empty.  Blast it. */
11484 			IP_REASS_SET_START(mp, 0);
11485 			IP_REASS_SET_END(mp, 0);
11486 			/*
11487 			 * If the ipf points to the mblk we are about to free,
11488 			 * update ipf to point to the next mblk (or NULL
11489 			 * if none).
11490 			 */
11491 			if (ipf->ipf_mp->b_cont == mp)
11492 				ipf->ipf_mp->b_cont = next_mp;
11493 			freeb(mp);
11494 			continue;
11495 		}
11496 		mp->b_cont = NULL;
11497 		IP_REASS_SET_START(mp, start);
11498 		IP_REASS_SET_END(mp, end);
11499 		if (!ipf->ipf_tail_mp) {
11500 			ipf->ipf_tail_mp = mp;
11501 			ipf->ipf_mp->b_cont = mp;
11502 			if (start == 0 || !more) {
11503 				ipf->ipf_hole_cnt = 1;
11504 				/*
11505 				 * if the first fragment comes in more than one
11506 				 * mblk, this loop will be executed for each
11507 				 * mblk. Need to adjust hole count so exiting
11508 				 * this routine will leave hole count at 1.
11509 				 */
11510 				if (next_mp)
11511 					ipf->ipf_hole_cnt++;
11512 			} else
11513 				ipf->ipf_hole_cnt = 2;
11514 			continue;
11515 		} else if (ipf->ipf_last_frag_seen && !more &&
11516 			    !pkt_boundary_checked) {
11517 			/*
11518 			 * We check datagram boundary only if this fragment
11519 			 * claims to be the last fragment and we have seen a
11520 			 * last fragment in the past too. We do this only
11521 			 * once for a given fragment.
11522 			 *
11523 			 * start cannot be 0 here as fragments with start=0
11524 			 * and MF=0 gets handled as a complete packet. These
11525 			 * fragments should not reach here.
11526 			 */
11527 
11528 			if (start + msgdsize(mp) !=
11529 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11530 				/*
11531 				 * We have two fragments both of which claim
11532 				 * to be the last fragment but gives conflicting
11533 				 * information about the whole datagram size.
11534 				 * Something fishy is going on. Drop the
11535 				 * fragment and free up the reassembly list.
11536 				 */
11537 				return (IP_REASS_FAILED);
11538 			}
11539 
11540 			/*
11541 			 * We shouldn't come to this code block again for this
11542 			 * particular fragment.
11543 			 */
11544 			pkt_boundary_checked = B_TRUE;
11545 		}
11546 
11547 		/* New stuff at or beyond tail? */
11548 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11549 		if (start >= offset) {
11550 			if (ipf->ipf_last_frag_seen) {
11551 				/* current fragment is beyond last fragment */
11552 				return (IP_REASS_FAILED);
11553 			}
11554 			/* Link it on end. */
11555 			ipf->ipf_tail_mp->b_cont = mp;
11556 			ipf->ipf_tail_mp = mp;
11557 			if (more) {
11558 				if (start != offset)
11559 					ipf->ipf_hole_cnt++;
11560 			} else if (start == offset && next_mp == NULL)
11561 					ipf->ipf_hole_cnt--;
11562 			continue;
11563 		}
11564 		mp1 = ipf->ipf_mp->b_cont;
11565 		offset = IP_REASS_START(mp1);
11566 		/* New stuff at the front? */
11567 		if (start < offset) {
11568 			if (start == 0) {
11569 				if (end >= offset) {
11570 					/* Nailed the hole at the begining. */
11571 					ipf->ipf_hole_cnt--;
11572 				}
11573 			} else if (end < offset) {
11574 				/*
11575 				 * A hole, stuff, and a hole where there used
11576 				 * to be just a hole.
11577 				 */
11578 				ipf->ipf_hole_cnt++;
11579 			}
11580 			mp->b_cont = mp1;
11581 			/* Check for overlap. */
11582 			while (end > offset) {
11583 				if (end < IP_REASS_END(mp1)) {
11584 					mp->b_wptr -= end - offset;
11585 					IP_REASS_SET_END(mp, offset);
11586 					if (ill->ill_isv6) {
11587 						BUMP_MIB(ill->ill_ip6_mib,
11588 						    ipv6ReasmPartDups);
11589 					} else {
11590 						BUMP_MIB(&ip_mib,
11591 						    ipReasmPartDups);
11592 					}
11593 					break;
11594 				}
11595 				/* Did we cover another hole? */
11596 				if ((mp1->b_cont &&
11597 				    IP_REASS_END(mp1) !=
11598 				    IP_REASS_START(mp1->b_cont) &&
11599 				    end >= IP_REASS_START(mp1->b_cont)) ||
11600 				    (!ipf->ipf_last_frag_seen && !more)) {
11601 					ipf->ipf_hole_cnt--;
11602 				}
11603 				/* Clip out mp1. */
11604 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11605 					/*
11606 					 * After clipping out mp1, this guy
11607 					 * is now hanging off the end.
11608 					 */
11609 					ipf->ipf_tail_mp = mp;
11610 				}
11611 				IP_REASS_SET_START(mp1, 0);
11612 				IP_REASS_SET_END(mp1, 0);
11613 				/* Subtract byte count */
11614 				ipf->ipf_count -= mp1->b_datap->db_lim -
11615 				    mp1->b_datap->db_base;
11616 				freeb(mp1);
11617 				if (ill->ill_isv6) {
11618 					BUMP_MIB(ill->ill_ip6_mib,
11619 					    ipv6ReasmPartDups);
11620 				} else {
11621 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11622 				}
11623 				mp1 = mp->b_cont;
11624 				if (!mp1)
11625 					break;
11626 				offset = IP_REASS_START(mp1);
11627 			}
11628 			ipf->ipf_mp->b_cont = mp;
11629 			continue;
11630 		}
11631 		/*
11632 		 * The new piece starts somewhere between the start of the head
11633 		 * and before the end of the tail.
11634 		 */
11635 		for (; mp1; mp1 = mp1->b_cont) {
11636 			offset = IP_REASS_END(mp1);
11637 			if (start < offset) {
11638 				if (end <= offset) {
11639 					/* Nothing new. */
11640 					IP_REASS_SET_START(mp, 0);
11641 					IP_REASS_SET_END(mp, 0);
11642 					/* Subtract byte count */
11643 					ipf->ipf_count -= mp->b_datap->db_lim -
11644 					    mp->b_datap->db_base;
11645 					if (incr_dups) {
11646 						ipf->ipf_num_dups++;
11647 						incr_dups = B_FALSE;
11648 					}
11649 					freeb(mp);
11650 					if (ill->ill_isv6) {
11651 						BUMP_MIB(ill->ill_ip6_mib,
11652 						    ipv6ReasmDuplicates);
11653 					} else {
11654 						BUMP_MIB(&ip_mib,
11655 						    ipReasmDuplicates);
11656 					}
11657 					break;
11658 				}
11659 				/*
11660 				 * Trim redundant stuff off beginning of new
11661 				 * piece.
11662 				 */
11663 				IP_REASS_SET_START(mp, offset);
11664 				mp->b_rptr += offset - start;
11665 				if (ill->ill_isv6) {
11666 					BUMP_MIB(ill->ill_ip6_mib,
11667 					    ipv6ReasmPartDups);
11668 				} else {
11669 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11670 				}
11671 				start = offset;
11672 				if (!mp1->b_cont) {
11673 					/*
11674 					 * After trimming, this guy is now
11675 					 * hanging off the end.
11676 					 */
11677 					mp1->b_cont = mp;
11678 					ipf->ipf_tail_mp = mp;
11679 					if (!more) {
11680 						ipf->ipf_hole_cnt--;
11681 					}
11682 					break;
11683 				}
11684 			}
11685 			if (start >= IP_REASS_START(mp1->b_cont))
11686 				continue;
11687 			/* Fill a hole */
11688 			if (start > offset)
11689 				ipf->ipf_hole_cnt++;
11690 			mp->b_cont = mp1->b_cont;
11691 			mp1->b_cont = mp;
11692 			mp1 = mp->b_cont;
11693 			offset = IP_REASS_START(mp1);
11694 			if (end >= offset) {
11695 				ipf->ipf_hole_cnt--;
11696 				/* Check for overlap. */
11697 				while (end > offset) {
11698 					if (end < IP_REASS_END(mp1)) {
11699 						mp->b_wptr -= end - offset;
11700 						IP_REASS_SET_END(mp, offset);
11701 						/*
11702 						 * TODO we might bump
11703 						 * this up twice if there is
11704 						 * overlap at both ends.
11705 						 */
11706 						if (ill->ill_isv6) {
11707 							BUMP_MIB(
11708 							    ill->ill_ip6_mib,
11709 							    ipv6ReasmPartDups);
11710 						} else {
11711 							BUMP_MIB(&ip_mib,
11712 							    ipReasmPartDups);
11713 						}
11714 						break;
11715 					}
11716 					/* Did we cover another hole? */
11717 					if ((mp1->b_cont &&
11718 					    IP_REASS_END(mp1)
11719 					    != IP_REASS_START(mp1->b_cont) &&
11720 					    end >=
11721 					    IP_REASS_START(mp1->b_cont)) ||
11722 					    (!ipf->ipf_last_frag_seen &&
11723 					    !more)) {
11724 						ipf->ipf_hole_cnt--;
11725 					}
11726 					/* Clip out mp1. */
11727 					if ((mp->b_cont = mp1->b_cont) ==
11728 					    NULL) {
11729 						/*
11730 						 * After clipping out mp1,
11731 						 * this guy is now hanging
11732 						 * off the end.
11733 						 */
11734 						ipf->ipf_tail_mp = mp;
11735 					}
11736 					IP_REASS_SET_START(mp1, 0);
11737 					IP_REASS_SET_END(mp1, 0);
11738 					/* Subtract byte count */
11739 					ipf->ipf_count -=
11740 					    mp1->b_datap->db_lim -
11741 					    mp1->b_datap->db_base;
11742 					freeb(mp1);
11743 					if (ill->ill_isv6) {
11744 						BUMP_MIB(ill->ill_ip6_mib,
11745 						    ipv6ReasmPartDups);
11746 					} else {
11747 						BUMP_MIB(&ip_mib,
11748 						    ipReasmPartDups);
11749 					}
11750 					mp1 = mp->b_cont;
11751 					if (!mp1)
11752 						break;
11753 					offset = IP_REASS_START(mp1);
11754 				}
11755 			}
11756 			break;
11757 		}
11758 	} while (start = end, mp = next_mp);
11759 
11760 	/* Fragment just processed could be the last one. Remember this fact */
11761 	if (!more)
11762 		ipf->ipf_last_frag_seen = B_TRUE;
11763 
11764 	/* Still got holes? */
11765 	if (ipf->ipf_hole_cnt)
11766 		return (IP_REASS_PARTIAL);
11767 	/* Clean up overloaded fields to avoid upstream disasters. */
11768 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11769 		IP_REASS_SET_START(mp1, 0);
11770 		IP_REASS_SET_END(mp1, 0);
11771 	}
11772 	return (IP_REASS_COMPLETE);
11773 }
11774 
11775 /*
11776  * ipsec processing for the fast path, used for input UDP Packets
11777  */
11778 static boolean_t
11779 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11780     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11781 {
11782 	uint32_t	ill_index;
11783 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11784 
11785 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11786 	/* The ill_index of the incoming ILL */
11787 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11788 
11789 	/* pass packet up to the transport */
11790 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11791 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11792 		    NULL, mctl_present);
11793 		if (*first_mpp == NULL) {
11794 			return (B_FALSE);
11795 		}
11796 	}
11797 
11798 	/* Initiate IPPF processing for fastpath UDP */
11799 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11800 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11801 		if (*mpp == NULL) {
11802 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11803 			    "deferred/dropped during IPPF processing\n"));
11804 			return (B_FALSE);
11805 		}
11806 	}
11807 	/*
11808 	 * We make the checks as below since we are in the fast path
11809 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11810 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11811 	 */
11812 	if (connp->conn_recvif || connp->conn_recvslla ||
11813 	    connp->conn_ipv6_recvpktinfo) {
11814 		if (connp->conn_recvif ||
11815 		    connp->conn_ipv6_recvpktinfo) {
11816 			in_flags = IPF_RECVIF;
11817 		}
11818 		if (connp->conn_recvslla) {
11819 			in_flags |= IPF_RECVSLLA;
11820 		}
11821 		/*
11822 		 * since in_flags are being set ill will be
11823 		 * referenced in ip_add_info, so it better not
11824 		 * be NULL.
11825 		 */
11826 		/*
11827 		 * the actual data will be contained in b_cont
11828 		 * upon successful return of the following call.
11829 		 * If the call fails then the original mblk is
11830 		 * returned.
11831 		 */
11832 		*mpp = ip_add_info(*mpp, ill, in_flags);
11833 	}
11834 
11835 	return (B_TRUE);
11836 }
11837 
11838 /*
11839  * Fragmentation reassembly.  Each ILL has a hash table for
11840  * queuing packets undergoing reassembly for all IPIFs
11841  * associated with the ILL.  The hash is based on the packet
11842  * IP ident field.  The ILL frag hash table was allocated
11843  * as a timer block at the time the ILL was created.  Whenever
11844  * there is anything on the reassembly queue, the timer will
11845  * be running.  Returns B_TRUE if successful else B_FALSE;
11846  * frees mp on failure.
11847  */
11848 static boolean_t
11849 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11850     uint32_t *cksum_val, uint16_t *cksum_flags)
11851 {
11852 	uint32_t	frag_offset_flags;
11853 	ill_t		*ill = (ill_t *)q->q_ptr;
11854 	mblk_t		*mp = *mpp;
11855 	mblk_t		*t_mp;
11856 	ipaddr_t	dst;
11857 	uint8_t		proto = ipha->ipha_protocol;
11858 	uint32_t	sum_val;
11859 	uint16_t	sum_flags;
11860 	ipf_t		*ipf;
11861 	ipf_t		**ipfp;
11862 	ipfb_t		*ipfb;
11863 	uint16_t	ident;
11864 	uint32_t	offset;
11865 	ipaddr_t	src;
11866 	uint_t		hdr_length;
11867 	uint32_t	end;
11868 	mblk_t		*mp1;
11869 	mblk_t		*tail_mp;
11870 	size_t		count;
11871 	size_t		msg_len;
11872 	uint8_t		ecn_info = 0;
11873 	uint32_t	packet_size;
11874 	boolean_t	pruned = B_FALSE;
11875 
11876 	if (cksum_val != NULL)
11877 		*cksum_val = 0;
11878 	if (cksum_flags != NULL)
11879 		*cksum_flags = 0;
11880 
11881 	/*
11882 	 * Drop the fragmented as early as possible, if
11883 	 * we don't have resource(s) to re-assemble.
11884 	 */
11885 	if (ip_reass_queue_bytes == 0) {
11886 		freemsg(mp);
11887 		return (B_FALSE);
11888 	}
11889 
11890 	/* Check for fragmentation offset; return if there's none */
11891 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
11892 	    (IPH_MF | IPH_OFFSET)) == 0)
11893 		return (B_TRUE);
11894 
11895 	/*
11896 	 * We utilize hardware computed checksum info only for UDP since
11897 	 * IP fragmentation is a normal occurence for the protocol.  In
11898 	 * addition, checksum offload support for IP fragments carrying
11899 	 * UDP payload is commonly implemented across network adapters.
11900 	 */
11901 	ASSERT(ill != NULL);
11902 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
11903 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
11904 		mblk_t *mp1 = mp->b_cont;
11905 		int32_t len;
11906 
11907 		/* Record checksum information from the packet */
11908 		sum_val = (uint32_t)DB_CKSUM16(mp);
11909 		sum_flags = DB_CKSUMFLAGS(mp);
11910 
11911 		/* IP payload offset from beginning of mblk */
11912 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
11913 
11914 		if ((sum_flags & HCK_PARTIALCKSUM) &&
11915 		    (mp1 == NULL || mp1->b_cont == NULL) &&
11916 		    offset >= DB_CKSUMSTART(mp) &&
11917 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
11918 			uint32_t adj;
11919 			/*
11920 			 * Partial checksum has been calculated by hardware
11921 			 * and attached to the packet; in addition, any
11922 			 * prepended extraneous data is even byte aligned.
11923 			 * If any such data exists, we adjust the checksum;
11924 			 * this would also handle any postpended data.
11925 			 */
11926 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
11927 			    mp, mp1, len, adj);
11928 
11929 			/* One's complement subtract extraneous checksum */
11930 			if (adj >= sum_val)
11931 				sum_val = ~(adj - sum_val) & 0xFFFF;
11932 			else
11933 				sum_val -= adj;
11934 		}
11935 	} else {
11936 		sum_val = 0;
11937 		sum_flags = 0;
11938 	}
11939 
11940 	/* Clear hardware checksumming flag */
11941 	DB_CKSUMFLAGS(mp) = 0;
11942 
11943 	ident = ipha->ipha_ident;
11944 	offset = (frag_offset_flags << 3) & 0xFFFF;
11945 	src = ipha->ipha_src;
11946 	dst = ipha->ipha_dst;
11947 	hdr_length = IPH_HDR_LENGTH(ipha);
11948 	end = ntohs(ipha->ipha_length) - hdr_length;
11949 
11950 	/* If end == 0 then we have a packet with no data, so just free it */
11951 	if (end == 0) {
11952 		freemsg(mp);
11953 		return (B_FALSE);
11954 	}
11955 
11956 	/* Record the ECN field info. */
11957 	ecn_info = (ipha->ipha_type_of_service & 0x3);
11958 	if (offset != 0) {
11959 		/*
11960 		 * If this isn't the first piece, strip the header, and
11961 		 * add the offset to the end value.
11962 		 */
11963 		mp->b_rptr += hdr_length;
11964 		end += offset;
11965 	}
11966 
11967 	msg_len = MBLKSIZE(mp);
11968 	tail_mp = mp;
11969 	while (tail_mp->b_cont != NULL) {
11970 		tail_mp = tail_mp->b_cont;
11971 		msg_len += MBLKSIZE(tail_mp);
11972 	}
11973 
11974 	/* If the reassembly list for this ILL will get too big, prune it */
11975 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
11976 	    ip_reass_queue_bytes) {
11977 		ill_frag_prune(ill,
11978 		    (ip_reass_queue_bytes < msg_len) ? 0 :
11979 		    (ip_reass_queue_bytes - msg_len));
11980 		pruned = B_TRUE;
11981 	}
11982 
11983 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
11984 	mutex_enter(&ipfb->ipfb_lock);
11985 
11986 	ipfp = &ipfb->ipfb_ipf;
11987 	/* Try to find an existing fragment queue for this packet. */
11988 	for (;;) {
11989 		ipf = ipfp[0];
11990 		if (ipf != NULL) {
11991 			/*
11992 			 * It has to match on ident and src/dst address.
11993 			 */
11994 			if (ipf->ipf_ident == ident &&
11995 			    ipf->ipf_src == src &&
11996 			    ipf->ipf_dst == dst &&
11997 			    ipf->ipf_protocol == proto) {
11998 				/*
11999 				 * If we have received too many
12000 				 * duplicate fragments for this packet
12001 				 * free it.
12002 				 */
12003 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12004 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12005 					freemsg(mp);
12006 					mutex_exit(&ipfb->ipfb_lock);
12007 					return (B_FALSE);
12008 				}
12009 				/* Found it. */
12010 				break;
12011 			}
12012 			ipfp = &ipf->ipf_hash_next;
12013 			continue;
12014 		}
12015 
12016 		/*
12017 		 * If we pruned the list, do we want to store this new
12018 		 * fragment?. We apply an optimization here based on the
12019 		 * fact that most fragments will be received in order.
12020 		 * So if the offset of this incoming fragment is zero,
12021 		 * it is the first fragment of a new packet. We will
12022 		 * keep it.  Otherwise drop the fragment, as we have
12023 		 * probably pruned the packet already (since the
12024 		 * packet cannot be found).
12025 		 */
12026 		if (pruned && offset != 0) {
12027 			mutex_exit(&ipfb->ipfb_lock);
12028 			freemsg(mp);
12029 			return (B_FALSE);
12030 		}
12031 
12032 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12033 			/*
12034 			 * Too many fragmented packets in this hash
12035 			 * bucket. Free the oldest.
12036 			 */
12037 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12038 		}
12039 
12040 		/* New guy.  Allocate a frag message. */
12041 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12042 		if (mp1 == NULL) {
12043 			BUMP_MIB(&ip_mib, ipInDiscards);
12044 			freemsg(mp);
12045 reass_done:
12046 			mutex_exit(&ipfb->ipfb_lock);
12047 			return (B_FALSE);
12048 		}
12049 
12050 
12051 		BUMP_MIB(&ip_mib, ipReasmReqds);
12052 		mp1->b_cont = mp;
12053 
12054 		/* Initialize the fragment header. */
12055 		ipf = (ipf_t *)mp1->b_rptr;
12056 		ipf->ipf_mp = mp1;
12057 		ipf->ipf_ptphn = ipfp;
12058 		ipfp[0] = ipf;
12059 		ipf->ipf_hash_next = NULL;
12060 		ipf->ipf_ident = ident;
12061 		ipf->ipf_protocol = proto;
12062 		ipf->ipf_src = src;
12063 		ipf->ipf_dst = dst;
12064 		ipf->ipf_nf_hdr_len = 0;
12065 		/* Record reassembly start time. */
12066 		ipf->ipf_timestamp = gethrestime_sec();
12067 		/* Record ipf generation and account for frag header */
12068 		ipf->ipf_gen = ill->ill_ipf_gen++;
12069 		ipf->ipf_count = MBLKSIZE(mp1);
12070 		ipf->ipf_last_frag_seen = B_FALSE;
12071 		ipf->ipf_ecn = ecn_info;
12072 		ipf->ipf_num_dups = 0;
12073 		ipfb->ipfb_frag_pkts++;
12074 		ipf->ipf_checksum = 0;
12075 		ipf->ipf_checksum_flags = 0;
12076 
12077 		/* Store checksum value in fragment header */
12078 		if (sum_flags != 0) {
12079 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12080 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12081 			ipf->ipf_checksum = sum_val;
12082 			ipf->ipf_checksum_flags = sum_flags;
12083 		}
12084 
12085 		/*
12086 		 * We handle reassembly two ways.  In the easy case,
12087 		 * where all the fragments show up in order, we do
12088 		 * minimal bookkeeping, and just clip new pieces on
12089 		 * the end.  If we ever see a hole, then we go off
12090 		 * to ip_reassemble which has to mark the pieces and
12091 		 * keep track of the number of holes, etc.  Obviously,
12092 		 * the point of having both mechanisms is so we can
12093 		 * handle the easy case as efficiently as possible.
12094 		 */
12095 		if (offset == 0) {
12096 			/* Easy case, in-order reassembly so far. */
12097 			ipf->ipf_count += msg_len;
12098 			ipf->ipf_tail_mp = tail_mp;
12099 			/*
12100 			 * Keep track of next expected offset in
12101 			 * ipf_end.
12102 			 */
12103 			ipf->ipf_end = end;
12104 			ipf->ipf_nf_hdr_len = hdr_length;
12105 		} else {
12106 			/* Hard case, hole at the beginning. */
12107 			ipf->ipf_tail_mp = NULL;
12108 			/*
12109 			 * ipf_end == 0 means that we have given up
12110 			 * on easy reassembly.
12111 			 */
12112 			ipf->ipf_end = 0;
12113 
12114 			/* Forget checksum offload from now on */
12115 			ipf->ipf_checksum_flags = 0;
12116 
12117 			/*
12118 			 * ipf_hole_cnt is set by ip_reassemble.
12119 			 * ipf_count is updated by ip_reassemble.
12120 			 * No need to check for return value here
12121 			 * as we don't expect reassembly to complete
12122 			 * or fail for the first fragment itself.
12123 			 */
12124 			(void) ip_reassemble(mp, ipf,
12125 			    (frag_offset_flags & IPH_OFFSET) << 3,
12126 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12127 		}
12128 		/* Update per ipfb and ill byte counts */
12129 		ipfb->ipfb_count += ipf->ipf_count;
12130 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12131 		ill->ill_frag_count += ipf->ipf_count;
12132 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12133 		/* If the frag timer wasn't already going, start it. */
12134 		mutex_enter(&ill->ill_lock);
12135 		ill_frag_timer_start(ill);
12136 		mutex_exit(&ill->ill_lock);
12137 		goto reass_done;
12138 	}
12139 
12140 	/*
12141 	 * If the packet's flag has changed (it could be coming up
12142 	 * from an interface different than the previous, therefore
12143 	 * possibly different checksum capability), then forget about
12144 	 * any stored checksum states.  Otherwise add the value to
12145 	 * the existing one stored in the fragment header.
12146 	 */
12147 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12148 		sum_val += ipf->ipf_checksum;
12149 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12150 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12151 		ipf->ipf_checksum = sum_val;
12152 	} else if (ipf->ipf_checksum_flags != 0) {
12153 		/* Forget checksum offload from now on */
12154 		ipf->ipf_checksum_flags = 0;
12155 	}
12156 
12157 	/*
12158 	 * We have a new piece of a datagram which is already being
12159 	 * reassembled.  Update the ECN info if all IP fragments
12160 	 * are ECN capable.  If there is one which is not, clear
12161 	 * all the info.  If there is at least one which has CE
12162 	 * code point, IP needs to report that up to transport.
12163 	 */
12164 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12165 		if (ecn_info == IPH_ECN_CE)
12166 			ipf->ipf_ecn = IPH_ECN_CE;
12167 	} else {
12168 		ipf->ipf_ecn = IPH_ECN_NECT;
12169 	}
12170 	if (offset && ipf->ipf_end == offset) {
12171 		/* The new fragment fits at the end */
12172 		ipf->ipf_tail_mp->b_cont = mp;
12173 		/* Update the byte count */
12174 		ipf->ipf_count += msg_len;
12175 		/* Update per ipfb and ill byte counts */
12176 		ipfb->ipfb_count += msg_len;
12177 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12178 		ill->ill_frag_count += msg_len;
12179 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12180 		if (frag_offset_flags & IPH_MF) {
12181 			/* More to come. */
12182 			ipf->ipf_end = end;
12183 			ipf->ipf_tail_mp = tail_mp;
12184 			goto reass_done;
12185 		}
12186 	} else {
12187 		/* Go do the hard cases. */
12188 		int ret;
12189 
12190 		if (offset == 0)
12191 			ipf->ipf_nf_hdr_len = hdr_length;
12192 
12193 		/* Save current byte count */
12194 		count = ipf->ipf_count;
12195 		ret = ip_reassemble(mp, ipf,
12196 		    (frag_offset_flags & IPH_OFFSET) << 3,
12197 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12198 		/* Count of bytes added and subtracted (freeb()ed) */
12199 		count = ipf->ipf_count - count;
12200 		if (count) {
12201 			/* Update per ipfb and ill byte counts */
12202 			ipfb->ipfb_count += count;
12203 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12204 			ill->ill_frag_count += count;
12205 			ASSERT(ill->ill_frag_count > 0);
12206 		}
12207 		if (ret == IP_REASS_PARTIAL) {
12208 			goto reass_done;
12209 		} else if (ret == IP_REASS_FAILED) {
12210 			/* Reassembly failed. Free up all resources */
12211 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12212 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12213 				IP_REASS_SET_START(t_mp, 0);
12214 				IP_REASS_SET_END(t_mp, 0);
12215 			}
12216 			freemsg(mp);
12217 			goto reass_done;
12218 		}
12219 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12220 	}
12221 	/*
12222 	 * We have completed reassembly.  Unhook the frag header from
12223 	 * the reassembly list.
12224 	 *
12225 	 * Before we free the frag header, record the ECN info
12226 	 * to report back to the transport.
12227 	 */
12228 	ecn_info = ipf->ipf_ecn;
12229 	BUMP_MIB(&ip_mib, ipReasmOKs);
12230 	ipfp = ipf->ipf_ptphn;
12231 
12232 	/* We need to supply these to caller */
12233 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12234 		sum_val = ipf->ipf_checksum;
12235 	else
12236 		sum_val = 0;
12237 
12238 	mp1 = ipf->ipf_mp;
12239 	count = ipf->ipf_count;
12240 	ipf = ipf->ipf_hash_next;
12241 	if (ipf != NULL)
12242 		ipf->ipf_ptphn = ipfp;
12243 	ipfp[0] = ipf;
12244 	ill->ill_frag_count -= count;
12245 	ASSERT(ipfb->ipfb_count >= count);
12246 	ipfb->ipfb_count -= count;
12247 	ipfb->ipfb_frag_pkts--;
12248 	mutex_exit(&ipfb->ipfb_lock);
12249 	/* Ditch the frag header. */
12250 	mp = mp1->b_cont;
12251 
12252 	freeb(mp1);
12253 
12254 	/* Restore original IP length in header. */
12255 	packet_size = (uint32_t)msgdsize(mp);
12256 	if (packet_size > IP_MAXPACKET) {
12257 		freemsg(mp);
12258 		BUMP_MIB(&ip_mib, ipInHdrErrors);
12259 		return (B_FALSE);
12260 	}
12261 
12262 	if (DB_REF(mp) > 1) {
12263 		mblk_t *mp2 = copymsg(mp);
12264 
12265 		freemsg(mp);
12266 		if (mp2 == NULL) {
12267 			BUMP_MIB(&ip_mib, ipInDiscards);
12268 			return (B_FALSE);
12269 		}
12270 		mp = mp2;
12271 	}
12272 	ipha = (ipha_t *)mp->b_rptr;
12273 
12274 	ipha->ipha_length = htons((uint16_t)packet_size);
12275 	/* We're now complete, zip the frag state */
12276 	ipha->ipha_fragment_offset_and_flags = 0;
12277 	/* Record the ECN info. */
12278 	ipha->ipha_type_of_service &= 0xFC;
12279 	ipha->ipha_type_of_service |= ecn_info;
12280 	*mpp = mp;
12281 
12282 	/* Reassembly is successful; return checksum information if needed */
12283 	if (cksum_val != NULL)
12284 		*cksum_val = sum_val;
12285 	if (cksum_flags != NULL)
12286 		*cksum_flags = sum_flags;
12287 
12288 	return (B_TRUE);
12289 }
12290 
12291 /*
12292  * Perform ip header check sum update local options.
12293  * return B_TRUE if all is well, else return B_FALSE and release
12294  * the mp. caller is responsible for decrementing ire ref cnt.
12295  */
12296 static boolean_t
12297 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12298 {
12299 	mblk_t		*first_mp;
12300 	boolean_t	mctl_present;
12301 	uint16_t	sum;
12302 
12303 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12304 	/*
12305 	 * Don't do the checksum if it has gone through AH/ESP
12306 	 * processing.
12307 	 */
12308 	if (!mctl_present) {
12309 		sum = ip_csum_hdr(ipha);
12310 		if (sum != 0) {
12311 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12312 			freemsg(first_mp);
12313 			return (B_FALSE);
12314 		}
12315 	}
12316 
12317 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12318 		if (mctl_present)
12319 			freeb(first_mp);
12320 		return (B_FALSE);
12321 	}
12322 
12323 	return (B_TRUE);
12324 }
12325 
12326 /*
12327  * All udp packet are delivered to the local host via this routine.
12328  */
12329 void
12330 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12331     ill_t *recv_ill)
12332 {
12333 	uint32_t	sum;
12334 	uint32_t	u1;
12335 	boolean_t	mctl_present;
12336 	conn_t		*connp;
12337 	mblk_t		*first_mp;
12338 	uint16_t	*up;
12339 	ill_t		*ill = (ill_t *)q->q_ptr;
12340 	uint16_t	reass_hck_flags = 0;
12341 
12342 #define	rptr    ((uchar_t *)ipha)
12343 
12344 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12345 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12346 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12347 
12348 	/*
12349 	 * FAST PATH for udp packets
12350 	 */
12351 
12352 	/* u1 is # words of IP options */
12353 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12354 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12355 
12356 	/* IP options present */
12357 	if (u1 != 0)
12358 		goto ipoptions;
12359 
12360 	/* Check the IP header checksum.  */
12361 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12362 		/* Clear the IP header h/w cksum flag */
12363 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12364 	} else {
12365 #define	uph	((uint16_t *)ipha)
12366 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12367 		    uph[6] + uph[7] + uph[8] + uph[9];
12368 #undef	uph
12369 		/* finish doing IP checksum */
12370 		sum = (sum & 0xFFFF) + (sum >> 16);
12371 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12372 		/*
12373 		 * Don't verify header checksum if this packet is coming
12374 		 * back from AH/ESP as we already did it.
12375 		 */
12376 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12377 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12378 			freemsg(first_mp);
12379 			return;
12380 		}
12381 	}
12382 
12383 	/*
12384 	 * Count for SNMP of inbound packets for ire.
12385 	 * if mctl is present this might be a secure packet and
12386 	 * has already been counted for in ip_proto_input().
12387 	 */
12388 	if (!mctl_present) {
12389 		UPDATE_IB_PKT_COUNT(ire);
12390 		ire->ire_last_used_time = lbolt;
12391 	}
12392 
12393 	/* packet part of fragmented IP packet? */
12394 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12395 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12396 		goto fragmented;
12397 	}
12398 
12399 	/* u1 = IP header length (20 bytes) */
12400 	u1 = IP_SIMPLE_HDR_LENGTH;
12401 
12402 	/* packet does not contain complete IP & UDP headers */
12403 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12404 		goto udppullup;
12405 
12406 	/* up points to UDP header */
12407 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12408 #define	iphs    ((uint16_t *)ipha)
12409 
12410 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12411 	if (up[3] != 0) {
12412 		mblk_t *mp1 = mp->b_cont;
12413 		boolean_t cksum_err;
12414 		uint16_t hck_flags = 0;
12415 
12416 		/* Pseudo-header checksum */
12417 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12418 		    iphs[9] + up[2];
12419 
12420 		/*
12421 		 * Revert to software checksum calculation if the interface
12422 		 * isn't capable of checksum offload or if IPsec is present.
12423 		 */
12424 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12425 			hck_flags = DB_CKSUMFLAGS(mp);
12426 
12427 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12428 			IP_STAT(ip_in_sw_cksum);
12429 
12430 		IP_CKSUM_RECV(hck_flags, u1,
12431 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12432 		    (int32_t)((uchar_t *)up - rptr),
12433 		    mp, mp1, cksum_err);
12434 
12435 		if (cksum_err) {
12436 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12437 
12438 			if (hck_flags & HCK_FULLCKSUM)
12439 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12440 			else if (hck_flags & HCK_PARTIALCKSUM)
12441 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12442 			else
12443 				IP_STAT(ip_udp_in_sw_cksum_err);
12444 
12445 			freemsg(first_mp);
12446 			return;
12447 		}
12448 	}
12449 
12450 	/* Non-fragmented broadcast or multicast packet? */
12451 	if (ire->ire_type == IRE_BROADCAST)
12452 		goto udpslowpath;
12453 
12454 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12455 	    ire->ire_zoneid)) != NULL) {
12456 		ASSERT(connp->conn_upq != NULL);
12457 		IP_STAT(ip_udp_fast_path);
12458 
12459 		if (CONN_UDP_FLOWCTLD(connp)) {
12460 			freemsg(mp);
12461 			BUMP_MIB(&ip_mib, udpInOverflows);
12462 		} else {
12463 			if (!mctl_present) {
12464 				BUMP_MIB(&ip_mib, ipInDelivers);
12465 			}
12466 			/*
12467 			 * mp and first_mp can change.
12468 			 */
12469 			if (ip_udp_check(q, connp, recv_ill,
12470 			    ipha, &mp, &first_mp, mctl_present)) {
12471 				/* Send it upstream */
12472 				CONN_UDP_RECV(connp, mp);
12473 			}
12474 		}
12475 		/*
12476 		 * freeb() cannot deal with null mblk being passed
12477 		 * in and first_mp can be set to null in the call
12478 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12479 		 */
12480 		if (mctl_present && first_mp != NULL) {
12481 			freeb(first_mp);
12482 		}
12483 		CONN_DEC_REF(connp);
12484 		return;
12485 	}
12486 
12487 	/*
12488 	 * if we got here we know the packet is not fragmented and
12489 	 * has no options. The classifier could not find a conn_t and
12490 	 * most likely its an icmp packet so send it through slow path.
12491 	 */
12492 
12493 	goto udpslowpath;
12494 
12495 ipoptions:
12496 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12497 		goto slow_done;
12498 	}
12499 
12500 	UPDATE_IB_PKT_COUNT(ire);
12501 	ire->ire_last_used_time = lbolt;
12502 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12503 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12504 fragmented:
12505 		/*
12506 		 * "sum" and "reass_hck_flags" are non-zero if the
12507 		 * reassembled packet has a valid hardware computed
12508 		 * checksum information associated with it.
12509 		 */
12510 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12511 			goto slow_done;
12512 		/*
12513 		 * Make sure that first_mp points back to mp as
12514 		 * the mp we came in with could have changed in
12515 		 * ip_rput_fragment().
12516 		 */
12517 		ASSERT(!mctl_present);
12518 		ipha = (ipha_t *)mp->b_rptr;
12519 		first_mp = mp;
12520 	}
12521 
12522 	/* Now we have a complete datagram, destined for this machine. */
12523 	u1 = IPH_HDR_LENGTH(ipha);
12524 	/* Pull up the UDP header, if necessary. */
12525 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12526 udppullup:
12527 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12528 			BUMP_MIB(&ip_mib, ipInDiscards);
12529 			freemsg(first_mp);
12530 			goto slow_done;
12531 		}
12532 		ipha = (ipha_t *)mp->b_rptr;
12533 	}
12534 
12535 	/*
12536 	 * Validate the checksum for the reassembled packet; for the
12537 	 * pullup case we calculate the payload checksum in software.
12538 	 */
12539 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12540 	if (up[3] != 0) {
12541 		boolean_t cksum_err;
12542 
12543 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12544 			IP_STAT(ip_in_sw_cksum);
12545 
12546 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12547 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12548 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12549 		    iphs[9] + up[2], sum, cksum_err);
12550 
12551 		if (cksum_err) {
12552 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12553 
12554 			if (reass_hck_flags & HCK_FULLCKSUM)
12555 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12556 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12557 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12558 			else
12559 				IP_STAT(ip_udp_in_sw_cksum_err);
12560 
12561 			freemsg(first_mp);
12562 			goto slow_done;
12563 		}
12564 	}
12565 udpslowpath:
12566 
12567 	/* Clear hardware checksum flag to be safe */
12568 	DB_CKSUMFLAGS(mp) = 0;
12569 
12570 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12571 	    (ire->ire_type == IRE_BROADCAST),
12572 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12573 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12574 
12575 slow_done:
12576 	IP_STAT(ip_udp_slow_path);
12577 	return;
12578 
12579 #undef  iphs
12580 #undef  rptr
12581 }
12582 
12583 /* ARGSUSED */
12584 static mblk_t *
12585 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12586     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12587     ill_rx_ring_t *ill_ring)
12588 {
12589 	conn_t		*connp;
12590 	uint32_t	sum;
12591 	uint32_t	u1;
12592 	uint16_t	*up;
12593 	int		offset;
12594 	ssize_t		len;
12595 	mblk_t		*mp1;
12596 	boolean_t	syn_present = B_FALSE;
12597 	tcph_t		*tcph;
12598 	uint_t		ip_hdr_len;
12599 	ill_t		*ill = (ill_t *)q->q_ptr;
12600 	zoneid_t	zoneid = ire->ire_zoneid;
12601 	boolean_t	cksum_err;
12602 	uint16_t	hck_flags = 0;
12603 
12604 #define	rptr	((uchar_t *)ipha)
12605 
12606 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12607 
12608 	/*
12609 	 * FAST PATH for tcp packets
12610 	 */
12611 
12612 	/* u1 is # words of IP options */
12613 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12614 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12615 
12616 	/* IP options present */
12617 	if (u1) {
12618 		goto ipoptions;
12619 	} else {
12620 		/* Check the IP header checksum.  */
12621 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12622 			/* Clear the IP header h/w cksum flag */
12623 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12624 		} else {
12625 #define	uph	((uint16_t *)ipha)
12626 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12627 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12628 #undef	uph
12629 			/* finish doing IP checksum */
12630 			sum = (sum & 0xFFFF) + (sum >> 16);
12631 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12632 			/*
12633 			 * Don't verify header checksum if this packet
12634 			 * is coming back from AH/ESP as we already did it.
12635 			 */
12636 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12637 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12638 				goto error;
12639 			}
12640 		}
12641 	}
12642 
12643 	if (!mctl_present) {
12644 		UPDATE_IB_PKT_COUNT(ire);
12645 		ire->ire_last_used_time = lbolt;
12646 	}
12647 
12648 	/* packet part of fragmented IP packet? */
12649 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12650 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12651 		goto fragmented;
12652 	}
12653 
12654 	/* u1 = IP header length (20 bytes) */
12655 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12656 
12657 	/* does packet contain IP+TCP headers? */
12658 	len = mp->b_wptr - rptr;
12659 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12660 		IP_STAT(ip_tcppullup);
12661 		goto tcppullup;
12662 	}
12663 
12664 	/* TCP options present? */
12665 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12666 
12667 	/*
12668 	 * If options need to be pulled up, then goto tcpoptions.
12669 	 * otherwise we are still in the fast path
12670 	 */
12671 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12672 		IP_STAT(ip_tcpoptions);
12673 		goto tcpoptions;
12674 	}
12675 
12676 	/* multiple mblks of tcp data? */
12677 	if ((mp1 = mp->b_cont) != NULL) {
12678 		/* more then two? */
12679 		if (mp1->b_cont != NULL) {
12680 			IP_STAT(ip_multipkttcp);
12681 			goto multipkttcp;
12682 		}
12683 		len += mp1->b_wptr - mp1->b_rptr;
12684 	}
12685 
12686 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12687 
12688 	/* part of pseudo checksum */
12689 
12690 	/* TCP datagram length */
12691 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12692 
12693 #define	iphs    ((uint16_t *)ipha)
12694 
12695 #ifdef	_BIG_ENDIAN
12696 	u1 += IPPROTO_TCP;
12697 #else
12698 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12699 #endif
12700 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12701 
12702 	/*
12703 	 * Revert to software checksum calculation if the interface
12704 	 * isn't capable of checksum offload or if IPsec is present.
12705 	 */
12706 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12707 		hck_flags = DB_CKSUMFLAGS(mp);
12708 
12709 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12710 		IP_STAT(ip_in_sw_cksum);
12711 
12712 	IP_CKSUM_RECV(hck_flags, u1,
12713 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12714 	    (int32_t)((uchar_t *)up - rptr),
12715 	    mp, mp1, cksum_err);
12716 
12717 	if (cksum_err) {
12718 		BUMP_MIB(&ip_mib, tcpInErrs);
12719 
12720 		if (hck_flags & HCK_FULLCKSUM)
12721 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12722 		else if (hck_flags & HCK_PARTIALCKSUM)
12723 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12724 		else
12725 			IP_STAT(ip_tcp_in_sw_cksum_err);
12726 
12727 		goto error;
12728 	}
12729 
12730 try_again:
12731 
12732 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12733 	    NULL) {
12734 		/* Send the TH_RST */
12735 		goto no_conn;
12736 	}
12737 
12738 	/*
12739 	 * TCP FAST PATH for AF_INET socket.
12740 	 *
12741 	 * TCP fast path to avoid extra work. An AF_INET socket type
12742 	 * does not have facility to receive extra information via
12743 	 * ip_process or ip_add_info. Also, when the connection was
12744 	 * established, we made a check if this connection is impacted
12745 	 * by any global IPSec policy or per connection policy (a
12746 	 * policy that comes in effect later will not apply to this
12747 	 * connection). Since all this can be determined at the
12748 	 * connection establishment time, a quick check of flags
12749 	 * can avoid extra work.
12750 	 */
12751 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12752 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12753 		ASSERT(first_mp == mp);
12754 		SET_SQUEUE(mp, tcp_rput_data, connp);
12755 		return (mp);
12756 	}
12757 
12758 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12759 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12760 		if (IPCL_IS_TCP(connp)) {
12761 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12762 			DB_CKSUMSTART(mp) =
12763 			    (intptr_t)ip_squeue_get(ill_ring);
12764 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12765 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12766 				SET_SQUEUE(mp, connp->conn_recv, connp);
12767 				return (mp);
12768 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12769 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12770 				ip_squeue_enter_unbound++;
12771 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12772 				    connp);
12773 				return (mp);
12774 			}
12775 			syn_present = B_TRUE;
12776 		}
12777 
12778 	}
12779 
12780 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12781 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12782 
12783 		/* No need to send this packet to TCP */
12784 		if ((flags & TH_RST) || (flags & TH_URG)) {
12785 			CONN_DEC_REF(connp);
12786 			freemsg(first_mp);
12787 			return (NULL);
12788 		}
12789 		if (flags & TH_ACK) {
12790 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
12791 			CONN_DEC_REF(connp);
12792 			return (NULL);
12793 		}
12794 
12795 		CONN_DEC_REF(connp);
12796 		freemsg(first_mp);
12797 		return (NULL);
12798 	}
12799 
12800 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12801 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12802 		    ipha, NULL, mctl_present);
12803 		if (first_mp == NULL) {
12804 			CONN_DEC_REF(connp);
12805 			return (NULL);
12806 		}
12807 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12808 			ASSERT(syn_present);
12809 			if (mctl_present) {
12810 				ASSERT(first_mp != mp);
12811 				first_mp->b_datap->db_struioflag |=
12812 				    STRUIO_POLICY;
12813 			} else {
12814 				ASSERT(first_mp == mp);
12815 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12816 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12817 			}
12818 		} else {
12819 			/*
12820 			 * Discard first_mp early since we're dealing with a
12821 			 * fully-connected conn_t and tcp doesn't do policy in
12822 			 * this case.
12823 			 */
12824 			if (mctl_present) {
12825 				freeb(first_mp);
12826 				mctl_present = B_FALSE;
12827 			}
12828 			first_mp = mp;
12829 		}
12830 	}
12831 
12832 	/* Initiate IPPF processing for fastpath */
12833 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12834 		uint32_t	ill_index;
12835 
12836 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12837 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12838 		if (mp == NULL) {
12839 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12840 			    "deferred/dropped during IPPF processing\n"));
12841 			CONN_DEC_REF(connp);
12842 			if (mctl_present)
12843 				freeb(first_mp);
12844 			return (NULL);
12845 		} else if (mctl_present) {
12846 			/*
12847 			 * ip_process might return a new mp.
12848 			 */
12849 			ASSERT(first_mp != mp);
12850 			first_mp->b_cont = mp;
12851 		} else {
12852 			first_mp = mp;
12853 		}
12854 
12855 	}
12856 
12857 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12858 		mp = ip_add_info(mp, recv_ill, flags);
12859 		if (mp == NULL) {
12860 			CONN_DEC_REF(connp);
12861 			if (mctl_present)
12862 				freeb(first_mp);
12863 			return (NULL);
12864 		} else if (mctl_present) {
12865 			/*
12866 			 * ip_add_info might return a new mp.
12867 			 */
12868 			ASSERT(first_mp != mp);
12869 			first_mp->b_cont = mp;
12870 		} else {
12871 			first_mp = mp;
12872 		}
12873 	}
12874 
12875 	if (IPCL_IS_TCP(connp)) {
12876 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
12877 		return (first_mp);
12878 	} else {
12879 		putnext(connp->conn_rq, first_mp);
12880 		CONN_DEC_REF(connp);
12881 		return (NULL);
12882 	}
12883 
12884 no_conn:
12885 	/* Initiate IPPf processing, if needed. */
12886 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12887 		uint32_t ill_index;
12888 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12889 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
12890 		if (first_mp == NULL) {
12891 			return (NULL);
12892 		}
12893 	}
12894 	BUMP_MIB(&ip_mib, ipInDelivers);
12895 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
12896 	return (NULL);
12897 ipoptions:
12898 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
12899 		goto slow_done;
12900 	}
12901 
12902 	UPDATE_IB_PKT_COUNT(ire);
12903 	ire->ire_last_used_time = lbolt;
12904 
12905 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12906 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12907 fragmented:
12908 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
12909 			if (mctl_present)
12910 				freeb(first_mp);
12911 			goto slow_done;
12912 		}
12913 		/*
12914 		 * Make sure that first_mp points back to mp as
12915 		 * the mp we came in with could have changed in
12916 		 * ip_rput_fragment().
12917 		 */
12918 		ASSERT(!mctl_present);
12919 		ipha = (ipha_t *)mp->b_rptr;
12920 		first_mp = mp;
12921 	}
12922 
12923 	/* Now we have a complete datagram, destined for this machine. */
12924 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12925 
12926 	len = mp->b_wptr - mp->b_rptr;
12927 	/* Pull up a minimal TCP header, if necessary. */
12928 	if (len < (u1 + 20)) {
12929 tcppullup:
12930 		if (!pullupmsg(mp, u1 + 20)) {
12931 			BUMP_MIB(&ip_mib, ipInDiscards);
12932 			goto error;
12933 		}
12934 		ipha = (ipha_t *)mp->b_rptr;
12935 		len = mp->b_wptr - mp->b_rptr;
12936 	}
12937 
12938 	/*
12939 	 * Extract the offset field from the TCP header.  As usual, we
12940 	 * try to help the compiler more than the reader.
12941 	 */
12942 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
12943 	if (offset != 5) {
12944 tcpoptions:
12945 		if (offset < 5) {
12946 			BUMP_MIB(&ip_mib, ipInDiscards);
12947 			goto error;
12948 		}
12949 		/*
12950 		 * There must be TCP options.
12951 		 * Make sure we can grab them.
12952 		 */
12953 		offset <<= 2;
12954 		offset += u1;
12955 		if (len < offset) {
12956 			if (!pullupmsg(mp, offset)) {
12957 				BUMP_MIB(&ip_mib, ipInDiscards);
12958 				goto error;
12959 			}
12960 			ipha = (ipha_t *)mp->b_rptr;
12961 			len = mp->b_wptr - rptr;
12962 		}
12963 	}
12964 
12965 	/* Get the total packet length in len, including headers. */
12966 	if (mp->b_cont) {
12967 multipkttcp:
12968 		len = msgdsize(mp);
12969 	}
12970 
12971 	/*
12972 	 * Check the TCP checksum by pulling together the pseudo-
12973 	 * header checksum, and passing it to ip_csum to be added in
12974 	 * with the TCP datagram.
12975 	 *
12976 	 * Since we are not using the hwcksum if available we must
12977 	 * clear the flag. We may come here via tcppullup or tcpoptions.
12978 	 * If either of these fails along the way the mblk is freed.
12979 	 * If this logic ever changes and mblk is reused to say send
12980 	 * ICMP's back, then this flag may need to be cleared in
12981 	 * other places as well.
12982 	 */
12983 	DB_CKSUMFLAGS(mp) = 0;
12984 
12985 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
12986 
12987 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
12988 #ifdef	_BIG_ENDIAN
12989 	u1 += IPPROTO_TCP;
12990 #else
12991 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12992 #endif
12993 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12994 	/*
12995 	 * Not M_DATA mblk or its a dup, so do the checksum now.
12996 	 */
12997 	IP_STAT(ip_in_sw_cksum);
12998 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
12999 		BUMP_MIB(&ip_mib, tcpInErrs);
13000 		goto error;
13001 	}
13002 
13003 	IP_STAT(ip_tcp_slow_path);
13004 	goto try_again;
13005 #undef  iphs
13006 #undef  rptr
13007 
13008 error:
13009 	freemsg(first_mp);
13010 slow_done:
13011 	return (NULL);
13012 }
13013 
13014 /* ARGSUSED */
13015 static void
13016 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13017     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13018 {
13019 	conn_t		*connp;
13020 	uint32_t	sum;
13021 	uint32_t	u1;
13022 	ssize_t		len;
13023 	sctp_hdr_t	*sctph;
13024 	zoneid_t	zoneid = ire->ire_zoneid;
13025 	uint32_t	pktsum;
13026 	uint32_t	calcsum;
13027 	uint32_t	ports;
13028 	uint_t		ipif_seqid;
13029 	in6_addr_t	map_src, map_dst;
13030 	ill_t		*ill = (ill_t *)q->q_ptr;
13031 
13032 #define	rptr	((uchar_t *)ipha)
13033 
13034 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13035 
13036 	/* u1 is # words of IP options */
13037 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13038 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13039 
13040 	/* IP options present */
13041 	if (u1 > 0) {
13042 		goto ipoptions;
13043 	} else {
13044 		/* Check the IP header checksum.  */
13045 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13046 #define	uph	((uint16_t *)ipha)
13047 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13048 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13049 #undef	uph
13050 			/* finish doing IP checksum */
13051 			sum = (sum & 0xFFFF) + (sum >> 16);
13052 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13053 			/*
13054 			 * Don't verify header checksum if this packet
13055 			 * is coming back from AH/ESP as we already did it.
13056 			 */
13057 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13058 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13059 				goto error;
13060 			}
13061 		}
13062 		/*
13063 		 * Since there is no SCTP h/w cksum support yet, just
13064 		 * clear the flag.
13065 		 */
13066 		DB_CKSUMFLAGS(mp) = 0;
13067 	}
13068 
13069 	/*
13070 	 * Don't verify header checksum if this packet is coming
13071 	 * back from AH/ESP as we already did it.
13072 	 */
13073 	if (!mctl_present) {
13074 		UPDATE_IB_PKT_COUNT(ire);
13075 		ire->ire_last_used_time = lbolt;
13076 	}
13077 
13078 	/* packet part of fragmented IP packet? */
13079 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13080 	if (u1 & (IPH_MF | IPH_OFFSET))
13081 		goto fragmented;
13082 
13083 	/* u1 = IP header length (20 bytes) */
13084 	u1 = IP_SIMPLE_HDR_LENGTH;
13085 
13086 find_sctp_client:
13087 	/* Pullup if we don't have the sctp common header. */
13088 	len = MBLKL(mp);
13089 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13090 		if (mp->b_cont == NULL ||
13091 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13092 			BUMP_MIB(&ip_mib, ipInDiscards);
13093 			goto error;
13094 		}
13095 		ipha = (ipha_t *)mp->b_rptr;
13096 		len = MBLKL(mp);
13097 	}
13098 
13099 	sctph = (sctp_hdr_t *)(rptr + u1);
13100 #ifdef	DEBUG
13101 	if (!skip_sctp_cksum) {
13102 #endif
13103 		pktsum = sctph->sh_chksum;
13104 		sctph->sh_chksum = 0;
13105 		calcsum = sctp_cksum(mp, u1);
13106 		if (calcsum != pktsum) {
13107 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13108 			goto error;
13109 		}
13110 		sctph->sh_chksum = pktsum;
13111 #ifdef	DEBUG	/* skip_sctp_cksum */
13112 	}
13113 #endif
13114 	/* get the ports */
13115 	ports = *(uint32_t *)&sctph->sh_sport;
13116 
13117 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13118 	IRE_REFRELE(ire);
13119 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13120 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13121 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13122 	    mp)) == NULL) {
13123 		/* Check for raw socket or OOTB handling */
13124 		goto no_conn;
13125 	}
13126 
13127 	/* Found a client; up it goes */
13128 	BUMP_MIB(&ip_mib, ipInDelivers);
13129 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13130 	return;
13131 
13132 no_conn:
13133 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13134 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13135 	return;
13136 
13137 ipoptions:
13138 	DB_CKSUMFLAGS(mp) = 0;
13139 	if (!ip_options_cksum(q, first_mp, ipha, ire))
13140 		goto slow_done;
13141 
13142 	UPDATE_IB_PKT_COUNT(ire);
13143 	ire->ire_last_used_time = lbolt;
13144 
13145 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13146 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13147 fragmented:
13148 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13149 			goto slow_done;
13150 		/*
13151 		 * Make sure that first_mp points back to mp as
13152 		 * the mp we came in with could have changed in
13153 		 * ip_rput_fragment().
13154 		 */
13155 		ASSERT(!mctl_present);
13156 		ipha = (ipha_t *)mp->b_rptr;
13157 		first_mp = mp;
13158 	}
13159 
13160 	/* Now we have a complete datagram, destined for this machine. */
13161 	u1 = IPH_HDR_LENGTH(ipha);
13162 	goto find_sctp_client;
13163 #undef  iphs
13164 #undef  rptr
13165 
13166 error:
13167 	freemsg(first_mp);
13168 slow_done:
13169 	IRE_REFRELE(ire);
13170 }
13171 
13172 #define	VER_BITS	0xF0
13173 #define	VERSION_6	0x60
13174 
13175 static boolean_t
13176 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
13177     ipaddr_t *dstp)
13178 {
13179 	uint_t	opt_len;
13180 	ipha_t *ipha;
13181 	ssize_t len;
13182 	uint_t	pkt_len;
13183 
13184 	IP_STAT(ip_ipoptions);
13185 	ipha = *iphapp;
13186 
13187 #define	rptr    ((uchar_t *)ipha)
13188 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13189 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13190 		BUMP_MIB(&ip_mib, ipInIPv6);
13191 		freemsg(mp);
13192 		return (B_FALSE);
13193 	}
13194 
13195 	/* multiple mblk or too short */
13196 	pkt_len = ntohs(ipha->ipha_length);
13197 
13198 	/* Get the number of words of IP options in the IP header. */
13199 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13200 	if (opt_len) {
13201 		/* IP Options present!  Validate and process. */
13202 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13203 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13204 			goto done;
13205 		}
13206 		/*
13207 		 * Recompute complete header length and make sure we
13208 		 * have access to all of it.
13209 		 */
13210 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13211 		if (len > (mp->b_wptr - rptr)) {
13212 			if (len > pkt_len) {
13213 				BUMP_MIB(&ip_mib, ipInHdrErrors);
13214 				goto done;
13215 			}
13216 			if (!pullupmsg(mp, len)) {
13217 				BUMP_MIB(&ip_mib, ipInDiscards);
13218 				goto done;
13219 			}
13220 			ipha = (ipha_t *)mp->b_rptr;
13221 		}
13222 		/*
13223 		 * Go off to ip_rput_options which returns the next hop
13224 		 * destination address, which may have been affected
13225 		 * by source routing.
13226 		 */
13227 		IP_STAT(ip_opt);
13228 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13229 			return (B_FALSE);
13230 		}
13231 	}
13232 	*iphapp = ipha;
13233 	return (B_TRUE);
13234 done:
13235 	/* clear b_prev - used by ip_mroute_decap */
13236 	mp->b_prev = NULL;
13237 	freemsg(mp);
13238 	return (B_FALSE);
13239 #undef  rptr
13240 }
13241 
13242 /*
13243  * Deal with the fact that there is no ire for the destination.
13244  * The incoming ill (in_ill) is passed in to ip_newroute only
13245  * in the case of packets coming from mobile ip forward tunnel.
13246  * It must be null otherwise.
13247  */
13248 static ire_t *
13249 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13250     ipaddr_t dst)
13251 {
13252 	ipha_t	*ipha;
13253 	ill_t	*ill;
13254 	ire_t	*ire;
13255 	boolean_t	check_multirt = B_FALSE;
13256 
13257 	ipha = (ipha_t *)mp->b_rptr;
13258 	ill = (ill_t *)q->q_ptr;
13259 
13260 	ASSERT(ill != NULL);
13261 	/*
13262 	 * No IRE for this destination, so it can't be for us.
13263 	 * Unless we are forwarding, drop the packet.
13264 	 * We have to let source routed packets through
13265 	 * since we don't yet know if they are 'ping -l'
13266 	 * packets i.e. if they will go out over the
13267 	 * same interface as they came in on.
13268 	 */
13269 	if (ll_multicast) {
13270 		freemsg(mp);
13271 		return (NULL);
13272 	}
13273 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13274 		BUMP_MIB(&ip_mib, ipForwProhibits);
13275 		freemsg(mp);
13276 		return (NULL);
13277 	}
13278 
13279 	/*
13280 	 * Mark this packet as having originated externally.
13281 	 *
13282 	 * For non-forwarding code path, ire_send later double
13283 	 * checks this interface to see if it is still exists
13284 	 * post-ARP resolution.
13285 	 *
13286 	 * Also, IPQOS uses this to differentiate between
13287 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13288 	 * QOS packet processing in ip_wput_attach_llhdr().
13289 	 * The QoS module can mark the b_band for a fastpath message
13290 	 * or the dl_priority field in a unitdata_req header for
13291 	 * CoS marking. This info can only be found in
13292 	 * ip_wput_attach_llhdr().
13293 	 */
13294 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13295 	/*
13296 	 * Clear the indication that this may have a hardware checksum
13297 	 * as we are not using it
13298 	 */
13299 	DB_CKSUMFLAGS(mp) = 0;
13300 
13301 	if (in_ill != NULL) {
13302 		/*
13303 		 * Now hand the packet to ip_newroute.
13304 		 */
13305 		ip_newroute(q, mp, dst, in_ill, NULL);
13306 		return (NULL);
13307 	}
13308 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13309 	    MBLK_GETLABEL(mp));
13310 
13311 	if (ire == NULL && check_multirt) {
13312 		/* Let ip_newroute handle CGTP  */
13313 		ip_newroute(q, mp, dst, in_ill, NULL);
13314 		return (NULL);
13315 	}
13316 
13317 	if (ire != NULL)
13318 		return (ire);
13319 
13320 	mp->b_prev = mp->b_next = 0;
13321 	/* send icmp unreachable */
13322 	q = WR(q);
13323 	if (ip_source_routed(ipha))
13324 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
13325 	else
13326 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
13327 
13328 	return (NULL);
13329 
13330 }
13331 
13332 /*
13333  * check ip header length and align it.
13334  */
13335 static boolean_t
13336 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13337 {
13338 	ssize_t len;
13339 	ill_t *ill;
13340 	ipha_t	*ipha;
13341 
13342 	len = MBLKL(mp);
13343 
13344 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13345 		if (!OK_32PTR(mp->b_rptr))
13346 			IP_STAT(ip_notaligned1);
13347 		else
13348 			IP_STAT(ip_notaligned2);
13349 		/* Guard against bogus device drivers */
13350 		if (len < 0) {
13351 			/* clear b_prev - used by ip_mroute_decap */
13352 			mp->b_prev = NULL;
13353 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13354 			freemsg(mp);
13355 			return (B_FALSE);
13356 		}
13357 
13358 		if (ip_rput_pullups++ == 0) {
13359 			ill = (ill_t *)q->q_ptr;
13360 			ipha = (ipha_t *)mp->b_rptr;
13361 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13362 			    "ip_check_and_align_header: %s forced us to "
13363 			    " pullup pkt, hdr len %ld, hdr addr %p",
13364 			    ill->ill_name, len, ipha);
13365 		}
13366 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13367 			/* clear b_prev - used by ip_mroute_decap */
13368 			mp->b_prev = NULL;
13369 			BUMP_MIB(&ip_mib, ipInDiscards);
13370 			freemsg(mp);
13371 			return (B_FALSE);
13372 		}
13373 	}
13374 	return (B_TRUE);
13375 }
13376 
13377 static boolean_t
13378 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13379 {
13380 	ill_group_t	*ill_group;
13381 	ill_group_t	*ire_group;
13382 	queue_t 	*q;
13383 	ill_t		*ire_ill;
13384 	uint_t		ill_ifindex;
13385 
13386 	q = *qp;
13387 	/*
13388 	 * We need to check to make sure the packet came in
13389 	 * on the queue associated with the destination IRE.
13390 	 * Note that for multicast packets and broadcast packets sent to
13391 	 * a broadcast address which is shared between multiple interfaces
13392 	 * we should not do this since we just got a random broadcast ire.
13393 	 */
13394 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13395 		boolean_t check_multi = B_TRUE;
13396 
13397 		/*
13398 		 * This packet came in on an interface other than the
13399 		 * one associated with the destination address.
13400 		 * "Gateway" it to the appropriate interface here.
13401 		 * As long as the ills belong to the same group,
13402 		 * we don't consider them to arriving on the wrong
13403 		 * interface. Thus, when the switch is doing inbound
13404 		 * load spreading, we won't drop packets when we
13405 		 * are doing strict multihoming checks. Note, the
13406 		 * same holds true for 'usesrc groups' where the
13407 		 * destination address may belong to another interface
13408 		 * to allow multipathing to happen
13409 		 */
13410 		ill_group = ill->ill_group;
13411 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13412 		ill_ifindex = ill->ill_usesrc_ifindex;
13413 		ire_group = ire_ill->ill_group;
13414 
13415 		/*
13416 		 * If it's part of the same IPMP group, or if it's a legal
13417 		 * address on the 'usesrc' interface, then bypass strict
13418 		 * checks.
13419 		 */
13420 		if (ill_group != NULL && ill_group == ire_group) {
13421 			check_multi = B_FALSE;
13422 		} else if (ill_ifindex != 0 &&
13423 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13424 			check_multi = B_FALSE;
13425 		}
13426 
13427 		if (check_multi &&
13428 		    ip_strict_dst_multihoming &&
13429 		    ((ill->ill_flags &
13430 		    ire->ire_ipif->ipif_ill->ill_flags &
13431 		    ILLF_ROUTER) == 0)) {
13432 			/* Drop packet */
13433 			BUMP_MIB(&ip_mib, ipForwProhibits);
13434 			freemsg(mp);
13435 			return (B_TRUE);
13436 		}
13437 
13438 		/*
13439 		 * Change the queue (for non-virtual destination network
13440 		 * interfaces) and ip_rput_local will be called with the right
13441 		 * queue
13442 		 */
13443 		q = ire->ire_rfq;
13444 	}
13445 	/* Must be broadcast.  We'll take it. */
13446 	*qp = q;
13447 	return (B_FALSE);
13448 }
13449 
13450 #define	SEND_PKT(ire, mp)			\
13451 {						\
13452 	UPDATE_IB_PKT_COUNT(ire);		\
13453 	(ire)->ire_last_used_time = lbolt;	\
13454 	BUMP_MIB(&ip_mib, ipForwDatagrams);	\
13455 	putnext((ire)->ire_stq, mp);		\
13456 }
13457 
13458 ire_t *
13459 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13460 {
13461 	ipha_t	*ipha;
13462 	ipaddr_t ip_dst, ip_src;
13463 	ire_t	*src_ire = NULL;
13464 	ill_t	*stq_ill;
13465 	uint_t	hlen;
13466 	uint32_t sum;
13467 	queue_t	*dev_q;
13468 	boolean_t check_multirt = B_FALSE;
13469 
13470 
13471 	ipha = (ipha_t *)mp->b_rptr;
13472 
13473 	/*
13474 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13475 	 * The loopback address check for both src and dst has already
13476 	 * been checked in ip_input
13477 	 */
13478 	ip_dst = ntohl(dst);
13479 	ip_src = ntohl(ipha->ipha_src);
13480 
13481 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13482 	    IN_CLASSD(ip_src)) {
13483 		BUMP_MIB(&ip_mib, ipForwProhibits);
13484 		goto drop;
13485 	}
13486 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13487 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13488 
13489 	if (src_ire != NULL) {
13490 		BUMP_MIB(&ip_mib, ipForwProhibits);
13491 		goto drop;
13492 	}
13493 
13494 	/* No ire cache of nexthop. So first create one  */
13495 	if (ire == NULL) {
13496 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13497 		/*
13498 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13499 		 * is not set. So upon return from ire_forward
13500 		 * check_multirt should remain as false.
13501 		 */
13502 		ASSERT(!check_multirt);
13503 		if (ire == NULL) {
13504 			BUMP_MIB(&ip_mib, ipInDiscards);
13505 			mp->b_prev = mp->b_next = 0;
13506 			/* send icmp unreachable */
13507 			if (ip_source_routed(ipha)) {
13508 				icmp_unreachable(ill->ill_wq, mp,
13509 				    ICMP_SOURCE_ROUTE_FAILED);
13510 			} else {
13511 				icmp_unreachable(ill->ill_wq, mp,
13512 				    ICMP_HOST_UNREACHABLE);
13513 			}
13514 			return (ire);
13515 		}
13516 	}
13517 
13518 	/*
13519 	 * Forwarding fastpath exception case:
13520 	 * If either of the follwoing case is true, we take
13521 	 * the slowpath
13522 	 *	o forwarding is not enabled
13523 	 *	o IPMP is enabled
13524 	 *	o corresponding ire is in incomplete state
13525 	 *	o packet needs fragmentation
13526 	 *
13527 	 * The codeflow from here on is thus:
13528 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13529 	 */
13530 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13531 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13532 	    !(ill->ill_flags & ILLF_ROUTER) || SAME_IPMP_GROUP(ill, stq_ill) ||
13533 	    (ire->ire_nce == NULL) ||
13534 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13535 	    (ntohs(ipha->ipha_length) > ire->ire_max_frag) ||
13536 	    ipha->ipha_ttl <= 1) {
13537 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13538 		    ipha, ill, B_FALSE);
13539 		return (ire);
13540 	}
13541 
13542 	mp->b_datap->db_struioun.cksum.flags = 0;
13543 	/* Adjust the checksum to reflect the ttl decrement. */
13544 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13545 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13546 	ipha->ipha_ttl--;
13547 
13548 	dev_q = ire->ire_stq->q_next;
13549 	if ((dev_q->q_next != NULL ||
13550 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13551 		goto indiscard;
13552 	}
13553 
13554 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13555 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13556 
13557 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13558 		mp = ip_wput_attach_llhdr(mp, ire, 0, 0);
13559 		if (mp != NULL) {
13560 			SEND_PKT(ire, mp);
13561 			return (ire);
13562 		}
13563 	}
13564 
13565 indiscard:
13566 	BUMP_MIB(&ip_mib, ipInDiscards);
13567 drop:
13568 	if (mp != NULL)
13569 		freemsg(mp);
13570 	if (src_ire != NULL)
13571 		ire_refrele(src_ire);
13572 	return (ire);
13573 
13574 }
13575 
13576 /*
13577  * This function is called in the forwarding slowpath, when
13578  * either the ire lacks the link-layer address, or the packet needs
13579  * further processing(eg. fragmentation), before transmission.
13580  */
13581 static void
13582 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13583     ill_t *ill, boolean_t ll_multicast)
13584 {
13585 	ill_group_t	*ill_group;
13586 	ill_group_t	*ire_group;
13587 	queue_t		*dev_q;
13588 	ire_t		*src_ire;
13589 
13590 	ASSERT(ire->ire_stq != NULL);
13591 
13592 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13593 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13594 
13595 	if (ll_multicast != 0)
13596 		goto drop_pkt;
13597 
13598 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13599 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13600 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13601 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13602 		if (src_ire != NULL)
13603 			ire_refrele(src_ire);
13604 		BUMP_MIB(&ip_mib, ipForwProhibits);
13605 		ip2dbg(("ip_rput_process_forward: Received packet with"
13606 		    " bad src/dst address on %s\n", ill->ill_name));
13607 	}
13608 
13609 	ill_group = ill->ill_group;
13610 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13611 	/*
13612 	 * Check if we want to forward this one at this time.
13613 	 * We allow source routed packets on a host provided that
13614 	 * they go out the same interface or same interface group
13615 	 * as they came in on.
13616 	 *
13617 	 * XXX To be quicker, we may wish to not chase pointers to
13618 	 * get the ILLF_ROUTER flag and instead store the
13619 	 * forwarding policy in the ire.  An unfortunate
13620 	 * side-effect of that would be requiring an ire flush
13621 	 * whenever the ILLF_ROUTER flag changes.
13622 	 */
13623 	if (((ill->ill_flags &
13624 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13625 	    ILLF_ROUTER) == 0) &&
13626 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13627 	    (ill_group != NULL && ill_group == ire_group)))) {
13628 		BUMP_MIB(&ip_mib, ipForwProhibits);
13629 		if (ip_source_routed(ipha)) {
13630 			q = WR(q);
13631 			/*
13632 			 * Clear the indication that this may have
13633 			 * hardware checksum as we are not using it.
13634 			 */
13635 			DB_CKSUMFLAGS(mp) = 0;
13636 			icmp_unreachable(q, mp,
13637 			    ICMP_SOURCE_ROUTE_FAILED);
13638 			return;
13639 		}
13640 		goto drop_pkt;
13641 	}
13642 
13643 	/* Packet is being forwarded. Turning off hwcksum flag. */
13644 	DB_CKSUMFLAGS(mp) = 0;
13645 	if (ip_g_send_redirects) {
13646 		/*
13647 		 * Check whether the incoming interface and outgoing
13648 		 * interface is part of the same group. If so,
13649 		 * send redirects.
13650 		 *
13651 		 * Check the source address to see if it originated
13652 		 * on the same logical subnet it is going back out on.
13653 		 * If so, we should be able to send it a redirect.
13654 		 * Avoid sending a redirect if the destination
13655 		 * is directly connected (gw_addr == 0),
13656 		 * or if the packet was source routed out this
13657 		 * interface.
13658 		 */
13659 		ipaddr_t src;
13660 		mblk_t	*mp1;
13661 		ire_t	*src_ire = NULL;
13662 
13663 		/*
13664 		 * Check whether ire_rfq and q are from the same ill
13665 		 * or if they are not same, they at least belong
13666 		 * to the same group. If so, send redirects.
13667 		 */
13668 		if ((ire->ire_rfq == q ||
13669 		    (ill_group != NULL && ill_group == ire_group)) &&
13670 		    (ire->ire_gateway_addr != 0) &&
13671 		    !ip_source_routed(ipha)) {
13672 
13673 			src = ipha->ipha_src;
13674 			src_ire = ire_ftable_lookup(src, 0, 0,
13675 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
13676 			    0, NULL, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
13677 
13678 			if (src_ire != NULL) {
13679 				/*
13680 				 * The source is directly connected.
13681 				 * Just copy the ip header (which is
13682 				 * in the first mblk)
13683 				 */
13684 				mp1 = copyb(mp);
13685 				if (mp1 != NULL) {
13686 					icmp_send_redirect(WR(q), mp1,
13687 					    ire->ire_gateway_addr);
13688 				}
13689 				ire_refrele(src_ire);
13690 			}
13691 		}
13692 	}
13693 
13694 	dev_q = ire->ire_stq->q_next;
13695 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13696 		BUMP_MIB(&ip_mib, ipInDiscards);
13697 		freemsg(mp);
13698 		return;
13699 	}
13700 
13701 	ip_rput_forward(ire, ipha, mp, ill);
13702 	return;
13703 
13704 drop_pkt:
13705 	ip2dbg(("ip_rput_forward: drop pkt\n"));
13706 	freemsg(mp);
13707 }
13708 
13709 ire_t *
13710 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13711     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13712 {
13713 	queue_t		*q;
13714 	uint16_t	hcksumflags;
13715 
13716 	q = *qp;
13717 
13718 	/*
13719 	 * Clear the indication that this may have hardware
13720 	 * checksum as we are not using it for forwarding.
13721 	 */
13722 	hcksumflags = DB_CKSUMFLAGS(mp);
13723 	DB_CKSUMFLAGS(mp) = 0;
13724 
13725 	/*
13726 	 * Directed broadcast forwarding: if the packet came in over a
13727 	 * different interface then it is routed out over we can forward it.
13728 	 */
13729 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13730 		ire_refrele(ire);
13731 		freemsg(mp);
13732 		BUMP_MIB(&ip_mib, ipInDiscards);
13733 		return (NULL);
13734 	}
13735 	/*
13736 	 * For multicast we have set dst to be INADDR_BROADCAST
13737 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13738 	 * only for broadcast packets.
13739 	 */
13740 	if (!CLASSD(ipha->ipha_dst)) {
13741 		ire_t *new_ire;
13742 		ipif_t *ipif;
13743 		/*
13744 		 * For ill groups, as the switch duplicates broadcasts
13745 		 * across all the ports, we need to filter out and
13746 		 * send up only one copy. There is one copy for every
13747 		 * broadcast address on each ill. Thus, we look for a
13748 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13749 		 * later to see whether this ill is eligible to receive
13750 		 * them or not. ill_nominate_bcast_rcv() nominates only
13751 		 * one set of IREs for receiving.
13752 		 */
13753 
13754 		ipif = ipif_get_next_ipif(NULL, ill);
13755 		if (ipif == NULL) {
13756 			ire_refrele(ire);
13757 			freemsg(mp);
13758 			BUMP_MIB(&ip_mib, ipInDiscards);
13759 			return (NULL);
13760 		}
13761 		new_ire = ire_ctable_lookup(dst, 0, 0,
13762 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13763 		ipif_refrele(ipif);
13764 
13765 		if (new_ire != NULL) {
13766 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13767 				ire_refrele(ire);
13768 				ire_refrele(new_ire);
13769 				freemsg(mp);
13770 				BUMP_MIB(&ip_mib, ipInDiscards);
13771 				return (NULL);
13772 			}
13773 			/*
13774 			 * In the special case of multirouted broadcast
13775 			 * packets, we unconditionally need to "gateway"
13776 			 * them to the appropriate interface here.
13777 			 * In the normal case, this cannot happen, because
13778 			 * there is no broadcast IRE tagged with the
13779 			 * RTF_MULTIRT flag.
13780 			 */
13781 			if (new_ire->ire_flags & RTF_MULTIRT) {
13782 				ire_refrele(new_ire);
13783 				if (ire->ire_rfq != NULL) {
13784 					q = ire->ire_rfq;
13785 					*qp = q;
13786 				}
13787 			} else {
13788 				ire_refrele(ire);
13789 				ire = new_ire;
13790 			}
13791 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
13792 			if (!ip_g_forward_directed_bcast) {
13793 				/*
13794 				 * Free the message if
13795 				 * ip_g_forward_directed_bcast is turned
13796 				 * off for non-local broadcast.
13797 				 */
13798 				ire_refrele(ire);
13799 				freemsg(mp);
13800 				BUMP_MIB(&ip_mib, ipInDiscards);
13801 				return (NULL);
13802 			}
13803 		} else {
13804 			/*
13805 			 * This CGTP packet successfully passed the
13806 			 * CGTP filter, but the related CGTP
13807 			 * broadcast IRE has not been found,
13808 			 * meaning that the redundant ipif is
13809 			 * probably down. However, if we discarded
13810 			 * this packet, its duplicate would be
13811 			 * filtered out by the CGTP filter so none
13812 			 * of them would get through. So we keep
13813 			 * going with this one.
13814 			 */
13815 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
13816 			if (ire->ire_rfq != NULL) {
13817 				q = ire->ire_rfq;
13818 				*qp = q;
13819 			}
13820 		}
13821 	}
13822 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
13823 		/*
13824 		 * Verify that there are not more then one
13825 		 * IRE_BROADCAST with this broadcast address which
13826 		 * has ire_stq set.
13827 		 * TODO: simplify, loop over all IRE's
13828 		 */
13829 		ire_t	*ire1;
13830 		int	num_stq = 0;
13831 		mblk_t	*mp1;
13832 
13833 		/* Find the first one with ire_stq set */
13834 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
13835 		for (ire1 = ire; ire1 &&
13836 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
13837 		    ire1 = ire1->ire_next)
13838 			;
13839 		if (ire1) {
13840 			ire_refrele(ire);
13841 			ire = ire1;
13842 			IRE_REFHOLD(ire);
13843 		}
13844 
13845 		/* Check if there are additional ones with stq set */
13846 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
13847 			if (ire->ire_addr != ire1->ire_addr)
13848 				break;
13849 			if (ire1->ire_stq) {
13850 				num_stq++;
13851 				break;
13852 			}
13853 		}
13854 		rw_exit(&ire->ire_bucket->irb_lock);
13855 		if (num_stq == 1 && ire->ire_stq != NULL) {
13856 			ip1dbg(("ip_rput_process_broadcast: directed "
13857 			    "broadcast to 0x%x\n",
13858 			    ntohl(ire->ire_addr)));
13859 			mp1 = copymsg(mp);
13860 			if (mp1) {
13861 				switch (ipha->ipha_protocol) {
13862 				case IPPROTO_UDP:
13863 					ip_udp_input(q, mp1, ipha, ire, ill);
13864 					break;
13865 				default:
13866 					ip_proto_input(q, mp1, ipha, ire, ill);
13867 					break;
13868 				}
13869 			}
13870 			/*
13871 			 * Adjust ttl to 2 (1+1 - the forward engine
13872 			 * will decrement it by one.
13873 			 */
13874 			if (ip_csum_hdr(ipha)) {
13875 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13876 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
13877 				freemsg(mp);
13878 				ire_refrele(ire);
13879 				return (NULL);
13880 			}
13881 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
13882 			ipha->ipha_hdr_checksum = 0;
13883 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
13884 			ip_rput_process_forward(q, mp, ire, ipha,
13885 			    ill, ll_multicast);
13886 			ire_refrele(ire);
13887 			return (NULL);
13888 		}
13889 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
13890 		    ntohl(ire->ire_addr)));
13891 	}
13892 
13893 
13894 	/* Restore any hardware checksum flags */
13895 	DB_CKSUMFLAGS(mp) = hcksumflags;
13896 	return (ire);
13897 }
13898 
13899 /* ARGSUSED */
13900 static boolean_t
13901 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
13902     int *ll_multicast, ipaddr_t *dstp)
13903 {
13904 	/*
13905 	 * Forward packets only if we have joined the allmulti
13906 	 * group on this interface.
13907 	 */
13908 	if (ip_g_mrouter && ill->ill_join_allmulti) {
13909 		int retval;
13910 
13911 		/*
13912 		 * Clear the indication that this may have hardware
13913 		 * checksum as we are not using it.
13914 		 */
13915 		DB_CKSUMFLAGS(mp) = 0;
13916 		retval = ip_mforward(ill, ipha, mp);
13917 		/* ip_mforward updates mib variables if needed */
13918 		/* clear b_prev - used by ip_mroute_decap */
13919 		mp->b_prev = NULL;
13920 
13921 		switch (retval) {
13922 		case 0:
13923 			/*
13924 			 * pkt is okay and arrived on phyint.
13925 			 *
13926 			 * If we are running as a multicast router
13927 			 * we need to see all IGMP and/or PIM packets.
13928 			 */
13929 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
13930 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
13931 				goto done;
13932 			}
13933 			break;
13934 		case -1:
13935 			/* pkt is mal-formed, toss it */
13936 			goto drop_pkt;
13937 		case 1:
13938 			/* pkt is okay and arrived on a tunnel */
13939 			/*
13940 			 * If we are running a multicast router
13941 			 *  we need to see all igmp packets.
13942 			 */
13943 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
13944 				*dstp = INADDR_BROADCAST;
13945 				*ll_multicast = 1;
13946 				return (B_FALSE);
13947 			}
13948 
13949 			goto drop_pkt;
13950 		}
13951 	}
13952 
13953 	ILM_WALKER_HOLD(ill);
13954 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
13955 		/*
13956 		 * This might just be caused by the fact that
13957 		 * multiple IP Multicast addresses map to the same
13958 		 * link layer multicast - no need to increment counter!
13959 		 */
13960 		ILM_WALKER_RELE(ill);
13961 		freemsg(mp);
13962 		return (B_TRUE);
13963 	}
13964 	ILM_WALKER_RELE(ill);
13965 done:
13966 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
13967 	/*
13968 	 * This assumes the we deliver to all streams for multicast
13969 	 * and broadcast packets.
13970 	 */
13971 	*dstp = INADDR_BROADCAST;
13972 	*ll_multicast = 1;
13973 	return (B_FALSE);
13974 drop_pkt:
13975 	ip2dbg(("ip_rput: drop pkt\n"));
13976 	freemsg(mp);
13977 	return (B_TRUE);
13978 }
13979 
13980 static boolean_t
13981 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
13982     int *ll_multicast, mblk_t **mpp)
13983 {
13984 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
13985 	boolean_t must_copy = B_FALSE;
13986 	struct iocblk   *iocp;
13987 	ipha_t		*ipha;
13988 
13989 #define	rptr    ((uchar_t *)ipha)
13990 
13991 	first_mp = *first_mpp;
13992 	mp = *mpp;
13993 
13994 	ASSERT(first_mp == mp);
13995 
13996 	/*
13997 	 * if db_ref > 1 then copymsg and free original. Packet may be
13998 	 * changed and do not want other entity who has a reference to this
13999 	 * message to trip over the changes. This is a blind change because
14000 	 * trying to catch all places that might change packet is too
14001 	 * difficult (since it may be a module above this one)
14002 	 *
14003 	 * This corresponds to the non-fast path case. We walk down the full
14004 	 * chain in this case, and check the db_ref count of all the dblks,
14005 	 * and do a copymsg if required. It is possible that the db_ref counts
14006 	 * of the data blocks in the mblk chain can be different.
14007 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14008 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14009 	 * 'snoop' is running.
14010 	 */
14011 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14012 		if (mp1->b_datap->db_ref > 1) {
14013 			must_copy = B_TRUE;
14014 			break;
14015 		}
14016 	}
14017 
14018 	if (must_copy) {
14019 		mp1 = copymsg(mp);
14020 		if (mp1 == NULL) {
14021 			for (mp1 = mp; mp1 != NULL;
14022 			    mp1 = mp1->b_cont) {
14023 				mp1->b_next = NULL;
14024 				mp1->b_prev = NULL;
14025 			}
14026 			freemsg(mp);
14027 			BUMP_MIB(&ip_mib, ipInDiscards);
14028 			return (B_TRUE);
14029 		}
14030 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14031 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14032 			/* Copy b_prev - used by ip_mroute_decap */
14033 			to_mp->b_prev = from_mp->b_prev;
14034 			from_mp->b_prev = NULL;
14035 		}
14036 		*first_mpp = first_mp = mp1;
14037 		freemsg(mp);
14038 		mp = mp1;
14039 		*mpp = mp1;
14040 	}
14041 
14042 	ipha = (ipha_t *)mp->b_rptr;
14043 
14044 	/*
14045 	 * previous code has a case for M_DATA.
14046 	 * We want to check how that happens.
14047 	 */
14048 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14049 	switch (first_mp->b_datap->db_type) {
14050 	case M_PROTO:
14051 	case M_PCPROTO:
14052 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14053 		    DL_UNITDATA_IND) {
14054 			/* Go handle anything other than data elsewhere. */
14055 			ip_rput_dlpi(q, mp);
14056 			return (B_TRUE);
14057 		}
14058 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14059 		/* Ditch the DLPI header. */
14060 		mp1 = mp->b_cont;
14061 		ASSERT(first_mp == mp);
14062 		*first_mpp = mp1;
14063 		freeb(mp);
14064 		*mpp = mp1;
14065 		return (B_FALSE);
14066 	case M_IOCACK:
14067 		ip1dbg(("got iocack "));
14068 		iocp = (struct iocblk *)mp->b_rptr;
14069 		switch (iocp->ioc_cmd) {
14070 		case DL_IOC_HDR_INFO:
14071 			ill = (ill_t *)q->q_ptr;
14072 			ill_fastpath_ack(ill, mp);
14073 			return (B_TRUE);
14074 		case SIOCSTUNPARAM:
14075 		case OSIOCSTUNPARAM:
14076 			/* Go through qwriter_ip */
14077 			break;
14078 		case SIOCGTUNPARAM:
14079 		case OSIOCGTUNPARAM:
14080 			ip_rput_other(NULL, q, mp, NULL);
14081 			return (B_TRUE);
14082 		default:
14083 			putnext(q, mp);
14084 			return (B_TRUE);
14085 		}
14086 		/* FALLTHRU */
14087 	case M_ERROR:
14088 	case M_HANGUP:
14089 		/*
14090 		 * Since this is on the ill stream we unconditionally
14091 		 * bump up the refcount
14092 		 */
14093 		ill_refhold(ill);
14094 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14095 		    B_FALSE);
14096 		return (B_TRUE);
14097 	case M_CTL:
14098 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14099 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14100 			IPHADA_M_CTL)) {
14101 			/*
14102 			 * It's an IPsec accelerated packet.
14103 			 * Make sure that the ill from which we received the
14104 			 * packet has enabled IPsec hardware acceleration.
14105 			 */
14106 			if (!(ill->ill_capabilities &
14107 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14108 				/* IPsec kstats: bean counter */
14109 				freemsg(mp);
14110 				return (B_TRUE);
14111 			}
14112 
14113 			/*
14114 			 * Make mp point to the mblk following the M_CTL,
14115 			 * then process according to type of mp.
14116 			 * After this processing, first_mp will point to
14117 			 * the data-attributes and mp to the pkt following
14118 			 * the M_CTL.
14119 			 */
14120 			mp = first_mp->b_cont;
14121 			if (mp == NULL) {
14122 				freemsg(first_mp);
14123 				return (B_TRUE);
14124 			}
14125 			/*
14126 			 * A Hardware Accelerated packet can only be M_DATA
14127 			 * ESP or AH packet.
14128 			 */
14129 			if (mp->b_datap->db_type != M_DATA) {
14130 				/* non-M_DATA IPsec accelerated packet */
14131 				IPSECHW_DEBUG(IPSECHW_PKT,
14132 				    ("non-M_DATA IPsec accelerated pkt\n"));
14133 				freemsg(first_mp);
14134 				return (B_TRUE);
14135 			}
14136 			ipha = (ipha_t *)mp->b_rptr;
14137 			if (ipha->ipha_protocol != IPPROTO_AH &&
14138 			    ipha->ipha_protocol != IPPROTO_ESP) {
14139 				IPSECHW_DEBUG(IPSECHW_PKT,
14140 				    ("non-M_DATA IPsec accelerated pkt\n"));
14141 				freemsg(first_mp);
14142 				return (B_TRUE);
14143 			}
14144 			*mpp = mp;
14145 			return (B_FALSE);
14146 		}
14147 		putnext(q, mp);
14148 		return (B_TRUE);
14149 	case M_FLUSH:
14150 		if (*mp->b_rptr & FLUSHW) {
14151 			*mp->b_rptr &= ~FLUSHR;
14152 			qreply(q, mp);
14153 			return (B_TRUE);
14154 		}
14155 		freemsg(mp);
14156 		return (B_TRUE);
14157 	case M_IOCNAK:
14158 		ip1dbg(("got iocnak "));
14159 		iocp = (struct iocblk *)mp->b_rptr;
14160 		switch (iocp->ioc_cmd) {
14161 		case DL_IOC_HDR_INFO:
14162 		case SIOCSTUNPARAM:
14163 		case OSIOCSTUNPARAM:
14164 			/*
14165 			 * Since this is on the ill stream we unconditionally
14166 			 * bump up the refcount
14167 			 */
14168 			ill_refhold(ill);
14169 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14170 			    CUR_OP, B_FALSE);
14171 			return (B_TRUE);
14172 		case SIOCGTUNPARAM:
14173 		case OSIOCGTUNPARAM:
14174 			ip_rput_other(NULL, q, mp, NULL);
14175 			return (B_TRUE);
14176 		default:
14177 			break;
14178 		}
14179 		/* FALLTHRU */
14180 	default:
14181 		putnext(q, mp);
14182 		return (B_TRUE);
14183 	}
14184 }
14185 
14186 /* Read side put procedure.  Packets coming from the wire arrive here. */
14187 void
14188 ip_rput(queue_t *q, mblk_t *mp)
14189 {
14190 	ill_t	*ill;
14191 	mblk_t	 *dmp = NULL;
14192 
14193 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14194 
14195 	ill = (ill_t *)q->q_ptr;
14196 
14197 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14198 		union DL_primitives *dl;
14199 
14200 		/*
14201 		 * Things are opening or closing. Only accept DLPI control
14202 		 * messages. In the open case, the ill->ill_ipif has not yet
14203 		 * been created. In the close case, things hanging off the
14204 		 * ill could have been freed already. In either case it
14205 		 * may not be safe to proceed further.
14206 		 */
14207 
14208 		dl = (union DL_primitives *)mp->b_rptr;
14209 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14210 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14211 			/*
14212 			 * Also SIOC[GS]TUN* ioctls can come here.
14213 			 */
14214 			inet_freemsg(mp);
14215 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14216 			    "ip_input_end: q %p (%S)", q, "uninit");
14217 			return;
14218 		}
14219 	}
14220 
14221 	/*
14222 	 * if db_ref > 1 then copymsg and free original. Packet may be
14223 	 * changed and we do not want the other entity who has a reference to
14224 	 * this message to trip over the changes. This is a blind change because
14225 	 * trying to catch all places that might change the packet is too
14226 	 * difficult.
14227 	 *
14228 	 * This corresponds to the fast path case, where we have a chain of
14229 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14230 	 * in the mblk chain. There doesn't seem to be a reason why a device
14231 	 * driver would send up data with varying db_ref counts in the mblk
14232 	 * chain. In any case the Fast path is a private interface, and our
14233 	 * drivers don't do such a thing. Given the above assumption, there is
14234 	 * no need to walk down the entire mblk chain (which could have a
14235 	 * potential performance problem)
14236 	 */
14237 	if (mp->b_datap->db_ref > 1) {
14238 		mblk_t  *mp1;
14239 		boolean_t adjusted = B_FALSE;
14240 		IP_STAT(ip_db_ref);
14241 
14242 		/*
14243 		 * The IP_RECVSLLA option depends on having the link layer
14244 		 * header. First check that:
14245 		 * a> the underlying device is of type ether, since this
14246 		 * option is currently supported only over ethernet.
14247 		 * b> there is enough room to copy over the link layer header.
14248 		 *
14249 		 * Once the checks are done, adjust rptr so that the link layer
14250 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14251 		 * be returned by some non-ethernet drivers but in this case the
14252 		 * second check will fail.
14253 		 */
14254 		if (ill->ill_type == IFT_ETHER &&
14255 		    (mp->b_rptr - mp->b_datap->db_base) >=
14256 		    sizeof (struct ether_header)) {
14257 			mp->b_rptr -= sizeof (struct ether_header);
14258 			adjusted = B_TRUE;
14259 		}
14260 		mp1 = copymsg(mp);
14261 		if (mp1 == NULL) {
14262 			mp->b_next = NULL;
14263 			/* clear b_prev - used by ip_mroute_decap */
14264 			mp->b_prev = NULL;
14265 			freemsg(mp);
14266 			BUMP_MIB(&ip_mib, ipInDiscards);
14267 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14268 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14269 			return;
14270 		}
14271 		if (adjusted) {
14272 			/*
14273 			 * Copy is done. Restore the pointer in the _new_ mblk
14274 			 */
14275 			mp1->b_rptr += sizeof (struct ether_header);
14276 		}
14277 		/* Copy b_prev - used by ip_mroute_decap */
14278 		mp1->b_prev = mp->b_prev;
14279 		mp->b_prev = NULL;
14280 		freemsg(mp);
14281 		mp = mp1;
14282 	}
14283 	if (DB_TYPE(mp) == M_DATA) {
14284 		dmp = mp;
14285 	} else if (DB_TYPE(mp) == M_PROTO &&
14286 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14287 		dmp = mp->b_cont;
14288 	}
14289 	if (dmp != NULL) {
14290 		/*
14291 		 * IP header ptr not aligned?
14292 		 * OR IP header not complete in first mblk
14293 		 */
14294 		if (!OK_32PTR(dmp->b_rptr) ||
14295 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14296 			if (!ip_check_and_align_header(q, dmp))
14297 				return;
14298 		}
14299 	}
14300 
14301 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14302 	    "ip_rput_end: q %p (%S)", q, "end");
14303 
14304 	ip_input(ill, NULL, mp, 0);
14305 }
14306 
14307 /*
14308  * Direct read side procedure capable of dealing with chains. GLDv3 based
14309  * drivers call this function directly with mblk chains while STREAMS
14310  * read side procedure ip_rput() calls this for single packet with ip_ring
14311  * set to NULL to process one packet at a time.
14312  *
14313  * The ill will always be valid if this function is called directly from
14314  * the driver.
14315  */
14316 /* ARGSUSED */
14317 void
14318 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
14319 {
14320 	ipaddr_t		dst = NULL;
14321 	ipaddr_t		prev_dst;
14322 	ire_t			*ire = NULL;
14323 	ipha_t			*ipha;
14324 	uint_t			pkt_len;
14325 	ssize_t			len;
14326 	uint_t			opt_len;
14327 	int			ll_multicast;
14328 	int			cgtp_flt_pkt;
14329 	queue_t			*q = ill->ill_rq;
14330 	squeue_t		*curr_sqp = NULL;
14331 	mblk_t 			*head = NULL;
14332 	mblk_t			*tail = NULL;
14333 	mblk_t			*first_mp;
14334 	mblk_t 			*mp;
14335 	int			cnt = 0;
14336 
14337 	ASSERT(mp_chain != NULL);
14338 	ASSERT(ill != NULL);
14339 
14340 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14341 
14342 #define	rptr	((uchar_t *)ipha)
14343 
14344 	while (mp_chain != NULL) {
14345 		first_mp = mp = mp_chain;
14346 		mp_chain = mp_chain->b_next;
14347 		mp->b_next = NULL;
14348 		ll_multicast = 0;
14349 
14350 		/*
14351 		 * We do ire caching from one iteration to
14352 		 * another. In the event the packet chain contains
14353 		 * all packets from the same dst, this caching saves
14354 		 * an ire_cache_lookup for each of the succeeding
14355 		 * packets in a packet chain.
14356 		 */
14357 		prev_dst = dst;
14358 
14359 		/*
14360 		 * ip_input fast path
14361 		 */
14362 
14363 		/* mblk type is not M_DATA */
14364 		if (mp->b_datap->db_type != M_DATA) {
14365 			if (ip_rput_process_notdata(q, &first_mp, ill,
14366 			    &ll_multicast, &mp))
14367 				continue;
14368 		}
14369 
14370 		/* Make sure its an M_DATA and that its aligned */
14371 		ASSERT(mp->b_datap->db_type == M_DATA);
14372 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14373 
14374 		ipha = (ipha_t *)mp->b_rptr;
14375 		len = mp->b_wptr - rptr;
14376 
14377 		BUMP_MIB(&ip_mib, ipInReceives);
14378 
14379 
14380 		/* multiple mblk or too short */
14381 		pkt_len = ntohs(ipha->ipha_length);
14382 		len -= pkt_len;
14383 		if (len != 0) {
14384 			/*
14385 			 * Make sure we have data length consistent
14386 			 * with the IP header.
14387 			 */
14388 			if (mp->b_cont == NULL) {
14389 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14390 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14391 					ip2dbg(("ip_input: drop pkt\n"));
14392 					freemsg(mp);
14393 					continue;
14394 				}
14395 				mp->b_wptr = rptr + pkt_len;
14396 			} else if (len += msgdsize(mp->b_cont)) {
14397 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14398 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14399 					ip2dbg(("ip_input: drop pkt\n"));
14400 					freemsg(mp);
14401 					continue;
14402 				}
14403 				(void) adjmsg(mp, -len);
14404 				IP_STAT(ip_multimblk3);
14405 			}
14406 		}
14407 
14408 		/* Obtain the dst of the current packet */
14409 		dst = ipha->ipha_dst;
14410 
14411 		if (IP_LOOPBACK_ADDR(dst) ||
14412 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14413 			BUMP_MIB(&ip_mib, ipInAddrErrors);
14414 			cmn_err(CE_CONT, "dst %X src %X\n",
14415 			    dst, ipha->ipha_src);
14416 			freemsg(mp);
14417 			continue;
14418 		}
14419 
14420 		/*
14421 		 * Attach any necessary label information to
14422 		 * this packet
14423 		 */
14424 		if (is_system_labeled() &&
14425 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14426 			BUMP_MIB(&ip_mib, ipInDiscards);
14427 			freemsg(mp);
14428 			continue;
14429 		}
14430 
14431 		/*
14432 		 * Reuse the cached ire only if the ipha_dst of the previous
14433 		 * packet is the same as the current packet AND it is not
14434 		 * INADDR_ANY.
14435 		 */
14436 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14437 		    (ire != NULL)) {
14438 			ire_refrele(ire);
14439 			ire = NULL;
14440 		}
14441 		opt_len = ipha->ipha_version_and_hdr_length -
14442 		    IP_SIMPLE_HDR_VERSION;
14443 
14444 		/*
14445 		 * Check to see if we can take the fastpath.
14446 		 * That is possible if the following conditions are met
14447 		 *	o Tsol disabled
14448 		 *	o CGTP disabled
14449 		 *	o ipp_action_count is 0
14450 		 *	o Mobile IP not running
14451 		 *	o no options in the packet
14452 		 *	o not a RSVP packet
14453 		 * 	o not a multicast packet
14454 		 */
14455 		if (!is_system_labeled() &&
14456 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14457 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14458 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14459 		    !ll_multicast && !CLASSD(dst)) {
14460 			if (ire == NULL)
14461 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14462 
14463 			/* incoming packet is for forwarding */
14464 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14465 				ire = ip_fast_forward(ire, dst, ill, mp);
14466 				continue;
14467 			}
14468 			/* incoming packet is for local consumption */
14469 			if (ire->ire_type & IRE_LOCAL)
14470 				goto local;
14471 		}
14472 
14473 		/*
14474 		 * Disable ire caching for anything more complex
14475 		 * than the simple fast path case we checked for above.
14476 		 */
14477 		if (ire != NULL) {
14478 			ire_refrele(ire);
14479 			ire = NULL;
14480 		}
14481 
14482 		/* Full-blown slow path */
14483 		if (opt_len != 0) {
14484 			if (len != 0)
14485 				IP_STAT(ip_multimblk4);
14486 			else
14487 				IP_STAT(ip_ipoptions);
14488 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
14489 				continue;
14490 		}
14491 
14492 		/*
14493 		 * Invoke the CGTP (multirouting) filtering module to process
14494 		 * the incoming packet. Packets identified as duplicates
14495 		 * must be discarded. Filtering is active only if the
14496 		 * the ip_cgtp_filter ndd variable is non-zero.
14497 		 */
14498 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14499 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
14500 			cgtp_flt_pkt =
14501 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14502 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14503 				freemsg(first_mp);
14504 				continue;
14505 			}
14506 		}
14507 
14508 		/*
14509 		 * If rsvpd is running, let RSVP daemon handle its processing
14510 		 * and forwarding of RSVP multicast/unicast packets.
14511 		 * If rsvpd is not running but mrouted is running, RSVP
14512 		 * multicast packets are forwarded as multicast traffic
14513 		 * and RSVP unicast packets are forwarded by unicast router.
14514 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14515 		 * packets are not forwarded, but the unicast packets are
14516 		 * forwarded like unicast traffic.
14517 		 */
14518 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14519 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
14520 			/* RSVP packet and rsvpd running. Treat as ours */
14521 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14522 			/*
14523 			 * This assumes that we deliver to all streams for
14524 			 * multicast and broadcast packets.
14525 			 * We have to force ll_multicast to 1 to handle the
14526 			 * M_DATA messages passed in from ip_mroute_decap.
14527 			 */
14528 			dst = INADDR_BROADCAST;
14529 			ll_multicast = 1;
14530 		} else if (CLASSD(dst)) {
14531 			/* packet is multicast */
14532 			mp->b_next = NULL;
14533 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14534 			    &ll_multicast, &dst))
14535 				continue;
14536 		}
14537 
14538 
14539 		/*
14540 		 * Check if the packet is coming from the Mobile IP
14541 		 * forward tunnel interface
14542 		 */
14543 		if (ill->ill_srcif_refcnt > 0) {
14544 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
14545 			    NULL, ill, MATCH_IRE_TYPE);
14546 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
14547 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
14548 
14549 				/* We need to resolve the link layer info */
14550 				ire_refrele(ire);
14551 				ire = NULL;
14552 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
14553 				    ll_multicast, dst);
14554 				continue;
14555 			}
14556 		}
14557 
14558 		if (ire == NULL) {
14559 			ire = ire_cache_lookup(dst, ALL_ZONES,
14560 			    MBLK_GETLABEL(mp));
14561 		}
14562 
14563 		/*
14564 		 * If mipagent is running and reverse tunnel is created as per
14565 		 * mobile node request, then any packet coming through the
14566 		 * incoming interface from the mobile-node, should be reverse
14567 		 * tunneled to it's home agent except those that are destined
14568 		 * to foreign agent only.
14569 		 * This needs source address based ire lookup. The routing
14570 		 * entries for source address based lookup are only created by
14571 		 * mipagent program only when a reverse tunnel is created.
14572 		 * Reference : RFC2002, RFC2344
14573 		 */
14574 		if (ill->ill_mrtun_refcnt > 0) {
14575 			ipaddr_t	srcaddr;
14576 			ire_t		*tmp_ire;
14577 
14578 			tmp_ire = ire;	/* Save, we might need it later */
14579 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14580 			    ire->ire_type != IRE_BROADCAST)) {
14581 				srcaddr = ipha->ipha_src;
14582 				ire = ire_mrtun_lookup(srcaddr, ill);
14583 				if (ire != NULL) {
14584 					/*
14585 					 * Should not be getting iphada packet
14586 					 * here. we should only get those for
14587 					 * IRE_LOCAL traffic, excluded above.
14588 					 * Fail-safe (drop packet) in the event
14589 					 * hardware is misbehaving.
14590 					 */
14591 					if (first_mp != mp) {
14592 						/* IPsec KSTATS: beancount me */
14593 						freemsg(first_mp);
14594 					} else {
14595 						/*
14596 						 * This packet must be forwarded
14597 						 * to Reverse Tunnel
14598 						 */
14599 						ip_mrtun_forward(ire, ill, mp);
14600 					}
14601 					ire_refrele(ire);
14602 					ire = NULL;
14603 					if (tmp_ire != NULL) {
14604 						ire_refrele(tmp_ire);
14605 						tmp_ire = NULL;
14606 					}
14607 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14608 					    "ip_input_end: q %p (%S)",
14609 					    q, "uninit");
14610 					continue;
14611 				}
14612 			}
14613 			/*
14614 			 * If this packet is from a non-mobilenode  or a
14615 			 * mobile-node which does not request reverse
14616 			 * tunnel service
14617 			 */
14618 			ire = tmp_ire;
14619 		}
14620 
14621 
14622 		/*
14623 		 * If we reach here that means the incoming packet satisfies
14624 		 * one of the following conditions:
14625 		 *   - packet is from a mobile node which does not request
14626 		 *	reverse tunnel
14627 		 *   - packet is from a non-mobile node, which is the most
14628 		 *	common case
14629 		 *   - packet is from a reverse tunnel enabled mobile node
14630 		 *	and destined to foreign agent only
14631 		 */
14632 
14633 		if (ire == NULL) {
14634 			/*
14635 			 * No IRE for this destination, so it can't be for us.
14636 			 * Unless we are forwarding, drop the packet.
14637 			 * We have to let source routed packets through
14638 			 * since we don't yet know if they are 'ping -l'
14639 			 * packets i.e. if they will go out over the
14640 			 * same interface as they came in on.
14641 			 */
14642 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14643 			if (ire == NULL)
14644 				continue;
14645 		}
14646 
14647 		/*
14648 		 * Broadcast IRE may indicate either broadcast or
14649 		 * multicast packet
14650 		 */
14651 		if (ire->ire_type == IRE_BROADCAST) {
14652 			/*
14653 			 * Skip broadcast checks if packet is UDP multicast;
14654 			 * we'd rather not enter ip_rput_process_broadcast()
14655 			 * unless the packet is broadcast for real, since
14656 			 * that routine is a no-op for multicast.
14657 			 */
14658 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14659 			    !CLASSD(ipha->ipha_dst)) {
14660 				ire = ip_rput_process_broadcast(&q, mp,
14661 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14662 				    ll_multicast);
14663 				if (ire == NULL)
14664 					continue;
14665 			}
14666 		} else if (ire->ire_stq != NULL) {
14667 			/* fowarding? */
14668 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14669 			    ll_multicast);
14670 			/* ip_rput_process_forward consumed the packet */
14671 			continue;
14672 		}
14673 
14674 local:
14675 		/* packet not for us */
14676 		if (ire->ire_rfq != q) {
14677 			if (ip_rput_notforus(&q, mp, ire, ill))
14678 				continue;
14679 		}
14680 
14681 		switch (ipha->ipha_protocol) {
14682 		case IPPROTO_TCP:
14683 			ASSERT(first_mp == mp);
14684 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14685 				mp, 0, q, ip_ring)) != NULL) {
14686 				if (curr_sqp == NULL) {
14687 					curr_sqp = GET_SQUEUE(mp);
14688 					ASSERT(cnt == 0);
14689 					cnt++;
14690 					head = tail = mp;
14691 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14692 					ASSERT(tail != NULL);
14693 					cnt++;
14694 					tail->b_next = mp;
14695 					tail = mp;
14696 				} else {
14697 					/*
14698 					 * A different squeue. Send the
14699 					 * chain for the previous squeue on
14700 					 * its way. This shouldn't happen
14701 					 * often unless interrupt binding
14702 					 * changes.
14703 					 */
14704 					IP_STAT(ip_input_multi_squeue);
14705 					squeue_enter_chain(curr_sqp, head,
14706 					    tail, cnt, SQTAG_IP_INPUT);
14707 					curr_sqp = GET_SQUEUE(mp);
14708 					head = mp;
14709 					tail = mp;
14710 					cnt = 1;
14711 				}
14712 			}
14713 			continue;
14714 		case IPPROTO_UDP:
14715 			ASSERT(first_mp == mp);
14716 			ip_udp_input(q, mp, ipha, ire, ill);
14717 			continue;
14718 		case IPPROTO_SCTP:
14719 			ASSERT(first_mp == mp);
14720 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14721 			    q, dst);
14722 			/* ire has been released by ip_sctp_input */
14723 			ire = NULL;
14724 			continue;
14725 		default:
14726 			ip_proto_input(q, first_mp, ipha, ire, ill);
14727 			continue;
14728 		}
14729 	}
14730 
14731 	if (ire != NULL)
14732 		ire_refrele(ire);
14733 
14734 	if (head != NULL)
14735 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14736 
14737 	/*
14738 	 * This code is there just to make netperf/ttcp look good.
14739 	 *
14740 	 * Its possible that after being in polling mode (and having cleared
14741 	 * the backlog), squeues have turned the interrupt frequency higher
14742 	 * to improve latency at the expense of more CPU utilization (less
14743 	 * packets per interrupts or more number of interrupts). Workloads
14744 	 * like ttcp/netperf do manage to tickle polling once in a while
14745 	 * but for the remaining time, stay in higher interrupt mode since
14746 	 * their packet arrival rate is pretty uniform and this shows up
14747 	 * as higher CPU utilization. Since people care about CPU utilization
14748 	 * while running netperf/ttcp, turn the interrupt frequency back to
14749 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14750 	 */
14751 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14752 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14753 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14754 			ip_ring->rr_blank(ip_ring->rr_handle,
14755 			    ip_ring->rr_normal_blank_time,
14756 			    ip_ring->rr_normal_pkt_cnt);
14757 		}
14758 	}
14759 
14760 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14761 	    "ip_input_end: q %p (%S)", q, "end");
14762 #undef	rptr
14763 }
14764 
14765 static void
14766 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
14767     t_uscalar_t err)
14768 {
14769 	if (dl_err == DL_SYSERR) {
14770 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14771 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
14772 		    ill->ill_name, dlpi_prim_str(prim), err);
14773 		return;
14774 	}
14775 
14776 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14777 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
14778 	    dlpi_err_str(dl_err));
14779 }
14780 
14781 /*
14782  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
14783  * than DL_UNITDATA_IND messages. If we need to process this message
14784  * exclusively, we call qwriter_ip, in which case we also need to call
14785  * ill_refhold before that, since qwriter_ip does an ill_refrele.
14786  */
14787 void
14788 ip_rput_dlpi(queue_t *q, mblk_t *mp)
14789 {
14790 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14791 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14792 	ill_t		*ill;
14793 
14794 	ip1dbg(("ip_rput_dlpi"));
14795 	ill = (ill_t *)q->q_ptr;
14796 	switch (dloa->dl_primitive) {
14797 	case DL_ERROR_ACK:
14798 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
14799 		    "%s (0x%x), unix %u\n", ill->ill_name,
14800 		    dlpi_prim_str(dlea->dl_error_primitive),
14801 		    dlea->dl_error_primitive,
14802 		    dlpi_err_str(dlea->dl_errno),
14803 		    dlea->dl_errno,
14804 		    dlea->dl_unix_errno));
14805 		switch (dlea->dl_error_primitive) {
14806 		case DL_UNBIND_REQ:
14807 			mutex_enter(&ill->ill_lock);
14808 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14809 			cv_signal(&ill->ill_cv);
14810 			mutex_exit(&ill->ill_lock);
14811 			/* FALLTHRU */
14812 		case DL_NOTIFY_REQ:
14813 		case DL_ATTACH_REQ:
14814 		case DL_DETACH_REQ:
14815 		case DL_INFO_REQ:
14816 		case DL_BIND_REQ:
14817 		case DL_ENABMULTI_REQ:
14818 		case DL_PHYS_ADDR_REQ:
14819 		case DL_CAPABILITY_REQ:
14820 		case DL_CONTROL_REQ:
14821 			/*
14822 			 * Refhold the ill to match qwriter_ip which does a
14823 			 * refrele. Since this is on the ill stream we
14824 			 * unconditionally bump up the refcount without
14825 			 * checking for ILL_CAN_LOOKUP
14826 			 */
14827 			ill_refhold(ill);
14828 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14829 			    CUR_OP, B_FALSE);
14830 			return;
14831 		case DL_DISABMULTI_REQ:
14832 			freemsg(mp);	/* Don't want to pass this up */
14833 			return;
14834 		default:
14835 			break;
14836 		}
14837 		ip_dlpi_error(ill, dlea->dl_error_primitive,
14838 		    dlea->dl_errno, dlea->dl_unix_errno);
14839 		freemsg(mp);
14840 		return;
14841 	case DL_INFO_ACK:
14842 	case DL_BIND_ACK:
14843 	case DL_PHYS_ADDR_ACK:
14844 	case DL_NOTIFY_ACK:
14845 	case DL_CAPABILITY_ACK:
14846 	case DL_CONTROL_ACK:
14847 		/*
14848 		 * Refhold the ill to match qwriter_ip which does a refrele
14849 		 * Since this is on the ill stream we unconditionally
14850 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
14851 		 */
14852 		ill_refhold(ill);
14853 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14854 		    CUR_OP, B_FALSE);
14855 		return;
14856 	case DL_NOTIFY_IND:
14857 		ill_refhold(ill);
14858 		/*
14859 		 * The DL_NOTIFY_IND is an asynchronous message that has no
14860 		 * relation to the current ioctl in progress (if any). Hence we
14861 		 * pass in NEW_OP in this case.
14862 		 */
14863 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14864 		    NEW_OP, B_FALSE);
14865 		return;
14866 	case DL_OK_ACK:
14867 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
14868 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
14869 		switch (dloa->dl_correct_primitive) {
14870 		case DL_UNBIND_REQ:
14871 			mutex_enter(&ill->ill_lock);
14872 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14873 			cv_signal(&ill->ill_cv);
14874 			mutex_exit(&ill->ill_lock);
14875 			/* FALLTHRU */
14876 		case DL_ATTACH_REQ:
14877 		case DL_DETACH_REQ:
14878 			/*
14879 			 * Refhold the ill to match qwriter_ip which does a
14880 			 * refrele. Since this is on the ill stream we
14881 			 * unconditionally bump up the refcount
14882 			 */
14883 			ill_refhold(ill);
14884 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14885 			    CUR_OP, B_FALSE);
14886 			return;
14887 		case DL_ENABMULTI_REQ:
14888 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14889 				ill->ill_dlpi_multicast_state = IDMS_OK;
14890 			break;
14891 
14892 		}
14893 		break;
14894 	default:
14895 		break;
14896 	}
14897 	freemsg(mp);
14898 }
14899 
14900 /*
14901  * Handling of DLPI messages that require exclusive access to the ipsq.
14902  *
14903  * Need to do ill_pending_mp_release on ioctl completion, which could
14904  * happen here. (along with mi_copy_done)
14905  */
14906 /* ARGSUSED */
14907 static void
14908 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14909 {
14910 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14911 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14912 	int		err = 0;
14913 	ill_t		*ill;
14914 	ipif_t		*ipif = NULL;
14915 	mblk_t		*mp1 = NULL;
14916 	conn_t		*connp = NULL;
14917 	t_uscalar_t	physaddr_req;
14918 	mblk_t		*mp_hw;
14919 	union DL_primitives *dlp;
14920 	boolean_t	success;
14921 	boolean_t	ioctl_aborted = B_FALSE;
14922 	boolean_t	log = B_TRUE;
14923 
14924 	ip1dbg(("ip_rput_dlpi_writer .."));
14925 	ill = (ill_t *)q->q_ptr;
14926 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14927 
14928 	ASSERT(IAM_WRITER_ILL(ill));
14929 
14930 	/*
14931 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
14932 	 * both are null or non-null. However we can assert that only
14933 	 * after grabbing the ipsq_lock. So we don't make any assertion
14934 	 * here and in other places in the code.
14935 	 */
14936 	ipif = ipsq->ipsq_pending_ipif;
14937 	/*
14938 	 * The current ioctl could have been aborted by the user and a new
14939 	 * ioctl to bring up another ill could have started. We could still
14940 	 * get a response from the driver later.
14941 	 */
14942 	if (ipif != NULL && ipif->ipif_ill != ill)
14943 		ioctl_aborted = B_TRUE;
14944 
14945 	switch (dloa->dl_primitive) {
14946 	case DL_ERROR_ACK:
14947 		switch (dlea->dl_error_primitive) {
14948 		case DL_UNBIND_REQ:
14949 		case DL_ATTACH_REQ:
14950 		case DL_DETACH_REQ:
14951 		case DL_INFO_REQ:
14952 			ill_dlpi_done(ill, dlea->dl_error_primitive);
14953 			break;
14954 		case DL_NOTIFY_REQ:
14955 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
14956 			log = B_FALSE;
14957 			break;
14958 		case DL_PHYS_ADDR_REQ:
14959 			/*
14960 			 * For IPv6 only, there are two additional
14961 			 * phys_addr_req's sent to the driver to get the
14962 			 * IPv6 token and lla. This allows IP to acquire
14963 			 * the hardware address format for a given interface
14964 			 * without having built in knowledge of the hardware
14965 			 * address. ill_phys_addr_pend keeps track of the last
14966 			 * DL_PAR sent so we know which response we are
14967 			 * dealing with. ill_dlpi_done will update
14968 			 * ill_phys_addr_pend when it sends the next req.
14969 			 * We don't complete the IOCTL until all three DL_PARs
14970 			 * have been attempted, so set *_len to 0 and break.
14971 			 */
14972 			physaddr_req = ill->ill_phys_addr_pend;
14973 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14974 			if (physaddr_req == DL_IPV6_TOKEN) {
14975 				ill->ill_token_length = 0;
14976 				log = B_FALSE;
14977 				break;
14978 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14979 				ill->ill_nd_lla_len = 0;
14980 				log = B_FALSE;
14981 				break;
14982 			}
14983 			/*
14984 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
14985 			 * We presumably have an IOCTL hanging out waiting
14986 			 * for completion. Find it and complete the IOCTL
14987 			 * with the error noted.
14988 			 * However, ill_dl_phys was called on an ill queue
14989 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
14990 			 * set. But the ioctl is known to be pending on ill_wq.
14991 			 */
14992 			if (!ill->ill_ifname_pending)
14993 				break;
14994 			ill->ill_ifname_pending = 0;
14995 			if (!ioctl_aborted)
14996 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14997 			if (mp1 != NULL) {
14998 				/*
14999 				 * This operation (SIOCSLIFNAME) must have
15000 				 * happened on the ill. Assert there is no conn
15001 				 */
15002 				ASSERT(connp == NULL);
15003 				q = ill->ill_wq;
15004 			}
15005 			break;
15006 		case DL_BIND_REQ:
15007 			ill_dlpi_done(ill, DL_BIND_REQ);
15008 			if (ill->ill_ifname_pending)
15009 				break;
15010 			/*
15011 			 * Something went wrong with the bind.  We presumably
15012 			 * have an IOCTL hanging out waiting for completion.
15013 			 * Find it, take down the interface that was coming
15014 			 * up, and complete the IOCTL with the error noted.
15015 			 */
15016 			if (!ioctl_aborted)
15017 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15018 			if (mp1 != NULL) {
15019 				/*
15020 				 * This operation (SIOCSLIFFLAGS) must have
15021 				 * happened from a conn.
15022 				 */
15023 				ASSERT(connp != NULL);
15024 				q = CONNP_TO_WQ(connp);
15025 				if (ill->ill_move_in_progress) {
15026 					ILL_CLEAR_MOVE(ill);
15027 				}
15028 				(void) ipif_down(ipif, NULL, NULL);
15029 				/* error is set below the switch */
15030 			}
15031 			break;
15032 		case DL_ENABMULTI_REQ:
15033 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15034 
15035 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
15036 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
15037 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
15038 				ipif_t *ipif;
15039 
15040 				log = B_FALSE;
15041 				printf("ip: joining multicasts failed (%d)"
15042 				    " on %s - will use link layer "
15043 				    "broadcasts for multicast\n",
15044 				    dlea->dl_errno, ill->ill_name);
15045 
15046 				/*
15047 				 * Set up the multicast mapping alone.
15048 				 * writer, so ok to access ill->ill_ipif
15049 				 * without any lock.
15050 				 */
15051 				ipif = ill->ill_ipif;
15052 				mutex_enter(&ill->ill_phyint->phyint_lock);
15053 				ill->ill_phyint->phyint_flags |=
15054 				    PHYI_MULTI_BCAST;
15055 				mutex_exit(&ill->ill_phyint->phyint_lock);
15056 
15057 				if (!ill->ill_isv6) {
15058 					(void) ipif_arp_setup_multicast(ipif,
15059 					    NULL);
15060 				} else {
15061 					(void) ipif_ndp_setup_multicast(ipif,
15062 					    NULL);
15063 				}
15064 			}
15065 			freemsg(mp);	/* Don't want to pass this up */
15066 			return;
15067 		case DL_CAPABILITY_REQ:
15068 		case DL_CONTROL_REQ:
15069 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15070 			    "DL_CAPABILITY/CONTROL REQ\n"));
15071 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15072 			ill->ill_capab_state = IDMS_FAILED;
15073 			freemsg(mp);
15074 			return;
15075 		}
15076 		/*
15077 		 * Note the error for IOCTL completion (mp1 is set when
15078 		 * ready to complete ioctl). If ill_ifname_pending_err is
15079 		 * set, an error occured during plumbing (ill_ifname_pending),
15080 		 * so we want to report that error.
15081 		 *
15082 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15083 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15084 		 * expected to get errack'd if the driver doesn't support
15085 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15086 		 * if these error conditions are encountered.
15087 		 */
15088 		if (mp1 != NULL) {
15089 			if (ill->ill_ifname_pending_err != 0)  {
15090 				err = ill->ill_ifname_pending_err;
15091 				ill->ill_ifname_pending_err = 0;
15092 			} else {
15093 				err = dlea->dl_unix_errno ?
15094 				    dlea->dl_unix_errno : ENXIO;
15095 			}
15096 		/*
15097 		 * If we're plumbing an interface and an error hasn't already
15098 		 * been saved, set ill_ifname_pending_err to the error passed
15099 		 * up. Ignore the error if log is B_FALSE (see comment above).
15100 		 */
15101 		} else if (log && ill->ill_ifname_pending &&
15102 		    ill->ill_ifname_pending_err == 0) {
15103 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15104 			dlea->dl_unix_errno : ENXIO;
15105 		}
15106 
15107 		if (log)
15108 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15109 			    dlea->dl_errno, dlea->dl_unix_errno);
15110 		break;
15111 	case DL_CAPABILITY_ACK: {
15112 		boolean_t reneg_flag = B_FALSE;
15113 		/* Call a routine to handle this one. */
15114 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15115 		/*
15116 		 * Check if the ACK is due to renegotiation case since we
15117 		 * will need to send a new CAPABILITY_REQ later.
15118 		 */
15119 		if (ill->ill_capab_state == IDMS_RENEG) {
15120 			/* This is the ack for a renogiation case */
15121 			reneg_flag = B_TRUE;
15122 			ill->ill_capab_state = IDMS_UNKNOWN;
15123 		}
15124 		ill_capability_ack(ill, mp);
15125 		if (reneg_flag)
15126 			ill_capability_probe(ill);
15127 		break;
15128 	}
15129 	case DL_CONTROL_ACK:
15130 		/* We treat all of these as "fire and forget" */
15131 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15132 		break;
15133 	case DL_INFO_ACK:
15134 		/* Call a routine to handle this one. */
15135 		ill_dlpi_done(ill, DL_INFO_REQ);
15136 		ip_ll_subnet_defaults(ill, mp);
15137 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15138 		return;
15139 	case DL_BIND_ACK:
15140 		/*
15141 		 * We should have an IOCTL waiting on this unless
15142 		 * sent by ill_dl_phys, in which case just return
15143 		 */
15144 		ill_dlpi_done(ill, DL_BIND_REQ);
15145 		if (ill->ill_ifname_pending)
15146 			break;
15147 
15148 		if (!ioctl_aborted)
15149 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15150 		if (mp1 == NULL)
15151 			break;
15152 		ASSERT(connp != NULL);
15153 		q = CONNP_TO_WQ(connp);
15154 
15155 		/*
15156 		 * We are exclusive. So nothing can change even after
15157 		 * we get the pending mp. If need be we can put it back
15158 		 * and restart, as in calling ipif_arp_up()  below.
15159 		 */
15160 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15161 
15162 		mutex_enter(&ill->ill_lock);
15163 		ill->ill_dl_up = 1;
15164 		mutex_exit(&ill->ill_lock);
15165 
15166 		/*
15167 		 * Now bring up the resolver, when that is
15168 		 * done we'll create IREs and we are done.
15169 		 */
15170 		if (ill->ill_isv6) {
15171 			/*
15172 			 * v6 interfaces.
15173 			 * Unlike ARP which has to do another bind
15174 			 * and attach, once we get here we are
15175 			 * done with NDP. Except in the case of
15176 			 * ILLF_XRESOLV, in which case we send an
15177 			 * AR_INTERFACE_UP to the external resolver.
15178 			 * If all goes well, the ioctl will complete
15179 			 * in ip_rput(). If there's an error, we
15180 			 * complete it here.
15181 			 */
15182 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15183 			    B_FALSE);
15184 			if (err == 0) {
15185 				if (ill->ill_flags & ILLF_XRESOLV) {
15186 					mutex_enter(&connp->conn_lock);
15187 					mutex_enter(&ill->ill_lock);
15188 					success = ipsq_pending_mp_add(
15189 					    connp, ipif, q, mp1, 0);
15190 					mutex_exit(&ill->ill_lock);
15191 					mutex_exit(&connp->conn_lock);
15192 					if (success) {
15193 						err = ipif_resolver_up(ipif,
15194 						    Res_act_initial);
15195 						if (err == EINPROGRESS) {
15196 							freemsg(mp);
15197 							return;
15198 						}
15199 						ASSERT(err != 0);
15200 						mp1 = ipsq_pending_mp_get(ipsq,
15201 						    &connp);
15202 						ASSERT(mp1 != NULL);
15203 					} else {
15204 						/* conn has started closing */
15205 						err = EINTR;
15206 					}
15207 				} else { /* Non XRESOLV interface */
15208 					err = ipif_up_done_v6(ipif);
15209 				}
15210 			}
15211 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15212 			/*
15213 			 * ARP and other v4 external resolvers.
15214 			 * Leave the pending mblk intact so that
15215 			 * the ioctl completes in ip_rput().
15216 			 */
15217 			mutex_enter(&connp->conn_lock);
15218 			mutex_enter(&ill->ill_lock);
15219 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15220 			mutex_exit(&ill->ill_lock);
15221 			mutex_exit(&connp->conn_lock);
15222 			if (success) {
15223 				err = ipif_resolver_up(ipif, Res_act_initial);
15224 				if (err == EINPROGRESS) {
15225 					freemsg(mp);
15226 					return;
15227 				}
15228 				ASSERT(err != 0);
15229 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15230 			} else {
15231 				/* The conn has started closing */
15232 				err = EINTR;
15233 			}
15234 		} else {
15235 			/*
15236 			 * This one is complete. Reply to pending ioctl.
15237 			 */
15238 			err = ipif_up_done(ipif);
15239 		}
15240 
15241 		if ((err == 0) && (ill->ill_up_ipifs)) {
15242 			err = ill_up_ipifs(ill, q, mp1);
15243 			if (err == EINPROGRESS) {
15244 				freemsg(mp);
15245 				return;
15246 			}
15247 		}
15248 
15249 		if (ill->ill_up_ipifs) {
15250 			ill_group_cleanup(ill);
15251 		}
15252 
15253 		break;
15254 	case DL_NOTIFY_IND: {
15255 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15256 		ire_t *ire;
15257 		boolean_t need_ire_walk_v4 = B_FALSE;
15258 		boolean_t need_ire_walk_v6 = B_FALSE;
15259 
15260 		/*
15261 		 * Change the address everywhere we need to.
15262 		 * What we're getting here is a link-level addr or phys addr.
15263 		 * The new addr is at notify + notify->dl_addr_offset
15264 		 * The address length is notify->dl_addr_length;
15265 		 */
15266 		switch (notify->dl_notification) {
15267 		case DL_NOTE_PHYS_ADDR:
15268 			mp_hw = copyb(mp);
15269 			if (mp_hw == NULL) {
15270 				err = ENOMEM;
15271 				break;
15272 			}
15273 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15274 			/*
15275 			 * We currently don't support changing
15276 			 * the token via DL_NOTIFY_IND.
15277 			 * When we do support it, we have to consider
15278 			 * what the implications are with respect to
15279 			 * the token and the link local address.
15280 			 */
15281 			mutex_enter(&ill->ill_lock);
15282 			if (dlp->notify_ind.dl_data ==
15283 			    DL_IPV6_LINK_LAYER_ADDR) {
15284 				if (ill->ill_nd_lla_mp != NULL)
15285 					freemsg(ill->ill_nd_lla_mp);
15286 				ill->ill_nd_lla_mp = mp_hw;
15287 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15288 				    dlp->notify_ind.dl_addr_offset;
15289 				ill->ill_nd_lla_len =
15290 				    dlp->notify_ind.dl_addr_length -
15291 				    ABS(ill->ill_sap_length);
15292 				mutex_exit(&ill->ill_lock);
15293 				break;
15294 			} else if (dlp->notify_ind.dl_data ==
15295 			    DL_CURR_PHYS_ADDR) {
15296 				if (ill->ill_phys_addr_mp != NULL)
15297 					freemsg(ill->ill_phys_addr_mp);
15298 				ill->ill_phys_addr_mp = mp_hw;
15299 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15300 				    dlp->notify_ind.dl_addr_offset;
15301 				ill->ill_phys_addr_length =
15302 				    dlp->notify_ind.dl_addr_length -
15303 				    ABS(ill->ill_sap_length);
15304 				if (ill->ill_isv6 &&
15305 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15306 					if (ill->ill_nd_lla_mp != NULL)
15307 						freemsg(ill->ill_nd_lla_mp);
15308 					ill->ill_nd_lla_mp = copyb(mp_hw);
15309 					ill->ill_nd_lla = (uchar_t *)
15310 					    ill->ill_nd_lla_mp->b_rptr +
15311 					    dlp->notify_ind.dl_addr_offset;
15312 					ill->ill_nd_lla_len =
15313 					    ill->ill_phys_addr_length;
15314 				}
15315 			}
15316 			mutex_exit(&ill->ill_lock);
15317 			/*
15318 			 * Send out gratuitous arp request for our new
15319 			 * hardware address.
15320 			 */
15321 			for (ipif = ill->ill_ipif; ipif != NULL;
15322 			    ipif = ipif->ipif_next) {
15323 				if (!(ipif->ipif_flags & IPIF_UP))
15324 					continue;
15325 				if (ill->ill_isv6) {
15326 					ipif_ndp_down(ipif);
15327 					/*
15328 					 * Set B_TRUE to enable
15329 					 * ipif_ndp_up() to send out
15330 					 * unsolicited advertisements.
15331 					 */
15332 					err = ipif_ndp_up(ipif,
15333 					    &ipif->ipif_v6lcl_addr,
15334 					    B_TRUE);
15335 					if (err) {
15336 						ip1dbg((
15337 						    "ip_rput_dlpi_writer: "
15338 						    "Failed to update ndp "
15339 						    "err %d\n", err));
15340 					}
15341 				} else {
15342 					/*
15343 					 * IPv4 ARP case
15344 					 *
15345 					 * Set Res_act_move, as we only want
15346 					 * ipif_resolver_up to send an
15347 					 * AR_ENTRY_ADD request up to
15348 					 * ARP.
15349 					 */
15350 					err = ipif_resolver_up(ipif,
15351 					    Res_act_move);
15352 					if (err) {
15353 						ip1dbg((
15354 						    "ip_rput_dlpi_writer: "
15355 						    "Failed to update arp "
15356 						    "err %d\n", err));
15357 					}
15358 				}
15359 			}
15360 			/*
15361 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15362 			 * case so that all old fastpath information can be
15363 			 * purged from IRE caches.
15364 			 */
15365 		/* FALLTHRU */
15366 		case DL_NOTE_FASTPATH_FLUSH:
15367 			/*
15368 			 * Any fastpath probe sent henceforth will get the
15369 			 * new fp mp. So we first delete any ires that are
15370 			 * waiting for the fastpath. Then walk all ires and
15371 			 * delete the ire or delete the fp mp. In the case of
15372 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15373 			 * recreate the ire's without going through a complex
15374 			 * ipif up/down dance. So we don't delete the ire
15375 			 * itself, but just the nce_fp_mp for these 2 ire's
15376 			 * In the case of the other ire's we delete the ire's
15377 			 * themselves. Access to nce_fp_mp is completely
15378 			 * protected by ire_lock for IRE_MIPRTUN and
15379 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15380 			 * other cases for performance.
15381 			 */
15382 			if (ill->ill_isv6) {
15383 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15384 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15385 				    NULL);
15386 			} else {
15387 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15388 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15389 				    IRE_CACHE | IRE_BROADCAST,
15390 				    ire_fastpath_flush, NULL, ill);
15391 				mutex_enter(&ire_mrtun_lock);
15392 				if (ire_mrtun_count != 0) {
15393 					mutex_exit(&ire_mrtun_lock);
15394 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15395 					    IRE_MIPRTUN, ire_fastpath_flush,
15396 					    NULL, ill);
15397 				} else {
15398 					mutex_exit(&ire_mrtun_lock);
15399 				}
15400 			}
15401 			break;
15402 		case DL_NOTE_SDU_SIZE:
15403 			/*
15404 			 * Change the MTU size of the interface, of all
15405 			 * attached ipif's, and of all relevant ire's.  The
15406 			 * new value's a uint32_t at notify->dl_data.
15407 			 * Mtu change Vs. new ire creation - protocol below.
15408 			 *
15409 			 * a Mark the ipif as IPIF_CHANGING.
15410 			 * b Set the new mtu in the ipif.
15411 			 * c Change the ire_max_frag on all affected ires
15412 			 * d Unmark the IPIF_CHANGING
15413 			 *
15414 			 * To see how the protocol works, assume an interface
15415 			 * route is also being added simultaneously by
15416 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15417 			 * the ire. If the ire is created before step a,
15418 			 * it will be cleaned up by step c. If the ire is
15419 			 * created after step d, it will see the new value of
15420 			 * ipif_mtu. Any attempt to create the ire between
15421 			 * steps a to d will fail because of the IPIF_CHANGING
15422 			 * flag. Note that ire_create() is passed a pointer to
15423 			 * the ipif_mtu, and not the value. During ire_add
15424 			 * under the bucket lock, the ire_max_frag of the
15425 			 * new ire being created is set from the ipif/ire from
15426 			 * which it is being derived.
15427 			 */
15428 			mutex_enter(&ill->ill_lock);
15429 			ill->ill_max_frag = (uint_t)notify->dl_data;
15430 
15431 			/*
15432 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15433 			 * leave it alone
15434 			 */
15435 			if (ill->ill_mtu_userspecified) {
15436 				mutex_exit(&ill->ill_lock);
15437 				break;
15438 			}
15439 			ill->ill_max_mtu = ill->ill_max_frag;
15440 			if (ill->ill_isv6) {
15441 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15442 					ill->ill_max_mtu = IPV6_MIN_MTU;
15443 			} else {
15444 				if (ill->ill_max_mtu < IP_MIN_MTU)
15445 					ill->ill_max_mtu = IP_MIN_MTU;
15446 			}
15447 			for (ipif = ill->ill_ipif; ipif != NULL;
15448 			    ipif = ipif->ipif_next) {
15449 				/*
15450 				 * Don't override the mtu if the user
15451 				 * has explicitly set it.
15452 				 */
15453 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15454 					continue;
15455 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15456 				if (ipif->ipif_isv6)
15457 					ire = ipif_to_ire_v6(ipif);
15458 				else
15459 					ire = ipif_to_ire(ipif);
15460 				if (ire != NULL) {
15461 					ire->ire_max_frag = ipif->ipif_mtu;
15462 					ire_refrele(ire);
15463 				}
15464 				if (ipif->ipif_flags & IPIF_UP) {
15465 					if (ill->ill_isv6)
15466 						need_ire_walk_v6 = B_TRUE;
15467 					else
15468 						need_ire_walk_v4 = B_TRUE;
15469 				}
15470 			}
15471 			mutex_exit(&ill->ill_lock);
15472 			if (need_ire_walk_v4)
15473 				ire_walk_v4(ill_mtu_change, (char *)ill,
15474 				    ALL_ZONES);
15475 			if (need_ire_walk_v6)
15476 				ire_walk_v6(ill_mtu_change, (char *)ill,
15477 				    ALL_ZONES);
15478 			break;
15479 		case DL_NOTE_LINK_UP:
15480 		case DL_NOTE_LINK_DOWN: {
15481 			/*
15482 			 * We are writer. ill / phyint / ipsq assocs stable.
15483 			 * The RUNNING flag reflects the state of the link.
15484 			 */
15485 			phyint_t *phyint = ill->ill_phyint;
15486 			uint64_t new_phyint_flags;
15487 			boolean_t changed = B_FALSE;
15488 			boolean_t went_up;
15489 
15490 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15491 			mutex_enter(&phyint->phyint_lock);
15492 			new_phyint_flags = went_up ?
15493 			    phyint->phyint_flags | PHYI_RUNNING :
15494 			    phyint->phyint_flags & ~PHYI_RUNNING;
15495 			if (new_phyint_flags != phyint->phyint_flags) {
15496 				phyint->phyint_flags = new_phyint_flags;
15497 				changed = B_TRUE;
15498 			}
15499 			mutex_exit(&phyint->phyint_lock);
15500 			/*
15501 			 * ill_restart_dad handles the DAD restart and routing
15502 			 * socket notification logic.
15503 			 */
15504 			if (changed) {
15505 				ill_restart_dad(phyint->phyint_illv4, went_up);
15506 				ill_restart_dad(phyint->phyint_illv6, went_up);
15507 			}
15508 			break;
15509 		}
15510 		case DL_NOTE_PROMISC_ON_PHYS:
15511 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15512 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15513 			mutex_enter(&ill->ill_lock);
15514 			ill->ill_promisc_on_phys = B_TRUE;
15515 			mutex_exit(&ill->ill_lock);
15516 			break;
15517 		case DL_NOTE_PROMISC_OFF_PHYS:
15518 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15519 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15520 			mutex_enter(&ill->ill_lock);
15521 			ill->ill_promisc_on_phys = B_FALSE;
15522 			mutex_exit(&ill->ill_lock);
15523 			break;
15524 		case DL_NOTE_CAPAB_RENEG:
15525 			/*
15526 			 * Something changed on the driver side.
15527 			 * It wants us to renegotiate the capabilities
15528 			 * on this ill. The most likely cause is the
15529 			 * aggregation interface under us where a
15530 			 * port got added or went away.
15531 			 *
15532 			 * We reset the capabilities and set the
15533 			 * state to IDMS_RENG so that when the ack
15534 			 * comes back, we can start the
15535 			 * renegotiation process.
15536 			 */
15537 			ill_capability_reset(ill);
15538 			ill->ill_capab_state = IDMS_RENEG;
15539 			break;
15540 		default:
15541 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15542 			    "type 0x%x for DL_NOTIFY_IND\n",
15543 			    notify->dl_notification));
15544 			break;
15545 		}
15546 
15547 		/*
15548 		 * As this is an asynchronous operation, we
15549 		 * should not call ill_dlpi_done
15550 		 */
15551 		break;
15552 	}
15553 	case DL_NOTIFY_ACK: {
15554 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15555 
15556 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15557 			ill->ill_note_link = 1;
15558 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15559 		break;
15560 	}
15561 	case DL_PHYS_ADDR_ACK: {
15562 		/*
15563 		 * We should have an IOCTL waiting on this when request
15564 		 * sent by ill_dl_phys.
15565 		 * However, ill_dl_phys was called on an ill queue (from
15566 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15567 		 * ioctl is known to be pending on ill_wq.
15568 		 * There are two additional phys_addr_req's sent to the
15569 		 * driver to get the token and lla. ill_phys_addr_pend
15570 		 * keeps track of the last one sent so we know which
15571 		 * response we are dealing with. ill_dlpi_done will
15572 		 * update ill_phys_addr_pend when it sends the next req.
15573 		 * We don't complete the IOCTL until all three DL_PARs
15574 		 * have been attempted.
15575 		 *
15576 		 * We don't need any lock to update ill_nd_lla* fields,
15577 		 * since the ill is not yet up, We grab the lock just
15578 		 * for uniformity with other code that accesses ill_nd_lla.
15579 		 */
15580 		physaddr_req = ill->ill_phys_addr_pend;
15581 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15582 		if (physaddr_req == DL_IPV6_TOKEN ||
15583 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15584 			if (physaddr_req == DL_IPV6_TOKEN) {
15585 				/*
15586 				 * bcopy to low-order bits of ill_token
15587 				 *
15588 				 * XXX Temporary hack - currently,
15589 				 * all known tokens are 64 bits,
15590 				 * so I'll cheat for the moment.
15591 				 */
15592 				dlp = (union DL_primitives *)mp->b_rptr;
15593 
15594 				mutex_enter(&ill->ill_lock);
15595 				bcopy((uchar_t *)(mp->b_rptr +
15596 				dlp->physaddr_ack.dl_addr_offset),
15597 				(void *)&ill->ill_token.s6_addr32[2],
15598 				dlp->physaddr_ack.dl_addr_length);
15599 				ill->ill_token_length =
15600 					dlp->physaddr_ack.dl_addr_length;
15601 				mutex_exit(&ill->ill_lock);
15602 			} else {
15603 				ASSERT(ill->ill_nd_lla_mp == NULL);
15604 				mp_hw = copyb(mp);
15605 				if (mp_hw == NULL) {
15606 					err = ENOMEM;
15607 					break;
15608 				}
15609 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15610 				mutex_enter(&ill->ill_lock);
15611 				ill->ill_nd_lla_mp = mp_hw;
15612 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15613 				dlp->physaddr_ack.dl_addr_offset;
15614 				ill->ill_nd_lla_len =
15615 					dlp->physaddr_ack.dl_addr_length;
15616 				mutex_exit(&ill->ill_lock);
15617 			}
15618 			break;
15619 		}
15620 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15621 		ASSERT(ill->ill_phys_addr_mp == NULL);
15622 		if (!ill->ill_ifname_pending)
15623 			break;
15624 		ill->ill_ifname_pending = 0;
15625 		if (!ioctl_aborted)
15626 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15627 		if (mp1 != NULL) {
15628 			ASSERT(connp == NULL);
15629 			q = ill->ill_wq;
15630 		}
15631 		/*
15632 		 * If any error acks received during the plumbing sequence,
15633 		 * ill_ifname_pending_err will be set. Break out and send up
15634 		 * the error to the pending ioctl.
15635 		 */
15636 		if (ill->ill_ifname_pending_err != 0) {
15637 			err = ill->ill_ifname_pending_err;
15638 			ill->ill_ifname_pending_err = 0;
15639 			break;
15640 		}
15641 		/*
15642 		 * Get the interface token.  If the zeroth interface
15643 		 * address is zero then set the address to the link local
15644 		 * address
15645 		 */
15646 		mp_hw = copyb(mp);
15647 		if (mp_hw == NULL) {
15648 			err = ENOMEM;
15649 			break;
15650 		}
15651 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15652 		ill->ill_phys_addr_mp = mp_hw;
15653 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15654 				dlp->physaddr_ack.dl_addr_offset;
15655 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15656 		    ill->ill_phys_addr_length == 0 ||
15657 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15658 			/*
15659 			 * Compatibility: atun driver returns a length of 0.
15660 			 * ipdptp has an ill_phys_addr_length of zero(from
15661 			 * DL_BIND_ACK) but a non-zero length here.
15662 			 * ipd has an ill_phys_addr_length of 4(from
15663 			 * DL_BIND_ACK) but a non-zero length here.
15664 			 */
15665 			ill->ill_phys_addr = NULL;
15666 		} else if (dlp->physaddr_ack.dl_addr_length !=
15667 		    ill->ill_phys_addr_length) {
15668 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15669 			    "Address length mismatch %d %d\n",
15670 			    dlp->physaddr_ack.dl_addr_length,
15671 			    ill->ill_phys_addr_length));
15672 			err = EINVAL;
15673 			break;
15674 		}
15675 		mutex_enter(&ill->ill_lock);
15676 		if (ill->ill_nd_lla_mp == NULL) {
15677 			ill->ill_nd_lla_mp = copyb(mp_hw);
15678 			if (ill->ill_nd_lla_mp == NULL) {
15679 				err = ENOMEM;
15680 				mutex_exit(&ill->ill_lock);
15681 				break;
15682 			}
15683 			ill->ill_nd_lla =
15684 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15685 			    dlp->physaddr_ack.dl_addr_offset;
15686 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15687 		}
15688 		mutex_exit(&ill->ill_lock);
15689 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15690 			(void) ill_setdefaulttoken(ill);
15691 
15692 		/*
15693 		 * If the ill zero interface has a zero address assign
15694 		 * it the proper link local address.
15695 		 */
15696 		ASSERT(ill->ill_ipif->ipif_id == 0);
15697 		if (ipif != NULL &&
15698 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15699 			(void) ipif_setlinklocal(ipif);
15700 		break;
15701 	}
15702 	case DL_OK_ACK:
15703 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15704 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15705 		    dloa->dl_correct_primitive));
15706 		switch (dloa->dl_correct_primitive) {
15707 		case DL_UNBIND_REQ:
15708 		case DL_ATTACH_REQ:
15709 		case DL_DETACH_REQ:
15710 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15711 			break;
15712 		}
15713 		break;
15714 	default:
15715 		break;
15716 	}
15717 
15718 	freemsg(mp);
15719 	if (mp1) {
15720 		struct iocblk *iocp;
15721 		int mode;
15722 
15723 		/*
15724 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15725 		 * SIOCSLIFNAME do a copyout.
15726 		 */
15727 		iocp = (struct iocblk *)mp1->b_rptr;
15728 
15729 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
15730 		    iocp->ioc_cmd == SIOCSLIFNAME)
15731 			mode = COPYOUT;
15732 		else
15733 			mode = NO_COPYOUT;
15734 		/*
15735 		 * The ioctl must complete now without EINPROGRESS
15736 		 * since ipsq_pending_mp_get has removed the ioctl mblk
15737 		 * from ipsq_pending_mp. Otherwise the ioctl will be
15738 		 * stuck for ever in the ipsq.
15739 		 */
15740 		ASSERT(err != EINPROGRESS);
15741 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
15742 
15743 	}
15744 }
15745 
15746 /*
15747  * ip_rput_other is called by ip_rput to handle messages modifying the global
15748  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15749  */
15750 /* ARGSUSED */
15751 void
15752 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15753 {
15754 	ill_t		*ill;
15755 	struct iocblk	*iocp;
15756 	mblk_t		*mp1;
15757 	conn_t		*connp = NULL;
15758 
15759 	ip1dbg(("ip_rput_other "));
15760 	ill = (ill_t *)q->q_ptr;
15761 	/*
15762 	 * This routine is not a writer in the case of SIOCGTUNPARAM
15763 	 * in which case ipsq is NULL.
15764 	 */
15765 	if (ipsq != NULL) {
15766 		ASSERT(IAM_WRITER_IPSQ(ipsq));
15767 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15768 	}
15769 
15770 	switch (mp->b_datap->db_type) {
15771 	case M_ERROR:
15772 	case M_HANGUP:
15773 		/*
15774 		 * The device has a problem.  We force the ILL down.  It can
15775 		 * be brought up again manually using SIOCSIFFLAGS (via
15776 		 * ifconfig or equivalent).
15777 		 */
15778 		ASSERT(ipsq != NULL);
15779 		if (mp->b_rptr < mp->b_wptr)
15780 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
15781 		if (ill->ill_error == 0)
15782 			ill->ill_error = ENXIO;
15783 		if (!ill_down_start(q, mp))
15784 			return;
15785 		ipif_all_down_tail(ipsq, q, mp, NULL);
15786 		break;
15787 	case M_IOCACK:
15788 		iocp = (struct iocblk *)mp->b_rptr;
15789 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
15790 		switch (iocp->ioc_cmd) {
15791 		case SIOCSTUNPARAM:
15792 		case OSIOCSTUNPARAM:
15793 			ASSERT(ipsq != NULL);
15794 			/*
15795 			 * Finish socket ioctl passed through to tun.
15796 			 * We should have an IOCTL waiting on this.
15797 			 */
15798 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15799 			if (ill->ill_isv6) {
15800 				struct iftun_req *ta;
15801 
15802 				/*
15803 				 * if a source or destination is
15804 				 * being set, try and set the link
15805 				 * local address for the tunnel
15806 				 */
15807 				ta = (struct iftun_req *)mp->b_cont->
15808 				    b_cont->b_rptr;
15809 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
15810 					ipif_set_tun_llink(ill, ta);
15811 				}
15812 
15813 			}
15814 			if (mp1 != NULL) {
15815 				/*
15816 				 * Now copy back the b_next/b_prev used by
15817 				 * mi code for the mi_copy* functions.
15818 				 * See ip_sioctl_tunparam() for the reason.
15819 				 * Also protect against missing b_cont.
15820 				 */
15821 				if (mp->b_cont != NULL) {
15822 					mp->b_cont->b_next =
15823 					    mp1->b_cont->b_next;
15824 					mp->b_cont->b_prev =
15825 					    mp1->b_cont->b_prev;
15826 				}
15827 				inet_freemsg(mp1);
15828 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15829 				ASSERT(connp != NULL);
15830 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15831 				    iocp->ioc_error, NO_COPYOUT,
15832 				    ipsq->ipsq_current_ipif, ipsq);
15833 			} else {
15834 				ASSERT(connp == NULL);
15835 				putnext(q, mp);
15836 			}
15837 			break;
15838 		case SIOCGTUNPARAM:
15839 		case OSIOCGTUNPARAM:
15840 			/*
15841 			 * This is really M_IOCDATA from the tunnel driver.
15842 			 * convert back and complete the ioctl.
15843 			 * We should have an IOCTL waiting on this.
15844 			 */
15845 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
15846 			if (mp1) {
15847 				/*
15848 				 * Now copy back the b_next/b_prev used by
15849 				 * mi code for the mi_copy* functions.
15850 				 * See ip_sioctl_tunparam() for the reason.
15851 				 * Also protect against missing b_cont.
15852 				 */
15853 				if (mp->b_cont != NULL) {
15854 					mp->b_cont->b_next =
15855 					    mp1->b_cont->b_next;
15856 					mp->b_cont->b_prev =
15857 					    mp1->b_cont->b_prev;
15858 				}
15859 				inet_freemsg(mp1);
15860 				if (iocp->ioc_error == 0)
15861 					mp->b_datap->db_type = M_IOCDATA;
15862 				ASSERT(connp != NULL);
15863 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15864 				    iocp->ioc_error, COPYOUT, NULL, NULL);
15865 			} else {
15866 				ASSERT(connp == NULL);
15867 				putnext(q, mp);
15868 			}
15869 			break;
15870 		default:
15871 			break;
15872 		}
15873 		break;
15874 	case M_IOCNAK:
15875 		iocp = (struct iocblk *)mp->b_rptr;
15876 
15877 		switch (iocp->ioc_cmd) {
15878 		int mode;
15879 		ipif_t	*ipif;
15880 
15881 		case DL_IOC_HDR_INFO:
15882 			/*
15883 			 * If this was the first attempt turn of the
15884 			 * fastpath probing.
15885 			 */
15886 			mutex_enter(&ill->ill_lock);
15887 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
15888 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
15889 				mutex_exit(&ill->ill_lock);
15890 				ill_fastpath_nack(ill);
15891 				ip1dbg(("ip_rput: DLPI fastpath off on "
15892 				    "interface %s\n",
15893 				    ill->ill_name));
15894 			} else {
15895 				mutex_exit(&ill->ill_lock);
15896 			}
15897 			freemsg(mp);
15898 			break;
15899 		case SIOCSTUNPARAM:
15900 		case OSIOCSTUNPARAM:
15901 			ASSERT(ipsq != NULL);
15902 			/*
15903 			 * Finish socket ioctl passed through to tun
15904 			 * We should have an IOCTL waiting on this.
15905 			 */
15906 			/* FALLTHRU */
15907 		case SIOCGTUNPARAM:
15908 		case OSIOCGTUNPARAM:
15909 			/*
15910 			 * This is really M_IOCDATA from the tunnel driver.
15911 			 * convert back and complete the ioctl.
15912 			 * We should have an IOCTL waiting on this.
15913 			 */
15914 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
15915 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
15916 				mp1 = ill_pending_mp_get(ill, &connp,
15917 				    iocp->ioc_id);
15918 				mode = COPYOUT;
15919 				ipsq = NULL;
15920 				ipif = NULL;
15921 			} else {
15922 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15923 				mode = NO_COPYOUT;
15924 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15925 				ipif = ipsq->ipsq_current_ipif;
15926 			}
15927 			if (mp1 != NULL) {
15928 				/*
15929 				 * Now copy back the b_next/b_prev used by
15930 				 * mi code for the mi_copy* functions.
15931 				 * See ip_sioctl_tunparam() for the reason.
15932 				 * Also protect against missing b_cont.
15933 				 */
15934 				if (mp->b_cont != NULL) {
15935 					mp->b_cont->b_next =
15936 					    mp1->b_cont->b_next;
15937 					mp->b_cont->b_prev =
15938 					    mp1->b_cont->b_prev;
15939 				}
15940 				inet_freemsg(mp1);
15941 				if (iocp->ioc_error == 0)
15942 					iocp->ioc_error = EINVAL;
15943 				ASSERT(connp != NULL);
15944 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15945 				    iocp->ioc_error, mode, ipif, ipsq);
15946 			} else {
15947 				ASSERT(connp == NULL);
15948 				putnext(q, mp);
15949 			}
15950 			break;
15951 		default:
15952 			break;
15953 		}
15954 	default:
15955 		break;
15956 	}
15957 }
15958 
15959 /*
15960  * NOTE : This function does not ire_refrele the ire argument passed in.
15961  *
15962  * IPQoS notes
15963  * IP policy is invoked twice for a forwarded packet, once on the read side
15964  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
15965  * enabled. An additional parameter, in_ill, has been added for this purpose.
15966  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
15967  * because ip_mroute drops this information.
15968  *
15969  */
15970 void
15971 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
15972 {
15973 	uint32_t	pkt_len;
15974 	queue_t	*q;
15975 	uint32_t	sum;
15976 #define	rptr	((uchar_t *)ipha)
15977 	uint32_t	max_frag;
15978 	uint32_t	ill_index;
15979 
15980 	/* Get the ill_index of the incoming ILL */
15981 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
15982 
15983 	/* Initiate Read side IPPF processing */
15984 	if (IPP_ENABLED(IPP_FWD_IN)) {
15985 		ip_process(IPP_FWD_IN, &mp, ill_index);
15986 		if (mp == NULL) {
15987 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
15988 			    "during IPPF processing\n"));
15989 			return;
15990 		}
15991 	}
15992 
15993 	pkt_len = ntohs(ipha->ipha_length);
15994 
15995 	/* Adjust the checksum to reflect the ttl decrement. */
15996 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
15997 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
15998 
15999 	if (ipha->ipha_ttl-- <= 1) {
16000 		if (ip_csum_hdr(ipha)) {
16001 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16002 			goto drop_pkt;
16003 		}
16004 		/*
16005 		 * Note: ire_stq this will be NULL for multicast
16006 		 * datagrams using the long path through arp (the IRE
16007 		 * is not an IRE_CACHE). This should not cause
16008 		 * problems since we don't generate ICMP errors for
16009 		 * multicast packets.
16010 		 */
16011 		q = ire->ire_stq;
16012 		if (q)
16013 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
16014 		else
16015 			freemsg(mp);
16016 		return;
16017 	}
16018 
16019 	/*
16020 	 * Don't forward if the interface is down
16021 	 */
16022 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16023 		BUMP_MIB(&ip_mib, ipInDiscards);
16024 		ip2dbg(("ip_rput_forward:interface is down\n"));
16025 		goto drop_pkt;
16026 	}
16027 
16028 	/* Get the ill_index of the outgoing ILL */
16029 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16030 
16031 	if (is_system_labeled()) {
16032 		mblk_t *mp1;
16033 
16034 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16035 			BUMP_MIB(&ip_mib, ipForwProhibits);
16036 			goto drop_pkt;
16037 		}
16038 		/* Size may have changed */
16039 		mp = mp1;
16040 		ipha = (ipha_t *)mp->b_rptr;
16041 		pkt_len = ntohs(ipha->ipha_length);
16042 	}
16043 
16044 	/* Check if there are options to update */
16045 	if (!IS_SIMPLE_IPH(ipha)) {
16046 		if (ip_csum_hdr(ipha)) {
16047 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16048 			goto drop_pkt;
16049 		}
16050 		if (ip_rput_forward_options(mp, ipha, ire)) {
16051 			return;
16052 		}
16053 
16054 		ipha->ipha_hdr_checksum = 0;
16055 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16056 	}
16057 	max_frag = ire->ire_max_frag;
16058 	if (pkt_len > max_frag) {
16059 		/*
16060 		 * It needs fragging on its way out.  We haven't
16061 		 * verified the header checksum yet.  Since we
16062 		 * are going to put a surely good checksum in the
16063 		 * outgoing header, we have to make sure that it
16064 		 * was good coming in.
16065 		 */
16066 		if (ip_csum_hdr(ipha)) {
16067 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16068 			goto drop_pkt;
16069 		}
16070 		/* Initiate Write side IPPF processing */
16071 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16072 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16073 			if (mp == NULL) {
16074 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16075 				    " during IPPF processing\n"));
16076 				return;
16077 			}
16078 		}
16079 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
16080 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16081 		return;
16082 	}
16083 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16084 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16085 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16086 	/* ip_xmit_v4 always consumes the packet */
16087 	return;
16088 
16089 drop_pkt:;
16090 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16091 	freemsg(mp);
16092 #undef	rptr
16093 }
16094 
16095 void
16096 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16097 {
16098 	ire_t	*ire;
16099 
16100 	ASSERT(!ipif->ipif_isv6);
16101 	/*
16102 	 * Find an IRE which matches the destination and the outgoing
16103 	 * queue in the cache table. All we need is an IRE_CACHE which
16104 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16105 	 * then it is enough to have some IRE_CACHE in the group.
16106 	 */
16107 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16108 		dst = ipif->ipif_pp_dst_addr;
16109 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16110 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16111 	if (ire == NULL) {
16112 		/*
16113 		 * Mark this packet to make it be delivered to
16114 		 * ip_rput_forward after the new ire has been
16115 		 * created.
16116 		 */
16117 		mp->b_prev = NULL;
16118 		mp->b_next = mp;
16119 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16120 		    NULL, 0);
16121 	} else {
16122 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16123 		IRE_REFRELE(ire);
16124 	}
16125 }
16126 
16127 /* Update any source route, record route or timestamp options */
16128 static int
16129 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16130 {
16131 	ipoptp_t	opts;
16132 	uchar_t		*opt;
16133 	uint8_t		optval;
16134 	uint8_t		optlen;
16135 	ipaddr_t	dst;
16136 	uint32_t	ts;
16137 	ire_t		*dst_ire = NULL;
16138 	ire_t		*tmp_ire = NULL;
16139 	timestruc_t	now;
16140 
16141 	ip2dbg(("ip_rput_forward_options\n"));
16142 	dst = ipha->ipha_dst;
16143 	for (optval = ipoptp_first(&opts, ipha);
16144 	    optval != IPOPT_EOL;
16145 	    optval = ipoptp_next(&opts)) {
16146 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16147 		opt = opts.ipoptp_cur;
16148 		optlen = opts.ipoptp_len;
16149 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16150 		    optval, opts.ipoptp_len));
16151 		switch (optval) {
16152 			uint32_t off;
16153 		case IPOPT_SSRR:
16154 		case IPOPT_LSRR:
16155 			/* Check if adminstratively disabled */
16156 			if (!ip_forward_src_routed) {
16157 				BUMP_MIB(&ip_mib, ipForwProhibits);
16158 				if (ire->ire_stq)
16159 					icmp_unreachable(ire->ire_stq, mp,
16160 					    ICMP_SOURCE_ROUTE_FAILED);
16161 				else {
16162 					ip0dbg(("ip_rput_forward_options: "
16163 					    "unable to send unreach\n"));
16164 					freemsg(mp);
16165 				}
16166 				return (-1);
16167 			}
16168 
16169 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16170 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16171 			if (dst_ire == NULL) {
16172 				/*
16173 				 * Must be partial since ip_rput_options
16174 				 * checked for strict.
16175 				 */
16176 				break;
16177 			}
16178 			off = opt[IPOPT_OFFSET];
16179 			off--;
16180 		redo_srr:
16181 			if (optlen < IP_ADDR_LEN ||
16182 			    off > optlen - IP_ADDR_LEN) {
16183 				/* End of source route */
16184 				ip1dbg((
16185 				    "ip_rput_forward_options: end of SR\n"));
16186 				ire_refrele(dst_ire);
16187 				break;
16188 			}
16189 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16190 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16191 			    IP_ADDR_LEN);
16192 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16193 			    ntohl(dst)));
16194 
16195 			/*
16196 			 * Check if our address is present more than
16197 			 * once as consecutive hops in source route.
16198 			 */
16199 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16200 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16201 			if (tmp_ire != NULL) {
16202 				ire_refrele(tmp_ire);
16203 				off += IP_ADDR_LEN;
16204 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16205 				goto redo_srr;
16206 			}
16207 			ipha->ipha_dst = dst;
16208 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16209 			ire_refrele(dst_ire);
16210 			break;
16211 		case IPOPT_RR:
16212 			off = opt[IPOPT_OFFSET];
16213 			off--;
16214 			if (optlen < IP_ADDR_LEN ||
16215 			    off > optlen - IP_ADDR_LEN) {
16216 				/* No more room - ignore */
16217 				ip1dbg((
16218 				    "ip_rput_forward_options: end of RR\n"));
16219 				break;
16220 			}
16221 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16222 			    IP_ADDR_LEN);
16223 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16224 			break;
16225 		case IPOPT_TS:
16226 			/* Insert timestamp if there is room */
16227 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16228 			case IPOPT_TS_TSONLY:
16229 				off = IPOPT_TS_TIMELEN;
16230 				break;
16231 			case IPOPT_TS_PRESPEC:
16232 			case IPOPT_TS_PRESPEC_RFC791:
16233 				/* Verify that the address matched */
16234 				off = opt[IPOPT_OFFSET] - 1;
16235 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16236 				dst_ire = ire_ctable_lookup(dst, 0,
16237 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16238 				    MATCH_IRE_TYPE);
16239 
16240 				if (dst_ire == NULL) {
16241 					/* Not for us */
16242 					break;
16243 				}
16244 				ire_refrele(dst_ire);
16245 				/* FALLTHRU */
16246 			case IPOPT_TS_TSANDADDR:
16247 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16248 				break;
16249 			default:
16250 				/*
16251 				 * ip_*put_options should have already
16252 				 * dropped this packet.
16253 				 */
16254 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16255 				    "unknown IT - bug in ip_rput_options?\n");
16256 				return (0);	/* Keep "lint" happy */
16257 			}
16258 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16259 				/* Increase overflow counter */
16260 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16261 				opt[IPOPT_POS_OV_FLG] =
16262 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16263 				    (off << 4));
16264 				break;
16265 			}
16266 			off = opt[IPOPT_OFFSET] - 1;
16267 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16268 			case IPOPT_TS_PRESPEC:
16269 			case IPOPT_TS_PRESPEC_RFC791:
16270 			case IPOPT_TS_TSANDADDR:
16271 				bcopy(&ire->ire_src_addr,
16272 				    (char *)opt + off, IP_ADDR_LEN);
16273 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16274 				/* FALLTHRU */
16275 			case IPOPT_TS_TSONLY:
16276 				off = opt[IPOPT_OFFSET] - 1;
16277 				/* Compute # of milliseconds since midnight */
16278 				gethrestime(&now);
16279 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16280 				    now.tv_nsec / (NANOSEC / MILLISEC);
16281 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16282 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16283 				break;
16284 			}
16285 			break;
16286 		}
16287 	}
16288 	return (0);
16289 }
16290 
16291 /*
16292  * This is called after processing at least one of AH/ESP headers.
16293  *
16294  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16295  * the actual, physical interface on which the packet was received,
16296  * but, when ip_strict_dst_multihoming is set to 1, could be the
16297  * interface which had the ipha_dst configured when the packet went
16298  * through ip_rput. The ill_index corresponding to the recv_ill
16299  * is saved in ipsec_in_rill_index
16300  */
16301 void
16302 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16303 {
16304 	mblk_t *mp;
16305 	ipaddr_t dst;
16306 	in6_addr_t *v6dstp;
16307 	ipha_t *ipha;
16308 	ip6_t *ip6h;
16309 	ipsec_in_t *ii;
16310 	boolean_t ill_need_rele = B_FALSE;
16311 	boolean_t rill_need_rele = B_FALSE;
16312 	boolean_t ire_need_rele = B_FALSE;
16313 
16314 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16315 	ASSERT(ii->ipsec_in_ill_index != 0);
16316 
16317 	mp = ipsec_mp->b_cont;
16318 	ASSERT(mp != NULL);
16319 
16320 
16321 	if (ill == NULL) {
16322 		ASSERT(recv_ill == NULL);
16323 		/*
16324 		 * We need to get the original queue on which ip_rput_local
16325 		 * or ip_rput_data_v6 was called.
16326 		 */
16327 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16328 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16329 		ill_need_rele = B_TRUE;
16330 
16331 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16332 			recv_ill = ill_lookup_on_ifindex(
16333 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16334 			    NULL, NULL, NULL, NULL);
16335 			rill_need_rele = B_TRUE;
16336 		} else {
16337 			recv_ill = ill;
16338 		}
16339 
16340 		if ((ill == NULL) || (recv_ill == NULL)) {
16341 			ip0dbg(("ip_fanout_proto_again: interface "
16342 			    "disappeared\n"));
16343 			if (ill != NULL)
16344 				ill_refrele(ill);
16345 			if (recv_ill != NULL)
16346 				ill_refrele(recv_ill);
16347 			freemsg(ipsec_mp);
16348 			return;
16349 		}
16350 	}
16351 
16352 	ASSERT(ill != NULL && recv_ill != NULL);
16353 
16354 	if (mp->b_datap->db_type == M_CTL) {
16355 		/*
16356 		 * AH/ESP is returning the ICMP message after
16357 		 * removing their headers. Fanout again till
16358 		 * it gets to the right protocol.
16359 		 */
16360 		if (ii->ipsec_in_v4) {
16361 			icmph_t *icmph;
16362 			int iph_hdr_length;
16363 			int hdr_length;
16364 
16365 			ipha = (ipha_t *)mp->b_rptr;
16366 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16367 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16368 			ipha = (ipha_t *)&icmph[1];
16369 			hdr_length = IPH_HDR_LENGTH(ipha);
16370 			/*
16371 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16372 			 * Reset the type to M_DATA.
16373 			 */
16374 			mp->b_datap->db_type = M_DATA;
16375 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16376 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16377 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16378 		} else {
16379 			icmp6_t *icmp6;
16380 			int hdr_length;
16381 
16382 			ip6h = (ip6_t *)mp->b_rptr;
16383 			/* Don't call hdr_length_v6() unless you have to. */
16384 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16385 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16386 			else
16387 				hdr_length = IPV6_HDR_LEN;
16388 
16389 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16390 			/*
16391 			 * icmp_inbound_error_fanout_v6 may need to do
16392 			 * pullupmsg.  Reset the type to M_DATA.
16393 			 */
16394 			mp->b_datap->db_type = M_DATA;
16395 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16396 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16397 		}
16398 		if (ill_need_rele)
16399 			ill_refrele(ill);
16400 		if (rill_need_rele)
16401 			ill_refrele(recv_ill);
16402 		return;
16403 	}
16404 
16405 	if (ii->ipsec_in_v4) {
16406 		ipha = (ipha_t *)mp->b_rptr;
16407 		dst = ipha->ipha_dst;
16408 		if (CLASSD(dst)) {
16409 			/*
16410 			 * Multicast has to be delivered to all streams.
16411 			 */
16412 			dst = INADDR_BROADCAST;
16413 		}
16414 
16415 		if (ire == NULL) {
16416 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16417 			    MBLK_GETLABEL(mp));
16418 			if (ire == NULL) {
16419 				if (ill_need_rele)
16420 					ill_refrele(ill);
16421 				if (rill_need_rele)
16422 					ill_refrele(recv_ill);
16423 				ip1dbg(("ip_fanout_proto_again: "
16424 				    "IRE not found"));
16425 				freemsg(ipsec_mp);
16426 				return;
16427 			}
16428 			ire_need_rele = B_TRUE;
16429 		}
16430 
16431 		switch (ipha->ipha_protocol) {
16432 			case IPPROTO_UDP:
16433 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16434 				    recv_ill);
16435 				if (ire_need_rele)
16436 					ire_refrele(ire);
16437 				break;
16438 			case IPPROTO_TCP:
16439 				if (!ire_need_rele)
16440 					IRE_REFHOLD(ire);
16441 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16442 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16443 				IRE_REFRELE(ire);
16444 				if (mp != NULL)
16445 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16446 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16447 				break;
16448 			case IPPROTO_SCTP:
16449 				if (!ire_need_rele)
16450 					IRE_REFHOLD(ire);
16451 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16452 				    ipsec_mp, 0, ill->ill_rq, dst);
16453 				break;
16454 			default:
16455 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16456 				    recv_ill);
16457 				if (ire_need_rele)
16458 					ire_refrele(ire);
16459 				break;
16460 		}
16461 	} else {
16462 		uint32_t rput_flags = 0;
16463 
16464 		ip6h = (ip6_t *)mp->b_rptr;
16465 		v6dstp = &ip6h->ip6_dst;
16466 		/*
16467 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16468 		 * address.
16469 		 *
16470 		 * Currently, we don't store that state in the IPSEC_IN
16471 		 * message, and we may need to.
16472 		 */
16473 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16474 		    IP6_IN_LLMCAST : 0);
16475 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16476 		    NULL, NULL);
16477 	}
16478 	if (ill_need_rele)
16479 		ill_refrele(ill);
16480 	if (rill_need_rele)
16481 		ill_refrele(recv_ill);
16482 }
16483 
16484 /*
16485  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16486  * returns 'true' if there are still fragments left on the queue, in
16487  * which case we restart the timer.
16488  */
16489 void
16490 ill_frag_timer(void *arg)
16491 {
16492 	ill_t	*ill = (ill_t *)arg;
16493 	boolean_t frag_pending;
16494 
16495 	mutex_enter(&ill->ill_lock);
16496 	ASSERT(!ill->ill_fragtimer_executing);
16497 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16498 		ill->ill_frag_timer_id = 0;
16499 		mutex_exit(&ill->ill_lock);
16500 		return;
16501 	}
16502 	ill->ill_fragtimer_executing = 1;
16503 	mutex_exit(&ill->ill_lock);
16504 
16505 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16506 
16507 	/*
16508 	 * Restart the timer, if we have fragments pending or if someone
16509 	 * wanted us to be scheduled again.
16510 	 */
16511 	mutex_enter(&ill->ill_lock);
16512 	ill->ill_fragtimer_executing = 0;
16513 	ill->ill_frag_timer_id = 0;
16514 	if (frag_pending || ill->ill_fragtimer_needrestart)
16515 		ill_frag_timer_start(ill);
16516 	mutex_exit(&ill->ill_lock);
16517 }
16518 
16519 void
16520 ill_frag_timer_start(ill_t *ill)
16521 {
16522 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16523 
16524 	/* If the ill is closing or opening don't proceed */
16525 	if (ill->ill_state_flags & ILL_CONDEMNED)
16526 		return;
16527 
16528 	if (ill->ill_fragtimer_executing) {
16529 		/*
16530 		 * ill_frag_timer is currently executing. Just record the
16531 		 * the fact that we want the timer to be restarted.
16532 		 * ill_frag_timer will post a timeout before it returns,
16533 		 * ensuring it will be called again.
16534 		 */
16535 		ill->ill_fragtimer_needrestart = 1;
16536 		return;
16537 	}
16538 
16539 	if (ill->ill_frag_timer_id == 0) {
16540 		/*
16541 		 * The timer is neither running nor is the timeout handler
16542 		 * executing. Post a timeout so that ill_frag_timer will be
16543 		 * called
16544 		 */
16545 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16546 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16547 		ill->ill_fragtimer_needrestart = 0;
16548 	}
16549 }
16550 
16551 /*
16552  * This routine is needed for loopback when forwarding multicasts.
16553  *
16554  * IPQoS Notes:
16555  * IPPF processing is done in fanout routines.
16556  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16557  * processing for IPSec packets is done when it comes back in clear.
16558  * NOTE : The callers of this function need to do the ire_refrele for the
16559  *	  ire that is being passed in.
16560  */
16561 void
16562 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16563     ill_t *recv_ill)
16564 {
16565 	ill_t	*ill = (ill_t *)q->q_ptr;
16566 	uint32_t	sum;
16567 	uint32_t	u1;
16568 	uint32_t	u2;
16569 	int		hdr_length;
16570 	boolean_t	mctl_present;
16571 	mblk_t		*first_mp = mp;
16572 	mblk_t		*hada_mp = NULL;
16573 	ipha_t		*inner_ipha;
16574 
16575 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16576 	    "ip_rput_locl_start: q %p", q);
16577 
16578 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16579 
16580 
16581 #define	rptr	((uchar_t *)ipha)
16582 #define	iphs	((uint16_t *)ipha)
16583 
16584 	/*
16585 	 * no UDP or TCP packet should come here anymore.
16586 	 */
16587 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16588 	    (ipha->ipha_protocol != IPPROTO_UDP));
16589 
16590 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16591 	if (mctl_present &&
16592 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16593 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16594 
16595 		/*
16596 		 * It's an IPsec accelerated packet.
16597 		 * Keep a pointer to the data attributes around until
16598 		 * we allocate the ipsec_info_t.
16599 		 */
16600 		IPSECHW_DEBUG(IPSECHW_PKT,
16601 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16602 		hada_mp = first_mp;
16603 		hada_mp->b_cont = NULL;
16604 		/*
16605 		 * Since it is accelerated, it comes directly from
16606 		 * the ill and the data attributes is followed by
16607 		 * the packet data.
16608 		 */
16609 		ASSERT(mp->b_datap->db_type != M_CTL);
16610 		first_mp = mp;
16611 		mctl_present = B_FALSE;
16612 	}
16613 
16614 	/*
16615 	 * IF M_CTL is not present, then ipsec_in_is_secure
16616 	 * should return B_TRUE. There is a case where loopback
16617 	 * packets has an M_CTL in the front with all the
16618 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16619 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16620 	 * packets never comes here, it is safe to ASSERT the
16621 	 * following.
16622 	 */
16623 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16624 
16625 
16626 	/* u1 is # words of IP options */
16627 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16628 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16629 
16630 	if (u1) {
16631 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16632 			if (hada_mp != NULL)
16633 				freemsg(hada_mp);
16634 			return;
16635 		}
16636 	} else {
16637 		/* Check the IP header checksum.  */
16638 #define	uph	((uint16_t *)ipha)
16639 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16640 		    uph[6] + uph[7] + uph[8] + uph[9];
16641 #undef  uph
16642 		/* finish doing IP checksum */
16643 		sum = (sum & 0xFFFF) + (sum >> 16);
16644 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16645 		/*
16646 		 * Don't verify header checksum if this packet is coming
16647 		 * back from AH/ESP as we already did it.
16648 		 */
16649 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16650 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16651 			goto drop_pkt;
16652 		}
16653 	}
16654 
16655 	/*
16656 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16657 	 * might be called more than once for secure packets, count only
16658 	 * the first time.
16659 	 */
16660 	if (!mctl_present) {
16661 		UPDATE_IB_PKT_COUNT(ire);
16662 		ire->ire_last_used_time = lbolt;
16663 	}
16664 
16665 	/* Check for fragmentation offset. */
16666 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16667 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16668 	if (u1) {
16669 		/*
16670 		 * We re-assemble fragments before we do the AH/ESP
16671 		 * processing. Thus, M_CTL should not be present
16672 		 * while we are re-assembling.
16673 		 */
16674 		ASSERT(!mctl_present);
16675 		ASSERT(first_mp == mp);
16676 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16677 			return;
16678 		}
16679 		/*
16680 		 * Make sure that first_mp points back to mp as
16681 		 * the mp we came in with could have changed in
16682 		 * ip_rput_fragment().
16683 		 */
16684 		ipha = (ipha_t *)mp->b_rptr;
16685 		first_mp = mp;
16686 	}
16687 
16688 	/*
16689 	 * Clear hardware checksumming flag as it is currently only
16690 	 * used by TCP and UDP.
16691 	 */
16692 	DB_CKSUMFLAGS(mp) = 0;
16693 
16694 	/* Now we have a complete datagram, destined for this machine. */
16695 	u1 = IPH_HDR_LENGTH(ipha);
16696 	switch (ipha->ipha_protocol) {
16697 	case IPPROTO_ICMP: {
16698 		ire_t		*ire_zone;
16699 		ilm_t		*ilm;
16700 		mblk_t		*mp1;
16701 		zoneid_t	last_zoneid;
16702 
16703 		if (CLASSD(ipha->ipha_dst) &&
16704 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
16705 			ASSERT(ire->ire_type == IRE_BROADCAST);
16706 			/*
16707 			 * In the multicast case, applications may have joined
16708 			 * the group from different zones, so we need to deliver
16709 			 * the packet to each of them. Loop through the
16710 			 * multicast memberships structures (ilm) on the receive
16711 			 * ill and send a copy of the packet up each matching
16712 			 * one. However, we don't do this for multicasts sent on
16713 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16714 			 * they must stay in the sender's zone.
16715 			 *
16716 			 * ilm_add_v6() ensures that ilms in the same zone are
16717 			 * contiguous in the ill_ilm list. We use this property
16718 			 * to avoid sending duplicates needed when two
16719 			 * applications in the same zone join the same group on
16720 			 * different logical interfaces: we ignore the ilm if
16721 			 * its zoneid is the same as the last matching one.
16722 			 * In addition, the sending of the packet for
16723 			 * ire_zoneid is delayed until all of the other ilms
16724 			 * have been exhausted.
16725 			 */
16726 			last_zoneid = -1;
16727 			ILM_WALKER_HOLD(recv_ill);
16728 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
16729 			    ilm = ilm->ilm_next) {
16730 				if ((ilm->ilm_flags & ILM_DELETED) ||
16731 				    ipha->ipha_dst != ilm->ilm_addr ||
16732 				    ilm->ilm_zoneid == last_zoneid ||
16733 				    ilm->ilm_zoneid == ire->ire_zoneid ||
16734 				    ilm->ilm_zoneid == ALL_ZONES ||
16735 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
16736 					continue;
16737 				mp1 = ip_copymsg(first_mp);
16738 				if (mp1 == NULL)
16739 					continue;
16740 				icmp_inbound(q, mp1, B_TRUE, ill,
16741 				    0, sum, mctl_present, B_TRUE,
16742 				    recv_ill, ilm->ilm_zoneid);
16743 				last_zoneid = ilm->ilm_zoneid;
16744 			}
16745 			ILM_WALKER_RELE(recv_ill);
16746 		} else if (ire->ire_type == IRE_BROADCAST) {
16747 			/*
16748 			 * In the broadcast case, there may be many zones
16749 			 * which need a copy of the packet delivered to them.
16750 			 * There is one IRE_BROADCAST per broadcast address
16751 			 * and per zone; we walk those using a helper function.
16752 			 * In addition, the sending of the packet for ire is
16753 			 * delayed until all of the other ires have been
16754 			 * processed.
16755 			 */
16756 			IRB_REFHOLD(ire->ire_bucket);
16757 			ire_zone = NULL;
16758 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
16759 			    ire)) != NULL) {
16760 				mp1 = ip_copymsg(first_mp);
16761 				if (mp1 == NULL)
16762 					continue;
16763 
16764 				UPDATE_IB_PKT_COUNT(ire_zone);
16765 				ire_zone->ire_last_used_time = lbolt;
16766 				icmp_inbound(q, mp1, B_TRUE, ill,
16767 				    0, sum, mctl_present, B_TRUE,
16768 				    recv_ill, ire_zone->ire_zoneid);
16769 			}
16770 			IRB_REFRELE(ire->ire_bucket);
16771 		}
16772 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
16773 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
16774 		    ire->ire_zoneid);
16775 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16776 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
16777 		return;
16778 	}
16779 	case IPPROTO_IGMP:
16780 		/*
16781 		 * If we are not willing to accept IGMP packets in clear,
16782 		 * then check with global policy.
16783 		 */
16784 		if (igmp_accept_clear_messages == 0) {
16785 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16786 			    ipha, NULL, mctl_present);
16787 			if (first_mp == NULL)
16788 				return;
16789 		}
16790 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16791 			freemsg(first_mp);
16792 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
16793 			BUMP_MIB(&ip_mib, ipInDiscards);
16794 			return;
16795 		}
16796 		if (igmp_input(q, mp, ill)) {
16797 			/* Bad packet - discarded by igmp_input */
16798 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16799 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
16800 			if (mctl_present)
16801 				freeb(first_mp);
16802 			return;
16803 		}
16804 		/*
16805 		 * igmp_input() may have pulled up the message so ipha needs to
16806 		 * be reinitialized.
16807 		 */
16808 		ipha = (ipha_t *)mp->b_rptr;
16809 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16810 			/* No user-level listener for IGMP packets */
16811 			goto drop_pkt;
16812 		}
16813 		/* deliver to local raw users */
16814 		break;
16815 	case IPPROTO_PIM:
16816 		/*
16817 		 * If we are not willing to accept PIM packets in clear,
16818 		 * then check with global policy.
16819 		 */
16820 		if (pim_accept_clear_messages == 0) {
16821 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16822 			    ipha, NULL, mctl_present);
16823 			if (first_mp == NULL)
16824 				return;
16825 		}
16826 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16827 			freemsg(first_mp);
16828 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
16829 			BUMP_MIB(&ip_mib, ipInDiscards);
16830 			return;
16831 		}
16832 		if (pim_input(q, mp) != 0) {
16833 			/* Bad packet - discarded by pim_input */
16834 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16835 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
16836 			if (mctl_present)
16837 				freeb(first_mp);
16838 			return;
16839 		}
16840 
16841 		/*
16842 		 * pim_input() may have pulled up the message so ipha needs to
16843 		 * be reinitialized.
16844 		 */
16845 		ipha = (ipha_t *)mp->b_rptr;
16846 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16847 			/* No user-level listener for PIM packets */
16848 			goto drop_pkt;
16849 		}
16850 		/* deliver to local raw users */
16851 		break;
16852 	case IPPROTO_ENCAP:
16853 		/*
16854 		 * Handle self-encapsulated packets (IP-in-IP where
16855 		 * the inner addresses == the outer addresses).
16856 		 */
16857 		hdr_length = IPH_HDR_LENGTH(ipha);
16858 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
16859 		    mp->b_wptr) {
16860 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
16861 			    sizeof (ipha_t) - mp->b_rptr)) {
16862 				BUMP_MIB(&ip_mib, ipInDiscards);
16863 				freemsg(first_mp);
16864 				return;
16865 			}
16866 			ipha = (ipha_t *)mp->b_rptr;
16867 		}
16868 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
16869 		/*
16870 		 * Check the sanity of the inner IP header.
16871 		 */
16872 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
16873 			BUMP_MIB(&ip_mib, ipInDiscards);
16874 			freemsg(first_mp);
16875 			return;
16876 		}
16877 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
16878 			BUMP_MIB(&ip_mib, ipInDiscards);
16879 			freemsg(first_mp);
16880 			return;
16881 		}
16882 		if (inner_ipha->ipha_src == ipha->ipha_src &&
16883 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
16884 			ipsec_in_t *ii;
16885 
16886 			/*
16887 			 * Self-encapsulated tunnel packet. Remove
16888 			 * the outer IP header and fanout again.
16889 			 * We also need to make sure that the inner
16890 			 * header is pulled up until options.
16891 			 */
16892 			mp->b_rptr = (uchar_t *)inner_ipha;
16893 			ipha = inner_ipha;
16894 			hdr_length = IPH_HDR_LENGTH(ipha);
16895 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
16896 				if (!pullupmsg(mp, (uchar_t *)ipha +
16897 				    + hdr_length - mp->b_rptr)) {
16898 					freemsg(first_mp);
16899 					return;
16900 				}
16901 				ipha = (ipha_t *)mp->b_rptr;
16902 			}
16903 			if (!mctl_present) {
16904 				ASSERT(first_mp == mp);
16905 				/*
16906 				 * This means that somebody is sending
16907 				 * Self-encapsualted packets without AH/ESP.
16908 				 * If AH/ESP was present, we would have already
16909 				 * allocated the first_mp.
16910 				 */
16911 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
16912 				    NULL) {
16913 					ip1dbg(("ip_proto_input: IPSEC_IN "
16914 					    "allocation failure.\n"));
16915 					BUMP_MIB(&ip_mib, ipInDiscards);
16916 					freemsg(mp);
16917 					return;
16918 				}
16919 				first_mp->b_cont = mp;
16920 			}
16921 			/*
16922 			 * We generally store the ill_index if we need to
16923 			 * do IPSEC processing as we lose the ill queue when
16924 			 * we come back. But in this case, we never should
16925 			 * have to store the ill_index here as it should have
16926 			 * been stored previously when we processed the
16927 			 * AH/ESP header in this routine or for non-ipsec
16928 			 * cases, we still have the queue. But for some bad
16929 			 * packets from the wire, we can get to IPSEC after
16930 			 * this and we better store the index for that case.
16931 			 */
16932 			ill = (ill_t *)q->q_ptr;
16933 			ii = (ipsec_in_t *)first_mp->b_rptr;
16934 			ii->ipsec_in_ill_index =
16935 			    ill->ill_phyint->phyint_ifindex;
16936 			ii->ipsec_in_rill_index =
16937 			    recv_ill->ill_phyint->phyint_ifindex;
16938 			if (ii->ipsec_in_decaps) {
16939 				/*
16940 				 * This packet is self-encapsulated multiple
16941 				 * times. We don't want to recurse infinitely.
16942 				 * To keep it simple, drop the packet.
16943 				 */
16944 				BUMP_MIB(&ip_mib, ipInDiscards);
16945 				freemsg(first_mp);
16946 				return;
16947 			}
16948 			ii->ipsec_in_decaps = B_TRUE;
16949 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
16950 			return;
16951 		}
16952 		break;
16953 	case IPPROTO_AH:
16954 	case IPPROTO_ESP: {
16955 		/*
16956 		 * Fast path for AH/ESP. If this is the first time
16957 		 * we are sending a datagram to AH/ESP, allocate
16958 		 * a IPSEC_IN message and prepend it. Otherwise,
16959 		 * just fanout.
16960 		 */
16961 
16962 		int ipsec_rc;
16963 		ipsec_in_t *ii;
16964 
16965 		IP_STAT(ipsec_proto_ahesp);
16966 		if (!mctl_present) {
16967 			ASSERT(first_mp == mp);
16968 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
16969 				ip1dbg(("ip_proto_input: IPSEC_IN "
16970 				    "allocation failure.\n"));
16971 				freemsg(hada_mp); /* okay ifnull */
16972 				BUMP_MIB(&ip_mib, ipInDiscards);
16973 				freemsg(mp);
16974 				return;
16975 			}
16976 			/*
16977 			 * Store the ill_index so that when we come back
16978 			 * from IPSEC we ride on the same queue.
16979 			 */
16980 			ill = (ill_t *)q->q_ptr;
16981 			ii = (ipsec_in_t *)first_mp->b_rptr;
16982 			ii->ipsec_in_ill_index =
16983 			    ill->ill_phyint->phyint_ifindex;
16984 			ii->ipsec_in_rill_index =
16985 			    recv_ill->ill_phyint->phyint_ifindex;
16986 			first_mp->b_cont = mp;
16987 			/*
16988 			 * Cache hardware acceleration info.
16989 			 */
16990 			if (hada_mp != NULL) {
16991 				IPSECHW_DEBUG(IPSECHW_PKT,
16992 				    ("ip_rput_local: caching data attr.\n"));
16993 				ii->ipsec_in_accelerated = B_TRUE;
16994 				ii->ipsec_in_da = hada_mp;
16995 				hada_mp = NULL;
16996 			}
16997 		} else {
16998 			ii = (ipsec_in_t *)first_mp->b_rptr;
16999 		}
17000 
17001 		if (!ipsec_loaded()) {
17002 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17003 			    ire->ire_zoneid);
17004 			return;
17005 		}
17006 
17007 		/* select inbound SA and have IPsec process the pkt */
17008 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17009 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17010 			if (esph == NULL)
17011 				return;
17012 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17013 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17014 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17015 			    first_mp, esph);
17016 		} else {
17017 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17018 			if (ah == NULL)
17019 				return;
17020 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17021 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17022 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17023 			    first_mp, ah);
17024 		}
17025 
17026 		switch (ipsec_rc) {
17027 		case IPSEC_STATUS_SUCCESS:
17028 			break;
17029 		case IPSEC_STATUS_FAILED:
17030 			BUMP_MIB(&ip_mib, ipInDiscards);
17031 			/* FALLTHRU */
17032 		case IPSEC_STATUS_PENDING:
17033 			return;
17034 		}
17035 		/* we're done with IPsec processing, send it up */
17036 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17037 		return;
17038 	}
17039 	default:
17040 		break;
17041 	}
17042 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17043 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17044 		    ire->ire_zoneid));
17045 		goto drop_pkt;
17046 	}
17047 	/*
17048 	 * Handle protocols with which IP is less intimate.  There
17049 	 * can be more than one stream bound to a particular
17050 	 * protocol.  When this is the case, each one gets a copy
17051 	 * of any incoming packets.
17052 	 */
17053 	ip_fanout_proto(q, first_mp, ill, ipha,
17054 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17055 	    B_TRUE, recv_ill, ire->ire_zoneid);
17056 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17057 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17058 	return;
17059 
17060 drop_pkt:
17061 	freemsg(first_mp);
17062 	if (hada_mp != NULL)
17063 		freeb(hada_mp);
17064 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17065 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17066 #undef	rptr
17067 #undef  iphs
17068 
17069 }
17070 
17071 /*
17072  * Update any source route, record route or timestamp options.
17073  * Check that we are at end of strict source route.
17074  * The options have already been checked for sanity in ip_rput_options().
17075  */
17076 static boolean_t
17077 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17078 {
17079 	ipoptp_t	opts;
17080 	uchar_t		*opt;
17081 	uint8_t		optval;
17082 	uint8_t		optlen;
17083 	ipaddr_t	dst;
17084 	uint32_t	ts;
17085 	ire_t		*dst_ire;
17086 	timestruc_t	now;
17087 
17088 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17089 
17090 	ip2dbg(("ip_rput_local_options\n"));
17091 
17092 	for (optval = ipoptp_first(&opts, ipha);
17093 	    optval != IPOPT_EOL;
17094 	    optval = ipoptp_next(&opts)) {
17095 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17096 		opt = opts.ipoptp_cur;
17097 		optlen = opts.ipoptp_len;
17098 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17099 		    optval, optlen));
17100 		switch (optval) {
17101 			uint32_t off;
17102 		case IPOPT_SSRR:
17103 		case IPOPT_LSRR:
17104 			off = opt[IPOPT_OFFSET];
17105 			off--;
17106 			if (optlen < IP_ADDR_LEN ||
17107 			    off > optlen - IP_ADDR_LEN) {
17108 				/* End of source route */
17109 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17110 				break;
17111 			}
17112 			/*
17113 			 * This will only happen if two consecutive entries
17114 			 * in the source route contains our address or if
17115 			 * it is a packet with a loose source route which
17116 			 * reaches us before consuming the whole source route
17117 			 */
17118 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17119 			if (optval == IPOPT_SSRR) {
17120 				goto bad_src_route;
17121 			}
17122 			/*
17123 			 * Hack: instead of dropping the packet truncate the
17124 			 * source route to what has been used by filling the
17125 			 * rest with IPOPT_NOP.
17126 			 */
17127 			opt[IPOPT_OLEN] = (uint8_t)off;
17128 			while (off < optlen) {
17129 				opt[off++] = IPOPT_NOP;
17130 			}
17131 			break;
17132 		case IPOPT_RR:
17133 			off = opt[IPOPT_OFFSET];
17134 			off--;
17135 			if (optlen < IP_ADDR_LEN ||
17136 			    off > optlen - IP_ADDR_LEN) {
17137 				/* No more room - ignore */
17138 				ip1dbg((
17139 				    "ip_rput_local_options: end of RR\n"));
17140 				break;
17141 			}
17142 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17143 			    IP_ADDR_LEN);
17144 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17145 			break;
17146 		case IPOPT_TS:
17147 			/* Insert timestamp if there is romm */
17148 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17149 			case IPOPT_TS_TSONLY:
17150 				off = IPOPT_TS_TIMELEN;
17151 				break;
17152 			case IPOPT_TS_PRESPEC:
17153 			case IPOPT_TS_PRESPEC_RFC791:
17154 				/* Verify that the address matched */
17155 				off = opt[IPOPT_OFFSET] - 1;
17156 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17157 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17158 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17159 				if (dst_ire == NULL) {
17160 					/* Not for us */
17161 					break;
17162 				}
17163 				ire_refrele(dst_ire);
17164 				/* FALLTHRU */
17165 			case IPOPT_TS_TSANDADDR:
17166 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17167 				break;
17168 			default:
17169 				/*
17170 				 * ip_*put_options should have already
17171 				 * dropped this packet.
17172 				 */
17173 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17174 				    "unknown IT - bug in ip_rput_options?\n");
17175 				return (B_TRUE);	/* Keep "lint" happy */
17176 			}
17177 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17178 				/* Increase overflow counter */
17179 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17180 				opt[IPOPT_POS_OV_FLG] =
17181 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17182 				    (off << 4));
17183 				break;
17184 			}
17185 			off = opt[IPOPT_OFFSET] - 1;
17186 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17187 			case IPOPT_TS_PRESPEC:
17188 			case IPOPT_TS_PRESPEC_RFC791:
17189 			case IPOPT_TS_TSANDADDR:
17190 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17191 				    IP_ADDR_LEN);
17192 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17193 				/* FALLTHRU */
17194 			case IPOPT_TS_TSONLY:
17195 				off = opt[IPOPT_OFFSET] - 1;
17196 				/* Compute # of milliseconds since midnight */
17197 				gethrestime(&now);
17198 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17199 				    now.tv_nsec / (NANOSEC / MILLISEC);
17200 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17201 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17202 				break;
17203 			}
17204 			break;
17205 		}
17206 	}
17207 	return (B_TRUE);
17208 
17209 bad_src_route:
17210 	q = WR(q);
17211 	/* make sure we clear any indication of a hardware checksum */
17212 	DB_CKSUMFLAGS(mp) = 0;
17213 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
17214 	return (B_FALSE);
17215 
17216 }
17217 
17218 /*
17219  * Process IP options in an inbound packet.  If an option affects the
17220  * effective destination address, return the next hop address via dstp.
17221  * Returns -1 if something fails in which case an ICMP error has been sent
17222  * and mp freed.
17223  */
17224 static int
17225 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17226 {
17227 	ipoptp_t	opts;
17228 	uchar_t		*opt;
17229 	uint8_t		optval;
17230 	uint8_t		optlen;
17231 	ipaddr_t	dst;
17232 	intptr_t	code = 0;
17233 	ire_t		*ire = NULL;
17234 
17235 	ip2dbg(("ip_rput_options\n"));
17236 	dst = ipha->ipha_dst;
17237 	for (optval = ipoptp_first(&opts, ipha);
17238 	    optval != IPOPT_EOL;
17239 	    optval = ipoptp_next(&opts)) {
17240 		opt = opts.ipoptp_cur;
17241 		optlen = opts.ipoptp_len;
17242 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17243 		    optval, optlen));
17244 		/*
17245 		 * Note: we need to verify the checksum before we
17246 		 * modify anything thus this routine only extracts the next
17247 		 * hop dst from any source route.
17248 		 */
17249 		switch (optval) {
17250 			uint32_t off;
17251 		case IPOPT_SSRR:
17252 		case IPOPT_LSRR:
17253 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17254 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17255 			if (ire == NULL) {
17256 				if (optval == IPOPT_SSRR) {
17257 					ip1dbg(("ip_rput_options: not next"
17258 					    " strict source route 0x%x\n",
17259 					    ntohl(dst)));
17260 					code = (char *)&ipha->ipha_dst -
17261 					    (char *)ipha;
17262 					goto param_prob; /* RouterReq's */
17263 				}
17264 				ip2dbg(("ip_rput_options: "
17265 				    "not next source route 0x%x\n",
17266 				    ntohl(dst)));
17267 				break;
17268 			}
17269 			ire_refrele(ire);
17270 
17271 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17272 				ip1dbg((
17273 				    "ip_rput_options: bad option offset\n"));
17274 				code = (char *)&opt[IPOPT_OLEN] -
17275 				    (char *)ipha;
17276 				goto param_prob;
17277 			}
17278 			off = opt[IPOPT_OFFSET];
17279 			off--;
17280 		redo_srr:
17281 			if (optlen < IP_ADDR_LEN ||
17282 			    off > optlen - IP_ADDR_LEN) {
17283 				/* End of source route */
17284 				ip1dbg(("ip_rput_options: end of SR\n"));
17285 				break;
17286 			}
17287 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17288 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17289 			    ntohl(dst)));
17290 
17291 			/*
17292 			 * Check if our address is present more than
17293 			 * once as consecutive hops in source route.
17294 			 * XXX verify per-interface ip_forwarding
17295 			 * for source route?
17296 			 */
17297 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17298 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17299 
17300 			if (ire != NULL) {
17301 				ire_refrele(ire);
17302 				off += IP_ADDR_LEN;
17303 				goto redo_srr;
17304 			}
17305 
17306 			if (dst == htonl(INADDR_LOOPBACK)) {
17307 				ip1dbg(("ip_rput_options: loopback addr in "
17308 				    "source route!\n"));
17309 				goto bad_src_route;
17310 			}
17311 			/*
17312 			 * For strict: verify that dst is directly
17313 			 * reachable.
17314 			 */
17315 			if (optval == IPOPT_SSRR) {
17316 				ire = ire_ftable_lookup(dst, 0, 0,
17317 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17318 				    MBLK_GETLABEL(mp),
17319 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17320 				if (ire == NULL) {
17321 					ip1dbg(("ip_rput_options: SSRR not "
17322 					    "directly reachable: 0x%x\n",
17323 					    ntohl(dst)));
17324 					goto bad_src_route;
17325 				}
17326 				ire_refrele(ire);
17327 			}
17328 			/*
17329 			 * Defer update of the offset and the record route
17330 			 * until the packet is forwarded.
17331 			 */
17332 			break;
17333 		case IPOPT_RR:
17334 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17335 				ip1dbg((
17336 				    "ip_rput_options: bad option offset\n"));
17337 				code = (char *)&opt[IPOPT_OLEN] -
17338 				    (char *)ipha;
17339 				goto param_prob;
17340 			}
17341 			break;
17342 		case IPOPT_TS:
17343 			/*
17344 			 * Verify that length >= 5 and that there is either
17345 			 * room for another timestamp or that the overflow
17346 			 * counter is not maxed out.
17347 			 */
17348 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17349 			if (optlen < IPOPT_MINLEN_IT) {
17350 				goto param_prob;
17351 			}
17352 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17353 				ip1dbg((
17354 				    "ip_rput_options: bad option offset\n"));
17355 				code = (char *)&opt[IPOPT_OFFSET] -
17356 				    (char *)ipha;
17357 				goto param_prob;
17358 			}
17359 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17360 			case IPOPT_TS_TSONLY:
17361 				off = IPOPT_TS_TIMELEN;
17362 				break;
17363 			case IPOPT_TS_TSANDADDR:
17364 			case IPOPT_TS_PRESPEC:
17365 			case IPOPT_TS_PRESPEC_RFC791:
17366 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17367 				break;
17368 			default:
17369 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17370 				    (char *)ipha;
17371 				goto param_prob;
17372 			}
17373 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17374 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17375 				/*
17376 				 * No room and the overflow counter is 15
17377 				 * already.
17378 				 */
17379 				goto param_prob;
17380 			}
17381 			break;
17382 		}
17383 	}
17384 
17385 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17386 		*dstp = dst;
17387 		return (0);
17388 	}
17389 
17390 	ip1dbg(("ip_rput_options: error processing IP options."));
17391 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17392 
17393 param_prob:
17394 	q = WR(q);
17395 	/* make sure we clear any indication of a hardware checksum */
17396 	DB_CKSUMFLAGS(mp) = 0;
17397 	icmp_param_problem(q, mp, (uint8_t)code);
17398 	return (-1);
17399 
17400 bad_src_route:
17401 	q = WR(q);
17402 	/* make sure we clear any indication of a hardware checksum */
17403 	DB_CKSUMFLAGS(mp) = 0;
17404 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
17405 	return (-1);
17406 }
17407 
17408 /*
17409  * IP & ICMP info in >=14 msg's ...
17410  *  - ip fixed part (mib2_ip_t)
17411  *  - icmp fixed part (mib2_icmp_t)
17412  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17413  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17414  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
17415  *  - ipRouteAttributeTable (ip 102)	labeled routes
17416  *  - ip multicast membership (ip_member_t)
17417  *  - ip multicast source filtering (ip_grpsrc_t)
17418  *  - igmp fixed part (struct igmpstat)
17419  *  - multicast routing stats (struct mrtstat)
17420  *  - multicast routing vifs (array of struct vifctl)
17421  *  - multicast routing routes (array of struct mfcctl)
17422  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17423  *					One per ill plus one generic
17424  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17425  *					One per ill plus one generic
17426  *  - ipv6RouteEntry			all IPv6 IREs
17427  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17428  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17429  *  - ipv6AddrEntry			all IPv6 ipifs
17430  *  - ipv6 multicast membership (ipv6_member_t)
17431  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17432  *
17433  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
17434  * already present.
17435  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17436  * already filled in by the caller.
17437  * Return value of 0 indicates that no messages were sent and caller
17438  * should free mpctl.
17439  */
17440 int
17441 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17442 {
17443 
17444 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17445 		return (0);
17446 	}
17447 
17448 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
17449 		return (1);
17450 	}
17451 
17452 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17453 		return (1);
17454 	}
17455 
17456 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17457 		return (1);
17458 	}
17459 
17460 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17461 		return (1);
17462 	}
17463 
17464 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17465 		return (1);
17466 	}
17467 
17468 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17469 		return (1);
17470 	}
17471 
17472 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17473 		return (1);
17474 	}
17475 
17476 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17477 		return (1);
17478 	}
17479 
17480 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17481 		return (1);
17482 	}
17483 
17484 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17485 		return (1);
17486 	}
17487 
17488 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17489 		return (1);
17490 	}
17491 
17492 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17493 		return (1);
17494 	}
17495 
17496 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17497 		return (1);
17498 	}
17499 
17500 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17501 		return (1);
17502 	}
17503 
17504 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17505 		return (1);
17506 	}
17507 
17508 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17509 		return (1);
17510 	}
17511 
17512 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17513 		return (1);
17514 	}
17515 	freemsg(mpctl);
17516 	return (1);
17517 }
17518 
17519 
17520 /* Get global IPv4 statistics */
17521 static mblk_t *
17522 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
17523 {
17524 	struct opthdr		*optp;
17525 	mblk_t			*mp2ctl;
17526 
17527 	/*
17528 	 * make a copy of the original message
17529 	 */
17530 	mp2ctl = copymsg(mpctl);
17531 
17532 	/* fixed length IP structure... */
17533 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17534 	optp->level = MIB2_IP;
17535 	optp->name = 0;
17536 	SET_MIB(ip_mib.ipForwarding,
17537 	    (WE_ARE_FORWARDING ? 1 : 2));
17538 	SET_MIB(ip_mib.ipDefaultTTL,
17539 	    (uint32_t)ip_def_ttl);
17540 	SET_MIB(ip_mib.ipReasmTimeout,
17541 	    ip_g_frag_timeout);
17542 	SET_MIB(ip_mib.ipAddrEntrySize,
17543 	    sizeof (mib2_ipAddrEntry_t));
17544 	SET_MIB(ip_mib.ipRouteEntrySize,
17545 	    sizeof (mib2_ipRouteEntry_t));
17546 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
17547 	    sizeof (mib2_ipNetToMediaEntry_t));
17548 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17549 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17550 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
17551 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17552 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
17553 	    (int)sizeof (ip_mib))) {
17554 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17555 		    (uint_t)sizeof (ip_mib)));
17556 	}
17557 
17558 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17559 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17560 	    (int)optp->level, (int)optp->name, (int)optp->len));
17561 	qreply(q, mpctl);
17562 	return (mp2ctl);
17563 }
17564 
17565 /* Global IPv4 ICMP statistics */
17566 static mblk_t *
17567 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
17568 {
17569 	struct opthdr		*optp;
17570 	mblk_t			*mp2ctl;
17571 
17572 	/*
17573 	 * Make a copy of the original message
17574 	 */
17575 	mp2ctl = copymsg(mpctl);
17576 
17577 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17578 	optp->level = MIB2_ICMP;
17579 	optp->name = 0;
17580 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17581 	    (int)sizeof (icmp_mib))) {
17582 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17583 		    (uint_t)sizeof (icmp_mib)));
17584 	}
17585 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17586 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17587 	    (int)optp->level, (int)optp->name, (int)optp->len));
17588 	qreply(q, mpctl);
17589 	return (mp2ctl);
17590 }
17591 
17592 /* Global IPv4 IGMP statistics */
17593 static mblk_t *
17594 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17595 {
17596 	struct opthdr		*optp;
17597 	mblk_t			*mp2ctl;
17598 
17599 	/*
17600 	 * make a copy of the original message
17601 	 */
17602 	mp2ctl = copymsg(mpctl);
17603 
17604 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17605 	optp->level = EXPER_IGMP;
17606 	optp->name = 0;
17607 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17608 	    (int)sizeof (igmpstat))) {
17609 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17610 		    (uint_t)sizeof (igmpstat)));
17611 	}
17612 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17613 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17614 	    (int)optp->level, (int)optp->name, (int)optp->len));
17615 	qreply(q, mpctl);
17616 	return (mp2ctl);
17617 }
17618 
17619 /* Global IPv4 Multicast Routing statistics */
17620 static mblk_t *
17621 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17622 {
17623 	struct opthdr		*optp;
17624 	mblk_t			*mp2ctl;
17625 
17626 	/*
17627 	 * make a copy of the original message
17628 	 */
17629 	mp2ctl = copymsg(mpctl);
17630 
17631 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17632 	optp->level = EXPER_DVMRP;
17633 	optp->name = 0;
17634 	if (!ip_mroute_stats(mpctl->b_cont)) {
17635 		ip0dbg(("ip_mroute_stats: failed\n"));
17636 	}
17637 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17638 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17639 	    (int)optp->level, (int)optp->name, (int)optp->len));
17640 	qreply(q, mpctl);
17641 	return (mp2ctl);
17642 }
17643 
17644 /* IPv4 address information */
17645 static mblk_t *
17646 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17647 {
17648 	struct opthdr		*optp;
17649 	mblk_t			*mp2ctl;
17650 	mblk_t			*mp_tail = NULL;
17651 	ill_t			*ill;
17652 	ipif_t			*ipif;
17653 	uint_t			bitval;
17654 	mib2_ipAddrEntry_t	mae;
17655 	zoneid_t		zoneid;
17656 	ill_walk_context_t ctx;
17657 
17658 	/*
17659 	 * make a copy of the original message
17660 	 */
17661 	mp2ctl = copymsg(mpctl);
17662 
17663 	/* ipAddrEntryTable */
17664 
17665 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17666 	optp->level = MIB2_IP;
17667 	optp->name = MIB2_IP_ADDR;
17668 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17669 
17670 	rw_enter(&ill_g_lock, RW_READER);
17671 	ill = ILL_START_WALK_V4(&ctx);
17672 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17673 		for (ipif = ill->ill_ipif; ipif != NULL;
17674 		    ipif = ipif->ipif_next) {
17675 			if (ipif->ipif_zoneid != zoneid &&
17676 			    ipif->ipif_zoneid != ALL_ZONES)
17677 				continue;
17678 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17679 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17680 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17681 
17682 			(void) ipif_get_name(ipif,
17683 			    mae.ipAdEntIfIndex.o_bytes,
17684 			    OCTET_LENGTH);
17685 			mae.ipAdEntIfIndex.o_length =
17686 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
17687 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
17688 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
17689 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
17690 			mae.ipAdEntInfo.ae_subnet_len =
17691 			    ip_mask_to_plen(ipif->ipif_net_mask);
17692 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
17693 			for (bitval = 1;
17694 			    bitval &&
17695 			    !(bitval & ipif->ipif_brd_addr);
17696 			    bitval <<= 1)
17697 				noop;
17698 			mae.ipAdEntBcastAddr = bitval;
17699 			mae.ipAdEntReasmMaxSize = 65535;
17700 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
17701 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
17702 			mae.ipAdEntInfo.ae_broadcast_addr =
17703 			    ipif->ipif_brd_addr;
17704 			mae.ipAdEntInfo.ae_pp_dst_addr =
17705 			    ipif->ipif_pp_dst_addr;
17706 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
17707 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17708 
17709 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17710 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
17711 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
17712 				    "allocate %u bytes\n",
17713 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
17714 			}
17715 		}
17716 	}
17717 	rw_exit(&ill_g_lock);
17718 
17719 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17720 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
17721 	    (int)optp->level, (int)optp->name, (int)optp->len));
17722 	qreply(q, mpctl);
17723 	return (mp2ctl);
17724 }
17725 
17726 /* IPv6 address information */
17727 static mblk_t *
17728 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
17729 {
17730 	struct opthdr		*optp;
17731 	mblk_t			*mp2ctl;
17732 	mblk_t			*mp_tail = NULL;
17733 	ill_t			*ill;
17734 	ipif_t			*ipif;
17735 	mib2_ipv6AddrEntry_t	mae6;
17736 	zoneid_t		zoneid;
17737 	ill_walk_context_t	ctx;
17738 
17739 	/*
17740 	 * make a copy of the original message
17741 	 */
17742 	mp2ctl = copymsg(mpctl);
17743 
17744 	/* ipv6AddrEntryTable */
17745 
17746 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17747 	optp->level = MIB2_IP6;
17748 	optp->name = MIB2_IP6_ADDR;
17749 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17750 
17751 	rw_enter(&ill_g_lock, RW_READER);
17752 	ill = ILL_START_WALK_V6(&ctx);
17753 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17754 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
17755 			if (ipif->ipif_zoneid != zoneid &&
17756 			    ipif->ipif_zoneid != ALL_ZONES)
17757 				continue;
17758 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17759 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17760 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17761 
17762 			(void) ipif_get_name(ipif,
17763 			    mae6.ipv6AddrIfIndex.o_bytes,
17764 			    OCTET_LENGTH);
17765 			mae6.ipv6AddrIfIndex.o_length =
17766 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
17767 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
17768 			mae6.ipv6AddrPfxLength =
17769 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
17770 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
17771 			mae6.ipv6AddrInfo.ae_subnet_len =
17772 			    mae6.ipv6AddrPfxLength;
17773 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
17774 
17775 			/* Type: stateless(1), stateful(2), unknown(3) */
17776 			if (ipif->ipif_flags & IPIF_ADDRCONF)
17777 				mae6.ipv6AddrType = 1;
17778 			else
17779 				mae6.ipv6AddrType = 2;
17780 			/* Anycast: true(1), false(2) */
17781 			if (ipif->ipif_flags & IPIF_ANYCAST)
17782 				mae6.ipv6AddrAnycastFlag = 1;
17783 			else
17784 				mae6.ipv6AddrAnycastFlag = 2;
17785 
17786 			/*
17787 			 * Address status: preferred(1), deprecated(2),
17788 			 * invalid(3), inaccessible(4), unknown(5)
17789 			 */
17790 			if (ipif->ipif_flags & IPIF_NOLOCAL)
17791 				mae6.ipv6AddrStatus = 3;
17792 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
17793 				mae6.ipv6AddrStatus = 2;
17794 			else
17795 				mae6.ipv6AddrStatus = 1;
17796 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
17797 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
17798 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
17799 						ipif->ipif_v6pp_dst_addr;
17800 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
17801 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17802 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17803 				(char *)&mae6,
17804 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
17805 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
17806 				    "allocate %u bytes\n",
17807 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
17808 			}
17809 		}
17810 	}
17811 	rw_exit(&ill_g_lock);
17812 
17813 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17814 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
17815 	    (int)optp->level, (int)optp->name, (int)optp->len));
17816 	qreply(q, mpctl);
17817 	return (mp2ctl);
17818 }
17819 
17820 /* IPv4 multicast group membership. */
17821 static mblk_t *
17822 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
17823 {
17824 	struct opthdr		*optp;
17825 	mblk_t			*mp2ctl;
17826 	ill_t			*ill;
17827 	ipif_t			*ipif;
17828 	ilm_t			*ilm;
17829 	ip_member_t		ipm;
17830 	mblk_t			*mp_tail = NULL;
17831 	ill_walk_context_t	ctx;
17832 	zoneid_t		zoneid;
17833 
17834 	/*
17835 	 * make a copy of the original message
17836 	 */
17837 	mp2ctl = copymsg(mpctl);
17838 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17839 
17840 	/* ipGroupMember table */
17841 	optp = (struct opthdr *)&mpctl->b_rptr[
17842 	    sizeof (struct T_optmgmt_ack)];
17843 	optp->level = MIB2_IP;
17844 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
17845 
17846 	rw_enter(&ill_g_lock, RW_READER);
17847 	ill = ILL_START_WALK_V4(&ctx);
17848 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17849 		ILM_WALKER_HOLD(ill);
17850 		for (ipif = ill->ill_ipif; ipif != NULL;
17851 		    ipif = ipif->ipif_next) {
17852 			if (ipif->ipif_zoneid != zoneid &&
17853 			    ipif->ipif_zoneid != ALL_ZONES)
17854 				continue;	/* not this zone */
17855 			(void) ipif_get_name(ipif,
17856 			    ipm.ipGroupMemberIfIndex.o_bytes,
17857 			    OCTET_LENGTH);
17858 			ipm.ipGroupMemberIfIndex.o_length =
17859 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
17860 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17861 				ASSERT(ilm->ilm_ipif != NULL);
17862 				ASSERT(ilm->ilm_ill == NULL);
17863 				if (ilm->ilm_ipif != ipif)
17864 					continue;
17865 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
17866 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
17867 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
17868 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17869 				    (char *)&ipm, (int)sizeof (ipm))) {
17870 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
17871 					    "failed to allocate %u bytes\n",
17872 						(uint_t)sizeof (ipm)));
17873 				}
17874 			}
17875 		}
17876 		ILM_WALKER_RELE(ill);
17877 	}
17878 	rw_exit(&ill_g_lock);
17879 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17880 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17881 	    (int)optp->level, (int)optp->name, (int)optp->len));
17882 	qreply(q, mpctl);
17883 	return (mp2ctl);
17884 }
17885 
17886 /* IPv6 multicast group membership. */
17887 static mblk_t *
17888 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
17889 {
17890 	struct opthdr		*optp;
17891 	mblk_t			*mp2ctl;
17892 	ill_t			*ill;
17893 	ilm_t			*ilm;
17894 	ipv6_member_t		ipm6;
17895 	mblk_t			*mp_tail = NULL;
17896 	ill_walk_context_t	ctx;
17897 	zoneid_t		zoneid;
17898 
17899 	/*
17900 	 * make a copy of the original message
17901 	 */
17902 	mp2ctl = copymsg(mpctl);
17903 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17904 
17905 	/* ip6GroupMember table */
17906 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17907 	optp->level = MIB2_IP6;
17908 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
17909 
17910 	rw_enter(&ill_g_lock, RW_READER);
17911 	ill = ILL_START_WALK_V6(&ctx);
17912 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17913 		ILM_WALKER_HOLD(ill);
17914 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
17915 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17916 			ASSERT(ilm->ilm_ipif == NULL);
17917 			ASSERT(ilm->ilm_ill != NULL);
17918 			if (ilm->ilm_zoneid != zoneid)
17919 				continue;	/* not this zone */
17920 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
17921 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
17922 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
17923 			if (!snmp_append_data2(mpctl->b_cont,
17924 			    &mp_tail,
17925 			    (char *)&ipm6, (int)sizeof (ipm6))) {
17926 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
17927 				    "failed to allocate %u bytes\n",
17928 				    (uint_t)sizeof (ipm6)));
17929 			}
17930 		}
17931 		ILM_WALKER_RELE(ill);
17932 	}
17933 	rw_exit(&ill_g_lock);
17934 
17935 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17936 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17937 	    (int)optp->level, (int)optp->name, (int)optp->len));
17938 	qreply(q, mpctl);
17939 	return (mp2ctl);
17940 }
17941 
17942 /* IP multicast filtered sources */
17943 static mblk_t *
17944 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
17945 {
17946 	struct opthdr		*optp;
17947 	mblk_t			*mp2ctl;
17948 	ill_t			*ill;
17949 	ipif_t			*ipif;
17950 	ilm_t			*ilm;
17951 	ip_grpsrc_t		ips;
17952 	mblk_t			*mp_tail = NULL;
17953 	ill_walk_context_t	ctx;
17954 	zoneid_t		zoneid;
17955 	int			i;
17956 	slist_t			*sl;
17957 
17958 	/*
17959 	 * make a copy of the original message
17960 	 */
17961 	mp2ctl = copymsg(mpctl);
17962 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17963 
17964 	/* ipGroupSource table */
17965 	optp = (struct opthdr *)&mpctl->b_rptr[
17966 	    sizeof (struct T_optmgmt_ack)];
17967 	optp->level = MIB2_IP;
17968 	optp->name = EXPER_IP_GROUP_SOURCES;
17969 
17970 	rw_enter(&ill_g_lock, RW_READER);
17971 	ill = ILL_START_WALK_V4(&ctx);
17972 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17973 		ILM_WALKER_HOLD(ill);
17974 		for (ipif = ill->ill_ipif; ipif != NULL;
17975 		    ipif = ipif->ipif_next) {
17976 			if (ipif->ipif_zoneid != zoneid)
17977 				continue;	/* not this zone */
17978 			(void) ipif_get_name(ipif,
17979 			    ips.ipGroupSourceIfIndex.o_bytes,
17980 			    OCTET_LENGTH);
17981 			ips.ipGroupSourceIfIndex.o_length =
17982 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
17983 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17984 				ASSERT(ilm->ilm_ipif != NULL);
17985 				ASSERT(ilm->ilm_ill == NULL);
17986 				sl = ilm->ilm_filter;
17987 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
17988 					continue;
17989 				ips.ipGroupSourceGroup = ilm->ilm_addr;
17990 				for (i = 0; i < sl->sl_numsrc; i++) {
17991 					if (!IN6_IS_ADDR_V4MAPPED(
17992 					    &sl->sl_addr[i]))
17993 						continue;
17994 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
17995 					    ips.ipGroupSourceAddress);
17996 					if (snmp_append_data2(mpctl->b_cont,
17997 					    &mp_tail, (char *)&ips,
17998 					    (int)sizeof (ips)) == 0) {
17999 						ip1dbg(("ip_snmp_get_mib2_"
18000 						    "ip_group_src: failed to "
18001 						    "allocate %u bytes\n",
18002 						    (uint_t)sizeof (ips)));
18003 					}
18004 				}
18005 			}
18006 		}
18007 		ILM_WALKER_RELE(ill);
18008 	}
18009 	rw_exit(&ill_g_lock);
18010 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18011 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18012 	    (int)optp->level, (int)optp->name, (int)optp->len));
18013 	qreply(q, mpctl);
18014 	return (mp2ctl);
18015 }
18016 
18017 /* IPv6 multicast filtered sources. */
18018 static mblk_t *
18019 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18020 {
18021 	struct opthdr		*optp;
18022 	mblk_t			*mp2ctl;
18023 	ill_t			*ill;
18024 	ilm_t			*ilm;
18025 	ipv6_grpsrc_t		ips6;
18026 	mblk_t			*mp_tail = NULL;
18027 	ill_walk_context_t	ctx;
18028 	zoneid_t		zoneid;
18029 	int			i;
18030 	slist_t			*sl;
18031 
18032 	/*
18033 	 * make a copy of the original message
18034 	 */
18035 	mp2ctl = copymsg(mpctl);
18036 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18037 
18038 	/* ip6GroupMember table */
18039 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18040 	optp->level = MIB2_IP6;
18041 	optp->name = EXPER_IP6_GROUP_SOURCES;
18042 
18043 	rw_enter(&ill_g_lock, RW_READER);
18044 	ill = ILL_START_WALK_V6(&ctx);
18045 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18046 		ILM_WALKER_HOLD(ill);
18047 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18048 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18049 			ASSERT(ilm->ilm_ipif == NULL);
18050 			ASSERT(ilm->ilm_ill != NULL);
18051 			sl = ilm->ilm_filter;
18052 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18053 				continue;
18054 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18055 			for (i = 0; i < sl->sl_numsrc; i++) {
18056 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18057 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18058 				    (char *)&ips6, (int)sizeof (ips6))) {
18059 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18060 					    "group_src: failed to allocate "
18061 					    "%u bytes\n",
18062 					    (uint_t)sizeof (ips6)));
18063 				}
18064 			}
18065 		}
18066 		ILM_WALKER_RELE(ill);
18067 	}
18068 	rw_exit(&ill_g_lock);
18069 
18070 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18071 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18072 	    (int)optp->level, (int)optp->name, (int)optp->len));
18073 	qreply(q, mpctl);
18074 	return (mp2ctl);
18075 }
18076 
18077 /* Multicast routing virtual interface table. */
18078 static mblk_t *
18079 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18080 {
18081 	struct opthdr		*optp;
18082 	mblk_t			*mp2ctl;
18083 
18084 	/*
18085 	 * make a copy of the original message
18086 	 */
18087 	mp2ctl = copymsg(mpctl);
18088 
18089 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18090 	optp->level = EXPER_DVMRP;
18091 	optp->name = EXPER_DVMRP_VIF;
18092 	if (!ip_mroute_vif(mpctl->b_cont)) {
18093 		ip0dbg(("ip_mroute_vif: failed\n"));
18094 	}
18095 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18096 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18097 	    (int)optp->level, (int)optp->name, (int)optp->len));
18098 	qreply(q, mpctl);
18099 	return (mp2ctl);
18100 }
18101 
18102 /* Multicast routing table. */
18103 static mblk_t *
18104 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18105 {
18106 	struct opthdr		*optp;
18107 	mblk_t			*mp2ctl;
18108 
18109 	/*
18110 	 * make a copy of the original message
18111 	 */
18112 	mp2ctl = copymsg(mpctl);
18113 
18114 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18115 	optp->level = EXPER_DVMRP;
18116 	optp->name = EXPER_DVMRP_MRT;
18117 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18118 		ip0dbg(("ip_mroute_mrt: failed\n"));
18119 	}
18120 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18121 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18122 	    (int)optp->level, (int)optp->name, (int)optp->len));
18123 	qreply(q, mpctl);
18124 	return (mp2ctl);
18125 }
18126 
18127 /*
18128  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18129  * in one IRE walk.
18130  */
18131 static mblk_t *
18132 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18133 {
18134 	struct opthdr	*optp;
18135 	mblk_t		*mp2ctl;	/* Returned */
18136 	mblk_t		*mp3ctl;	/* nettomedia */
18137 	mblk_t		*mp4ctl;	/* routeattrs */
18138 	iproutedata_t	ird;
18139 	zoneid_t	zoneid;
18140 
18141 	/*
18142 	 * make copies of the original message
18143 	 *	- mp2ctl is returned unchanged to the caller for his use
18144 	 *	- mpctl is sent upstream as ipRouteEntryTable
18145 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18146 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18147 	 */
18148 	mp2ctl = copymsg(mpctl);
18149 	mp3ctl = copymsg(mpctl);
18150 	mp4ctl = copymsg(mpctl);
18151 	if (mp3ctl == NULL || mp4ctl == NULL) {
18152 		freemsg(mp4ctl);
18153 		freemsg(mp3ctl);
18154 		freemsg(mp2ctl);
18155 		freemsg(mpctl);
18156 		return (NULL);
18157 	}
18158 
18159 	bzero(&ird, sizeof (ird));
18160 
18161 	ird.ird_route.lp_head = mpctl->b_cont;
18162 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18163 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18164 
18165 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18166 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18167 	if (zoneid == GLOBAL_ZONEID) {
18168 		/*
18169 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18170 		 * the sys_net_config privilege, it can only run in the global
18171 		 * zone, so we don't display these IREs in the other zones.
18172 		 */
18173 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18174 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18175 	}
18176 
18177 	/* ipRouteEntryTable in mpctl */
18178 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18179 	optp->level = MIB2_IP;
18180 	optp->name = MIB2_IP_ROUTE;
18181 	optp->len = msgdsize(ird.ird_route.lp_head);
18182 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18183 	    (int)optp->level, (int)optp->name, (int)optp->len));
18184 	qreply(q, mpctl);
18185 
18186 	/* ipNetToMediaEntryTable in mp3ctl */
18187 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18188 	optp->level = MIB2_IP;
18189 	optp->name = MIB2_IP_MEDIA;
18190 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18191 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18192 	    (int)optp->level, (int)optp->name, (int)optp->len));
18193 	qreply(q, mp3ctl);
18194 
18195 	/* ipRouteAttributeTable in mp4ctl */
18196 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18197 	optp->level = MIB2_IP;
18198 	optp->name = EXPER_IP_RTATTR;
18199 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18200 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18201 	    (int)optp->level, (int)optp->name, (int)optp->len));
18202 	if (optp->len == 0)
18203 		freemsg(mp4ctl);
18204 	else
18205 		qreply(q, mp4ctl);
18206 
18207 	return (mp2ctl);
18208 }
18209 
18210 /*
18211  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18212  * ipv6NetToMediaEntryTable in an NDP walk.
18213  */
18214 static mblk_t *
18215 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18216 {
18217 	struct opthdr	*optp;
18218 	mblk_t		*mp2ctl;	/* Returned */
18219 	mblk_t		*mp3ctl;	/* nettomedia */
18220 	mblk_t		*mp4ctl;	/* routeattrs */
18221 	iproutedata_t	ird;
18222 	zoneid_t	zoneid;
18223 
18224 	/*
18225 	 * make copies of the original message
18226 	 *	- mp2ctl is returned unchanged to the caller for his use
18227 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18228 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18229 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18230 	 */
18231 	mp2ctl = copymsg(mpctl);
18232 	mp3ctl = copymsg(mpctl);
18233 	mp4ctl = copymsg(mpctl);
18234 	if (mp3ctl == NULL || mp4ctl == NULL) {
18235 		freemsg(mp4ctl);
18236 		freemsg(mp3ctl);
18237 		freemsg(mp2ctl);
18238 		freemsg(mpctl);
18239 		return (NULL);
18240 	}
18241 
18242 	bzero(&ird, sizeof (ird));
18243 
18244 	ird.ird_route.lp_head = mpctl->b_cont;
18245 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18246 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18247 
18248 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18249 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18250 
18251 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18252 	optp->level = MIB2_IP6;
18253 	optp->name = MIB2_IP6_ROUTE;
18254 	optp->len = msgdsize(ird.ird_route.lp_head);
18255 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18256 	    (int)optp->level, (int)optp->name, (int)optp->len));
18257 	qreply(q, mpctl);
18258 
18259 	/* ipv6NetToMediaEntryTable in mp3ctl */
18260 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18261 
18262 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18263 	optp->level = MIB2_IP6;
18264 	optp->name = MIB2_IP6_MEDIA;
18265 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18266 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18267 	    (int)optp->level, (int)optp->name, (int)optp->len));
18268 	qreply(q, mp3ctl);
18269 
18270 	/* ipv6RouteAttributeTable in mp4ctl */
18271 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18272 	optp->level = MIB2_IP6;
18273 	optp->name = EXPER_IP_RTATTR;
18274 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18275 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18276 	    (int)optp->level, (int)optp->name, (int)optp->len));
18277 	if (optp->len == 0)
18278 		freemsg(mp4ctl);
18279 	else
18280 		qreply(q, mp4ctl);
18281 
18282 	return (mp2ctl);
18283 }
18284 
18285 /*
18286  * ICMPv6 mib: One per ill
18287  */
18288 static mblk_t *
18289 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18290 {
18291 	struct opthdr		*optp;
18292 	mblk_t			*mp2ctl;
18293 	ill_t			*ill;
18294 	ill_walk_context_t	ctx;
18295 	mblk_t			*mp_tail = NULL;
18296 
18297 	/*
18298 	 * Make a copy of the original message
18299 	 */
18300 	mp2ctl = copymsg(mpctl);
18301 
18302 	/* fixed length IPv6 structure ... */
18303 
18304 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18305 	optp->level = MIB2_IP6;
18306 	optp->name = 0;
18307 	/* Include "unknown interface" ip6_mib */
18308 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
18309 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
18310 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
18311 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
18312 	    sizeof (mib2_ipv6IfStatsEntry_t));
18313 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18314 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
18315 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
18316 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18317 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
18318 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18319 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18320 	    (int)sizeof (ip6_mib))) {
18321 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18322 		    (uint_t)sizeof (ip6_mib)));
18323 	}
18324 
18325 	rw_enter(&ill_g_lock, RW_READER);
18326 	ill = ILL_START_WALK_V6(&ctx);
18327 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18328 		ill->ill_ip6_mib->ipv6IfIndex =
18329 		    ill->ill_phyint->phyint_ifindex;
18330 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
18331 		    ipv6_forward ? 1 : 2);
18332 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
18333 		    ill->ill_max_hops);
18334 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
18335 		    sizeof (mib2_ipv6IfStatsEntry_t));
18336 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
18337 		    sizeof (mib2_ipv6AddrEntry_t));
18338 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
18339 		    sizeof (mib2_ipv6RouteEntry_t));
18340 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
18341 		    sizeof (mib2_ipv6NetToMediaEntry_t));
18342 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
18343 		    sizeof (ipv6_member_t));
18344 
18345 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18346 		    (char *)ill->ill_ip6_mib,
18347 		    (int)sizeof (*ill->ill_ip6_mib))) {
18348 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18349 				"%u bytes\n",
18350 				(uint_t)sizeof (*ill->ill_ip6_mib)));
18351 		}
18352 	}
18353 	rw_exit(&ill_g_lock);
18354 
18355 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18356 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18357 	    (int)optp->level, (int)optp->name, (int)optp->len));
18358 	qreply(q, mpctl);
18359 	return (mp2ctl);
18360 }
18361 
18362 /*
18363  * ICMPv6 mib: One per ill
18364  */
18365 static mblk_t *
18366 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18367 {
18368 	struct opthdr		*optp;
18369 	mblk_t			*mp2ctl;
18370 	ill_t			*ill;
18371 	ill_walk_context_t	ctx;
18372 	mblk_t			*mp_tail = NULL;
18373 	/*
18374 	 * Make a copy of the original message
18375 	 */
18376 	mp2ctl = copymsg(mpctl);
18377 
18378 	/* fixed length ICMPv6 structure ... */
18379 
18380 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18381 	optp->level = MIB2_ICMP6;
18382 	optp->name = 0;
18383 	/* Include "unknown interface" icmp6_mib */
18384 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
18385 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18386 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18387 	    (int)sizeof (icmp6_mib))) {
18388 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18389 		    (uint_t)sizeof (icmp6_mib)));
18390 	}
18391 
18392 	rw_enter(&ill_g_lock, RW_READER);
18393 	ill = ILL_START_WALK_V6(&ctx);
18394 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18395 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18396 		    ill->ill_phyint->phyint_ifindex;
18397 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
18398 		    sizeof (mib2_ipv6IfIcmpEntry_t);
18399 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18400 		    (char *)ill->ill_icmp6_mib,
18401 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18402 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18403 			    "%u bytes\n",
18404 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18405 		}
18406 	}
18407 	rw_exit(&ill_g_lock);
18408 
18409 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18410 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18411 	    (int)optp->level, (int)optp->name, (int)optp->len));
18412 	qreply(q, mpctl);
18413 	return (mp2ctl);
18414 }
18415 
18416 /*
18417  * ire_walk routine to create both ipRouteEntryTable and
18418  * ipNetToMediaEntryTable in one IRE walk
18419  */
18420 static void
18421 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18422 {
18423 	ill_t				*ill;
18424 	ipif_t				*ipif;
18425 	mblk_t				*llmp;
18426 	dl_unitdata_req_t		*dlup;
18427 	mib2_ipRouteEntry_t		*re;
18428 	mib2_ipNetToMediaEntry_t	ntme;
18429 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18430 	ipaddr_t			gw_addr;
18431 	tsol_ire_gw_secattr_t		*attrp;
18432 	tsol_gc_t			*gc = NULL;
18433 	tsol_gcgrp_t			*gcgrp = NULL;
18434 	uint_t				sacnt = 0;
18435 	int				i;
18436 
18437 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18438 
18439 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18440 		return;
18441 
18442 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18443 		mutex_enter(&attrp->igsa_lock);
18444 		if ((gc = attrp->igsa_gc) != NULL) {
18445 			gcgrp = gc->gc_grp;
18446 			ASSERT(gcgrp != NULL);
18447 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18448 			sacnt = 1;
18449 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18450 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18451 			gc = gcgrp->gcgrp_head;
18452 			sacnt = gcgrp->gcgrp_count;
18453 		}
18454 		mutex_exit(&attrp->igsa_lock);
18455 
18456 		/* do nothing if there's no gc to report */
18457 		if (gc == NULL) {
18458 			ASSERT(sacnt == 0);
18459 			if (gcgrp != NULL) {
18460 				/* we might as well drop the lock now */
18461 				rw_exit(&gcgrp->gcgrp_rwlock);
18462 				gcgrp = NULL;
18463 			}
18464 			attrp = NULL;
18465 		}
18466 
18467 		ASSERT(gc == NULL || (gcgrp != NULL &&
18468 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18469 	}
18470 	ASSERT(sacnt == 0 || gc != NULL);
18471 
18472 	if (sacnt != 0 &&
18473 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18474 		kmem_free(re, sizeof (*re));
18475 		rw_exit(&gcgrp->gcgrp_rwlock);
18476 		return;
18477 	}
18478 
18479 	/*
18480 	 * Return all IRE types for route table... let caller pick and choose
18481 	 */
18482 	re->ipRouteDest = ire->ire_addr;
18483 	ipif = ire->ire_ipif;
18484 	re->ipRouteIfIndex.o_length = 0;
18485 	if (ire->ire_type == IRE_CACHE) {
18486 		ill = (ill_t *)ire->ire_stq->q_ptr;
18487 		re->ipRouteIfIndex.o_length =
18488 		    ill->ill_name_length == 0 ? 0 :
18489 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18490 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18491 		    re->ipRouteIfIndex.o_length);
18492 	} else if (ipif != NULL) {
18493 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18494 		    OCTET_LENGTH);
18495 		re->ipRouteIfIndex.o_length =
18496 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18497 	}
18498 	re->ipRouteMetric1 = -1;
18499 	re->ipRouteMetric2 = -1;
18500 	re->ipRouteMetric3 = -1;
18501 	re->ipRouteMetric4 = -1;
18502 
18503 	gw_addr = ire->ire_gateway_addr;
18504 
18505 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18506 		re->ipRouteNextHop = ire->ire_src_addr;
18507 	else
18508 		re->ipRouteNextHop = gw_addr;
18509 	/* indirect(4), direct(3), or invalid(2) */
18510 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18511 		re->ipRouteType = 2;
18512 	else
18513 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18514 	re->ipRouteProto = -1;
18515 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18516 	re->ipRouteMask = ire->ire_mask;
18517 	re->ipRouteMetric5 = -1;
18518 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
18519 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
18520 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
18521 	if (ire->ire_nce &&
18522 	    ire->ire_nce->nce_state == ND_REACHABLE)
18523 		llmp = ire->ire_nce->nce_res_mp;
18524 	else
18525 		llmp = NULL;
18526 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
18527 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
18528 	re->ipRouteInfo.re_ire_type	= ire->ire_type;
18529 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18530 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18531 	re->ipRouteInfo.re_flags	= ire->ire_flags;
18532 	re->ipRouteInfo.re_in_ill.o_length = 0;
18533 	if (ire->ire_in_ill != NULL) {
18534 		re->ipRouteInfo.re_in_ill.o_length =
18535 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
18536 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
18537 		bcopy(ire->ire_in_ill->ill_name,
18538 		    re->ipRouteInfo.re_in_ill.o_bytes,
18539 		    re->ipRouteInfo.re_in_ill.o_length);
18540 	}
18541 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
18542 
18543 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18544 	    (char *)re, (int)sizeof (*re))) {
18545 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18546 		    (uint_t)sizeof (*re)));
18547 	}
18548 
18549 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18550 		iaeptr->iae_routeidx = ird->ird_idx;
18551 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18552 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18553 	}
18554 
18555 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18556 	    (char *)iae, sacnt * sizeof (*iae))) {
18557 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18558 		    (unsigned)(sacnt * sizeof (*iae))));
18559 	}
18560 
18561 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
18562 		goto done;
18563 	/*
18564 	 * only IRE_CACHE entries that are for a directly connected subnet
18565 	 * get appended to net -> phys addr table
18566 	 * (others in arp)
18567 	 */
18568 	ntme.ipNetToMediaIfIndex.o_length = 0;
18569 	ill = ire_to_ill(ire);
18570 	ASSERT(ill != NULL);
18571 	ntme.ipNetToMediaIfIndex.o_length =
18572 	    ill->ill_name_length == 0 ? 0 :
18573 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18574 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
18575 		    ntme.ipNetToMediaIfIndex.o_length);
18576 
18577 	ntme.ipNetToMediaPhysAddress.o_length = 0;
18578 	if (llmp) {
18579 		uchar_t *addr;
18580 
18581 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
18582 		/* Remove sap from  address */
18583 		if (ill->ill_sap_length < 0)
18584 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
18585 		else
18586 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
18587 			    ill->ill_sap_length;
18588 
18589 		ntme.ipNetToMediaPhysAddress.o_length =
18590 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18591 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18592 		    ntme.ipNetToMediaPhysAddress.o_length);
18593 	}
18594 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18595 	/* assume dynamic (may be changed in arp) */
18596 	ntme.ipNetToMediaType = 3;
18597 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18598 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18599 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18600 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18601 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18602 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18603 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18604 		    (uint_t)sizeof (ntme)));
18605 	}
18606 done:
18607 	/* bump route index for next pass */
18608 	ird->ird_idx++;
18609 
18610 	kmem_free(re, sizeof (*re));
18611 	if (sacnt != 0)
18612 		kmem_free(iae, sacnt * sizeof (*iae));
18613 
18614 	if (gcgrp != NULL)
18615 		rw_exit(&gcgrp->gcgrp_rwlock);
18616 }
18617 
18618 /*
18619  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18620  */
18621 static void
18622 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18623 {
18624 	ill_t				*ill;
18625 	ipif_t				*ipif;
18626 	mib2_ipv6RouteEntry_t		*re;
18627 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18628 	in6_addr_t			gw_addr_v6;
18629 	tsol_ire_gw_secattr_t		*attrp;
18630 	tsol_gc_t			*gc = NULL;
18631 	tsol_gcgrp_t			*gcgrp = NULL;
18632 	uint_t				sacnt = 0;
18633 	int				i;
18634 
18635 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18636 
18637 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18638 		return;
18639 
18640 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18641 		mutex_enter(&attrp->igsa_lock);
18642 		if ((gc = attrp->igsa_gc) != NULL) {
18643 			gcgrp = gc->gc_grp;
18644 			ASSERT(gcgrp != NULL);
18645 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18646 			sacnt = 1;
18647 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18648 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18649 			gc = gcgrp->gcgrp_head;
18650 			sacnt = gcgrp->gcgrp_count;
18651 		}
18652 		mutex_exit(&attrp->igsa_lock);
18653 
18654 		/* do nothing if there's no gc to report */
18655 		if (gc == NULL) {
18656 			ASSERT(sacnt == 0);
18657 			if (gcgrp != NULL) {
18658 				/* we might as well drop the lock now */
18659 				rw_exit(&gcgrp->gcgrp_rwlock);
18660 				gcgrp = NULL;
18661 			}
18662 			attrp = NULL;
18663 		}
18664 
18665 		ASSERT(gc == NULL || (gcgrp != NULL &&
18666 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18667 	}
18668 	ASSERT(sacnt == 0 || gc != NULL);
18669 
18670 	if (sacnt != 0 &&
18671 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18672 		kmem_free(re, sizeof (*re));
18673 		rw_exit(&gcgrp->gcgrp_rwlock);
18674 		return;
18675 	}
18676 
18677 	/*
18678 	 * Return all IRE types for route table... let caller pick and choose
18679 	 */
18680 	re->ipv6RouteDest = ire->ire_addr_v6;
18681 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18682 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18683 	re->ipv6RouteIfIndex.o_length = 0;
18684 	ipif = ire->ire_ipif;
18685 	if (ire->ire_type == IRE_CACHE) {
18686 		ill = (ill_t *)ire->ire_stq->q_ptr;
18687 		re->ipv6RouteIfIndex.o_length =
18688 		    ill->ill_name_length == 0 ? 0 :
18689 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18690 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
18691 		    re->ipv6RouteIfIndex.o_length);
18692 	} else if (ipif != NULL) {
18693 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
18694 		    OCTET_LENGTH);
18695 		re->ipv6RouteIfIndex.o_length =
18696 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
18697 	}
18698 
18699 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18700 
18701 	mutex_enter(&ire->ire_lock);
18702 	gw_addr_v6 = ire->ire_gateway_addr_v6;
18703 	mutex_exit(&ire->ire_lock);
18704 
18705 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
18706 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
18707 	else
18708 		re->ipv6RouteNextHop = gw_addr_v6;
18709 
18710 	/* remote(4), local(3), or discard(2) */
18711 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18712 		re->ipv6RouteType = 2;
18713 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
18714 		re->ipv6RouteType = 3;
18715 	else
18716 		re->ipv6RouteType = 4;
18717 
18718 	re->ipv6RouteProtocol	= -1;
18719 	re->ipv6RoutePolicy	= 0;
18720 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
18721 	re->ipv6RouteNextHopRDI	= 0;
18722 	re->ipv6RouteWeight	= 0;
18723 	re->ipv6RouteMetric	= 0;
18724 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
18725 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
18726 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
18727 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
18728 	re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
18729 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18730 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18731 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
18732 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
18733 
18734 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18735 	    (char *)re, (int)sizeof (*re))) {
18736 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18737 		    (uint_t)sizeof (*re)));
18738 	}
18739 
18740 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18741 		iaeptr->iae_routeidx = ird->ird_idx;
18742 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18743 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18744 	}
18745 
18746 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18747 	    (char *)iae, sacnt * sizeof (*iae))) {
18748 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18749 		    (unsigned)(sacnt * sizeof (*iae))));
18750 	}
18751 
18752 	/* bump route index for next pass */
18753 	ird->ird_idx++;
18754 
18755 	kmem_free(re, sizeof (*re));
18756 	if (sacnt != 0)
18757 		kmem_free(iae, sacnt * sizeof (*iae));
18758 
18759 	if (gcgrp != NULL)
18760 		rw_exit(&gcgrp->gcgrp_rwlock);
18761 }
18762 
18763 /*
18764  * ndp_walk routine to create ipv6NetToMediaEntryTable
18765  */
18766 static int
18767 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
18768 {
18769 	ill_t				*ill;
18770 	mib2_ipv6NetToMediaEntry_t	ntme;
18771 	dl_unitdata_req_t		*dl;
18772 
18773 	ill = nce->nce_ill;
18774 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
18775 		return (0);
18776 
18777 	/*
18778 	 * Neighbor cache entry attached to IRE with on-link
18779 	 * destination.
18780 	 */
18781 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
18782 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
18783 	if ((ill->ill_flags & ILLF_XRESOLV) &&
18784 	    (nce->nce_res_mp != NULL)) {
18785 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
18786 		ntme.ipv6NetToMediaPhysAddress.o_length =
18787 		    dl->dl_dest_addr_length;
18788 	} else {
18789 		ntme.ipv6NetToMediaPhysAddress.o_length =
18790 		    ill->ill_phys_addr_length;
18791 	}
18792 	if (nce->nce_res_mp != NULL) {
18793 		bcopy((char *)nce->nce_res_mp->b_rptr +
18794 		    NCE_LL_ADDR_OFFSET(ill),
18795 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
18796 		    ntme.ipv6NetToMediaPhysAddress.o_length);
18797 	} else {
18798 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
18799 		    ill->ill_phys_addr_length);
18800 	}
18801 	/*
18802 	 * Note: Returns ND_* states. Should be:
18803 	 * reachable(1), stale(2), delay(3), probe(4),
18804 	 * invalid(5), unknown(6)
18805 	 */
18806 	ntme.ipv6NetToMediaState = nce->nce_state;
18807 	ntme.ipv6NetToMediaLastUpdated = 0;
18808 
18809 	/* other(1), dynamic(2), static(3), local(4) */
18810 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
18811 		ntme.ipv6NetToMediaType = 4;
18812 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
18813 		ntme.ipv6NetToMediaType = 1;
18814 	} else {
18815 		ntme.ipv6NetToMediaType = 2;
18816 	}
18817 
18818 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18819 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18820 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
18821 		    (uint_t)sizeof (ntme)));
18822 	}
18823 	return (0);
18824 }
18825 
18826 /*
18827  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
18828  */
18829 /* ARGSUSED */
18830 int
18831 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
18832 {
18833 	switch (level) {
18834 	case MIB2_IP:
18835 	case MIB2_ICMP:
18836 		switch (name) {
18837 		default:
18838 			break;
18839 		}
18840 		return (1);
18841 	default:
18842 		return (1);
18843 	}
18844 }
18845 
18846 /*
18847  * Called before the options are updated to check if this packet will
18848  * be source routed from here.
18849  * This routine assumes that the options are well formed i.e. that they
18850  * have already been checked.
18851  */
18852 static boolean_t
18853 ip_source_routed(ipha_t *ipha)
18854 {
18855 	ipoptp_t	opts;
18856 	uchar_t		*opt;
18857 	uint8_t		optval;
18858 	uint8_t		optlen;
18859 	ipaddr_t	dst;
18860 	ire_t		*ire;
18861 
18862 	if (IS_SIMPLE_IPH(ipha)) {
18863 		ip2dbg(("not source routed\n"));
18864 		return (B_FALSE);
18865 	}
18866 	dst = ipha->ipha_dst;
18867 	for (optval = ipoptp_first(&opts, ipha);
18868 	    optval != IPOPT_EOL;
18869 	    optval = ipoptp_next(&opts)) {
18870 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18871 		opt = opts.ipoptp_cur;
18872 		optlen = opts.ipoptp_len;
18873 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
18874 		    optval, optlen));
18875 		switch (optval) {
18876 			uint32_t off;
18877 		case IPOPT_SSRR:
18878 		case IPOPT_LSRR:
18879 			/*
18880 			 * If dst is one of our addresses and there are some
18881 			 * entries left in the source route return (true).
18882 			 */
18883 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18884 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
18885 			if (ire == NULL) {
18886 				ip2dbg(("ip_source_routed: not next"
18887 				    " source route 0x%x\n",
18888 				    ntohl(dst)));
18889 				return (B_FALSE);
18890 			}
18891 			ire_refrele(ire);
18892 			off = opt[IPOPT_OFFSET];
18893 			off--;
18894 			if (optlen < IP_ADDR_LEN ||
18895 			    off > optlen - IP_ADDR_LEN) {
18896 				/* End of source route */
18897 				ip1dbg(("ip_source_routed: end of SR\n"));
18898 				return (B_FALSE);
18899 			}
18900 			return (B_TRUE);
18901 		}
18902 	}
18903 	ip2dbg(("not source routed\n"));
18904 	return (B_FALSE);
18905 }
18906 
18907 /*
18908  * Check if the packet contains any source route.
18909  */
18910 static boolean_t
18911 ip_source_route_included(ipha_t *ipha)
18912 {
18913 	ipoptp_t	opts;
18914 	uint8_t		optval;
18915 
18916 	if (IS_SIMPLE_IPH(ipha))
18917 		return (B_FALSE);
18918 	for (optval = ipoptp_first(&opts, ipha);
18919 	    optval != IPOPT_EOL;
18920 	    optval = ipoptp_next(&opts)) {
18921 		switch (optval) {
18922 		case IPOPT_SSRR:
18923 		case IPOPT_LSRR:
18924 			return (B_TRUE);
18925 		}
18926 	}
18927 	return (B_FALSE);
18928 }
18929 
18930 /*
18931  * Called when the IRE expiration timer fires.
18932  */
18933 /* ARGSUSED */
18934 void
18935 ip_trash_timer_expire(void *args)
18936 {
18937 	int	flush_flag = 0;
18938 
18939 	/*
18940 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
18941 	 * This lock makes sure that a new invocation of this function
18942 	 * that occurs due to an almost immediate timer firing will not
18943 	 * progress beyond this point until the current invocation is done
18944 	 */
18945 	mutex_enter(&ip_trash_timer_lock);
18946 	ip_ire_expire_id = 0;
18947 	mutex_exit(&ip_trash_timer_lock);
18948 
18949 	/* Periodic timer */
18950 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
18951 		/*
18952 		 * Remove all IRE_CACHE entries since they might
18953 		 * contain arp information.
18954 		 */
18955 		flush_flag |= FLUSH_ARP_TIME;
18956 		ip_ire_arp_time_elapsed = 0;
18957 		IP_STAT(ip_ire_arp_timer_expired);
18958 	}
18959 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
18960 		/* Remove all redirects */
18961 		flush_flag |= FLUSH_REDIRECT_TIME;
18962 		ip_ire_rd_time_elapsed = 0;
18963 		IP_STAT(ip_ire_redirect_timer_expired);
18964 	}
18965 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
18966 		/* Increase path mtu */
18967 		flush_flag |= FLUSH_MTU_TIME;
18968 		ip_ire_pmtu_time_elapsed = 0;
18969 		IP_STAT(ip_ire_pmtu_timer_expired);
18970 	}
18971 
18972 	/*
18973 	 * Optimize for the case when there are no redirects in the
18974 	 * ftable, that is, no need to walk the ftable in that case.
18975 	 */
18976 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
18977 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
18978 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
18979 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
18980 	}
18981 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
18982 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
18983 		    ire_expire, (char *)(uintptr_t)flush_flag,
18984 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
18985 	}
18986 	if (flush_flag & FLUSH_MTU_TIME) {
18987 		/*
18988 		 * Walk all IPv6 IRE's and update them
18989 		 * Note that ARP and redirect timers are not
18990 		 * needed since NUD handles stale entries.
18991 		 */
18992 		flush_flag = FLUSH_MTU_TIME;
18993 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
18994 		    ALL_ZONES);
18995 	}
18996 
18997 	ip_ire_arp_time_elapsed += ip_timer_interval;
18998 	ip_ire_rd_time_elapsed += ip_timer_interval;
18999 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19000 
19001 	/*
19002 	 * Hold the lock to serialize timeout calls and prevent
19003 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19004 	 * for the timer to fire and a new invocation of this function
19005 	 * to start before the return value of timeout has been stored
19006 	 * in ip_ire_expire_id by the current invocation.
19007 	 */
19008 	mutex_enter(&ip_trash_timer_lock);
19009 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19010 	    MSEC_TO_TICK(ip_timer_interval));
19011 	mutex_exit(&ip_trash_timer_lock);
19012 }
19013 
19014 /*
19015  * Called by the memory allocator subsystem directly, when the system
19016  * is running low on memory.
19017  */
19018 /* ARGSUSED */
19019 void
19020 ip_trash_ire_reclaim(void *args)
19021 {
19022 	ire_cache_count_t icc;
19023 	ire_cache_reclaim_t icr;
19024 	ncc_cache_count_t ncc;
19025 	nce_cache_reclaim_t ncr;
19026 	uint_t delete_cnt;
19027 	/*
19028 	 * Memory reclaim call back.
19029 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19030 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19031 	 * entries, determine what fraction to free for
19032 	 * each category of IRE_CACHE entries giving absolute priority
19033 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19034 	 * entry will be freed unless all offlink entries are freed).
19035 	 */
19036 	icc.icc_total = 0;
19037 	icc.icc_unused = 0;
19038 	icc.icc_offlink = 0;
19039 	icc.icc_pmtu = 0;
19040 	icc.icc_onlink = 0;
19041 	ire_walk(ire_cache_count, (char *)&icc);
19042 
19043 	/*
19044 	 * Free NCEs for IPv6 like the onlink ires.
19045 	 */
19046 	ncc.ncc_total = 0;
19047 	ncc.ncc_host = 0;
19048 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19049 
19050 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19051 	    icc.icc_pmtu + icc.icc_onlink);
19052 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19053 	IP_STAT(ip_trash_ire_reclaim_calls);
19054 	if (delete_cnt == 0)
19055 		return;
19056 	IP_STAT(ip_trash_ire_reclaim_success);
19057 	/* Always delete all unused offlink entries */
19058 	icr.icr_unused = 1;
19059 	if (delete_cnt <= icc.icc_unused) {
19060 		/*
19061 		 * Only need to free unused entries.  In other words,
19062 		 * there are enough unused entries to free to meet our
19063 		 * target number of freed ire cache entries.
19064 		 */
19065 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19066 		ncr.ncr_host = 0;
19067 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19068 		/*
19069 		 * Only need to free unused entries, plus a fraction of offlink
19070 		 * entries.  It follows from the first if statement that
19071 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19072 		 */
19073 		delete_cnt -= icc.icc_unused;
19074 		/* Round up # deleted by truncating fraction */
19075 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19076 		icr.icr_pmtu = icr.icr_onlink = 0;
19077 		ncr.ncr_host = 0;
19078 	} else if (delete_cnt <=
19079 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19080 		/*
19081 		 * Free all unused and offlink entries, plus a fraction of
19082 		 * pmtu entries.  It follows from the previous if statement
19083 		 * that icc_pmtu is non-zero, and that
19084 		 * delete_cnt != icc_unused + icc_offlink.
19085 		 */
19086 		icr.icr_offlink = 1;
19087 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19088 		/* Round up # deleted by truncating fraction */
19089 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19090 		icr.icr_onlink = 0;
19091 		ncr.ncr_host = 0;
19092 	} else {
19093 		/*
19094 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19095 		 * of onlink entries.  If we're here, then we know that
19096 		 * icc_onlink is non-zero, and that
19097 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19098 		 */
19099 		icr.icr_offlink = icr.icr_pmtu = 1;
19100 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19101 		    icc.icc_pmtu;
19102 		/* Round up # deleted by truncating fraction */
19103 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19104 		/* Using the same delete fraction as for onlink IREs */
19105 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19106 	}
19107 #ifdef DEBUG
19108 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19109 	    "fractions %d/%d/%d/%d\n",
19110 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19111 	    icc.icc_unused, icc.icc_offlink,
19112 	    icc.icc_pmtu, icc.icc_onlink,
19113 	    icr.icr_unused, icr.icr_offlink,
19114 	    icr.icr_pmtu, icr.icr_onlink));
19115 #endif
19116 	ire_walk(ire_cache_reclaim, (char *)&icr);
19117 	if (ncr.ncr_host != 0)
19118 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19119 		    (uchar_t *)&ncr);
19120 #ifdef DEBUG
19121 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19122 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19123 	ire_walk(ire_cache_count, (char *)&icc);
19124 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19125 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19126 	    icc.icc_pmtu, icc.icc_onlink));
19127 #endif
19128 }
19129 
19130 /*
19131  * ip_unbind is called when a copy of an unbind request is received from the
19132  * upper level protocol.  We remove this conn from any fanout hash list it is
19133  * on, and zero out the bind information.  No reply is expected up above.
19134  */
19135 mblk_t *
19136 ip_unbind(queue_t *q, mblk_t *mp)
19137 {
19138 	conn_t	*connp = Q_TO_CONN(q);
19139 
19140 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19141 
19142 	if (is_system_labeled() && connp->conn_anon_port) {
19143 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19144 		    connp->conn_mlp_type, connp->conn_ulp,
19145 		    ntohs(connp->conn_lport), B_FALSE);
19146 		connp->conn_anon_port = 0;
19147 	}
19148 	connp->conn_mlp_type = mlptSingle;
19149 
19150 	ipcl_hash_remove(connp);
19151 
19152 	ASSERT(mp->b_cont == NULL);
19153 	/*
19154 	 * Convert mp into a T_OK_ACK
19155 	 */
19156 	mp = mi_tpi_ok_ack_alloc(mp);
19157 
19158 	/*
19159 	 * should not happen in practice... T_OK_ACK is smaller than the
19160 	 * original message.
19161 	 */
19162 	if (mp == NULL)
19163 		return (NULL);
19164 
19165 	/*
19166 	 * Don't bzero the ports if its TCP since TCP still needs the
19167 	 * lport to remove it from its own bind hash. TCP will do the
19168 	 * cleanup.
19169 	 */
19170 	if (!IPCL_IS_TCP(connp))
19171 		bzero(&connp->u_port, sizeof (connp->u_port));
19172 
19173 	return (mp);
19174 }
19175 
19176 /*
19177  * Write side put procedure.  Outbound data, IOCTLs, responses from
19178  * resolvers, etc, come down through here.
19179  */
19180 void
19181 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19182 {
19183 	conn_t		*connp = NULL;
19184 	queue_t		*q = (queue_t *)arg2;
19185 	ipha_t		*ipha;
19186 #define	rptr	((uchar_t *)ipha)
19187 	ire_t		*ire = NULL;
19188 	ire_t		*sctp_ire = NULL;
19189 	uint32_t	v_hlen_tos_len;
19190 	ipaddr_t	dst;
19191 	mblk_t		*first_mp = NULL;
19192 	boolean_t	mctl_present;
19193 	ipsec_out_t	*io;
19194 	int		match_flags;
19195 	ill_t		*attach_ill = NULL;
19196 					/* Bind to IPIF_NOFAILOVER ill etc. */
19197 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19198 	ipif_t		*dst_ipif;
19199 	boolean_t	multirt_need_resolve = B_FALSE;
19200 	mblk_t		*copy_mp = NULL;
19201 	int		err;
19202 	zoneid_t	zoneid;
19203 	int	adjust;
19204 	uint16_t iplen;
19205 	boolean_t	need_decref = B_FALSE;
19206 	boolean_t	ignore_dontroute = B_FALSE;
19207 	boolean_t	ignore_nexthop = B_FALSE;
19208 	boolean_t	ip_nexthop = B_FALSE;
19209 	ipaddr_t	nexthop_addr;
19210 
19211 #ifdef	_BIG_ENDIAN
19212 #define	V_HLEN	(v_hlen_tos_len >> 24)
19213 #else
19214 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19215 #endif
19216 
19217 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19218 	    "ip_wput_start: q %p", q);
19219 
19220 	/*
19221 	 * ip_wput fast path
19222 	 */
19223 
19224 	/* is packet from ARP ? */
19225 	if (q->q_next != NULL)
19226 		goto qnext;
19227 
19228 	connp = (conn_t *)arg;
19229 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
19230 
19231 	/* is queue flow controlled? */
19232 	if ((q->q_first != NULL || connp->conn_draining) &&
19233 	    (caller == IP_WPUT)) {
19234 		ASSERT(!need_decref);
19235 		(void) putq(q, mp);
19236 		return;
19237 	}
19238 
19239 	/* Multidata transmit? */
19240 	if (DB_TYPE(mp) == M_MULTIDATA) {
19241 		/*
19242 		 * We should never get here, since all Multidata messages
19243 		 * originating from tcp should have been directed over to
19244 		 * tcp_multisend() in the first place.
19245 		 */
19246 		BUMP_MIB(&ip_mib, ipOutDiscards);
19247 		freemsg(mp);
19248 		return;
19249 	} else if (DB_TYPE(mp) != M_DATA)
19250 		goto notdata;
19251 
19252 	if (mp->b_flag & MSGHASREF) {
19253 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19254 		mp->b_flag &= ~MSGHASREF;
19255 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19256 		need_decref = B_TRUE;
19257 	}
19258 	ipha = (ipha_t *)mp->b_rptr;
19259 
19260 	/* is IP header non-aligned or mblk smaller than basic IP header */
19261 #ifndef SAFETY_BEFORE_SPEED
19262 	if (!OK_32PTR(rptr) ||
19263 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19264 		goto hdrtoosmall;
19265 #endif
19266 
19267 	ASSERT(OK_32PTR(ipha));
19268 
19269 	/*
19270 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19271 	 * wrong version, we'll catch it again in ip_output_v6.
19272 	 *
19273 	 * Note that this is *only* locally-generated output here, and never
19274 	 * forwarded data, and that we need to deal only with transports that
19275 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19276 	 * label.)
19277 	 */
19278 	if (is_system_labeled() &&
19279 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19280 	    !connp->conn_ulp_labeled) {
19281 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19282 		    connp->conn_mac_exempt);
19283 		ipha = (ipha_t *)mp->b_rptr;
19284 		if (err != 0) {
19285 			first_mp = mp;
19286 			if (err == EINVAL)
19287 				goto icmp_parameter_problem;
19288 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19289 			goto drop_pkt;
19290 		}
19291 		iplen = ntohs(ipha->ipha_length) + adjust;
19292 		ipha->ipha_length = htons(iplen);
19293 	}
19294 
19295 	/*
19296 	 * If there is a policy, try to attach an ipsec_out in
19297 	 * the front. At the end, first_mp either points to a
19298 	 * M_DATA message or IPSEC_OUT message linked to a
19299 	 * M_DATA message. We have to do it now as we might
19300 	 * lose the "conn" if we go through ip_newroute.
19301 	 */
19302 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19303 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
19304 		    ipha->ipha_protocol)) == NULL)) {
19305 			if (need_decref)
19306 				CONN_DEC_REF(connp);
19307 			return;
19308 		} else {
19309 			ASSERT(mp->b_datap->db_type == M_CTL);
19310 			first_mp = mp;
19311 			mp = mp->b_cont;
19312 			mctl_present = B_TRUE;
19313 		}
19314 	} else {
19315 		first_mp = mp;
19316 		mctl_present = B_FALSE;
19317 	}
19318 
19319 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19320 
19321 	/* is wrong version or IP options present */
19322 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19323 		goto version_hdrlen_check;
19324 	dst = ipha->ipha_dst;
19325 
19326 	if (connp->conn_nofailover_ill != NULL) {
19327 		attach_ill = conn_get_held_ill(connp,
19328 		    &connp->conn_nofailover_ill, &err);
19329 		if (err == ILL_LOOKUP_FAILED) {
19330 			if (need_decref)
19331 				CONN_DEC_REF(connp);
19332 			freemsg(first_mp);
19333 			return;
19334 		}
19335 	}
19336 
19337 	/* is packet multicast? */
19338 	if (CLASSD(dst))
19339 		goto multicast;
19340 
19341 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19342 	    (connp->conn_nexthop_set)) {
19343 		/*
19344 		 * If the destination is a broadcast or a loopback
19345 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
19346 		 * through the standard path. But in the case of local
19347 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
19348 		 * the standard path not IP_XMIT_IF.
19349 		 */
19350 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19351 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
19352 		    (ire->ire_type != IRE_LOOPBACK))) {
19353 			if ((connp->conn_dontroute ||
19354 			    connp->conn_nexthop_set) && (ire != NULL) &&
19355 			    (ire->ire_type == IRE_LOCAL))
19356 				goto standard_path;
19357 
19358 			if (ire != NULL) {
19359 				ire_refrele(ire);
19360 				/* No more access to ire */
19361 				ire = NULL;
19362 			}
19363 			/*
19364 			 * bypass routing checks and go directly to
19365 			 * interface.
19366 			 */
19367 			if (connp->conn_dontroute) {
19368 				goto dontroute;
19369 			} else if (connp->conn_nexthop_set) {
19370 				ip_nexthop = B_TRUE;
19371 				nexthop_addr = connp->conn_nexthop_v4;
19372 				goto send_from_ill;
19373 			}
19374 
19375 			/*
19376 			 * If IP_XMIT_IF socket option is set,
19377 			 * then we allow unicast and multicast
19378 			 * packets to go through the ill. It is
19379 			 * quite possible that the destination
19380 			 * is not in the ire cache table and we
19381 			 * do not want to go to ip_newroute()
19382 			 * instead we call ip_newroute_ipif.
19383 			 */
19384 			xmit_ill = conn_get_held_ill(connp,
19385 			    &connp->conn_xmit_if_ill, &err);
19386 			if (err == ILL_LOOKUP_FAILED) {
19387 				if (attach_ill != NULL)
19388 					ill_refrele(attach_ill);
19389 				if (need_decref)
19390 					CONN_DEC_REF(connp);
19391 				freemsg(first_mp);
19392 				return;
19393 			}
19394 			goto send_from_ill;
19395 		}
19396 standard_path:
19397 		/* Must be a broadcast, a loopback or a local ire */
19398 		if (ire != NULL) {
19399 			ire_refrele(ire);
19400 			/* No more access to ire */
19401 			ire = NULL;
19402 		}
19403 	}
19404 
19405 	if (attach_ill != NULL)
19406 		goto send_from_ill;
19407 
19408 	/*
19409 	 * We cache IRE_CACHEs to avoid lookups. We don't do
19410 	 * this for the tcp global queue and listen end point
19411 	 * as it does not really have a real destination to
19412 	 * talk to.  This is also true for SCTP.
19413 	 */
19414 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
19415 	    !connp->conn_fully_bound) {
19416 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19417 		if (ire == NULL)
19418 			goto noirefound;
19419 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19420 		    "ip_wput_end: q %p (%S)", q, "end");
19421 
19422 		/*
19423 		 * Check if the ire has the RTF_MULTIRT flag, inherited
19424 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19425 		 */
19426 		if (ire->ire_flags & RTF_MULTIRT) {
19427 
19428 			/*
19429 			 * Force the TTL of multirouted packets if required.
19430 			 * The TTL of such packets is bounded by the
19431 			 * ip_multirt_ttl ndd variable.
19432 			 */
19433 			if ((ip_multirt_ttl > 0) &&
19434 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
19435 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
19436 				    "(was %d), dst 0x%08x\n",
19437 				    ip_multirt_ttl, ipha->ipha_ttl,
19438 				    ntohl(ire->ire_addr)));
19439 				ipha->ipha_ttl = ip_multirt_ttl;
19440 			}
19441 			/*
19442 			 * We look at this point if there are pending
19443 			 * unresolved routes. ire_multirt_resolvable()
19444 			 * checks in O(n) that all IRE_OFFSUBNET ire
19445 			 * entries for the packet's destination and
19446 			 * flagged RTF_MULTIRT are currently resolved.
19447 			 * If some remain unresolved, we make a copy
19448 			 * of the current message. It will be used
19449 			 * to initiate additional route resolutions.
19450 			 */
19451 			multirt_need_resolve =
19452 			    ire_multirt_need_resolve(ire->ire_addr,
19453 			    MBLK_GETLABEL(first_mp));
19454 			ip2dbg(("ip_wput[TCP]: ire %p, "
19455 			    "multirt_need_resolve %d, first_mp %p\n",
19456 			    (void *)ire, multirt_need_resolve,
19457 			    (void *)first_mp));
19458 			if (multirt_need_resolve) {
19459 				copy_mp = copymsg(first_mp);
19460 				if (copy_mp != NULL) {
19461 					MULTIRT_DEBUG_TAG(copy_mp);
19462 				}
19463 			}
19464 		}
19465 
19466 		ip_wput_ire(q, first_mp, ire, connp, caller);
19467 
19468 		/*
19469 		 * Try to resolve another multiroute if
19470 		 * ire_multirt_need_resolve() deemed it necessary.
19471 		 */
19472 		if (copy_mp != NULL) {
19473 			ip_newroute(q, copy_mp, dst, NULL, connp);
19474 		}
19475 		if (need_decref)
19476 			CONN_DEC_REF(connp);
19477 		return;
19478 	}
19479 
19480 	/*
19481 	 * Access to conn_ire_cache. (protected by conn_lock)
19482 	 *
19483 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
19484 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
19485 	 * send a packet or two with the IRE_CACHE that is going away.
19486 	 * Access to the ire requires an ire refhold on the ire prior to
19487 	 * its use since an interface unplumb thread may delete the cached
19488 	 * ire and release the refhold at any time.
19489 	 *
19490 	 * Caching an ire in the conn_ire_cache
19491 	 *
19492 	 * o Caching an ire pointer in the conn requires a strict check for
19493 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
19494 	 * ires  before cleaning up the conns. So the caching of an ire pointer
19495 	 * in the conn is done after making sure under the bucket lock that the
19496 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
19497 	 * caching an ire after the unplumb thread has cleaned up the conn.
19498 	 * If the conn does not send a packet subsequently the unplumb thread
19499 	 * will be hanging waiting for the ire count to drop to zero.
19500 	 *
19501 	 * o We also need to atomically test for a null conn_ire_cache and
19502 	 * set the conn_ire_cache under the the protection of the conn_lock
19503 	 * to avoid races among concurrent threads trying to simultaneously
19504 	 * cache an ire in the conn_ire_cache.
19505 	 */
19506 	mutex_enter(&connp->conn_lock);
19507 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
19508 
19509 	if (ire != NULL && ire->ire_addr == dst &&
19510 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19511 
19512 		IRE_REFHOLD(ire);
19513 		mutex_exit(&connp->conn_lock);
19514 
19515 	} else {
19516 		boolean_t cached = B_FALSE;
19517 		connp->conn_ire_cache = NULL;
19518 		mutex_exit(&connp->conn_lock);
19519 		/* Release the old ire */
19520 		if (ire != NULL && sctp_ire == NULL)
19521 			IRE_REFRELE_NOTR(ire);
19522 
19523 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19524 		if (ire == NULL)
19525 			goto noirefound;
19526 		IRE_REFHOLD_NOTR(ire);
19527 
19528 		mutex_enter(&connp->conn_lock);
19529 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
19530 		    connp->conn_ire_cache == NULL) {
19531 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19532 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19533 				connp->conn_ire_cache = ire;
19534 				cached = B_TRUE;
19535 			}
19536 			rw_exit(&ire->ire_bucket->irb_lock);
19537 		}
19538 		mutex_exit(&connp->conn_lock);
19539 
19540 		/*
19541 		 * We can continue to use the ire but since it was
19542 		 * not cached, we should drop the extra reference.
19543 		 */
19544 		if (!cached)
19545 			IRE_REFRELE_NOTR(ire);
19546 	}
19547 
19548 
19549 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19550 	    "ip_wput_end: q %p (%S)", q, "end");
19551 
19552 	/*
19553 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19554 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19555 	 */
19556 	if (ire->ire_flags & RTF_MULTIRT) {
19557 
19558 		/*
19559 		 * Force the TTL of multirouted packets if required.
19560 		 * The TTL of such packets is bounded by the
19561 		 * ip_multirt_ttl ndd variable.
19562 		 */
19563 		if ((ip_multirt_ttl > 0) &&
19564 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19565 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19566 			    "(was %d), dst 0x%08x\n",
19567 			    ip_multirt_ttl, ipha->ipha_ttl,
19568 			    ntohl(ire->ire_addr)));
19569 			ipha->ipha_ttl = ip_multirt_ttl;
19570 		}
19571 
19572 		/*
19573 		 * At this point, we check to see if there are any pending
19574 		 * unresolved routes. ire_multirt_resolvable()
19575 		 * checks in O(n) that all IRE_OFFSUBNET ire
19576 		 * entries for the packet's destination and
19577 		 * flagged RTF_MULTIRT are currently resolved.
19578 		 * If some remain unresolved, we make a copy
19579 		 * of the current message. It will be used
19580 		 * to initiate additional route resolutions.
19581 		 */
19582 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19583 		    MBLK_GETLABEL(first_mp));
19584 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19585 		    "multirt_need_resolve %d, first_mp %p\n",
19586 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19587 		if (multirt_need_resolve) {
19588 			copy_mp = copymsg(first_mp);
19589 			if (copy_mp != NULL) {
19590 				MULTIRT_DEBUG_TAG(copy_mp);
19591 			}
19592 		}
19593 	}
19594 
19595 	ip_wput_ire(q, first_mp, ire, connp, caller);
19596 
19597 	/*
19598 	 * Try to resolve another multiroute if
19599 	 * ire_multirt_resolvable() deemed it necessary
19600 	 */
19601 	if (copy_mp != NULL) {
19602 		ip_newroute(q, copy_mp, dst, NULL, connp);
19603 	}
19604 	if (need_decref)
19605 		CONN_DEC_REF(connp);
19606 	return;
19607 
19608 qnext:
19609 	/*
19610 	 * Upper Level Protocols pass down complete IP datagrams
19611 	 * as M_DATA messages.	Everything else is a sideshow.
19612 	 *
19613 	 * 1) We could be re-entering ip_wput because of ip_neworute
19614 	 *    in which case we could have a IPSEC_OUT message. We
19615 	 *    need to pass through ip_wput like other datagrams and
19616 	 *    hence cannot branch to ip_wput_nondata.
19617 	 *
19618 	 * 2) ARP, AH, ESP, and other clients who are on the module
19619 	 *    instance of IP stream, give us something to deal with.
19620 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19621 	 *
19622 	 * 3) ICMP replies also could come here.
19623 	 */
19624 	if (DB_TYPE(mp) != M_DATA) {
19625 	    notdata:
19626 		if (DB_TYPE(mp) == M_CTL) {
19627 			/*
19628 			 * M_CTL messages are used by ARP, AH and ESP to
19629 			 * communicate with IP. We deal with IPSEC_IN and
19630 			 * IPSEC_OUT here. ip_wput_nondata handles other
19631 			 * cases.
19632 			 */
19633 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19634 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19635 				first_mp = mp->b_cont;
19636 				first_mp->b_flag &= ~MSGHASREF;
19637 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19638 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19639 				CONN_DEC_REF(connp);
19640 				connp = NULL;
19641 			}
19642 			if (ii->ipsec_info_type == IPSEC_IN) {
19643 				/*
19644 				 * Either this message goes back to
19645 				 * IPSEC for further processing or to
19646 				 * ULP after policy checks.
19647 				 */
19648 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19649 				return;
19650 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19651 				io = (ipsec_out_t *)ii;
19652 				if (io->ipsec_out_proc_begin) {
19653 					/*
19654 					 * IPSEC processing has already started.
19655 					 * Complete it.
19656 					 * IPQoS notes: We don't care what is
19657 					 * in ipsec_out_ill_index since this
19658 					 * won't be processed for IPQoS policies
19659 					 * in ipsec_out_process.
19660 					 */
19661 					ipsec_out_process(q, mp, NULL,
19662 					    io->ipsec_out_ill_index);
19663 					return;
19664 				} else {
19665 					connp = (q->q_next != NULL) ?
19666 					    NULL : Q_TO_CONN(q);
19667 					first_mp = mp;
19668 					mp = mp->b_cont;
19669 					mctl_present = B_TRUE;
19670 				}
19671 				zoneid = io->ipsec_out_zoneid;
19672 				ASSERT(zoneid != ALL_ZONES);
19673 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
19674 				/*
19675 				 * It's an IPsec control message requesting
19676 				 * an SADB update to be sent to the IPsec
19677 				 * hardware acceleration capable ills.
19678 				 */
19679 				ipsec_ctl_t *ipsec_ctl =
19680 				    (ipsec_ctl_t *)mp->b_rptr;
19681 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
19682 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
19683 				mblk_t *cmp = mp->b_cont;
19684 
19685 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
19686 				ASSERT(cmp != NULL);
19687 
19688 				freeb(mp);
19689 				ill_ipsec_capab_send_all(satype, cmp, sa);
19690 				return;
19691 			} else {
19692 				/*
19693 				 * This must be ARP or special TSOL signaling.
19694 				 */
19695 				ip_wput_nondata(NULL, q, mp, NULL);
19696 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19697 				    "ip_wput_end: q %p (%S)", q, "nondata");
19698 				return;
19699 			}
19700 		} else {
19701 			/*
19702 			 * This must be non-(ARP/AH/ESP) messages.
19703 			 */
19704 			ASSERT(!need_decref);
19705 			ip_wput_nondata(NULL, q, mp, NULL);
19706 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19707 			    "ip_wput_end: q %p (%S)", q, "nondata");
19708 			return;
19709 		}
19710 	} else {
19711 		first_mp = mp;
19712 		mctl_present = B_FALSE;
19713 	}
19714 
19715 	ASSERT(first_mp != NULL);
19716 	/*
19717 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
19718 	 * to make sure that this packet goes out on the same interface it
19719 	 * came in. We handle that here.
19720 	 */
19721 	if (mctl_present) {
19722 		uint_t ifindex;
19723 
19724 		io = (ipsec_out_t *)first_mp->b_rptr;
19725 		if (io->ipsec_out_attach_if ||
19726 		    io->ipsec_out_xmit_if ||
19727 		    io->ipsec_out_ip_nexthop) {
19728 			ill_t	*ill;
19729 
19730 			/*
19731 			 * We may have lost the conn context if we are
19732 			 * coming here from ip_newroute(). Copy the
19733 			 * nexthop information.
19734 			 */
19735 			if (io->ipsec_out_ip_nexthop) {
19736 				ip_nexthop = B_TRUE;
19737 				nexthop_addr = io->ipsec_out_nexthop_addr;
19738 
19739 				ipha = (ipha_t *)mp->b_rptr;
19740 				dst = ipha->ipha_dst;
19741 				goto send_from_ill;
19742 			} else {
19743 				ASSERT(io->ipsec_out_ill_index != 0);
19744 				ifindex = io->ipsec_out_ill_index;
19745 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
19746 				    NULL, NULL, NULL, NULL);
19747 				/*
19748 				 * ipsec_out_xmit_if bit is used to tell
19749 				 * ip_wput to use the ill to send outgoing data
19750 				 * as we have no conn when data comes from ICMP
19751 				 * error msg routines. Currently this feature is
19752 				 * only used by ip_mrtun_forward routine.
19753 				 */
19754 				if (io->ipsec_out_xmit_if) {
19755 					xmit_ill = ill;
19756 					if (xmit_ill == NULL) {
19757 						ip1dbg(("ip_output:bad ifindex "
19758 						    "for xmit_ill %d\n",
19759 						    ifindex));
19760 						freemsg(first_mp);
19761 						BUMP_MIB(&ip_mib,
19762 						    ipOutDiscards);
19763 						ASSERT(!need_decref);
19764 						return;
19765 					}
19766 					/* Free up the ipsec_out_t mblk */
19767 					ASSERT(first_mp->b_cont == mp);
19768 					first_mp->b_cont = NULL;
19769 					freeb(first_mp);
19770 					/* Just send the IP header+ICMP+data */
19771 					first_mp = mp;
19772 					ipha = (ipha_t *)mp->b_rptr;
19773 					dst = ipha->ipha_dst;
19774 					goto send_from_ill;
19775 				} else {
19776 					attach_ill = ill;
19777 				}
19778 
19779 				if (attach_ill == NULL) {
19780 					ASSERT(xmit_ill == NULL);
19781 					ip1dbg(("ip_output: bad ifindex for "
19782 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
19783 					    ifindex));
19784 					freemsg(first_mp);
19785 					BUMP_MIB(&ip_mib, ipOutDiscards);
19786 					ASSERT(!need_decref);
19787 					return;
19788 				}
19789 			}
19790 		}
19791 	}
19792 
19793 	ASSERT(xmit_ill == NULL);
19794 
19795 	/* We have a complete IP datagram heading outbound. */
19796 	ipha = (ipha_t *)mp->b_rptr;
19797 
19798 #ifndef SPEED_BEFORE_SAFETY
19799 	/*
19800 	 * Make sure we have a full-word aligned message and that at least
19801 	 * a simple IP header is accessible in the first message.  If not,
19802 	 * try a pullup.
19803 	 */
19804 	if (!OK_32PTR(rptr) ||
19805 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
19806 	    hdrtoosmall:
19807 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
19808 			BUMP_MIB(&ip_mib, ipOutDiscards);
19809 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19810 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
19811 			if (first_mp == NULL)
19812 				first_mp = mp;
19813 			goto drop_pkt;
19814 		}
19815 
19816 		/* This function assumes that mp points to an IPv4 packet. */
19817 		if (is_system_labeled() && q->q_next == NULL &&
19818 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
19819 		    !connp->conn_ulp_labeled) {
19820 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
19821 			    &adjust, connp->conn_mac_exempt);
19822 			ipha = (ipha_t *)mp->b_rptr;
19823 			if (first_mp != NULL)
19824 				first_mp->b_cont = mp;
19825 			if (err != 0) {
19826 				if (first_mp == NULL)
19827 					first_mp = mp;
19828 				if (err == EINVAL)
19829 					goto icmp_parameter_problem;
19830 				ip2dbg(("ip_wput: label check failed (%d)\n",
19831 				    err));
19832 				goto drop_pkt;
19833 			}
19834 			iplen = ntohs(ipha->ipha_length) + adjust;
19835 			ipha->ipha_length = htons(iplen);
19836 		}
19837 
19838 		ipha = (ipha_t *)mp->b_rptr;
19839 		if (first_mp == NULL) {
19840 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
19841 			/*
19842 			 * If we got here because of "goto hdrtoosmall"
19843 			 * We need to attach a IPSEC_OUT.
19844 			 */
19845 			if (connp->conn_out_enforce_policy) {
19846 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
19847 				    NULL, ipha->ipha_protocol)) == NULL)) {
19848 					if (need_decref)
19849 						CONN_DEC_REF(connp);
19850 					return;
19851 				} else {
19852 					ASSERT(mp->b_datap->db_type == M_CTL);
19853 					first_mp = mp;
19854 					mp = mp->b_cont;
19855 					mctl_present = B_TRUE;
19856 				}
19857 			} else {
19858 				first_mp = mp;
19859 				mctl_present = B_FALSE;
19860 			}
19861 		}
19862 	}
19863 #endif
19864 
19865 	/* Most of the code below is written for speed, not readability */
19866 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19867 
19868 	/*
19869 	 * If ip_newroute() fails, we're going to need a full
19870 	 * header for the icmp wraparound.
19871 	 */
19872 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
19873 		uint_t	v_hlen;
19874 	    version_hdrlen_check:
19875 		ASSERT(first_mp != NULL);
19876 		v_hlen = V_HLEN;
19877 		/*
19878 		 * siphon off IPv6 packets coming down from transport
19879 		 * layer modules here.
19880 		 * Note: high-order bit carries NUD reachability confirmation
19881 		 */
19882 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
19883 			/*
19884 			 * XXX implement a IPv4 and IPv6 packet counter per
19885 			 * conn and switch when ratio exceeds e.g. 10:1
19886 			 */
19887 #ifdef notyet
19888 			if (q->q_next == NULL) /* Avoid ill queue */
19889 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
19890 #endif
19891 			BUMP_MIB(&ip_mib, ipOutIPv6);
19892 			ASSERT(xmit_ill == NULL);
19893 			if (attach_ill != NULL)
19894 				ill_refrele(attach_ill);
19895 			if (need_decref)
19896 				mp->b_flag |= MSGHASREF;
19897 			(void) ip_output_v6(connp, first_mp, q, caller);
19898 			return;
19899 		}
19900 
19901 		if ((v_hlen >> 4) != IP_VERSION) {
19902 			BUMP_MIB(&ip_mib, ipOutDiscards);
19903 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19904 			    "ip_wput_end: q %p (%S)", q, "badvers");
19905 			goto drop_pkt;
19906 		}
19907 		/*
19908 		 * Is the header length at least 20 bytes?
19909 		 *
19910 		 * Are there enough bytes accessible in the header?  If
19911 		 * not, try a pullup.
19912 		 */
19913 		v_hlen &= 0xF;
19914 		v_hlen <<= 2;
19915 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
19916 			BUMP_MIB(&ip_mib, ipOutDiscards);
19917 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19918 			    "ip_wput_end: q %p (%S)", q, "badlen");
19919 			goto drop_pkt;
19920 		}
19921 		if (v_hlen > (mp->b_wptr - rptr)) {
19922 			if (!pullupmsg(mp, v_hlen)) {
19923 				BUMP_MIB(&ip_mib, ipOutDiscards);
19924 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19925 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
19926 				goto drop_pkt;
19927 			}
19928 			ipha = (ipha_t *)mp->b_rptr;
19929 		}
19930 		/*
19931 		 * Move first entry from any source route into ipha_dst and
19932 		 * verify the options
19933 		 */
19934 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
19935 			ASSERT(xmit_ill == NULL);
19936 			if (attach_ill != NULL)
19937 				ill_refrele(attach_ill);
19938 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19939 			    "ip_wput_end: q %p (%S)", q, "badopts");
19940 			if (need_decref)
19941 				CONN_DEC_REF(connp);
19942 			return;
19943 		}
19944 	}
19945 	dst = ipha->ipha_dst;
19946 
19947 	/*
19948 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
19949 	 * we have to run the packet through ip_newroute which will take
19950 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
19951 	 * a resolver, or assigning a default gateway, etc.
19952 	 */
19953 	if (CLASSD(dst)) {
19954 		ipif_t	*ipif;
19955 		uint32_t setsrc = 0;
19956 
19957 	    multicast:
19958 		ASSERT(first_mp != NULL);
19959 		ASSERT(xmit_ill == NULL);
19960 		ip2dbg(("ip_wput: CLASSD\n"));
19961 		if (connp == NULL) {
19962 			/*
19963 			 * Use the first good ipif on the ill.
19964 			 * XXX Should this ever happen? (Appears
19965 			 * to show up with just ppp and no ethernet due
19966 			 * to in.rdisc.)
19967 			 * However, ire_send should be able to
19968 			 * call ip_wput_ire directly.
19969 			 *
19970 			 * XXX Also, this can happen for ICMP and other packets
19971 			 * with multicast source addresses.  Perhaps we should
19972 			 * fix things so that we drop the packet in question,
19973 			 * but for now, just run with it.
19974 			 */
19975 			ill_t *ill = (ill_t *)q->q_ptr;
19976 
19977 			/*
19978 			 * Don't honor attach_if for this case. If ill
19979 			 * is part of the group, ipif could belong to
19980 			 * any ill and we cannot maintain attach_ill
19981 			 * and ipif_ill same anymore and the assert
19982 			 * below would fail.
19983 			 */
19984 			if (mctl_present) {
19985 				io->ipsec_out_ill_index = 0;
19986 				io->ipsec_out_attach_if = B_FALSE;
19987 				ASSERT(attach_ill != NULL);
19988 				ill_refrele(attach_ill);
19989 				attach_ill = NULL;
19990 			}
19991 
19992 			ASSERT(attach_ill == NULL);
19993 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
19994 			if (ipif == NULL) {
19995 				if (need_decref)
19996 					CONN_DEC_REF(connp);
19997 				freemsg(first_mp);
19998 				return;
19999 			}
20000 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20001 			    ntohl(dst), ill->ill_name));
20002 		} else {
20003 			/*
20004 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
20005 			 * IP_XMIT_IF is honoured.
20006 			 * Block comment above this function explains the
20007 			 * locking mechanism used here
20008 			 */
20009 			xmit_ill = conn_get_held_ill(connp,
20010 			    &connp->conn_xmit_if_ill, &err);
20011 			if (err == ILL_LOOKUP_FAILED) {
20012 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
20013 				goto drop_pkt;
20014 			}
20015 			if (xmit_ill == NULL) {
20016 				ipif = conn_get_held_ipif(connp,
20017 				    &connp->conn_multicast_ipif, &err);
20018 				if (err == IPIF_LOOKUP_FAILED) {
20019 					ip1dbg(("ip_wput: No ipif for "
20020 					    "multicast\n"));
20021 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20022 					goto drop_pkt;
20023 				}
20024 			}
20025 			if (xmit_ill != NULL) {
20026 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20027 				if (ipif == NULL) {
20028 					ip1dbg(("ip_wput: No ipif for "
20029 					    "IP_XMIT_IF\n"));
20030 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20031 					goto drop_pkt;
20032 				}
20033 			} else if (ipif == NULL || ipif->ipif_isv6) {
20034 				/*
20035 				 * We must do this ipif determination here
20036 				 * else we could pass through ip_newroute
20037 				 * and come back here without the conn context.
20038 				 *
20039 				 * Note: we do late binding i.e. we bind to
20040 				 * the interface when the first packet is sent.
20041 				 * For performance reasons we do not rebind on
20042 				 * each packet but keep the binding until the
20043 				 * next IP_MULTICAST_IF option.
20044 				 *
20045 				 * conn_multicast_{ipif,ill} are shared between
20046 				 * IPv4 and IPv6 and AF_INET6 sockets can
20047 				 * send both IPv4 and IPv6 packets. Hence
20048 				 * we have to check that "isv6" matches above.
20049 				 */
20050 				if (ipif != NULL)
20051 					ipif_refrele(ipif);
20052 				ipif = ipif_lookup_group(dst, zoneid);
20053 				if (ipif == NULL) {
20054 					ip1dbg(("ip_wput: No ipif for "
20055 					    "multicast\n"));
20056 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20057 					goto drop_pkt;
20058 				}
20059 				err = conn_set_held_ipif(connp,
20060 				    &connp->conn_multicast_ipif, ipif);
20061 				if (err == IPIF_LOOKUP_FAILED) {
20062 					ipif_refrele(ipif);
20063 					ip1dbg(("ip_wput: No ipif for "
20064 					    "multicast\n"));
20065 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20066 					goto drop_pkt;
20067 				}
20068 			}
20069 		}
20070 		ASSERT(!ipif->ipif_isv6);
20071 		/*
20072 		 * As we may lose the conn by the time we reach ip_wput_ire,
20073 		 * we copy conn_multicast_loop and conn_dontroute on to an
20074 		 * ipsec_out. In case if this datagram goes out secure,
20075 		 * we need the ill_index also. Copy that also into the
20076 		 * ipsec_out.
20077 		 */
20078 		if (mctl_present) {
20079 			io = (ipsec_out_t *)first_mp->b_rptr;
20080 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20081 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20082 		} else {
20083 			ASSERT(mp == first_mp);
20084 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20085 			    BPRI_HI)) == NULL) {
20086 				ipif_refrele(ipif);
20087 				first_mp = mp;
20088 				goto drop_pkt;
20089 			}
20090 			first_mp->b_datap->db_type = M_CTL;
20091 			first_mp->b_wptr += sizeof (ipsec_info_t);
20092 			/* ipsec_out_secure is B_FALSE now */
20093 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20094 			io = (ipsec_out_t *)first_mp->b_rptr;
20095 			io->ipsec_out_type = IPSEC_OUT;
20096 			io->ipsec_out_len = sizeof (ipsec_out_t);
20097 			io->ipsec_out_use_global_policy = B_TRUE;
20098 			first_mp->b_cont = mp;
20099 			mctl_present = B_TRUE;
20100 		}
20101 		if (attach_ill != NULL) {
20102 			ASSERT(attach_ill == ipif->ipif_ill);
20103 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20104 
20105 			/*
20106 			 * Check if we need an ire that will not be
20107 			 * looked up by anybody else i.e. HIDDEN.
20108 			 */
20109 			if (ill_is_probeonly(attach_ill)) {
20110 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20111 			}
20112 			io->ipsec_out_ill_index =
20113 			    attach_ill->ill_phyint->phyint_ifindex;
20114 			io->ipsec_out_attach_if = B_TRUE;
20115 		} else {
20116 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20117 			io->ipsec_out_ill_index =
20118 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20119 		}
20120 		if (connp != NULL) {
20121 			io->ipsec_out_multicast_loop =
20122 			    connp->conn_multicast_loop;
20123 			io->ipsec_out_dontroute = connp->conn_dontroute;
20124 			io->ipsec_out_zoneid = connp->conn_zoneid;
20125 		}
20126 		/*
20127 		 * If the application uses IP_MULTICAST_IF with
20128 		 * different logical addresses of the same ILL, we
20129 		 * need to make sure that the soruce address of
20130 		 * the packet matches the logical IP address used
20131 		 * in the option. We do it by initializing ipha_src
20132 		 * here. This should keep IPSEC also happy as
20133 		 * when we return from IPSEC processing, we don't
20134 		 * have to worry about getting the right address on
20135 		 * the packet. Thus it is sufficient to look for
20136 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20137 		 * MATCH_IRE_IPIF.
20138 		 *
20139 		 * NOTE : We need to do it for non-secure case also as
20140 		 * this might go out secure if there is a global policy
20141 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20142 		 * address, the source should be initialized already and
20143 		 * hence we won't be initializing here.
20144 		 *
20145 		 * As we do not have the ire yet, it is possible that
20146 		 * we set the source address here and then later discover
20147 		 * that the ire implies the source address to be assigned
20148 		 * through the RTF_SETSRC flag.
20149 		 * In that case, the setsrc variable will remind us
20150 		 * that overwritting the source address by the one
20151 		 * of the RTF_SETSRC-flagged ire is allowed.
20152 		 */
20153 		if (ipha->ipha_src == INADDR_ANY &&
20154 		    (connp == NULL || !connp->conn_unspec_src)) {
20155 			ipha->ipha_src = ipif->ipif_src_addr;
20156 			setsrc = RTF_SETSRC;
20157 		}
20158 		/*
20159 		 * Find an IRE which matches the destination and the outgoing
20160 		 * queue (i.e. the outgoing interface.)
20161 		 * For loopback use a unicast IP address for
20162 		 * the ire lookup.
20163 		 */
20164 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20165 		    PHYI_LOOPBACK) {
20166 			dst = ipif->ipif_lcl_addr;
20167 		}
20168 		/*
20169 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20170 		 * We don't need to lookup ire in ctable as the packet
20171 		 * needs to be sent to the destination through the specified
20172 		 * ill irrespective of ires in the cache table.
20173 		 */
20174 		ire = NULL;
20175 		if (xmit_ill == NULL) {
20176 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20177 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20178 		}
20179 
20180 		/*
20181 		 * refrele attach_ill as its not needed anymore.
20182 		 */
20183 		if (attach_ill != NULL) {
20184 			ill_refrele(attach_ill);
20185 			attach_ill = NULL;
20186 		}
20187 
20188 		if (ire == NULL) {
20189 			/*
20190 			 * Multicast loopback and multicast forwarding is
20191 			 * done in ip_wput_ire.
20192 			 *
20193 			 * Mark this packet to make it be delivered to
20194 			 * ip_wput_ire after the new ire has been
20195 			 * created.
20196 			 *
20197 			 * The call to ip_newroute_ipif takes into account
20198 			 * the setsrc reminder. In any case, we take care
20199 			 * of the RTF_MULTIRT flag.
20200 			 */
20201 			mp->b_prev = mp->b_next = NULL;
20202 			if (xmit_ill == NULL ||
20203 			    xmit_ill->ill_ipif_up_count > 0) {
20204 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20205 				    setsrc | RTF_MULTIRT);
20206 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20207 				    "ip_wput_end: q %p (%S)", q, "noire");
20208 			} else {
20209 				freemsg(first_mp);
20210 			}
20211 			ipif_refrele(ipif);
20212 			if (xmit_ill != NULL)
20213 				ill_refrele(xmit_ill);
20214 			if (need_decref)
20215 				CONN_DEC_REF(connp);
20216 			return;
20217 		}
20218 
20219 		ipif_refrele(ipif);
20220 		ipif = NULL;
20221 		ASSERT(xmit_ill == NULL);
20222 
20223 		/*
20224 		 * Honor the RTF_SETSRC flag for multicast packets,
20225 		 * if allowed by the setsrc reminder.
20226 		 */
20227 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20228 			ipha->ipha_src = ire->ire_src_addr;
20229 		}
20230 
20231 		/*
20232 		 * Unconditionally force the TTL to 1 for
20233 		 * multirouted multicast packets:
20234 		 * multirouted multicast should not cross
20235 		 * multicast routers.
20236 		 */
20237 		if (ire->ire_flags & RTF_MULTIRT) {
20238 			if (ipha->ipha_ttl > 1) {
20239 				ip2dbg(("ip_wput: forcing multicast "
20240 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20241 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20242 				ipha->ipha_ttl = 1;
20243 			}
20244 		}
20245 	} else {
20246 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20247 		if ((ire != NULL) && (ire->ire_type &
20248 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20249 			ignore_dontroute = B_TRUE;
20250 			ignore_nexthop = B_TRUE;
20251 		}
20252 		if (ire != NULL) {
20253 			ire_refrele(ire);
20254 			ire = NULL;
20255 		}
20256 		/*
20257 		 * Guard against coming in from arp in which case conn is NULL.
20258 		 * Also guard against non M_DATA with dontroute set but
20259 		 * destined to local, loopback or broadcast addresses.
20260 		 */
20261 		if (connp != NULL && connp->conn_dontroute &&
20262 		    !ignore_dontroute) {
20263 dontroute:
20264 			/*
20265 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20266 			 * routing protocols from seeing false direct
20267 			 * connectivity.
20268 			 */
20269 			ipha->ipha_ttl = 1;
20270 			/*
20271 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20272 			 * along with SO_DONTROUTE, higher precedence is
20273 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20274 			 */
20275 			if (connp->conn_xmit_if_ill == NULL) {
20276 				/* If suitable ipif not found, drop packet */
20277 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20278 				if (dst_ipif == NULL) {
20279 					ip1dbg(("ip_wput: no route for "
20280 					    "dst using SO_DONTROUTE\n"));
20281 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20282 					mp->b_prev = mp->b_next = NULL;
20283 					if (first_mp == NULL)
20284 						first_mp = mp;
20285 					goto drop_pkt;
20286 				} else {
20287 					/*
20288 					 * If suitable ipif has been found, set
20289 					 * xmit_ill to the corresponding
20290 					 * ipif_ill because we'll be following
20291 					 * the IP_XMIT_IF logic.
20292 					 */
20293 					ASSERT(xmit_ill == NULL);
20294 					xmit_ill = dst_ipif->ipif_ill;
20295 					mutex_enter(&xmit_ill->ill_lock);
20296 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20297 						mutex_exit(&xmit_ill->ill_lock);
20298 						xmit_ill = NULL;
20299 						ipif_refrele(dst_ipif);
20300 						ip1dbg(("ip_wput: no route for"
20301 						    " dst using"
20302 						    " SO_DONTROUTE\n"));
20303 						BUMP_MIB(&ip_mib,
20304 						    ipOutNoRoutes);
20305 						mp->b_prev = mp->b_next = NULL;
20306 						if (first_mp == NULL)
20307 							first_mp = mp;
20308 						goto drop_pkt;
20309 					}
20310 					ill_refhold_locked(xmit_ill);
20311 					mutex_exit(&xmit_ill->ill_lock);
20312 					ipif_refrele(dst_ipif);
20313 				}
20314 			}
20315 
20316 		}
20317 		/*
20318 		 * If we are bound to IPIF_NOFAILOVER address, look for
20319 		 * an IRE_CACHE matching the ill.
20320 		 */
20321 send_from_ill:
20322 		if (attach_ill != NULL) {
20323 			ipif_t	*attach_ipif;
20324 
20325 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20326 
20327 			/*
20328 			 * Check if we need an ire that will not be
20329 			 * looked up by anybody else i.e. HIDDEN.
20330 			 */
20331 			if (ill_is_probeonly(attach_ill)) {
20332 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20333 			}
20334 
20335 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20336 			if (attach_ipif == NULL) {
20337 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20338 				goto drop_pkt;
20339 			}
20340 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20341 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20342 			ipif_refrele(attach_ipif);
20343 		} else if (xmit_ill != NULL || (connp != NULL &&
20344 			    connp->conn_xmit_if_ill != NULL)) {
20345 			/*
20346 			 * Mark this packet as originated locally
20347 			 */
20348 			mp->b_prev = mp->b_next = NULL;
20349 			/*
20350 			 * xmit_ill could be NULL if SO_DONTROUTE
20351 			 * is also set.
20352 			 */
20353 			if (xmit_ill == NULL) {
20354 				xmit_ill = conn_get_held_ill(connp,
20355 				    &connp->conn_xmit_if_ill, &err);
20356 				if (err == ILL_LOOKUP_FAILED) {
20357 					if (need_decref)
20358 						CONN_DEC_REF(connp);
20359 					freemsg(first_mp);
20360 					return;
20361 				}
20362 				if (xmit_ill == NULL) {
20363 					if (connp->conn_dontroute)
20364 						goto dontroute;
20365 					goto send_from_ill;
20366 				}
20367 			}
20368 			/*
20369 			 * could be SO_DONTROUTE case also.
20370 			 * check at least one interface is UP as
20371 			 * spcified by this ILL, and then call
20372 			 * ip_newroute_ipif()
20373 			 */
20374 			if (xmit_ill->ill_ipif_up_count > 0) {
20375 				ipif_t *ipif;
20376 
20377 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20378 				if (ipif != NULL) {
20379 					ip_newroute_ipif(q, first_mp, ipif,
20380 					    dst, connp, 0);
20381 					ipif_refrele(ipif);
20382 					ip1dbg(("ip_wput: ip_unicast_if\n"));
20383 				}
20384 			} else {
20385 				freemsg(first_mp);
20386 			}
20387 			ill_refrele(xmit_ill);
20388 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20389 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
20390 			if (need_decref)
20391 				CONN_DEC_REF(connp);
20392 			return;
20393 		} else if (ip_nexthop || (connp != NULL &&
20394 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
20395 			if (!ip_nexthop) {
20396 				ip_nexthop = B_TRUE;
20397 				nexthop_addr = connp->conn_nexthop_v4;
20398 			}
20399 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
20400 			    MATCH_IRE_GW;
20401 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
20402 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
20403 		} else {
20404 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20405 		}
20406 		if (!ire) {
20407 			/*
20408 			 * Make sure we don't load spread if this
20409 			 * is IPIF_NOFAILOVER case.
20410 			 */
20411 			if ((attach_ill != NULL) ||
20412 			    (ip_nexthop && !ignore_nexthop)) {
20413 				if (mctl_present) {
20414 					io = (ipsec_out_t *)first_mp->b_rptr;
20415 					ASSERT(first_mp->b_datap->db_type ==
20416 					    M_CTL);
20417 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
20418 				} else {
20419 					ASSERT(mp == first_mp);
20420 					first_mp = allocb(
20421 					    sizeof (ipsec_info_t), BPRI_HI);
20422 					if (first_mp == NULL) {
20423 						first_mp = mp;
20424 						goto drop_pkt;
20425 					}
20426 					first_mp->b_datap->db_type = M_CTL;
20427 					first_mp->b_wptr +=
20428 					    sizeof (ipsec_info_t);
20429 					/* ipsec_out_secure is B_FALSE now */
20430 					bzero(first_mp->b_rptr,
20431 					    sizeof (ipsec_info_t));
20432 					io = (ipsec_out_t *)first_mp->b_rptr;
20433 					io->ipsec_out_type = IPSEC_OUT;
20434 					io->ipsec_out_len =
20435 					    sizeof (ipsec_out_t);
20436 					io->ipsec_out_use_global_policy =
20437 					    B_TRUE;
20438 					first_mp->b_cont = mp;
20439 					mctl_present = B_TRUE;
20440 				}
20441 				if (attach_ill != NULL) {
20442 					io->ipsec_out_ill_index = attach_ill->
20443 					    ill_phyint->phyint_ifindex;
20444 					io->ipsec_out_attach_if = B_TRUE;
20445 				} else {
20446 					io->ipsec_out_ip_nexthop = ip_nexthop;
20447 					io->ipsec_out_nexthop_addr =
20448 					    nexthop_addr;
20449 				}
20450 			}
20451 noirefound:
20452 			/*
20453 			 * Mark this packet as having originated on
20454 			 * this machine.  This will be noted in
20455 			 * ire_add_then_send, which needs to know
20456 			 * whether to run it back through ip_wput or
20457 			 * ip_rput following successful resolution.
20458 			 */
20459 			mp->b_prev = NULL;
20460 			mp->b_next = NULL;
20461 			ip_newroute(q, first_mp, dst, NULL, connp);
20462 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20463 			    "ip_wput_end: q %p (%S)", q, "newroute");
20464 			if (attach_ill != NULL)
20465 				ill_refrele(attach_ill);
20466 			if (xmit_ill != NULL)
20467 				ill_refrele(xmit_ill);
20468 			if (need_decref)
20469 				CONN_DEC_REF(connp);
20470 			return;
20471 		}
20472 	}
20473 
20474 	/* We now know where we are going with it. */
20475 
20476 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20477 	    "ip_wput_end: q %p (%S)", q, "end");
20478 
20479 	/*
20480 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20481 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
20482 	 */
20483 	if (ire->ire_flags & RTF_MULTIRT) {
20484 		/*
20485 		 * Force the TTL of multirouted packets if required.
20486 		 * The TTL of such packets is bounded by the
20487 		 * ip_multirt_ttl ndd variable.
20488 		 */
20489 		if ((ip_multirt_ttl > 0) &&
20490 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20491 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20492 			    "(was %d), dst 0x%08x\n",
20493 			    ip_multirt_ttl, ipha->ipha_ttl,
20494 			    ntohl(ire->ire_addr)));
20495 			ipha->ipha_ttl = ip_multirt_ttl;
20496 		}
20497 		/*
20498 		 * At this point, we check to see if there are any pending
20499 		 * unresolved routes. ire_multirt_resolvable()
20500 		 * checks in O(n) that all IRE_OFFSUBNET ire
20501 		 * entries for the packet's destination and
20502 		 * flagged RTF_MULTIRT are currently resolved.
20503 		 * If some remain unresolved, we make a copy
20504 		 * of the current message. It will be used
20505 		 * to initiate additional route resolutions.
20506 		 */
20507 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20508 		    MBLK_GETLABEL(first_mp));
20509 		ip2dbg(("ip_wput[noirefound]: ire %p, "
20510 		    "multirt_need_resolve %d, first_mp %p\n",
20511 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20512 		if (multirt_need_resolve) {
20513 			copy_mp = copymsg(first_mp);
20514 			if (copy_mp != NULL) {
20515 				MULTIRT_DEBUG_TAG(copy_mp);
20516 			}
20517 		}
20518 	}
20519 
20520 	ip_wput_ire(q, first_mp, ire, connp, caller);
20521 	/*
20522 	 * Try to resolve another multiroute if
20523 	 * ire_multirt_resolvable() deemed it necessary.
20524 	 * At this point, we need to distinguish
20525 	 * multicasts from other packets. For multicasts,
20526 	 * we call ip_newroute_ipif() and request that both
20527 	 * multirouting and setsrc flags are checked.
20528 	 */
20529 	if (copy_mp != NULL) {
20530 		if (CLASSD(dst)) {
20531 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
20532 			if (ipif) {
20533 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
20534 				    RTF_SETSRC | RTF_MULTIRT);
20535 				ipif_refrele(ipif);
20536 			} else {
20537 				MULTIRT_DEBUG_UNTAG(copy_mp);
20538 				freemsg(copy_mp);
20539 				copy_mp = NULL;
20540 			}
20541 		} else {
20542 			ip_newroute(q, copy_mp, dst, NULL, connp);
20543 		}
20544 	}
20545 	if (attach_ill != NULL)
20546 		ill_refrele(attach_ill);
20547 	if (xmit_ill != NULL)
20548 		ill_refrele(xmit_ill);
20549 	if (need_decref)
20550 		CONN_DEC_REF(connp);
20551 	return;
20552 
20553 icmp_parameter_problem:
20554 	/* could not have originated externally */
20555 	ASSERT(mp->b_prev == NULL);
20556 	if (ip_hdr_complete(ipha, zoneid) == 0) {
20557 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
20558 		/* it's the IP header length that's in trouble */
20559 		icmp_param_problem(q, first_mp, 0);
20560 		first_mp = NULL;
20561 	}
20562 
20563 drop_pkt:
20564 	ip1dbg(("ip_wput: dropped packet\n"));
20565 	if (ire != NULL)
20566 		ire_refrele(ire);
20567 	if (need_decref)
20568 		CONN_DEC_REF(connp);
20569 	freemsg(first_mp);
20570 	if (attach_ill != NULL)
20571 		ill_refrele(attach_ill);
20572 	if (xmit_ill != NULL)
20573 		ill_refrele(xmit_ill);
20574 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20575 	    "ip_wput_end: q %p (%S)", q, "droppkt");
20576 }
20577 
20578 void
20579 ip_wput(queue_t *q, mblk_t *mp)
20580 {
20581 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20582 }
20583 
20584 /*
20585  *
20586  * The following rules must be observed when accessing any ipif or ill
20587  * that has been cached in the conn. Typically conn_nofailover_ill,
20588  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20589  *
20590  * Access: The ipif or ill pointed to from the conn can be accessed under
20591  * the protection of the conn_lock or after it has been refheld under the
20592  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20593  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20594  * The reason for this is that a concurrent unplumb could actually be
20595  * cleaning up these cached pointers by walking the conns and might have
20596  * finished cleaning up the conn in question. The macros check that an
20597  * unplumb has not yet started on the ipif or ill.
20598  *
20599  * Caching: An ipif or ill pointer may be cached in the conn only after
20600  * making sure that an unplumb has not started. So the caching is done
20601  * while holding both the conn_lock and the ill_lock and after using the
20602  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20603  * flag before starting the cleanup of conns.
20604  *
20605  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20606  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20607  * or a reference to the ipif or a reference to an ire that references the
20608  * ipif. An ipif does not change its ill except for failover/failback. Since
20609  * failover/failback happens only after bringing down the ipif and making sure
20610  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20611  * the above holds.
20612  */
20613 ipif_t *
20614 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20615 {
20616 	ipif_t	*ipif;
20617 	ill_t	*ill;
20618 
20619 	*err = 0;
20620 	rw_enter(&ill_g_lock, RW_READER);
20621 	mutex_enter(&connp->conn_lock);
20622 	ipif = *ipifp;
20623 	if (ipif != NULL) {
20624 		ill = ipif->ipif_ill;
20625 		mutex_enter(&ill->ill_lock);
20626 		if (IPIF_CAN_LOOKUP(ipif)) {
20627 			ipif_refhold_locked(ipif);
20628 			mutex_exit(&ill->ill_lock);
20629 			mutex_exit(&connp->conn_lock);
20630 			rw_exit(&ill_g_lock);
20631 			return (ipif);
20632 		} else {
20633 			*err = IPIF_LOOKUP_FAILED;
20634 		}
20635 		mutex_exit(&ill->ill_lock);
20636 	}
20637 	mutex_exit(&connp->conn_lock);
20638 	rw_exit(&ill_g_lock);
20639 	return (NULL);
20640 }
20641 
20642 ill_t *
20643 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20644 {
20645 	ill_t	*ill;
20646 
20647 	*err = 0;
20648 	mutex_enter(&connp->conn_lock);
20649 	ill = *illp;
20650 	if (ill != NULL) {
20651 		mutex_enter(&ill->ill_lock);
20652 		if (ILL_CAN_LOOKUP(ill)) {
20653 			ill_refhold_locked(ill);
20654 			mutex_exit(&ill->ill_lock);
20655 			mutex_exit(&connp->conn_lock);
20656 			return (ill);
20657 		} else {
20658 			*err = ILL_LOOKUP_FAILED;
20659 		}
20660 		mutex_exit(&ill->ill_lock);
20661 	}
20662 	mutex_exit(&connp->conn_lock);
20663 	return (NULL);
20664 }
20665 
20666 static int
20667 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
20668 {
20669 	ill_t	*ill;
20670 
20671 	ill = ipif->ipif_ill;
20672 	mutex_enter(&connp->conn_lock);
20673 	mutex_enter(&ill->ill_lock);
20674 	if (IPIF_CAN_LOOKUP(ipif)) {
20675 		*ipifp = ipif;
20676 		mutex_exit(&ill->ill_lock);
20677 		mutex_exit(&connp->conn_lock);
20678 		return (0);
20679 	}
20680 	mutex_exit(&ill->ill_lock);
20681 	mutex_exit(&connp->conn_lock);
20682 	return (IPIF_LOOKUP_FAILED);
20683 }
20684 
20685 /*
20686  * This is called if the outbound datagram needs fragmentation.
20687  *
20688  * NOTE : This function does not ire_refrele the ire argument passed in.
20689  */
20690 static void
20691 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
20692 {
20693 	ipha_t		*ipha;
20694 	mblk_t		*mp;
20695 	uint32_t	v_hlen_tos_len;
20696 	uint32_t	max_frag;
20697 	uint32_t	frag_flag;
20698 	boolean_t	dont_use;
20699 
20700 	if (ipsec_mp->b_datap->db_type == M_CTL) {
20701 		mp = ipsec_mp->b_cont;
20702 	} else {
20703 		mp = ipsec_mp;
20704 	}
20705 
20706 	ipha = (ipha_t *)mp->b_rptr;
20707 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20708 
20709 #ifdef	_BIG_ENDIAN
20710 #define	V_HLEN	(v_hlen_tos_len >> 24)
20711 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20712 #else
20713 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20714 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20715 #endif
20716 
20717 #ifndef SPEED_BEFORE_SAFETY
20718 	/*
20719 	 * Check that ipha_length is consistent with
20720 	 * the mblk length
20721 	 */
20722 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
20723 		ip0dbg(("Packet length mismatch: %d, %ld\n",
20724 		    LENGTH, msgdsize(mp)));
20725 		freemsg(ipsec_mp);
20726 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20727 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
20728 		    "packet length mismatch");
20729 		return;
20730 	}
20731 #endif
20732 	/*
20733 	 * Don't use frag_flag if pre-built packet or source
20734 	 * routed or if multicast (since multicast packets do not solicit
20735 	 * ICMP "packet too big" messages). Get the values of
20736 	 * max_frag and frag_flag atomically by acquiring the
20737 	 * ire_lock.
20738 	 */
20739 	mutex_enter(&ire->ire_lock);
20740 	max_frag = ire->ire_max_frag;
20741 	frag_flag = ire->ire_frag_flag;
20742 	mutex_exit(&ire->ire_lock);
20743 
20744 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
20745 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
20746 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
20747 
20748 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
20749 	    (dont_use ? 0 : frag_flag));
20750 }
20751 
20752 /*
20753  * Used for deciding the MSS size for the upper layer. Thus
20754  * we need to check the outbound policy values in the conn.
20755  */
20756 int
20757 conn_ipsec_length(conn_t *connp)
20758 {
20759 	ipsec_latch_t *ipl;
20760 
20761 	ipl = connp->conn_latch;
20762 	if (ipl == NULL)
20763 		return (0);
20764 
20765 	if (ipl->ipl_out_policy == NULL)
20766 		return (0);
20767 
20768 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
20769 }
20770 
20771 /*
20772  * Returns an estimate of the IPSEC headers size. This is used if
20773  * we don't want to call into IPSEC to get the exact size.
20774  */
20775 int
20776 ipsec_out_extra_length(mblk_t *ipsec_mp)
20777 {
20778 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
20779 	ipsec_action_t *a;
20780 
20781 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
20782 	if (!io->ipsec_out_secure)
20783 		return (0);
20784 
20785 	a = io->ipsec_out_act;
20786 
20787 	if (a == NULL) {
20788 		ASSERT(io->ipsec_out_policy != NULL);
20789 		a = io->ipsec_out_policy->ipsp_act;
20790 	}
20791 	ASSERT(a != NULL);
20792 
20793 	return (a->ipa_ovhd);
20794 }
20795 
20796 /*
20797  * Returns an estimate of the IPSEC headers size. This is used if
20798  * we don't want to call into IPSEC to get the exact size.
20799  */
20800 int
20801 ipsec_in_extra_length(mblk_t *ipsec_mp)
20802 {
20803 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
20804 	ipsec_action_t *a;
20805 
20806 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
20807 
20808 	a = ii->ipsec_in_action;
20809 	return (a == NULL ? 0 : a->ipa_ovhd);
20810 }
20811 
20812 /*
20813  * If there are any source route options, return the true final
20814  * destination. Otherwise, return the destination.
20815  */
20816 ipaddr_t
20817 ip_get_dst(ipha_t *ipha)
20818 {
20819 	ipoptp_t	opts;
20820 	uchar_t		*opt;
20821 	uint8_t		optval;
20822 	uint8_t		optlen;
20823 	ipaddr_t	dst;
20824 	uint32_t off;
20825 
20826 	dst = ipha->ipha_dst;
20827 
20828 	if (IS_SIMPLE_IPH(ipha))
20829 		return (dst);
20830 
20831 	for (optval = ipoptp_first(&opts, ipha);
20832 	    optval != IPOPT_EOL;
20833 	    optval = ipoptp_next(&opts)) {
20834 		opt = opts.ipoptp_cur;
20835 		optlen = opts.ipoptp_len;
20836 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20837 		switch (optval) {
20838 		case IPOPT_SSRR:
20839 		case IPOPT_LSRR:
20840 			off = opt[IPOPT_OFFSET];
20841 			/*
20842 			 * If one of the conditions is true, it means
20843 			 * end of options and dst already has the right
20844 			 * value.
20845 			 */
20846 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
20847 				off = optlen - IP_ADDR_LEN;
20848 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
20849 			}
20850 			return (dst);
20851 		default:
20852 			break;
20853 		}
20854 	}
20855 
20856 	return (dst);
20857 }
20858 
20859 mblk_t *
20860 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
20861     conn_t *connp, boolean_t unspec_src)
20862 {
20863 	ipsec_out_t	*io;
20864 	mblk_t		*first_mp;
20865 	boolean_t policy_present;
20866 
20867 	first_mp = mp;
20868 	if (mp->b_datap->db_type == M_CTL) {
20869 		io = (ipsec_out_t *)first_mp->b_rptr;
20870 		/*
20871 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
20872 		 *
20873 		 * 1) There is per-socket policy (including cached global
20874 		 *    policy).
20875 		 * 2) There is no per-socket policy, but it is
20876 		 *    a multicast packet that needs to go out
20877 		 *    on a specific interface. This is the case
20878 		 *    where (ip_wput and ip_wput_multicast) attaches
20879 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
20880 		 *
20881 		 * In case (2) we check with global policy to
20882 		 * see if there is a match and set the ill_index
20883 		 * appropriately so that we can lookup the ire
20884 		 * properly in ip_wput_ipsec_out.
20885 		 */
20886 
20887 		/*
20888 		 * ipsec_out_use_global_policy is set to B_FALSE
20889 		 * in ipsec_in_to_out(). Refer to that function for
20890 		 * details.
20891 		 */
20892 		if ((io->ipsec_out_latch == NULL) &&
20893 		    (io->ipsec_out_use_global_policy)) {
20894 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
20895 			    ire, connp, unspec_src));
20896 		}
20897 		if (!io->ipsec_out_secure) {
20898 			/*
20899 			 * If this is not a secure packet, drop
20900 			 * the IPSEC_OUT mp and treat it as a clear
20901 			 * packet. This happens when we are sending
20902 			 * a ICMP reply back to a clear packet. See
20903 			 * ipsec_in_to_out() for details.
20904 			 */
20905 			mp = first_mp->b_cont;
20906 			freeb(first_mp);
20907 		}
20908 		return (mp);
20909 	}
20910 	/*
20911 	 * See whether we need to attach a global policy here. We
20912 	 * don't depend on the conn (as it could be null) for deciding
20913 	 * what policy this datagram should go through because it
20914 	 * should have happened in ip_wput if there was some
20915 	 * policy. This normally happens for connections which are not
20916 	 * fully bound preventing us from caching policies in
20917 	 * ip_bind. Packets coming from the TCP listener/global queue
20918 	 * - which are non-hard_bound - could also be affected by
20919 	 * applying policy here.
20920 	 *
20921 	 * If this packet is coming from tcp global queue or listener,
20922 	 * we will be applying policy here.  This may not be *right*
20923 	 * if these packets are coming from the detached connection as
20924 	 * it could have gone in clear before. This happens only if a
20925 	 * TCP connection started when there is no policy and somebody
20926 	 * added policy before it became detached. Thus packets of the
20927 	 * detached connection could go out secure and the other end
20928 	 * would drop it because it will be expecting in clear. The
20929 	 * converse is not true i.e if somebody starts a TCP
20930 	 * connection and deletes the policy, all the packets will
20931 	 * still go out with the policy that existed before deleting
20932 	 * because ip_unbind sends up policy information which is used
20933 	 * by TCP on subsequent ip_wputs. The right solution is to fix
20934 	 * TCP to attach a dummy IPSEC_OUT and set
20935 	 * ipsec_out_use_global_policy to B_FALSE. As this might
20936 	 * affect performance for normal cases, we are not doing it.
20937 	 * Thus, set policy before starting any TCP connections.
20938 	 *
20939 	 * NOTE - We might apply policy even for a hard bound connection
20940 	 * - for which we cached policy in ip_bind - if somebody added
20941 	 * global policy after we inherited the policy in ip_bind.
20942 	 * This means that the packets that were going out in clear
20943 	 * previously would start going secure and hence get dropped
20944 	 * on the other side. To fix this, TCP attaches a dummy
20945 	 * ipsec_out and make sure that we don't apply global policy.
20946 	 */
20947 	if (ipha != NULL)
20948 		policy_present = ipsec_outbound_v4_policy_present;
20949 	else
20950 		policy_present = ipsec_outbound_v6_policy_present;
20951 	if (!policy_present)
20952 		return (mp);
20953 
20954 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
20955 }
20956 
20957 ire_t *
20958 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
20959 {
20960 	ipaddr_t addr;
20961 	ire_t *save_ire;
20962 	irb_t *irb;
20963 	ill_group_t *illgrp;
20964 	int	err;
20965 
20966 	save_ire = ire;
20967 	addr = ire->ire_addr;
20968 
20969 	ASSERT(ire->ire_type == IRE_BROADCAST);
20970 
20971 	illgrp = connp->conn_outgoing_ill->ill_group;
20972 	if (illgrp == NULL) {
20973 		*conn_outgoing_ill = conn_get_held_ill(connp,
20974 		    &connp->conn_outgoing_ill, &err);
20975 		if (err == ILL_LOOKUP_FAILED) {
20976 			ire_refrele(save_ire);
20977 			return (NULL);
20978 		}
20979 		return (save_ire);
20980 	}
20981 	/*
20982 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
20983 	 * If it is part of the group, we need to send on the ire
20984 	 * that has been cleared of IRE_MARK_NORECV and that belongs
20985 	 * to this group. This is okay as IP_BOUND_IF really means
20986 	 * any ill in the group. We depend on the fact that the
20987 	 * first ire in the group is always cleared of IRE_MARK_NORECV
20988 	 * if such an ire exists. This is possible only if you have
20989 	 * at least one ill in the group that has not failed.
20990 	 *
20991 	 * First get to the ire that matches the address and group.
20992 	 *
20993 	 * We don't look for an ire with a matching zoneid because a given zone
20994 	 * won't always have broadcast ires on all ills in the group.
20995 	 */
20996 	irb = ire->ire_bucket;
20997 	rw_enter(&irb->irb_lock, RW_READER);
20998 	if (ire->ire_marks & IRE_MARK_NORECV) {
20999 		/*
21000 		 * If the current zone only has an ire broadcast for this
21001 		 * address marked NORECV, the ire we want is ahead in the
21002 		 * bucket, so we look it up deliberately ignoring the zoneid.
21003 		 */
21004 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21005 			if (ire->ire_addr != addr)
21006 				continue;
21007 			/* skip over deleted ires */
21008 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21009 				continue;
21010 		}
21011 	}
21012 	while (ire != NULL) {
21013 		/*
21014 		 * If a new interface is coming up, we could end up
21015 		 * seeing the loopback ire and the non-loopback ire
21016 		 * may not have been added yet. So check for ire_stq
21017 		 */
21018 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21019 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21020 			break;
21021 		}
21022 		ire = ire->ire_next;
21023 	}
21024 	if (ire != NULL && ire->ire_addr == addr &&
21025 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21026 		IRE_REFHOLD(ire);
21027 		rw_exit(&irb->irb_lock);
21028 		ire_refrele(save_ire);
21029 		*conn_outgoing_ill = ire_to_ill(ire);
21030 		/*
21031 		 * Refhold the ill to make the conn_outgoing_ill
21032 		 * independent of the ire. ip_wput_ire goes in a loop
21033 		 * and may refrele the ire. Since we have an ire at this
21034 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21035 		 */
21036 		ill_refhold(*conn_outgoing_ill);
21037 		return (ire);
21038 	}
21039 	rw_exit(&irb->irb_lock);
21040 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21041 	/*
21042 	 * If we can't find a suitable ire, return the original ire.
21043 	 */
21044 	return (save_ire);
21045 }
21046 
21047 /*
21048  * This function does the ire_refrele of the ire passed in as the
21049  * argument. As this function looks up more ires i.e broadcast ires,
21050  * it needs to REFRELE them. Currently, for simplicity we don't
21051  * differentiate the one passed in and looked up here. We always
21052  * REFRELE.
21053  * IPQoS Notes:
21054  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21055  * IPSec packets are done in ipsec_out_process.
21056  *
21057  */
21058 void
21059 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
21060 {
21061 	ipha_t		*ipha;
21062 #define	rptr	((uchar_t *)ipha)
21063 	queue_t		*stq;
21064 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21065 	uint32_t	v_hlen_tos_len;
21066 	uint32_t	ttl_protocol;
21067 	ipaddr_t	src;
21068 	ipaddr_t	dst;
21069 	uint32_t	cksum;
21070 	ipaddr_t	orig_src;
21071 	ire_t		*ire1;
21072 	mblk_t		*next_mp;
21073 	uint_t		hlen;
21074 	uint16_t	*up;
21075 	uint32_t	max_frag = ire->ire_max_frag;
21076 	ill_t		*ill = ire_to_ill(ire);
21077 	int		clusterwide;
21078 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21079 	int		ipsec_len;
21080 	mblk_t		*first_mp;
21081 	ipsec_out_t	*io;
21082 	boolean_t	conn_dontroute;		/* conn value for multicast */
21083 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21084 	boolean_t	multicast_forward;	/* Should we forward ? */
21085 	boolean_t	unspec_src;
21086 	ill_t		*conn_outgoing_ill = NULL;
21087 	ill_t		*ire_ill;
21088 	ill_t		*ire1_ill;
21089 	uint32_t 	ill_index = 0;
21090 	boolean_t	multirt_send = B_FALSE;
21091 	int		err;
21092 	zoneid_t	zoneid;
21093 	ipxmit_state_t	pktxmit_state;
21094 
21095 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21096 	    "ip_wput_ire_start: q %p", q);
21097 
21098 	multicast_forward = B_FALSE;
21099 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21100 
21101 	if (ire->ire_flags & RTF_MULTIRT) {
21102 		/*
21103 		 * Multirouting case. The bucket where ire is stored
21104 		 * probably holds other RTF_MULTIRT flagged ire
21105 		 * to the destination. In this call to ip_wput_ire,
21106 		 * we attempt to send the packet through all
21107 		 * those ires. Thus, we first ensure that ire is the
21108 		 * first RTF_MULTIRT ire in the bucket,
21109 		 * before walking the ire list.
21110 		 */
21111 		ire_t *first_ire;
21112 		irb_t *irb = ire->ire_bucket;
21113 		ASSERT(irb != NULL);
21114 
21115 		/* Make sure we do not omit any multiroute ire. */
21116 		IRB_REFHOLD(irb);
21117 		for (first_ire = irb->irb_ire;
21118 		    first_ire != NULL;
21119 		    first_ire = first_ire->ire_next) {
21120 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21121 			    (first_ire->ire_addr == ire->ire_addr) &&
21122 			    !(first_ire->ire_marks &
21123 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21124 				break;
21125 		}
21126 
21127 		if ((first_ire != NULL) && (first_ire != ire)) {
21128 			IRE_REFHOLD(first_ire);
21129 			ire_refrele(ire);
21130 			ire = first_ire;
21131 			ill = ire_to_ill(ire);
21132 		}
21133 		IRB_REFRELE(irb);
21134 	}
21135 
21136 	/*
21137 	 * conn_outgoing_ill is used only in the broadcast loop.
21138 	 * for performance we don't grab the mutexs in the fastpath
21139 	 */
21140 	if ((connp != NULL) &&
21141 	    (connp->conn_xmit_if_ill == NULL) &&
21142 	    (ire->ire_type == IRE_BROADCAST) &&
21143 	    ((connp->conn_nofailover_ill != NULL) ||
21144 	    (connp->conn_outgoing_ill != NULL))) {
21145 		/*
21146 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21147 		 * option. So, see if this endpoint is bound to a
21148 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21149 		 * that if the interface is failed, we will still send
21150 		 * the packet on the same ill which is what we want.
21151 		 */
21152 		conn_outgoing_ill = conn_get_held_ill(connp,
21153 		    &connp->conn_nofailover_ill, &err);
21154 		if (err == ILL_LOOKUP_FAILED) {
21155 			ire_refrele(ire);
21156 			freemsg(mp);
21157 			return;
21158 		}
21159 		if (conn_outgoing_ill == NULL) {
21160 			/*
21161 			 * Choose a good ill in the group to send the
21162 			 * packets on.
21163 			 */
21164 			ire = conn_set_outgoing_ill(connp, ire,
21165 			    &conn_outgoing_ill);
21166 			if (ire == NULL) {
21167 				freemsg(mp);
21168 				return;
21169 			}
21170 		}
21171 	}
21172 
21173 	if (mp->b_datap->db_type != M_CTL) {
21174 		ipha = (ipha_t *)mp->b_rptr;
21175 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
21176 	} else {
21177 		io = (ipsec_out_t *)mp->b_rptr;
21178 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21179 		zoneid = io->ipsec_out_zoneid;
21180 		ASSERT(zoneid != ALL_ZONES);
21181 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21182 		dst = ipha->ipha_dst;
21183 		/*
21184 		 * For the multicast case, ipsec_out carries conn_dontroute and
21185 		 * conn_multicast_loop as conn may not be available here. We
21186 		 * need this for multicast loopback and forwarding which is done
21187 		 * later in the code.
21188 		 */
21189 		if (CLASSD(dst)) {
21190 			conn_dontroute = io->ipsec_out_dontroute;
21191 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21192 			/*
21193 			 * If conn_dontroute is not set or conn_multicast_loop
21194 			 * is set, we need to do forwarding/loopback. For
21195 			 * datagrams from ip_wput_multicast, conn_dontroute is
21196 			 * set to B_TRUE and conn_multicast_loop is set to
21197 			 * B_FALSE so that we neither do forwarding nor
21198 			 * loopback.
21199 			 */
21200 			if (!conn_dontroute || conn_multicast_loop)
21201 				multicast_forward = B_TRUE;
21202 		}
21203 	}
21204 
21205 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21206 	    ire->ire_zoneid != ALL_ZONES) {
21207 		/*
21208 		 * When a zone sends a packet to another zone, we try to deliver
21209 		 * the packet under the same conditions as if the destination
21210 		 * was a real node on the network. To do so, we look for a
21211 		 * matching route in the forwarding table.
21212 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21213 		 * ip_newroute() does.
21214 		 */
21215 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21216 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21217 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
21218 		if (src_ire != NULL &&
21219 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
21220 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21221 				ipha->ipha_src = src_ire->ire_src_addr;
21222 			ire_refrele(src_ire);
21223 		} else {
21224 			ire_refrele(ire);
21225 			if (conn_outgoing_ill != NULL)
21226 				ill_refrele(conn_outgoing_ill);
21227 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
21228 			if (src_ire != NULL) {
21229 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21230 					ire_refrele(src_ire);
21231 					freemsg(mp);
21232 					return;
21233 				}
21234 				ire_refrele(src_ire);
21235 			}
21236 			if (ip_hdr_complete(ipha, zoneid)) {
21237 				/* Failed */
21238 				freemsg(mp);
21239 				return;
21240 			}
21241 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
21242 			return;
21243 		}
21244 	}
21245 
21246 	if (mp->b_datap->db_type == M_CTL ||
21247 	    ipsec_outbound_v4_policy_present) {
21248 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21249 		    unspec_src);
21250 		if (mp == NULL) {
21251 			ire_refrele(ire);
21252 			if (conn_outgoing_ill != NULL)
21253 				ill_refrele(conn_outgoing_ill);
21254 			return;
21255 		}
21256 	}
21257 
21258 	first_mp = mp;
21259 	ipsec_len = 0;
21260 
21261 	if (first_mp->b_datap->db_type == M_CTL) {
21262 		io = (ipsec_out_t *)first_mp->b_rptr;
21263 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21264 		mp = first_mp->b_cont;
21265 		ipsec_len = ipsec_out_extra_length(first_mp);
21266 		ASSERT(ipsec_len >= 0);
21267 		zoneid = io->ipsec_out_zoneid;
21268 		ASSERT(zoneid != ALL_ZONES);
21269 
21270 		/*
21271 		 * Drop M_CTL here if IPsec processing is not needed.
21272 		 * (Non-IPsec use of M_CTL extracted any information it
21273 		 * needed above).
21274 		 */
21275 		if (ipsec_len == 0) {
21276 			freeb(first_mp);
21277 			first_mp = mp;
21278 		}
21279 	}
21280 
21281 	/*
21282 	 * Fast path for ip_wput_ire
21283 	 */
21284 
21285 	ipha = (ipha_t *)mp->b_rptr;
21286 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21287 	dst = ipha->ipha_dst;
21288 
21289 	/*
21290 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21291 	 * if the socket is a SOCK_RAW type. The transport checksum should
21292 	 * be provided in the pre-built packet, so we don't need to compute it.
21293 	 * Also, other application set flags, like DF, should not be altered.
21294 	 * Other transport MUST pass down zero.
21295 	 */
21296 	ip_hdr_included = ipha->ipha_ident;
21297 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21298 
21299 	if (CLASSD(dst)) {
21300 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
21301 		    ntohl(dst),
21302 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
21303 		    ntohl(ire->ire_addr)));
21304 	}
21305 
21306 /* Macros to extract header fields from data already in registers */
21307 #ifdef	_BIG_ENDIAN
21308 #define	V_HLEN	(v_hlen_tos_len >> 24)
21309 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21310 #define	PROTO	(ttl_protocol & 0xFF)
21311 #else
21312 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21313 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21314 #define	PROTO	(ttl_protocol >> 8)
21315 #endif
21316 
21317 
21318 	orig_src = src = ipha->ipha_src;
21319 	/* (The loop back to "another" is explained down below.) */
21320 another:;
21321 	/*
21322 	 * Assign an ident value for this packet.  We assign idents on
21323 	 * a per destination basis out of the IRE.  There could be
21324 	 * other threads targeting the same destination, so we have to
21325 	 * arrange for a atomic increment.  Note that we use a 32-bit
21326 	 * atomic add because it has better performance than its
21327 	 * 16-bit sibling.
21328 	 *
21329 	 * If running in cluster mode and if the source address
21330 	 * belongs to a replicated service then vector through
21331 	 * cl_inet_ipident vector to allocate ip identifier
21332 	 * NOTE: This is a contract private interface with the
21333 	 * clustering group.
21334 	 */
21335 	clusterwide = 0;
21336 	if (cl_inet_ipident) {
21337 		ASSERT(cl_inet_isclusterwide);
21338 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21339 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
21340 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
21341 			    AF_INET, (uint8_t *)(uintptr_t)src,
21342 			    (uint8_t *)(uintptr_t)dst);
21343 			clusterwide = 1;
21344 		}
21345 	}
21346 	if (!clusterwide) {
21347 		ipha->ipha_ident =
21348 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
21349 	}
21350 
21351 #ifndef _BIG_ENDIAN
21352 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21353 #endif
21354 
21355 	/*
21356 	 * Set source address unless sent on an ill or conn_unspec_src is set.
21357 	 * This is needed to obey conn_unspec_src when packets go through
21358 	 * ip_newroute + arp.
21359 	 * Assumes ip_newroute{,_multi} sets the source address as well.
21360 	 */
21361 	if (src == INADDR_ANY && !unspec_src) {
21362 		/*
21363 		 * Assign the appropriate source address from the IRE if none
21364 		 * was specified.
21365 		 */
21366 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
21367 
21368 		/*
21369 		 * With IP multipathing, broadcast packets are sent on the ire
21370 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
21371 		 * the group. However, this ire might not be in the same zone so
21372 		 * we can't always use its source address. We look for a
21373 		 * broadcast ire in the same group and in the right zone.
21374 		 */
21375 		if (ire->ire_type == IRE_BROADCAST &&
21376 		    ire->ire_zoneid != zoneid) {
21377 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
21378 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
21379 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
21380 			if (src_ire != NULL) {
21381 				src = src_ire->ire_src_addr;
21382 				ire_refrele(src_ire);
21383 			} else {
21384 				ire_refrele(ire);
21385 				if (conn_outgoing_ill != NULL)
21386 					ill_refrele(conn_outgoing_ill);
21387 				freemsg(first_mp);
21388 				BUMP_MIB(&ip_mib, ipOutDiscards);
21389 				return;
21390 			}
21391 		} else {
21392 			src = ire->ire_src_addr;
21393 		}
21394 
21395 		if (connp == NULL) {
21396 			ip1dbg(("ip_wput_ire: no connp and no src "
21397 			    "address for dst 0x%x, using src 0x%x\n",
21398 			    ntohl(dst),
21399 			    ntohl(src)));
21400 		}
21401 		ipha->ipha_src = src;
21402 	}
21403 	stq = ire->ire_stq;
21404 
21405 	/*
21406 	 * We only allow ire chains for broadcasts since there will
21407 	 * be multiple IRE_CACHE entries for the same multicast
21408 	 * address (one per ipif).
21409 	 */
21410 	next_mp = NULL;
21411 
21412 	/* broadcast packet */
21413 	if (ire->ire_type == IRE_BROADCAST)
21414 		goto broadcast;
21415 
21416 	/* loopback ? */
21417 	if (stq == NULL)
21418 		goto nullstq;
21419 
21420 	/* The ill_index for outbound ILL */
21421 	ill_index = Q_TO_INDEX(stq);
21422 
21423 	BUMP_MIB(&ip_mib, ipOutRequests);
21424 	ttl_protocol = ((uint16_t *)ipha)[4];
21425 
21426 	/* pseudo checksum (do it in parts for IP header checksum) */
21427 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21428 
21429 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
21430 		queue_t *dev_q = stq->q_next;
21431 
21432 		/* flow controlled */
21433 		if ((dev_q->q_next || dev_q->q_first) &&
21434 		    !canput(dev_q))
21435 			goto blocked;
21436 		if ((PROTO == IPPROTO_UDP) &&
21437 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21438 			hlen = (V_HLEN & 0xF) << 2;
21439 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21440 			if (*up != 0) {
21441 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
21442 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
21443 				/* Software checksum? */
21444 				if (DB_CKSUMFLAGS(mp) == 0) {
21445 					IP_STAT(ip_out_sw_cksum);
21446 					IP_STAT_UPDATE(
21447 					    ip_udp_out_sw_cksum_bytes,
21448 					    LENGTH - hlen);
21449 				}
21450 			}
21451 		}
21452 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
21453 		hlen = (V_HLEN & 0xF) << 2;
21454 		if (PROTO == IPPROTO_TCP) {
21455 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21456 			/*
21457 			 * The packet header is processed once and for all, even
21458 			 * in the multirouting case. We disable hardware
21459 			 * checksum if the packet is multirouted, as it will be
21460 			 * replicated via several interfaces, and not all of
21461 			 * them may have this capability.
21462 			 */
21463 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
21464 			    LENGTH, max_frag, ipsec_len, cksum);
21465 			/* Software checksum? */
21466 			if (DB_CKSUMFLAGS(mp) == 0) {
21467 				IP_STAT(ip_out_sw_cksum);
21468 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21469 				    LENGTH - hlen);
21470 			}
21471 		} else {
21472 			sctp_hdr_t	*sctph;
21473 
21474 			ASSERT(PROTO == IPPROTO_SCTP);
21475 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21476 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21477 			/*
21478 			 * Zero out the checksum field to ensure proper
21479 			 * checksum calculation.
21480 			 */
21481 			sctph->sh_chksum = 0;
21482 #ifdef	DEBUG
21483 			if (!skip_sctp_cksum)
21484 #endif
21485 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21486 		}
21487 	}
21488 
21489 	/*
21490 	 * If this is a multicast packet and originated from ip_wput
21491 	 * we need to do loopback and forwarding checks. If it comes
21492 	 * from ip_wput_multicast, we SHOULD not do this.
21493 	 */
21494 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
21495 
21496 	/* checksum */
21497 	cksum += ttl_protocol;
21498 
21499 	/* fragment the packet */
21500 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
21501 		goto fragmentit;
21502 	/*
21503 	 * Don't use frag_flag if packet is pre-built or source
21504 	 * routed or if multicast (since multicast packets do
21505 	 * not solicit ICMP "packet too big" messages).
21506 	 */
21507 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21508 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21509 	    !ip_source_route_included(ipha)) &&
21510 	    !CLASSD(ipha->ipha_dst))
21511 		ipha->ipha_fragment_offset_and_flags |=
21512 		    htons(ire->ire_frag_flag);
21513 
21514 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21515 		/* calculate IP header checksum */
21516 		cksum += ipha->ipha_ident;
21517 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
21518 		cksum += ipha->ipha_fragment_offset_and_flags;
21519 
21520 		/* IP options present */
21521 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21522 		if (hlen)
21523 			goto checksumoptions;
21524 
21525 		/* calculate hdr checksum */
21526 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21527 		cksum = ~(cksum + (cksum >> 16));
21528 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
21529 	}
21530 	if (ipsec_len != 0) {
21531 		/*
21532 		 * We will do the rest of the processing after
21533 		 * we come back from IPSEC in ip_wput_ipsec_out().
21534 		 */
21535 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
21536 
21537 		io = (ipsec_out_t *)first_mp->b_rptr;
21538 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
21539 				ill_phyint->phyint_ifindex;
21540 
21541 		ipsec_out_process(q, first_mp, ire, ill_index);
21542 		ire_refrele(ire);
21543 		if (conn_outgoing_ill != NULL)
21544 			ill_refrele(conn_outgoing_ill);
21545 		return;
21546 	}
21547 
21548 	/*
21549 	 * In most cases, the emission loop below is entered only
21550 	 * once. Only in the case where the ire holds the
21551 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
21552 	 * flagged ires in the bucket, and send the packet
21553 	 * through all crossed RTF_MULTIRT routes.
21554 	 */
21555 	if (ire->ire_flags & RTF_MULTIRT) {
21556 		multirt_send = B_TRUE;
21557 	}
21558 	do {
21559 		if (multirt_send) {
21560 			irb_t *irb;
21561 			/*
21562 			 * We are in a multiple send case, need to get
21563 			 * the next ire and make a duplicate of the packet.
21564 			 * ire1 holds here the next ire to process in the
21565 			 * bucket. If multirouting is expected,
21566 			 * any non-RTF_MULTIRT ire that has the
21567 			 * right destination address is ignored.
21568 			 */
21569 			irb = ire->ire_bucket;
21570 			ASSERT(irb != NULL);
21571 
21572 			IRB_REFHOLD(irb);
21573 			for (ire1 = ire->ire_next;
21574 			    ire1 != NULL;
21575 			    ire1 = ire1->ire_next) {
21576 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21577 					continue;
21578 				if (ire1->ire_addr != ire->ire_addr)
21579 					continue;
21580 				if (ire1->ire_marks &
21581 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21582 					continue;
21583 
21584 				/* Got one */
21585 				IRE_REFHOLD(ire1);
21586 				break;
21587 			}
21588 			IRB_REFRELE(irb);
21589 
21590 			if (ire1 != NULL) {
21591 				next_mp = copyb(mp);
21592 				if ((next_mp == NULL) ||
21593 				    ((mp->b_cont != NULL) &&
21594 				    ((next_mp->b_cont =
21595 				    dupmsg(mp->b_cont)) == NULL))) {
21596 					freemsg(next_mp);
21597 					next_mp = NULL;
21598 					ire_refrele(ire1);
21599 					ire1 = NULL;
21600 				}
21601 			}
21602 
21603 			/* Last multiroute ire; don't loop anymore. */
21604 			if (ire1 == NULL) {
21605 				multirt_send = B_FALSE;
21606 			}
21607 		}
21608 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
21609 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
21610 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
21611 		if ((pktxmit_state == SEND_FAILED) ||
21612 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
21613 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
21614 			    "- packet dropped\n"));
21615 			ire_refrele(ire);
21616 			if (next_mp != NULL) {
21617 				freemsg(next_mp);
21618 				ire_refrele(ire1);
21619 			}
21620 			if (conn_outgoing_ill != NULL)
21621 				ill_refrele(conn_outgoing_ill);
21622 			return;
21623 		}
21624 
21625 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21626 		    "ip_wput_ire_end: q %p (%S)",
21627 		    q, "last copy out");
21628 		IRE_REFRELE(ire);
21629 
21630 		if (multirt_send) {
21631 			ASSERT(ire1);
21632 			/*
21633 			 * Proceed with the next RTF_MULTIRT ire,
21634 			 * Also set up the send-to queue accordingly.
21635 			 */
21636 			ire = ire1;
21637 			ire1 = NULL;
21638 			stq = ire->ire_stq;
21639 			mp = next_mp;
21640 			next_mp = NULL;
21641 			ipha = (ipha_t *)mp->b_rptr;
21642 			ill_index = Q_TO_INDEX(stq);
21643 		}
21644 	} while (multirt_send);
21645 	if (conn_outgoing_ill != NULL)
21646 		ill_refrele(conn_outgoing_ill);
21647 	return;
21648 
21649 	/*
21650 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
21651 	 */
21652 broadcast:
21653 	{
21654 		/*
21655 		 * Avoid broadcast storms by setting the ttl to 1
21656 		 * for broadcasts. This parameter can be set
21657 		 * via ndd, so make sure that for the SO_DONTROUTE
21658 		 * case that ipha_ttl is always set to 1.
21659 		 * In the event that we are replying to incoming
21660 		 * ICMP packets, conn could be NULL.
21661 		 */
21662 		if ((connp != NULL) && connp->conn_dontroute)
21663 			ipha->ipha_ttl = 1;
21664 		else
21665 			ipha->ipha_ttl = ip_broadcast_ttl;
21666 
21667 		/*
21668 		 * Note that we are not doing a IRB_REFHOLD here.
21669 		 * Actually we don't care if the list changes i.e
21670 		 * if somebody deletes an IRE from the list while
21671 		 * we drop the lock, the next time we come around
21672 		 * ire_next will be NULL and hence we won't send
21673 		 * out multiple copies which is fine.
21674 		 */
21675 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
21676 		ire1 = ire->ire_next;
21677 		if (conn_outgoing_ill != NULL) {
21678 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
21679 				ASSERT(ire1 == ire->ire_next);
21680 				if (ire1 != NULL && ire1->ire_addr == dst) {
21681 					ire_refrele(ire);
21682 					ire = ire1;
21683 					IRE_REFHOLD(ire);
21684 					ire1 = ire->ire_next;
21685 					continue;
21686 				}
21687 				rw_exit(&ire->ire_bucket->irb_lock);
21688 				/* Did not find a matching ill */
21689 				ip1dbg(("ip_wput_ire: broadcast with no "
21690 				    "matching IP_BOUND_IF ill %s\n",
21691 				    conn_outgoing_ill->ill_name));
21692 				freemsg(first_mp);
21693 				if (ire != NULL)
21694 					ire_refrele(ire);
21695 				ill_refrele(conn_outgoing_ill);
21696 				return;
21697 			}
21698 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
21699 			/*
21700 			 * If the next IRE has the same address and is not one
21701 			 * of the two copies that we need to send, try to see
21702 			 * whether this copy should be sent at all. This
21703 			 * assumes that we insert loopbacks first and then
21704 			 * non-loopbacks. This is acheived by inserting the
21705 			 * loopback always before non-loopback.
21706 			 * This is used to send a single copy of a broadcast
21707 			 * packet out all physical interfaces that have an
21708 			 * matching IRE_BROADCAST while also looping
21709 			 * back one copy (to ip_wput_local) for each
21710 			 * matching physical interface. However, we avoid
21711 			 * sending packets out different logical that match by
21712 			 * having ipif_up/ipif_down supress duplicate
21713 			 * IRE_BROADCASTS.
21714 			 *
21715 			 * This feature is currently used to get broadcasts
21716 			 * sent to multiple interfaces, when the broadcast
21717 			 * address being used applies to multiple interfaces.
21718 			 * For example, a whole net broadcast will be
21719 			 * replicated on every connected subnet of
21720 			 * the target net.
21721 			 *
21722 			 * Each zone has its own set of IRE_BROADCASTs, so that
21723 			 * we're able to distribute inbound packets to multiple
21724 			 * zones who share a broadcast address. We avoid looping
21725 			 * back outbound packets in different zones but on the
21726 			 * same ill, as the application would see duplicates.
21727 			 *
21728 			 * If the interfaces are part of the same group,
21729 			 * we would want to send only one copy out for
21730 			 * whole group.
21731 			 *
21732 			 * This logic assumes that ire_add_v4() groups the
21733 			 * IRE_BROADCAST entries so that those with the same
21734 			 * ire_addr and ill_group are kept together.
21735 			 */
21736 			ire_ill = ire->ire_ipif->ipif_ill;
21737 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
21738 				if (ire_ill->ill_group != NULL &&
21739 				    (ire->ire_marks & IRE_MARK_NORECV)) {
21740 					/*
21741 					 * If the current zone only has an ire
21742 					 * broadcast for this address marked
21743 					 * NORECV, the ire we want is ahead in
21744 					 * the bucket, so we look it up
21745 					 * deliberately ignoring the zoneid.
21746 					 */
21747 					for (ire1 = ire->ire_bucket->irb_ire;
21748 					    ire1 != NULL;
21749 					    ire1 = ire1->ire_next) {
21750 						ire1_ill =
21751 						    ire1->ire_ipif->ipif_ill;
21752 						if (ire1->ire_addr != dst)
21753 							continue;
21754 						/* skip over the current ire */
21755 						if (ire1 == ire)
21756 							continue;
21757 						/* skip over deleted ires */
21758 						if (ire1->ire_marks &
21759 						    IRE_MARK_CONDEMNED)
21760 							continue;
21761 						/*
21762 						 * non-loopback ire in our
21763 						 * group: use it for the next
21764 						 * pass in the loop
21765 						 */
21766 						if (ire1->ire_stq != NULL &&
21767 						    ire1_ill->ill_group ==
21768 						    ire_ill->ill_group)
21769 							break;
21770 					}
21771 				}
21772 			} else {
21773 				while (ire1 != NULL && ire1->ire_addr == dst) {
21774 					ire1_ill = ire1->ire_ipif->ipif_ill;
21775 					/*
21776 					 * We can have two broadcast ires on the
21777 					 * same ill in different zones; here
21778 					 * we'll send a copy of the packet on
21779 					 * each ill and the fanout code will
21780 					 * call conn_wantpacket() to check that
21781 					 * the zone has the broadcast address
21782 					 * configured on the ill. If the two
21783 					 * ires are in the same group we only
21784 					 * send one copy up.
21785 					 */
21786 					if (ire1_ill != ire_ill &&
21787 					    (ire1_ill->ill_group == NULL ||
21788 					    ire_ill->ill_group == NULL ||
21789 					    ire1_ill->ill_group !=
21790 					    ire_ill->ill_group)) {
21791 						break;
21792 					}
21793 					ire1 = ire1->ire_next;
21794 				}
21795 			}
21796 		}
21797 		ASSERT(multirt_send == B_FALSE);
21798 		if (ire1 != NULL && ire1->ire_addr == dst) {
21799 			if ((ire->ire_flags & RTF_MULTIRT) &&
21800 			    (ire1->ire_flags & RTF_MULTIRT)) {
21801 				/*
21802 				 * We are in the multirouting case.
21803 				 * The message must be sent at least
21804 				 * on both ires. These ires have been
21805 				 * inserted AFTER the standard ones
21806 				 * in ip_rt_add(). There are thus no
21807 				 * other ire entries for the destination
21808 				 * address in the rest of the bucket
21809 				 * that do not have the RTF_MULTIRT
21810 				 * flag. We don't process a copy
21811 				 * of the message here. This will be
21812 				 * done in the final sending loop.
21813 				 */
21814 				multirt_send = B_TRUE;
21815 			} else {
21816 				next_mp = ip_copymsg(first_mp);
21817 				if (next_mp != NULL)
21818 					IRE_REFHOLD(ire1);
21819 			}
21820 		}
21821 		rw_exit(&ire->ire_bucket->irb_lock);
21822 	}
21823 
21824 	if (stq) {
21825 		/*
21826 		 * A non-NULL send-to queue means this packet is going
21827 		 * out of this machine.
21828 		 */
21829 
21830 		BUMP_MIB(&ip_mib, ipOutRequests);
21831 		ttl_protocol = ((uint16_t *)ipha)[4];
21832 		/*
21833 		 * We accumulate the pseudo header checksum in cksum.
21834 		 * This is pretty hairy code, so watch close.  One
21835 		 * thing to keep in mind is that UDP and TCP have
21836 		 * stored their respective datagram lengths in their
21837 		 * checksum fields.  This lines things up real nice.
21838 		 */
21839 		cksum = (dst >> 16) + (dst & 0xFFFF) +
21840 		    (src >> 16) + (src & 0xFFFF);
21841 		/*
21842 		 * We assume the udp checksum field contains the
21843 		 * length, so to compute the pseudo header checksum,
21844 		 * all we need is the protocol number and src/dst.
21845 		 */
21846 		/* Provide the checksums for UDP and TCP. */
21847 		if ((PROTO == IPPROTO_TCP) &&
21848 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21849 			/* hlen gets the number of uchar_ts in the IP header */
21850 			hlen = (V_HLEN & 0xF) << 2;
21851 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21852 			IP_STAT(ip_out_sw_cksum);
21853 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21854 			    LENGTH - hlen);
21855 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
21856 			if (*up == 0)
21857 				*up = 0xFFFF;
21858 		} else if (PROTO == IPPROTO_SCTP &&
21859 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21860 			sctp_hdr_t	*sctph;
21861 
21862 			hlen = (V_HLEN & 0xF) << 2;
21863 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21864 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21865 			sctph->sh_chksum = 0;
21866 #ifdef	DEBUG
21867 			if (!skip_sctp_cksum)
21868 #endif
21869 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21870 		} else {
21871 			queue_t *dev_q = stq->q_next;
21872 
21873 			if ((dev_q->q_next || dev_q->q_first) &&
21874 			    !canput(dev_q)) {
21875 			    blocked:
21876 				ipha->ipha_ident = ip_hdr_included;
21877 				/*
21878 				 * If we don't have a conn to apply
21879 				 * backpressure, free the message.
21880 				 * In the ire_send path, we don't know
21881 				 * the position to requeue the packet. Rather
21882 				 * than reorder packets, we just drop this
21883 				 * packet.
21884 				 */
21885 				if (ip_output_queue && connp != NULL &&
21886 				    caller != IRE_SEND) {
21887 					if (caller == IP_WSRV) {
21888 						connp->conn_did_putbq = 1;
21889 						(void) putbq(connp->conn_wq,
21890 						    first_mp);
21891 						conn_drain_insert(connp);
21892 						/*
21893 						 * This is the service thread,
21894 						 * and the queue is already
21895 						 * noenabled. The check for
21896 						 * canput and the putbq is not
21897 						 * atomic. So we need to check
21898 						 * again.
21899 						 */
21900 						if (canput(stq->q_next))
21901 							connp->conn_did_putbq
21902 							    = 0;
21903 						IP_STAT(ip_conn_flputbq);
21904 					} else {
21905 						/*
21906 						 * We are not the service proc.
21907 						 * ip_wsrv will be scheduled or
21908 						 * is already running.
21909 						 */
21910 						(void) putq(connp->conn_wq,
21911 						    first_mp);
21912 					}
21913 				} else {
21914 					BUMP_MIB(&ip_mib, ipOutDiscards);
21915 					freemsg(first_mp);
21916 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21917 					    "ip_wput_ire_end: q %p (%S)",
21918 					    q, "discard");
21919 				}
21920 				ire_refrele(ire);
21921 				if (next_mp) {
21922 					ire_refrele(ire1);
21923 					freemsg(next_mp);
21924 				}
21925 				if (conn_outgoing_ill != NULL)
21926 					ill_refrele(conn_outgoing_ill);
21927 				return;
21928 			}
21929 			if ((PROTO == IPPROTO_UDP) &&
21930 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
21931 				/*
21932 				 * hlen gets the number of uchar_ts in the
21933 				 * IP header
21934 				 */
21935 				hlen = (V_HLEN & 0xF) << 2;
21936 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21937 				max_frag = ire->ire_max_frag;
21938 				if (*up != 0) {
21939 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
21940 					    up, PROTO, hlen, LENGTH, max_frag,
21941 					    ipsec_len, cksum);
21942 					/* Software checksum? */
21943 					if (DB_CKSUMFLAGS(mp) == 0) {
21944 						IP_STAT(ip_out_sw_cksum);
21945 						IP_STAT_UPDATE(
21946 						    ip_udp_out_sw_cksum_bytes,
21947 						    LENGTH - hlen);
21948 					}
21949 				}
21950 			}
21951 		}
21952 		/*
21953 		 * Need to do this even when fragmenting. The local
21954 		 * loopback can be done without computing checksums
21955 		 * but forwarding out other interface must be done
21956 		 * after the IP checksum (and ULP checksums) have been
21957 		 * computed.
21958 		 *
21959 		 * NOTE : multicast_forward is set only if this packet
21960 		 * originated from ip_wput. For packets originating from
21961 		 * ip_wput_multicast, it is not set.
21962 		 */
21963 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
21964 		    multi_loopback:
21965 			ip2dbg(("ip_wput: multicast, loop %d\n",
21966 			    conn_multicast_loop));
21967 
21968 			/*  Forget header checksum offload */
21969 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
21970 
21971 			/*
21972 			 * Local loopback of multicasts?  Check the
21973 			 * ill.
21974 			 *
21975 			 * Note that the loopback function will not come
21976 			 * in through ip_rput - it will only do the
21977 			 * client fanout thus we need to do an mforward
21978 			 * as well.  The is different from the BSD
21979 			 * logic.
21980 			 */
21981 			if (ill != NULL) {
21982 				ilm_t	*ilm;
21983 
21984 				ILM_WALKER_HOLD(ill);
21985 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
21986 				    ALL_ZONES);
21987 				ILM_WALKER_RELE(ill);
21988 				if (ilm != NULL) {
21989 					/*
21990 					 * Pass along the virtual output q.
21991 					 * ip_wput_local() will distribute the
21992 					 * packet to all the matching zones,
21993 					 * except the sending zone when
21994 					 * IP_MULTICAST_LOOP is false.
21995 					 */
21996 					ip_multicast_loopback(q, ill, first_mp,
21997 					    conn_multicast_loop ? 0 :
21998 					    IP_FF_NO_MCAST_LOOP, zoneid);
21999 				}
22000 			}
22001 			if (ipha->ipha_ttl == 0) {
22002 				/*
22003 				 * 0 => only to this host i.e. we are
22004 				 * done. We are also done if this was the
22005 				 * loopback interface since it is sufficient
22006 				 * to loopback one copy of a multicast packet.
22007 				 */
22008 				freemsg(first_mp);
22009 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22010 				    "ip_wput_ire_end: q %p (%S)",
22011 				    q, "loopback");
22012 				ire_refrele(ire);
22013 				if (conn_outgoing_ill != NULL)
22014 					ill_refrele(conn_outgoing_ill);
22015 				return;
22016 			}
22017 			/*
22018 			 * ILLF_MULTICAST is checked in ip_newroute
22019 			 * i.e. we don't need to check it here since
22020 			 * all IRE_CACHEs come from ip_newroute.
22021 			 * For multicast traffic, SO_DONTROUTE is interpreted
22022 			 * to mean only send the packet out the interface
22023 			 * (optionally specified with IP_MULTICAST_IF)
22024 			 * and do not forward it out additional interfaces.
22025 			 * RSVP and the rsvp daemon is an example of a
22026 			 * protocol and user level process that
22027 			 * handles it's own routing. Hence, it uses the
22028 			 * SO_DONTROUTE option to accomplish this.
22029 			 */
22030 
22031 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22032 				/* Unconditionally redo the checksum */
22033 				ipha->ipha_hdr_checksum = 0;
22034 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22035 
22036 				/*
22037 				 * If this needs to go out secure, we need
22038 				 * to wait till we finish the IPSEC
22039 				 * processing.
22040 				 */
22041 				if (ipsec_len == 0 &&
22042 				    ip_mforward(ill, ipha, mp)) {
22043 					freemsg(first_mp);
22044 					ip1dbg(("ip_wput: mforward failed\n"));
22045 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22046 					    "ip_wput_ire_end: q %p (%S)",
22047 					    q, "mforward failed");
22048 					ire_refrele(ire);
22049 					if (conn_outgoing_ill != NULL)
22050 						ill_refrele(conn_outgoing_ill);
22051 					return;
22052 				}
22053 			}
22054 		}
22055 		max_frag = ire->ire_max_frag;
22056 		cksum += ttl_protocol;
22057 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22058 			/* No fragmentation required for this one. */
22059 			/*
22060 			 * Don't use frag_flag if packet is pre-built or source
22061 			 * routed or if multicast (since multicast packets do
22062 			 * not solicit ICMP "packet too big" messages).
22063 			 */
22064 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22065 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22066 			    !ip_source_route_included(ipha)) &&
22067 			    !CLASSD(ipha->ipha_dst))
22068 				ipha->ipha_fragment_offset_and_flags |=
22069 				    htons(ire->ire_frag_flag);
22070 
22071 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22072 				/* Complete the IP header checksum. */
22073 				cksum += ipha->ipha_ident;
22074 				cksum += (v_hlen_tos_len >> 16)+
22075 				    (v_hlen_tos_len & 0xFFFF);
22076 				cksum += ipha->ipha_fragment_offset_and_flags;
22077 				hlen = (V_HLEN & 0xF) -
22078 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22079 				if (hlen) {
22080 				    checksumoptions:
22081 					/*
22082 					 * Account for the IP Options in the IP
22083 					 * header checksum.
22084 					 */
22085 					up = (uint16_t *)(rptr+
22086 					    IP_SIMPLE_HDR_LENGTH);
22087 					do {
22088 						cksum += up[0];
22089 						cksum += up[1];
22090 						up += 2;
22091 					} while (--hlen);
22092 				}
22093 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22094 				cksum = ~(cksum + (cksum >> 16));
22095 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22096 			}
22097 			if (ipsec_len != 0) {
22098 				ipsec_out_process(q, first_mp, ire, ill_index);
22099 				if (!next_mp) {
22100 					ire_refrele(ire);
22101 					if (conn_outgoing_ill != NULL)
22102 						ill_refrele(conn_outgoing_ill);
22103 					return;
22104 				}
22105 				goto next;
22106 			}
22107 
22108 			/*
22109 			 * multirt_send has already been handled
22110 			 * for broadcast, but not yet for multicast
22111 			 * or IP options.
22112 			 */
22113 			if (next_mp == NULL) {
22114 				if (ire->ire_flags & RTF_MULTIRT) {
22115 					multirt_send = B_TRUE;
22116 				}
22117 			}
22118 
22119 			/*
22120 			 * In most cases, the emission loop below is
22121 			 * entered only once. Only in the case where
22122 			 * the ire holds the RTF_MULTIRT flag, do we loop
22123 			 * to process all RTF_MULTIRT ires in the bucket,
22124 			 * and send the packet through all crossed
22125 			 * RTF_MULTIRT routes.
22126 			 */
22127 			do {
22128 				if (multirt_send) {
22129 					irb_t *irb;
22130 
22131 					irb = ire->ire_bucket;
22132 					ASSERT(irb != NULL);
22133 					/*
22134 					 * We are in a multiple send case,
22135 					 * need to get the next IRE and make
22136 					 * a duplicate of the packet.
22137 					 */
22138 					IRB_REFHOLD(irb);
22139 					for (ire1 = ire->ire_next;
22140 					    ire1 != NULL;
22141 					    ire1 = ire1->ire_next) {
22142 						if (!(ire1->ire_flags &
22143 						    RTF_MULTIRT))
22144 							continue;
22145 						if (ire1->ire_addr !=
22146 						    ire->ire_addr)
22147 							continue;
22148 						if (ire1->ire_marks &
22149 						    (IRE_MARK_CONDEMNED|
22150 							IRE_MARK_HIDDEN))
22151 							continue;
22152 
22153 						/* Got one */
22154 						IRE_REFHOLD(ire1);
22155 						break;
22156 					}
22157 					IRB_REFRELE(irb);
22158 
22159 					if (ire1 != NULL) {
22160 						next_mp = copyb(mp);
22161 						if ((next_mp == NULL) ||
22162 						    ((mp->b_cont != NULL) &&
22163 						    ((next_mp->b_cont =
22164 						    dupmsg(mp->b_cont))
22165 						    == NULL))) {
22166 							freemsg(next_mp);
22167 							next_mp = NULL;
22168 							ire_refrele(ire1);
22169 							ire1 = NULL;
22170 						}
22171 					}
22172 
22173 					/*
22174 					 * Last multiroute ire; don't loop
22175 					 * anymore. The emission is over
22176 					 * and next_mp is NULL.
22177 					 */
22178 					if (ire1 == NULL) {
22179 						multirt_send = B_FALSE;
22180 					}
22181 				}
22182 
22183 				ASSERT(ipsec_len == 0);
22184 				mp->b_prev =
22185 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22186 				DTRACE_PROBE2(ip__xmit__2,
22187 				    mblk_t *, mp, ire_t *, ire);
22188 				pktxmit_state = ip_xmit_v4(mp, ire,
22189 				    NULL, B_TRUE);
22190 				if ((pktxmit_state == SEND_FAILED) ||
22191 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22192 					if (next_mp) {
22193 						freemsg(next_mp);
22194 						ire_refrele(ire1);
22195 					}
22196 					ire_refrele(ire);
22197 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22198 					    "ip_wput_ire_end: q %p (%S)",
22199 					    q, "discard MDATA");
22200 					if (conn_outgoing_ill != NULL)
22201 						ill_refrele(conn_outgoing_ill);
22202 					return;
22203 				}
22204 
22205 				if (multirt_send) {
22206 					/*
22207 					 * We are in a multiple send case,
22208 					 * need to re-enter the sending loop
22209 					 * using the next ire.
22210 					 */
22211 					ire_refrele(ire);
22212 					ire = ire1;
22213 					stq = ire->ire_stq;
22214 					mp = next_mp;
22215 					next_mp = NULL;
22216 					ipha = (ipha_t *)mp->b_rptr;
22217 					ill_index = Q_TO_INDEX(stq);
22218 				}
22219 			} while (multirt_send);
22220 
22221 			if (!next_mp) {
22222 				/*
22223 				 * Last copy going out (the ultra-common
22224 				 * case).  Note that we intentionally replicate
22225 				 * the putnext rather than calling it before
22226 				 * the next_mp check in hopes of a little
22227 				 * tail-call action out of the compiler.
22228 				 */
22229 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22230 				    "ip_wput_ire_end: q %p (%S)",
22231 				    q, "last copy out(1)");
22232 				ire_refrele(ire);
22233 				if (conn_outgoing_ill != NULL)
22234 					ill_refrele(conn_outgoing_ill);
22235 				return;
22236 			}
22237 			/* More copies going out below. */
22238 		} else {
22239 			int offset;
22240 		    fragmentit:
22241 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22242 			/*
22243 			 * If this would generate a icmp_frag_needed message,
22244 			 * we need to handle it before we do the IPSEC
22245 			 * processing. Otherwise, we need to strip the IPSEC
22246 			 * headers before we send up the message to the ULPs
22247 			 * which becomes messy and difficult.
22248 			 */
22249 			if (ipsec_len != 0) {
22250 				if ((max_frag < (unsigned int)(LENGTH +
22251 				    ipsec_len)) && (offset & IPH_DF)) {
22252 
22253 					BUMP_MIB(&ip_mib, ipFragFails);
22254 					ipha->ipha_hdr_checksum = 0;
22255 					ipha->ipha_hdr_checksum =
22256 					    (uint16_t)ip_csum_hdr(ipha);
22257 					icmp_frag_needed(ire->ire_stq, first_mp,
22258 					    max_frag);
22259 					if (!next_mp) {
22260 						ire_refrele(ire);
22261 						if (conn_outgoing_ill != NULL) {
22262 							ill_refrele(
22263 							    conn_outgoing_ill);
22264 						}
22265 						return;
22266 					}
22267 				} else {
22268 					/*
22269 					 * This won't cause a icmp_frag_needed
22270 					 * message. to be gnerated. Send it on
22271 					 * the wire. Note that this could still
22272 					 * cause fragmentation and all we
22273 					 * do is the generation of the message
22274 					 * to the ULP if needed before IPSEC.
22275 					 */
22276 					if (!next_mp) {
22277 						ipsec_out_process(q, first_mp,
22278 						    ire, ill_index);
22279 						TRACE_2(TR_FAC_IP,
22280 						    TR_IP_WPUT_IRE_END,
22281 						    "ip_wput_ire_end: q %p "
22282 						    "(%S)", q,
22283 						    "last ipsec_out_process");
22284 						ire_refrele(ire);
22285 						if (conn_outgoing_ill != NULL) {
22286 							ill_refrele(
22287 							    conn_outgoing_ill);
22288 						}
22289 						return;
22290 					}
22291 					ipsec_out_process(q, first_mp,
22292 					    ire, ill_index);
22293 				}
22294 			} else {
22295 				/*
22296 				 * Initiate IPPF processing. For
22297 				 * fragmentable packets we finish
22298 				 * all QOS packet processing before
22299 				 * calling:
22300 				 * ip_wput_ire_fragmentit->ip_wput_frag
22301 				 */
22302 
22303 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22304 					ip_process(IPP_LOCAL_OUT, &mp,
22305 					    ill_index);
22306 					if (mp == NULL) {
22307 						BUMP_MIB(&ip_mib,
22308 						    ipOutDiscards);
22309 						if (next_mp != NULL) {
22310 							freemsg(next_mp);
22311 							ire_refrele(ire1);
22312 						}
22313 						ire_refrele(ire);
22314 						TRACE_2(TR_FAC_IP,
22315 						    TR_IP_WPUT_IRE_END,
22316 						    "ip_wput_ire: q %p (%S)",
22317 						    q, "discard MDATA");
22318 						if (conn_outgoing_ill != NULL) {
22319 							ill_refrele(
22320 							    conn_outgoing_ill);
22321 						}
22322 						return;
22323 					}
22324 				}
22325 				if (!next_mp) {
22326 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22327 					    "ip_wput_ire_end: q %p (%S)",
22328 					    q, "last fragmentation");
22329 					ip_wput_ire_fragmentit(mp, ire);
22330 					ire_refrele(ire);
22331 					if (conn_outgoing_ill != NULL)
22332 						ill_refrele(conn_outgoing_ill);
22333 					return;
22334 				}
22335 				ip_wput_ire_fragmentit(mp, ire);
22336 			}
22337 		}
22338 	} else {
22339 	    nullstq:
22340 		/* A NULL stq means the destination address is local. */
22341 		UPDATE_OB_PKT_COUNT(ire);
22342 		ire->ire_last_used_time = lbolt;
22343 		ASSERT(ire->ire_ipif != NULL);
22344 		if (!next_mp) {
22345 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22346 			    "ip_wput_ire_end: q %p (%S)",
22347 			    q, "local address");
22348 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
22349 			    first_mp, ire, 0, ire->ire_zoneid);
22350 			ire_refrele(ire);
22351 			if (conn_outgoing_ill != NULL)
22352 				ill_refrele(conn_outgoing_ill);
22353 			return;
22354 		}
22355 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
22356 		    ire, 0, ire->ire_zoneid);
22357 	}
22358 next:
22359 	/*
22360 	 * More copies going out to additional interfaces.
22361 	 * ire1 has already been held. We don't need the
22362 	 * "ire" anymore.
22363 	 */
22364 	ire_refrele(ire);
22365 	ire = ire1;
22366 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
22367 	mp = next_mp;
22368 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
22369 	ill = ire_to_ill(ire);
22370 	first_mp = mp;
22371 	if (ipsec_len != 0) {
22372 		ASSERT(first_mp->b_datap->db_type == M_CTL);
22373 		mp = mp->b_cont;
22374 	}
22375 	dst = ire->ire_addr;
22376 	ipha = (ipha_t *)mp->b_rptr;
22377 	/*
22378 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
22379 	 * Restore ipha_ident "no checksum" flag.
22380 	 */
22381 	src = orig_src;
22382 	ipha->ipha_ident = ip_hdr_included;
22383 	goto another;
22384 
22385 #undef	rptr
22386 #undef	Q_TO_INDEX
22387 }
22388 
22389 /*
22390  * Routine to allocate a message that is used to notify the ULP about MDT.
22391  * The caller may provide a pointer to the link-layer MDT capabilities,
22392  * or NULL if MDT is to be disabled on the stream.
22393  */
22394 mblk_t *
22395 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
22396 {
22397 	mblk_t *mp;
22398 	ip_mdt_info_t *mdti;
22399 	ill_mdt_capab_t *idst;
22400 
22401 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
22402 		DB_TYPE(mp) = M_CTL;
22403 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
22404 		mdti = (ip_mdt_info_t *)mp->b_rptr;
22405 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
22406 		idst = &(mdti->mdt_capab);
22407 
22408 		/*
22409 		 * If the caller provides us with the capability, copy
22410 		 * it over into our notification message; otherwise
22411 		 * we zero out the capability portion.
22412 		 */
22413 		if (isrc != NULL)
22414 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22415 		else
22416 			bzero((caddr_t)idst, sizeof (*idst));
22417 	}
22418 	return (mp);
22419 }
22420 
22421 /*
22422  * Routine which determines whether MDT can be enabled on the destination
22423  * IRE and IPC combination, and if so, allocates and returns the MDT
22424  * notification mblk that may be used by ULP.  We also check if we need to
22425  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
22426  * MDT usage in the past have been lifted.  This gets called during IP
22427  * and ULP binding.
22428  */
22429 mblk_t *
22430 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22431     ill_mdt_capab_t *mdt_cap)
22432 {
22433 	mblk_t *mp;
22434 	boolean_t rc = B_FALSE;
22435 
22436 	ASSERT(dst_ire != NULL);
22437 	ASSERT(connp != NULL);
22438 	ASSERT(mdt_cap != NULL);
22439 
22440 	/*
22441 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
22442 	 * Multidata, which is handled in tcp_multisend().  This
22443 	 * is the reason why we do all these checks here, to ensure
22444 	 * that we don't enable Multidata for the cases which we
22445 	 * can't handle at the moment.
22446 	 */
22447 	do {
22448 		/* Only do TCP at the moment */
22449 		if (connp->conn_ulp != IPPROTO_TCP)
22450 			break;
22451 
22452 		/*
22453 		 * IPSEC outbound policy present?  Note that we get here
22454 		 * after calling ipsec_conn_cache_policy() where the global
22455 		 * policy checking is performed.  conn_latch will be
22456 		 * non-NULL as long as there's a policy defined,
22457 		 * i.e. conn_out_enforce_policy may be NULL in such case
22458 		 * when the connection is non-secure, and hence we check
22459 		 * further if the latch refers to an outbound policy.
22460 		 */
22461 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
22462 			break;
22463 
22464 		/* CGTP (multiroute) is enabled? */
22465 		if (dst_ire->ire_flags & RTF_MULTIRT)
22466 			break;
22467 
22468 		/* Outbound IPQoS enabled? */
22469 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22470 			/*
22471 			 * In this case, we disable MDT for this and all
22472 			 * future connections going over the interface.
22473 			 */
22474 			mdt_cap->ill_mdt_on = 0;
22475 			break;
22476 		}
22477 
22478 		/* socket option(s) present? */
22479 		if (!CONN_IS_MD_FASTPATH(connp))
22480 			break;
22481 
22482 		rc = B_TRUE;
22483 	/* CONSTCOND */
22484 	} while (0);
22485 
22486 	/* Remember the result */
22487 	connp->conn_mdt_ok = rc;
22488 
22489 	if (!rc)
22490 		return (NULL);
22491 	else if (!mdt_cap->ill_mdt_on) {
22492 		/*
22493 		 * If MDT has been previously turned off in the past, and we
22494 		 * currently can do MDT (due to IPQoS policy removal, etc.)
22495 		 * then enable it for this interface.
22496 		 */
22497 		mdt_cap->ill_mdt_on = 1;
22498 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
22499 		    "interface %s\n", ill_name));
22500 	}
22501 
22502 	/* Allocate the MDT info mblk */
22503 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
22504 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
22505 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
22506 		return (NULL);
22507 	}
22508 	return (mp);
22509 }
22510 
22511 /*
22512  * Create destination address attribute, and fill it with the physical
22513  * destination address and SAP taken from the template DL_UNITDATA_REQ
22514  * message block.
22515  */
22516 boolean_t
22517 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
22518 {
22519 	dl_unitdata_req_t *dlurp;
22520 	pattr_t *pa;
22521 	pattrinfo_t pa_info;
22522 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
22523 	uint_t das_len, das_off;
22524 
22525 	ASSERT(dlmp != NULL);
22526 
22527 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
22528 	das_len = dlurp->dl_dest_addr_length;
22529 	das_off = dlurp->dl_dest_addr_offset;
22530 
22531 	pa_info.type = PATTR_DSTADDRSAP;
22532 	pa_info.len = sizeof (**das) + das_len - 1;
22533 
22534 	/* create and associate the attribute */
22535 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22536 	if (pa != NULL) {
22537 		ASSERT(*das != NULL);
22538 		(*das)->addr_is_group = 0;
22539 		(*das)->addr_len = (uint8_t)das_len;
22540 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
22541 	}
22542 
22543 	return (pa != NULL);
22544 }
22545 
22546 /*
22547  * Create hardware checksum attribute and fill it with the values passed.
22548  */
22549 boolean_t
22550 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
22551     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
22552 {
22553 	pattr_t *pa;
22554 	pattrinfo_t pa_info;
22555 
22556 	ASSERT(mmd != NULL);
22557 
22558 	pa_info.type = PATTR_HCKSUM;
22559 	pa_info.len = sizeof (pattr_hcksum_t);
22560 
22561 	/* create and associate the attribute */
22562 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22563 	if (pa != NULL) {
22564 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
22565 
22566 		hck->hcksum_start_offset = start_offset;
22567 		hck->hcksum_stuff_offset = stuff_offset;
22568 		hck->hcksum_end_offset = end_offset;
22569 		hck->hcksum_flags = flags;
22570 	}
22571 	return (pa != NULL);
22572 }
22573 
22574 /*
22575  * Create zerocopy attribute and fill it with the specified flags
22576  */
22577 boolean_t
22578 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
22579 {
22580 	pattr_t *pa;
22581 	pattrinfo_t pa_info;
22582 
22583 	ASSERT(mmd != NULL);
22584 	pa_info.type = PATTR_ZCOPY;
22585 	pa_info.len = sizeof (pattr_zcopy_t);
22586 
22587 	/* create and associate the attribute */
22588 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22589 	if (pa != NULL) {
22590 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
22591 
22592 		zcopy->zcopy_flags = flags;
22593 	}
22594 	return (pa != NULL);
22595 }
22596 
22597 /*
22598  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
22599  * block chain. We could rewrite to handle arbitrary message block chains but
22600  * that would make the code complicated and slow. Right now there three
22601  * restrictions:
22602  *
22603  *   1. The first message block must contain the complete IP header and
22604  *	at least 1 byte of payload data.
22605  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
22606  *	so that we can use a single Multidata message.
22607  *   3. No frag must be distributed over two or more message blocks so
22608  *	that we don't need more than two packet descriptors per frag.
22609  *
22610  * The above restrictions allow us to support userland applications (which
22611  * will send down a single message block) and NFS over UDP (which will
22612  * send down a chain of at most three message blocks).
22613  *
22614  * We also don't use MDT for payloads with less than or equal to
22615  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
22616  */
22617 boolean_t
22618 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
22619 {
22620 	int	blocks;
22621 	ssize_t	total, missing, size;
22622 
22623 	ASSERT(mp != NULL);
22624 	ASSERT(hdr_len > 0);
22625 
22626 	size = MBLKL(mp) - hdr_len;
22627 	if (size <= 0)
22628 		return (B_FALSE);
22629 
22630 	/* The first mblk contains the header and some payload. */
22631 	blocks = 1;
22632 	total = size;
22633 	size %= len;
22634 	missing = (size == 0) ? 0 : (len - size);
22635 	mp = mp->b_cont;
22636 
22637 	while (mp != NULL) {
22638 		/*
22639 		 * Give up if we encounter a zero length message block.
22640 		 * In practice, this should rarely happen and therefore
22641 		 * not worth the trouble of freeing and re-linking the
22642 		 * mblk from the chain to handle such case.
22643 		 */
22644 		if ((size = MBLKL(mp)) == 0)
22645 			return (B_FALSE);
22646 
22647 		/* Too many payload buffers for a single Multidata message? */
22648 		if (++blocks > MULTIDATA_MAX_PBUFS)
22649 			return (B_FALSE);
22650 
22651 		total += size;
22652 		/* Is a frag distributed over two or more message blocks? */
22653 		if (missing > size)
22654 			return (B_FALSE);
22655 		size -= missing;
22656 
22657 		size %= len;
22658 		missing = (size == 0) ? 0 : (len - size);
22659 
22660 		mp = mp->b_cont;
22661 	}
22662 
22663 	return (total > ip_wput_frag_mdt_min);
22664 }
22665 
22666 /*
22667  * Outbound IPv4 fragmentation routine using MDT.
22668  */
22669 static void
22670 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
22671     uint32_t frag_flag, int offset)
22672 {
22673 	ipha_t		*ipha_orig;
22674 	int		i1, ip_data_end;
22675 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
22676 	mblk_t		*hdr_mp, *md_mp = NULL;
22677 	unsigned char	*hdr_ptr, *pld_ptr;
22678 	multidata_t	*mmd;
22679 	ip_pdescinfo_t	pdi;
22680 
22681 	ASSERT(DB_TYPE(mp) == M_DATA);
22682 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
22683 
22684 	ipha_orig = (ipha_t *)mp->b_rptr;
22685 	mp->b_rptr += sizeof (ipha_t);
22686 
22687 	/* Calculate how many packets we will send out */
22688 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
22689 	pkts = (i1 + len - 1) / len;
22690 	ASSERT(pkts > 1);
22691 
22692 	/* Allocate a message block which will hold all the IP Headers. */
22693 	wroff = ip_wroff_extra;
22694 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
22695 
22696 	i1 = pkts * hdr_chunk_len;
22697 	/*
22698 	 * Create the header buffer, Multidata and destination address
22699 	 * and SAP attribute that should be associated with it.
22700 	 */
22701 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
22702 	    ((hdr_mp->b_wptr += i1),
22703 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
22704 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
22705 		freemsg(mp);
22706 		if (md_mp == NULL) {
22707 			freemsg(hdr_mp);
22708 		} else {
22709 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
22710 			freemsg(md_mp);
22711 		}
22712 		IP_STAT(ip_frag_mdt_allocfail);
22713 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
22714 		return;
22715 	}
22716 	IP_STAT(ip_frag_mdt_allocd);
22717 
22718 	/*
22719 	 * Add a payload buffer to the Multidata; this operation must not
22720 	 * fail, or otherwise our logic in this routine is broken.  There
22721 	 * is no memory allocation done by the routine, so any returned
22722 	 * failure simply tells us that we've done something wrong.
22723 	 *
22724 	 * A failure tells us that either we're adding the same payload
22725 	 * buffer more than once, or we're trying to add more buffers than
22726 	 * allowed.  None of the above cases should happen, and we panic
22727 	 * because either there's horrible heap corruption, and/or
22728 	 * programming mistake.
22729 	 */
22730 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22731 		goto pbuf_panic;
22732 
22733 	hdr_ptr = hdr_mp->b_rptr;
22734 	pld_ptr = mp->b_rptr;
22735 
22736 	/* Establish the ending byte offset, based on the starting offset. */
22737 	offset <<= 3;
22738 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
22739 	    IP_SIMPLE_HDR_LENGTH;
22740 
22741 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
22742 
22743 	while (pld_ptr < mp->b_wptr) {
22744 		ipha_t		*ipha;
22745 		uint16_t	offset_and_flags;
22746 		uint16_t	ip_len;
22747 		int		error;
22748 
22749 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
22750 		ipha = (ipha_t *)(hdr_ptr + wroff);
22751 		ASSERT(OK_32PTR(ipha));
22752 		*ipha = *ipha_orig;
22753 
22754 		if (ip_data_end - offset > len) {
22755 			offset_and_flags = IPH_MF;
22756 		} else {
22757 			/*
22758 			 * Last frag. Set len to the length of this last piece.
22759 			 */
22760 			len = ip_data_end - offset;
22761 			/* A frag of a frag might have IPH_MF non-zero */
22762 			offset_and_flags =
22763 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22764 			    IPH_MF;
22765 		}
22766 		offset_and_flags |= (uint16_t)(offset >> 3);
22767 		offset_and_flags |= (uint16_t)frag_flag;
22768 		/* Store the offset and flags in the IP header. */
22769 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22770 
22771 		/* Store the length in the IP header. */
22772 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
22773 		ipha->ipha_length = htons(ip_len);
22774 
22775 		/*
22776 		 * Set the IP header checksum.  Note that mp is just
22777 		 * the header, so this is easy to pass to ip_csum.
22778 		 */
22779 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22780 
22781 		/*
22782 		 * Record offset and size of header and data of the next packet
22783 		 * in the multidata message.
22784 		 */
22785 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
22786 		PDESC_PLD_INIT(&pdi);
22787 		i1 = MIN(mp->b_wptr - pld_ptr, len);
22788 		ASSERT(i1 > 0);
22789 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
22790 		if (i1 == len) {
22791 			pld_ptr += len;
22792 		} else {
22793 			i1 = len - i1;
22794 			mp = mp->b_cont;
22795 			ASSERT(mp != NULL);
22796 			ASSERT(MBLKL(mp) >= i1);
22797 			/*
22798 			 * Attach the next payload message block to the
22799 			 * multidata message.
22800 			 */
22801 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22802 				goto pbuf_panic;
22803 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
22804 			pld_ptr = mp->b_rptr + i1;
22805 		}
22806 
22807 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
22808 		    KM_NOSLEEP)) == NULL) {
22809 			/*
22810 			 * Any failure other than ENOMEM indicates that we
22811 			 * have passed in invalid pdesc info or parameters
22812 			 * to mmd_addpdesc, which must not happen.
22813 			 *
22814 			 * EINVAL is a result of failure on boundary checks
22815 			 * against the pdesc info contents.  It should not
22816 			 * happen, and we panic because either there's
22817 			 * horrible heap corruption, and/or programming
22818 			 * mistake.
22819 			 */
22820 			if (error != ENOMEM) {
22821 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
22822 				    "pdesc logic error detected for "
22823 				    "mmd %p pinfo %p (%d)\n",
22824 				    (void *)mmd, (void *)&pdi, error);
22825 				/* NOTREACHED */
22826 			}
22827 			IP_STAT(ip_frag_mdt_addpdescfail);
22828 			/* Free unattached payload message blocks as well */
22829 			md_mp->b_cont = mp->b_cont;
22830 			goto free_mmd;
22831 		}
22832 
22833 		/* Advance fragment offset. */
22834 		offset += len;
22835 
22836 		/* Advance to location for next header in the buffer. */
22837 		hdr_ptr += hdr_chunk_len;
22838 
22839 		/* Did we reach the next payload message block? */
22840 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
22841 			mp = mp->b_cont;
22842 			/*
22843 			 * Attach the next message block with payload
22844 			 * data to the multidata message.
22845 			 */
22846 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22847 				goto pbuf_panic;
22848 			pld_ptr = mp->b_rptr;
22849 		}
22850 	}
22851 
22852 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
22853 	ASSERT(mp->b_wptr == pld_ptr);
22854 
22855 	/* Update IP statistics */
22856 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
22857 	BUMP_MIB(&ip_mib, ipFragOKs);
22858 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
22859 
22860 	if (pkt_type == OB_PKT) {
22861 		ire->ire_ob_pkt_count += pkts;
22862 		if (ire->ire_ipif != NULL)
22863 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
22864 	} else {
22865 		/*
22866 		 * The type is IB_PKT in the forwarding path and in
22867 		 * the mobile IP case when the packet is being reverse-
22868 		 * tunneled to the home agent.
22869 		 */
22870 		ire->ire_ib_pkt_count += pkts;
22871 		ASSERT(!IRE_IS_LOCAL(ire));
22872 		if (ire->ire_type & IRE_BROADCAST)
22873 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
22874 		else
22875 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
22876 	}
22877 	ire->ire_last_used_time = lbolt;
22878 	/* Send it down */
22879 	putnext(ire->ire_stq, md_mp);
22880 	return;
22881 
22882 pbuf_panic:
22883 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
22884 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
22885 	    pbuf_idx);
22886 	/* NOTREACHED */
22887 }
22888 
22889 /*
22890  * Outbound IP fragmentation routine.
22891  *
22892  * NOTE : This routine does not ire_refrele the ire that is passed in
22893  * as the argument.
22894  */
22895 static void
22896 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
22897     uint32_t frag_flag)
22898 {
22899 	int		i1;
22900 	mblk_t		*ll_hdr_mp;
22901 	int 		ll_hdr_len;
22902 	int		hdr_len;
22903 	mblk_t		*hdr_mp;
22904 	ipha_t		*ipha;
22905 	int		ip_data_end;
22906 	int		len;
22907 	mblk_t		*mp = mp_orig;
22908 	int		offset;
22909 	queue_t		*q;
22910 	uint32_t	v_hlen_tos_len;
22911 	mblk_t		*first_mp;
22912 	boolean_t	mctl_present;
22913 	ill_t		*ill;
22914 	mblk_t		*xmit_mp;
22915 	mblk_t		*carve_mp;
22916 	ire_t		*ire1 = NULL;
22917 	ire_t		*save_ire = NULL;
22918 	mblk_t  	*next_mp = NULL;
22919 	boolean_t	last_frag = B_FALSE;
22920 	boolean_t	multirt_send = B_FALSE;
22921 	ire_t		*first_ire = NULL;
22922 	irb_t		*irb = NULL;
22923 
22924 	/*
22925 	 * IPSEC does not allow hw accelerated packets to be fragmented
22926 	 * This check is made in ip_wput_ipsec_out prior to coming here
22927 	 * via ip_wput_ire_fragmentit.
22928 	 *
22929 	 * If at this point we have an ire whose ARP request has not
22930 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
22931 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
22932 	 * This packet and all fragmentable packets for this ire will
22933 	 * continue to get dropped while ire_nce->nce_state remains in
22934 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
22935 	 * ND_REACHABLE, all subsquent large packets for this ire will
22936 	 * get fragemented and sent out by this function.
22937 	 */
22938 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
22939 		/* If nce_state is ND_INITIAL, trigger ARP query */
22940 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
22941 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
22942 		    " -  dropping packet\n"));
22943 		BUMP_MIB(&ip_mib, ipFragFails);
22944 		freemsg(mp);
22945 		return;
22946 	}
22947 
22948 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
22949 	    "ip_wput_frag_start:");
22950 
22951 	if (mp->b_datap->db_type == M_CTL) {
22952 		first_mp = mp;
22953 		mp_orig = mp = mp->b_cont;
22954 		mctl_present = B_TRUE;
22955 	} else {
22956 		first_mp = mp;
22957 		mctl_present = B_FALSE;
22958 	}
22959 
22960 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
22961 	ipha = (ipha_t *)mp->b_rptr;
22962 
22963 	/*
22964 	 * If the Don't Fragment flag is on, generate an ICMP destination
22965 	 * unreachable, fragmentation needed.
22966 	 */
22967 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22968 	if (offset & IPH_DF) {
22969 		BUMP_MIB(&ip_mib, ipFragFails);
22970 		/*
22971 		 * Need to compute hdr checksum if called from ip_wput_ire.
22972 		 * Note that ip_rput_forward verifies the checksum before
22973 		 * calling this routine so in that case this is a noop.
22974 		 */
22975 		ipha->ipha_hdr_checksum = 0;
22976 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22977 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
22978 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22979 		    "ip_wput_frag_end:(%S)",
22980 		    "don't fragment");
22981 		return;
22982 	}
22983 	if (mctl_present)
22984 		freeb(first_mp);
22985 	/*
22986 	 * Establish the starting offset.  May not be zero if we are fragging
22987 	 * a fragment that is being forwarded.
22988 	 */
22989 	offset = offset & IPH_OFFSET;
22990 
22991 	/* TODO why is this test needed? */
22992 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22993 	if (((max_frag - LENGTH) & ~7) < 8) {
22994 		/* TODO: notify ulp somehow */
22995 		BUMP_MIB(&ip_mib, ipFragFails);
22996 		freemsg(mp);
22997 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22998 		    "ip_wput_frag_end:(%S)",
22999 		    "len < 8");
23000 		return;
23001 	}
23002 
23003 	hdr_len = (V_HLEN & 0xF) << 2;
23004 
23005 	ipha->ipha_hdr_checksum = 0;
23006 
23007 	/*
23008 	 * Establish the number of bytes maximum per frag, after putting
23009 	 * in the header.
23010 	 */
23011 	len = (max_frag - hdr_len) & ~7;
23012 
23013 	/* Check if we can use MDT to send out the frags. */
23014 	ASSERT(!IRE_IS_LOCAL(ire));
23015 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
23016 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
23017 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
23018 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23019 		ASSERT(ill->ill_mdt_capab != NULL);
23020 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23021 			/*
23022 			 * If MDT has been previously turned off in the past,
23023 			 * and we currently can do MDT (due to IPQoS policy
23024 			 * removal, etc.) then enable it for this interface.
23025 			 */
23026 			ill->ill_mdt_capab->ill_mdt_on = 1;
23027 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23028 			    ill->ill_name));
23029 		}
23030 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23031 		    offset);
23032 		return;
23033 	}
23034 
23035 	/* Get a copy of the header for the trailing frags */
23036 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
23037 	if (!hdr_mp) {
23038 		BUMP_MIB(&ip_mib, ipOutDiscards);
23039 		freemsg(mp);
23040 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23041 		    "ip_wput_frag_end:(%S)",
23042 		    "couldn't copy hdr");
23043 		return;
23044 	}
23045 	if (DB_CRED(mp) != NULL)
23046 		mblk_setcred(hdr_mp, DB_CRED(mp));
23047 
23048 	/* Store the starting offset, with the MoreFrags flag. */
23049 	i1 = offset | IPH_MF | frag_flag;
23050 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23051 
23052 	/* Establish the ending byte offset, based on the starting offset. */
23053 	offset <<= 3;
23054 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23055 
23056 	/* Store the length of the first fragment in the IP header. */
23057 	i1 = len + hdr_len;
23058 	ASSERT(i1 <= IP_MAXPACKET);
23059 	ipha->ipha_length = htons((uint16_t)i1);
23060 
23061 	/*
23062 	 * Compute the IP header checksum for the first frag.  We have to
23063 	 * watch out that we stop at the end of the header.
23064 	 */
23065 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23066 
23067 	/*
23068 	 * Now carve off the first frag.  Note that this will include the
23069 	 * original IP header.
23070 	 */
23071 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
23072 		BUMP_MIB(&ip_mib, ipOutDiscards);
23073 		freeb(hdr_mp);
23074 		freemsg(mp_orig);
23075 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23076 		    "ip_wput_frag_end:(%S)",
23077 		    "couldn't carve first");
23078 		return;
23079 	}
23080 
23081 	/*
23082 	 * Multirouting case. Each fragment is replicated
23083 	 * via all non-condemned RTF_MULTIRT routes
23084 	 * currently resolved.
23085 	 * We ensure that first_ire is the first RTF_MULTIRT
23086 	 * ire in the bucket.
23087 	 */
23088 	if (ire->ire_flags & RTF_MULTIRT) {
23089 		irb = ire->ire_bucket;
23090 		ASSERT(irb != NULL);
23091 
23092 		multirt_send = B_TRUE;
23093 
23094 		/* Make sure we do not omit any multiroute ire. */
23095 		IRB_REFHOLD(irb);
23096 		for (first_ire = irb->irb_ire;
23097 		    first_ire != NULL;
23098 		    first_ire = first_ire->ire_next) {
23099 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23100 			    (first_ire->ire_addr == ire->ire_addr) &&
23101 			    !(first_ire->ire_marks &
23102 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23103 				break;
23104 		}
23105 
23106 		if (first_ire != NULL) {
23107 			if (first_ire != ire) {
23108 				IRE_REFHOLD(first_ire);
23109 				/*
23110 				 * Do not release the ire passed in
23111 				 * as the argument.
23112 				 */
23113 				ire = first_ire;
23114 			} else {
23115 				first_ire = NULL;
23116 			}
23117 		}
23118 		IRB_REFRELE(irb);
23119 
23120 		/*
23121 		 * Save the first ire; we will need to restore it
23122 		 * for the trailing frags.
23123 		 * We REFHOLD save_ire, as each iterated ire will be
23124 		 * REFRELEd.
23125 		 */
23126 		save_ire = ire;
23127 		IRE_REFHOLD(save_ire);
23128 	}
23129 
23130 	/*
23131 	 * First fragment emission loop.
23132 	 * In most cases, the emission loop below is entered only
23133 	 * once. Only in the case where the ire holds the RTF_MULTIRT
23134 	 * flag, do we loop to process all RTF_MULTIRT ires in the
23135 	 * bucket, and send the fragment through all crossed
23136 	 * RTF_MULTIRT routes.
23137 	 */
23138 	do {
23139 		if (ire->ire_flags & RTF_MULTIRT) {
23140 			/*
23141 			 * We are in a multiple send case, need to get
23142 			 * the next ire and make a copy of the packet.
23143 			 * ire1 holds here the next ire to process in the
23144 			 * bucket. If multirouting is expected,
23145 			 * any non-RTF_MULTIRT ire that has the
23146 			 * right destination address is ignored.
23147 			 *
23148 			 * We have to take into account the MTU of
23149 			 * each walked ire. max_frag is set by the
23150 			 * the caller and generally refers to
23151 			 * the primary ire entry. Here we ensure that
23152 			 * no route with a lower MTU will be used, as
23153 			 * fragments are carved once for all ires,
23154 			 * then replicated.
23155 			 */
23156 			ASSERT(irb != NULL);
23157 			IRB_REFHOLD(irb);
23158 			for (ire1 = ire->ire_next;
23159 			    ire1 != NULL;
23160 			    ire1 = ire1->ire_next) {
23161 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23162 					continue;
23163 				if (ire1->ire_addr != ire->ire_addr)
23164 					continue;
23165 				if (ire1->ire_marks &
23166 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23167 					continue;
23168 				/*
23169 				 * Ensure we do not exceed the MTU
23170 				 * of the next route.
23171 				 */
23172 				if (ire1->ire_max_frag < max_frag) {
23173 					ip_multirt_bad_mtu(ire1, max_frag);
23174 					continue;
23175 				}
23176 
23177 				/* Got one. */
23178 				IRE_REFHOLD(ire1);
23179 				break;
23180 			}
23181 			IRB_REFRELE(irb);
23182 
23183 			if (ire1 != NULL) {
23184 				next_mp = copyb(mp);
23185 				if ((next_mp == NULL) ||
23186 				    ((mp->b_cont != NULL) &&
23187 				    ((next_mp->b_cont =
23188 				    dupmsg(mp->b_cont)) == NULL))) {
23189 					freemsg(next_mp);
23190 					next_mp = NULL;
23191 					ire_refrele(ire1);
23192 					ire1 = NULL;
23193 				}
23194 			}
23195 
23196 			/* Last multiroute ire; don't loop anymore. */
23197 			if (ire1 == NULL) {
23198 				multirt_send = B_FALSE;
23199 			}
23200 		}
23201 
23202 		ll_hdr_len = 0;
23203 		LOCK_IRE_FP_MP(ire);
23204 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23205 		if (ll_hdr_mp != NULL) {
23206 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23207 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
23208 		} else {
23209 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
23210 		}
23211 
23212 		/* If there is a transmit header, get a copy for this frag. */
23213 		/*
23214 		 * TODO: should check db_ref before calling ip_carve_mp since
23215 		 * it might give us a dup.
23216 		 */
23217 		if (!ll_hdr_mp) {
23218 			/* No xmit header. */
23219 			xmit_mp = mp;
23220 
23221 		/* We have a link-layer header that can fit in our mblk. */
23222 		} else if (mp->b_datap->db_ref == 1 &&
23223 		    ll_hdr_len != 0 &&
23224 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23225 			/* M_DATA fastpath */
23226 			mp->b_rptr -= ll_hdr_len;
23227 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
23228 			xmit_mp = mp;
23229 
23230 		/* Corner case if copyb has failed */
23231 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
23232 			UNLOCK_IRE_FP_MP(ire);
23233 			BUMP_MIB(&ip_mib, ipOutDiscards);
23234 			freeb(hdr_mp);
23235 			freemsg(mp);
23236 			freemsg(mp_orig);
23237 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23238 			    "ip_wput_frag_end:(%S)",
23239 			    "discard");
23240 
23241 			if (multirt_send) {
23242 				ASSERT(ire1);
23243 				ASSERT(next_mp);
23244 
23245 				freemsg(next_mp);
23246 				ire_refrele(ire1);
23247 			}
23248 			if (save_ire != NULL)
23249 				IRE_REFRELE(save_ire);
23250 
23251 			if (first_ire != NULL)
23252 				ire_refrele(first_ire);
23253 			return;
23254 
23255 		/*
23256 		 * Case of res_mp OR the fastpath mp can't fit
23257 		 * in the mblk
23258 		 */
23259 		} else {
23260 			xmit_mp->b_cont = mp;
23261 			if (DB_CRED(mp) != NULL)
23262 				mblk_setcred(xmit_mp, DB_CRED(mp));
23263 			/*
23264 			 * Get priority marking, if any.
23265 			 * We propagate the CoS marking from the
23266 			 * original packet that went to QoS processing
23267 			 * in ip_wput_ire to the newly carved mp.
23268 			 */
23269 			if (DB_TYPE(xmit_mp) == M_DATA)
23270 				xmit_mp->b_band = mp->b_band;
23271 		}
23272 		UNLOCK_IRE_FP_MP(ire);
23273 		q = ire->ire_stq;
23274 		BUMP_MIB(&ip_mib, ipFragCreates);
23275 		putnext(q, xmit_mp);
23276 		if (pkt_type != OB_PKT) {
23277 			/*
23278 			 * Update the packet count of trailing
23279 			 * RTF_MULTIRT ires.
23280 			 */
23281 			UPDATE_OB_PKT_COUNT(ire);
23282 		}
23283 
23284 		if (multirt_send) {
23285 			/*
23286 			 * We are in a multiple send case; look for
23287 			 * the next ire and re-enter the loop.
23288 			 */
23289 			ASSERT(ire1);
23290 			ASSERT(next_mp);
23291 			/* REFRELE the current ire before looping */
23292 			ire_refrele(ire);
23293 			ire = ire1;
23294 			ire1 = NULL;
23295 			mp = next_mp;
23296 			next_mp = NULL;
23297 		}
23298 	} while (multirt_send);
23299 
23300 	ASSERT(ire1 == NULL);
23301 
23302 	/* Restore the original ire; we need it for the trailing frags */
23303 	if (save_ire != NULL) {
23304 		/* REFRELE the last iterated ire */
23305 		ire_refrele(ire);
23306 		/* save_ire has been REFHOLDed */
23307 		ire = save_ire;
23308 		save_ire = NULL;
23309 		q = ire->ire_stq;
23310 	}
23311 
23312 	if (pkt_type == OB_PKT) {
23313 		UPDATE_OB_PKT_COUNT(ire);
23314 	} else {
23315 		UPDATE_IB_PKT_COUNT(ire);
23316 	}
23317 
23318 	/* Advance the offset to the second frag starting point. */
23319 	offset += len;
23320 	/*
23321 	 * Update hdr_len from the copied header - there might be less options
23322 	 * in the later fragments.
23323 	 */
23324 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
23325 	/* Loop until done. */
23326 	for (;;) {
23327 		uint16_t	offset_and_flags;
23328 		uint16_t	ip_len;
23329 
23330 		if (ip_data_end - offset > len) {
23331 			/*
23332 			 * Carve off the appropriate amount from the original
23333 			 * datagram.
23334 			 */
23335 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23336 				mp = NULL;
23337 				break;
23338 			}
23339 			/*
23340 			 * More frags after this one.  Get another copy
23341 			 * of the header.
23342 			 */
23343 			if (carve_mp->b_datap->db_ref == 1 &&
23344 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23345 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23346 				/* Inline IP header */
23347 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23348 				    hdr_mp->b_rptr;
23349 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23350 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23351 				mp = carve_mp;
23352 			} else {
23353 				if (!(mp = copyb(hdr_mp))) {
23354 					freemsg(carve_mp);
23355 					break;
23356 				}
23357 				/* Get priority marking, if any. */
23358 				mp->b_band = carve_mp->b_band;
23359 				mp->b_cont = carve_mp;
23360 			}
23361 			ipha = (ipha_t *)mp->b_rptr;
23362 			offset_and_flags = IPH_MF;
23363 		} else {
23364 			/*
23365 			 * Last frag.  Consume the header. Set len to
23366 			 * the length of this last piece.
23367 			 */
23368 			len = ip_data_end - offset;
23369 
23370 			/*
23371 			 * Carve off the appropriate amount from the original
23372 			 * datagram.
23373 			 */
23374 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23375 				mp = NULL;
23376 				break;
23377 			}
23378 			if (carve_mp->b_datap->db_ref == 1 &&
23379 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23380 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23381 				/* Inline IP header */
23382 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23383 				    hdr_mp->b_rptr;
23384 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23385 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23386 				mp = carve_mp;
23387 				freeb(hdr_mp);
23388 				hdr_mp = mp;
23389 			} else {
23390 				mp = hdr_mp;
23391 				/* Get priority marking, if any. */
23392 				mp->b_band = carve_mp->b_band;
23393 				mp->b_cont = carve_mp;
23394 			}
23395 			ipha = (ipha_t *)mp->b_rptr;
23396 			/* A frag of a frag might have IPH_MF non-zero */
23397 			offset_and_flags =
23398 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23399 			    IPH_MF;
23400 		}
23401 		offset_and_flags |= (uint16_t)(offset >> 3);
23402 		offset_and_flags |= (uint16_t)frag_flag;
23403 		/* Store the offset and flags in the IP header. */
23404 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23405 
23406 		/* Store the length in the IP header. */
23407 		ip_len = (uint16_t)(len + hdr_len);
23408 		ipha->ipha_length = htons(ip_len);
23409 
23410 		/*
23411 		 * Set the IP header checksum.	Note that mp is just
23412 		 * the header, so this is easy to pass to ip_csum.
23413 		 */
23414 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23415 
23416 		/* Attach a transmit header, if any, and ship it. */
23417 		if (pkt_type == OB_PKT) {
23418 			UPDATE_OB_PKT_COUNT(ire);
23419 		} else {
23420 			UPDATE_IB_PKT_COUNT(ire);
23421 		}
23422 
23423 		if (ire->ire_flags & RTF_MULTIRT) {
23424 			irb = ire->ire_bucket;
23425 			ASSERT(irb != NULL);
23426 
23427 			multirt_send = B_TRUE;
23428 
23429 			/*
23430 			 * Save the original ire; we will need to restore it
23431 			 * for the tailing frags.
23432 			 */
23433 			save_ire = ire;
23434 			IRE_REFHOLD(save_ire);
23435 		}
23436 		/*
23437 		 * Emission loop for this fragment, similar
23438 		 * to what is done for the first fragment.
23439 		 */
23440 		do {
23441 			if (multirt_send) {
23442 				/*
23443 				 * We are in a multiple send case, need to get
23444 				 * the next ire and make a copy of the packet.
23445 				 */
23446 				ASSERT(irb != NULL);
23447 				IRB_REFHOLD(irb);
23448 				for (ire1 = ire->ire_next;
23449 				    ire1 != NULL;
23450 				    ire1 = ire1->ire_next) {
23451 					if (!(ire1->ire_flags & RTF_MULTIRT))
23452 						continue;
23453 					if (ire1->ire_addr != ire->ire_addr)
23454 						continue;
23455 					if (ire1->ire_marks &
23456 					    (IRE_MARK_CONDEMNED|
23457 						IRE_MARK_HIDDEN))
23458 						continue;
23459 					/*
23460 					 * Ensure we do not exceed the MTU
23461 					 * of the next route.
23462 					 */
23463 					if (ire1->ire_max_frag < max_frag) {
23464 						ip_multirt_bad_mtu(ire1,
23465 						    max_frag);
23466 						continue;
23467 					}
23468 
23469 					/* Got one. */
23470 					IRE_REFHOLD(ire1);
23471 					break;
23472 				}
23473 				IRB_REFRELE(irb);
23474 
23475 				if (ire1 != NULL) {
23476 					next_mp = copyb(mp);
23477 					if ((next_mp == NULL) ||
23478 					    ((mp->b_cont != NULL) &&
23479 					    ((next_mp->b_cont =
23480 					    dupmsg(mp->b_cont)) == NULL))) {
23481 						freemsg(next_mp);
23482 						next_mp = NULL;
23483 						ire_refrele(ire1);
23484 						ire1 = NULL;
23485 					}
23486 				}
23487 
23488 				/* Last multiroute ire; don't loop anymore. */
23489 				if (ire1 == NULL) {
23490 					multirt_send = B_FALSE;
23491 				}
23492 			}
23493 
23494 			/* Update transmit header */
23495 			ll_hdr_len = 0;
23496 			LOCK_IRE_FP_MP(ire);
23497 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23498 			if (ll_hdr_mp != NULL) {
23499 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23500 				ll_hdr_len = MBLKL(ll_hdr_mp);
23501 			} else {
23502 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
23503 			}
23504 
23505 			if (!ll_hdr_mp) {
23506 				xmit_mp = mp;
23507 
23508 			/*
23509 			 * We have link-layer header that can fit in
23510 			 * our mblk.
23511 			 */
23512 			} else if (mp->b_datap->db_ref == 1 &&
23513 			    ll_hdr_len != 0 &&
23514 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23515 				/* M_DATA fastpath */
23516 				mp->b_rptr -= ll_hdr_len;
23517 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
23518 				    ll_hdr_len);
23519 				xmit_mp = mp;
23520 
23521 			/*
23522 			 * Case of res_mp OR the fastpath mp can't fit
23523 			 * in the mblk
23524 			 */
23525 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
23526 				xmit_mp->b_cont = mp;
23527 				if (DB_CRED(mp) != NULL)
23528 					mblk_setcred(xmit_mp, DB_CRED(mp));
23529 				/* Get priority marking, if any. */
23530 				if (DB_TYPE(xmit_mp) == M_DATA)
23531 					xmit_mp->b_band = mp->b_band;
23532 
23533 			/* Corner case if copyb failed */
23534 			} else {
23535 				/*
23536 				 * Exit both the replication and
23537 				 * fragmentation loops.
23538 				 */
23539 				UNLOCK_IRE_FP_MP(ire);
23540 				goto drop_pkt;
23541 			}
23542 			UNLOCK_IRE_FP_MP(ire);
23543 			BUMP_MIB(&ip_mib, ipFragCreates);
23544 			putnext(q, xmit_mp);
23545 
23546 			if (pkt_type != OB_PKT) {
23547 				/*
23548 				 * Update the packet count of trailing
23549 				 * RTF_MULTIRT ires.
23550 				 */
23551 				UPDATE_OB_PKT_COUNT(ire);
23552 			}
23553 
23554 			/* All done if we just consumed the hdr_mp. */
23555 			if (mp == hdr_mp) {
23556 				last_frag = B_TRUE;
23557 			}
23558 
23559 			if (multirt_send) {
23560 				/*
23561 				 * We are in a multiple send case; look for
23562 				 * the next ire and re-enter the loop.
23563 				 */
23564 				ASSERT(ire1);
23565 				ASSERT(next_mp);
23566 				/* REFRELE the current ire before looping */
23567 				ire_refrele(ire);
23568 				ire = ire1;
23569 				ire1 = NULL;
23570 				q = ire->ire_stq;
23571 				mp = next_mp;
23572 				next_mp = NULL;
23573 			}
23574 		} while (multirt_send);
23575 		/*
23576 		 * Restore the original ire; we need it for the
23577 		 * trailing frags
23578 		 */
23579 		if (save_ire != NULL) {
23580 			ASSERT(ire1 == NULL);
23581 			/* REFRELE the last iterated ire */
23582 			ire_refrele(ire);
23583 			/* save_ire has been REFHOLDed */
23584 			ire = save_ire;
23585 			q = ire->ire_stq;
23586 			save_ire = NULL;
23587 		}
23588 
23589 		if (last_frag) {
23590 			BUMP_MIB(&ip_mib, ipFragOKs);
23591 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23592 			    "ip_wput_frag_end:(%S)",
23593 			    "consumed hdr_mp");
23594 
23595 			if (first_ire != NULL)
23596 				ire_refrele(first_ire);
23597 			return;
23598 		}
23599 		/* Otherwise, advance and loop. */
23600 		offset += len;
23601 	}
23602 
23603 drop_pkt:
23604 	/* Clean up following allocation failure. */
23605 	BUMP_MIB(&ip_mib, ipOutDiscards);
23606 	freemsg(mp);
23607 	if (mp != hdr_mp)
23608 		freeb(hdr_mp);
23609 	if (mp != mp_orig)
23610 		freemsg(mp_orig);
23611 
23612 	if (save_ire != NULL)
23613 		IRE_REFRELE(save_ire);
23614 	if (first_ire != NULL)
23615 		ire_refrele(first_ire);
23616 
23617 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23618 	    "ip_wput_frag_end:(%S)",
23619 	    "end--alloc failure");
23620 }
23621 
23622 /*
23623  * Copy the header plus those options which have the copy bit set
23624  */
23625 static mblk_t *
23626 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
23627 {
23628 	mblk_t	*mp;
23629 	uchar_t	*up;
23630 
23631 	/*
23632 	 * Quick check if we need to look for options without the copy bit
23633 	 * set
23634 	 */
23635 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
23636 	if (!mp)
23637 		return (mp);
23638 	mp->b_rptr += ip_wroff_extra;
23639 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
23640 		bcopy(rptr, mp->b_rptr, hdr_len);
23641 		mp->b_wptr += hdr_len + ip_wroff_extra;
23642 		return (mp);
23643 	}
23644 	up  = mp->b_rptr;
23645 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
23646 	up += IP_SIMPLE_HDR_LENGTH;
23647 	rptr += IP_SIMPLE_HDR_LENGTH;
23648 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
23649 	while (hdr_len > 0) {
23650 		uint32_t optval;
23651 		uint32_t optlen;
23652 
23653 		optval = *rptr;
23654 		if (optval == IPOPT_EOL)
23655 			break;
23656 		if (optval == IPOPT_NOP)
23657 			optlen = 1;
23658 		else
23659 			optlen = rptr[1];
23660 		if (optval & IPOPT_COPY) {
23661 			bcopy(rptr, up, optlen);
23662 			up += optlen;
23663 		}
23664 		rptr += optlen;
23665 		hdr_len -= optlen;
23666 	}
23667 	/*
23668 	 * Make sure that we drop an even number of words by filling
23669 	 * with EOL to the next word boundary.
23670 	 */
23671 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
23672 	    hdr_len & 0x3; hdr_len++)
23673 		*up++ = IPOPT_EOL;
23674 	mp->b_wptr = up;
23675 	/* Update header length */
23676 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
23677 	return (mp);
23678 }
23679 
23680 /*
23681  * Delivery to local recipients including fanout to multiple recipients.
23682  * Does not do checksumming of UDP/TCP.
23683  * Note: q should be the read side queue for either the ill or conn.
23684  * Note: rq should be the read side q for the lower (ill) stream.
23685  * We don't send packets to IPPF processing, thus the last argument
23686  * to all the fanout calls are B_FALSE.
23687  */
23688 void
23689 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
23690     int fanout_flags, zoneid_t zoneid)
23691 {
23692 	uint32_t	protocol;
23693 	mblk_t		*first_mp;
23694 	boolean_t	mctl_present;
23695 	int		ire_type;
23696 #define	rptr	((uchar_t *)ipha)
23697 
23698 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
23699 	    "ip_wput_local_start: q %p", q);
23700 
23701 	if (ire != NULL) {
23702 		ire_type = ire->ire_type;
23703 	} else {
23704 		/*
23705 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
23706 		 * packet is not multicast, we can't tell the ire type.
23707 		 */
23708 		ASSERT(CLASSD(ipha->ipha_dst));
23709 		ire_type = IRE_BROADCAST;
23710 	}
23711 
23712 	first_mp = mp;
23713 	if (first_mp->b_datap->db_type == M_CTL) {
23714 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
23715 		if (!io->ipsec_out_secure) {
23716 			/*
23717 			 * This ipsec_out_t was allocated in ip_wput
23718 			 * for multicast packets to store the ill_index.
23719 			 * As this is being delivered locally, we don't
23720 			 * need this anymore.
23721 			 */
23722 			mp = first_mp->b_cont;
23723 			freeb(first_mp);
23724 			first_mp = mp;
23725 			mctl_present = B_FALSE;
23726 		} else {
23727 			mctl_present = B_TRUE;
23728 			mp = first_mp->b_cont;
23729 			ASSERT(mp != NULL);
23730 			ipsec_out_to_in(first_mp);
23731 		}
23732 	} else {
23733 		mctl_present = B_FALSE;
23734 	}
23735 
23736 	loopback_packets++;
23737 
23738 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
23739 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
23740 	if (!IS_SIMPLE_IPH(ipha)) {
23741 		ip_wput_local_options(ipha);
23742 	}
23743 
23744 	protocol = ipha->ipha_protocol;
23745 	switch (protocol) {
23746 	case IPPROTO_ICMP: {
23747 		ire_t		*ire_zone;
23748 		ilm_t		*ilm;
23749 		mblk_t		*mp1;
23750 		zoneid_t	last_zoneid;
23751 
23752 		if (CLASSD(ipha->ipha_dst) &&
23753 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
23754 			ASSERT(ire_type == IRE_BROADCAST);
23755 			/*
23756 			 * In the multicast case, applications may have joined
23757 			 * the group from different zones, so we need to deliver
23758 			 * the packet to each of them. Loop through the
23759 			 * multicast memberships structures (ilm) on the receive
23760 			 * ill and send a copy of the packet up each matching
23761 			 * one. However, we don't do this for multicasts sent on
23762 			 * the loopback interface (PHYI_LOOPBACK flag set) as
23763 			 * they must stay in the sender's zone.
23764 			 *
23765 			 * ilm_add_v6() ensures that ilms in the same zone are
23766 			 * contiguous in the ill_ilm list. We use this property
23767 			 * to avoid sending duplicates needed when two
23768 			 * applications in the same zone join the same group on
23769 			 * different logical interfaces: we ignore the ilm if
23770 			 * it's zoneid is the same as the last matching one.
23771 			 * In addition, the sending of the packet for
23772 			 * ire_zoneid is delayed until all of the other ilms
23773 			 * have been exhausted.
23774 			 */
23775 			last_zoneid = -1;
23776 			ILM_WALKER_HOLD(ill);
23777 			for (ilm = ill->ill_ilm; ilm != NULL;
23778 			    ilm = ilm->ilm_next) {
23779 				if ((ilm->ilm_flags & ILM_DELETED) ||
23780 				    ipha->ipha_dst != ilm->ilm_addr ||
23781 				    ilm->ilm_zoneid == last_zoneid ||
23782 				    ilm->ilm_zoneid == zoneid ||
23783 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
23784 					continue;
23785 				mp1 = ip_copymsg(first_mp);
23786 				if (mp1 == NULL)
23787 					continue;
23788 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23789 				    mctl_present, B_FALSE, ill,
23790 				    ilm->ilm_zoneid);
23791 				last_zoneid = ilm->ilm_zoneid;
23792 			}
23793 			ILM_WALKER_RELE(ill);
23794 			/*
23795 			 * Loopback case: the sending endpoint has
23796 			 * IP_MULTICAST_LOOP disabled, therefore we don't
23797 			 * dispatch the multicast packet to the sending zone.
23798 			 */
23799 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
23800 				freemsg(first_mp);
23801 				return;
23802 			}
23803 		} else if (ire_type == IRE_BROADCAST) {
23804 			/*
23805 			 * In the broadcast case, there may be many zones
23806 			 * which need a copy of the packet delivered to them.
23807 			 * There is one IRE_BROADCAST per broadcast address
23808 			 * and per zone; we walk those using a helper function.
23809 			 * In addition, the sending of the packet for zoneid is
23810 			 * delayed until all of the other ires have been
23811 			 * processed.
23812 			 */
23813 			IRB_REFHOLD(ire->ire_bucket);
23814 			ire_zone = NULL;
23815 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
23816 			    ire)) != NULL) {
23817 				mp1 = ip_copymsg(first_mp);
23818 				if (mp1 == NULL)
23819 					continue;
23820 
23821 				UPDATE_IB_PKT_COUNT(ire_zone);
23822 				ire_zone->ire_last_used_time = lbolt;
23823 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23824 				    mctl_present, B_FALSE, ill,
23825 				    ire_zone->ire_zoneid);
23826 			}
23827 			IRB_REFRELE(ire->ire_bucket);
23828 		}
23829 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
23830 		    0, mctl_present, B_FALSE, ill, zoneid);
23831 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23832 		    "ip_wput_local_end: q %p (%S)",
23833 		    q, "icmp");
23834 		return;
23835 	}
23836 	case IPPROTO_IGMP:
23837 		if (igmp_input(q, mp, ill)) {
23838 			/* Bad packet - discarded by igmp_input */
23839 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23840 			    "ip_wput_local_end: q %p (%S)",
23841 			    q, "igmp_input--bad packet");
23842 			if (mctl_present)
23843 				freeb(first_mp);
23844 			return;
23845 		}
23846 		/*
23847 		 * igmp_input() may have pulled up the message so ipha needs to
23848 		 * be reinitialized.
23849 		 */
23850 		ipha = (ipha_t *)mp->b_rptr;
23851 		/* deliver to local raw users */
23852 		break;
23853 	case IPPROTO_ENCAP:
23854 		/*
23855 		 * This case is covered by either ip_fanout_proto, or by
23856 		 * the above security processing for self-tunneled packets.
23857 		 */
23858 		break;
23859 	case IPPROTO_UDP: {
23860 		uint16_t	*up;
23861 		uint32_t	ports;
23862 
23863 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
23864 		    UDP_PORTS_OFFSET);
23865 		/* Force a 'valid' checksum. */
23866 		up[3] = 0;
23867 
23868 		ports = *(uint32_t *)up;
23869 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
23870 		    (ire_type == IRE_BROADCAST),
23871 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23872 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
23873 		    ill, zoneid);
23874 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23875 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
23876 		return;
23877 	}
23878 	case IPPROTO_TCP: {
23879 
23880 		/*
23881 		 * For TCP, discard broadcast packets.
23882 		 */
23883 		if ((ushort_t)ire_type == IRE_BROADCAST) {
23884 			freemsg(first_mp);
23885 			BUMP_MIB(&ip_mib, ipInDiscards);
23886 			ip2dbg(("ip_wput_local: discard broadcast\n"));
23887 			return;
23888 		}
23889 
23890 		if (mp->b_datap->db_type == M_DATA) {
23891 			/*
23892 			 * M_DATA mblk, so init mblk (chain) for no struio().
23893 			 */
23894 			mblk_t	*mp1 = mp;
23895 
23896 			do
23897 				mp1->b_datap->db_struioflag = 0;
23898 			while ((mp1 = mp1->b_cont) != NULL);
23899 		}
23900 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
23901 		    <= mp->b_wptr);
23902 		ip_fanout_tcp(q, first_mp, ill, ipha,
23903 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23904 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
23905 		    mctl_present, B_FALSE, zoneid);
23906 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23907 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
23908 		return;
23909 	}
23910 	case IPPROTO_SCTP:
23911 	{
23912 		uint32_t	ports;
23913 
23914 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
23915 		ip_fanout_sctp(first_mp, ill, ipha, ports,
23916 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23917 		    IP_FF_IP6INFO,
23918 		    mctl_present, B_FALSE, 0, zoneid);
23919 		return;
23920 	}
23921 
23922 	default:
23923 		break;
23924 	}
23925 	/*
23926 	 * Find a client for some other protocol.  We give
23927 	 * copies to multiple clients, if more than one is
23928 	 * bound.
23929 	 */
23930 	ip_fanout_proto(q, first_mp, ill, ipha,
23931 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
23932 	    mctl_present, B_FALSE, ill, zoneid);
23933 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23934 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
23935 #undef	rptr
23936 }
23937 
23938 /*
23939  * Update any source route, record route, or timestamp options.
23940  * Check that we are at end of strict source route.
23941  * The options have been sanity checked by ip_wput_options().
23942  */
23943 static void
23944 ip_wput_local_options(ipha_t *ipha)
23945 {
23946 	ipoptp_t	opts;
23947 	uchar_t		*opt;
23948 	uint8_t		optval;
23949 	uint8_t		optlen;
23950 	ipaddr_t	dst;
23951 	uint32_t	ts;
23952 	ire_t		*ire;
23953 	timestruc_t	now;
23954 
23955 	ip2dbg(("ip_wput_local_options\n"));
23956 	for (optval = ipoptp_first(&opts, ipha);
23957 	    optval != IPOPT_EOL;
23958 	    optval = ipoptp_next(&opts)) {
23959 		opt = opts.ipoptp_cur;
23960 		optlen = opts.ipoptp_len;
23961 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
23962 		switch (optval) {
23963 			uint32_t off;
23964 		case IPOPT_SSRR:
23965 		case IPOPT_LSRR:
23966 			off = opt[IPOPT_OFFSET];
23967 			off--;
23968 			if (optlen < IP_ADDR_LEN ||
23969 			    off > optlen - IP_ADDR_LEN) {
23970 				/* End of source route */
23971 				break;
23972 			}
23973 			/*
23974 			 * This will only happen if two consecutive entries
23975 			 * in the source route contains our address or if
23976 			 * it is a packet with a loose source route which
23977 			 * reaches us before consuming the whole source route
23978 			 */
23979 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
23980 			if (optval == IPOPT_SSRR) {
23981 				return;
23982 			}
23983 			/*
23984 			 * Hack: instead of dropping the packet truncate the
23985 			 * source route to what has been used by filling the
23986 			 * rest with IPOPT_NOP.
23987 			 */
23988 			opt[IPOPT_OLEN] = (uint8_t)off;
23989 			while (off < optlen) {
23990 				opt[off++] = IPOPT_NOP;
23991 			}
23992 			break;
23993 		case IPOPT_RR:
23994 			off = opt[IPOPT_OFFSET];
23995 			off--;
23996 			if (optlen < IP_ADDR_LEN ||
23997 			    off > optlen - IP_ADDR_LEN) {
23998 				/* No more room - ignore */
23999 				ip1dbg((
24000 				    "ip_wput_forward_options: end of RR\n"));
24001 				break;
24002 			}
24003 			dst = htonl(INADDR_LOOPBACK);
24004 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24005 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24006 			break;
24007 		case IPOPT_TS:
24008 			/* Insert timestamp if there is romm */
24009 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24010 			case IPOPT_TS_TSONLY:
24011 				off = IPOPT_TS_TIMELEN;
24012 				break;
24013 			case IPOPT_TS_PRESPEC:
24014 			case IPOPT_TS_PRESPEC_RFC791:
24015 				/* Verify that the address matched */
24016 				off = opt[IPOPT_OFFSET] - 1;
24017 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
24018 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
24019 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
24020 				if (ire == NULL) {
24021 					/* Not for us */
24022 					break;
24023 				}
24024 				ire_refrele(ire);
24025 				/* FALLTHRU */
24026 			case IPOPT_TS_TSANDADDR:
24027 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24028 				break;
24029 			default:
24030 				/*
24031 				 * ip_*put_options should have already
24032 				 * dropped this packet.
24033 				 */
24034 				cmn_err(CE_PANIC, "ip_wput_local_options: "
24035 				    "unknown IT - bug in ip_wput_options?\n");
24036 				return;	/* Keep "lint" happy */
24037 			}
24038 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
24039 				/* Increase overflow counter */
24040 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
24041 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
24042 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
24043 				    (off << 4);
24044 				break;
24045 			}
24046 			off = opt[IPOPT_OFFSET] - 1;
24047 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24048 			case IPOPT_TS_PRESPEC:
24049 			case IPOPT_TS_PRESPEC_RFC791:
24050 			case IPOPT_TS_TSANDADDR:
24051 				dst = htonl(INADDR_LOOPBACK);
24052 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24053 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24054 				/* FALLTHRU */
24055 			case IPOPT_TS_TSONLY:
24056 				off = opt[IPOPT_OFFSET] - 1;
24057 				/* Compute # of milliseconds since midnight */
24058 				gethrestime(&now);
24059 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
24060 				    now.tv_nsec / (NANOSEC / MILLISEC);
24061 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
24062 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
24063 				break;
24064 			}
24065 			break;
24066 		}
24067 	}
24068 }
24069 
24070 /*
24071  * Send out a multicast packet on interface ipif.
24072  * The sender does not have an conn.
24073  * Caller verifies that this isn't a PHYI_LOOPBACK.
24074  */
24075 void
24076 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
24077 {
24078 	ipha_t	*ipha;
24079 	ire_t	*ire;
24080 	ipaddr_t	dst;
24081 	mblk_t		*first_mp;
24082 
24083 	/* igmp_sendpkt always allocates a ipsec_out_t */
24084 	ASSERT(mp->b_datap->db_type == M_CTL);
24085 	ASSERT(!ipif->ipif_isv6);
24086 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
24087 
24088 	first_mp = mp;
24089 	mp = first_mp->b_cont;
24090 	ASSERT(mp->b_datap->db_type == M_DATA);
24091 	ipha = (ipha_t *)mp->b_rptr;
24092 
24093 	/*
24094 	 * Find an IRE which matches the destination and the outgoing
24095 	 * queue (i.e. the outgoing interface.)
24096 	 */
24097 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
24098 		dst = ipif->ipif_pp_dst_addr;
24099 	else
24100 		dst = ipha->ipha_dst;
24101 	/*
24102 	 * The source address has already been initialized by the
24103 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
24104 	 * be sufficient rather than MATCH_IRE_IPIF.
24105 	 *
24106 	 * This function is used for sending IGMP packets. We need
24107 	 * to make sure that we send the packet out of the interface
24108 	 * (ipif->ipif_ill) where we joined the group. This is to
24109 	 * prevent from switches doing IGMP snooping to send us multicast
24110 	 * packets for a given group on the interface we have joined.
24111 	 * If we can't find an ire, igmp_sendpkt has already initialized
24112 	 * ipsec_out_attach_if so that this will not be load spread in
24113 	 * ip_newroute_ipif.
24114 	 */
24115 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, NULL,
24116 	    MATCH_IRE_ILL);
24117 	if (!ire) {
24118 		/*
24119 		 * Mark this packet to make it be delivered to
24120 		 * ip_wput_ire after the new ire has been
24121 		 * created.
24122 		 */
24123 		mp->b_prev = NULL;
24124 		mp->b_next = NULL;
24125 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
24126 		return;
24127 	}
24128 
24129 	/*
24130 	 * Honor the RTF_SETSRC flag; this is the only case
24131 	 * where we force this addr whatever the current src addr is,
24132 	 * because this address is set by igmp_sendpkt(), and
24133 	 * cannot be specified by any user.
24134 	 */
24135 	if (ire->ire_flags & RTF_SETSRC) {
24136 		ipha->ipha_src = ire->ire_src_addr;
24137 	}
24138 
24139 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
24140 }
24141 
24142 /*
24143  * NOTE : This function does not ire_refrele the ire argument passed in.
24144  *
24145  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
24146  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
24147  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
24148  * the ire_lock to access the nce_fp_mp in this case.
24149  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
24150  * prepending a fastpath message IPQoS processing must precede it, we also set
24151  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
24152  * (IPQoS might have set the b_band for CoS marking).
24153  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
24154  * must follow it so that IPQoS can mark the dl_priority field for CoS
24155  * marking, if needed.
24156  */
24157 static mblk_t *
24158 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
24159 {
24160 	uint_t	hlen;
24161 	ipha_t *ipha;
24162 	mblk_t *mp1;
24163 	boolean_t qos_done = B_FALSE;
24164 	uchar_t	*ll_hdr;
24165 
24166 #define	rptr	((uchar_t *)ipha)
24167 
24168 	ipha = (ipha_t *)mp->b_rptr;
24169 	hlen = 0;
24170 	LOCK_IRE_FP_MP(ire);
24171 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
24172 		ASSERT(DB_TYPE(mp1) == M_DATA);
24173 		/* Initiate IPPF processing */
24174 		if ((proc != 0) && IPP_ENABLED(proc)) {
24175 			UNLOCK_IRE_FP_MP(ire);
24176 			ip_process(proc, &mp, ill_index);
24177 			if (mp == NULL)
24178 				return (NULL);
24179 
24180 			ipha = (ipha_t *)mp->b_rptr;
24181 			LOCK_IRE_FP_MP(ire);
24182 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
24183 				qos_done = B_TRUE;
24184 				goto no_fp_mp;
24185 			}
24186 			ASSERT(DB_TYPE(mp1) == M_DATA);
24187 		}
24188 		hlen = MBLKL(mp1);
24189 		/*
24190 		 * Check if we have enough room to prepend fastpath
24191 		 * header
24192 		 */
24193 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
24194 			ll_hdr = rptr - hlen;
24195 			bcopy(mp1->b_rptr, ll_hdr, hlen);
24196 			/*
24197 			 * Set the b_rptr to the start of the link layer
24198 			 * header
24199 			 */
24200 			mp->b_rptr = ll_hdr;
24201 			mp1 = mp;
24202 		} else {
24203 			mp1 = copyb(mp1);
24204 			if (mp1 == NULL)
24205 				goto unlock_err;
24206 			mp1->b_band = mp->b_band;
24207 			mp1->b_cont = mp;
24208 			/*
24209 			 * certain system generated traffic may not
24210 			 * have cred/label in ip header block. This
24211 			 * is true even for a labeled system. But for
24212 			 * labeled traffic, inherit the label in the
24213 			 * new header.
24214 			 */
24215 			if (DB_CRED(mp) != NULL)
24216 				mblk_setcred(mp1, DB_CRED(mp));
24217 			/*
24218 			 * XXX disable ICK_VALID and compute checksum
24219 			 * here; can happen if nce_fp_mp changes and
24220 			 * it can't be copied now due to insufficient
24221 			 * space. (unlikely, fp mp can change, but it
24222 			 * does not increase in length)
24223 			 */
24224 		}
24225 		UNLOCK_IRE_FP_MP(ire);
24226 	} else {
24227 no_fp_mp:
24228 		mp1 = copyb(ire->ire_nce->nce_res_mp);
24229 		if (mp1 == NULL) {
24230 unlock_err:
24231 			UNLOCK_IRE_FP_MP(ire);
24232 			freemsg(mp);
24233 			return (NULL);
24234 		}
24235 		UNLOCK_IRE_FP_MP(ire);
24236 		mp1->b_cont = mp;
24237 		/*
24238 		 * certain system generated traffic may not
24239 		 * have cred/label in ip header block. This
24240 		 * is true even for a labeled system. But for
24241 		 * labeled traffic, inherit the label in the
24242 		 * new header.
24243 		 */
24244 		if (DB_CRED(mp) != NULL)
24245 			mblk_setcred(mp1, DB_CRED(mp));
24246 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
24247 			ip_process(proc, &mp1, ill_index);
24248 			if (mp1 == NULL)
24249 				return (NULL);
24250 		}
24251 	}
24252 	return (mp1);
24253 #undef rptr
24254 }
24255 
24256 /*
24257  * Finish the outbound IPsec processing for an IPv6 packet. This function
24258  * is called from ipsec_out_process() if the IPsec packet was processed
24259  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24260  * asynchronously.
24261  */
24262 void
24263 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
24264     ire_t *ire_arg)
24265 {
24266 	in6_addr_t *v6dstp;
24267 	ire_t *ire;
24268 	mblk_t *mp;
24269 	uint_t	ill_index;
24270 	ipsec_out_t *io;
24271 	boolean_t attach_if, hwaccel;
24272 	uint32_t flags = IP6_NO_IPPOLICY;
24273 	int match_flags;
24274 	zoneid_t zoneid;
24275 	boolean_t ill_need_rele = B_FALSE;
24276 	boolean_t ire_need_rele = B_FALSE;
24277 
24278 	mp = ipsec_mp->b_cont;
24279 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24280 	ill_index = io->ipsec_out_ill_index;
24281 	if (io->ipsec_out_reachable) {
24282 		flags |= IPV6_REACHABILITY_CONFIRMATION;
24283 	}
24284 	attach_if = io->ipsec_out_attach_if;
24285 	hwaccel = io->ipsec_out_accelerated;
24286 	zoneid = io->ipsec_out_zoneid;
24287 	ASSERT(zoneid != ALL_ZONES);
24288 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24289 	/* Multicast addresses should have non-zero ill_index. */
24290 	v6dstp = &ip6h->ip6_dst;
24291 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
24292 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
24293 	ASSERT(!attach_if || ill_index != 0);
24294 	if (ill_index != 0) {
24295 		if (ill == NULL) {
24296 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
24297 			    B_TRUE);
24298 
24299 			/* Failure case frees things for us. */
24300 			if (ill == NULL)
24301 				return;
24302 
24303 			ill_need_rele = B_TRUE;
24304 		}
24305 		/*
24306 		 * If this packet needs to go out on a particular interface
24307 		 * honor it.
24308 		 */
24309 		if (attach_if) {
24310 			match_flags = MATCH_IRE_ILL;
24311 
24312 			/*
24313 			 * Check if we need an ire that will not be
24314 			 * looked up by anybody else i.e. HIDDEN.
24315 			 */
24316 			if (ill_is_probeonly(ill)) {
24317 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24318 			}
24319 		}
24320 	}
24321 	ASSERT(mp != NULL);
24322 
24323 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
24324 		boolean_t unspec_src;
24325 		ipif_t	*ipif;
24326 
24327 		/*
24328 		 * Use the ill_index to get the right ill.
24329 		 */
24330 		unspec_src = io->ipsec_out_unspec_src;
24331 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24332 		if (ipif == NULL) {
24333 			if (ill_need_rele)
24334 				ill_refrele(ill);
24335 			freemsg(ipsec_mp);
24336 			return;
24337 		}
24338 
24339 		if (ire_arg != NULL) {
24340 			ire = ire_arg;
24341 		} else {
24342 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24343 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24344 			ire_need_rele = B_TRUE;
24345 		}
24346 		if (ire != NULL) {
24347 			ipif_refrele(ipif);
24348 			/*
24349 			 * XXX Do the multicast forwarding now, as the IPSEC
24350 			 * processing has been done.
24351 			 */
24352 			goto send;
24353 		}
24354 
24355 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
24356 		mp->b_prev = NULL;
24357 		mp->b_next = NULL;
24358 
24359 		/*
24360 		 * If the IPsec packet was processed asynchronously,
24361 		 * drop it now.
24362 		 */
24363 		if (q == NULL) {
24364 			if (ill_need_rele)
24365 				ill_refrele(ill);
24366 			freemsg(ipsec_mp);
24367 			return;
24368 		}
24369 
24370 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
24371 		    unspec_src, zoneid);
24372 		ipif_refrele(ipif);
24373 	} else {
24374 		if (attach_if) {
24375 			ipif_t	*ipif;
24376 
24377 			ipif = ipif_get_next_ipif(NULL, ill);
24378 			if (ipif == NULL) {
24379 				if (ill_need_rele)
24380 					ill_refrele(ill);
24381 				freemsg(ipsec_mp);
24382 				return;
24383 			}
24384 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24385 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24386 			ire_need_rele = B_TRUE;
24387 			ipif_refrele(ipif);
24388 		} else {
24389 			if (ire_arg != NULL) {
24390 				ire = ire_arg;
24391 			} else {
24392 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
24393 				ire_need_rele = B_TRUE;
24394 			}
24395 		}
24396 		if (ire != NULL)
24397 			goto send;
24398 		/*
24399 		 * ire disappeared underneath.
24400 		 *
24401 		 * What we need to do here is the ip_newroute
24402 		 * logic to get the ire without doing the IPSEC
24403 		 * processing. Follow the same old path. But this
24404 		 * time, ip_wput or ire_add_then_send will call us
24405 		 * directly as all the IPSEC operations are done.
24406 		 */
24407 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
24408 		mp->b_prev = NULL;
24409 		mp->b_next = NULL;
24410 
24411 		/*
24412 		 * If the IPsec packet was processed asynchronously,
24413 		 * drop it now.
24414 		 */
24415 		if (q == NULL) {
24416 			if (ill_need_rele)
24417 				ill_refrele(ill);
24418 			freemsg(ipsec_mp);
24419 			return;
24420 		}
24421 
24422 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
24423 		    zoneid);
24424 	}
24425 	if (ill != NULL && ill_need_rele)
24426 		ill_refrele(ill);
24427 	return;
24428 send:
24429 	if (ill != NULL && ill_need_rele)
24430 		ill_refrele(ill);
24431 
24432 	/* Local delivery */
24433 	if (ire->ire_stq == NULL) {
24434 		ASSERT(q != NULL);
24435 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
24436 		    ire, 0);
24437 		if (ire_need_rele)
24438 			ire_refrele(ire);
24439 		return;
24440 	}
24441 	/*
24442 	 * Everything is done. Send it out on the wire.
24443 	 * We force the insertion of a fragment header using the
24444 	 * IPH_FRAG_HDR flag in two cases:
24445 	 * - after reception of an ICMPv6 "packet too big" message
24446 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
24447 	 * - for multirouted IPv6 packets, so that the receiver can
24448 	 *   discard duplicates according to their fragment identifier
24449 	 */
24450 	/* XXX fix flow control problems. */
24451 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
24452 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
24453 		if (hwaccel) {
24454 			/*
24455 			 * hardware acceleration does not handle these
24456 			 * "slow path" cases.
24457 			 */
24458 			/* IPsec KSTATS: should bump bean counter here. */
24459 			if (ire_need_rele)
24460 				ire_refrele(ire);
24461 			freemsg(ipsec_mp);
24462 			return;
24463 		}
24464 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
24465 		    (mp->b_cont ? msgdsize(mp) :
24466 		    mp->b_wptr - (uchar_t *)ip6h)) {
24467 			/* IPsec KSTATS: should bump bean counter here. */
24468 			ip0dbg(("Packet length mismatch: %d, %ld\n",
24469 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
24470 			    msgdsize(mp)));
24471 			if (ire_need_rele)
24472 				ire_refrele(ire);
24473 			freemsg(ipsec_mp);
24474 			return;
24475 		}
24476 		ASSERT(mp->b_prev == NULL);
24477 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
24478 		    ntohs(ip6h->ip6_plen) +
24479 		    IPV6_HDR_LEN, ire->ire_max_frag));
24480 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
24481 		    ire->ire_max_frag);
24482 	} else {
24483 		UPDATE_OB_PKT_COUNT(ire);
24484 		ire->ire_last_used_time = lbolt;
24485 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
24486 	}
24487 	if (ire_need_rele)
24488 		ire_refrele(ire);
24489 	freeb(ipsec_mp);
24490 }
24491 
24492 void
24493 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
24494 {
24495 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
24496 	da_ipsec_t *hada;	/* data attributes */
24497 	ill_t *ill = (ill_t *)q->q_ptr;
24498 
24499 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
24500 
24501 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
24502 		/* IPsec KSTATS: Bump lose counter here! */
24503 		freemsg(mp);
24504 		return;
24505 	}
24506 
24507 	/*
24508 	 * It's an IPsec packet that must be
24509 	 * accelerated by the Provider, and the
24510 	 * outbound ill is IPsec acceleration capable.
24511 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
24512 	 * to the ill.
24513 	 * IPsec KSTATS: should bump packet counter here.
24514 	 */
24515 
24516 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
24517 	if (hada_mp == NULL) {
24518 		/* IPsec KSTATS: should bump packet counter here. */
24519 		freemsg(mp);
24520 		return;
24521 	}
24522 
24523 	hada_mp->b_datap->db_type = M_CTL;
24524 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
24525 	hada_mp->b_cont = mp;
24526 
24527 	hada = (da_ipsec_t *)hada_mp->b_rptr;
24528 	bzero(hada, sizeof (da_ipsec_t));
24529 	hada->da_type = IPHADA_M_CTL;
24530 
24531 	putnext(q, hada_mp);
24532 }
24533 
24534 /*
24535  * Finish the outbound IPsec processing. This function is called from
24536  * ipsec_out_process() if the IPsec packet was processed
24537  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24538  * asynchronously.
24539  */
24540 void
24541 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
24542     ire_t *ire_arg)
24543 {
24544 	uint32_t v_hlen_tos_len;
24545 	ipaddr_t	dst;
24546 	ipif_t	*ipif = NULL;
24547 	ire_t *ire;
24548 	ire_t *ire1 = NULL;
24549 	mblk_t *next_mp = NULL;
24550 	uint32_t max_frag;
24551 	boolean_t multirt_send = B_FALSE;
24552 	mblk_t *mp;
24553 	mblk_t *mp1;
24554 	uint_t	ill_index;
24555 	ipsec_out_t *io;
24556 	boolean_t attach_if;
24557 	int match_flags, offset;
24558 	irb_t *irb = NULL;
24559 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
24560 	zoneid_t zoneid;
24561 	uint32_t cksum;
24562 	uint16_t *up;
24563 	ipxmit_state_t	pktxmit_state;
24564 #ifdef	_BIG_ENDIAN
24565 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
24566 #else
24567 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
24568 #endif
24569 
24570 	mp = ipsec_mp->b_cont;
24571 	ASSERT(mp != NULL);
24572 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24573 	dst = ipha->ipha_dst;
24574 
24575 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24576 	ill_index = io->ipsec_out_ill_index;
24577 	attach_if = io->ipsec_out_attach_if;
24578 	zoneid = io->ipsec_out_zoneid;
24579 	ASSERT(zoneid != ALL_ZONES);
24580 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24581 	if (ill_index != 0) {
24582 		if (ill == NULL) {
24583 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
24584 			    ill_index, B_FALSE);
24585 
24586 			/* Failure case frees things for us. */
24587 			if (ill == NULL)
24588 				return;
24589 
24590 			ill_need_rele = B_TRUE;
24591 		}
24592 		/*
24593 		 * If this packet needs to go out on a particular interface
24594 		 * honor it.
24595 		 */
24596 		if (attach_if) {
24597 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
24598 
24599 			/*
24600 			 * Check if we need an ire that will not be
24601 			 * looked up by anybody else i.e. HIDDEN.
24602 			 */
24603 			if (ill_is_probeonly(ill)) {
24604 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24605 			}
24606 		}
24607 	}
24608 
24609 	if (CLASSD(dst)) {
24610 		boolean_t conn_dontroute;
24611 		/*
24612 		 * Use the ill_index to get the right ipif.
24613 		 */
24614 		conn_dontroute = io->ipsec_out_dontroute;
24615 		if (ill_index == 0)
24616 			ipif = ipif_lookup_group(dst, zoneid);
24617 		else
24618 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24619 		if (ipif == NULL) {
24620 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
24621 			    " multicast\n"));
24622 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
24623 			freemsg(ipsec_mp);
24624 			goto done;
24625 		}
24626 		/*
24627 		 * ipha_src has already been intialized with the
24628 		 * value of the ipif in ip_wput. All we need now is
24629 		 * an ire to send this downstream.
24630 		 */
24631 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
24632 		    MBLK_GETLABEL(mp), match_flags);
24633 		if (ire != NULL) {
24634 			ill_t *ill1;
24635 			/*
24636 			 * Do the multicast forwarding now, as the IPSEC
24637 			 * processing has been done.
24638 			 */
24639 			if (ip_g_mrouter && !conn_dontroute &&
24640 			    (ill1 = ire_to_ill(ire))) {
24641 				if (ip_mforward(ill1, ipha, mp)) {
24642 					freemsg(ipsec_mp);
24643 					ip1dbg(("ip_wput_ipsec_out: mforward "
24644 					    "failed\n"));
24645 					ire_refrele(ire);
24646 					goto done;
24647 				}
24648 			}
24649 			goto send;
24650 		}
24651 
24652 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
24653 		mp->b_prev = NULL;
24654 		mp->b_next = NULL;
24655 
24656 		/*
24657 		 * If the IPsec packet was processed asynchronously,
24658 		 * drop it now.
24659 		 */
24660 		if (q == NULL) {
24661 			freemsg(ipsec_mp);
24662 			goto done;
24663 		}
24664 
24665 		/*
24666 		 * We may be using a wrong ipif to create the ire.
24667 		 * But it is okay as the source address is assigned
24668 		 * for the packet already. Next outbound packet would
24669 		 * create the IRE with the right IPIF in ip_wput.
24670 		 *
24671 		 * Also handle RTF_MULTIRT routes.
24672 		 */
24673 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
24674 	} else {
24675 		if (attach_if) {
24676 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
24677 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24678 		} else {
24679 			if (ire_arg != NULL) {
24680 				ire = ire_arg;
24681 				ire_need_rele = B_FALSE;
24682 			} else {
24683 				ire = ire_cache_lookup(dst, zoneid,
24684 				    MBLK_GETLABEL(mp));
24685 			}
24686 		}
24687 		if (ire != NULL) {
24688 			goto send;
24689 		}
24690 
24691 		/*
24692 		 * ire disappeared underneath.
24693 		 *
24694 		 * What we need to do here is the ip_newroute
24695 		 * logic to get the ire without doing the IPSEC
24696 		 * processing. Follow the same old path. But this
24697 		 * time, ip_wput or ire_add_then_put will call us
24698 		 * directly as all the IPSEC operations are done.
24699 		 */
24700 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
24701 		mp->b_prev = NULL;
24702 		mp->b_next = NULL;
24703 
24704 		/*
24705 		 * If the IPsec packet was processed asynchronously,
24706 		 * drop it now.
24707 		 */
24708 		if (q == NULL) {
24709 			freemsg(ipsec_mp);
24710 			goto done;
24711 		}
24712 
24713 		/*
24714 		 * Since we're going through ip_newroute() again, we
24715 		 * need to make sure we don't:
24716 		 *
24717 		 *	1.) Trigger the ASSERT() with the ipha_ident
24718 		 *	    overloading.
24719 		 *	2.) Redo transport-layer checksumming, since we've
24720 		 *	    already done all that to get this far.
24721 		 *
24722 		 * The easiest way not do either of the above is to set
24723 		 * the ipha_ident field to IP_HDR_INCLUDED.
24724 		 */
24725 		ipha->ipha_ident = IP_HDR_INCLUDED;
24726 		ip_newroute(q, ipsec_mp, dst, NULL,
24727 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
24728 	}
24729 	goto done;
24730 send:
24731 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
24732 		/*
24733 		 * ESP NAT-Traversal packet.
24734 		 *
24735 		 * Just do software checksum for now.
24736 		 */
24737 
24738 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
24739 		IP_STAT(ip_out_sw_cksum);
24740 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
24741 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
24742 #define	iphs	((uint16_t *)ipha)
24743 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
24744 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
24745 		    IP_SIMPLE_HDR_LENGTH);
24746 #undef iphs
24747 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
24748 			cksum = 0xFFFF;
24749 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
24750 			if (mp1->b_wptr - mp1->b_rptr >=
24751 			    offset + sizeof (uint16_t)) {
24752 				up = (uint16_t *)(mp1->b_rptr + offset);
24753 				*up = cksum;
24754 				break;	/* out of for loop */
24755 			} else {
24756 				offset -= (mp->b_wptr - mp->b_rptr);
24757 			}
24758 	} /* Otherwise, just keep the all-zero checksum. */
24759 
24760 	if (ire->ire_stq == NULL) {
24761 		/*
24762 		 * Loopbacks go through ip_wput_local except for one case.
24763 		 * We come here if we generate a icmp_frag_needed message
24764 		 * after IPSEC processing is over. When this function calls
24765 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
24766 		 * icmp_frag_needed. The message generated comes back here
24767 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
24768 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
24769 		 * source address as it is usually set in ip_wput_ire. As
24770 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
24771 		 * and we end up here. We can't enter ip_wput_ire once the
24772 		 * IPSEC processing is over and hence we need to do it here.
24773 		 */
24774 		ASSERT(q != NULL);
24775 		UPDATE_OB_PKT_COUNT(ire);
24776 		ire->ire_last_used_time = lbolt;
24777 		if (ipha->ipha_src == 0)
24778 			ipha->ipha_src = ire->ire_src_addr;
24779 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
24780 		    ire, 0, zoneid);
24781 		if (ire_need_rele)
24782 			ire_refrele(ire);
24783 		goto done;
24784 	}
24785 
24786 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
24787 		/*
24788 		 * We are through with IPSEC processing.
24789 		 * Fragment this and send it on the wire.
24790 		 */
24791 		if (io->ipsec_out_accelerated) {
24792 			/*
24793 			 * The packet has been accelerated but must
24794 			 * be fragmented. This should not happen
24795 			 * since AH and ESP must not accelerate
24796 			 * packets that need fragmentation, however
24797 			 * the configuration could have changed
24798 			 * since the AH or ESP processing.
24799 			 * Drop packet.
24800 			 * IPsec KSTATS: bump bean counter here.
24801 			 */
24802 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
24803 			    "fragmented accelerated packet!\n"));
24804 			freemsg(ipsec_mp);
24805 		} else {
24806 			ip_wput_ire_fragmentit(ipsec_mp, ire);
24807 		}
24808 		if (ire_need_rele)
24809 			ire_refrele(ire);
24810 		goto done;
24811 	}
24812 
24813 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
24814 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
24815 	    (void *)ire->ire_ipif, (void *)ipif));
24816 
24817 	/*
24818 	 * Multiroute the secured packet, unless IPsec really
24819 	 * requires the packet to go out only through a particular
24820 	 * interface.
24821 	 */
24822 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
24823 		ire_t *first_ire;
24824 		irb = ire->ire_bucket;
24825 		ASSERT(irb != NULL);
24826 		/*
24827 		 * This ire has been looked up as the one that
24828 		 * goes through the given ipif;
24829 		 * make sure we do not omit any other multiroute ire
24830 		 * that may be present in the bucket before this one.
24831 		 */
24832 		IRB_REFHOLD(irb);
24833 		for (first_ire = irb->irb_ire;
24834 		    first_ire != NULL;
24835 		    first_ire = first_ire->ire_next) {
24836 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24837 			    (first_ire->ire_addr == ire->ire_addr) &&
24838 			    !(first_ire->ire_marks &
24839 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24840 				break;
24841 		}
24842 
24843 		if ((first_ire != NULL) && (first_ire != ire)) {
24844 			/*
24845 			 * Don't change the ire if the packet must
24846 			 * be fragmented if sent via this new one.
24847 			 */
24848 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
24849 				IRE_REFHOLD(first_ire);
24850 				if (ire_need_rele)
24851 					ire_refrele(ire);
24852 				else
24853 					ire_need_rele = B_TRUE;
24854 				ire = first_ire;
24855 			}
24856 		}
24857 		IRB_REFRELE(irb);
24858 
24859 		multirt_send = B_TRUE;
24860 		max_frag = ire->ire_max_frag;
24861 	} else {
24862 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
24863 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
24864 			    "flag, attach_if %d\n", attach_if));
24865 		}
24866 	}
24867 
24868 	/*
24869 	 * In most cases, the emission loop below is entered only once.
24870 	 * Only in the case where the ire holds the RTF_MULTIRT
24871 	 * flag, we loop to process all RTF_MULTIRT ires in the
24872 	 * bucket, and send the packet through all crossed
24873 	 * RTF_MULTIRT routes.
24874 	 */
24875 	do {
24876 		if (multirt_send) {
24877 			/*
24878 			 * ire1 holds here the next ire to process in the
24879 			 * bucket. If multirouting is expected,
24880 			 * any non-RTF_MULTIRT ire that has the
24881 			 * right destination address is ignored.
24882 			 */
24883 			ASSERT(irb != NULL);
24884 			IRB_REFHOLD(irb);
24885 			for (ire1 = ire->ire_next;
24886 			    ire1 != NULL;
24887 			    ire1 = ire1->ire_next) {
24888 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24889 					continue;
24890 				if (ire1->ire_addr != ire->ire_addr)
24891 					continue;
24892 				if (ire1->ire_marks &
24893 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24894 					continue;
24895 				/* No loopback here */
24896 				if (ire1->ire_stq == NULL)
24897 					continue;
24898 				/*
24899 				 * Ensure we do not exceed the MTU
24900 				 * of the next route.
24901 				 */
24902 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
24903 					ip_multirt_bad_mtu(ire1, max_frag);
24904 					continue;
24905 				}
24906 
24907 				IRE_REFHOLD(ire1);
24908 				break;
24909 			}
24910 			IRB_REFRELE(irb);
24911 			if (ire1 != NULL) {
24912 				/*
24913 				 * We are in a multiple send case, need to
24914 				 * make a copy of the packet.
24915 				 */
24916 				next_mp = copymsg(ipsec_mp);
24917 				if (next_mp == NULL) {
24918 					ire_refrele(ire1);
24919 					ire1 = NULL;
24920 				}
24921 			}
24922 		}
24923 		/*
24924 		 * Everything is done. Send it out on the wire
24925 		 *
24926 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
24927 		 * either send it on the wire or, in the case of
24928 		 * HW acceleration, call ipsec_hw_putnext.
24929 		 */
24930 		if (ire->ire_nce &&
24931 		    ire->ire_nce->nce_state != ND_REACHABLE) {
24932 			DTRACE_PROBE2(ip__wput__ipsec__bail,
24933 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
24934 			/*
24935 			 * If ire's link-layer is unresolved (this
24936 			 * would only happen if the incomplete ire
24937 			 * was added to cachetable via forwarding path)
24938 			 * don't bother going to ip_xmit_v4. Just drop the
24939 			 * packet.
24940 			 * There is a slight risk here, in that, if we
24941 			 * have the forwarding path create an incomplete
24942 			 * IRE, then until the IRE is completed, any
24943 			 * transmitted IPSEC packets will be dropped
24944 			 * instead of being queued waiting for resolution.
24945 			 *
24946 			 * But the likelihood of a forwarding packet and a wput
24947 			 * packet sending to the same dst at the same time
24948 			 * and there not yet be an ARP entry for it is small.
24949 			 * Furthermore, if this actually happens, it might
24950 			 * be likely that wput would generate multiple
24951 			 * packets (and forwarding would also have a train
24952 			 * of packets) for that destination. If this is
24953 			 * the case, some of them would have been dropped
24954 			 * anyway, since ARP only queues a few packets while
24955 			 * waiting for resolution
24956 			 *
24957 			 * NOTE: We should really call ip_xmit_v4,
24958 			 * and let it queue the packet and send the
24959 			 * ARP query and have ARP come back thus:
24960 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
24961 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
24962 			 * hw accel work. But it's too complex to get
24963 			 * the IPsec hw  acceleration approach to fit
24964 			 * well with ip_xmit_v4 doing ARP without
24965 			 * doing IPSEC simplification. For now, we just
24966 			 * poke ip_xmit_v4 to trigger the arp resolve, so
24967 			 * that we can continue with the send on the next
24968 			 * attempt.
24969 			 *
24970 			 * XXX THis should be revisited, when
24971 			 * the IPsec/IP interaction is cleaned up
24972 			 */
24973 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
24974 			    " - dropping packet\n"));
24975 			freemsg(ipsec_mp);
24976 			/*
24977 			 * Call ip_xmit_v4() to trigger ARP query
24978 			 * in case the nce_state is ND_INITIAL
24979 			 */
24980 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24981 			goto drop_pkt;
24982 		}
24983 
24984 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
24985 		pktxmit_state = ip_xmit_v4(mp, ire,
24986 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
24987 
24988 		if ((pktxmit_state ==  SEND_FAILED) ||
24989 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
24990 
24991 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
24992 drop_pkt:
24993 			BUMP_MIB(&ip_mib, ipOutDiscards);
24994 			if (ire_need_rele)
24995 				ire_refrele(ire);
24996 			if (ire1 != NULL) {
24997 				ire_refrele(ire1);
24998 				freemsg(next_mp);
24999 			}
25000 			goto done;
25001 		}
25002 
25003 		freeb(ipsec_mp);
25004 		if (ire_need_rele)
25005 			ire_refrele(ire);
25006 
25007 		if (ire1 != NULL) {
25008 			ire = ire1;
25009 			ire_need_rele = B_TRUE;
25010 			ASSERT(next_mp);
25011 			ipsec_mp = next_mp;
25012 			mp = ipsec_mp->b_cont;
25013 			ire1 = NULL;
25014 			next_mp = NULL;
25015 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
25016 		} else {
25017 			multirt_send = B_FALSE;
25018 		}
25019 	} while (multirt_send);
25020 done:
25021 	if (ill != NULL && ill_need_rele)
25022 		ill_refrele(ill);
25023 	if (ipif != NULL)
25024 		ipif_refrele(ipif);
25025 }
25026 
25027 /*
25028  * Get the ill corresponding to the specified ire, and compare its
25029  * capabilities with the protocol and algorithms specified by the
25030  * the SA obtained from ipsec_out. If they match, annotate the
25031  * ipsec_out structure to indicate that the packet needs acceleration.
25032  *
25033  *
25034  * A packet is eligible for outbound hardware acceleration if the
25035  * following conditions are satisfied:
25036  *
25037  * 1. the packet will not be fragmented
25038  * 2. the provider supports the algorithm
25039  * 3. there is no pending control message being exchanged
25040  * 4. snoop is not attached
25041  * 5. the destination address is not a broadcast or multicast address.
25042  *
25043  * Rationale:
25044  *	- Hardware drivers do not support fragmentation with
25045  *	  the current interface.
25046  *	- snoop, multicast, and broadcast may result in exposure of
25047  *	  a cleartext datagram.
25048  * We check all five of these conditions here.
25049  *
25050  * XXX would like to nuke "ire_t *" parameter here; problem is that
25051  * IRE is only way to figure out if a v4 address is a broadcast and
25052  * thus ineligible for acceleration...
25053  */
25054 static void
25055 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
25056 {
25057 	ipsec_out_t *io;
25058 	mblk_t *data_mp;
25059 	uint_t plen, overhead;
25060 
25061 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
25062 		return;
25063 
25064 	if (ill == NULL)
25065 		return;
25066 
25067 	/*
25068 	 * Destination address is a broadcast or multicast.  Punt.
25069 	 */
25070 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
25071 	    IRE_LOCAL)))
25072 		return;
25073 
25074 	data_mp = ipsec_mp->b_cont;
25075 
25076 	if (ill->ill_isv6) {
25077 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
25078 
25079 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
25080 			return;
25081 
25082 		plen = ip6h->ip6_plen;
25083 	} else {
25084 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
25085 
25086 		if (CLASSD(ipha->ipha_dst))
25087 			return;
25088 
25089 		plen = ipha->ipha_length;
25090 	}
25091 	/*
25092 	 * Is there a pending DLPI control message being exchanged
25093 	 * between IP/IPsec and the DLS Provider? If there is, it
25094 	 * could be a SADB update, and the state of the DLS Provider
25095 	 * SADB might not be in sync with the SADB maintained by
25096 	 * IPsec. To avoid dropping packets or using the wrong keying
25097 	 * material, we do not accelerate this packet.
25098 	 */
25099 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
25100 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25101 		    "ill_dlpi_pending! don't accelerate packet\n"));
25102 		return;
25103 	}
25104 
25105 	/*
25106 	 * Is the Provider in promiscous mode? If it does, we don't
25107 	 * accelerate the packet since it will bounce back up to the
25108 	 * listeners in the clear.
25109 	 */
25110 	if (ill->ill_promisc_on_phys) {
25111 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25112 		    "ill in promiscous mode, don't accelerate packet\n"));
25113 		return;
25114 	}
25115 
25116 	/*
25117 	 * Will the packet require fragmentation?
25118 	 */
25119 
25120 	/*
25121 	 * IPsec ESP note: this is a pessimistic estimate, but the same
25122 	 * as is used elsewhere.
25123 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
25124 	 *	+ 2-byte trailer
25125 	 */
25126 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
25127 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
25128 
25129 	if ((plen + overhead) > ill->ill_max_mtu)
25130 		return;
25131 
25132 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25133 
25134 	/*
25135 	 * Can the ill accelerate this IPsec protocol and algorithm
25136 	 * specified by the SA?
25137 	 */
25138 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
25139 	    ill->ill_isv6, sa)) {
25140 		return;
25141 	}
25142 
25143 	/*
25144 	 * Tell AH or ESP that the outbound ill is capable of
25145 	 * accelerating this packet.
25146 	 */
25147 	io->ipsec_out_is_capab_ill = B_TRUE;
25148 }
25149 
25150 /*
25151  * Select which AH & ESP SA's to use (if any) for the outbound packet.
25152  *
25153  * If this function returns B_TRUE, the requested SA's have been filled
25154  * into the ipsec_out_*_sa pointers.
25155  *
25156  * If the function returns B_FALSE, the packet has been "consumed", most
25157  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
25158  *
25159  * The SA references created by the protocol-specific "select"
25160  * function will be released when the ipsec_mp is freed, thanks to the
25161  * ipsec_out_free destructor -- see spd.c.
25162  */
25163 static boolean_t
25164 ipsec_out_select_sa(mblk_t *ipsec_mp)
25165 {
25166 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
25167 	ipsec_out_t *io;
25168 	ipsec_policy_t *pp;
25169 	ipsec_action_t *ap;
25170 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25171 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25172 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25173 
25174 	if (!io->ipsec_out_secure) {
25175 		/*
25176 		 * We came here by mistake.
25177 		 * Don't bother with ipsec processing
25178 		 * We should "discourage" this path in the future.
25179 		 */
25180 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25181 		return (B_FALSE);
25182 	}
25183 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25184 	ASSERT((io->ipsec_out_policy != NULL) ||
25185 	    (io->ipsec_out_act != NULL));
25186 
25187 	ASSERT(io->ipsec_out_failed == B_FALSE);
25188 
25189 	/*
25190 	 * IPSEC processing has started.
25191 	 */
25192 	io->ipsec_out_proc_begin = B_TRUE;
25193 	ap = io->ipsec_out_act;
25194 	if (ap == NULL) {
25195 		pp = io->ipsec_out_policy;
25196 		ASSERT(pp != NULL);
25197 		ap = pp->ipsp_act;
25198 		ASSERT(ap != NULL);
25199 	}
25200 
25201 	/*
25202 	 * We have an action.  now, let's select SA's.
25203 	 * (In the future, we can cache this in the conn_t..)
25204 	 */
25205 	if (ap->ipa_want_esp) {
25206 		if (io->ipsec_out_esp_sa == NULL) {
25207 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
25208 			    IPPROTO_ESP);
25209 		}
25210 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
25211 	}
25212 
25213 	if (ap->ipa_want_ah) {
25214 		if (io->ipsec_out_ah_sa == NULL) {
25215 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
25216 			    IPPROTO_AH);
25217 		}
25218 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
25219 		/*
25220 		 * The ESP and AH processing order needs to be preserved
25221 		 * when both protocols are required (ESP should be applied
25222 		 * before AH for an outbound packet). Force an ESP ACQUIRE
25223 		 * when both ESP and AH are required, and an AH ACQUIRE
25224 		 * is needed.
25225 		 */
25226 		if (ap->ipa_want_esp && need_ah_acquire)
25227 			need_esp_acquire = B_TRUE;
25228 	}
25229 
25230 	/*
25231 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
25232 	 * Release SAs that got referenced, but will not be used until we
25233 	 * acquire _all_ of the SAs we need.
25234 	 */
25235 	if (need_ah_acquire || need_esp_acquire) {
25236 		if (io->ipsec_out_ah_sa != NULL) {
25237 			IPSA_REFRELE(io->ipsec_out_ah_sa);
25238 			io->ipsec_out_ah_sa = NULL;
25239 		}
25240 		if (io->ipsec_out_esp_sa != NULL) {
25241 			IPSA_REFRELE(io->ipsec_out_esp_sa);
25242 			io->ipsec_out_esp_sa = NULL;
25243 		}
25244 
25245 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
25246 		return (B_FALSE);
25247 	}
25248 
25249 	return (B_TRUE);
25250 }
25251 
25252 /*
25253  * Process an IPSEC_OUT message and see what you can
25254  * do with it.
25255  * IPQoS Notes:
25256  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
25257  * IPSec.
25258  * XXX would like to nuke ire_t.
25259  * XXX ill_index better be "real"
25260  */
25261 void
25262 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
25263 {
25264 	ipsec_out_t *io;
25265 	ipsec_policy_t *pp;
25266 	ipsec_action_t *ap;
25267 	ipha_t *ipha;
25268 	ip6_t *ip6h;
25269 	mblk_t *mp;
25270 	ill_t *ill;
25271 	zoneid_t zoneid;
25272 	ipsec_status_t ipsec_rc;
25273 	boolean_t ill_need_rele = B_FALSE;
25274 
25275 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25276 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25277 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25278 	mp = ipsec_mp->b_cont;
25279 
25280 	/*
25281 	 * Initiate IPPF processing. We do it here to account for packets
25282 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
25283 	 * We can check for ipsec_out_proc_begin even for such packets, as
25284 	 * they will always be false (asserted below).
25285 	 */
25286 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
25287 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
25288 		    io->ipsec_out_ill_index : ill_index);
25289 		if (mp == NULL) {
25290 			ip2dbg(("ipsec_out_process: packet dropped "\
25291 			    "during IPPF processing\n"));
25292 			freeb(ipsec_mp);
25293 			BUMP_MIB(&ip_mib, ipOutDiscards);
25294 			return;
25295 		}
25296 	}
25297 
25298 	if (!io->ipsec_out_secure) {
25299 		/*
25300 		 * We came here by mistake.
25301 		 * Don't bother with ipsec processing
25302 		 * Should "discourage" this path in the future.
25303 		 */
25304 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25305 		goto done;
25306 	}
25307 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25308 	ASSERT((io->ipsec_out_policy != NULL) ||
25309 	    (io->ipsec_out_act != NULL));
25310 	ASSERT(io->ipsec_out_failed == B_FALSE);
25311 
25312 	if (!ipsec_loaded()) {
25313 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
25314 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25315 			BUMP_MIB(&ip_mib, ipOutDiscards);
25316 		} else {
25317 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
25318 		}
25319 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
25320 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
25321 		return;
25322 	}
25323 
25324 	/*
25325 	 * IPSEC processing has started.
25326 	 */
25327 	io->ipsec_out_proc_begin = B_TRUE;
25328 	ap = io->ipsec_out_act;
25329 	if (ap == NULL) {
25330 		pp = io->ipsec_out_policy;
25331 		ASSERT(pp != NULL);
25332 		ap = pp->ipsp_act;
25333 		ASSERT(ap != NULL);
25334 	}
25335 
25336 	/*
25337 	 * Save the outbound ill index. When the packet comes back
25338 	 * from IPsec, we make sure the ill hasn't changed or disappeared
25339 	 * before sending it the accelerated packet.
25340 	 */
25341 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
25342 		int ifindex;
25343 		ill = ire_to_ill(ire);
25344 		ifindex = ill->ill_phyint->phyint_ifindex;
25345 		io->ipsec_out_capab_ill_index = ifindex;
25346 	}
25347 
25348 	/*
25349 	 * The order of processing is first insert a IP header if needed.
25350 	 * Then insert the ESP header and then the AH header.
25351 	 */
25352 	if ((io->ipsec_out_se_done == B_FALSE) &&
25353 	    (ap->ipa_want_se)) {
25354 		/*
25355 		 * First get the outer IP header before sending
25356 		 * it to ESP.
25357 		 */
25358 		ipha_t *oipha, *iipha;
25359 		mblk_t *outer_mp, *inner_mp;
25360 
25361 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
25362 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
25363 			    "ipsec_out_process: "
25364 			    "Self-Encapsulation failed: Out of memory\n");
25365 			freemsg(ipsec_mp);
25366 			BUMP_MIB(&ip_mib, ipOutDiscards);
25367 			return;
25368 		}
25369 		inner_mp = ipsec_mp->b_cont;
25370 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
25371 		oipha = (ipha_t *)outer_mp->b_rptr;
25372 		iipha = (ipha_t *)inner_mp->b_rptr;
25373 		*oipha = *iipha;
25374 		outer_mp->b_wptr += sizeof (ipha_t);
25375 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
25376 		    sizeof (ipha_t));
25377 		oipha->ipha_protocol = IPPROTO_ENCAP;
25378 		oipha->ipha_version_and_hdr_length =
25379 		    IP_SIMPLE_HDR_VERSION;
25380 		oipha->ipha_hdr_checksum = 0;
25381 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
25382 		outer_mp->b_cont = inner_mp;
25383 		ipsec_mp->b_cont = outer_mp;
25384 
25385 		io->ipsec_out_se_done = B_TRUE;
25386 		io->ipsec_out_encaps = B_TRUE;
25387 	}
25388 
25389 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
25390 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
25391 	    !ipsec_out_select_sa(ipsec_mp))
25392 		return;
25393 
25394 	/*
25395 	 * By now, we know what SA's to use.  Toss over to ESP & AH
25396 	 * to do the heavy lifting.
25397 	 */
25398 	zoneid = io->ipsec_out_zoneid;
25399 	ASSERT(zoneid != ALL_ZONES);
25400 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
25401 		ASSERT(io->ipsec_out_esp_sa != NULL);
25402 		io->ipsec_out_esp_done = B_TRUE;
25403 		/*
25404 		 * Note that since hw accel can only apply one transform,
25405 		 * not two, we skip hw accel for ESP if we also have AH
25406 		 * This is an design limitation of the interface
25407 		 * which should be revisited.
25408 		 */
25409 		ASSERT(ire != NULL);
25410 		if (io->ipsec_out_ah_sa == NULL) {
25411 			ill = (ill_t *)ire->ire_stq->q_ptr;
25412 			ipsec_out_is_accelerated(ipsec_mp,
25413 			    io->ipsec_out_esp_sa, ill, ire);
25414 		}
25415 
25416 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
25417 		switch (ipsec_rc) {
25418 		case IPSEC_STATUS_SUCCESS:
25419 			break;
25420 		case IPSEC_STATUS_FAILED:
25421 			BUMP_MIB(&ip_mib, ipOutDiscards);
25422 			/* FALLTHRU */
25423 		case IPSEC_STATUS_PENDING:
25424 			return;
25425 		}
25426 	}
25427 
25428 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
25429 		ASSERT(io->ipsec_out_ah_sa != NULL);
25430 		io->ipsec_out_ah_done = B_TRUE;
25431 		if (ire == NULL) {
25432 			int idx = io->ipsec_out_capab_ill_index;
25433 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
25434 			    NULL, NULL, NULL, NULL);
25435 			ill_need_rele = B_TRUE;
25436 		} else {
25437 			ill = (ill_t *)ire->ire_stq->q_ptr;
25438 		}
25439 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
25440 		    ire);
25441 
25442 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
25443 		switch (ipsec_rc) {
25444 		case IPSEC_STATUS_SUCCESS:
25445 			break;
25446 		case IPSEC_STATUS_FAILED:
25447 			BUMP_MIB(&ip_mib, ipOutDiscards);
25448 			/* FALLTHRU */
25449 		case IPSEC_STATUS_PENDING:
25450 			if (ill != NULL && ill_need_rele)
25451 				ill_refrele(ill);
25452 			return;
25453 		}
25454 	}
25455 	/*
25456 	 * We are done with IPSEC processing. Send it over
25457 	 * the wire.
25458 	 */
25459 done:
25460 	mp = ipsec_mp->b_cont;
25461 	ipha = (ipha_t *)mp->b_rptr;
25462 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25463 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
25464 	} else {
25465 		ip6h = (ip6_t *)ipha;
25466 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
25467 	}
25468 	if (ill != NULL && ill_need_rele)
25469 		ill_refrele(ill);
25470 }
25471 
25472 /* ARGSUSED */
25473 void
25474 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
25475 {
25476 	opt_restart_t	*or;
25477 	int	err;
25478 	conn_t	*connp;
25479 
25480 	ASSERT(CONN_Q(q));
25481 	connp = Q_TO_CONN(q);
25482 
25483 	ASSERT(first_mp->b_datap->db_type == M_CTL);
25484 	or = (opt_restart_t *)first_mp->b_rptr;
25485 	/*
25486 	 * We don't need to pass any credentials here since this is just
25487 	 * a restart. The credentials are passed in when svr4_optcom_req
25488 	 * is called the first time (from ip_wput_nondata).
25489 	 */
25490 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
25491 		err = svr4_optcom_req(q, first_mp, NULL,
25492 		    &ip_opt_obj);
25493 	} else {
25494 		ASSERT(or->or_type == T_OPTMGMT_REQ);
25495 		err = tpi_optcom_req(q, first_mp, NULL,
25496 		    &ip_opt_obj);
25497 	}
25498 	if (err != EINPROGRESS) {
25499 		/* operation is done */
25500 		CONN_OPER_PENDING_DONE(connp);
25501 	}
25502 }
25503 
25504 /*
25505  * ioctls that go through a down/up sequence may need to wait for the down
25506  * to complete. This involves waiting for the ire and ipif refcnts to go down
25507  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
25508  */
25509 /* ARGSUSED */
25510 void
25511 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25512 {
25513 	struct iocblk *iocp;
25514 	mblk_t *mp1;
25515 	ipif_t	*ipif;
25516 	ip_ioctl_cmd_t *ipip;
25517 	int err;
25518 	sin_t	*sin;
25519 	struct lifreq *lifr;
25520 	struct ifreq *ifr;
25521 
25522 	iocp = (struct iocblk *)mp->b_rptr;
25523 	ASSERT(ipsq != NULL);
25524 	/* Existence of mp1 verified in ip_wput_nondata */
25525 	mp1 = mp->b_cont->b_cont;
25526 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25527 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
25528 		ill_t *ill;
25529 		/*
25530 		 * Special case where ipsq_current_ipif may not be set.
25531 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
25532 		 * ill could also have become part of a ipmp group in the
25533 		 * process, we are here as were not able to complete the
25534 		 * operation in ipif_set_values because we could not become
25535 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
25536 		 * will not be set so we need to set it.
25537 		 */
25538 		ill = (ill_t *)q->q_ptr;
25539 		ipsq->ipsq_current_ipif = ill->ill_ipif;
25540 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25541 	}
25542 
25543 	ipif = ipsq->ipsq_current_ipif;
25544 	ASSERT(ipif != NULL);
25545 	if (ipip->ipi_cmd_type == IF_CMD) {
25546 		/* This a old style SIOC[GS]IF* command */
25547 		ifr = (struct ifreq *)mp1->b_rptr;
25548 		sin = (sin_t *)&ifr->ifr_addr;
25549 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
25550 		/* This a new style SIOC[GS]LIF* command */
25551 		lifr = (struct lifreq *)mp1->b_rptr;
25552 		sin = (sin_t *)&lifr->lifr_addr;
25553 	} else {
25554 		sin = NULL;
25555 	}
25556 
25557 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
25558 	    (void *)mp1->b_rptr);
25559 
25560 	/* SIOCLIFREMOVEIF could have removed the ipif */
25561 	ip_ioctl_finish(q, mp, err,
25562 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25563 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
25564 }
25565 
25566 /*
25567  * ioctl processing
25568  *
25569  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
25570  * the ioctl command in the ioctl tables and determines the copyin data size
25571  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
25572  * size.
25573  *
25574  * ioctl processing then continues when the M_IOCDATA makes its way down.
25575  * Now the ioctl is looked up again in the ioctl table, and its properties are
25576  * extracted. The associated 'conn' is then refheld till the end of the ioctl
25577  * and the general ioctl processing function ip_process_ioctl is called.
25578  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
25579  * so goes thru the serialization primitive ipsq_try_enter. Then the
25580  * appropriate function to handle the ioctl is called based on the entry in
25581  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
25582  * which also refreleases the 'conn' that was refheld at the start of the
25583  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
25584  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
25585  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
25586  *
25587  * Many exclusive ioctls go thru an internal down up sequence as part of
25588  * the operation. For example an attempt to change the IP address of an
25589  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
25590  * does all the cleanup such as deleting all ires that use this address.
25591  * Then we need to wait till all references to the interface go away.
25592  */
25593 void
25594 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
25595 {
25596 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
25597 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
25598 	cmd_info_t ci;
25599 	int err;
25600 	boolean_t entered_ipsq = B_FALSE;
25601 
25602 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
25603 
25604 	if (ipip == NULL)
25605 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25606 
25607 	/*
25608 	 * SIOCLIFADDIF needs to go thru a special path since the
25609 	 * ill may not exist yet. This happens in the case of lo0
25610 	 * which is created using this ioctl.
25611 	 */
25612 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
25613 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
25614 		ip_ioctl_finish(q, mp, err,
25615 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25616 		    NULL, NULL);
25617 		return;
25618 	}
25619 
25620 	ci.ci_ipif = NULL;
25621 	switch (ipip->ipi_cmd_type) {
25622 	case IF_CMD:
25623 	case LIF_CMD:
25624 		/*
25625 		 * ioctls that pass in a [l]ifreq appear here.
25626 		 * ip_extract_lifreq_cmn returns a refheld ipif in
25627 		 * ci.ci_ipif
25628 		 */
25629 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
25630 		    ipip->ipi_flags, &ci, ip_process_ioctl);
25631 		if (err != 0) {
25632 			ip_ioctl_finish(q, mp, err,
25633 			    ipip->ipi_flags & IPI_GET_CMD ?
25634 			    COPYOUT : NO_COPYOUT, NULL, NULL);
25635 			return;
25636 		}
25637 		ASSERT(ci.ci_ipif != NULL);
25638 		break;
25639 
25640 	case TUN_CMD:
25641 		/*
25642 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
25643 		 * a refheld ipif in ci.ci_ipif
25644 		 */
25645 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
25646 		if (err != 0) {
25647 			ip_ioctl_finish(q, mp, err,
25648 			    ipip->ipi_flags & IPI_GET_CMD ?
25649 			    COPYOUT : NO_COPYOUT, NULL, NULL);
25650 			return;
25651 		}
25652 		ASSERT(ci.ci_ipif != NULL);
25653 		break;
25654 
25655 	case MISC_CMD:
25656 		/*
25657 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
25658 		 * For eg. SIOCGLIFCONF will appear here.
25659 		 */
25660 		switch (ipip->ipi_cmd) {
25661 		case IF_UNITSEL:
25662 			/* ioctl comes down the ill */
25663 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
25664 			ipif_refhold(ci.ci_ipif);
25665 			break;
25666 		case SIOCGMSFILTER:
25667 		case SIOCSMSFILTER:
25668 		case SIOCGIPMSFILTER:
25669 		case SIOCSIPMSFILTER:
25670 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
25671 			    ip_process_ioctl);
25672 			if (err != 0) {
25673 				ip_ioctl_finish(q, mp, err,
25674 				    ipip->ipi_flags & IPI_GET_CMD ?
25675 				    COPYOUT : NO_COPYOUT, NULL, NULL);
25676 				return;
25677 			}
25678 			break;
25679 		}
25680 		err = 0;
25681 		ci.ci_sin = NULL;
25682 		ci.ci_sin6 = NULL;
25683 		ci.ci_lifr = NULL;
25684 		break;
25685 	}
25686 
25687 	/*
25688 	 * If ipsq is non-null, we are already being called exclusively
25689 	 */
25690 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
25691 	if (!(ipip->ipi_flags & IPI_WR)) {
25692 		/*
25693 		 * A return value of EINPROGRESS means the ioctl is
25694 		 * either queued and waiting for some reason or has
25695 		 * already completed.
25696 		 */
25697 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25698 		    ci.ci_lifr);
25699 		if (ci.ci_ipif != NULL)
25700 			ipif_refrele(ci.ci_ipif);
25701 		ip_ioctl_finish(q, mp, err,
25702 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25703 		    NULL, NULL);
25704 		return;
25705 	}
25706 
25707 	ASSERT(ci.ci_ipif != NULL);
25708 
25709 	if (ipsq == NULL) {
25710 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
25711 		    ip_process_ioctl, NEW_OP, B_TRUE);
25712 		entered_ipsq = B_TRUE;
25713 	}
25714 	/*
25715 	 * Release the ipif so that ipif_down and friends that wait for
25716 	 * references to go away are not misled about the current ipif_refcnt
25717 	 * values. We are writer so we can access the ipif even after releasing
25718 	 * the ipif.
25719 	 */
25720 	ipif_refrele(ci.ci_ipif);
25721 	if (ipsq == NULL)
25722 		return;
25723 
25724 	mutex_enter(&ipsq->ipsq_lock);
25725 	ASSERT(ipsq->ipsq_current_ipif == NULL);
25726 	ipsq->ipsq_current_ipif = ci.ci_ipif;
25727 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25728 	mutex_exit(&ipsq->ipsq_lock);
25729 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
25730 	/*
25731 	 * For most set ioctls that come here, this serves as a single point
25732 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
25733 	 * be any new references to the ipif. This helps functions that go
25734 	 * through this path and end up trying to wait for the refcnts
25735 	 * associated with the ipif to go down to zero. Some exceptions are
25736 	 * Failover, Failback, and Groupname commands that operate on more than
25737 	 * just the ci.ci_ipif. These commands internally determine the
25738 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
25739 	 * flags on that set. Another exception is the Removeif command that
25740 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
25741 	 * ipif to operate on.
25742 	 */
25743 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
25744 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
25745 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
25746 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
25747 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
25748 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
25749 
25750 	/*
25751 	 * A return value of EINPROGRESS means the ioctl is
25752 	 * either queued and waiting for some reason or has
25753 	 * already completed.
25754 	 */
25755 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25756 	    ci.ci_lifr);
25757 
25758 	/* SIOCLIFREMOVEIF could have removed the ipif */
25759 	ip_ioctl_finish(q, mp, err,
25760 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25761 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
25762 
25763 	if (entered_ipsq)
25764 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
25765 }
25766 
25767 /*
25768  * Complete the ioctl. Typically ioctls use the mi package and need to
25769  * do mi_copyout/mi_copy_done.
25770  */
25771 void
25772 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
25773     ipif_t *ipif, ipsq_t *ipsq)
25774 {
25775 	conn_t	*connp = NULL;
25776 
25777 	if (err == EINPROGRESS)
25778 		return;
25779 
25780 	if (CONN_Q(q)) {
25781 		connp = Q_TO_CONN(q);
25782 		ASSERT(connp->conn_ref >= 2);
25783 	}
25784 
25785 	switch (mode) {
25786 	case COPYOUT:
25787 		if (err == 0)
25788 			mi_copyout(q, mp);
25789 		else
25790 			mi_copy_done(q, mp, err);
25791 		break;
25792 
25793 	case NO_COPYOUT:
25794 		mi_copy_done(q, mp, err);
25795 		break;
25796 
25797 	default:
25798 		/* An ioctl aborted through a conn close would take this path */
25799 		break;
25800 	}
25801 
25802 	/*
25803 	 * The refhold placed at the start of the ioctl is released here.
25804 	 */
25805 	if (connp != NULL)
25806 		CONN_OPER_PENDING_DONE(connp);
25807 
25808 	/*
25809 	 * If the ioctl were an exclusive ioctl it would have set
25810 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
25811 	 */
25812 	if (ipif != NULL) {
25813 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
25814 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
25815 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
25816 	}
25817 
25818 	/*
25819 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
25820 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
25821 	 * entering the ipsq
25822 	 */
25823 	if (ipsq != NULL) {
25824 		mutex_enter(&ipsq->ipsq_lock);
25825 		ipsq->ipsq_current_ipif = NULL;
25826 		mutex_exit(&ipsq->ipsq_lock);
25827 	}
25828 }
25829 
25830 /*
25831  * This is called from ip_wput_nondata to resume a deferred TCP bind.
25832  */
25833 /* ARGSUSED */
25834 void
25835 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
25836 {
25837 	conn_t *connp = arg;
25838 	tcp_t	*tcp;
25839 
25840 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
25841 	tcp = connp->conn_tcp;
25842 
25843 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
25844 		freemsg(mp);
25845 	else
25846 		tcp_rput_other(tcp, mp);
25847 	CONN_OPER_PENDING_DONE(connp);
25848 }
25849 
25850 /* Called from ip_wput for all non data messages */
25851 /* ARGSUSED */
25852 void
25853 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25854 {
25855 	mblk_t		*mp1;
25856 	ire_t		*ire, *fake_ire;
25857 	ill_t		*ill;
25858 	struct iocblk	*iocp;
25859 	ip_ioctl_cmd_t	*ipip;
25860 	cred_t		*cr;
25861 	conn_t		*connp = NULL;
25862 	int		cmd, err;
25863 	nce_t		*nce;
25864 	ipif_t		*ipif;
25865 
25866 	if (CONN_Q(q))
25867 		connp = Q_TO_CONN(q);
25868 
25869 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
25870 
25871 	/* Check if it is a queue to /dev/sctp. */
25872 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
25873 	    connp->conn_rq == NULL) {
25874 		sctp_wput(q, mp);
25875 		return;
25876 	}
25877 
25878 	switch (DB_TYPE(mp)) {
25879 	case M_IOCTL:
25880 		/*
25881 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
25882 		 * will arrange to copy in associated control structures.
25883 		 */
25884 		ip_sioctl_copyin_setup(q, mp);
25885 		return;
25886 	case M_IOCDATA:
25887 		/*
25888 		 * Ensure that this is associated with one of our trans-
25889 		 * parent ioctls.  If it's not ours, discard it if we're
25890 		 * running as a driver, or pass it on if we're a module.
25891 		 */
25892 		iocp = (struct iocblk *)mp->b_rptr;
25893 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25894 		if (ipip == NULL) {
25895 			if (q->q_next == NULL) {
25896 				goto nak;
25897 			} else {
25898 				putnext(q, mp);
25899 			}
25900 			return;
25901 		} else if ((q->q_next != NULL) &&
25902 		    !(ipip->ipi_flags & IPI_MODOK)) {
25903 			/*
25904 			 * the ioctl is one we recognise, but is not
25905 			 * consumed by IP as a module, pass M_IOCDATA
25906 			 * for processing downstream, but only for
25907 			 * common Streams ioctls.
25908 			 */
25909 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
25910 				putnext(q, mp);
25911 				return;
25912 			} else {
25913 				goto nak;
25914 			}
25915 		}
25916 
25917 		/* IOCTL continuation following copyin or copyout. */
25918 		if (mi_copy_state(q, mp, NULL) == -1) {
25919 			/*
25920 			 * The copy operation failed.  mi_copy_state already
25921 			 * cleaned up, so we're out of here.
25922 			 */
25923 			return;
25924 		}
25925 		/*
25926 		 * If we just completed a copy in, we become writer and
25927 		 * continue processing in ip_sioctl_copyin_done.  If it
25928 		 * was a copy out, we call mi_copyout again.  If there is
25929 		 * nothing more to copy out, it will complete the IOCTL.
25930 		 */
25931 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
25932 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
25933 				mi_copy_done(q, mp, EPROTO);
25934 				return;
25935 			}
25936 			/*
25937 			 * Check for cases that need more copying.  A return
25938 			 * value of 0 means a second copyin has been started,
25939 			 * so we return; a return value of 1 means no more
25940 			 * copying is needed, so we continue.
25941 			 */
25942 			cmd = iocp->ioc_cmd;
25943 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
25944 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
25945 			    MI_COPY_COUNT(mp) == 1) {
25946 				if (ip_copyin_msfilter(q, mp) == 0)
25947 					return;
25948 			}
25949 			/*
25950 			 * Refhold the conn, till the ioctl completes. This is
25951 			 * needed in case the ioctl ends up in the pending mp
25952 			 * list. Every mp in the ill_pending_mp list and
25953 			 * the ipsq_pending_mp must have a refhold on the conn
25954 			 * to resume processing. The refhold is released when
25955 			 * the ioctl completes. (normally or abnormally)
25956 			 * In all cases ip_ioctl_finish is called to finish
25957 			 * the ioctl.
25958 			 */
25959 			if (connp != NULL) {
25960 				/* This is not a reentry */
25961 				ASSERT(ipsq == NULL);
25962 				CONN_INC_REF(connp);
25963 			} else {
25964 				if (!(ipip->ipi_flags & IPI_MODOK)) {
25965 					mi_copy_done(q, mp, EINVAL);
25966 					return;
25967 				}
25968 			}
25969 
25970 			ip_process_ioctl(ipsq, q, mp, ipip);
25971 
25972 		} else {
25973 			mi_copyout(q, mp);
25974 		}
25975 		return;
25976 nak:
25977 		iocp->ioc_error = EINVAL;
25978 		mp->b_datap->db_type = M_IOCNAK;
25979 		iocp->ioc_count = 0;
25980 		qreply(q, mp);
25981 		return;
25982 
25983 	case M_IOCNAK:
25984 		/*
25985 		 * The only way we could get here is if a resolver didn't like
25986 		 * an IOCTL we sent it.	 This shouldn't happen.
25987 		 */
25988 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
25989 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
25990 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
25991 		freemsg(mp);
25992 		return;
25993 	case M_IOCACK:
25994 		/* Finish socket ioctls passed through to ARP. */
25995 		ip_sioctl_iocack(q, mp);
25996 		return;
25997 	case M_FLUSH:
25998 		if (*mp->b_rptr & FLUSHW)
25999 			flushq(q, FLUSHALL);
26000 		if (q->q_next) {
26001 			/*
26002 			 * M_FLUSH is sent up to IP by some drivers during
26003 			 * unbind. ip_rput has already replied to it. We are
26004 			 * here for the M_FLUSH that we originated in IP
26005 			 * before sending the unbind request to the driver.
26006 			 * Just free it as we don't queue packets in IP
26007 			 * on the write side of the device instance.
26008 			 */
26009 			freemsg(mp);
26010 			return;
26011 		}
26012 		if (*mp->b_rptr & FLUSHR) {
26013 			*mp->b_rptr &= ~FLUSHW;
26014 			qreply(q, mp);
26015 			return;
26016 		}
26017 		freemsg(mp);
26018 		return;
26019 	case IRE_DB_REQ_TYPE:
26020 		/* An Upper Level Protocol wants a copy of an IRE. */
26021 		ip_ire_req(q, mp);
26022 		return;
26023 	case M_CTL:
26024 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
26025 			break;
26026 
26027 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
26028 		    IP_ULP_OUT_LABELED) {
26029 			out_labeled_t *olp;
26030 
26031 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
26032 				break;
26033 			olp = (out_labeled_t *)mp->b_rptr;
26034 			connp->conn_ulp_labeled = olp->out_qnext == q;
26035 			freemsg(mp);
26036 			return;
26037 		}
26038 
26039 		/* M_CTL messages are used by ARP to tell us things. */
26040 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
26041 			break;
26042 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
26043 		case AR_ENTRY_SQUERY:
26044 			ip_wput_ctl(q, mp);
26045 			return;
26046 		case AR_CLIENT_NOTIFY:
26047 			ip_arp_news(q, mp);
26048 			return;
26049 		case AR_DLPIOP_DONE:
26050 			ASSERT(q->q_next != NULL);
26051 			ill = (ill_t *)q->q_ptr;
26052 			/* qwriter_ip releases the refhold */
26053 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
26054 			ill_refhold(ill);
26055 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
26056 			    CUR_OP, B_FALSE);
26057 			return;
26058 		case AR_ARP_CLOSING:
26059 			/*
26060 			 * ARP (above us) is closing. If no ARP bringup is
26061 			 * currently pending, ack the message so that ARP
26062 			 * can complete its close. Also mark ill_arp_closing
26063 			 * so that new ARP bringups will fail. If any
26064 			 * ARP bringup is currently in progress, we will
26065 			 * ack this when the current ARP bringup completes.
26066 			 */
26067 			ASSERT(q->q_next != NULL);
26068 			ill = (ill_t *)q->q_ptr;
26069 			mutex_enter(&ill->ill_lock);
26070 			ill->ill_arp_closing = 1;
26071 			if (!ill->ill_arp_bringup_pending) {
26072 				mutex_exit(&ill->ill_lock);
26073 				qreply(q, mp);
26074 			} else {
26075 				mutex_exit(&ill->ill_lock);
26076 				freemsg(mp);
26077 			}
26078 			return;
26079 		case AR_ARP_EXTEND:
26080 			/*
26081 			 * The ARP module above us is capable of duplicate
26082 			 * address detection.  Old ATM drivers will not send
26083 			 * this message.
26084 			 */
26085 			ASSERT(q->q_next != NULL);
26086 			ill = (ill_t *)q->q_ptr;
26087 			ill->ill_arp_extend = B_TRUE;
26088 			freemsg(mp);
26089 			return;
26090 		default:
26091 			break;
26092 		}
26093 		break;
26094 	case M_PROTO:
26095 	case M_PCPROTO:
26096 		/*
26097 		 * The only PROTO messages we expect are ULP binds and
26098 		 * copies of option negotiation acknowledgements.
26099 		 */
26100 		switch (((union T_primitives *)mp->b_rptr)->type) {
26101 		case O_T_BIND_REQ:
26102 		case T_BIND_REQ: {
26103 			/* Request can get queued in bind */
26104 			ASSERT(connp != NULL);
26105 			/*
26106 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
26107 			 * instead of going through this path.  We only get
26108 			 * here in the following cases:
26109 			 *
26110 			 * a. Bind retries, where ipsq is non-NULL.
26111 			 * b. T_BIND_REQ is issued from non TCP/UDP
26112 			 *    transport, e.g. icmp for raw socket,
26113 			 *    in which case ipsq will be NULL.
26114 			 */
26115 			ASSERT(ipsq != NULL ||
26116 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
26117 
26118 			/* Don't increment refcnt if this is a re-entry */
26119 			if (ipsq == NULL)
26120 				CONN_INC_REF(connp);
26121 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
26122 			    connp, NULL) : ip_bind_v4(q, mp, connp);
26123 			if (mp == NULL)
26124 				return;
26125 			if (IPCL_IS_TCP(connp)) {
26126 				/*
26127 				 * In the case of TCP endpoint we
26128 				 * come here only for bind retries
26129 				 */
26130 				ASSERT(ipsq != NULL);
26131 				CONN_INC_REF(connp);
26132 				squeue_fill(connp->conn_sqp, mp,
26133 				    ip_resume_tcp_bind, connp,
26134 				    SQTAG_BIND_RETRY);
26135 				return;
26136 			} else if (IPCL_IS_UDP(connp)) {
26137 				/*
26138 				 * In the case of UDP endpoint we
26139 				 * come here only for bind retries
26140 				 */
26141 				ASSERT(ipsq != NULL);
26142 				udp_resume_bind(connp, mp);
26143 				return;
26144 			}
26145 			qreply(q, mp);
26146 			CONN_OPER_PENDING_DONE(connp);
26147 			return;
26148 		}
26149 		case T_SVR4_OPTMGMT_REQ:
26150 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
26151 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
26152 
26153 			ASSERT(connp != NULL);
26154 			if (!snmpcom_req(q, mp, ip_snmp_set,
26155 			    ip_snmp_get, cr)) {
26156 				/*
26157 				 * Call svr4_optcom_req so that it can
26158 				 * generate the ack. We don't come here
26159 				 * if this operation is being restarted.
26160 				 * ip_restart_optmgmt will drop the conn ref.
26161 				 * In the case of ipsec option after the ipsec
26162 				 * load is complete conn_restart_ipsec_waiter
26163 				 * drops the conn ref.
26164 				 */
26165 				ASSERT(ipsq == NULL);
26166 				CONN_INC_REF(connp);
26167 				if (ip_check_for_ipsec_opt(q, mp))
26168 					return;
26169 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
26170 				if (err != EINPROGRESS) {
26171 					/* Operation is done */
26172 					CONN_OPER_PENDING_DONE(connp);
26173 				}
26174 			}
26175 			return;
26176 		case T_OPTMGMT_REQ:
26177 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
26178 			/*
26179 			 * Note: No snmpcom_req support through new
26180 			 * T_OPTMGMT_REQ.
26181 			 * Call tpi_optcom_req so that it can
26182 			 * generate the ack.
26183 			 */
26184 			ASSERT(connp != NULL);
26185 			ASSERT(ipsq == NULL);
26186 			/*
26187 			 * We don't come here for restart. ip_restart_optmgmt
26188 			 * will drop the conn ref. In the case of ipsec option
26189 			 * after the ipsec load is complete
26190 			 * conn_restart_ipsec_waiter drops the conn ref.
26191 			 */
26192 			CONN_INC_REF(connp);
26193 			if (ip_check_for_ipsec_opt(q, mp))
26194 				return;
26195 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
26196 			if (err != EINPROGRESS) {
26197 				/* Operation is done */
26198 				CONN_OPER_PENDING_DONE(connp);
26199 			}
26200 			return;
26201 		case T_UNBIND_REQ:
26202 			mp = ip_unbind(q, mp);
26203 			qreply(q, mp);
26204 			return;
26205 		default:
26206 			/*
26207 			 * Have to drop any DLPI messages coming down from
26208 			 * arp (such as an info_req which would cause ip
26209 			 * to receive an extra info_ack if it was passed
26210 			 * through.
26211 			 */
26212 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
26213 			    (int)*(uint_t *)mp->b_rptr));
26214 			freemsg(mp);
26215 			return;
26216 		}
26217 		/* NOTREACHED */
26218 	case IRE_DB_TYPE: {
26219 		nce_t		*nce;
26220 		ill_t		*ill;
26221 		in6_addr_t	gw_addr_v6;
26222 
26223 
26224 		/*
26225 		 * This is a response back from a resolver.  It
26226 		 * consists of a message chain containing:
26227 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
26228 		 * The IRE_MBLK is the one we allocated in ip_newroute.
26229 		 * The LL_HDR_MBLK is the DLPI header to use to get
26230 		 * the attached packet, and subsequent ones for the
26231 		 * same destination, transmitted.
26232 		 */
26233 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
26234 			break;
26235 		/*
26236 		 * First, check to make sure the resolution succeeded.
26237 		 * If it failed, the second mblk will be empty.
26238 		 * If it is, free the chain, dropping the packet.
26239 		 * (We must ire_delete the ire; that frees the ire mblk)
26240 		 * We're doing this now to support PVCs for ATM; it's
26241 		 * a partial xresolv implementation. When we fully implement
26242 		 * xresolv interfaces, instead of freeing everything here
26243 		 * we'll initiate neighbor discovery.
26244 		 *
26245 		 * For v4 (ARP and other external resolvers) the resolver
26246 		 * frees the message, so no check is needed. This check
26247 		 * is required, though, for a full xresolve implementation.
26248 		 * Including this code here now both shows how external
26249 		 * resolvers can NACK a resolution request using an
26250 		 * existing design that has no specific provisions for NACKs,
26251 		 * and also takes into account that the current non-ARP
26252 		 * external resolver has been coded to use this method of
26253 		 * NACKing for all IPv6 (xresolv) cases,
26254 		 * whether our xresolv implementation is complete or not.
26255 		 *
26256 		 */
26257 		ire = (ire_t *)mp->b_rptr;
26258 		ill = ire_to_ill(ire);
26259 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26260 		if (mp1->b_rptr == mp1->b_wptr) {
26261 			if (ire->ire_ipversion == IPV6_VERSION) {
26262 				/*
26263 				 * XRESOLV interface.
26264 				 */
26265 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
26266 				mutex_enter(&ire->ire_lock);
26267 				gw_addr_v6 = ire->ire_gateway_addr_v6;
26268 				mutex_exit(&ire->ire_lock);
26269 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26270 					nce = ndp_lookup_v6(ill,
26271 					    &ire->ire_addr_v6, B_FALSE);
26272 				} else {
26273 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
26274 					    B_FALSE);
26275 				}
26276 				if (nce != NULL) {
26277 					nce_resolv_failed(nce);
26278 					ndp_delete(nce);
26279 					NCE_REFRELE(nce);
26280 				}
26281 			}
26282 			mp->b_cont = NULL;
26283 			freemsg(mp1);		/* frees the pkt as well */
26284 			ASSERT(ire->ire_nce == NULL);
26285 			ire_delete((ire_t *)mp->b_rptr);
26286 			return;
26287 		}
26288 
26289 		/*
26290 		 * Split them into IRE_MBLK and pkt and feed it into
26291 		 * ire_add_then_send. Then in ire_add_then_send
26292 		 * the IRE will be added, and then the packet will be
26293 		 * run back through ip_wput. This time it will make
26294 		 * it to the wire.
26295 		 */
26296 		mp->b_cont = NULL;
26297 		mp = mp1->b_cont;		/* now, mp points to pkt */
26298 		mp1->b_cont = NULL;
26299 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
26300 		if (ire->ire_ipversion == IPV6_VERSION) {
26301 			/*
26302 			 * XRESOLV interface. Find the nce and put a copy
26303 			 * of the dl_unitdata_req in nce_res_mp
26304 			 */
26305 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
26306 			mutex_enter(&ire->ire_lock);
26307 			gw_addr_v6 = ire->ire_gateway_addr_v6;
26308 			mutex_exit(&ire->ire_lock);
26309 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26310 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
26311 				    B_FALSE);
26312 			} else {
26313 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
26314 			}
26315 			if (nce != NULL) {
26316 				/*
26317 				 * We have to protect nce_res_mp here
26318 				 * from being accessed by other threads
26319 				 * while we change the mblk pointer.
26320 				 * Other functions will also lock the nce when
26321 				 * accessing nce_res_mp.
26322 				 *
26323 				 * The reason we change the mblk pointer
26324 				 * here rather than copying the resolved address
26325 				 * into the template is that, unlike with
26326 				 * ethernet, we have no guarantee that the
26327 				 * resolved address length will be
26328 				 * smaller than or equal to the lla length
26329 				 * with which the template was allocated,
26330 				 * (for ethernet, they're equal)
26331 				 * so we have to use the actual resolved
26332 				 * address mblk - which holds the real
26333 				 * dl_unitdata_req with the resolved address.
26334 				 *
26335 				 * Doing this is the same behavior as was
26336 				 * previously used in the v4 ARP case.
26337 				 */
26338 				mutex_enter(&nce->nce_lock);
26339 				if (nce->nce_res_mp != NULL)
26340 					freemsg(nce->nce_res_mp);
26341 				nce->nce_res_mp = mp1;
26342 				mutex_exit(&nce->nce_lock);
26343 				/*
26344 				 * We do a fastpath probe here because
26345 				 * we have resolved the address without
26346 				 * using Neighbor Discovery.
26347 				 * In the non-XRESOLV v6 case, the fastpath
26348 				 * probe is done right after neighbor
26349 				 * discovery completes.
26350 				 */
26351 				if (nce->nce_res_mp != NULL) {
26352 					int res;
26353 					nce_fastpath_list_add(nce);
26354 					res = ill_fastpath_probe(ill,
26355 					    nce->nce_res_mp);
26356 					if (res != 0 && res != EAGAIN)
26357 						nce_fastpath_list_delete(nce);
26358 				}
26359 
26360 				ire_add_then_send(q, ire, mp);
26361 				/*
26362 				 * Now we have to clean out any packets
26363 				 * that may have been queued on the nce
26364 				 * while it was waiting for address resolution
26365 				 * to complete.
26366 				 */
26367 				mutex_enter(&nce->nce_lock);
26368 				mp1 = nce->nce_qd_mp;
26369 				nce->nce_qd_mp = NULL;
26370 				mutex_exit(&nce->nce_lock);
26371 				while (mp1 != NULL) {
26372 					mblk_t *nxt_mp;
26373 					queue_t *fwdq = NULL;
26374 					ill_t   *inbound_ill;
26375 					uint_t ifindex;
26376 
26377 					nxt_mp = mp1->b_next;
26378 					mp1->b_next = NULL;
26379 					/*
26380 					 * Retrieve ifindex stored in
26381 					 * ip_rput_data_v6()
26382 					 */
26383 					ifindex =
26384 					    (uint_t)(uintptr_t)mp1->b_prev;
26385 					inbound_ill =
26386 						ill_lookup_on_ifindex(ifindex,
26387 						    B_TRUE, NULL, NULL, NULL,
26388 						    NULL);
26389 					mp1->b_prev = NULL;
26390 					if (inbound_ill != NULL)
26391 						fwdq = inbound_ill->ill_rq;
26392 
26393 					if (fwdq != NULL) {
26394 						put(fwdq, mp1);
26395 						ill_refrele(inbound_ill);
26396 					} else
26397 						put(WR(ill->ill_rq), mp1);
26398 					mp1 = nxt_mp;
26399 				}
26400 				NCE_REFRELE(nce);
26401 			} else {	/* nce is NULL; clean up */
26402 				ire_delete(ire);
26403 				freemsg(mp);
26404 				freemsg(mp1);
26405 				return;
26406 			}
26407 		} else {
26408 			nce_t *arpce;
26409 			/*
26410 			 * Link layer resolution succeeded. Recompute the
26411 			 * ire_nce.
26412 			 */
26413 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
26414 			if ((arpce = ndp_lookup_v4(ill,
26415 			    (ire->ire_gateway_addr != INADDR_ANY ?
26416 			    &ire->ire_gateway_addr : &ire->ire_addr),
26417 			    B_FALSE)) == NULL) {
26418 				freeb(ire->ire_mp);
26419 				freeb(mp1);
26420 				freemsg(mp);
26421 				return;
26422 			}
26423 			mutex_enter(&arpce->nce_lock);
26424 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
26425 			if (arpce->nce_state == ND_REACHABLE) {
26426 				/*
26427 				 * Someone resolved this before us;
26428 				 * cleanup the res_mp. Since ire has
26429 				 * not been added yet, the call to ire_add_v4
26430 				 * from ire_add_then_send (when a dup is
26431 				 * detected) will clean up the ire.
26432 				 */
26433 				freeb(mp1);
26434 			} else {
26435 				if (arpce->nce_res_mp != NULL)
26436 					freemsg(arpce->nce_res_mp);
26437 				arpce->nce_res_mp = mp1;
26438 				arpce->nce_state = ND_REACHABLE;
26439 			}
26440 			mutex_exit(&arpce->nce_lock);
26441 			if (ire->ire_marks & IRE_MARK_NOADD) {
26442 				/*
26443 				 * this ire will not be added to the ire
26444 				 * cache table, so we can set the ire_nce
26445 				 * here, as there are no atomicity constraints.
26446 				 */
26447 				ire->ire_nce = arpce;
26448 				/*
26449 				 * We are associating this nce with the ire
26450 				 * so change the nce ref taken in
26451 				 * ndp_lookup_v4() from
26452 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
26453 				 */
26454 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
26455 			} else {
26456 				NCE_REFRELE(arpce);
26457 			}
26458 			ire_add_then_send(q, ire, mp);
26459 		}
26460 		return;	/* All is well, the packet has been sent. */
26461 	}
26462 	case IRE_ARPRESOLVE_TYPE: {
26463 
26464 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
26465 			break;
26466 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26467 		mp->b_cont = NULL;
26468 		/*
26469 		 * First, check to make sure the resolution succeeded.
26470 		 * If it failed, the second mblk will be empty.
26471 		 */
26472 		if (mp1->b_rptr == mp1->b_wptr) {
26473 			/* cleanup  the incomplete ire, free queued packets */
26474 			freemsg(mp); /* fake ire */
26475 			freeb(mp1);  /* dl_unitdata response */
26476 			return;
26477 		}
26478 
26479 		/*
26480 		 * update any incomplete nce_t found. we lookup the ctable
26481 		 * and find the nce from the ire->ire_nce because we need
26482 		 * to pass the ire to ip_xmit_v4 later, and can find both
26483 		 * ire and nce in one lookup from the ctable.
26484 		 */
26485 		fake_ire = (ire_t *)mp->b_rptr;
26486 		/*
26487 		 * By the time we come back here from ARP
26488 		 * the logical outgoing interface  of the incomplete ire
26489 		 * we added in ire_forward could have disappeared,
26490 		 * causing the incomplete ire to also have
26491 		 * dissapeared. So we need to retreive the
26492 		 * proper ipif for the ire  before looking
26493 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
26494 		 */
26495 		ill = q->q_ptr;
26496 
26497 		/* Get the outgoing ipif */
26498 		mutex_enter(&ill->ill_lock);
26499 		if (ill->ill_state_flags & ILL_CONDEMNED) {
26500 			mutex_exit(&ill->ill_lock);
26501 			freemsg(mp); /* fake ire */
26502 			freeb(mp1);  /* dl_unitdata response */
26503 			return;
26504 		}
26505 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
26506 
26507 		if (ipif == NULL) {
26508 			mutex_exit(&ill->ill_lock);
26509 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
26510 			freemsg(mp);
26511 			freeb(mp1);
26512 			return;
26513 		}
26514 		ipif_refhold_locked(ipif);
26515 		mutex_exit(&ill->ill_lock);
26516 		ire = ire_ctable_lookup(fake_ire->ire_addr,
26517 		    fake_ire->ire_gateway_addr, IRE_CACHE,
26518 		    ipif, fake_ire->ire_zoneid, NULL,
26519 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
26520 		ipif_refrele(ipif);
26521 		if (ire == NULL) {
26522 			/*
26523 			 * no ire was found; check if there is an nce
26524 			 * for this lookup; if it has no ire's pointing at it
26525 			 * cleanup.
26526 			 */
26527 			if ((nce = ndp_lookup_v4(ill,
26528 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
26529 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
26530 			    B_FALSE)) != NULL) {
26531 				/*
26532 				 * cleanup: just reset nce.
26533 				 * We check for refcnt 2 (one for the nce
26534 				 * hash list + 1 for the ref taken by
26535 				 * ndp_lookup_v4) to ensure that there are
26536 				 * no ire's pointing at the nce.
26537 				 */
26538 				if (nce->nce_refcnt == 2) {
26539 					nce = nce_reinit(nce);
26540 				}
26541 				if (nce != NULL)
26542 					NCE_REFRELE(nce);
26543 			}
26544 			freeb(mp1);  /* dl_unitdata response */
26545 			freemsg(mp); /* fake ire */
26546 			return;
26547 		}
26548 		nce = ire->ire_nce;
26549 		DTRACE_PROBE2(ire__arpresolve__type,
26550 		    ire_t *, ire, nce_t *, nce);
26551 		ASSERT(nce->nce_state != ND_INITIAL);
26552 		mutex_enter(&nce->nce_lock);
26553 		nce->nce_last = TICK_TO_MSEC(lbolt64);
26554 		if (nce->nce_state == ND_REACHABLE) {
26555 			/*
26556 			 * Someone resolved this before us;
26557 			 * our response is not needed any more.
26558 			 */
26559 			mutex_exit(&nce->nce_lock);
26560 			freeb(mp1);  /* dl_unitdata response */
26561 		} else {
26562 			if (nce->nce_res_mp != NULL) {
26563 				freemsg(nce->nce_res_mp);
26564 				/* existing dl_unitdata template */
26565 			}
26566 			nce->nce_res_mp = mp1;
26567 			nce->nce_state = ND_REACHABLE;
26568 			mutex_exit(&nce->nce_lock);
26569 			ire_fastpath(ire);
26570 		}
26571 		/*
26572 		 * The cached nce_t has been updated to be reachable;
26573 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
26574 		 */
26575 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
26576 		freemsg(mp);
26577 		/*
26578 		 * send out queued packets.
26579 		 */
26580 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26581 
26582 		IRE_REFRELE(ire);
26583 		return;
26584 	}
26585 	default:
26586 		break;
26587 	}
26588 	if (q->q_next) {
26589 		putnext(q, mp);
26590 	} else
26591 		freemsg(mp);
26592 }
26593 
26594 /*
26595  * Process IP options in an outbound packet.  Modify the destination if there
26596  * is a source route option.
26597  * Returns non-zero if something fails in which case an ICMP error has been
26598  * sent and mp freed.
26599  */
26600 static int
26601 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
26602     boolean_t mctl_present, zoneid_t zoneid)
26603 {
26604 	ipoptp_t	opts;
26605 	uchar_t		*opt;
26606 	uint8_t		optval;
26607 	uint8_t		optlen;
26608 	ipaddr_t	dst;
26609 	intptr_t	code = 0;
26610 	mblk_t		*mp;
26611 	ire_t		*ire = NULL;
26612 
26613 	ip2dbg(("ip_wput_options\n"));
26614 	mp = ipsec_mp;
26615 	if (mctl_present) {
26616 		mp = ipsec_mp->b_cont;
26617 	}
26618 
26619 	dst = ipha->ipha_dst;
26620 	for (optval = ipoptp_first(&opts, ipha);
26621 	    optval != IPOPT_EOL;
26622 	    optval = ipoptp_next(&opts)) {
26623 		opt = opts.ipoptp_cur;
26624 		optlen = opts.ipoptp_len;
26625 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
26626 		    optval, optlen));
26627 		switch (optval) {
26628 			uint32_t off;
26629 		case IPOPT_SSRR:
26630 		case IPOPT_LSRR:
26631 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26632 				ip1dbg((
26633 				    "ip_wput_options: bad option offset\n"));
26634 				code = (char *)&opt[IPOPT_OLEN] -
26635 				    (char *)ipha;
26636 				goto param_prob;
26637 			}
26638 			off = opt[IPOPT_OFFSET];
26639 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
26640 			    ntohl(dst)));
26641 			/*
26642 			 * For strict: verify that dst is directly
26643 			 * reachable.
26644 			 */
26645 			if (optval == IPOPT_SSRR) {
26646 				ire = ire_ftable_lookup(dst, 0, 0,
26647 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
26648 				    MBLK_GETLABEL(mp),
26649 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
26650 				if (ire == NULL) {
26651 					ip1dbg(("ip_wput_options: SSRR not"
26652 					    " directly reachable: 0x%x\n",
26653 					    ntohl(dst)));
26654 					goto bad_src_route;
26655 				}
26656 				ire_refrele(ire);
26657 			}
26658 			break;
26659 		case IPOPT_RR:
26660 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26661 				ip1dbg((
26662 				    "ip_wput_options: bad option offset\n"));
26663 				code = (char *)&opt[IPOPT_OLEN] -
26664 				    (char *)ipha;
26665 				goto param_prob;
26666 			}
26667 			break;
26668 		case IPOPT_TS:
26669 			/*
26670 			 * Verify that length >=5 and that there is either
26671 			 * room for another timestamp or that the overflow
26672 			 * counter is not maxed out.
26673 			 */
26674 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
26675 			if (optlen < IPOPT_MINLEN_IT) {
26676 				goto param_prob;
26677 			}
26678 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26679 				ip1dbg((
26680 				    "ip_wput_options: bad option offset\n"));
26681 				code = (char *)&opt[IPOPT_OFFSET] -
26682 				    (char *)ipha;
26683 				goto param_prob;
26684 			}
26685 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
26686 			case IPOPT_TS_TSONLY:
26687 				off = IPOPT_TS_TIMELEN;
26688 				break;
26689 			case IPOPT_TS_TSANDADDR:
26690 			case IPOPT_TS_PRESPEC:
26691 			case IPOPT_TS_PRESPEC_RFC791:
26692 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
26693 				break;
26694 			default:
26695 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
26696 				    (char *)ipha;
26697 				goto param_prob;
26698 			}
26699 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
26700 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
26701 				/*
26702 				 * No room and the overflow counter is 15
26703 				 * already.
26704 				 */
26705 				goto param_prob;
26706 			}
26707 			break;
26708 		}
26709 	}
26710 
26711 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
26712 		return (0);
26713 
26714 	ip1dbg(("ip_wput_options: error processing IP options."));
26715 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
26716 
26717 param_prob:
26718 	/*
26719 	 * Since ip_wput() isn't close to finished, we fill
26720 	 * in enough of the header for credible error reporting.
26721 	 */
26722 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
26723 		/* Failed */
26724 		freemsg(ipsec_mp);
26725 		return (-1);
26726 	}
26727 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
26728 	return (-1);
26729 
26730 bad_src_route:
26731 	/*
26732 	 * Since ip_wput() isn't close to finished, we fill
26733 	 * in enough of the header for credible error reporting.
26734 	 */
26735 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
26736 		/* Failed */
26737 		freemsg(ipsec_mp);
26738 		return (-1);
26739 	}
26740 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
26741 	return (-1);
26742 }
26743 
26744 /*
26745  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
26746  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
26747  * thru /etc/system.
26748  */
26749 #define	CONN_MAXDRAINCNT	64
26750 
26751 static void
26752 conn_drain_init(void)
26753 {
26754 	int i;
26755 
26756 	conn_drain_list_cnt = conn_drain_nthreads;
26757 
26758 	if ((conn_drain_list_cnt == 0) ||
26759 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
26760 		/*
26761 		 * Default value of the number of drainers is the
26762 		 * number of cpus, subject to maximum of 8 drainers.
26763 		 */
26764 		if (boot_max_ncpus != -1)
26765 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
26766 		else
26767 			conn_drain_list_cnt = MIN(max_ncpus, 8);
26768 	}
26769 
26770 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
26771 	    KM_SLEEP);
26772 
26773 	for (i = 0; i < conn_drain_list_cnt; i++) {
26774 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
26775 		    MUTEX_DEFAULT, NULL);
26776 	}
26777 }
26778 
26779 static void
26780 conn_drain_fini(void)
26781 {
26782 	int i;
26783 
26784 	for (i = 0; i < conn_drain_list_cnt; i++)
26785 		mutex_destroy(&conn_drain_list[i].idl_lock);
26786 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
26787 	conn_drain_list = NULL;
26788 }
26789 
26790 /*
26791  * Note: For an overview of how flowcontrol is handled in IP please see the
26792  * IP Flowcontrol notes at the top of this file.
26793  *
26794  * Flow control has blocked us from proceeding. Insert the given conn in one
26795  * of the conn drain lists. These conn wq's will be qenabled later on when
26796  * STREAMS flow control does a backenable. conn_walk_drain will enable
26797  * the first conn in each of these drain lists. Each of these qenabled conns
26798  * in turn enables the next in the list, after it runs, or when it closes,
26799  * thus sustaining the drain process.
26800  *
26801  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
26802  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
26803  * running at any time, on a given conn, since there can be only 1 service proc
26804  * running on a queue at any time.
26805  */
26806 void
26807 conn_drain_insert(conn_t *connp)
26808 {
26809 	idl_t	*idl;
26810 	uint_t	index;
26811 
26812 	mutex_enter(&connp->conn_lock);
26813 	if (connp->conn_state_flags & CONN_CLOSING) {
26814 		/*
26815 		 * The conn is closing as a result of which CONN_CLOSING
26816 		 * is set. Return.
26817 		 */
26818 		mutex_exit(&connp->conn_lock);
26819 		return;
26820 	} else if (connp->conn_idl == NULL) {
26821 		/*
26822 		 * Assign the next drain list round robin. We dont' use
26823 		 * a lock, and thus it may not be strictly round robin.
26824 		 * Atomicity of load/stores is enough to make sure that
26825 		 * conn_drain_list_index is always within bounds.
26826 		 */
26827 		index = conn_drain_list_index;
26828 		ASSERT(index < conn_drain_list_cnt);
26829 		connp->conn_idl = &conn_drain_list[index];
26830 		index++;
26831 		if (index == conn_drain_list_cnt)
26832 			index = 0;
26833 		conn_drain_list_index = index;
26834 	}
26835 	mutex_exit(&connp->conn_lock);
26836 
26837 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
26838 	if ((connp->conn_drain_prev != NULL) ||
26839 	    (connp->conn_state_flags & CONN_CLOSING)) {
26840 		/*
26841 		 * The conn is already in the drain list, OR
26842 		 * the conn is closing. We need to check again for
26843 		 * the closing case again since close can happen
26844 		 * after we drop the conn_lock, and before we
26845 		 * acquire the CONN_DRAIN_LIST_LOCK.
26846 		 */
26847 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26848 		return;
26849 	} else {
26850 		idl = connp->conn_idl;
26851 	}
26852 
26853 	/*
26854 	 * The conn is not in the drain list. Insert it at the
26855 	 * tail of the drain list. The drain list is circular
26856 	 * and doubly linked. idl_conn points to the 1st element
26857 	 * in the list.
26858 	 */
26859 	if (idl->idl_conn == NULL) {
26860 		idl->idl_conn = connp;
26861 		connp->conn_drain_next = connp;
26862 		connp->conn_drain_prev = connp;
26863 	} else {
26864 		conn_t *head = idl->idl_conn;
26865 
26866 		connp->conn_drain_next = head;
26867 		connp->conn_drain_prev = head->conn_drain_prev;
26868 		head->conn_drain_prev->conn_drain_next = connp;
26869 		head->conn_drain_prev = connp;
26870 	}
26871 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26872 }
26873 
26874 /*
26875  * This conn is closing, and we are called from ip_close. OR
26876  * This conn has been serviced by ip_wsrv, and we need to do the tail
26877  * processing.
26878  * If this conn is part of the drain list, we may need to sustain the drain
26879  * process by qenabling the next conn in the drain list. We may also need to
26880  * remove this conn from the list, if it is done.
26881  */
26882 static void
26883 conn_drain_tail(conn_t *connp, boolean_t closing)
26884 {
26885 	idl_t *idl;
26886 
26887 	/*
26888 	 * connp->conn_idl is stable at this point, and no lock is needed
26889 	 * to check it. If we are called from ip_close, close has already
26890 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
26891 	 * called us only because conn_idl is non-null. If we are called thru
26892 	 * service, conn_idl could be null, but it cannot change because
26893 	 * service is single-threaded per queue, and there cannot be another
26894 	 * instance of service trying to call conn_drain_insert on this conn
26895 	 * now.
26896 	 */
26897 	ASSERT(!closing || (connp->conn_idl != NULL));
26898 
26899 	/*
26900 	 * If connp->conn_idl is null, the conn has not been inserted into any
26901 	 * drain list even once since creation of the conn. Just return.
26902 	 */
26903 	if (connp->conn_idl == NULL)
26904 		return;
26905 
26906 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
26907 
26908 	if (connp->conn_drain_prev == NULL) {
26909 		/* This conn is currently not in the drain list.  */
26910 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26911 		return;
26912 	}
26913 	idl = connp->conn_idl;
26914 	if (idl->idl_conn_draining == connp) {
26915 		/*
26916 		 * This conn is the current drainer. If this is the last conn
26917 		 * in the drain list, we need to do more checks, in the 'if'
26918 		 * below. Otherwwise we need to just qenable the next conn,
26919 		 * to sustain the draining, and is handled in the 'else'
26920 		 * below.
26921 		 */
26922 		if (connp->conn_drain_next == idl->idl_conn) {
26923 			/*
26924 			 * This conn is the last in this list. This round
26925 			 * of draining is complete. If idl_repeat is set,
26926 			 * it means another flow enabling has happened from
26927 			 * the driver/streams and we need to another round
26928 			 * of draining.
26929 			 * If there are more than 2 conns in the drain list,
26930 			 * do a left rotate by 1, so that all conns except the
26931 			 * conn at the head move towards the head by 1, and the
26932 			 * the conn at the head goes to the tail. This attempts
26933 			 * a more even share for all queues that are being
26934 			 * drained.
26935 			 */
26936 			if ((connp->conn_drain_next != connp) &&
26937 			    (idl->idl_conn->conn_drain_next != connp)) {
26938 				idl->idl_conn = idl->idl_conn->conn_drain_next;
26939 			}
26940 			if (idl->idl_repeat) {
26941 				qenable(idl->idl_conn->conn_wq);
26942 				idl->idl_conn_draining = idl->idl_conn;
26943 				idl->idl_repeat = 0;
26944 			} else {
26945 				idl->idl_conn_draining = NULL;
26946 			}
26947 		} else {
26948 			/*
26949 			 * If the next queue that we are now qenable'ing,
26950 			 * is closing, it will remove itself from this list
26951 			 * and qenable the subsequent queue in ip_close().
26952 			 * Serialization is acheived thru idl_lock.
26953 			 */
26954 			qenable(connp->conn_drain_next->conn_wq);
26955 			idl->idl_conn_draining = connp->conn_drain_next;
26956 		}
26957 	}
26958 	if (!connp->conn_did_putbq || closing) {
26959 		/*
26960 		 * Remove ourself from the drain list, if we did not do
26961 		 * a putbq, or if the conn is closing.
26962 		 * Note: It is possible that q->q_first is non-null. It means
26963 		 * that these messages landed after we did a enableok() in
26964 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
26965 		 * service them.
26966 		 */
26967 		if (connp->conn_drain_next == connp) {
26968 			/* Singleton in the list */
26969 			ASSERT(connp->conn_drain_prev == connp);
26970 			idl->idl_conn = NULL;
26971 			idl->idl_conn_draining = NULL;
26972 		} else {
26973 			connp->conn_drain_prev->conn_drain_next =
26974 			    connp->conn_drain_next;
26975 			connp->conn_drain_next->conn_drain_prev =
26976 			    connp->conn_drain_prev;
26977 			if (idl->idl_conn == connp)
26978 				idl->idl_conn = connp->conn_drain_next;
26979 			ASSERT(idl->idl_conn_draining != connp);
26980 
26981 		}
26982 		connp->conn_drain_next = NULL;
26983 		connp->conn_drain_prev = NULL;
26984 	}
26985 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26986 }
26987 
26988 /*
26989  * Write service routine. Shared perimeter entry point.
26990  * ip_wsrv can be called in any of the following ways.
26991  * 1. The device queue's messages has fallen below the low water mark
26992  *    and STREAMS has backenabled the ill_wq. We walk thru all the
26993  *    the drain lists and backenable the first conn in each list.
26994  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
26995  *    qenabled non-tcp upper layers. We start dequeing messages and call
26996  *    ip_wput for each message.
26997  */
26998 
26999 void
27000 ip_wsrv(queue_t *q)
27001 {
27002 	conn_t	*connp;
27003 	ill_t	*ill;
27004 	mblk_t	*mp;
27005 
27006 	if (q->q_next) {
27007 		ill = (ill_t *)q->q_ptr;
27008 		if (ill->ill_state_flags == 0) {
27009 			/*
27010 			 * The device flow control has opened up.
27011 			 * Walk through conn drain lists and qenable the
27012 			 * first conn in each list. This makes sense only
27013 			 * if the stream is fully plumbed and setup.
27014 			 * Hence the if check above.
27015 			 */
27016 			ip1dbg(("ip_wsrv: walking\n"));
27017 			conn_walk_drain();
27018 		}
27019 		return;
27020 	}
27021 
27022 	connp = Q_TO_CONN(q);
27023 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
27024 
27025 	/*
27026 	 * 1. Set conn_draining flag to signal that service is active.
27027 	 *
27028 	 * 2. ip_output determines whether it has been called from service,
27029 	 *    based on the last parameter. If it is IP_WSRV it concludes it
27030 	 *    has been called from service.
27031 	 *
27032 	 * 3. Message ordering is preserved by the following logic.
27033 	 *    i. A directly called ip_output (i.e. not thru service) will queue
27034 	 *    the message at the tail, if conn_draining is set (i.e. service
27035 	 *    is running) or if q->q_first is non-null.
27036 	 *
27037 	 *    ii. If ip_output is called from service, and if ip_output cannot
27038 	 *    putnext due to flow control, it does a putbq.
27039 	 *
27040 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
27041 	 *    (causing an infinite loop).
27042 	 */
27043 	ASSERT(!connp->conn_did_putbq);
27044 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
27045 		connp->conn_draining = 1;
27046 		noenable(q);
27047 		while ((mp = getq(q)) != NULL) {
27048 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
27049 			if (connp->conn_did_putbq) {
27050 				/* ip_wput did a putbq */
27051 				break;
27052 			}
27053 		}
27054 		/*
27055 		 * At this point, a thread coming down from top, calling
27056 		 * ip_wput, may end up queueing the message. We have not yet
27057 		 * enabled the queue, so ip_wsrv won't be called again.
27058 		 * To avoid this race, check q->q_first again (in the loop)
27059 		 * If the other thread queued the message before we call
27060 		 * enableok(), we will catch it in the q->q_first check.
27061 		 * If the other thread queues the message after we call
27062 		 * enableok(), ip_wsrv will be called again by STREAMS.
27063 		 */
27064 		connp->conn_draining = 0;
27065 		enableok(q);
27066 	}
27067 
27068 	/* Enable the next conn for draining */
27069 	conn_drain_tail(connp, B_FALSE);
27070 
27071 	connp->conn_did_putbq = 0;
27072 }
27073 
27074 /*
27075  * Walk the list of all conn's calling the function provided with the
27076  * specified argument for each.	 Note that this only walks conn's that
27077  * have been bound.
27078  * Applies to both IPv4 and IPv6.
27079  */
27080 static void
27081 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
27082 {
27083 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
27084 	    func, arg, zoneid);
27085 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
27086 	    func, arg, zoneid);
27087 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
27088 	    func, arg, zoneid);
27089 	conn_walk_fanout_table(ipcl_proto_fanout,
27090 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
27091 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
27092 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
27093 }
27094 
27095 /*
27096  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
27097  * of conns that need to be drained, check if drain is already in progress.
27098  * If so set the idl_repeat bit, indicating that the last conn in the list
27099  * needs to reinitiate the drain once again, for the list. If drain is not
27100  * in progress for the list, initiate the draining, by qenabling the 1st
27101  * conn in the list. The drain is self-sustaining, each qenabled conn will
27102  * in turn qenable the next conn, when it is done/blocked/closing.
27103  */
27104 static void
27105 conn_walk_drain(void)
27106 {
27107 	int i;
27108 	idl_t *idl;
27109 
27110 	IP_STAT(ip_conn_walk_drain);
27111 
27112 	for (i = 0; i < conn_drain_list_cnt; i++) {
27113 		idl = &conn_drain_list[i];
27114 		mutex_enter(&idl->idl_lock);
27115 		if (idl->idl_conn == NULL) {
27116 			mutex_exit(&idl->idl_lock);
27117 			continue;
27118 		}
27119 		/*
27120 		 * If this list is not being drained currently by
27121 		 * an ip_wsrv thread, start the process.
27122 		 */
27123 		if (idl->idl_conn_draining == NULL) {
27124 			ASSERT(idl->idl_repeat == 0);
27125 			qenable(idl->idl_conn->conn_wq);
27126 			idl->idl_conn_draining = idl->idl_conn;
27127 		} else {
27128 			idl->idl_repeat = 1;
27129 		}
27130 		mutex_exit(&idl->idl_lock);
27131 	}
27132 }
27133 
27134 /*
27135  * Walk an conn hash table of `count' buckets, calling func for each entry.
27136  */
27137 static void
27138 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
27139     zoneid_t zoneid)
27140 {
27141 	conn_t	*connp;
27142 
27143 	while (count-- > 0) {
27144 		mutex_enter(&connfp->connf_lock);
27145 		for (connp = connfp->connf_head; connp != NULL;
27146 		    connp = connp->conn_next) {
27147 			if (zoneid == GLOBAL_ZONEID ||
27148 			    zoneid == connp->conn_zoneid) {
27149 				CONN_INC_REF(connp);
27150 				mutex_exit(&connfp->connf_lock);
27151 				(*func)(connp, arg);
27152 				mutex_enter(&connfp->connf_lock);
27153 				CONN_DEC_REF(connp);
27154 			}
27155 		}
27156 		mutex_exit(&connfp->connf_lock);
27157 		connfp++;
27158 	}
27159 }
27160 
27161 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
27162 static void
27163 conn_report1(conn_t *connp, void *mp)
27164 {
27165 	char	buf1[INET6_ADDRSTRLEN];
27166 	char	buf2[INET6_ADDRSTRLEN];
27167 	uint_t	print_len, buf_len;
27168 
27169 	ASSERT(connp != NULL);
27170 
27171 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
27172 	if (buf_len <= 0)
27173 		return;
27174 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
27175 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
27176 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
27177 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
27178 	    "%5d %s/%05d %s/%05d\n",
27179 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
27180 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
27181 	    buf1, connp->conn_lport,
27182 	    buf2, connp->conn_fport);
27183 	if (print_len < buf_len) {
27184 		((mblk_t *)mp)->b_wptr += print_len;
27185 	} else {
27186 		((mblk_t *)mp)->b_wptr += buf_len;
27187 	}
27188 }
27189 
27190 /*
27191  * Named Dispatch routine to produce a formatted report on all conns
27192  * that are listed in one of the fanout tables.
27193  * This report is accessed by using the ndd utility to "get" ND variable
27194  * "ip_conn_status".
27195  */
27196 /* ARGSUSED */
27197 static int
27198 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
27199 {
27200 	(void) mi_mpprintf(mp,
27201 	    "CONN      " MI_COL_HDRPAD_STR
27202 	    "rfq      " MI_COL_HDRPAD_STR
27203 	    "stq      " MI_COL_HDRPAD_STR
27204 	    " zone local                 remote");
27205 
27206 	/*
27207 	 * Because of the ndd constraint, at most we can have 64K buffer
27208 	 * to put in all conn info.  So to be more efficient, just
27209 	 * allocate a 64K buffer here, assuming we need that large buffer.
27210 	 * This should be OK as only privileged processes can do ndd /dev/ip.
27211 	 */
27212 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
27213 		/* The following may work even if we cannot get a large buf. */
27214 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
27215 		return (0);
27216 	}
27217 
27218 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
27219 	return (0);
27220 }
27221 
27222 /*
27223  * Determine if the ill and multicast aspects of that packets
27224  * "matches" the conn.
27225  */
27226 boolean_t
27227 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
27228     zoneid_t zoneid)
27229 {
27230 	ill_t *in_ill;
27231 	boolean_t found;
27232 	ipif_t *ipif;
27233 	ire_t *ire;
27234 	ipaddr_t dst, src;
27235 
27236 	dst = ipha->ipha_dst;
27237 	src = ipha->ipha_src;
27238 
27239 	/*
27240 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
27241 	 * unicast, broadcast and multicast reception to
27242 	 * conn_incoming_ill. conn_wantpacket itself is called
27243 	 * only for BROADCAST and multicast.
27244 	 *
27245 	 * 1) ip_rput supresses duplicate broadcasts if the ill
27246 	 *    is part of a group. Hence, we should be receiving
27247 	 *    just one copy of broadcast for the whole group.
27248 	 *    Thus, if it is part of the group the packet could
27249 	 *    come on any ill of the group and hence we need a
27250 	 *    match on the group. Otherwise, match on ill should
27251 	 *    be sufficient.
27252 	 *
27253 	 * 2) ip_rput does not suppress duplicate multicast packets.
27254 	 *    If there are two interfaces in a ill group and we have
27255 	 *    2 applications (conns) joined a multicast group G on
27256 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
27257 	 *    will give us two packets because we join G on both the
27258 	 *    interfaces rather than nominating just one interface
27259 	 *    for receiving multicast like broadcast above. So,
27260 	 *    we have to call ilg_lookup_ill to filter out duplicate
27261 	 *    copies, if ill is part of a group.
27262 	 */
27263 	in_ill = connp->conn_incoming_ill;
27264 	if (in_ill != NULL) {
27265 		if (in_ill->ill_group == NULL) {
27266 			if (in_ill != ill)
27267 				return (B_FALSE);
27268 		} else if (in_ill->ill_group != ill->ill_group) {
27269 			return (B_FALSE);
27270 		}
27271 	}
27272 
27273 	if (!CLASSD(dst)) {
27274 		if (IPCL_ZONE_MATCH(connp, zoneid))
27275 			return (B_TRUE);
27276 		/*
27277 		 * The conn is in a different zone; we need to check that this
27278 		 * broadcast address is configured in the application's zone and
27279 		 * on one ill in the group.
27280 		 */
27281 		ipif = ipif_get_next_ipif(NULL, ill);
27282 		if (ipif == NULL)
27283 			return (B_FALSE);
27284 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
27285 		    connp->conn_zoneid, NULL,
27286 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
27287 		ipif_refrele(ipif);
27288 		if (ire != NULL) {
27289 			ire_refrele(ire);
27290 			return (B_TRUE);
27291 		} else {
27292 			return (B_FALSE);
27293 		}
27294 	}
27295 
27296 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
27297 	    connp->conn_zoneid == zoneid) {
27298 		/*
27299 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
27300 		 * disabled, therefore we don't dispatch the multicast packet to
27301 		 * the sending zone.
27302 		 */
27303 		return (B_FALSE);
27304 	}
27305 
27306 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
27307 	    connp->conn_zoneid != zoneid) {
27308 		/*
27309 		 * Multicast packet on the loopback interface: we only match
27310 		 * conns who joined the group in the specified zone.
27311 		 */
27312 		return (B_FALSE);
27313 	}
27314 
27315 	if (connp->conn_multi_router) {
27316 		/* multicast packet and multicast router socket: send up */
27317 		return (B_TRUE);
27318 	}
27319 
27320 	mutex_enter(&connp->conn_lock);
27321 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
27322 	mutex_exit(&connp->conn_lock);
27323 	return (found);
27324 }
27325 
27326 /*
27327  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
27328  */
27329 /* ARGSUSED */
27330 static void
27331 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
27332 {
27333 	ill_t *ill = (ill_t *)q->q_ptr;
27334 	mblk_t	*mp1, *mp2;
27335 	ipif_t  *ipif;
27336 	int err = 0;
27337 	conn_t *connp = NULL;
27338 	ipsq_t	*ipsq;
27339 	arc_t	*arc;
27340 
27341 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
27342 
27343 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
27344 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
27345 
27346 	ASSERT(IAM_WRITER_ILL(ill));
27347 	mp2 = mp->b_cont;
27348 	mp->b_cont = NULL;
27349 
27350 	/*
27351 	 * We have now received the arp bringup completion message
27352 	 * from ARP. Mark the arp bringup as done. Also if the arp
27353 	 * stream has already started closing, send up the AR_ARP_CLOSING
27354 	 * ack now since ARP is waiting in close for this ack.
27355 	 */
27356 	mutex_enter(&ill->ill_lock);
27357 	ill->ill_arp_bringup_pending = 0;
27358 	if (ill->ill_arp_closing) {
27359 		mutex_exit(&ill->ill_lock);
27360 		/* Let's reuse the mp for sending the ack */
27361 		arc = (arc_t *)mp->b_rptr;
27362 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
27363 		arc->arc_cmd = AR_ARP_CLOSING;
27364 		qreply(q, mp);
27365 	} else {
27366 		mutex_exit(&ill->ill_lock);
27367 		freeb(mp);
27368 	}
27369 
27370 	/* We should have an IOCTL waiting on this. */
27371 	ipsq = ill->ill_phyint->phyint_ipsq;
27372 	ipif = ipsq->ipsq_pending_ipif;
27373 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
27374 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
27375 	if (mp1 == NULL) {
27376 		/* bringup was aborted by the user */
27377 		freemsg(mp2);
27378 		return;
27379 	}
27380 	ASSERT(connp != NULL);
27381 	q = CONNP_TO_WQ(connp);
27382 	/*
27383 	 * If the DL_BIND_REQ fails, it is noted
27384 	 * in arc_name_offset.
27385 	 */
27386 	err = *((int *)mp2->b_rptr);
27387 	if (err == 0) {
27388 		if (ipif->ipif_isv6) {
27389 			if ((err = ipif_up_done_v6(ipif)) != 0)
27390 				ip0dbg(("ip_arp_done: init failed\n"));
27391 		} else {
27392 			if ((err = ipif_up_done(ipif)) != 0)
27393 				ip0dbg(("ip_arp_done: init failed\n"));
27394 		}
27395 	} else {
27396 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
27397 	}
27398 
27399 	freemsg(mp2);
27400 
27401 	if ((err == 0) && (ill->ill_up_ipifs)) {
27402 		err = ill_up_ipifs(ill, q, mp1);
27403 		if (err == EINPROGRESS)
27404 			return;
27405 	}
27406 
27407 	if (ill->ill_up_ipifs) {
27408 		ill_group_cleanup(ill);
27409 	}
27410 
27411 	/*
27412 	 * The ioctl must complete now without EINPROGRESS
27413 	 * since ipsq_pending_mp_get has removed the ioctl mblk
27414 	 * from ipsq_pending_mp. Otherwise the ioctl will be
27415 	 * stuck for ever in the ipsq.
27416 	 */
27417 	ASSERT(err != EINPROGRESS);
27418 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
27419 }
27420 
27421 /* Allocate the private structure */
27422 static int
27423 ip_priv_alloc(void **bufp)
27424 {
27425 	void	*buf;
27426 
27427 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
27428 		return (ENOMEM);
27429 
27430 	*bufp = buf;
27431 	return (0);
27432 }
27433 
27434 /* Function to delete the private structure */
27435 void
27436 ip_priv_free(void *buf)
27437 {
27438 	ASSERT(buf != NULL);
27439 	kmem_free(buf, sizeof (ip_priv_t));
27440 }
27441 
27442 /*
27443  * The entry point for IPPF processing.
27444  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
27445  * routine just returns.
27446  *
27447  * When called, ip_process generates an ipp_packet_t structure
27448  * which holds the state information for this packet and invokes the
27449  * the classifier (via ipp_packet_process). The classification, depending on
27450  * configured filters, results in a list of actions for this packet. Invoking
27451  * an action may cause the packet to be dropped, in which case the resulting
27452  * mblk (*mpp) is NULL. proc indicates the callout position for
27453  * this packet and ill_index is the interface this packet on or will leave
27454  * on (inbound and outbound resp.).
27455  */
27456 void
27457 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
27458 {
27459 	mblk_t		*mp;
27460 	ip_priv_t	*priv;
27461 	ipp_action_id_t	aid;
27462 	int		rc = 0;
27463 	ipp_packet_t	*pp;
27464 #define	IP_CLASS	"ip"
27465 
27466 	/* If the classifier is not loaded, return  */
27467 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
27468 		return;
27469 	}
27470 
27471 	mp = *mpp;
27472 	ASSERT(mp != NULL);
27473 
27474 	/* Allocate the packet structure */
27475 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
27476 	if (rc != 0) {
27477 		*mpp = NULL;
27478 		freemsg(mp);
27479 		return;
27480 	}
27481 
27482 	/* Allocate the private structure */
27483 	rc = ip_priv_alloc((void **)&priv);
27484 	if (rc != 0) {
27485 		*mpp = NULL;
27486 		freemsg(mp);
27487 		ipp_packet_free(pp);
27488 		return;
27489 	}
27490 	priv->proc = proc;
27491 	priv->ill_index = ill_index;
27492 	ipp_packet_set_private(pp, priv, ip_priv_free);
27493 	ipp_packet_set_data(pp, mp);
27494 
27495 	/* Invoke the classifier */
27496 	rc = ipp_packet_process(&pp);
27497 	if (pp != NULL) {
27498 		mp = ipp_packet_get_data(pp);
27499 		ipp_packet_free(pp);
27500 		if (rc != 0) {
27501 			freemsg(mp);
27502 			*mpp = NULL;
27503 		}
27504 	} else {
27505 		*mpp = NULL;
27506 	}
27507 #undef	IP_CLASS
27508 }
27509 
27510 /*
27511  * Propagate a multicast group membership operation (add/drop) on
27512  * all the interfaces crossed by the related multirt routes.
27513  * The call is considered successful if the operation succeeds
27514  * on at least one interface.
27515  */
27516 static int
27517 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
27518     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
27519     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
27520     mblk_t *first_mp)
27521 {
27522 	ire_t		*ire_gw;
27523 	irb_t		*irb;
27524 	int		error = 0;
27525 	opt_restart_t	*or;
27526 
27527 	irb = ire->ire_bucket;
27528 	ASSERT(irb != NULL);
27529 
27530 	ASSERT(DB_TYPE(first_mp) == M_CTL);
27531 
27532 	or = (opt_restart_t *)first_mp->b_rptr;
27533 	IRB_REFHOLD(irb);
27534 	for (; ire != NULL; ire = ire->ire_next) {
27535 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
27536 			continue;
27537 		if (ire->ire_addr != group)
27538 			continue;
27539 
27540 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
27541 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
27542 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
27543 		/* No resolver exists for the gateway; skip this ire. */
27544 		if (ire_gw == NULL)
27545 			continue;
27546 
27547 		/*
27548 		 * This function can return EINPROGRESS. If so the operation
27549 		 * will be restarted from ip_restart_optmgmt which will
27550 		 * call ip_opt_set and option processing will restart for
27551 		 * this option. So we may end up calling 'fn' more than once.
27552 		 * This requires that 'fn' is idempotent except for the
27553 		 * return value. The operation is considered a success if
27554 		 * it succeeds at least once on any one interface.
27555 		 */
27556 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
27557 		    NULL, fmode, src, first_mp);
27558 		if (error == 0)
27559 			or->or_private = CGTP_MCAST_SUCCESS;
27560 
27561 		if (ip_debug > 0) {
27562 			ulong_t	off;
27563 			char	*ksym;
27564 			ksym = kobj_getsymname((uintptr_t)fn, &off);
27565 			ip2dbg(("ip_multirt_apply_membership: "
27566 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
27567 			    "error %d [success %u]\n",
27568 			    ksym ? ksym : "?",
27569 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
27570 			    error, or->or_private));
27571 		}
27572 
27573 		ire_refrele(ire_gw);
27574 		if (error == EINPROGRESS) {
27575 			IRB_REFRELE(irb);
27576 			return (error);
27577 		}
27578 	}
27579 	IRB_REFRELE(irb);
27580 	/*
27581 	 * Consider the call as successful if we succeeded on at least
27582 	 * one interface. Otherwise, return the last encountered error.
27583 	 */
27584 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
27585 }
27586 
27587 
27588 /*
27589  * Issue a warning regarding a route crossing an interface with an
27590  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
27591  * amount of time is logged.
27592  */
27593 static void
27594 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
27595 {
27596 	hrtime_t	current = gethrtime();
27597 	char		buf[INET_ADDRSTRLEN];
27598 
27599 	/* Convert interval in ms to hrtime in ns */
27600 	if (multirt_bad_mtu_last_time +
27601 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
27602 	    current) {
27603 		cmn_err(CE_WARN, "ip: ignoring multiroute "
27604 		    "to %s, incorrect MTU %u (expected %u)\n",
27605 		    ip_dot_addr(ire->ire_addr, buf),
27606 		    ire->ire_max_frag, max_frag);
27607 
27608 		multirt_bad_mtu_last_time = current;
27609 	}
27610 }
27611 
27612 
27613 /*
27614  * Get the CGTP (multirouting) filtering status.
27615  * If 0, the CGTP hooks are transparent.
27616  */
27617 /* ARGSUSED */
27618 static int
27619 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
27620 {
27621 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
27622 
27623 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
27624 	return (0);
27625 }
27626 
27627 
27628 /*
27629  * Set the CGTP (multirouting) filtering status.
27630  * If the status is changed from active to transparent
27631  * or from transparent to active, forward the new status
27632  * to the filtering module (if loaded).
27633  */
27634 /* ARGSUSED */
27635 static int
27636 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
27637     cred_t *ioc_cr)
27638 {
27639 	long		new_value;
27640 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
27641 
27642 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
27643 	    new_value < 0 || new_value > 1) {
27644 		return (EINVAL);
27645 	}
27646 
27647 	/*
27648 	 * Do not enable CGTP filtering - thus preventing the hooks
27649 	 * from being invoked - if the version number of the
27650 	 * filtering module hooks does not match.
27651 	 */
27652 	if ((ip_cgtp_filter_ops != NULL) &&
27653 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
27654 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
27655 		    "(module hooks version %d, expecting %d)\n",
27656 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
27657 		return (ENOTSUP);
27658 	}
27659 
27660 	if ((!*ip_cgtp_filter_value) && new_value) {
27661 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
27662 		    ip_cgtp_filter_ops == NULL ?
27663 		    " (module not loaded)" : "");
27664 	}
27665 	if (*ip_cgtp_filter_value && (!new_value)) {
27666 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
27667 		    ip_cgtp_filter_ops == NULL ?
27668 		    " (module not loaded)" : "");
27669 	}
27670 
27671 	if (ip_cgtp_filter_ops != NULL) {
27672 		int	res;
27673 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
27674 			return (res);
27675 		}
27676 	}
27677 
27678 	*ip_cgtp_filter_value = (boolean_t)new_value;
27679 
27680 	return (0);
27681 }
27682 
27683 
27684 /*
27685  * Return the expected CGTP hooks version number.
27686  */
27687 int
27688 ip_cgtp_filter_supported(void)
27689 {
27690 	return (ip_cgtp_filter_rev);
27691 }
27692 
27693 
27694 /*
27695  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
27696  * or by invoking this function. In the first case, the version number
27697  * of the registered structure is checked at hooks activation time
27698  * in ip_cgtp_filter_set().
27699  */
27700 int
27701 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
27702 {
27703 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
27704 		return (ENOTSUP);
27705 
27706 	ip_cgtp_filter_ops = ops;
27707 	return (0);
27708 }
27709 
27710 static squeue_func_t
27711 ip_squeue_switch(int val)
27712 {
27713 	squeue_func_t rval = squeue_fill;
27714 
27715 	switch (val) {
27716 	case IP_SQUEUE_ENTER_NODRAIN:
27717 		rval = squeue_enter_nodrain;
27718 		break;
27719 	case IP_SQUEUE_ENTER:
27720 		rval = squeue_enter;
27721 		break;
27722 	default:
27723 		break;
27724 	}
27725 	return (rval);
27726 }
27727 
27728 /* ARGSUSED */
27729 static int
27730 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
27731     caddr_t addr, cred_t *cr)
27732 {
27733 	int *v = (int *)addr;
27734 	long new_value;
27735 
27736 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
27737 		return (EINVAL);
27738 
27739 	ip_input_proc = ip_squeue_switch(new_value);
27740 	*v = new_value;
27741 	return (0);
27742 }
27743 
27744 /* ARGSUSED */
27745 static int
27746 ip_int_set(queue_t *q, mblk_t *mp, char *value,
27747     caddr_t addr, cred_t *cr)
27748 {
27749 	int *v = (int *)addr;
27750 	long new_value;
27751 
27752 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
27753 		return (EINVAL);
27754 
27755 	*v = new_value;
27756 	return (0);
27757 }
27758 
27759 static void
27760 ip_kstat_init(void)
27761 {
27762 	ip_named_kstat_t template = {
27763 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
27764 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
27765 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
27766 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
27767 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
27768 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
27769 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
27770 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
27771 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
27772 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
27773 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
27774 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
27775 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
27776 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
27777 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
27778 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
27779 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
27780 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
27781 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
27782 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
27783 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
27784 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
27785 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
27786 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
27787 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
27788 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
27789 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
27790 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
27791 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
27792 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
27793 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
27794 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
27795 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
27796 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
27797 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
27798 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
27799 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
27800 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
27801 	};
27802 
27803 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
27804 					NUM_OF_FIELDS(ip_named_kstat_t),
27805 					0);
27806 	if (!ip_mibkp)
27807 		return;
27808 
27809 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
27810 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
27811 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
27812 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
27813 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
27814 
27815 	template.netToMediaEntrySize.value.i32 =
27816 		sizeof (mib2_ipNetToMediaEntry_t);
27817 
27818 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
27819 
27820 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
27821 
27822 	ip_mibkp->ks_update = ip_kstat_update;
27823 
27824 	kstat_install(ip_mibkp);
27825 }
27826 
27827 static void
27828 ip_kstat_fini(void)
27829 {
27830 
27831 	if (ip_mibkp != NULL) {
27832 		kstat_delete(ip_mibkp);
27833 		ip_mibkp = NULL;
27834 	}
27835 }
27836 
27837 static int
27838 ip_kstat_update(kstat_t *kp, int rw)
27839 {
27840 	ip_named_kstat_t *ipkp;
27841 
27842 	if (!kp || !kp->ks_data)
27843 		return (EIO);
27844 
27845 	if (rw == KSTAT_WRITE)
27846 		return (EACCES);
27847 
27848 	ipkp = (ip_named_kstat_t *)kp->ks_data;
27849 
27850 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
27851 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
27852 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
27853 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
27854 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
27855 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
27856 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
27857 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
27858 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
27859 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
27860 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
27861 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
27862 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
27863 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
27864 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
27865 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
27866 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
27867 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
27868 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
27869 
27870 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
27871 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
27872 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
27873 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
27874 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
27875 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
27876 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
27877 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
27878 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
27879 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
27880 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
27881 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
27882 
27883 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
27884 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
27885 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
27886 
27887 	return (0);
27888 }
27889 
27890 static void
27891 icmp_kstat_init(void)
27892 {
27893 	icmp_named_kstat_t template = {
27894 		{ "inMsgs",		KSTAT_DATA_UINT32 },
27895 		{ "inErrors",		KSTAT_DATA_UINT32 },
27896 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
27897 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
27898 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
27899 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
27900 		{ "inRedirects",	KSTAT_DATA_UINT32 },
27901 		{ "inEchos",		KSTAT_DATA_UINT32 },
27902 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
27903 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
27904 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
27905 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
27906 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
27907 		{ "outMsgs",		KSTAT_DATA_UINT32 },
27908 		{ "outErrors",		KSTAT_DATA_UINT32 },
27909 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
27910 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
27911 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
27912 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
27913 		{ "outRedirects",	KSTAT_DATA_UINT32 },
27914 		{ "outEchos",		KSTAT_DATA_UINT32 },
27915 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
27916 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
27917 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
27918 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
27919 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
27920 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
27921 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
27922 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
27923 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
27924 		{ "outDrops",		KSTAT_DATA_UINT32 },
27925 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
27926 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
27927 	};
27928 
27929 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
27930 					NUM_OF_FIELDS(icmp_named_kstat_t),
27931 					0);
27932 	if (icmp_mibkp == NULL)
27933 		return;
27934 
27935 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
27936 
27937 	icmp_mibkp->ks_update = icmp_kstat_update;
27938 
27939 	kstat_install(icmp_mibkp);
27940 }
27941 
27942 static void
27943 icmp_kstat_fini(void)
27944 {
27945 
27946 	if (icmp_mibkp != NULL) {
27947 		kstat_delete(icmp_mibkp);
27948 		icmp_mibkp = NULL;
27949 	}
27950 }
27951 
27952 static int
27953 icmp_kstat_update(kstat_t *kp, int rw)
27954 {
27955 	icmp_named_kstat_t *icmpkp;
27956 
27957 	if ((kp == NULL) || (kp->ks_data == NULL))
27958 		return (EIO);
27959 
27960 	if (rw == KSTAT_WRITE)
27961 		return (EACCES);
27962 
27963 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
27964 
27965 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
27966 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
27967 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
27968 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
27969 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
27970 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
27971 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
27972 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
27973 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
27974 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
27975 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
27976 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
27977 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
27978 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
27979 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
27980 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
27981 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
27982 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
27983 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
27984 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
27985 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
27986 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
27987 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
27988 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
27989 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
27990 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
27991 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
27992 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
27993 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
27994 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
27995 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
27996 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
27997 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
27998 
27999 	return (0);
28000 }
28001 
28002 /*
28003  * This is the fanout function for raw socket opened for SCTP.  Note
28004  * that it is called after SCTP checks that there is no socket which
28005  * wants a packet.  Then before SCTP handles this out of the blue packet,
28006  * this function is called to see if there is any raw socket for SCTP.
28007  * If there is and it is bound to the correct address, the packet will
28008  * be sent to that socket.  Note that only one raw socket can be bound to
28009  * a port.  This is assured in ipcl_sctp_hash_insert();
28010  */
28011 void
28012 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
28013     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
28014     uint_t ipif_seqid, zoneid_t zoneid)
28015 {
28016 	conn_t		*connp;
28017 	queue_t		*rq;
28018 	mblk_t		*first_mp;
28019 	boolean_t	secure;
28020 	ip6_t		*ip6h;
28021 
28022 	first_mp = mp;
28023 	if (mctl_present) {
28024 		mp = first_mp->b_cont;
28025 		secure = ipsec_in_is_secure(first_mp);
28026 		ASSERT(mp != NULL);
28027 	} else {
28028 		secure = B_FALSE;
28029 	}
28030 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
28031 
28032 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
28033 	if (connp == NULL) {
28034 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
28035 		    mctl_present);
28036 		return;
28037 	}
28038 	rq = connp->conn_rq;
28039 	if (!canputnext(rq)) {
28040 		CONN_DEC_REF(connp);
28041 		BUMP_MIB(&ip_mib, rawipInOverflows);
28042 		freemsg(first_mp);
28043 		return;
28044 	}
28045 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
28046 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
28047 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
28048 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
28049 		if (first_mp == NULL) {
28050 			CONN_DEC_REF(connp);
28051 			return;
28052 		}
28053 	}
28054 	/*
28055 	 * We probably should not send M_CTL message up to
28056 	 * raw socket.
28057 	 */
28058 	if (mctl_present)
28059 		freeb(first_mp);
28060 
28061 	/* Initiate IPPF processing here if needed. */
28062 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
28063 	    (!isv4 && IP6_IN_IPP(flags))) {
28064 		ip_process(IPP_LOCAL_IN, &mp,
28065 		    recv_ill->ill_phyint->phyint_ifindex);
28066 		if (mp == NULL) {
28067 			CONN_DEC_REF(connp);
28068 			return;
28069 		}
28070 	}
28071 
28072 	if (connp->conn_recvif || connp->conn_recvslla ||
28073 	    ((connp->conn_ipv6_recvpktinfo ||
28074 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
28075 	    (flags & IP_FF_IP6INFO))) {
28076 		int in_flags = 0;
28077 
28078 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
28079 			in_flags = IPF_RECVIF;
28080 		}
28081 		if (connp->conn_recvslla) {
28082 			in_flags |= IPF_RECVSLLA;
28083 		}
28084 		if (isv4) {
28085 			mp = ip_add_info(mp, recv_ill, in_flags);
28086 		} else {
28087 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
28088 			if (mp == NULL) {
28089 				CONN_DEC_REF(connp);
28090 				return;
28091 			}
28092 		}
28093 	}
28094 
28095 	BUMP_MIB(&ip_mib, ipInDelivers);
28096 	/*
28097 	 * We are sending the IPSEC_IN message also up. Refer
28098 	 * to comments above this function.
28099 	 */
28100 	putnext(rq, mp);
28101 	CONN_DEC_REF(connp);
28102 }
28103 
28104 /*
28105  * This function should be called only if all packet processing
28106  * including fragmentation is complete. Callers of this function
28107  * must set mp->b_prev to one of these values:
28108  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
28109  * prior to handing over the mp as first argument to this function.
28110  *
28111  * If the ire passed by caller is incomplete, this function
28112  * queues the packet and if necessary, sends ARP request and bails.
28113  * If the ire passed is fully resolved, we simply prepend
28114  * the link-layer header to the packet, do ipsec hw acceleration
28115  * work if necessary, and send the packet out on the wire.
28116  *
28117  * NOTE: IPSEC will only call this function with fully resolved
28118  * ires if hw acceleration is involved.
28119  * TODO list :
28120  * 	a Handle M_MULTIDATA so that
28121  *	  tcp_multisend->tcp_multisend_data can
28122  *	  call ip_xmit_v4 directly
28123  *	b Handle post-ARP work for fragments so that
28124  *	  ip_wput_frag can call this function.
28125  */
28126 ipxmit_state_t
28127 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
28128 {
28129 	nce_t		*arpce;
28130 	queue_t		*q;
28131 	int		ill_index;
28132 	mblk_t		*nxt_mp;
28133 	boolean_t	xmit_drop = B_FALSE;
28134 	ip_proc_t	proc;
28135 
28136 	arpce = ire->ire_nce;
28137 	ASSERT(arpce != NULL);
28138 
28139 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
28140 
28141 	mutex_enter(&arpce->nce_lock);
28142 	switch (arpce->nce_state) {
28143 	case ND_REACHABLE:
28144 		/* If there are other queued packets, queue this packet */
28145 		if (arpce->nce_qd_mp != NULL) {
28146 			if (mp != NULL)
28147 				nce_queue_mp_common(arpce, mp, B_FALSE);
28148 			mp = arpce->nce_qd_mp;
28149 		}
28150 		arpce->nce_qd_mp = NULL;
28151 		mutex_exit(&arpce->nce_lock);
28152 
28153 		/*
28154 		 * Flush the queue.  In the common case, where the
28155 		 * ARP is already resolved,  it will go through the
28156 		 * while loop only once.
28157 		 */
28158 		while (mp != NULL) {
28159 
28160 			nxt_mp = mp->b_next;
28161 			mp->b_next = NULL;
28162 			/*
28163 			 * This info is needed for IPQOS to do COS marking
28164 			 * in ip_wput_attach_llhdr->ip_process.
28165 			 */
28166 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
28167 			mp->b_prev = NULL;
28168 
28169 			/* set up ill index for outbound qos processing */
28170 			ill_index =
28171 			    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
28172 			mp = ip_wput_attach_llhdr(mp, ire, proc, ill_index);
28173 			if (mp == NULL) {
28174 				xmit_drop = B_TRUE;
28175 				if (proc == IPP_FWD_OUT) {
28176 					BUMP_MIB(&ip_mib, ipInDiscards);
28177 				} else {
28178 					BUMP_MIB(&ip_mib, ipOutDiscards);
28179 				}
28180 				goto next_mp;
28181 			}
28182 			/* non-ipsec hw accel case */
28183 			if (io == NULL || !io->ipsec_out_accelerated) {
28184 				/* send it */
28185 				q = ire->ire_stq;
28186 				if (proc == IPP_FWD_OUT) {
28187 					UPDATE_IB_PKT_COUNT(ire);
28188 				} else {
28189 					UPDATE_OB_PKT_COUNT(ire);
28190 				}
28191 				ire->ire_last_used_time = lbolt;
28192 
28193 				if (flow_ctl_enabled) {
28194 					/*
28195 					 * We are here from ip_wout_ire
28196 					 * which has already done canput
28197 					 * check and has enabled flow
28198 					 * control, so skip the canputnext
28199 					 * check.
28200 					 */
28201 					putnext(q, mp);
28202 					goto next_mp;
28203 				}
28204 				if (canputnext(q))  {
28205 					if (proc == IPP_FWD_OUT) {
28206 						BUMP_MIB(&ip_mib,
28207 						    ipForwDatagrams);
28208 					}
28209 					putnext(q, mp);
28210 				} else {
28211 					BUMP_MIB(&ip_mib,
28212 					    ipOutDiscards);
28213 					xmit_drop = B_TRUE;
28214 					freemsg(mp);
28215 				}
28216 			} else {
28217 				/*
28218 				 * Safety Pup says: make sure this
28219 				 *  is going to the right interface!
28220 				 */
28221 				ill_t *ill1 =
28222 				    (ill_t *)ire->ire_stq->q_ptr;
28223 				int ifindex =
28224 				    ill1->ill_phyint->phyint_ifindex;
28225 				if (ifindex !=
28226 				    io->ipsec_out_capab_ill_index) {
28227 					xmit_drop = B_TRUE;
28228 					freemsg(mp);
28229 				} else {
28230 					ipsec_hw_putnext(ire->ire_stq,
28231 					    mp);
28232 				}
28233 			}
28234 next_mp:
28235 			mp = nxt_mp;
28236 		} /* while (mp != NULL) */
28237 		if (xmit_drop)
28238 			return (SEND_FAILED);
28239 		else
28240 			return (SEND_PASSED);
28241 
28242 	case ND_INITIAL:
28243 	case ND_INCOMPLETE:
28244 
28245 		/*
28246 		 * While we do send off packets to dests that
28247 		 * use fully-resolved CGTP routes, we do not
28248 		 * handle unresolved CGTP routes.
28249 		 */
28250 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
28251 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
28252 
28253 		if (mp != NULL) {
28254 			/* queue the packet */
28255 			nce_queue_mp_common(arpce, mp, B_FALSE);
28256 		}
28257 
28258 		if (arpce->nce_state == ND_INCOMPLETE) {
28259 			mutex_exit(&arpce->nce_lock);
28260 			DTRACE_PROBE3(ip__xmit__incomplete,
28261 			    (ire_t *), ire, (mblk_t *), mp,
28262 			    (ipsec_out_t *), io);
28263 			return (LOOKUP_IN_PROGRESS);
28264 		}
28265 
28266 		arpce->nce_state = ND_INCOMPLETE;
28267 		mutex_exit(&arpce->nce_lock);
28268 		/*
28269 		 * Note that ire_add() (called from ire_forward())
28270 		 * holds a ref on the ire until ARP is completed.
28271 		 */
28272 
28273 		ire_arpresolve(ire, ire->ire_ipif->ipif_ill);
28274 		return (LOOKUP_IN_PROGRESS);
28275 	default:
28276 		ASSERT(0);
28277 		mutex_exit(&arpce->nce_lock);
28278 		return (LLHDR_RESLV_FAILED);
28279 	}
28280 }
28281 
28282 /*
28283  * Return B_TRUE if the buffers differ in length or content.
28284  * This is used for comparing extension header buffers.
28285  * Note that an extension header would be declared different
28286  * even if all that changed was the next header value in that header i.e.
28287  * what really changed is the next extension header.
28288  */
28289 boolean_t
28290 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
28291     uint_t blen)
28292 {
28293 	if (!b_valid)
28294 		blen = 0;
28295 
28296 	if (alen != blen)
28297 		return (B_TRUE);
28298 	if (alen == 0)
28299 		return (B_FALSE);	/* Both zero length */
28300 	return (bcmp(abuf, bbuf, alen));
28301 }
28302 
28303 /*
28304  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
28305  * Return B_FALSE if memory allocation fails - don't change any state!
28306  */
28307 boolean_t
28308 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28309     const void *src, uint_t srclen)
28310 {
28311 	void *dst;
28312 
28313 	if (!src_valid)
28314 		srclen = 0;
28315 
28316 	ASSERT(*dstlenp == 0);
28317 	if (src != NULL && srclen != 0) {
28318 		dst = mi_alloc(srclen, BPRI_MED);
28319 		if (dst == NULL)
28320 			return (B_FALSE);
28321 	} else {
28322 		dst = NULL;
28323 	}
28324 	if (*dstp != NULL)
28325 		mi_free(*dstp);
28326 	*dstp = dst;
28327 	*dstlenp = dst == NULL ? 0 : srclen;
28328 	return (B_TRUE);
28329 }
28330 
28331 /*
28332  * Replace what is in *dst, *dstlen with the source.
28333  * Assumes ip_allocbuf has already been called.
28334  */
28335 void
28336 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28337     const void *src, uint_t srclen)
28338 {
28339 	if (!src_valid)
28340 		srclen = 0;
28341 
28342 	ASSERT(*dstlenp == srclen);
28343 	if (src != NULL && srclen != 0)
28344 		bcopy(src, *dstp, srclen);
28345 }
28346 
28347 /*
28348  * Free the storage pointed to by the members of an ip6_pkt_t.
28349  */
28350 void
28351 ip6_pkt_free(ip6_pkt_t *ipp)
28352 {
28353 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
28354 
28355 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
28356 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
28357 		ipp->ipp_hopopts = NULL;
28358 		ipp->ipp_hopoptslen = 0;
28359 	}
28360 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
28361 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
28362 		ipp->ipp_rtdstopts = NULL;
28363 		ipp->ipp_rtdstoptslen = 0;
28364 	}
28365 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
28366 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
28367 		ipp->ipp_dstopts = NULL;
28368 		ipp->ipp_dstoptslen = 0;
28369 	}
28370 	if (ipp->ipp_fields & IPPF_RTHDR) {
28371 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
28372 		ipp->ipp_rthdr = NULL;
28373 		ipp->ipp_rthdrlen = 0;
28374 	}
28375 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
28376 	    IPPF_RTHDR);
28377 }
28378