xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision ac204d0d8540b5aa1b97cb5de5984f6cb831c517)
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 complete, we'll
15168 		 * create IREs.  Note that we intentionally mirror what
15169 		 * ipif_up() would have done, because we got here by way of
15170 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15171 		 */
15172 		if (ill->ill_isv6) {
15173 			/*
15174 			 * v6 interfaces.
15175 			 * Unlike ARP which has to do another bind
15176 			 * and attach, once we get here we are
15177 			 * done with NDP. Except in the case of
15178 			 * ILLF_XRESOLV, in which case we send an
15179 			 * AR_INTERFACE_UP to the external resolver.
15180 			 * If all goes well, the ioctl will complete
15181 			 * in ip_rput(). If there's an error, we
15182 			 * complete it here.
15183 			 */
15184 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15185 			    B_FALSE);
15186 			if (err == 0) {
15187 				if (ill->ill_flags & ILLF_XRESOLV) {
15188 					mutex_enter(&connp->conn_lock);
15189 					mutex_enter(&ill->ill_lock);
15190 					success = ipsq_pending_mp_add(
15191 					    connp, ipif, q, mp1, 0);
15192 					mutex_exit(&ill->ill_lock);
15193 					mutex_exit(&connp->conn_lock);
15194 					if (success) {
15195 						err = ipif_resolver_up(ipif,
15196 						    Res_act_initial);
15197 						if (err == EINPROGRESS) {
15198 							freemsg(mp);
15199 							return;
15200 						}
15201 						ASSERT(err != 0);
15202 						mp1 = ipsq_pending_mp_get(ipsq,
15203 						    &connp);
15204 						ASSERT(mp1 != NULL);
15205 					} else {
15206 						/* conn has started closing */
15207 						err = EINTR;
15208 					}
15209 				} else { /* Non XRESOLV interface */
15210 					(void) ipif_resolver_up(ipif,
15211 					    Res_act_initial);
15212 					err = ipif_up_done_v6(ipif);
15213 				}
15214 			}
15215 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15216 			/*
15217 			 * ARP and other v4 external resolvers.
15218 			 * Leave the pending mblk intact so that
15219 			 * the ioctl completes in ip_rput().
15220 			 */
15221 			mutex_enter(&connp->conn_lock);
15222 			mutex_enter(&ill->ill_lock);
15223 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15224 			mutex_exit(&ill->ill_lock);
15225 			mutex_exit(&connp->conn_lock);
15226 			if (success) {
15227 				err = ipif_resolver_up(ipif, Res_act_initial);
15228 				if (err == EINPROGRESS) {
15229 					freemsg(mp);
15230 					return;
15231 				}
15232 				ASSERT(err != 0);
15233 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15234 			} else {
15235 				/* The conn has started closing */
15236 				err = EINTR;
15237 			}
15238 		} else {
15239 			/*
15240 			 * This one is complete. Reply to pending ioctl.
15241 			 */
15242 			(void) ipif_resolver_up(ipif, Res_act_initial);
15243 			err = ipif_up_done(ipif);
15244 		}
15245 
15246 		if ((err == 0) && (ill->ill_up_ipifs)) {
15247 			err = ill_up_ipifs(ill, q, mp1);
15248 			if (err == EINPROGRESS) {
15249 				freemsg(mp);
15250 				return;
15251 			}
15252 		}
15253 
15254 		if (ill->ill_up_ipifs) {
15255 			ill_group_cleanup(ill);
15256 		}
15257 
15258 		break;
15259 	case DL_NOTIFY_IND: {
15260 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15261 		ire_t *ire;
15262 		boolean_t need_ire_walk_v4 = B_FALSE;
15263 		boolean_t need_ire_walk_v6 = B_FALSE;
15264 
15265 		/*
15266 		 * Change the address everywhere we need to.
15267 		 * What we're getting here is a link-level addr or phys addr.
15268 		 * The new addr is at notify + notify->dl_addr_offset
15269 		 * The address length is notify->dl_addr_length;
15270 		 */
15271 		switch (notify->dl_notification) {
15272 		case DL_NOTE_PHYS_ADDR:
15273 			mp_hw = copyb(mp);
15274 			if (mp_hw == NULL) {
15275 				err = ENOMEM;
15276 				break;
15277 			}
15278 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15279 			/*
15280 			 * We currently don't support changing
15281 			 * the token via DL_NOTIFY_IND.
15282 			 * When we do support it, we have to consider
15283 			 * what the implications are with respect to
15284 			 * the token and the link local address.
15285 			 */
15286 			mutex_enter(&ill->ill_lock);
15287 			if (dlp->notify_ind.dl_data ==
15288 			    DL_IPV6_LINK_LAYER_ADDR) {
15289 				if (ill->ill_nd_lla_mp != NULL)
15290 					freemsg(ill->ill_nd_lla_mp);
15291 				ill->ill_nd_lla_mp = mp_hw;
15292 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15293 				    dlp->notify_ind.dl_addr_offset;
15294 				ill->ill_nd_lla_len =
15295 				    dlp->notify_ind.dl_addr_length -
15296 				    ABS(ill->ill_sap_length);
15297 				mutex_exit(&ill->ill_lock);
15298 				break;
15299 			} else if (dlp->notify_ind.dl_data ==
15300 			    DL_CURR_PHYS_ADDR) {
15301 				if (ill->ill_phys_addr_mp != NULL)
15302 					freemsg(ill->ill_phys_addr_mp);
15303 				ill->ill_phys_addr_mp = mp_hw;
15304 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15305 				    dlp->notify_ind.dl_addr_offset;
15306 				ill->ill_phys_addr_length =
15307 				    dlp->notify_ind.dl_addr_length -
15308 				    ABS(ill->ill_sap_length);
15309 				if (ill->ill_isv6 &&
15310 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15311 					if (ill->ill_nd_lla_mp != NULL)
15312 						freemsg(ill->ill_nd_lla_mp);
15313 					ill->ill_nd_lla_mp = copyb(mp_hw);
15314 					ill->ill_nd_lla = (uchar_t *)
15315 					    ill->ill_nd_lla_mp->b_rptr +
15316 					    dlp->notify_ind.dl_addr_offset;
15317 					ill->ill_nd_lla_len =
15318 					    ill->ill_phys_addr_length;
15319 				}
15320 			}
15321 			mutex_exit(&ill->ill_lock);
15322 			/*
15323 			 * Send out gratuitous arp request for our new
15324 			 * hardware address.
15325 			 */
15326 			for (ipif = ill->ill_ipif; ipif != NULL;
15327 			    ipif = ipif->ipif_next) {
15328 				if (!(ipif->ipif_flags & IPIF_UP))
15329 					continue;
15330 				if (ill->ill_isv6) {
15331 					ipif_ndp_down(ipif);
15332 					/*
15333 					 * Set B_TRUE to enable
15334 					 * ipif_ndp_up() to send out
15335 					 * unsolicited advertisements.
15336 					 */
15337 					err = ipif_ndp_up(ipif,
15338 					    &ipif->ipif_v6lcl_addr,
15339 					    B_TRUE);
15340 					if (err) {
15341 						ip1dbg((
15342 						    "ip_rput_dlpi_writer: "
15343 						    "Failed to update ndp "
15344 						    "err %d\n", err));
15345 					}
15346 				} else {
15347 					/*
15348 					 * IPv4 ARP case
15349 					 *
15350 					 * Set Res_act_move, as we only want
15351 					 * ipif_resolver_up to send an
15352 					 * AR_ENTRY_ADD request up to
15353 					 * ARP.
15354 					 */
15355 					err = ipif_resolver_up(ipif,
15356 					    Res_act_move);
15357 					if (err) {
15358 						ip1dbg((
15359 						    "ip_rput_dlpi_writer: "
15360 						    "Failed to update arp "
15361 						    "err %d\n", err));
15362 					}
15363 				}
15364 			}
15365 			/*
15366 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15367 			 * case so that all old fastpath information can be
15368 			 * purged from IRE caches.
15369 			 */
15370 		/* FALLTHRU */
15371 		case DL_NOTE_FASTPATH_FLUSH:
15372 			/*
15373 			 * Any fastpath probe sent henceforth will get the
15374 			 * new fp mp. So we first delete any ires that are
15375 			 * waiting for the fastpath. Then walk all ires and
15376 			 * delete the ire or delete the fp mp. In the case of
15377 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15378 			 * recreate the ire's without going through a complex
15379 			 * ipif up/down dance. So we don't delete the ire
15380 			 * itself, but just the nce_fp_mp for these 2 ire's
15381 			 * In the case of the other ire's we delete the ire's
15382 			 * themselves. Access to nce_fp_mp is completely
15383 			 * protected by ire_lock for IRE_MIPRTUN and
15384 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15385 			 * other cases for performance.
15386 			 */
15387 			if (ill->ill_isv6) {
15388 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15389 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15390 				    NULL);
15391 			} else {
15392 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15393 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15394 				    IRE_CACHE | IRE_BROADCAST,
15395 				    ire_fastpath_flush, NULL, ill);
15396 				mutex_enter(&ire_mrtun_lock);
15397 				if (ire_mrtun_count != 0) {
15398 					mutex_exit(&ire_mrtun_lock);
15399 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15400 					    IRE_MIPRTUN, ire_fastpath_flush,
15401 					    NULL, ill);
15402 				} else {
15403 					mutex_exit(&ire_mrtun_lock);
15404 				}
15405 			}
15406 			break;
15407 		case DL_NOTE_SDU_SIZE:
15408 			/*
15409 			 * Change the MTU size of the interface, of all
15410 			 * attached ipif's, and of all relevant ire's.  The
15411 			 * new value's a uint32_t at notify->dl_data.
15412 			 * Mtu change Vs. new ire creation - protocol below.
15413 			 *
15414 			 * a Mark the ipif as IPIF_CHANGING.
15415 			 * b Set the new mtu in the ipif.
15416 			 * c Change the ire_max_frag on all affected ires
15417 			 * d Unmark the IPIF_CHANGING
15418 			 *
15419 			 * To see how the protocol works, assume an interface
15420 			 * route is also being added simultaneously by
15421 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15422 			 * the ire. If the ire is created before step a,
15423 			 * it will be cleaned up by step c. If the ire is
15424 			 * created after step d, it will see the new value of
15425 			 * ipif_mtu. Any attempt to create the ire between
15426 			 * steps a to d will fail because of the IPIF_CHANGING
15427 			 * flag. Note that ire_create() is passed a pointer to
15428 			 * the ipif_mtu, and not the value. During ire_add
15429 			 * under the bucket lock, the ire_max_frag of the
15430 			 * new ire being created is set from the ipif/ire from
15431 			 * which it is being derived.
15432 			 */
15433 			mutex_enter(&ill->ill_lock);
15434 			ill->ill_max_frag = (uint_t)notify->dl_data;
15435 
15436 			/*
15437 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15438 			 * leave it alone
15439 			 */
15440 			if (ill->ill_mtu_userspecified) {
15441 				mutex_exit(&ill->ill_lock);
15442 				break;
15443 			}
15444 			ill->ill_max_mtu = ill->ill_max_frag;
15445 			if (ill->ill_isv6) {
15446 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15447 					ill->ill_max_mtu = IPV6_MIN_MTU;
15448 			} else {
15449 				if (ill->ill_max_mtu < IP_MIN_MTU)
15450 					ill->ill_max_mtu = IP_MIN_MTU;
15451 			}
15452 			for (ipif = ill->ill_ipif; ipif != NULL;
15453 			    ipif = ipif->ipif_next) {
15454 				/*
15455 				 * Don't override the mtu if the user
15456 				 * has explicitly set it.
15457 				 */
15458 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15459 					continue;
15460 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15461 				if (ipif->ipif_isv6)
15462 					ire = ipif_to_ire_v6(ipif);
15463 				else
15464 					ire = ipif_to_ire(ipif);
15465 				if (ire != NULL) {
15466 					ire->ire_max_frag = ipif->ipif_mtu;
15467 					ire_refrele(ire);
15468 				}
15469 				if (ipif->ipif_flags & IPIF_UP) {
15470 					if (ill->ill_isv6)
15471 						need_ire_walk_v6 = B_TRUE;
15472 					else
15473 						need_ire_walk_v4 = B_TRUE;
15474 				}
15475 			}
15476 			mutex_exit(&ill->ill_lock);
15477 			if (need_ire_walk_v4)
15478 				ire_walk_v4(ill_mtu_change, (char *)ill,
15479 				    ALL_ZONES);
15480 			if (need_ire_walk_v6)
15481 				ire_walk_v6(ill_mtu_change, (char *)ill,
15482 				    ALL_ZONES);
15483 			break;
15484 		case DL_NOTE_LINK_UP:
15485 		case DL_NOTE_LINK_DOWN: {
15486 			/*
15487 			 * We are writer. ill / phyint / ipsq assocs stable.
15488 			 * The RUNNING flag reflects the state of the link.
15489 			 */
15490 			phyint_t *phyint = ill->ill_phyint;
15491 			uint64_t new_phyint_flags;
15492 			boolean_t changed = B_FALSE;
15493 			boolean_t went_up;
15494 
15495 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15496 			mutex_enter(&phyint->phyint_lock);
15497 			new_phyint_flags = went_up ?
15498 			    phyint->phyint_flags | PHYI_RUNNING :
15499 			    phyint->phyint_flags & ~PHYI_RUNNING;
15500 			if (new_phyint_flags != phyint->phyint_flags) {
15501 				phyint->phyint_flags = new_phyint_flags;
15502 				changed = B_TRUE;
15503 			}
15504 			mutex_exit(&phyint->phyint_lock);
15505 			/*
15506 			 * ill_restart_dad handles the DAD restart and routing
15507 			 * socket notification logic.
15508 			 */
15509 			if (changed) {
15510 				ill_restart_dad(phyint->phyint_illv4, went_up);
15511 				ill_restart_dad(phyint->phyint_illv6, went_up);
15512 			}
15513 			break;
15514 		}
15515 		case DL_NOTE_PROMISC_ON_PHYS:
15516 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15517 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15518 			mutex_enter(&ill->ill_lock);
15519 			ill->ill_promisc_on_phys = B_TRUE;
15520 			mutex_exit(&ill->ill_lock);
15521 			break;
15522 		case DL_NOTE_PROMISC_OFF_PHYS:
15523 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15524 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15525 			mutex_enter(&ill->ill_lock);
15526 			ill->ill_promisc_on_phys = B_FALSE;
15527 			mutex_exit(&ill->ill_lock);
15528 			break;
15529 		case DL_NOTE_CAPAB_RENEG:
15530 			/*
15531 			 * Something changed on the driver side.
15532 			 * It wants us to renegotiate the capabilities
15533 			 * on this ill. The most likely cause is the
15534 			 * aggregation interface under us where a
15535 			 * port got added or went away.
15536 			 *
15537 			 * We reset the capabilities and set the
15538 			 * state to IDMS_RENG so that when the ack
15539 			 * comes back, we can start the
15540 			 * renegotiation process.
15541 			 */
15542 			ill_capability_reset(ill);
15543 			ill->ill_capab_state = IDMS_RENEG;
15544 			break;
15545 		default:
15546 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15547 			    "type 0x%x for DL_NOTIFY_IND\n",
15548 			    notify->dl_notification));
15549 			break;
15550 		}
15551 
15552 		/*
15553 		 * As this is an asynchronous operation, we
15554 		 * should not call ill_dlpi_done
15555 		 */
15556 		break;
15557 	}
15558 	case DL_NOTIFY_ACK: {
15559 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15560 
15561 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15562 			ill->ill_note_link = 1;
15563 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15564 		break;
15565 	}
15566 	case DL_PHYS_ADDR_ACK: {
15567 		/*
15568 		 * We should have an IOCTL waiting on this when request
15569 		 * sent by ill_dl_phys.
15570 		 * However, ill_dl_phys was called on an ill queue (from
15571 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15572 		 * ioctl is known to be pending on ill_wq.
15573 		 * There are two additional phys_addr_req's sent to the
15574 		 * driver to get the token and lla. ill_phys_addr_pend
15575 		 * keeps track of the last one sent so we know which
15576 		 * response we are dealing with. ill_dlpi_done will
15577 		 * update ill_phys_addr_pend when it sends the next req.
15578 		 * We don't complete the IOCTL until all three DL_PARs
15579 		 * have been attempted.
15580 		 *
15581 		 * We don't need any lock to update ill_nd_lla* fields,
15582 		 * since the ill is not yet up, We grab the lock just
15583 		 * for uniformity with other code that accesses ill_nd_lla.
15584 		 */
15585 		physaddr_req = ill->ill_phys_addr_pend;
15586 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15587 		if (physaddr_req == DL_IPV6_TOKEN ||
15588 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15589 			if (physaddr_req == DL_IPV6_TOKEN) {
15590 				/*
15591 				 * bcopy to low-order bits of ill_token
15592 				 *
15593 				 * XXX Temporary hack - currently,
15594 				 * all known tokens are 64 bits,
15595 				 * so I'll cheat for the moment.
15596 				 */
15597 				dlp = (union DL_primitives *)mp->b_rptr;
15598 
15599 				mutex_enter(&ill->ill_lock);
15600 				bcopy((uchar_t *)(mp->b_rptr +
15601 				dlp->physaddr_ack.dl_addr_offset),
15602 				(void *)&ill->ill_token.s6_addr32[2],
15603 				dlp->physaddr_ack.dl_addr_length);
15604 				ill->ill_token_length =
15605 					dlp->physaddr_ack.dl_addr_length;
15606 				mutex_exit(&ill->ill_lock);
15607 			} else {
15608 				ASSERT(ill->ill_nd_lla_mp == NULL);
15609 				mp_hw = copyb(mp);
15610 				if (mp_hw == NULL) {
15611 					err = ENOMEM;
15612 					break;
15613 				}
15614 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15615 				mutex_enter(&ill->ill_lock);
15616 				ill->ill_nd_lla_mp = mp_hw;
15617 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15618 				dlp->physaddr_ack.dl_addr_offset;
15619 				ill->ill_nd_lla_len =
15620 					dlp->physaddr_ack.dl_addr_length;
15621 				mutex_exit(&ill->ill_lock);
15622 			}
15623 			break;
15624 		}
15625 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15626 		ASSERT(ill->ill_phys_addr_mp == NULL);
15627 		if (!ill->ill_ifname_pending)
15628 			break;
15629 		ill->ill_ifname_pending = 0;
15630 		if (!ioctl_aborted)
15631 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15632 		if (mp1 != NULL) {
15633 			ASSERT(connp == NULL);
15634 			q = ill->ill_wq;
15635 		}
15636 		/*
15637 		 * If any error acks received during the plumbing sequence,
15638 		 * ill_ifname_pending_err will be set. Break out and send up
15639 		 * the error to the pending ioctl.
15640 		 */
15641 		if (ill->ill_ifname_pending_err != 0) {
15642 			err = ill->ill_ifname_pending_err;
15643 			ill->ill_ifname_pending_err = 0;
15644 			break;
15645 		}
15646 		/*
15647 		 * Get the interface token.  If the zeroth interface
15648 		 * address is zero then set the address to the link local
15649 		 * address
15650 		 */
15651 		mp_hw = copyb(mp);
15652 		if (mp_hw == NULL) {
15653 			err = ENOMEM;
15654 			break;
15655 		}
15656 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15657 		ill->ill_phys_addr_mp = mp_hw;
15658 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15659 				dlp->physaddr_ack.dl_addr_offset;
15660 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15661 		    ill->ill_phys_addr_length == 0 ||
15662 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15663 			/*
15664 			 * Compatibility: atun driver returns a length of 0.
15665 			 * ipdptp has an ill_phys_addr_length of zero(from
15666 			 * DL_BIND_ACK) but a non-zero length here.
15667 			 * ipd has an ill_phys_addr_length of 4(from
15668 			 * DL_BIND_ACK) but a non-zero length here.
15669 			 */
15670 			ill->ill_phys_addr = NULL;
15671 		} else if (dlp->physaddr_ack.dl_addr_length !=
15672 		    ill->ill_phys_addr_length) {
15673 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15674 			    "Address length mismatch %d %d\n",
15675 			    dlp->physaddr_ack.dl_addr_length,
15676 			    ill->ill_phys_addr_length));
15677 			err = EINVAL;
15678 			break;
15679 		}
15680 		mutex_enter(&ill->ill_lock);
15681 		if (ill->ill_nd_lla_mp == NULL) {
15682 			ill->ill_nd_lla_mp = copyb(mp_hw);
15683 			if (ill->ill_nd_lla_mp == NULL) {
15684 				err = ENOMEM;
15685 				mutex_exit(&ill->ill_lock);
15686 				break;
15687 			}
15688 			ill->ill_nd_lla =
15689 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15690 			    dlp->physaddr_ack.dl_addr_offset;
15691 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15692 		}
15693 		mutex_exit(&ill->ill_lock);
15694 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15695 			(void) ill_setdefaulttoken(ill);
15696 
15697 		/*
15698 		 * If the ill zero interface has a zero address assign
15699 		 * it the proper link local address.
15700 		 */
15701 		ASSERT(ill->ill_ipif->ipif_id == 0);
15702 		if (ipif != NULL &&
15703 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15704 			(void) ipif_setlinklocal(ipif);
15705 		break;
15706 	}
15707 	case DL_OK_ACK:
15708 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15709 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15710 		    dloa->dl_correct_primitive));
15711 		switch (dloa->dl_correct_primitive) {
15712 		case DL_UNBIND_REQ:
15713 		case DL_ATTACH_REQ:
15714 		case DL_DETACH_REQ:
15715 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15716 			break;
15717 		}
15718 		break;
15719 	default:
15720 		break;
15721 	}
15722 
15723 	freemsg(mp);
15724 	if (mp1) {
15725 		struct iocblk *iocp;
15726 		int mode;
15727 
15728 		/*
15729 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15730 		 * SIOCSLIFNAME do a copyout.
15731 		 */
15732 		iocp = (struct iocblk *)mp1->b_rptr;
15733 
15734 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
15735 		    iocp->ioc_cmd == SIOCSLIFNAME)
15736 			mode = COPYOUT;
15737 		else
15738 			mode = NO_COPYOUT;
15739 		/*
15740 		 * The ioctl must complete now without EINPROGRESS
15741 		 * since ipsq_pending_mp_get has removed the ioctl mblk
15742 		 * from ipsq_pending_mp. Otherwise the ioctl will be
15743 		 * stuck for ever in the ipsq.
15744 		 */
15745 		ASSERT(err != EINPROGRESS);
15746 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
15747 
15748 	}
15749 }
15750 
15751 /*
15752  * ip_rput_other is called by ip_rput to handle messages modifying the global
15753  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15754  */
15755 /* ARGSUSED */
15756 void
15757 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15758 {
15759 	ill_t		*ill;
15760 	struct iocblk	*iocp;
15761 	mblk_t		*mp1;
15762 	conn_t		*connp = NULL;
15763 
15764 	ip1dbg(("ip_rput_other "));
15765 	ill = (ill_t *)q->q_ptr;
15766 	/*
15767 	 * This routine is not a writer in the case of SIOCGTUNPARAM
15768 	 * in which case ipsq is NULL.
15769 	 */
15770 	if (ipsq != NULL) {
15771 		ASSERT(IAM_WRITER_IPSQ(ipsq));
15772 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15773 	}
15774 
15775 	switch (mp->b_datap->db_type) {
15776 	case M_ERROR:
15777 	case M_HANGUP:
15778 		/*
15779 		 * The device has a problem.  We force the ILL down.  It can
15780 		 * be brought up again manually using SIOCSIFFLAGS (via
15781 		 * ifconfig or equivalent).
15782 		 */
15783 		ASSERT(ipsq != NULL);
15784 		if (mp->b_rptr < mp->b_wptr)
15785 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
15786 		if (ill->ill_error == 0)
15787 			ill->ill_error = ENXIO;
15788 		if (!ill_down_start(q, mp))
15789 			return;
15790 		ipif_all_down_tail(ipsq, q, mp, NULL);
15791 		break;
15792 	case M_IOCACK:
15793 		iocp = (struct iocblk *)mp->b_rptr;
15794 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
15795 		switch (iocp->ioc_cmd) {
15796 		case SIOCSTUNPARAM:
15797 		case OSIOCSTUNPARAM:
15798 			ASSERT(ipsq != NULL);
15799 			/*
15800 			 * Finish socket ioctl passed through to tun.
15801 			 * We should have an IOCTL waiting on this.
15802 			 */
15803 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15804 			if (ill->ill_isv6) {
15805 				struct iftun_req *ta;
15806 
15807 				/*
15808 				 * if a source or destination is
15809 				 * being set, try and set the link
15810 				 * local address for the tunnel
15811 				 */
15812 				ta = (struct iftun_req *)mp->b_cont->
15813 				    b_cont->b_rptr;
15814 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
15815 					ipif_set_tun_llink(ill, ta);
15816 				}
15817 
15818 			}
15819 			if (mp1 != NULL) {
15820 				/*
15821 				 * Now copy back the b_next/b_prev used by
15822 				 * mi code for the mi_copy* functions.
15823 				 * See ip_sioctl_tunparam() for the reason.
15824 				 * Also protect against missing b_cont.
15825 				 */
15826 				if (mp->b_cont != NULL) {
15827 					mp->b_cont->b_next =
15828 					    mp1->b_cont->b_next;
15829 					mp->b_cont->b_prev =
15830 					    mp1->b_cont->b_prev;
15831 				}
15832 				inet_freemsg(mp1);
15833 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15834 				ASSERT(connp != NULL);
15835 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15836 				    iocp->ioc_error, NO_COPYOUT,
15837 				    ipsq->ipsq_current_ipif, ipsq);
15838 			} else {
15839 				ASSERT(connp == NULL);
15840 				putnext(q, mp);
15841 			}
15842 			break;
15843 		case SIOCGTUNPARAM:
15844 		case OSIOCGTUNPARAM:
15845 			/*
15846 			 * This is really M_IOCDATA from the tunnel driver.
15847 			 * convert back and complete the ioctl.
15848 			 * We should have an IOCTL waiting on this.
15849 			 */
15850 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
15851 			if (mp1) {
15852 				/*
15853 				 * Now copy back the b_next/b_prev used by
15854 				 * mi code for the mi_copy* functions.
15855 				 * See ip_sioctl_tunparam() for the reason.
15856 				 * Also protect against missing b_cont.
15857 				 */
15858 				if (mp->b_cont != NULL) {
15859 					mp->b_cont->b_next =
15860 					    mp1->b_cont->b_next;
15861 					mp->b_cont->b_prev =
15862 					    mp1->b_cont->b_prev;
15863 				}
15864 				inet_freemsg(mp1);
15865 				if (iocp->ioc_error == 0)
15866 					mp->b_datap->db_type = M_IOCDATA;
15867 				ASSERT(connp != NULL);
15868 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15869 				    iocp->ioc_error, COPYOUT, NULL, NULL);
15870 			} else {
15871 				ASSERT(connp == NULL);
15872 				putnext(q, mp);
15873 			}
15874 			break;
15875 		default:
15876 			break;
15877 		}
15878 		break;
15879 	case M_IOCNAK:
15880 		iocp = (struct iocblk *)mp->b_rptr;
15881 
15882 		switch (iocp->ioc_cmd) {
15883 		int mode;
15884 		ipif_t	*ipif;
15885 
15886 		case DL_IOC_HDR_INFO:
15887 			/*
15888 			 * If this was the first attempt turn of the
15889 			 * fastpath probing.
15890 			 */
15891 			mutex_enter(&ill->ill_lock);
15892 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
15893 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
15894 				mutex_exit(&ill->ill_lock);
15895 				ill_fastpath_nack(ill);
15896 				ip1dbg(("ip_rput: DLPI fastpath off on "
15897 				    "interface %s\n",
15898 				    ill->ill_name));
15899 			} else {
15900 				mutex_exit(&ill->ill_lock);
15901 			}
15902 			freemsg(mp);
15903 			break;
15904 		case SIOCSTUNPARAM:
15905 		case OSIOCSTUNPARAM:
15906 			ASSERT(ipsq != NULL);
15907 			/*
15908 			 * Finish socket ioctl passed through to tun
15909 			 * We should have an IOCTL waiting on this.
15910 			 */
15911 			/* FALLTHRU */
15912 		case SIOCGTUNPARAM:
15913 		case OSIOCGTUNPARAM:
15914 			/*
15915 			 * This is really M_IOCDATA from the tunnel driver.
15916 			 * convert back and complete the ioctl.
15917 			 * We should have an IOCTL waiting on this.
15918 			 */
15919 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
15920 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
15921 				mp1 = ill_pending_mp_get(ill, &connp,
15922 				    iocp->ioc_id);
15923 				mode = COPYOUT;
15924 				ipsq = NULL;
15925 				ipif = NULL;
15926 			} else {
15927 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15928 				mode = NO_COPYOUT;
15929 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15930 				ipif = ipsq->ipsq_current_ipif;
15931 			}
15932 			if (mp1 != NULL) {
15933 				/*
15934 				 * Now copy back the b_next/b_prev used by
15935 				 * mi code for the mi_copy* functions.
15936 				 * See ip_sioctl_tunparam() for the reason.
15937 				 * Also protect against missing b_cont.
15938 				 */
15939 				if (mp->b_cont != NULL) {
15940 					mp->b_cont->b_next =
15941 					    mp1->b_cont->b_next;
15942 					mp->b_cont->b_prev =
15943 					    mp1->b_cont->b_prev;
15944 				}
15945 				inet_freemsg(mp1);
15946 				if (iocp->ioc_error == 0)
15947 					iocp->ioc_error = EINVAL;
15948 				ASSERT(connp != NULL);
15949 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15950 				    iocp->ioc_error, mode, ipif, ipsq);
15951 			} else {
15952 				ASSERT(connp == NULL);
15953 				putnext(q, mp);
15954 			}
15955 			break;
15956 		default:
15957 			break;
15958 		}
15959 	default:
15960 		break;
15961 	}
15962 }
15963 
15964 /*
15965  * NOTE : This function does not ire_refrele the ire argument passed in.
15966  *
15967  * IPQoS notes
15968  * IP policy is invoked twice for a forwarded packet, once on the read side
15969  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
15970  * enabled. An additional parameter, in_ill, has been added for this purpose.
15971  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
15972  * because ip_mroute drops this information.
15973  *
15974  */
15975 void
15976 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
15977 {
15978 	uint32_t	pkt_len;
15979 	queue_t	*q;
15980 	uint32_t	sum;
15981 #define	rptr	((uchar_t *)ipha)
15982 	uint32_t	max_frag;
15983 	uint32_t	ill_index;
15984 
15985 	/* Get the ill_index of the incoming ILL */
15986 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
15987 
15988 	/* Initiate Read side IPPF processing */
15989 	if (IPP_ENABLED(IPP_FWD_IN)) {
15990 		ip_process(IPP_FWD_IN, &mp, ill_index);
15991 		if (mp == NULL) {
15992 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
15993 			    "during IPPF processing\n"));
15994 			return;
15995 		}
15996 	}
15997 
15998 	pkt_len = ntohs(ipha->ipha_length);
15999 
16000 	/* Adjust the checksum to reflect the ttl decrement. */
16001 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16002 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16003 
16004 	if (ipha->ipha_ttl-- <= 1) {
16005 		if (ip_csum_hdr(ipha)) {
16006 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16007 			goto drop_pkt;
16008 		}
16009 		/*
16010 		 * Note: ire_stq this will be NULL for multicast
16011 		 * datagrams using the long path through arp (the IRE
16012 		 * is not an IRE_CACHE). This should not cause
16013 		 * problems since we don't generate ICMP errors for
16014 		 * multicast packets.
16015 		 */
16016 		q = ire->ire_stq;
16017 		if (q)
16018 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
16019 		else
16020 			freemsg(mp);
16021 		return;
16022 	}
16023 
16024 	/*
16025 	 * Don't forward if the interface is down
16026 	 */
16027 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16028 		BUMP_MIB(&ip_mib, ipInDiscards);
16029 		ip2dbg(("ip_rput_forward:interface is down\n"));
16030 		goto drop_pkt;
16031 	}
16032 
16033 	/* Get the ill_index of the outgoing ILL */
16034 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16035 
16036 	if (is_system_labeled()) {
16037 		mblk_t *mp1;
16038 
16039 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16040 			BUMP_MIB(&ip_mib, ipForwProhibits);
16041 			goto drop_pkt;
16042 		}
16043 		/* Size may have changed */
16044 		mp = mp1;
16045 		ipha = (ipha_t *)mp->b_rptr;
16046 		pkt_len = ntohs(ipha->ipha_length);
16047 	}
16048 
16049 	/* Check if there are options to update */
16050 	if (!IS_SIMPLE_IPH(ipha)) {
16051 		if (ip_csum_hdr(ipha)) {
16052 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16053 			goto drop_pkt;
16054 		}
16055 		if (ip_rput_forward_options(mp, ipha, ire)) {
16056 			return;
16057 		}
16058 
16059 		ipha->ipha_hdr_checksum = 0;
16060 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16061 	}
16062 	max_frag = ire->ire_max_frag;
16063 	if (pkt_len > max_frag) {
16064 		/*
16065 		 * It needs fragging on its way out.  We haven't
16066 		 * verified the header checksum yet.  Since we
16067 		 * are going to put a surely good checksum in the
16068 		 * outgoing header, we have to make sure that it
16069 		 * was good coming in.
16070 		 */
16071 		if (ip_csum_hdr(ipha)) {
16072 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16073 			goto drop_pkt;
16074 		}
16075 		/* Initiate Write side IPPF processing */
16076 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16077 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16078 			if (mp == NULL) {
16079 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16080 				    " during IPPF processing\n"));
16081 				return;
16082 			}
16083 		}
16084 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
16085 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16086 		return;
16087 	}
16088 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16089 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16090 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16091 	/* ip_xmit_v4 always consumes the packet */
16092 	return;
16093 
16094 drop_pkt:;
16095 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16096 	freemsg(mp);
16097 #undef	rptr
16098 }
16099 
16100 void
16101 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16102 {
16103 	ire_t	*ire;
16104 
16105 	ASSERT(!ipif->ipif_isv6);
16106 	/*
16107 	 * Find an IRE which matches the destination and the outgoing
16108 	 * queue in the cache table. All we need is an IRE_CACHE which
16109 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16110 	 * then it is enough to have some IRE_CACHE in the group.
16111 	 */
16112 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16113 		dst = ipif->ipif_pp_dst_addr;
16114 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16115 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16116 	if (ire == NULL) {
16117 		/*
16118 		 * Mark this packet to make it be delivered to
16119 		 * ip_rput_forward after the new ire has been
16120 		 * created.
16121 		 */
16122 		mp->b_prev = NULL;
16123 		mp->b_next = mp;
16124 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16125 		    NULL, 0);
16126 	} else {
16127 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16128 		IRE_REFRELE(ire);
16129 	}
16130 }
16131 
16132 /* Update any source route, record route or timestamp options */
16133 static int
16134 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16135 {
16136 	ipoptp_t	opts;
16137 	uchar_t		*opt;
16138 	uint8_t		optval;
16139 	uint8_t		optlen;
16140 	ipaddr_t	dst;
16141 	uint32_t	ts;
16142 	ire_t		*dst_ire = NULL;
16143 	ire_t		*tmp_ire = NULL;
16144 	timestruc_t	now;
16145 
16146 	ip2dbg(("ip_rput_forward_options\n"));
16147 	dst = ipha->ipha_dst;
16148 	for (optval = ipoptp_first(&opts, ipha);
16149 	    optval != IPOPT_EOL;
16150 	    optval = ipoptp_next(&opts)) {
16151 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16152 		opt = opts.ipoptp_cur;
16153 		optlen = opts.ipoptp_len;
16154 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16155 		    optval, opts.ipoptp_len));
16156 		switch (optval) {
16157 			uint32_t off;
16158 		case IPOPT_SSRR:
16159 		case IPOPT_LSRR:
16160 			/* Check if adminstratively disabled */
16161 			if (!ip_forward_src_routed) {
16162 				BUMP_MIB(&ip_mib, ipForwProhibits);
16163 				if (ire->ire_stq)
16164 					icmp_unreachable(ire->ire_stq, mp,
16165 					    ICMP_SOURCE_ROUTE_FAILED);
16166 				else {
16167 					ip0dbg(("ip_rput_forward_options: "
16168 					    "unable to send unreach\n"));
16169 					freemsg(mp);
16170 				}
16171 				return (-1);
16172 			}
16173 
16174 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16175 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16176 			if (dst_ire == NULL) {
16177 				/*
16178 				 * Must be partial since ip_rput_options
16179 				 * checked for strict.
16180 				 */
16181 				break;
16182 			}
16183 			off = opt[IPOPT_OFFSET];
16184 			off--;
16185 		redo_srr:
16186 			if (optlen < IP_ADDR_LEN ||
16187 			    off > optlen - IP_ADDR_LEN) {
16188 				/* End of source route */
16189 				ip1dbg((
16190 				    "ip_rput_forward_options: end of SR\n"));
16191 				ire_refrele(dst_ire);
16192 				break;
16193 			}
16194 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16195 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16196 			    IP_ADDR_LEN);
16197 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16198 			    ntohl(dst)));
16199 
16200 			/*
16201 			 * Check if our address is present more than
16202 			 * once as consecutive hops in source route.
16203 			 */
16204 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16205 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16206 			if (tmp_ire != NULL) {
16207 				ire_refrele(tmp_ire);
16208 				off += IP_ADDR_LEN;
16209 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16210 				goto redo_srr;
16211 			}
16212 			ipha->ipha_dst = dst;
16213 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16214 			ire_refrele(dst_ire);
16215 			break;
16216 		case IPOPT_RR:
16217 			off = opt[IPOPT_OFFSET];
16218 			off--;
16219 			if (optlen < IP_ADDR_LEN ||
16220 			    off > optlen - IP_ADDR_LEN) {
16221 				/* No more room - ignore */
16222 				ip1dbg((
16223 				    "ip_rput_forward_options: end of RR\n"));
16224 				break;
16225 			}
16226 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16227 			    IP_ADDR_LEN);
16228 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16229 			break;
16230 		case IPOPT_TS:
16231 			/* Insert timestamp if there is room */
16232 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16233 			case IPOPT_TS_TSONLY:
16234 				off = IPOPT_TS_TIMELEN;
16235 				break;
16236 			case IPOPT_TS_PRESPEC:
16237 			case IPOPT_TS_PRESPEC_RFC791:
16238 				/* Verify that the address matched */
16239 				off = opt[IPOPT_OFFSET] - 1;
16240 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16241 				dst_ire = ire_ctable_lookup(dst, 0,
16242 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16243 				    MATCH_IRE_TYPE);
16244 
16245 				if (dst_ire == NULL) {
16246 					/* Not for us */
16247 					break;
16248 				}
16249 				ire_refrele(dst_ire);
16250 				/* FALLTHRU */
16251 			case IPOPT_TS_TSANDADDR:
16252 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16253 				break;
16254 			default:
16255 				/*
16256 				 * ip_*put_options should have already
16257 				 * dropped this packet.
16258 				 */
16259 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16260 				    "unknown IT - bug in ip_rput_options?\n");
16261 				return (0);	/* Keep "lint" happy */
16262 			}
16263 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16264 				/* Increase overflow counter */
16265 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16266 				opt[IPOPT_POS_OV_FLG] =
16267 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16268 				    (off << 4));
16269 				break;
16270 			}
16271 			off = opt[IPOPT_OFFSET] - 1;
16272 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16273 			case IPOPT_TS_PRESPEC:
16274 			case IPOPT_TS_PRESPEC_RFC791:
16275 			case IPOPT_TS_TSANDADDR:
16276 				bcopy(&ire->ire_src_addr,
16277 				    (char *)opt + off, IP_ADDR_LEN);
16278 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16279 				/* FALLTHRU */
16280 			case IPOPT_TS_TSONLY:
16281 				off = opt[IPOPT_OFFSET] - 1;
16282 				/* Compute # of milliseconds since midnight */
16283 				gethrestime(&now);
16284 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16285 				    now.tv_nsec / (NANOSEC / MILLISEC);
16286 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16287 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16288 				break;
16289 			}
16290 			break;
16291 		}
16292 	}
16293 	return (0);
16294 }
16295 
16296 /*
16297  * This is called after processing at least one of AH/ESP headers.
16298  *
16299  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16300  * the actual, physical interface on which the packet was received,
16301  * but, when ip_strict_dst_multihoming is set to 1, could be the
16302  * interface which had the ipha_dst configured when the packet went
16303  * through ip_rput. The ill_index corresponding to the recv_ill
16304  * is saved in ipsec_in_rill_index
16305  */
16306 void
16307 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16308 {
16309 	mblk_t *mp;
16310 	ipaddr_t dst;
16311 	in6_addr_t *v6dstp;
16312 	ipha_t *ipha;
16313 	ip6_t *ip6h;
16314 	ipsec_in_t *ii;
16315 	boolean_t ill_need_rele = B_FALSE;
16316 	boolean_t rill_need_rele = B_FALSE;
16317 	boolean_t ire_need_rele = B_FALSE;
16318 
16319 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16320 	ASSERT(ii->ipsec_in_ill_index != 0);
16321 
16322 	mp = ipsec_mp->b_cont;
16323 	ASSERT(mp != NULL);
16324 
16325 
16326 	if (ill == NULL) {
16327 		ASSERT(recv_ill == NULL);
16328 		/*
16329 		 * We need to get the original queue on which ip_rput_local
16330 		 * or ip_rput_data_v6 was called.
16331 		 */
16332 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16333 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16334 		ill_need_rele = B_TRUE;
16335 
16336 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16337 			recv_ill = ill_lookup_on_ifindex(
16338 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16339 			    NULL, NULL, NULL, NULL);
16340 			rill_need_rele = B_TRUE;
16341 		} else {
16342 			recv_ill = ill;
16343 		}
16344 
16345 		if ((ill == NULL) || (recv_ill == NULL)) {
16346 			ip0dbg(("ip_fanout_proto_again: interface "
16347 			    "disappeared\n"));
16348 			if (ill != NULL)
16349 				ill_refrele(ill);
16350 			if (recv_ill != NULL)
16351 				ill_refrele(recv_ill);
16352 			freemsg(ipsec_mp);
16353 			return;
16354 		}
16355 	}
16356 
16357 	ASSERT(ill != NULL && recv_ill != NULL);
16358 
16359 	if (mp->b_datap->db_type == M_CTL) {
16360 		/*
16361 		 * AH/ESP is returning the ICMP message after
16362 		 * removing their headers. Fanout again till
16363 		 * it gets to the right protocol.
16364 		 */
16365 		if (ii->ipsec_in_v4) {
16366 			icmph_t *icmph;
16367 			int iph_hdr_length;
16368 			int hdr_length;
16369 
16370 			ipha = (ipha_t *)mp->b_rptr;
16371 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16372 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16373 			ipha = (ipha_t *)&icmph[1];
16374 			hdr_length = IPH_HDR_LENGTH(ipha);
16375 			/*
16376 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16377 			 * Reset the type to M_DATA.
16378 			 */
16379 			mp->b_datap->db_type = M_DATA;
16380 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16381 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16382 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16383 		} else {
16384 			icmp6_t *icmp6;
16385 			int hdr_length;
16386 
16387 			ip6h = (ip6_t *)mp->b_rptr;
16388 			/* Don't call hdr_length_v6() unless you have to. */
16389 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16390 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16391 			else
16392 				hdr_length = IPV6_HDR_LEN;
16393 
16394 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16395 			/*
16396 			 * icmp_inbound_error_fanout_v6 may need to do
16397 			 * pullupmsg.  Reset the type to M_DATA.
16398 			 */
16399 			mp->b_datap->db_type = M_DATA;
16400 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16401 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16402 		}
16403 		if (ill_need_rele)
16404 			ill_refrele(ill);
16405 		if (rill_need_rele)
16406 			ill_refrele(recv_ill);
16407 		return;
16408 	}
16409 
16410 	if (ii->ipsec_in_v4) {
16411 		ipha = (ipha_t *)mp->b_rptr;
16412 		dst = ipha->ipha_dst;
16413 		if (CLASSD(dst)) {
16414 			/*
16415 			 * Multicast has to be delivered to all streams.
16416 			 */
16417 			dst = INADDR_BROADCAST;
16418 		}
16419 
16420 		if (ire == NULL) {
16421 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16422 			    MBLK_GETLABEL(mp));
16423 			if (ire == NULL) {
16424 				if (ill_need_rele)
16425 					ill_refrele(ill);
16426 				if (rill_need_rele)
16427 					ill_refrele(recv_ill);
16428 				ip1dbg(("ip_fanout_proto_again: "
16429 				    "IRE not found"));
16430 				freemsg(ipsec_mp);
16431 				return;
16432 			}
16433 			ire_need_rele = B_TRUE;
16434 		}
16435 
16436 		switch (ipha->ipha_protocol) {
16437 			case IPPROTO_UDP:
16438 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16439 				    recv_ill);
16440 				if (ire_need_rele)
16441 					ire_refrele(ire);
16442 				break;
16443 			case IPPROTO_TCP:
16444 				if (!ire_need_rele)
16445 					IRE_REFHOLD(ire);
16446 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16447 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16448 				IRE_REFRELE(ire);
16449 				if (mp != NULL)
16450 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16451 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16452 				break;
16453 			case IPPROTO_SCTP:
16454 				if (!ire_need_rele)
16455 					IRE_REFHOLD(ire);
16456 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16457 				    ipsec_mp, 0, ill->ill_rq, dst);
16458 				break;
16459 			default:
16460 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16461 				    recv_ill);
16462 				if (ire_need_rele)
16463 					ire_refrele(ire);
16464 				break;
16465 		}
16466 	} else {
16467 		uint32_t rput_flags = 0;
16468 
16469 		ip6h = (ip6_t *)mp->b_rptr;
16470 		v6dstp = &ip6h->ip6_dst;
16471 		/*
16472 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16473 		 * address.
16474 		 *
16475 		 * Currently, we don't store that state in the IPSEC_IN
16476 		 * message, and we may need to.
16477 		 */
16478 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16479 		    IP6_IN_LLMCAST : 0);
16480 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16481 		    NULL, NULL);
16482 	}
16483 	if (ill_need_rele)
16484 		ill_refrele(ill);
16485 	if (rill_need_rele)
16486 		ill_refrele(recv_ill);
16487 }
16488 
16489 /*
16490  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16491  * returns 'true' if there are still fragments left on the queue, in
16492  * which case we restart the timer.
16493  */
16494 void
16495 ill_frag_timer(void *arg)
16496 {
16497 	ill_t	*ill = (ill_t *)arg;
16498 	boolean_t frag_pending;
16499 
16500 	mutex_enter(&ill->ill_lock);
16501 	ASSERT(!ill->ill_fragtimer_executing);
16502 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16503 		ill->ill_frag_timer_id = 0;
16504 		mutex_exit(&ill->ill_lock);
16505 		return;
16506 	}
16507 	ill->ill_fragtimer_executing = 1;
16508 	mutex_exit(&ill->ill_lock);
16509 
16510 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16511 
16512 	/*
16513 	 * Restart the timer, if we have fragments pending or if someone
16514 	 * wanted us to be scheduled again.
16515 	 */
16516 	mutex_enter(&ill->ill_lock);
16517 	ill->ill_fragtimer_executing = 0;
16518 	ill->ill_frag_timer_id = 0;
16519 	if (frag_pending || ill->ill_fragtimer_needrestart)
16520 		ill_frag_timer_start(ill);
16521 	mutex_exit(&ill->ill_lock);
16522 }
16523 
16524 void
16525 ill_frag_timer_start(ill_t *ill)
16526 {
16527 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16528 
16529 	/* If the ill is closing or opening don't proceed */
16530 	if (ill->ill_state_flags & ILL_CONDEMNED)
16531 		return;
16532 
16533 	if (ill->ill_fragtimer_executing) {
16534 		/*
16535 		 * ill_frag_timer is currently executing. Just record the
16536 		 * the fact that we want the timer to be restarted.
16537 		 * ill_frag_timer will post a timeout before it returns,
16538 		 * ensuring it will be called again.
16539 		 */
16540 		ill->ill_fragtimer_needrestart = 1;
16541 		return;
16542 	}
16543 
16544 	if (ill->ill_frag_timer_id == 0) {
16545 		/*
16546 		 * The timer is neither running nor is the timeout handler
16547 		 * executing. Post a timeout so that ill_frag_timer will be
16548 		 * called
16549 		 */
16550 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16551 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16552 		ill->ill_fragtimer_needrestart = 0;
16553 	}
16554 }
16555 
16556 /*
16557  * This routine is needed for loopback when forwarding multicasts.
16558  *
16559  * IPQoS Notes:
16560  * IPPF processing is done in fanout routines.
16561  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16562  * processing for IPSec packets is done when it comes back in clear.
16563  * NOTE : The callers of this function need to do the ire_refrele for the
16564  *	  ire that is being passed in.
16565  */
16566 void
16567 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16568     ill_t *recv_ill)
16569 {
16570 	ill_t	*ill = (ill_t *)q->q_ptr;
16571 	uint32_t	sum;
16572 	uint32_t	u1;
16573 	uint32_t	u2;
16574 	int		hdr_length;
16575 	boolean_t	mctl_present;
16576 	mblk_t		*first_mp = mp;
16577 	mblk_t		*hada_mp = NULL;
16578 	ipha_t		*inner_ipha;
16579 
16580 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16581 	    "ip_rput_locl_start: q %p", q);
16582 
16583 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16584 
16585 
16586 #define	rptr	((uchar_t *)ipha)
16587 #define	iphs	((uint16_t *)ipha)
16588 
16589 	/*
16590 	 * no UDP or TCP packet should come here anymore.
16591 	 */
16592 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16593 	    (ipha->ipha_protocol != IPPROTO_UDP));
16594 
16595 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16596 	if (mctl_present &&
16597 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16598 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16599 
16600 		/*
16601 		 * It's an IPsec accelerated packet.
16602 		 * Keep a pointer to the data attributes around until
16603 		 * we allocate the ipsec_info_t.
16604 		 */
16605 		IPSECHW_DEBUG(IPSECHW_PKT,
16606 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16607 		hada_mp = first_mp;
16608 		hada_mp->b_cont = NULL;
16609 		/*
16610 		 * Since it is accelerated, it comes directly from
16611 		 * the ill and the data attributes is followed by
16612 		 * the packet data.
16613 		 */
16614 		ASSERT(mp->b_datap->db_type != M_CTL);
16615 		first_mp = mp;
16616 		mctl_present = B_FALSE;
16617 	}
16618 
16619 	/*
16620 	 * IF M_CTL is not present, then ipsec_in_is_secure
16621 	 * should return B_TRUE. There is a case where loopback
16622 	 * packets has an M_CTL in the front with all the
16623 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16624 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16625 	 * packets never comes here, it is safe to ASSERT the
16626 	 * following.
16627 	 */
16628 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16629 
16630 
16631 	/* u1 is # words of IP options */
16632 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16633 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16634 
16635 	if (u1) {
16636 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16637 			if (hada_mp != NULL)
16638 				freemsg(hada_mp);
16639 			return;
16640 		}
16641 	} else {
16642 		/* Check the IP header checksum.  */
16643 #define	uph	((uint16_t *)ipha)
16644 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16645 		    uph[6] + uph[7] + uph[8] + uph[9];
16646 #undef  uph
16647 		/* finish doing IP checksum */
16648 		sum = (sum & 0xFFFF) + (sum >> 16);
16649 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16650 		/*
16651 		 * Don't verify header checksum if this packet is coming
16652 		 * back from AH/ESP as we already did it.
16653 		 */
16654 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16655 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16656 			goto drop_pkt;
16657 		}
16658 	}
16659 
16660 	/*
16661 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16662 	 * might be called more than once for secure packets, count only
16663 	 * the first time.
16664 	 */
16665 	if (!mctl_present) {
16666 		UPDATE_IB_PKT_COUNT(ire);
16667 		ire->ire_last_used_time = lbolt;
16668 	}
16669 
16670 	/* Check for fragmentation offset. */
16671 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16672 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16673 	if (u1) {
16674 		/*
16675 		 * We re-assemble fragments before we do the AH/ESP
16676 		 * processing. Thus, M_CTL should not be present
16677 		 * while we are re-assembling.
16678 		 */
16679 		ASSERT(!mctl_present);
16680 		ASSERT(first_mp == mp);
16681 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16682 			return;
16683 		}
16684 		/*
16685 		 * Make sure that first_mp points back to mp as
16686 		 * the mp we came in with could have changed in
16687 		 * ip_rput_fragment().
16688 		 */
16689 		ipha = (ipha_t *)mp->b_rptr;
16690 		first_mp = mp;
16691 	}
16692 
16693 	/*
16694 	 * Clear hardware checksumming flag as it is currently only
16695 	 * used by TCP and UDP.
16696 	 */
16697 	DB_CKSUMFLAGS(mp) = 0;
16698 
16699 	/* Now we have a complete datagram, destined for this machine. */
16700 	u1 = IPH_HDR_LENGTH(ipha);
16701 	switch (ipha->ipha_protocol) {
16702 	case IPPROTO_ICMP: {
16703 		ire_t		*ire_zone;
16704 		ilm_t		*ilm;
16705 		mblk_t		*mp1;
16706 		zoneid_t	last_zoneid;
16707 
16708 		if (CLASSD(ipha->ipha_dst) &&
16709 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
16710 			ASSERT(ire->ire_type == IRE_BROADCAST);
16711 			/*
16712 			 * In the multicast case, applications may have joined
16713 			 * the group from different zones, so we need to deliver
16714 			 * the packet to each of them. Loop through the
16715 			 * multicast memberships structures (ilm) on the receive
16716 			 * ill and send a copy of the packet up each matching
16717 			 * one. However, we don't do this for multicasts sent on
16718 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16719 			 * they must stay in the sender's zone.
16720 			 *
16721 			 * ilm_add_v6() ensures that ilms in the same zone are
16722 			 * contiguous in the ill_ilm list. We use this property
16723 			 * to avoid sending duplicates needed when two
16724 			 * applications in the same zone join the same group on
16725 			 * different logical interfaces: we ignore the ilm if
16726 			 * its zoneid is the same as the last matching one.
16727 			 * In addition, the sending of the packet for
16728 			 * ire_zoneid is delayed until all of the other ilms
16729 			 * have been exhausted.
16730 			 */
16731 			last_zoneid = -1;
16732 			ILM_WALKER_HOLD(recv_ill);
16733 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
16734 			    ilm = ilm->ilm_next) {
16735 				if ((ilm->ilm_flags & ILM_DELETED) ||
16736 				    ipha->ipha_dst != ilm->ilm_addr ||
16737 				    ilm->ilm_zoneid == last_zoneid ||
16738 				    ilm->ilm_zoneid == ire->ire_zoneid ||
16739 				    ilm->ilm_zoneid == ALL_ZONES ||
16740 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
16741 					continue;
16742 				mp1 = ip_copymsg(first_mp);
16743 				if (mp1 == NULL)
16744 					continue;
16745 				icmp_inbound(q, mp1, B_TRUE, ill,
16746 				    0, sum, mctl_present, B_TRUE,
16747 				    recv_ill, ilm->ilm_zoneid);
16748 				last_zoneid = ilm->ilm_zoneid;
16749 			}
16750 			ILM_WALKER_RELE(recv_ill);
16751 		} else if (ire->ire_type == IRE_BROADCAST) {
16752 			/*
16753 			 * In the broadcast case, there may be many zones
16754 			 * which need a copy of the packet delivered to them.
16755 			 * There is one IRE_BROADCAST per broadcast address
16756 			 * and per zone; we walk those using a helper function.
16757 			 * In addition, the sending of the packet for ire is
16758 			 * delayed until all of the other ires have been
16759 			 * processed.
16760 			 */
16761 			IRB_REFHOLD(ire->ire_bucket);
16762 			ire_zone = NULL;
16763 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
16764 			    ire)) != NULL) {
16765 				mp1 = ip_copymsg(first_mp);
16766 				if (mp1 == NULL)
16767 					continue;
16768 
16769 				UPDATE_IB_PKT_COUNT(ire_zone);
16770 				ire_zone->ire_last_used_time = lbolt;
16771 				icmp_inbound(q, mp1, B_TRUE, ill,
16772 				    0, sum, mctl_present, B_TRUE,
16773 				    recv_ill, ire_zone->ire_zoneid);
16774 			}
16775 			IRB_REFRELE(ire->ire_bucket);
16776 		}
16777 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
16778 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
16779 		    ire->ire_zoneid);
16780 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16781 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
16782 		return;
16783 	}
16784 	case IPPROTO_IGMP:
16785 		/*
16786 		 * If we are not willing to accept IGMP packets in clear,
16787 		 * then check with global policy.
16788 		 */
16789 		if (igmp_accept_clear_messages == 0) {
16790 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16791 			    ipha, NULL, mctl_present);
16792 			if (first_mp == NULL)
16793 				return;
16794 		}
16795 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16796 			freemsg(first_mp);
16797 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
16798 			BUMP_MIB(&ip_mib, ipInDiscards);
16799 			return;
16800 		}
16801 		if (igmp_input(q, mp, ill)) {
16802 			/* Bad packet - discarded by igmp_input */
16803 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16804 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
16805 			if (mctl_present)
16806 				freeb(first_mp);
16807 			return;
16808 		}
16809 		/*
16810 		 * igmp_input() may have pulled up the message so ipha needs to
16811 		 * be reinitialized.
16812 		 */
16813 		ipha = (ipha_t *)mp->b_rptr;
16814 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16815 			/* No user-level listener for IGMP packets */
16816 			goto drop_pkt;
16817 		}
16818 		/* deliver to local raw users */
16819 		break;
16820 	case IPPROTO_PIM:
16821 		/*
16822 		 * If we are not willing to accept PIM packets in clear,
16823 		 * then check with global policy.
16824 		 */
16825 		if (pim_accept_clear_messages == 0) {
16826 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16827 			    ipha, NULL, mctl_present);
16828 			if (first_mp == NULL)
16829 				return;
16830 		}
16831 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16832 			freemsg(first_mp);
16833 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
16834 			BUMP_MIB(&ip_mib, ipInDiscards);
16835 			return;
16836 		}
16837 		if (pim_input(q, mp) != 0) {
16838 			/* Bad packet - discarded by pim_input */
16839 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16840 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
16841 			if (mctl_present)
16842 				freeb(first_mp);
16843 			return;
16844 		}
16845 
16846 		/*
16847 		 * pim_input() may have pulled up the message so ipha needs to
16848 		 * be reinitialized.
16849 		 */
16850 		ipha = (ipha_t *)mp->b_rptr;
16851 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16852 			/* No user-level listener for PIM packets */
16853 			goto drop_pkt;
16854 		}
16855 		/* deliver to local raw users */
16856 		break;
16857 	case IPPROTO_ENCAP:
16858 		/*
16859 		 * Handle self-encapsulated packets (IP-in-IP where
16860 		 * the inner addresses == the outer addresses).
16861 		 */
16862 		hdr_length = IPH_HDR_LENGTH(ipha);
16863 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
16864 		    mp->b_wptr) {
16865 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
16866 			    sizeof (ipha_t) - mp->b_rptr)) {
16867 				BUMP_MIB(&ip_mib, ipInDiscards);
16868 				freemsg(first_mp);
16869 				return;
16870 			}
16871 			ipha = (ipha_t *)mp->b_rptr;
16872 		}
16873 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
16874 		/*
16875 		 * Check the sanity of the inner IP header.
16876 		 */
16877 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
16878 			BUMP_MIB(&ip_mib, ipInDiscards);
16879 			freemsg(first_mp);
16880 			return;
16881 		}
16882 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
16883 			BUMP_MIB(&ip_mib, ipInDiscards);
16884 			freemsg(first_mp);
16885 			return;
16886 		}
16887 		if (inner_ipha->ipha_src == ipha->ipha_src &&
16888 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
16889 			ipsec_in_t *ii;
16890 
16891 			/*
16892 			 * Self-encapsulated tunnel packet. Remove
16893 			 * the outer IP header and fanout again.
16894 			 * We also need to make sure that the inner
16895 			 * header is pulled up until options.
16896 			 */
16897 			mp->b_rptr = (uchar_t *)inner_ipha;
16898 			ipha = inner_ipha;
16899 			hdr_length = IPH_HDR_LENGTH(ipha);
16900 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
16901 				if (!pullupmsg(mp, (uchar_t *)ipha +
16902 				    + hdr_length - mp->b_rptr)) {
16903 					freemsg(first_mp);
16904 					return;
16905 				}
16906 				ipha = (ipha_t *)mp->b_rptr;
16907 			}
16908 			if (!mctl_present) {
16909 				ASSERT(first_mp == mp);
16910 				/*
16911 				 * This means that somebody is sending
16912 				 * Self-encapsualted packets without AH/ESP.
16913 				 * If AH/ESP was present, we would have already
16914 				 * allocated the first_mp.
16915 				 */
16916 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
16917 				    NULL) {
16918 					ip1dbg(("ip_proto_input: IPSEC_IN "
16919 					    "allocation failure.\n"));
16920 					BUMP_MIB(&ip_mib, ipInDiscards);
16921 					freemsg(mp);
16922 					return;
16923 				}
16924 				first_mp->b_cont = mp;
16925 			}
16926 			/*
16927 			 * We generally store the ill_index if we need to
16928 			 * do IPSEC processing as we lose the ill queue when
16929 			 * we come back. But in this case, we never should
16930 			 * have to store the ill_index here as it should have
16931 			 * been stored previously when we processed the
16932 			 * AH/ESP header in this routine or for non-ipsec
16933 			 * cases, we still have the queue. But for some bad
16934 			 * packets from the wire, we can get to IPSEC after
16935 			 * this and we better store the index for that case.
16936 			 */
16937 			ill = (ill_t *)q->q_ptr;
16938 			ii = (ipsec_in_t *)first_mp->b_rptr;
16939 			ii->ipsec_in_ill_index =
16940 			    ill->ill_phyint->phyint_ifindex;
16941 			ii->ipsec_in_rill_index =
16942 			    recv_ill->ill_phyint->phyint_ifindex;
16943 			if (ii->ipsec_in_decaps) {
16944 				/*
16945 				 * This packet is self-encapsulated multiple
16946 				 * times. We don't want to recurse infinitely.
16947 				 * To keep it simple, drop the packet.
16948 				 */
16949 				BUMP_MIB(&ip_mib, ipInDiscards);
16950 				freemsg(first_mp);
16951 				return;
16952 			}
16953 			ii->ipsec_in_decaps = B_TRUE;
16954 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
16955 			return;
16956 		}
16957 		break;
16958 	case IPPROTO_AH:
16959 	case IPPROTO_ESP: {
16960 		/*
16961 		 * Fast path for AH/ESP. If this is the first time
16962 		 * we are sending a datagram to AH/ESP, allocate
16963 		 * a IPSEC_IN message and prepend it. Otherwise,
16964 		 * just fanout.
16965 		 */
16966 
16967 		int ipsec_rc;
16968 		ipsec_in_t *ii;
16969 
16970 		IP_STAT(ipsec_proto_ahesp);
16971 		if (!mctl_present) {
16972 			ASSERT(first_mp == mp);
16973 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
16974 				ip1dbg(("ip_proto_input: IPSEC_IN "
16975 				    "allocation failure.\n"));
16976 				freemsg(hada_mp); /* okay ifnull */
16977 				BUMP_MIB(&ip_mib, ipInDiscards);
16978 				freemsg(mp);
16979 				return;
16980 			}
16981 			/*
16982 			 * Store the ill_index so that when we come back
16983 			 * from IPSEC we ride on the same queue.
16984 			 */
16985 			ill = (ill_t *)q->q_ptr;
16986 			ii = (ipsec_in_t *)first_mp->b_rptr;
16987 			ii->ipsec_in_ill_index =
16988 			    ill->ill_phyint->phyint_ifindex;
16989 			ii->ipsec_in_rill_index =
16990 			    recv_ill->ill_phyint->phyint_ifindex;
16991 			first_mp->b_cont = mp;
16992 			/*
16993 			 * Cache hardware acceleration info.
16994 			 */
16995 			if (hada_mp != NULL) {
16996 				IPSECHW_DEBUG(IPSECHW_PKT,
16997 				    ("ip_rput_local: caching data attr.\n"));
16998 				ii->ipsec_in_accelerated = B_TRUE;
16999 				ii->ipsec_in_da = hada_mp;
17000 				hada_mp = NULL;
17001 			}
17002 		} else {
17003 			ii = (ipsec_in_t *)first_mp->b_rptr;
17004 		}
17005 
17006 		if (!ipsec_loaded()) {
17007 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17008 			    ire->ire_zoneid);
17009 			return;
17010 		}
17011 
17012 		/* select inbound SA and have IPsec process the pkt */
17013 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17014 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17015 			if (esph == NULL)
17016 				return;
17017 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17018 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17019 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17020 			    first_mp, esph);
17021 		} else {
17022 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17023 			if (ah == NULL)
17024 				return;
17025 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17026 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17027 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17028 			    first_mp, ah);
17029 		}
17030 
17031 		switch (ipsec_rc) {
17032 		case IPSEC_STATUS_SUCCESS:
17033 			break;
17034 		case IPSEC_STATUS_FAILED:
17035 			BUMP_MIB(&ip_mib, ipInDiscards);
17036 			/* FALLTHRU */
17037 		case IPSEC_STATUS_PENDING:
17038 			return;
17039 		}
17040 		/* we're done with IPsec processing, send it up */
17041 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17042 		return;
17043 	}
17044 	default:
17045 		break;
17046 	}
17047 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17048 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17049 		    ire->ire_zoneid));
17050 		goto drop_pkt;
17051 	}
17052 	/*
17053 	 * Handle protocols with which IP is less intimate.  There
17054 	 * can be more than one stream bound to a particular
17055 	 * protocol.  When this is the case, each one gets a copy
17056 	 * of any incoming packets.
17057 	 */
17058 	ip_fanout_proto(q, first_mp, ill, ipha,
17059 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17060 	    B_TRUE, recv_ill, ire->ire_zoneid);
17061 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17062 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17063 	return;
17064 
17065 drop_pkt:
17066 	freemsg(first_mp);
17067 	if (hada_mp != NULL)
17068 		freeb(hada_mp);
17069 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17070 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17071 #undef	rptr
17072 #undef  iphs
17073 
17074 }
17075 
17076 /*
17077  * Update any source route, record route or timestamp options.
17078  * Check that we are at end of strict source route.
17079  * The options have already been checked for sanity in ip_rput_options().
17080  */
17081 static boolean_t
17082 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17083 {
17084 	ipoptp_t	opts;
17085 	uchar_t		*opt;
17086 	uint8_t		optval;
17087 	uint8_t		optlen;
17088 	ipaddr_t	dst;
17089 	uint32_t	ts;
17090 	ire_t		*dst_ire;
17091 	timestruc_t	now;
17092 
17093 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17094 
17095 	ip2dbg(("ip_rput_local_options\n"));
17096 
17097 	for (optval = ipoptp_first(&opts, ipha);
17098 	    optval != IPOPT_EOL;
17099 	    optval = ipoptp_next(&opts)) {
17100 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17101 		opt = opts.ipoptp_cur;
17102 		optlen = opts.ipoptp_len;
17103 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17104 		    optval, optlen));
17105 		switch (optval) {
17106 			uint32_t off;
17107 		case IPOPT_SSRR:
17108 		case IPOPT_LSRR:
17109 			off = opt[IPOPT_OFFSET];
17110 			off--;
17111 			if (optlen < IP_ADDR_LEN ||
17112 			    off > optlen - IP_ADDR_LEN) {
17113 				/* End of source route */
17114 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17115 				break;
17116 			}
17117 			/*
17118 			 * This will only happen if two consecutive entries
17119 			 * in the source route contains our address or if
17120 			 * it is a packet with a loose source route which
17121 			 * reaches us before consuming the whole source route
17122 			 */
17123 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17124 			if (optval == IPOPT_SSRR) {
17125 				goto bad_src_route;
17126 			}
17127 			/*
17128 			 * Hack: instead of dropping the packet truncate the
17129 			 * source route to what has been used by filling the
17130 			 * rest with IPOPT_NOP.
17131 			 */
17132 			opt[IPOPT_OLEN] = (uint8_t)off;
17133 			while (off < optlen) {
17134 				opt[off++] = IPOPT_NOP;
17135 			}
17136 			break;
17137 		case IPOPT_RR:
17138 			off = opt[IPOPT_OFFSET];
17139 			off--;
17140 			if (optlen < IP_ADDR_LEN ||
17141 			    off > optlen - IP_ADDR_LEN) {
17142 				/* No more room - ignore */
17143 				ip1dbg((
17144 				    "ip_rput_local_options: end of RR\n"));
17145 				break;
17146 			}
17147 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17148 			    IP_ADDR_LEN);
17149 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17150 			break;
17151 		case IPOPT_TS:
17152 			/* Insert timestamp if there is romm */
17153 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17154 			case IPOPT_TS_TSONLY:
17155 				off = IPOPT_TS_TIMELEN;
17156 				break;
17157 			case IPOPT_TS_PRESPEC:
17158 			case IPOPT_TS_PRESPEC_RFC791:
17159 				/* Verify that the address matched */
17160 				off = opt[IPOPT_OFFSET] - 1;
17161 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17162 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17163 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17164 				if (dst_ire == NULL) {
17165 					/* Not for us */
17166 					break;
17167 				}
17168 				ire_refrele(dst_ire);
17169 				/* FALLTHRU */
17170 			case IPOPT_TS_TSANDADDR:
17171 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17172 				break;
17173 			default:
17174 				/*
17175 				 * ip_*put_options should have already
17176 				 * dropped this packet.
17177 				 */
17178 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17179 				    "unknown IT - bug in ip_rput_options?\n");
17180 				return (B_TRUE);	/* Keep "lint" happy */
17181 			}
17182 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17183 				/* Increase overflow counter */
17184 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17185 				opt[IPOPT_POS_OV_FLG] =
17186 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17187 				    (off << 4));
17188 				break;
17189 			}
17190 			off = opt[IPOPT_OFFSET] - 1;
17191 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17192 			case IPOPT_TS_PRESPEC:
17193 			case IPOPT_TS_PRESPEC_RFC791:
17194 			case IPOPT_TS_TSANDADDR:
17195 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17196 				    IP_ADDR_LEN);
17197 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17198 				/* FALLTHRU */
17199 			case IPOPT_TS_TSONLY:
17200 				off = opt[IPOPT_OFFSET] - 1;
17201 				/* Compute # of milliseconds since midnight */
17202 				gethrestime(&now);
17203 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17204 				    now.tv_nsec / (NANOSEC / MILLISEC);
17205 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17206 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17207 				break;
17208 			}
17209 			break;
17210 		}
17211 	}
17212 	return (B_TRUE);
17213 
17214 bad_src_route:
17215 	q = WR(q);
17216 	/* make sure we clear any indication of a hardware checksum */
17217 	DB_CKSUMFLAGS(mp) = 0;
17218 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
17219 	return (B_FALSE);
17220 
17221 }
17222 
17223 /*
17224  * Process IP options in an inbound packet.  If an option affects the
17225  * effective destination address, return the next hop address via dstp.
17226  * Returns -1 if something fails in which case an ICMP error has been sent
17227  * and mp freed.
17228  */
17229 static int
17230 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17231 {
17232 	ipoptp_t	opts;
17233 	uchar_t		*opt;
17234 	uint8_t		optval;
17235 	uint8_t		optlen;
17236 	ipaddr_t	dst;
17237 	intptr_t	code = 0;
17238 	ire_t		*ire = NULL;
17239 
17240 	ip2dbg(("ip_rput_options\n"));
17241 	dst = ipha->ipha_dst;
17242 	for (optval = ipoptp_first(&opts, ipha);
17243 	    optval != IPOPT_EOL;
17244 	    optval = ipoptp_next(&opts)) {
17245 		opt = opts.ipoptp_cur;
17246 		optlen = opts.ipoptp_len;
17247 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17248 		    optval, optlen));
17249 		/*
17250 		 * Note: we need to verify the checksum before we
17251 		 * modify anything thus this routine only extracts the next
17252 		 * hop dst from any source route.
17253 		 */
17254 		switch (optval) {
17255 			uint32_t off;
17256 		case IPOPT_SSRR:
17257 		case IPOPT_LSRR:
17258 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17259 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17260 			if (ire == NULL) {
17261 				if (optval == IPOPT_SSRR) {
17262 					ip1dbg(("ip_rput_options: not next"
17263 					    " strict source route 0x%x\n",
17264 					    ntohl(dst)));
17265 					code = (char *)&ipha->ipha_dst -
17266 					    (char *)ipha;
17267 					goto param_prob; /* RouterReq's */
17268 				}
17269 				ip2dbg(("ip_rput_options: "
17270 				    "not next source route 0x%x\n",
17271 				    ntohl(dst)));
17272 				break;
17273 			}
17274 			ire_refrele(ire);
17275 
17276 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17277 				ip1dbg((
17278 				    "ip_rput_options: bad option offset\n"));
17279 				code = (char *)&opt[IPOPT_OLEN] -
17280 				    (char *)ipha;
17281 				goto param_prob;
17282 			}
17283 			off = opt[IPOPT_OFFSET];
17284 			off--;
17285 		redo_srr:
17286 			if (optlen < IP_ADDR_LEN ||
17287 			    off > optlen - IP_ADDR_LEN) {
17288 				/* End of source route */
17289 				ip1dbg(("ip_rput_options: end of SR\n"));
17290 				break;
17291 			}
17292 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17293 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17294 			    ntohl(dst)));
17295 
17296 			/*
17297 			 * Check if our address is present more than
17298 			 * once as consecutive hops in source route.
17299 			 * XXX verify per-interface ip_forwarding
17300 			 * for source route?
17301 			 */
17302 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17303 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17304 
17305 			if (ire != NULL) {
17306 				ire_refrele(ire);
17307 				off += IP_ADDR_LEN;
17308 				goto redo_srr;
17309 			}
17310 
17311 			if (dst == htonl(INADDR_LOOPBACK)) {
17312 				ip1dbg(("ip_rput_options: loopback addr in "
17313 				    "source route!\n"));
17314 				goto bad_src_route;
17315 			}
17316 			/*
17317 			 * For strict: verify that dst is directly
17318 			 * reachable.
17319 			 */
17320 			if (optval == IPOPT_SSRR) {
17321 				ire = ire_ftable_lookup(dst, 0, 0,
17322 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17323 				    MBLK_GETLABEL(mp),
17324 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17325 				if (ire == NULL) {
17326 					ip1dbg(("ip_rput_options: SSRR not "
17327 					    "directly reachable: 0x%x\n",
17328 					    ntohl(dst)));
17329 					goto bad_src_route;
17330 				}
17331 				ire_refrele(ire);
17332 			}
17333 			/*
17334 			 * Defer update of the offset and the record route
17335 			 * until the packet is forwarded.
17336 			 */
17337 			break;
17338 		case IPOPT_RR:
17339 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17340 				ip1dbg((
17341 				    "ip_rput_options: bad option offset\n"));
17342 				code = (char *)&opt[IPOPT_OLEN] -
17343 				    (char *)ipha;
17344 				goto param_prob;
17345 			}
17346 			break;
17347 		case IPOPT_TS:
17348 			/*
17349 			 * Verify that length >= 5 and that there is either
17350 			 * room for another timestamp or that the overflow
17351 			 * counter is not maxed out.
17352 			 */
17353 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17354 			if (optlen < IPOPT_MINLEN_IT) {
17355 				goto param_prob;
17356 			}
17357 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17358 				ip1dbg((
17359 				    "ip_rput_options: bad option offset\n"));
17360 				code = (char *)&opt[IPOPT_OFFSET] -
17361 				    (char *)ipha;
17362 				goto param_prob;
17363 			}
17364 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17365 			case IPOPT_TS_TSONLY:
17366 				off = IPOPT_TS_TIMELEN;
17367 				break;
17368 			case IPOPT_TS_TSANDADDR:
17369 			case IPOPT_TS_PRESPEC:
17370 			case IPOPT_TS_PRESPEC_RFC791:
17371 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17372 				break;
17373 			default:
17374 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17375 				    (char *)ipha;
17376 				goto param_prob;
17377 			}
17378 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17379 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17380 				/*
17381 				 * No room and the overflow counter is 15
17382 				 * already.
17383 				 */
17384 				goto param_prob;
17385 			}
17386 			break;
17387 		}
17388 	}
17389 
17390 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17391 		*dstp = dst;
17392 		return (0);
17393 	}
17394 
17395 	ip1dbg(("ip_rput_options: error processing IP options."));
17396 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17397 
17398 param_prob:
17399 	q = WR(q);
17400 	/* make sure we clear any indication of a hardware checksum */
17401 	DB_CKSUMFLAGS(mp) = 0;
17402 	icmp_param_problem(q, mp, (uint8_t)code);
17403 	return (-1);
17404 
17405 bad_src_route:
17406 	q = WR(q);
17407 	/* make sure we clear any indication of a hardware checksum */
17408 	DB_CKSUMFLAGS(mp) = 0;
17409 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
17410 	return (-1);
17411 }
17412 
17413 /*
17414  * IP & ICMP info in >=14 msg's ...
17415  *  - ip fixed part (mib2_ip_t)
17416  *  - icmp fixed part (mib2_icmp_t)
17417  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17418  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17419  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
17420  *  - ipRouteAttributeTable (ip 102)	labeled routes
17421  *  - ip multicast membership (ip_member_t)
17422  *  - ip multicast source filtering (ip_grpsrc_t)
17423  *  - igmp fixed part (struct igmpstat)
17424  *  - multicast routing stats (struct mrtstat)
17425  *  - multicast routing vifs (array of struct vifctl)
17426  *  - multicast routing routes (array of struct mfcctl)
17427  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17428  *					One per ill plus one generic
17429  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17430  *					One per ill plus one generic
17431  *  - ipv6RouteEntry			all IPv6 IREs
17432  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17433  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17434  *  - ipv6AddrEntry			all IPv6 ipifs
17435  *  - ipv6 multicast membership (ipv6_member_t)
17436  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17437  *
17438  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
17439  * already present.
17440  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17441  * already filled in by the caller.
17442  * Return value of 0 indicates that no messages were sent and caller
17443  * should free mpctl.
17444  */
17445 int
17446 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17447 {
17448 
17449 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17450 		return (0);
17451 	}
17452 
17453 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
17454 		return (1);
17455 	}
17456 
17457 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17458 		return (1);
17459 	}
17460 
17461 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17462 		return (1);
17463 	}
17464 
17465 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17466 		return (1);
17467 	}
17468 
17469 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17470 		return (1);
17471 	}
17472 
17473 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17474 		return (1);
17475 	}
17476 
17477 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17478 		return (1);
17479 	}
17480 
17481 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17482 		return (1);
17483 	}
17484 
17485 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17486 		return (1);
17487 	}
17488 
17489 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17490 		return (1);
17491 	}
17492 
17493 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17494 		return (1);
17495 	}
17496 
17497 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17498 		return (1);
17499 	}
17500 
17501 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17502 		return (1);
17503 	}
17504 
17505 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17506 		return (1);
17507 	}
17508 
17509 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17510 		return (1);
17511 	}
17512 
17513 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17514 		return (1);
17515 	}
17516 
17517 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17518 		return (1);
17519 	}
17520 	freemsg(mpctl);
17521 	return (1);
17522 }
17523 
17524 
17525 /* Get global IPv4 statistics */
17526 static mblk_t *
17527 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
17528 {
17529 	struct opthdr		*optp;
17530 	mblk_t			*mp2ctl;
17531 
17532 	/*
17533 	 * make a copy of the original message
17534 	 */
17535 	mp2ctl = copymsg(mpctl);
17536 
17537 	/* fixed length IP structure... */
17538 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17539 	optp->level = MIB2_IP;
17540 	optp->name = 0;
17541 	SET_MIB(ip_mib.ipForwarding,
17542 	    (WE_ARE_FORWARDING ? 1 : 2));
17543 	SET_MIB(ip_mib.ipDefaultTTL,
17544 	    (uint32_t)ip_def_ttl);
17545 	SET_MIB(ip_mib.ipReasmTimeout,
17546 	    ip_g_frag_timeout);
17547 	SET_MIB(ip_mib.ipAddrEntrySize,
17548 	    sizeof (mib2_ipAddrEntry_t));
17549 	SET_MIB(ip_mib.ipRouteEntrySize,
17550 	    sizeof (mib2_ipRouteEntry_t));
17551 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
17552 	    sizeof (mib2_ipNetToMediaEntry_t));
17553 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17554 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17555 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
17556 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17557 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
17558 	    (int)sizeof (ip_mib))) {
17559 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17560 		    (uint_t)sizeof (ip_mib)));
17561 	}
17562 
17563 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17564 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17565 	    (int)optp->level, (int)optp->name, (int)optp->len));
17566 	qreply(q, mpctl);
17567 	return (mp2ctl);
17568 }
17569 
17570 /* Global IPv4 ICMP statistics */
17571 static mblk_t *
17572 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
17573 {
17574 	struct opthdr		*optp;
17575 	mblk_t			*mp2ctl;
17576 
17577 	/*
17578 	 * Make a copy of the original message
17579 	 */
17580 	mp2ctl = copymsg(mpctl);
17581 
17582 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17583 	optp->level = MIB2_ICMP;
17584 	optp->name = 0;
17585 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17586 	    (int)sizeof (icmp_mib))) {
17587 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17588 		    (uint_t)sizeof (icmp_mib)));
17589 	}
17590 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17591 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17592 	    (int)optp->level, (int)optp->name, (int)optp->len));
17593 	qreply(q, mpctl);
17594 	return (mp2ctl);
17595 }
17596 
17597 /* Global IPv4 IGMP statistics */
17598 static mblk_t *
17599 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17600 {
17601 	struct opthdr		*optp;
17602 	mblk_t			*mp2ctl;
17603 
17604 	/*
17605 	 * make a copy of the original message
17606 	 */
17607 	mp2ctl = copymsg(mpctl);
17608 
17609 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17610 	optp->level = EXPER_IGMP;
17611 	optp->name = 0;
17612 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17613 	    (int)sizeof (igmpstat))) {
17614 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17615 		    (uint_t)sizeof (igmpstat)));
17616 	}
17617 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17618 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17619 	    (int)optp->level, (int)optp->name, (int)optp->len));
17620 	qreply(q, mpctl);
17621 	return (mp2ctl);
17622 }
17623 
17624 /* Global IPv4 Multicast Routing statistics */
17625 static mblk_t *
17626 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17627 {
17628 	struct opthdr		*optp;
17629 	mblk_t			*mp2ctl;
17630 
17631 	/*
17632 	 * make a copy of the original message
17633 	 */
17634 	mp2ctl = copymsg(mpctl);
17635 
17636 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17637 	optp->level = EXPER_DVMRP;
17638 	optp->name = 0;
17639 	if (!ip_mroute_stats(mpctl->b_cont)) {
17640 		ip0dbg(("ip_mroute_stats: failed\n"));
17641 	}
17642 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17643 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17644 	    (int)optp->level, (int)optp->name, (int)optp->len));
17645 	qreply(q, mpctl);
17646 	return (mp2ctl);
17647 }
17648 
17649 /* IPv4 address information */
17650 static mblk_t *
17651 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17652 {
17653 	struct opthdr		*optp;
17654 	mblk_t			*mp2ctl;
17655 	mblk_t			*mp_tail = NULL;
17656 	ill_t			*ill;
17657 	ipif_t			*ipif;
17658 	uint_t			bitval;
17659 	mib2_ipAddrEntry_t	mae;
17660 	zoneid_t		zoneid;
17661 	ill_walk_context_t ctx;
17662 
17663 	/*
17664 	 * make a copy of the original message
17665 	 */
17666 	mp2ctl = copymsg(mpctl);
17667 
17668 	/* ipAddrEntryTable */
17669 
17670 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17671 	optp->level = MIB2_IP;
17672 	optp->name = MIB2_IP_ADDR;
17673 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17674 
17675 	rw_enter(&ill_g_lock, RW_READER);
17676 	ill = ILL_START_WALK_V4(&ctx);
17677 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17678 		for (ipif = ill->ill_ipif; ipif != NULL;
17679 		    ipif = ipif->ipif_next) {
17680 			if (ipif->ipif_zoneid != zoneid &&
17681 			    ipif->ipif_zoneid != ALL_ZONES)
17682 				continue;
17683 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17684 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17685 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17686 
17687 			(void) ipif_get_name(ipif,
17688 			    mae.ipAdEntIfIndex.o_bytes,
17689 			    OCTET_LENGTH);
17690 			mae.ipAdEntIfIndex.o_length =
17691 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
17692 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
17693 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
17694 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
17695 			mae.ipAdEntInfo.ae_subnet_len =
17696 			    ip_mask_to_plen(ipif->ipif_net_mask);
17697 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
17698 			for (bitval = 1;
17699 			    bitval &&
17700 			    !(bitval & ipif->ipif_brd_addr);
17701 			    bitval <<= 1)
17702 				noop;
17703 			mae.ipAdEntBcastAddr = bitval;
17704 			mae.ipAdEntReasmMaxSize = 65535;
17705 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
17706 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
17707 			mae.ipAdEntInfo.ae_broadcast_addr =
17708 			    ipif->ipif_brd_addr;
17709 			mae.ipAdEntInfo.ae_pp_dst_addr =
17710 			    ipif->ipif_pp_dst_addr;
17711 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
17712 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17713 
17714 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17715 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
17716 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
17717 				    "allocate %u bytes\n",
17718 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
17719 			}
17720 		}
17721 	}
17722 	rw_exit(&ill_g_lock);
17723 
17724 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17725 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
17726 	    (int)optp->level, (int)optp->name, (int)optp->len));
17727 	qreply(q, mpctl);
17728 	return (mp2ctl);
17729 }
17730 
17731 /* IPv6 address information */
17732 static mblk_t *
17733 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
17734 {
17735 	struct opthdr		*optp;
17736 	mblk_t			*mp2ctl;
17737 	mblk_t			*mp_tail = NULL;
17738 	ill_t			*ill;
17739 	ipif_t			*ipif;
17740 	mib2_ipv6AddrEntry_t	mae6;
17741 	zoneid_t		zoneid;
17742 	ill_walk_context_t	ctx;
17743 
17744 	/*
17745 	 * make a copy of the original message
17746 	 */
17747 	mp2ctl = copymsg(mpctl);
17748 
17749 	/* ipv6AddrEntryTable */
17750 
17751 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17752 	optp->level = MIB2_IP6;
17753 	optp->name = MIB2_IP6_ADDR;
17754 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17755 
17756 	rw_enter(&ill_g_lock, RW_READER);
17757 	ill = ILL_START_WALK_V6(&ctx);
17758 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17759 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
17760 			if (ipif->ipif_zoneid != zoneid &&
17761 			    ipif->ipif_zoneid != ALL_ZONES)
17762 				continue;
17763 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17764 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17765 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17766 
17767 			(void) ipif_get_name(ipif,
17768 			    mae6.ipv6AddrIfIndex.o_bytes,
17769 			    OCTET_LENGTH);
17770 			mae6.ipv6AddrIfIndex.o_length =
17771 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
17772 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
17773 			mae6.ipv6AddrPfxLength =
17774 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
17775 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
17776 			mae6.ipv6AddrInfo.ae_subnet_len =
17777 			    mae6.ipv6AddrPfxLength;
17778 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
17779 
17780 			/* Type: stateless(1), stateful(2), unknown(3) */
17781 			if (ipif->ipif_flags & IPIF_ADDRCONF)
17782 				mae6.ipv6AddrType = 1;
17783 			else
17784 				mae6.ipv6AddrType = 2;
17785 			/* Anycast: true(1), false(2) */
17786 			if (ipif->ipif_flags & IPIF_ANYCAST)
17787 				mae6.ipv6AddrAnycastFlag = 1;
17788 			else
17789 				mae6.ipv6AddrAnycastFlag = 2;
17790 
17791 			/*
17792 			 * Address status: preferred(1), deprecated(2),
17793 			 * invalid(3), inaccessible(4), unknown(5)
17794 			 */
17795 			if (ipif->ipif_flags & IPIF_NOLOCAL)
17796 				mae6.ipv6AddrStatus = 3;
17797 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
17798 				mae6.ipv6AddrStatus = 2;
17799 			else
17800 				mae6.ipv6AddrStatus = 1;
17801 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
17802 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
17803 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
17804 						ipif->ipif_v6pp_dst_addr;
17805 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
17806 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17807 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17808 				(char *)&mae6,
17809 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
17810 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
17811 				    "allocate %u bytes\n",
17812 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
17813 			}
17814 		}
17815 	}
17816 	rw_exit(&ill_g_lock);
17817 
17818 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17819 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
17820 	    (int)optp->level, (int)optp->name, (int)optp->len));
17821 	qreply(q, mpctl);
17822 	return (mp2ctl);
17823 }
17824 
17825 /* IPv4 multicast group membership. */
17826 static mblk_t *
17827 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
17828 {
17829 	struct opthdr		*optp;
17830 	mblk_t			*mp2ctl;
17831 	ill_t			*ill;
17832 	ipif_t			*ipif;
17833 	ilm_t			*ilm;
17834 	ip_member_t		ipm;
17835 	mblk_t			*mp_tail = NULL;
17836 	ill_walk_context_t	ctx;
17837 	zoneid_t		zoneid;
17838 
17839 	/*
17840 	 * make a copy of the original message
17841 	 */
17842 	mp2ctl = copymsg(mpctl);
17843 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17844 
17845 	/* ipGroupMember table */
17846 	optp = (struct opthdr *)&mpctl->b_rptr[
17847 	    sizeof (struct T_optmgmt_ack)];
17848 	optp->level = MIB2_IP;
17849 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
17850 
17851 	rw_enter(&ill_g_lock, RW_READER);
17852 	ill = ILL_START_WALK_V4(&ctx);
17853 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17854 		ILM_WALKER_HOLD(ill);
17855 		for (ipif = ill->ill_ipif; ipif != NULL;
17856 		    ipif = ipif->ipif_next) {
17857 			if (ipif->ipif_zoneid != zoneid &&
17858 			    ipif->ipif_zoneid != ALL_ZONES)
17859 				continue;	/* not this zone */
17860 			(void) ipif_get_name(ipif,
17861 			    ipm.ipGroupMemberIfIndex.o_bytes,
17862 			    OCTET_LENGTH);
17863 			ipm.ipGroupMemberIfIndex.o_length =
17864 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
17865 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17866 				ASSERT(ilm->ilm_ipif != NULL);
17867 				ASSERT(ilm->ilm_ill == NULL);
17868 				if (ilm->ilm_ipif != ipif)
17869 					continue;
17870 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
17871 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
17872 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
17873 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17874 				    (char *)&ipm, (int)sizeof (ipm))) {
17875 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
17876 					    "failed to allocate %u bytes\n",
17877 						(uint_t)sizeof (ipm)));
17878 				}
17879 			}
17880 		}
17881 		ILM_WALKER_RELE(ill);
17882 	}
17883 	rw_exit(&ill_g_lock);
17884 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17885 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17886 	    (int)optp->level, (int)optp->name, (int)optp->len));
17887 	qreply(q, mpctl);
17888 	return (mp2ctl);
17889 }
17890 
17891 /* IPv6 multicast group membership. */
17892 static mblk_t *
17893 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
17894 {
17895 	struct opthdr		*optp;
17896 	mblk_t			*mp2ctl;
17897 	ill_t			*ill;
17898 	ilm_t			*ilm;
17899 	ipv6_member_t		ipm6;
17900 	mblk_t			*mp_tail = NULL;
17901 	ill_walk_context_t	ctx;
17902 	zoneid_t		zoneid;
17903 
17904 	/*
17905 	 * make a copy of the original message
17906 	 */
17907 	mp2ctl = copymsg(mpctl);
17908 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17909 
17910 	/* ip6GroupMember table */
17911 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17912 	optp->level = MIB2_IP6;
17913 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
17914 
17915 	rw_enter(&ill_g_lock, RW_READER);
17916 	ill = ILL_START_WALK_V6(&ctx);
17917 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17918 		ILM_WALKER_HOLD(ill);
17919 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
17920 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17921 			ASSERT(ilm->ilm_ipif == NULL);
17922 			ASSERT(ilm->ilm_ill != NULL);
17923 			if (ilm->ilm_zoneid != zoneid)
17924 				continue;	/* not this zone */
17925 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
17926 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
17927 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
17928 			if (!snmp_append_data2(mpctl->b_cont,
17929 			    &mp_tail,
17930 			    (char *)&ipm6, (int)sizeof (ipm6))) {
17931 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
17932 				    "failed to allocate %u bytes\n",
17933 				    (uint_t)sizeof (ipm6)));
17934 			}
17935 		}
17936 		ILM_WALKER_RELE(ill);
17937 	}
17938 	rw_exit(&ill_g_lock);
17939 
17940 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17941 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17942 	    (int)optp->level, (int)optp->name, (int)optp->len));
17943 	qreply(q, mpctl);
17944 	return (mp2ctl);
17945 }
17946 
17947 /* IP multicast filtered sources */
17948 static mblk_t *
17949 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
17950 {
17951 	struct opthdr		*optp;
17952 	mblk_t			*mp2ctl;
17953 	ill_t			*ill;
17954 	ipif_t			*ipif;
17955 	ilm_t			*ilm;
17956 	ip_grpsrc_t		ips;
17957 	mblk_t			*mp_tail = NULL;
17958 	ill_walk_context_t	ctx;
17959 	zoneid_t		zoneid;
17960 	int			i;
17961 	slist_t			*sl;
17962 
17963 	/*
17964 	 * make a copy of the original message
17965 	 */
17966 	mp2ctl = copymsg(mpctl);
17967 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17968 
17969 	/* ipGroupSource table */
17970 	optp = (struct opthdr *)&mpctl->b_rptr[
17971 	    sizeof (struct T_optmgmt_ack)];
17972 	optp->level = MIB2_IP;
17973 	optp->name = EXPER_IP_GROUP_SOURCES;
17974 
17975 	rw_enter(&ill_g_lock, RW_READER);
17976 	ill = ILL_START_WALK_V4(&ctx);
17977 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17978 		ILM_WALKER_HOLD(ill);
17979 		for (ipif = ill->ill_ipif; ipif != NULL;
17980 		    ipif = ipif->ipif_next) {
17981 			if (ipif->ipif_zoneid != zoneid)
17982 				continue;	/* not this zone */
17983 			(void) ipif_get_name(ipif,
17984 			    ips.ipGroupSourceIfIndex.o_bytes,
17985 			    OCTET_LENGTH);
17986 			ips.ipGroupSourceIfIndex.o_length =
17987 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
17988 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17989 				ASSERT(ilm->ilm_ipif != NULL);
17990 				ASSERT(ilm->ilm_ill == NULL);
17991 				sl = ilm->ilm_filter;
17992 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
17993 					continue;
17994 				ips.ipGroupSourceGroup = ilm->ilm_addr;
17995 				for (i = 0; i < sl->sl_numsrc; i++) {
17996 					if (!IN6_IS_ADDR_V4MAPPED(
17997 					    &sl->sl_addr[i]))
17998 						continue;
17999 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18000 					    ips.ipGroupSourceAddress);
18001 					if (snmp_append_data2(mpctl->b_cont,
18002 					    &mp_tail, (char *)&ips,
18003 					    (int)sizeof (ips)) == 0) {
18004 						ip1dbg(("ip_snmp_get_mib2_"
18005 						    "ip_group_src: failed to "
18006 						    "allocate %u bytes\n",
18007 						    (uint_t)sizeof (ips)));
18008 					}
18009 				}
18010 			}
18011 		}
18012 		ILM_WALKER_RELE(ill);
18013 	}
18014 	rw_exit(&ill_g_lock);
18015 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18016 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18017 	    (int)optp->level, (int)optp->name, (int)optp->len));
18018 	qreply(q, mpctl);
18019 	return (mp2ctl);
18020 }
18021 
18022 /* IPv6 multicast filtered sources. */
18023 static mblk_t *
18024 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18025 {
18026 	struct opthdr		*optp;
18027 	mblk_t			*mp2ctl;
18028 	ill_t			*ill;
18029 	ilm_t			*ilm;
18030 	ipv6_grpsrc_t		ips6;
18031 	mblk_t			*mp_tail = NULL;
18032 	ill_walk_context_t	ctx;
18033 	zoneid_t		zoneid;
18034 	int			i;
18035 	slist_t			*sl;
18036 
18037 	/*
18038 	 * make a copy of the original message
18039 	 */
18040 	mp2ctl = copymsg(mpctl);
18041 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18042 
18043 	/* ip6GroupMember table */
18044 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18045 	optp->level = MIB2_IP6;
18046 	optp->name = EXPER_IP6_GROUP_SOURCES;
18047 
18048 	rw_enter(&ill_g_lock, RW_READER);
18049 	ill = ILL_START_WALK_V6(&ctx);
18050 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18051 		ILM_WALKER_HOLD(ill);
18052 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18053 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18054 			ASSERT(ilm->ilm_ipif == NULL);
18055 			ASSERT(ilm->ilm_ill != NULL);
18056 			sl = ilm->ilm_filter;
18057 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18058 				continue;
18059 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18060 			for (i = 0; i < sl->sl_numsrc; i++) {
18061 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18062 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18063 				    (char *)&ips6, (int)sizeof (ips6))) {
18064 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18065 					    "group_src: failed to allocate "
18066 					    "%u bytes\n",
18067 					    (uint_t)sizeof (ips6)));
18068 				}
18069 			}
18070 		}
18071 		ILM_WALKER_RELE(ill);
18072 	}
18073 	rw_exit(&ill_g_lock);
18074 
18075 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18076 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18077 	    (int)optp->level, (int)optp->name, (int)optp->len));
18078 	qreply(q, mpctl);
18079 	return (mp2ctl);
18080 }
18081 
18082 /* Multicast routing virtual interface table. */
18083 static mblk_t *
18084 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18085 {
18086 	struct opthdr		*optp;
18087 	mblk_t			*mp2ctl;
18088 
18089 	/*
18090 	 * make a copy of the original message
18091 	 */
18092 	mp2ctl = copymsg(mpctl);
18093 
18094 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18095 	optp->level = EXPER_DVMRP;
18096 	optp->name = EXPER_DVMRP_VIF;
18097 	if (!ip_mroute_vif(mpctl->b_cont)) {
18098 		ip0dbg(("ip_mroute_vif: failed\n"));
18099 	}
18100 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18101 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18102 	    (int)optp->level, (int)optp->name, (int)optp->len));
18103 	qreply(q, mpctl);
18104 	return (mp2ctl);
18105 }
18106 
18107 /* Multicast routing table. */
18108 static mblk_t *
18109 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18110 {
18111 	struct opthdr		*optp;
18112 	mblk_t			*mp2ctl;
18113 
18114 	/*
18115 	 * make a copy of the original message
18116 	 */
18117 	mp2ctl = copymsg(mpctl);
18118 
18119 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18120 	optp->level = EXPER_DVMRP;
18121 	optp->name = EXPER_DVMRP_MRT;
18122 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18123 		ip0dbg(("ip_mroute_mrt: failed\n"));
18124 	}
18125 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18126 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18127 	    (int)optp->level, (int)optp->name, (int)optp->len));
18128 	qreply(q, mpctl);
18129 	return (mp2ctl);
18130 }
18131 
18132 /*
18133  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18134  * in one IRE walk.
18135  */
18136 static mblk_t *
18137 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18138 {
18139 	struct opthdr	*optp;
18140 	mblk_t		*mp2ctl;	/* Returned */
18141 	mblk_t		*mp3ctl;	/* nettomedia */
18142 	mblk_t		*mp4ctl;	/* routeattrs */
18143 	iproutedata_t	ird;
18144 	zoneid_t	zoneid;
18145 
18146 	/*
18147 	 * make copies of the original message
18148 	 *	- mp2ctl is returned unchanged to the caller for his use
18149 	 *	- mpctl is sent upstream as ipRouteEntryTable
18150 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18151 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18152 	 */
18153 	mp2ctl = copymsg(mpctl);
18154 	mp3ctl = copymsg(mpctl);
18155 	mp4ctl = copymsg(mpctl);
18156 	if (mp3ctl == NULL || mp4ctl == NULL) {
18157 		freemsg(mp4ctl);
18158 		freemsg(mp3ctl);
18159 		freemsg(mp2ctl);
18160 		freemsg(mpctl);
18161 		return (NULL);
18162 	}
18163 
18164 	bzero(&ird, sizeof (ird));
18165 
18166 	ird.ird_route.lp_head = mpctl->b_cont;
18167 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18168 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18169 
18170 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18171 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18172 	if (zoneid == GLOBAL_ZONEID) {
18173 		/*
18174 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18175 		 * the sys_net_config privilege, it can only run in the global
18176 		 * zone, so we don't display these IREs in the other zones.
18177 		 */
18178 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18179 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18180 	}
18181 
18182 	/* ipRouteEntryTable in mpctl */
18183 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18184 	optp->level = MIB2_IP;
18185 	optp->name = MIB2_IP_ROUTE;
18186 	optp->len = msgdsize(ird.ird_route.lp_head);
18187 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18188 	    (int)optp->level, (int)optp->name, (int)optp->len));
18189 	qreply(q, mpctl);
18190 
18191 	/* ipNetToMediaEntryTable in mp3ctl */
18192 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18193 	optp->level = MIB2_IP;
18194 	optp->name = MIB2_IP_MEDIA;
18195 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18196 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18197 	    (int)optp->level, (int)optp->name, (int)optp->len));
18198 	qreply(q, mp3ctl);
18199 
18200 	/* ipRouteAttributeTable in mp4ctl */
18201 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18202 	optp->level = MIB2_IP;
18203 	optp->name = EXPER_IP_RTATTR;
18204 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18205 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18206 	    (int)optp->level, (int)optp->name, (int)optp->len));
18207 	if (optp->len == 0)
18208 		freemsg(mp4ctl);
18209 	else
18210 		qreply(q, mp4ctl);
18211 
18212 	return (mp2ctl);
18213 }
18214 
18215 /*
18216  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18217  * ipv6NetToMediaEntryTable in an NDP walk.
18218  */
18219 static mblk_t *
18220 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18221 {
18222 	struct opthdr	*optp;
18223 	mblk_t		*mp2ctl;	/* Returned */
18224 	mblk_t		*mp3ctl;	/* nettomedia */
18225 	mblk_t		*mp4ctl;	/* routeattrs */
18226 	iproutedata_t	ird;
18227 	zoneid_t	zoneid;
18228 
18229 	/*
18230 	 * make copies of the original message
18231 	 *	- mp2ctl is returned unchanged to the caller for his use
18232 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18233 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18234 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18235 	 */
18236 	mp2ctl = copymsg(mpctl);
18237 	mp3ctl = copymsg(mpctl);
18238 	mp4ctl = copymsg(mpctl);
18239 	if (mp3ctl == NULL || mp4ctl == NULL) {
18240 		freemsg(mp4ctl);
18241 		freemsg(mp3ctl);
18242 		freemsg(mp2ctl);
18243 		freemsg(mpctl);
18244 		return (NULL);
18245 	}
18246 
18247 	bzero(&ird, sizeof (ird));
18248 
18249 	ird.ird_route.lp_head = mpctl->b_cont;
18250 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18251 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18252 
18253 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18254 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18255 
18256 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18257 	optp->level = MIB2_IP6;
18258 	optp->name = MIB2_IP6_ROUTE;
18259 	optp->len = msgdsize(ird.ird_route.lp_head);
18260 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18261 	    (int)optp->level, (int)optp->name, (int)optp->len));
18262 	qreply(q, mpctl);
18263 
18264 	/* ipv6NetToMediaEntryTable in mp3ctl */
18265 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18266 
18267 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18268 	optp->level = MIB2_IP6;
18269 	optp->name = MIB2_IP6_MEDIA;
18270 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18271 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18272 	    (int)optp->level, (int)optp->name, (int)optp->len));
18273 	qreply(q, mp3ctl);
18274 
18275 	/* ipv6RouteAttributeTable in mp4ctl */
18276 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18277 	optp->level = MIB2_IP6;
18278 	optp->name = EXPER_IP_RTATTR;
18279 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18280 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18281 	    (int)optp->level, (int)optp->name, (int)optp->len));
18282 	if (optp->len == 0)
18283 		freemsg(mp4ctl);
18284 	else
18285 		qreply(q, mp4ctl);
18286 
18287 	return (mp2ctl);
18288 }
18289 
18290 /*
18291  * ICMPv6 mib: One per ill
18292  */
18293 static mblk_t *
18294 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18295 {
18296 	struct opthdr		*optp;
18297 	mblk_t			*mp2ctl;
18298 	ill_t			*ill;
18299 	ill_walk_context_t	ctx;
18300 	mblk_t			*mp_tail = NULL;
18301 
18302 	/*
18303 	 * Make a copy of the original message
18304 	 */
18305 	mp2ctl = copymsg(mpctl);
18306 
18307 	/* fixed length IPv6 structure ... */
18308 
18309 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18310 	optp->level = MIB2_IP6;
18311 	optp->name = 0;
18312 	/* Include "unknown interface" ip6_mib */
18313 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
18314 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
18315 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
18316 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
18317 	    sizeof (mib2_ipv6IfStatsEntry_t));
18318 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18319 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
18320 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
18321 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18322 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
18323 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18324 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18325 	    (int)sizeof (ip6_mib))) {
18326 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18327 		    (uint_t)sizeof (ip6_mib)));
18328 	}
18329 
18330 	rw_enter(&ill_g_lock, RW_READER);
18331 	ill = ILL_START_WALK_V6(&ctx);
18332 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18333 		ill->ill_ip6_mib->ipv6IfIndex =
18334 		    ill->ill_phyint->phyint_ifindex;
18335 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
18336 		    ipv6_forward ? 1 : 2);
18337 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
18338 		    ill->ill_max_hops);
18339 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
18340 		    sizeof (mib2_ipv6IfStatsEntry_t));
18341 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
18342 		    sizeof (mib2_ipv6AddrEntry_t));
18343 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
18344 		    sizeof (mib2_ipv6RouteEntry_t));
18345 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
18346 		    sizeof (mib2_ipv6NetToMediaEntry_t));
18347 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
18348 		    sizeof (ipv6_member_t));
18349 
18350 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18351 		    (char *)ill->ill_ip6_mib,
18352 		    (int)sizeof (*ill->ill_ip6_mib))) {
18353 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18354 				"%u bytes\n",
18355 				(uint_t)sizeof (*ill->ill_ip6_mib)));
18356 		}
18357 	}
18358 	rw_exit(&ill_g_lock);
18359 
18360 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18361 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18362 	    (int)optp->level, (int)optp->name, (int)optp->len));
18363 	qreply(q, mpctl);
18364 	return (mp2ctl);
18365 }
18366 
18367 /*
18368  * ICMPv6 mib: One per ill
18369  */
18370 static mblk_t *
18371 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18372 {
18373 	struct opthdr		*optp;
18374 	mblk_t			*mp2ctl;
18375 	ill_t			*ill;
18376 	ill_walk_context_t	ctx;
18377 	mblk_t			*mp_tail = NULL;
18378 	/*
18379 	 * Make a copy of the original message
18380 	 */
18381 	mp2ctl = copymsg(mpctl);
18382 
18383 	/* fixed length ICMPv6 structure ... */
18384 
18385 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18386 	optp->level = MIB2_ICMP6;
18387 	optp->name = 0;
18388 	/* Include "unknown interface" icmp6_mib */
18389 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
18390 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18391 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18392 	    (int)sizeof (icmp6_mib))) {
18393 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18394 		    (uint_t)sizeof (icmp6_mib)));
18395 	}
18396 
18397 	rw_enter(&ill_g_lock, RW_READER);
18398 	ill = ILL_START_WALK_V6(&ctx);
18399 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18400 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18401 		    ill->ill_phyint->phyint_ifindex;
18402 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
18403 		    sizeof (mib2_ipv6IfIcmpEntry_t);
18404 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18405 		    (char *)ill->ill_icmp6_mib,
18406 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18407 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18408 			    "%u bytes\n",
18409 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18410 		}
18411 	}
18412 	rw_exit(&ill_g_lock);
18413 
18414 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18415 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18416 	    (int)optp->level, (int)optp->name, (int)optp->len));
18417 	qreply(q, mpctl);
18418 	return (mp2ctl);
18419 }
18420 
18421 /*
18422  * ire_walk routine to create both ipRouteEntryTable and
18423  * ipNetToMediaEntryTable in one IRE walk
18424  */
18425 static void
18426 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18427 {
18428 	ill_t				*ill;
18429 	ipif_t				*ipif;
18430 	mblk_t				*llmp;
18431 	dl_unitdata_req_t		*dlup;
18432 	mib2_ipRouteEntry_t		*re;
18433 	mib2_ipNetToMediaEntry_t	ntme;
18434 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18435 	ipaddr_t			gw_addr;
18436 	tsol_ire_gw_secattr_t		*attrp;
18437 	tsol_gc_t			*gc = NULL;
18438 	tsol_gcgrp_t			*gcgrp = NULL;
18439 	uint_t				sacnt = 0;
18440 	int				i;
18441 
18442 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18443 
18444 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18445 		return;
18446 
18447 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18448 		mutex_enter(&attrp->igsa_lock);
18449 		if ((gc = attrp->igsa_gc) != NULL) {
18450 			gcgrp = gc->gc_grp;
18451 			ASSERT(gcgrp != NULL);
18452 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18453 			sacnt = 1;
18454 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18455 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18456 			gc = gcgrp->gcgrp_head;
18457 			sacnt = gcgrp->gcgrp_count;
18458 		}
18459 		mutex_exit(&attrp->igsa_lock);
18460 
18461 		/* do nothing if there's no gc to report */
18462 		if (gc == NULL) {
18463 			ASSERT(sacnt == 0);
18464 			if (gcgrp != NULL) {
18465 				/* we might as well drop the lock now */
18466 				rw_exit(&gcgrp->gcgrp_rwlock);
18467 				gcgrp = NULL;
18468 			}
18469 			attrp = NULL;
18470 		}
18471 
18472 		ASSERT(gc == NULL || (gcgrp != NULL &&
18473 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18474 	}
18475 	ASSERT(sacnt == 0 || gc != NULL);
18476 
18477 	if (sacnt != 0 &&
18478 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18479 		kmem_free(re, sizeof (*re));
18480 		rw_exit(&gcgrp->gcgrp_rwlock);
18481 		return;
18482 	}
18483 
18484 	/*
18485 	 * Return all IRE types for route table... let caller pick and choose
18486 	 */
18487 	re->ipRouteDest = ire->ire_addr;
18488 	ipif = ire->ire_ipif;
18489 	re->ipRouteIfIndex.o_length = 0;
18490 	if (ire->ire_type == IRE_CACHE) {
18491 		ill = (ill_t *)ire->ire_stq->q_ptr;
18492 		re->ipRouteIfIndex.o_length =
18493 		    ill->ill_name_length == 0 ? 0 :
18494 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18495 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18496 		    re->ipRouteIfIndex.o_length);
18497 	} else if (ipif != NULL) {
18498 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18499 		    OCTET_LENGTH);
18500 		re->ipRouteIfIndex.o_length =
18501 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18502 	}
18503 	re->ipRouteMetric1 = -1;
18504 	re->ipRouteMetric2 = -1;
18505 	re->ipRouteMetric3 = -1;
18506 	re->ipRouteMetric4 = -1;
18507 
18508 	gw_addr = ire->ire_gateway_addr;
18509 
18510 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18511 		re->ipRouteNextHop = ire->ire_src_addr;
18512 	else
18513 		re->ipRouteNextHop = gw_addr;
18514 	/* indirect(4), direct(3), or invalid(2) */
18515 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18516 		re->ipRouteType = 2;
18517 	else
18518 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18519 	re->ipRouteProto = -1;
18520 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18521 	re->ipRouteMask = ire->ire_mask;
18522 	re->ipRouteMetric5 = -1;
18523 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
18524 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
18525 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
18526 	if (ire->ire_nce &&
18527 	    ire->ire_nce->nce_state == ND_REACHABLE)
18528 		llmp = ire->ire_nce->nce_res_mp;
18529 	else
18530 		llmp = NULL;
18531 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
18532 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
18533 	re->ipRouteInfo.re_ire_type	= ire->ire_type;
18534 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18535 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18536 	re->ipRouteInfo.re_flags	= ire->ire_flags;
18537 	re->ipRouteInfo.re_in_ill.o_length = 0;
18538 	if (ire->ire_in_ill != NULL) {
18539 		re->ipRouteInfo.re_in_ill.o_length =
18540 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
18541 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
18542 		bcopy(ire->ire_in_ill->ill_name,
18543 		    re->ipRouteInfo.re_in_ill.o_bytes,
18544 		    re->ipRouteInfo.re_in_ill.o_length);
18545 	}
18546 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
18547 
18548 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18549 	    (char *)re, (int)sizeof (*re))) {
18550 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18551 		    (uint_t)sizeof (*re)));
18552 	}
18553 
18554 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18555 		iaeptr->iae_routeidx = ird->ird_idx;
18556 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18557 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18558 	}
18559 
18560 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18561 	    (char *)iae, sacnt * sizeof (*iae))) {
18562 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18563 		    (unsigned)(sacnt * sizeof (*iae))));
18564 	}
18565 
18566 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
18567 		goto done;
18568 	/*
18569 	 * only IRE_CACHE entries that are for a directly connected subnet
18570 	 * get appended to net -> phys addr table
18571 	 * (others in arp)
18572 	 */
18573 	ntme.ipNetToMediaIfIndex.o_length = 0;
18574 	ill = ire_to_ill(ire);
18575 	ASSERT(ill != NULL);
18576 	ntme.ipNetToMediaIfIndex.o_length =
18577 	    ill->ill_name_length == 0 ? 0 :
18578 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18579 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
18580 		    ntme.ipNetToMediaIfIndex.o_length);
18581 
18582 	ntme.ipNetToMediaPhysAddress.o_length = 0;
18583 	if (llmp) {
18584 		uchar_t *addr;
18585 
18586 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
18587 		/* Remove sap from  address */
18588 		if (ill->ill_sap_length < 0)
18589 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
18590 		else
18591 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
18592 			    ill->ill_sap_length;
18593 
18594 		ntme.ipNetToMediaPhysAddress.o_length =
18595 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18596 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18597 		    ntme.ipNetToMediaPhysAddress.o_length);
18598 	}
18599 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18600 	/* assume dynamic (may be changed in arp) */
18601 	ntme.ipNetToMediaType = 3;
18602 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18603 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18604 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18605 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18606 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18607 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18608 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18609 		    (uint_t)sizeof (ntme)));
18610 	}
18611 done:
18612 	/* bump route index for next pass */
18613 	ird->ird_idx++;
18614 
18615 	kmem_free(re, sizeof (*re));
18616 	if (sacnt != 0)
18617 		kmem_free(iae, sacnt * sizeof (*iae));
18618 
18619 	if (gcgrp != NULL)
18620 		rw_exit(&gcgrp->gcgrp_rwlock);
18621 }
18622 
18623 /*
18624  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18625  */
18626 static void
18627 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18628 {
18629 	ill_t				*ill;
18630 	ipif_t				*ipif;
18631 	mib2_ipv6RouteEntry_t		*re;
18632 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18633 	in6_addr_t			gw_addr_v6;
18634 	tsol_ire_gw_secattr_t		*attrp;
18635 	tsol_gc_t			*gc = NULL;
18636 	tsol_gcgrp_t			*gcgrp = NULL;
18637 	uint_t				sacnt = 0;
18638 	int				i;
18639 
18640 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18641 
18642 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18643 		return;
18644 
18645 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18646 		mutex_enter(&attrp->igsa_lock);
18647 		if ((gc = attrp->igsa_gc) != NULL) {
18648 			gcgrp = gc->gc_grp;
18649 			ASSERT(gcgrp != NULL);
18650 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18651 			sacnt = 1;
18652 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18653 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18654 			gc = gcgrp->gcgrp_head;
18655 			sacnt = gcgrp->gcgrp_count;
18656 		}
18657 		mutex_exit(&attrp->igsa_lock);
18658 
18659 		/* do nothing if there's no gc to report */
18660 		if (gc == NULL) {
18661 			ASSERT(sacnt == 0);
18662 			if (gcgrp != NULL) {
18663 				/* we might as well drop the lock now */
18664 				rw_exit(&gcgrp->gcgrp_rwlock);
18665 				gcgrp = NULL;
18666 			}
18667 			attrp = NULL;
18668 		}
18669 
18670 		ASSERT(gc == NULL || (gcgrp != NULL &&
18671 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18672 	}
18673 	ASSERT(sacnt == 0 || gc != NULL);
18674 
18675 	if (sacnt != 0 &&
18676 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18677 		kmem_free(re, sizeof (*re));
18678 		rw_exit(&gcgrp->gcgrp_rwlock);
18679 		return;
18680 	}
18681 
18682 	/*
18683 	 * Return all IRE types for route table... let caller pick and choose
18684 	 */
18685 	re->ipv6RouteDest = ire->ire_addr_v6;
18686 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18687 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18688 	re->ipv6RouteIfIndex.o_length = 0;
18689 	ipif = ire->ire_ipif;
18690 	if (ire->ire_type == IRE_CACHE) {
18691 		ill = (ill_t *)ire->ire_stq->q_ptr;
18692 		re->ipv6RouteIfIndex.o_length =
18693 		    ill->ill_name_length == 0 ? 0 :
18694 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18695 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
18696 		    re->ipv6RouteIfIndex.o_length);
18697 	} else if (ipif != NULL) {
18698 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
18699 		    OCTET_LENGTH);
18700 		re->ipv6RouteIfIndex.o_length =
18701 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
18702 	}
18703 
18704 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18705 
18706 	mutex_enter(&ire->ire_lock);
18707 	gw_addr_v6 = ire->ire_gateway_addr_v6;
18708 	mutex_exit(&ire->ire_lock);
18709 
18710 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
18711 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
18712 	else
18713 		re->ipv6RouteNextHop = gw_addr_v6;
18714 
18715 	/* remote(4), local(3), or discard(2) */
18716 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18717 		re->ipv6RouteType = 2;
18718 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
18719 		re->ipv6RouteType = 3;
18720 	else
18721 		re->ipv6RouteType = 4;
18722 
18723 	re->ipv6RouteProtocol	= -1;
18724 	re->ipv6RoutePolicy	= 0;
18725 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
18726 	re->ipv6RouteNextHopRDI	= 0;
18727 	re->ipv6RouteWeight	= 0;
18728 	re->ipv6RouteMetric	= 0;
18729 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
18730 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
18731 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
18732 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
18733 	re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
18734 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18735 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18736 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
18737 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
18738 
18739 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18740 	    (char *)re, (int)sizeof (*re))) {
18741 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18742 		    (uint_t)sizeof (*re)));
18743 	}
18744 
18745 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18746 		iaeptr->iae_routeidx = ird->ird_idx;
18747 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18748 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18749 	}
18750 
18751 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18752 	    (char *)iae, sacnt * sizeof (*iae))) {
18753 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18754 		    (unsigned)(sacnt * sizeof (*iae))));
18755 	}
18756 
18757 	/* bump route index for next pass */
18758 	ird->ird_idx++;
18759 
18760 	kmem_free(re, sizeof (*re));
18761 	if (sacnt != 0)
18762 		kmem_free(iae, sacnt * sizeof (*iae));
18763 
18764 	if (gcgrp != NULL)
18765 		rw_exit(&gcgrp->gcgrp_rwlock);
18766 }
18767 
18768 /*
18769  * ndp_walk routine to create ipv6NetToMediaEntryTable
18770  */
18771 static int
18772 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
18773 {
18774 	ill_t				*ill;
18775 	mib2_ipv6NetToMediaEntry_t	ntme;
18776 	dl_unitdata_req_t		*dl;
18777 
18778 	ill = nce->nce_ill;
18779 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
18780 		return (0);
18781 
18782 	/*
18783 	 * Neighbor cache entry attached to IRE with on-link
18784 	 * destination.
18785 	 */
18786 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
18787 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
18788 	if ((ill->ill_flags & ILLF_XRESOLV) &&
18789 	    (nce->nce_res_mp != NULL)) {
18790 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
18791 		ntme.ipv6NetToMediaPhysAddress.o_length =
18792 		    dl->dl_dest_addr_length;
18793 	} else {
18794 		ntme.ipv6NetToMediaPhysAddress.o_length =
18795 		    ill->ill_phys_addr_length;
18796 	}
18797 	if (nce->nce_res_mp != NULL) {
18798 		bcopy((char *)nce->nce_res_mp->b_rptr +
18799 		    NCE_LL_ADDR_OFFSET(ill),
18800 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
18801 		    ntme.ipv6NetToMediaPhysAddress.o_length);
18802 	} else {
18803 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
18804 		    ill->ill_phys_addr_length);
18805 	}
18806 	/*
18807 	 * Note: Returns ND_* states. Should be:
18808 	 * reachable(1), stale(2), delay(3), probe(4),
18809 	 * invalid(5), unknown(6)
18810 	 */
18811 	ntme.ipv6NetToMediaState = nce->nce_state;
18812 	ntme.ipv6NetToMediaLastUpdated = 0;
18813 
18814 	/* other(1), dynamic(2), static(3), local(4) */
18815 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
18816 		ntme.ipv6NetToMediaType = 4;
18817 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
18818 		ntme.ipv6NetToMediaType = 1;
18819 	} else {
18820 		ntme.ipv6NetToMediaType = 2;
18821 	}
18822 
18823 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18824 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18825 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
18826 		    (uint_t)sizeof (ntme)));
18827 	}
18828 	return (0);
18829 }
18830 
18831 /*
18832  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
18833  */
18834 /* ARGSUSED */
18835 int
18836 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
18837 {
18838 	switch (level) {
18839 	case MIB2_IP:
18840 	case MIB2_ICMP:
18841 		switch (name) {
18842 		default:
18843 			break;
18844 		}
18845 		return (1);
18846 	default:
18847 		return (1);
18848 	}
18849 }
18850 
18851 /*
18852  * Called before the options are updated to check if this packet will
18853  * be source routed from here.
18854  * This routine assumes that the options are well formed i.e. that they
18855  * have already been checked.
18856  */
18857 static boolean_t
18858 ip_source_routed(ipha_t *ipha)
18859 {
18860 	ipoptp_t	opts;
18861 	uchar_t		*opt;
18862 	uint8_t		optval;
18863 	uint8_t		optlen;
18864 	ipaddr_t	dst;
18865 	ire_t		*ire;
18866 
18867 	if (IS_SIMPLE_IPH(ipha)) {
18868 		ip2dbg(("not source routed\n"));
18869 		return (B_FALSE);
18870 	}
18871 	dst = ipha->ipha_dst;
18872 	for (optval = ipoptp_first(&opts, ipha);
18873 	    optval != IPOPT_EOL;
18874 	    optval = ipoptp_next(&opts)) {
18875 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18876 		opt = opts.ipoptp_cur;
18877 		optlen = opts.ipoptp_len;
18878 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
18879 		    optval, optlen));
18880 		switch (optval) {
18881 			uint32_t off;
18882 		case IPOPT_SSRR:
18883 		case IPOPT_LSRR:
18884 			/*
18885 			 * If dst is one of our addresses and there are some
18886 			 * entries left in the source route return (true).
18887 			 */
18888 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18889 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
18890 			if (ire == NULL) {
18891 				ip2dbg(("ip_source_routed: not next"
18892 				    " source route 0x%x\n",
18893 				    ntohl(dst)));
18894 				return (B_FALSE);
18895 			}
18896 			ire_refrele(ire);
18897 			off = opt[IPOPT_OFFSET];
18898 			off--;
18899 			if (optlen < IP_ADDR_LEN ||
18900 			    off > optlen - IP_ADDR_LEN) {
18901 				/* End of source route */
18902 				ip1dbg(("ip_source_routed: end of SR\n"));
18903 				return (B_FALSE);
18904 			}
18905 			return (B_TRUE);
18906 		}
18907 	}
18908 	ip2dbg(("not source routed\n"));
18909 	return (B_FALSE);
18910 }
18911 
18912 /*
18913  * Check if the packet contains any source route.
18914  */
18915 static boolean_t
18916 ip_source_route_included(ipha_t *ipha)
18917 {
18918 	ipoptp_t	opts;
18919 	uint8_t		optval;
18920 
18921 	if (IS_SIMPLE_IPH(ipha))
18922 		return (B_FALSE);
18923 	for (optval = ipoptp_first(&opts, ipha);
18924 	    optval != IPOPT_EOL;
18925 	    optval = ipoptp_next(&opts)) {
18926 		switch (optval) {
18927 		case IPOPT_SSRR:
18928 		case IPOPT_LSRR:
18929 			return (B_TRUE);
18930 		}
18931 	}
18932 	return (B_FALSE);
18933 }
18934 
18935 /*
18936  * Called when the IRE expiration timer fires.
18937  */
18938 /* ARGSUSED */
18939 void
18940 ip_trash_timer_expire(void *args)
18941 {
18942 	int	flush_flag = 0;
18943 
18944 	/*
18945 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
18946 	 * This lock makes sure that a new invocation of this function
18947 	 * that occurs due to an almost immediate timer firing will not
18948 	 * progress beyond this point until the current invocation is done
18949 	 */
18950 	mutex_enter(&ip_trash_timer_lock);
18951 	ip_ire_expire_id = 0;
18952 	mutex_exit(&ip_trash_timer_lock);
18953 
18954 	/* Periodic timer */
18955 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
18956 		/*
18957 		 * Remove all IRE_CACHE entries since they might
18958 		 * contain arp information.
18959 		 */
18960 		flush_flag |= FLUSH_ARP_TIME;
18961 		ip_ire_arp_time_elapsed = 0;
18962 		IP_STAT(ip_ire_arp_timer_expired);
18963 	}
18964 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
18965 		/* Remove all redirects */
18966 		flush_flag |= FLUSH_REDIRECT_TIME;
18967 		ip_ire_rd_time_elapsed = 0;
18968 		IP_STAT(ip_ire_redirect_timer_expired);
18969 	}
18970 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
18971 		/* Increase path mtu */
18972 		flush_flag |= FLUSH_MTU_TIME;
18973 		ip_ire_pmtu_time_elapsed = 0;
18974 		IP_STAT(ip_ire_pmtu_timer_expired);
18975 	}
18976 
18977 	/*
18978 	 * Optimize for the case when there are no redirects in the
18979 	 * ftable, that is, no need to walk the ftable in that case.
18980 	 */
18981 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
18982 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
18983 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
18984 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
18985 	}
18986 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
18987 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
18988 		    ire_expire, (char *)(uintptr_t)flush_flag,
18989 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
18990 	}
18991 	if (flush_flag & FLUSH_MTU_TIME) {
18992 		/*
18993 		 * Walk all IPv6 IRE's and update them
18994 		 * Note that ARP and redirect timers are not
18995 		 * needed since NUD handles stale entries.
18996 		 */
18997 		flush_flag = FLUSH_MTU_TIME;
18998 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
18999 		    ALL_ZONES);
19000 	}
19001 
19002 	ip_ire_arp_time_elapsed += ip_timer_interval;
19003 	ip_ire_rd_time_elapsed += ip_timer_interval;
19004 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19005 
19006 	/*
19007 	 * Hold the lock to serialize timeout calls and prevent
19008 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19009 	 * for the timer to fire and a new invocation of this function
19010 	 * to start before the return value of timeout has been stored
19011 	 * in ip_ire_expire_id by the current invocation.
19012 	 */
19013 	mutex_enter(&ip_trash_timer_lock);
19014 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19015 	    MSEC_TO_TICK(ip_timer_interval));
19016 	mutex_exit(&ip_trash_timer_lock);
19017 }
19018 
19019 /*
19020  * Called by the memory allocator subsystem directly, when the system
19021  * is running low on memory.
19022  */
19023 /* ARGSUSED */
19024 void
19025 ip_trash_ire_reclaim(void *args)
19026 {
19027 	ire_cache_count_t icc;
19028 	ire_cache_reclaim_t icr;
19029 	ncc_cache_count_t ncc;
19030 	nce_cache_reclaim_t ncr;
19031 	uint_t delete_cnt;
19032 	/*
19033 	 * Memory reclaim call back.
19034 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19035 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19036 	 * entries, determine what fraction to free for
19037 	 * each category of IRE_CACHE entries giving absolute priority
19038 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19039 	 * entry will be freed unless all offlink entries are freed).
19040 	 */
19041 	icc.icc_total = 0;
19042 	icc.icc_unused = 0;
19043 	icc.icc_offlink = 0;
19044 	icc.icc_pmtu = 0;
19045 	icc.icc_onlink = 0;
19046 	ire_walk(ire_cache_count, (char *)&icc);
19047 
19048 	/*
19049 	 * Free NCEs for IPv6 like the onlink ires.
19050 	 */
19051 	ncc.ncc_total = 0;
19052 	ncc.ncc_host = 0;
19053 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19054 
19055 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19056 	    icc.icc_pmtu + icc.icc_onlink);
19057 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19058 	IP_STAT(ip_trash_ire_reclaim_calls);
19059 	if (delete_cnt == 0)
19060 		return;
19061 	IP_STAT(ip_trash_ire_reclaim_success);
19062 	/* Always delete all unused offlink entries */
19063 	icr.icr_unused = 1;
19064 	if (delete_cnt <= icc.icc_unused) {
19065 		/*
19066 		 * Only need to free unused entries.  In other words,
19067 		 * there are enough unused entries to free to meet our
19068 		 * target number of freed ire cache entries.
19069 		 */
19070 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19071 		ncr.ncr_host = 0;
19072 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19073 		/*
19074 		 * Only need to free unused entries, plus a fraction of offlink
19075 		 * entries.  It follows from the first if statement that
19076 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19077 		 */
19078 		delete_cnt -= icc.icc_unused;
19079 		/* Round up # deleted by truncating fraction */
19080 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19081 		icr.icr_pmtu = icr.icr_onlink = 0;
19082 		ncr.ncr_host = 0;
19083 	} else if (delete_cnt <=
19084 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19085 		/*
19086 		 * Free all unused and offlink entries, plus a fraction of
19087 		 * pmtu entries.  It follows from the previous if statement
19088 		 * that icc_pmtu is non-zero, and that
19089 		 * delete_cnt != icc_unused + icc_offlink.
19090 		 */
19091 		icr.icr_offlink = 1;
19092 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19093 		/* Round up # deleted by truncating fraction */
19094 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19095 		icr.icr_onlink = 0;
19096 		ncr.ncr_host = 0;
19097 	} else {
19098 		/*
19099 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19100 		 * of onlink entries.  If we're here, then we know that
19101 		 * icc_onlink is non-zero, and that
19102 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19103 		 */
19104 		icr.icr_offlink = icr.icr_pmtu = 1;
19105 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19106 		    icc.icc_pmtu;
19107 		/* Round up # deleted by truncating fraction */
19108 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19109 		/* Using the same delete fraction as for onlink IREs */
19110 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19111 	}
19112 #ifdef DEBUG
19113 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19114 	    "fractions %d/%d/%d/%d\n",
19115 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19116 	    icc.icc_unused, icc.icc_offlink,
19117 	    icc.icc_pmtu, icc.icc_onlink,
19118 	    icr.icr_unused, icr.icr_offlink,
19119 	    icr.icr_pmtu, icr.icr_onlink));
19120 #endif
19121 	ire_walk(ire_cache_reclaim, (char *)&icr);
19122 	if (ncr.ncr_host != 0)
19123 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19124 		    (uchar_t *)&ncr);
19125 #ifdef DEBUG
19126 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19127 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19128 	ire_walk(ire_cache_count, (char *)&icc);
19129 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19130 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19131 	    icc.icc_pmtu, icc.icc_onlink));
19132 #endif
19133 }
19134 
19135 /*
19136  * ip_unbind is called when a copy of an unbind request is received from the
19137  * upper level protocol.  We remove this conn from any fanout hash list it is
19138  * on, and zero out the bind information.  No reply is expected up above.
19139  */
19140 mblk_t *
19141 ip_unbind(queue_t *q, mblk_t *mp)
19142 {
19143 	conn_t	*connp = Q_TO_CONN(q);
19144 
19145 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19146 
19147 	if (is_system_labeled() && connp->conn_anon_port) {
19148 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19149 		    connp->conn_mlp_type, connp->conn_ulp,
19150 		    ntohs(connp->conn_lport), B_FALSE);
19151 		connp->conn_anon_port = 0;
19152 	}
19153 	connp->conn_mlp_type = mlptSingle;
19154 
19155 	ipcl_hash_remove(connp);
19156 
19157 	ASSERT(mp->b_cont == NULL);
19158 	/*
19159 	 * Convert mp into a T_OK_ACK
19160 	 */
19161 	mp = mi_tpi_ok_ack_alloc(mp);
19162 
19163 	/*
19164 	 * should not happen in practice... T_OK_ACK is smaller than the
19165 	 * original message.
19166 	 */
19167 	if (mp == NULL)
19168 		return (NULL);
19169 
19170 	/*
19171 	 * Don't bzero the ports if its TCP since TCP still needs the
19172 	 * lport to remove it from its own bind hash. TCP will do the
19173 	 * cleanup.
19174 	 */
19175 	if (!IPCL_IS_TCP(connp))
19176 		bzero(&connp->u_port, sizeof (connp->u_port));
19177 
19178 	return (mp);
19179 }
19180 
19181 /*
19182  * Write side put procedure.  Outbound data, IOCTLs, responses from
19183  * resolvers, etc, come down through here.
19184  */
19185 void
19186 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19187 {
19188 	conn_t		*connp = NULL;
19189 	queue_t		*q = (queue_t *)arg2;
19190 	ipha_t		*ipha;
19191 #define	rptr	((uchar_t *)ipha)
19192 	ire_t		*ire = NULL;
19193 	ire_t		*sctp_ire = NULL;
19194 	uint32_t	v_hlen_tos_len;
19195 	ipaddr_t	dst;
19196 	mblk_t		*first_mp = NULL;
19197 	boolean_t	mctl_present;
19198 	ipsec_out_t	*io;
19199 	int		match_flags;
19200 	ill_t		*attach_ill = NULL;
19201 					/* Bind to IPIF_NOFAILOVER ill etc. */
19202 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19203 	ipif_t		*dst_ipif;
19204 	boolean_t	multirt_need_resolve = B_FALSE;
19205 	mblk_t		*copy_mp = NULL;
19206 	int		err;
19207 	zoneid_t	zoneid;
19208 	int	adjust;
19209 	uint16_t iplen;
19210 	boolean_t	need_decref = B_FALSE;
19211 	boolean_t	ignore_dontroute = B_FALSE;
19212 	boolean_t	ignore_nexthop = B_FALSE;
19213 	boolean_t	ip_nexthop = B_FALSE;
19214 	ipaddr_t	nexthop_addr;
19215 
19216 #ifdef	_BIG_ENDIAN
19217 #define	V_HLEN	(v_hlen_tos_len >> 24)
19218 #else
19219 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19220 #endif
19221 
19222 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19223 	    "ip_wput_start: q %p", q);
19224 
19225 	/*
19226 	 * ip_wput fast path
19227 	 */
19228 
19229 	/* is packet from ARP ? */
19230 	if (q->q_next != NULL)
19231 		goto qnext;
19232 
19233 	connp = (conn_t *)arg;
19234 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
19235 
19236 	/* is queue flow controlled? */
19237 	if ((q->q_first != NULL || connp->conn_draining) &&
19238 	    (caller == IP_WPUT)) {
19239 		ASSERT(!need_decref);
19240 		(void) putq(q, mp);
19241 		return;
19242 	}
19243 
19244 	/* Multidata transmit? */
19245 	if (DB_TYPE(mp) == M_MULTIDATA) {
19246 		/*
19247 		 * We should never get here, since all Multidata messages
19248 		 * originating from tcp should have been directed over to
19249 		 * tcp_multisend() in the first place.
19250 		 */
19251 		BUMP_MIB(&ip_mib, ipOutDiscards);
19252 		freemsg(mp);
19253 		return;
19254 	} else if (DB_TYPE(mp) != M_DATA)
19255 		goto notdata;
19256 
19257 	if (mp->b_flag & MSGHASREF) {
19258 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19259 		mp->b_flag &= ~MSGHASREF;
19260 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19261 		need_decref = B_TRUE;
19262 	}
19263 	ipha = (ipha_t *)mp->b_rptr;
19264 
19265 	/* is IP header non-aligned or mblk smaller than basic IP header */
19266 #ifndef SAFETY_BEFORE_SPEED
19267 	if (!OK_32PTR(rptr) ||
19268 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19269 		goto hdrtoosmall;
19270 #endif
19271 
19272 	ASSERT(OK_32PTR(ipha));
19273 
19274 	/*
19275 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19276 	 * wrong version, we'll catch it again in ip_output_v6.
19277 	 *
19278 	 * Note that this is *only* locally-generated output here, and never
19279 	 * forwarded data, and that we need to deal only with transports that
19280 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19281 	 * label.)
19282 	 */
19283 	if (is_system_labeled() &&
19284 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19285 	    !connp->conn_ulp_labeled) {
19286 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19287 		    connp->conn_mac_exempt);
19288 		ipha = (ipha_t *)mp->b_rptr;
19289 		if (err != 0) {
19290 			first_mp = mp;
19291 			if (err == EINVAL)
19292 				goto icmp_parameter_problem;
19293 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19294 			goto drop_pkt;
19295 		}
19296 		iplen = ntohs(ipha->ipha_length) + adjust;
19297 		ipha->ipha_length = htons(iplen);
19298 	}
19299 
19300 	/*
19301 	 * If there is a policy, try to attach an ipsec_out in
19302 	 * the front. At the end, first_mp either points to a
19303 	 * M_DATA message or IPSEC_OUT message linked to a
19304 	 * M_DATA message. We have to do it now as we might
19305 	 * lose the "conn" if we go through ip_newroute.
19306 	 */
19307 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19308 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
19309 		    ipha->ipha_protocol)) == NULL)) {
19310 			if (need_decref)
19311 				CONN_DEC_REF(connp);
19312 			return;
19313 		} else {
19314 			ASSERT(mp->b_datap->db_type == M_CTL);
19315 			first_mp = mp;
19316 			mp = mp->b_cont;
19317 			mctl_present = B_TRUE;
19318 		}
19319 	} else {
19320 		first_mp = mp;
19321 		mctl_present = B_FALSE;
19322 	}
19323 
19324 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19325 
19326 	/* is wrong version or IP options present */
19327 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19328 		goto version_hdrlen_check;
19329 	dst = ipha->ipha_dst;
19330 
19331 	if (connp->conn_nofailover_ill != NULL) {
19332 		attach_ill = conn_get_held_ill(connp,
19333 		    &connp->conn_nofailover_ill, &err);
19334 		if (err == ILL_LOOKUP_FAILED) {
19335 			if (need_decref)
19336 				CONN_DEC_REF(connp);
19337 			freemsg(first_mp);
19338 			return;
19339 		}
19340 	}
19341 
19342 	/* is packet multicast? */
19343 	if (CLASSD(dst))
19344 		goto multicast;
19345 
19346 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19347 	    (connp->conn_nexthop_set)) {
19348 		/*
19349 		 * If the destination is a broadcast or a loopback
19350 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
19351 		 * through the standard path. But in the case of local
19352 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
19353 		 * the standard path not IP_XMIT_IF.
19354 		 */
19355 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19356 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
19357 		    (ire->ire_type != IRE_LOOPBACK))) {
19358 			if ((connp->conn_dontroute ||
19359 			    connp->conn_nexthop_set) && (ire != NULL) &&
19360 			    (ire->ire_type == IRE_LOCAL))
19361 				goto standard_path;
19362 
19363 			if (ire != NULL) {
19364 				ire_refrele(ire);
19365 				/* No more access to ire */
19366 				ire = NULL;
19367 			}
19368 			/*
19369 			 * bypass routing checks and go directly to
19370 			 * interface.
19371 			 */
19372 			if (connp->conn_dontroute) {
19373 				goto dontroute;
19374 			} else if (connp->conn_nexthop_set) {
19375 				ip_nexthop = B_TRUE;
19376 				nexthop_addr = connp->conn_nexthop_v4;
19377 				goto send_from_ill;
19378 			}
19379 
19380 			/*
19381 			 * If IP_XMIT_IF socket option is set,
19382 			 * then we allow unicast and multicast
19383 			 * packets to go through the ill. It is
19384 			 * quite possible that the destination
19385 			 * is not in the ire cache table and we
19386 			 * do not want to go to ip_newroute()
19387 			 * instead we call ip_newroute_ipif.
19388 			 */
19389 			xmit_ill = conn_get_held_ill(connp,
19390 			    &connp->conn_xmit_if_ill, &err);
19391 			if (err == ILL_LOOKUP_FAILED) {
19392 				if (attach_ill != NULL)
19393 					ill_refrele(attach_ill);
19394 				if (need_decref)
19395 					CONN_DEC_REF(connp);
19396 				freemsg(first_mp);
19397 				return;
19398 			}
19399 			goto send_from_ill;
19400 		}
19401 standard_path:
19402 		/* Must be a broadcast, a loopback or a local ire */
19403 		if (ire != NULL) {
19404 			ire_refrele(ire);
19405 			/* No more access to ire */
19406 			ire = NULL;
19407 		}
19408 	}
19409 
19410 	if (attach_ill != NULL)
19411 		goto send_from_ill;
19412 
19413 	/*
19414 	 * We cache IRE_CACHEs to avoid lookups. We don't do
19415 	 * this for the tcp global queue and listen end point
19416 	 * as it does not really have a real destination to
19417 	 * talk to.  This is also true for SCTP.
19418 	 */
19419 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
19420 	    !connp->conn_fully_bound) {
19421 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19422 		if (ire == NULL)
19423 			goto noirefound;
19424 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19425 		    "ip_wput_end: q %p (%S)", q, "end");
19426 
19427 		/*
19428 		 * Check if the ire has the RTF_MULTIRT flag, inherited
19429 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19430 		 */
19431 		if (ire->ire_flags & RTF_MULTIRT) {
19432 
19433 			/*
19434 			 * Force the TTL of multirouted packets if required.
19435 			 * The TTL of such packets is bounded by the
19436 			 * ip_multirt_ttl ndd variable.
19437 			 */
19438 			if ((ip_multirt_ttl > 0) &&
19439 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
19440 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
19441 				    "(was %d), dst 0x%08x\n",
19442 				    ip_multirt_ttl, ipha->ipha_ttl,
19443 				    ntohl(ire->ire_addr)));
19444 				ipha->ipha_ttl = ip_multirt_ttl;
19445 			}
19446 			/*
19447 			 * We look at this point if there are pending
19448 			 * unresolved routes. ire_multirt_resolvable()
19449 			 * checks in O(n) that all IRE_OFFSUBNET ire
19450 			 * entries for the packet's destination and
19451 			 * flagged RTF_MULTIRT are currently resolved.
19452 			 * If some remain unresolved, we make a copy
19453 			 * of the current message. It will be used
19454 			 * to initiate additional route resolutions.
19455 			 */
19456 			multirt_need_resolve =
19457 			    ire_multirt_need_resolve(ire->ire_addr,
19458 			    MBLK_GETLABEL(first_mp));
19459 			ip2dbg(("ip_wput[TCP]: ire %p, "
19460 			    "multirt_need_resolve %d, first_mp %p\n",
19461 			    (void *)ire, multirt_need_resolve,
19462 			    (void *)first_mp));
19463 			if (multirt_need_resolve) {
19464 				copy_mp = copymsg(first_mp);
19465 				if (copy_mp != NULL) {
19466 					MULTIRT_DEBUG_TAG(copy_mp);
19467 				}
19468 			}
19469 		}
19470 
19471 		ip_wput_ire(q, first_mp, ire, connp, caller);
19472 
19473 		/*
19474 		 * Try to resolve another multiroute if
19475 		 * ire_multirt_need_resolve() deemed it necessary.
19476 		 */
19477 		if (copy_mp != NULL) {
19478 			ip_newroute(q, copy_mp, dst, NULL, connp);
19479 		}
19480 		if (need_decref)
19481 			CONN_DEC_REF(connp);
19482 		return;
19483 	}
19484 
19485 	/*
19486 	 * Access to conn_ire_cache. (protected by conn_lock)
19487 	 *
19488 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
19489 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
19490 	 * send a packet or two with the IRE_CACHE that is going away.
19491 	 * Access to the ire requires an ire refhold on the ire prior to
19492 	 * its use since an interface unplumb thread may delete the cached
19493 	 * ire and release the refhold at any time.
19494 	 *
19495 	 * Caching an ire in the conn_ire_cache
19496 	 *
19497 	 * o Caching an ire pointer in the conn requires a strict check for
19498 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
19499 	 * ires  before cleaning up the conns. So the caching of an ire pointer
19500 	 * in the conn is done after making sure under the bucket lock that the
19501 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
19502 	 * caching an ire after the unplumb thread has cleaned up the conn.
19503 	 * If the conn does not send a packet subsequently the unplumb thread
19504 	 * will be hanging waiting for the ire count to drop to zero.
19505 	 *
19506 	 * o We also need to atomically test for a null conn_ire_cache and
19507 	 * set the conn_ire_cache under the the protection of the conn_lock
19508 	 * to avoid races among concurrent threads trying to simultaneously
19509 	 * cache an ire in the conn_ire_cache.
19510 	 */
19511 	mutex_enter(&connp->conn_lock);
19512 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
19513 
19514 	if (ire != NULL && ire->ire_addr == dst &&
19515 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19516 
19517 		IRE_REFHOLD(ire);
19518 		mutex_exit(&connp->conn_lock);
19519 
19520 	} else {
19521 		boolean_t cached = B_FALSE;
19522 		connp->conn_ire_cache = NULL;
19523 		mutex_exit(&connp->conn_lock);
19524 		/* Release the old ire */
19525 		if (ire != NULL && sctp_ire == NULL)
19526 			IRE_REFRELE_NOTR(ire);
19527 
19528 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19529 		if (ire == NULL)
19530 			goto noirefound;
19531 		IRE_REFHOLD_NOTR(ire);
19532 
19533 		mutex_enter(&connp->conn_lock);
19534 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
19535 		    connp->conn_ire_cache == NULL) {
19536 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19537 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19538 				connp->conn_ire_cache = ire;
19539 				cached = B_TRUE;
19540 			}
19541 			rw_exit(&ire->ire_bucket->irb_lock);
19542 		}
19543 		mutex_exit(&connp->conn_lock);
19544 
19545 		/*
19546 		 * We can continue to use the ire but since it was
19547 		 * not cached, we should drop the extra reference.
19548 		 */
19549 		if (!cached)
19550 			IRE_REFRELE_NOTR(ire);
19551 	}
19552 
19553 
19554 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19555 	    "ip_wput_end: q %p (%S)", q, "end");
19556 
19557 	/*
19558 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19559 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19560 	 */
19561 	if (ire->ire_flags & RTF_MULTIRT) {
19562 
19563 		/*
19564 		 * Force the TTL of multirouted packets if required.
19565 		 * The TTL of such packets is bounded by the
19566 		 * ip_multirt_ttl ndd variable.
19567 		 */
19568 		if ((ip_multirt_ttl > 0) &&
19569 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19570 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19571 			    "(was %d), dst 0x%08x\n",
19572 			    ip_multirt_ttl, ipha->ipha_ttl,
19573 			    ntohl(ire->ire_addr)));
19574 			ipha->ipha_ttl = ip_multirt_ttl;
19575 		}
19576 
19577 		/*
19578 		 * At this point, we check to see if there are any pending
19579 		 * unresolved routes. ire_multirt_resolvable()
19580 		 * checks in O(n) that all IRE_OFFSUBNET ire
19581 		 * entries for the packet's destination and
19582 		 * flagged RTF_MULTIRT are currently resolved.
19583 		 * If some remain unresolved, we make a copy
19584 		 * of the current message. It will be used
19585 		 * to initiate additional route resolutions.
19586 		 */
19587 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19588 		    MBLK_GETLABEL(first_mp));
19589 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19590 		    "multirt_need_resolve %d, first_mp %p\n",
19591 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19592 		if (multirt_need_resolve) {
19593 			copy_mp = copymsg(first_mp);
19594 			if (copy_mp != NULL) {
19595 				MULTIRT_DEBUG_TAG(copy_mp);
19596 			}
19597 		}
19598 	}
19599 
19600 	ip_wput_ire(q, first_mp, ire, connp, caller);
19601 
19602 	/*
19603 	 * Try to resolve another multiroute if
19604 	 * ire_multirt_resolvable() deemed it necessary
19605 	 */
19606 	if (copy_mp != NULL) {
19607 		ip_newroute(q, copy_mp, dst, NULL, connp);
19608 	}
19609 	if (need_decref)
19610 		CONN_DEC_REF(connp);
19611 	return;
19612 
19613 qnext:
19614 	/*
19615 	 * Upper Level Protocols pass down complete IP datagrams
19616 	 * as M_DATA messages.	Everything else is a sideshow.
19617 	 *
19618 	 * 1) We could be re-entering ip_wput because of ip_neworute
19619 	 *    in which case we could have a IPSEC_OUT message. We
19620 	 *    need to pass through ip_wput like other datagrams and
19621 	 *    hence cannot branch to ip_wput_nondata.
19622 	 *
19623 	 * 2) ARP, AH, ESP, and other clients who are on the module
19624 	 *    instance of IP stream, give us something to deal with.
19625 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19626 	 *
19627 	 * 3) ICMP replies also could come here.
19628 	 */
19629 	if (DB_TYPE(mp) != M_DATA) {
19630 	    notdata:
19631 		if (DB_TYPE(mp) == M_CTL) {
19632 			/*
19633 			 * M_CTL messages are used by ARP, AH and ESP to
19634 			 * communicate with IP. We deal with IPSEC_IN and
19635 			 * IPSEC_OUT here. ip_wput_nondata handles other
19636 			 * cases.
19637 			 */
19638 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19639 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19640 				first_mp = mp->b_cont;
19641 				first_mp->b_flag &= ~MSGHASREF;
19642 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19643 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19644 				CONN_DEC_REF(connp);
19645 				connp = NULL;
19646 			}
19647 			if (ii->ipsec_info_type == IPSEC_IN) {
19648 				/*
19649 				 * Either this message goes back to
19650 				 * IPSEC for further processing or to
19651 				 * ULP after policy checks.
19652 				 */
19653 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19654 				return;
19655 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19656 				io = (ipsec_out_t *)ii;
19657 				if (io->ipsec_out_proc_begin) {
19658 					/*
19659 					 * IPSEC processing has already started.
19660 					 * Complete it.
19661 					 * IPQoS notes: We don't care what is
19662 					 * in ipsec_out_ill_index since this
19663 					 * won't be processed for IPQoS policies
19664 					 * in ipsec_out_process.
19665 					 */
19666 					ipsec_out_process(q, mp, NULL,
19667 					    io->ipsec_out_ill_index);
19668 					return;
19669 				} else {
19670 					connp = (q->q_next != NULL) ?
19671 					    NULL : Q_TO_CONN(q);
19672 					first_mp = mp;
19673 					mp = mp->b_cont;
19674 					mctl_present = B_TRUE;
19675 				}
19676 				zoneid = io->ipsec_out_zoneid;
19677 				ASSERT(zoneid != ALL_ZONES);
19678 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
19679 				/*
19680 				 * It's an IPsec control message requesting
19681 				 * an SADB update to be sent to the IPsec
19682 				 * hardware acceleration capable ills.
19683 				 */
19684 				ipsec_ctl_t *ipsec_ctl =
19685 				    (ipsec_ctl_t *)mp->b_rptr;
19686 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
19687 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
19688 				mblk_t *cmp = mp->b_cont;
19689 
19690 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
19691 				ASSERT(cmp != NULL);
19692 
19693 				freeb(mp);
19694 				ill_ipsec_capab_send_all(satype, cmp, sa);
19695 				return;
19696 			} else {
19697 				/*
19698 				 * This must be ARP or special TSOL signaling.
19699 				 */
19700 				ip_wput_nondata(NULL, q, mp, NULL);
19701 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19702 				    "ip_wput_end: q %p (%S)", q, "nondata");
19703 				return;
19704 			}
19705 		} else {
19706 			/*
19707 			 * This must be non-(ARP/AH/ESP) messages.
19708 			 */
19709 			ASSERT(!need_decref);
19710 			ip_wput_nondata(NULL, q, mp, NULL);
19711 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19712 			    "ip_wput_end: q %p (%S)", q, "nondata");
19713 			return;
19714 		}
19715 	} else {
19716 		first_mp = mp;
19717 		mctl_present = B_FALSE;
19718 	}
19719 
19720 	ASSERT(first_mp != NULL);
19721 	/*
19722 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
19723 	 * to make sure that this packet goes out on the same interface it
19724 	 * came in. We handle that here.
19725 	 */
19726 	if (mctl_present) {
19727 		uint_t ifindex;
19728 
19729 		io = (ipsec_out_t *)first_mp->b_rptr;
19730 		if (io->ipsec_out_attach_if ||
19731 		    io->ipsec_out_xmit_if ||
19732 		    io->ipsec_out_ip_nexthop) {
19733 			ill_t	*ill;
19734 
19735 			/*
19736 			 * We may have lost the conn context if we are
19737 			 * coming here from ip_newroute(). Copy the
19738 			 * nexthop information.
19739 			 */
19740 			if (io->ipsec_out_ip_nexthop) {
19741 				ip_nexthop = B_TRUE;
19742 				nexthop_addr = io->ipsec_out_nexthop_addr;
19743 
19744 				ipha = (ipha_t *)mp->b_rptr;
19745 				dst = ipha->ipha_dst;
19746 				goto send_from_ill;
19747 			} else {
19748 				ASSERT(io->ipsec_out_ill_index != 0);
19749 				ifindex = io->ipsec_out_ill_index;
19750 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
19751 				    NULL, NULL, NULL, NULL);
19752 				/*
19753 				 * ipsec_out_xmit_if bit is used to tell
19754 				 * ip_wput to use the ill to send outgoing data
19755 				 * as we have no conn when data comes from ICMP
19756 				 * error msg routines. Currently this feature is
19757 				 * only used by ip_mrtun_forward routine.
19758 				 */
19759 				if (io->ipsec_out_xmit_if) {
19760 					xmit_ill = ill;
19761 					if (xmit_ill == NULL) {
19762 						ip1dbg(("ip_output:bad ifindex "
19763 						    "for xmit_ill %d\n",
19764 						    ifindex));
19765 						freemsg(first_mp);
19766 						BUMP_MIB(&ip_mib,
19767 						    ipOutDiscards);
19768 						ASSERT(!need_decref);
19769 						return;
19770 					}
19771 					/* Free up the ipsec_out_t mblk */
19772 					ASSERT(first_mp->b_cont == mp);
19773 					first_mp->b_cont = NULL;
19774 					freeb(first_mp);
19775 					/* Just send the IP header+ICMP+data */
19776 					first_mp = mp;
19777 					ipha = (ipha_t *)mp->b_rptr;
19778 					dst = ipha->ipha_dst;
19779 					goto send_from_ill;
19780 				} else {
19781 					attach_ill = ill;
19782 				}
19783 
19784 				if (attach_ill == NULL) {
19785 					ASSERT(xmit_ill == NULL);
19786 					ip1dbg(("ip_output: bad ifindex for "
19787 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
19788 					    ifindex));
19789 					freemsg(first_mp);
19790 					BUMP_MIB(&ip_mib, ipOutDiscards);
19791 					ASSERT(!need_decref);
19792 					return;
19793 				}
19794 			}
19795 		}
19796 	}
19797 
19798 	ASSERT(xmit_ill == NULL);
19799 
19800 	/* We have a complete IP datagram heading outbound. */
19801 	ipha = (ipha_t *)mp->b_rptr;
19802 
19803 #ifndef SPEED_BEFORE_SAFETY
19804 	/*
19805 	 * Make sure we have a full-word aligned message and that at least
19806 	 * a simple IP header is accessible in the first message.  If not,
19807 	 * try a pullup.
19808 	 */
19809 	if (!OK_32PTR(rptr) ||
19810 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
19811 	    hdrtoosmall:
19812 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
19813 			BUMP_MIB(&ip_mib, ipOutDiscards);
19814 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19815 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
19816 			if (first_mp == NULL)
19817 				first_mp = mp;
19818 			goto drop_pkt;
19819 		}
19820 
19821 		/* This function assumes that mp points to an IPv4 packet. */
19822 		if (is_system_labeled() && q->q_next == NULL &&
19823 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
19824 		    !connp->conn_ulp_labeled) {
19825 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
19826 			    &adjust, connp->conn_mac_exempt);
19827 			ipha = (ipha_t *)mp->b_rptr;
19828 			if (first_mp != NULL)
19829 				first_mp->b_cont = mp;
19830 			if (err != 0) {
19831 				if (first_mp == NULL)
19832 					first_mp = mp;
19833 				if (err == EINVAL)
19834 					goto icmp_parameter_problem;
19835 				ip2dbg(("ip_wput: label check failed (%d)\n",
19836 				    err));
19837 				goto drop_pkt;
19838 			}
19839 			iplen = ntohs(ipha->ipha_length) + adjust;
19840 			ipha->ipha_length = htons(iplen);
19841 		}
19842 
19843 		ipha = (ipha_t *)mp->b_rptr;
19844 		if (first_mp == NULL) {
19845 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
19846 			/*
19847 			 * If we got here because of "goto hdrtoosmall"
19848 			 * We need to attach a IPSEC_OUT.
19849 			 */
19850 			if (connp->conn_out_enforce_policy) {
19851 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
19852 				    NULL, ipha->ipha_protocol)) == NULL)) {
19853 					if (need_decref)
19854 						CONN_DEC_REF(connp);
19855 					return;
19856 				} else {
19857 					ASSERT(mp->b_datap->db_type == M_CTL);
19858 					first_mp = mp;
19859 					mp = mp->b_cont;
19860 					mctl_present = B_TRUE;
19861 				}
19862 			} else {
19863 				first_mp = mp;
19864 				mctl_present = B_FALSE;
19865 			}
19866 		}
19867 	}
19868 #endif
19869 
19870 	/* Most of the code below is written for speed, not readability */
19871 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19872 
19873 	/*
19874 	 * If ip_newroute() fails, we're going to need a full
19875 	 * header for the icmp wraparound.
19876 	 */
19877 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
19878 		uint_t	v_hlen;
19879 	    version_hdrlen_check:
19880 		ASSERT(first_mp != NULL);
19881 		v_hlen = V_HLEN;
19882 		/*
19883 		 * siphon off IPv6 packets coming down from transport
19884 		 * layer modules here.
19885 		 * Note: high-order bit carries NUD reachability confirmation
19886 		 */
19887 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
19888 			/*
19889 			 * XXX implement a IPv4 and IPv6 packet counter per
19890 			 * conn and switch when ratio exceeds e.g. 10:1
19891 			 */
19892 #ifdef notyet
19893 			if (q->q_next == NULL) /* Avoid ill queue */
19894 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
19895 #endif
19896 			BUMP_MIB(&ip_mib, ipOutIPv6);
19897 			ASSERT(xmit_ill == NULL);
19898 			if (attach_ill != NULL)
19899 				ill_refrele(attach_ill);
19900 			if (need_decref)
19901 				mp->b_flag |= MSGHASREF;
19902 			(void) ip_output_v6(connp, first_mp, q, caller);
19903 			return;
19904 		}
19905 
19906 		if ((v_hlen >> 4) != IP_VERSION) {
19907 			BUMP_MIB(&ip_mib, ipOutDiscards);
19908 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19909 			    "ip_wput_end: q %p (%S)", q, "badvers");
19910 			goto drop_pkt;
19911 		}
19912 		/*
19913 		 * Is the header length at least 20 bytes?
19914 		 *
19915 		 * Are there enough bytes accessible in the header?  If
19916 		 * not, try a pullup.
19917 		 */
19918 		v_hlen &= 0xF;
19919 		v_hlen <<= 2;
19920 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
19921 			BUMP_MIB(&ip_mib, ipOutDiscards);
19922 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19923 			    "ip_wput_end: q %p (%S)", q, "badlen");
19924 			goto drop_pkt;
19925 		}
19926 		if (v_hlen > (mp->b_wptr - rptr)) {
19927 			if (!pullupmsg(mp, v_hlen)) {
19928 				BUMP_MIB(&ip_mib, ipOutDiscards);
19929 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19930 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
19931 				goto drop_pkt;
19932 			}
19933 			ipha = (ipha_t *)mp->b_rptr;
19934 		}
19935 		/*
19936 		 * Move first entry from any source route into ipha_dst and
19937 		 * verify the options
19938 		 */
19939 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
19940 			ASSERT(xmit_ill == NULL);
19941 			if (attach_ill != NULL)
19942 				ill_refrele(attach_ill);
19943 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19944 			    "ip_wput_end: q %p (%S)", q, "badopts");
19945 			if (need_decref)
19946 				CONN_DEC_REF(connp);
19947 			return;
19948 		}
19949 	}
19950 	dst = ipha->ipha_dst;
19951 
19952 	/*
19953 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
19954 	 * we have to run the packet through ip_newroute which will take
19955 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
19956 	 * a resolver, or assigning a default gateway, etc.
19957 	 */
19958 	if (CLASSD(dst)) {
19959 		ipif_t	*ipif;
19960 		uint32_t setsrc = 0;
19961 
19962 	    multicast:
19963 		ASSERT(first_mp != NULL);
19964 		ASSERT(xmit_ill == NULL);
19965 		ip2dbg(("ip_wput: CLASSD\n"));
19966 		if (connp == NULL) {
19967 			/*
19968 			 * Use the first good ipif on the ill.
19969 			 * XXX Should this ever happen? (Appears
19970 			 * to show up with just ppp and no ethernet due
19971 			 * to in.rdisc.)
19972 			 * However, ire_send should be able to
19973 			 * call ip_wput_ire directly.
19974 			 *
19975 			 * XXX Also, this can happen for ICMP and other packets
19976 			 * with multicast source addresses.  Perhaps we should
19977 			 * fix things so that we drop the packet in question,
19978 			 * but for now, just run with it.
19979 			 */
19980 			ill_t *ill = (ill_t *)q->q_ptr;
19981 
19982 			/*
19983 			 * Don't honor attach_if for this case. If ill
19984 			 * is part of the group, ipif could belong to
19985 			 * any ill and we cannot maintain attach_ill
19986 			 * and ipif_ill same anymore and the assert
19987 			 * below would fail.
19988 			 */
19989 			if (mctl_present) {
19990 				io->ipsec_out_ill_index = 0;
19991 				io->ipsec_out_attach_if = B_FALSE;
19992 				ASSERT(attach_ill != NULL);
19993 				ill_refrele(attach_ill);
19994 				attach_ill = NULL;
19995 			}
19996 
19997 			ASSERT(attach_ill == NULL);
19998 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
19999 			if (ipif == NULL) {
20000 				if (need_decref)
20001 					CONN_DEC_REF(connp);
20002 				freemsg(first_mp);
20003 				return;
20004 			}
20005 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20006 			    ntohl(dst), ill->ill_name));
20007 		} else {
20008 			/*
20009 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
20010 			 * IP_XMIT_IF is honoured.
20011 			 * Block comment above this function explains the
20012 			 * locking mechanism used here
20013 			 */
20014 			xmit_ill = conn_get_held_ill(connp,
20015 			    &connp->conn_xmit_if_ill, &err);
20016 			if (err == ILL_LOOKUP_FAILED) {
20017 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
20018 				goto drop_pkt;
20019 			}
20020 			if (xmit_ill == NULL) {
20021 				ipif = conn_get_held_ipif(connp,
20022 				    &connp->conn_multicast_ipif, &err);
20023 				if (err == IPIF_LOOKUP_FAILED) {
20024 					ip1dbg(("ip_wput: No ipif for "
20025 					    "multicast\n"));
20026 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20027 					goto drop_pkt;
20028 				}
20029 			}
20030 			if (xmit_ill != NULL) {
20031 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20032 				if (ipif == NULL) {
20033 					ip1dbg(("ip_wput: No ipif for "
20034 					    "IP_XMIT_IF\n"));
20035 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20036 					goto drop_pkt;
20037 				}
20038 			} else if (ipif == NULL || ipif->ipif_isv6) {
20039 				/*
20040 				 * We must do this ipif determination here
20041 				 * else we could pass through ip_newroute
20042 				 * and come back here without the conn context.
20043 				 *
20044 				 * Note: we do late binding i.e. we bind to
20045 				 * the interface when the first packet is sent.
20046 				 * For performance reasons we do not rebind on
20047 				 * each packet but keep the binding until the
20048 				 * next IP_MULTICAST_IF option.
20049 				 *
20050 				 * conn_multicast_{ipif,ill} are shared between
20051 				 * IPv4 and IPv6 and AF_INET6 sockets can
20052 				 * send both IPv4 and IPv6 packets. Hence
20053 				 * we have to check that "isv6" matches above.
20054 				 */
20055 				if (ipif != NULL)
20056 					ipif_refrele(ipif);
20057 				ipif = ipif_lookup_group(dst, zoneid);
20058 				if (ipif == NULL) {
20059 					ip1dbg(("ip_wput: No ipif for "
20060 					    "multicast\n"));
20061 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20062 					goto drop_pkt;
20063 				}
20064 				err = conn_set_held_ipif(connp,
20065 				    &connp->conn_multicast_ipif, ipif);
20066 				if (err == IPIF_LOOKUP_FAILED) {
20067 					ipif_refrele(ipif);
20068 					ip1dbg(("ip_wput: No ipif for "
20069 					    "multicast\n"));
20070 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20071 					goto drop_pkt;
20072 				}
20073 			}
20074 		}
20075 		ASSERT(!ipif->ipif_isv6);
20076 		/*
20077 		 * As we may lose the conn by the time we reach ip_wput_ire,
20078 		 * we copy conn_multicast_loop and conn_dontroute on to an
20079 		 * ipsec_out. In case if this datagram goes out secure,
20080 		 * we need the ill_index also. Copy that also into the
20081 		 * ipsec_out.
20082 		 */
20083 		if (mctl_present) {
20084 			io = (ipsec_out_t *)first_mp->b_rptr;
20085 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20086 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20087 		} else {
20088 			ASSERT(mp == first_mp);
20089 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20090 			    BPRI_HI)) == NULL) {
20091 				ipif_refrele(ipif);
20092 				first_mp = mp;
20093 				goto drop_pkt;
20094 			}
20095 			first_mp->b_datap->db_type = M_CTL;
20096 			first_mp->b_wptr += sizeof (ipsec_info_t);
20097 			/* ipsec_out_secure is B_FALSE now */
20098 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20099 			io = (ipsec_out_t *)first_mp->b_rptr;
20100 			io->ipsec_out_type = IPSEC_OUT;
20101 			io->ipsec_out_len = sizeof (ipsec_out_t);
20102 			io->ipsec_out_use_global_policy = B_TRUE;
20103 			first_mp->b_cont = mp;
20104 			mctl_present = B_TRUE;
20105 		}
20106 		if (attach_ill != NULL) {
20107 			ASSERT(attach_ill == ipif->ipif_ill);
20108 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20109 
20110 			/*
20111 			 * Check if we need an ire that will not be
20112 			 * looked up by anybody else i.e. HIDDEN.
20113 			 */
20114 			if (ill_is_probeonly(attach_ill)) {
20115 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20116 			}
20117 			io->ipsec_out_ill_index =
20118 			    attach_ill->ill_phyint->phyint_ifindex;
20119 			io->ipsec_out_attach_if = B_TRUE;
20120 		} else {
20121 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20122 			io->ipsec_out_ill_index =
20123 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20124 		}
20125 		if (connp != NULL) {
20126 			io->ipsec_out_multicast_loop =
20127 			    connp->conn_multicast_loop;
20128 			io->ipsec_out_dontroute = connp->conn_dontroute;
20129 			io->ipsec_out_zoneid = connp->conn_zoneid;
20130 		}
20131 		/*
20132 		 * If the application uses IP_MULTICAST_IF with
20133 		 * different logical addresses of the same ILL, we
20134 		 * need to make sure that the soruce address of
20135 		 * the packet matches the logical IP address used
20136 		 * in the option. We do it by initializing ipha_src
20137 		 * here. This should keep IPSEC also happy as
20138 		 * when we return from IPSEC processing, we don't
20139 		 * have to worry about getting the right address on
20140 		 * the packet. Thus it is sufficient to look for
20141 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20142 		 * MATCH_IRE_IPIF.
20143 		 *
20144 		 * NOTE : We need to do it for non-secure case also as
20145 		 * this might go out secure if there is a global policy
20146 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20147 		 * address, the source should be initialized already and
20148 		 * hence we won't be initializing here.
20149 		 *
20150 		 * As we do not have the ire yet, it is possible that
20151 		 * we set the source address here and then later discover
20152 		 * that the ire implies the source address to be assigned
20153 		 * through the RTF_SETSRC flag.
20154 		 * In that case, the setsrc variable will remind us
20155 		 * that overwritting the source address by the one
20156 		 * of the RTF_SETSRC-flagged ire is allowed.
20157 		 */
20158 		if (ipha->ipha_src == INADDR_ANY &&
20159 		    (connp == NULL || !connp->conn_unspec_src)) {
20160 			ipha->ipha_src = ipif->ipif_src_addr;
20161 			setsrc = RTF_SETSRC;
20162 		}
20163 		/*
20164 		 * Find an IRE which matches the destination and the outgoing
20165 		 * queue (i.e. the outgoing interface.)
20166 		 * For loopback use a unicast IP address for
20167 		 * the ire lookup.
20168 		 */
20169 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20170 		    PHYI_LOOPBACK) {
20171 			dst = ipif->ipif_lcl_addr;
20172 		}
20173 		/*
20174 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20175 		 * We don't need to lookup ire in ctable as the packet
20176 		 * needs to be sent to the destination through the specified
20177 		 * ill irrespective of ires in the cache table.
20178 		 */
20179 		ire = NULL;
20180 		if (xmit_ill == NULL) {
20181 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20182 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20183 		}
20184 
20185 		/*
20186 		 * refrele attach_ill as its not needed anymore.
20187 		 */
20188 		if (attach_ill != NULL) {
20189 			ill_refrele(attach_ill);
20190 			attach_ill = NULL;
20191 		}
20192 
20193 		if (ire == NULL) {
20194 			/*
20195 			 * Multicast loopback and multicast forwarding is
20196 			 * done in ip_wput_ire.
20197 			 *
20198 			 * Mark this packet to make it be delivered to
20199 			 * ip_wput_ire after the new ire has been
20200 			 * created.
20201 			 *
20202 			 * The call to ip_newroute_ipif takes into account
20203 			 * the setsrc reminder. In any case, we take care
20204 			 * of the RTF_MULTIRT flag.
20205 			 */
20206 			mp->b_prev = mp->b_next = NULL;
20207 			if (xmit_ill == NULL ||
20208 			    xmit_ill->ill_ipif_up_count > 0) {
20209 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20210 				    setsrc | RTF_MULTIRT);
20211 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20212 				    "ip_wput_end: q %p (%S)", q, "noire");
20213 			} else {
20214 				freemsg(first_mp);
20215 			}
20216 			ipif_refrele(ipif);
20217 			if (xmit_ill != NULL)
20218 				ill_refrele(xmit_ill);
20219 			if (need_decref)
20220 				CONN_DEC_REF(connp);
20221 			return;
20222 		}
20223 
20224 		ipif_refrele(ipif);
20225 		ipif = NULL;
20226 		ASSERT(xmit_ill == NULL);
20227 
20228 		/*
20229 		 * Honor the RTF_SETSRC flag for multicast packets,
20230 		 * if allowed by the setsrc reminder.
20231 		 */
20232 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20233 			ipha->ipha_src = ire->ire_src_addr;
20234 		}
20235 
20236 		/*
20237 		 * Unconditionally force the TTL to 1 for
20238 		 * multirouted multicast packets:
20239 		 * multirouted multicast should not cross
20240 		 * multicast routers.
20241 		 */
20242 		if (ire->ire_flags & RTF_MULTIRT) {
20243 			if (ipha->ipha_ttl > 1) {
20244 				ip2dbg(("ip_wput: forcing multicast "
20245 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20246 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20247 				ipha->ipha_ttl = 1;
20248 			}
20249 		}
20250 	} else {
20251 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20252 		if ((ire != NULL) && (ire->ire_type &
20253 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20254 			ignore_dontroute = B_TRUE;
20255 			ignore_nexthop = B_TRUE;
20256 		}
20257 		if (ire != NULL) {
20258 			ire_refrele(ire);
20259 			ire = NULL;
20260 		}
20261 		/*
20262 		 * Guard against coming in from arp in which case conn is NULL.
20263 		 * Also guard against non M_DATA with dontroute set but
20264 		 * destined to local, loopback or broadcast addresses.
20265 		 */
20266 		if (connp != NULL && connp->conn_dontroute &&
20267 		    !ignore_dontroute) {
20268 dontroute:
20269 			/*
20270 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20271 			 * routing protocols from seeing false direct
20272 			 * connectivity.
20273 			 */
20274 			ipha->ipha_ttl = 1;
20275 			/*
20276 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20277 			 * along with SO_DONTROUTE, higher precedence is
20278 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20279 			 */
20280 			if (connp->conn_xmit_if_ill == NULL) {
20281 				/* If suitable ipif not found, drop packet */
20282 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20283 				if (dst_ipif == NULL) {
20284 					ip1dbg(("ip_wput: no route for "
20285 					    "dst using SO_DONTROUTE\n"));
20286 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20287 					mp->b_prev = mp->b_next = NULL;
20288 					if (first_mp == NULL)
20289 						first_mp = mp;
20290 					goto drop_pkt;
20291 				} else {
20292 					/*
20293 					 * If suitable ipif has been found, set
20294 					 * xmit_ill to the corresponding
20295 					 * ipif_ill because we'll be following
20296 					 * the IP_XMIT_IF logic.
20297 					 */
20298 					ASSERT(xmit_ill == NULL);
20299 					xmit_ill = dst_ipif->ipif_ill;
20300 					mutex_enter(&xmit_ill->ill_lock);
20301 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20302 						mutex_exit(&xmit_ill->ill_lock);
20303 						xmit_ill = NULL;
20304 						ipif_refrele(dst_ipif);
20305 						ip1dbg(("ip_wput: no route for"
20306 						    " dst using"
20307 						    " SO_DONTROUTE\n"));
20308 						BUMP_MIB(&ip_mib,
20309 						    ipOutNoRoutes);
20310 						mp->b_prev = mp->b_next = NULL;
20311 						if (first_mp == NULL)
20312 							first_mp = mp;
20313 						goto drop_pkt;
20314 					}
20315 					ill_refhold_locked(xmit_ill);
20316 					mutex_exit(&xmit_ill->ill_lock);
20317 					ipif_refrele(dst_ipif);
20318 				}
20319 			}
20320 
20321 		}
20322 		/*
20323 		 * If we are bound to IPIF_NOFAILOVER address, look for
20324 		 * an IRE_CACHE matching the ill.
20325 		 */
20326 send_from_ill:
20327 		if (attach_ill != NULL) {
20328 			ipif_t	*attach_ipif;
20329 
20330 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20331 
20332 			/*
20333 			 * Check if we need an ire that will not be
20334 			 * looked up by anybody else i.e. HIDDEN.
20335 			 */
20336 			if (ill_is_probeonly(attach_ill)) {
20337 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20338 			}
20339 
20340 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20341 			if (attach_ipif == NULL) {
20342 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20343 				goto drop_pkt;
20344 			}
20345 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20346 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20347 			ipif_refrele(attach_ipif);
20348 		} else if (xmit_ill != NULL || (connp != NULL &&
20349 			    connp->conn_xmit_if_ill != NULL)) {
20350 			/*
20351 			 * Mark this packet as originated locally
20352 			 */
20353 			mp->b_prev = mp->b_next = NULL;
20354 			/*
20355 			 * xmit_ill could be NULL if SO_DONTROUTE
20356 			 * is also set.
20357 			 */
20358 			if (xmit_ill == NULL) {
20359 				xmit_ill = conn_get_held_ill(connp,
20360 				    &connp->conn_xmit_if_ill, &err);
20361 				if (err == ILL_LOOKUP_FAILED) {
20362 					if (need_decref)
20363 						CONN_DEC_REF(connp);
20364 					freemsg(first_mp);
20365 					return;
20366 				}
20367 				if (xmit_ill == NULL) {
20368 					if (connp->conn_dontroute)
20369 						goto dontroute;
20370 					goto send_from_ill;
20371 				}
20372 			}
20373 			/*
20374 			 * could be SO_DONTROUTE case also.
20375 			 * check at least one interface is UP as
20376 			 * spcified by this ILL, and then call
20377 			 * ip_newroute_ipif()
20378 			 */
20379 			if (xmit_ill->ill_ipif_up_count > 0) {
20380 				ipif_t *ipif;
20381 
20382 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20383 				if (ipif != NULL) {
20384 					ip_newroute_ipif(q, first_mp, ipif,
20385 					    dst, connp, 0);
20386 					ipif_refrele(ipif);
20387 					ip1dbg(("ip_wput: ip_unicast_if\n"));
20388 				}
20389 			} else {
20390 				freemsg(first_mp);
20391 			}
20392 			ill_refrele(xmit_ill);
20393 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20394 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
20395 			if (need_decref)
20396 				CONN_DEC_REF(connp);
20397 			return;
20398 		} else if (ip_nexthop || (connp != NULL &&
20399 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
20400 			if (!ip_nexthop) {
20401 				ip_nexthop = B_TRUE;
20402 				nexthop_addr = connp->conn_nexthop_v4;
20403 			}
20404 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
20405 			    MATCH_IRE_GW;
20406 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
20407 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
20408 		} else {
20409 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20410 		}
20411 		if (!ire) {
20412 			/*
20413 			 * Make sure we don't load spread if this
20414 			 * is IPIF_NOFAILOVER case.
20415 			 */
20416 			if ((attach_ill != NULL) ||
20417 			    (ip_nexthop && !ignore_nexthop)) {
20418 				if (mctl_present) {
20419 					io = (ipsec_out_t *)first_mp->b_rptr;
20420 					ASSERT(first_mp->b_datap->db_type ==
20421 					    M_CTL);
20422 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
20423 				} else {
20424 					ASSERT(mp == first_mp);
20425 					first_mp = allocb(
20426 					    sizeof (ipsec_info_t), BPRI_HI);
20427 					if (first_mp == NULL) {
20428 						first_mp = mp;
20429 						goto drop_pkt;
20430 					}
20431 					first_mp->b_datap->db_type = M_CTL;
20432 					first_mp->b_wptr +=
20433 					    sizeof (ipsec_info_t);
20434 					/* ipsec_out_secure is B_FALSE now */
20435 					bzero(first_mp->b_rptr,
20436 					    sizeof (ipsec_info_t));
20437 					io = (ipsec_out_t *)first_mp->b_rptr;
20438 					io->ipsec_out_type = IPSEC_OUT;
20439 					io->ipsec_out_len =
20440 					    sizeof (ipsec_out_t);
20441 					io->ipsec_out_use_global_policy =
20442 					    B_TRUE;
20443 					first_mp->b_cont = mp;
20444 					mctl_present = B_TRUE;
20445 				}
20446 				if (attach_ill != NULL) {
20447 					io->ipsec_out_ill_index = attach_ill->
20448 					    ill_phyint->phyint_ifindex;
20449 					io->ipsec_out_attach_if = B_TRUE;
20450 				} else {
20451 					io->ipsec_out_ip_nexthop = ip_nexthop;
20452 					io->ipsec_out_nexthop_addr =
20453 					    nexthop_addr;
20454 				}
20455 			}
20456 noirefound:
20457 			/*
20458 			 * Mark this packet as having originated on
20459 			 * this machine.  This will be noted in
20460 			 * ire_add_then_send, which needs to know
20461 			 * whether to run it back through ip_wput or
20462 			 * ip_rput following successful resolution.
20463 			 */
20464 			mp->b_prev = NULL;
20465 			mp->b_next = NULL;
20466 			ip_newroute(q, first_mp, dst, NULL, connp);
20467 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20468 			    "ip_wput_end: q %p (%S)", q, "newroute");
20469 			if (attach_ill != NULL)
20470 				ill_refrele(attach_ill);
20471 			if (xmit_ill != NULL)
20472 				ill_refrele(xmit_ill);
20473 			if (need_decref)
20474 				CONN_DEC_REF(connp);
20475 			return;
20476 		}
20477 	}
20478 
20479 	/* We now know where we are going with it. */
20480 
20481 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20482 	    "ip_wput_end: q %p (%S)", q, "end");
20483 
20484 	/*
20485 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20486 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
20487 	 */
20488 	if (ire->ire_flags & RTF_MULTIRT) {
20489 		/*
20490 		 * Force the TTL of multirouted packets if required.
20491 		 * The TTL of such packets is bounded by the
20492 		 * ip_multirt_ttl ndd variable.
20493 		 */
20494 		if ((ip_multirt_ttl > 0) &&
20495 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20496 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20497 			    "(was %d), dst 0x%08x\n",
20498 			    ip_multirt_ttl, ipha->ipha_ttl,
20499 			    ntohl(ire->ire_addr)));
20500 			ipha->ipha_ttl = ip_multirt_ttl;
20501 		}
20502 		/*
20503 		 * At this point, we check to see if there are any pending
20504 		 * unresolved routes. ire_multirt_resolvable()
20505 		 * checks in O(n) that all IRE_OFFSUBNET ire
20506 		 * entries for the packet's destination and
20507 		 * flagged RTF_MULTIRT are currently resolved.
20508 		 * If some remain unresolved, we make a copy
20509 		 * of the current message. It will be used
20510 		 * to initiate additional route resolutions.
20511 		 */
20512 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20513 		    MBLK_GETLABEL(first_mp));
20514 		ip2dbg(("ip_wput[noirefound]: ire %p, "
20515 		    "multirt_need_resolve %d, first_mp %p\n",
20516 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20517 		if (multirt_need_resolve) {
20518 			copy_mp = copymsg(first_mp);
20519 			if (copy_mp != NULL) {
20520 				MULTIRT_DEBUG_TAG(copy_mp);
20521 			}
20522 		}
20523 	}
20524 
20525 	ip_wput_ire(q, first_mp, ire, connp, caller);
20526 	/*
20527 	 * Try to resolve another multiroute if
20528 	 * ire_multirt_resolvable() deemed it necessary.
20529 	 * At this point, we need to distinguish
20530 	 * multicasts from other packets. For multicasts,
20531 	 * we call ip_newroute_ipif() and request that both
20532 	 * multirouting and setsrc flags are checked.
20533 	 */
20534 	if (copy_mp != NULL) {
20535 		if (CLASSD(dst)) {
20536 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
20537 			if (ipif) {
20538 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
20539 				    RTF_SETSRC | RTF_MULTIRT);
20540 				ipif_refrele(ipif);
20541 			} else {
20542 				MULTIRT_DEBUG_UNTAG(copy_mp);
20543 				freemsg(copy_mp);
20544 				copy_mp = NULL;
20545 			}
20546 		} else {
20547 			ip_newroute(q, copy_mp, dst, NULL, connp);
20548 		}
20549 	}
20550 	if (attach_ill != NULL)
20551 		ill_refrele(attach_ill);
20552 	if (xmit_ill != NULL)
20553 		ill_refrele(xmit_ill);
20554 	if (need_decref)
20555 		CONN_DEC_REF(connp);
20556 	return;
20557 
20558 icmp_parameter_problem:
20559 	/* could not have originated externally */
20560 	ASSERT(mp->b_prev == NULL);
20561 	if (ip_hdr_complete(ipha, zoneid) == 0) {
20562 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
20563 		/* it's the IP header length that's in trouble */
20564 		icmp_param_problem(q, first_mp, 0);
20565 		first_mp = NULL;
20566 	}
20567 
20568 drop_pkt:
20569 	ip1dbg(("ip_wput: dropped packet\n"));
20570 	if (ire != NULL)
20571 		ire_refrele(ire);
20572 	if (need_decref)
20573 		CONN_DEC_REF(connp);
20574 	freemsg(first_mp);
20575 	if (attach_ill != NULL)
20576 		ill_refrele(attach_ill);
20577 	if (xmit_ill != NULL)
20578 		ill_refrele(xmit_ill);
20579 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20580 	    "ip_wput_end: q %p (%S)", q, "droppkt");
20581 }
20582 
20583 void
20584 ip_wput(queue_t *q, mblk_t *mp)
20585 {
20586 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20587 }
20588 
20589 /*
20590  *
20591  * The following rules must be observed when accessing any ipif or ill
20592  * that has been cached in the conn. Typically conn_nofailover_ill,
20593  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20594  *
20595  * Access: The ipif or ill pointed to from the conn can be accessed under
20596  * the protection of the conn_lock or after it has been refheld under the
20597  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20598  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20599  * The reason for this is that a concurrent unplumb could actually be
20600  * cleaning up these cached pointers by walking the conns and might have
20601  * finished cleaning up the conn in question. The macros check that an
20602  * unplumb has not yet started on the ipif or ill.
20603  *
20604  * Caching: An ipif or ill pointer may be cached in the conn only after
20605  * making sure that an unplumb has not started. So the caching is done
20606  * while holding both the conn_lock and the ill_lock and after using the
20607  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20608  * flag before starting the cleanup of conns.
20609  *
20610  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20611  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20612  * or a reference to the ipif or a reference to an ire that references the
20613  * ipif. An ipif does not change its ill except for failover/failback. Since
20614  * failover/failback happens only after bringing down the ipif and making sure
20615  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20616  * the above holds.
20617  */
20618 ipif_t *
20619 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20620 {
20621 	ipif_t	*ipif;
20622 	ill_t	*ill;
20623 
20624 	*err = 0;
20625 	rw_enter(&ill_g_lock, RW_READER);
20626 	mutex_enter(&connp->conn_lock);
20627 	ipif = *ipifp;
20628 	if (ipif != NULL) {
20629 		ill = ipif->ipif_ill;
20630 		mutex_enter(&ill->ill_lock);
20631 		if (IPIF_CAN_LOOKUP(ipif)) {
20632 			ipif_refhold_locked(ipif);
20633 			mutex_exit(&ill->ill_lock);
20634 			mutex_exit(&connp->conn_lock);
20635 			rw_exit(&ill_g_lock);
20636 			return (ipif);
20637 		} else {
20638 			*err = IPIF_LOOKUP_FAILED;
20639 		}
20640 		mutex_exit(&ill->ill_lock);
20641 	}
20642 	mutex_exit(&connp->conn_lock);
20643 	rw_exit(&ill_g_lock);
20644 	return (NULL);
20645 }
20646 
20647 ill_t *
20648 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20649 {
20650 	ill_t	*ill;
20651 
20652 	*err = 0;
20653 	mutex_enter(&connp->conn_lock);
20654 	ill = *illp;
20655 	if (ill != NULL) {
20656 		mutex_enter(&ill->ill_lock);
20657 		if (ILL_CAN_LOOKUP(ill)) {
20658 			ill_refhold_locked(ill);
20659 			mutex_exit(&ill->ill_lock);
20660 			mutex_exit(&connp->conn_lock);
20661 			return (ill);
20662 		} else {
20663 			*err = ILL_LOOKUP_FAILED;
20664 		}
20665 		mutex_exit(&ill->ill_lock);
20666 	}
20667 	mutex_exit(&connp->conn_lock);
20668 	return (NULL);
20669 }
20670 
20671 static int
20672 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
20673 {
20674 	ill_t	*ill;
20675 
20676 	ill = ipif->ipif_ill;
20677 	mutex_enter(&connp->conn_lock);
20678 	mutex_enter(&ill->ill_lock);
20679 	if (IPIF_CAN_LOOKUP(ipif)) {
20680 		*ipifp = ipif;
20681 		mutex_exit(&ill->ill_lock);
20682 		mutex_exit(&connp->conn_lock);
20683 		return (0);
20684 	}
20685 	mutex_exit(&ill->ill_lock);
20686 	mutex_exit(&connp->conn_lock);
20687 	return (IPIF_LOOKUP_FAILED);
20688 }
20689 
20690 /*
20691  * This is called if the outbound datagram needs fragmentation.
20692  *
20693  * NOTE : This function does not ire_refrele the ire argument passed in.
20694  */
20695 static void
20696 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
20697 {
20698 	ipha_t		*ipha;
20699 	mblk_t		*mp;
20700 	uint32_t	v_hlen_tos_len;
20701 	uint32_t	max_frag;
20702 	uint32_t	frag_flag;
20703 	boolean_t	dont_use;
20704 
20705 	if (ipsec_mp->b_datap->db_type == M_CTL) {
20706 		mp = ipsec_mp->b_cont;
20707 	} else {
20708 		mp = ipsec_mp;
20709 	}
20710 
20711 	ipha = (ipha_t *)mp->b_rptr;
20712 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20713 
20714 #ifdef	_BIG_ENDIAN
20715 #define	V_HLEN	(v_hlen_tos_len >> 24)
20716 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20717 #else
20718 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20719 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20720 #endif
20721 
20722 #ifndef SPEED_BEFORE_SAFETY
20723 	/*
20724 	 * Check that ipha_length is consistent with
20725 	 * the mblk length
20726 	 */
20727 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
20728 		ip0dbg(("Packet length mismatch: %d, %ld\n",
20729 		    LENGTH, msgdsize(mp)));
20730 		freemsg(ipsec_mp);
20731 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20732 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
20733 		    "packet length mismatch");
20734 		return;
20735 	}
20736 #endif
20737 	/*
20738 	 * Don't use frag_flag if pre-built packet or source
20739 	 * routed or if multicast (since multicast packets do not solicit
20740 	 * ICMP "packet too big" messages). Get the values of
20741 	 * max_frag and frag_flag atomically by acquiring the
20742 	 * ire_lock.
20743 	 */
20744 	mutex_enter(&ire->ire_lock);
20745 	max_frag = ire->ire_max_frag;
20746 	frag_flag = ire->ire_frag_flag;
20747 	mutex_exit(&ire->ire_lock);
20748 
20749 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
20750 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
20751 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
20752 
20753 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
20754 	    (dont_use ? 0 : frag_flag));
20755 }
20756 
20757 /*
20758  * Used for deciding the MSS size for the upper layer. Thus
20759  * we need to check the outbound policy values in the conn.
20760  */
20761 int
20762 conn_ipsec_length(conn_t *connp)
20763 {
20764 	ipsec_latch_t *ipl;
20765 
20766 	ipl = connp->conn_latch;
20767 	if (ipl == NULL)
20768 		return (0);
20769 
20770 	if (ipl->ipl_out_policy == NULL)
20771 		return (0);
20772 
20773 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
20774 }
20775 
20776 /*
20777  * Returns an estimate of the IPSEC headers size. This is used if
20778  * we don't want to call into IPSEC to get the exact size.
20779  */
20780 int
20781 ipsec_out_extra_length(mblk_t *ipsec_mp)
20782 {
20783 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
20784 	ipsec_action_t *a;
20785 
20786 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
20787 	if (!io->ipsec_out_secure)
20788 		return (0);
20789 
20790 	a = io->ipsec_out_act;
20791 
20792 	if (a == NULL) {
20793 		ASSERT(io->ipsec_out_policy != NULL);
20794 		a = io->ipsec_out_policy->ipsp_act;
20795 	}
20796 	ASSERT(a != NULL);
20797 
20798 	return (a->ipa_ovhd);
20799 }
20800 
20801 /*
20802  * Returns an estimate of the IPSEC headers size. This is used if
20803  * we don't want to call into IPSEC to get the exact size.
20804  */
20805 int
20806 ipsec_in_extra_length(mblk_t *ipsec_mp)
20807 {
20808 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
20809 	ipsec_action_t *a;
20810 
20811 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
20812 
20813 	a = ii->ipsec_in_action;
20814 	return (a == NULL ? 0 : a->ipa_ovhd);
20815 }
20816 
20817 /*
20818  * If there are any source route options, return the true final
20819  * destination. Otherwise, return the destination.
20820  */
20821 ipaddr_t
20822 ip_get_dst(ipha_t *ipha)
20823 {
20824 	ipoptp_t	opts;
20825 	uchar_t		*opt;
20826 	uint8_t		optval;
20827 	uint8_t		optlen;
20828 	ipaddr_t	dst;
20829 	uint32_t off;
20830 
20831 	dst = ipha->ipha_dst;
20832 
20833 	if (IS_SIMPLE_IPH(ipha))
20834 		return (dst);
20835 
20836 	for (optval = ipoptp_first(&opts, ipha);
20837 	    optval != IPOPT_EOL;
20838 	    optval = ipoptp_next(&opts)) {
20839 		opt = opts.ipoptp_cur;
20840 		optlen = opts.ipoptp_len;
20841 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20842 		switch (optval) {
20843 		case IPOPT_SSRR:
20844 		case IPOPT_LSRR:
20845 			off = opt[IPOPT_OFFSET];
20846 			/*
20847 			 * If one of the conditions is true, it means
20848 			 * end of options and dst already has the right
20849 			 * value.
20850 			 */
20851 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
20852 				off = optlen - IP_ADDR_LEN;
20853 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
20854 			}
20855 			return (dst);
20856 		default:
20857 			break;
20858 		}
20859 	}
20860 
20861 	return (dst);
20862 }
20863 
20864 mblk_t *
20865 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
20866     conn_t *connp, boolean_t unspec_src)
20867 {
20868 	ipsec_out_t	*io;
20869 	mblk_t		*first_mp;
20870 	boolean_t policy_present;
20871 
20872 	first_mp = mp;
20873 	if (mp->b_datap->db_type == M_CTL) {
20874 		io = (ipsec_out_t *)first_mp->b_rptr;
20875 		/*
20876 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
20877 		 *
20878 		 * 1) There is per-socket policy (including cached global
20879 		 *    policy).
20880 		 * 2) There is no per-socket policy, but it is
20881 		 *    a multicast packet that needs to go out
20882 		 *    on a specific interface. This is the case
20883 		 *    where (ip_wput and ip_wput_multicast) attaches
20884 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
20885 		 *
20886 		 * In case (2) we check with global policy to
20887 		 * see if there is a match and set the ill_index
20888 		 * appropriately so that we can lookup the ire
20889 		 * properly in ip_wput_ipsec_out.
20890 		 */
20891 
20892 		/*
20893 		 * ipsec_out_use_global_policy is set to B_FALSE
20894 		 * in ipsec_in_to_out(). Refer to that function for
20895 		 * details.
20896 		 */
20897 		if ((io->ipsec_out_latch == NULL) &&
20898 		    (io->ipsec_out_use_global_policy)) {
20899 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
20900 			    ire, connp, unspec_src));
20901 		}
20902 		if (!io->ipsec_out_secure) {
20903 			/*
20904 			 * If this is not a secure packet, drop
20905 			 * the IPSEC_OUT mp and treat it as a clear
20906 			 * packet. This happens when we are sending
20907 			 * a ICMP reply back to a clear packet. See
20908 			 * ipsec_in_to_out() for details.
20909 			 */
20910 			mp = first_mp->b_cont;
20911 			freeb(first_mp);
20912 		}
20913 		return (mp);
20914 	}
20915 	/*
20916 	 * See whether we need to attach a global policy here. We
20917 	 * don't depend on the conn (as it could be null) for deciding
20918 	 * what policy this datagram should go through because it
20919 	 * should have happened in ip_wput if there was some
20920 	 * policy. This normally happens for connections which are not
20921 	 * fully bound preventing us from caching policies in
20922 	 * ip_bind. Packets coming from the TCP listener/global queue
20923 	 * - which are non-hard_bound - could also be affected by
20924 	 * applying policy here.
20925 	 *
20926 	 * If this packet is coming from tcp global queue or listener,
20927 	 * we will be applying policy here.  This may not be *right*
20928 	 * if these packets are coming from the detached connection as
20929 	 * it could have gone in clear before. This happens only if a
20930 	 * TCP connection started when there is no policy and somebody
20931 	 * added policy before it became detached. Thus packets of the
20932 	 * detached connection could go out secure and the other end
20933 	 * would drop it because it will be expecting in clear. The
20934 	 * converse is not true i.e if somebody starts a TCP
20935 	 * connection and deletes the policy, all the packets will
20936 	 * still go out with the policy that existed before deleting
20937 	 * because ip_unbind sends up policy information which is used
20938 	 * by TCP on subsequent ip_wputs. The right solution is to fix
20939 	 * TCP to attach a dummy IPSEC_OUT and set
20940 	 * ipsec_out_use_global_policy to B_FALSE. As this might
20941 	 * affect performance for normal cases, we are not doing it.
20942 	 * Thus, set policy before starting any TCP connections.
20943 	 *
20944 	 * NOTE - We might apply policy even for a hard bound connection
20945 	 * - for which we cached policy in ip_bind - if somebody added
20946 	 * global policy after we inherited the policy in ip_bind.
20947 	 * This means that the packets that were going out in clear
20948 	 * previously would start going secure and hence get dropped
20949 	 * on the other side. To fix this, TCP attaches a dummy
20950 	 * ipsec_out and make sure that we don't apply global policy.
20951 	 */
20952 	if (ipha != NULL)
20953 		policy_present = ipsec_outbound_v4_policy_present;
20954 	else
20955 		policy_present = ipsec_outbound_v6_policy_present;
20956 	if (!policy_present)
20957 		return (mp);
20958 
20959 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
20960 }
20961 
20962 ire_t *
20963 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
20964 {
20965 	ipaddr_t addr;
20966 	ire_t *save_ire;
20967 	irb_t *irb;
20968 	ill_group_t *illgrp;
20969 	int	err;
20970 
20971 	save_ire = ire;
20972 	addr = ire->ire_addr;
20973 
20974 	ASSERT(ire->ire_type == IRE_BROADCAST);
20975 
20976 	illgrp = connp->conn_outgoing_ill->ill_group;
20977 	if (illgrp == NULL) {
20978 		*conn_outgoing_ill = conn_get_held_ill(connp,
20979 		    &connp->conn_outgoing_ill, &err);
20980 		if (err == ILL_LOOKUP_FAILED) {
20981 			ire_refrele(save_ire);
20982 			return (NULL);
20983 		}
20984 		return (save_ire);
20985 	}
20986 	/*
20987 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
20988 	 * If it is part of the group, we need to send on the ire
20989 	 * that has been cleared of IRE_MARK_NORECV and that belongs
20990 	 * to this group. This is okay as IP_BOUND_IF really means
20991 	 * any ill in the group. We depend on the fact that the
20992 	 * first ire in the group is always cleared of IRE_MARK_NORECV
20993 	 * if such an ire exists. This is possible only if you have
20994 	 * at least one ill in the group that has not failed.
20995 	 *
20996 	 * First get to the ire that matches the address and group.
20997 	 *
20998 	 * We don't look for an ire with a matching zoneid because a given zone
20999 	 * won't always have broadcast ires on all ills in the group.
21000 	 */
21001 	irb = ire->ire_bucket;
21002 	rw_enter(&irb->irb_lock, RW_READER);
21003 	if (ire->ire_marks & IRE_MARK_NORECV) {
21004 		/*
21005 		 * If the current zone only has an ire broadcast for this
21006 		 * address marked NORECV, the ire we want is ahead in the
21007 		 * bucket, so we look it up deliberately ignoring the zoneid.
21008 		 */
21009 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21010 			if (ire->ire_addr != addr)
21011 				continue;
21012 			/* skip over deleted ires */
21013 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21014 				continue;
21015 		}
21016 	}
21017 	while (ire != NULL) {
21018 		/*
21019 		 * If a new interface is coming up, we could end up
21020 		 * seeing the loopback ire and the non-loopback ire
21021 		 * may not have been added yet. So check for ire_stq
21022 		 */
21023 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21024 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21025 			break;
21026 		}
21027 		ire = ire->ire_next;
21028 	}
21029 	if (ire != NULL && ire->ire_addr == addr &&
21030 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21031 		IRE_REFHOLD(ire);
21032 		rw_exit(&irb->irb_lock);
21033 		ire_refrele(save_ire);
21034 		*conn_outgoing_ill = ire_to_ill(ire);
21035 		/*
21036 		 * Refhold the ill to make the conn_outgoing_ill
21037 		 * independent of the ire. ip_wput_ire goes in a loop
21038 		 * and may refrele the ire. Since we have an ire at this
21039 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21040 		 */
21041 		ill_refhold(*conn_outgoing_ill);
21042 		return (ire);
21043 	}
21044 	rw_exit(&irb->irb_lock);
21045 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21046 	/*
21047 	 * If we can't find a suitable ire, return the original ire.
21048 	 */
21049 	return (save_ire);
21050 }
21051 
21052 /*
21053  * This function does the ire_refrele of the ire passed in as the
21054  * argument. As this function looks up more ires i.e broadcast ires,
21055  * it needs to REFRELE them. Currently, for simplicity we don't
21056  * differentiate the one passed in and looked up here. We always
21057  * REFRELE.
21058  * IPQoS Notes:
21059  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21060  * IPSec packets are done in ipsec_out_process.
21061  *
21062  */
21063 void
21064 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
21065 {
21066 	ipha_t		*ipha;
21067 #define	rptr	((uchar_t *)ipha)
21068 	queue_t		*stq;
21069 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21070 	uint32_t	v_hlen_tos_len;
21071 	uint32_t	ttl_protocol;
21072 	ipaddr_t	src;
21073 	ipaddr_t	dst;
21074 	uint32_t	cksum;
21075 	ipaddr_t	orig_src;
21076 	ire_t		*ire1;
21077 	mblk_t		*next_mp;
21078 	uint_t		hlen;
21079 	uint16_t	*up;
21080 	uint32_t	max_frag = ire->ire_max_frag;
21081 	ill_t		*ill = ire_to_ill(ire);
21082 	int		clusterwide;
21083 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21084 	int		ipsec_len;
21085 	mblk_t		*first_mp;
21086 	ipsec_out_t	*io;
21087 	boolean_t	conn_dontroute;		/* conn value for multicast */
21088 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21089 	boolean_t	multicast_forward;	/* Should we forward ? */
21090 	boolean_t	unspec_src;
21091 	ill_t		*conn_outgoing_ill = NULL;
21092 	ill_t		*ire_ill;
21093 	ill_t		*ire1_ill;
21094 	uint32_t 	ill_index = 0;
21095 	boolean_t	multirt_send = B_FALSE;
21096 	int		err;
21097 	zoneid_t	zoneid;
21098 	ipxmit_state_t	pktxmit_state;
21099 
21100 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21101 	    "ip_wput_ire_start: q %p", q);
21102 
21103 	multicast_forward = B_FALSE;
21104 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21105 
21106 	if (ire->ire_flags & RTF_MULTIRT) {
21107 		/*
21108 		 * Multirouting case. The bucket where ire is stored
21109 		 * probably holds other RTF_MULTIRT flagged ire
21110 		 * to the destination. In this call to ip_wput_ire,
21111 		 * we attempt to send the packet through all
21112 		 * those ires. Thus, we first ensure that ire is the
21113 		 * first RTF_MULTIRT ire in the bucket,
21114 		 * before walking the ire list.
21115 		 */
21116 		ire_t *first_ire;
21117 		irb_t *irb = ire->ire_bucket;
21118 		ASSERT(irb != NULL);
21119 
21120 		/* Make sure we do not omit any multiroute ire. */
21121 		IRB_REFHOLD(irb);
21122 		for (first_ire = irb->irb_ire;
21123 		    first_ire != NULL;
21124 		    first_ire = first_ire->ire_next) {
21125 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21126 			    (first_ire->ire_addr == ire->ire_addr) &&
21127 			    !(first_ire->ire_marks &
21128 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21129 				break;
21130 		}
21131 
21132 		if ((first_ire != NULL) && (first_ire != ire)) {
21133 			IRE_REFHOLD(first_ire);
21134 			ire_refrele(ire);
21135 			ire = first_ire;
21136 			ill = ire_to_ill(ire);
21137 		}
21138 		IRB_REFRELE(irb);
21139 	}
21140 
21141 	/*
21142 	 * conn_outgoing_ill is used only in the broadcast loop.
21143 	 * for performance we don't grab the mutexs in the fastpath
21144 	 */
21145 	if ((connp != NULL) &&
21146 	    (connp->conn_xmit_if_ill == NULL) &&
21147 	    (ire->ire_type == IRE_BROADCAST) &&
21148 	    ((connp->conn_nofailover_ill != NULL) ||
21149 	    (connp->conn_outgoing_ill != NULL))) {
21150 		/*
21151 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21152 		 * option. So, see if this endpoint is bound to a
21153 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21154 		 * that if the interface is failed, we will still send
21155 		 * the packet on the same ill which is what we want.
21156 		 */
21157 		conn_outgoing_ill = conn_get_held_ill(connp,
21158 		    &connp->conn_nofailover_ill, &err);
21159 		if (err == ILL_LOOKUP_FAILED) {
21160 			ire_refrele(ire);
21161 			freemsg(mp);
21162 			return;
21163 		}
21164 		if (conn_outgoing_ill == NULL) {
21165 			/*
21166 			 * Choose a good ill in the group to send the
21167 			 * packets on.
21168 			 */
21169 			ire = conn_set_outgoing_ill(connp, ire,
21170 			    &conn_outgoing_ill);
21171 			if (ire == NULL) {
21172 				freemsg(mp);
21173 				return;
21174 			}
21175 		}
21176 	}
21177 
21178 	if (mp->b_datap->db_type != M_CTL) {
21179 		ipha = (ipha_t *)mp->b_rptr;
21180 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
21181 	} else {
21182 		io = (ipsec_out_t *)mp->b_rptr;
21183 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21184 		zoneid = io->ipsec_out_zoneid;
21185 		ASSERT(zoneid != ALL_ZONES);
21186 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21187 		dst = ipha->ipha_dst;
21188 		/*
21189 		 * For the multicast case, ipsec_out carries conn_dontroute and
21190 		 * conn_multicast_loop as conn may not be available here. We
21191 		 * need this for multicast loopback and forwarding which is done
21192 		 * later in the code.
21193 		 */
21194 		if (CLASSD(dst)) {
21195 			conn_dontroute = io->ipsec_out_dontroute;
21196 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21197 			/*
21198 			 * If conn_dontroute is not set or conn_multicast_loop
21199 			 * is set, we need to do forwarding/loopback. For
21200 			 * datagrams from ip_wput_multicast, conn_dontroute is
21201 			 * set to B_TRUE and conn_multicast_loop is set to
21202 			 * B_FALSE so that we neither do forwarding nor
21203 			 * loopback.
21204 			 */
21205 			if (!conn_dontroute || conn_multicast_loop)
21206 				multicast_forward = B_TRUE;
21207 		}
21208 	}
21209 
21210 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21211 	    ire->ire_zoneid != ALL_ZONES) {
21212 		/*
21213 		 * When a zone sends a packet to another zone, we try to deliver
21214 		 * the packet under the same conditions as if the destination
21215 		 * was a real node on the network. To do so, we look for a
21216 		 * matching route in the forwarding table.
21217 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21218 		 * ip_newroute() does.
21219 		 */
21220 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21221 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21222 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
21223 		if (src_ire != NULL &&
21224 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
21225 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21226 				ipha->ipha_src = src_ire->ire_src_addr;
21227 			ire_refrele(src_ire);
21228 		} else {
21229 			ire_refrele(ire);
21230 			if (conn_outgoing_ill != NULL)
21231 				ill_refrele(conn_outgoing_ill);
21232 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
21233 			if (src_ire != NULL) {
21234 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21235 					ire_refrele(src_ire);
21236 					freemsg(mp);
21237 					return;
21238 				}
21239 				ire_refrele(src_ire);
21240 			}
21241 			if (ip_hdr_complete(ipha, zoneid)) {
21242 				/* Failed */
21243 				freemsg(mp);
21244 				return;
21245 			}
21246 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
21247 			return;
21248 		}
21249 	}
21250 
21251 	if (mp->b_datap->db_type == M_CTL ||
21252 	    ipsec_outbound_v4_policy_present) {
21253 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21254 		    unspec_src);
21255 		if (mp == NULL) {
21256 			ire_refrele(ire);
21257 			if (conn_outgoing_ill != NULL)
21258 				ill_refrele(conn_outgoing_ill);
21259 			return;
21260 		}
21261 	}
21262 
21263 	first_mp = mp;
21264 	ipsec_len = 0;
21265 
21266 	if (first_mp->b_datap->db_type == M_CTL) {
21267 		io = (ipsec_out_t *)first_mp->b_rptr;
21268 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21269 		mp = first_mp->b_cont;
21270 		ipsec_len = ipsec_out_extra_length(first_mp);
21271 		ASSERT(ipsec_len >= 0);
21272 		zoneid = io->ipsec_out_zoneid;
21273 		ASSERT(zoneid != ALL_ZONES);
21274 
21275 		/*
21276 		 * Drop M_CTL here if IPsec processing is not needed.
21277 		 * (Non-IPsec use of M_CTL extracted any information it
21278 		 * needed above).
21279 		 */
21280 		if (ipsec_len == 0) {
21281 			freeb(first_mp);
21282 			first_mp = mp;
21283 		}
21284 	}
21285 
21286 	/*
21287 	 * Fast path for ip_wput_ire
21288 	 */
21289 
21290 	ipha = (ipha_t *)mp->b_rptr;
21291 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21292 	dst = ipha->ipha_dst;
21293 
21294 	/*
21295 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21296 	 * if the socket is a SOCK_RAW type. The transport checksum should
21297 	 * be provided in the pre-built packet, so we don't need to compute it.
21298 	 * Also, other application set flags, like DF, should not be altered.
21299 	 * Other transport MUST pass down zero.
21300 	 */
21301 	ip_hdr_included = ipha->ipha_ident;
21302 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21303 
21304 	if (CLASSD(dst)) {
21305 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
21306 		    ntohl(dst),
21307 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
21308 		    ntohl(ire->ire_addr)));
21309 	}
21310 
21311 /* Macros to extract header fields from data already in registers */
21312 #ifdef	_BIG_ENDIAN
21313 #define	V_HLEN	(v_hlen_tos_len >> 24)
21314 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21315 #define	PROTO	(ttl_protocol & 0xFF)
21316 #else
21317 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21318 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21319 #define	PROTO	(ttl_protocol >> 8)
21320 #endif
21321 
21322 
21323 	orig_src = src = ipha->ipha_src;
21324 	/* (The loop back to "another" is explained down below.) */
21325 another:;
21326 	/*
21327 	 * Assign an ident value for this packet.  We assign idents on
21328 	 * a per destination basis out of the IRE.  There could be
21329 	 * other threads targeting the same destination, so we have to
21330 	 * arrange for a atomic increment.  Note that we use a 32-bit
21331 	 * atomic add because it has better performance than its
21332 	 * 16-bit sibling.
21333 	 *
21334 	 * If running in cluster mode and if the source address
21335 	 * belongs to a replicated service then vector through
21336 	 * cl_inet_ipident vector to allocate ip identifier
21337 	 * NOTE: This is a contract private interface with the
21338 	 * clustering group.
21339 	 */
21340 	clusterwide = 0;
21341 	if (cl_inet_ipident) {
21342 		ASSERT(cl_inet_isclusterwide);
21343 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21344 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
21345 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
21346 			    AF_INET, (uint8_t *)(uintptr_t)src,
21347 			    (uint8_t *)(uintptr_t)dst);
21348 			clusterwide = 1;
21349 		}
21350 	}
21351 	if (!clusterwide) {
21352 		ipha->ipha_ident =
21353 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
21354 	}
21355 
21356 #ifndef _BIG_ENDIAN
21357 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21358 #endif
21359 
21360 	/*
21361 	 * Set source address unless sent on an ill or conn_unspec_src is set.
21362 	 * This is needed to obey conn_unspec_src when packets go through
21363 	 * ip_newroute + arp.
21364 	 * Assumes ip_newroute{,_multi} sets the source address as well.
21365 	 */
21366 	if (src == INADDR_ANY && !unspec_src) {
21367 		/*
21368 		 * Assign the appropriate source address from the IRE if none
21369 		 * was specified.
21370 		 */
21371 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
21372 
21373 		/*
21374 		 * With IP multipathing, broadcast packets are sent on the ire
21375 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
21376 		 * the group. However, this ire might not be in the same zone so
21377 		 * we can't always use its source address. We look for a
21378 		 * broadcast ire in the same group and in the right zone.
21379 		 */
21380 		if (ire->ire_type == IRE_BROADCAST &&
21381 		    ire->ire_zoneid != zoneid) {
21382 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
21383 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
21384 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
21385 			if (src_ire != NULL) {
21386 				src = src_ire->ire_src_addr;
21387 				ire_refrele(src_ire);
21388 			} else {
21389 				ire_refrele(ire);
21390 				if (conn_outgoing_ill != NULL)
21391 					ill_refrele(conn_outgoing_ill);
21392 				freemsg(first_mp);
21393 				BUMP_MIB(&ip_mib, ipOutDiscards);
21394 				return;
21395 			}
21396 		} else {
21397 			src = ire->ire_src_addr;
21398 		}
21399 
21400 		if (connp == NULL) {
21401 			ip1dbg(("ip_wput_ire: no connp and no src "
21402 			    "address for dst 0x%x, using src 0x%x\n",
21403 			    ntohl(dst),
21404 			    ntohl(src)));
21405 		}
21406 		ipha->ipha_src = src;
21407 	}
21408 	stq = ire->ire_stq;
21409 
21410 	/*
21411 	 * We only allow ire chains for broadcasts since there will
21412 	 * be multiple IRE_CACHE entries for the same multicast
21413 	 * address (one per ipif).
21414 	 */
21415 	next_mp = NULL;
21416 
21417 	/* broadcast packet */
21418 	if (ire->ire_type == IRE_BROADCAST)
21419 		goto broadcast;
21420 
21421 	/* loopback ? */
21422 	if (stq == NULL)
21423 		goto nullstq;
21424 
21425 	/* The ill_index for outbound ILL */
21426 	ill_index = Q_TO_INDEX(stq);
21427 
21428 	BUMP_MIB(&ip_mib, ipOutRequests);
21429 	ttl_protocol = ((uint16_t *)ipha)[4];
21430 
21431 	/* pseudo checksum (do it in parts for IP header checksum) */
21432 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21433 
21434 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
21435 		queue_t *dev_q = stq->q_next;
21436 
21437 		/* flow controlled */
21438 		if ((dev_q->q_next || dev_q->q_first) &&
21439 		    !canput(dev_q))
21440 			goto blocked;
21441 		if ((PROTO == IPPROTO_UDP) &&
21442 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21443 			hlen = (V_HLEN & 0xF) << 2;
21444 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21445 			if (*up != 0) {
21446 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
21447 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
21448 				/* Software checksum? */
21449 				if (DB_CKSUMFLAGS(mp) == 0) {
21450 					IP_STAT(ip_out_sw_cksum);
21451 					IP_STAT_UPDATE(
21452 					    ip_udp_out_sw_cksum_bytes,
21453 					    LENGTH - hlen);
21454 				}
21455 			}
21456 		}
21457 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
21458 		hlen = (V_HLEN & 0xF) << 2;
21459 		if (PROTO == IPPROTO_TCP) {
21460 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21461 			/*
21462 			 * The packet header is processed once and for all, even
21463 			 * in the multirouting case. We disable hardware
21464 			 * checksum if the packet is multirouted, as it will be
21465 			 * replicated via several interfaces, and not all of
21466 			 * them may have this capability.
21467 			 */
21468 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
21469 			    LENGTH, max_frag, ipsec_len, cksum);
21470 			/* Software checksum? */
21471 			if (DB_CKSUMFLAGS(mp) == 0) {
21472 				IP_STAT(ip_out_sw_cksum);
21473 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21474 				    LENGTH - hlen);
21475 			}
21476 		} else {
21477 			sctp_hdr_t	*sctph;
21478 
21479 			ASSERT(PROTO == IPPROTO_SCTP);
21480 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21481 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21482 			/*
21483 			 * Zero out the checksum field to ensure proper
21484 			 * checksum calculation.
21485 			 */
21486 			sctph->sh_chksum = 0;
21487 #ifdef	DEBUG
21488 			if (!skip_sctp_cksum)
21489 #endif
21490 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21491 		}
21492 	}
21493 
21494 	/*
21495 	 * If this is a multicast packet and originated from ip_wput
21496 	 * we need to do loopback and forwarding checks. If it comes
21497 	 * from ip_wput_multicast, we SHOULD not do this.
21498 	 */
21499 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
21500 
21501 	/* checksum */
21502 	cksum += ttl_protocol;
21503 
21504 	/* fragment the packet */
21505 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
21506 		goto fragmentit;
21507 	/*
21508 	 * Don't use frag_flag if packet is pre-built or source
21509 	 * routed or if multicast (since multicast packets do
21510 	 * not solicit ICMP "packet too big" messages).
21511 	 */
21512 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21513 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21514 	    !ip_source_route_included(ipha)) &&
21515 	    !CLASSD(ipha->ipha_dst))
21516 		ipha->ipha_fragment_offset_and_flags |=
21517 		    htons(ire->ire_frag_flag);
21518 
21519 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21520 		/* calculate IP header checksum */
21521 		cksum += ipha->ipha_ident;
21522 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
21523 		cksum += ipha->ipha_fragment_offset_and_flags;
21524 
21525 		/* IP options present */
21526 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21527 		if (hlen)
21528 			goto checksumoptions;
21529 
21530 		/* calculate hdr checksum */
21531 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21532 		cksum = ~(cksum + (cksum >> 16));
21533 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
21534 	}
21535 	if (ipsec_len != 0) {
21536 		/*
21537 		 * We will do the rest of the processing after
21538 		 * we come back from IPSEC in ip_wput_ipsec_out().
21539 		 */
21540 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
21541 
21542 		io = (ipsec_out_t *)first_mp->b_rptr;
21543 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
21544 				ill_phyint->phyint_ifindex;
21545 
21546 		ipsec_out_process(q, first_mp, ire, ill_index);
21547 		ire_refrele(ire);
21548 		if (conn_outgoing_ill != NULL)
21549 			ill_refrele(conn_outgoing_ill);
21550 		return;
21551 	}
21552 
21553 	/*
21554 	 * In most cases, the emission loop below is entered only
21555 	 * once. Only in the case where the ire holds the
21556 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
21557 	 * flagged ires in the bucket, and send the packet
21558 	 * through all crossed RTF_MULTIRT routes.
21559 	 */
21560 	if (ire->ire_flags & RTF_MULTIRT) {
21561 		multirt_send = B_TRUE;
21562 	}
21563 	do {
21564 		if (multirt_send) {
21565 			irb_t *irb;
21566 			/*
21567 			 * We are in a multiple send case, need to get
21568 			 * the next ire and make a duplicate of the packet.
21569 			 * ire1 holds here the next ire to process in the
21570 			 * bucket. If multirouting is expected,
21571 			 * any non-RTF_MULTIRT ire that has the
21572 			 * right destination address is ignored.
21573 			 */
21574 			irb = ire->ire_bucket;
21575 			ASSERT(irb != NULL);
21576 
21577 			IRB_REFHOLD(irb);
21578 			for (ire1 = ire->ire_next;
21579 			    ire1 != NULL;
21580 			    ire1 = ire1->ire_next) {
21581 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21582 					continue;
21583 				if (ire1->ire_addr != ire->ire_addr)
21584 					continue;
21585 				if (ire1->ire_marks &
21586 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21587 					continue;
21588 
21589 				/* Got one */
21590 				IRE_REFHOLD(ire1);
21591 				break;
21592 			}
21593 			IRB_REFRELE(irb);
21594 
21595 			if (ire1 != NULL) {
21596 				next_mp = copyb(mp);
21597 				if ((next_mp == NULL) ||
21598 				    ((mp->b_cont != NULL) &&
21599 				    ((next_mp->b_cont =
21600 				    dupmsg(mp->b_cont)) == NULL))) {
21601 					freemsg(next_mp);
21602 					next_mp = NULL;
21603 					ire_refrele(ire1);
21604 					ire1 = NULL;
21605 				}
21606 			}
21607 
21608 			/* Last multiroute ire; don't loop anymore. */
21609 			if (ire1 == NULL) {
21610 				multirt_send = B_FALSE;
21611 			}
21612 		}
21613 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
21614 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
21615 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
21616 		if ((pktxmit_state == SEND_FAILED) ||
21617 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
21618 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
21619 			    "- packet dropped\n"));
21620 			ire_refrele(ire);
21621 			if (next_mp != NULL) {
21622 				freemsg(next_mp);
21623 				ire_refrele(ire1);
21624 			}
21625 			if (conn_outgoing_ill != NULL)
21626 				ill_refrele(conn_outgoing_ill);
21627 			return;
21628 		}
21629 
21630 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21631 		    "ip_wput_ire_end: q %p (%S)",
21632 		    q, "last copy out");
21633 		IRE_REFRELE(ire);
21634 
21635 		if (multirt_send) {
21636 			ASSERT(ire1);
21637 			/*
21638 			 * Proceed with the next RTF_MULTIRT ire,
21639 			 * Also set up the send-to queue accordingly.
21640 			 */
21641 			ire = ire1;
21642 			ire1 = NULL;
21643 			stq = ire->ire_stq;
21644 			mp = next_mp;
21645 			next_mp = NULL;
21646 			ipha = (ipha_t *)mp->b_rptr;
21647 			ill_index = Q_TO_INDEX(stq);
21648 		}
21649 	} while (multirt_send);
21650 	if (conn_outgoing_ill != NULL)
21651 		ill_refrele(conn_outgoing_ill);
21652 	return;
21653 
21654 	/*
21655 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
21656 	 */
21657 broadcast:
21658 	{
21659 		/*
21660 		 * Avoid broadcast storms by setting the ttl to 1
21661 		 * for broadcasts. This parameter can be set
21662 		 * via ndd, so make sure that for the SO_DONTROUTE
21663 		 * case that ipha_ttl is always set to 1.
21664 		 * In the event that we are replying to incoming
21665 		 * ICMP packets, conn could be NULL.
21666 		 */
21667 		if ((connp != NULL) && connp->conn_dontroute)
21668 			ipha->ipha_ttl = 1;
21669 		else
21670 			ipha->ipha_ttl = ip_broadcast_ttl;
21671 
21672 		/*
21673 		 * Note that we are not doing a IRB_REFHOLD here.
21674 		 * Actually we don't care if the list changes i.e
21675 		 * if somebody deletes an IRE from the list while
21676 		 * we drop the lock, the next time we come around
21677 		 * ire_next will be NULL and hence we won't send
21678 		 * out multiple copies which is fine.
21679 		 */
21680 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
21681 		ire1 = ire->ire_next;
21682 		if (conn_outgoing_ill != NULL) {
21683 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
21684 				ASSERT(ire1 == ire->ire_next);
21685 				if (ire1 != NULL && ire1->ire_addr == dst) {
21686 					ire_refrele(ire);
21687 					ire = ire1;
21688 					IRE_REFHOLD(ire);
21689 					ire1 = ire->ire_next;
21690 					continue;
21691 				}
21692 				rw_exit(&ire->ire_bucket->irb_lock);
21693 				/* Did not find a matching ill */
21694 				ip1dbg(("ip_wput_ire: broadcast with no "
21695 				    "matching IP_BOUND_IF ill %s\n",
21696 				    conn_outgoing_ill->ill_name));
21697 				freemsg(first_mp);
21698 				if (ire != NULL)
21699 					ire_refrele(ire);
21700 				ill_refrele(conn_outgoing_ill);
21701 				return;
21702 			}
21703 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
21704 			/*
21705 			 * If the next IRE has the same address and is not one
21706 			 * of the two copies that we need to send, try to see
21707 			 * whether this copy should be sent at all. This
21708 			 * assumes that we insert loopbacks first and then
21709 			 * non-loopbacks. This is acheived by inserting the
21710 			 * loopback always before non-loopback.
21711 			 * This is used to send a single copy of a broadcast
21712 			 * packet out all physical interfaces that have an
21713 			 * matching IRE_BROADCAST while also looping
21714 			 * back one copy (to ip_wput_local) for each
21715 			 * matching physical interface. However, we avoid
21716 			 * sending packets out different logical that match by
21717 			 * having ipif_up/ipif_down supress duplicate
21718 			 * IRE_BROADCASTS.
21719 			 *
21720 			 * This feature is currently used to get broadcasts
21721 			 * sent to multiple interfaces, when the broadcast
21722 			 * address being used applies to multiple interfaces.
21723 			 * For example, a whole net broadcast will be
21724 			 * replicated on every connected subnet of
21725 			 * the target net.
21726 			 *
21727 			 * Each zone has its own set of IRE_BROADCASTs, so that
21728 			 * we're able to distribute inbound packets to multiple
21729 			 * zones who share a broadcast address. We avoid looping
21730 			 * back outbound packets in different zones but on the
21731 			 * same ill, as the application would see duplicates.
21732 			 *
21733 			 * If the interfaces are part of the same group,
21734 			 * we would want to send only one copy out for
21735 			 * whole group.
21736 			 *
21737 			 * This logic assumes that ire_add_v4() groups the
21738 			 * IRE_BROADCAST entries so that those with the same
21739 			 * ire_addr and ill_group are kept together.
21740 			 */
21741 			ire_ill = ire->ire_ipif->ipif_ill;
21742 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
21743 				if (ire_ill->ill_group != NULL &&
21744 				    (ire->ire_marks & IRE_MARK_NORECV)) {
21745 					/*
21746 					 * If the current zone only has an ire
21747 					 * broadcast for this address marked
21748 					 * NORECV, the ire we want is ahead in
21749 					 * the bucket, so we look it up
21750 					 * deliberately ignoring the zoneid.
21751 					 */
21752 					for (ire1 = ire->ire_bucket->irb_ire;
21753 					    ire1 != NULL;
21754 					    ire1 = ire1->ire_next) {
21755 						ire1_ill =
21756 						    ire1->ire_ipif->ipif_ill;
21757 						if (ire1->ire_addr != dst)
21758 							continue;
21759 						/* skip over the current ire */
21760 						if (ire1 == ire)
21761 							continue;
21762 						/* skip over deleted ires */
21763 						if (ire1->ire_marks &
21764 						    IRE_MARK_CONDEMNED)
21765 							continue;
21766 						/*
21767 						 * non-loopback ire in our
21768 						 * group: use it for the next
21769 						 * pass in the loop
21770 						 */
21771 						if (ire1->ire_stq != NULL &&
21772 						    ire1_ill->ill_group ==
21773 						    ire_ill->ill_group)
21774 							break;
21775 					}
21776 				}
21777 			} else {
21778 				while (ire1 != NULL && ire1->ire_addr == dst) {
21779 					ire1_ill = ire1->ire_ipif->ipif_ill;
21780 					/*
21781 					 * We can have two broadcast ires on the
21782 					 * same ill in different zones; here
21783 					 * we'll send a copy of the packet on
21784 					 * each ill and the fanout code will
21785 					 * call conn_wantpacket() to check that
21786 					 * the zone has the broadcast address
21787 					 * configured on the ill. If the two
21788 					 * ires are in the same group we only
21789 					 * send one copy up.
21790 					 */
21791 					if (ire1_ill != ire_ill &&
21792 					    (ire1_ill->ill_group == NULL ||
21793 					    ire_ill->ill_group == NULL ||
21794 					    ire1_ill->ill_group !=
21795 					    ire_ill->ill_group)) {
21796 						break;
21797 					}
21798 					ire1 = ire1->ire_next;
21799 				}
21800 			}
21801 		}
21802 		ASSERT(multirt_send == B_FALSE);
21803 		if (ire1 != NULL && ire1->ire_addr == dst) {
21804 			if ((ire->ire_flags & RTF_MULTIRT) &&
21805 			    (ire1->ire_flags & RTF_MULTIRT)) {
21806 				/*
21807 				 * We are in the multirouting case.
21808 				 * The message must be sent at least
21809 				 * on both ires. These ires have been
21810 				 * inserted AFTER the standard ones
21811 				 * in ip_rt_add(). There are thus no
21812 				 * other ire entries for the destination
21813 				 * address in the rest of the bucket
21814 				 * that do not have the RTF_MULTIRT
21815 				 * flag. We don't process a copy
21816 				 * of the message here. This will be
21817 				 * done in the final sending loop.
21818 				 */
21819 				multirt_send = B_TRUE;
21820 			} else {
21821 				next_mp = ip_copymsg(first_mp);
21822 				if (next_mp != NULL)
21823 					IRE_REFHOLD(ire1);
21824 			}
21825 		}
21826 		rw_exit(&ire->ire_bucket->irb_lock);
21827 	}
21828 
21829 	if (stq) {
21830 		/*
21831 		 * A non-NULL send-to queue means this packet is going
21832 		 * out of this machine.
21833 		 */
21834 
21835 		BUMP_MIB(&ip_mib, ipOutRequests);
21836 		ttl_protocol = ((uint16_t *)ipha)[4];
21837 		/*
21838 		 * We accumulate the pseudo header checksum in cksum.
21839 		 * This is pretty hairy code, so watch close.  One
21840 		 * thing to keep in mind is that UDP and TCP have
21841 		 * stored their respective datagram lengths in their
21842 		 * checksum fields.  This lines things up real nice.
21843 		 */
21844 		cksum = (dst >> 16) + (dst & 0xFFFF) +
21845 		    (src >> 16) + (src & 0xFFFF);
21846 		/*
21847 		 * We assume the udp checksum field contains the
21848 		 * length, so to compute the pseudo header checksum,
21849 		 * all we need is the protocol number and src/dst.
21850 		 */
21851 		/* Provide the checksums for UDP and TCP. */
21852 		if ((PROTO == IPPROTO_TCP) &&
21853 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21854 			/* hlen gets the number of uchar_ts in the IP header */
21855 			hlen = (V_HLEN & 0xF) << 2;
21856 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21857 			IP_STAT(ip_out_sw_cksum);
21858 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21859 			    LENGTH - hlen);
21860 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
21861 			if (*up == 0)
21862 				*up = 0xFFFF;
21863 		} else if (PROTO == IPPROTO_SCTP &&
21864 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21865 			sctp_hdr_t	*sctph;
21866 
21867 			hlen = (V_HLEN & 0xF) << 2;
21868 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21869 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21870 			sctph->sh_chksum = 0;
21871 #ifdef	DEBUG
21872 			if (!skip_sctp_cksum)
21873 #endif
21874 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21875 		} else {
21876 			queue_t *dev_q = stq->q_next;
21877 
21878 			if ((dev_q->q_next || dev_q->q_first) &&
21879 			    !canput(dev_q)) {
21880 			    blocked:
21881 				ipha->ipha_ident = ip_hdr_included;
21882 				/*
21883 				 * If we don't have a conn to apply
21884 				 * backpressure, free the message.
21885 				 * In the ire_send path, we don't know
21886 				 * the position to requeue the packet. Rather
21887 				 * than reorder packets, we just drop this
21888 				 * packet.
21889 				 */
21890 				if (ip_output_queue && connp != NULL &&
21891 				    caller != IRE_SEND) {
21892 					if (caller == IP_WSRV) {
21893 						connp->conn_did_putbq = 1;
21894 						(void) putbq(connp->conn_wq,
21895 						    first_mp);
21896 						conn_drain_insert(connp);
21897 						/*
21898 						 * This is the service thread,
21899 						 * and the queue is already
21900 						 * noenabled. The check for
21901 						 * canput and the putbq is not
21902 						 * atomic. So we need to check
21903 						 * again.
21904 						 */
21905 						if (canput(stq->q_next))
21906 							connp->conn_did_putbq
21907 							    = 0;
21908 						IP_STAT(ip_conn_flputbq);
21909 					} else {
21910 						/*
21911 						 * We are not the service proc.
21912 						 * ip_wsrv will be scheduled or
21913 						 * is already running.
21914 						 */
21915 						(void) putq(connp->conn_wq,
21916 						    first_mp);
21917 					}
21918 				} else {
21919 					BUMP_MIB(&ip_mib, ipOutDiscards);
21920 					freemsg(first_mp);
21921 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21922 					    "ip_wput_ire_end: q %p (%S)",
21923 					    q, "discard");
21924 				}
21925 				ire_refrele(ire);
21926 				if (next_mp) {
21927 					ire_refrele(ire1);
21928 					freemsg(next_mp);
21929 				}
21930 				if (conn_outgoing_ill != NULL)
21931 					ill_refrele(conn_outgoing_ill);
21932 				return;
21933 			}
21934 			if ((PROTO == IPPROTO_UDP) &&
21935 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
21936 				/*
21937 				 * hlen gets the number of uchar_ts in the
21938 				 * IP header
21939 				 */
21940 				hlen = (V_HLEN & 0xF) << 2;
21941 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21942 				max_frag = ire->ire_max_frag;
21943 				if (*up != 0) {
21944 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
21945 					    up, PROTO, hlen, LENGTH, max_frag,
21946 					    ipsec_len, cksum);
21947 					/* Software checksum? */
21948 					if (DB_CKSUMFLAGS(mp) == 0) {
21949 						IP_STAT(ip_out_sw_cksum);
21950 						IP_STAT_UPDATE(
21951 						    ip_udp_out_sw_cksum_bytes,
21952 						    LENGTH - hlen);
21953 					}
21954 				}
21955 			}
21956 		}
21957 		/*
21958 		 * Need to do this even when fragmenting. The local
21959 		 * loopback can be done without computing checksums
21960 		 * but forwarding out other interface must be done
21961 		 * after the IP checksum (and ULP checksums) have been
21962 		 * computed.
21963 		 *
21964 		 * NOTE : multicast_forward is set only if this packet
21965 		 * originated from ip_wput. For packets originating from
21966 		 * ip_wput_multicast, it is not set.
21967 		 */
21968 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
21969 		    multi_loopback:
21970 			ip2dbg(("ip_wput: multicast, loop %d\n",
21971 			    conn_multicast_loop));
21972 
21973 			/*  Forget header checksum offload */
21974 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
21975 
21976 			/*
21977 			 * Local loopback of multicasts?  Check the
21978 			 * ill.
21979 			 *
21980 			 * Note that the loopback function will not come
21981 			 * in through ip_rput - it will only do the
21982 			 * client fanout thus we need to do an mforward
21983 			 * as well.  The is different from the BSD
21984 			 * logic.
21985 			 */
21986 			if (ill != NULL) {
21987 				ilm_t	*ilm;
21988 
21989 				ILM_WALKER_HOLD(ill);
21990 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
21991 				    ALL_ZONES);
21992 				ILM_WALKER_RELE(ill);
21993 				if (ilm != NULL) {
21994 					/*
21995 					 * Pass along the virtual output q.
21996 					 * ip_wput_local() will distribute the
21997 					 * packet to all the matching zones,
21998 					 * except the sending zone when
21999 					 * IP_MULTICAST_LOOP is false.
22000 					 */
22001 					ip_multicast_loopback(q, ill, first_mp,
22002 					    conn_multicast_loop ? 0 :
22003 					    IP_FF_NO_MCAST_LOOP, zoneid);
22004 				}
22005 			}
22006 			if (ipha->ipha_ttl == 0) {
22007 				/*
22008 				 * 0 => only to this host i.e. we are
22009 				 * done. We are also done if this was the
22010 				 * loopback interface since it is sufficient
22011 				 * to loopback one copy of a multicast packet.
22012 				 */
22013 				freemsg(first_mp);
22014 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22015 				    "ip_wput_ire_end: q %p (%S)",
22016 				    q, "loopback");
22017 				ire_refrele(ire);
22018 				if (conn_outgoing_ill != NULL)
22019 					ill_refrele(conn_outgoing_ill);
22020 				return;
22021 			}
22022 			/*
22023 			 * ILLF_MULTICAST is checked in ip_newroute
22024 			 * i.e. we don't need to check it here since
22025 			 * all IRE_CACHEs come from ip_newroute.
22026 			 * For multicast traffic, SO_DONTROUTE is interpreted
22027 			 * to mean only send the packet out the interface
22028 			 * (optionally specified with IP_MULTICAST_IF)
22029 			 * and do not forward it out additional interfaces.
22030 			 * RSVP and the rsvp daemon is an example of a
22031 			 * protocol and user level process that
22032 			 * handles it's own routing. Hence, it uses the
22033 			 * SO_DONTROUTE option to accomplish this.
22034 			 */
22035 
22036 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22037 				/* Unconditionally redo the checksum */
22038 				ipha->ipha_hdr_checksum = 0;
22039 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22040 
22041 				/*
22042 				 * If this needs to go out secure, we need
22043 				 * to wait till we finish the IPSEC
22044 				 * processing.
22045 				 */
22046 				if (ipsec_len == 0 &&
22047 				    ip_mforward(ill, ipha, mp)) {
22048 					freemsg(first_mp);
22049 					ip1dbg(("ip_wput: mforward failed\n"));
22050 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22051 					    "ip_wput_ire_end: q %p (%S)",
22052 					    q, "mforward failed");
22053 					ire_refrele(ire);
22054 					if (conn_outgoing_ill != NULL)
22055 						ill_refrele(conn_outgoing_ill);
22056 					return;
22057 				}
22058 			}
22059 		}
22060 		max_frag = ire->ire_max_frag;
22061 		cksum += ttl_protocol;
22062 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22063 			/* No fragmentation required for this one. */
22064 			/*
22065 			 * Don't use frag_flag if packet is pre-built or source
22066 			 * routed or if multicast (since multicast packets do
22067 			 * not solicit ICMP "packet too big" messages).
22068 			 */
22069 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22070 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22071 			    !ip_source_route_included(ipha)) &&
22072 			    !CLASSD(ipha->ipha_dst))
22073 				ipha->ipha_fragment_offset_and_flags |=
22074 				    htons(ire->ire_frag_flag);
22075 
22076 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22077 				/* Complete the IP header checksum. */
22078 				cksum += ipha->ipha_ident;
22079 				cksum += (v_hlen_tos_len >> 16)+
22080 				    (v_hlen_tos_len & 0xFFFF);
22081 				cksum += ipha->ipha_fragment_offset_and_flags;
22082 				hlen = (V_HLEN & 0xF) -
22083 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22084 				if (hlen) {
22085 				    checksumoptions:
22086 					/*
22087 					 * Account for the IP Options in the IP
22088 					 * header checksum.
22089 					 */
22090 					up = (uint16_t *)(rptr+
22091 					    IP_SIMPLE_HDR_LENGTH);
22092 					do {
22093 						cksum += up[0];
22094 						cksum += up[1];
22095 						up += 2;
22096 					} while (--hlen);
22097 				}
22098 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22099 				cksum = ~(cksum + (cksum >> 16));
22100 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22101 			}
22102 			if (ipsec_len != 0) {
22103 				ipsec_out_process(q, first_mp, ire, ill_index);
22104 				if (!next_mp) {
22105 					ire_refrele(ire);
22106 					if (conn_outgoing_ill != NULL)
22107 						ill_refrele(conn_outgoing_ill);
22108 					return;
22109 				}
22110 				goto next;
22111 			}
22112 
22113 			/*
22114 			 * multirt_send has already been handled
22115 			 * for broadcast, but not yet for multicast
22116 			 * or IP options.
22117 			 */
22118 			if (next_mp == NULL) {
22119 				if (ire->ire_flags & RTF_MULTIRT) {
22120 					multirt_send = B_TRUE;
22121 				}
22122 			}
22123 
22124 			/*
22125 			 * In most cases, the emission loop below is
22126 			 * entered only once. Only in the case where
22127 			 * the ire holds the RTF_MULTIRT flag, do we loop
22128 			 * to process all RTF_MULTIRT ires in the bucket,
22129 			 * and send the packet through all crossed
22130 			 * RTF_MULTIRT routes.
22131 			 */
22132 			do {
22133 				if (multirt_send) {
22134 					irb_t *irb;
22135 
22136 					irb = ire->ire_bucket;
22137 					ASSERT(irb != NULL);
22138 					/*
22139 					 * We are in a multiple send case,
22140 					 * need to get the next IRE and make
22141 					 * a duplicate of the packet.
22142 					 */
22143 					IRB_REFHOLD(irb);
22144 					for (ire1 = ire->ire_next;
22145 					    ire1 != NULL;
22146 					    ire1 = ire1->ire_next) {
22147 						if (!(ire1->ire_flags &
22148 						    RTF_MULTIRT))
22149 							continue;
22150 						if (ire1->ire_addr !=
22151 						    ire->ire_addr)
22152 							continue;
22153 						if (ire1->ire_marks &
22154 						    (IRE_MARK_CONDEMNED|
22155 							IRE_MARK_HIDDEN))
22156 							continue;
22157 
22158 						/* Got one */
22159 						IRE_REFHOLD(ire1);
22160 						break;
22161 					}
22162 					IRB_REFRELE(irb);
22163 
22164 					if (ire1 != NULL) {
22165 						next_mp = copyb(mp);
22166 						if ((next_mp == NULL) ||
22167 						    ((mp->b_cont != NULL) &&
22168 						    ((next_mp->b_cont =
22169 						    dupmsg(mp->b_cont))
22170 						    == NULL))) {
22171 							freemsg(next_mp);
22172 							next_mp = NULL;
22173 							ire_refrele(ire1);
22174 							ire1 = NULL;
22175 						}
22176 					}
22177 
22178 					/*
22179 					 * Last multiroute ire; don't loop
22180 					 * anymore. The emission is over
22181 					 * and next_mp is NULL.
22182 					 */
22183 					if (ire1 == NULL) {
22184 						multirt_send = B_FALSE;
22185 					}
22186 				}
22187 
22188 				ASSERT(ipsec_len == 0);
22189 				mp->b_prev =
22190 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22191 				DTRACE_PROBE2(ip__xmit__2,
22192 				    mblk_t *, mp, ire_t *, ire);
22193 				pktxmit_state = ip_xmit_v4(mp, ire,
22194 				    NULL, B_TRUE);
22195 				if ((pktxmit_state == SEND_FAILED) ||
22196 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22197 					if (next_mp) {
22198 						freemsg(next_mp);
22199 						ire_refrele(ire1);
22200 					}
22201 					ire_refrele(ire);
22202 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22203 					    "ip_wput_ire_end: q %p (%S)",
22204 					    q, "discard MDATA");
22205 					if (conn_outgoing_ill != NULL)
22206 						ill_refrele(conn_outgoing_ill);
22207 					return;
22208 				}
22209 
22210 				if (multirt_send) {
22211 					/*
22212 					 * We are in a multiple send case,
22213 					 * need to re-enter the sending loop
22214 					 * using the next ire.
22215 					 */
22216 					ire_refrele(ire);
22217 					ire = ire1;
22218 					stq = ire->ire_stq;
22219 					mp = next_mp;
22220 					next_mp = NULL;
22221 					ipha = (ipha_t *)mp->b_rptr;
22222 					ill_index = Q_TO_INDEX(stq);
22223 				}
22224 			} while (multirt_send);
22225 
22226 			if (!next_mp) {
22227 				/*
22228 				 * Last copy going out (the ultra-common
22229 				 * case).  Note that we intentionally replicate
22230 				 * the putnext rather than calling it before
22231 				 * the next_mp check in hopes of a little
22232 				 * tail-call action out of the compiler.
22233 				 */
22234 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22235 				    "ip_wput_ire_end: q %p (%S)",
22236 				    q, "last copy out(1)");
22237 				ire_refrele(ire);
22238 				if (conn_outgoing_ill != NULL)
22239 					ill_refrele(conn_outgoing_ill);
22240 				return;
22241 			}
22242 			/* More copies going out below. */
22243 		} else {
22244 			int offset;
22245 		    fragmentit:
22246 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22247 			/*
22248 			 * If this would generate a icmp_frag_needed message,
22249 			 * we need to handle it before we do the IPSEC
22250 			 * processing. Otherwise, we need to strip the IPSEC
22251 			 * headers before we send up the message to the ULPs
22252 			 * which becomes messy and difficult.
22253 			 */
22254 			if (ipsec_len != 0) {
22255 				if ((max_frag < (unsigned int)(LENGTH +
22256 				    ipsec_len)) && (offset & IPH_DF)) {
22257 
22258 					BUMP_MIB(&ip_mib, ipFragFails);
22259 					ipha->ipha_hdr_checksum = 0;
22260 					ipha->ipha_hdr_checksum =
22261 					    (uint16_t)ip_csum_hdr(ipha);
22262 					icmp_frag_needed(ire->ire_stq, first_mp,
22263 					    max_frag);
22264 					if (!next_mp) {
22265 						ire_refrele(ire);
22266 						if (conn_outgoing_ill != NULL) {
22267 							ill_refrele(
22268 							    conn_outgoing_ill);
22269 						}
22270 						return;
22271 					}
22272 				} else {
22273 					/*
22274 					 * This won't cause a icmp_frag_needed
22275 					 * message. to be gnerated. Send it on
22276 					 * the wire. Note that this could still
22277 					 * cause fragmentation and all we
22278 					 * do is the generation of the message
22279 					 * to the ULP if needed before IPSEC.
22280 					 */
22281 					if (!next_mp) {
22282 						ipsec_out_process(q, first_mp,
22283 						    ire, ill_index);
22284 						TRACE_2(TR_FAC_IP,
22285 						    TR_IP_WPUT_IRE_END,
22286 						    "ip_wput_ire_end: q %p "
22287 						    "(%S)", q,
22288 						    "last ipsec_out_process");
22289 						ire_refrele(ire);
22290 						if (conn_outgoing_ill != NULL) {
22291 							ill_refrele(
22292 							    conn_outgoing_ill);
22293 						}
22294 						return;
22295 					}
22296 					ipsec_out_process(q, first_mp,
22297 					    ire, ill_index);
22298 				}
22299 			} else {
22300 				/*
22301 				 * Initiate IPPF processing. For
22302 				 * fragmentable packets we finish
22303 				 * all QOS packet processing before
22304 				 * calling:
22305 				 * ip_wput_ire_fragmentit->ip_wput_frag
22306 				 */
22307 
22308 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22309 					ip_process(IPP_LOCAL_OUT, &mp,
22310 					    ill_index);
22311 					if (mp == NULL) {
22312 						BUMP_MIB(&ip_mib,
22313 						    ipOutDiscards);
22314 						if (next_mp != NULL) {
22315 							freemsg(next_mp);
22316 							ire_refrele(ire1);
22317 						}
22318 						ire_refrele(ire);
22319 						TRACE_2(TR_FAC_IP,
22320 						    TR_IP_WPUT_IRE_END,
22321 						    "ip_wput_ire: q %p (%S)",
22322 						    q, "discard MDATA");
22323 						if (conn_outgoing_ill != NULL) {
22324 							ill_refrele(
22325 							    conn_outgoing_ill);
22326 						}
22327 						return;
22328 					}
22329 				}
22330 				if (!next_mp) {
22331 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22332 					    "ip_wput_ire_end: q %p (%S)",
22333 					    q, "last fragmentation");
22334 					ip_wput_ire_fragmentit(mp, ire);
22335 					ire_refrele(ire);
22336 					if (conn_outgoing_ill != NULL)
22337 						ill_refrele(conn_outgoing_ill);
22338 					return;
22339 				}
22340 				ip_wput_ire_fragmentit(mp, ire);
22341 			}
22342 		}
22343 	} else {
22344 	    nullstq:
22345 		/* A NULL stq means the destination address is local. */
22346 		UPDATE_OB_PKT_COUNT(ire);
22347 		ire->ire_last_used_time = lbolt;
22348 		ASSERT(ire->ire_ipif != NULL);
22349 		if (!next_mp) {
22350 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22351 			    "ip_wput_ire_end: q %p (%S)",
22352 			    q, "local address");
22353 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
22354 			    first_mp, ire, 0, ire->ire_zoneid);
22355 			ire_refrele(ire);
22356 			if (conn_outgoing_ill != NULL)
22357 				ill_refrele(conn_outgoing_ill);
22358 			return;
22359 		}
22360 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
22361 		    ire, 0, ire->ire_zoneid);
22362 	}
22363 next:
22364 	/*
22365 	 * More copies going out to additional interfaces.
22366 	 * ire1 has already been held. We don't need the
22367 	 * "ire" anymore.
22368 	 */
22369 	ire_refrele(ire);
22370 	ire = ire1;
22371 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
22372 	mp = next_mp;
22373 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
22374 	ill = ire_to_ill(ire);
22375 	first_mp = mp;
22376 	if (ipsec_len != 0) {
22377 		ASSERT(first_mp->b_datap->db_type == M_CTL);
22378 		mp = mp->b_cont;
22379 	}
22380 	dst = ire->ire_addr;
22381 	ipha = (ipha_t *)mp->b_rptr;
22382 	/*
22383 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
22384 	 * Restore ipha_ident "no checksum" flag.
22385 	 */
22386 	src = orig_src;
22387 	ipha->ipha_ident = ip_hdr_included;
22388 	goto another;
22389 
22390 #undef	rptr
22391 #undef	Q_TO_INDEX
22392 }
22393 
22394 /*
22395  * Routine to allocate a message that is used to notify the ULP about MDT.
22396  * The caller may provide a pointer to the link-layer MDT capabilities,
22397  * or NULL if MDT is to be disabled on the stream.
22398  */
22399 mblk_t *
22400 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
22401 {
22402 	mblk_t *mp;
22403 	ip_mdt_info_t *mdti;
22404 	ill_mdt_capab_t *idst;
22405 
22406 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
22407 		DB_TYPE(mp) = M_CTL;
22408 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
22409 		mdti = (ip_mdt_info_t *)mp->b_rptr;
22410 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
22411 		idst = &(mdti->mdt_capab);
22412 
22413 		/*
22414 		 * If the caller provides us with the capability, copy
22415 		 * it over into our notification message; otherwise
22416 		 * we zero out the capability portion.
22417 		 */
22418 		if (isrc != NULL)
22419 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22420 		else
22421 			bzero((caddr_t)idst, sizeof (*idst));
22422 	}
22423 	return (mp);
22424 }
22425 
22426 /*
22427  * Routine which determines whether MDT can be enabled on the destination
22428  * IRE and IPC combination, and if so, allocates and returns the MDT
22429  * notification mblk that may be used by ULP.  We also check if we need to
22430  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
22431  * MDT usage in the past have been lifted.  This gets called during IP
22432  * and ULP binding.
22433  */
22434 mblk_t *
22435 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22436     ill_mdt_capab_t *mdt_cap)
22437 {
22438 	mblk_t *mp;
22439 	boolean_t rc = B_FALSE;
22440 
22441 	ASSERT(dst_ire != NULL);
22442 	ASSERT(connp != NULL);
22443 	ASSERT(mdt_cap != NULL);
22444 
22445 	/*
22446 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
22447 	 * Multidata, which is handled in tcp_multisend().  This
22448 	 * is the reason why we do all these checks here, to ensure
22449 	 * that we don't enable Multidata for the cases which we
22450 	 * can't handle at the moment.
22451 	 */
22452 	do {
22453 		/* Only do TCP at the moment */
22454 		if (connp->conn_ulp != IPPROTO_TCP)
22455 			break;
22456 
22457 		/*
22458 		 * IPSEC outbound policy present?  Note that we get here
22459 		 * after calling ipsec_conn_cache_policy() where the global
22460 		 * policy checking is performed.  conn_latch will be
22461 		 * non-NULL as long as there's a policy defined,
22462 		 * i.e. conn_out_enforce_policy may be NULL in such case
22463 		 * when the connection is non-secure, and hence we check
22464 		 * further if the latch refers to an outbound policy.
22465 		 */
22466 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
22467 			break;
22468 
22469 		/* CGTP (multiroute) is enabled? */
22470 		if (dst_ire->ire_flags & RTF_MULTIRT)
22471 			break;
22472 
22473 		/* Outbound IPQoS enabled? */
22474 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22475 			/*
22476 			 * In this case, we disable MDT for this and all
22477 			 * future connections going over the interface.
22478 			 */
22479 			mdt_cap->ill_mdt_on = 0;
22480 			break;
22481 		}
22482 
22483 		/* socket option(s) present? */
22484 		if (!CONN_IS_MD_FASTPATH(connp))
22485 			break;
22486 
22487 		rc = B_TRUE;
22488 	/* CONSTCOND */
22489 	} while (0);
22490 
22491 	/* Remember the result */
22492 	connp->conn_mdt_ok = rc;
22493 
22494 	if (!rc)
22495 		return (NULL);
22496 	else if (!mdt_cap->ill_mdt_on) {
22497 		/*
22498 		 * If MDT has been previously turned off in the past, and we
22499 		 * currently can do MDT (due to IPQoS policy removal, etc.)
22500 		 * then enable it for this interface.
22501 		 */
22502 		mdt_cap->ill_mdt_on = 1;
22503 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
22504 		    "interface %s\n", ill_name));
22505 	}
22506 
22507 	/* Allocate the MDT info mblk */
22508 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
22509 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
22510 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
22511 		return (NULL);
22512 	}
22513 	return (mp);
22514 }
22515 
22516 /*
22517  * Create destination address attribute, and fill it with the physical
22518  * destination address and SAP taken from the template DL_UNITDATA_REQ
22519  * message block.
22520  */
22521 boolean_t
22522 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
22523 {
22524 	dl_unitdata_req_t *dlurp;
22525 	pattr_t *pa;
22526 	pattrinfo_t pa_info;
22527 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
22528 	uint_t das_len, das_off;
22529 
22530 	ASSERT(dlmp != NULL);
22531 
22532 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
22533 	das_len = dlurp->dl_dest_addr_length;
22534 	das_off = dlurp->dl_dest_addr_offset;
22535 
22536 	pa_info.type = PATTR_DSTADDRSAP;
22537 	pa_info.len = sizeof (**das) + das_len - 1;
22538 
22539 	/* create and associate the attribute */
22540 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22541 	if (pa != NULL) {
22542 		ASSERT(*das != NULL);
22543 		(*das)->addr_is_group = 0;
22544 		(*das)->addr_len = (uint8_t)das_len;
22545 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
22546 	}
22547 
22548 	return (pa != NULL);
22549 }
22550 
22551 /*
22552  * Create hardware checksum attribute and fill it with the values passed.
22553  */
22554 boolean_t
22555 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
22556     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
22557 {
22558 	pattr_t *pa;
22559 	pattrinfo_t pa_info;
22560 
22561 	ASSERT(mmd != NULL);
22562 
22563 	pa_info.type = PATTR_HCKSUM;
22564 	pa_info.len = sizeof (pattr_hcksum_t);
22565 
22566 	/* create and associate the attribute */
22567 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22568 	if (pa != NULL) {
22569 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
22570 
22571 		hck->hcksum_start_offset = start_offset;
22572 		hck->hcksum_stuff_offset = stuff_offset;
22573 		hck->hcksum_end_offset = end_offset;
22574 		hck->hcksum_flags = flags;
22575 	}
22576 	return (pa != NULL);
22577 }
22578 
22579 /*
22580  * Create zerocopy attribute and fill it with the specified flags
22581  */
22582 boolean_t
22583 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
22584 {
22585 	pattr_t *pa;
22586 	pattrinfo_t pa_info;
22587 
22588 	ASSERT(mmd != NULL);
22589 	pa_info.type = PATTR_ZCOPY;
22590 	pa_info.len = sizeof (pattr_zcopy_t);
22591 
22592 	/* create and associate the attribute */
22593 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22594 	if (pa != NULL) {
22595 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
22596 
22597 		zcopy->zcopy_flags = flags;
22598 	}
22599 	return (pa != NULL);
22600 }
22601 
22602 /*
22603  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
22604  * block chain. We could rewrite to handle arbitrary message block chains but
22605  * that would make the code complicated and slow. Right now there three
22606  * restrictions:
22607  *
22608  *   1. The first message block must contain the complete IP header and
22609  *	at least 1 byte of payload data.
22610  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
22611  *	so that we can use a single Multidata message.
22612  *   3. No frag must be distributed over two or more message blocks so
22613  *	that we don't need more than two packet descriptors per frag.
22614  *
22615  * The above restrictions allow us to support userland applications (which
22616  * will send down a single message block) and NFS over UDP (which will
22617  * send down a chain of at most three message blocks).
22618  *
22619  * We also don't use MDT for payloads with less than or equal to
22620  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
22621  */
22622 boolean_t
22623 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
22624 {
22625 	int	blocks;
22626 	ssize_t	total, missing, size;
22627 
22628 	ASSERT(mp != NULL);
22629 	ASSERT(hdr_len > 0);
22630 
22631 	size = MBLKL(mp) - hdr_len;
22632 	if (size <= 0)
22633 		return (B_FALSE);
22634 
22635 	/* The first mblk contains the header and some payload. */
22636 	blocks = 1;
22637 	total = size;
22638 	size %= len;
22639 	missing = (size == 0) ? 0 : (len - size);
22640 	mp = mp->b_cont;
22641 
22642 	while (mp != NULL) {
22643 		/*
22644 		 * Give up if we encounter a zero length message block.
22645 		 * In practice, this should rarely happen and therefore
22646 		 * not worth the trouble of freeing and re-linking the
22647 		 * mblk from the chain to handle such case.
22648 		 */
22649 		if ((size = MBLKL(mp)) == 0)
22650 			return (B_FALSE);
22651 
22652 		/* Too many payload buffers for a single Multidata message? */
22653 		if (++blocks > MULTIDATA_MAX_PBUFS)
22654 			return (B_FALSE);
22655 
22656 		total += size;
22657 		/* Is a frag distributed over two or more message blocks? */
22658 		if (missing > size)
22659 			return (B_FALSE);
22660 		size -= missing;
22661 
22662 		size %= len;
22663 		missing = (size == 0) ? 0 : (len - size);
22664 
22665 		mp = mp->b_cont;
22666 	}
22667 
22668 	return (total > ip_wput_frag_mdt_min);
22669 }
22670 
22671 /*
22672  * Outbound IPv4 fragmentation routine using MDT.
22673  */
22674 static void
22675 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
22676     uint32_t frag_flag, int offset)
22677 {
22678 	ipha_t		*ipha_orig;
22679 	int		i1, ip_data_end;
22680 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
22681 	mblk_t		*hdr_mp, *md_mp = NULL;
22682 	unsigned char	*hdr_ptr, *pld_ptr;
22683 	multidata_t	*mmd;
22684 	ip_pdescinfo_t	pdi;
22685 
22686 	ASSERT(DB_TYPE(mp) == M_DATA);
22687 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
22688 
22689 	ipha_orig = (ipha_t *)mp->b_rptr;
22690 	mp->b_rptr += sizeof (ipha_t);
22691 
22692 	/* Calculate how many packets we will send out */
22693 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
22694 	pkts = (i1 + len - 1) / len;
22695 	ASSERT(pkts > 1);
22696 
22697 	/* Allocate a message block which will hold all the IP Headers. */
22698 	wroff = ip_wroff_extra;
22699 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
22700 
22701 	i1 = pkts * hdr_chunk_len;
22702 	/*
22703 	 * Create the header buffer, Multidata and destination address
22704 	 * and SAP attribute that should be associated with it.
22705 	 */
22706 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
22707 	    ((hdr_mp->b_wptr += i1),
22708 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
22709 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
22710 		freemsg(mp);
22711 		if (md_mp == NULL) {
22712 			freemsg(hdr_mp);
22713 		} else {
22714 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
22715 			freemsg(md_mp);
22716 		}
22717 		IP_STAT(ip_frag_mdt_allocfail);
22718 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
22719 		return;
22720 	}
22721 	IP_STAT(ip_frag_mdt_allocd);
22722 
22723 	/*
22724 	 * Add a payload buffer to the Multidata; this operation must not
22725 	 * fail, or otherwise our logic in this routine is broken.  There
22726 	 * is no memory allocation done by the routine, so any returned
22727 	 * failure simply tells us that we've done something wrong.
22728 	 *
22729 	 * A failure tells us that either we're adding the same payload
22730 	 * buffer more than once, or we're trying to add more buffers than
22731 	 * allowed.  None of the above cases should happen, and we panic
22732 	 * because either there's horrible heap corruption, and/or
22733 	 * programming mistake.
22734 	 */
22735 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22736 		goto pbuf_panic;
22737 
22738 	hdr_ptr = hdr_mp->b_rptr;
22739 	pld_ptr = mp->b_rptr;
22740 
22741 	/* Establish the ending byte offset, based on the starting offset. */
22742 	offset <<= 3;
22743 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
22744 	    IP_SIMPLE_HDR_LENGTH;
22745 
22746 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
22747 
22748 	while (pld_ptr < mp->b_wptr) {
22749 		ipha_t		*ipha;
22750 		uint16_t	offset_and_flags;
22751 		uint16_t	ip_len;
22752 		int		error;
22753 
22754 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
22755 		ipha = (ipha_t *)(hdr_ptr + wroff);
22756 		ASSERT(OK_32PTR(ipha));
22757 		*ipha = *ipha_orig;
22758 
22759 		if (ip_data_end - offset > len) {
22760 			offset_and_flags = IPH_MF;
22761 		} else {
22762 			/*
22763 			 * Last frag. Set len to the length of this last piece.
22764 			 */
22765 			len = ip_data_end - offset;
22766 			/* A frag of a frag might have IPH_MF non-zero */
22767 			offset_and_flags =
22768 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22769 			    IPH_MF;
22770 		}
22771 		offset_and_flags |= (uint16_t)(offset >> 3);
22772 		offset_and_flags |= (uint16_t)frag_flag;
22773 		/* Store the offset and flags in the IP header. */
22774 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22775 
22776 		/* Store the length in the IP header. */
22777 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
22778 		ipha->ipha_length = htons(ip_len);
22779 
22780 		/*
22781 		 * Set the IP header checksum.  Note that mp is just
22782 		 * the header, so this is easy to pass to ip_csum.
22783 		 */
22784 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22785 
22786 		/*
22787 		 * Record offset and size of header and data of the next packet
22788 		 * in the multidata message.
22789 		 */
22790 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
22791 		PDESC_PLD_INIT(&pdi);
22792 		i1 = MIN(mp->b_wptr - pld_ptr, len);
22793 		ASSERT(i1 > 0);
22794 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
22795 		if (i1 == len) {
22796 			pld_ptr += len;
22797 		} else {
22798 			i1 = len - i1;
22799 			mp = mp->b_cont;
22800 			ASSERT(mp != NULL);
22801 			ASSERT(MBLKL(mp) >= i1);
22802 			/*
22803 			 * Attach the next payload message block to the
22804 			 * multidata message.
22805 			 */
22806 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22807 				goto pbuf_panic;
22808 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
22809 			pld_ptr = mp->b_rptr + i1;
22810 		}
22811 
22812 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
22813 		    KM_NOSLEEP)) == NULL) {
22814 			/*
22815 			 * Any failure other than ENOMEM indicates that we
22816 			 * have passed in invalid pdesc info or parameters
22817 			 * to mmd_addpdesc, which must not happen.
22818 			 *
22819 			 * EINVAL is a result of failure on boundary checks
22820 			 * against the pdesc info contents.  It should not
22821 			 * happen, and we panic because either there's
22822 			 * horrible heap corruption, and/or programming
22823 			 * mistake.
22824 			 */
22825 			if (error != ENOMEM) {
22826 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
22827 				    "pdesc logic error detected for "
22828 				    "mmd %p pinfo %p (%d)\n",
22829 				    (void *)mmd, (void *)&pdi, error);
22830 				/* NOTREACHED */
22831 			}
22832 			IP_STAT(ip_frag_mdt_addpdescfail);
22833 			/* Free unattached payload message blocks as well */
22834 			md_mp->b_cont = mp->b_cont;
22835 			goto free_mmd;
22836 		}
22837 
22838 		/* Advance fragment offset. */
22839 		offset += len;
22840 
22841 		/* Advance to location for next header in the buffer. */
22842 		hdr_ptr += hdr_chunk_len;
22843 
22844 		/* Did we reach the next payload message block? */
22845 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
22846 			mp = mp->b_cont;
22847 			/*
22848 			 * Attach the next message block with payload
22849 			 * data to the multidata message.
22850 			 */
22851 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22852 				goto pbuf_panic;
22853 			pld_ptr = mp->b_rptr;
22854 		}
22855 	}
22856 
22857 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
22858 	ASSERT(mp->b_wptr == pld_ptr);
22859 
22860 	/* Update IP statistics */
22861 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
22862 	BUMP_MIB(&ip_mib, ipFragOKs);
22863 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
22864 
22865 	if (pkt_type == OB_PKT) {
22866 		ire->ire_ob_pkt_count += pkts;
22867 		if (ire->ire_ipif != NULL)
22868 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
22869 	} else {
22870 		/*
22871 		 * The type is IB_PKT in the forwarding path and in
22872 		 * the mobile IP case when the packet is being reverse-
22873 		 * tunneled to the home agent.
22874 		 */
22875 		ire->ire_ib_pkt_count += pkts;
22876 		ASSERT(!IRE_IS_LOCAL(ire));
22877 		if (ire->ire_type & IRE_BROADCAST)
22878 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
22879 		else
22880 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
22881 	}
22882 	ire->ire_last_used_time = lbolt;
22883 	/* Send it down */
22884 	putnext(ire->ire_stq, md_mp);
22885 	return;
22886 
22887 pbuf_panic:
22888 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
22889 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
22890 	    pbuf_idx);
22891 	/* NOTREACHED */
22892 }
22893 
22894 /*
22895  * Outbound IP fragmentation routine.
22896  *
22897  * NOTE : This routine does not ire_refrele the ire that is passed in
22898  * as the argument.
22899  */
22900 static void
22901 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
22902     uint32_t frag_flag)
22903 {
22904 	int		i1;
22905 	mblk_t		*ll_hdr_mp;
22906 	int 		ll_hdr_len;
22907 	int		hdr_len;
22908 	mblk_t		*hdr_mp;
22909 	ipha_t		*ipha;
22910 	int		ip_data_end;
22911 	int		len;
22912 	mblk_t		*mp = mp_orig;
22913 	int		offset;
22914 	queue_t		*q;
22915 	uint32_t	v_hlen_tos_len;
22916 	mblk_t		*first_mp;
22917 	boolean_t	mctl_present;
22918 	ill_t		*ill;
22919 	mblk_t		*xmit_mp;
22920 	mblk_t		*carve_mp;
22921 	ire_t		*ire1 = NULL;
22922 	ire_t		*save_ire = NULL;
22923 	mblk_t  	*next_mp = NULL;
22924 	boolean_t	last_frag = B_FALSE;
22925 	boolean_t	multirt_send = B_FALSE;
22926 	ire_t		*first_ire = NULL;
22927 	irb_t		*irb = NULL;
22928 
22929 	/*
22930 	 * IPSEC does not allow hw accelerated packets to be fragmented
22931 	 * This check is made in ip_wput_ipsec_out prior to coming here
22932 	 * via ip_wput_ire_fragmentit.
22933 	 *
22934 	 * If at this point we have an ire whose ARP request has not
22935 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
22936 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
22937 	 * This packet and all fragmentable packets for this ire will
22938 	 * continue to get dropped while ire_nce->nce_state remains in
22939 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
22940 	 * ND_REACHABLE, all subsquent large packets for this ire will
22941 	 * get fragemented and sent out by this function.
22942 	 */
22943 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
22944 		/* If nce_state is ND_INITIAL, trigger ARP query */
22945 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
22946 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
22947 		    " -  dropping packet\n"));
22948 		BUMP_MIB(&ip_mib, ipFragFails);
22949 		freemsg(mp);
22950 		return;
22951 	}
22952 
22953 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
22954 	    "ip_wput_frag_start:");
22955 
22956 	if (mp->b_datap->db_type == M_CTL) {
22957 		first_mp = mp;
22958 		mp_orig = mp = mp->b_cont;
22959 		mctl_present = B_TRUE;
22960 	} else {
22961 		first_mp = mp;
22962 		mctl_present = B_FALSE;
22963 	}
22964 
22965 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
22966 	ipha = (ipha_t *)mp->b_rptr;
22967 
22968 	/*
22969 	 * If the Don't Fragment flag is on, generate an ICMP destination
22970 	 * unreachable, fragmentation needed.
22971 	 */
22972 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22973 	if (offset & IPH_DF) {
22974 		BUMP_MIB(&ip_mib, ipFragFails);
22975 		/*
22976 		 * Need to compute hdr checksum if called from ip_wput_ire.
22977 		 * Note that ip_rput_forward verifies the checksum before
22978 		 * calling this routine so in that case this is a noop.
22979 		 */
22980 		ipha->ipha_hdr_checksum = 0;
22981 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22982 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
22983 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22984 		    "ip_wput_frag_end:(%S)",
22985 		    "don't fragment");
22986 		return;
22987 	}
22988 	if (mctl_present)
22989 		freeb(first_mp);
22990 	/*
22991 	 * Establish the starting offset.  May not be zero if we are fragging
22992 	 * a fragment that is being forwarded.
22993 	 */
22994 	offset = offset & IPH_OFFSET;
22995 
22996 	/* TODO why is this test needed? */
22997 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22998 	if (((max_frag - LENGTH) & ~7) < 8) {
22999 		/* TODO: notify ulp somehow */
23000 		BUMP_MIB(&ip_mib, ipFragFails);
23001 		freemsg(mp);
23002 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23003 		    "ip_wput_frag_end:(%S)",
23004 		    "len < 8");
23005 		return;
23006 	}
23007 
23008 	hdr_len = (V_HLEN & 0xF) << 2;
23009 
23010 	ipha->ipha_hdr_checksum = 0;
23011 
23012 	/*
23013 	 * Establish the number of bytes maximum per frag, after putting
23014 	 * in the header.
23015 	 */
23016 	len = (max_frag - hdr_len) & ~7;
23017 
23018 	/* Check if we can use MDT to send out the frags. */
23019 	ASSERT(!IRE_IS_LOCAL(ire));
23020 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
23021 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
23022 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
23023 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23024 		ASSERT(ill->ill_mdt_capab != NULL);
23025 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23026 			/*
23027 			 * If MDT has been previously turned off in the past,
23028 			 * and we currently can do MDT (due to IPQoS policy
23029 			 * removal, etc.) then enable it for this interface.
23030 			 */
23031 			ill->ill_mdt_capab->ill_mdt_on = 1;
23032 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23033 			    ill->ill_name));
23034 		}
23035 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23036 		    offset);
23037 		return;
23038 	}
23039 
23040 	/* Get a copy of the header for the trailing frags */
23041 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
23042 	if (!hdr_mp) {
23043 		BUMP_MIB(&ip_mib, ipOutDiscards);
23044 		freemsg(mp);
23045 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23046 		    "ip_wput_frag_end:(%S)",
23047 		    "couldn't copy hdr");
23048 		return;
23049 	}
23050 	if (DB_CRED(mp) != NULL)
23051 		mblk_setcred(hdr_mp, DB_CRED(mp));
23052 
23053 	/* Store the starting offset, with the MoreFrags flag. */
23054 	i1 = offset | IPH_MF | frag_flag;
23055 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23056 
23057 	/* Establish the ending byte offset, based on the starting offset. */
23058 	offset <<= 3;
23059 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23060 
23061 	/* Store the length of the first fragment in the IP header. */
23062 	i1 = len + hdr_len;
23063 	ASSERT(i1 <= IP_MAXPACKET);
23064 	ipha->ipha_length = htons((uint16_t)i1);
23065 
23066 	/*
23067 	 * Compute the IP header checksum for the first frag.  We have to
23068 	 * watch out that we stop at the end of the header.
23069 	 */
23070 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23071 
23072 	/*
23073 	 * Now carve off the first frag.  Note that this will include the
23074 	 * original IP header.
23075 	 */
23076 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
23077 		BUMP_MIB(&ip_mib, ipOutDiscards);
23078 		freeb(hdr_mp);
23079 		freemsg(mp_orig);
23080 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23081 		    "ip_wput_frag_end:(%S)",
23082 		    "couldn't carve first");
23083 		return;
23084 	}
23085 
23086 	/*
23087 	 * Multirouting case. Each fragment is replicated
23088 	 * via all non-condemned RTF_MULTIRT routes
23089 	 * currently resolved.
23090 	 * We ensure that first_ire is the first RTF_MULTIRT
23091 	 * ire in the bucket.
23092 	 */
23093 	if (ire->ire_flags & RTF_MULTIRT) {
23094 		irb = ire->ire_bucket;
23095 		ASSERT(irb != NULL);
23096 
23097 		multirt_send = B_TRUE;
23098 
23099 		/* Make sure we do not omit any multiroute ire. */
23100 		IRB_REFHOLD(irb);
23101 		for (first_ire = irb->irb_ire;
23102 		    first_ire != NULL;
23103 		    first_ire = first_ire->ire_next) {
23104 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23105 			    (first_ire->ire_addr == ire->ire_addr) &&
23106 			    !(first_ire->ire_marks &
23107 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23108 				break;
23109 		}
23110 
23111 		if (first_ire != NULL) {
23112 			if (first_ire != ire) {
23113 				IRE_REFHOLD(first_ire);
23114 				/*
23115 				 * Do not release the ire passed in
23116 				 * as the argument.
23117 				 */
23118 				ire = first_ire;
23119 			} else {
23120 				first_ire = NULL;
23121 			}
23122 		}
23123 		IRB_REFRELE(irb);
23124 
23125 		/*
23126 		 * Save the first ire; we will need to restore it
23127 		 * for the trailing frags.
23128 		 * We REFHOLD save_ire, as each iterated ire will be
23129 		 * REFRELEd.
23130 		 */
23131 		save_ire = ire;
23132 		IRE_REFHOLD(save_ire);
23133 	}
23134 
23135 	/*
23136 	 * First fragment emission loop.
23137 	 * In most cases, the emission loop below is entered only
23138 	 * once. Only in the case where the ire holds the RTF_MULTIRT
23139 	 * flag, do we loop to process all RTF_MULTIRT ires in the
23140 	 * bucket, and send the fragment through all crossed
23141 	 * RTF_MULTIRT routes.
23142 	 */
23143 	do {
23144 		if (ire->ire_flags & RTF_MULTIRT) {
23145 			/*
23146 			 * We are in a multiple send case, need to get
23147 			 * the next ire and make a copy of the packet.
23148 			 * ire1 holds here the next ire to process in the
23149 			 * bucket. If multirouting is expected,
23150 			 * any non-RTF_MULTIRT ire that has the
23151 			 * right destination address is ignored.
23152 			 *
23153 			 * We have to take into account the MTU of
23154 			 * each walked ire. max_frag is set by the
23155 			 * the caller and generally refers to
23156 			 * the primary ire entry. Here we ensure that
23157 			 * no route with a lower MTU will be used, as
23158 			 * fragments are carved once for all ires,
23159 			 * then replicated.
23160 			 */
23161 			ASSERT(irb != NULL);
23162 			IRB_REFHOLD(irb);
23163 			for (ire1 = ire->ire_next;
23164 			    ire1 != NULL;
23165 			    ire1 = ire1->ire_next) {
23166 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23167 					continue;
23168 				if (ire1->ire_addr != ire->ire_addr)
23169 					continue;
23170 				if (ire1->ire_marks &
23171 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23172 					continue;
23173 				/*
23174 				 * Ensure we do not exceed the MTU
23175 				 * of the next route.
23176 				 */
23177 				if (ire1->ire_max_frag < max_frag) {
23178 					ip_multirt_bad_mtu(ire1, max_frag);
23179 					continue;
23180 				}
23181 
23182 				/* Got one. */
23183 				IRE_REFHOLD(ire1);
23184 				break;
23185 			}
23186 			IRB_REFRELE(irb);
23187 
23188 			if (ire1 != NULL) {
23189 				next_mp = copyb(mp);
23190 				if ((next_mp == NULL) ||
23191 				    ((mp->b_cont != NULL) &&
23192 				    ((next_mp->b_cont =
23193 				    dupmsg(mp->b_cont)) == NULL))) {
23194 					freemsg(next_mp);
23195 					next_mp = NULL;
23196 					ire_refrele(ire1);
23197 					ire1 = NULL;
23198 				}
23199 			}
23200 
23201 			/* Last multiroute ire; don't loop anymore. */
23202 			if (ire1 == NULL) {
23203 				multirt_send = B_FALSE;
23204 			}
23205 		}
23206 
23207 		ll_hdr_len = 0;
23208 		LOCK_IRE_FP_MP(ire);
23209 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23210 		if (ll_hdr_mp != NULL) {
23211 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23212 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
23213 		} else {
23214 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
23215 		}
23216 
23217 		/* If there is a transmit header, get a copy for this frag. */
23218 		/*
23219 		 * TODO: should check db_ref before calling ip_carve_mp since
23220 		 * it might give us a dup.
23221 		 */
23222 		if (!ll_hdr_mp) {
23223 			/* No xmit header. */
23224 			xmit_mp = mp;
23225 
23226 		/* We have a link-layer header that can fit in our mblk. */
23227 		} else if (mp->b_datap->db_ref == 1 &&
23228 		    ll_hdr_len != 0 &&
23229 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23230 			/* M_DATA fastpath */
23231 			mp->b_rptr -= ll_hdr_len;
23232 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
23233 			xmit_mp = mp;
23234 
23235 		/* Corner case if copyb has failed */
23236 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
23237 			UNLOCK_IRE_FP_MP(ire);
23238 			BUMP_MIB(&ip_mib, ipOutDiscards);
23239 			freeb(hdr_mp);
23240 			freemsg(mp);
23241 			freemsg(mp_orig);
23242 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23243 			    "ip_wput_frag_end:(%S)",
23244 			    "discard");
23245 
23246 			if (multirt_send) {
23247 				ASSERT(ire1);
23248 				ASSERT(next_mp);
23249 
23250 				freemsg(next_mp);
23251 				ire_refrele(ire1);
23252 			}
23253 			if (save_ire != NULL)
23254 				IRE_REFRELE(save_ire);
23255 
23256 			if (first_ire != NULL)
23257 				ire_refrele(first_ire);
23258 			return;
23259 
23260 		/*
23261 		 * Case of res_mp OR the fastpath mp can't fit
23262 		 * in the mblk
23263 		 */
23264 		} else {
23265 			xmit_mp->b_cont = mp;
23266 			if (DB_CRED(mp) != NULL)
23267 				mblk_setcred(xmit_mp, DB_CRED(mp));
23268 			/*
23269 			 * Get priority marking, if any.
23270 			 * We propagate the CoS marking from the
23271 			 * original packet that went to QoS processing
23272 			 * in ip_wput_ire to the newly carved mp.
23273 			 */
23274 			if (DB_TYPE(xmit_mp) == M_DATA)
23275 				xmit_mp->b_band = mp->b_band;
23276 		}
23277 		UNLOCK_IRE_FP_MP(ire);
23278 		q = ire->ire_stq;
23279 		BUMP_MIB(&ip_mib, ipFragCreates);
23280 		putnext(q, xmit_mp);
23281 		if (pkt_type != OB_PKT) {
23282 			/*
23283 			 * Update the packet count of trailing
23284 			 * RTF_MULTIRT ires.
23285 			 */
23286 			UPDATE_OB_PKT_COUNT(ire);
23287 		}
23288 
23289 		if (multirt_send) {
23290 			/*
23291 			 * We are in a multiple send case; look for
23292 			 * the next ire and re-enter the loop.
23293 			 */
23294 			ASSERT(ire1);
23295 			ASSERT(next_mp);
23296 			/* REFRELE the current ire before looping */
23297 			ire_refrele(ire);
23298 			ire = ire1;
23299 			ire1 = NULL;
23300 			mp = next_mp;
23301 			next_mp = NULL;
23302 		}
23303 	} while (multirt_send);
23304 
23305 	ASSERT(ire1 == NULL);
23306 
23307 	/* Restore the original ire; we need it for the trailing frags */
23308 	if (save_ire != NULL) {
23309 		/* REFRELE the last iterated ire */
23310 		ire_refrele(ire);
23311 		/* save_ire has been REFHOLDed */
23312 		ire = save_ire;
23313 		save_ire = NULL;
23314 		q = ire->ire_stq;
23315 	}
23316 
23317 	if (pkt_type == OB_PKT) {
23318 		UPDATE_OB_PKT_COUNT(ire);
23319 	} else {
23320 		UPDATE_IB_PKT_COUNT(ire);
23321 	}
23322 
23323 	/* Advance the offset to the second frag starting point. */
23324 	offset += len;
23325 	/*
23326 	 * Update hdr_len from the copied header - there might be less options
23327 	 * in the later fragments.
23328 	 */
23329 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
23330 	/* Loop until done. */
23331 	for (;;) {
23332 		uint16_t	offset_and_flags;
23333 		uint16_t	ip_len;
23334 
23335 		if (ip_data_end - offset > len) {
23336 			/*
23337 			 * Carve off the appropriate amount from the original
23338 			 * datagram.
23339 			 */
23340 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23341 				mp = NULL;
23342 				break;
23343 			}
23344 			/*
23345 			 * More frags after this one.  Get another copy
23346 			 * of the header.
23347 			 */
23348 			if (carve_mp->b_datap->db_ref == 1 &&
23349 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23350 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23351 				/* Inline IP header */
23352 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23353 				    hdr_mp->b_rptr;
23354 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23355 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23356 				mp = carve_mp;
23357 			} else {
23358 				if (!(mp = copyb(hdr_mp))) {
23359 					freemsg(carve_mp);
23360 					break;
23361 				}
23362 				/* Get priority marking, if any. */
23363 				mp->b_band = carve_mp->b_band;
23364 				mp->b_cont = carve_mp;
23365 			}
23366 			ipha = (ipha_t *)mp->b_rptr;
23367 			offset_and_flags = IPH_MF;
23368 		} else {
23369 			/*
23370 			 * Last frag.  Consume the header. Set len to
23371 			 * the length of this last piece.
23372 			 */
23373 			len = ip_data_end - offset;
23374 
23375 			/*
23376 			 * Carve off the appropriate amount from the original
23377 			 * datagram.
23378 			 */
23379 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23380 				mp = NULL;
23381 				break;
23382 			}
23383 			if (carve_mp->b_datap->db_ref == 1 &&
23384 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23385 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23386 				/* Inline IP header */
23387 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23388 				    hdr_mp->b_rptr;
23389 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23390 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23391 				mp = carve_mp;
23392 				freeb(hdr_mp);
23393 				hdr_mp = mp;
23394 			} else {
23395 				mp = hdr_mp;
23396 				/* Get priority marking, if any. */
23397 				mp->b_band = carve_mp->b_band;
23398 				mp->b_cont = carve_mp;
23399 			}
23400 			ipha = (ipha_t *)mp->b_rptr;
23401 			/* A frag of a frag might have IPH_MF non-zero */
23402 			offset_and_flags =
23403 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23404 			    IPH_MF;
23405 		}
23406 		offset_and_flags |= (uint16_t)(offset >> 3);
23407 		offset_and_flags |= (uint16_t)frag_flag;
23408 		/* Store the offset and flags in the IP header. */
23409 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23410 
23411 		/* Store the length in the IP header. */
23412 		ip_len = (uint16_t)(len + hdr_len);
23413 		ipha->ipha_length = htons(ip_len);
23414 
23415 		/*
23416 		 * Set the IP header checksum.	Note that mp is just
23417 		 * the header, so this is easy to pass to ip_csum.
23418 		 */
23419 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23420 
23421 		/* Attach a transmit header, if any, and ship it. */
23422 		if (pkt_type == OB_PKT) {
23423 			UPDATE_OB_PKT_COUNT(ire);
23424 		} else {
23425 			UPDATE_IB_PKT_COUNT(ire);
23426 		}
23427 
23428 		if (ire->ire_flags & RTF_MULTIRT) {
23429 			irb = ire->ire_bucket;
23430 			ASSERT(irb != NULL);
23431 
23432 			multirt_send = B_TRUE;
23433 
23434 			/*
23435 			 * Save the original ire; we will need to restore it
23436 			 * for the tailing frags.
23437 			 */
23438 			save_ire = ire;
23439 			IRE_REFHOLD(save_ire);
23440 		}
23441 		/*
23442 		 * Emission loop for this fragment, similar
23443 		 * to what is done for the first fragment.
23444 		 */
23445 		do {
23446 			if (multirt_send) {
23447 				/*
23448 				 * We are in a multiple send case, need to get
23449 				 * the next ire and make a copy of the packet.
23450 				 */
23451 				ASSERT(irb != NULL);
23452 				IRB_REFHOLD(irb);
23453 				for (ire1 = ire->ire_next;
23454 				    ire1 != NULL;
23455 				    ire1 = ire1->ire_next) {
23456 					if (!(ire1->ire_flags & RTF_MULTIRT))
23457 						continue;
23458 					if (ire1->ire_addr != ire->ire_addr)
23459 						continue;
23460 					if (ire1->ire_marks &
23461 					    (IRE_MARK_CONDEMNED|
23462 						IRE_MARK_HIDDEN))
23463 						continue;
23464 					/*
23465 					 * Ensure we do not exceed the MTU
23466 					 * of the next route.
23467 					 */
23468 					if (ire1->ire_max_frag < max_frag) {
23469 						ip_multirt_bad_mtu(ire1,
23470 						    max_frag);
23471 						continue;
23472 					}
23473 
23474 					/* Got one. */
23475 					IRE_REFHOLD(ire1);
23476 					break;
23477 				}
23478 				IRB_REFRELE(irb);
23479 
23480 				if (ire1 != NULL) {
23481 					next_mp = copyb(mp);
23482 					if ((next_mp == NULL) ||
23483 					    ((mp->b_cont != NULL) &&
23484 					    ((next_mp->b_cont =
23485 					    dupmsg(mp->b_cont)) == NULL))) {
23486 						freemsg(next_mp);
23487 						next_mp = NULL;
23488 						ire_refrele(ire1);
23489 						ire1 = NULL;
23490 					}
23491 				}
23492 
23493 				/* Last multiroute ire; don't loop anymore. */
23494 				if (ire1 == NULL) {
23495 					multirt_send = B_FALSE;
23496 				}
23497 			}
23498 
23499 			/* Update transmit header */
23500 			ll_hdr_len = 0;
23501 			LOCK_IRE_FP_MP(ire);
23502 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23503 			if (ll_hdr_mp != NULL) {
23504 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23505 				ll_hdr_len = MBLKL(ll_hdr_mp);
23506 			} else {
23507 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
23508 			}
23509 
23510 			if (!ll_hdr_mp) {
23511 				xmit_mp = mp;
23512 
23513 			/*
23514 			 * We have link-layer header that can fit in
23515 			 * our mblk.
23516 			 */
23517 			} else if (mp->b_datap->db_ref == 1 &&
23518 			    ll_hdr_len != 0 &&
23519 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23520 				/* M_DATA fastpath */
23521 				mp->b_rptr -= ll_hdr_len;
23522 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
23523 				    ll_hdr_len);
23524 				xmit_mp = mp;
23525 
23526 			/*
23527 			 * Case of res_mp OR the fastpath mp can't fit
23528 			 * in the mblk
23529 			 */
23530 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
23531 				xmit_mp->b_cont = mp;
23532 				if (DB_CRED(mp) != NULL)
23533 					mblk_setcred(xmit_mp, DB_CRED(mp));
23534 				/* Get priority marking, if any. */
23535 				if (DB_TYPE(xmit_mp) == M_DATA)
23536 					xmit_mp->b_band = mp->b_band;
23537 
23538 			/* Corner case if copyb failed */
23539 			} else {
23540 				/*
23541 				 * Exit both the replication and
23542 				 * fragmentation loops.
23543 				 */
23544 				UNLOCK_IRE_FP_MP(ire);
23545 				goto drop_pkt;
23546 			}
23547 			UNLOCK_IRE_FP_MP(ire);
23548 			BUMP_MIB(&ip_mib, ipFragCreates);
23549 			putnext(q, xmit_mp);
23550 
23551 			if (pkt_type != OB_PKT) {
23552 				/*
23553 				 * Update the packet count of trailing
23554 				 * RTF_MULTIRT ires.
23555 				 */
23556 				UPDATE_OB_PKT_COUNT(ire);
23557 			}
23558 
23559 			/* All done if we just consumed the hdr_mp. */
23560 			if (mp == hdr_mp) {
23561 				last_frag = B_TRUE;
23562 			}
23563 
23564 			if (multirt_send) {
23565 				/*
23566 				 * We are in a multiple send case; look for
23567 				 * the next ire and re-enter the loop.
23568 				 */
23569 				ASSERT(ire1);
23570 				ASSERT(next_mp);
23571 				/* REFRELE the current ire before looping */
23572 				ire_refrele(ire);
23573 				ire = ire1;
23574 				ire1 = NULL;
23575 				q = ire->ire_stq;
23576 				mp = next_mp;
23577 				next_mp = NULL;
23578 			}
23579 		} while (multirt_send);
23580 		/*
23581 		 * Restore the original ire; we need it for the
23582 		 * trailing frags
23583 		 */
23584 		if (save_ire != NULL) {
23585 			ASSERT(ire1 == NULL);
23586 			/* REFRELE the last iterated ire */
23587 			ire_refrele(ire);
23588 			/* save_ire has been REFHOLDed */
23589 			ire = save_ire;
23590 			q = ire->ire_stq;
23591 			save_ire = NULL;
23592 		}
23593 
23594 		if (last_frag) {
23595 			BUMP_MIB(&ip_mib, ipFragOKs);
23596 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23597 			    "ip_wput_frag_end:(%S)",
23598 			    "consumed hdr_mp");
23599 
23600 			if (first_ire != NULL)
23601 				ire_refrele(first_ire);
23602 			return;
23603 		}
23604 		/* Otherwise, advance and loop. */
23605 		offset += len;
23606 	}
23607 
23608 drop_pkt:
23609 	/* Clean up following allocation failure. */
23610 	BUMP_MIB(&ip_mib, ipOutDiscards);
23611 	freemsg(mp);
23612 	if (mp != hdr_mp)
23613 		freeb(hdr_mp);
23614 	if (mp != mp_orig)
23615 		freemsg(mp_orig);
23616 
23617 	if (save_ire != NULL)
23618 		IRE_REFRELE(save_ire);
23619 	if (first_ire != NULL)
23620 		ire_refrele(first_ire);
23621 
23622 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23623 	    "ip_wput_frag_end:(%S)",
23624 	    "end--alloc failure");
23625 }
23626 
23627 /*
23628  * Copy the header plus those options which have the copy bit set
23629  */
23630 static mblk_t *
23631 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
23632 {
23633 	mblk_t	*mp;
23634 	uchar_t	*up;
23635 
23636 	/*
23637 	 * Quick check if we need to look for options without the copy bit
23638 	 * set
23639 	 */
23640 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
23641 	if (!mp)
23642 		return (mp);
23643 	mp->b_rptr += ip_wroff_extra;
23644 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
23645 		bcopy(rptr, mp->b_rptr, hdr_len);
23646 		mp->b_wptr += hdr_len + ip_wroff_extra;
23647 		return (mp);
23648 	}
23649 	up  = mp->b_rptr;
23650 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
23651 	up += IP_SIMPLE_HDR_LENGTH;
23652 	rptr += IP_SIMPLE_HDR_LENGTH;
23653 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
23654 	while (hdr_len > 0) {
23655 		uint32_t optval;
23656 		uint32_t optlen;
23657 
23658 		optval = *rptr;
23659 		if (optval == IPOPT_EOL)
23660 			break;
23661 		if (optval == IPOPT_NOP)
23662 			optlen = 1;
23663 		else
23664 			optlen = rptr[1];
23665 		if (optval & IPOPT_COPY) {
23666 			bcopy(rptr, up, optlen);
23667 			up += optlen;
23668 		}
23669 		rptr += optlen;
23670 		hdr_len -= optlen;
23671 	}
23672 	/*
23673 	 * Make sure that we drop an even number of words by filling
23674 	 * with EOL to the next word boundary.
23675 	 */
23676 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
23677 	    hdr_len & 0x3; hdr_len++)
23678 		*up++ = IPOPT_EOL;
23679 	mp->b_wptr = up;
23680 	/* Update header length */
23681 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
23682 	return (mp);
23683 }
23684 
23685 /*
23686  * Delivery to local recipients including fanout to multiple recipients.
23687  * Does not do checksumming of UDP/TCP.
23688  * Note: q should be the read side queue for either the ill or conn.
23689  * Note: rq should be the read side q for the lower (ill) stream.
23690  * We don't send packets to IPPF processing, thus the last argument
23691  * to all the fanout calls are B_FALSE.
23692  */
23693 void
23694 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
23695     int fanout_flags, zoneid_t zoneid)
23696 {
23697 	uint32_t	protocol;
23698 	mblk_t		*first_mp;
23699 	boolean_t	mctl_present;
23700 	int		ire_type;
23701 #define	rptr	((uchar_t *)ipha)
23702 
23703 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
23704 	    "ip_wput_local_start: q %p", q);
23705 
23706 	if (ire != NULL) {
23707 		ire_type = ire->ire_type;
23708 	} else {
23709 		/*
23710 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
23711 		 * packet is not multicast, we can't tell the ire type.
23712 		 */
23713 		ASSERT(CLASSD(ipha->ipha_dst));
23714 		ire_type = IRE_BROADCAST;
23715 	}
23716 
23717 	first_mp = mp;
23718 	if (first_mp->b_datap->db_type == M_CTL) {
23719 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
23720 		if (!io->ipsec_out_secure) {
23721 			/*
23722 			 * This ipsec_out_t was allocated in ip_wput
23723 			 * for multicast packets to store the ill_index.
23724 			 * As this is being delivered locally, we don't
23725 			 * need this anymore.
23726 			 */
23727 			mp = first_mp->b_cont;
23728 			freeb(first_mp);
23729 			first_mp = mp;
23730 			mctl_present = B_FALSE;
23731 		} else {
23732 			mctl_present = B_TRUE;
23733 			mp = first_mp->b_cont;
23734 			ASSERT(mp != NULL);
23735 			ipsec_out_to_in(first_mp);
23736 		}
23737 	} else {
23738 		mctl_present = B_FALSE;
23739 	}
23740 
23741 	loopback_packets++;
23742 
23743 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
23744 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
23745 	if (!IS_SIMPLE_IPH(ipha)) {
23746 		ip_wput_local_options(ipha);
23747 	}
23748 
23749 	protocol = ipha->ipha_protocol;
23750 	switch (protocol) {
23751 	case IPPROTO_ICMP: {
23752 		ire_t		*ire_zone;
23753 		ilm_t		*ilm;
23754 		mblk_t		*mp1;
23755 		zoneid_t	last_zoneid;
23756 
23757 		if (CLASSD(ipha->ipha_dst) &&
23758 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
23759 			ASSERT(ire_type == IRE_BROADCAST);
23760 			/*
23761 			 * In the multicast case, applications may have joined
23762 			 * the group from different zones, so we need to deliver
23763 			 * the packet to each of them. Loop through the
23764 			 * multicast memberships structures (ilm) on the receive
23765 			 * ill and send a copy of the packet up each matching
23766 			 * one. However, we don't do this for multicasts sent on
23767 			 * the loopback interface (PHYI_LOOPBACK flag set) as
23768 			 * they must stay in the sender's zone.
23769 			 *
23770 			 * ilm_add_v6() ensures that ilms in the same zone are
23771 			 * contiguous in the ill_ilm list. We use this property
23772 			 * to avoid sending duplicates needed when two
23773 			 * applications in the same zone join the same group on
23774 			 * different logical interfaces: we ignore the ilm if
23775 			 * it's zoneid is the same as the last matching one.
23776 			 * In addition, the sending of the packet for
23777 			 * ire_zoneid is delayed until all of the other ilms
23778 			 * have been exhausted.
23779 			 */
23780 			last_zoneid = -1;
23781 			ILM_WALKER_HOLD(ill);
23782 			for (ilm = ill->ill_ilm; ilm != NULL;
23783 			    ilm = ilm->ilm_next) {
23784 				if ((ilm->ilm_flags & ILM_DELETED) ||
23785 				    ipha->ipha_dst != ilm->ilm_addr ||
23786 				    ilm->ilm_zoneid == last_zoneid ||
23787 				    ilm->ilm_zoneid == zoneid ||
23788 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
23789 					continue;
23790 				mp1 = ip_copymsg(first_mp);
23791 				if (mp1 == NULL)
23792 					continue;
23793 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23794 				    mctl_present, B_FALSE, ill,
23795 				    ilm->ilm_zoneid);
23796 				last_zoneid = ilm->ilm_zoneid;
23797 			}
23798 			ILM_WALKER_RELE(ill);
23799 			/*
23800 			 * Loopback case: the sending endpoint has
23801 			 * IP_MULTICAST_LOOP disabled, therefore we don't
23802 			 * dispatch the multicast packet to the sending zone.
23803 			 */
23804 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
23805 				freemsg(first_mp);
23806 				return;
23807 			}
23808 		} else if (ire_type == IRE_BROADCAST) {
23809 			/*
23810 			 * In the broadcast case, there may be many zones
23811 			 * which need a copy of the packet delivered to them.
23812 			 * There is one IRE_BROADCAST per broadcast address
23813 			 * and per zone; we walk those using a helper function.
23814 			 * In addition, the sending of the packet for zoneid is
23815 			 * delayed until all of the other ires have been
23816 			 * processed.
23817 			 */
23818 			IRB_REFHOLD(ire->ire_bucket);
23819 			ire_zone = NULL;
23820 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
23821 			    ire)) != NULL) {
23822 				mp1 = ip_copymsg(first_mp);
23823 				if (mp1 == NULL)
23824 					continue;
23825 
23826 				UPDATE_IB_PKT_COUNT(ire_zone);
23827 				ire_zone->ire_last_used_time = lbolt;
23828 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23829 				    mctl_present, B_FALSE, ill,
23830 				    ire_zone->ire_zoneid);
23831 			}
23832 			IRB_REFRELE(ire->ire_bucket);
23833 		}
23834 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
23835 		    0, mctl_present, B_FALSE, ill, zoneid);
23836 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23837 		    "ip_wput_local_end: q %p (%S)",
23838 		    q, "icmp");
23839 		return;
23840 	}
23841 	case IPPROTO_IGMP:
23842 		if (igmp_input(q, mp, ill)) {
23843 			/* Bad packet - discarded by igmp_input */
23844 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23845 			    "ip_wput_local_end: q %p (%S)",
23846 			    q, "igmp_input--bad packet");
23847 			if (mctl_present)
23848 				freeb(first_mp);
23849 			return;
23850 		}
23851 		/*
23852 		 * igmp_input() may have pulled up the message so ipha needs to
23853 		 * be reinitialized.
23854 		 */
23855 		ipha = (ipha_t *)mp->b_rptr;
23856 		/* deliver to local raw users */
23857 		break;
23858 	case IPPROTO_ENCAP:
23859 		/*
23860 		 * This case is covered by either ip_fanout_proto, or by
23861 		 * the above security processing for self-tunneled packets.
23862 		 */
23863 		break;
23864 	case IPPROTO_UDP: {
23865 		uint16_t	*up;
23866 		uint32_t	ports;
23867 
23868 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
23869 		    UDP_PORTS_OFFSET);
23870 		/* Force a 'valid' checksum. */
23871 		up[3] = 0;
23872 
23873 		ports = *(uint32_t *)up;
23874 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
23875 		    (ire_type == IRE_BROADCAST),
23876 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23877 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
23878 		    ill, zoneid);
23879 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23880 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
23881 		return;
23882 	}
23883 	case IPPROTO_TCP: {
23884 
23885 		/*
23886 		 * For TCP, discard broadcast packets.
23887 		 */
23888 		if ((ushort_t)ire_type == IRE_BROADCAST) {
23889 			freemsg(first_mp);
23890 			BUMP_MIB(&ip_mib, ipInDiscards);
23891 			ip2dbg(("ip_wput_local: discard broadcast\n"));
23892 			return;
23893 		}
23894 
23895 		if (mp->b_datap->db_type == M_DATA) {
23896 			/*
23897 			 * M_DATA mblk, so init mblk (chain) for no struio().
23898 			 */
23899 			mblk_t	*mp1 = mp;
23900 
23901 			do
23902 				mp1->b_datap->db_struioflag = 0;
23903 			while ((mp1 = mp1->b_cont) != NULL);
23904 		}
23905 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
23906 		    <= mp->b_wptr);
23907 		ip_fanout_tcp(q, first_mp, ill, ipha,
23908 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23909 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
23910 		    mctl_present, B_FALSE, zoneid);
23911 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23912 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
23913 		return;
23914 	}
23915 	case IPPROTO_SCTP:
23916 	{
23917 		uint32_t	ports;
23918 
23919 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
23920 		ip_fanout_sctp(first_mp, ill, ipha, ports,
23921 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23922 		    IP_FF_IP6INFO,
23923 		    mctl_present, B_FALSE, 0, zoneid);
23924 		return;
23925 	}
23926 
23927 	default:
23928 		break;
23929 	}
23930 	/*
23931 	 * Find a client for some other protocol.  We give
23932 	 * copies to multiple clients, if more than one is
23933 	 * bound.
23934 	 */
23935 	ip_fanout_proto(q, first_mp, ill, ipha,
23936 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
23937 	    mctl_present, B_FALSE, ill, zoneid);
23938 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23939 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
23940 #undef	rptr
23941 }
23942 
23943 /*
23944  * Update any source route, record route, or timestamp options.
23945  * Check that we are at end of strict source route.
23946  * The options have been sanity checked by ip_wput_options().
23947  */
23948 static void
23949 ip_wput_local_options(ipha_t *ipha)
23950 {
23951 	ipoptp_t	opts;
23952 	uchar_t		*opt;
23953 	uint8_t		optval;
23954 	uint8_t		optlen;
23955 	ipaddr_t	dst;
23956 	uint32_t	ts;
23957 	ire_t		*ire;
23958 	timestruc_t	now;
23959 
23960 	ip2dbg(("ip_wput_local_options\n"));
23961 	for (optval = ipoptp_first(&opts, ipha);
23962 	    optval != IPOPT_EOL;
23963 	    optval = ipoptp_next(&opts)) {
23964 		opt = opts.ipoptp_cur;
23965 		optlen = opts.ipoptp_len;
23966 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
23967 		switch (optval) {
23968 			uint32_t off;
23969 		case IPOPT_SSRR:
23970 		case IPOPT_LSRR:
23971 			off = opt[IPOPT_OFFSET];
23972 			off--;
23973 			if (optlen < IP_ADDR_LEN ||
23974 			    off > optlen - IP_ADDR_LEN) {
23975 				/* End of source route */
23976 				break;
23977 			}
23978 			/*
23979 			 * This will only happen if two consecutive entries
23980 			 * in the source route contains our address or if
23981 			 * it is a packet with a loose source route which
23982 			 * reaches us before consuming the whole source route
23983 			 */
23984 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
23985 			if (optval == IPOPT_SSRR) {
23986 				return;
23987 			}
23988 			/*
23989 			 * Hack: instead of dropping the packet truncate the
23990 			 * source route to what has been used by filling the
23991 			 * rest with IPOPT_NOP.
23992 			 */
23993 			opt[IPOPT_OLEN] = (uint8_t)off;
23994 			while (off < optlen) {
23995 				opt[off++] = IPOPT_NOP;
23996 			}
23997 			break;
23998 		case IPOPT_RR:
23999 			off = opt[IPOPT_OFFSET];
24000 			off--;
24001 			if (optlen < IP_ADDR_LEN ||
24002 			    off > optlen - IP_ADDR_LEN) {
24003 				/* No more room - ignore */
24004 				ip1dbg((
24005 				    "ip_wput_forward_options: end of RR\n"));
24006 				break;
24007 			}
24008 			dst = htonl(INADDR_LOOPBACK);
24009 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24010 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24011 			break;
24012 		case IPOPT_TS:
24013 			/* Insert timestamp if there is romm */
24014 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24015 			case IPOPT_TS_TSONLY:
24016 				off = IPOPT_TS_TIMELEN;
24017 				break;
24018 			case IPOPT_TS_PRESPEC:
24019 			case IPOPT_TS_PRESPEC_RFC791:
24020 				/* Verify that the address matched */
24021 				off = opt[IPOPT_OFFSET] - 1;
24022 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
24023 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
24024 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
24025 				if (ire == NULL) {
24026 					/* Not for us */
24027 					break;
24028 				}
24029 				ire_refrele(ire);
24030 				/* FALLTHRU */
24031 			case IPOPT_TS_TSANDADDR:
24032 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24033 				break;
24034 			default:
24035 				/*
24036 				 * ip_*put_options should have already
24037 				 * dropped this packet.
24038 				 */
24039 				cmn_err(CE_PANIC, "ip_wput_local_options: "
24040 				    "unknown IT - bug in ip_wput_options?\n");
24041 				return;	/* Keep "lint" happy */
24042 			}
24043 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
24044 				/* Increase overflow counter */
24045 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
24046 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
24047 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
24048 				    (off << 4);
24049 				break;
24050 			}
24051 			off = opt[IPOPT_OFFSET] - 1;
24052 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24053 			case IPOPT_TS_PRESPEC:
24054 			case IPOPT_TS_PRESPEC_RFC791:
24055 			case IPOPT_TS_TSANDADDR:
24056 				dst = htonl(INADDR_LOOPBACK);
24057 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24058 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24059 				/* FALLTHRU */
24060 			case IPOPT_TS_TSONLY:
24061 				off = opt[IPOPT_OFFSET] - 1;
24062 				/* Compute # of milliseconds since midnight */
24063 				gethrestime(&now);
24064 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
24065 				    now.tv_nsec / (NANOSEC / MILLISEC);
24066 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
24067 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
24068 				break;
24069 			}
24070 			break;
24071 		}
24072 	}
24073 }
24074 
24075 /*
24076  * Send out a multicast packet on interface ipif.
24077  * The sender does not have an conn.
24078  * Caller verifies that this isn't a PHYI_LOOPBACK.
24079  */
24080 void
24081 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
24082 {
24083 	ipha_t	*ipha;
24084 	ire_t	*ire;
24085 	ipaddr_t	dst;
24086 	mblk_t		*first_mp;
24087 
24088 	/* igmp_sendpkt always allocates a ipsec_out_t */
24089 	ASSERT(mp->b_datap->db_type == M_CTL);
24090 	ASSERT(!ipif->ipif_isv6);
24091 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
24092 
24093 	first_mp = mp;
24094 	mp = first_mp->b_cont;
24095 	ASSERT(mp->b_datap->db_type == M_DATA);
24096 	ipha = (ipha_t *)mp->b_rptr;
24097 
24098 	/*
24099 	 * Find an IRE which matches the destination and the outgoing
24100 	 * queue (i.e. the outgoing interface.)
24101 	 */
24102 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
24103 		dst = ipif->ipif_pp_dst_addr;
24104 	else
24105 		dst = ipha->ipha_dst;
24106 	/*
24107 	 * The source address has already been initialized by the
24108 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
24109 	 * be sufficient rather than MATCH_IRE_IPIF.
24110 	 *
24111 	 * This function is used for sending IGMP packets. We need
24112 	 * to make sure that we send the packet out of the interface
24113 	 * (ipif->ipif_ill) where we joined the group. This is to
24114 	 * prevent from switches doing IGMP snooping to send us multicast
24115 	 * packets for a given group on the interface we have joined.
24116 	 * If we can't find an ire, igmp_sendpkt has already initialized
24117 	 * ipsec_out_attach_if so that this will not be load spread in
24118 	 * ip_newroute_ipif.
24119 	 */
24120 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, NULL,
24121 	    MATCH_IRE_ILL);
24122 	if (!ire) {
24123 		/*
24124 		 * Mark this packet to make it be delivered to
24125 		 * ip_wput_ire after the new ire has been
24126 		 * created.
24127 		 */
24128 		mp->b_prev = NULL;
24129 		mp->b_next = NULL;
24130 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
24131 		return;
24132 	}
24133 
24134 	/*
24135 	 * Honor the RTF_SETSRC flag; this is the only case
24136 	 * where we force this addr whatever the current src addr is,
24137 	 * because this address is set by igmp_sendpkt(), and
24138 	 * cannot be specified by any user.
24139 	 */
24140 	if (ire->ire_flags & RTF_SETSRC) {
24141 		ipha->ipha_src = ire->ire_src_addr;
24142 	}
24143 
24144 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
24145 }
24146 
24147 /*
24148  * NOTE : This function does not ire_refrele the ire argument passed in.
24149  *
24150  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
24151  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
24152  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
24153  * the ire_lock to access the nce_fp_mp in this case.
24154  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
24155  * prepending a fastpath message IPQoS processing must precede it, we also set
24156  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
24157  * (IPQoS might have set the b_band for CoS marking).
24158  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
24159  * must follow it so that IPQoS can mark the dl_priority field for CoS
24160  * marking, if needed.
24161  */
24162 static mblk_t *
24163 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
24164 {
24165 	uint_t	hlen;
24166 	ipha_t *ipha;
24167 	mblk_t *mp1;
24168 	boolean_t qos_done = B_FALSE;
24169 	uchar_t	*ll_hdr;
24170 
24171 #define	rptr	((uchar_t *)ipha)
24172 
24173 	ipha = (ipha_t *)mp->b_rptr;
24174 	hlen = 0;
24175 	LOCK_IRE_FP_MP(ire);
24176 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
24177 		ASSERT(DB_TYPE(mp1) == M_DATA);
24178 		/* Initiate IPPF processing */
24179 		if ((proc != 0) && IPP_ENABLED(proc)) {
24180 			UNLOCK_IRE_FP_MP(ire);
24181 			ip_process(proc, &mp, ill_index);
24182 			if (mp == NULL)
24183 				return (NULL);
24184 
24185 			ipha = (ipha_t *)mp->b_rptr;
24186 			LOCK_IRE_FP_MP(ire);
24187 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
24188 				qos_done = B_TRUE;
24189 				goto no_fp_mp;
24190 			}
24191 			ASSERT(DB_TYPE(mp1) == M_DATA);
24192 		}
24193 		hlen = MBLKL(mp1);
24194 		/*
24195 		 * Check if we have enough room to prepend fastpath
24196 		 * header
24197 		 */
24198 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
24199 			ll_hdr = rptr - hlen;
24200 			bcopy(mp1->b_rptr, ll_hdr, hlen);
24201 			/*
24202 			 * Set the b_rptr to the start of the link layer
24203 			 * header
24204 			 */
24205 			mp->b_rptr = ll_hdr;
24206 			mp1 = mp;
24207 		} else {
24208 			mp1 = copyb(mp1);
24209 			if (mp1 == NULL)
24210 				goto unlock_err;
24211 			mp1->b_band = mp->b_band;
24212 			mp1->b_cont = mp;
24213 			/*
24214 			 * certain system generated traffic may not
24215 			 * have cred/label in ip header block. This
24216 			 * is true even for a labeled system. But for
24217 			 * labeled traffic, inherit the label in the
24218 			 * new header.
24219 			 */
24220 			if (DB_CRED(mp) != NULL)
24221 				mblk_setcred(mp1, DB_CRED(mp));
24222 			/*
24223 			 * XXX disable ICK_VALID and compute checksum
24224 			 * here; can happen if nce_fp_mp changes and
24225 			 * it can't be copied now due to insufficient
24226 			 * space. (unlikely, fp mp can change, but it
24227 			 * does not increase in length)
24228 			 */
24229 		}
24230 		UNLOCK_IRE_FP_MP(ire);
24231 	} else {
24232 no_fp_mp:
24233 		mp1 = copyb(ire->ire_nce->nce_res_mp);
24234 		if (mp1 == NULL) {
24235 unlock_err:
24236 			UNLOCK_IRE_FP_MP(ire);
24237 			freemsg(mp);
24238 			return (NULL);
24239 		}
24240 		UNLOCK_IRE_FP_MP(ire);
24241 		mp1->b_cont = mp;
24242 		/*
24243 		 * certain system generated traffic may not
24244 		 * have cred/label in ip header block. This
24245 		 * is true even for a labeled system. But for
24246 		 * labeled traffic, inherit the label in the
24247 		 * new header.
24248 		 */
24249 		if (DB_CRED(mp) != NULL)
24250 			mblk_setcred(mp1, DB_CRED(mp));
24251 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
24252 			ip_process(proc, &mp1, ill_index);
24253 			if (mp1 == NULL)
24254 				return (NULL);
24255 		}
24256 	}
24257 	return (mp1);
24258 #undef rptr
24259 }
24260 
24261 /*
24262  * Finish the outbound IPsec processing for an IPv6 packet. This function
24263  * is called from ipsec_out_process() if the IPsec packet was processed
24264  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24265  * asynchronously.
24266  */
24267 void
24268 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
24269     ire_t *ire_arg)
24270 {
24271 	in6_addr_t *v6dstp;
24272 	ire_t *ire;
24273 	mblk_t *mp;
24274 	uint_t	ill_index;
24275 	ipsec_out_t *io;
24276 	boolean_t attach_if, hwaccel;
24277 	uint32_t flags = IP6_NO_IPPOLICY;
24278 	int match_flags;
24279 	zoneid_t zoneid;
24280 	boolean_t ill_need_rele = B_FALSE;
24281 	boolean_t ire_need_rele = B_FALSE;
24282 
24283 	mp = ipsec_mp->b_cont;
24284 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24285 	ill_index = io->ipsec_out_ill_index;
24286 	if (io->ipsec_out_reachable) {
24287 		flags |= IPV6_REACHABILITY_CONFIRMATION;
24288 	}
24289 	attach_if = io->ipsec_out_attach_if;
24290 	hwaccel = io->ipsec_out_accelerated;
24291 	zoneid = io->ipsec_out_zoneid;
24292 	ASSERT(zoneid != ALL_ZONES);
24293 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24294 	/* Multicast addresses should have non-zero ill_index. */
24295 	v6dstp = &ip6h->ip6_dst;
24296 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
24297 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
24298 	ASSERT(!attach_if || ill_index != 0);
24299 	if (ill_index != 0) {
24300 		if (ill == NULL) {
24301 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
24302 			    B_TRUE);
24303 
24304 			/* Failure case frees things for us. */
24305 			if (ill == NULL)
24306 				return;
24307 
24308 			ill_need_rele = B_TRUE;
24309 		}
24310 		/*
24311 		 * If this packet needs to go out on a particular interface
24312 		 * honor it.
24313 		 */
24314 		if (attach_if) {
24315 			match_flags = MATCH_IRE_ILL;
24316 
24317 			/*
24318 			 * Check if we need an ire that will not be
24319 			 * looked up by anybody else i.e. HIDDEN.
24320 			 */
24321 			if (ill_is_probeonly(ill)) {
24322 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24323 			}
24324 		}
24325 	}
24326 	ASSERT(mp != NULL);
24327 
24328 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
24329 		boolean_t unspec_src;
24330 		ipif_t	*ipif;
24331 
24332 		/*
24333 		 * Use the ill_index to get the right ill.
24334 		 */
24335 		unspec_src = io->ipsec_out_unspec_src;
24336 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24337 		if (ipif == NULL) {
24338 			if (ill_need_rele)
24339 				ill_refrele(ill);
24340 			freemsg(ipsec_mp);
24341 			return;
24342 		}
24343 
24344 		if (ire_arg != NULL) {
24345 			ire = ire_arg;
24346 		} else {
24347 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24348 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24349 			ire_need_rele = B_TRUE;
24350 		}
24351 		if (ire != NULL) {
24352 			ipif_refrele(ipif);
24353 			/*
24354 			 * XXX Do the multicast forwarding now, as the IPSEC
24355 			 * processing has been done.
24356 			 */
24357 			goto send;
24358 		}
24359 
24360 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
24361 		mp->b_prev = NULL;
24362 		mp->b_next = NULL;
24363 
24364 		/*
24365 		 * If the IPsec packet was processed asynchronously,
24366 		 * drop it now.
24367 		 */
24368 		if (q == NULL) {
24369 			if (ill_need_rele)
24370 				ill_refrele(ill);
24371 			freemsg(ipsec_mp);
24372 			return;
24373 		}
24374 
24375 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
24376 		    unspec_src, zoneid);
24377 		ipif_refrele(ipif);
24378 	} else {
24379 		if (attach_if) {
24380 			ipif_t	*ipif;
24381 
24382 			ipif = ipif_get_next_ipif(NULL, ill);
24383 			if (ipif == NULL) {
24384 				if (ill_need_rele)
24385 					ill_refrele(ill);
24386 				freemsg(ipsec_mp);
24387 				return;
24388 			}
24389 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24390 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24391 			ire_need_rele = B_TRUE;
24392 			ipif_refrele(ipif);
24393 		} else {
24394 			if (ire_arg != NULL) {
24395 				ire = ire_arg;
24396 			} else {
24397 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
24398 				ire_need_rele = B_TRUE;
24399 			}
24400 		}
24401 		if (ire != NULL)
24402 			goto send;
24403 		/*
24404 		 * ire disappeared underneath.
24405 		 *
24406 		 * What we need to do here is the ip_newroute
24407 		 * logic to get the ire without doing the IPSEC
24408 		 * processing. Follow the same old path. But this
24409 		 * time, ip_wput or ire_add_then_send will call us
24410 		 * directly as all the IPSEC operations are done.
24411 		 */
24412 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
24413 		mp->b_prev = NULL;
24414 		mp->b_next = NULL;
24415 
24416 		/*
24417 		 * If the IPsec packet was processed asynchronously,
24418 		 * drop it now.
24419 		 */
24420 		if (q == NULL) {
24421 			if (ill_need_rele)
24422 				ill_refrele(ill);
24423 			freemsg(ipsec_mp);
24424 			return;
24425 		}
24426 
24427 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
24428 		    zoneid);
24429 	}
24430 	if (ill != NULL && ill_need_rele)
24431 		ill_refrele(ill);
24432 	return;
24433 send:
24434 	if (ill != NULL && ill_need_rele)
24435 		ill_refrele(ill);
24436 
24437 	/* Local delivery */
24438 	if (ire->ire_stq == NULL) {
24439 		ASSERT(q != NULL);
24440 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
24441 		    ire, 0);
24442 		if (ire_need_rele)
24443 			ire_refrele(ire);
24444 		return;
24445 	}
24446 	/*
24447 	 * Everything is done. Send it out on the wire.
24448 	 * We force the insertion of a fragment header using the
24449 	 * IPH_FRAG_HDR flag in two cases:
24450 	 * - after reception of an ICMPv6 "packet too big" message
24451 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
24452 	 * - for multirouted IPv6 packets, so that the receiver can
24453 	 *   discard duplicates according to their fragment identifier
24454 	 */
24455 	/* XXX fix flow control problems. */
24456 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
24457 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
24458 		if (hwaccel) {
24459 			/*
24460 			 * hardware acceleration does not handle these
24461 			 * "slow path" cases.
24462 			 */
24463 			/* IPsec KSTATS: should bump bean counter here. */
24464 			if (ire_need_rele)
24465 				ire_refrele(ire);
24466 			freemsg(ipsec_mp);
24467 			return;
24468 		}
24469 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
24470 		    (mp->b_cont ? msgdsize(mp) :
24471 		    mp->b_wptr - (uchar_t *)ip6h)) {
24472 			/* IPsec KSTATS: should bump bean counter here. */
24473 			ip0dbg(("Packet length mismatch: %d, %ld\n",
24474 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
24475 			    msgdsize(mp)));
24476 			if (ire_need_rele)
24477 				ire_refrele(ire);
24478 			freemsg(ipsec_mp);
24479 			return;
24480 		}
24481 		ASSERT(mp->b_prev == NULL);
24482 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
24483 		    ntohs(ip6h->ip6_plen) +
24484 		    IPV6_HDR_LEN, ire->ire_max_frag));
24485 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
24486 		    ire->ire_max_frag);
24487 	} else {
24488 		UPDATE_OB_PKT_COUNT(ire);
24489 		ire->ire_last_used_time = lbolt;
24490 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
24491 	}
24492 	if (ire_need_rele)
24493 		ire_refrele(ire);
24494 	freeb(ipsec_mp);
24495 }
24496 
24497 void
24498 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
24499 {
24500 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
24501 	da_ipsec_t *hada;	/* data attributes */
24502 	ill_t *ill = (ill_t *)q->q_ptr;
24503 
24504 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
24505 
24506 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
24507 		/* IPsec KSTATS: Bump lose counter here! */
24508 		freemsg(mp);
24509 		return;
24510 	}
24511 
24512 	/*
24513 	 * It's an IPsec packet that must be
24514 	 * accelerated by the Provider, and the
24515 	 * outbound ill is IPsec acceleration capable.
24516 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
24517 	 * to the ill.
24518 	 * IPsec KSTATS: should bump packet counter here.
24519 	 */
24520 
24521 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
24522 	if (hada_mp == NULL) {
24523 		/* IPsec KSTATS: should bump packet counter here. */
24524 		freemsg(mp);
24525 		return;
24526 	}
24527 
24528 	hada_mp->b_datap->db_type = M_CTL;
24529 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
24530 	hada_mp->b_cont = mp;
24531 
24532 	hada = (da_ipsec_t *)hada_mp->b_rptr;
24533 	bzero(hada, sizeof (da_ipsec_t));
24534 	hada->da_type = IPHADA_M_CTL;
24535 
24536 	putnext(q, hada_mp);
24537 }
24538 
24539 /*
24540  * Finish the outbound IPsec processing. This function is called from
24541  * ipsec_out_process() if the IPsec packet was processed
24542  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24543  * asynchronously.
24544  */
24545 void
24546 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
24547     ire_t *ire_arg)
24548 {
24549 	uint32_t v_hlen_tos_len;
24550 	ipaddr_t	dst;
24551 	ipif_t	*ipif = NULL;
24552 	ire_t *ire;
24553 	ire_t *ire1 = NULL;
24554 	mblk_t *next_mp = NULL;
24555 	uint32_t max_frag;
24556 	boolean_t multirt_send = B_FALSE;
24557 	mblk_t *mp;
24558 	mblk_t *mp1;
24559 	uint_t	ill_index;
24560 	ipsec_out_t *io;
24561 	boolean_t attach_if;
24562 	int match_flags, offset;
24563 	irb_t *irb = NULL;
24564 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
24565 	zoneid_t zoneid;
24566 	uint32_t cksum;
24567 	uint16_t *up;
24568 	ipxmit_state_t	pktxmit_state;
24569 #ifdef	_BIG_ENDIAN
24570 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
24571 #else
24572 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
24573 #endif
24574 
24575 	mp = ipsec_mp->b_cont;
24576 	ASSERT(mp != NULL);
24577 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24578 	dst = ipha->ipha_dst;
24579 
24580 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24581 	ill_index = io->ipsec_out_ill_index;
24582 	attach_if = io->ipsec_out_attach_if;
24583 	zoneid = io->ipsec_out_zoneid;
24584 	ASSERT(zoneid != ALL_ZONES);
24585 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24586 	if (ill_index != 0) {
24587 		if (ill == NULL) {
24588 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
24589 			    ill_index, B_FALSE);
24590 
24591 			/* Failure case frees things for us. */
24592 			if (ill == NULL)
24593 				return;
24594 
24595 			ill_need_rele = B_TRUE;
24596 		}
24597 		/*
24598 		 * If this packet needs to go out on a particular interface
24599 		 * honor it.
24600 		 */
24601 		if (attach_if) {
24602 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
24603 
24604 			/*
24605 			 * Check if we need an ire that will not be
24606 			 * looked up by anybody else i.e. HIDDEN.
24607 			 */
24608 			if (ill_is_probeonly(ill)) {
24609 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24610 			}
24611 		}
24612 	}
24613 
24614 	if (CLASSD(dst)) {
24615 		boolean_t conn_dontroute;
24616 		/*
24617 		 * Use the ill_index to get the right ipif.
24618 		 */
24619 		conn_dontroute = io->ipsec_out_dontroute;
24620 		if (ill_index == 0)
24621 			ipif = ipif_lookup_group(dst, zoneid);
24622 		else
24623 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24624 		if (ipif == NULL) {
24625 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
24626 			    " multicast\n"));
24627 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
24628 			freemsg(ipsec_mp);
24629 			goto done;
24630 		}
24631 		/*
24632 		 * ipha_src has already been intialized with the
24633 		 * value of the ipif in ip_wput. All we need now is
24634 		 * an ire to send this downstream.
24635 		 */
24636 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
24637 		    MBLK_GETLABEL(mp), match_flags);
24638 		if (ire != NULL) {
24639 			ill_t *ill1;
24640 			/*
24641 			 * Do the multicast forwarding now, as the IPSEC
24642 			 * processing has been done.
24643 			 */
24644 			if (ip_g_mrouter && !conn_dontroute &&
24645 			    (ill1 = ire_to_ill(ire))) {
24646 				if (ip_mforward(ill1, ipha, mp)) {
24647 					freemsg(ipsec_mp);
24648 					ip1dbg(("ip_wput_ipsec_out: mforward "
24649 					    "failed\n"));
24650 					ire_refrele(ire);
24651 					goto done;
24652 				}
24653 			}
24654 			goto send;
24655 		}
24656 
24657 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
24658 		mp->b_prev = NULL;
24659 		mp->b_next = NULL;
24660 
24661 		/*
24662 		 * If the IPsec packet was processed asynchronously,
24663 		 * drop it now.
24664 		 */
24665 		if (q == NULL) {
24666 			freemsg(ipsec_mp);
24667 			goto done;
24668 		}
24669 
24670 		/*
24671 		 * We may be using a wrong ipif to create the ire.
24672 		 * But it is okay as the source address is assigned
24673 		 * for the packet already. Next outbound packet would
24674 		 * create the IRE with the right IPIF in ip_wput.
24675 		 *
24676 		 * Also handle RTF_MULTIRT routes.
24677 		 */
24678 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
24679 	} else {
24680 		if (attach_if) {
24681 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
24682 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24683 		} else {
24684 			if (ire_arg != NULL) {
24685 				ire = ire_arg;
24686 				ire_need_rele = B_FALSE;
24687 			} else {
24688 				ire = ire_cache_lookup(dst, zoneid,
24689 				    MBLK_GETLABEL(mp));
24690 			}
24691 		}
24692 		if (ire != NULL) {
24693 			goto send;
24694 		}
24695 
24696 		/*
24697 		 * ire disappeared underneath.
24698 		 *
24699 		 * What we need to do here is the ip_newroute
24700 		 * logic to get the ire without doing the IPSEC
24701 		 * processing. Follow the same old path. But this
24702 		 * time, ip_wput or ire_add_then_put will call us
24703 		 * directly as all the IPSEC operations are done.
24704 		 */
24705 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
24706 		mp->b_prev = NULL;
24707 		mp->b_next = NULL;
24708 
24709 		/*
24710 		 * If the IPsec packet was processed asynchronously,
24711 		 * drop it now.
24712 		 */
24713 		if (q == NULL) {
24714 			freemsg(ipsec_mp);
24715 			goto done;
24716 		}
24717 
24718 		/*
24719 		 * Since we're going through ip_newroute() again, we
24720 		 * need to make sure we don't:
24721 		 *
24722 		 *	1.) Trigger the ASSERT() with the ipha_ident
24723 		 *	    overloading.
24724 		 *	2.) Redo transport-layer checksumming, since we've
24725 		 *	    already done all that to get this far.
24726 		 *
24727 		 * The easiest way not do either of the above is to set
24728 		 * the ipha_ident field to IP_HDR_INCLUDED.
24729 		 */
24730 		ipha->ipha_ident = IP_HDR_INCLUDED;
24731 		ip_newroute(q, ipsec_mp, dst, NULL,
24732 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
24733 	}
24734 	goto done;
24735 send:
24736 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
24737 		/*
24738 		 * ESP NAT-Traversal packet.
24739 		 *
24740 		 * Just do software checksum for now.
24741 		 */
24742 
24743 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
24744 		IP_STAT(ip_out_sw_cksum);
24745 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
24746 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
24747 #define	iphs	((uint16_t *)ipha)
24748 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
24749 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
24750 		    IP_SIMPLE_HDR_LENGTH);
24751 #undef iphs
24752 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
24753 			cksum = 0xFFFF;
24754 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
24755 			if (mp1->b_wptr - mp1->b_rptr >=
24756 			    offset + sizeof (uint16_t)) {
24757 				up = (uint16_t *)(mp1->b_rptr + offset);
24758 				*up = cksum;
24759 				break;	/* out of for loop */
24760 			} else {
24761 				offset -= (mp->b_wptr - mp->b_rptr);
24762 			}
24763 	} /* Otherwise, just keep the all-zero checksum. */
24764 
24765 	if (ire->ire_stq == NULL) {
24766 		/*
24767 		 * Loopbacks go through ip_wput_local except for one case.
24768 		 * We come here if we generate a icmp_frag_needed message
24769 		 * after IPSEC processing is over. When this function calls
24770 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
24771 		 * icmp_frag_needed. The message generated comes back here
24772 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
24773 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
24774 		 * source address as it is usually set in ip_wput_ire. As
24775 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
24776 		 * and we end up here. We can't enter ip_wput_ire once the
24777 		 * IPSEC processing is over and hence we need to do it here.
24778 		 */
24779 		ASSERT(q != NULL);
24780 		UPDATE_OB_PKT_COUNT(ire);
24781 		ire->ire_last_used_time = lbolt;
24782 		if (ipha->ipha_src == 0)
24783 			ipha->ipha_src = ire->ire_src_addr;
24784 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
24785 		    ire, 0, zoneid);
24786 		if (ire_need_rele)
24787 			ire_refrele(ire);
24788 		goto done;
24789 	}
24790 
24791 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
24792 		/*
24793 		 * We are through with IPSEC processing.
24794 		 * Fragment this and send it on the wire.
24795 		 */
24796 		if (io->ipsec_out_accelerated) {
24797 			/*
24798 			 * The packet has been accelerated but must
24799 			 * be fragmented. This should not happen
24800 			 * since AH and ESP must not accelerate
24801 			 * packets that need fragmentation, however
24802 			 * the configuration could have changed
24803 			 * since the AH or ESP processing.
24804 			 * Drop packet.
24805 			 * IPsec KSTATS: bump bean counter here.
24806 			 */
24807 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
24808 			    "fragmented accelerated packet!\n"));
24809 			freemsg(ipsec_mp);
24810 		} else {
24811 			ip_wput_ire_fragmentit(ipsec_mp, ire);
24812 		}
24813 		if (ire_need_rele)
24814 			ire_refrele(ire);
24815 		goto done;
24816 	}
24817 
24818 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
24819 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
24820 	    (void *)ire->ire_ipif, (void *)ipif));
24821 
24822 	/*
24823 	 * Multiroute the secured packet, unless IPsec really
24824 	 * requires the packet to go out only through a particular
24825 	 * interface.
24826 	 */
24827 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
24828 		ire_t *first_ire;
24829 		irb = ire->ire_bucket;
24830 		ASSERT(irb != NULL);
24831 		/*
24832 		 * This ire has been looked up as the one that
24833 		 * goes through the given ipif;
24834 		 * make sure we do not omit any other multiroute ire
24835 		 * that may be present in the bucket before this one.
24836 		 */
24837 		IRB_REFHOLD(irb);
24838 		for (first_ire = irb->irb_ire;
24839 		    first_ire != NULL;
24840 		    first_ire = first_ire->ire_next) {
24841 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24842 			    (first_ire->ire_addr == ire->ire_addr) &&
24843 			    !(first_ire->ire_marks &
24844 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24845 				break;
24846 		}
24847 
24848 		if ((first_ire != NULL) && (first_ire != ire)) {
24849 			/*
24850 			 * Don't change the ire if the packet must
24851 			 * be fragmented if sent via this new one.
24852 			 */
24853 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
24854 				IRE_REFHOLD(first_ire);
24855 				if (ire_need_rele)
24856 					ire_refrele(ire);
24857 				else
24858 					ire_need_rele = B_TRUE;
24859 				ire = first_ire;
24860 			}
24861 		}
24862 		IRB_REFRELE(irb);
24863 
24864 		multirt_send = B_TRUE;
24865 		max_frag = ire->ire_max_frag;
24866 	} else {
24867 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
24868 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
24869 			    "flag, attach_if %d\n", attach_if));
24870 		}
24871 	}
24872 
24873 	/*
24874 	 * In most cases, the emission loop below is entered only once.
24875 	 * Only in the case where the ire holds the RTF_MULTIRT
24876 	 * flag, we loop to process all RTF_MULTIRT ires in the
24877 	 * bucket, and send the packet through all crossed
24878 	 * RTF_MULTIRT routes.
24879 	 */
24880 	do {
24881 		if (multirt_send) {
24882 			/*
24883 			 * ire1 holds here the next ire to process in the
24884 			 * bucket. If multirouting is expected,
24885 			 * any non-RTF_MULTIRT ire that has the
24886 			 * right destination address is ignored.
24887 			 */
24888 			ASSERT(irb != NULL);
24889 			IRB_REFHOLD(irb);
24890 			for (ire1 = ire->ire_next;
24891 			    ire1 != NULL;
24892 			    ire1 = ire1->ire_next) {
24893 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24894 					continue;
24895 				if (ire1->ire_addr != ire->ire_addr)
24896 					continue;
24897 				if (ire1->ire_marks &
24898 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24899 					continue;
24900 				/* No loopback here */
24901 				if (ire1->ire_stq == NULL)
24902 					continue;
24903 				/*
24904 				 * Ensure we do not exceed the MTU
24905 				 * of the next route.
24906 				 */
24907 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
24908 					ip_multirt_bad_mtu(ire1, max_frag);
24909 					continue;
24910 				}
24911 
24912 				IRE_REFHOLD(ire1);
24913 				break;
24914 			}
24915 			IRB_REFRELE(irb);
24916 			if (ire1 != NULL) {
24917 				/*
24918 				 * We are in a multiple send case, need to
24919 				 * make a copy of the packet.
24920 				 */
24921 				next_mp = copymsg(ipsec_mp);
24922 				if (next_mp == NULL) {
24923 					ire_refrele(ire1);
24924 					ire1 = NULL;
24925 				}
24926 			}
24927 		}
24928 		/*
24929 		 * Everything is done. Send it out on the wire
24930 		 *
24931 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
24932 		 * either send it on the wire or, in the case of
24933 		 * HW acceleration, call ipsec_hw_putnext.
24934 		 */
24935 		if (ire->ire_nce &&
24936 		    ire->ire_nce->nce_state != ND_REACHABLE) {
24937 			DTRACE_PROBE2(ip__wput__ipsec__bail,
24938 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
24939 			/*
24940 			 * If ire's link-layer is unresolved (this
24941 			 * would only happen if the incomplete ire
24942 			 * was added to cachetable via forwarding path)
24943 			 * don't bother going to ip_xmit_v4. Just drop the
24944 			 * packet.
24945 			 * There is a slight risk here, in that, if we
24946 			 * have the forwarding path create an incomplete
24947 			 * IRE, then until the IRE is completed, any
24948 			 * transmitted IPSEC packets will be dropped
24949 			 * instead of being queued waiting for resolution.
24950 			 *
24951 			 * But the likelihood of a forwarding packet and a wput
24952 			 * packet sending to the same dst at the same time
24953 			 * and there not yet be an ARP entry for it is small.
24954 			 * Furthermore, if this actually happens, it might
24955 			 * be likely that wput would generate multiple
24956 			 * packets (and forwarding would also have a train
24957 			 * of packets) for that destination. If this is
24958 			 * the case, some of them would have been dropped
24959 			 * anyway, since ARP only queues a few packets while
24960 			 * waiting for resolution
24961 			 *
24962 			 * NOTE: We should really call ip_xmit_v4,
24963 			 * and let it queue the packet and send the
24964 			 * ARP query and have ARP come back thus:
24965 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
24966 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
24967 			 * hw accel work. But it's too complex to get
24968 			 * the IPsec hw  acceleration approach to fit
24969 			 * well with ip_xmit_v4 doing ARP without
24970 			 * doing IPSEC simplification. For now, we just
24971 			 * poke ip_xmit_v4 to trigger the arp resolve, so
24972 			 * that we can continue with the send on the next
24973 			 * attempt.
24974 			 *
24975 			 * XXX THis should be revisited, when
24976 			 * the IPsec/IP interaction is cleaned up
24977 			 */
24978 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
24979 			    " - dropping packet\n"));
24980 			freemsg(ipsec_mp);
24981 			/*
24982 			 * Call ip_xmit_v4() to trigger ARP query
24983 			 * in case the nce_state is ND_INITIAL
24984 			 */
24985 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24986 			goto drop_pkt;
24987 		}
24988 
24989 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
24990 		pktxmit_state = ip_xmit_v4(mp, ire,
24991 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
24992 
24993 		if ((pktxmit_state ==  SEND_FAILED) ||
24994 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
24995 
24996 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
24997 drop_pkt:
24998 			BUMP_MIB(&ip_mib, ipOutDiscards);
24999 			if (ire_need_rele)
25000 				ire_refrele(ire);
25001 			if (ire1 != NULL) {
25002 				ire_refrele(ire1);
25003 				freemsg(next_mp);
25004 			}
25005 			goto done;
25006 		}
25007 
25008 		freeb(ipsec_mp);
25009 		if (ire_need_rele)
25010 			ire_refrele(ire);
25011 
25012 		if (ire1 != NULL) {
25013 			ire = ire1;
25014 			ire_need_rele = B_TRUE;
25015 			ASSERT(next_mp);
25016 			ipsec_mp = next_mp;
25017 			mp = ipsec_mp->b_cont;
25018 			ire1 = NULL;
25019 			next_mp = NULL;
25020 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
25021 		} else {
25022 			multirt_send = B_FALSE;
25023 		}
25024 	} while (multirt_send);
25025 done:
25026 	if (ill != NULL && ill_need_rele)
25027 		ill_refrele(ill);
25028 	if (ipif != NULL)
25029 		ipif_refrele(ipif);
25030 }
25031 
25032 /*
25033  * Get the ill corresponding to the specified ire, and compare its
25034  * capabilities with the protocol and algorithms specified by the
25035  * the SA obtained from ipsec_out. If they match, annotate the
25036  * ipsec_out structure to indicate that the packet needs acceleration.
25037  *
25038  *
25039  * A packet is eligible for outbound hardware acceleration if the
25040  * following conditions are satisfied:
25041  *
25042  * 1. the packet will not be fragmented
25043  * 2. the provider supports the algorithm
25044  * 3. there is no pending control message being exchanged
25045  * 4. snoop is not attached
25046  * 5. the destination address is not a broadcast or multicast address.
25047  *
25048  * Rationale:
25049  *	- Hardware drivers do not support fragmentation with
25050  *	  the current interface.
25051  *	- snoop, multicast, and broadcast may result in exposure of
25052  *	  a cleartext datagram.
25053  * We check all five of these conditions here.
25054  *
25055  * XXX would like to nuke "ire_t *" parameter here; problem is that
25056  * IRE is only way to figure out if a v4 address is a broadcast and
25057  * thus ineligible for acceleration...
25058  */
25059 static void
25060 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
25061 {
25062 	ipsec_out_t *io;
25063 	mblk_t *data_mp;
25064 	uint_t plen, overhead;
25065 
25066 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
25067 		return;
25068 
25069 	if (ill == NULL)
25070 		return;
25071 
25072 	/*
25073 	 * Destination address is a broadcast or multicast.  Punt.
25074 	 */
25075 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
25076 	    IRE_LOCAL)))
25077 		return;
25078 
25079 	data_mp = ipsec_mp->b_cont;
25080 
25081 	if (ill->ill_isv6) {
25082 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
25083 
25084 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
25085 			return;
25086 
25087 		plen = ip6h->ip6_plen;
25088 	} else {
25089 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
25090 
25091 		if (CLASSD(ipha->ipha_dst))
25092 			return;
25093 
25094 		plen = ipha->ipha_length;
25095 	}
25096 	/*
25097 	 * Is there a pending DLPI control message being exchanged
25098 	 * between IP/IPsec and the DLS Provider? If there is, it
25099 	 * could be a SADB update, and the state of the DLS Provider
25100 	 * SADB might not be in sync with the SADB maintained by
25101 	 * IPsec. To avoid dropping packets or using the wrong keying
25102 	 * material, we do not accelerate this packet.
25103 	 */
25104 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
25105 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25106 		    "ill_dlpi_pending! don't accelerate packet\n"));
25107 		return;
25108 	}
25109 
25110 	/*
25111 	 * Is the Provider in promiscous mode? If it does, we don't
25112 	 * accelerate the packet since it will bounce back up to the
25113 	 * listeners in the clear.
25114 	 */
25115 	if (ill->ill_promisc_on_phys) {
25116 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25117 		    "ill in promiscous mode, don't accelerate packet\n"));
25118 		return;
25119 	}
25120 
25121 	/*
25122 	 * Will the packet require fragmentation?
25123 	 */
25124 
25125 	/*
25126 	 * IPsec ESP note: this is a pessimistic estimate, but the same
25127 	 * as is used elsewhere.
25128 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
25129 	 *	+ 2-byte trailer
25130 	 */
25131 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
25132 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
25133 
25134 	if ((plen + overhead) > ill->ill_max_mtu)
25135 		return;
25136 
25137 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25138 
25139 	/*
25140 	 * Can the ill accelerate this IPsec protocol and algorithm
25141 	 * specified by the SA?
25142 	 */
25143 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
25144 	    ill->ill_isv6, sa)) {
25145 		return;
25146 	}
25147 
25148 	/*
25149 	 * Tell AH or ESP that the outbound ill is capable of
25150 	 * accelerating this packet.
25151 	 */
25152 	io->ipsec_out_is_capab_ill = B_TRUE;
25153 }
25154 
25155 /*
25156  * Select which AH & ESP SA's to use (if any) for the outbound packet.
25157  *
25158  * If this function returns B_TRUE, the requested SA's have been filled
25159  * into the ipsec_out_*_sa pointers.
25160  *
25161  * If the function returns B_FALSE, the packet has been "consumed", most
25162  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
25163  *
25164  * The SA references created by the protocol-specific "select"
25165  * function will be released when the ipsec_mp is freed, thanks to the
25166  * ipsec_out_free destructor -- see spd.c.
25167  */
25168 static boolean_t
25169 ipsec_out_select_sa(mblk_t *ipsec_mp)
25170 {
25171 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
25172 	ipsec_out_t *io;
25173 	ipsec_policy_t *pp;
25174 	ipsec_action_t *ap;
25175 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25176 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25177 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25178 
25179 	if (!io->ipsec_out_secure) {
25180 		/*
25181 		 * We came here by mistake.
25182 		 * Don't bother with ipsec processing
25183 		 * We should "discourage" this path in the future.
25184 		 */
25185 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25186 		return (B_FALSE);
25187 	}
25188 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25189 	ASSERT((io->ipsec_out_policy != NULL) ||
25190 	    (io->ipsec_out_act != NULL));
25191 
25192 	ASSERT(io->ipsec_out_failed == B_FALSE);
25193 
25194 	/*
25195 	 * IPSEC processing has started.
25196 	 */
25197 	io->ipsec_out_proc_begin = B_TRUE;
25198 	ap = io->ipsec_out_act;
25199 	if (ap == NULL) {
25200 		pp = io->ipsec_out_policy;
25201 		ASSERT(pp != NULL);
25202 		ap = pp->ipsp_act;
25203 		ASSERT(ap != NULL);
25204 	}
25205 
25206 	/*
25207 	 * We have an action.  now, let's select SA's.
25208 	 * (In the future, we can cache this in the conn_t..)
25209 	 */
25210 	if (ap->ipa_want_esp) {
25211 		if (io->ipsec_out_esp_sa == NULL) {
25212 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
25213 			    IPPROTO_ESP);
25214 		}
25215 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
25216 	}
25217 
25218 	if (ap->ipa_want_ah) {
25219 		if (io->ipsec_out_ah_sa == NULL) {
25220 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
25221 			    IPPROTO_AH);
25222 		}
25223 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
25224 		/*
25225 		 * The ESP and AH processing order needs to be preserved
25226 		 * when both protocols are required (ESP should be applied
25227 		 * before AH for an outbound packet). Force an ESP ACQUIRE
25228 		 * when both ESP and AH are required, and an AH ACQUIRE
25229 		 * is needed.
25230 		 */
25231 		if (ap->ipa_want_esp && need_ah_acquire)
25232 			need_esp_acquire = B_TRUE;
25233 	}
25234 
25235 	/*
25236 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
25237 	 * Release SAs that got referenced, but will not be used until we
25238 	 * acquire _all_ of the SAs we need.
25239 	 */
25240 	if (need_ah_acquire || need_esp_acquire) {
25241 		if (io->ipsec_out_ah_sa != NULL) {
25242 			IPSA_REFRELE(io->ipsec_out_ah_sa);
25243 			io->ipsec_out_ah_sa = NULL;
25244 		}
25245 		if (io->ipsec_out_esp_sa != NULL) {
25246 			IPSA_REFRELE(io->ipsec_out_esp_sa);
25247 			io->ipsec_out_esp_sa = NULL;
25248 		}
25249 
25250 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
25251 		return (B_FALSE);
25252 	}
25253 
25254 	return (B_TRUE);
25255 }
25256 
25257 /*
25258  * Process an IPSEC_OUT message and see what you can
25259  * do with it.
25260  * IPQoS Notes:
25261  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
25262  * IPSec.
25263  * XXX would like to nuke ire_t.
25264  * XXX ill_index better be "real"
25265  */
25266 void
25267 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
25268 {
25269 	ipsec_out_t *io;
25270 	ipsec_policy_t *pp;
25271 	ipsec_action_t *ap;
25272 	ipha_t *ipha;
25273 	ip6_t *ip6h;
25274 	mblk_t *mp;
25275 	ill_t *ill;
25276 	zoneid_t zoneid;
25277 	ipsec_status_t ipsec_rc;
25278 	boolean_t ill_need_rele = B_FALSE;
25279 
25280 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25281 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25282 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25283 	mp = ipsec_mp->b_cont;
25284 
25285 	/*
25286 	 * Initiate IPPF processing. We do it here to account for packets
25287 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
25288 	 * We can check for ipsec_out_proc_begin even for such packets, as
25289 	 * they will always be false (asserted below).
25290 	 */
25291 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
25292 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
25293 		    io->ipsec_out_ill_index : ill_index);
25294 		if (mp == NULL) {
25295 			ip2dbg(("ipsec_out_process: packet dropped "\
25296 			    "during IPPF processing\n"));
25297 			freeb(ipsec_mp);
25298 			BUMP_MIB(&ip_mib, ipOutDiscards);
25299 			return;
25300 		}
25301 	}
25302 
25303 	if (!io->ipsec_out_secure) {
25304 		/*
25305 		 * We came here by mistake.
25306 		 * Don't bother with ipsec processing
25307 		 * Should "discourage" this path in the future.
25308 		 */
25309 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25310 		goto done;
25311 	}
25312 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25313 	ASSERT((io->ipsec_out_policy != NULL) ||
25314 	    (io->ipsec_out_act != NULL));
25315 	ASSERT(io->ipsec_out_failed == B_FALSE);
25316 
25317 	if (!ipsec_loaded()) {
25318 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
25319 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25320 			BUMP_MIB(&ip_mib, ipOutDiscards);
25321 		} else {
25322 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
25323 		}
25324 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
25325 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
25326 		return;
25327 	}
25328 
25329 	/*
25330 	 * IPSEC processing has started.
25331 	 */
25332 	io->ipsec_out_proc_begin = B_TRUE;
25333 	ap = io->ipsec_out_act;
25334 	if (ap == NULL) {
25335 		pp = io->ipsec_out_policy;
25336 		ASSERT(pp != NULL);
25337 		ap = pp->ipsp_act;
25338 		ASSERT(ap != NULL);
25339 	}
25340 
25341 	/*
25342 	 * Save the outbound ill index. When the packet comes back
25343 	 * from IPsec, we make sure the ill hasn't changed or disappeared
25344 	 * before sending it the accelerated packet.
25345 	 */
25346 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
25347 		int ifindex;
25348 		ill = ire_to_ill(ire);
25349 		ifindex = ill->ill_phyint->phyint_ifindex;
25350 		io->ipsec_out_capab_ill_index = ifindex;
25351 	}
25352 
25353 	/*
25354 	 * The order of processing is first insert a IP header if needed.
25355 	 * Then insert the ESP header and then the AH header.
25356 	 */
25357 	if ((io->ipsec_out_se_done == B_FALSE) &&
25358 	    (ap->ipa_want_se)) {
25359 		/*
25360 		 * First get the outer IP header before sending
25361 		 * it to ESP.
25362 		 */
25363 		ipha_t *oipha, *iipha;
25364 		mblk_t *outer_mp, *inner_mp;
25365 
25366 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
25367 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
25368 			    "ipsec_out_process: "
25369 			    "Self-Encapsulation failed: Out of memory\n");
25370 			freemsg(ipsec_mp);
25371 			BUMP_MIB(&ip_mib, ipOutDiscards);
25372 			return;
25373 		}
25374 		inner_mp = ipsec_mp->b_cont;
25375 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
25376 		oipha = (ipha_t *)outer_mp->b_rptr;
25377 		iipha = (ipha_t *)inner_mp->b_rptr;
25378 		*oipha = *iipha;
25379 		outer_mp->b_wptr += sizeof (ipha_t);
25380 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
25381 		    sizeof (ipha_t));
25382 		oipha->ipha_protocol = IPPROTO_ENCAP;
25383 		oipha->ipha_version_and_hdr_length =
25384 		    IP_SIMPLE_HDR_VERSION;
25385 		oipha->ipha_hdr_checksum = 0;
25386 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
25387 		outer_mp->b_cont = inner_mp;
25388 		ipsec_mp->b_cont = outer_mp;
25389 
25390 		io->ipsec_out_se_done = B_TRUE;
25391 		io->ipsec_out_encaps = B_TRUE;
25392 	}
25393 
25394 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
25395 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
25396 	    !ipsec_out_select_sa(ipsec_mp))
25397 		return;
25398 
25399 	/*
25400 	 * By now, we know what SA's to use.  Toss over to ESP & AH
25401 	 * to do the heavy lifting.
25402 	 */
25403 	zoneid = io->ipsec_out_zoneid;
25404 	ASSERT(zoneid != ALL_ZONES);
25405 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
25406 		ASSERT(io->ipsec_out_esp_sa != NULL);
25407 		io->ipsec_out_esp_done = B_TRUE;
25408 		/*
25409 		 * Note that since hw accel can only apply one transform,
25410 		 * not two, we skip hw accel for ESP if we also have AH
25411 		 * This is an design limitation of the interface
25412 		 * which should be revisited.
25413 		 */
25414 		ASSERT(ire != NULL);
25415 		if (io->ipsec_out_ah_sa == NULL) {
25416 			ill = (ill_t *)ire->ire_stq->q_ptr;
25417 			ipsec_out_is_accelerated(ipsec_mp,
25418 			    io->ipsec_out_esp_sa, ill, ire);
25419 		}
25420 
25421 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
25422 		switch (ipsec_rc) {
25423 		case IPSEC_STATUS_SUCCESS:
25424 			break;
25425 		case IPSEC_STATUS_FAILED:
25426 			BUMP_MIB(&ip_mib, ipOutDiscards);
25427 			/* FALLTHRU */
25428 		case IPSEC_STATUS_PENDING:
25429 			return;
25430 		}
25431 	}
25432 
25433 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
25434 		ASSERT(io->ipsec_out_ah_sa != NULL);
25435 		io->ipsec_out_ah_done = B_TRUE;
25436 		if (ire == NULL) {
25437 			int idx = io->ipsec_out_capab_ill_index;
25438 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
25439 			    NULL, NULL, NULL, NULL);
25440 			ill_need_rele = B_TRUE;
25441 		} else {
25442 			ill = (ill_t *)ire->ire_stq->q_ptr;
25443 		}
25444 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
25445 		    ire);
25446 
25447 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
25448 		switch (ipsec_rc) {
25449 		case IPSEC_STATUS_SUCCESS:
25450 			break;
25451 		case IPSEC_STATUS_FAILED:
25452 			BUMP_MIB(&ip_mib, ipOutDiscards);
25453 			/* FALLTHRU */
25454 		case IPSEC_STATUS_PENDING:
25455 			if (ill != NULL && ill_need_rele)
25456 				ill_refrele(ill);
25457 			return;
25458 		}
25459 	}
25460 	/*
25461 	 * We are done with IPSEC processing. Send it over
25462 	 * the wire.
25463 	 */
25464 done:
25465 	mp = ipsec_mp->b_cont;
25466 	ipha = (ipha_t *)mp->b_rptr;
25467 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25468 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
25469 	} else {
25470 		ip6h = (ip6_t *)ipha;
25471 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
25472 	}
25473 	if (ill != NULL && ill_need_rele)
25474 		ill_refrele(ill);
25475 }
25476 
25477 /* ARGSUSED */
25478 void
25479 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
25480 {
25481 	opt_restart_t	*or;
25482 	int	err;
25483 	conn_t	*connp;
25484 
25485 	ASSERT(CONN_Q(q));
25486 	connp = Q_TO_CONN(q);
25487 
25488 	ASSERT(first_mp->b_datap->db_type == M_CTL);
25489 	or = (opt_restart_t *)first_mp->b_rptr;
25490 	/*
25491 	 * We don't need to pass any credentials here since this is just
25492 	 * a restart. The credentials are passed in when svr4_optcom_req
25493 	 * is called the first time (from ip_wput_nondata).
25494 	 */
25495 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
25496 		err = svr4_optcom_req(q, first_mp, NULL,
25497 		    &ip_opt_obj);
25498 	} else {
25499 		ASSERT(or->or_type == T_OPTMGMT_REQ);
25500 		err = tpi_optcom_req(q, first_mp, NULL,
25501 		    &ip_opt_obj);
25502 	}
25503 	if (err != EINPROGRESS) {
25504 		/* operation is done */
25505 		CONN_OPER_PENDING_DONE(connp);
25506 	}
25507 }
25508 
25509 /*
25510  * ioctls that go through a down/up sequence may need to wait for the down
25511  * to complete. This involves waiting for the ire and ipif refcnts to go down
25512  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
25513  */
25514 /* ARGSUSED */
25515 void
25516 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25517 {
25518 	struct iocblk *iocp;
25519 	mblk_t *mp1;
25520 	ipif_t	*ipif;
25521 	ip_ioctl_cmd_t *ipip;
25522 	int err;
25523 	sin_t	*sin;
25524 	struct lifreq *lifr;
25525 	struct ifreq *ifr;
25526 
25527 	iocp = (struct iocblk *)mp->b_rptr;
25528 	ASSERT(ipsq != NULL);
25529 	/* Existence of mp1 verified in ip_wput_nondata */
25530 	mp1 = mp->b_cont->b_cont;
25531 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25532 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
25533 		ill_t *ill;
25534 		/*
25535 		 * Special case where ipsq_current_ipif may not be set.
25536 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
25537 		 * ill could also have become part of a ipmp group in the
25538 		 * process, we are here as were not able to complete the
25539 		 * operation in ipif_set_values because we could not become
25540 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
25541 		 * will not be set so we need to set it.
25542 		 */
25543 		ill = (ill_t *)q->q_ptr;
25544 		ipsq->ipsq_current_ipif = ill->ill_ipif;
25545 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25546 	}
25547 
25548 	ipif = ipsq->ipsq_current_ipif;
25549 	ASSERT(ipif != NULL);
25550 	if (ipip->ipi_cmd_type == IF_CMD) {
25551 		/* This a old style SIOC[GS]IF* command */
25552 		ifr = (struct ifreq *)mp1->b_rptr;
25553 		sin = (sin_t *)&ifr->ifr_addr;
25554 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
25555 		/* This a new style SIOC[GS]LIF* command */
25556 		lifr = (struct lifreq *)mp1->b_rptr;
25557 		sin = (sin_t *)&lifr->lifr_addr;
25558 	} else {
25559 		sin = NULL;
25560 	}
25561 
25562 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
25563 	    (void *)mp1->b_rptr);
25564 
25565 	/* SIOCLIFREMOVEIF could have removed the ipif */
25566 	ip_ioctl_finish(q, mp, err,
25567 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25568 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
25569 }
25570 
25571 /*
25572  * ioctl processing
25573  *
25574  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
25575  * the ioctl command in the ioctl tables and determines the copyin data size
25576  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
25577  * size.
25578  *
25579  * ioctl processing then continues when the M_IOCDATA makes its way down.
25580  * Now the ioctl is looked up again in the ioctl table, and its properties are
25581  * extracted. The associated 'conn' is then refheld till the end of the ioctl
25582  * and the general ioctl processing function ip_process_ioctl is called.
25583  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
25584  * so goes thru the serialization primitive ipsq_try_enter. Then the
25585  * appropriate function to handle the ioctl is called based on the entry in
25586  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
25587  * which also refreleases the 'conn' that was refheld at the start of the
25588  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
25589  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
25590  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
25591  *
25592  * Many exclusive ioctls go thru an internal down up sequence as part of
25593  * the operation. For example an attempt to change the IP address of an
25594  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
25595  * does all the cleanup such as deleting all ires that use this address.
25596  * Then we need to wait till all references to the interface go away.
25597  */
25598 void
25599 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
25600 {
25601 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
25602 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
25603 	cmd_info_t ci;
25604 	int err;
25605 	boolean_t entered_ipsq = B_FALSE;
25606 
25607 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
25608 
25609 	if (ipip == NULL)
25610 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25611 
25612 	/*
25613 	 * SIOCLIFADDIF needs to go thru a special path since the
25614 	 * ill may not exist yet. This happens in the case of lo0
25615 	 * which is created using this ioctl.
25616 	 */
25617 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
25618 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
25619 		ip_ioctl_finish(q, mp, err,
25620 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25621 		    NULL, NULL);
25622 		return;
25623 	}
25624 
25625 	ci.ci_ipif = NULL;
25626 	switch (ipip->ipi_cmd_type) {
25627 	case IF_CMD:
25628 	case LIF_CMD:
25629 		/*
25630 		 * ioctls that pass in a [l]ifreq appear here.
25631 		 * ip_extract_lifreq_cmn returns a refheld ipif in
25632 		 * ci.ci_ipif
25633 		 */
25634 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
25635 		    ipip->ipi_flags, &ci, ip_process_ioctl);
25636 		if (err != 0) {
25637 			ip_ioctl_finish(q, mp, err,
25638 			    ipip->ipi_flags & IPI_GET_CMD ?
25639 			    COPYOUT : NO_COPYOUT, NULL, NULL);
25640 			return;
25641 		}
25642 		ASSERT(ci.ci_ipif != NULL);
25643 		break;
25644 
25645 	case TUN_CMD:
25646 		/*
25647 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
25648 		 * a refheld ipif in ci.ci_ipif
25649 		 */
25650 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
25651 		if (err != 0) {
25652 			ip_ioctl_finish(q, mp, err,
25653 			    ipip->ipi_flags & IPI_GET_CMD ?
25654 			    COPYOUT : NO_COPYOUT, NULL, NULL);
25655 			return;
25656 		}
25657 		ASSERT(ci.ci_ipif != NULL);
25658 		break;
25659 
25660 	case MISC_CMD:
25661 		/*
25662 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
25663 		 * For eg. SIOCGLIFCONF will appear here.
25664 		 */
25665 		switch (ipip->ipi_cmd) {
25666 		case IF_UNITSEL:
25667 			/* ioctl comes down the ill */
25668 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
25669 			ipif_refhold(ci.ci_ipif);
25670 			break;
25671 		case SIOCGMSFILTER:
25672 		case SIOCSMSFILTER:
25673 		case SIOCGIPMSFILTER:
25674 		case SIOCSIPMSFILTER:
25675 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
25676 			    ip_process_ioctl);
25677 			if (err != 0) {
25678 				ip_ioctl_finish(q, mp, err,
25679 				    ipip->ipi_flags & IPI_GET_CMD ?
25680 				    COPYOUT : NO_COPYOUT, NULL, NULL);
25681 				return;
25682 			}
25683 			break;
25684 		}
25685 		err = 0;
25686 		ci.ci_sin = NULL;
25687 		ci.ci_sin6 = NULL;
25688 		ci.ci_lifr = NULL;
25689 		break;
25690 	}
25691 
25692 	/*
25693 	 * If ipsq is non-null, we are already being called exclusively
25694 	 */
25695 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
25696 	if (!(ipip->ipi_flags & IPI_WR)) {
25697 		/*
25698 		 * A return value of EINPROGRESS means the ioctl is
25699 		 * either queued and waiting for some reason or has
25700 		 * already completed.
25701 		 */
25702 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25703 		    ci.ci_lifr);
25704 		if (ci.ci_ipif != NULL)
25705 			ipif_refrele(ci.ci_ipif);
25706 		ip_ioctl_finish(q, mp, err,
25707 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25708 		    NULL, NULL);
25709 		return;
25710 	}
25711 
25712 	ASSERT(ci.ci_ipif != NULL);
25713 
25714 	if (ipsq == NULL) {
25715 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
25716 		    ip_process_ioctl, NEW_OP, B_TRUE);
25717 		entered_ipsq = B_TRUE;
25718 	}
25719 	/*
25720 	 * Release the ipif so that ipif_down and friends that wait for
25721 	 * references to go away are not misled about the current ipif_refcnt
25722 	 * values. We are writer so we can access the ipif even after releasing
25723 	 * the ipif.
25724 	 */
25725 	ipif_refrele(ci.ci_ipif);
25726 	if (ipsq == NULL)
25727 		return;
25728 
25729 	mutex_enter(&ipsq->ipsq_lock);
25730 	ASSERT(ipsq->ipsq_current_ipif == NULL);
25731 	ipsq->ipsq_current_ipif = ci.ci_ipif;
25732 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25733 	mutex_exit(&ipsq->ipsq_lock);
25734 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
25735 	/*
25736 	 * For most set ioctls that come here, this serves as a single point
25737 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
25738 	 * be any new references to the ipif. This helps functions that go
25739 	 * through this path and end up trying to wait for the refcnts
25740 	 * associated with the ipif to go down to zero. Some exceptions are
25741 	 * Failover, Failback, and Groupname commands that operate on more than
25742 	 * just the ci.ci_ipif. These commands internally determine the
25743 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
25744 	 * flags on that set. Another exception is the Removeif command that
25745 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
25746 	 * ipif to operate on.
25747 	 */
25748 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
25749 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
25750 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
25751 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
25752 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
25753 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
25754 
25755 	/*
25756 	 * A return value of EINPROGRESS means the ioctl is
25757 	 * either queued and waiting for some reason or has
25758 	 * already completed.
25759 	 */
25760 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25761 	    ci.ci_lifr);
25762 
25763 	/* SIOCLIFREMOVEIF could have removed the ipif */
25764 	ip_ioctl_finish(q, mp, err,
25765 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25766 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
25767 
25768 	if (entered_ipsq)
25769 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
25770 }
25771 
25772 /*
25773  * Complete the ioctl. Typically ioctls use the mi package and need to
25774  * do mi_copyout/mi_copy_done.
25775  */
25776 void
25777 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
25778     ipif_t *ipif, ipsq_t *ipsq)
25779 {
25780 	conn_t	*connp = NULL;
25781 
25782 	if (err == EINPROGRESS)
25783 		return;
25784 
25785 	if (CONN_Q(q)) {
25786 		connp = Q_TO_CONN(q);
25787 		ASSERT(connp->conn_ref >= 2);
25788 	}
25789 
25790 	switch (mode) {
25791 	case COPYOUT:
25792 		if (err == 0)
25793 			mi_copyout(q, mp);
25794 		else
25795 			mi_copy_done(q, mp, err);
25796 		break;
25797 
25798 	case NO_COPYOUT:
25799 		mi_copy_done(q, mp, err);
25800 		break;
25801 
25802 	default:
25803 		/* An ioctl aborted through a conn close would take this path */
25804 		break;
25805 	}
25806 
25807 	/*
25808 	 * The refhold placed at the start of the ioctl is released here.
25809 	 */
25810 	if (connp != NULL)
25811 		CONN_OPER_PENDING_DONE(connp);
25812 
25813 	/*
25814 	 * If the ioctl were an exclusive ioctl it would have set
25815 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
25816 	 */
25817 	if (ipif != NULL) {
25818 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
25819 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
25820 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
25821 	}
25822 
25823 	/*
25824 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
25825 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
25826 	 * entering the ipsq
25827 	 */
25828 	if (ipsq != NULL) {
25829 		mutex_enter(&ipsq->ipsq_lock);
25830 		ipsq->ipsq_current_ipif = NULL;
25831 		mutex_exit(&ipsq->ipsq_lock);
25832 	}
25833 }
25834 
25835 /*
25836  * This is called from ip_wput_nondata to resume a deferred TCP bind.
25837  */
25838 /* ARGSUSED */
25839 void
25840 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
25841 {
25842 	conn_t *connp = arg;
25843 	tcp_t	*tcp;
25844 
25845 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
25846 	tcp = connp->conn_tcp;
25847 
25848 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
25849 		freemsg(mp);
25850 	else
25851 		tcp_rput_other(tcp, mp);
25852 	CONN_OPER_PENDING_DONE(connp);
25853 }
25854 
25855 /* Called from ip_wput for all non data messages */
25856 /* ARGSUSED */
25857 void
25858 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25859 {
25860 	mblk_t		*mp1;
25861 	ire_t		*ire, *fake_ire;
25862 	ill_t		*ill;
25863 	struct iocblk	*iocp;
25864 	ip_ioctl_cmd_t	*ipip;
25865 	cred_t		*cr;
25866 	conn_t		*connp = NULL;
25867 	int		cmd, err;
25868 	nce_t		*nce;
25869 	ipif_t		*ipif;
25870 
25871 	if (CONN_Q(q))
25872 		connp = Q_TO_CONN(q);
25873 
25874 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
25875 
25876 	/* Check if it is a queue to /dev/sctp. */
25877 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
25878 	    connp->conn_rq == NULL) {
25879 		sctp_wput(q, mp);
25880 		return;
25881 	}
25882 
25883 	switch (DB_TYPE(mp)) {
25884 	case M_IOCTL:
25885 		/*
25886 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
25887 		 * will arrange to copy in associated control structures.
25888 		 */
25889 		ip_sioctl_copyin_setup(q, mp);
25890 		return;
25891 	case M_IOCDATA:
25892 		/*
25893 		 * Ensure that this is associated with one of our trans-
25894 		 * parent ioctls.  If it's not ours, discard it if we're
25895 		 * running as a driver, or pass it on if we're a module.
25896 		 */
25897 		iocp = (struct iocblk *)mp->b_rptr;
25898 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25899 		if (ipip == NULL) {
25900 			if (q->q_next == NULL) {
25901 				goto nak;
25902 			} else {
25903 				putnext(q, mp);
25904 			}
25905 			return;
25906 		} else if ((q->q_next != NULL) &&
25907 		    !(ipip->ipi_flags & IPI_MODOK)) {
25908 			/*
25909 			 * the ioctl is one we recognise, but is not
25910 			 * consumed by IP as a module, pass M_IOCDATA
25911 			 * for processing downstream, but only for
25912 			 * common Streams ioctls.
25913 			 */
25914 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
25915 				putnext(q, mp);
25916 				return;
25917 			} else {
25918 				goto nak;
25919 			}
25920 		}
25921 
25922 		/* IOCTL continuation following copyin or copyout. */
25923 		if (mi_copy_state(q, mp, NULL) == -1) {
25924 			/*
25925 			 * The copy operation failed.  mi_copy_state already
25926 			 * cleaned up, so we're out of here.
25927 			 */
25928 			return;
25929 		}
25930 		/*
25931 		 * If we just completed a copy in, we become writer and
25932 		 * continue processing in ip_sioctl_copyin_done.  If it
25933 		 * was a copy out, we call mi_copyout again.  If there is
25934 		 * nothing more to copy out, it will complete the IOCTL.
25935 		 */
25936 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
25937 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
25938 				mi_copy_done(q, mp, EPROTO);
25939 				return;
25940 			}
25941 			/*
25942 			 * Check for cases that need more copying.  A return
25943 			 * value of 0 means a second copyin has been started,
25944 			 * so we return; a return value of 1 means no more
25945 			 * copying is needed, so we continue.
25946 			 */
25947 			cmd = iocp->ioc_cmd;
25948 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
25949 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
25950 			    MI_COPY_COUNT(mp) == 1) {
25951 				if (ip_copyin_msfilter(q, mp) == 0)
25952 					return;
25953 			}
25954 			/*
25955 			 * Refhold the conn, till the ioctl completes. This is
25956 			 * needed in case the ioctl ends up in the pending mp
25957 			 * list. Every mp in the ill_pending_mp list and
25958 			 * the ipsq_pending_mp must have a refhold on the conn
25959 			 * to resume processing. The refhold is released when
25960 			 * the ioctl completes. (normally or abnormally)
25961 			 * In all cases ip_ioctl_finish is called to finish
25962 			 * the ioctl.
25963 			 */
25964 			if (connp != NULL) {
25965 				/* This is not a reentry */
25966 				ASSERT(ipsq == NULL);
25967 				CONN_INC_REF(connp);
25968 			} else {
25969 				if (!(ipip->ipi_flags & IPI_MODOK)) {
25970 					mi_copy_done(q, mp, EINVAL);
25971 					return;
25972 				}
25973 			}
25974 
25975 			ip_process_ioctl(ipsq, q, mp, ipip);
25976 
25977 		} else {
25978 			mi_copyout(q, mp);
25979 		}
25980 		return;
25981 nak:
25982 		iocp->ioc_error = EINVAL;
25983 		mp->b_datap->db_type = M_IOCNAK;
25984 		iocp->ioc_count = 0;
25985 		qreply(q, mp);
25986 		return;
25987 
25988 	case M_IOCNAK:
25989 		/*
25990 		 * The only way we could get here is if a resolver didn't like
25991 		 * an IOCTL we sent it.	 This shouldn't happen.
25992 		 */
25993 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
25994 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
25995 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
25996 		freemsg(mp);
25997 		return;
25998 	case M_IOCACK:
25999 		/* Finish socket ioctls passed through to ARP. */
26000 		ip_sioctl_iocack(q, mp);
26001 		return;
26002 	case M_FLUSH:
26003 		if (*mp->b_rptr & FLUSHW)
26004 			flushq(q, FLUSHALL);
26005 		if (q->q_next) {
26006 			/*
26007 			 * M_FLUSH is sent up to IP by some drivers during
26008 			 * unbind. ip_rput has already replied to it. We are
26009 			 * here for the M_FLUSH that we originated in IP
26010 			 * before sending the unbind request to the driver.
26011 			 * Just free it as we don't queue packets in IP
26012 			 * on the write side of the device instance.
26013 			 */
26014 			freemsg(mp);
26015 			return;
26016 		}
26017 		if (*mp->b_rptr & FLUSHR) {
26018 			*mp->b_rptr &= ~FLUSHW;
26019 			qreply(q, mp);
26020 			return;
26021 		}
26022 		freemsg(mp);
26023 		return;
26024 	case IRE_DB_REQ_TYPE:
26025 		/* An Upper Level Protocol wants a copy of an IRE. */
26026 		ip_ire_req(q, mp);
26027 		return;
26028 	case M_CTL:
26029 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
26030 			break;
26031 
26032 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
26033 		    IP_ULP_OUT_LABELED) {
26034 			out_labeled_t *olp;
26035 
26036 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
26037 				break;
26038 			olp = (out_labeled_t *)mp->b_rptr;
26039 			connp->conn_ulp_labeled = olp->out_qnext == q;
26040 			freemsg(mp);
26041 			return;
26042 		}
26043 
26044 		/* M_CTL messages are used by ARP to tell us things. */
26045 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
26046 			break;
26047 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
26048 		case AR_ENTRY_SQUERY:
26049 			ip_wput_ctl(q, mp);
26050 			return;
26051 		case AR_CLIENT_NOTIFY:
26052 			ip_arp_news(q, mp);
26053 			return;
26054 		case AR_DLPIOP_DONE:
26055 			ASSERT(q->q_next != NULL);
26056 			ill = (ill_t *)q->q_ptr;
26057 			/* qwriter_ip releases the refhold */
26058 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
26059 			ill_refhold(ill);
26060 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
26061 			    CUR_OP, B_FALSE);
26062 			return;
26063 		case AR_ARP_CLOSING:
26064 			/*
26065 			 * ARP (above us) is closing. If no ARP bringup is
26066 			 * currently pending, ack the message so that ARP
26067 			 * can complete its close. Also mark ill_arp_closing
26068 			 * so that new ARP bringups will fail. If any
26069 			 * ARP bringup is currently in progress, we will
26070 			 * ack this when the current ARP bringup completes.
26071 			 */
26072 			ASSERT(q->q_next != NULL);
26073 			ill = (ill_t *)q->q_ptr;
26074 			mutex_enter(&ill->ill_lock);
26075 			ill->ill_arp_closing = 1;
26076 			if (!ill->ill_arp_bringup_pending) {
26077 				mutex_exit(&ill->ill_lock);
26078 				qreply(q, mp);
26079 			} else {
26080 				mutex_exit(&ill->ill_lock);
26081 				freemsg(mp);
26082 			}
26083 			return;
26084 		case AR_ARP_EXTEND:
26085 			/*
26086 			 * The ARP module above us is capable of duplicate
26087 			 * address detection.  Old ATM drivers will not send
26088 			 * this message.
26089 			 */
26090 			ASSERT(q->q_next != NULL);
26091 			ill = (ill_t *)q->q_ptr;
26092 			ill->ill_arp_extend = B_TRUE;
26093 			freemsg(mp);
26094 			return;
26095 		default:
26096 			break;
26097 		}
26098 		break;
26099 	case M_PROTO:
26100 	case M_PCPROTO:
26101 		/*
26102 		 * The only PROTO messages we expect are ULP binds and
26103 		 * copies of option negotiation acknowledgements.
26104 		 */
26105 		switch (((union T_primitives *)mp->b_rptr)->type) {
26106 		case O_T_BIND_REQ:
26107 		case T_BIND_REQ: {
26108 			/* Request can get queued in bind */
26109 			ASSERT(connp != NULL);
26110 			/*
26111 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
26112 			 * instead of going through this path.  We only get
26113 			 * here in the following cases:
26114 			 *
26115 			 * a. Bind retries, where ipsq is non-NULL.
26116 			 * b. T_BIND_REQ is issued from non TCP/UDP
26117 			 *    transport, e.g. icmp for raw socket,
26118 			 *    in which case ipsq will be NULL.
26119 			 */
26120 			ASSERT(ipsq != NULL ||
26121 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
26122 
26123 			/* Don't increment refcnt if this is a re-entry */
26124 			if (ipsq == NULL)
26125 				CONN_INC_REF(connp);
26126 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
26127 			    connp, NULL) : ip_bind_v4(q, mp, connp);
26128 			if (mp == NULL)
26129 				return;
26130 			if (IPCL_IS_TCP(connp)) {
26131 				/*
26132 				 * In the case of TCP endpoint we
26133 				 * come here only for bind retries
26134 				 */
26135 				ASSERT(ipsq != NULL);
26136 				CONN_INC_REF(connp);
26137 				squeue_fill(connp->conn_sqp, mp,
26138 				    ip_resume_tcp_bind, connp,
26139 				    SQTAG_BIND_RETRY);
26140 				return;
26141 			} else if (IPCL_IS_UDP(connp)) {
26142 				/*
26143 				 * In the case of UDP endpoint we
26144 				 * come here only for bind retries
26145 				 */
26146 				ASSERT(ipsq != NULL);
26147 				udp_resume_bind(connp, mp);
26148 				return;
26149 			}
26150 			qreply(q, mp);
26151 			CONN_OPER_PENDING_DONE(connp);
26152 			return;
26153 		}
26154 		case T_SVR4_OPTMGMT_REQ:
26155 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
26156 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
26157 
26158 			ASSERT(connp != NULL);
26159 			if (!snmpcom_req(q, mp, ip_snmp_set,
26160 			    ip_snmp_get, cr)) {
26161 				/*
26162 				 * Call svr4_optcom_req so that it can
26163 				 * generate the ack. We don't come here
26164 				 * if this operation is being restarted.
26165 				 * ip_restart_optmgmt will drop the conn ref.
26166 				 * In the case of ipsec option after the ipsec
26167 				 * load is complete conn_restart_ipsec_waiter
26168 				 * drops the conn ref.
26169 				 */
26170 				ASSERT(ipsq == NULL);
26171 				CONN_INC_REF(connp);
26172 				if (ip_check_for_ipsec_opt(q, mp))
26173 					return;
26174 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
26175 				if (err != EINPROGRESS) {
26176 					/* Operation is done */
26177 					CONN_OPER_PENDING_DONE(connp);
26178 				}
26179 			}
26180 			return;
26181 		case T_OPTMGMT_REQ:
26182 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
26183 			/*
26184 			 * Note: No snmpcom_req support through new
26185 			 * T_OPTMGMT_REQ.
26186 			 * Call tpi_optcom_req so that it can
26187 			 * generate the ack.
26188 			 */
26189 			ASSERT(connp != NULL);
26190 			ASSERT(ipsq == NULL);
26191 			/*
26192 			 * We don't come here for restart. ip_restart_optmgmt
26193 			 * will drop the conn ref. In the case of ipsec option
26194 			 * after the ipsec load is complete
26195 			 * conn_restart_ipsec_waiter drops the conn ref.
26196 			 */
26197 			CONN_INC_REF(connp);
26198 			if (ip_check_for_ipsec_opt(q, mp))
26199 				return;
26200 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
26201 			if (err != EINPROGRESS) {
26202 				/* Operation is done */
26203 				CONN_OPER_PENDING_DONE(connp);
26204 			}
26205 			return;
26206 		case T_UNBIND_REQ:
26207 			mp = ip_unbind(q, mp);
26208 			qreply(q, mp);
26209 			return;
26210 		default:
26211 			/*
26212 			 * Have to drop any DLPI messages coming down from
26213 			 * arp (such as an info_req which would cause ip
26214 			 * to receive an extra info_ack if it was passed
26215 			 * through.
26216 			 */
26217 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
26218 			    (int)*(uint_t *)mp->b_rptr));
26219 			freemsg(mp);
26220 			return;
26221 		}
26222 		/* NOTREACHED */
26223 	case IRE_DB_TYPE: {
26224 		nce_t		*nce;
26225 		ill_t		*ill;
26226 		in6_addr_t	gw_addr_v6;
26227 
26228 
26229 		/*
26230 		 * This is a response back from a resolver.  It
26231 		 * consists of a message chain containing:
26232 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
26233 		 * The IRE_MBLK is the one we allocated in ip_newroute.
26234 		 * The LL_HDR_MBLK is the DLPI header to use to get
26235 		 * the attached packet, and subsequent ones for the
26236 		 * same destination, transmitted.
26237 		 */
26238 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
26239 			break;
26240 		/*
26241 		 * First, check to make sure the resolution succeeded.
26242 		 * If it failed, the second mblk will be empty.
26243 		 * If it is, free the chain, dropping the packet.
26244 		 * (We must ire_delete the ire; that frees the ire mblk)
26245 		 * We're doing this now to support PVCs for ATM; it's
26246 		 * a partial xresolv implementation. When we fully implement
26247 		 * xresolv interfaces, instead of freeing everything here
26248 		 * we'll initiate neighbor discovery.
26249 		 *
26250 		 * For v4 (ARP and other external resolvers) the resolver
26251 		 * frees the message, so no check is needed. This check
26252 		 * is required, though, for a full xresolve implementation.
26253 		 * Including this code here now both shows how external
26254 		 * resolvers can NACK a resolution request using an
26255 		 * existing design that has no specific provisions for NACKs,
26256 		 * and also takes into account that the current non-ARP
26257 		 * external resolver has been coded to use this method of
26258 		 * NACKing for all IPv6 (xresolv) cases,
26259 		 * whether our xresolv implementation is complete or not.
26260 		 *
26261 		 */
26262 		ire = (ire_t *)mp->b_rptr;
26263 		ill = ire_to_ill(ire);
26264 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26265 		if (mp1->b_rptr == mp1->b_wptr) {
26266 			if (ire->ire_ipversion == IPV6_VERSION) {
26267 				/*
26268 				 * XRESOLV interface.
26269 				 */
26270 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
26271 				mutex_enter(&ire->ire_lock);
26272 				gw_addr_v6 = ire->ire_gateway_addr_v6;
26273 				mutex_exit(&ire->ire_lock);
26274 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26275 					nce = ndp_lookup_v6(ill,
26276 					    &ire->ire_addr_v6, B_FALSE);
26277 				} else {
26278 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
26279 					    B_FALSE);
26280 				}
26281 				if (nce != NULL) {
26282 					nce_resolv_failed(nce);
26283 					ndp_delete(nce);
26284 					NCE_REFRELE(nce);
26285 				}
26286 			}
26287 			mp->b_cont = NULL;
26288 			freemsg(mp1);		/* frees the pkt as well */
26289 			ASSERT(ire->ire_nce == NULL);
26290 			ire_delete((ire_t *)mp->b_rptr);
26291 			return;
26292 		}
26293 
26294 		/*
26295 		 * Split them into IRE_MBLK and pkt and feed it into
26296 		 * ire_add_then_send. Then in ire_add_then_send
26297 		 * the IRE will be added, and then the packet will be
26298 		 * run back through ip_wput. This time it will make
26299 		 * it to the wire.
26300 		 */
26301 		mp->b_cont = NULL;
26302 		mp = mp1->b_cont;		/* now, mp points to pkt */
26303 		mp1->b_cont = NULL;
26304 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
26305 		if (ire->ire_ipversion == IPV6_VERSION) {
26306 			/*
26307 			 * XRESOLV interface. Find the nce and put a copy
26308 			 * of the dl_unitdata_req in nce_res_mp
26309 			 */
26310 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
26311 			mutex_enter(&ire->ire_lock);
26312 			gw_addr_v6 = ire->ire_gateway_addr_v6;
26313 			mutex_exit(&ire->ire_lock);
26314 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26315 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
26316 				    B_FALSE);
26317 			} else {
26318 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
26319 			}
26320 			if (nce != NULL) {
26321 				/*
26322 				 * We have to protect nce_res_mp here
26323 				 * from being accessed by other threads
26324 				 * while we change the mblk pointer.
26325 				 * Other functions will also lock the nce when
26326 				 * accessing nce_res_mp.
26327 				 *
26328 				 * The reason we change the mblk pointer
26329 				 * here rather than copying the resolved address
26330 				 * into the template is that, unlike with
26331 				 * ethernet, we have no guarantee that the
26332 				 * resolved address length will be
26333 				 * smaller than or equal to the lla length
26334 				 * with which the template was allocated,
26335 				 * (for ethernet, they're equal)
26336 				 * so we have to use the actual resolved
26337 				 * address mblk - which holds the real
26338 				 * dl_unitdata_req with the resolved address.
26339 				 *
26340 				 * Doing this is the same behavior as was
26341 				 * previously used in the v4 ARP case.
26342 				 */
26343 				mutex_enter(&nce->nce_lock);
26344 				if (nce->nce_res_mp != NULL)
26345 					freemsg(nce->nce_res_mp);
26346 				nce->nce_res_mp = mp1;
26347 				mutex_exit(&nce->nce_lock);
26348 				/*
26349 				 * We do a fastpath probe here because
26350 				 * we have resolved the address without
26351 				 * using Neighbor Discovery.
26352 				 * In the non-XRESOLV v6 case, the fastpath
26353 				 * probe is done right after neighbor
26354 				 * discovery completes.
26355 				 */
26356 				if (nce->nce_res_mp != NULL) {
26357 					int res;
26358 					nce_fastpath_list_add(nce);
26359 					res = ill_fastpath_probe(ill,
26360 					    nce->nce_res_mp);
26361 					if (res != 0 && res != EAGAIN)
26362 						nce_fastpath_list_delete(nce);
26363 				}
26364 
26365 				ire_add_then_send(q, ire, mp);
26366 				/*
26367 				 * Now we have to clean out any packets
26368 				 * that may have been queued on the nce
26369 				 * while it was waiting for address resolution
26370 				 * to complete.
26371 				 */
26372 				mutex_enter(&nce->nce_lock);
26373 				mp1 = nce->nce_qd_mp;
26374 				nce->nce_qd_mp = NULL;
26375 				mutex_exit(&nce->nce_lock);
26376 				while (mp1 != NULL) {
26377 					mblk_t *nxt_mp;
26378 					queue_t *fwdq = NULL;
26379 					ill_t   *inbound_ill;
26380 					uint_t ifindex;
26381 
26382 					nxt_mp = mp1->b_next;
26383 					mp1->b_next = NULL;
26384 					/*
26385 					 * Retrieve ifindex stored in
26386 					 * ip_rput_data_v6()
26387 					 */
26388 					ifindex =
26389 					    (uint_t)(uintptr_t)mp1->b_prev;
26390 					inbound_ill =
26391 						ill_lookup_on_ifindex(ifindex,
26392 						    B_TRUE, NULL, NULL, NULL,
26393 						    NULL);
26394 					mp1->b_prev = NULL;
26395 					if (inbound_ill != NULL)
26396 						fwdq = inbound_ill->ill_rq;
26397 
26398 					if (fwdq != NULL) {
26399 						put(fwdq, mp1);
26400 						ill_refrele(inbound_ill);
26401 					} else
26402 						put(WR(ill->ill_rq), mp1);
26403 					mp1 = nxt_mp;
26404 				}
26405 				NCE_REFRELE(nce);
26406 			} else {	/* nce is NULL; clean up */
26407 				ire_delete(ire);
26408 				freemsg(mp);
26409 				freemsg(mp1);
26410 				return;
26411 			}
26412 		} else {
26413 			nce_t *arpce;
26414 			/*
26415 			 * Link layer resolution succeeded. Recompute the
26416 			 * ire_nce.
26417 			 */
26418 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
26419 			if ((arpce = ndp_lookup_v4(ill,
26420 			    (ire->ire_gateway_addr != INADDR_ANY ?
26421 			    &ire->ire_gateway_addr : &ire->ire_addr),
26422 			    B_FALSE)) == NULL) {
26423 				freeb(ire->ire_mp);
26424 				freeb(mp1);
26425 				freemsg(mp);
26426 				return;
26427 			}
26428 			mutex_enter(&arpce->nce_lock);
26429 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
26430 			if (arpce->nce_state == ND_REACHABLE) {
26431 				/*
26432 				 * Someone resolved this before us;
26433 				 * cleanup the res_mp. Since ire has
26434 				 * not been added yet, the call to ire_add_v4
26435 				 * from ire_add_then_send (when a dup is
26436 				 * detected) will clean up the ire.
26437 				 */
26438 				freeb(mp1);
26439 			} else {
26440 				if (arpce->nce_res_mp != NULL)
26441 					freemsg(arpce->nce_res_mp);
26442 				arpce->nce_res_mp = mp1;
26443 				arpce->nce_state = ND_REACHABLE;
26444 			}
26445 			mutex_exit(&arpce->nce_lock);
26446 			if (ire->ire_marks & IRE_MARK_NOADD) {
26447 				/*
26448 				 * this ire will not be added to the ire
26449 				 * cache table, so we can set the ire_nce
26450 				 * here, as there are no atomicity constraints.
26451 				 */
26452 				ire->ire_nce = arpce;
26453 				/*
26454 				 * We are associating this nce with the ire
26455 				 * so change the nce ref taken in
26456 				 * ndp_lookup_v4() from
26457 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
26458 				 */
26459 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
26460 			} else {
26461 				NCE_REFRELE(arpce);
26462 			}
26463 			ire_add_then_send(q, ire, mp);
26464 		}
26465 		return;	/* All is well, the packet has been sent. */
26466 	}
26467 	case IRE_ARPRESOLVE_TYPE: {
26468 
26469 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
26470 			break;
26471 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26472 		mp->b_cont = NULL;
26473 		/*
26474 		 * First, check to make sure the resolution succeeded.
26475 		 * If it failed, the second mblk will be empty.
26476 		 */
26477 		if (mp1->b_rptr == mp1->b_wptr) {
26478 			/* cleanup  the incomplete ire, free queued packets */
26479 			freemsg(mp); /* fake ire */
26480 			freeb(mp1);  /* dl_unitdata response */
26481 			return;
26482 		}
26483 
26484 		/*
26485 		 * update any incomplete nce_t found. we lookup the ctable
26486 		 * and find the nce from the ire->ire_nce because we need
26487 		 * to pass the ire to ip_xmit_v4 later, and can find both
26488 		 * ire and nce in one lookup from the ctable.
26489 		 */
26490 		fake_ire = (ire_t *)mp->b_rptr;
26491 		/*
26492 		 * By the time we come back here from ARP
26493 		 * the logical outgoing interface  of the incomplete ire
26494 		 * we added in ire_forward could have disappeared,
26495 		 * causing the incomplete ire to also have
26496 		 * dissapeared. So we need to retreive the
26497 		 * proper ipif for the ire  before looking
26498 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
26499 		 */
26500 		ill = q->q_ptr;
26501 
26502 		/* Get the outgoing ipif */
26503 		mutex_enter(&ill->ill_lock);
26504 		if (ill->ill_state_flags & ILL_CONDEMNED) {
26505 			mutex_exit(&ill->ill_lock);
26506 			freemsg(mp); /* fake ire */
26507 			freeb(mp1);  /* dl_unitdata response */
26508 			return;
26509 		}
26510 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
26511 
26512 		if (ipif == NULL) {
26513 			mutex_exit(&ill->ill_lock);
26514 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
26515 			freemsg(mp);
26516 			freeb(mp1);
26517 			return;
26518 		}
26519 		ipif_refhold_locked(ipif);
26520 		mutex_exit(&ill->ill_lock);
26521 		ire = ire_ctable_lookup(fake_ire->ire_addr,
26522 		    fake_ire->ire_gateway_addr, IRE_CACHE,
26523 		    ipif, fake_ire->ire_zoneid, NULL,
26524 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
26525 		ipif_refrele(ipif);
26526 		if (ire == NULL) {
26527 			/*
26528 			 * no ire was found; check if there is an nce
26529 			 * for this lookup; if it has no ire's pointing at it
26530 			 * cleanup.
26531 			 */
26532 			if ((nce = ndp_lookup_v4(ill,
26533 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
26534 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
26535 			    B_FALSE)) != NULL) {
26536 				/*
26537 				 * cleanup: just reset nce.
26538 				 * We check for refcnt 2 (one for the nce
26539 				 * hash list + 1 for the ref taken by
26540 				 * ndp_lookup_v4) to ensure that there are
26541 				 * no ire's pointing at the nce.
26542 				 */
26543 				if (nce->nce_refcnt == 2) {
26544 					nce = nce_reinit(nce);
26545 				}
26546 				if (nce != NULL)
26547 					NCE_REFRELE(nce);
26548 			}
26549 			freeb(mp1);  /* dl_unitdata response */
26550 			freemsg(mp); /* fake ire */
26551 			return;
26552 		}
26553 		nce = ire->ire_nce;
26554 		DTRACE_PROBE2(ire__arpresolve__type,
26555 		    ire_t *, ire, nce_t *, nce);
26556 		ASSERT(nce->nce_state != ND_INITIAL);
26557 		mutex_enter(&nce->nce_lock);
26558 		nce->nce_last = TICK_TO_MSEC(lbolt64);
26559 		if (nce->nce_state == ND_REACHABLE) {
26560 			/*
26561 			 * Someone resolved this before us;
26562 			 * our response is not needed any more.
26563 			 */
26564 			mutex_exit(&nce->nce_lock);
26565 			freeb(mp1);  /* dl_unitdata response */
26566 		} else {
26567 			if (nce->nce_res_mp != NULL) {
26568 				freemsg(nce->nce_res_mp);
26569 				/* existing dl_unitdata template */
26570 			}
26571 			nce->nce_res_mp = mp1;
26572 			nce->nce_state = ND_REACHABLE;
26573 			mutex_exit(&nce->nce_lock);
26574 			ire_fastpath(ire);
26575 		}
26576 		/*
26577 		 * The cached nce_t has been updated to be reachable;
26578 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
26579 		 */
26580 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
26581 		freemsg(mp);
26582 		/*
26583 		 * send out queued packets.
26584 		 */
26585 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26586 
26587 		IRE_REFRELE(ire);
26588 		return;
26589 	}
26590 	default:
26591 		break;
26592 	}
26593 	if (q->q_next) {
26594 		putnext(q, mp);
26595 	} else
26596 		freemsg(mp);
26597 }
26598 
26599 /*
26600  * Process IP options in an outbound packet.  Modify the destination if there
26601  * is a source route option.
26602  * Returns non-zero if something fails in which case an ICMP error has been
26603  * sent and mp freed.
26604  */
26605 static int
26606 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
26607     boolean_t mctl_present, zoneid_t zoneid)
26608 {
26609 	ipoptp_t	opts;
26610 	uchar_t		*opt;
26611 	uint8_t		optval;
26612 	uint8_t		optlen;
26613 	ipaddr_t	dst;
26614 	intptr_t	code = 0;
26615 	mblk_t		*mp;
26616 	ire_t		*ire = NULL;
26617 
26618 	ip2dbg(("ip_wput_options\n"));
26619 	mp = ipsec_mp;
26620 	if (mctl_present) {
26621 		mp = ipsec_mp->b_cont;
26622 	}
26623 
26624 	dst = ipha->ipha_dst;
26625 	for (optval = ipoptp_first(&opts, ipha);
26626 	    optval != IPOPT_EOL;
26627 	    optval = ipoptp_next(&opts)) {
26628 		opt = opts.ipoptp_cur;
26629 		optlen = opts.ipoptp_len;
26630 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
26631 		    optval, optlen));
26632 		switch (optval) {
26633 			uint32_t off;
26634 		case IPOPT_SSRR:
26635 		case IPOPT_LSRR:
26636 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26637 				ip1dbg((
26638 				    "ip_wput_options: bad option offset\n"));
26639 				code = (char *)&opt[IPOPT_OLEN] -
26640 				    (char *)ipha;
26641 				goto param_prob;
26642 			}
26643 			off = opt[IPOPT_OFFSET];
26644 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
26645 			    ntohl(dst)));
26646 			/*
26647 			 * For strict: verify that dst is directly
26648 			 * reachable.
26649 			 */
26650 			if (optval == IPOPT_SSRR) {
26651 				ire = ire_ftable_lookup(dst, 0, 0,
26652 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
26653 				    MBLK_GETLABEL(mp),
26654 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
26655 				if (ire == NULL) {
26656 					ip1dbg(("ip_wput_options: SSRR not"
26657 					    " directly reachable: 0x%x\n",
26658 					    ntohl(dst)));
26659 					goto bad_src_route;
26660 				}
26661 				ire_refrele(ire);
26662 			}
26663 			break;
26664 		case IPOPT_RR:
26665 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26666 				ip1dbg((
26667 				    "ip_wput_options: bad option offset\n"));
26668 				code = (char *)&opt[IPOPT_OLEN] -
26669 				    (char *)ipha;
26670 				goto param_prob;
26671 			}
26672 			break;
26673 		case IPOPT_TS:
26674 			/*
26675 			 * Verify that length >=5 and that there is either
26676 			 * room for another timestamp or that the overflow
26677 			 * counter is not maxed out.
26678 			 */
26679 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
26680 			if (optlen < IPOPT_MINLEN_IT) {
26681 				goto param_prob;
26682 			}
26683 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
26684 				ip1dbg((
26685 				    "ip_wput_options: bad option offset\n"));
26686 				code = (char *)&opt[IPOPT_OFFSET] -
26687 				    (char *)ipha;
26688 				goto param_prob;
26689 			}
26690 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
26691 			case IPOPT_TS_TSONLY:
26692 				off = IPOPT_TS_TIMELEN;
26693 				break;
26694 			case IPOPT_TS_TSANDADDR:
26695 			case IPOPT_TS_PRESPEC:
26696 			case IPOPT_TS_PRESPEC_RFC791:
26697 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
26698 				break;
26699 			default:
26700 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
26701 				    (char *)ipha;
26702 				goto param_prob;
26703 			}
26704 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
26705 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
26706 				/*
26707 				 * No room and the overflow counter is 15
26708 				 * already.
26709 				 */
26710 				goto param_prob;
26711 			}
26712 			break;
26713 		}
26714 	}
26715 
26716 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
26717 		return (0);
26718 
26719 	ip1dbg(("ip_wput_options: error processing IP options."));
26720 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
26721 
26722 param_prob:
26723 	/*
26724 	 * Since ip_wput() isn't close to finished, we fill
26725 	 * in enough of the header for credible error reporting.
26726 	 */
26727 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
26728 		/* Failed */
26729 		freemsg(ipsec_mp);
26730 		return (-1);
26731 	}
26732 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
26733 	return (-1);
26734 
26735 bad_src_route:
26736 	/*
26737 	 * Since ip_wput() isn't close to finished, we fill
26738 	 * in enough of the header for credible error reporting.
26739 	 */
26740 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
26741 		/* Failed */
26742 		freemsg(ipsec_mp);
26743 		return (-1);
26744 	}
26745 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
26746 	return (-1);
26747 }
26748 
26749 /*
26750  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
26751  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
26752  * thru /etc/system.
26753  */
26754 #define	CONN_MAXDRAINCNT	64
26755 
26756 static void
26757 conn_drain_init(void)
26758 {
26759 	int i;
26760 
26761 	conn_drain_list_cnt = conn_drain_nthreads;
26762 
26763 	if ((conn_drain_list_cnt == 0) ||
26764 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
26765 		/*
26766 		 * Default value of the number of drainers is the
26767 		 * number of cpus, subject to maximum of 8 drainers.
26768 		 */
26769 		if (boot_max_ncpus != -1)
26770 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
26771 		else
26772 			conn_drain_list_cnt = MIN(max_ncpus, 8);
26773 	}
26774 
26775 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
26776 	    KM_SLEEP);
26777 
26778 	for (i = 0; i < conn_drain_list_cnt; i++) {
26779 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
26780 		    MUTEX_DEFAULT, NULL);
26781 	}
26782 }
26783 
26784 static void
26785 conn_drain_fini(void)
26786 {
26787 	int i;
26788 
26789 	for (i = 0; i < conn_drain_list_cnt; i++)
26790 		mutex_destroy(&conn_drain_list[i].idl_lock);
26791 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
26792 	conn_drain_list = NULL;
26793 }
26794 
26795 /*
26796  * Note: For an overview of how flowcontrol is handled in IP please see the
26797  * IP Flowcontrol notes at the top of this file.
26798  *
26799  * Flow control has blocked us from proceeding. Insert the given conn in one
26800  * of the conn drain lists. These conn wq's will be qenabled later on when
26801  * STREAMS flow control does a backenable. conn_walk_drain will enable
26802  * the first conn in each of these drain lists. Each of these qenabled conns
26803  * in turn enables the next in the list, after it runs, or when it closes,
26804  * thus sustaining the drain process.
26805  *
26806  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
26807  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
26808  * running at any time, on a given conn, since there can be only 1 service proc
26809  * running on a queue at any time.
26810  */
26811 void
26812 conn_drain_insert(conn_t *connp)
26813 {
26814 	idl_t	*idl;
26815 	uint_t	index;
26816 
26817 	mutex_enter(&connp->conn_lock);
26818 	if (connp->conn_state_flags & CONN_CLOSING) {
26819 		/*
26820 		 * The conn is closing as a result of which CONN_CLOSING
26821 		 * is set. Return.
26822 		 */
26823 		mutex_exit(&connp->conn_lock);
26824 		return;
26825 	} else if (connp->conn_idl == NULL) {
26826 		/*
26827 		 * Assign the next drain list round robin. We dont' use
26828 		 * a lock, and thus it may not be strictly round robin.
26829 		 * Atomicity of load/stores is enough to make sure that
26830 		 * conn_drain_list_index is always within bounds.
26831 		 */
26832 		index = conn_drain_list_index;
26833 		ASSERT(index < conn_drain_list_cnt);
26834 		connp->conn_idl = &conn_drain_list[index];
26835 		index++;
26836 		if (index == conn_drain_list_cnt)
26837 			index = 0;
26838 		conn_drain_list_index = index;
26839 	}
26840 	mutex_exit(&connp->conn_lock);
26841 
26842 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
26843 	if ((connp->conn_drain_prev != NULL) ||
26844 	    (connp->conn_state_flags & CONN_CLOSING)) {
26845 		/*
26846 		 * The conn is already in the drain list, OR
26847 		 * the conn is closing. We need to check again for
26848 		 * the closing case again since close can happen
26849 		 * after we drop the conn_lock, and before we
26850 		 * acquire the CONN_DRAIN_LIST_LOCK.
26851 		 */
26852 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26853 		return;
26854 	} else {
26855 		idl = connp->conn_idl;
26856 	}
26857 
26858 	/*
26859 	 * The conn is not in the drain list. Insert it at the
26860 	 * tail of the drain list. The drain list is circular
26861 	 * and doubly linked. idl_conn points to the 1st element
26862 	 * in the list.
26863 	 */
26864 	if (idl->idl_conn == NULL) {
26865 		idl->idl_conn = connp;
26866 		connp->conn_drain_next = connp;
26867 		connp->conn_drain_prev = connp;
26868 	} else {
26869 		conn_t *head = idl->idl_conn;
26870 
26871 		connp->conn_drain_next = head;
26872 		connp->conn_drain_prev = head->conn_drain_prev;
26873 		head->conn_drain_prev->conn_drain_next = connp;
26874 		head->conn_drain_prev = connp;
26875 	}
26876 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26877 }
26878 
26879 /*
26880  * This conn is closing, and we are called from ip_close. OR
26881  * This conn has been serviced by ip_wsrv, and we need to do the tail
26882  * processing.
26883  * If this conn is part of the drain list, we may need to sustain the drain
26884  * process by qenabling the next conn in the drain list. We may also need to
26885  * remove this conn from the list, if it is done.
26886  */
26887 static void
26888 conn_drain_tail(conn_t *connp, boolean_t closing)
26889 {
26890 	idl_t *idl;
26891 
26892 	/*
26893 	 * connp->conn_idl is stable at this point, and no lock is needed
26894 	 * to check it. If we are called from ip_close, close has already
26895 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
26896 	 * called us only because conn_idl is non-null. If we are called thru
26897 	 * service, conn_idl could be null, but it cannot change because
26898 	 * service is single-threaded per queue, and there cannot be another
26899 	 * instance of service trying to call conn_drain_insert on this conn
26900 	 * now.
26901 	 */
26902 	ASSERT(!closing || (connp->conn_idl != NULL));
26903 
26904 	/*
26905 	 * If connp->conn_idl is null, the conn has not been inserted into any
26906 	 * drain list even once since creation of the conn. Just return.
26907 	 */
26908 	if (connp->conn_idl == NULL)
26909 		return;
26910 
26911 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
26912 
26913 	if (connp->conn_drain_prev == NULL) {
26914 		/* This conn is currently not in the drain list.  */
26915 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26916 		return;
26917 	}
26918 	idl = connp->conn_idl;
26919 	if (idl->idl_conn_draining == connp) {
26920 		/*
26921 		 * This conn is the current drainer. If this is the last conn
26922 		 * in the drain list, we need to do more checks, in the 'if'
26923 		 * below. Otherwwise we need to just qenable the next conn,
26924 		 * to sustain the draining, and is handled in the 'else'
26925 		 * below.
26926 		 */
26927 		if (connp->conn_drain_next == idl->idl_conn) {
26928 			/*
26929 			 * This conn is the last in this list. This round
26930 			 * of draining is complete. If idl_repeat is set,
26931 			 * it means another flow enabling has happened from
26932 			 * the driver/streams and we need to another round
26933 			 * of draining.
26934 			 * If there are more than 2 conns in the drain list,
26935 			 * do a left rotate by 1, so that all conns except the
26936 			 * conn at the head move towards the head by 1, and the
26937 			 * the conn at the head goes to the tail. This attempts
26938 			 * a more even share for all queues that are being
26939 			 * drained.
26940 			 */
26941 			if ((connp->conn_drain_next != connp) &&
26942 			    (idl->idl_conn->conn_drain_next != connp)) {
26943 				idl->idl_conn = idl->idl_conn->conn_drain_next;
26944 			}
26945 			if (idl->idl_repeat) {
26946 				qenable(idl->idl_conn->conn_wq);
26947 				idl->idl_conn_draining = idl->idl_conn;
26948 				idl->idl_repeat = 0;
26949 			} else {
26950 				idl->idl_conn_draining = NULL;
26951 			}
26952 		} else {
26953 			/*
26954 			 * If the next queue that we are now qenable'ing,
26955 			 * is closing, it will remove itself from this list
26956 			 * and qenable the subsequent queue in ip_close().
26957 			 * Serialization is acheived thru idl_lock.
26958 			 */
26959 			qenable(connp->conn_drain_next->conn_wq);
26960 			idl->idl_conn_draining = connp->conn_drain_next;
26961 		}
26962 	}
26963 	if (!connp->conn_did_putbq || closing) {
26964 		/*
26965 		 * Remove ourself from the drain list, if we did not do
26966 		 * a putbq, or if the conn is closing.
26967 		 * Note: It is possible that q->q_first is non-null. It means
26968 		 * that these messages landed after we did a enableok() in
26969 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
26970 		 * service them.
26971 		 */
26972 		if (connp->conn_drain_next == connp) {
26973 			/* Singleton in the list */
26974 			ASSERT(connp->conn_drain_prev == connp);
26975 			idl->idl_conn = NULL;
26976 			idl->idl_conn_draining = NULL;
26977 		} else {
26978 			connp->conn_drain_prev->conn_drain_next =
26979 			    connp->conn_drain_next;
26980 			connp->conn_drain_next->conn_drain_prev =
26981 			    connp->conn_drain_prev;
26982 			if (idl->idl_conn == connp)
26983 				idl->idl_conn = connp->conn_drain_next;
26984 			ASSERT(idl->idl_conn_draining != connp);
26985 
26986 		}
26987 		connp->conn_drain_next = NULL;
26988 		connp->conn_drain_prev = NULL;
26989 	}
26990 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26991 }
26992 
26993 /*
26994  * Write service routine. Shared perimeter entry point.
26995  * ip_wsrv can be called in any of the following ways.
26996  * 1. The device queue's messages has fallen below the low water mark
26997  *    and STREAMS has backenabled the ill_wq. We walk thru all the
26998  *    the drain lists and backenable the first conn in each list.
26999  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
27000  *    qenabled non-tcp upper layers. We start dequeing messages and call
27001  *    ip_wput for each message.
27002  */
27003 
27004 void
27005 ip_wsrv(queue_t *q)
27006 {
27007 	conn_t	*connp;
27008 	ill_t	*ill;
27009 	mblk_t	*mp;
27010 
27011 	if (q->q_next) {
27012 		ill = (ill_t *)q->q_ptr;
27013 		if (ill->ill_state_flags == 0) {
27014 			/*
27015 			 * The device flow control has opened up.
27016 			 * Walk through conn drain lists and qenable the
27017 			 * first conn in each list. This makes sense only
27018 			 * if the stream is fully plumbed and setup.
27019 			 * Hence the if check above.
27020 			 */
27021 			ip1dbg(("ip_wsrv: walking\n"));
27022 			conn_walk_drain();
27023 		}
27024 		return;
27025 	}
27026 
27027 	connp = Q_TO_CONN(q);
27028 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
27029 
27030 	/*
27031 	 * 1. Set conn_draining flag to signal that service is active.
27032 	 *
27033 	 * 2. ip_output determines whether it has been called from service,
27034 	 *    based on the last parameter. If it is IP_WSRV it concludes it
27035 	 *    has been called from service.
27036 	 *
27037 	 * 3. Message ordering is preserved by the following logic.
27038 	 *    i. A directly called ip_output (i.e. not thru service) will queue
27039 	 *    the message at the tail, if conn_draining is set (i.e. service
27040 	 *    is running) or if q->q_first is non-null.
27041 	 *
27042 	 *    ii. If ip_output is called from service, and if ip_output cannot
27043 	 *    putnext due to flow control, it does a putbq.
27044 	 *
27045 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
27046 	 *    (causing an infinite loop).
27047 	 */
27048 	ASSERT(!connp->conn_did_putbq);
27049 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
27050 		connp->conn_draining = 1;
27051 		noenable(q);
27052 		while ((mp = getq(q)) != NULL) {
27053 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
27054 			if (connp->conn_did_putbq) {
27055 				/* ip_wput did a putbq */
27056 				break;
27057 			}
27058 		}
27059 		/*
27060 		 * At this point, a thread coming down from top, calling
27061 		 * ip_wput, may end up queueing the message. We have not yet
27062 		 * enabled the queue, so ip_wsrv won't be called again.
27063 		 * To avoid this race, check q->q_first again (in the loop)
27064 		 * If the other thread queued the message before we call
27065 		 * enableok(), we will catch it in the q->q_first check.
27066 		 * If the other thread queues the message after we call
27067 		 * enableok(), ip_wsrv will be called again by STREAMS.
27068 		 */
27069 		connp->conn_draining = 0;
27070 		enableok(q);
27071 	}
27072 
27073 	/* Enable the next conn for draining */
27074 	conn_drain_tail(connp, B_FALSE);
27075 
27076 	connp->conn_did_putbq = 0;
27077 }
27078 
27079 /*
27080  * Walk the list of all conn's calling the function provided with the
27081  * specified argument for each.	 Note that this only walks conn's that
27082  * have been bound.
27083  * Applies to both IPv4 and IPv6.
27084  */
27085 static void
27086 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
27087 {
27088 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
27089 	    func, arg, zoneid);
27090 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
27091 	    func, arg, zoneid);
27092 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
27093 	    func, arg, zoneid);
27094 	conn_walk_fanout_table(ipcl_proto_fanout,
27095 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
27096 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
27097 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
27098 }
27099 
27100 /*
27101  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
27102  * of conns that need to be drained, check if drain is already in progress.
27103  * If so set the idl_repeat bit, indicating that the last conn in the list
27104  * needs to reinitiate the drain once again, for the list. If drain is not
27105  * in progress for the list, initiate the draining, by qenabling the 1st
27106  * conn in the list. The drain is self-sustaining, each qenabled conn will
27107  * in turn qenable the next conn, when it is done/blocked/closing.
27108  */
27109 static void
27110 conn_walk_drain(void)
27111 {
27112 	int i;
27113 	idl_t *idl;
27114 
27115 	IP_STAT(ip_conn_walk_drain);
27116 
27117 	for (i = 0; i < conn_drain_list_cnt; i++) {
27118 		idl = &conn_drain_list[i];
27119 		mutex_enter(&idl->idl_lock);
27120 		if (idl->idl_conn == NULL) {
27121 			mutex_exit(&idl->idl_lock);
27122 			continue;
27123 		}
27124 		/*
27125 		 * If this list is not being drained currently by
27126 		 * an ip_wsrv thread, start the process.
27127 		 */
27128 		if (idl->idl_conn_draining == NULL) {
27129 			ASSERT(idl->idl_repeat == 0);
27130 			qenable(idl->idl_conn->conn_wq);
27131 			idl->idl_conn_draining = idl->idl_conn;
27132 		} else {
27133 			idl->idl_repeat = 1;
27134 		}
27135 		mutex_exit(&idl->idl_lock);
27136 	}
27137 }
27138 
27139 /*
27140  * Walk an conn hash table of `count' buckets, calling func for each entry.
27141  */
27142 static void
27143 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
27144     zoneid_t zoneid)
27145 {
27146 	conn_t	*connp;
27147 
27148 	while (count-- > 0) {
27149 		mutex_enter(&connfp->connf_lock);
27150 		for (connp = connfp->connf_head; connp != NULL;
27151 		    connp = connp->conn_next) {
27152 			if (zoneid == GLOBAL_ZONEID ||
27153 			    zoneid == connp->conn_zoneid) {
27154 				CONN_INC_REF(connp);
27155 				mutex_exit(&connfp->connf_lock);
27156 				(*func)(connp, arg);
27157 				mutex_enter(&connfp->connf_lock);
27158 				CONN_DEC_REF(connp);
27159 			}
27160 		}
27161 		mutex_exit(&connfp->connf_lock);
27162 		connfp++;
27163 	}
27164 }
27165 
27166 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
27167 static void
27168 conn_report1(conn_t *connp, void *mp)
27169 {
27170 	char	buf1[INET6_ADDRSTRLEN];
27171 	char	buf2[INET6_ADDRSTRLEN];
27172 	uint_t	print_len, buf_len;
27173 
27174 	ASSERT(connp != NULL);
27175 
27176 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
27177 	if (buf_len <= 0)
27178 		return;
27179 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
27180 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
27181 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
27182 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
27183 	    "%5d %s/%05d %s/%05d\n",
27184 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
27185 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
27186 	    buf1, connp->conn_lport,
27187 	    buf2, connp->conn_fport);
27188 	if (print_len < buf_len) {
27189 		((mblk_t *)mp)->b_wptr += print_len;
27190 	} else {
27191 		((mblk_t *)mp)->b_wptr += buf_len;
27192 	}
27193 }
27194 
27195 /*
27196  * Named Dispatch routine to produce a formatted report on all conns
27197  * that are listed in one of the fanout tables.
27198  * This report is accessed by using the ndd utility to "get" ND variable
27199  * "ip_conn_status".
27200  */
27201 /* ARGSUSED */
27202 static int
27203 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
27204 {
27205 	(void) mi_mpprintf(mp,
27206 	    "CONN      " MI_COL_HDRPAD_STR
27207 	    "rfq      " MI_COL_HDRPAD_STR
27208 	    "stq      " MI_COL_HDRPAD_STR
27209 	    " zone local                 remote");
27210 
27211 	/*
27212 	 * Because of the ndd constraint, at most we can have 64K buffer
27213 	 * to put in all conn info.  So to be more efficient, just
27214 	 * allocate a 64K buffer here, assuming we need that large buffer.
27215 	 * This should be OK as only privileged processes can do ndd /dev/ip.
27216 	 */
27217 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
27218 		/* The following may work even if we cannot get a large buf. */
27219 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
27220 		return (0);
27221 	}
27222 
27223 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
27224 	return (0);
27225 }
27226 
27227 /*
27228  * Determine if the ill and multicast aspects of that packets
27229  * "matches" the conn.
27230  */
27231 boolean_t
27232 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
27233     zoneid_t zoneid)
27234 {
27235 	ill_t *in_ill;
27236 	boolean_t found;
27237 	ipif_t *ipif;
27238 	ire_t *ire;
27239 	ipaddr_t dst, src;
27240 
27241 	dst = ipha->ipha_dst;
27242 	src = ipha->ipha_src;
27243 
27244 	/*
27245 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
27246 	 * unicast, broadcast and multicast reception to
27247 	 * conn_incoming_ill. conn_wantpacket itself is called
27248 	 * only for BROADCAST and multicast.
27249 	 *
27250 	 * 1) ip_rput supresses duplicate broadcasts if the ill
27251 	 *    is part of a group. Hence, we should be receiving
27252 	 *    just one copy of broadcast for the whole group.
27253 	 *    Thus, if it is part of the group the packet could
27254 	 *    come on any ill of the group and hence we need a
27255 	 *    match on the group. Otherwise, match on ill should
27256 	 *    be sufficient.
27257 	 *
27258 	 * 2) ip_rput does not suppress duplicate multicast packets.
27259 	 *    If there are two interfaces in a ill group and we have
27260 	 *    2 applications (conns) joined a multicast group G on
27261 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
27262 	 *    will give us two packets because we join G on both the
27263 	 *    interfaces rather than nominating just one interface
27264 	 *    for receiving multicast like broadcast above. So,
27265 	 *    we have to call ilg_lookup_ill to filter out duplicate
27266 	 *    copies, if ill is part of a group.
27267 	 */
27268 	in_ill = connp->conn_incoming_ill;
27269 	if (in_ill != NULL) {
27270 		if (in_ill->ill_group == NULL) {
27271 			if (in_ill != ill)
27272 				return (B_FALSE);
27273 		} else if (in_ill->ill_group != ill->ill_group) {
27274 			return (B_FALSE);
27275 		}
27276 	}
27277 
27278 	if (!CLASSD(dst)) {
27279 		if (IPCL_ZONE_MATCH(connp, zoneid))
27280 			return (B_TRUE);
27281 		/*
27282 		 * The conn is in a different zone; we need to check that this
27283 		 * broadcast address is configured in the application's zone and
27284 		 * on one ill in the group.
27285 		 */
27286 		ipif = ipif_get_next_ipif(NULL, ill);
27287 		if (ipif == NULL)
27288 			return (B_FALSE);
27289 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
27290 		    connp->conn_zoneid, NULL,
27291 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
27292 		ipif_refrele(ipif);
27293 		if (ire != NULL) {
27294 			ire_refrele(ire);
27295 			return (B_TRUE);
27296 		} else {
27297 			return (B_FALSE);
27298 		}
27299 	}
27300 
27301 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
27302 	    connp->conn_zoneid == zoneid) {
27303 		/*
27304 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
27305 		 * disabled, therefore we don't dispatch the multicast packet to
27306 		 * the sending zone.
27307 		 */
27308 		return (B_FALSE);
27309 	}
27310 
27311 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
27312 	    connp->conn_zoneid != zoneid) {
27313 		/*
27314 		 * Multicast packet on the loopback interface: we only match
27315 		 * conns who joined the group in the specified zone.
27316 		 */
27317 		return (B_FALSE);
27318 	}
27319 
27320 	if (connp->conn_multi_router) {
27321 		/* multicast packet and multicast router socket: send up */
27322 		return (B_TRUE);
27323 	}
27324 
27325 	mutex_enter(&connp->conn_lock);
27326 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
27327 	mutex_exit(&connp->conn_lock);
27328 	return (found);
27329 }
27330 
27331 /*
27332  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
27333  */
27334 /* ARGSUSED */
27335 static void
27336 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
27337 {
27338 	ill_t *ill = (ill_t *)q->q_ptr;
27339 	mblk_t	*mp1, *mp2;
27340 	ipif_t  *ipif;
27341 	int err = 0;
27342 	conn_t *connp = NULL;
27343 	ipsq_t	*ipsq;
27344 	arc_t	*arc;
27345 
27346 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
27347 
27348 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
27349 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
27350 
27351 	ASSERT(IAM_WRITER_ILL(ill));
27352 	mp2 = mp->b_cont;
27353 	mp->b_cont = NULL;
27354 
27355 	/*
27356 	 * We have now received the arp bringup completion message
27357 	 * from ARP. Mark the arp bringup as done. Also if the arp
27358 	 * stream has already started closing, send up the AR_ARP_CLOSING
27359 	 * ack now since ARP is waiting in close for this ack.
27360 	 */
27361 	mutex_enter(&ill->ill_lock);
27362 	ill->ill_arp_bringup_pending = 0;
27363 	if (ill->ill_arp_closing) {
27364 		mutex_exit(&ill->ill_lock);
27365 		/* Let's reuse the mp for sending the ack */
27366 		arc = (arc_t *)mp->b_rptr;
27367 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
27368 		arc->arc_cmd = AR_ARP_CLOSING;
27369 		qreply(q, mp);
27370 	} else {
27371 		mutex_exit(&ill->ill_lock);
27372 		freeb(mp);
27373 	}
27374 
27375 	/* We should have an IOCTL waiting on this. */
27376 	ipsq = ill->ill_phyint->phyint_ipsq;
27377 	ipif = ipsq->ipsq_pending_ipif;
27378 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
27379 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
27380 	if (mp1 == NULL) {
27381 		/* bringup was aborted by the user */
27382 		freemsg(mp2);
27383 		return;
27384 	}
27385 	ASSERT(connp != NULL);
27386 	q = CONNP_TO_WQ(connp);
27387 	/*
27388 	 * If the DL_BIND_REQ fails, it is noted
27389 	 * in arc_name_offset.
27390 	 */
27391 	err = *((int *)mp2->b_rptr);
27392 	if (err == 0) {
27393 		if (ipif->ipif_isv6) {
27394 			if ((err = ipif_up_done_v6(ipif)) != 0)
27395 				ip0dbg(("ip_arp_done: init failed\n"));
27396 		} else {
27397 			if ((err = ipif_up_done(ipif)) != 0)
27398 				ip0dbg(("ip_arp_done: init failed\n"));
27399 		}
27400 	} else {
27401 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
27402 	}
27403 
27404 	freemsg(mp2);
27405 
27406 	if ((err == 0) && (ill->ill_up_ipifs)) {
27407 		err = ill_up_ipifs(ill, q, mp1);
27408 		if (err == EINPROGRESS)
27409 			return;
27410 	}
27411 
27412 	if (ill->ill_up_ipifs) {
27413 		ill_group_cleanup(ill);
27414 	}
27415 
27416 	/*
27417 	 * The ioctl must complete now without EINPROGRESS
27418 	 * since ipsq_pending_mp_get has removed the ioctl mblk
27419 	 * from ipsq_pending_mp. Otherwise the ioctl will be
27420 	 * stuck for ever in the ipsq.
27421 	 */
27422 	ASSERT(err != EINPROGRESS);
27423 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
27424 }
27425 
27426 /* Allocate the private structure */
27427 static int
27428 ip_priv_alloc(void **bufp)
27429 {
27430 	void	*buf;
27431 
27432 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
27433 		return (ENOMEM);
27434 
27435 	*bufp = buf;
27436 	return (0);
27437 }
27438 
27439 /* Function to delete the private structure */
27440 void
27441 ip_priv_free(void *buf)
27442 {
27443 	ASSERT(buf != NULL);
27444 	kmem_free(buf, sizeof (ip_priv_t));
27445 }
27446 
27447 /*
27448  * The entry point for IPPF processing.
27449  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
27450  * routine just returns.
27451  *
27452  * When called, ip_process generates an ipp_packet_t structure
27453  * which holds the state information for this packet and invokes the
27454  * the classifier (via ipp_packet_process). The classification, depending on
27455  * configured filters, results in a list of actions for this packet. Invoking
27456  * an action may cause the packet to be dropped, in which case the resulting
27457  * mblk (*mpp) is NULL. proc indicates the callout position for
27458  * this packet and ill_index is the interface this packet on or will leave
27459  * on (inbound and outbound resp.).
27460  */
27461 void
27462 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
27463 {
27464 	mblk_t		*mp;
27465 	ip_priv_t	*priv;
27466 	ipp_action_id_t	aid;
27467 	int		rc = 0;
27468 	ipp_packet_t	*pp;
27469 #define	IP_CLASS	"ip"
27470 
27471 	/* If the classifier is not loaded, return  */
27472 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
27473 		return;
27474 	}
27475 
27476 	mp = *mpp;
27477 	ASSERT(mp != NULL);
27478 
27479 	/* Allocate the packet structure */
27480 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
27481 	if (rc != 0) {
27482 		*mpp = NULL;
27483 		freemsg(mp);
27484 		return;
27485 	}
27486 
27487 	/* Allocate the private structure */
27488 	rc = ip_priv_alloc((void **)&priv);
27489 	if (rc != 0) {
27490 		*mpp = NULL;
27491 		freemsg(mp);
27492 		ipp_packet_free(pp);
27493 		return;
27494 	}
27495 	priv->proc = proc;
27496 	priv->ill_index = ill_index;
27497 	ipp_packet_set_private(pp, priv, ip_priv_free);
27498 	ipp_packet_set_data(pp, mp);
27499 
27500 	/* Invoke the classifier */
27501 	rc = ipp_packet_process(&pp);
27502 	if (pp != NULL) {
27503 		mp = ipp_packet_get_data(pp);
27504 		ipp_packet_free(pp);
27505 		if (rc != 0) {
27506 			freemsg(mp);
27507 			*mpp = NULL;
27508 		}
27509 	} else {
27510 		*mpp = NULL;
27511 	}
27512 #undef	IP_CLASS
27513 }
27514 
27515 /*
27516  * Propagate a multicast group membership operation (add/drop) on
27517  * all the interfaces crossed by the related multirt routes.
27518  * The call is considered successful if the operation succeeds
27519  * on at least one interface.
27520  */
27521 static int
27522 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
27523     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
27524     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
27525     mblk_t *first_mp)
27526 {
27527 	ire_t		*ire_gw;
27528 	irb_t		*irb;
27529 	int		error = 0;
27530 	opt_restart_t	*or;
27531 
27532 	irb = ire->ire_bucket;
27533 	ASSERT(irb != NULL);
27534 
27535 	ASSERT(DB_TYPE(first_mp) == M_CTL);
27536 
27537 	or = (opt_restart_t *)first_mp->b_rptr;
27538 	IRB_REFHOLD(irb);
27539 	for (; ire != NULL; ire = ire->ire_next) {
27540 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
27541 			continue;
27542 		if (ire->ire_addr != group)
27543 			continue;
27544 
27545 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
27546 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
27547 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
27548 		/* No resolver exists for the gateway; skip this ire. */
27549 		if (ire_gw == NULL)
27550 			continue;
27551 
27552 		/*
27553 		 * This function can return EINPROGRESS. If so the operation
27554 		 * will be restarted from ip_restart_optmgmt which will
27555 		 * call ip_opt_set and option processing will restart for
27556 		 * this option. So we may end up calling 'fn' more than once.
27557 		 * This requires that 'fn' is idempotent except for the
27558 		 * return value. The operation is considered a success if
27559 		 * it succeeds at least once on any one interface.
27560 		 */
27561 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
27562 		    NULL, fmode, src, first_mp);
27563 		if (error == 0)
27564 			or->or_private = CGTP_MCAST_SUCCESS;
27565 
27566 		if (ip_debug > 0) {
27567 			ulong_t	off;
27568 			char	*ksym;
27569 			ksym = kobj_getsymname((uintptr_t)fn, &off);
27570 			ip2dbg(("ip_multirt_apply_membership: "
27571 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
27572 			    "error %d [success %u]\n",
27573 			    ksym ? ksym : "?",
27574 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
27575 			    error, or->or_private));
27576 		}
27577 
27578 		ire_refrele(ire_gw);
27579 		if (error == EINPROGRESS) {
27580 			IRB_REFRELE(irb);
27581 			return (error);
27582 		}
27583 	}
27584 	IRB_REFRELE(irb);
27585 	/*
27586 	 * Consider the call as successful if we succeeded on at least
27587 	 * one interface. Otherwise, return the last encountered error.
27588 	 */
27589 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
27590 }
27591 
27592 
27593 /*
27594  * Issue a warning regarding a route crossing an interface with an
27595  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
27596  * amount of time is logged.
27597  */
27598 static void
27599 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
27600 {
27601 	hrtime_t	current = gethrtime();
27602 	char		buf[INET_ADDRSTRLEN];
27603 
27604 	/* Convert interval in ms to hrtime in ns */
27605 	if (multirt_bad_mtu_last_time +
27606 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
27607 	    current) {
27608 		cmn_err(CE_WARN, "ip: ignoring multiroute "
27609 		    "to %s, incorrect MTU %u (expected %u)\n",
27610 		    ip_dot_addr(ire->ire_addr, buf),
27611 		    ire->ire_max_frag, max_frag);
27612 
27613 		multirt_bad_mtu_last_time = current;
27614 	}
27615 }
27616 
27617 
27618 /*
27619  * Get the CGTP (multirouting) filtering status.
27620  * If 0, the CGTP hooks are transparent.
27621  */
27622 /* ARGSUSED */
27623 static int
27624 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
27625 {
27626 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
27627 
27628 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
27629 	return (0);
27630 }
27631 
27632 
27633 /*
27634  * Set the CGTP (multirouting) filtering status.
27635  * If the status is changed from active to transparent
27636  * or from transparent to active, forward the new status
27637  * to the filtering module (if loaded).
27638  */
27639 /* ARGSUSED */
27640 static int
27641 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
27642     cred_t *ioc_cr)
27643 {
27644 	long		new_value;
27645 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
27646 
27647 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
27648 	    new_value < 0 || new_value > 1) {
27649 		return (EINVAL);
27650 	}
27651 
27652 	/*
27653 	 * Do not enable CGTP filtering - thus preventing the hooks
27654 	 * from being invoked - if the version number of the
27655 	 * filtering module hooks does not match.
27656 	 */
27657 	if ((ip_cgtp_filter_ops != NULL) &&
27658 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
27659 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
27660 		    "(module hooks version %d, expecting %d)\n",
27661 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
27662 		return (ENOTSUP);
27663 	}
27664 
27665 	if ((!*ip_cgtp_filter_value) && new_value) {
27666 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
27667 		    ip_cgtp_filter_ops == NULL ?
27668 		    " (module not loaded)" : "");
27669 	}
27670 	if (*ip_cgtp_filter_value && (!new_value)) {
27671 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
27672 		    ip_cgtp_filter_ops == NULL ?
27673 		    " (module not loaded)" : "");
27674 	}
27675 
27676 	if (ip_cgtp_filter_ops != NULL) {
27677 		int	res;
27678 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
27679 			return (res);
27680 		}
27681 	}
27682 
27683 	*ip_cgtp_filter_value = (boolean_t)new_value;
27684 
27685 	return (0);
27686 }
27687 
27688 
27689 /*
27690  * Return the expected CGTP hooks version number.
27691  */
27692 int
27693 ip_cgtp_filter_supported(void)
27694 {
27695 	return (ip_cgtp_filter_rev);
27696 }
27697 
27698 
27699 /*
27700  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
27701  * or by invoking this function. In the first case, the version number
27702  * of the registered structure is checked at hooks activation time
27703  * in ip_cgtp_filter_set().
27704  */
27705 int
27706 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
27707 {
27708 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
27709 		return (ENOTSUP);
27710 
27711 	ip_cgtp_filter_ops = ops;
27712 	return (0);
27713 }
27714 
27715 static squeue_func_t
27716 ip_squeue_switch(int val)
27717 {
27718 	squeue_func_t rval = squeue_fill;
27719 
27720 	switch (val) {
27721 	case IP_SQUEUE_ENTER_NODRAIN:
27722 		rval = squeue_enter_nodrain;
27723 		break;
27724 	case IP_SQUEUE_ENTER:
27725 		rval = squeue_enter;
27726 		break;
27727 	default:
27728 		break;
27729 	}
27730 	return (rval);
27731 }
27732 
27733 /* ARGSUSED */
27734 static int
27735 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
27736     caddr_t addr, cred_t *cr)
27737 {
27738 	int *v = (int *)addr;
27739 	long new_value;
27740 
27741 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
27742 		return (EINVAL);
27743 
27744 	ip_input_proc = ip_squeue_switch(new_value);
27745 	*v = new_value;
27746 	return (0);
27747 }
27748 
27749 /* ARGSUSED */
27750 static int
27751 ip_int_set(queue_t *q, mblk_t *mp, char *value,
27752     caddr_t addr, cred_t *cr)
27753 {
27754 	int *v = (int *)addr;
27755 	long new_value;
27756 
27757 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
27758 		return (EINVAL);
27759 
27760 	*v = new_value;
27761 	return (0);
27762 }
27763 
27764 static void
27765 ip_kstat_init(void)
27766 {
27767 	ip_named_kstat_t template = {
27768 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
27769 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
27770 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
27771 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
27772 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
27773 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
27774 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
27775 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
27776 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
27777 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
27778 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
27779 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
27780 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
27781 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
27782 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
27783 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
27784 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
27785 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
27786 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
27787 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
27788 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
27789 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
27790 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
27791 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
27792 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
27793 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
27794 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
27795 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
27796 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
27797 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
27798 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
27799 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
27800 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
27801 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
27802 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
27803 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
27804 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
27805 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
27806 	};
27807 
27808 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
27809 					NUM_OF_FIELDS(ip_named_kstat_t),
27810 					0);
27811 	if (!ip_mibkp)
27812 		return;
27813 
27814 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
27815 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
27816 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
27817 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
27818 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
27819 
27820 	template.netToMediaEntrySize.value.i32 =
27821 		sizeof (mib2_ipNetToMediaEntry_t);
27822 
27823 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
27824 
27825 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
27826 
27827 	ip_mibkp->ks_update = ip_kstat_update;
27828 
27829 	kstat_install(ip_mibkp);
27830 }
27831 
27832 static void
27833 ip_kstat_fini(void)
27834 {
27835 
27836 	if (ip_mibkp != NULL) {
27837 		kstat_delete(ip_mibkp);
27838 		ip_mibkp = NULL;
27839 	}
27840 }
27841 
27842 static int
27843 ip_kstat_update(kstat_t *kp, int rw)
27844 {
27845 	ip_named_kstat_t *ipkp;
27846 
27847 	if (!kp || !kp->ks_data)
27848 		return (EIO);
27849 
27850 	if (rw == KSTAT_WRITE)
27851 		return (EACCES);
27852 
27853 	ipkp = (ip_named_kstat_t *)kp->ks_data;
27854 
27855 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
27856 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
27857 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
27858 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
27859 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
27860 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
27861 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
27862 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
27863 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
27864 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
27865 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
27866 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
27867 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
27868 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
27869 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
27870 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
27871 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
27872 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
27873 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
27874 
27875 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
27876 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
27877 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
27878 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
27879 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
27880 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
27881 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
27882 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
27883 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
27884 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
27885 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
27886 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
27887 
27888 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
27889 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
27890 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
27891 
27892 	return (0);
27893 }
27894 
27895 static void
27896 icmp_kstat_init(void)
27897 {
27898 	icmp_named_kstat_t template = {
27899 		{ "inMsgs",		KSTAT_DATA_UINT32 },
27900 		{ "inErrors",		KSTAT_DATA_UINT32 },
27901 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
27902 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
27903 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
27904 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
27905 		{ "inRedirects",	KSTAT_DATA_UINT32 },
27906 		{ "inEchos",		KSTAT_DATA_UINT32 },
27907 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
27908 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
27909 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
27910 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
27911 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
27912 		{ "outMsgs",		KSTAT_DATA_UINT32 },
27913 		{ "outErrors",		KSTAT_DATA_UINT32 },
27914 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
27915 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
27916 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
27917 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
27918 		{ "outRedirects",	KSTAT_DATA_UINT32 },
27919 		{ "outEchos",		KSTAT_DATA_UINT32 },
27920 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
27921 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
27922 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
27923 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
27924 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
27925 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
27926 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
27927 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
27928 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
27929 		{ "outDrops",		KSTAT_DATA_UINT32 },
27930 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
27931 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
27932 	};
27933 
27934 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
27935 					NUM_OF_FIELDS(icmp_named_kstat_t),
27936 					0);
27937 	if (icmp_mibkp == NULL)
27938 		return;
27939 
27940 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
27941 
27942 	icmp_mibkp->ks_update = icmp_kstat_update;
27943 
27944 	kstat_install(icmp_mibkp);
27945 }
27946 
27947 static void
27948 icmp_kstat_fini(void)
27949 {
27950 
27951 	if (icmp_mibkp != NULL) {
27952 		kstat_delete(icmp_mibkp);
27953 		icmp_mibkp = NULL;
27954 	}
27955 }
27956 
27957 static int
27958 icmp_kstat_update(kstat_t *kp, int rw)
27959 {
27960 	icmp_named_kstat_t *icmpkp;
27961 
27962 	if ((kp == NULL) || (kp->ks_data == NULL))
27963 		return (EIO);
27964 
27965 	if (rw == KSTAT_WRITE)
27966 		return (EACCES);
27967 
27968 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
27969 
27970 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
27971 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
27972 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
27973 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
27974 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
27975 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
27976 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
27977 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
27978 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
27979 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
27980 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
27981 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
27982 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
27983 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
27984 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
27985 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
27986 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
27987 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
27988 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
27989 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
27990 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
27991 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
27992 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
27993 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
27994 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
27995 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
27996 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
27997 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
27998 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
27999 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
28000 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
28001 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
28002 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
28003 
28004 	return (0);
28005 }
28006 
28007 /*
28008  * This is the fanout function for raw socket opened for SCTP.  Note
28009  * that it is called after SCTP checks that there is no socket which
28010  * wants a packet.  Then before SCTP handles this out of the blue packet,
28011  * this function is called to see if there is any raw socket for SCTP.
28012  * If there is and it is bound to the correct address, the packet will
28013  * be sent to that socket.  Note that only one raw socket can be bound to
28014  * a port.  This is assured in ipcl_sctp_hash_insert();
28015  */
28016 void
28017 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
28018     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
28019     uint_t ipif_seqid, zoneid_t zoneid)
28020 {
28021 	conn_t		*connp;
28022 	queue_t		*rq;
28023 	mblk_t		*first_mp;
28024 	boolean_t	secure;
28025 	ip6_t		*ip6h;
28026 
28027 	first_mp = mp;
28028 	if (mctl_present) {
28029 		mp = first_mp->b_cont;
28030 		secure = ipsec_in_is_secure(first_mp);
28031 		ASSERT(mp != NULL);
28032 	} else {
28033 		secure = B_FALSE;
28034 	}
28035 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
28036 
28037 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
28038 	if (connp == NULL) {
28039 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
28040 		    mctl_present);
28041 		return;
28042 	}
28043 	rq = connp->conn_rq;
28044 	if (!canputnext(rq)) {
28045 		CONN_DEC_REF(connp);
28046 		BUMP_MIB(&ip_mib, rawipInOverflows);
28047 		freemsg(first_mp);
28048 		return;
28049 	}
28050 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
28051 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
28052 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
28053 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
28054 		if (first_mp == NULL) {
28055 			CONN_DEC_REF(connp);
28056 			return;
28057 		}
28058 	}
28059 	/*
28060 	 * We probably should not send M_CTL message up to
28061 	 * raw socket.
28062 	 */
28063 	if (mctl_present)
28064 		freeb(first_mp);
28065 
28066 	/* Initiate IPPF processing here if needed. */
28067 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
28068 	    (!isv4 && IP6_IN_IPP(flags))) {
28069 		ip_process(IPP_LOCAL_IN, &mp,
28070 		    recv_ill->ill_phyint->phyint_ifindex);
28071 		if (mp == NULL) {
28072 			CONN_DEC_REF(connp);
28073 			return;
28074 		}
28075 	}
28076 
28077 	if (connp->conn_recvif || connp->conn_recvslla ||
28078 	    ((connp->conn_ipv6_recvpktinfo ||
28079 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
28080 	    (flags & IP_FF_IP6INFO))) {
28081 		int in_flags = 0;
28082 
28083 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
28084 			in_flags = IPF_RECVIF;
28085 		}
28086 		if (connp->conn_recvslla) {
28087 			in_flags |= IPF_RECVSLLA;
28088 		}
28089 		if (isv4) {
28090 			mp = ip_add_info(mp, recv_ill, in_flags);
28091 		} else {
28092 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
28093 			if (mp == NULL) {
28094 				CONN_DEC_REF(connp);
28095 				return;
28096 			}
28097 		}
28098 	}
28099 
28100 	BUMP_MIB(&ip_mib, ipInDelivers);
28101 	/*
28102 	 * We are sending the IPSEC_IN message also up. Refer
28103 	 * to comments above this function.
28104 	 */
28105 	putnext(rq, mp);
28106 	CONN_DEC_REF(connp);
28107 }
28108 
28109 /*
28110  * This function should be called only if all packet processing
28111  * including fragmentation is complete. Callers of this function
28112  * must set mp->b_prev to one of these values:
28113  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
28114  * prior to handing over the mp as first argument to this function.
28115  *
28116  * If the ire passed by caller is incomplete, this function
28117  * queues the packet and if necessary, sends ARP request and bails.
28118  * If the ire passed is fully resolved, we simply prepend
28119  * the link-layer header to the packet, do ipsec hw acceleration
28120  * work if necessary, and send the packet out on the wire.
28121  *
28122  * NOTE: IPSEC will only call this function with fully resolved
28123  * ires if hw acceleration is involved.
28124  * TODO list :
28125  * 	a Handle M_MULTIDATA so that
28126  *	  tcp_multisend->tcp_multisend_data can
28127  *	  call ip_xmit_v4 directly
28128  *	b Handle post-ARP work for fragments so that
28129  *	  ip_wput_frag can call this function.
28130  */
28131 ipxmit_state_t
28132 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
28133 {
28134 	nce_t		*arpce;
28135 	queue_t		*q;
28136 	int		ill_index;
28137 	mblk_t		*nxt_mp;
28138 	boolean_t	xmit_drop = B_FALSE;
28139 	ip_proc_t	proc;
28140 
28141 	arpce = ire->ire_nce;
28142 	ASSERT(arpce != NULL);
28143 
28144 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
28145 
28146 	mutex_enter(&arpce->nce_lock);
28147 	switch (arpce->nce_state) {
28148 	case ND_REACHABLE:
28149 		/* If there are other queued packets, queue this packet */
28150 		if (arpce->nce_qd_mp != NULL) {
28151 			if (mp != NULL)
28152 				nce_queue_mp_common(arpce, mp, B_FALSE);
28153 			mp = arpce->nce_qd_mp;
28154 		}
28155 		arpce->nce_qd_mp = NULL;
28156 		mutex_exit(&arpce->nce_lock);
28157 
28158 		/*
28159 		 * Flush the queue.  In the common case, where the
28160 		 * ARP is already resolved,  it will go through the
28161 		 * while loop only once.
28162 		 */
28163 		while (mp != NULL) {
28164 
28165 			nxt_mp = mp->b_next;
28166 			mp->b_next = NULL;
28167 			/*
28168 			 * This info is needed for IPQOS to do COS marking
28169 			 * in ip_wput_attach_llhdr->ip_process.
28170 			 */
28171 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
28172 			mp->b_prev = NULL;
28173 
28174 			/* set up ill index for outbound qos processing */
28175 			ill_index =
28176 			    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
28177 			mp = ip_wput_attach_llhdr(mp, ire, proc, ill_index);
28178 			if (mp == NULL) {
28179 				xmit_drop = B_TRUE;
28180 				if (proc == IPP_FWD_OUT) {
28181 					BUMP_MIB(&ip_mib, ipInDiscards);
28182 				} else {
28183 					BUMP_MIB(&ip_mib, ipOutDiscards);
28184 				}
28185 				goto next_mp;
28186 			}
28187 			/* non-ipsec hw accel case */
28188 			if (io == NULL || !io->ipsec_out_accelerated) {
28189 				/* send it */
28190 				q = ire->ire_stq;
28191 				if (proc == IPP_FWD_OUT) {
28192 					UPDATE_IB_PKT_COUNT(ire);
28193 				} else {
28194 					UPDATE_OB_PKT_COUNT(ire);
28195 				}
28196 				ire->ire_last_used_time = lbolt;
28197 
28198 				if (flow_ctl_enabled) {
28199 					/*
28200 					 * We are here from ip_wout_ire
28201 					 * which has already done canput
28202 					 * check and has enabled flow
28203 					 * control, so skip the canputnext
28204 					 * check.
28205 					 */
28206 					putnext(q, mp);
28207 					goto next_mp;
28208 				}
28209 				if (canputnext(q))  {
28210 					if (proc == IPP_FWD_OUT) {
28211 						BUMP_MIB(&ip_mib,
28212 						    ipForwDatagrams);
28213 					}
28214 					putnext(q, mp);
28215 				} else {
28216 					BUMP_MIB(&ip_mib,
28217 					    ipOutDiscards);
28218 					xmit_drop = B_TRUE;
28219 					freemsg(mp);
28220 				}
28221 			} else {
28222 				/*
28223 				 * Safety Pup says: make sure this
28224 				 *  is going to the right interface!
28225 				 */
28226 				ill_t *ill1 =
28227 				    (ill_t *)ire->ire_stq->q_ptr;
28228 				int ifindex =
28229 				    ill1->ill_phyint->phyint_ifindex;
28230 				if (ifindex !=
28231 				    io->ipsec_out_capab_ill_index) {
28232 					xmit_drop = B_TRUE;
28233 					freemsg(mp);
28234 				} else {
28235 					ipsec_hw_putnext(ire->ire_stq,
28236 					    mp);
28237 				}
28238 			}
28239 next_mp:
28240 			mp = nxt_mp;
28241 		} /* while (mp != NULL) */
28242 		if (xmit_drop)
28243 			return (SEND_FAILED);
28244 		else
28245 			return (SEND_PASSED);
28246 
28247 	case ND_INITIAL:
28248 	case ND_INCOMPLETE:
28249 
28250 		/*
28251 		 * While we do send off packets to dests that
28252 		 * use fully-resolved CGTP routes, we do not
28253 		 * handle unresolved CGTP routes.
28254 		 */
28255 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
28256 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
28257 
28258 		if (mp != NULL) {
28259 			/* queue the packet */
28260 			nce_queue_mp_common(arpce, mp, B_FALSE);
28261 		}
28262 
28263 		if (arpce->nce_state == ND_INCOMPLETE) {
28264 			mutex_exit(&arpce->nce_lock);
28265 			DTRACE_PROBE3(ip__xmit__incomplete,
28266 			    (ire_t *), ire, (mblk_t *), mp,
28267 			    (ipsec_out_t *), io);
28268 			return (LOOKUP_IN_PROGRESS);
28269 		}
28270 
28271 		arpce->nce_state = ND_INCOMPLETE;
28272 		mutex_exit(&arpce->nce_lock);
28273 		/*
28274 		 * Note that ire_add() (called from ire_forward())
28275 		 * holds a ref on the ire until ARP is completed.
28276 		 */
28277 
28278 		ire_arpresolve(ire, ire->ire_ipif->ipif_ill);
28279 		return (LOOKUP_IN_PROGRESS);
28280 	default:
28281 		ASSERT(0);
28282 		mutex_exit(&arpce->nce_lock);
28283 		return (LLHDR_RESLV_FAILED);
28284 	}
28285 }
28286 
28287 /*
28288  * Return B_TRUE if the buffers differ in length or content.
28289  * This is used for comparing extension header buffers.
28290  * Note that an extension header would be declared different
28291  * even if all that changed was the next header value in that header i.e.
28292  * what really changed is the next extension header.
28293  */
28294 boolean_t
28295 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
28296     uint_t blen)
28297 {
28298 	if (!b_valid)
28299 		blen = 0;
28300 
28301 	if (alen != blen)
28302 		return (B_TRUE);
28303 	if (alen == 0)
28304 		return (B_FALSE);	/* Both zero length */
28305 	return (bcmp(abuf, bbuf, alen));
28306 }
28307 
28308 /*
28309  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
28310  * Return B_FALSE if memory allocation fails - don't change any state!
28311  */
28312 boolean_t
28313 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28314     const void *src, uint_t srclen)
28315 {
28316 	void *dst;
28317 
28318 	if (!src_valid)
28319 		srclen = 0;
28320 
28321 	ASSERT(*dstlenp == 0);
28322 	if (src != NULL && srclen != 0) {
28323 		dst = mi_alloc(srclen, BPRI_MED);
28324 		if (dst == NULL)
28325 			return (B_FALSE);
28326 	} else {
28327 		dst = NULL;
28328 	}
28329 	if (*dstp != NULL)
28330 		mi_free(*dstp);
28331 	*dstp = dst;
28332 	*dstlenp = dst == NULL ? 0 : srclen;
28333 	return (B_TRUE);
28334 }
28335 
28336 /*
28337  * Replace what is in *dst, *dstlen with the source.
28338  * Assumes ip_allocbuf has already been called.
28339  */
28340 void
28341 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28342     const void *src, uint_t srclen)
28343 {
28344 	if (!src_valid)
28345 		srclen = 0;
28346 
28347 	ASSERT(*dstlenp == srclen);
28348 	if (src != NULL && srclen != 0)
28349 		bcopy(src, *dstp, srclen);
28350 }
28351 
28352 /*
28353  * Free the storage pointed to by the members of an ip6_pkt_t.
28354  */
28355 void
28356 ip6_pkt_free(ip6_pkt_t *ipp)
28357 {
28358 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
28359 
28360 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
28361 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
28362 		ipp->ipp_hopopts = NULL;
28363 		ipp->ipp_hopoptslen = 0;
28364 	}
28365 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
28366 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
28367 		ipp->ipp_rtdstopts = NULL;
28368 		ipp->ipp_rtdstoptslen = 0;
28369 	}
28370 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
28371 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
28372 		ipp->ipp_dstopts = NULL;
28373 		ipp->ipp_dstoptslen = 0;
28374 	}
28375 	if (ipp->ipp_fields & IPPF_RTHDR) {
28376 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
28377 		ipp->ipp_rthdr = NULL;
28378 		ipp->ipp_rthdrlen = 0;
28379 	}
28380 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
28381 	    IPPF_RTHDR);
28382 }
28383