xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision d51e90740114c60620c0febffd4d3ce6e280a107)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /* Copyright (c) 1990 Mentat Inc. */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/stream.h>
31 #include <sys/dlpi.h>
32 #include <sys/stropts.h>
33 #include <sys/sysmacros.h>
34 #include <sys/strsubr.h>
35 #include <sys/strlog.h>
36 #include <sys/strsun.h>
37 #include <sys/zone.h>
38 #define	_SUN_TPI_VERSION 2
39 #include <sys/tihdr.h>
40 #include <sys/xti_inet.h>
41 #include <sys/ddi.h>
42 #include <sys/sunddi.h>
43 #include <sys/cmn_err.h>
44 #include <sys/debug.h>
45 #include <sys/kobj.h>
46 #include <sys/modctl.h>
47 #include <sys/atomic.h>
48 #include <sys/policy.h>
49 #include <sys/priv.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/sdt.h>
55 #include <sys/socket.h>
56 #include <sys/vtrace.h>
57 #include <sys/isa_defs.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/kstatcom.h>
72 
73 #include <netinet/igmp_var.h>
74 #include <netinet/ip6.h>
75 #include <netinet/icmp6.h>
76 #include <netinet/sctp.h>
77 
78 #include <inet/ip.h>
79 #include <inet/ip_impl.h>
80 #include <inet/ip6.h>
81 #include <inet/ip6_asp.h>
82 #include <inet/tcp.h>
83 #include <inet/tcp_impl.h>
84 #include <inet/ip_multi.h>
85 #include <inet/ip_if.h>
86 #include <inet/ip_ire.h>
87 #include <inet/ip_ftable.h>
88 #include <inet/ip_rts.h>
89 #include <inet/optcom.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <sys/sunddi.h>
121 
122 #include <sys/tsol/label.h>
123 #include <sys/tsol/tnet.h>
124 
125 #include <rpc/pmap_prot.h>
126 
127 /*
128  * Values for squeue switch:
129  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
130  * IP_SQUEUE_ENTER: squeue_enter
131  * IP_SQUEUE_FILL: squeue_fill
132  */
133 int ip_squeue_enter = 2;
134 squeue_func_t ip_input_proc;
135 /*
136  * IP statistics.
137  */
138 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
139 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
140 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
141 
142 typedef struct ip_stat {
143 	kstat_named_t	ipsec_fanout_proto;
144 	kstat_named_t	ip_udp_fannorm;
145 	kstat_named_t	ip_udp_fanmb;
146 	kstat_named_t	ip_udp_fanothers;
147 	kstat_named_t	ip_udp_fast_path;
148 	kstat_named_t	ip_udp_slow_path;
149 	kstat_named_t	ip_udp_input_err;
150 	kstat_named_t	ip_tcppullup;
151 	kstat_named_t	ip_tcpoptions;
152 	kstat_named_t	ip_multipkttcp;
153 	kstat_named_t	ip_tcp_fast_path;
154 	kstat_named_t	ip_tcp_slow_path;
155 	kstat_named_t	ip_tcp_input_error;
156 	kstat_named_t	ip_db_ref;
157 	kstat_named_t	ip_notaligned1;
158 	kstat_named_t	ip_notaligned2;
159 	kstat_named_t	ip_multimblk3;
160 	kstat_named_t	ip_multimblk4;
161 	kstat_named_t	ip_ipoptions;
162 	kstat_named_t	ip_classify_fail;
163 	kstat_named_t	ip_opt;
164 	kstat_named_t	ip_udp_rput_local;
165 	kstat_named_t	ipsec_proto_ahesp;
166 	kstat_named_t	ip_conn_flputbq;
167 	kstat_named_t	ip_conn_walk_drain;
168 	kstat_named_t   ip_out_sw_cksum;
169 	kstat_named_t   ip_in_sw_cksum;
170 	kstat_named_t   ip_trash_ire_reclaim_calls;
171 	kstat_named_t   ip_trash_ire_reclaim_success;
172 	kstat_named_t   ip_ire_arp_timer_expired;
173 	kstat_named_t   ip_ire_redirect_timer_expired;
174 	kstat_named_t	ip_ire_pmtu_timer_expired;
175 	kstat_named_t	ip_input_multi_squeue;
176 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
177 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
178 	kstat_named_t	ip_tcp_in_sw_cksum_err;
179 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
180 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
181 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
182 	kstat_named_t	ip_udp_in_sw_cksum_err;
183 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
184 	kstat_named_t	ip_frag_mdt_pkt_out;
185 	kstat_named_t	ip_frag_mdt_discarded;
186 	kstat_named_t	ip_frag_mdt_allocfail;
187 	kstat_named_t	ip_frag_mdt_addpdescfail;
188 	kstat_named_t	ip_frag_mdt_allocd;
189 } ip_stat_t;
190 
191 static ip_stat_t ip_statistics = {
192 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
193 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
194 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
195 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
196 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
197 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
198 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
199 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
200 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
201 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
202 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
203 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
204 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
205 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
206 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
207 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
208 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
209 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
210 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
211 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
212 	{ "ip_opt",				KSTAT_DATA_UINT64 },
213 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
214 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
215 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
216 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
217 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
218 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
219 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
220 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
221 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
222 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
223 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
224 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
225 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
226 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
227 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
228 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
229 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
230 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
231 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
232 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
233 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
234 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
235 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
236 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
237 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
238 };
239 
240 static kstat_t *ip_kstat;
241 
242 #define	TCP6 "tcp6"
243 #define	TCP "tcp"
244 #define	SCTP "sctp"
245 #define	SCTP6 "sctp6"
246 
247 major_t TCP6_MAJ;
248 major_t TCP_MAJ;
249 major_t SCTP_MAJ;
250 major_t SCTP6_MAJ;
251 
252 int ip_poll_normal_ms = 100;
253 int ip_poll_normal_ticks = 0;
254 int ip_modclose_ackwait_ms = 3000;
255 
256 /*
257  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
258  */
259 
260 struct listptr_s {
261 	mblk_t	*lp_head;	/* pointer to the head of the list */
262 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
263 };
264 
265 typedef struct listptr_s listptr_t;
266 
267 /*
268  * This is used by ip_snmp_get_mib2_ip_route_media and
269  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
270  */
271 typedef struct iproutedata_s {
272 	uint_t		ird_idx;
273 	listptr_t	ird_route;	/* ipRouteEntryTable */
274 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
275 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
276 } iproutedata_t;
277 
278 /*
279  * Cluster specific hooks. These should be NULL when booted as a non-cluster
280  */
281 
282 /*
283  * Hook functions to enable cluster networking
284  * On non-clustered systems these vectors must always be NULL.
285  *
286  * Hook function to Check ip specified ip address is a shared ip address
287  * in the cluster
288  *
289  */
290 int (*cl_inet_isclusterwide)(uint8_t protocol,
291     sa_family_t addr_family, uint8_t *laddrp) = NULL;
292 
293 /*
294  * Hook function to generate cluster wide ip fragment identifier
295  */
296 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
297     uint8_t *laddrp, uint8_t *faddrp) = NULL;
298 
299 /*
300  * Synchronization notes:
301  *
302  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
303  * MT level protection given by STREAMS. IP uses a combination of its own
304  * internal serialization mechanism and standard Solaris locking techniques.
305  * The internal serialization is per phyint (no IPMP) or per IPMP group.
306  * This is used to serialize plumbing operations, IPMP operations, certain
307  * multicast operations, most set ioctls, igmp/mld timers etc.
308  *
309  * Plumbing is a long sequence of operations involving message
310  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
311  * involved in plumbing operations. A natural model is to serialize these
312  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
313  * parallel without any interference. But various set ioctls on hme0 are best
314  * serialized. However if the system uses IPMP, the operations are easier if
315  * they are serialized on a per IPMP group basis since IPMP operations
316  * happen across ill's of a group. Thus the lowest common denominator is to
317  * serialize most set ioctls, multicast join/leave operations, IPMP operations
318  * igmp/mld timer operations, and processing of DLPI control messages received
319  * from drivers on a per IPMP group basis. If the system does not employ
320  * IPMP the serialization is on a per phyint basis. This serialization is
321  * provided by the ipsq_t and primitives operating on this. Details can
322  * be found in ip_if.c above the core primitives operating on ipsq_t.
323  *
324  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
325  * Simiarly lookup of an ire by a thread also returns a refheld ire.
326  * In addition ipif's and ill's referenced by the ire are also indirectly
327  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
328  * the ipif's address or netmask change as long as an ipif is refheld
329  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
330  * address of an ipif has to go through the ipsq_t. This ensures that only
331  * 1 such exclusive operation proceeds at any time on the ipif. It then
332  * deletes all ires associated with this ipif, and waits for all refcnts
333  * associated with this ipif to come down to zero. The address is changed
334  * only after the ipif has been quiesced. Then the ipif is brought up again.
335  * More details are described above the comment in ip_sioctl_flags.
336  *
337  * Packet processing is based mostly on IREs and are fully multi-threaded
338  * using standard Solaris MT techniques.
339  *
340  * There are explicit locks in IP to handle:
341  * - The ip_g_head list maintained by mi_open_link() and friends.
342  *
343  * - The reassembly data structures (one lock per hash bucket)
344  *
345  * - conn_lock is meant to protect conn_t fields. The fields actually
346  *   protected by conn_lock are documented in the conn_t definition.
347  *
348  * - ire_lock to protect some of the fields of the ire, IRE tables
349  *   (one lock per hash bucket). Refer to ip_ire.c for details.
350  *
351  * - ndp_g_lock and nce_lock for protecting NCEs.
352  *
353  * - ill_lock protects fields of the ill and ipif. Details in ip.h
354  *
355  * - ill_g_lock: This is a global reader/writer lock. Protects the following
356  *	* The AVL tree based global multi list of all ills.
357  *	* The linked list of all ipifs of an ill
358  *	* The <ill-ipsq> mapping
359  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
360  *	* The illgroup list threaded by ill_group_next.
361  *	* <ill-phyint> association
362  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
363  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
364  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
365  *   will all have to hold the ill_g_lock as writer for the actual duration
366  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
367  *   may be found in the IPMP section.
368  *
369  * - ill_lock:  This is a per ill mutex.
370  *   It protects some members of the ill and is documented below.
371  *   It also protects the <ill-ipsq> mapping
372  *   It also protects the illgroup list threaded by ill_group_next.
373  *   It also protects the <ill-phyint> assoc.
374  *   It also protects the list of ipifs hanging off the ill.
375  *
376  * - ipsq_lock: This is a per ipsq_t mutex lock.
377  *   This protects all the other members of the ipsq struct except
378  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
379  *
380  * - illgrp_lock: This is a per ill_group mutex lock.
381  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
382  *   which dictates which is the next ill in an ill_group that is to be chosen
383  *   for sending outgoing packets, through creation of an IRE_CACHE that
384  *   references this ill.
385  *
386  * - phyint_lock: This is a per phyint mutex lock. Protects just the
387  *   phyint_flags
388  *
389  * - ip_g_nd_lock: This is a global reader/writer lock.
390  *   Any call to nd_load to load a new parameter to the ND table must hold the
391  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
392  *   as reader.
393  *
394  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
395  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
396  *   uniqueness check also done atomically.
397  *
398  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
399  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
400  *   as a writer when adding or deleting elements from these lists, and
401  *   as a reader when walking these lists to send a SADB update to the
402  *   IPsec capable ills.
403  *
404  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
405  *   group list linked by ill_usesrc_grp_next. It also protects the
406  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
407  *   group is being added or deleted.  This lock is taken as a reader when
408  *   walking the list/group(eg: to get the number of members in a usesrc group).
409  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
410  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
411  *   example, it is not necessary to take this lock in the initial portion
412  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
413  *   ip_sioctl_flags since the these operations are executed exclusively and
414  *   that ensures that the "usesrc group state" cannot change. The "usesrc
415  *   group state" change can happen only in the latter part of
416  *   ip_sioctl_slifusesrc and in ill_delete.
417  *
418  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
419  *
420  * To change the <ill-phyint> association, the ill_g_lock must be held
421  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
422  * must be held.
423  *
424  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
425  * and the ill_lock of the ill in question must be held.
426  *
427  * To change the <ill-illgroup> association the ill_g_lock must be held as
428  * writer and the ill_lock of the ill in question must be held.
429  *
430  * To add or delete an ipif from the list of ipifs hanging off the ill,
431  * ill_g_lock (writer) and ill_lock must be held and the thread must be
432  * a writer on the associated ipsq,.
433  *
434  * To add or delete an ill to the system, the ill_g_lock must be held as
435  * writer and the thread must be a writer on the associated ipsq.
436  *
437  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
438  * must be a writer on the associated ipsq.
439  *
440  * Lock hierarchy
441  *
442  * Some lock hierarchy scenarios are listed below.
443  *
444  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
445  * ill_g_lock -> illgrp_lock -> ill_lock
446  * ill_g_lock -> ill_lock(s) -> phyint_lock
447  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
448  * ill_g_lock -> ip_addr_avail_lock
449  * conn_lock -> irb_lock -> ill_lock -> ire_lock
450  * ill_g_lock -> ip_g_nd_lock
451  *
452  * When more than 1 ill lock is needed to be held, all ill lock addresses
453  * are sorted on address and locked starting from highest addressed lock
454  * downward.
455  *
456  * Mobile-IP scenarios
457  *
458  * irb_lock -> ill_lock -> ire_mrtun_lock
459  * irb_lock -> ill_lock -> ire_srcif_table_lock
460  *
461  * IPsec scenarios
462  *
463  * ipsa_lock -> ill_g_lock -> ill_lock
464  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
465  * ipsec_capab_ills_lock -> ipsa_lock
466  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
467  *
468  * Trusted Solaris scenarios
469  *
470  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
471  * igsa_lock -> gcdb_lock
472  * gcgrp_rwlock -> ire_lock
473  * gcgrp_rwlock -> gcdb_lock
474  *
475  *
476  * Routing/forwarding table locking notes:
477  *
478  * Lock acquisition order: Radix tree lock, irb_lock.
479  * Requirements:
480  * i.  Walker must not hold any locks during the walker callback.
481  * ii  Walker must not see a truncated tree during the walk because of any node
482  *     deletion.
483  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
484  *     in many places in the code to walk the irb list. Thus even if all the
485  *     ires in a bucket have been deleted, we still can't free the radix node
486  *     until the ires have actually been inactive'd (freed).
487  *
488  * Tree traversal - Need to hold the global tree lock in read mode.
489  * Before dropping the global tree lock, need to either increment the ire_refcnt
490  * to ensure that the radix node can't be deleted.
491  *
492  * Tree add - Need to hold the global tree lock in write mode to add a
493  * radix node. To prevent the node from being deleted, increment the
494  * irb_refcnt, after the node is added to the tree. The ire itself is
495  * added later while holding the irb_lock, but not the tree lock.
496  *
497  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
498  * All associated ires must be inactive (i.e. freed), and irb_refcnt
499  * must be zero.
500  *
501  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
502  * global tree lock (read mode) for traversal.
503  *
504  * IPSEC notes :
505  *
506  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
507  * in front of the actual packet. For outbound datagrams, the M_CTL
508  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
509  * information used by the IPSEC code for applying the right level of
510  * protection. The information initialized by IP in the ipsec_out_t
511  * is determined by the per-socket policy or global policy in the system.
512  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
513  * ipsec_info.h) which starts out with nothing in it. It gets filled
514  * with the right information if it goes through the AH/ESP code, which
515  * happens if the incoming packet is secure. The information initialized
516  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
517  * the policy requirements needed by per-socket policy or global policy
518  * is met or not.
519  *
520  * If there is both per-socket policy (set using setsockopt) and there
521  * is also global policy match for the 5 tuples of the socket,
522  * ipsec_override_policy() makes the decision of which one to use.
523  *
524  * For fully connected sockets i.e dst, src [addr, port] is known,
525  * conn_policy_cached is set indicating that policy has been cached.
526  * conn_in_enforce_policy may or may not be set depending on whether
527  * there is a global policy match or per-socket policy match.
528  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
529  * Once the right policy is set on the conn_t, policy cannot change for
530  * this socket. This makes life simpler for TCP (UDP ?) where
531  * re-transmissions go out with the same policy. For symmetry, policy
532  * is cached for fully connected UDP sockets also. Thus if policy is cached,
533  * it also implies that policy is latched i.e policy cannot change
534  * on these sockets. As we have the right policy on the conn, we don't
535  * have to lookup global policy for every outbound and inbound datagram
536  * and thus serving as an optimization. Note that a global policy change
537  * does not affect fully connected sockets if they have policy. If fully
538  * connected sockets did not have any policy associated with it, global
539  * policy change may affect them.
540  *
541  * IP Flow control notes:
542  *
543  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
544  * cannot be sent down to the driver by IP, because of a canput failure, IP
545  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
546  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
547  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
548  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
549  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
550  * the queued messages, and removes the conn from the drain list, if all
551  * messages were drained. It also qenables the next conn in the drain list to
552  * continue the drain process.
553  *
554  * In reality the drain list is not a single list, but a configurable number
555  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
556  * list. If the ip_wsrv of the next qenabled conn does not run, because the
557  * stream closes, ip_close takes responsibility to qenable the next conn in
558  * the drain list. The directly called ip_wput path always does a putq, if
559  * it cannot putnext. Thus synchronization problems are handled between
560  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
561  * functions that manipulate this drain list. Furthermore conn_drain_insert
562  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
563  * running on a queue at any time. conn_drain_tail can be simultaneously called
564  * from both ip_wsrv and ip_close.
565  *
566  * IPQOS notes:
567  *
568  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
569  * and IPQoS modules. IPPF includes hooks in IP at different control points
570  * (callout positions) which direct packets to IPQoS modules for policy
571  * processing. Policies, if present, are global.
572  *
573  * The callout positions are located in the following paths:
574  *		o local_in (packets destined for this host)
575  *		o local_out (packets orginating from this host )
576  *		o fwd_in  (packets forwarded by this m/c - inbound)
577  *		o fwd_out (packets forwarded by this m/c - outbound)
578  * Hooks at these callout points can be enabled/disabled using the ndd variable
579  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
580  * By default all the callout positions are enabled.
581  *
582  * Outbound (local_out)
583  * Hooks are placed in ip_wput_ire and ipsec_out_process.
584  *
585  * Inbound (local_in)
586  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
587  * TCP and UDP fanout routines.
588  *
589  * Forwarding (in and out)
590  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
591  *
592  * IP Policy Framework processing (IPPF processing)
593  * Policy processing for a packet is initiated by ip_process, which ascertains
594  * that the classifier (ipgpc) is loaded and configured, failing which the
595  * packet resumes normal processing in IP. If the clasifier is present, the
596  * packet is acted upon by one or more IPQoS modules (action instances), per
597  * filters configured in ipgpc and resumes normal IP processing thereafter.
598  * An action instance can drop a packet in course of its processing.
599  *
600  * A boolean variable, ip_policy, is used in all the fanout routines that can
601  * invoke ip_process for a packet. This variable indicates if the packet should
602  * to be sent for policy processing. The variable is set to B_TRUE by default,
603  * i.e. when the routines are invoked in the normal ip procesing path for a
604  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
605  * ip_policy is set to B_FALSE for all the routines called in these two
606  * functions because, in the former case,  we don't process loopback traffic
607  * currently while in the latter, the packets have already been processed in
608  * icmp_inbound.
609  *
610  * Zones notes:
611  *
612  * The partitioning rules for networking are as follows:
613  * 1) Packets coming from a zone must have a source address belonging to that
614  * zone.
615  * 2) Packets coming from a zone can only be sent on a physical interface on
616  * which the zone has an IP address.
617  * 3) Between two zones on the same machine, packet delivery is only allowed if
618  * there's a matching route for the destination and zone in the forwarding
619  * table.
620  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
621  * different zones can bind to the same port with the wildcard address
622  * (INADDR_ANY).
623  *
624  * The granularity of interface partitioning is at the logical interface level.
625  * Therefore, every zone has its own IP addresses, and incoming packets can be
626  * attributed to a zone unambiguously. A logical interface is placed into a zone
627  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
628  * structure. Rule (1) is implemented by modifying the source address selection
629  * algorithm so that the list of eligible addresses is filtered based on the
630  * sending process zone.
631  *
632  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
633  * across all zones, depending on their type. Here is the break-up:
634  *
635  * IRE type				Shared/exclusive
636  * --------				----------------
637  * IRE_BROADCAST			Exclusive
638  * IRE_DEFAULT (default routes)		Shared (*)
639  * IRE_LOCAL				Exclusive (x)
640  * IRE_LOOPBACK				Exclusive
641  * IRE_PREFIX (net routes)		Shared (*)
642  * IRE_CACHE				Exclusive
643  * IRE_IF_NORESOLVER (interface routes)	Exclusive
644  * IRE_IF_RESOLVER (interface routes)	Exclusive
645  * IRE_HOST (host routes)		Shared (*)
646  *
647  * (*) A zone can only use a default or off-subnet route if the gateway is
648  * directly reachable from the zone, that is, if the gateway's address matches
649  * one of the zone's logical interfaces.
650  *
651  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
652  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
653  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
654  * address of the zone itself (the destination). Since IRE_LOCAL is used
655  * for communication between zones, ip_wput_ire has special logic to set
656  * the right source address when sending using an IRE_LOCAL.
657  *
658  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
659  * ire_cache_lookup restricts loopback using an IRE_LOCAL
660  * between zone to the case when L2 would have conceptually looped the packet
661  * back, i.e. the loopback which is required since neither Ethernet drivers
662  * nor Ethernet hardware loops them back. This is the case when the normal
663  * routes (ignoring IREs with different zoneids) would send out the packet on
664  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
665  * associated.
666  *
667  * Multiple zones can share a common broadcast address; typically all zones
668  * share the 255.255.255.255 address. Incoming as well as locally originated
669  * broadcast packets must be dispatched to all the zones on the broadcast
670  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
671  * since some zones may not be on the 10.16.72/24 network. To handle this, each
672  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
673  * sent to every zone that has an IRE_BROADCAST entry for the destination
674  * address on the input ill, see conn_wantpacket().
675  *
676  * Applications in different zones can join the same multicast group address.
677  * For IPv4, group memberships are per-logical interface, so they're already
678  * inherently part of a zone. For IPv6, group memberships are per-physical
679  * interface, so we distinguish IPv6 group memberships based on group address,
680  * interface and zoneid. In both cases, received multicast packets are sent to
681  * every zone for which a group membership entry exists. On IPv6 we need to
682  * check that the target zone still has an address on the receiving physical
683  * interface; it could have been removed since the application issued the
684  * IPV6_JOIN_GROUP.
685  */
686 
687 /*
688  * Squeue Fanout flags:
689  *	0: No fanout.
690  *	1: Fanout across all squeues
691  */
692 boolean_t	ip_squeue_fanout = 0;
693 
694 /*
695  * Maximum dups allowed per packet.
696  */
697 uint_t ip_max_frag_dups = 10;
698 
699 #define	IS_SIMPLE_IPH(ipha)						\
700 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
701 
702 /* RFC1122 Conformance */
703 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
704 
705 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
706 
707 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
708 
709 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
710 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
711 
712 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t);
713 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
714     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
715 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
716 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
717 		    mblk_t *, int);
718 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
719 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
720 		    ill_t *, zoneid_t);
721 static void	icmp_options_update(ipha_t *);
722 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t);
723 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
724 		    zoneid_t zoneid);
725 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
726 static void	icmp_redirect(mblk_t *);
727 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
728 
729 static void	ip_arp_news(queue_t *, mblk_t *);
730 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
731 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
732 char		*ip_dot_addr(ipaddr_t, char *);
733 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
734 int		ip_close(queue_t *, int);
735 static char	*ip_dot_saddr(uchar_t *, char *);
736 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
737 		    boolean_t, boolean_t, ill_t *, zoneid_t);
738 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
739 		    boolean_t, boolean_t, zoneid_t);
740 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
741 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
742 static void	ip_lrput(queue_t *, mblk_t *);
743 ipaddr_t	ip_massage_options(ipha_t *);
744 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
745 ipaddr_t	ip_net_mask(ipaddr_t);
746 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
747 		    zoneid_t);
748 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
749 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
750 char		*ip_nv_lookup(nv_t *, int);
751 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
752 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
754 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
755 			    size_t);
756 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 void	ip_rput(queue_t *, mblk_t *);
758 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
759 		    void *dummy_arg);
760 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
761 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
762 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
763 			    ire_t *);
764 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
765 			    mblk_t *, ipha_t **, ipaddr_t *);
766 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
767 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
768 		    uint16_t *);
769 int		ip_snmp_get(queue_t *, mblk_t *);
770 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
771 		    mib2_ipIfStatsEntry_t *);
772 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *);
773 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
774 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
775 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
776 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
777 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
778 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
779 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
780 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
781 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
782 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
783 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
784 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
785 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
786 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
787 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
788 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
789 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
790 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
791 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
792 static boolean_t	ip_source_routed(ipha_t *);
793 static boolean_t	ip_source_route_included(ipha_t *);
794 
795 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
796 		    zoneid_t);
797 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
798 static void	ip_wput_local_options(ipha_t *);
799 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
800 		    zoneid_t);
801 
802 static void	conn_drain_init(void);
803 static void	conn_drain_fini(void);
804 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
805 
806 static void	conn_walk_drain(void);
807 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
808     zoneid_t);
809 
810 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
811     zoneid_t);
812 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
813     void *dummy_arg);
814 
815 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
816 
817 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
818     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
819     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
820 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
821 
822 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
823 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
824     caddr_t, cred_t *);
825 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
826     caddr_t cp, cred_t *cr);
827 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
828     cred_t *);
829 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
830     caddr_t cp, cred_t *cr);
831 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
832     cred_t *);
833 static squeue_func_t ip_squeue_switch(int);
834 
835 static void	ip_kstat_init(void);
836 static void	ip_kstat_fini(void);
837 static int	ip_kstat_update(kstat_t *kp, int rw);
838 static void	icmp_kstat_init(void);
839 static void	icmp_kstat_fini(void);
840 static int	icmp_kstat_update(kstat_t *kp, int rw);
841 
842 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
843 
844 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
845     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
846 
847 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
848     ipha_t *, ill_t *, boolean_t);
849 
850 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
851 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
852 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
853 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
854 
855 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
856 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
857 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
858 
859 /* How long, in seconds, we allow frags to hang around. */
860 #define	IP_FRAG_TIMEOUT	60
861 
862 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
863 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
864 
865 /*
866  * Threshold which determines whether MDT should be used when
867  * generating IP fragments; payload size must be greater than
868  * this threshold for MDT to take place.
869  */
870 #define	IP_WPUT_FRAG_MDT_MIN	32768
871 
872 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
873 
874 /* Protected by ip_mi_lock */
875 static void	*ip_g_head;		/* Instance Data List Head */
876 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
877 
878 /* Only modified during _init and _fini thus no locking is needed. */
879 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
880 
881 
882 static long ip_rput_pullups;
883 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
884 
885 vmem_t *ip_minor_arena;
886 
887 /*
888  * MIB-2 stuff for SNMP (both IP and ICMP)
889  */
890 mib2_ipIfStatsEntry_t	ip_mib;
891 mib2_icmp_t		icmp_mib;
892 
893 #ifdef DEBUG
894 uint32_t ipsechw_debug = 0;
895 #endif
896 
897 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
898 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
899 
900 uint_t	loopback_packets = 0;
901 
902 /*
903  * Multirouting/CGTP stuff
904  */
905 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
906 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
907 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
908 /* Interval (in ms) between consecutive 'bad MTU' warnings */
909 hrtime_t ip_multirt_log_interval = 1000;
910 /* Time since last warning issued. */
911 static hrtime_t	multirt_bad_mtu_last_time = 0;
912 
913 kmutex_t ip_trash_timer_lock;
914 krwlock_t ip_g_nd_lock;
915 
916 /*
917  * XXX following really should only be in a header. Would need more
918  * header and .c clean up first.
919  */
920 extern optdb_obj_t	ip_opt_obj;
921 
922 ulong_t ip_squeue_enter_unbound = 0;
923 
924 /*
925  * Named Dispatch Parameter Table.
926  * All of these are alterable, within the min/max values given, at run time.
927  */
928 static ipparam_t	lcl_param_arr[] = {
929 	/* min	max	value	name */
930 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
931 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
932 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
933 	{  0,	1,	0,	"ip_respond_to_timestamp"},
934 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
935 	{  0,	1,	1,	"ip_send_redirects"},
936 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
937 	{  0,	10,	0,	"ip_debug"},
938 	{  0,	10,	0,	"ip_mrtdebug"},
939 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
940 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
941 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
942 	{  1,	255,	255,	"ip_def_ttl" },
943 	{  0,	1,	0,	"ip_forward_src_routed"},
944 	{  0,	256,	32,	"ip_wroff_extra" },
945 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
946 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
947 	{  0,	1,	1,	"ip_path_mtu_discovery" },
948 	{  0,	240,	30,	"ip_ignore_delete_time" },
949 	{  0,	1,	0,	"ip_ignore_redirect" },
950 	{  0,	1,	1,	"ip_output_queue" },
951 	{  1,	254,	1,	"ip_broadcast_ttl" },
952 	{  0,	99999,	100,	"ip_icmp_err_interval" },
953 	{  1,	99999,	10,	"ip_icmp_err_burst" },
954 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
955 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
956 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
957 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
958 	{  0,	1,	1,	"icmp_accept_clear_messages" },
959 	{  0,	1,	1,	"igmp_accept_clear_messages" },
960 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
961 				"ip_ndp_delay_first_probe_time"},
962 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
963 				"ip_ndp_max_unicast_solicit"},
964 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
965 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
966 	{  0,	1,	0,	"ip6_forward_src_routed"},
967 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
968 	{  0,	1,	1,	"ip6_send_redirects"},
969 	{  0,	1,	0,	"ip6_ignore_redirect" },
970 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
971 
972 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
973 
974 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
975 
976 	{  0,	1,	1,	"pim_accept_clear_messages" },
977 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
978 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
979 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
980 	{  0,	15,	0,	"ip_policy_mask" },
981 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
982 	{  0,	255,	1,	"ip_multirt_ttl" },
983 	{  0,	1,	1,	"ip_multidata_outbound" },
984 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
985 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
986 	{  0,	1000,	1,	"ip_max_temp_defend" },
987 	{  0,	1000,	3,	"ip_max_defend" },
988 	{  0,	999999,	30,	"ip_defend_interval" },
989 	{  0,	3600000, 300000, "ip_dup_recovery" },
990 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
991 	{  0,	1,	1,	"ip_lso_outbound" },
992 #ifdef DEBUG
993 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
994 #endif
995 };
996 
997 ipparam_t	*ip_param_arr = lcl_param_arr;
998 
999 /* Extended NDP table */
1000 static ipndp_t	lcl_ndp_arr[] = {
1001 	/* getf			setf		data			name */
1002 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
1003 	    "ip_forwarding" },
1004 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
1005 	    "ip6_forwarding" },
1006 	{  ip_ill_report,	NULL,		NULL,
1007 	    "ip_ill_status" },
1008 	{  ip_ipif_report,	NULL,		NULL,
1009 	    "ip_ipif_status" },
1010 	{  ip_ire_report,	NULL,		NULL,
1011 	    "ipv4_ire_status" },
1012 	{  ip_ire_report_mrtun,	NULL,		NULL,
1013 	    "ipv4_mrtun_ire_status" },
1014 	{  ip_ire_report_srcif,	NULL,		NULL,
1015 	    "ipv4_srcif_ire_status" },
1016 	{  ip_ire_report_v6,	NULL,		NULL,
1017 	    "ipv6_ire_status" },
1018 	{  ip_conn_report,	NULL,		NULL,
1019 	    "ip_conn_status" },
1020 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1021 	    "ip_rput_pullups" },
1022 	{  ndp_report,		NULL,		NULL,
1023 	    "ip_ndp_cache_report" },
1024 	{  ip_srcid_report,	NULL,		NULL,
1025 	    "ip_srcid_status" },
1026 	{ ip_param_generic_get, ip_squeue_profile_set,
1027 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
1028 	{ ip_param_generic_get, ip_squeue_bind_set,
1029 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
1030 	{ ip_param_generic_get, ip_input_proc_set,
1031 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1032 	{ ip_param_generic_get, ip_int_set,
1033 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1034 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
1035 	    "ip_cgtp_filter" },
1036 	{ ip_param_generic_get, ip_int_set,
1037 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
1038 };
1039 
1040 /*
1041  * ip_g_forward controls IP forwarding.  It takes two values:
1042  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
1043  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
1044  *
1045  * RFC1122 says there must be a configuration switch to control forwarding,
1046  * but that the default MUST be to not forward packets ever.  Implicit
1047  * control based on configuration of multiple interfaces MUST NOT be
1048  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
1049  * and, in fact, it was the default.  That capability is now provided in the
1050  * /etc/rc2.d/S69inet script.
1051  */
1052 int ip_g_forward = IP_FORWARD_DEFAULT;
1053 
1054 /* It also has an IPv6 counterpart. */
1055 
1056 int ipv6_forward = IP_FORWARD_DEFAULT;
1057 
1058 /*
1059  * Table of IP ioctls encoding the various properties of the ioctl and
1060  * indexed based on the last byte of the ioctl command. Occasionally there
1061  * is a clash, and there is more than 1 ioctl with the same last byte.
1062  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1063  * ioctls are encoded in the misc table. An entry in the ndx table is
1064  * retrieved by indexing on the last byte of the ioctl command and comparing
1065  * the ioctl command with the value in the ndx table. In the event of a
1066  * mismatch the misc table is then searched sequentially for the desired
1067  * ioctl command.
1068  *
1069  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1070  */
1071 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1072 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 
1083 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1084 			MISC_CMD, ip_siocaddrt, NULL },
1085 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1086 			MISC_CMD, ip_siocdelrt, NULL },
1087 
1088 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1089 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1090 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1091 			IF_CMD, ip_sioctl_get_addr, NULL },
1092 
1093 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1094 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1095 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1096 			IPI_GET_CMD | IPI_REPL,
1097 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1098 
1099 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1100 			IPI_PRIV | IPI_WR | IPI_REPL,
1101 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1102 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1103 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1104 			IF_CMD, ip_sioctl_get_flags, NULL },
1105 
1106 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 
1109 	/* copyin size cannot be coded for SIOCGIFCONF */
1110 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1111 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1112 
1113 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1114 			IF_CMD, ip_sioctl_mtu, NULL },
1115 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1116 			IF_CMD, ip_sioctl_get_mtu, NULL },
1117 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1118 			IPI_GET_CMD | IPI_REPL,
1119 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1120 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1121 			IF_CMD, ip_sioctl_brdaddr, NULL },
1122 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1123 			IPI_GET_CMD | IPI_REPL,
1124 			IF_CMD, ip_sioctl_get_netmask, NULL },
1125 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1126 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1127 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1128 			IPI_GET_CMD | IPI_REPL,
1129 			IF_CMD, ip_sioctl_get_metric, NULL },
1130 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1131 			IF_CMD, ip_sioctl_metric, NULL },
1132 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 
1134 	/* See 166-168 below for extended SIOC*XARP ioctls */
1135 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1136 			MISC_CMD, ip_sioctl_arp, NULL },
1137 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1138 			MISC_CMD, ip_sioctl_arp, NULL },
1139 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1140 			MISC_CMD, ip_sioctl_arp, NULL },
1141 
1142 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1158 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1159 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1160 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1161 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 
1164 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1165 			MISC_CMD, if_unitsel, if_unitsel_restart },
1166 
1167 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 
1186 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1187 			IPI_PRIV | IPI_WR | IPI_MODOK,
1188 			IF_CMD, ip_sioctl_sifname, NULL },
1189 
1190 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1200 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1201 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1202 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1203 
1204 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1205 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1206 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1207 			IF_CMD, ip_sioctl_get_muxid, NULL },
1208 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1209 			IPI_PRIV | IPI_WR | IPI_REPL,
1210 			IF_CMD, ip_sioctl_muxid, NULL },
1211 
1212 	/* Both if and lif variants share same func */
1213 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1214 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1215 	/* Both if and lif variants share same func */
1216 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1217 			IPI_PRIV | IPI_WR | IPI_REPL,
1218 			IF_CMD, ip_sioctl_slifindex, NULL },
1219 
1220 	/* copyin size cannot be coded for SIOCGIFCONF */
1221 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1222 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1223 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1226 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1227 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1228 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1229 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1230 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1231 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1232 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1233 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1234 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1235 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1236 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1237 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1238 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1239 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1240 
1241 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1242 			IPI_PRIV | IPI_WR | IPI_REPL,
1243 			LIF_CMD, ip_sioctl_removeif,
1244 			ip_sioctl_removeif_restart },
1245 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1246 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1247 			LIF_CMD, ip_sioctl_addif, NULL },
1248 #define	SIOCLIFADDR_NDX 112
1249 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1250 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1251 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1252 			IPI_GET_CMD | IPI_REPL,
1253 			LIF_CMD, ip_sioctl_get_addr, NULL },
1254 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1255 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1256 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1257 			IPI_GET_CMD | IPI_REPL,
1258 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1259 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1260 			IPI_PRIV | IPI_WR | IPI_REPL,
1261 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1262 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1263 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1264 			LIF_CMD, ip_sioctl_get_flags, NULL },
1265 
1266 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1267 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1268 
1269 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1270 			ip_sioctl_get_lifconf, NULL },
1271 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1272 			LIF_CMD, ip_sioctl_mtu, NULL },
1273 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1274 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1275 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1276 			IPI_GET_CMD | IPI_REPL,
1277 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1278 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1279 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1280 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1281 			IPI_GET_CMD | IPI_REPL,
1282 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1283 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1284 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1285 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1286 			IPI_GET_CMD | IPI_REPL,
1287 			LIF_CMD, ip_sioctl_get_metric, NULL },
1288 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1289 			LIF_CMD, ip_sioctl_metric, NULL },
1290 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1291 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1292 			LIF_CMD, ip_sioctl_slifname,
1293 			ip_sioctl_slifname_restart },
1294 
1295 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1296 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1297 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1298 			IPI_GET_CMD | IPI_REPL,
1299 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1300 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1301 			IPI_PRIV | IPI_WR | IPI_REPL,
1302 			LIF_CMD, ip_sioctl_muxid, NULL },
1303 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1304 			IPI_GET_CMD | IPI_REPL,
1305 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1306 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1307 			IPI_PRIV | IPI_WR | IPI_REPL,
1308 			LIF_CMD, ip_sioctl_slifindex, 0 },
1309 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1310 			LIF_CMD, ip_sioctl_token, NULL },
1311 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1312 			IPI_GET_CMD | IPI_REPL,
1313 			LIF_CMD, ip_sioctl_get_token, NULL },
1314 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1315 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1316 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1317 			IPI_GET_CMD | IPI_REPL,
1318 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1319 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1320 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1321 
1322 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1323 			IPI_GET_CMD | IPI_REPL,
1324 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1325 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1326 			LIF_CMD, ip_siocdelndp_v6, NULL },
1327 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1328 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1329 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1330 			LIF_CMD, ip_siocsetndp_v6, NULL },
1331 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1332 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1333 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1334 			MISC_CMD, ip_sioctl_tonlink, NULL },
1335 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1336 			MISC_CMD, ip_sioctl_tmysite, NULL },
1337 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1338 			TUN_CMD, ip_sioctl_tunparam, NULL },
1339 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1340 			IPI_PRIV | IPI_WR,
1341 			TUN_CMD, ip_sioctl_tunparam, NULL },
1342 
1343 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1344 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1345 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1346 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1347 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1348 
1349 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1350 			IPI_PRIV | IPI_WR | IPI_REPL,
1351 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1352 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1353 			IPI_PRIV | IPI_WR | IPI_REPL,
1354 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1355 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1356 			IPI_PRIV | IPI_WR,
1357 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1358 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1359 			IPI_GET_CMD | IPI_REPL,
1360 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1361 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1362 			IPI_GET_CMD | IPI_REPL,
1363 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1364 
1365 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1366 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1367 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1368 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1369 
1370 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1371 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1372 
1373 	/* These are handled in ip_sioctl_copyin_setup itself */
1374 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1375 			MISC_CMD, NULL, NULL },
1376 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1377 			MISC_CMD, NULL, NULL },
1378 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1379 
1380 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1381 			ip_sioctl_get_lifconf, NULL },
1382 
1383 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1384 			MISC_CMD, ip_sioctl_xarp, NULL },
1385 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1386 			MISC_CMD, ip_sioctl_xarp, NULL },
1387 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1388 			MISC_CMD, ip_sioctl_xarp, NULL },
1389 
1390 	/* SIOCPOPSOCKFS is not handled by IP */
1391 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1392 
1393 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1394 			IPI_GET_CMD | IPI_REPL,
1395 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1396 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1397 			IPI_PRIV | IPI_WR | IPI_REPL,
1398 			LIF_CMD, ip_sioctl_slifzone,
1399 			ip_sioctl_slifzone_restart },
1400 	/* 172-174 are SCTP ioctls and not handled by IP */
1401 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1402 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1403 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1404 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1405 			IPI_GET_CMD, LIF_CMD,
1406 			ip_sioctl_get_lifusesrc, 0 },
1407 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1408 			IPI_PRIV | IPI_WR,
1409 			LIF_CMD, ip_sioctl_slifusesrc,
1410 			NULL },
1411 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1412 			ip_sioctl_get_lifsrcof, NULL },
1413 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1414 			MISC_CMD, ip_sioctl_msfilter, NULL },
1415 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1416 			MISC_CMD, ip_sioctl_msfilter, NULL },
1417 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1418 			MISC_CMD, ip_sioctl_msfilter, NULL },
1419 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1420 			MISC_CMD, ip_sioctl_msfilter, NULL },
1421 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1422 			ip_sioctl_set_ipmpfailback, NULL }
1423 };
1424 
1425 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1426 
1427 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1428 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1429 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1430 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1431 		TUN_CMD, ip_sioctl_tunparam, NULL },
1432 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1433 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1434 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1435 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1436 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1437 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1438 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1439 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1440 		MISC_CMD, mrt_ioctl},
1441 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1442 		MISC_CMD, mrt_ioctl},
1443 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1444 		MISC_CMD, mrt_ioctl}
1445 };
1446 
1447 int ip_misc_ioctl_count =
1448     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1449 
1450 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1451 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1452 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1453 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1454 					/* Settable in /etc/system */
1455 uint_t	ip_redirect_cnt;		/* Num of redirect routes in ftable */
1456 
1457 /* Defined in ip_ire.c */
1458 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1459 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1460 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1461 
1462 static nv_t	ire_nv_arr[] = {
1463 	{ IRE_BROADCAST, "BROADCAST" },
1464 	{ IRE_LOCAL, "LOCAL" },
1465 	{ IRE_LOOPBACK, "LOOPBACK" },
1466 	{ IRE_CACHE, "CACHE" },
1467 	{ IRE_DEFAULT, "DEFAULT" },
1468 	{ IRE_PREFIX, "PREFIX" },
1469 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1470 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1471 	{ IRE_HOST, "HOST" },
1472 	{ 0 }
1473 };
1474 
1475 nv_t	*ire_nv_tbl = ire_nv_arr;
1476 
1477 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1478 extern krwlock_t ipsec_capab_ills_lock;
1479 
1480 /* Defined in ip_netinfo.c */
1481 extern ddi_taskq_t	*eventq_queue_nic;
1482 
1483 /* Packet dropper for IP IPsec processing failures */
1484 ipdropper_t ip_dropper;
1485 
1486 /* Simple ICMP IP Header Template */
1487 static ipha_t icmp_ipha = {
1488 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1489 };
1490 
1491 struct module_info ip_mod_info = {
1492 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1493 };
1494 
1495 /*
1496  * Duplicate static symbols within a module confuses mdb; so we avoid the
1497  * problem by making the symbols here distinct from those in udp.c.
1498  */
1499 
1500 static struct qinit iprinit = {
1501 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1502 	&ip_mod_info
1503 };
1504 
1505 static struct qinit ipwinit = {
1506 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1507 	&ip_mod_info
1508 };
1509 
1510 static struct qinit iplrinit = {
1511 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1512 	&ip_mod_info
1513 };
1514 
1515 static struct qinit iplwinit = {
1516 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1517 	&ip_mod_info
1518 };
1519 
1520 struct streamtab ipinfo = {
1521 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1522 };
1523 
1524 #ifdef	DEBUG
1525 static boolean_t skip_sctp_cksum = B_FALSE;
1526 #endif
1527 
1528 /*
1529  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1530  * ip_rput_v6(), ip_output(), etc.  If the message
1531  * block already has a M_CTL at the front of it, then simply set the zoneid
1532  * appropriately.
1533  */
1534 mblk_t *
1535 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid)
1536 {
1537 	mblk_t		*first_mp;
1538 	ipsec_out_t	*io;
1539 
1540 	ASSERT(zoneid != ALL_ZONES);
1541 	if (mp->b_datap->db_type == M_CTL) {
1542 		io = (ipsec_out_t *)mp->b_rptr;
1543 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1544 		io->ipsec_out_zoneid = zoneid;
1545 		return (mp);
1546 	}
1547 
1548 	first_mp = ipsec_alloc_ipsec_out();
1549 	if (first_mp == NULL)
1550 		return (NULL);
1551 	io = (ipsec_out_t *)first_mp->b_rptr;
1552 	/* This is not a secure packet */
1553 	io->ipsec_out_secure = B_FALSE;
1554 	io->ipsec_out_zoneid = zoneid;
1555 	first_mp->b_cont = mp;
1556 	return (first_mp);
1557 }
1558 
1559 /*
1560  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1561  */
1562 mblk_t *
1563 ip_copymsg(mblk_t *mp)
1564 {
1565 	mblk_t *nmp;
1566 	ipsec_info_t *in;
1567 
1568 	if (mp->b_datap->db_type != M_CTL)
1569 		return (copymsg(mp));
1570 
1571 	in = (ipsec_info_t *)mp->b_rptr;
1572 
1573 	/*
1574 	 * Note that M_CTL is also used for delivering ICMP error messages
1575 	 * upstream to transport layers.
1576 	 */
1577 	if (in->ipsec_info_type != IPSEC_OUT &&
1578 	    in->ipsec_info_type != IPSEC_IN)
1579 		return (copymsg(mp));
1580 
1581 	nmp = copymsg(mp->b_cont);
1582 
1583 	if (in->ipsec_info_type == IPSEC_OUT)
1584 		return (ipsec_out_tag(mp, nmp));
1585 	else
1586 		return (ipsec_in_tag(mp, nmp));
1587 }
1588 
1589 /* Generate an ICMP fragmentation needed message. */
1590 static void
1591 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid)
1592 {
1593 	icmph_t	icmph;
1594 	mblk_t *first_mp;
1595 	boolean_t mctl_present;
1596 
1597 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1598 
1599 	if (!(mp = icmp_pkt_err_ok(mp))) {
1600 		if (mctl_present)
1601 			freeb(first_mp);
1602 		return;
1603 	}
1604 
1605 	bzero(&icmph, sizeof (icmph_t));
1606 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1607 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1608 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1609 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1610 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1611 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
1612 }
1613 
1614 /*
1615  * icmp_inbound deals with ICMP messages in the following ways.
1616  *
1617  * 1) It needs to send a reply back and possibly delivering it
1618  *    to the "interested" upper clients.
1619  * 2) It needs to send it to the upper clients only.
1620  * 3) It needs to change some values in IP only.
1621  * 4) It needs to change some values in IP and upper layers e.g TCP.
1622  *
1623  * We need to accomodate icmp messages coming in clear until we get
1624  * everything secure from the wire. If icmp_accept_clear_messages
1625  * is zero we check with the global policy and act accordingly. If
1626  * it is non-zero, we accept the message without any checks. But
1627  * *this does not mean* that this will be delivered to the upper
1628  * clients. By accepting we might send replies back, change our MTU
1629  * value etc. but delivery to the ULP/clients depends on their policy
1630  * dispositions.
1631  *
1632  * We handle the above 4 cases in the context of IPSEC in the
1633  * following way :
1634  *
1635  * 1) Send the reply back in the same way as the request came in.
1636  *    If it came in encrypted, it goes out encrypted. If it came in
1637  *    clear, it goes out in clear. Thus, this will prevent chosen
1638  *    plain text attack.
1639  * 2) The client may or may not expect things to come in secure.
1640  *    If it comes in secure, the policy constraints are checked
1641  *    before delivering it to the upper layers. If it comes in
1642  *    clear, ipsec_inbound_accept_clear will decide whether to
1643  *    accept this in clear or not. In both the cases, if the returned
1644  *    message (IP header + 8 bytes) that caused the icmp message has
1645  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1646  *    sending up. If there are only 8 bytes of returned message, then
1647  *    upper client will not be notified.
1648  * 3) Check with global policy to see whether it matches the constaints.
1649  *    But this will be done only if icmp_accept_messages_in_clear is
1650  *    zero.
1651  * 4) If we need to change both in IP and ULP, then the decision taken
1652  *    while affecting the values in IP and while delivering up to TCP
1653  *    should be the same.
1654  *
1655  * 	There are two cases.
1656  *
1657  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1658  *	   failed), we will not deliver it to the ULP, even though they
1659  *	   are *willing* to accept in *clear*. This is fine as our global
1660  *	   disposition to icmp messages asks us reject the datagram.
1661  *
1662  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1663  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1664  *	   to deliver it to ULP (policy failed), it can lead to
1665  *	   consistency problems. The cases known at this time are
1666  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1667  *	   values :
1668  *
1669  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1670  *	     and Upper layer rejects. Then the communication will
1671  *	     come to a stop. This is solved by making similar decisions
1672  *	     at both levels. Currently, when we are unable to deliver
1673  *	     to the Upper Layer (due to policy failures) while IP has
1674  *	     adjusted ire_max_frag, the next outbound datagram would
1675  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1676  *	     will be with the right level of protection. Thus the right
1677  *	     value will be communicated even if we are not able to
1678  *	     communicate when we get from the wire initially. But this
1679  *	     assumes there would be at least one outbound datagram after
1680  *	     IP has adjusted its ire_max_frag value. To make things
1681  *	     simpler, we accept in clear after the validation of
1682  *	     AH/ESP headers.
1683  *
1684  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1685  *	     upper layer depending on the level of protection the upper
1686  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1687  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1688  *	     should be accepted in clear when the Upper layer expects secure.
1689  *	     Thus the communication may get aborted by some bad ICMP
1690  *	     packets.
1691  *
1692  * IPQoS Notes:
1693  * The only instance when a packet is sent for processing is when there
1694  * isn't an ICMP client and if we are interested in it.
1695  * If there is a client, IPPF processing will take place in the
1696  * ip_fanout_proto routine.
1697  *
1698  * Zones notes:
1699  * The packet is only processed in the context of the specified zone: typically
1700  * only this zone will reply to an echo request, and only interested clients in
1701  * this zone will receive a copy of the packet. This means that the caller must
1702  * call icmp_inbound() for each relevant zone.
1703  */
1704 static void
1705 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1706     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1707     ill_t *recv_ill, zoneid_t zoneid)
1708 {
1709 	icmph_t	*icmph;
1710 	ipha_t	*ipha;
1711 	int	iph_hdr_length;
1712 	int	hdr_length;
1713 	boolean_t	interested;
1714 	uint32_t	ts;
1715 	uchar_t	*wptr;
1716 	ipif_t	*ipif;
1717 	mblk_t *first_mp;
1718 	ipsec_in_t *ii;
1719 	ire_t *src_ire;
1720 	boolean_t onlink;
1721 	timestruc_t now;
1722 	uint32_t ill_index;
1723 
1724 	ASSERT(ill != NULL);
1725 
1726 	first_mp = mp;
1727 	if (mctl_present) {
1728 		mp = first_mp->b_cont;
1729 		ASSERT(mp != NULL);
1730 	}
1731 
1732 	ipha = (ipha_t *)mp->b_rptr;
1733 	if (icmp_accept_clear_messages == 0) {
1734 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1735 		    ipha, NULL, mctl_present);
1736 		if (first_mp == NULL)
1737 			return;
1738 	}
1739 
1740 	/*
1741 	 * On a labeled system, we have to check whether the zone itself is
1742 	 * permitted to receive raw traffic.
1743 	 */
1744 	if (is_system_labeled()) {
1745 		if (zoneid == ALL_ZONES)
1746 			zoneid = tsol_packet_to_zoneid(mp);
1747 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1748 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1749 			    zoneid));
1750 			BUMP_MIB(&icmp_mib, icmpInErrors);
1751 			freemsg(first_mp);
1752 			return;
1753 		}
1754 	}
1755 
1756 	/*
1757 	 * We have accepted the ICMP message. It means that we will
1758 	 * respond to the packet if needed. It may not be delivered
1759 	 * to the upper client depending on the policy constraints
1760 	 * and the disposition in ipsec_inbound_accept_clear.
1761 	 */
1762 
1763 	ASSERT(ill != NULL);
1764 
1765 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1766 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1767 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1768 		/* Last chance to get real. */
1769 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1770 			BUMP_MIB(&icmp_mib, icmpInErrors);
1771 			freemsg(first_mp);
1772 			return;
1773 		}
1774 		/* Refresh iph following the pullup. */
1775 		ipha = (ipha_t *)mp->b_rptr;
1776 	}
1777 	/* ICMP header checksum, including checksum field, should be zero. */
1778 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1779 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1780 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1781 		freemsg(first_mp);
1782 		return;
1783 	}
1784 	/* The IP header will always be a multiple of four bytes */
1785 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1786 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1787 	    icmph->icmph_code));
1788 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1789 	/* We will set "interested" to "true" if we want a copy */
1790 	interested = B_FALSE;
1791 	switch (icmph->icmph_type) {
1792 	case ICMP_ECHO_REPLY:
1793 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1794 		break;
1795 	case ICMP_DEST_UNREACHABLE:
1796 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1797 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1798 		interested = B_TRUE;	/* Pass up to transport */
1799 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1800 		break;
1801 	case ICMP_SOURCE_QUENCH:
1802 		interested = B_TRUE;	/* Pass up to transport */
1803 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1804 		break;
1805 	case ICMP_REDIRECT:
1806 		if (!ip_ignore_redirect)
1807 			interested = B_TRUE;
1808 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1809 		break;
1810 	case ICMP_ECHO_REQUEST:
1811 		/*
1812 		 * Whether to respond to echo requests that come in as IP
1813 		 * broadcasts or as IP multicast is subject to debate
1814 		 * (what isn't?).  We aim to please, you pick it.
1815 		 * Default is do it.
1816 		 */
1817 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1818 			/* unicast: always respond */
1819 			interested = B_TRUE;
1820 		} else if (CLASSD(ipha->ipha_dst)) {
1821 			/* multicast: respond based on tunable */
1822 			interested = ip_g_resp_to_echo_mcast;
1823 		} else if (broadcast) {
1824 			/* broadcast: respond based on tunable */
1825 			interested = ip_g_resp_to_echo_bcast;
1826 		}
1827 		BUMP_MIB(&icmp_mib, icmpInEchos);
1828 		break;
1829 	case ICMP_ROUTER_ADVERTISEMENT:
1830 	case ICMP_ROUTER_SOLICITATION:
1831 		break;
1832 	case ICMP_TIME_EXCEEDED:
1833 		interested = B_TRUE;	/* Pass up to transport */
1834 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1835 		break;
1836 	case ICMP_PARAM_PROBLEM:
1837 		interested = B_TRUE;	/* Pass up to transport */
1838 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1839 		break;
1840 	case ICMP_TIME_STAMP_REQUEST:
1841 		/* Response to Time Stamp Requests is local policy. */
1842 		if (ip_g_resp_to_timestamp &&
1843 		    /* So is whether to respond if it was an IP broadcast. */
1844 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1845 			int tstamp_len = 3 * sizeof (uint32_t);
1846 
1847 			if (wptr +  tstamp_len > mp->b_wptr) {
1848 				if (!pullupmsg(mp, wptr + tstamp_len -
1849 				    mp->b_rptr)) {
1850 					BUMP_MIB(ill->ill_ip_mib,
1851 					    ipIfStatsInDiscards);
1852 					freemsg(first_mp);
1853 					return;
1854 				}
1855 				/* Refresh ipha following the pullup. */
1856 				ipha = (ipha_t *)mp->b_rptr;
1857 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1858 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1859 			}
1860 			interested = B_TRUE;
1861 		}
1862 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1863 		break;
1864 	case ICMP_TIME_STAMP_REPLY:
1865 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1866 		break;
1867 	case ICMP_INFO_REQUEST:
1868 		/* Per RFC 1122 3.2.2.7, ignore this. */
1869 	case ICMP_INFO_REPLY:
1870 		break;
1871 	case ICMP_ADDRESS_MASK_REQUEST:
1872 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1873 		    /* TODO m_pullup of complete header? */
1874 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1875 			interested = B_TRUE;
1876 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1877 		break;
1878 	case ICMP_ADDRESS_MASK_REPLY:
1879 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1880 		break;
1881 	default:
1882 		interested = B_TRUE;	/* Pass up to transport */
1883 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1884 		break;
1885 	}
1886 	/* See if there is an ICMP client. */
1887 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1888 		/* If there is an ICMP client and we want one too, copy it. */
1889 		mblk_t *first_mp1;
1890 
1891 		if (!interested) {
1892 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1893 			    ip_policy, recv_ill, zoneid);
1894 			return;
1895 		}
1896 		first_mp1 = ip_copymsg(first_mp);
1897 		if (first_mp1 != NULL) {
1898 			ip_fanout_proto(q, first_mp1, ill, ipha,
1899 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1900 		}
1901 	} else if (!interested) {
1902 		freemsg(first_mp);
1903 		return;
1904 	} else {
1905 		/*
1906 		 * Initiate policy processing for this packet if ip_policy
1907 		 * is true.
1908 		 */
1909 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1910 			ill_index = ill->ill_phyint->phyint_ifindex;
1911 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1912 			if (mp == NULL) {
1913 				if (mctl_present) {
1914 					freeb(first_mp);
1915 				}
1916 				BUMP_MIB(&icmp_mib, icmpInErrors);
1917 				return;
1918 			}
1919 		}
1920 	}
1921 	/* We want to do something with it. */
1922 	/* Check db_ref to make sure we can modify the packet. */
1923 	if (mp->b_datap->db_ref > 1) {
1924 		mblk_t	*first_mp1;
1925 
1926 		first_mp1 = ip_copymsg(first_mp);
1927 		freemsg(first_mp);
1928 		if (!first_mp1) {
1929 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1930 			return;
1931 		}
1932 		first_mp = first_mp1;
1933 		if (mctl_present) {
1934 			mp = first_mp->b_cont;
1935 			ASSERT(mp != NULL);
1936 		} else {
1937 			mp = first_mp;
1938 		}
1939 		ipha = (ipha_t *)mp->b_rptr;
1940 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1941 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1942 	}
1943 	switch (icmph->icmph_type) {
1944 	case ICMP_ADDRESS_MASK_REQUEST:
1945 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1946 		if (ipif == NULL) {
1947 			freemsg(first_mp);
1948 			return;
1949 		}
1950 		/*
1951 		 * outging interface must be IPv4
1952 		 */
1953 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1954 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1955 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1956 		ipif_refrele(ipif);
1957 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1958 		break;
1959 	case ICMP_ECHO_REQUEST:
1960 		icmph->icmph_type = ICMP_ECHO_REPLY;
1961 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1962 		break;
1963 	case ICMP_TIME_STAMP_REQUEST: {
1964 		uint32_t *tsp;
1965 
1966 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1967 		tsp = (uint32_t *)wptr;
1968 		tsp++;		/* Skip past 'originate time' */
1969 		/* Compute # of milliseconds since midnight */
1970 		gethrestime(&now);
1971 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1972 		    now.tv_nsec / (NANOSEC / MILLISEC);
1973 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1974 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1975 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1976 		break;
1977 	}
1978 	default:
1979 		ipha = (ipha_t *)&icmph[1];
1980 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1981 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1982 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1983 				freemsg(first_mp);
1984 				return;
1985 			}
1986 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1987 			ipha = (ipha_t *)&icmph[1];
1988 		}
1989 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1990 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1991 			freemsg(first_mp);
1992 			return;
1993 		}
1994 		hdr_length = IPH_HDR_LENGTH(ipha);
1995 		if (hdr_length < sizeof (ipha_t)) {
1996 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1997 			freemsg(first_mp);
1998 			return;
1999 		}
2000 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
2001 			if (!pullupmsg(mp,
2002 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
2003 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2004 				freemsg(first_mp);
2005 				return;
2006 			}
2007 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2008 			ipha = (ipha_t *)&icmph[1];
2009 		}
2010 		switch (icmph->icmph_type) {
2011 		case ICMP_REDIRECT:
2012 			/*
2013 			 * As there is no upper client to deliver, we don't
2014 			 * need the first_mp any more.
2015 			 */
2016 			if (mctl_present) {
2017 				freeb(first_mp);
2018 			}
2019 			icmp_redirect(mp);
2020 			return;
2021 		case ICMP_DEST_UNREACHABLE:
2022 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
2023 				if (!icmp_inbound_too_big(icmph, ipha, ill,
2024 				    zoneid, mp, iph_hdr_length)) {
2025 					freemsg(first_mp);
2026 					return;
2027 				}
2028 				/*
2029 				 * icmp_inbound_too_big() may alter mp.
2030 				 * Resynch ipha and icmph accordingly.
2031 				 */
2032 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2033 				ipha = (ipha_t *)&icmph[1];
2034 			}
2035 			/* FALLTHRU */
2036 		default :
2037 			/*
2038 			 * IPQoS notes: Since we have already done IPQoS
2039 			 * processing we don't want to do it again in
2040 			 * the fanout routines called by
2041 			 * icmp_inbound_error_fanout, hence the last
2042 			 * argument, ip_policy, is B_FALSE.
2043 			 */
2044 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2045 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2046 			    B_FALSE, recv_ill, zoneid);
2047 		}
2048 		return;
2049 	}
2050 	/* Send out an ICMP packet */
2051 	icmph->icmph_checksum = 0;
2052 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2053 	if (icmph->icmph_checksum == 0)
2054 		icmph->icmph_checksum = 0xFFFF;
2055 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2056 		ipif_t	*ipif_chosen;
2057 		/*
2058 		 * Make it look like it was directed to us, so we don't look
2059 		 * like a fool with a broadcast or multicast source address.
2060 		 */
2061 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2062 		/*
2063 		 * Make sure that we haven't grabbed an interface that's DOWN.
2064 		 */
2065 		if (ipif != NULL) {
2066 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2067 			    ipha->ipha_src, zoneid);
2068 			if (ipif_chosen != NULL) {
2069 				ipif_refrele(ipif);
2070 				ipif = ipif_chosen;
2071 			}
2072 		}
2073 		if (ipif == NULL) {
2074 			ip0dbg(("icmp_inbound: "
2075 			    "No source for broadcast/multicast:\n"
2076 			    "\tsrc 0x%x dst 0x%x ill %p "
2077 			    "ipif_lcl_addr 0x%x\n",
2078 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2079 			    (void *)ill,
2080 			    ill->ill_ipif->ipif_lcl_addr));
2081 			freemsg(first_mp);
2082 			return;
2083 		}
2084 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2085 		ipha->ipha_dst = ipif->ipif_src_addr;
2086 		ipif_refrele(ipif);
2087 	}
2088 	/* Reset time to live. */
2089 	ipha->ipha_ttl = ip_def_ttl;
2090 	{
2091 		/* Swap source and destination addresses */
2092 		ipaddr_t tmp;
2093 
2094 		tmp = ipha->ipha_src;
2095 		ipha->ipha_src = ipha->ipha_dst;
2096 		ipha->ipha_dst = tmp;
2097 	}
2098 	ipha->ipha_ident = 0;
2099 	if (!IS_SIMPLE_IPH(ipha))
2100 		icmp_options_update(ipha);
2101 
2102 	/*
2103 	 * ICMP echo replies should go out on the same interface
2104 	 * the request came on as probes used by in.mpathd for detecting
2105 	 * NIC failures are ECHO packets. We turn-off load spreading
2106 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2107 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2108 	 * function. This is in turn handled by ip_wput and ip_newroute
2109 	 * to make sure that the packet goes out on the interface it came
2110 	 * in on. If we don't turnoff load spreading, the packets might get
2111 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2112 	 * to go out and in.mpathd would wrongly detect a failure or
2113 	 * mis-detect a NIC failure for link failure. As load spreading
2114 	 * can happen only if ill_group is not NULL, we do only for
2115 	 * that case and this does not affect the normal case.
2116 	 *
2117 	 * We turn off load spreading only on echo packets that came from
2118 	 * on-link hosts. If the interface route has been deleted, this will
2119 	 * not be enforced as we can't do much. For off-link hosts, as the
2120 	 * default routes in IPv4 does not typically have an ire_ipif
2121 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2122 	 * Moreover, expecting a default route through this interface may
2123 	 * not be correct. We use ipha_dst because of the swap above.
2124 	 */
2125 	onlink = B_FALSE;
2126 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2127 		/*
2128 		 * First, we need to make sure that it is not one of our
2129 		 * local addresses. If we set onlink when it is one of
2130 		 * our local addresses, we will end up creating IRE_CACHES
2131 		 * for one of our local addresses. Then, we will never
2132 		 * accept packets for them afterwards.
2133 		 */
2134 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2135 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2136 		if (src_ire == NULL) {
2137 			ipif = ipif_get_next_ipif(NULL, ill);
2138 			if (ipif == NULL) {
2139 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2140 				freemsg(mp);
2141 				return;
2142 			}
2143 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2144 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2145 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2146 			ipif_refrele(ipif);
2147 			if (src_ire != NULL) {
2148 				onlink = B_TRUE;
2149 				ire_refrele(src_ire);
2150 			}
2151 		} else {
2152 			ire_refrele(src_ire);
2153 		}
2154 	}
2155 	if (!mctl_present) {
2156 		/*
2157 		 * This packet should go out the same way as it
2158 		 * came in i.e in clear. To make sure that global
2159 		 * policy will not be applied to this in ip_wput_ire,
2160 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2161 		 */
2162 		ASSERT(first_mp == mp);
2163 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2164 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2165 			freemsg(mp);
2166 			return;
2167 		}
2168 		ii = (ipsec_in_t *)first_mp->b_rptr;
2169 
2170 		/* This is not a secure packet */
2171 		ii->ipsec_in_secure = B_FALSE;
2172 		if (onlink) {
2173 			ii->ipsec_in_attach_if = B_TRUE;
2174 			ii->ipsec_in_ill_index =
2175 			    ill->ill_phyint->phyint_ifindex;
2176 			ii->ipsec_in_rill_index =
2177 			    recv_ill->ill_phyint->phyint_ifindex;
2178 		}
2179 		first_mp->b_cont = mp;
2180 	} else if (onlink) {
2181 		ii = (ipsec_in_t *)first_mp->b_rptr;
2182 		ii->ipsec_in_attach_if = B_TRUE;
2183 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2184 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2185 	} else {
2186 		ii = (ipsec_in_t *)first_mp->b_rptr;
2187 	}
2188 	ii->ipsec_in_zoneid = zoneid;
2189 	ASSERT(zoneid != ALL_ZONES);
2190 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2191 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2192 		return;
2193 	}
2194 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2195 	put(WR(q), first_mp);
2196 }
2197 
2198 static ipaddr_t
2199 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2200 {
2201 	conn_t *connp;
2202 	connf_t *connfp;
2203 	ipaddr_t nexthop_addr = INADDR_ANY;
2204 	int hdr_length = IPH_HDR_LENGTH(ipha);
2205 	uint16_t *up;
2206 	uint32_t ports;
2207 
2208 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2209 	switch (ipha->ipha_protocol) {
2210 		case IPPROTO_TCP:
2211 		{
2212 			tcph_t *tcph;
2213 
2214 			/* do a reverse lookup */
2215 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2216 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2217 			    TCPS_LISTEN);
2218 			break;
2219 		}
2220 		case IPPROTO_UDP:
2221 		{
2222 			uint32_t dstport, srcport;
2223 
2224 			((uint16_t *)&ports)[0] = up[1];
2225 			((uint16_t *)&ports)[1] = up[0];
2226 
2227 			/* Extract ports in net byte order */
2228 			dstport = htons(ntohl(ports) & 0xFFFF);
2229 			srcport = htons(ntohl(ports) >> 16);
2230 
2231 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2232 			mutex_enter(&connfp->connf_lock);
2233 			connp = connfp->connf_head;
2234 
2235 			/* do a reverse lookup */
2236 			while ((connp != NULL) &&
2237 			    (!IPCL_UDP_MATCH(connp, dstport,
2238 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2239 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2240 				connp = connp->conn_next;
2241 			}
2242 			if (connp != NULL)
2243 				CONN_INC_REF(connp);
2244 			mutex_exit(&connfp->connf_lock);
2245 			break;
2246 		}
2247 		case IPPROTO_SCTP:
2248 		{
2249 			in6_addr_t map_src, map_dst;
2250 
2251 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2252 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2253 			((uint16_t *)&ports)[0] = up[1];
2254 			((uint16_t *)&ports)[1] = up[0];
2255 
2256 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2257 			    0, zoneid)) == NULL) {
2258 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2259 				    zoneid, ports, ipha);
2260 			} else {
2261 				CONN_INC_REF(connp);
2262 				SCTP_REFRELE(CONN2SCTP(connp));
2263 			}
2264 			break;
2265 		}
2266 		default:
2267 		{
2268 			ipha_t ripha;
2269 
2270 			ripha.ipha_src = ipha->ipha_dst;
2271 			ripha.ipha_dst = ipha->ipha_src;
2272 			ripha.ipha_protocol = ipha->ipha_protocol;
2273 
2274 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2275 			mutex_enter(&connfp->connf_lock);
2276 			connp = connfp->connf_head;
2277 			for (connp = connfp->connf_head; connp != NULL;
2278 			    connp = connp->conn_next) {
2279 				if (IPCL_PROTO_MATCH(connp,
2280 				    ipha->ipha_protocol, &ripha, ill,
2281 				    0, zoneid)) {
2282 					CONN_INC_REF(connp);
2283 					break;
2284 				}
2285 			}
2286 			mutex_exit(&connfp->connf_lock);
2287 		}
2288 	}
2289 	if (connp != NULL) {
2290 		if (connp->conn_nexthop_set)
2291 			nexthop_addr = connp->conn_nexthop_v4;
2292 		CONN_DEC_REF(connp);
2293 	}
2294 	return (nexthop_addr);
2295 }
2296 
2297 /* Table from RFC 1191 */
2298 static int icmp_frag_size_table[] =
2299 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2300 
2301 /*
2302  * Process received ICMP Packet too big.
2303  * After updating any IRE it does the fanout to any matching transport streams.
2304  * Assumes the message has been pulled up till the IP header that caused
2305  * the error.
2306  *
2307  * Returns B_FALSE on failure and B_TRUE on success.
2308  */
2309 static boolean_t
2310 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2311     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2312 {
2313 	ire_t	*ire, *first_ire;
2314 	int	mtu;
2315 	int	hdr_length;
2316 	ipaddr_t nexthop_addr;
2317 
2318 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2319 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2320 	ASSERT(ill != NULL);
2321 
2322 	hdr_length = IPH_HDR_LENGTH(ipha);
2323 
2324 	/* Drop if the original packet contained a source route */
2325 	if (ip_source_route_included(ipha)) {
2326 		return (B_FALSE);
2327 	}
2328 	/*
2329 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2330 	 * header.
2331 	 */
2332 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2333 	    mp->b_wptr) {
2334 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2335 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2336 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2337 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2338 			return (B_FALSE);
2339 		}
2340 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2341 		ipha = (ipha_t *)&icmph[1];
2342 	}
2343 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2344 	if (nexthop_addr != INADDR_ANY) {
2345 		/* nexthop set */
2346 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2347 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2348 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2349 	} else {
2350 		/* nexthop not set */
2351 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2352 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2353 	}
2354 
2355 	if (!first_ire) {
2356 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2357 		    ntohl(ipha->ipha_dst)));
2358 		return (B_FALSE);
2359 	}
2360 	/* Check for MTU discovery advice as described in RFC 1191 */
2361 	mtu = ntohs(icmph->icmph_du_mtu);
2362 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2363 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2364 	    ire = ire->ire_next) {
2365 		/*
2366 		 * Look for the connection to which this ICMP message is
2367 		 * directed. If it has the IP_NEXTHOP option set, then the
2368 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2369 		 * option. Else the search is limited to regular IREs.
2370 		 */
2371 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2372 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2373 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2374 		    (nexthop_addr != INADDR_ANY)))
2375 			continue;
2376 
2377 		mutex_enter(&ire->ire_lock);
2378 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2379 			/* Reduce the IRE max frag value as advised. */
2380 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2381 			    mtu, ire->ire_max_frag));
2382 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2383 		} else {
2384 			uint32_t length;
2385 			int	i;
2386 
2387 			/*
2388 			 * Use the table from RFC 1191 to figure out
2389 			 * the next "plateau" based on the length in
2390 			 * the original IP packet.
2391 			 */
2392 			length = ntohs(ipha->ipha_length);
2393 			if (ire->ire_max_frag <= length &&
2394 			    ire->ire_max_frag >= length - hdr_length) {
2395 				/*
2396 				 * Handle broken BSD 4.2 systems that
2397 				 * return the wrong iph_length in ICMP
2398 				 * errors.
2399 				 */
2400 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2401 				    length, ire->ire_max_frag));
2402 				length -= hdr_length;
2403 			}
2404 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2405 				if (length > icmp_frag_size_table[i])
2406 					break;
2407 			}
2408 			if (i == A_CNT(icmp_frag_size_table)) {
2409 				/* Smaller than 68! */
2410 				ip1dbg(("Too big for packet size %d\n",
2411 				    length));
2412 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2413 				ire->ire_frag_flag = 0;
2414 			} else {
2415 				mtu = icmp_frag_size_table[i];
2416 				ip1dbg(("Calculated mtu %d, packet size %d, "
2417 				    "before %d", mtu, length,
2418 				    ire->ire_max_frag));
2419 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2420 				ip1dbg((", after %d\n", ire->ire_max_frag));
2421 			}
2422 			/* Record the new max frag size for the ULP. */
2423 			icmph->icmph_du_zero = 0;
2424 			icmph->icmph_du_mtu =
2425 			    htons((uint16_t)ire->ire_max_frag);
2426 		}
2427 		mutex_exit(&ire->ire_lock);
2428 	}
2429 	rw_exit(&first_ire->ire_bucket->irb_lock);
2430 	ire_refrele(first_ire);
2431 	return (B_TRUE);
2432 }
2433 
2434 /*
2435  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2436  * calls this function.
2437  */
2438 static mblk_t *
2439 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2440 {
2441 	ipha_t *ipha;
2442 	icmph_t *icmph;
2443 	ipha_t *in_ipha;
2444 	int length;
2445 
2446 	ASSERT(mp->b_datap->db_type == M_DATA);
2447 
2448 	/*
2449 	 * For Self-encapsulated packets, we added an extra IP header
2450 	 * without the options. Inner IP header is the one from which
2451 	 * the outer IP header was formed. Thus, we need to remove the
2452 	 * outer IP header. To do this, we pullup the whole message
2453 	 * and overlay whatever follows the outer IP header over the
2454 	 * outer IP header.
2455 	 */
2456 
2457 	if (!pullupmsg(mp, -1))
2458 		return (NULL);
2459 
2460 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2461 	ipha = (ipha_t *)&icmph[1];
2462 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2463 
2464 	/*
2465 	 * The length that we want to overlay is following the inner
2466 	 * IP header. Subtracting the IP header + icmp header + outer
2467 	 * IP header's length should give us the length that we want to
2468 	 * overlay.
2469 	 */
2470 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2471 	    hdr_length;
2472 	/*
2473 	 * Overlay whatever follows the inner header over the
2474 	 * outer header.
2475 	 */
2476 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2477 
2478 	/* Set the wptr to account for the outer header */
2479 	mp->b_wptr -= hdr_length;
2480 	return (mp);
2481 }
2482 
2483 /*
2484  * Try to pass the ICMP message upstream in case the ULP cares.
2485  *
2486  * If the packet that caused the ICMP error is secure, we send
2487  * it to AH/ESP to make sure that the attached packet has a
2488  * valid association. ipha in the code below points to the
2489  * IP header of the packet that caused the error.
2490  *
2491  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2492  * in the context of IPSEC. Normally we tell the upper layer
2493  * whenever we send the ire (including ip_bind), the IPSEC header
2494  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2495  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2496  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2497  * same thing. As TCP has the IPSEC options size that needs to be
2498  * adjusted, we just pass the MTU unchanged.
2499  *
2500  * IFN could have been generated locally or by some router.
2501  *
2502  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2503  *	    This happens because IP adjusted its value of MTU on an
2504  *	    earlier IFN message and could not tell the upper layer,
2505  *	    the new adjusted value of MTU e.g. Packet was encrypted
2506  *	    or there was not enough information to fanout to upper
2507  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2508  *	    generates the IFN, where IPSEC processing has *not* been
2509  *	    done.
2510  *
2511  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2512  *	    could have generated this. This happens because ire_max_frag
2513  *	    value in IP was set to a new value, while the IPSEC processing
2514  *	    was being done and after we made the fragmentation check in
2515  *	    ip_wput_ire. Thus on return from IPSEC processing,
2516  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2517  *	    and generates the IFN. As IPSEC processing is over, we fanout
2518  *	    to AH/ESP to remove the header.
2519  *
2520  *	    In both these cases, ipsec_in_loopback will be set indicating
2521  *	    that IFN was generated locally.
2522  *
2523  * ROUTER : IFN could be secure or non-secure.
2524  *
2525  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2526  *	      packet in error has AH/ESP headers to validate the AH/ESP
2527  *	      headers. AH/ESP will verify whether there is a valid SA or
2528  *	      not and send it back. We will fanout again if we have more
2529  *	      data in the packet.
2530  *
2531  *	      If the packet in error does not have AH/ESP, we handle it
2532  *	      like any other case.
2533  *
2534  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2535  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2536  *	      for validation. AH/ESP will verify whether there is a
2537  *	      valid SA or not and send it back. We will fanout again if
2538  *	      we have more data in the packet.
2539  *
2540  *	      If the packet in error does not have AH/ESP, we handle it
2541  *	      like any other case.
2542  */
2543 static void
2544 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2545     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2546     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2547     zoneid_t zoneid)
2548 {
2549 	uint16_t *up;	/* Pointer to ports in ULP header */
2550 	uint32_t ports;	/* reversed ports for fanout */
2551 	ipha_t ripha;	/* With reversed addresses */
2552 	mblk_t *first_mp;
2553 	ipsec_in_t *ii;
2554 	tcph_t	*tcph;
2555 	conn_t	*connp;
2556 
2557 	ASSERT(ill != NULL);
2558 
2559 	first_mp = mp;
2560 	if (mctl_present) {
2561 		mp = first_mp->b_cont;
2562 		ASSERT(mp != NULL);
2563 
2564 		ii = (ipsec_in_t *)first_mp->b_rptr;
2565 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2566 	} else {
2567 		ii = NULL;
2568 	}
2569 
2570 	switch (ipha->ipha_protocol) {
2571 	case IPPROTO_UDP:
2572 		/*
2573 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2574 		 * transport header.
2575 		 */
2576 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2577 		    mp->b_wptr) {
2578 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2579 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2580 				goto discard_pkt;
2581 			}
2582 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2583 			ipha = (ipha_t *)&icmph[1];
2584 		}
2585 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2586 
2587 		/*
2588 		 * Attempt to find a client stream based on port.
2589 		 * Note that we do a reverse lookup since the header is
2590 		 * in the form we sent it out.
2591 		 * The ripha header is only used for the IP_UDP_MATCH and we
2592 		 * only set the src and dst addresses and protocol.
2593 		 */
2594 		ripha.ipha_src = ipha->ipha_dst;
2595 		ripha.ipha_dst = ipha->ipha_src;
2596 		ripha.ipha_protocol = ipha->ipha_protocol;
2597 		((uint16_t *)&ports)[0] = up[1];
2598 		((uint16_t *)&ports)[1] = up[0];
2599 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2600 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2601 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2602 		    icmph->icmph_type, icmph->icmph_code));
2603 
2604 		/* Have to change db_type after any pullupmsg */
2605 		DB_TYPE(mp) = M_CTL;
2606 
2607 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2608 		    mctl_present, ip_policy, recv_ill, zoneid);
2609 		return;
2610 
2611 	case IPPROTO_TCP:
2612 		/*
2613 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2614 		 * transport header.
2615 		 */
2616 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2617 		    mp->b_wptr) {
2618 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2619 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2620 				goto discard_pkt;
2621 			}
2622 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2623 			ipha = (ipha_t *)&icmph[1];
2624 		}
2625 		/*
2626 		 * Find a TCP client stream for this packet.
2627 		 * Note that we do a reverse lookup since the header is
2628 		 * in the form we sent it out.
2629 		 */
2630 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2631 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2632 		if (connp == NULL)
2633 			goto discard_pkt;
2634 
2635 		/* Have to change db_type after any pullupmsg */
2636 		DB_TYPE(mp) = M_CTL;
2637 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2638 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2639 		return;
2640 
2641 	case IPPROTO_SCTP:
2642 		/*
2643 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2644 		 * transport header.
2645 		 */
2646 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2647 		    mp->b_wptr) {
2648 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2649 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2650 				goto discard_pkt;
2651 			}
2652 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2653 			ipha = (ipha_t *)&icmph[1];
2654 		}
2655 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2656 		/*
2657 		 * Find a SCTP client stream for this packet.
2658 		 * Note that we do a reverse lookup since the header is
2659 		 * in the form we sent it out.
2660 		 * The ripha header is only used for the matching and we
2661 		 * only set the src and dst addresses, protocol, and version.
2662 		 */
2663 		ripha.ipha_src = ipha->ipha_dst;
2664 		ripha.ipha_dst = ipha->ipha_src;
2665 		ripha.ipha_protocol = ipha->ipha_protocol;
2666 		ripha.ipha_version_and_hdr_length =
2667 		    ipha->ipha_version_and_hdr_length;
2668 		((uint16_t *)&ports)[0] = up[1];
2669 		((uint16_t *)&ports)[1] = up[0];
2670 
2671 		/* Have to change db_type after any pullupmsg */
2672 		DB_TYPE(mp) = M_CTL;
2673 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2674 		    mctl_present, ip_policy, 0, zoneid);
2675 		return;
2676 
2677 	case IPPROTO_ESP:
2678 	case IPPROTO_AH: {
2679 		int ipsec_rc;
2680 
2681 		/*
2682 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2683 		 * We will re-use the IPSEC_IN if it is already present as
2684 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2685 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2686 		 * one and attach it in the front.
2687 		 */
2688 		if (ii != NULL) {
2689 			/*
2690 			 * ip_fanout_proto_again converts the ICMP errors
2691 			 * that come back from AH/ESP to M_DATA so that
2692 			 * if it is non-AH/ESP and we do a pullupmsg in
2693 			 * this function, it would work. Convert it back
2694 			 * to M_CTL before we send up as this is a ICMP
2695 			 * error. This could have been generated locally or
2696 			 * by some router. Validate the inner IPSEC
2697 			 * headers.
2698 			 *
2699 			 * NOTE : ill_index is used by ip_fanout_proto_again
2700 			 * to locate the ill.
2701 			 */
2702 			ASSERT(ill != NULL);
2703 			ii->ipsec_in_ill_index =
2704 			    ill->ill_phyint->phyint_ifindex;
2705 			ii->ipsec_in_rill_index =
2706 			    recv_ill->ill_phyint->phyint_ifindex;
2707 			DB_TYPE(first_mp->b_cont) = M_CTL;
2708 		} else {
2709 			/*
2710 			 * IPSEC_IN is not present. We attach a ipsec_in
2711 			 * message and send up to IPSEC for validating
2712 			 * and removing the IPSEC headers. Clear
2713 			 * ipsec_in_secure so that when we return
2714 			 * from IPSEC, we don't mistakenly think that this
2715 			 * is a secure packet came from the network.
2716 			 *
2717 			 * NOTE : ill_index is used by ip_fanout_proto_again
2718 			 * to locate the ill.
2719 			 */
2720 			ASSERT(first_mp == mp);
2721 			first_mp = ipsec_in_alloc(B_TRUE);
2722 			if (first_mp == NULL) {
2723 				freemsg(mp);
2724 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2725 				return;
2726 			}
2727 			ii = (ipsec_in_t *)first_mp->b_rptr;
2728 
2729 			/* This is not a secure packet */
2730 			ii->ipsec_in_secure = B_FALSE;
2731 			first_mp->b_cont = mp;
2732 			DB_TYPE(mp) = M_CTL;
2733 			ASSERT(ill != NULL);
2734 			ii->ipsec_in_ill_index =
2735 			    ill->ill_phyint->phyint_ifindex;
2736 			ii->ipsec_in_rill_index =
2737 			    recv_ill->ill_phyint->phyint_ifindex;
2738 		}
2739 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2740 
2741 		if (!ipsec_loaded()) {
2742 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2743 			return;
2744 		}
2745 
2746 		if (ipha->ipha_protocol == IPPROTO_ESP)
2747 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2748 		else
2749 			ipsec_rc = ipsecah_icmp_error(first_mp);
2750 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2751 			return;
2752 
2753 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2754 		return;
2755 	}
2756 	default:
2757 		/*
2758 		 * The ripha header is only used for the lookup and we
2759 		 * only set the src and dst addresses and protocol.
2760 		 */
2761 		ripha.ipha_src = ipha->ipha_dst;
2762 		ripha.ipha_dst = ipha->ipha_src;
2763 		ripha.ipha_protocol = ipha->ipha_protocol;
2764 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2765 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2766 		    ntohl(ipha->ipha_dst),
2767 		    icmph->icmph_type, icmph->icmph_code));
2768 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2769 			ipha_t *in_ipha;
2770 
2771 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2772 			    mp->b_wptr) {
2773 				if (!pullupmsg(mp, (uchar_t *)ipha +
2774 				    hdr_length + sizeof (ipha_t) -
2775 				    mp->b_rptr)) {
2776 					goto discard_pkt;
2777 				}
2778 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2779 				ipha = (ipha_t *)&icmph[1];
2780 			}
2781 			/*
2782 			 * Caller has verified that length has to be
2783 			 * at least the size of IP header.
2784 			 */
2785 			ASSERT(hdr_length >= sizeof (ipha_t));
2786 			/*
2787 			 * Check the sanity of the inner IP header like
2788 			 * we did for the outer header.
2789 			 */
2790 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2791 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2792 				goto discard_pkt;
2793 			}
2794 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2795 				goto discard_pkt;
2796 			}
2797 			/* Check for Self-encapsulated tunnels */
2798 			if (in_ipha->ipha_src == ipha->ipha_src &&
2799 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2800 
2801 				mp = icmp_inbound_self_encap_error(mp,
2802 				    iph_hdr_length, hdr_length);
2803 				if (mp == NULL)
2804 					goto discard_pkt;
2805 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2806 				ipha = (ipha_t *)&icmph[1];
2807 				hdr_length = IPH_HDR_LENGTH(ipha);
2808 				/*
2809 				 * The packet in error is self-encapsualted.
2810 				 * And we are finding it further encapsulated
2811 				 * which we could not have possibly generated.
2812 				 */
2813 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2814 					goto discard_pkt;
2815 				}
2816 				icmp_inbound_error_fanout(q, ill, first_mp,
2817 				    icmph, ipha, iph_hdr_length, hdr_length,
2818 				    mctl_present, ip_policy, recv_ill, zoneid);
2819 				return;
2820 			}
2821 		}
2822 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2823 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2824 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2825 		    ii != NULL &&
2826 		    ii->ipsec_in_loopback &&
2827 		    ii->ipsec_in_secure) {
2828 			/*
2829 			 * For IP tunnels that get a looped-back
2830 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2831 			 * reported new MTU to take into account the IPsec
2832 			 * headers protecting this configured tunnel.
2833 			 *
2834 			 * This allows the tunnel module (tun.c) to blindly
2835 			 * accept the MTU reported in an ICMP "too big"
2836 			 * message.
2837 			 *
2838 			 * Non-looped back ICMP messages will just be
2839 			 * handled by the security protocols (if needed),
2840 			 * and the first subsequent packet will hit this
2841 			 * path.
2842 			 */
2843 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2844 			    ipsec_in_extra_length(first_mp));
2845 		}
2846 		/* Have to change db_type after any pullupmsg */
2847 		DB_TYPE(mp) = M_CTL;
2848 
2849 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2850 		    ip_policy, recv_ill, zoneid);
2851 		return;
2852 	}
2853 	/* NOTREACHED */
2854 discard_pkt:
2855 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2856 drop_pkt:;
2857 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2858 	freemsg(first_mp);
2859 }
2860 
2861 /*
2862  * Common IP options parser.
2863  *
2864  * Setup routine: fill in *optp with options-parsing state, then
2865  * tail-call ipoptp_next to return the first option.
2866  */
2867 uint8_t
2868 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2869 {
2870 	uint32_t totallen; /* total length of all options */
2871 
2872 	totallen = ipha->ipha_version_and_hdr_length -
2873 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2874 	totallen <<= 2;
2875 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2876 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2877 	optp->ipoptp_flags = 0;
2878 	return (ipoptp_next(optp));
2879 }
2880 
2881 /*
2882  * Common IP options parser: extract next option.
2883  */
2884 uint8_t
2885 ipoptp_next(ipoptp_t *optp)
2886 {
2887 	uint8_t *end = optp->ipoptp_end;
2888 	uint8_t *cur = optp->ipoptp_next;
2889 	uint8_t opt, len, pointer;
2890 
2891 	/*
2892 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2893 	 * has been corrupted.
2894 	 */
2895 	ASSERT(cur <= end);
2896 
2897 	if (cur == end)
2898 		return (IPOPT_EOL);
2899 
2900 	opt = cur[IPOPT_OPTVAL];
2901 
2902 	/*
2903 	 * Skip any NOP options.
2904 	 */
2905 	while (opt == IPOPT_NOP) {
2906 		cur++;
2907 		if (cur == end)
2908 			return (IPOPT_EOL);
2909 		opt = cur[IPOPT_OPTVAL];
2910 	}
2911 
2912 	if (opt == IPOPT_EOL)
2913 		return (IPOPT_EOL);
2914 
2915 	/*
2916 	 * Option requiring a length.
2917 	 */
2918 	if ((cur + 1) >= end) {
2919 		optp->ipoptp_flags |= IPOPTP_ERROR;
2920 		return (IPOPT_EOL);
2921 	}
2922 	len = cur[IPOPT_OLEN];
2923 	if (len < 2) {
2924 		optp->ipoptp_flags |= IPOPTP_ERROR;
2925 		return (IPOPT_EOL);
2926 	}
2927 	optp->ipoptp_cur = cur;
2928 	optp->ipoptp_len = len;
2929 	optp->ipoptp_next = cur + len;
2930 	if (cur + len > end) {
2931 		optp->ipoptp_flags |= IPOPTP_ERROR;
2932 		return (IPOPT_EOL);
2933 	}
2934 
2935 	/*
2936 	 * For the options which require a pointer field, make sure
2937 	 * its there, and make sure it points to either something
2938 	 * inside this option, or the end of the option.
2939 	 */
2940 	switch (opt) {
2941 	case IPOPT_RR:
2942 	case IPOPT_TS:
2943 	case IPOPT_LSRR:
2944 	case IPOPT_SSRR:
2945 		if (len <= IPOPT_OFFSET) {
2946 			optp->ipoptp_flags |= IPOPTP_ERROR;
2947 			return (opt);
2948 		}
2949 		pointer = cur[IPOPT_OFFSET];
2950 		if (pointer - 1 > len) {
2951 			optp->ipoptp_flags |= IPOPTP_ERROR;
2952 			return (opt);
2953 		}
2954 		break;
2955 	}
2956 
2957 	/*
2958 	 * Sanity check the pointer field based on the type of the
2959 	 * option.
2960 	 */
2961 	switch (opt) {
2962 	case IPOPT_RR:
2963 	case IPOPT_SSRR:
2964 	case IPOPT_LSRR:
2965 		if (pointer < IPOPT_MINOFF_SR)
2966 			optp->ipoptp_flags |= IPOPTP_ERROR;
2967 		break;
2968 	case IPOPT_TS:
2969 		if (pointer < IPOPT_MINOFF_IT)
2970 			optp->ipoptp_flags |= IPOPTP_ERROR;
2971 		/*
2972 		 * Note that the Internet Timestamp option also
2973 		 * contains two four bit fields (the Overflow field,
2974 		 * and the Flag field), which follow the pointer
2975 		 * field.  We don't need to check that these fields
2976 		 * fall within the length of the option because this
2977 		 * was implicitely done above.  We've checked that the
2978 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2979 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2980 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2981 		 */
2982 		ASSERT(len > IPOPT_POS_OV_FLG);
2983 		break;
2984 	}
2985 
2986 	return (opt);
2987 }
2988 
2989 /*
2990  * Use the outgoing IP header to create an IP_OPTIONS option the way
2991  * it was passed down from the application.
2992  */
2993 int
2994 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2995 {
2996 	ipoptp_t	opts;
2997 	const uchar_t	*opt;
2998 	uint8_t		optval;
2999 	uint8_t		optlen;
3000 	uint32_t	len = 0;
3001 	uchar_t	*buf1 = buf;
3002 
3003 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
3004 	len += IP_ADDR_LEN;
3005 	bzero(buf1, IP_ADDR_LEN);
3006 
3007 	/*
3008 	 * OK to cast away const here, as we don't store through the returned
3009 	 * opts.ipoptp_cur pointer.
3010 	 */
3011 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
3012 	    optval != IPOPT_EOL;
3013 	    optval = ipoptp_next(&opts)) {
3014 		int	off;
3015 
3016 		opt = opts.ipoptp_cur;
3017 		optlen = opts.ipoptp_len;
3018 		switch (optval) {
3019 		case IPOPT_SSRR:
3020 		case IPOPT_LSRR:
3021 
3022 			/*
3023 			 * Insert ipha_dst as the first entry in the source
3024 			 * route and move down the entries on step.
3025 			 * The last entry gets placed at buf1.
3026 			 */
3027 			buf[IPOPT_OPTVAL] = optval;
3028 			buf[IPOPT_OLEN] = optlen;
3029 			buf[IPOPT_OFFSET] = optlen;
3030 
3031 			off = optlen - IP_ADDR_LEN;
3032 			if (off < 0) {
3033 				/* No entries in source route */
3034 				break;
3035 			}
3036 			/* Last entry in source route */
3037 			bcopy(opt + off, buf1, IP_ADDR_LEN);
3038 			off -= IP_ADDR_LEN;
3039 
3040 			while (off > 0) {
3041 				bcopy(opt + off,
3042 				    buf + off + IP_ADDR_LEN,
3043 				    IP_ADDR_LEN);
3044 				off -= IP_ADDR_LEN;
3045 			}
3046 			/* ipha_dst into first slot */
3047 			bcopy(&ipha->ipha_dst,
3048 			    buf + off + IP_ADDR_LEN,
3049 			    IP_ADDR_LEN);
3050 			buf += optlen;
3051 			len += optlen;
3052 			break;
3053 
3054 		case IPOPT_COMSEC:
3055 		case IPOPT_SECURITY:
3056 			/* if passing up a label is not ok, then remove */
3057 			if (is_system_labeled())
3058 				break;
3059 			/* FALLTHROUGH */
3060 		default:
3061 			bcopy(opt, buf, optlen);
3062 			buf += optlen;
3063 			len += optlen;
3064 			break;
3065 		}
3066 	}
3067 done:
3068 	/* Pad the resulting options */
3069 	while (len & 0x3) {
3070 		*buf++ = IPOPT_EOL;
3071 		len++;
3072 	}
3073 	return (len);
3074 }
3075 
3076 /*
3077  * Update any record route or timestamp options to include this host.
3078  * Reverse any source route option.
3079  * This routine assumes that the options are well formed i.e. that they
3080  * have already been checked.
3081  */
3082 static void
3083 icmp_options_update(ipha_t *ipha)
3084 {
3085 	ipoptp_t	opts;
3086 	uchar_t		*opt;
3087 	uint8_t		optval;
3088 	ipaddr_t	src;		/* Our local address */
3089 	ipaddr_t	dst;
3090 
3091 	ip2dbg(("icmp_options_update\n"));
3092 	src = ipha->ipha_src;
3093 	dst = ipha->ipha_dst;
3094 
3095 	for (optval = ipoptp_first(&opts, ipha);
3096 	    optval != IPOPT_EOL;
3097 	    optval = ipoptp_next(&opts)) {
3098 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3099 		opt = opts.ipoptp_cur;
3100 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3101 		    optval, opts.ipoptp_len));
3102 		switch (optval) {
3103 			int off1, off2;
3104 		case IPOPT_SSRR:
3105 		case IPOPT_LSRR:
3106 			/*
3107 			 * Reverse the source route.  The first entry
3108 			 * should be the next to last one in the current
3109 			 * source route (the last entry is our address).
3110 			 * The last entry should be the final destination.
3111 			 */
3112 			off1 = IPOPT_MINOFF_SR - 1;
3113 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3114 			if (off2 < 0) {
3115 				/* No entries in source route */
3116 				ip1dbg((
3117 				    "icmp_options_update: bad src route\n"));
3118 				break;
3119 			}
3120 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3121 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3122 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3123 			off2 -= IP_ADDR_LEN;
3124 
3125 			while (off1 < off2) {
3126 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3127 				bcopy((char *)opt + off2, (char *)opt + off1,
3128 				    IP_ADDR_LEN);
3129 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3130 				off1 += IP_ADDR_LEN;
3131 				off2 -= IP_ADDR_LEN;
3132 			}
3133 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3134 			break;
3135 		}
3136 	}
3137 }
3138 
3139 /*
3140  * Process received ICMP Redirect messages.
3141  */
3142 /* ARGSUSED */
3143 static void
3144 icmp_redirect(mblk_t *mp)
3145 {
3146 	ipha_t	*ipha;
3147 	int	iph_hdr_length;
3148 	icmph_t	*icmph;
3149 	ipha_t	*ipha_err;
3150 	ire_t	*ire;
3151 	ire_t	*prev_ire;
3152 	ire_t	*save_ire;
3153 	ipaddr_t  src, dst, gateway;
3154 	iulp_t	ulp_info = { 0 };
3155 	int	error;
3156 
3157 	ipha = (ipha_t *)mp->b_rptr;
3158 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3159 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3160 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3161 		BUMP_MIB(&icmp_mib, icmpInErrors);
3162 		freemsg(mp);
3163 		return;
3164 	}
3165 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3166 	ipha_err = (ipha_t *)&icmph[1];
3167 	src = ipha->ipha_src;
3168 	dst = ipha_err->ipha_dst;
3169 	gateway = icmph->icmph_rd_gateway;
3170 	/* Make sure the new gateway is reachable somehow. */
3171 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3172 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3173 	/*
3174 	 * Make sure we had a route for the dest in question and that
3175 	 * that route was pointing to the old gateway (the source of the
3176 	 * redirect packet.)
3177 	 */
3178 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3179 	    NULL, MATCH_IRE_GW);
3180 	/*
3181 	 * Check that
3182 	 *	the redirect was not from ourselves
3183 	 *	the new gateway and the old gateway are directly reachable
3184 	 */
3185 	if (!prev_ire ||
3186 	    !ire ||
3187 	    ire->ire_type == IRE_LOCAL) {
3188 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3189 		freemsg(mp);
3190 		if (ire != NULL)
3191 			ire_refrele(ire);
3192 		if (prev_ire != NULL)
3193 			ire_refrele(prev_ire);
3194 		return;
3195 	}
3196 
3197 	/*
3198 	 * Should we use the old ULP info to create the new gateway?  From
3199 	 * a user's perspective, we should inherit the info so that it
3200 	 * is a "smooth" transition.  If we do not do that, then new
3201 	 * connections going thru the new gateway will have no route metrics,
3202 	 * which is counter-intuitive to user.  From a network point of
3203 	 * view, this may or may not make sense even though the new gateway
3204 	 * is still directly connected to us so the route metrics should not
3205 	 * change much.
3206 	 *
3207 	 * But if the old ire_uinfo is not initialized, we do another
3208 	 * recursive lookup on the dest using the new gateway.  There may
3209 	 * be a route to that.  If so, use it to initialize the redirect
3210 	 * route.
3211 	 */
3212 	if (prev_ire->ire_uinfo.iulp_set) {
3213 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3214 	} else {
3215 		ire_t *tmp_ire;
3216 		ire_t *sire;
3217 
3218 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3219 		    ALL_ZONES, 0, NULL,
3220 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3221 		if (sire != NULL) {
3222 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3223 			/*
3224 			 * If sire != NULL, ire_ftable_lookup() should not
3225 			 * return a NULL value.
3226 			 */
3227 			ASSERT(tmp_ire != NULL);
3228 			ire_refrele(tmp_ire);
3229 			ire_refrele(sire);
3230 		} else if (tmp_ire != NULL) {
3231 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3232 			    sizeof (iulp_t));
3233 			ire_refrele(tmp_ire);
3234 		}
3235 	}
3236 	if (prev_ire->ire_type == IRE_CACHE)
3237 		ire_delete(prev_ire);
3238 	ire_refrele(prev_ire);
3239 	/*
3240 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3241 	 * require TOS routing
3242 	 */
3243 	switch (icmph->icmph_code) {
3244 	case 0:
3245 	case 1:
3246 		/* TODO: TOS specificity for cases 2 and 3 */
3247 	case 2:
3248 	case 3:
3249 		break;
3250 	default:
3251 		freemsg(mp);
3252 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3253 		ire_refrele(ire);
3254 		return;
3255 	}
3256 	/*
3257 	 * Create a Route Association.  This will allow us to remember that
3258 	 * someone we believe told us to use the particular gateway.
3259 	 */
3260 	save_ire = ire;
3261 	ire = ire_create(
3262 		(uchar_t *)&dst,			/* dest addr */
3263 		(uchar_t *)&ip_g_all_ones,		/* mask */
3264 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3265 		(uchar_t *)&gateway,			/* gateway addr */
3266 		NULL,					/* no in_srcaddr */
3267 		&save_ire->ire_max_frag,		/* max frag */
3268 		NULL,					/* Fast Path header */
3269 		NULL,					/* no rfq */
3270 		NULL,					/* no stq */
3271 		IRE_HOST,
3272 		NULL,
3273 		NULL,
3274 		NULL,
3275 		0,
3276 		0,
3277 		0,
3278 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3279 		&ulp_info,
3280 		NULL,
3281 		NULL);
3282 
3283 	if (ire == NULL) {
3284 		freemsg(mp);
3285 		ire_refrele(save_ire);
3286 		return;
3287 	}
3288 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3289 	ire_refrele(save_ire);
3290 	atomic_inc_32(&ip_redirect_cnt);
3291 
3292 	if (error == 0) {
3293 		ire_refrele(ire);		/* Held in ire_add_v4 */
3294 		/* tell routing sockets that we received a redirect */
3295 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3296 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3297 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3298 	}
3299 
3300 	/*
3301 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3302 	 * This together with the added IRE has the effect of
3303 	 * modifying an existing redirect.
3304 	 */
3305 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3306 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3307 	if (prev_ire != NULL) {
3308 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3309 			ire_delete(prev_ire);
3310 		ire_refrele(prev_ire);
3311 	}
3312 
3313 	freemsg(mp);
3314 }
3315 
3316 /*
3317  * Generate an ICMP parameter problem message.
3318  */
3319 static void
3320 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid)
3321 {
3322 	icmph_t	icmph;
3323 	boolean_t mctl_present;
3324 	mblk_t *first_mp;
3325 
3326 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3327 
3328 	if (!(mp = icmp_pkt_err_ok(mp))) {
3329 		if (mctl_present)
3330 			freeb(first_mp);
3331 		return;
3332 	}
3333 
3334 	bzero(&icmph, sizeof (icmph_t));
3335 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3336 	icmph.icmph_pp_ptr = ptr;
3337 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3338 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3339 }
3340 
3341 /*
3342  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3343  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3344  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3345  * an icmp error packet can be sent.
3346  * Assigns an appropriate source address to the packet. If ipha_dst is
3347  * one of our addresses use it for source. Otherwise pick a source based
3348  * on a route lookup back to ipha_src.
3349  * Note that ipha_src must be set here since the
3350  * packet is likely to arrive on an ill queue in ip_wput() which will
3351  * not set a source address.
3352  */
3353 static void
3354 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3355     boolean_t mctl_present, zoneid_t zoneid)
3356 {
3357 	ipaddr_t dst;
3358 	icmph_t	*icmph;
3359 	ipha_t	*ipha;
3360 	uint_t	len_needed;
3361 	size_t	msg_len;
3362 	mblk_t	*mp1;
3363 	ipaddr_t src;
3364 	ire_t	*ire;
3365 	mblk_t *ipsec_mp;
3366 	ipsec_out_t	*io = NULL;
3367 	boolean_t xmit_if_on = B_FALSE;
3368 
3369 	if (mctl_present) {
3370 		/*
3371 		 * If it is :
3372 		 *
3373 		 * 1) a IPSEC_OUT, then this is caused by outbound
3374 		 *    datagram originating on this host. IPSEC processing
3375 		 *    may or may not have been done. Refer to comments above
3376 		 *    icmp_inbound_error_fanout for details.
3377 		 *
3378 		 * 2) a IPSEC_IN if we are generating a icmp_message
3379 		 *    for an incoming datagram destined for us i.e called
3380 		 *    from ip_fanout_send_icmp.
3381 		 */
3382 		ipsec_info_t *in;
3383 		ipsec_mp = mp;
3384 		mp = ipsec_mp->b_cont;
3385 
3386 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3387 		ipha = (ipha_t *)mp->b_rptr;
3388 
3389 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3390 		    in->ipsec_info_type == IPSEC_IN);
3391 
3392 		if (in->ipsec_info_type == IPSEC_IN) {
3393 			/*
3394 			 * Convert the IPSEC_IN to IPSEC_OUT.
3395 			 */
3396 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3397 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
3398 				return;
3399 			}
3400 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3401 		} else {
3402 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3403 			io = (ipsec_out_t *)in;
3404 			if (io->ipsec_out_xmit_if)
3405 				xmit_if_on = B_TRUE;
3406 			/*
3407 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3408 			 * ire lookup.
3409 			 */
3410 			io->ipsec_out_proc_begin = B_FALSE;
3411 		}
3412 		ASSERT(zoneid == io->ipsec_out_zoneid);
3413 		ASSERT(zoneid != ALL_ZONES);
3414 	} else {
3415 		/*
3416 		 * This is in clear. The icmp message we are building
3417 		 * here should go out in clear.
3418 		 *
3419 		 * Pardon the convolution of it all, but it's easier to
3420 		 * allocate a "use cleartext" IPSEC_IN message and convert
3421 		 * it than it is to allocate a new one.
3422 		 */
3423 		ipsec_in_t *ii;
3424 		ASSERT(DB_TYPE(mp) == M_DATA);
3425 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3426 			freemsg(mp);
3427 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
3428 			return;
3429 		}
3430 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3431 
3432 		/* This is not a secure packet */
3433 		ii->ipsec_in_secure = B_FALSE;
3434 		/*
3435 		 * For trusted extensions using a shared IP address we can
3436 		 * send using any zoneid.
3437 		 */
3438 		if (zoneid == ALL_ZONES)
3439 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3440 		else
3441 			ii->ipsec_in_zoneid = zoneid;
3442 		ipsec_mp->b_cont = mp;
3443 		ipha = (ipha_t *)mp->b_rptr;
3444 		/*
3445 		 * Convert the IPSEC_IN to IPSEC_OUT.
3446 		 */
3447 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3448 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
3449 			return;
3450 		}
3451 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3452 	}
3453 
3454 	/* Remember our eventual destination */
3455 	dst = ipha->ipha_src;
3456 
3457 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3458 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3459 	if (ire != NULL &&
3460 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3461 		src = ipha->ipha_dst;
3462 	} else if (!xmit_if_on) {
3463 		if (ire != NULL)
3464 			ire_refrele(ire);
3465 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3466 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3467 		if (ire == NULL) {
3468 			BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
3469 			freemsg(ipsec_mp);
3470 			return;
3471 		}
3472 		src = ire->ire_src_addr;
3473 	} else {
3474 		ipif_t	*ipif = NULL;
3475 		ill_t	*ill;
3476 		/*
3477 		 * This must be an ICMP error coming from
3478 		 * ip_mrtun_forward(). The src addr should
3479 		 * be equal to the IP-addr of the outgoing
3480 		 * interface.
3481 		 */
3482 		if (io == NULL) {
3483 			/* This is not a IPSEC_OUT type control msg */
3484 			BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
3485 			freemsg(ipsec_mp);
3486 			return;
3487 		}
3488 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3489 		    NULL, NULL, NULL, NULL);
3490 		if (ill != NULL) {
3491 			ipif = ipif_get_next_ipif(NULL, ill);
3492 			ill_refrele(ill);
3493 		}
3494 		if (ipif == NULL) {
3495 			BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
3496 			freemsg(ipsec_mp);
3497 			return;
3498 		}
3499 		src = ipif->ipif_src_addr;
3500 		ipif_refrele(ipif);
3501 	}
3502 
3503 	if (ire != NULL)
3504 		ire_refrele(ire);
3505 
3506 	/*
3507 	 * Check if we can send back more then 8 bytes in addition
3508 	 * to the IP header. We will include as much as 64 bytes.
3509 	 */
3510 	len_needed = IPH_HDR_LENGTH(ipha);
3511 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3512 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3513 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3514 	}
3515 	len_needed += ip_icmp_return;
3516 	msg_len = msgdsize(mp);
3517 	if (msg_len > len_needed) {
3518 		(void) adjmsg(mp, len_needed - msg_len);
3519 		msg_len = len_needed;
3520 	}
3521 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3522 	if (mp1 == NULL) {
3523 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3524 		freemsg(ipsec_mp);
3525 		return;
3526 	}
3527 	/*
3528 	 * On an unlabeled system, dblks don't necessarily have creds.
3529 	 */
3530 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3531 	if (DB_CRED(mp) != NULL)
3532 		mblk_setcred(mp1, DB_CRED(mp));
3533 	mp1->b_cont = mp;
3534 	mp = mp1;
3535 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3536 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3537 	    io->ipsec_out_type == IPSEC_OUT);
3538 	ipsec_mp->b_cont = mp;
3539 
3540 	/*
3541 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3542 	 * node generates be accepted in peace by all on-host destinations.
3543 	 * If we do NOT assume that all on-host destinations trust
3544 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3545 	 * (Look for ipsec_out_icmp_loopback).
3546 	 */
3547 	io->ipsec_out_icmp_loopback = B_TRUE;
3548 
3549 	ipha = (ipha_t *)mp->b_rptr;
3550 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3551 	*ipha = icmp_ipha;
3552 	ipha->ipha_src = src;
3553 	ipha->ipha_dst = dst;
3554 	ipha->ipha_ttl = ip_def_ttl;
3555 	msg_len += sizeof (icmp_ipha) + len;
3556 	if (msg_len > IP_MAXPACKET) {
3557 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3558 		msg_len = IP_MAXPACKET;
3559 	}
3560 	ipha->ipha_length = htons((uint16_t)msg_len);
3561 	icmph = (icmph_t *)&ipha[1];
3562 	bcopy(stuff, icmph, len);
3563 	icmph->icmph_checksum = 0;
3564 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3565 	if (icmph->icmph_checksum == 0)
3566 		icmph->icmph_checksum = 0xFFFF;
3567 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3568 	put(q, ipsec_mp);
3569 }
3570 
3571 /*
3572  * Determine if an ICMP error packet can be sent given the rate limit.
3573  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3574  * in milliseconds) and a burst size. Burst size number of packets can
3575  * be sent arbitrarely closely spaced.
3576  * The state is tracked using two variables to implement an approximate
3577  * token bucket filter:
3578  *	icmp_pkt_err_last - lbolt value when the last burst started
3579  *	icmp_pkt_err_sent - number of packets sent in current burst
3580  */
3581 boolean_t
3582 icmp_err_rate_limit(void)
3583 {
3584 	clock_t now = TICK_TO_MSEC(lbolt);
3585 	uint_t refilled; /* Number of packets refilled in tbf since last */
3586 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3587 
3588 	if (err_interval == 0)
3589 		return (B_FALSE);
3590 
3591 	if (icmp_pkt_err_last > now) {
3592 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3593 		icmp_pkt_err_last = 0;
3594 		icmp_pkt_err_sent = 0;
3595 	}
3596 	/*
3597 	 * If we are in a burst update the token bucket filter.
3598 	 * Update the "last" time to be close to "now" but make sure
3599 	 * we don't loose precision.
3600 	 */
3601 	if (icmp_pkt_err_sent != 0) {
3602 		refilled = (now - icmp_pkt_err_last)/err_interval;
3603 		if (refilled > icmp_pkt_err_sent) {
3604 			icmp_pkt_err_sent = 0;
3605 		} else {
3606 			icmp_pkt_err_sent -= refilled;
3607 			icmp_pkt_err_last += refilled * err_interval;
3608 		}
3609 	}
3610 	if (icmp_pkt_err_sent == 0) {
3611 		/* Start of new burst */
3612 		icmp_pkt_err_last = now;
3613 	}
3614 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3615 		icmp_pkt_err_sent++;
3616 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3617 		    icmp_pkt_err_sent));
3618 		return (B_FALSE);
3619 	}
3620 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3621 	return (B_TRUE);
3622 }
3623 
3624 /*
3625  * Check if it is ok to send an IPv4 ICMP error packet in
3626  * response to the IPv4 packet in mp.
3627  * Free the message and return null if no
3628  * ICMP error packet should be sent.
3629  */
3630 static mblk_t *
3631 icmp_pkt_err_ok(mblk_t *mp)
3632 {
3633 	icmph_t	*icmph;
3634 	ipha_t	*ipha;
3635 	uint_t	len_needed;
3636 	ire_t	*src_ire;
3637 	ire_t	*dst_ire;
3638 
3639 	if (!mp)
3640 		return (NULL);
3641 	ipha = (ipha_t *)mp->b_rptr;
3642 	if (ip_csum_hdr(ipha)) {
3643 		BUMP_MIB(&ip_mib, ipIfStatsInCksumErrs);
3644 		freemsg(mp);
3645 		return (NULL);
3646 	}
3647 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3648 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3649 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3650 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3651 	if (src_ire != NULL || dst_ire != NULL ||
3652 	    CLASSD(ipha->ipha_dst) ||
3653 	    CLASSD(ipha->ipha_src) ||
3654 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3655 		/* Note: only errors to the fragment with offset 0 */
3656 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3657 		freemsg(mp);
3658 		if (src_ire != NULL)
3659 			ire_refrele(src_ire);
3660 		if (dst_ire != NULL)
3661 			ire_refrele(dst_ire);
3662 		return (NULL);
3663 	}
3664 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3665 		/*
3666 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3667 		 * errors in response to any ICMP errors.
3668 		 */
3669 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3670 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3671 			if (!pullupmsg(mp, len_needed)) {
3672 				BUMP_MIB(&icmp_mib, icmpInErrors);
3673 				freemsg(mp);
3674 				return (NULL);
3675 			}
3676 			ipha = (ipha_t *)mp->b_rptr;
3677 		}
3678 		icmph = (icmph_t *)
3679 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3680 		switch (icmph->icmph_type) {
3681 		case ICMP_DEST_UNREACHABLE:
3682 		case ICMP_SOURCE_QUENCH:
3683 		case ICMP_TIME_EXCEEDED:
3684 		case ICMP_PARAM_PROBLEM:
3685 		case ICMP_REDIRECT:
3686 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3687 			freemsg(mp);
3688 			return (NULL);
3689 		default:
3690 			break;
3691 		}
3692 	}
3693 	/*
3694 	 * If this is a labeled system, then check to see if we're allowed to
3695 	 * send a response to this particular sender.  If not, then just drop.
3696 	 */
3697 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3698 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3699 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3700 		freemsg(mp);
3701 		return (NULL);
3702 	}
3703 	if (icmp_err_rate_limit()) {
3704 		/*
3705 		 * Only send ICMP error packets every so often.
3706 		 * This should be done on a per port/source basis,
3707 		 * but for now this will suffice.
3708 		 */
3709 		freemsg(mp);
3710 		return (NULL);
3711 	}
3712 	return (mp);
3713 }
3714 
3715 /*
3716  * Generate an ICMP redirect message.
3717  */
3718 static void
3719 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3720 {
3721 	icmph_t	icmph;
3722 
3723 	/*
3724 	 * We are called from ip_rput where we could
3725 	 * not have attached an IPSEC_IN.
3726 	 */
3727 	ASSERT(mp->b_datap->db_type == M_DATA);
3728 
3729 	if (!(mp = icmp_pkt_err_ok(mp))) {
3730 		return;
3731 	}
3732 
3733 	bzero(&icmph, sizeof (icmph_t));
3734 	icmph.icmph_type = ICMP_REDIRECT;
3735 	icmph.icmph_code = 1;
3736 	icmph.icmph_rd_gateway = gateway;
3737 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3738 	/* Redirects sent by router, and router is global zone */
3739 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID);
3740 }
3741 
3742 /*
3743  * Generate an ICMP time exceeded message.
3744  */
3745 void
3746 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3747 {
3748 	icmph_t	icmph;
3749 	boolean_t mctl_present;
3750 	mblk_t *first_mp;
3751 
3752 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3753 
3754 	if (!(mp = icmp_pkt_err_ok(mp))) {
3755 		if (mctl_present)
3756 			freeb(first_mp);
3757 		return;
3758 	}
3759 
3760 	bzero(&icmph, sizeof (icmph_t));
3761 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3762 	icmph.icmph_code = code;
3763 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3764 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3765 }
3766 
3767 /*
3768  * Generate an ICMP unreachable message.
3769  */
3770 void
3771 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3772 {
3773 	icmph_t	icmph;
3774 	mblk_t *first_mp;
3775 	boolean_t mctl_present;
3776 
3777 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3778 
3779 	if (!(mp = icmp_pkt_err_ok(mp))) {
3780 		if (mctl_present)
3781 			freeb(first_mp);
3782 		return;
3783 	}
3784 
3785 	bzero(&icmph, sizeof (icmph_t));
3786 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3787 	icmph.icmph_code = code;
3788 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3789 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3790 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3791 	    zoneid);
3792 }
3793 
3794 /*
3795  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3796  * duplicate.  As long as someone else holds the address, the interface will
3797  * stay down.  When that conflict goes away, the interface is brought back up.
3798  * This is done so that accidental shutdowns of addresses aren't made
3799  * permanent.  Your server will recover from a failure.
3800  *
3801  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3802  * user space process (dhcpagent).
3803  *
3804  * Recovery completes if ARP reports that the address is now ours (via
3805  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3806  *
3807  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3808  */
3809 static void
3810 ipif_dup_recovery(void *arg)
3811 {
3812 	ipif_t *ipif = arg;
3813 	ill_t *ill = ipif->ipif_ill;
3814 	mblk_t *arp_add_mp;
3815 	mblk_t *arp_del_mp;
3816 	area_t *area;
3817 
3818 	ipif->ipif_recovery_id = 0;
3819 
3820 	/*
3821 	 * No lock needed for moving or condemned check, as this is just an
3822 	 * optimization.
3823 	 */
3824 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3825 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3826 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3827 		/* No reason to try to bring this address back. */
3828 		return;
3829 	}
3830 
3831 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3832 		goto alloc_fail;
3833 
3834 	if (ipif->ipif_arp_del_mp == NULL) {
3835 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3836 			goto alloc_fail;
3837 		ipif->ipif_arp_del_mp = arp_del_mp;
3838 	}
3839 
3840 	/* Setting the 'unverified' flag restarts DAD */
3841 	area = (area_t *)arp_add_mp->b_rptr;
3842 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3843 	    ACE_F_UNVERIFIED;
3844 	putnext(ill->ill_rq, arp_add_mp);
3845 	return;
3846 
3847 alloc_fail:
3848 	/*
3849 	 * On allocation failure, just restart the timer.  Note that the ipif
3850 	 * is down here, so no other thread could be trying to start a recovery
3851 	 * timer.  The ill_lock protects the condemned flag and the recovery
3852 	 * timer ID.
3853 	 */
3854 	freemsg(arp_add_mp);
3855 	mutex_enter(&ill->ill_lock);
3856 	if (ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3857 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3858 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3859 		    MSEC_TO_TICK(ip_dup_recovery));
3860 	}
3861 	mutex_exit(&ill->ill_lock);
3862 }
3863 
3864 /*
3865  * This is for exclusive changes due to ARP.  Either tear down an interface due
3866  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3867  */
3868 /* ARGSUSED */
3869 static void
3870 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3871 {
3872 	ill_t	*ill = rq->q_ptr;
3873 	arh_t *arh;
3874 	ipaddr_t src;
3875 	ipif_t	*ipif;
3876 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3877 	char hbuf[MAC_STR_LEN];
3878 	char sbuf[INET_ADDRSTRLEN];
3879 	const char *failtype;
3880 	boolean_t bring_up;
3881 
3882 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3883 	case AR_CN_READY:
3884 		failtype = NULL;
3885 		bring_up = B_TRUE;
3886 		break;
3887 	case AR_CN_FAILED:
3888 		failtype = "in use";
3889 		bring_up = B_FALSE;
3890 		break;
3891 	default:
3892 		failtype = "claimed";
3893 		bring_up = B_FALSE;
3894 		break;
3895 	}
3896 
3897 	arh = (arh_t *)mp->b_cont->b_rptr;
3898 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3899 
3900 	/* Handle failures due to probes */
3901 	if (src == 0) {
3902 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3903 		    IP_ADDR_LEN);
3904 	}
3905 
3906 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3907 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3908 	    sizeof (hbuf));
3909 	(void) ip_dot_addr(src, sbuf);
3910 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3911 
3912 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3913 		    ipif->ipif_lcl_addr != src) {
3914 			continue;
3915 		}
3916 
3917 		/*
3918 		 * If we failed on a recovery probe, then restart the timer to
3919 		 * try again later.
3920 		 */
3921 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3922 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3923 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3924 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3925 		    ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0) {
3926 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3927 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3928 			continue;
3929 		}
3930 
3931 		/*
3932 		 * If what we're trying to do has already been done, then do
3933 		 * nothing.
3934 		 */
3935 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3936 			continue;
3937 
3938 		if (ipif->ipif_id != 0) {
3939 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3940 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3941 			    ipif->ipif_id);
3942 		}
3943 		if (failtype == NULL) {
3944 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3945 			    ibuf);
3946 		} else {
3947 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3948 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3949 		}
3950 
3951 		if (bring_up) {
3952 			ASSERT(ill->ill_dl_up);
3953 			/*
3954 			 * Free up the ARP delete message so we can allocate
3955 			 * a fresh one through the normal path.
3956 			 */
3957 			freemsg(ipif->ipif_arp_del_mp);
3958 			ipif->ipif_arp_del_mp = NULL;
3959 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3960 			    EINPROGRESS) {
3961 				ipif->ipif_addr_ready = 1;
3962 				(void) ipif_up_done(ipif);
3963 			}
3964 			continue;
3965 		}
3966 
3967 		mutex_enter(&ill->ill_lock);
3968 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3969 		ipif->ipif_flags |= IPIF_DUPLICATE;
3970 		ill->ill_ipif_dup_count++;
3971 		mutex_exit(&ill->ill_lock);
3972 		/*
3973 		 * Already exclusive on the ill; no need to handle deferred
3974 		 * processing here.
3975 		 */
3976 		(void) ipif_down(ipif, NULL, NULL);
3977 		ipif_down_tail(ipif);
3978 		mutex_enter(&ill->ill_lock);
3979 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3980 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3981 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3982 		    ip_dup_recovery > 0) {
3983 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3984 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3985 		}
3986 		mutex_exit(&ill->ill_lock);
3987 	}
3988 	freemsg(mp);
3989 }
3990 
3991 /* ARGSUSED */
3992 static void
3993 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3994 {
3995 	ill_t	*ill = rq->q_ptr;
3996 	arh_t *arh;
3997 	ipaddr_t src;
3998 	ipif_t	*ipif;
3999 
4000 	arh = (arh_t *)mp->b_cont->b_rptr;
4001 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
4002 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
4003 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
4004 			(void) ipif_resolver_up(ipif, Res_act_defend);
4005 	}
4006 	freemsg(mp);
4007 }
4008 
4009 /*
4010  * News from ARP.  ARP sends notification of interesting events down
4011  * to its clients using M_CTL messages with the interesting ARP packet
4012  * attached via b_cont.
4013  * The interesting event from a device comes up the corresponding ARP-IP-DEV
4014  * queue as opposed to ARP sending the message to all the clients, i.e. all
4015  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
4016  * table if a cache IRE is found to delete all the entries for the address in
4017  * the packet.
4018  */
4019 static void
4020 ip_arp_news(queue_t *q, mblk_t *mp)
4021 {
4022 	arcn_t		*arcn;
4023 	arh_t		*arh;
4024 	ire_t		*ire = NULL;
4025 	char		hbuf[MAC_STR_LEN];
4026 	char		sbuf[INET_ADDRSTRLEN];
4027 	ipaddr_t	src;
4028 	in6_addr_t	v6src;
4029 	boolean_t	isv6 = B_FALSE;
4030 	ipif_t		*ipif;
4031 	ill_t		*ill;
4032 
4033 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
4034 		if (q->q_next) {
4035 			putnext(q, mp);
4036 		} else
4037 			freemsg(mp);
4038 		return;
4039 	}
4040 	arh = (arh_t *)mp->b_cont->b_rptr;
4041 	/* Is it one we are interested in? */
4042 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
4043 		isv6 = B_TRUE;
4044 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
4045 		    IPV6_ADDR_LEN);
4046 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
4047 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
4048 		    IP_ADDR_LEN);
4049 	} else {
4050 		freemsg(mp);
4051 		return;
4052 	}
4053 
4054 	ill = q->q_ptr;
4055 
4056 	arcn = (arcn_t *)mp->b_rptr;
4057 	switch (arcn->arcn_code) {
4058 	case AR_CN_BOGON:
4059 		/*
4060 		 * Someone is sending ARP packets with a source protocol
4061 		 * address that we have published and for which we believe our
4062 		 * entry is authoritative and (when ill_arp_extend is set)
4063 		 * verified to be unique on the network.
4064 		 *
4065 		 * The ARP module internally handles the cases where the sender
4066 		 * is just probing (for DAD) and where the hardware address of
4067 		 * a non-authoritative entry has changed.  Thus, these are the
4068 		 * real conflicts, and we have to do resolution.
4069 		 *
4070 		 * We back away quickly from the address if it's from DHCP or
4071 		 * otherwise temporary and hasn't been used recently (or at
4072 		 * all).  We'd like to include "deprecated" addresses here as
4073 		 * well (as there's no real reason to defend something we're
4074 		 * discarding), but IPMP "reuses" this flag to mean something
4075 		 * other than the standard meaning.
4076 		 *
4077 		 * If the ARP module above is not extended (meaning that it
4078 		 * doesn't know how to defend the address), then we just log
4079 		 * the problem as we always did and continue on.  It's not
4080 		 * right, but there's little else we can do, and those old ATM
4081 		 * users are going away anyway.
4082 		 */
4083 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4084 		    hbuf, sizeof (hbuf));
4085 		(void) ip_dot_addr(src, sbuf);
4086 		if (isv6)
4087 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
4088 		else
4089 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
4090 
4091 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4092 			uint32_t now;
4093 			uint32_t maxage;
4094 			clock_t lused;
4095 			uint_t maxdefense;
4096 			uint_t defs;
4097 
4098 			/*
4099 			 * First, figure out if this address hasn't been used
4100 			 * in a while.  If it hasn't, then it's a better
4101 			 * candidate for abandoning.
4102 			 */
4103 			ipif = ire->ire_ipif;
4104 			ASSERT(ipif != NULL);
4105 			now = gethrestime_sec();
4106 			maxage = now - ire->ire_create_time;
4107 			if (maxage > ip_max_temp_idle)
4108 				maxage = ip_max_temp_idle;
4109 			lused = drv_hztousec(ddi_get_lbolt() -
4110 			    ire->ire_last_used_time) / MICROSEC + 1;
4111 			if (lused >= maxage && (ipif->ipif_flags &
4112 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4113 				maxdefense = ip_max_temp_defend;
4114 			else
4115 				maxdefense = ip_max_defend;
4116 
4117 			/*
4118 			 * Now figure out how many times we've defended
4119 			 * ourselves.  Ignore defenses that happened long in
4120 			 * the past.
4121 			 */
4122 			mutex_enter(&ire->ire_lock);
4123 			if ((defs = ire->ire_defense_count) > 0 &&
4124 			    now - ire->ire_defense_time > ip_defend_interval) {
4125 				ire->ire_defense_count = defs = 0;
4126 			}
4127 			ire->ire_defense_count++;
4128 			ire->ire_defense_time = now;
4129 			mutex_exit(&ire->ire_lock);
4130 			ill_refhold(ill);
4131 			ire_refrele(ire);
4132 
4133 			/*
4134 			 * If we've defended ourselves too many times already,
4135 			 * then give up and tear down the interface(s) using
4136 			 * this address.  Otherwise, defend by sending out a
4137 			 * gratuitous ARP.
4138 			 */
4139 			if (defs >= maxdefense && ill->ill_arp_extend) {
4140 				(void) qwriter_ip(NULL, ill, q, mp,
4141 				    ip_arp_excl, CUR_OP, B_FALSE);
4142 			} else {
4143 				cmn_err(CE_WARN,
4144 				    "node %s is using our IP address %s on %s",
4145 				    hbuf, sbuf, ill->ill_name);
4146 				/*
4147 				 * If this is an old (ATM) ARP module, then
4148 				 * don't try to defend the address.  Remain
4149 				 * compatible with the old behavior.  Defend
4150 				 * only with new ARP.
4151 				 */
4152 				if (ill->ill_arp_extend) {
4153 					(void) qwriter_ip(NULL, ill, q, mp,
4154 					    ip_arp_defend, CUR_OP, B_FALSE);
4155 				} else {
4156 					ill_refrele(ill);
4157 				}
4158 			}
4159 			return;
4160 		}
4161 		cmn_err(CE_WARN,
4162 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4163 		    hbuf, sbuf, ill->ill_name);
4164 		if (ire != NULL)
4165 			ire_refrele(ire);
4166 		break;
4167 	case AR_CN_ANNOUNCE:
4168 		if (isv6) {
4169 			/*
4170 			 * For XRESOLV interfaces.
4171 			 * Delete the IRE cache entry and NCE for this
4172 			 * v6 address
4173 			 */
4174 			ip_ire_clookup_and_delete_v6(&v6src);
4175 			/*
4176 			 * If v6src is a non-zero, it's a router address
4177 			 * as below. Do the same sort of thing to clean
4178 			 * out off-net IRE_CACHE entries that go through
4179 			 * the router.
4180 			 */
4181 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4182 				ire_walk_v6(ire_delete_cache_gw_v6,
4183 				    (char *)&v6src, ALL_ZONES);
4184 			}
4185 		} else {
4186 			nce_hw_map_t hwm;
4187 
4188 			/*
4189 			 * ARP gives us a copy of any packet where it thinks
4190 			 * the address has changed, so that we can update our
4191 			 * caches.  We're responsible for caching known answers
4192 			 * in the current design.  We check whether the
4193 			 * hardware address really has changed in all of our
4194 			 * entries that have cached this mapping, and if so, we
4195 			 * blow them away.  This way we will immediately pick
4196 			 * up the rare case of a host changing hardware
4197 			 * address.
4198 			 */
4199 			if (src == 0)
4200 				break;
4201 			hwm.hwm_addr = src;
4202 			hwm.hwm_hwlen = arh->arh_hlen;
4203 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4204 			ndp_walk_common(&ndp4, NULL,
4205 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4206 		}
4207 		break;
4208 	case AR_CN_READY:
4209 		/* No external v6 resolver has a contract to use this */
4210 		if (isv6)
4211 			break;
4212 		/* If the link is down, we'll retry this later */
4213 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4214 			break;
4215 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4216 		    NULL, NULL);
4217 		if (ipif != NULL) {
4218 			/*
4219 			 * If this is a duplicate recovery, then we now need to
4220 			 * go exclusive to bring this thing back up.
4221 			 */
4222 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4223 			    IPIF_DUPLICATE) {
4224 				ipif_refrele(ipif);
4225 				ill_refhold(ill);
4226 				(void) qwriter_ip(NULL, ill, q, mp,
4227 				    ip_arp_excl, CUR_OP, B_FALSE);
4228 				return;
4229 			}
4230 			/*
4231 			 * If this is the first notice that this address is
4232 			 * ready, then let the user know now.
4233 			 */
4234 			if ((ipif->ipif_flags & IPIF_UP) &&
4235 			    !ipif->ipif_addr_ready) {
4236 				ipif_mask_reply(ipif);
4237 				ip_rts_ifmsg(ipif);
4238 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4239 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4240 			}
4241 			ipif->ipif_addr_ready = 1;
4242 			ipif_refrele(ipif);
4243 		}
4244 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp));
4245 		if (ire != NULL) {
4246 			ire->ire_defense_count = 0;
4247 			ire_refrele(ire);
4248 		}
4249 		break;
4250 	case AR_CN_FAILED:
4251 		/* No external v6 resolver has a contract to use this */
4252 		if (isv6)
4253 			break;
4254 		ill_refhold(ill);
4255 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4256 		    B_FALSE);
4257 		return;
4258 	}
4259 	freemsg(mp);
4260 }
4261 
4262 /*
4263  * Create a mblk suitable for carrying the interface index and/or source link
4264  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4265  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4266  * application.
4267  */
4268 mblk_t *
4269 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid)
4270 {
4271 	mblk_t		*mp;
4272 	ip_pktinfo_t	*pinfo;
4273 	ipha_t *ipha;
4274 	struct ether_header *pether;
4275 
4276 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4277 	if (mp == NULL) {
4278 		ip1dbg(("ip_add_info: allocation failure.\n"));
4279 		return (data_mp);
4280 	}
4281 
4282 	ipha	= (ipha_t *)data_mp->b_rptr;
4283 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4284 	bzero(pinfo, sizeof (ip_pktinfo_t));
4285 	pinfo->ip_pkt_flags = (uchar_t)flags;
4286 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4287 
4288 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4289 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4290 	if (flags & IPF_RECVADDR) {
4291 		ipif_t	*ipif;
4292 		ire_t	*ire;
4293 
4294 		/*
4295 		 * Only valid for V4
4296 		 */
4297 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4298 		    (IPV4_VERSION << 4));
4299 
4300 		ipif = ipif_get_next_ipif(NULL, ill);
4301 		if (ipif != NULL) {
4302 			/*
4303 			 * Since a decision has already been made to deliver the
4304 			 * packet, there is no need to test for SECATTR and
4305 			 * ZONEONLY.
4306 			 */
4307 			ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0, ipif,
4308 			    zoneid, NULL, MATCH_IRE_ILL_GROUP);
4309 			if (ire == NULL) {
4310 				/*
4311 				 * packet must have come on a different
4312 				 * interface.
4313 				 * Since a decision has already been made to
4314 				 * deliver the packet, there is no need to test
4315 				 * for SECATTR and ZONEONLY.
4316 				 */
4317 				ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0,
4318 				    ipif, zoneid, NULL, NULL);
4319 			}
4320 
4321 			if (ire == NULL) {
4322 				/*
4323 				 * This is either a multicast packet or
4324 				 * the address has been removed since
4325 				 * the packet was received.
4326 				 * Return INADDR_ANY so that normal source
4327 				 * selection occurs for the response.
4328 				 */
4329 
4330 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4331 			} else {
4332 				ASSERT(ire->ire_type != IRE_CACHE);
4333 				pinfo->ip_pkt_match_addr.s_addr =
4334 				    ire->ire_src_addr;
4335 				ire_refrele(ire);
4336 			}
4337 			ipif_refrele(ipif);
4338 		} else {
4339 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4340 		}
4341 	}
4342 
4343 	pether = (struct ether_header *)((char *)ipha
4344 	    - sizeof (struct ether_header));
4345 	/*
4346 	 * Make sure the interface is an ethernet type, since this option
4347 	 * is currently supported only on this type of interface. Also make
4348 	 * sure we are pointing correctly above db_base.
4349 	 */
4350 
4351 	if ((flags & IPF_RECVSLLA) &&
4352 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4353 	    (ill->ill_type == IFT_ETHER) &&
4354 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4355 
4356 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4357 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4358 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4359 	} else {
4360 		/*
4361 		 * Clear the bit. Indicate to upper layer that IP is not
4362 		 * sending this ancillary info.
4363 		 */
4364 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4365 	}
4366 
4367 	mp->b_datap->db_type = M_CTL;
4368 	mp->b_wptr += sizeof (ip_pktinfo_t);
4369 	mp->b_cont = data_mp;
4370 
4371 	return (mp);
4372 }
4373 
4374 /*
4375  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4376  * part of the bind request.
4377  */
4378 
4379 boolean_t
4380 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4381 {
4382 	ipsec_in_t *ii;
4383 
4384 	ASSERT(policy_mp != NULL);
4385 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4386 
4387 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4388 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4389 
4390 	connp->conn_policy = ii->ipsec_in_policy;
4391 	ii->ipsec_in_policy = NULL;
4392 
4393 	if (ii->ipsec_in_action != NULL) {
4394 		if (connp->conn_latch == NULL) {
4395 			connp->conn_latch = iplatch_create();
4396 			if (connp->conn_latch == NULL)
4397 				return (B_FALSE);
4398 		}
4399 		ipsec_latch_inbound(connp->conn_latch, ii);
4400 	}
4401 	return (B_TRUE);
4402 }
4403 
4404 /*
4405  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4406  * and to arrange for power-fanout assist.  The ULP is identified by
4407  * adding a single byte at the end of the original bind message.
4408  * A ULP other than UDP or TCP that wishes to be recognized passes
4409  * down a bind with a zero length address.
4410  *
4411  * The binding works as follows:
4412  * - A zero byte address means just bind to the protocol.
4413  * - A four byte address is treated as a request to validate
4414  *   that the address is a valid local address, appropriate for
4415  *   an application to bind to. This does not affect any fanout
4416  *   information in IP.
4417  * - A sizeof sin_t byte address is used to bind to only the local address
4418  *   and port.
4419  * - A sizeof ipa_conn_t byte address contains complete fanout information
4420  *   consisting of local and remote addresses and ports.  In
4421  *   this case, the addresses are both validated as appropriate
4422  *   for this operation, and, if so, the information is retained
4423  *   for use in the inbound fanout.
4424  *
4425  * The ULP (except in the zero-length bind) can append an
4426  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4427  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4428  * a copy of the source or destination IRE (source for local bind;
4429  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4430  * policy information contained should be copied on to the conn.
4431  *
4432  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4433  */
4434 mblk_t *
4435 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4436 {
4437 	ssize_t		len;
4438 	struct T_bind_req	*tbr;
4439 	sin_t		*sin;
4440 	ipa_conn_t	*ac;
4441 	uchar_t		*ucp;
4442 	mblk_t		*mp1;
4443 	boolean_t	ire_requested;
4444 	boolean_t	ipsec_policy_set = B_FALSE;
4445 	int		error = 0;
4446 	int		protocol;
4447 	ipa_conn_x_t	*acx;
4448 
4449 	ASSERT(!connp->conn_af_isv6);
4450 	connp->conn_pkt_isv6 = B_FALSE;
4451 
4452 	len = MBLKL(mp);
4453 	if (len < (sizeof (*tbr) + 1)) {
4454 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4455 		    "ip_bind: bogus msg, len %ld", len);
4456 		/* XXX: Need to return something better */
4457 		goto bad_addr;
4458 	}
4459 	/* Back up and extract the protocol identifier. */
4460 	mp->b_wptr--;
4461 	protocol = *mp->b_wptr & 0xFF;
4462 	tbr = (struct T_bind_req *)mp->b_rptr;
4463 	/* Reset the message type in preparation for shipping it back. */
4464 	DB_TYPE(mp) = M_PCPROTO;
4465 
4466 	connp->conn_ulp = (uint8_t)protocol;
4467 
4468 	/*
4469 	 * Check for a zero length address.  This is from a protocol that
4470 	 * wants to register to receive all packets of its type.
4471 	 */
4472 	if (tbr->ADDR_length == 0) {
4473 		/*
4474 		 * These protocols are now intercepted in ip_bind_v6().
4475 		 * Reject protocol-level binds here for now.
4476 		 *
4477 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4478 		 * so that the protocol type cannot be SCTP.
4479 		 */
4480 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4481 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4482 			goto bad_addr;
4483 		}
4484 
4485 		/*
4486 		 *
4487 		 * The udp module never sends down a zero-length address,
4488 		 * and allowing this on a labeled system will break MLP
4489 		 * functionality.
4490 		 */
4491 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4492 			goto bad_addr;
4493 
4494 		if (connp->conn_mac_exempt)
4495 			goto bad_addr;
4496 
4497 		/* No hash here really.  The table is big enough. */
4498 		connp->conn_srcv6 = ipv6_all_zeros;
4499 
4500 		ipcl_proto_insert(connp, protocol);
4501 
4502 		tbr->PRIM_type = T_BIND_ACK;
4503 		return (mp);
4504 	}
4505 
4506 	/* Extract the address pointer from the message. */
4507 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4508 	    tbr->ADDR_length);
4509 	if (ucp == NULL) {
4510 		ip1dbg(("ip_bind: no address\n"));
4511 		goto bad_addr;
4512 	}
4513 	if (!OK_32PTR(ucp)) {
4514 		ip1dbg(("ip_bind: unaligned address\n"));
4515 		goto bad_addr;
4516 	}
4517 	/*
4518 	 * Check for trailing mps.
4519 	 */
4520 
4521 	mp1 = mp->b_cont;
4522 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4523 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4524 
4525 	switch (tbr->ADDR_length) {
4526 	default:
4527 		ip1dbg(("ip_bind: bad address length %d\n",
4528 		    (int)tbr->ADDR_length));
4529 		goto bad_addr;
4530 
4531 	case IP_ADDR_LEN:
4532 		/* Verification of local address only */
4533 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4534 		    ire_requested, ipsec_policy_set, B_FALSE);
4535 		break;
4536 
4537 	case sizeof (sin_t):
4538 		sin = (sin_t *)ucp;
4539 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4540 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4541 		break;
4542 
4543 	case sizeof (ipa_conn_t):
4544 		ac = (ipa_conn_t *)ucp;
4545 		/* For raw socket, the local port is not set. */
4546 		if (ac->ac_lport == 0)
4547 			ac->ac_lport = connp->conn_lport;
4548 		/* Always verify destination reachability. */
4549 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4550 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4551 		    ipsec_policy_set, B_TRUE, B_TRUE);
4552 		break;
4553 
4554 	case sizeof (ipa_conn_x_t):
4555 		acx = (ipa_conn_x_t *)ucp;
4556 		/*
4557 		 * Whether or not to verify destination reachability depends
4558 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4559 		 */
4560 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4561 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4562 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4563 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4564 		break;
4565 	}
4566 	if (error == EINPROGRESS)
4567 		return (NULL);
4568 	else if (error != 0)
4569 		goto bad_addr;
4570 	/*
4571 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4572 	 * We can't do this in ip_bind_insert_ire because the policy
4573 	 * may not have been inherited at that point in time and hence
4574 	 * conn_out_enforce_policy may not be set.
4575 	 */
4576 	mp1 = mp->b_cont;
4577 	if (ire_requested && connp->conn_out_enforce_policy &&
4578 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4579 		ire_t *ire = (ire_t *)mp1->b_rptr;
4580 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4581 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4582 	}
4583 
4584 	/* Send it home. */
4585 	mp->b_datap->db_type = M_PCPROTO;
4586 	tbr->PRIM_type = T_BIND_ACK;
4587 	return (mp);
4588 
4589 bad_addr:
4590 	/*
4591 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4592 	 * a unix errno.
4593 	 */
4594 	if (error > 0)
4595 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4596 	else
4597 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4598 	return (mp);
4599 }
4600 
4601 /*
4602  * Here address is verified to be a valid local address.
4603  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4604  * address is also considered a valid local address.
4605  * In the case of a broadcast/multicast address, however, the
4606  * upper protocol is expected to reset the src address
4607  * to 0 if it sees a IRE_BROADCAST type returned so that
4608  * no packets are emitted with broadcast/multicast address as
4609  * source address (that violates hosts requirements RFC1122)
4610  * The addresses valid for bind are:
4611  *	(1) - INADDR_ANY (0)
4612  *	(2) - IP address of an UP interface
4613  *	(3) - IP address of a DOWN interface
4614  *	(4) - valid local IP broadcast addresses. In this case
4615  *	the conn will only receive packets destined to
4616  *	the specified broadcast address.
4617  *	(5) - a multicast address. In this case
4618  *	the conn will only receive packets destined to
4619  *	the specified multicast address. Note: the
4620  *	application still has to issue an
4621  *	IP_ADD_MEMBERSHIP socket option.
4622  *
4623  * On error, return -1 for TBADADDR otherwise pass the
4624  * errno with TSYSERR reply.
4625  *
4626  * In all the above cases, the bound address must be valid in the current zone.
4627  * When the address is loopback, multicast or broadcast, there might be many
4628  * matching IREs so bind has to look up based on the zone.
4629  *
4630  * Note: lport is in network byte order.
4631  */
4632 int
4633 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4634     boolean_t ire_requested, boolean_t ipsec_policy_set,
4635     boolean_t fanout_insert)
4636 {
4637 	int		error = 0;
4638 	ire_t		*src_ire;
4639 	mblk_t		*policy_mp;
4640 	ipif_t		*ipif;
4641 	zoneid_t	zoneid;
4642 
4643 	if (ipsec_policy_set) {
4644 		policy_mp = mp->b_cont;
4645 	}
4646 
4647 	/*
4648 	 * If it was previously connected, conn_fully_bound would have
4649 	 * been set.
4650 	 */
4651 	connp->conn_fully_bound = B_FALSE;
4652 
4653 	src_ire = NULL;
4654 	ipif = NULL;
4655 
4656 	zoneid = IPCL_ZONEID(connp);
4657 
4658 	if (src_addr) {
4659 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4660 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4661 		/*
4662 		 * If an address other than 0.0.0.0 is requested,
4663 		 * we verify that it is a valid address for bind
4664 		 * Note: Following code is in if-else-if form for
4665 		 * readability compared to a condition check.
4666 		 */
4667 		/* LINTED - statement has no consequent */
4668 		if (IRE_IS_LOCAL(src_ire)) {
4669 			/*
4670 			 * (2) Bind to address of local UP interface
4671 			 */
4672 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4673 			/*
4674 			 * (4) Bind to broadcast address
4675 			 * Note: permitted only from transports that
4676 			 * request IRE
4677 			 */
4678 			if (!ire_requested)
4679 				error = EADDRNOTAVAIL;
4680 		} else {
4681 			/*
4682 			 * (3) Bind to address of local DOWN interface
4683 			 * (ipif_lookup_addr() looks up all interfaces
4684 			 * but we do not get here for UP interfaces
4685 			 * - case (2) above)
4686 			 * We put the protocol byte back into the mblk
4687 			 * since we may come back via ip_wput_nondata()
4688 			 * later with this mblk if ipif_lookup_addr chooses
4689 			 * to defer processing.
4690 			 */
4691 			*mp->b_wptr++ = (char)connp->conn_ulp;
4692 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4693 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4694 			    &error)) != NULL) {
4695 				ipif_refrele(ipif);
4696 			} else if (error == EINPROGRESS) {
4697 				if (src_ire != NULL)
4698 					ire_refrele(src_ire);
4699 				return (EINPROGRESS);
4700 			} else if (CLASSD(src_addr)) {
4701 				error = 0;
4702 				if (src_ire != NULL)
4703 					ire_refrele(src_ire);
4704 				/*
4705 				 * (5) bind to multicast address.
4706 				 * Fake out the IRE returned to upper
4707 				 * layer to be a broadcast IRE.
4708 				 */
4709 				src_ire = ire_ctable_lookup(
4710 				    INADDR_BROADCAST, INADDR_ANY,
4711 				    IRE_BROADCAST, NULL, zoneid, NULL,
4712 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4713 				if (src_ire == NULL || !ire_requested)
4714 					error = EADDRNOTAVAIL;
4715 			} else {
4716 				/*
4717 				 * Not a valid address for bind
4718 				 */
4719 				error = EADDRNOTAVAIL;
4720 			}
4721 			/*
4722 			 * Just to keep it consistent with the processing in
4723 			 * ip_bind_v4()
4724 			 */
4725 			mp->b_wptr--;
4726 		}
4727 		if (error) {
4728 			/* Red Alert!  Attempting to be a bogon! */
4729 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4730 			    ntohl(src_addr)));
4731 			goto bad_addr;
4732 		}
4733 	}
4734 
4735 	/*
4736 	 * Allow setting new policies. For example, disconnects come
4737 	 * down as ipa_t bind. As we would have set conn_policy_cached
4738 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4739 	 * can change after the disconnect.
4740 	 */
4741 	connp->conn_policy_cached = B_FALSE;
4742 
4743 	/*
4744 	 * If not fanout_insert this was just an address verification
4745 	 */
4746 	if (fanout_insert) {
4747 		/*
4748 		 * The addresses have been verified. Time to insert in
4749 		 * the correct fanout list.
4750 		 */
4751 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4752 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4753 		connp->conn_lport = lport;
4754 		connp->conn_fport = 0;
4755 		/*
4756 		 * Do we need to add a check to reject Multicast packets
4757 		 *
4758 		 * We need to make sure that the conn_recv is set to a non-null
4759 		 * value before we insert the conn into the classifier table.
4760 		 * This is to avoid a race with an incoming packet which does an
4761 		 * ipcl_classify().
4762 		 */
4763 		if (*mp->b_wptr == IPPROTO_TCP)
4764 			connp->conn_recv = tcp_conn_request;
4765 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4766 	}
4767 
4768 	if (error == 0) {
4769 		if (ire_requested) {
4770 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4771 				error = -1;
4772 				/* Falls through to bad_addr */
4773 			}
4774 		} else if (ipsec_policy_set) {
4775 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4776 				error = -1;
4777 				/* Falls through to bad_addr */
4778 			}
4779 		}
4780 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4781 		connp->conn_recv = tcp_input;
4782 	}
4783 bad_addr:
4784 	if (error != 0) {
4785 		if (connp->conn_anon_port) {
4786 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4787 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4788 			    B_FALSE);
4789 		}
4790 		connp->conn_mlp_type = mlptSingle;
4791 	}
4792 	if (src_ire != NULL)
4793 		IRE_REFRELE(src_ire);
4794 	if (ipsec_policy_set) {
4795 		ASSERT(policy_mp == mp->b_cont);
4796 		ASSERT(policy_mp != NULL);
4797 		freeb(policy_mp);
4798 		/*
4799 		 * As of now assume that nothing else accompanies
4800 		 * IPSEC_POLICY_SET.
4801 		 */
4802 		mp->b_cont = NULL;
4803 	}
4804 	return (error);
4805 }
4806 
4807 /*
4808  * Verify that both the source and destination addresses
4809  * are valid.  If verify_dst is false, then the destination address may be
4810  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4811  * destination reachability, while tunnels do not.
4812  * Note that we allow connect to broadcast and multicast
4813  * addresses when ire_requested is set. Thus the ULP
4814  * has to check for IRE_BROADCAST and multicast.
4815  *
4816  * Returns zero if ok.
4817  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4818  * (for use with TSYSERR reply).
4819  *
4820  * Note: lport and fport are in network byte order.
4821  */
4822 int
4823 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4824     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4825     boolean_t ire_requested, boolean_t ipsec_policy_set,
4826     boolean_t fanout_insert, boolean_t verify_dst)
4827 {
4828 	ire_t		*src_ire;
4829 	ire_t		*dst_ire;
4830 	int		error = 0;
4831 	int 		protocol;
4832 	mblk_t		*policy_mp;
4833 	ire_t		*sire = NULL;
4834 	ire_t		*md_dst_ire = NULL;
4835 	ire_t		*lso_dst_ire = NULL;
4836 	ill_t		*ill = NULL;
4837 	zoneid_t	zoneid;
4838 	ipaddr_t	src_addr = *src_addrp;
4839 
4840 	src_ire = dst_ire = NULL;
4841 	protocol = *mp->b_wptr & 0xFF;
4842 
4843 	/*
4844 	 * If we never got a disconnect before, clear it now.
4845 	 */
4846 	connp->conn_fully_bound = B_FALSE;
4847 
4848 	if (ipsec_policy_set) {
4849 		policy_mp = mp->b_cont;
4850 	}
4851 
4852 	zoneid = IPCL_ZONEID(connp);
4853 
4854 	if (CLASSD(dst_addr)) {
4855 		/* Pick up an IRE_BROADCAST */
4856 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4857 		    NULL, zoneid, MBLK_GETLABEL(mp),
4858 		    (MATCH_IRE_RECURSIVE |
4859 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4860 		    MATCH_IRE_SECATTR));
4861 	} else {
4862 		/*
4863 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4864 		 * and onlink ipif is not found set ENETUNREACH error.
4865 		 */
4866 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4867 			ipif_t *ipif;
4868 
4869 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4870 			    dst_addr : connp->conn_nexthop_v4,
4871 			    connp->conn_zoneid);
4872 			if (ipif == NULL) {
4873 				error = ENETUNREACH;
4874 				goto bad_addr;
4875 			}
4876 			ipif_refrele(ipif);
4877 		}
4878 
4879 		if (connp->conn_nexthop_set) {
4880 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4881 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4882 			    MATCH_IRE_SECATTR);
4883 		} else {
4884 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4885 			    &sire, zoneid, MBLK_GETLABEL(mp),
4886 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4887 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4888 			    MATCH_IRE_SECATTR));
4889 		}
4890 	}
4891 	/*
4892 	 * dst_ire can't be a broadcast when not ire_requested.
4893 	 * We also prevent ire's with src address INADDR_ANY to
4894 	 * be used, which are created temporarily for
4895 	 * sending out packets from endpoints that have
4896 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4897 	 * reachable.  If verify_dst is false, the destination needn't be
4898 	 * reachable.
4899 	 *
4900 	 * If we match on a reject or black hole, then we've got a
4901 	 * local failure.  May as well fail out the connect() attempt,
4902 	 * since it's never going to succeed.
4903 	 */
4904 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4905 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4906 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4907 		/*
4908 		 * If we're verifying destination reachability, we always want
4909 		 * to complain here.
4910 		 *
4911 		 * If we're not verifying destination reachability but the
4912 		 * destination has a route, we still want to fail on the
4913 		 * temporary address and broadcast address tests.
4914 		 */
4915 		if (verify_dst || (dst_ire != NULL)) {
4916 			if (ip_debug > 2) {
4917 				pr_addr_dbg("ip_bind_connected: bad connected "
4918 				    "dst %s\n", AF_INET, &dst_addr);
4919 			}
4920 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4921 				error = ENETUNREACH;
4922 			else
4923 				error = EHOSTUNREACH;
4924 			goto bad_addr;
4925 		}
4926 	}
4927 
4928 	/*
4929 	 * We now know that routing will allow us to reach the destination.
4930 	 * Check whether Trusted Solaris policy allows communication with this
4931 	 * host, and pretend that the destination is unreachable if not.
4932 	 *
4933 	 * This is never a problem for TCP, since that transport is known to
4934 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4935 	 * handling.  If the remote is unreachable, it will be detected at that
4936 	 * point, so there's no reason to check it here.
4937 	 *
4938 	 * Note that for sendto (and other datagram-oriented friends), this
4939 	 * check is done as part of the data path label computation instead.
4940 	 * The check here is just to make non-TCP connect() report the right
4941 	 * error.
4942 	 */
4943 	if (dst_ire != NULL && is_system_labeled() &&
4944 	    !IPCL_IS_TCP(connp) &&
4945 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4946 	    connp->conn_mac_exempt) != 0) {
4947 		error = EHOSTUNREACH;
4948 		if (ip_debug > 2) {
4949 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4950 			    AF_INET, &dst_addr);
4951 		}
4952 		goto bad_addr;
4953 	}
4954 
4955 	/*
4956 	 * If the app does a connect(), it means that it will most likely
4957 	 * send more than 1 packet to the destination.  It makes sense
4958 	 * to clear the temporary flag.
4959 	 */
4960 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4961 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4962 		irb_t *irb = dst_ire->ire_bucket;
4963 
4964 		rw_enter(&irb->irb_lock, RW_WRITER);
4965 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4966 		irb->irb_tmp_ire_cnt--;
4967 		rw_exit(&irb->irb_lock);
4968 	}
4969 
4970 	/*
4971 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4972 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4973 	 * eligibility tests for passive connects are handled separately
4974 	 * through tcp_adapt_ire().  We do this before the source address
4975 	 * selection, because dst_ire may change after a call to
4976 	 * ipif_select_source().  This is a best-effort check, as the
4977 	 * packet for this connection may not actually go through
4978 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4979 	 * calling ip_newroute().  This is why we further check on the
4980 	 * IRE during LSO/Multidata packet transmission in
4981 	 * tcp_lsosend()/tcp_multisend().
4982 	 */
4983 	if (!ipsec_policy_set && dst_ire != NULL &&
4984 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4985 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4986 		if (ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4987 			lso_dst_ire = dst_ire;
4988 			IRE_REFHOLD(lso_dst_ire);
4989 		} else if (ip_multidata_outbound && ILL_MDT_CAPABLE(ill)) {
4990 			md_dst_ire = dst_ire;
4991 			IRE_REFHOLD(md_dst_ire);
4992 		}
4993 	}
4994 
4995 	if (dst_ire != NULL &&
4996 	    dst_ire->ire_type == IRE_LOCAL &&
4997 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4998 		/*
4999 		 * If the IRE belongs to a different zone, look for a matching
5000 		 * route in the forwarding table and use the source address from
5001 		 * that route.
5002 		 */
5003 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
5004 		    zoneid, 0, NULL,
5005 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
5006 		    MATCH_IRE_RJ_BHOLE);
5007 		if (src_ire == NULL) {
5008 			error = EHOSTUNREACH;
5009 			goto bad_addr;
5010 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
5011 			if (!(src_ire->ire_type & IRE_HOST))
5012 				error = ENETUNREACH;
5013 			else
5014 				error = EHOSTUNREACH;
5015 			goto bad_addr;
5016 		}
5017 		if (src_addr == INADDR_ANY)
5018 			src_addr = src_ire->ire_src_addr;
5019 		ire_refrele(src_ire);
5020 		src_ire = NULL;
5021 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
5022 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
5023 			src_addr = sire->ire_src_addr;
5024 			ire_refrele(dst_ire);
5025 			dst_ire = sire;
5026 			sire = NULL;
5027 		} else {
5028 			/*
5029 			 * Pick a source address so that a proper inbound
5030 			 * load spreading would happen.
5031 			 */
5032 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
5033 			ipif_t *src_ipif = NULL;
5034 			ire_t *ipif_ire;
5035 
5036 			/*
5037 			 * Supply a local source address such that inbound
5038 			 * load spreading happens.
5039 			 *
5040 			 * Determine the best source address on this ill for
5041 			 * the destination.
5042 			 *
5043 			 * 1) For broadcast, we should return a broadcast ire
5044 			 *    found above so that upper layers know that the
5045 			 *    destination address is a broadcast address.
5046 			 *
5047 			 * 2) If this is part of a group, select a better
5048 			 *    source address so that better inbound load
5049 			 *    balancing happens. Do the same if the ipif
5050 			 *    is DEPRECATED.
5051 			 *
5052 			 * 3) If the outgoing interface is part of a usesrc
5053 			 *    group, then try selecting a source address from
5054 			 *    the usesrc ILL.
5055 			 */
5056 			if ((dst_ire->ire_zoneid != zoneid &&
5057 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5058 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5059 			    ((dst_ill->ill_group != NULL) ||
5060 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5061 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
5062 				/*
5063 				 * If the destination is reachable via a
5064 				 * given gateway, the selected source address
5065 				 * should be in the same subnet as the gateway.
5066 				 * Otherwise, the destination is not reachable.
5067 				 *
5068 				 * If there are no interfaces on the same subnet
5069 				 * as the destination, ipif_select_source gives
5070 				 * first non-deprecated interface which might be
5071 				 * on a different subnet than the gateway.
5072 				 * This is not desirable. Hence pass the dst_ire
5073 				 * source address to ipif_select_source.
5074 				 * It is sure that the destination is reachable
5075 				 * with the dst_ire source address subnet.
5076 				 * So passing dst_ire source address to
5077 				 * ipif_select_source will make sure that the
5078 				 * selected source will be on the same subnet
5079 				 * as dst_ire source address.
5080 				 */
5081 				ipaddr_t saddr =
5082 				    dst_ire->ire_ipif->ipif_src_addr;
5083 				src_ipif = ipif_select_source(dst_ill,
5084 				    saddr, zoneid);
5085 				if (src_ipif != NULL) {
5086 					if (IS_VNI(src_ipif->ipif_ill)) {
5087 						/*
5088 						 * For VNI there is no
5089 						 * interface route
5090 						 */
5091 						src_addr =
5092 						    src_ipif->ipif_src_addr;
5093 					} else {
5094 						ipif_ire =
5095 						    ipif_to_ire(src_ipif);
5096 						if (ipif_ire != NULL) {
5097 							IRE_REFRELE(dst_ire);
5098 							dst_ire = ipif_ire;
5099 						}
5100 						src_addr =
5101 						    dst_ire->ire_src_addr;
5102 					}
5103 					ipif_refrele(src_ipif);
5104 				} else {
5105 					src_addr = dst_ire->ire_src_addr;
5106 				}
5107 			} else {
5108 				src_addr = dst_ire->ire_src_addr;
5109 			}
5110 		}
5111 	}
5112 
5113 	/*
5114 	 * We do ire_route_lookup() here (and not
5115 	 * interface lookup as we assert that
5116 	 * src_addr should only come from an
5117 	 * UP interface for hard binding.
5118 	 */
5119 	ASSERT(src_ire == NULL);
5120 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5121 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
5122 	/* src_ire must be a local|loopback */
5123 	if (!IRE_IS_LOCAL(src_ire)) {
5124 		if (ip_debug > 2) {
5125 			pr_addr_dbg("ip_bind_connected: bad connected "
5126 			    "src %s\n", AF_INET, &src_addr);
5127 		}
5128 		error = EADDRNOTAVAIL;
5129 		goto bad_addr;
5130 	}
5131 
5132 	/*
5133 	 * If the source address is a loopback address, the
5134 	 * destination had best be local or multicast.
5135 	 * The transports that can't handle multicast will reject
5136 	 * those addresses.
5137 	 */
5138 	if (src_ire->ire_type == IRE_LOOPBACK &&
5139 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5140 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5141 		error = -1;
5142 		goto bad_addr;
5143 	}
5144 
5145 	/*
5146 	 * Allow setting new policies. For example, disconnects come
5147 	 * down as ipa_t bind. As we would have set conn_policy_cached
5148 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5149 	 * can change after the disconnect.
5150 	 */
5151 	connp->conn_policy_cached = B_FALSE;
5152 
5153 	/*
5154 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5155 	 * can handle their passed-in conn's.
5156 	 */
5157 
5158 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5159 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5160 	connp->conn_lport = lport;
5161 	connp->conn_fport = fport;
5162 	*src_addrp = src_addr;
5163 
5164 	ASSERT(!(ipsec_policy_set && ire_requested));
5165 	if (ire_requested) {
5166 		iulp_t *ulp_info = NULL;
5167 
5168 		/*
5169 		 * Note that sire will not be NULL if this is an off-link
5170 		 * connection and there is not cache for that dest yet.
5171 		 *
5172 		 * XXX Because of an existing bug, if there are multiple
5173 		 * default routes, the IRE returned now may not be the actual
5174 		 * default route used (default routes are chosen in a
5175 		 * round robin fashion).  So if the metrics for different
5176 		 * default routes are different, we may return the wrong
5177 		 * metrics.  This will not be a problem if the existing
5178 		 * bug is fixed.
5179 		 */
5180 		if (sire != NULL) {
5181 			ulp_info = &(sire->ire_uinfo);
5182 		}
5183 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5184 			error = -1;
5185 			goto bad_addr;
5186 		}
5187 	} else if (ipsec_policy_set) {
5188 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5189 			error = -1;
5190 			goto bad_addr;
5191 		}
5192 	}
5193 
5194 	/*
5195 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5196 	 * we'll cache that.  If we don't, we'll inherit global policy.
5197 	 *
5198 	 * We can't insert until the conn reflects the policy. Note that
5199 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5200 	 * connections where we don't have a policy. This is to prevent
5201 	 * global policy lookups in the inbound path.
5202 	 *
5203 	 * If we insert before we set conn_policy_cached,
5204 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5205 	 * because global policy cound be non-empty. We normally call
5206 	 * ipsec_check_policy() for conn_policy_cached connections only if
5207 	 * ipc_in_enforce_policy is set. But in this case,
5208 	 * conn_policy_cached can get set anytime since we made the
5209 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5210 	 * called, which will make the above assumption false.  Thus, we
5211 	 * need to insert after we set conn_policy_cached.
5212 	 */
5213 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5214 		goto bad_addr;
5215 
5216 	if (fanout_insert) {
5217 		/*
5218 		 * The addresses have been verified. Time to insert in
5219 		 * the correct fanout list.
5220 		 * We need to make sure that the conn_recv is set to a non-null
5221 		 * value before we insert into the classifier table to avoid a
5222 		 * race with an incoming packet which does an ipcl_classify().
5223 		 */
5224 		if (protocol == IPPROTO_TCP)
5225 			connp->conn_recv = tcp_input;
5226 		error = ipcl_conn_insert(connp, protocol, src_addr,
5227 		    dst_addr, connp->conn_ports);
5228 	}
5229 
5230 	if (error == 0) {
5231 		connp->conn_fully_bound = B_TRUE;
5232 		/*
5233 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5234 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5235 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5236 		 * ip_xxinfo_return(), which performs further checks
5237 		 * against them and upon success, returns the LSO/MDT info
5238 		 * mblk which we will attach to the bind acknowledgment.
5239 		 */
5240 		if (lso_dst_ire != NULL) {
5241 			mblk_t *lsoinfo_mp;
5242 
5243 			ASSERT(ill->ill_lso_capab != NULL);
5244 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5245 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5246 				linkb(mp, lsoinfo_mp);
5247 		} else if (md_dst_ire != NULL) {
5248 			mblk_t *mdinfo_mp;
5249 
5250 			ASSERT(ill->ill_mdt_capab != NULL);
5251 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5252 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5253 				linkb(mp, mdinfo_mp);
5254 		}
5255 	}
5256 bad_addr:
5257 	if (ipsec_policy_set) {
5258 		ASSERT(policy_mp == mp->b_cont);
5259 		ASSERT(policy_mp != NULL);
5260 		freeb(policy_mp);
5261 		/*
5262 		 * As of now assume that nothing else accompanies
5263 		 * IPSEC_POLICY_SET.
5264 		 */
5265 		mp->b_cont = NULL;
5266 	}
5267 	if (src_ire != NULL)
5268 		IRE_REFRELE(src_ire);
5269 	if (dst_ire != NULL)
5270 		IRE_REFRELE(dst_ire);
5271 	if (sire != NULL)
5272 		IRE_REFRELE(sire);
5273 	if (md_dst_ire != NULL)
5274 		IRE_REFRELE(md_dst_ire);
5275 	if (lso_dst_ire != NULL)
5276 		IRE_REFRELE(lso_dst_ire);
5277 	return (error);
5278 }
5279 
5280 /*
5281  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5282  * Prefers dst_ire over src_ire.
5283  */
5284 static boolean_t
5285 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5286 {
5287 	mblk_t	*mp1;
5288 	ire_t *ret_ire = NULL;
5289 
5290 	mp1 = mp->b_cont;
5291 	ASSERT(mp1 != NULL);
5292 
5293 	if (ire != NULL) {
5294 		/*
5295 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5296 		 * appended mblk. Its <upper protocol>'s
5297 		 * job to make sure there is room.
5298 		 */
5299 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5300 			return (0);
5301 
5302 		mp1->b_datap->db_type = IRE_DB_TYPE;
5303 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5304 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5305 		ret_ire = (ire_t *)mp1->b_rptr;
5306 		/*
5307 		 * Pass the latest setting of the ip_path_mtu_discovery and
5308 		 * copy the ulp info if any.
5309 		 */
5310 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5311 		    IPH_DF : 0;
5312 		if (ulp_info != NULL) {
5313 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5314 			    sizeof (iulp_t));
5315 		}
5316 		ret_ire->ire_mp = mp1;
5317 	} else {
5318 		/*
5319 		 * No IRE was found. Remove IRE mblk.
5320 		 */
5321 		mp->b_cont = mp1->b_cont;
5322 		freeb(mp1);
5323 	}
5324 
5325 	return (1);
5326 }
5327 
5328 /*
5329  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5330  * the final piece where we don't.  Return a pointer to the first mblk in the
5331  * result, and update the pointer to the next mblk to chew on.  If anything
5332  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5333  * NULL pointer.
5334  */
5335 mblk_t *
5336 ip_carve_mp(mblk_t **mpp, ssize_t len)
5337 {
5338 	mblk_t	*mp0;
5339 	mblk_t	*mp1;
5340 	mblk_t	*mp2;
5341 
5342 	if (!len || !mpp || !(mp0 = *mpp))
5343 		return (NULL);
5344 	/* If we aren't going to consume the first mblk, we need a dup. */
5345 	if (mp0->b_wptr - mp0->b_rptr > len) {
5346 		mp1 = dupb(mp0);
5347 		if (mp1) {
5348 			/* Partition the data between the two mblks. */
5349 			mp1->b_wptr = mp1->b_rptr + len;
5350 			mp0->b_rptr = mp1->b_wptr;
5351 			/*
5352 			 * after adjustments if mblk not consumed is now
5353 			 * unaligned, try to align it. If this fails free
5354 			 * all messages and let upper layer recover.
5355 			 */
5356 			if (!OK_32PTR(mp0->b_rptr)) {
5357 				if (!pullupmsg(mp0, -1)) {
5358 					freemsg(mp0);
5359 					freemsg(mp1);
5360 					*mpp = NULL;
5361 					return (NULL);
5362 				}
5363 			}
5364 		}
5365 		return (mp1);
5366 	}
5367 	/* Eat through as many mblks as we need to get len bytes. */
5368 	len -= mp0->b_wptr - mp0->b_rptr;
5369 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5370 		if (mp2->b_wptr - mp2->b_rptr > len) {
5371 			/*
5372 			 * We won't consume the entire last mblk.  Like
5373 			 * above, dup and partition it.
5374 			 */
5375 			mp1->b_cont = dupb(mp2);
5376 			mp1 = mp1->b_cont;
5377 			if (!mp1) {
5378 				/*
5379 				 * Trouble.  Rather than go to a lot of
5380 				 * trouble to clean up, we free the messages.
5381 				 * This won't be any worse than losing it on
5382 				 * the wire.
5383 				 */
5384 				freemsg(mp0);
5385 				freemsg(mp2);
5386 				*mpp = NULL;
5387 				return (NULL);
5388 			}
5389 			mp1->b_wptr = mp1->b_rptr + len;
5390 			mp2->b_rptr = mp1->b_wptr;
5391 			/*
5392 			 * after adjustments if mblk not consumed is now
5393 			 * unaligned, try to align it. If this fails free
5394 			 * all messages and let upper layer recover.
5395 			 */
5396 			if (!OK_32PTR(mp2->b_rptr)) {
5397 				if (!pullupmsg(mp2, -1)) {
5398 					freemsg(mp0);
5399 					freemsg(mp2);
5400 					*mpp = NULL;
5401 					return (NULL);
5402 				}
5403 			}
5404 			*mpp = mp2;
5405 			return (mp0);
5406 		}
5407 		/* Decrement len by the amount we just got. */
5408 		len -= mp2->b_wptr - mp2->b_rptr;
5409 	}
5410 	/*
5411 	 * len should be reduced to zero now.  If not our caller has
5412 	 * screwed up.
5413 	 */
5414 	if (len) {
5415 		/* Shouldn't happen! */
5416 		freemsg(mp0);
5417 		*mpp = NULL;
5418 		return (NULL);
5419 	}
5420 	/*
5421 	 * We consumed up to exactly the end of an mblk.  Detach the part
5422 	 * we are returning from the rest of the chain.
5423 	 */
5424 	mp1->b_cont = NULL;
5425 	*mpp = mp2;
5426 	return (mp0);
5427 }
5428 
5429 /* The ill stream is being unplumbed. Called from ip_close */
5430 int
5431 ip_modclose(ill_t *ill)
5432 {
5433 
5434 	boolean_t success;
5435 	ipsq_t	*ipsq;
5436 	ipif_t	*ipif;
5437 	queue_t	*q = ill->ill_rq;
5438 	hook_nic_event_t *info;
5439 	clock_t timeout;
5440 
5441 	/*
5442 	 * Wait for the ACKs of all deferred control messages to be processed.
5443 	 * In particular, we wait for a potential capability reset initiated
5444 	 * in ip_sioctl_plink() to complete before proceeding.
5445 	 *
5446 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5447 	 * in case the driver never replies.
5448 	 */
5449 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5450 	mutex_enter(&ill->ill_lock);
5451 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5452 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5453 			/* Timeout */
5454 			break;
5455 		}
5456 	}
5457 	mutex_exit(&ill->ill_lock);
5458 
5459 	/*
5460 	 * Forcibly enter the ipsq after some delay. This is to take
5461 	 * care of the case when some ioctl does not complete because
5462 	 * we sent a control message to the driver and it did not
5463 	 * send us a reply. We want to be able to at least unplumb
5464 	 * and replumb rather than force the user to reboot the system.
5465 	 */
5466 	success = ipsq_enter(ill, B_FALSE);
5467 
5468 	/*
5469 	 * Open/close/push/pop is guaranteed to be single threaded
5470 	 * per stream by STREAMS. FS guarantees that all references
5471 	 * from top are gone before close is called. So there can't
5472 	 * be another close thread that has set CONDEMNED on this ill.
5473 	 * and cause ipsq_enter to return failure.
5474 	 */
5475 	ASSERT(success);
5476 	ipsq = ill->ill_phyint->phyint_ipsq;
5477 
5478 	/*
5479 	 * Mark it condemned. No new reference will be made to this ill.
5480 	 * Lookup functions will return an error. Threads that try to
5481 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5482 	 * that the refcnt will drop down to zero.
5483 	 */
5484 	mutex_enter(&ill->ill_lock);
5485 	ill->ill_state_flags |= ILL_CONDEMNED;
5486 	for (ipif = ill->ill_ipif; ipif != NULL;
5487 	    ipif = ipif->ipif_next) {
5488 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5489 	}
5490 	/*
5491 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5492 	 * returns  error if ILL_CONDEMNED is set
5493 	 */
5494 	cv_broadcast(&ill->ill_cv);
5495 	mutex_exit(&ill->ill_lock);
5496 
5497 	/*
5498 	 * Send all the deferred control messages downstream which came in
5499 	 * during the small window right before ipsq_enter(). We do this
5500 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5501 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5502 	 */
5503 	ill_send_all_deferred_mp(ill);
5504 
5505 	/*
5506 	 * Shut down fragmentation reassembly.
5507 	 * ill_frag_timer won't start a timer again.
5508 	 * Now cancel any existing timer
5509 	 */
5510 	(void) untimeout(ill->ill_frag_timer_id);
5511 	(void) ill_frag_timeout(ill, 0);
5512 
5513 	/*
5514 	 * If MOVE was in progress, clear the
5515 	 * move_in_progress fields also.
5516 	 */
5517 	if (ill->ill_move_in_progress) {
5518 		ILL_CLEAR_MOVE(ill);
5519 	}
5520 
5521 	/*
5522 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5523 	 * this ill. Then wait for the refcnts to drop to zero.
5524 	 * ill_is_quiescent checks whether the ill is really quiescent.
5525 	 * Then make sure that threads that are waiting to enter the
5526 	 * ipsq have seen the error returned by ipsq_enter and have
5527 	 * gone away. Then we call ill_delete_tail which does the
5528 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5529 	 */
5530 	ill_delete(ill);
5531 	mutex_enter(&ill->ill_lock);
5532 	while (!ill_is_quiescent(ill))
5533 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5534 	while (ill->ill_waiters)
5535 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5536 
5537 	mutex_exit(&ill->ill_lock);
5538 
5539 	/* qprocsoff is called in ill_delete_tail */
5540 	ill_delete_tail(ill);
5541 
5542 	/*
5543 	 * Walk through all upper (conn) streams and qenable
5544 	 * those that have queued data.
5545 	 * close synchronization needs this to
5546 	 * be done to ensure that all upper layers blocked
5547 	 * due to flow control to the closing device
5548 	 * get unblocked.
5549 	 */
5550 	ip1dbg(("ip_wsrv: walking\n"));
5551 	conn_walk_drain();
5552 
5553 	mutex_enter(&ip_mi_lock);
5554 	mi_close_unlink(&ip_g_head, (IDP)ill);
5555 	mutex_exit(&ip_mi_lock);
5556 
5557 	/*
5558 	 * credp could be null if the open didn't succeed and ip_modopen
5559 	 * itself calls ip_close.
5560 	 */
5561 	if (ill->ill_credp != NULL)
5562 		crfree(ill->ill_credp);
5563 
5564 	/*
5565 	 * Unhook the nic event message from the ill and enqueue it into the nic
5566 	 * event taskq.
5567 	 */
5568 	if ((info = ill->ill_nic_event_info) != NULL) {
5569 		if (ddi_taskq_dispatch(eventq_queue_nic, ip_ne_queue_func,
5570 		    (void *)info, DDI_SLEEP) == DDI_FAILURE) {
5571 			ip2dbg(("ip_ioctl_finish:ddi_taskq_dispatch failed\n"));
5572 			if (info->hne_data != NULL)
5573 				kmem_free(info->hne_data, info->hne_datalen);
5574 			kmem_free(info, sizeof (hook_nic_event_t));
5575 		}
5576 		ill->ill_nic_event_info = NULL;
5577 	}
5578 
5579 	mi_close_free((IDP)ill);
5580 	q->q_ptr = WR(q)->q_ptr = NULL;
5581 
5582 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5583 
5584 	return (0);
5585 }
5586 
5587 /*
5588  * This is called as part of close() for both IP and UDP
5589  * in order to quiesce the conn.
5590  */
5591 void
5592 ip_quiesce_conn(conn_t *connp)
5593 {
5594 	boolean_t	drain_cleanup_reqd = B_FALSE;
5595 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5596 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5597 
5598 	ASSERT(!IPCL_IS_TCP(connp));
5599 
5600 	/*
5601 	 * Mark the conn as closing, and this conn must not be
5602 	 * inserted in future into any list. Eg. conn_drain_insert(),
5603 	 * won't insert this conn into the conn_drain_list.
5604 	 * Similarly ill_pending_mp_add() will not add any mp to
5605 	 * the pending mp list, after this conn has started closing.
5606 	 *
5607 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5608 	 * cannot get set henceforth.
5609 	 */
5610 	mutex_enter(&connp->conn_lock);
5611 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5612 	connp->conn_state_flags |= CONN_CLOSING;
5613 	if (connp->conn_idl != NULL)
5614 		drain_cleanup_reqd = B_TRUE;
5615 	if (connp->conn_oper_pending_ill != NULL)
5616 		conn_ioctl_cleanup_reqd = B_TRUE;
5617 	if (connp->conn_ilg_inuse != 0)
5618 		ilg_cleanup_reqd = B_TRUE;
5619 	mutex_exit(&connp->conn_lock);
5620 
5621 	if (IPCL_IS_UDP(connp))
5622 		udp_quiesce_conn(connp);
5623 
5624 	if (conn_ioctl_cleanup_reqd)
5625 		conn_ioctl_cleanup(connp);
5626 
5627 	if (is_system_labeled() && connp->conn_anon_port) {
5628 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5629 		    connp->conn_mlp_type, connp->conn_ulp,
5630 		    ntohs(connp->conn_lport), B_FALSE);
5631 		connp->conn_anon_port = 0;
5632 	}
5633 	connp->conn_mlp_type = mlptSingle;
5634 
5635 	/*
5636 	 * Remove this conn from any fanout list it is on.
5637 	 * and then wait for any threads currently operating
5638 	 * on this endpoint to finish
5639 	 */
5640 	ipcl_hash_remove(connp);
5641 
5642 	/*
5643 	 * Remove this conn from the drain list, and do
5644 	 * any other cleanup that may be required.
5645 	 * (Only non-tcp streams may have a non-null conn_idl.
5646 	 * TCP streams are never flow controlled, and
5647 	 * conn_idl will be null)
5648 	 */
5649 	if (drain_cleanup_reqd)
5650 		conn_drain_tail(connp, B_TRUE);
5651 
5652 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5653 		(void) ip_mrouter_done(NULL);
5654 
5655 	if (ilg_cleanup_reqd)
5656 		ilg_delete_all(connp);
5657 
5658 	conn_delete_ire(connp, NULL);
5659 
5660 	/*
5661 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5662 	 * callers from write side can't be there now because close
5663 	 * is in progress. The only other caller is ipcl_walk
5664 	 * which checks for the condemned flag.
5665 	 */
5666 	mutex_enter(&connp->conn_lock);
5667 	connp->conn_state_flags |= CONN_CONDEMNED;
5668 	while (connp->conn_ref != 1)
5669 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5670 	connp->conn_state_flags |= CONN_QUIESCED;
5671 	mutex_exit(&connp->conn_lock);
5672 }
5673 
5674 /* ARGSUSED */
5675 int
5676 ip_close(queue_t *q, int flags)
5677 {
5678 	conn_t		*connp;
5679 
5680 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5681 
5682 	/*
5683 	 * Call the appropriate delete routine depending on whether this is
5684 	 * a module or device.
5685 	 */
5686 	if (WR(q)->q_next != NULL) {
5687 		/* This is a module close */
5688 		return (ip_modclose((ill_t *)q->q_ptr));
5689 	}
5690 
5691 	connp = q->q_ptr;
5692 	ip_quiesce_conn(connp);
5693 
5694 	qprocsoff(q);
5695 
5696 	/*
5697 	 * Now we are truly single threaded on this stream, and can
5698 	 * delete the things hanging off the connp, and finally the connp.
5699 	 * We removed this connp from the fanout list, it cannot be
5700 	 * accessed thru the fanouts, and we already waited for the
5701 	 * conn_ref to drop to 0. We are already in close, so
5702 	 * there cannot be any other thread from the top. qprocsoff
5703 	 * has completed, and service has completed or won't run in
5704 	 * future.
5705 	 */
5706 	ASSERT(connp->conn_ref == 1);
5707 
5708 	/*
5709 	 * A conn which was previously marked as IPCL_UDP cannot
5710 	 * retain the flag because it would have been cleared by
5711 	 * udp_close().
5712 	 */
5713 	ASSERT(!IPCL_IS_UDP(connp));
5714 
5715 	if (connp->conn_latch != NULL) {
5716 		IPLATCH_REFRELE(connp->conn_latch);
5717 		connp->conn_latch = NULL;
5718 	}
5719 	if (connp->conn_policy != NULL) {
5720 		IPPH_REFRELE(connp->conn_policy);
5721 		connp->conn_policy = NULL;
5722 	}
5723 	if (connp->conn_ipsec_opt_mp != NULL) {
5724 		freemsg(connp->conn_ipsec_opt_mp);
5725 		connp->conn_ipsec_opt_mp = NULL;
5726 	}
5727 
5728 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5729 
5730 	connp->conn_ref--;
5731 	ipcl_conn_destroy(connp);
5732 
5733 	q->q_ptr = WR(q)->q_ptr = NULL;
5734 	return (0);
5735 }
5736 
5737 int
5738 ip_snmpmod_close(queue_t *q)
5739 {
5740 	conn_t *connp = Q_TO_CONN(q);
5741 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5742 
5743 	qprocsoff(q);
5744 
5745 	if (connp->conn_flags & IPCL_UDPMOD)
5746 		udp_close_free(connp);
5747 
5748 	if (connp->conn_cred != NULL) {
5749 		crfree(connp->conn_cred);
5750 		connp->conn_cred = NULL;
5751 	}
5752 	CONN_DEC_REF(connp);
5753 	q->q_ptr = WR(q)->q_ptr = NULL;
5754 	return (0);
5755 }
5756 
5757 /*
5758  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5759  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5760  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5761  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5762  * queues as we never enqueue messages there and we don't handle any ioctls.
5763  * Everything else is freed.
5764  */
5765 void
5766 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5767 {
5768 	conn_t	*connp = q->q_ptr;
5769 	pfi_t	setfn;
5770 	pfi_t	getfn;
5771 
5772 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5773 
5774 	switch (DB_TYPE(mp)) {
5775 	case M_PROTO:
5776 	case M_PCPROTO:
5777 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5778 		    ((((union T_primitives *)mp->b_rptr)->type ==
5779 			T_SVR4_OPTMGMT_REQ) ||
5780 		    (((union T_primitives *)mp->b_rptr)->type ==
5781 			T_OPTMGMT_REQ))) {
5782 			/*
5783 			 * This is the only TPI primitive supported. Its
5784 			 * handling does not require tcp_t, but it does require
5785 			 * conn_t to check permissions.
5786 			 */
5787 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5788 
5789 			if (connp->conn_flags & IPCL_TCPMOD) {
5790 				setfn = tcp_snmp_set;
5791 				getfn = tcp_snmp_get;
5792 			} else {
5793 				setfn = udp_snmp_set;
5794 				getfn = udp_snmp_get;
5795 			}
5796 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5797 				freemsg(mp);
5798 				return;
5799 			}
5800 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5801 		    != NULL)
5802 			qreply(q, mp);
5803 		break;
5804 	case M_FLUSH:
5805 	case M_IOCTL:
5806 		putnext(q, mp);
5807 		break;
5808 	default:
5809 		freemsg(mp);
5810 		break;
5811 	}
5812 }
5813 
5814 /* Return the IP checksum for the IP header at "iph". */
5815 uint16_t
5816 ip_csum_hdr(ipha_t *ipha)
5817 {
5818 	uint16_t	*uph;
5819 	uint32_t	sum;
5820 	int		opt_len;
5821 
5822 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5823 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5824 	uph = (uint16_t *)ipha;
5825 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5826 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5827 	if (opt_len > 0) {
5828 		do {
5829 			sum += uph[10];
5830 			sum += uph[11];
5831 			uph += 2;
5832 		} while (--opt_len);
5833 	}
5834 	sum = (sum & 0xFFFF) + (sum >> 16);
5835 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5836 	if (sum == 0xffff)
5837 		sum = 0;
5838 	return ((uint16_t)sum);
5839 }
5840 
5841 void
5842 ip_ddi_destroy(void)
5843 {
5844 	ipv4_hook_destroy();
5845 	ipv6_hook_destroy();
5846 	ip_net_destroy();
5847 
5848 	tnet_fini();
5849 	tcp_ddi_destroy();
5850 	sctp_ddi_destroy();
5851 	ipsec_loader_destroy();
5852 	ipsec_policy_destroy();
5853 	ipsec_kstat_destroy();
5854 	nd_free(&ip_g_nd);
5855 	mutex_destroy(&igmp_timer_lock);
5856 	mutex_destroy(&mld_timer_lock);
5857 	mutex_destroy(&igmp_slowtimeout_lock);
5858 	mutex_destroy(&mld_slowtimeout_lock);
5859 	mutex_destroy(&ip_mi_lock);
5860 	mutex_destroy(&rts_clients.connf_lock);
5861 	ip_ire_fini();
5862 	ip6_asp_free();
5863 	conn_drain_fini();
5864 	ipcl_destroy();
5865 	inet_minor_destroy(ip_minor_arena);
5866 	icmp_kstat_fini();
5867 	ip_kstat_fini();
5868 	rw_destroy(&ipsec_capab_ills_lock);
5869 	rw_destroy(&ill_g_usesrc_lock);
5870 	ip_drop_unregister(&ip_dropper);
5871 }
5872 
5873 
5874 void
5875 ip_ddi_init(void)
5876 {
5877 	TCP6_MAJ = ddi_name_to_major(TCP6);
5878 	TCP_MAJ	= ddi_name_to_major(TCP);
5879 	SCTP_MAJ = ddi_name_to_major(SCTP);
5880 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5881 
5882 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5883 
5884 	/* IP's IPsec code calls the packet dropper */
5885 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5886 
5887 	if (!ip_g_nd) {
5888 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5889 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5890 			nd_free(&ip_g_nd);
5891 		}
5892 	}
5893 
5894 	ipsec_loader_init();
5895 	ipsec_policy_init();
5896 	ipsec_kstat_init();
5897 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5898 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5899 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5900 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5901 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5902 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5903 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5904 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5905 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5906 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5907 
5908 	/*
5909 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5910 	 * initial devices: ip, ip6, tcp, tcp6.
5911 	 */
5912 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5913 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5914 		cmn_err(CE_PANIC,
5915 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5916 	}
5917 
5918 	ipcl_init();
5919 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5920 	ip_ire_init();
5921 	ip6_asp_init();
5922 	ipif_init();
5923 	conn_drain_init();
5924 	tcp_ddi_init();
5925 	sctp_ddi_init();
5926 
5927 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5928 
5929 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5930 		"net", KSTAT_TYPE_NAMED,
5931 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5932 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5933 		ip_kstat->ks_data = &ip_statistics;
5934 		kstat_install(ip_kstat);
5935 	}
5936 	ip_kstat_init();
5937 	ip6_kstat_init();
5938 	icmp_kstat_init();
5939 	ipsec_loader_start();
5940 	tnet_init();
5941 
5942 	ip_net_init();
5943 	ipv4_hook_init();
5944 	ipv6_hook_init();
5945 }
5946 
5947 /*
5948  * Allocate and initialize a DLPI template of the specified length.  (May be
5949  * called as writer.)
5950  */
5951 mblk_t *
5952 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5953 {
5954 	mblk_t	*mp;
5955 
5956 	mp = allocb(len, BPRI_MED);
5957 	if (!mp)
5958 		return (NULL);
5959 
5960 	/*
5961 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5962 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5963 	 * that other DLPI are M_PROTO.
5964 	 */
5965 	if (prim == DL_INFO_REQ) {
5966 		mp->b_datap->db_type = M_PCPROTO;
5967 	} else {
5968 		mp->b_datap->db_type = M_PROTO;
5969 	}
5970 
5971 	mp->b_wptr = mp->b_rptr + len;
5972 	bzero(mp->b_rptr, len);
5973 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5974 	return (mp);
5975 }
5976 
5977 const char *
5978 dlpi_prim_str(int prim)
5979 {
5980 	switch (prim) {
5981 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5982 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5983 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5984 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5985 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5986 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5987 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5988 	case DL_OK_ACK:		return ("DL_OK_ACK");
5989 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5990 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5991 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5992 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5993 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5994 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5995 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5996 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5997 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5998 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5999 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6000 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6001 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6002 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6003 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6004 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6005 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6006 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6007 	default:		return ("<unknown primitive>");
6008 	}
6009 }
6010 
6011 const char *
6012 dlpi_err_str(int err)
6013 {
6014 	switch (err) {
6015 	case DL_ACCESS:		return ("DL_ACCESS");
6016 	case DL_BADADDR:	return ("DL_BADADDR");
6017 	case DL_BADCORR:	return ("DL_BADCORR");
6018 	case DL_BADDATA:	return ("DL_BADDATA");
6019 	case DL_BADPPA:		return ("DL_BADPPA");
6020 	case DL_BADPRIM:	return ("DL_BADPRIM");
6021 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6022 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6023 	case DL_BADSAP:		return ("DL_BADSAP");
6024 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6025 	case DL_BOUND:		return ("DL_BOUND");
6026 	case DL_INITFAILED:	return ("DL_INITFAILED");
6027 	case DL_NOADDR:		return ("DL_NOADDR");
6028 	case DL_NOTINIT:	return ("DL_NOTINIT");
6029 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6030 	case DL_SYSERR:		return ("DL_SYSERR");
6031 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6032 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6033 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6034 	case DL_TOOMANY:	return ("DL_TOOMANY");
6035 	case DL_NOTENAB:	return ("DL_NOTENAB");
6036 	case DL_BUSY:		return ("DL_BUSY");
6037 	case DL_NOAUTO:		return ("DL_NOAUTO");
6038 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6039 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6040 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6041 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6042 	case DL_PENDING:	return ("DL_PENDING");
6043 	default:		return ("<unknown error>");
6044 	}
6045 }
6046 
6047 /*
6048  * Debug formatting routine.  Returns a character string representation of the
6049  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6050  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6051  *
6052  * Once the ndd table-printing interfaces are removed, this can be changed to
6053  * standard dotted-decimal form.
6054  */
6055 char *
6056 ip_dot_addr(ipaddr_t addr, char *buf)
6057 {
6058 	uint8_t *ap = (uint8_t *)&addr;
6059 
6060 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6061 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6062 	return (buf);
6063 }
6064 
6065 /*
6066  * Write the given MAC address as a printable string in the usual colon-
6067  * separated format.
6068  */
6069 const char *
6070 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6071 {
6072 	char *bp;
6073 
6074 	if (alen == 0 || buflen < 4)
6075 		return ("?");
6076 	bp = buf;
6077 	for (;;) {
6078 		/*
6079 		 * If there are more MAC address bytes available, but we won't
6080 		 * have any room to print them, then add "..." to the string
6081 		 * instead.  See below for the 'magic number' explanation.
6082 		 */
6083 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6084 			(void) strcpy(bp, "...");
6085 			break;
6086 		}
6087 		(void) sprintf(bp, "%02x", *addr++);
6088 		bp += 2;
6089 		if (--alen == 0)
6090 			break;
6091 		*bp++ = ':';
6092 		buflen -= 3;
6093 		/*
6094 		 * At this point, based on the first 'if' statement above,
6095 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6096 		 * buflen >= 4.  The first case leaves room for the final "xx"
6097 		 * number and trailing NUL byte.  The second leaves room for at
6098 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6099 		 * that statement.
6100 		 */
6101 	}
6102 	return (buf);
6103 }
6104 
6105 /*
6106  * Send an ICMP error after patching up the packet appropriately.  Returns
6107  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6108  */
6109 static boolean_t
6110 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6111     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
6112 {
6113 	ipha_t *ipha;
6114 	mblk_t *first_mp;
6115 	boolean_t secure;
6116 	unsigned char db_type;
6117 
6118 	first_mp = mp;
6119 	if (mctl_present) {
6120 		mp = mp->b_cont;
6121 		secure = ipsec_in_is_secure(first_mp);
6122 		ASSERT(mp != NULL);
6123 	} else {
6124 		/*
6125 		 * If this is an ICMP error being reported - which goes
6126 		 * up as M_CTLs, we need to convert them to M_DATA till
6127 		 * we finish checking with global policy because
6128 		 * ipsec_check_global_policy() assumes M_DATA as clear
6129 		 * and M_CTL as secure.
6130 		 */
6131 		db_type = DB_TYPE(mp);
6132 		DB_TYPE(mp) = M_DATA;
6133 		secure = B_FALSE;
6134 	}
6135 	/*
6136 	 * We are generating an icmp error for some inbound packet.
6137 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6138 	 * Before we generate an error, check with global policy
6139 	 * to see whether this is allowed to enter the system. As
6140 	 * there is no "conn", we are checking with global policy.
6141 	 */
6142 	ipha = (ipha_t *)mp->b_rptr;
6143 	if (secure || ipsec_inbound_v4_policy_present) {
6144 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6145 		    ipha, NULL, mctl_present);
6146 		if (first_mp == NULL)
6147 			return (B_FALSE);
6148 	}
6149 
6150 	if (!mctl_present)
6151 		DB_TYPE(mp) = db_type;
6152 
6153 	if (flags & IP_FF_SEND_ICMP) {
6154 		if (flags & IP_FF_HDR_COMPLETE) {
6155 			if (ip_hdr_complete(ipha, zoneid)) {
6156 				freemsg(first_mp);
6157 				return (B_TRUE);
6158 			}
6159 		}
6160 		if (flags & IP_FF_CKSUM) {
6161 			/*
6162 			 * Have to correct checksum since
6163 			 * the packet might have been
6164 			 * fragmented and the reassembly code in ip_rput
6165 			 * does not restore the IP checksum.
6166 			 */
6167 			ipha->ipha_hdr_checksum = 0;
6168 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6169 		}
6170 		switch (icmp_type) {
6171 		case ICMP_DEST_UNREACHABLE:
6172 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid);
6173 			break;
6174 		default:
6175 			freemsg(first_mp);
6176 			break;
6177 		}
6178 	} else {
6179 		freemsg(first_mp);
6180 		return (B_FALSE);
6181 	}
6182 
6183 	return (B_TRUE);
6184 }
6185 
6186 /*
6187  * Used to send an ICMP error message when a packet is received for
6188  * a protocol that is not supported. The mblk passed as argument
6189  * is consumed by this function.
6190  */
6191 void
6192 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
6193 {
6194 	mblk_t *mp;
6195 	ipha_t *ipha;
6196 	ill_t *ill;
6197 	ipsec_in_t *ii;
6198 
6199 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6200 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6201 
6202 	mp = ipsec_mp->b_cont;
6203 	ipsec_mp->b_cont = NULL;
6204 	ipha = (ipha_t *)mp->b_rptr;
6205 	/* Get ill from index in ipsec_in_t. */
6206 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6207 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL);
6208 	if (ill != NULL) {
6209 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6210 			if (ip_fanout_send_icmp(q, mp, flags,
6211 			    ICMP_DEST_UNREACHABLE,
6212 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6213 				BUMP_MIB(ill->ill_ip_mib,
6214 				    ipIfStatsInUnknownProtos);
6215 			}
6216 		} else {
6217 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6218 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6219 			    0, B_FALSE, zoneid)) {
6220 				BUMP_MIB(ill->ill_ip_mib,
6221 				    ipIfStatsInUnknownProtos);
6222 			}
6223 		}
6224 		ill_refrele(ill);
6225 	} else { /* re-link for the freemsg() below. */
6226 		ipsec_mp->b_cont = mp;
6227 	}
6228 
6229 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6230 	freemsg(ipsec_mp);
6231 }
6232 
6233 /*
6234  * See if the inbound datagram has had IPsec processing applied to it.
6235  */
6236 boolean_t
6237 ipsec_in_is_secure(mblk_t *ipsec_mp)
6238 {
6239 	ipsec_in_t *ii;
6240 
6241 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6242 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6243 
6244 	if (ii->ipsec_in_loopback) {
6245 		return (ii->ipsec_in_secure);
6246 	} else {
6247 		return (ii->ipsec_in_ah_sa != NULL ||
6248 		    ii->ipsec_in_esp_sa != NULL ||
6249 		    ii->ipsec_in_decaps);
6250 	}
6251 }
6252 
6253 /*
6254  * Handle protocols with which IP is less intimate.  There
6255  * can be more than one stream bound to a particular
6256  * protocol.  When this is the case, normally each one gets a copy
6257  * of any incoming packets.
6258  *
6259  * IPSEC NOTE :
6260  *
6261  * Don't allow a secure packet going up a non-secure connection.
6262  * We don't allow this because
6263  *
6264  * 1) Reply might go out in clear which will be dropped at
6265  *    the sending side.
6266  * 2) If the reply goes out in clear it will give the
6267  *    adversary enough information for getting the key in
6268  *    most of the cases.
6269  *
6270  * Moreover getting a secure packet when we expect clear
6271  * implies that SA's were added without checking for
6272  * policy on both ends. This should not happen once ISAKMP
6273  * is used to negotiate SAs as SAs will be added only after
6274  * verifying the policy.
6275  *
6276  * NOTE : If the packet was tunneled and not multicast we only send
6277  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6278  * back to delivering packets to AF_INET6 raw sockets.
6279  *
6280  * IPQoS Notes:
6281  * Once we have determined the client, invoke IPPF processing.
6282  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6283  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6284  * ip_policy will be false.
6285  *
6286  * Zones notes:
6287  * Currently only applications in the global zone can create raw sockets for
6288  * protocols other than ICMP. So unlike the broadcast / multicast case of
6289  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6290  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6291  */
6292 static void
6293 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6294     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6295     zoneid_t zoneid)
6296 {
6297 	queue_t	*rq;
6298 	mblk_t	*mp1, *first_mp1;
6299 	uint_t	protocol = ipha->ipha_protocol;
6300 	ipaddr_t dst;
6301 	boolean_t one_only;
6302 	mblk_t *first_mp = mp;
6303 	boolean_t secure;
6304 	uint32_t ill_index;
6305 	conn_t	*connp, *first_connp, *next_connp;
6306 	connf_t	*connfp;
6307 	boolean_t shared_addr;
6308 	mib2_ipIfStatsEntry_t *mibptr;
6309 
6310 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ip_mib;
6311 	if (mctl_present) {
6312 		mp = first_mp->b_cont;
6313 		secure = ipsec_in_is_secure(first_mp);
6314 		ASSERT(mp != NULL);
6315 	} else {
6316 		secure = B_FALSE;
6317 	}
6318 	dst = ipha->ipha_dst;
6319 	/*
6320 	 * If the packet was tunneled and not multicast we only send to it
6321 	 * the first match.
6322 	 */
6323 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6324 	    !CLASSD(dst));
6325 
6326 	shared_addr = (zoneid == ALL_ZONES);
6327 	if (shared_addr) {
6328 		/*
6329 		 * We don't allow multilevel ports for raw IP, so no need to
6330 		 * check for that here.
6331 		 */
6332 		zoneid = tsol_packet_to_zoneid(mp);
6333 	}
6334 
6335 	connfp = &ipcl_proto_fanout[protocol];
6336 	mutex_enter(&connfp->connf_lock);
6337 	connp = connfp->connf_head;
6338 	for (connp = connfp->connf_head; connp != NULL;
6339 		connp = connp->conn_next) {
6340 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6341 		    zoneid) &&
6342 		    (!is_system_labeled() ||
6343 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6344 		    connp)))
6345 			break;
6346 	}
6347 
6348 	if (connp == NULL || connp->conn_upq == NULL) {
6349 		/*
6350 		 * No one bound to these addresses.  Is
6351 		 * there a client that wants all
6352 		 * unclaimed datagrams?
6353 		 */
6354 		mutex_exit(&connfp->connf_lock);
6355 		/*
6356 		 * Check for IPPROTO_ENCAP...
6357 		 */
6358 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6359 			/*
6360 			 * If an IPsec mblk is here on a multicast
6361 			 * tunnel (using ip_mroute stuff), check policy here,
6362 			 * THEN ship off to ip_mroute_decap().
6363 			 *
6364 			 * BTW,  If I match a configured IP-in-IP
6365 			 * tunnel, this path will not be reached, and
6366 			 * ip_mroute_decap will never be called.
6367 			 */
6368 			first_mp = ipsec_check_global_policy(first_mp, connp,
6369 			    ipha, NULL, mctl_present);
6370 			if (first_mp != NULL) {
6371 				if (mctl_present)
6372 					freeb(first_mp);
6373 				ip_mroute_decap(q, mp);
6374 			} /* Else we already freed everything! */
6375 		} else {
6376 			/*
6377 			 * Otherwise send an ICMP protocol unreachable.
6378 			 */
6379 			if (ip_fanout_send_icmp(q, first_mp, flags,
6380 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6381 			    mctl_present, zoneid)) {
6382 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6383 			}
6384 		}
6385 		return;
6386 	}
6387 	CONN_INC_REF(connp);
6388 	first_connp = connp;
6389 
6390 	/*
6391 	 * Only send message to one tunnel driver by immediately
6392 	 * terminating the loop.
6393 	 */
6394 	connp = one_only ? NULL : connp->conn_next;
6395 
6396 	for (;;) {
6397 		while (connp != NULL) {
6398 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6399 			    flags, zoneid) &&
6400 			    (!is_system_labeled() ||
6401 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6402 			    shared_addr, connp)))
6403 				break;
6404 			connp = connp->conn_next;
6405 		}
6406 
6407 		/*
6408 		 * Copy the packet.
6409 		 */
6410 		if (connp == NULL || connp->conn_upq == NULL ||
6411 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6412 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6413 			/*
6414 			 * No more interested clients or memory
6415 			 * allocation failed
6416 			 */
6417 			connp = first_connp;
6418 			break;
6419 		}
6420 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6421 		CONN_INC_REF(connp);
6422 		mutex_exit(&connfp->connf_lock);
6423 		rq = connp->conn_rq;
6424 		if (!canputnext(rq)) {
6425 			if (flags & IP_FF_RAWIP) {
6426 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6427 			} else {
6428 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6429 			}
6430 
6431 			freemsg(first_mp1);
6432 		} else {
6433 			/*
6434 			 * Don't enforce here if we're an actual tunnel -
6435 			 * let "tun" do it instead.
6436 			 */
6437 			if (!IPCL_IS_IPTUN(connp) &&
6438 			    (CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6439 				first_mp1 = ipsec_check_inbound_policy
6440 				    (first_mp1, connp, ipha, NULL,
6441 				    mctl_present);
6442 			}
6443 			if (first_mp1 != NULL) {
6444 				int in_flags = 0;
6445 				/*
6446 				 * ip_fanout_proto also gets called from
6447 				 * icmp_inbound_error_fanout, in which case
6448 				 * the msg type is M_CTL.  Don't add info
6449 				 * in this case for the time being. In future
6450 				 * when there is a need for knowing the
6451 				 * inbound iface index for ICMP error msgs,
6452 				 * then this can be changed.
6453 				 */
6454 				if (connp->conn_recvif)
6455 					in_flags = IPF_RECVIF;
6456 				/*
6457 				 * The ULP may support IP_RECVPKTINFO for both
6458 				 * IP v4 and v6 so pass the appropriate argument
6459 				 * based on conn IP version.
6460 				 */
6461 				if (connp->conn_ip_recvpktinfo) {
6462 					if (connp->conn_af_isv6) {
6463 						/*
6464 						 * V6 only needs index
6465 						 */
6466 						in_flags |= IPF_RECVIF;
6467 					} else {
6468 						/*
6469 						 * V4 needs index +
6470 						 * matching address.
6471 						 */
6472 						in_flags |= IPF_RECVADDR;
6473 					}
6474 				}
6475 				if ((in_flags != 0) &&
6476 				    (mp->b_datap->db_type != M_CTL)) {
6477 					/*
6478 					 * the actual data will be
6479 					 * contained in b_cont upon
6480 					 * successful return of the
6481 					 * following call else
6482 					 * original mblk is returned
6483 					 */
6484 					ASSERT(recv_ill != NULL);
6485 					mp1 = ip_add_info(mp1, recv_ill,
6486 					    in_flags, IPCL_ZONEID(connp));
6487 				}
6488 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6489 				if (mctl_present)
6490 					freeb(first_mp1);
6491 				putnext(rq, mp1);
6492 			}
6493 		}
6494 		mutex_enter(&connfp->connf_lock);
6495 		/* Follow the next pointer before releasing the conn. */
6496 		next_connp = connp->conn_next;
6497 		CONN_DEC_REF(connp);
6498 		connp = next_connp;
6499 	}
6500 
6501 	/* Last one.  Send it upstream. */
6502 	mutex_exit(&connfp->connf_lock);
6503 
6504 	/*
6505 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6506 	 * will be set to false.
6507 	 */
6508 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6509 		ill_index = ill->ill_phyint->phyint_ifindex;
6510 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6511 		if (mp == NULL) {
6512 			CONN_DEC_REF(connp);
6513 			if (mctl_present) {
6514 				freeb(first_mp);
6515 			}
6516 			return;
6517 		}
6518 	}
6519 
6520 	rq = connp->conn_rq;
6521 	if (!canputnext(rq)) {
6522 		if (flags & IP_FF_RAWIP) {
6523 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6524 		} else {
6525 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6526 		}
6527 
6528 		freemsg(first_mp);
6529 	} else {
6530 		if (IPCL_IS_IPTUN(connp)) {
6531 			/*
6532 			 * Tunneled packet.  We enforce policy in the tunnel
6533 			 * module itself.
6534 			 *
6535 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6536 			 * a policy check.
6537 			 */
6538 			putnext(rq, first_mp);
6539 			CONN_DEC_REF(connp);
6540 			return;
6541 		}
6542 
6543 		if ((CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6544 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6545 			    ipha, NULL, mctl_present);
6546 		}
6547 
6548 		if (first_mp != NULL) {
6549 			int in_flags = 0;
6550 
6551 			/*
6552 			 * ip_fanout_proto also gets called
6553 			 * from icmp_inbound_error_fanout, in
6554 			 * which case the msg type is M_CTL.
6555 			 * Don't add info in this case for time
6556 			 * being. In future when there is a
6557 			 * need for knowing the inbound iface
6558 			 * index for ICMP error msgs, then this
6559 			 * can be changed
6560 			 */
6561 			if (connp->conn_recvif)
6562 				in_flags = IPF_RECVIF;
6563 			if (connp->conn_ip_recvpktinfo) {
6564 				if (connp->conn_af_isv6) {
6565 					/*
6566 					 * V6 only needs index
6567 					 */
6568 					in_flags |= IPF_RECVIF;
6569 				} else {
6570 					/*
6571 					 * V4 needs index +
6572 					 * matching address.
6573 					 */
6574 					in_flags |= IPF_RECVADDR;
6575 				}
6576 			}
6577 			if ((in_flags != 0) &&
6578 			    (mp->b_datap->db_type != M_CTL)) {
6579 
6580 				/*
6581 				 * the actual data will be contained in
6582 				 * b_cont upon successful return
6583 				 * of the following call else original
6584 				 * mblk is returned
6585 				 */
6586 				ASSERT(recv_ill != NULL);
6587 				mp = ip_add_info(mp, recv_ill,
6588 				    in_flags, IPCL_ZONEID(connp));
6589 			}
6590 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6591 			putnext(rq, mp);
6592 			if (mctl_present)
6593 				freeb(first_mp);
6594 		}
6595 	}
6596 	CONN_DEC_REF(connp);
6597 }
6598 
6599 /*
6600  * Fanout for TCP packets
6601  * The caller puts <fport, lport> in the ports parameter.
6602  *
6603  * IPQoS Notes
6604  * Before sending it to the client, invoke IPPF processing.
6605  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6606  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6607  * ip_policy is false.
6608  */
6609 static void
6610 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6611     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6612 {
6613 	mblk_t  *first_mp;
6614 	boolean_t secure;
6615 	uint32_t ill_index;
6616 	int	ip_hdr_len;
6617 	tcph_t	*tcph;
6618 	boolean_t syn_present = B_FALSE;
6619 	conn_t	*connp;
6620 
6621 	ASSERT(recv_ill != NULL);
6622 
6623 	first_mp = mp;
6624 	if (mctl_present) {
6625 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6626 		mp = first_mp->b_cont;
6627 		secure = ipsec_in_is_secure(first_mp);
6628 		ASSERT(mp != NULL);
6629 	} else {
6630 		secure = B_FALSE;
6631 	}
6632 
6633 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6634 
6635 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6636 	    NULL) {
6637 		/*
6638 		 * No connected connection or listener. Send a
6639 		 * TH_RST via tcp_xmit_listeners_reset.
6640 		 */
6641 
6642 		/* Initiate IPPf processing, if needed. */
6643 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6644 			uint32_t ill_index;
6645 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6646 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6647 			if (first_mp == NULL)
6648 				return;
6649 		}
6650 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6651 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6652 		    zoneid));
6653 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6654 		return;
6655 	}
6656 
6657 	/*
6658 	 * Allocate the SYN for the TCP connection here itself
6659 	 */
6660 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6661 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6662 		if (IPCL_IS_TCP(connp)) {
6663 			squeue_t *sqp;
6664 
6665 			/*
6666 			 * For fused tcp loopback, assign the eager's
6667 			 * squeue to be that of the active connect's.
6668 			 * Note that we don't check for IP_FF_LOOPBACK
6669 			 * here since this routine gets called only
6670 			 * for loopback (unlike the IPv6 counterpart).
6671 			 */
6672 			ASSERT(Q_TO_CONN(q) != NULL);
6673 			if (do_tcp_fusion &&
6674 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6675 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6676 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6677 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6678 				sqp = Q_TO_CONN(q)->conn_sqp;
6679 			} else {
6680 				sqp = IP_SQUEUE_GET(lbolt);
6681 			}
6682 
6683 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6684 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6685 			syn_present = B_TRUE;
6686 		}
6687 	}
6688 
6689 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6690 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6691 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6692 		if ((flags & TH_RST) || (flags & TH_URG)) {
6693 			CONN_DEC_REF(connp);
6694 			freemsg(first_mp);
6695 			return;
6696 		}
6697 		if (flags & TH_ACK) {
6698 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6699 			CONN_DEC_REF(connp);
6700 			return;
6701 		}
6702 
6703 		CONN_DEC_REF(connp);
6704 		freemsg(first_mp);
6705 		return;
6706 	}
6707 
6708 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6709 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6710 		    NULL, mctl_present);
6711 		if (first_mp == NULL) {
6712 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6713 			CONN_DEC_REF(connp);
6714 			return;
6715 		}
6716 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6717 			ASSERT(syn_present);
6718 			if (mctl_present) {
6719 				ASSERT(first_mp != mp);
6720 				first_mp->b_datap->db_struioflag |=
6721 				    STRUIO_POLICY;
6722 			} else {
6723 				ASSERT(first_mp == mp);
6724 				mp->b_datap->db_struioflag &=
6725 				    ~STRUIO_EAGER;
6726 				mp->b_datap->db_struioflag |=
6727 				    STRUIO_POLICY;
6728 			}
6729 		} else {
6730 			/*
6731 			 * Discard first_mp early since we're dealing with a
6732 			 * fully-connected conn_t and tcp doesn't do policy in
6733 			 * this case.
6734 			 */
6735 			if (mctl_present) {
6736 				freeb(first_mp);
6737 				mctl_present = B_FALSE;
6738 			}
6739 			first_mp = mp;
6740 		}
6741 	}
6742 
6743 	/*
6744 	 * Initiate policy processing here if needed. If we get here from
6745 	 * icmp_inbound_error_fanout, ip_policy is false.
6746 	 */
6747 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6748 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6749 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6750 		if (mp == NULL) {
6751 			CONN_DEC_REF(connp);
6752 			if (mctl_present)
6753 				freeb(first_mp);
6754 			return;
6755 		} else if (mctl_present) {
6756 			ASSERT(first_mp != mp);
6757 			first_mp->b_cont = mp;
6758 		} else {
6759 			first_mp = mp;
6760 		}
6761 	}
6762 
6763 
6764 
6765 	/* Handle socket options. */
6766 	if (!syn_present &&
6767 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6768 		/* Add header */
6769 		ASSERT(recv_ill != NULL);
6770 		/*
6771 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6772 		 * IPF_RECVIF.
6773 		 */
6774 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp));
6775 		if (mp == NULL) {
6776 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6777 			CONN_DEC_REF(connp);
6778 			if (mctl_present)
6779 				freeb(first_mp);
6780 			return;
6781 		} else if (mctl_present) {
6782 			/*
6783 			 * ip_add_info might return a new mp.
6784 			 */
6785 			ASSERT(first_mp != mp);
6786 			first_mp->b_cont = mp;
6787 		} else {
6788 			first_mp = mp;
6789 		}
6790 	}
6791 
6792 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6793 	if (IPCL_IS_TCP(connp)) {
6794 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6795 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6796 	} else {
6797 		putnext(connp->conn_rq, first_mp);
6798 		CONN_DEC_REF(connp);
6799 	}
6800 }
6801 
6802 /*
6803  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6804  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6805  * Caller is responsible for dropping references to the conn, and freeing
6806  * first_mp.
6807  *
6808  * IPQoS Notes
6809  * Before sending it to the client, invoke IPPF processing. Policy processing
6810  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6811  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6812  * ip_wput_local, ip_policy is false.
6813  */
6814 static void
6815 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6816     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6817     boolean_t ip_policy)
6818 {
6819 	boolean_t	mctl_present = (first_mp != NULL);
6820 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6821 	uint32_t	ill_index;
6822 
6823 	ASSERT(ill != NULL);
6824 
6825 	if (mctl_present)
6826 		first_mp->b_cont = mp;
6827 	else
6828 		first_mp = mp;
6829 
6830 	if (CONN_UDP_FLOWCTLD(connp)) {
6831 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6832 		freemsg(first_mp);
6833 		return;
6834 	}
6835 
6836 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6837 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6838 		    NULL, mctl_present);
6839 		if (first_mp == NULL) {
6840 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6841 			return;	/* Freed by ipsec_check_inbound_policy(). */
6842 		}
6843 	}
6844 	if (mctl_present)
6845 		freeb(first_mp);
6846 
6847 	/* Handle options. */
6848 	if (connp->conn_recvif)
6849 		in_flags = IPF_RECVIF;
6850 	/*
6851 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
6852 	 * passed to ip_add_info is based on IP version of connp.
6853 	 */
6854 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6855 		if (connp->conn_af_isv6) {
6856 			/*
6857 			 * V6 only needs index
6858 			 */
6859 			in_flags |= IPF_RECVIF;
6860 		} else {
6861 			/*
6862 			 * V4 needs index + matching address.
6863 			 */
6864 			in_flags |= IPF_RECVADDR;
6865 		}
6866 	}
6867 
6868 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6869 		in_flags |= IPF_RECVSLLA;
6870 
6871 	/*
6872 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6873 	 * freed if the packet is dropped. The caller will do so.
6874 	 */
6875 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6876 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6877 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6878 		if (mp == NULL) {
6879 			return;
6880 		}
6881 	}
6882 	if ((in_flags != 0) &&
6883 	    (mp->b_datap->db_type != M_CTL)) {
6884 		/*
6885 		 * The actual data will be contained in b_cont
6886 		 * upon successful return of the following call
6887 		 * else original mblk is returned
6888 		 */
6889 		ASSERT(recv_ill != NULL);
6890 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp));
6891 	}
6892 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
6893 	/* Send it upstream */
6894 	CONN_UDP_RECV(connp, mp);
6895 }
6896 
6897 /*
6898  * Fanout for UDP packets.
6899  * The caller puts <fport, lport> in the ports parameter.
6900  *
6901  * If SO_REUSEADDR is set all multicast and broadcast packets
6902  * will be delivered to all streams bound to the same port.
6903  *
6904  * Zones notes:
6905  * Multicast and broadcast packets will be distributed to streams in all zones.
6906  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6907  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6908  * packets. To maintain this behavior with multiple zones, the conns are grouped
6909  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6910  * each zone. If unset, all the following conns in the same zone are skipped.
6911  */
6912 static void
6913 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6914     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6915     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6916 {
6917 	uint32_t	dstport, srcport;
6918 	ipaddr_t	dst;
6919 	mblk_t		*first_mp;
6920 	boolean_t	secure;
6921 	in6_addr_t	v6src;
6922 	conn_t		*connp;
6923 	connf_t		*connfp;
6924 	conn_t		*first_connp;
6925 	conn_t		*next_connp;
6926 	mblk_t		*mp1, *first_mp1;
6927 	ipaddr_t	src;
6928 	zoneid_t	last_zoneid;
6929 	boolean_t	reuseaddr;
6930 	boolean_t	shared_addr;
6931 
6932 	first_mp = mp;
6933 	if (mctl_present) {
6934 		mp = first_mp->b_cont;
6935 		first_mp->b_cont = NULL;
6936 		secure = ipsec_in_is_secure(first_mp);
6937 		ASSERT(mp != NULL);
6938 	} else {
6939 		first_mp = NULL;
6940 		secure = B_FALSE;
6941 	}
6942 
6943 	/* Extract ports in net byte order */
6944 	dstport = htons(ntohl(ports) & 0xFFFF);
6945 	srcport = htons(ntohl(ports) >> 16);
6946 	dst = ipha->ipha_dst;
6947 	src = ipha->ipha_src;
6948 
6949 	shared_addr = (zoneid == ALL_ZONES);
6950 	if (shared_addr) {
6951 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6952 		if (zoneid == ALL_ZONES)
6953 			zoneid = tsol_packet_to_zoneid(mp);
6954 	}
6955 
6956 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6957 	mutex_enter(&connfp->connf_lock);
6958 	connp = connfp->connf_head;
6959 	if (!broadcast && !CLASSD(dst)) {
6960 		/*
6961 		 * Not broadcast or multicast. Send to the one (first)
6962 		 * client we find. No need to check conn_wantpacket()
6963 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6964 		 * IPv4 unicast packets.
6965 		 */
6966 		while ((connp != NULL) &&
6967 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
6968 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
6969 			connp = connp->conn_next;
6970 		}
6971 
6972 		if (connp == NULL || connp->conn_upq == NULL)
6973 			goto notfound;
6974 
6975 		if (is_system_labeled() &&
6976 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6977 		    connp))
6978 			goto notfound;
6979 
6980 		CONN_INC_REF(connp);
6981 		mutex_exit(&connfp->connf_lock);
6982 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
6983 		    flags, recv_ill, ip_policy);
6984 		IP_STAT(ip_udp_fannorm);
6985 		CONN_DEC_REF(connp);
6986 		return;
6987 	}
6988 
6989 	/*
6990 	 * Broadcast and multicast case
6991 	 *
6992 	 * Need to check conn_wantpacket().
6993 	 * If SO_REUSEADDR has been set on the first we send the
6994 	 * packet to all clients that have joined the group and
6995 	 * match the port.
6996 	 */
6997 
6998 	while (connp != NULL) {
6999 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7000 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7001 		    (!is_system_labeled() ||
7002 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7003 		    connp)))
7004 			break;
7005 		connp = connp->conn_next;
7006 	}
7007 
7008 	if (connp == NULL || connp->conn_upq == NULL)
7009 		goto notfound;
7010 
7011 	first_connp = connp;
7012 	/*
7013 	 * When SO_REUSEADDR is not set, send the packet only to the first
7014 	 * matching connection in its zone by keeping track of the zoneid.
7015 	 */
7016 	reuseaddr = first_connp->conn_reuseaddr;
7017 	last_zoneid = first_connp->conn_zoneid;
7018 
7019 	CONN_INC_REF(connp);
7020 	connp = connp->conn_next;
7021 	for (;;) {
7022 		while (connp != NULL) {
7023 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7024 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7025 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7026 			    (!is_system_labeled() ||
7027 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7028 			    shared_addr, connp)))
7029 				break;
7030 			connp = connp->conn_next;
7031 		}
7032 		/*
7033 		 * Just copy the data part alone. The mctl part is
7034 		 * needed just for verifying policy and it is never
7035 		 * sent up.
7036 		 */
7037 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7038 		    ((mp1 = copymsg(mp)) == NULL))) {
7039 			/*
7040 			 * No more interested clients or memory
7041 			 * allocation failed
7042 			 */
7043 			connp = first_connp;
7044 			break;
7045 		}
7046 		if (connp->conn_zoneid != last_zoneid) {
7047 			/*
7048 			 * Update the zoneid so that the packet isn't sent to
7049 			 * any more conns in the same zone unless SO_REUSEADDR
7050 			 * is set.
7051 			 */
7052 			reuseaddr = connp->conn_reuseaddr;
7053 			last_zoneid = connp->conn_zoneid;
7054 		}
7055 		if (first_mp != NULL) {
7056 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7057 			    ipsec_info_type == IPSEC_IN);
7058 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7059 			if (first_mp1 == NULL) {
7060 				freemsg(mp1);
7061 				connp = first_connp;
7062 				break;
7063 			}
7064 		} else {
7065 			first_mp1 = NULL;
7066 		}
7067 		CONN_INC_REF(connp);
7068 		mutex_exit(&connfp->connf_lock);
7069 		/*
7070 		 * IPQoS notes: We don't send the packet for policy
7071 		 * processing here, will do it for the last one (below).
7072 		 * i.e. we do it per-packet now, but if we do policy
7073 		 * processing per-conn, then we would need to do it
7074 		 * here too.
7075 		 */
7076 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7077 		    ipha, flags, recv_ill, B_FALSE);
7078 		mutex_enter(&connfp->connf_lock);
7079 		/* Follow the next pointer before releasing the conn. */
7080 		next_connp = connp->conn_next;
7081 		IP_STAT(ip_udp_fanmb);
7082 		CONN_DEC_REF(connp);
7083 		connp = next_connp;
7084 	}
7085 
7086 	/* Last one.  Send it upstream. */
7087 	mutex_exit(&connfp->connf_lock);
7088 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7089 	    recv_ill, ip_policy);
7090 	IP_STAT(ip_udp_fanmb);
7091 	CONN_DEC_REF(connp);
7092 	return;
7093 
7094 notfound:
7095 
7096 	mutex_exit(&connfp->connf_lock);
7097 	IP_STAT(ip_udp_fanothers);
7098 	/*
7099 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7100 	 * have already been matched above, since they live in the IPv4
7101 	 * fanout tables. This implies we only need to
7102 	 * check for IPv6 in6addr_any endpoints here.
7103 	 * Thus we compare using ipv6_all_zeros instead of the destination
7104 	 * address, except for the multicast group membership lookup which
7105 	 * uses the IPv4 destination.
7106 	 */
7107 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7108 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
7109 	mutex_enter(&connfp->connf_lock);
7110 	connp = connfp->connf_head;
7111 	if (!broadcast && !CLASSD(dst)) {
7112 		while (connp != NULL) {
7113 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7114 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7115 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7116 			    !connp->conn_ipv6_v6only)
7117 				break;
7118 			connp = connp->conn_next;
7119 		}
7120 
7121 		if (connp != NULL && is_system_labeled() &&
7122 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7123 		    connp))
7124 			connp = NULL;
7125 
7126 		if (connp == NULL || connp->conn_upq == NULL) {
7127 			/*
7128 			 * No one bound to this port.  Is
7129 			 * there a client that wants all
7130 			 * unclaimed datagrams?
7131 			 */
7132 			mutex_exit(&connfp->connf_lock);
7133 
7134 			if (mctl_present)
7135 				first_mp->b_cont = mp;
7136 			else
7137 				first_mp = mp;
7138 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
7139 				ip_fanout_proto(q, first_mp, ill, ipha,
7140 				    flags | IP_FF_RAWIP, mctl_present,
7141 				    ip_policy, recv_ill, zoneid);
7142 			} else {
7143 				if (ip_fanout_send_icmp(q, first_mp, flags,
7144 				    ICMP_DEST_UNREACHABLE,
7145 				    ICMP_PORT_UNREACHABLE,
7146 				    mctl_present, zoneid)) {
7147 					BUMP_MIB(ill->ill_ip_mib,
7148 					    udpIfStatsNoPorts);
7149 				}
7150 			}
7151 			return;
7152 		}
7153 
7154 		CONN_INC_REF(connp);
7155 		mutex_exit(&connfp->connf_lock);
7156 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7157 		    flags, recv_ill, ip_policy);
7158 		CONN_DEC_REF(connp);
7159 		return;
7160 	}
7161 	/*
7162 	 * IPv4 multicast packet being delivered to an AF_INET6
7163 	 * in6addr_any endpoint.
7164 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7165 	 * and not conn_wantpacket_v6() since any multicast membership is
7166 	 * for an IPv4-mapped multicast address.
7167 	 * The packet is sent to all clients in all zones that have joined the
7168 	 * group and match the port.
7169 	 */
7170 	while (connp != NULL) {
7171 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7172 		    srcport, v6src) &&
7173 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7174 		    (!is_system_labeled() ||
7175 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7176 		    connp)))
7177 			break;
7178 		connp = connp->conn_next;
7179 	}
7180 
7181 	if (connp == NULL || connp->conn_upq == NULL) {
7182 		/*
7183 		 * No one bound to this port.  Is
7184 		 * there a client that wants all
7185 		 * unclaimed datagrams?
7186 		 */
7187 		mutex_exit(&connfp->connf_lock);
7188 
7189 		if (mctl_present)
7190 			first_mp->b_cont = mp;
7191 		else
7192 			first_mp = mp;
7193 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
7194 			ip_fanout_proto(q, first_mp, ill, ipha,
7195 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7196 			    recv_ill, zoneid);
7197 		} else {
7198 			/*
7199 			 * We used to attempt to send an icmp error here, but
7200 			 * since this is known to be a multicast packet
7201 			 * and we don't send icmp errors in response to
7202 			 * multicast, just drop the packet and give up sooner.
7203 			 */
7204 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7205 			freemsg(first_mp);
7206 		}
7207 		return;
7208 	}
7209 
7210 	first_connp = connp;
7211 
7212 	CONN_INC_REF(connp);
7213 	connp = connp->conn_next;
7214 	for (;;) {
7215 		while (connp != NULL) {
7216 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7217 			    ipv6_all_zeros, srcport, v6src) &&
7218 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7219 			    (!is_system_labeled() ||
7220 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7221 			    shared_addr, connp)))
7222 				break;
7223 			connp = connp->conn_next;
7224 		}
7225 		/*
7226 		 * Just copy the data part alone. The mctl part is
7227 		 * needed just for verifying policy and it is never
7228 		 * sent up.
7229 		 */
7230 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7231 		    ((mp1 = copymsg(mp)) == NULL))) {
7232 			/*
7233 			 * No more intested clients or memory
7234 			 * allocation failed
7235 			 */
7236 			connp = first_connp;
7237 			break;
7238 		}
7239 		if (first_mp != NULL) {
7240 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7241 			    ipsec_info_type == IPSEC_IN);
7242 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7243 			if (first_mp1 == NULL) {
7244 				freemsg(mp1);
7245 				connp = first_connp;
7246 				break;
7247 			}
7248 		} else {
7249 			first_mp1 = NULL;
7250 		}
7251 		CONN_INC_REF(connp);
7252 		mutex_exit(&connfp->connf_lock);
7253 		/*
7254 		 * IPQoS notes: We don't send the packet for policy
7255 		 * processing here, will do it for the last one (below).
7256 		 * i.e. we do it per-packet now, but if we do policy
7257 		 * processing per-conn, then we would need to do it
7258 		 * here too.
7259 		 */
7260 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7261 		    ipha, flags, recv_ill, B_FALSE);
7262 		mutex_enter(&connfp->connf_lock);
7263 		/* Follow the next pointer before releasing the conn. */
7264 		next_connp = connp->conn_next;
7265 		CONN_DEC_REF(connp);
7266 		connp = next_connp;
7267 	}
7268 
7269 	/* Last one.  Send it upstream. */
7270 	mutex_exit(&connfp->connf_lock);
7271 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7272 	    recv_ill, ip_policy);
7273 	CONN_DEC_REF(connp);
7274 }
7275 
7276 /*
7277  * Complete the ip_wput header so that it
7278  * is possible to generate ICMP
7279  * errors.
7280  */
7281 int
7282 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
7283 {
7284 	ire_t *ire;
7285 
7286 	if (ipha->ipha_src == INADDR_ANY) {
7287 		ire = ire_lookup_local(zoneid);
7288 		if (ire == NULL) {
7289 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7290 			return (1);
7291 		}
7292 		ipha->ipha_src = ire->ire_addr;
7293 		ire_refrele(ire);
7294 	}
7295 	ipha->ipha_ttl = ip_def_ttl;
7296 	ipha->ipha_hdr_checksum = 0;
7297 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7298 	return (0);
7299 }
7300 
7301 /*
7302  * Nobody should be sending
7303  * packets up this stream
7304  */
7305 static void
7306 ip_lrput(queue_t *q, mblk_t *mp)
7307 {
7308 	mblk_t *mp1;
7309 
7310 	switch (mp->b_datap->db_type) {
7311 	case M_FLUSH:
7312 		/* Turn around */
7313 		if (*mp->b_rptr & FLUSHW) {
7314 			*mp->b_rptr &= ~FLUSHR;
7315 			qreply(q, mp);
7316 			return;
7317 		}
7318 		break;
7319 	}
7320 	/* Could receive messages that passed through ar_rput */
7321 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7322 		mp1->b_prev = mp1->b_next = NULL;
7323 	freemsg(mp);
7324 }
7325 
7326 /* Nobody should be sending packets down this stream */
7327 /* ARGSUSED */
7328 void
7329 ip_lwput(queue_t *q, mblk_t *mp)
7330 {
7331 	freemsg(mp);
7332 }
7333 
7334 /*
7335  * Move the first hop in any source route to ipha_dst and remove that part of
7336  * the source route.  Called by other protocols.  Errors in option formatting
7337  * are ignored - will be handled by ip_wput_options Return the final
7338  * destination (either ipha_dst or the last entry in a source route.)
7339  */
7340 ipaddr_t
7341 ip_massage_options(ipha_t *ipha)
7342 {
7343 	ipoptp_t	opts;
7344 	uchar_t		*opt;
7345 	uint8_t		optval;
7346 	uint8_t		optlen;
7347 	ipaddr_t	dst;
7348 	int		i;
7349 	ire_t		*ire;
7350 
7351 	ip2dbg(("ip_massage_options\n"));
7352 	dst = ipha->ipha_dst;
7353 	for (optval = ipoptp_first(&opts, ipha);
7354 	    optval != IPOPT_EOL;
7355 	    optval = ipoptp_next(&opts)) {
7356 		opt = opts.ipoptp_cur;
7357 		switch (optval) {
7358 			uint8_t off;
7359 		case IPOPT_SSRR:
7360 		case IPOPT_LSRR:
7361 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7362 				ip1dbg(("ip_massage_options: bad src route\n"));
7363 				break;
7364 			}
7365 			optlen = opts.ipoptp_len;
7366 			off = opt[IPOPT_OFFSET];
7367 			off--;
7368 		redo_srr:
7369 			if (optlen < IP_ADDR_LEN ||
7370 			    off > optlen - IP_ADDR_LEN) {
7371 				/* End of source route */
7372 				ip1dbg(("ip_massage_options: end of SR\n"));
7373 				break;
7374 			}
7375 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7376 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7377 			    ntohl(dst)));
7378 			/*
7379 			 * Check if our address is present more than
7380 			 * once as consecutive hops in source route.
7381 			 * XXX verify per-interface ip_forwarding
7382 			 * for source route?
7383 			 */
7384 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7385 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
7386 			if (ire != NULL) {
7387 				ire_refrele(ire);
7388 				off += IP_ADDR_LEN;
7389 				goto redo_srr;
7390 			}
7391 			if (dst == htonl(INADDR_LOOPBACK)) {
7392 				ip1dbg(("ip_massage_options: loopback addr in "
7393 				    "source route!\n"));
7394 				break;
7395 			}
7396 			/*
7397 			 * Update ipha_dst to be the first hop and remove the
7398 			 * first hop from the source route (by overwriting
7399 			 * part of the option with NOP options).
7400 			 */
7401 			ipha->ipha_dst = dst;
7402 			/* Put the last entry in dst */
7403 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7404 			    3;
7405 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7406 
7407 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7408 			    ntohl(dst)));
7409 			/* Move down and overwrite */
7410 			opt[IP_ADDR_LEN] = opt[0];
7411 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7412 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7413 			for (i = 0; i < IP_ADDR_LEN; i++)
7414 				opt[i] = IPOPT_NOP;
7415 			break;
7416 		}
7417 	}
7418 	return (dst);
7419 }
7420 
7421 /*
7422  * This function's job is to forward data to the reverse tunnel (FA->HA)
7423  * after doing a few checks. It is assumed that the incoming interface
7424  * of the packet is always different than the outgoing interface and the
7425  * ire_type of the found ire has to be a non-resolver type.
7426  *
7427  * IPQoS notes
7428  * IP policy is invoked twice for a forwarded packet, once on the read side
7429  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7430  * enabled.
7431  */
7432 static void
7433 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7434 {
7435 	ipha_t		*ipha;
7436 	queue_t		*q;
7437 	uint32_t 	pkt_len;
7438 #define	rptr    ((uchar_t *)ipha)
7439 	uint32_t 	sum;
7440 	uint32_t 	max_frag;
7441 	mblk_t		*first_mp;
7442 	uint32_t	ill_index;
7443 	ipxmit_state_t	pktxmit_state;
7444 	ill_t		*out_ill;
7445 
7446 	ASSERT(ire != NULL);
7447 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7448 	ASSERT(ire->ire_stq != NULL);
7449 
7450 	/* Initiate read side IPPF processing */
7451 	if (IPP_ENABLED(IPP_FWD_IN)) {
7452 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7453 		ip_process(IPP_FWD_IN, &mp, ill_index);
7454 		if (mp == NULL) {
7455 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7456 			    "dropped during IPPF processing\n"));
7457 			return;
7458 		}
7459 	}
7460 
7461 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7462 		ILLF_ROUTER) == 0) ||
7463 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7464 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7465 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7466 		    "forwarding is not turned on\n"));
7467 		goto drop_pkt;
7468 	}
7469 
7470 	/*
7471 	 * Don't forward if the interface is down
7472 	 */
7473 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7474 		goto discard_pkt;
7475 	}
7476 
7477 	ipha = (ipha_t *)mp->b_rptr;
7478 	pkt_len = ntohs(ipha->ipha_length);
7479 	/* Adjust the checksum to reflect the ttl decrement. */
7480 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7481 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7482 	if (ipha->ipha_ttl-- <= 1) {
7483 		if (ip_csum_hdr(ipha)) {
7484 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7485 			goto drop_pkt;
7486 		}
7487 		q = ire->ire_stq;
7488 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7489 		    BPRI_HI)) == NULL) {
7490 			goto discard_pkt;
7491 		}
7492 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7493 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7494 		/* Sent by forwarding path, and router is global zone */
7495 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7496 		    GLOBAL_ZONEID);
7497 		return;
7498 	}
7499 
7500 	/* Get the ill_index of the ILL */
7501 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7502 
7503 	/*
7504 	 * This location is chosen for the placement of the forwarding hook
7505 	 * because at this point we know that we have a path out for the
7506 	 * packet but haven't yet applied any logic (such as fragmenting)
7507 	 * that happen as part of transmitting the packet out.
7508 	 */
7509 	out_ill = ire->ire_ipif->ipif_ill;
7510 
7511 	DTRACE_PROBE4(ip4__forwarding__start,
7512 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7513 
7514 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
7515 	    in_ill, out_ill, ipha, mp, mp);
7516 
7517 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7518 
7519 	if (mp == NULL)
7520 		return;
7521 	pkt_len = ntohs(ipha->ipha_length);
7522 
7523 	/*
7524 	 * ip_mrtun_forward is only used by foreign agent to reverse
7525 	 * tunnel the incoming packet. So it does not do any option
7526 	 * processing for source routing.
7527 	 */
7528 	max_frag = ire->ire_max_frag;
7529 	if (pkt_len > max_frag) {
7530 		/*
7531 		 * It needs fragging on its way out.  We haven't
7532 		 * verified the header checksum yet.  Since we
7533 		 * are going to put a surely good checksum in the
7534 		 * outgoing header, we have to make sure that it
7535 		 * was good coming in.
7536 		 */
7537 		if (ip_csum_hdr(ipha)) {
7538 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7539 			goto drop_pkt;
7540 		}
7541 
7542 		/* Initiate write side IPPF processing */
7543 		if (IPP_ENABLED(IPP_FWD_OUT)) {
7544 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7545 			if (mp == NULL) {
7546 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7547 				    "dropped/deferred during ip policy "\
7548 				    "processing\n"));
7549 				return;
7550 			}
7551 		}
7552 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7553 		    BPRI_HI)) == NULL) {
7554 			goto discard_pkt;
7555 		}
7556 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7557 		mp = first_mp;
7558 
7559 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
7560 		return;
7561 	}
7562 
7563 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7564 
7565 	ASSERT(ire->ire_ipif != NULL);
7566 
7567 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7568 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7569 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
7570 	    NULL, out_ill, ipha, mp, mp);
7571 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7572 	if (mp == NULL)
7573 		return;
7574 
7575 	/* Now send the packet to the tunnel interface */
7576 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7577 	q = ire->ire_stq;
7578 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7579 	if ((pktxmit_state == SEND_FAILED) ||
7580 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7581 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7582 		    q->q_ptr));
7583 	}
7584 
7585 	return;
7586 discard_pkt:
7587 	BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
7588 drop_pkt:;
7589 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7590 	freemsg(mp);
7591 #undef	rptr
7592 }
7593 
7594 /*
7595  * Fills the ipsec_out_t data structure with appropriate fields and
7596  * prepends it to mp which contains the IP hdr + data that was meant
7597  * to be forwarded. Please note that ipsec_out_info data structure
7598  * is used here to communicate the outgoing ill path at ip_wput()
7599  * for the ICMP error packet. This has nothing to do with ipsec IP
7600  * security. ipsec_out_t is really used to pass the info to the module
7601  * IP where this information cannot be extracted from conn.
7602  * This functions is called by ip_mrtun_forward().
7603  */
7604 void
7605 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7606 {
7607 	ipsec_out_t	*io;
7608 
7609 	ASSERT(xmit_ill != NULL);
7610 	first_mp->b_datap->db_type = M_CTL;
7611 	first_mp->b_wptr += sizeof (ipsec_info_t);
7612 	/*
7613 	 * This is to pass info to ip_wput in absence of conn.
7614 	 * ipsec_out_secure will be B_FALSE because of this.
7615 	 * Thus ipsec_out_secure being B_FALSE indicates that
7616 	 * this is not IPSEC security related information.
7617 	 */
7618 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7619 	io = (ipsec_out_t *)first_mp->b_rptr;
7620 	io->ipsec_out_type = IPSEC_OUT;
7621 	io->ipsec_out_len = sizeof (ipsec_out_t);
7622 	first_mp->b_cont = mp;
7623 	io->ipsec_out_ill_index =
7624 	    xmit_ill->ill_phyint->phyint_ifindex;
7625 	io->ipsec_out_xmit_if = B_TRUE;
7626 }
7627 
7628 /*
7629  * Return the network mask
7630  * associated with the specified address.
7631  */
7632 ipaddr_t
7633 ip_net_mask(ipaddr_t addr)
7634 {
7635 	uchar_t	*up = (uchar_t *)&addr;
7636 	ipaddr_t mask = 0;
7637 	uchar_t	*maskp = (uchar_t *)&mask;
7638 
7639 #if defined(__i386) || defined(__amd64)
7640 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7641 #endif
7642 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7643 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7644 #endif
7645 	if (CLASSD(addr)) {
7646 		maskp[0] = 0xF0;
7647 		return (mask);
7648 	}
7649 	if (addr == 0)
7650 		return (0);
7651 	maskp[0] = 0xFF;
7652 	if ((up[0] & 0x80) == 0)
7653 		return (mask);
7654 
7655 	maskp[1] = 0xFF;
7656 	if ((up[0] & 0xC0) == 0x80)
7657 		return (mask);
7658 
7659 	maskp[2] = 0xFF;
7660 	if ((up[0] & 0xE0) == 0xC0)
7661 		return (mask);
7662 
7663 	/* Must be experimental or multicast, indicate as much */
7664 	return ((ipaddr_t)0);
7665 }
7666 
7667 /*
7668  * Select an ill for the packet by considering load spreading across
7669  * a different ill in the group if dst_ill is part of some group.
7670  */
7671 ill_t *
7672 ip_newroute_get_dst_ill(ill_t *dst_ill)
7673 {
7674 	ill_t *ill;
7675 
7676 	/*
7677 	 * We schedule irrespective of whether the source address is
7678 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7679 	 */
7680 	ill = illgrp_scheduler(dst_ill);
7681 	if (ill == NULL)
7682 		return (NULL);
7683 
7684 	/*
7685 	 * For groups with names ip_sioctl_groupname ensures that all
7686 	 * ills are of same type. For groups without names, ifgrp_insert
7687 	 * ensures this.
7688 	 */
7689 	ASSERT(dst_ill->ill_type == ill->ill_type);
7690 
7691 	return (ill);
7692 }
7693 
7694 /*
7695  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7696  */
7697 ill_t *
7698 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7699 {
7700 	ill_t *ret_ill;
7701 
7702 	ASSERT(ifindex != 0);
7703 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7704 	if (ret_ill == NULL ||
7705 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7706 		if (isv6) {
7707 			if (ill != NULL) {
7708 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7709 			} else {
7710 				BUMP_MIB(&ip6_mib, ipIfStatsOutDiscards);
7711 			}
7712 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7713 			    "bad ifindex %d.\n", ifindex));
7714 		} else {
7715 			if (ill != NULL) {
7716 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7717 			} else {
7718 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
7719 			}
7720 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7721 			    "bad ifindex %d.\n", ifindex));
7722 		}
7723 		if (ret_ill != NULL)
7724 			ill_refrele(ret_ill);
7725 		freemsg(first_mp);
7726 		return (NULL);
7727 	}
7728 
7729 	return (ret_ill);
7730 }
7731 
7732 /*
7733  * IPv4 -
7734  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7735  * out a packet to a destination address for which we do not have specific
7736  * (or sufficient) routing information.
7737  *
7738  * NOTE : These are the scopes of some of the variables that point at IRE,
7739  *	  which needs to be followed while making any future modifications
7740  *	  to avoid memory leaks.
7741  *
7742  *	- ire and sire are the entries looked up initially by
7743  *	  ire_ftable_lookup.
7744  *	- ipif_ire is used to hold the interface ire associated with
7745  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7746  *	  it before branching out to error paths.
7747  *	- save_ire is initialized before ire_create, so that ire returned
7748  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7749  *	  before breaking out of the switch.
7750  *
7751  *	Thus on failures, we have to REFRELE only ire and sire, if they
7752  *	are not NULL.
7753  */
7754 void
7755 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7756     zoneid_t zoneid)
7757 {
7758 	areq_t	*areq;
7759 	ipaddr_t gw = 0;
7760 	ire_t	*ire = NULL;
7761 	mblk_t	*res_mp;
7762 	ipaddr_t *addrp;
7763 	ipaddr_t nexthop_addr;
7764 	ipif_t  *src_ipif = NULL;
7765 	ill_t	*dst_ill = NULL;
7766 	ipha_t  *ipha;
7767 	ire_t	*sire = NULL;
7768 	mblk_t	*first_mp;
7769 	ire_t	*save_ire;
7770 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7771 	ushort_t ire_marks = 0;
7772 	boolean_t mctl_present;
7773 	ipsec_out_t *io;
7774 	mblk_t	*saved_mp;
7775 	ire_t	*first_sire = NULL;
7776 	mblk_t	*copy_mp = NULL;
7777 	mblk_t	*xmit_mp = NULL;
7778 	ipaddr_t save_dst;
7779 	uint32_t multirt_flags =
7780 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7781 	boolean_t multirt_is_resolvable;
7782 	boolean_t multirt_resolve_next;
7783 	boolean_t do_attach_ill = B_FALSE;
7784 	boolean_t ip_nexthop = B_FALSE;
7785 	tsol_ire_gw_secattr_t *attrp = NULL;
7786 	tsol_gcgrp_t *gcgrp = NULL;
7787 	tsol_gcgrp_addr_t ga;
7788 
7789 	if (ip_debug > 2) {
7790 		/* ip1dbg */
7791 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7792 	}
7793 
7794 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7795 	if (mctl_present) {
7796 		io = (ipsec_out_t *)first_mp->b_rptr;
7797 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7798 		ASSERT(zoneid == io->ipsec_out_zoneid);
7799 		ASSERT(zoneid != ALL_ZONES);
7800 	}
7801 
7802 	ipha = (ipha_t *)mp->b_rptr;
7803 
7804 	/* All multicast lookups come through ip_newroute_ipif() */
7805 	if (CLASSD(dst)) {
7806 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7807 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7808 		freemsg(first_mp);
7809 		return;
7810 	}
7811 
7812 	if (mctl_present && io->ipsec_out_attach_if) {
7813 		/* ip_grab_attach_ill returns a held ill */
7814 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7815 		    io->ipsec_out_ill_index, B_FALSE);
7816 
7817 		/* Failure case frees things for us. */
7818 		if (attach_ill == NULL)
7819 			return;
7820 
7821 		/*
7822 		 * Check if we need an ire that will not be
7823 		 * looked up by anybody else i.e. HIDDEN.
7824 		 */
7825 		if (ill_is_probeonly(attach_ill))
7826 			ire_marks = IRE_MARK_HIDDEN;
7827 	}
7828 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7829 		ip_nexthop = B_TRUE;
7830 		nexthop_addr = io->ipsec_out_nexthop_addr;
7831 	}
7832 	/*
7833 	 * If this IRE is created for forwarding or it is not for
7834 	 * traffic for congestion controlled protocols, mark it as temporary.
7835 	 */
7836 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7837 		ire_marks |= IRE_MARK_TEMPORARY;
7838 
7839 	/*
7840 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7841 	 * chain until it gets the most specific information available.
7842 	 * For example, we know that there is no IRE_CACHE for this dest,
7843 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7844 	 * ire_ftable_lookup will look up the gateway, etc.
7845 	 * Check if in_ill != NULL. If it is true, the packet must be
7846 	 * from an incoming interface where RTA_SRCIFP is set.
7847 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7848 	 * to the destination, of equal netmask length in the forward table,
7849 	 * will be recursively explored. If no information is available
7850 	 * for the final gateway of that route, we force the returned ire
7851 	 * to be equal to sire using MATCH_IRE_PARENT.
7852 	 * At least, in this case we have a starting point (in the buckets)
7853 	 * to look for other routes to the destination in the forward table.
7854 	 * This is actually used only for multirouting, where a list
7855 	 * of routes has to be processed in sequence.
7856 	 *
7857 	 * In the process of coming up with the most specific information,
7858 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7859 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7860 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7861 	 * Two caveats when handling incomplete ire's in ip_newroute:
7862 	 * - we should be careful when accessing its ire_nce (specifically
7863 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7864 	 * - not all legacy code path callers are prepared to handle
7865 	 *   incomplete ire's, so we should not create/add incomplete
7866 	 *   ire_cache entries here. (See discussion about temporary solution
7867 	 *   further below).
7868 	 *
7869 	 * In order to minimize packet dropping, and to preserve existing
7870 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7871 	 * gateway, and instead use the IF_RESOLVER ire to send out
7872 	 * another request to ARP (this is achieved by passing the
7873 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7874 	 * arp response comes back in ip_wput_nondata, we will create
7875 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7876 	 *
7877 	 * Note that this is a temporary solution; the correct solution is
7878 	 * to create an incomplete  per-dst ire_cache entry, and send the
7879 	 * packet out when the gw's nce is resolved. In order to achieve this,
7880 	 * all packet processing must have been completed prior to calling
7881 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7882 	 * to be modified to accomodate this solution.
7883 	 */
7884 	if (in_ill != NULL) {
7885 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7886 		    in_ill, MATCH_IRE_TYPE);
7887 	} else if (ip_nexthop) {
7888 		/*
7889 		 * The first time we come here, we look for an IRE_INTERFACE
7890 		 * entry for the specified nexthop, set the dst to be the
7891 		 * nexthop address and create an IRE_CACHE entry for the
7892 		 * nexthop. The next time around, we are able to find an
7893 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7894 		 * nexthop address and create an IRE_CACHE entry for the
7895 		 * destination address via the specified nexthop.
7896 		 */
7897 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7898 		    MBLK_GETLABEL(mp));
7899 		if (ire != NULL) {
7900 			gw = nexthop_addr;
7901 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7902 		} else {
7903 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7904 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7905 			    MBLK_GETLABEL(mp),
7906 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7907 			if (ire != NULL) {
7908 				dst = nexthop_addr;
7909 			}
7910 		}
7911 	} else if (attach_ill == NULL) {
7912 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7913 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7914 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7915 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7916 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7917 	} else {
7918 		/*
7919 		 * attach_ill is set only for communicating with
7920 		 * on-link hosts. So, don't look for DEFAULT.
7921 		 */
7922 		ipif_t	*attach_ipif;
7923 
7924 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7925 		if (attach_ipif == NULL) {
7926 			ill_refrele(attach_ill);
7927 			goto icmp_err_ret;
7928 		}
7929 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7930 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7931 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7932 		    MATCH_IRE_SECATTR);
7933 		ipif_refrele(attach_ipif);
7934 	}
7935 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7936 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7937 
7938 	/*
7939 	 * This loop is run only once in most cases.
7940 	 * We loop to resolve further routes only when the destination
7941 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7942 	 */
7943 	do {
7944 		/* Clear the previous iteration's values */
7945 		if (src_ipif != NULL) {
7946 			ipif_refrele(src_ipif);
7947 			src_ipif = NULL;
7948 		}
7949 		if (dst_ill != NULL) {
7950 			ill_refrele(dst_ill);
7951 			dst_ill = NULL;
7952 		}
7953 
7954 		multirt_resolve_next = B_FALSE;
7955 		/*
7956 		 * We check if packets have to be multirouted.
7957 		 * In this case, given the current <ire, sire> couple,
7958 		 * we look for the next suitable <ire, sire>.
7959 		 * This check is done in ire_multirt_lookup(),
7960 		 * which applies various criteria to find the next route
7961 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7962 		 * unchanged if it detects it has not been tried yet.
7963 		 */
7964 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7965 			ip3dbg(("ip_newroute: starting next_resolution "
7966 			    "with first_mp %p, tag %d\n",
7967 			    (void *)first_mp,
7968 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7969 
7970 			ASSERT(sire != NULL);
7971 			multirt_is_resolvable =
7972 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7973 				MBLK_GETLABEL(mp));
7974 
7975 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7976 			    "ire %p, sire %p\n",
7977 			    multirt_is_resolvable,
7978 			    (void *)ire, (void *)sire));
7979 
7980 			if (!multirt_is_resolvable) {
7981 				/*
7982 				 * No more multirt route to resolve; give up
7983 				 * (all routes resolved or no more
7984 				 * resolvable routes).
7985 				 */
7986 				if (ire != NULL) {
7987 					ire_refrele(ire);
7988 					ire = NULL;
7989 				}
7990 			} else {
7991 				ASSERT(sire != NULL);
7992 				ASSERT(ire != NULL);
7993 				/*
7994 				 * We simply use first_sire as a flag that
7995 				 * indicates if a resolvable multirt route
7996 				 * has already been found.
7997 				 * If it is not the case, we may have to send
7998 				 * an ICMP error to report that the
7999 				 * destination is unreachable.
8000 				 * We do not IRE_REFHOLD first_sire.
8001 				 */
8002 				if (first_sire == NULL) {
8003 					first_sire = sire;
8004 				}
8005 			}
8006 		}
8007 		if (ire == NULL) {
8008 			if (ip_debug > 3) {
8009 				/* ip2dbg */
8010 				pr_addr_dbg("ip_newroute: "
8011 				    "can't resolve %s\n", AF_INET, &dst);
8012 			}
8013 			ip3dbg(("ip_newroute: "
8014 			    "ire %p, sire %p, first_sire %p\n",
8015 			    (void *)ire, (void *)sire, (void *)first_sire));
8016 
8017 			if (sire != NULL) {
8018 				ire_refrele(sire);
8019 				sire = NULL;
8020 			}
8021 
8022 			if (first_sire != NULL) {
8023 				/*
8024 				 * At least one multirt route has been found
8025 				 * in the same call to ip_newroute();
8026 				 * there is no need to report an ICMP error.
8027 				 * first_sire was not IRE_REFHOLDed.
8028 				 */
8029 				MULTIRT_DEBUG_UNTAG(first_mp);
8030 				freemsg(first_mp);
8031 				return;
8032 			}
8033 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8034 			    RTA_DST);
8035 			if (attach_ill != NULL)
8036 				ill_refrele(attach_ill);
8037 			goto icmp_err_ret;
8038 		}
8039 
8040 		/*
8041 		 * When RTA_SRCIFP is used to add a route, then an interface
8042 		 * route is added in the source interface's routing table.
8043 		 * If the outgoing interface of this route is of type
8044 		 * IRE_IF_RESOLVER, then upon creation of the ire,
8045 		 * ire_nce->nce_res_mp is set to NULL.
8046 		 * Later, when this route is first used for forwarding
8047 		 * a packet, ip_newroute() is called
8048 		 * to resolve the hardware address of the outgoing ipif.
8049 		 * We do not come here for IRE_IF_NORESOLVER entries in the
8050 		 * source interface based table. We only come here if the
8051 		 * outgoing interface is a resolver interface and we don't
8052 		 * have the ire_nce->nce_res_mp information yet.
8053 		 * If in_ill is not null that means it is called from
8054 		 * ip_rput.
8055 		 */
8056 
8057 		ASSERT(ire->ire_in_ill == NULL ||
8058 		    (ire->ire_type == IRE_IF_RESOLVER &&
8059 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
8060 
8061 		/*
8062 		 * Verify that the returned IRE does not have either
8063 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8064 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8065 		 */
8066 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8067 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8068 			if (attach_ill != NULL)
8069 				ill_refrele(attach_ill);
8070 			goto icmp_err_ret;
8071 		}
8072 		/*
8073 		 * Increment the ire_ob_pkt_count field for ire if it is an
8074 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8075 		 * increment the same for the parent IRE, sire, if it is some
8076 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
8077 		 * and HOST_REDIRECT).
8078 		 */
8079 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8080 			UPDATE_OB_PKT_COUNT(ire);
8081 			ire->ire_last_used_time = lbolt;
8082 		}
8083 
8084 		if (sire != NULL) {
8085 			gw = sire->ire_gateway_addr;
8086 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8087 			    IRE_INTERFACE)) == 0);
8088 			UPDATE_OB_PKT_COUNT(sire);
8089 			sire->ire_last_used_time = lbolt;
8090 		}
8091 		/*
8092 		 * We have a route to reach the destination.
8093 		 *
8094 		 * 1) If the interface is part of ill group, try to get a new
8095 		 *    ill taking load spreading into account.
8096 		 *
8097 		 * 2) After selecting the ill, get a source address that
8098 		 *    might create good inbound load spreading.
8099 		 *    ipif_select_source does this for us.
8100 		 *
8101 		 * If the application specified the ill (ifindex), we still
8102 		 * load spread. Only if the packets needs to go out
8103 		 * specifically on a given ill e.g. binding to
8104 		 * IPIF_NOFAILOVER address, then we don't try to use a
8105 		 * different ill for load spreading.
8106 		 */
8107 		if (attach_ill == NULL) {
8108 			/*
8109 			 * Don't perform outbound load spreading in the
8110 			 * case of an RTF_MULTIRT route, as we actually
8111 			 * typically want to replicate outgoing packets
8112 			 * through particular interfaces.
8113 			 */
8114 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8115 				dst_ill = ire->ire_ipif->ipif_ill;
8116 				/* for uniformity */
8117 				ill_refhold(dst_ill);
8118 			} else {
8119 				/*
8120 				 * If we are here trying to create an IRE_CACHE
8121 				 * for an offlink destination and have the
8122 				 * IRE_CACHE for the next hop and the latter is
8123 				 * using virtual IP source address selection i.e
8124 				 * it's ire->ire_ipif is pointing to a virtual
8125 				 * network interface (vni) then
8126 				 * ip_newroute_get_dst_ll() will return the vni
8127 				 * interface as the dst_ill. Since the vni is
8128 				 * virtual i.e not associated with any physical
8129 				 * interface, it cannot be the dst_ill, hence
8130 				 * in such a case call ip_newroute_get_dst_ll()
8131 				 * with the stq_ill instead of the ire_ipif ILL.
8132 				 * The function returns a refheld ill.
8133 				 */
8134 				if ((ire->ire_type == IRE_CACHE) &&
8135 				    IS_VNI(ire->ire_ipif->ipif_ill))
8136 					dst_ill = ip_newroute_get_dst_ill(
8137 						ire->ire_stq->q_ptr);
8138 				else
8139 					dst_ill = ip_newroute_get_dst_ill(
8140 						ire->ire_ipif->ipif_ill);
8141 			}
8142 			if (dst_ill == NULL) {
8143 				if (ip_debug > 2) {
8144 					pr_addr_dbg("ip_newroute: "
8145 					    "no dst ill for dst"
8146 					    " %s\n", AF_INET, &dst);
8147 				}
8148 				goto icmp_err_ret;
8149 			}
8150 		} else {
8151 			dst_ill = ire->ire_ipif->ipif_ill;
8152 			/* for uniformity */
8153 			ill_refhold(dst_ill);
8154 			/*
8155 			 * We should have found a route matching ill as we
8156 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8157 			 * Rather than asserting, when there is a mismatch,
8158 			 * we just drop the packet.
8159 			 */
8160 			if (dst_ill != attach_ill) {
8161 				ip0dbg(("ip_newroute: Packet dropped as "
8162 				    "IPIF_NOFAILOVER ill is %s, "
8163 				    "ire->ire_ipif->ipif_ill is %s\n",
8164 				    attach_ill->ill_name,
8165 				    dst_ill->ill_name));
8166 				ill_refrele(attach_ill);
8167 				goto icmp_err_ret;
8168 			}
8169 		}
8170 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8171 		if (attach_ill != NULL) {
8172 			ill_refrele(attach_ill);
8173 			attach_ill = NULL;
8174 			do_attach_ill = B_TRUE;
8175 		}
8176 		ASSERT(dst_ill != NULL);
8177 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8178 
8179 		/*
8180 		 * Pick the best source address from dst_ill.
8181 		 *
8182 		 * 1) If it is part of a multipathing group, we would
8183 		 *    like to spread the inbound packets across different
8184 		 *    interfaces. ipif_select_source picks a random source
8185 		 *    across the different ills in the group.
8186 		 *
8187 		 * 2) If it is not part of a multipathing group, we try
8188 		 *    to pick the source address from the destination
8189 		 *    route. Clustering assumes that when we have multiple
8190 		 *    prefixes hosted on an interface, the prefix of the
8191 		 *    source address matches the prefix of the destination
8192 		 *    route. We do this only if the address is not
8193 		 *    DEPRECATED.
8194 		 *
8195 		 * 3) If the conn is in a different zone than the ire, we
8196 		 *    need to pick a source address from the right zone.
8197 		 *
8198 		 * NOTE : If we hit case (1) above, the prefix of the source
8199 		 *	  address picked may not match the prefix of the
8200 		 *	  destination routes prefix as ipif_select_source
8201 		 *	  does not look at "dst" while picking a source
8202 		 *	  address.
8203 		 *	  If we want the same behavior as (2), we will need
8204 		 *	  to change the behavior of ipif_select_source.
8205 		 */
8206 		ASSERT(src_ipif == NULL);
8207 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8208 			/*
8209 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8210 			 * Check that the ipif matching the requested source
8211 			 * address still exists.
8212 			 */
8213 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8214 			    zoneid, NULL, NULL, NULL, NULL);
8215 		}
8216 		if (src_ipif == NULL) {
8217 			ire_marks |= IRE_MARK_USESRC_CHECK;
8218 			if ((dst_ill->ill_group != NULL) ||
8219 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8220 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8221 			    ire->ire_zoneid != ALL_ZONES) ||
8222 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8223 				/*
8224 				 * If the destination is reachable via a
8225 				 * given gateway, the selected source address
8226 				 * should be in the same subnet as the gateway.
8227 				 * Otherwise, the destination is not reachable.
8228 				 *
8229 				 * If there are no interfaces on the same subnet
8230 				 * as the destination, ipif_select_source gives
8231 				 * first non-deprecated interface which might be
8232 				 * on a different subnet than the gateway.
8233 				 * This is not desirable. Hence pass the dst_ire
8234 				 * source address to ipif_select_source.
8235 				 * It is sure that the destination is reachable
8236 				 * with the dst_ire source address subnet.
8237 				 * So passing dst_ire source address to
8238 				 * ipif_select_source will make sure that the
8239 				 * selected source will be on the same subnet
8240 				 * as dst_ire source address.
8241 				 */
8242 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8243 				src_ipif = ipif_select_source(dst_ill, saddr,
8244 				    zoneid);
8245 				if (src_ipif == NULL) {
8246 					if (ip_debug > 2) {
8247 						pr_addr_dbg("ip_newroute: "
8248 						    "no src for dst %s ",
8249 						    AF_INET, &dst);
8250 						printf("through interface %s\n",
8251 						    dst_ill->ill_name);
8252 					}
8253 					goto icmp_err_ret;
8254 				}
8255 			} else {
8256 				src_ipif = ire->ire_ipif;
8257 				ASSERT(src_ipif != NULL);
8258 				/* hold src_ipif for uniformity */
8259 				ipif_refhold(src_ipif);
8260 			}
8261 		}
8262 
8263 		/*
8264 		 * Assign a source address while we have the conn.
8265 		 * We can't have ip_wput_ire pick a source address when the
8266 		 * packet returns from arp since we need to look at
8267 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8268 		 * going through arp.
8269 		 *
8270 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8271 		 *	  it uses ip6i to store this information.
8272 		 */
8273 		if (ipha->ipha_src == INADDR_ANY &&
8274 		    (connp == NULL || !connp->conn_unspec_src)) {
8275 			ipha->ipha_src = src_ipif->ipif_src_addr;
8276 		}
8277 		if (ip_debug > 3) {
8278 			/* ip2dbg */
8279 			pr_addr_dbg("ip_newroute: first hop %s\n",
8280 			    AF_INET, &gw);
8281 		}
8282 		ip2dbg(("\tire type %s (%d)\n",
8283 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8284 
8285 		/*
8286 		 * The TTL of multirouted packets is bounded by the
8287 		 * ip_multirt_ttl ndd variable.
8288 		 */
8289 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8290 			/* Force TTL of multirouted packets */
8291 			if ((ip_multirt_ttl > 0) &&
8292 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
8293 				ip2dbg(("ip_newroute: forcing multirt TTL "
8294 				    "to %d (was %d), dst 0x%08x\n",
8295 				    ip_multirt_ttl, ipha->ipha_ttl,
8296 				    ntohl(sire->ire_addr)));
8297 				ipha->ipha_ttl = ip_multirt_ttl;
8298 			}
8299 		}
8300 		/*
8301 		 * At this point in ip_newroute(), ire is either the
8302 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8303 		 * destination or an IRE_INTERFACE type that should be used
8304 		 * to resolve an on-subnet destination or an on-subnet
8305 		 * next-hop gateway.
8306 		 *
8307 		 * In the IRE_CACHE case, we have the following :
8308 		 *
8309 		 * 1) src_ipif - used for getting a source address.
8310 		 *
8311 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8312 		 *    means packets using this IRE_CACHE will go out on
8313 		 *    dst_ill.
8314 		 *
8315 		 * 3) The IRE sire will point to the prefix that is the
8316 		 *    longest  matching route for the destination. These
8317 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8318 		 *
8319 		 *    The newly created IRE_CACHE entry for the off-subnet
8320 		 *    destination is tied to both the prefix route and the
8321 		 *    interface route used to resolve the next-hop gateway
8322 		 *    via the ire_phandle and ire_ihandle fields,
8323 		 *    respectively.
8324 		 *
8325 		 * In the IRE_INTERFACE case, we have the following :
8326 		 *
8327 		 * 1) src_ipif - used for getting a source address.
8328 		 *
8329 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8330 		 *    means packets using the IRE_CACHE that we will build
8331 		 *    here will go out on dst_ill.
8332 		 *
8333 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8334 		 *    to be created will only be tied to the IRE_INTERFACE
8335 		 *    that was derived from the ire_ihandle field.
8336 		 *
8337 		 *    If sire is non-NULL, it means the destination is
8338 		 *    off-link and we will first create the IRE_CACHE for the
8339 		 *    gateway. Next time through ip_newroute, we will create
8340 		 *    the IRE_CACHE for the final destination as described
8341 		 *    above.
8342 		 *
8343 		 * In both cases, after the current resolution has been
8344 		 * completed (or possibly initialised, in the IRE_INTERFACE
8345 		 * case), the loop may be re-entered to attempt the resolution
8346 		 * of another RTF_MULTIRT route.
8347 		 *
8348 		 * When an IRE_CACHE entry for the off-subnet destination is
8349 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8350 		 * for further processing in emission loops.
8351 		 */
8352 		save_ire = ire;
8353 		switch (ire->ire_type) {
8354 		case IRE_CACHE: {
8355 			ire_t	*ipif_ire;
8356 			mblk_t	*ire_fp_mp;
8357 
8358 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8359 			if (gw == 0)
8360 				gw = ire->ire_gateway_addr;
8361 			/*
8362 			 * We need 3 ire's to create a new cache ire for an
8363 			 * off-link destination from the cache ire of the
8364 			 * gateway.
8365 			 *
8366 			 *	1. The prefix ire 'sire' (Note that this does
8367 			 *	   not apply to the conn_nexthop_set case)
8368 			 *	2. The cache ire of the gateway 'ire'
8369 			 *	3. The interface ire 'ipif_ire'
8370 			 *
8371 			 * We have (1) and (2). We lookup (3) below.
8372 			 *
8373 			 * If there is no interface route to the gateway,
8374 			 * it is a race condition, where we found the cache
8375 			 * but the interface route has been deleted.
8376 			 */
8377 			if (ip_nexthop) {
8378 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8379 			} else {
8380 				ipif_ire =
8381 				    ire_ihandle_lookup_offlink(ire, sire);
8382 			}
8383 			if (ipif_ire == NULL) {
8384 				ip1dbg(("ip_newroute: "
8385 				    "ire_ihandle_lookup_offlink failed\n"));
8386 				goto icmp_err_ret;
8387 			}
8388 			/*
8389 			 * XXX We are using the same res_mp
8390 			 * (DL_UNITDATA_REQ) though the save_ire is not
8391 			 * pointing at the same ill.
8392 			 * This is incorrect. We need to send it up to the
8393 			 * resolver to get the right res_mp. For ethernets
8394 			 * this may be okay (ill_type == DL_ETHER).
8395 			 */
8396 			res_mp = save_ire->ire_nce->nce_res_mp;
8397 			ire_fp_mp = NULL;
8398 			/*
8399 			 * save_ire's nce_fp_mp can't change since it is
8400 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8401 			 * LOCK_IRE_FP_MP does not do any useful work in
8402 			 * the case of IRE_CACHE. So we don't use it below.
8403 			 */
8404 			if (save_ire->ire_stq == dst_ill->ill_wq)
8405 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8406 
8407 			/*
8408 			 * Check cached gateway IRE for any security
8409 			 * attributes; if found, associate the gateway
8410 			 * credentials group to the destination IRE.
8411 			 */
8412 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8413 				mutex_enter(&attrp->igsa_lock);
8414 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8415 					GCGRP_REFHOLD(gcgrp);
8416 				mutex_exit(&attrp->igsa_lock);
8417 			}
8418 
8419 			ire = ire_create(
8420 			    (uchar_t *)&dst,		/* dest address */
8421 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8422 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8423 			    (uchar_t *)&gw,		/* gateway address */
8424 			    NULL,
8425 			    &save_ire->ire_max_frag,
8426 			    ire_fp_mp,			/* Fast Path header */
8427 			    dst_ill->ill_rq,		/* recv-from queue */
8428 			    dst_ill->ill_wq,		/* send-to queue */
8429 			    IRE_CACHE,			/* IRE type */
8430 			    res_mp,
8431 			    src_ipif,
8432 			    in_ill,			/* incoming ill */
8433 			    (sire != NULL) ?
8434 				sire->ire_mask : 0, 	/* Parent mask */
8435 			    (sire != NULL) ?
8436 				sire->ire_phandle : 0,  /* Parent handle */
8437 			    ipif_ire->ire_ihandle,	/* Interface handle */
8438 			    (sire != NULL) ? (sire->ire_flags &
8439 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8440 			    (sire != NULL) ?
8441 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8442 			    NULL,
8443 			    gcgrp);
8444 
8445 			if (ire == NULL) {
8446 				if (gcgrp != NULL) {
8447 					GCGRP_REFRELE(gcgrp);
8448 					gcgrp = NULL;
8449 				}
8450 				ire_refrele(ipif_ire);
8451 				ire_refrele(save_ire);
8452 				break;
8453 			}
8454 
8455 			/* reference now held by IRE */
8456 			gcgrp = NULL;
8457 
8458 			ire->ire_marks |= ire_marks;
8459 
8460 			/*
8461 			 * Prevent sire and ipif_ire from getting deleted.
8462 			 * The newly created ire is tied to both of them via
8463 			 * the phandle and ihandle respectively.
8464 			 */
8465 			if (sire != NULL) {
8466 				IRB_REFHOLD(sire->ire_bucket);
8467 				/* Has it been removed already ? */
8468 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8469 					IRB_REFRELE(sire->ire_bucket);
8470 					ire_refrele(ipif_ire);
8471 					ire_refrele(save_ire);
8472 					break;
8473 				}
8474 			}
8475 
8476 			IRB_REFHOLD(ipif_ire->ire_bucket);
8477 			/* Has it been removed already ? */
8478 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8479 				IRB_REFRELE(ipif_ire->ire_bucket);
8480 				if (sire != NULL)
8481 					IRB_REFRELE(sire->ire_bucket);
8482 				ire_refrele(ipif_ire);
8483 				ire_refrele(save_ire);
8484 				break;
8485 			}
8486 
8487 			xmit_mp = first_mp;
8488 			/*
8489 			 * In the case of multirouting, a copy
8490 			 * of the packet is done before its sending.
8491 			 * The copy is used to attempt another
8492 			 * route resolution, in a next loop.
8493 			 */
8494 			if (ire->ire_flags & RTF_MULTIRT) {
8495 				copy_mp = copymsg(first_mp);
8496 				if (copy_mp != NULL) {
8497 					xmit_mp = copy_mp;
8498 					MULTIRT_DEBUG_TAG(first_mp);
8499 				}
8500 			}
8501 			ire_add_then_send(q, ire, xmit_mp);
8502 			ire_refrele(save_ire);
8503 
8504 			/* Assert that sire is not deleted yet. */
8505 			if (sire != NULL) {
8506 				ASSERT(sire->ire_ptpn != NULL);
8507 				IRB_REFRELE(sire->ire_bucket);
8508 			}
8509 
8510 			/* Assert that ipif_ire is not deleted yet. */
8511 			ASSERT(ipif_ire->ire_ptpn != NULL);
8512 			IRB_REFRELE(ipif_ire->ire_bucket);
8513 			ire_refrele(ipif_ire);
8514 
8515 			/*
8516 			 * If copy_mp is not NULL, multirouting was
8517 			 * requested. We loop to initiate a next
8518 			 * route resolution attempt, starting from sire.
8519 			 */
8520 			if (copy_mp != NULL) {
8521 				/*
8522 				 * Search for the next unresolved
8523 				 * multirt route.
8524 				 */
8525 				copy_mp = NULL;
8526 				ipif_ire = NULL;
8527 				ire = NULL;
8528 				multirt_resolve_next = B_TRUE;
8529 				continue;
8530 			}
8531 			if (sire != NULL)
8532 				ire_refrele(sire);
8533 			ipif_refrele(src_ipif);
8534 			ill_refrele(dst_ill);
8535 			return;
8536 		}
8537 		case IRE_IF_NORESOLVER: {
8538 			/*
8539 			 * We have what we need to build an IRE_CACHE.
8540 			 *
8541 			 * Create a new res_mp with the IP gateway address
8542 			 * in destination address in the DLPI hdr if the
8543 			 * physical length is exactly 4 bytes.
8544 			 */
8545 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8546 				uchar_t *addr;
8547 
8548 				if (gw)
8549 					addr = (uchar_t *)&gw;
8550 				else
8551 					addr = (uchar_t *)&dst;
8552 
8553 				res_mp = ill_dlur_gen(addr,
8554 				    dst_ill->ill_phys_addr_length,
8555 				    dst_ill->ill_sap,
8556 				    dst_ill->ill_sap_length);
8557 
8558 				if (res_mp == NULL) {
8559 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8560 					break;
8561 				}
8562 			} else if (dst_ill->ill_resolver_mp == NULL) {
8563 				ip1dbg(("ip_newroute: dst_ill %p "
8564 				    "for IF_NORESOLV ire %p has "
8565 				    "no ill_resolver_mp\n",
8566 				    (void *)dst_ill, (void *)ire));
8567 				break;
8568 			} else {
8569 				res_mp = NULL;
8570 			}
8571 
8572 			/*
8573 			 * TSol note: We are creating the ire cache for the
8574 			 * destination 'dst'. If 'dst' is offlink, going
8575 			 * through the first hop 'gw', the security attributes
8576 			 * of 'dst' must be set to point to the gateway
8577 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8578 			 * is possible that 'dst' is a potential gateway that is
8579 			 * referenced by some route that has some security
8580 			 * attributes. Thus in the former case, we need to do a
8581 			 * gcgrp_lookup of 'gw' while in the latter case we
8582 			 * need to do gcgrp_lookup of 'dst' itself.
8583 			 */
8584 			ga.ga_af = AF_INET;
8585 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8586 			    &ga.ga_addr);
8587 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8588 
8589 			ire = ire_create(
8590 			    (uchar_t *)&dst,		/* dest address */
8591 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8592 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8593 			    (uchar_t *)&gw,		/* gateway address */
8594 			    NULL,
8595 			    &save_ire->ire_max_frag,
8596 			    NULL,			/* Fast Path header */
8597 			    dst_ill->ill_rq,		/* recv-from queue */
8598 			    dst_ill->ill_wq,		/* send-to queue */
8599 			    IRE_CACHE,
8600 			    res_mp,
8601 			    src_ipif,
8602 			    in_ill,			/* Incoming ill */
8603 			    save_ire->ire_mask,		/* Parent mask */
8604 			    (sire != NULL) ?		/* Parent handle */
8605 				sire->ire_phandle : 0,
8606 			    save_ire->ire_ihandle,	/* Interface handle */
8607 			    (sire != NULL) ? sire->ire_flags &
8608 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8609 			    &(save_ire->ire_uinfo),
8610 			    NULL,
8611 			    gcgrp);
8612 
8613 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8614 				freeb(res_mp);
8615 
8616 			if (ire == NULL) {
8617 				if (gcgrp != NULL) {
8618 					GCGRP_REFRELE(gcgrp);
8619 					gcgrp = NULL;
8620 				}
8621 				ire_refrele(save_ire);
8622 				break;
8623 			}
8624 
8625 			/* reference now held by IRE */
8626 			gcgrp = NULL;
8627 
8628 			ire->ire_marks |= ire_marks;
8629 
8630 			/* Prevent save_ire from getting deleted */
8631 			IRB_REFHOLD(save_ire->ire_bucket);
8632 			/* Has it been removed already ? */
8633 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8634 				IRB_REFRELE(save_ire->ire_bucket);
8635 				ire_refrele(save_ire);
8636 				break;
8637 			}
8638 
8639 			/*
8640 			 * In the case of multirouting, a copy
8641 			 * of the packet is made before it is sent.
8642 			 * The copy is used in the next
8643 			 * loop to attempt another resolution.
8644 			 */
8645 			xmit_mp = first_mp;
8646 			if ((sire != NULL) &&
8647 			    (sire->ire_flags & RTF_MULTIRT)) {
8648 				copy_mp = copymsg(first_mp);
8649 				if (copy_mp != NULL) {
8650 					xmit_mp = copy_mp;
8651 					MULTIRT_DEBUG_TAG(first_mp);
8652 				}
8653 			}
8654 			ire_add_then_send(q, ire, xmit_mp);
8655 
8656 			/* Assert that it is not deleted yet. */
8657 			ASSERT(save_ire->ire_ptpn != NULL);
8658 			IRB_REFRELE(save_ire->ire_bucket);
8659 			ire_refrele(save_ire);
8660 
8661 			if (copy_mp != NULL) {
8662 				/*
8663 				 * If we found a (no)resolver, we ignore any
8664 				 * trailing top priority IRE_CACHE in further
8665 				 * loops. This ensures that we do not omit any
8666 				 * (no)resolver.
8667 				 * This IRE_CACHE, if any, will be processed
8668 				 * by another thread entering ip_newroute().
8669 				 * IRE_CACHE entries, if any, will be processed
8670 				 * by another thread entering ip_newroute(),
8671 				 * (upon resolver response, for instance).
8672 				 * This aims to force parallel multirt
8673 				 * resolutions as soon as a packet must be sent.
8674 				 * In the best case, after the tx of only one
8675 				 * packet, all reachable routes are resolved.
8676 				 * Otherwise, the resolution of all RTF_MULTIRT
8677 				 * routes would require several emissions.
8678 				 */
8679 				multirt_flags &= ~MULTIRT_CACHEGW;
8680 
8681 				/*
8682 				 * Search for the next unresolved multirt
8683 				 * route.
8684 				 */
8685 				copy_mp = NULL;
8686 				save_ire = NULL;
8687 				ire = NULL;
8688 				multirt_resolve_next = B_TRUE;
8689 				continue;
8690 			}
8691 
8692 			/*
8693 			 * Don't need sire anymore
8694 			 */
8695 			if (sire != NULL)
8696 				ire_refrele(sire);
8697 
8698 			ipif_refrele(src_ipif);
8699 			ill_refrele(dst_ill);
8700 			return;
8701 		}
8702 		case IRE_IF_RESOLVER:
8703 			/*
8704 			 * We can't build an IRE_CACHE yet, but at least we
8705 			 * found a resolver that can help.
8706 			 */
8707 			res_mp = dst_ill->ill_resolver_mp;
8708 			if (!OK_RESOLVER_MP(res_mp))
8709 				break;
8710 
8711 			/*
8712 			 * To be at this point in the code with a non-zero gw
8713 			 * means that dst is reachable through a gateway that
8714 			 * we have never resolved.  By changing dst to the gw
8715 			 * addr we resolve the gateway first.
8716 			 * When ire_add_then_send() tries to put the IP dg
8717 			 * to dst, it will reenter ip_newroute() at which
8718 			 * time we will find the IRE_CACHE for the gw and
8719 			 * create another IRE_CACHE in case IRE_CACHE above.
8720 			 */
8721 			if (gw != INADDR_ANY) {
8722 				/*
8723 				 * The source ipif that was determined above was
8724 				 * relative to the destination address, not the
8725 				 * gateway's. If src_ipif was not taken out of
8726 				 * the IRE_IF_RESOLVER entry, we'll need to call
8727 				 * ipif_select_source() again.
8728 				 */
8729 				if (src_ipif != ire->ire_ipif) {
8730 					ipif_refrele(src_ipif);
8731 					src_ipif = ipif_select_source(dst_ill,
8732 					    gw, zoneid);
8733 					if (src_ipif == NULL) {
8734 						if (ip_debug > 2) {
8735 							pr_addr_dbg(
8736 							    "ip_newroute: no "
8737 							    "src for gw %s ",
8738 							    AF_INET, &gw);
8739 							printf("through "
8740 							    "interface %s\n",
8741 							    dst_ill->ill_name);
8742 						}
8743 						goto icmp_err_ret;
8744 					}
8745 				}
8746 				save_dst = dst;
8747 				dst = gw;
8748 				gw = INADDR_ANY;
8749 			}
8750 
8751 			/*
8752 			 * We obtain a partial IRE_CACHE which we will pass
8753 			 * along with the resolver query.  When the response
8754 			 * comes back it will be there ready for us to add.
8755 			 * The ire_max_frag is atomically set under the
8756 			 * irebucket lock in ire_add_v[46].
8757 			 */
8758 
8759 			ire = ire_create_mp(
8760 			    (uchar_t *)&dst,		/* dest address */
8761 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8762 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8763 			    (uchar_t *)&gw,		/* gateway address */
8764 			    NULL,			/* no in_src_addr */
8765 			    NULL,			/* ire_max_frag */
8766 			    NULL,			/* Fast Path header */
8767 			    dst_ill->ill_rq,		/* recv-from queue */
8768 			    dst_ill->ill_wq,		/* send-to queue */
8769 			    IRE_CACHE,
8770 			    NULL,
8771 			    src_ipif,			/* Interface ipif */
8772 			    in_ill,			/* Incoming ILL */
8773 			    save_ire->ire_mask,		/* Parent mask */
8774 			    0,
8775 			    save_ire->ire_ihandle,	/* Interface handle */
8776 			    0,				/* flags if any */
8777 			    &(save_ire->ire_uinfo),
8778 			    NULL,
8779 			    NULL);
8780 
8781 			if (ire == NULL) {
8782 				ire_refrele(save_ire);
8783 				break;
8784 			}
8785 
8786 			if ((sire != NULL) &&
8787 			    (sire->ire_flags & RTF_MULTIRT)) {
8788 				copy_mp = copymsg(first_mp);
8789 				if (copy_mp != NULL)
8790 					MULTIRT_DEBUG_TAG(copy_mp);
8791 			}
8792 
8793 			ire->ire_marks |= ire_marks;
8794 
8795 			/*
8796 			 * Construct message chain for the resolver
8797 			 * of the form:
8798 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8799 			 * Packet could contain a IPSEC_OUT mp.
8800 			 *
8801 			 * NOTE : ire will be added later when the response
8802 			 * comes back from ARP. If the response does not
8803 			 * come back, ARP frees the packet. For this reason,
8804 			 * we can't REFHOLD the bucket of save_ire to prevent
8805 			 * deletions. We may not be able to REFRELE the bucket
8806 			 * if the response never comes back. Thus, before
8807 			 * adding the ire, ire_add_v4 will make sure that the
8808 			 * interface route does not get deleted. This is the
8809 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8810 			 * where we can always prevent deletions because of
8811 			 * the synchronous nature of adding IRES i.e
8812 			 * ire_add_then_send is called after creating the IRE.
8813 			 */
8814 			ASSERT(ire->ire_mp != NULL);
8815 			ire->ire_mp->b_cont = first_mp;
8816 			/* Have saved_mp handy, for cleanup if canput fails */
8817 			saved_mp = mp;
8818 			mp = copyb(res_mp);
8819 			if (mp == NULL) {
8820 				/* Prepare for cleanup */
8821 				mp = saved_mp; /* pkt */
8822 				ire_delete(ire); /* ire_mp */
8823 				ire = NULL;
8824 				ire_refrele(save_ire);
8825 				if (copy_mp != NULL) {
8826 					MULTIRT_DEBUG_UNTAG(copy_mp);
8827 					freemsg(copy_mp);
8828 					copy_mp = NULL;
8829 				}
8830 				break;
8831 			}
8832 			linkb(mp, ire->ire_mp);
8833 
8834 			/*
8835 			 * Fill in the source and dest addrs for the resolver.
8836 			 * NOTE: this depends on memory layouts imposed by
8837 			 * ill_init().
8838 			 */
8839 			areq = (areq_t *)mp->b_rptr;
8840 			addrp = (ipaddr_t *)((char *)areq +
8841 			    areq->areq_sender_addr_offset);
8842 			if (do_attach_ill) {
8843 				/*
8844 				 * This is bind to no failover case.
8845 				 * arp packet also must go out on attach_ill.
8846 				 */
8847 				ASSERT(ipha->ipha_src != NULL);
8848 				*addrp = ipha->ipha_src;
8849 			} else {
8850 				*addrp = save_ire->ire_src_addr;
8851 			}
8852 
8853 			ire_refrele(save_ire);
8854 			addrp = (ipaddr_t *)((char *)areq +
8855 			    areq->areq_target_addr_offset);
8856 			*addrp = dst;
8857 			/* Up to the resolver. */
8858 			if (canputnext(dst_ill->ill_rq) &&
8859 			    !(dst_ill->ill_arp_closing)) {
8860 				putnext(dst_ill->ill_rq, mp);
8861 				ire = NULL;
8862 				if (copy_mp != NULL) {
8863 					/*
8864 					 * If we found a resolver, we ignore
8865 					 * any trailing top priority IRE_CACHE
8866 					 * in the further loops. This ensures
8867 					 * that we do not omit any resolver.
8868 					 * IRE_CACHE entries, if any, will be
8869 					 * processed next time we enter
8870 					 * ip_newroute().
8871 					 */
8872 					multirt_flags &= ~MULTIRT_CACHEGW;
8873 					/*
8874 					 * Search for the next unresolved
8875 					 * multirt route.
8876 					 */
8877 					first_mp = copy_mp;
8878 					copy_mp = NULL;
8879 					/* Prepare the next resolution loop. */
8880 					mp = first_mp;
8881 					EXTRACT_PKT_MP(mp, first_mp,
8882 					    mctl_present);
8883 					if (mctl_present)
8884 						io = (ipsec_out_t *)
8885 						    first_mp->b_rptr;
8886 					ipha = (ipha_t *)mp->b_rptr;
8887 
8888 					ASSERT(sire != NULL);
8889 
8890 					dst = save_dst;
8891 					multirt_resolve_next = B_TRUE;
8892 					continue;
8893 				}
8894 
8895 				if (sire != NULL)
8896 					ire_refrele(sire);
8897 
8898 				/*
8899 				 * The response will come back in ip_wput
8900 				 * with db_type IRE_DB_TYPE.
8901 				 */
8902 				ipif_refrele(src_ipif);
8903 				ill_refrele(dst_ill);
8904 				return;
8905 			} else {
8906 				/* Prepare for cleanup */
8907 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8908 				    mp);
8909 				mp->b_cont = NULL;
8910 				freeb(mp); /* areq */
8911 				/*
8912 				 * this is an ire that is not added to the
8913 				 * cache. ire_freemblk will handle the release
8914 				 * of any resources associated with the ire.
8915 				 */
8916 				ire_delete(ire); /* ire_mp */
8917 				mp = saved_mp; /* pkt */
8918 				ire = NULL;
8919 				if (copy_mp != NULL) {
8920 					MULTIRT_DEBUG_UNTAG(copy_mp);
8921 					freemsg(copy_mp);
8922 					copy_mp = NULL;
8923 				}
8924 				break;
8925 			}
8926 		default:
8927 			break;
8928 		}
8929 	} while (multirt_resolve_next);
8930 
8931 	ip1dbg(("ip_newroute: dropped\n"));
8932 	/* Did this packet originate externally? */
8933 	if (mp->b_prev) {
8934 		mp->b_next = NULL;
8935 		mp->b_prev = NULL;
8936 		if (in_ill != NULL) {
8937 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
8938 		} else {
8939 			BUMP_MIB(&ip_mib, ipIfStatsInDiscards);
8940 		}
8941 	} else {
8942 		if (dst_ill != NULL) {
8943 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8944 		} else {
8945 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
8946 		}
8947 	}
8948 	ASSERT(copy_mp == NULL);
8949 	MULTIRT_DEBUG_UNTAG(first_mp);
8950 	freemsg(first_mp);
8951 	if (ire != NULL)
8952 		ire_refrele(ire);
8953 	if (sire != NULL)
8954 		ire_refrele(sire);
8955 	if (src_ipif != NULL)
8956 		ipif_refrele(src_ipif);
8957 	if (dst_ill != NULL)
8958 		ill_refrele(dst_ill);
8959 	return;
8960 
8961 icmp_err_ret:
8962 	ip1dbg(("ip_newroute: no route\n"));
8963 	if (src_ipif != NULL)
8964 		ipif_refrele(src_ipif);
8965 	if (dst_ill != NULL)
8966 		ill_refrele(dst_ill);
8967 	if (sire != NULL)
8968 		ire_refrele(sire);
8969 	/* Did this packet originate externally? */
8970 	if (mp->b_prev) {
8971 		mp->b_next = NULL;
8972 		mp->b_prev = NULL;
8973 		if (in_ill != NULL) {
8974 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInNoRoutes);
8975 		} else {
8976 			BUMP_MIB(&ip_mib, ipIfStatsInNoRoutes);
8977 		}
8978 		q = WR(q);
8979 	} else {
8980 		/*
8981 		 * There is no outgoing ill, so just increment the
8982 		 * system MIB.
8983 		 */
8984 		BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
8985 		/*
8986 		 * Since ip_wput() isn't close to finished, we fill
8987 		 * in enough of the header for credible error reporting.
8988 		 */
8989 		if (ip_hdr_complete(ipha, zoneid)) {
8990 			/* Failed */
8991 			MULTIRT_DEBUG_UNTAG(first_mp);
8992 			freemsg(first_mp);
8993 			if (ire != NULL)
8994 				ire_refrele(ire);
8995 			return;
8996 		}
8997 	}
8998 
8999 	/*
9000 	 * At this point we will have ire only if RTF_BLACKHOLE
9001 	 * or RTF_REJECT flags are set on the IRE. It will not
9002 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9003 	 */
9004 	if (ire != NULL) {
9005 		if (ire->ire_flags & RTF_BLACKHOLE) {
9006 			ire_refrele(ire);
9007 			MULTIRT_DEBUG_UNTAG(first_mp);
9008 			freemsg(first_mp);
9009 			return;
9010 		}
9011 		ire_refrele(ire);
9012 	}
9013 	if (ip_source_routed(ipha)) {
9014 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9015 		    zoneid);
9016 		return;
9017 	}
9018 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9019 }
9020 
9021 ip_opt_info_t zero_info;
9022 
9023 /*
9024  * IPv4 -
9025  * ip_newroute_ipif is called by ip_wput_multicast and
9026  * ip_rput_forward_multicast whenever we need to send
9027  * out a packet to a destination address for which we do not have specific
9028  * routing information. It is used when the packet will be sent out
9029  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9030  * socket option is set or icmp error message wants to go out on a particular
9031  * interface for a unicast packet.
9032  *
9033  * In most cases, the destination address is resolved thanks to the ipif
9034  * intrinsic resolver. However, there are some cases where the call to
9035  * ip_newroute_ipif must take into account the potential presence of
9036  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9037  * that uses the interface. This is specified through flags,
9038  * which can be a combination of:
9039  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9040  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9041  *   and flags. Additionally, the packet source address has to be set to
9042  *   the specified address. The caller is thus expected to set this flag
9043  *   if the packet has no specific source address yet.
9044  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9045  *   flag, the resulting ire will inherit the flag. All unresolved routes
9046  *   to the destination must be explored in the same call to
9047  *   ip_newroute_ipif().
9048  */
9049 static void
9050 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9051     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9052 {
9053 	areq_t	*areq;
9054 	ire_t	*ire = NULL;
9055 	mblk_t	*res_mp;
9056 	ipaddr_t *addrp;
9057 	mblk_t *first_mp;
9058 	ire_t	*save_ire = NULL;
9059 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9060 	ipif_t	*src_ipif = NULL;
9061 	ushort_t ire_marks = 0;
9062 	ill_t	*dst_ill = NULL;
9063 	boolean_t mctl_present;
9064 	ipsec_out_t *io;
9065 	ipha_t *ipha;
9066 	int	ihandle = 0;
9067 	mblk_t	*saved_mp;
9068 	ire_t   *fire = NULL;
9069 	mblk_t  *copy_mp = NULL;
9070 	boolean_t multirt_resolve_next;
9071 	ipaddr_t ipha_dst;
9072 
9073 	/*
9074 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9075 	 * here for uniformity
9076 	 */
9077 	ipif_refhold(ipif);
9078 
9079 	/*
9080 	 * This loop is run only once in most cases.
9081 	 * We loop to resolve further routes only when the destination
9082 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9083 	 */
9084 	do {
9085 		if (dst_ill != NULL) {
9086 			ill_refrele(dst_ill);
9087 			dst_ill = NULL;
9088 		}
9089 		if (src_ipif != NULL) {
9090 			ipif_refrele(src_ipif);
9091 			src_ipif = NULL;
9092 		}
9093 		multirt_resolve_next = B_FALSE;
9094 
9095 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9096 		    ipif->ipif_ill->ill_name));
9097 
9098 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9099 		if (mctl_present)
9100 			io = (ipsec_out_t *)first_mp->b_rptr;
9101 
9102 		ipha = (ipha_t *)mp->b_rptr;
9103 
9104 		/*
9105 		 * Save the packet destination address, we may need it after
9106 		 * the packet has been consumed.
9107 		 */
9108 		ipha_dst = ipha->ipha_dst;
9109 
9110 		/*
9111 		 * If the interface is a pt-pt interface we look for an
9112 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9113 		 * local_address and the pt-pt destination address. Otherwise
9114 		 * we just match the local address.
9115 		 * NOTE: dst could be different than ipha->ipha_dst in case
9116 		 * of sending igmp multicast packets over a point-to-point
9117 		 * connection.
9118 		 * Thus we must be careful enough to check ipha_dst to be a
9119 		 * multicast address, otherwise it will take xmit_if path for
9120 		 * multicast packets resulting into kernel stack overflow by
9121 		 * repeated calls to ip_newroute_ipif from ire_send().
9122 		 */
9123 		if (CLASSD(ipha_dst) &&
9124 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9125 			goto err_ret;
9126 		}
9127 
9128 		/*
9129 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9130 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9131 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9132 		 * propagate its flags to the new ire.
9133 		 */
9134 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9135 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9136 			ip2dbg(("ip_newroute_ipif: "
9137 			    "ipif_lookup_multi_ire("
9138 			    "ipif %p, dst %08x) = fire %p\n",
9139 			    (void *)ipif, ntohl(dst), (void *)fire));
9140 		}
9141 
9142 		if (mctl_present && io->ipsec_out_attach_if) {
9143 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9144 			    io->ipsec_out_ill_index, B_FALSE);
9145 
9146 			/* Failure case frees things for us. */
9147 			if (attach_ill == NULL) {
9148 				ipif_refrele(ipif);
9149 				if (fire != NULL)
9150 					ire_refrele(fire);
9151 				return;
9152 			}
9153 
9154 			/*
9155 			 * Check if we need an ire that will not be
9156 			 * looked up by anybody else i.e. HIDDEN.
9157 			 */
9158 			if (ill_is_probeonly(attach_ill)) {
9159 				ire_marks = IRE_MARK_HIDDEN;
9160 			}
9161 			/*
9162 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9163 			 * case.
9164 			 */
9165 			dst_ill = ipif->ipif_ill;
9166 			/* attach_ill has been refheld by ip_grab_attach_ill */
9167 			ASSERT(dst_ill == attach_ill);
9168 		} else {
9169 			/*
9170 			 * If this is set by IP_XMIT_IF, then make sure that
9171 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9172 			 * specified ill.
9173 			 */
9174 			ASSERT((connp == NULL) ||
9175 			    (connp->conn_xmit_if_ill == NULL) ||
9176 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9177 			/*
9178 			 * If the interface belongs to an interface group,
9179 			 * make sure the next possible interface in the group
9180 			 * is used.  This encourages load spreading among
9181 			 * peers in an interface group.
9182 			 * Note: load spreading is disabled for RTF_MULTIRT
9183 			 * routes.
9184 			 */
9185 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9186 			    (fire->ire_flags & RTF_MULTIRT)) {
9187 				/*
9188 				 * Don't perform outbound load spreading
9189 				 * in the case of an RTF_MULTIRT issued route,
9190 				 * we actually typically want to replicate
9191 				 * outgoing packets through particular
9192 				 * interfaces.
9193 				 */
9194 				dst_ill = ipif->ipif_ill;
9195 				ill_refhold(dst_ill);
9196 			} else {
9197 				dst_ill = ip_newroute_get_dst_ill(
9198 				    ipif->ipif_ill);
9199 			}
9200 			if (dst_ill == NULL) {
9201 				if (ip_debug > 2) {
9202 					pr_addr_dbg("ip_newroute_ipif: "
9203 					    "no dst ill for dst %s\n",
9204 					    AF_INET, &dst);
9205 				}
9206 				goto err_ret;
9207 			}
9208 		}
9209 
9210 		/*
9211 		 * Pick a source address preferring non-deprecated ones.
9212 		 * Unlike ip_newroute, we don't do any source address
9213 		 * selection here since for multicast it really does not help
9214 		 * in inbound load spreading as in the unicast case.
9215 		 */
9216 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9217 		    (fire->ire_flags & RTF_SETSRC)) {
9218 			/*
9219 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9220 			 * on that interface. This ire has RTF_SETSRC flag, so
9221 			 * the source address of the packet must be changed.
9222 			 * Check that the ipif matching the requested source
9223 			 * address still exists.
9224 			 */
9225 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9226 			    zoneid, NULL, NULL, NULL, NULL);
9227 		}
9228 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9229 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9230 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9231 		    (src_ipif == NULL)) {
9232 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9233 			if (src_ipif == NULL) {
9234 				if (ip_debug > 2) {
9235 					/* ip1dbg */
9236 					pr_addr_dbg("ip_newroute_ipif: "
9237 					    "no src for dst %s",
9238 					    AF_INET, &dst);
9239 				}
9240 				ip1dbg((" through interface %s\n",
9241 				    dst_ill->ill_name));
9242 				goto err_ret;
9243 			}
9244 			ipif_refrele(ipif);
9245 			ipif = src_ipif;
9246 			ipif_refhold(ipif);
9247 		}
9248 		if (src_ipif == NULL) {
9249 			src_ipif = ipif;
9250 			ipif_refhold(src_ipif);
9251 		}
9252 
9253 		/*
9254 		 * Assign a source address while we have the conn.
9255 		 * We can't have ip_wput_ire pick a source address when the
9256 		 * packet returns from arp since conn_unspec_src might be set
9257 		 * and we loose the conn when going through arp.
9258 		 */
9259 		if (ipha->ipha_src == INADDR_ANY &&
9260 		    (connp == NULL || !connp->conn_unspec_src)) {
9261 			ipha->ipha_src = src_ipif->ipif_src_addr;
9262 		}
9263 
9264 		/*
9265 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9266 		 * interface does not have an interface ire.
9267 		 * Example: Thousands of mobileip PPP interfaces to mobile
9268 		 * nodes. We don't want to create interface ires because
9269 		 * packets from other mobile nodes must not take the route
9270 		 * via interface ires to the visiting mobile node without
9271 		 * going through the home agent, in absence of mobileip
9272 		 * route optimization.
9273 		 */
9274 		if (CLASSD(ipha_dst) && (connp == NULL ||
9275 		    connp->conn_xmit_if_ill == NULL) &&
9276 		    infop->ip_opt_ill_index == 0) {
9277 			/* ipif_to_ire returns an held ire */
9278 			ire = ipif_to_ire(ipif);
9279 			if (ire == NULL)
9280 				goto err_ret;
9281 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9282 				goto err_ret;
9283 			/*
9284 			 * ihandle is needed when the ire is added to
9285 			 * cache table.
9286 			 */
9287 			save_ire = ire;
9288 			ihandle = save_ire->ire_ihandle;
9289 
9290 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9291 			    "flags %04x\n",
9292 			    (void *)ire, (void *)ipif, flags));
9293 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9294 			    (fire->ire_flags & RTF_MULTIRT)) {
9295 				/*
9296 				 * As requested by flags, an IRE_OFFSUBNET was
9297 				 * looked up on that interface. This ire has
9298 				 * RTF_MULTIRT flag, so the resolution loop will
9299 				 * be re-entered to resolve additional routes on
9300 				 * other interfaces. For that purpose, a copy of
9301 				 * the packet is performed at this point.
9302 				 */
9303 				fire->ire_last_used_time = lbolt;
9304 				copy_mp = copymsg(first_mp);
9305 				if (copy_mp) {
9306 					MULTIRT_DEBUG_TAG(copy_mp);
9307 				}
9308 			}
9309 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9310 			    (fire->ire_flags & RTF_SETSRC)) {
9311 				/*
9312 				 * As requested by flags, an IRE_OFFSUBET was
9313 				 * looked up on that interface. This ire has
9314 				 * RTF_SETSRC flag, so the source address of the
9315 				 * packet must be changed.
9316 				 */
9317 				ipha->ipha_src = fire->ire_src_addr;
9318 			}
9319 		} else {
9320 			ASSERT((connp == NULL) ||
9321 			    (connp->conn_xmit_if_ill != NULL) ||
9322 			    (connp->conn_dontroute) ||
9323 			    infop->ip_opt_ill_index != 0);
9324 			/*
9325 			 * The only ways we can come here are:
9326 			 * 1) IP_XMIT_IF socket option is set
9327 			 * 2) ICMP error message generated from
9328 			 *    ip_mrtun_forward() routine and it needs
9329 			 *    to go through the specified ill.
9330 			 * 3) SO_DONTROUTE socket option is set
9331 			 * 4) IP_PKTINFO option is passed in as ancillary data.
9332 			 * In all cases, the new ire will not be added
9333 			 * into cache table.
9334 			 */
9335 			ire_marks |= IRE_MARK_NOADD;
9336 		}
9337 
9338 		switch (ipif->ipif_net_type) {
9339 		case IRE_IF_NORESOLVER: {
9340 			/* We have what we need to build an IRE_CACHE. */
9341 			mblk_t	*res_mp;
9342 
9343 			/*
9344 			 * Create a new res_mp with the
9345 			 * IP gateway address as destination address in the
9346 			 * DLPI hdr if the physical length is exactly 4 bytes.
9347 			 */
9348 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9349 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9350 				    dst_ill->ill_phys_addr_length,
9351 				    dst_ill->ill_sap,
9352 				    dst_ill->ill_sap_length);
9353 			} else if (dst_ill->ill_resolver_mp == NULL) {
9354 				ip1dbg(("ip_newroute: dst_ill %p "
9355 				    "for IF_NORESOLV ire %p has "
9356 				    "no ill_resolver_mp\n",
9357 				    (void *)dst_ill, (void *)ire));
9358 				break;
9359 			} else {
9360 				/* use the value set in ip_ll_subnet_defaults */
9361 				res_mp = ill_dlur_gen(NULL,
9362 				    dst_ill->ill_phys_addr_length,
9363 				    dst_ill->ill_sap,
9364 				    dst_ill->ill_sap_length);
9365 			}
9366 
9367 			if (res_mp == NULL)
9368 				break;
9369 			/*
9370 			 * The new ire inherits the IRE_OFFSUBNET flags
9371 			 * and source address, if this was requested.
9372 			 */
9373 			ire = ire_create(
9374 			    (uchar_t *)&dst,		/* dest address */
9375 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9376 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9377 			    NULL,			/* gateway address */
9378 			    NULL,
9379 			    &ipif->ipif_mtu,
9380 			    NULL,			/* Fast Path header */
9381 			    dst_ill->ill_rq,		/* recv-from queue */
9382 			    dst_ill->ill_wq,		/* send-to queue */
9383 			    IRE_CACHE,
9384 			    res_mp,
9385 			    src_ipif,
9386 			    NULL,
9387 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9388 			    (fire != NULL) ?		/* Parent handle */
9389 				fire->ire_phandle : 0,
9390 			    ihandle,			/* Interface handle */
9391 			    (fire != NULL) ?
9392 				(fire->ire_flags &
9393 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9394 			    (save_ire == NULL ? &ire_uinfo_null :
9395 				&save_ire->ire_uinfo),
9396 			    NULL,
9397 			    NULL);
9398 
9399 			freeb(res_mp);
9400 
9401 			if (ire == NULL) {
9402 				if (save_ire != NULL)
9403 					ire_refrele(save_ire);
9404 				break;
9405 			}
9406 
9407 			ire->ire_marks |= ire_marks;
9408 
9409 			/*
9410 			 * If IRE_MARK_NOADD is set then we need to convert
9411 			 * the max_fragp to a useable value now. This is
9412 			 * normally done in ire_add_v[46]. We also need to
9413 			 * associate the ire with an nce (normally would be
9414 			 * done in ip_wput_nondata()).
9415 			 *
9416 			 * Note that IRE_MARK_NOADD packets created here
9417 			 * do not have a non-null ire_mp pointer. The null
9418 			 * value of ire_bucket indicates that they were
9419 			 * never added.
9420 			 */
9421 			if (ire->ire_marks & IRE_MARK_NOADD) {
9422 				uint_t  max_frag;
9423 
9424 				max_frag = *ire->ire_max_fragp;
9425 				ire->ire_max_fragp = NULL;
9426 				ire->ire_max_frag = max_frag;
9427 
9428 				if ((ire->ire_nce = ndp_lookup_v4(
9429 				    ire_to_ill(ire),
9430 				    (ire->ire_gateway_addr != INADDR_ANY ?
9431 				    &ire->ire_gateway_addr : &ire->ire_addr),
9432 				    B_FALSE)) == NULL) {
9433 					if (save_ire != NULL)
9434 						ire_refrele(save_ire);
9435 					break;
9436 				}
9437 				ASSERT(ire->ire_nce->nce_state ==
9438 				    ND_REACHABLE);
9439 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9440 			}
9441 
9442 			/* Prevent save_ire from getting deleted */
9443 			if (save_ire != NULL) {
9444 				IRB_REFHOLD(save_ire->ire_bucket);
9445 				/* Has it been removed already ? */
9446 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9447 					IRB_REFRELE(save_ire->ire_bucket);
9448 					ire_refrele(save_ire);
9449 					break;
9450 				}
9451 			}
9452 
9453 			ire_add_then_send(q, ire, first_mp);
9454 
9455 			/* Assert that save_ire is not deleted yet. */
9456 			if (save_ire != NULL) {
9457 				ASSERT(save_ire->ire_ptpn != NULL);
9458 				IRB_REFRELE(save_ire->ire_bucket);
9459 				ire_refrele(save_ire);
9460 				save_ire = NULL;
9461 			}
9462 			if (fire != NULL) {
9463 				ire_refrele(fire);
9464 				fire = NULL;
9465 			}
9466 
9467 			/*
9468 			 * the resolution loop is re-entered if this
9469 			 * was requested through flags and if we
9470 			 * actually are in a multirouting case.
9471 			 */
9472 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9473 				boolean_t need_resolve =
9474 				    ire_multirt_need_resolve(ipha_dst,
9475 					MBLK_GETLABEL(copy_mp));
9476 				if (!need_resolve) {
9477 					MULTIRT_DEBUG_UNTAG(copy_mp);
9478 					freemsg(copy_mp);
9479 					copy_mp = NULL;
9480 				} else {
9481 					/*
9482 					 * ipif_lookup_group() calls
9483 					 * ire_lookup_multi() that uses
9484 					 * ire_ftable_lookup() to find
9485 					 * an IRE_INTERFACE for the group.
9486 					 * In the multirt case,
9487 					 * ire_lookup_multi() then invokes
9488 					 * ire_multirt_lookup() to find
9489 					 * the next resolvable ire.
9490 					 * As a result, we obtain an new
9491 					 * interface, derived from the
9492 					 * next ire.
9493 					 */
9494 					ipif_refrele(ipif);
9495 					ipif = ipif_lookup_group(ipha_dst,
9496 					    zoneid);
9497 					ip2dbg(("ip_newroute_ipif: "
9498 					    "multirt dst %08x, ipif %p\n",
9499 					    htonl(dst), (void *)ipif));
9500 					if (ipif != NULL) {
9501 						mp = copy_mp;
9502 						copy_mp = NULL;
9503 						multirt_resolve_next = B_TRUE;
9504 						continue;
9505 					} else {
9506 						freemsg(copy_mp);
9507 					}
9508 				}
9509 			}
9510 			if (ipif != NULL)
9511 				ipif_refrele(ipif);
9512 			ill_refrele(dst_ill);
9513 			ipif_refrele(src_ipif);
9514 			return;
9515 		}
9516 		case IRE_IF_RESOLVER:
9517 			/*
9518 			 * We can't build an IRE_CACHE yet, but at least
9519 			 * we found a resolver that can help.
9520 			 */
9521 			res_mp = dst_ill->ill_resolver_mp;
9522 			if (!OK_RESOLVER_MP(res_mp))
9523 				break;
9524 
9525 			/*
9526 			 * We obtain a partial IRE_CACHE which we will pass
9527 			 * along with the resolver query.  When the response
9528 			 * comes back it will be there ready for us to add.
9529 			 * The new ire inherits the IRE_OFFSUBNET flags
9530 			 * and source address, if this was requested.
9531 			 * The ire_max_frag is atomically set under the
9532 			 * irebucket lock in ire_add_v[46]. Only in the
9533 			 * case of IRE_MARK_NOADD, we set it here itself.
9534 			 */
9535 			ire = ire_create_mp(
9536 			    (uchar_t *)&dst,		/* dest address */
9537 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9538 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9539 			    NULL,			/* gateway address */
9540 			    NULL,			/* no in_src_addr */
9541 			    (ire_marks & IRE_MARK_NOADD) ?
9542 				ipif->ipif_mtu : 0,	/* max_frag */
9543 			    NULL,			/* Fast path header */
9544 			    dst_ill->ill_rq,		/* recv-from queue */
9545 			    dst_ill->ill_wq,		/* send-to queue */
9546 			    IRE_CACHE,
9547 			    NULL,	/* let ire_nce_init figure res_mp out */
9548 			    src_ipif,
9549 			    NULL,
9550 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9551 			    (fire != NULL) ?		/* Parent handle */
9552 				fire->ire_phandle : 0,
9553 			    ihandle,			/* Interface handle */
9554 			    (fire != NULL) ?		/* flags if any */
9555 				(fire->ire_flags &
9556 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9557 			    (save_ire == NULL ? &ire_uinfo_null :
9558 				&save_ire->ire_uinfo),
9559 			    NULL,
9560 			    NULL);
9561 
9562 			if (save_ire != NULL) {
9563 				ire_refrele(save_ire);
9564 				save_ire = NULL;
9565 			}
9566 			if (ire == NULL)
9567 				break;
9568 
9569 			ire->ire_marks |= ire_marks;
9570 			/*
9571 			 * Construct message chain for the resolver of the
9572 			 * form:
9573 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9574 			 *
9575 			 * NOTE : ire will be added later when the response
9576 			 * comes back from ARP. If the response does not
9577 			 * come back, ARP frees the packet. For this reason,
9578 			 * we can't REFHOLD the bucket of save_ire to prevent
9579 			 * deletions. We may not be able to REFRELE the
9580 			 * bucket if the response never comes back.
9581 			 * Thus, before adding the ire, ire_add_v4 will make
9582 			 * sure that the interface route does not get deleted.
9583 			 * This is the only case unlike ip_newroute_v6,
9584 			 * ip_newroute_ipif_v6 where we can always prevent
9585 			 * deletions because ire_add_then_send is called after
9586 			 * creating the IRE.
9587 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9588 			 * does not add this IRE into the IRE CACHE.
9589 			 */
9590 			ASSERT(ire->ire_mp != NULL);
9591 			ire->ire_mp->b_cont = first_mp;
9592 			/* Have saved_mp handy, for cleanup if canput fails */
9593 			saved_mp = mp;
9594 			mp = copyb(res_mp);
9595 			if (mp == NULL) {
9596 				/* Prepare for cleanup */
9597 				mp = saved_mp; /* pkt */
9598 				ire_delete(ire); /* ire_mp */
9599 				ire = NULL;
9600 				if (copy_mp != NULL) {
9601 					MULTIRT_DEBUG_UNTAG(copy_mp);
9602 					freemsg(copy_mp);
9603 					copy_mp = NULL;
9604 				}
9605 				break;
9606 			}
9607 			linkb(mp, ire->ire_mp);
9608 
9609 			/*
9610 			 * Fill in the source and dest addrs for the resolver.
9611 			 * NOTE: this depends on memory layouts imposed by
9612 			 * ill_init().
9613 			 */
9614 			areq = (areq_t *)mp->b_rptr;
9615 			addrp = (ipaddr_t *)((char *)areq +
9616 			    areq->areq_sender_addr_offset);
9617 			*addrp = ire->ire_src_addr;
9618 			addrp = (ipaddr_t *)((char *)areq +
9619 			    areq->areq_target_addr_offset);
9620 			*addrp = dst;
9621 			/* Up to the resolver. */
9622 			if (canputnext(dst_ill->ill_rq) &&
9623 			    !(dst_ill->ill_arp_closing)) {
9624 				putnext(dst_ill->ill_rq, mp);
9625 				/*
9626 				 * The response will come back in ip_wput
9627 				 * with db_type IRE_DB_TYPE.
9628 				 */
9629 			} else {
9630 				mp->b_cont = NULL;
9631 				freeb(mp); /* areq */
9632 				ire_delete(ire); /* ire_mp */
9633 				saved_mp->b_next = NULL;
9634 				saved_mp->b_prev = NULL;
9635 				freemsg(first_mp); /* pkt */
9636 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9637 			}
9638 
9639 			if (fire != NULL) {
9640 				ire_refrele(fire);
9641 				fire = NULL;
9642 			}
9643 
9644 
9645 			/*
9646 			 * The resolution loop is re-entered if this was
9647 			 * requested through flags and we actually are
9648 			 * in a multirouting case.
9649 			 */
9650 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9651 				boolean_t need_resolve =
9652 				    ire_multirt_need_resolve(ipha_dst,
9653 					MBLK_GETLABEL(copy_mp));
9654 				if (!need_resolve) {
9655 					MULTIRT_DEBUG_UNTAG(copy_mp);
9656 					freemsg(copy_mp);
9657 					copy_mp = NULL;
9658 				} else {
9659 					/*
9660 					 * ipif_lookup_group() calls
9661 					 * ire_lookup_multi() that uses
9662 					 * ire_ftable_lookup() to find
9663 					 * an IRE_INTERFACE for the group.
9664 					 * In the multirt case,
9665 					 * ire_lookup_multi() then invokes
9666 					 * ire_multirt_lookup() to find
9667 					 * the next resolvable ire.
9668 					 * As a result, we obtain an new
9669 					 * interface, derived from the
9670 					 * next ire.
9671 					 */
9672 					ipif_refrele(ipif);
9673 					ipif = ipif_lookup_group(ipha_dst,
9674 					    zoneid);
9675 					if (ipif != NULL) {
9676 						mp = copy_mp;
9677 						copy_mp = NULL;
9678 						multirt_resolve_next = B_TRUE;
9679 						continue;
9680 					} else {
9681 						freemsg(copy_mp);
9682 					}
9683 				}
9684 			}
9685 			if (ipif != NULL)
9686 				ipif_refrele(ipif);
9687 			ill_refrele(dst_ill);
9688 			ipif_refrele(src_ipif);
9689 			return;
9690 		default:
9691 			break;
9692 		}
9693 	} while (multirt_resolve_next);
9694 
9695 err_ret:
9696 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9697 	if (fire != NULL)
9698 		ire_refrele(fire);
9699 	ipif_refrele(ipif);
9700 	/* Did this packet originate externally? */
9701 	if (dst_ill != NULL)
9702 		ill_refrele(dst_ill);
9703 	if (src_ipif != NULL)
9704 		ipif_refrele(src_ipif);
9705 	if (mp->b_prev || mp->b_next) {
9706 		mp->b_next = NULL;
9707 		mp->b_prev = NULL;
9708 	} else {
9709 		/*
9710 		 * Since ip_wput() isn't close to finished, we fill
9711 		 * in enough of the header for credible error reporting.
9712 		 */
9713 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9714 			/* Failed */
9715 			freemsg(first_mp);
9716 			if (ire != NULL)
9717 				ire_refrele(ire);
9718 			return;
9719 		}
9720 	}
9721 	/*
9722 	 * At this point we will have ire only if RTF_BLACKHOLE
9723 	 * or RTF_REJECT flags are set on the IRE. It will not
9724 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9725 	 */
9726 	if (ire != NULL) {
9727 		if (ire->ire_flags & RTF_BLACKHOLE) {
9728 			ire_refrele(ire);
9729 			freemsg(first_mp);
9730 			return;
9731 		}
9732 		ire_refrele(ire);
9733 	}
9734 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9735 }
9736 
9737 /* Name/Value Table Lookup Routine */
9738 char *
9739 ip_nv_lookup(nv_t *nv, int value)
9740 {
9741 	if (!nv)
9742 		return (NULL);
9743 	for (; nv->nv_name; nv++) {
9744 		if (nv->nv_value == value)
9745 			return (nv->nv_name);
9746 	}
9747 	return ("unknown");
9748 }
9749 
9750 /*
9751  * one day it can be patched to 1 from /etc/system for machines that have few
9752  * fast network interfaces feeding multiple cpus.
9753  */
9754 int ill_stream_putlocks = 0;
9755 
9756 /*
9757  * This is a module open, i.e. this is a control stream for access
9758  * to a DLPI device.  We allocate an ill_t as the instance data in
9759  * this case.
9760  */
9761 int
9762 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9763 {
9764 	uint32_t mem_cnt;
9765 	uint32_t cpu_cnt;
9766 	uint32_t min_cnt;
9767 	pgcnt_t mem_avail;
9768 	ill_t	*ill;
9769 	int	err;
9770 
9771 	/*
9772 	 * Prevent unprivileged processes from pushing IP so that
9773 	 * they can't send raw IP.
9774 	 */
9775 	if (secpolicy_net_rawaccess(credp) != 0)
9776 		return (EPERM);
9777 
9778 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9779 	q->q_ptr = WR(q)->q_ptr = ill;
9780 
9781 	/*
9782 	 * ill_init initializes the ill fields and then sends down
9783 	 * down a DL_INFO_REQ after calling qprocson.
9784 	 */
9785 	err = ill_init(q, ill);
9786 	if (err != 0) {
9787 		mi_free(ill);
9788 		q->q_ptr = NULL;
9789 		WR(q)->q_ptr = NULL;
9790 		return (err);
9791 	}
9792 
9793 	/* ill_init initializes the ipsq marking this thread as writer */
9794 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9795 	/* Wait for the DL_INFO_ACK */
9796 	mutex_enter(&ill->ill_lock);
9797 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9798 		/*
9799 		 * Return value of 0 indicates a pending signal.
9800 		 */
9801 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9802 		if (err == 0) {
9803 			mutex_exit(&ill->ill_lock);
9804 			(void) ip_close(q, 0);
9805 			return (EINTR);
9806 		}
9807 	}
9808 	mutex_exit(&ill->ill_lock);
9809 
9810 	/*
9811 	 * ip_rput_other could have set an error  in ill_error on
9812 	 * receipt of M_ERROR.
9813 	 */
9814 
9815 	err = ill->ill_error;
9816 	if (err != 0) {
9817 		(void) ip_close(q, 0);
9818 		return (err);
9819 	}
9820 
9821 	/*
9822 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9823 	 * size and the cpu speed of the machine. This is upper
9824 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9825 	 * and is lower bounded by the compile time value of
9826 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9827 	 * ip6_ire_max_bucket_cnt.
9828 	 */
9829 	mem_avail = kmem_avail();
9830 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9831 	    ip_cache_table_size / sizeof (ire_t);
9832 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9833 
9834 	min_cnt = MIN(cpu_cnt, mem_cnt);
9835 	if (min_cnt < ip_ire_min_bucket_cnt)
9836 		min_cnt = ip_ire_min_bucket_cnt;
9837 	if (ip_ire_max_bucket_cnt > min_cnt) {
9838 		ip_ire_max_bucket_cnt = min_cnt;
9839 	}
9840 
9841 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9842 	    ip6_cache_table_size / sizeof (ire_t);
9843 	min_cnt = MIN(cpu_cnt, mem_cnt);
9844 	if (min_cnt < ip6_ire_min_bucket_cnt)
9845 		min_cnt = ip6_ire_min_bucket_cnt;
9846 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9847 		ip6_ire_max_bucket_cnt = min_cnt;
9848 	}
9849 
9850 	ill->ill_credp = credp;
9851 	crhold(credp);
9852 
9853 	mutex_enter(&ip_mi_lock);
9854 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9855 	mutex_exit(&ip_mi_lock);
9856 	if (err) {
9857 		(void) ip_close(q, 0);
9858 		return (err);
9859 	}
9860 	return (0);
9861 }
9862 
9863 /* IP open routine. */
9864 int
9865 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9866 {
9867 	conn_t 		*connp;
9868 	major_t		maj;
9869 
9870 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9871 
9872 	/* Allow reopen. */
9873 	if (q->q_ptr != NULL)
9874 		return (0);
9875 
9876 	if (sflag & MODOPEN) {
9877 		/* This is a module open */
9878 		return (ip_modopen(q, devp, flag, sflag, credp));
9879 	}
9880 
9881 	/*
9882 	 * We are opening as a device. This is an IP client stream, and we
9883 	 * allocate an conn_t as the instance data.
9884 	 */
9885 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9886 	connp->conn_upq = q;
9887 	q->q_ptr = WR(q)->q_ptr = connp;
9888 
9889 	if (flag & SO_SOCKSTR)
9890 		connp->conn_flags |= IPCL_SOCKET;
9891 
9892 	/* Minor tells us which /dev entry was opened */
9893 	if (geteminor(*devp) == IPV6_MINOR) {
9894 		connp->conn_flags |= IPCL_ISV6;
9895 		connp->conn_af_isv6 = B_TRUE;
9896 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9897 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9898 	} else {
9899 		connp->conn_af_isv6 = B_FALSE;
9900 		connp->conn_pkt_isv6 = B_FALSE;
9901 	}
9902 
9903 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9904 		q->q_ptr = WR(q)->q_ptr = NULL;
9905 		CONN_DEC_REF(connp);
9906 		return (EBUSY);
9907 	}
9908 
9909 	maj = getemajor(*devp);
9910 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9911 
9912 	/*
9913 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9914 	 */
9915 	connp->conn_cred = credp;
9916 	crhold(connp->conn_cred);
9917 
9918 	/*
9919 	 * If the caller has the process-wide flag set, then default to MAC
9920 	 * exempt mode.  This allows read-down to unlabeled hosts.
9921 	 */
9922 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9923 		connp->conn_mac_exempt = B_TRUE;
9924 
9925 	connp->conn_zoneid = getzoneid();
9926 
9927 	/*
9928 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9929 	 * administrative ops.  In these cases, we just need a normal conn_t
9930 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9931 	 * an error will be returned.
9932 	 */
9933 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9934 		connp->conn_rq = q;
9935 		connp->conn_wq = WR(q);
9936 	} else {
9937 		connp->conn_ulp = IPPROTO_SCTP;
9938 		connp->conn_rq = connp->conn_wq = NULL;
9939 	}
9940 	/* Non-zero default values */
9941 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9942 
9943 	/*
9944 	 * Make the conn globally visible to walkers
9945 	 */
9946 	mutex_enter(&connp->conn_lock);
9947 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9948 	mutex_exit(&connp->conn_lock);
9949 	ASSERT(connp->conn_ref == 1);
9950 
9951 	qprocson(q);
9952 
9953 	return (0);
9954 }
9955 
9956 /*
9957  * Change q_qinfo based on the value of isv6.
9958  * This can not called on an ill queue.
9959  * Note that there is no race since either q_qinfo works for conn queues - it
9960  * is just an optimization to enter the best wput routine directly.
9961  */
9962 void
9963 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9964 {
9965 	ASSERT(q->q_flag & QREADR);
9966 	ASSERT(WR(q)->q_next == NULL);
9967 	ASSERT(q->q_ptr != NULL);
9968 
9969 	if (minor == IPV6_MINOR)  {
9970 		if (bump_mib)
9971 			BUMP_MIB(&ip6_mib, ipIfStatsOutSwitchIPVersion);
9972 		q->q_qinfo = &rinit_ipv6;
9973 		WR(q)->q_qinfo = &winit_ipv6;
9974 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9975 	} else {
9976 		if (bump_mib)
9977 			BUMP_MIB(&ip_mib, ipIfStatsOutSwitchIPVersion);
9978 		q->q_qinfo = &iprinit;
9979 		WR(q)->q_qinfo = &ipwinit;
9980 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9981 	}
9982 
9983 }
9984 
9985 /*
9986  * See if IPsec needs loading because of the options in mp.
9987  */
9988 static boolean_t
9989 ipsec_opt_present(mblk_t *mp)
9990 {
9991 	uint8_t *optcp, *next_optcp, *opt_endcp;
9992 	struct opthdr *opt;
9993 	struct T_opthdr *topt;
9994 	int opthdr_len;
9995 	t_uscalar_t optname, optlevel;
9996 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9997 	ipsec_req_t *ipsr;
9998 
9999 	/*
10000 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10001 	 * return TRUE.
10002 	 */
10003 
10004 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10005 	opt_endcp = optcp + tor->OPT_length;
10006 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10007 		opthdr_len = sizeof (struct T_opthdr);
10008 	} else {		/* O_OPTMGMT_REQ */
10009 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10010 		opthdr_len = sizeof (struct opthdr);
10011 	}
10012 	for (; optcp < opt_endcp; optcp = next_optcp) {
10013 		if (optcp + opthdr_len > opt_endcp)
10014 			return (B_FALSE);	/* Not enough option header. */
10015 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10016 			topt = (struct T_opthdr *)optcp;
10017 			optlevel = topt->level;
10018 			optname = topt->name;
10019 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10020 		} else {
10021 			opt = (struct opthdr *)optcp;
10022 			optlevel = opt->level;
10023 			optname = opt->name;
10024 			next_optcp = optcp + opthdr_len +
10025 			    _TPI_ALIGN_OPT(opt->len);
10026 		}
10027 		if ((next_optcp < optcp) || /* wraparound pointer space */
10028 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10029 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10030 			return (B_FALSE); /* bad option buffer */
10031 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10032 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10033 			/*
10034 			 * Check to see if it's an all-bypass or all-zeroes
10035 			 * IPsec request.  Don't bother loading IPsec if
10036 			 * the socket doesn't want to use it.  (A good example
10037 			 * is a bypass request.)
10038 			 *
10039 			 * Basically, if any of the non-NEVER bits are set,
10040 			 * load IPsec.
10041 			 */
10042 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10043 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10044 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10045 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10046 			    != 0)
10047 				return (B_TRUE);
10048 		}
10049 	}
10050 	return (B_FALSE);
10051 }
10052 
10053 /*
10054  * If conn is is waiting for ipsec to finish loading, kick it.
10055  */
10056 /* ARGSUSED */
10057 static void
10058 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10059 {
10060 	t_scalar_t	optreq_prim;
10061 	mblk_t		*mp;
10062 	cred_t		*cr;
10063 	int		err = 0;
10064 
10065 	/*
10066 	 * This function is called, after ipsec loading is complete.
10067 	 * Since IP checks exclusively and atomically (i.e it prevents
10068 	 * ipsec load from completing until ip_optcom_req completes)
10069 	 * whether ipsec load is complete, there cannot be a race with IP
10070 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10071 	 */
10072 	mutex_enter(&connp->conn_lock);
10073 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10074 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10075 		mp = connp->conn_ipsec_opt_mp;
10076 		connp->conn_ipsec_opt_mp = NULL;
10077 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10078 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10079 		mutex_exit(&connp->conn_lock);
10080 
10081 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10082 
10083 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10084 		if (optreq_prim == T_OPTMGMT_REQ) {
10085 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10086 			    &ip_opt_obj);
10087 		} else {
10088 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10089 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10090 			    &ip_opt_obj);
10091 		}
10092 		if (err != EINPROGRESS)
10093 			CONN_OPER_PENDING_DONE(connp);
10094 		return;
10095 	}
10096 	mutex_exit(&connp->conn_lock);
10097 }
10098 
10099 /*
10100  * Called from the ipsec_loader thread, outside any perimeter, to tell
10101  * ip qenable any of the queues waiting for the ipsec loader to
10102  * complete.
10103  *
10104  * Use ip_mi_lock to be safe here: all modifications of the mi lists
10105  * are done with this lock held, so it's guaranteed that none of the
10106  * links will change along the way.
10107  */
10108 void
10109 ip_ipsec_load_complete()
10110 {
10111 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
10112 }
10113 
10114 /*
10115  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10116  * determines the grp on which it has to become exclusive, queues the mp
10117  * and sq draining restarts the optmgmt
10118  */
10119 static boolean_t
10120 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10121 {
10122 	conn_t *connp;
10123 
10124 	/*
10125 	 * Take IPsec requests and treat them special.
10126 	 */
10127 	if (ipsec_opt_present(mp)) {
10128 		/* First check if IPsec is loaded. */
10129 		mutex_enter(&ipsec_loader_lock);
10130 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
10131 			mutex_exit(&ipsec_loader_lock);
10132 			return (B_FALSE);
10133 		}
10134 		connp = Q_TO_CONN(q);
10135 		mutex_enter(&connp->conn_lock);
10136 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10137 
10138 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10139 		connp->conn_ipsec_opt_mp = mp;
10140 		mutex_exit(&connp->conn_lock);
10141 		mutex_exit(&ipsec_loader_lock);
10142 
10143 		ipsec_loader_loadnow();
10144 		return (B_TRUE);
10145 	}
10146 	return (B_FALSE);
10147 }
10148 
10149 /*
10150  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10151  * all of them are copied to the conn_t. If the req is "zero", the policy is
10152  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10153  * fields.
10154  * We keep only the latest setting of the policy and thus policy setting
10155  * is not incremental/cumulative.
10156  *
10157  * Requests to set policies with multiple alternative actions will
10158  * go through a different API.
10159  */
10160 int
10161 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10162 {
10163 	uint_t ah_req = 0;
10164 	uint_t esp_req = 0;
10165 	uint_t se_req = 0;
10166 	ipsec_selkey_t sel;
10167 	ipsec_act_t *actp = NULL;
10168 	uint_t nact;
10169 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10170 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10171 	ipsec_policy_root_t *pr;
10172 	ipsec_policy_head_t *ph;
10173 	int fam;
10174 	boolean_t is_pol_reset;
10175 	int error = 0;
10176 
10177 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10178 
10179 	/*
10180 	 * The IP_SEC_OPT option does not allow variable length parameters,
10181 	 * hence a request cannot be NULL.
10182 	 */
10183 	if (req == NULL)
10184 		return (EINVAL);
10185 
10186 	ah_req = req->ipsr_ah_req;
10187 	esp_req = req->ipsr_esp_req;
10188 	se_req = req->ipsr_self_encap_req;
10189 
10190 	/*
10191 	 * Are we dealing with a request to reset the policy (i.e.
10192 	 * zero requests).
10193 	 */
10194 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10195 	    (esp_req & REQ_MASK) == 0 &&
10196 	    (se_req & REQ_MASK) == 0);
10197 
10198 	if (!is_pol_reset) {
10199 		/*
10200 		 * If we couldn't load IPsec, fail with "protocol
10201 		 * not supported".
10202 		 * IPsec may not have been loaded for a request with zero
10203 		 * policies, so we don't fail in this case.
10204 		 */
10205 		mutex_enter(&ipsec_loader_lock);
10206 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10207 			mutex_exit(&ipsec_loader_lock);
10208 			return (EPROTONOSUPPORT);
10209 		}
10210 		mutex_exit(&ipsec_loader_lock);
10211 
10212 		/*
10213 		 * Test for valid requests. Invalid algorithms
10214 		 * need to be tested by IPSEC code because new
10215 		 * algorithms can be added dynamically.
10216 		 */
10217 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10218 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10219 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10220 			return (EINVAL);
10221 		}
10222 
10223 		/*
10224 		 * Only privileged users can issue these
10225 		 * requests.
10226 		 */
10227 		if (((ah_req & IPSEC_PREF_NEVER) ||
10228 		    (esp_req & IPSEC_PREF_NEVER) ||
10229 		    (se_req & IPSEC_PREF_NEVER)) &&
10230 		    secpolicy_net_config(cr, B_FALSE) != 0) {
10231 			return (EPERM);
10232 		}
10233 
10234 		/*
10235 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10236 		 * are mutually exclusive.
10237 		 */
10238 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10239 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10240 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10241 			/* Both of them are set */
10242 			return (EINVAL);
10243 		}
10244 	}
10245 
10246 	mutex_enter(&connp->conn_lock);
10247 
10248 	/*
10249 	 * If we have already cached policies in ip_bind_connected*(), don't
10250 	 * let them change now. We cache policies for connections
10251 	 * whose src,dst [addr, port] is known.
10252 	 */
10253 	if (connp->conn_policy_cached) {
10254 		mutex_exit(&connp->conn_lock);
10255 		return (EINVAL);
10256 	}
10257 
10258 	/*
10259 	 * We have a zero policies, reset the connection policy if already
10260 	 * set. This will cause the connection to inherit the
10261 	 * global policy, if any.
10262 	 */
10263 	if (is_pol_reset) {
10264 		if (connp->conn_policy != NULL) {
10265 			IPPH_REFRELE(connp->conn_policy);
10266 			connp->conn_policy = NULL;
10267 		}
10268 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10269 		connp->conn_in_enforce_policy = B_FALSE;
10270 		connp->conn_out_enforce_policy = B_FALSE;
10271 		mutex_exit(&connp->conn_lock);
10272 		return (0);
10273 	}
10274 
10275 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
10276 	if (ph == NULL)
10277 		goto enomem;
10278 
10279 	ipsec_actvec_from_req(req, &actp, &nact);
10280 	if (actp == NULL)
10281 		goto enomem;
10282 
10283 	/*
10284 	 * Always allocate IPv4 policy entries, since they can also
10285 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10286 	 */
10287 	bzero(&sel, sizeof (sel));
10288 	sel.ipsl_valid = IPSL_IPV4;
10289 
10290 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10291 	if (pin4 == NULL)
10292 		goto enomem;
10293 
10294 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10295 	if (pout4 == NULL)
10296 		goto enomem;
10297 
10298 	if (connp->conn_pkt_isv6) {
10299 		/*
10300 		 * We're looking at a v6 socket, also allocate the
10301 		 * v6-specific entries...
10302 		 */
10303 		sel.ipsl_valid = IPSL_IPV6;
10304 		pin6 = ipsec_policy_create(&sel, actp, nact,
10305 		    IPSEC_PRIO_SOCKET, NULL);
10306 		if (pin6 == NULL)
10307 			goto enomem;
10308 
10309 		pout6 = ipsec_policy_create(&sel, actp, nact,
10310 		    IPSEC_PRIO_SOCKET, NULL);
10311 		if (pout6 == NULL)
10312 			goto enomem;
10313 
10314 		/*
10315 		 * .. and file them away in the right place.
10316 		 */
10317 		fam = IPSEC_AF_V6;
10318 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10319 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10320 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10321 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10322 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10323 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10324 	}
10325 
10326 	ipsec_actvec_free(actp, nact);
10327 
10328 	/*
10329 	 * File the v4 policies.
10330 	 */
10331 	fam = IPSEC_AF_V4;
10332 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10333 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10334 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10335 
10336 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10337 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10338 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10339 
10340 	/*
10341 	 * If the requests need security, set enforce_policy.
10342 	 * If the requests are IPSEC_PREF_NEVER, one should
10343 	 * still set conn_out_enforce_policy so that an ipsec_out
10344 	 * gets attached in ip_wput. This is needed so that
10345 	 * for connections that we don't cache policy in ip_bind,
10346 	 * if global policy matches in ip_wput_attach_policy, we
10347 	 * don't wrongly inherit global policy. Similarly, we need
10348 	 * to set conn_in_enforce_policy also so that we don't verify
10349 	 * policy wrongly.
10350 	 */
10351 	if ((ah_req & REQ_MASK) != 0 ||
10352 	    (esp_req & REQ_MASK) != 0 ||
10353 	    (se_req & REQ_MASK) != 0) {
10354 		connp->conn_in_enforce_policy = B_TRUE;
10355 		connp->conn_out_enforce_policy = B_TRUE;
10356 		connp->conn_flags |= IPCL_CHECK_POLICY;
10357 	}
10358 
10359 	mutex_exit(&connp->conn_lock);
10360 	return (error);
10361 #undef REQ_MASK
10362 
10363 	/*
10364 	 * Common memory-allocation-failure exit path.
10365 	 */
10366 enomem:
10367 	mutex_exit(&connp->conn_lock);
10368 	if (actp != NULL)
10369 		ipsec_actvec_free(actp, nact);
10370 	if (pin4 != NULL)
10371 		IPPOL_REFRELE(pin4);
10372 	if (pout4 != NULL)
10373 		IPPOL_REFRELE(pout4);
10374 	if (pin6 != NULL)
10375 		IPPOL_REFRELE(pin6);
10376 	if (pout6 != NULL)
10377 		IPPOL_REFRELE(pout6);
10378 	return (ENOMEM);
10379 }
10380 
10381 /*
10382  * Only for options that pass in an IP addr. Currently only V4 options
10383  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10384  * So this function assumes level is IPPROTO_IP
10385  */
10386 int
10387 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10388     mblk_t *first_mp)
10389 {
10390 	ipif_t *ipif = NULL;
10391 	int error;
10392 	ill_t *ill;
10393 	int zoneid;
10394 
10395 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10396 
10397 	if (addr != INADDR_ANY || checkonly) {
10398 		ASSERT(connp != NULL);
10399 		zoneid = IPCL_ZONEID(connp);
10400 		if (option == IP_NEXTHOP) {
10401 			ipif = ipif_lookup_onlink_addr(addr,
10402 			    connp->conn_zoneid);
10403 		} else {
10404 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10405 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10406 			    &error);
10407 		}
10408 		if (ipif == NULL) {
10409 			if (error == EINPROGRESS)
10410 				return (error);
10411 			else if ((option == IP_MULTICAST_IF) ||
10412 			    (option == IP_NEXTHOP))
10413 				return (EHOSTUNREACH);
10414 			else
10415 				return (EINVAL);
10416 		} else if (checkonly) {
10417 			if (option == IP_MULTICAST_IF) {
10418 				ill = ipif->ipif_ill;
10419 				/* not supported by the virtual network iface */
10420 				if (IS_VNI(ill)) {
10421 					ipif_refrele(ipif);
10422 					return (EINVAL);
10423 				}
10424 			}
10425 			ipif_refrele(ipif);
10426 			return (0);
10427 		}
10428 		ill = ipif->ipif_ill;
10429 		mutex_enter(&connp->conn_lock);
10430 		mutex_enter(&ill->ill_lock);
10431 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10432 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10433 			mutex_exit(&ill->ill_lock);
10434 			mutex_exit(&connp->conn_lock);
10435 			ipif_refrele(ipif);
10436 			return (option == IP_MULTICAST_IF ?
10437 			    EHOSTUNREACH : EINVAL);
10438 		}
10439 	} else {
10440 		mutex_enter(&connp->conn_lock);
10441 	}
10442 
10443 	/* None of the options below are supported on the VNI */
10444 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10445 		mutex_exit(&ill->ill_lock);
10446 		mutex_exit(&connp->conn_lock);
10447 		ipif_refrele(ipif);
10448 		return (EINVAL);
10449 	}
10450 
10451 	switch (option) {
10452 	case IP_DONTFAILOVER_IF:
10453 		/*
10454 		 * This option is used by in.mpathd to ensure
10455 		 * that IPMP probe packets only go out on the
10456 		 * test interfaces. in.mpathd sets this option
10457 		 * on the non-failover interfaces.
10458 		 * For backward compatibility, this option
10459 		 * implicitly sets IP_MULTICAST_IF, as used
10460 		 * be done in bind(), so that ip_wput gets
10461 		 * this ipif to send mcast packets.
10462 		 */
10463 		if (ipif != NULL) {
10464 			ASSERT(addr != INADDR_ANY);
10465 			connp->conn_nofailover_ill = ipif->ipif_ill;
10466 			connp->conn_multicast_ipif = ipif;
10467 		} else {
10468 			ASSERT(addr == INADDR_ANY);
10469 			connp->conn_nofailover_ill = NULL;
10470 			connp->conn_multicast_ipif = NULL;
10471 		}
10472 		break;
10473 
10474 	case IP_MULTICAST_IF:
10475 		connp->conn_multicast_ipif = ipif;
10476 		break;
10477 	case IP_NEXTHOP:
10478 		connp->conn_nexthop_v4 = addr;
10479 		connp->conn_nexthop_set = B_TRUE;
10480 		break;
10481 	}
10482 
10483 	if (ipif != NULL) {
10484 		mutex_exit(&ill->ill_lock);
10485 		mutex_exit(&connp->conn_lock);
10486 		ipif_refrele(ipif);
10487 		return (0);
10488 	}
10489 	mutex_exit(&connp->conn_lock);
10490 	/* We succeded in cleared the option */
10491 	return (0);
10492 }
10493 
10494 /*
10495  * For options that pass in an ifindex specifying the ill. V6 options always
10496  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10497  */
10498 int
10499 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10500     int level, int option, mblk_t *first_mp)
10501 {
10502 	ill_t *ill = NULL;
10503 	int error = 0;
10504 
10505 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10506 	if (ifindex != 0) {
10507 		ASSERT(connp != NULL);
10508 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10509 		    first_mp, ip_restart_optmgmt, &error);
10510 		if (ill != NULL) {
10511 			if (checkonly) {
10512 				/* not supported by the virtual network iface */
10513 				if (IS_VNI(ill)) {
10514 					ill_refrele(ill);
10515 					return (EINVAL);
10516 				}
10517 				ill_refrele(ill);
10518 				return (0);
10519 			}
10520 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10521 			    0, NULL)) {
10522 				ill_refrele(ill);
10523 				ill = NULL;
10524 				mutex_enter(&connp->conn_lock);
10525 				goto setit;
10526 			}
10527 			mutex_enter(&connp->conn_lock);
10528 			mutex_enter(&ill->ill_lock);
10529 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10530 				mutex_exit(&ill->ill_lock);
10531 				mutex_exit(&connp->conn_lock);
10532 				ill_refrele(ill);
10533 				ill = NULL;
10534 				mutex_enter(&connp->conn_lock);
10535 			}
10536 			goto setit;
10537 		} else if (error == EINPROGRESS) {
10538 			return (error);
10539 		} else {
10540 			error = 0;
10541 		}
10542 	}
10543 	mutex_enter(&connp->conn_lock);
10544 setit:
10545 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10546 
10547 	/*
10548 	 * The options below assume that the ILL (if any) transmits and/or
10549 	 * receives traffic. Neither of which is true for the virtual network
10550 	 * interface, so fail setting these on a VNI.
10551 	 */
10552 	if (IS_VNI(ill)) {
10553 		ASSERT(ill != NULL);
10554 		mutex_exit(&ill->ill_lock);
10555 		mutex_exit(&connp->conn_lock);
10556 		ill_refrele(ill);
10557 		return (EINVAL);
10558 	}
10559 
10560 	if (level == IPPROTO_IP) {
10561 		switch (option) {
10562 		case IP_BOUND_IF:
10563 			connp->conn_incoming_ill = ill;
10564 			connp->conn_outgoing_ill = ill;
10565 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10566 			    0 : ifindex;
10567 			break;
10568 
10569 		case IP_XMIT_IF:
10570 			/*
10571 			 * Similar to IP_BOUND_IF, but this only
10572 			 * determines the outgoing interface for
10573 			 * unicast packets. Also no IRE_CACHE entry
10574 			 * is added for the destination of the
10575 			 * outgoing packets. This feature is needed
10576 			 * for mobile IP.
10577 			 */
10578 			connp->conn_xmit_if_ill = ill;
10579 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10580 			    0 : ifindex;
10581 			break;
10582 
10583 		case IP_MULTICAST_IF:
10584 			/*
10585 			 * This option is an internal special. The socket
10586 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10587 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10588 			 * specifies an ifindex and we try first on V6 ill's.
10589 			 * If we don't find one, we they try using on v4 ill's
10590 			 * intenally and we come here.
10591 			 */
10592 			if (!checkonly && ill != NULL) {
10593 				ipif_t	*ipif;
10594 				ipif = ill->ill_ipif;
10595 
10596 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10597 					mutex_exit(&ill->ill_lock);
10598 					mutex_exit(&connp->conn_lock);
10599 					ill_refrele(ill);
10600 					ill = NULL;
10601 					mutex_enter(&connp->conn_lock);
10602 				} else {
10603 					connp->conn_multicast_ipif = ipif;
10604 				}
10605 			}
10606 			break;
10607 		}
10608 	} else {
10609 		switch (option) {
10610 		case IPV6_BOUND_IF:
10611 			connp->conn_incoming_ill = ill;
10612 			connp->conn_outgoing_ill = ill;
10613 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10614 			    0 : ifindex;
10615 			break;
10616 
10617 		case IPV6_BOUND_PIF:
10618 			/*
10619 			 * Limit all transmit to this ill.
10620 			 * Unlike IPV6_BOUND_IF, using this option
10621 			 * prevents load spreading and failover from
10622 			 * happening when the interface is part of the
10623 			 * group. That's why we don't need to remember
10624 			 * the ifindex in orig_bound_ifindex as in
10625 			 * IPV6_BOUND_IF.
10626 			 */
10627 			connp->conn_outgoing_pill = ill;
10628 			break;
10629 
10630 		case IPV6_DONTFAILOVER_IF:
10631 			/*
10632 			 * This option is used by in.mpathd to ensure
10633 			 * that IPMP probe packets only go out on the
10634 			 * test interfaces. in.mpathd sets this option
10635 			 * on the non-failover interfaces.
10636 			 */
10637 			connp->conn_nofailover_ill = ill;
10638 			/*
10639 			 * For backward compatibility, this option
10640 			 * implicitly sets ip_multicast_ill as used in
10641 			 * IP_MULTICAST_IF so that ip_wput gets
10642 			 * this ipif to send mcast packets.
10643 			 */
10644 			connp->conn_multicast_ill = ill;
10645 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10646 			    0 : ifindex;
10647 			break;
10648 
10649 		case IPV6_MULTICAST_IF:
10650 			/*
10651 			 * Set conn_multicast_ill to be the IPv6 ill.
10652 			 * Set conn_multicast_ipif to be an IPv4 ipif
10653 			 * for ifindex to make IPv4 mapped addresses
10654 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10655 			 * Even if no IPv6 ill exists for the ifindex
10656 			 * we need to check for an IPv4 ifindex in order
10657 			 * for this to work with mapped addresses. In that
10658 			 * case only set conn_multicast_ipif.
10659 			 */
10660 			if (!checkonly) {
10661 				if (ifindex == 0) {
10662 					connp->conn_multicast_ill = NULL;
10663 					connp->conn_orig_multicast_ifindex = 0;
10664 					connp->conn_multicast_ipif = NULL;
10665 				} else if (ill != NULL) {
10666 					connp->conn_multicast_ill = ill;
10667 					connp->conn_orig_multicast_ifindex =
10668 					    ifindex;
10669 				}
10670 			}
10671 			break;
10672 		}
10673 	}
10674 
10675 	if (ill != NULL) {
10676 		mutex_exit(&ill->ill_lock);
10677 		mutex_exit(&connp->conn_lock);
10678 		ill_refrele(ill);
10679 		return (0);
10680 	}
10681 	mutex_exit(&connp->conn_lock);
10682 	/*
10683 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10684 	 * locate the ill and could not set the option (ifindex != 0)
10685 	 */
10686 	return (ifindex == 0 ? 0 : EINVAL);
10687 }
10688 
10689 /* This routine sets socket options. */
10690 /* ARGSUSED */
10691 int
10692 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10693     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10694     void *dummy, cred_t *cr, mblk_t *first_mp)
10695 {
10696 	int		*i1 = (int *)invalp;
10697 	conn_t		*connp = Q_TO_CONN(q);
10698 	int		error = 0;
10699 	boolean_t	checkonly;
10700 	ire_t		*ire;
10701 	boolean_t	found;
10702 
10703 	switch (optset_context) {
10704 
10705 	case SETFN_OPTCOM_CHECKONLY:
10706 		checkonly = B_TRUE;
10707 		/*
10708 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10709 		 * inlen != 0 implies value supplied and
10710 		 * 	we have to "pretend" to set it.
10711 		 * inlen == 0 implies that there is no
10712 		 * 	value part in T_CHECK request and just validation
10713 		 * done elsewhere should be enough, we just return here.
10714 		 */
10715 		if (inlen == 0) {
10716 			*outlenp = 0;
10717 			return (0);
10718 		}
10719 		break;
10720 	case SETFN_OPTCOM_NEGOTIATE:
10721 	case SETFN_UD_NEGOTIATE:
10722 	case SETFN_CONN_NEGOTIATE:
10723 		checkonly = B_FALSE;
10724 		break;
10725 	default:
10726 		/*
10727 		 * We should never get here
10728 		 */
10729 		*outlenp = 0;
10730 		return (EINVAL);
10731 	}
10732 
10733 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10734 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10735 
10736 	/*
10737 	 * For fixed length options, no sanity check
10738 	 * of passed in length is done. It is assumed *_optcom_req()
10739 	 * routines do the right thing.
10740 	 */
10741 
10742 	switch (level) {
10743 	case SOL_SOCKET:
10744 		/*
10745 		 * conn_lock protects the bitfields, and is used to
10746 		 * set the fields atomically.
10747 		 */
10748 		switch (name) {
10749 		case SO_BROADCAST:
10750 			if (!checkonly) {
10751 				/* TODO: use value someplace? */
10752 				mutex_enter(&connp->conn_lock);
10753 				connp->conn_broadcast = *i1 ? 1 : 0;
10754 				mutex_exit(&connp->conn_lock);
10755 			}
10756 			break;	/* goto sizeof (int) option return */
10757 		case SO_USELOOPBACK:
10758 			if (!checkonly) {
10759 				/* TODO: use value someplace? */
10760 				mutex_enter(&connp->conn_lock);
10761 				connp->conn_loopback = *i1 ? 1 : 0;
10762 				mutex_exit(&connp->conn_lock);
10763 			}
10764 			break;	/* goto sizeof (int) option return */
10765 		case SO_DONTROUTE:
10766 			if (!checkonly) {
10767 				mutex_enter(&connp->conn_lock);
10768 				connp->conn_dontroute = *i1 ? 1 : 0;
10769 				mutex_exit(&connp->conn_lock);
10770 			}
10771 			break;	/* goto sizeof (int) option return */
10772 		case SO_REUSEADDR:
10773 			if (!checkonly) {
10774 				mutex_enter(&connp->conn_lock);
10775 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10776 				mutex_exit(&connp->conn_lock);
10777 			}
10778 			break;	/* goto sizeof (int) option return */
10779 		case SO_PROTOTYPE:
10780 			if (!checkonly) {
10781 				mutex_enter(&connp->conn_lock);
10782 				connp->conn_proto = *i1;
10783 				mutex_exit(&connp->conn_lock);
10784 			}
10785 			break;	/* goto sizeof (int) option return */
10786 		case SO_ALLZONES:
10787 			if (!checkonly) {
10788 				mutex_enter(&connp->conn_lock);
10789 				if (IPCL_IS_BOUND(connp)) {
10790 					mutex_exit(&connp->conn_lock);
10791 					return (EINVAL);
10792 				}
10793 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10794 				mutex_exit(&connp->conn_lock);
10795 			}
10796 			break;	/* goto sizeof (int) option return */
10797 		case SO_ANON_MLP:
10798 			if (!checkonly) {
10799 				mutex_enter(&connp->conn_lock);
10800 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10801 				mutex_exit(&connp->conn_lock);
10802 			}
10803 			break;	/* goto sizeof (int) option return */
10804 		case SO_MAC_EXEMPT:
10805 			if (secpolicy_net_mac_aware(cr) != 0 ||
10806 			    IPCL_IS_BOUND(connp))
10807 				return (EACCES);
10808 			if (!checkonly) {
10809 				mutex_enter(&connp->conn_lock);
10810 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10811 				mutex_exit(&connp->conn_lock);
10812 			}
10813 			break;	/* goto sizeof (int) option return */
10814 		default:
10815 			/*
10816 			 * "soft" error (negative)
10817 			 * option not handled at this level
10818 			 * Note: Do not modify *outlenp
10819 			 */
10820 			return (-EINVAL);
10821 		}
10822 		break;
10823 	case IPPROTO_IP:
10824 		switch (name) {
10825 		case IP_NEXTHOP:
10826 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10827 				return (EPERM);
10828 			/* FALLTHRU */
10829 		case IP_MULTICAST_IF:
10830 		case IP_DONTFAILOVER_IF: {
10831 			ipaddr_t addr = *i1;
10832 
10833 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10834 			    first_mp);
10835 			if (error != 0)
10836 				return (error);
10837 			break;	/* goto sizeof (int) option return */
10838 		}
10839 
10840 		case IP_MULTICAST_TTL:
10841 			/* Recorded in transport above IP */
10842 			*outvalp = *invalp;
10843 			*outlenp = sizeof (uchar_t);
10844 			return (0);
10845 		case IP_MULTICAST_LOOP:
10846 			if (!checkonly) {
10847 				mutex_enter(&connp->conn_lock);
10848 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10849 				mutex_exit(&connp->conn_lock);
10850 			}
10851 			*outvalp = *invalp;
10852 			*outlenp = sizeof (uchar_t);
10853 			return (0);
10854 		case IP_ADD_MEMBERSHIP:
10855 		case MCAST_JOIN_GROUP:
10856 		case IP_DROP_MEMBERSHIP:
10857 		case MCAST_LEAVE_GROUP: {
10858 			struct ip_mreq *mreqp;
10859 			struct group_req *greqp;
10860 			ire_t *ire;
10861 			boolean_t done = B_FALSE;
10862 			ipaddr_t group, ifaddr;
10863 			struct sockaddr_in *sin;
10864 			uint32_t *ifindexp;
10865 			boolean_t mcast_opt = B_TRUE;
10866 			mcast_record_t fmode;
10867 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10868 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10869 
10870 			switch (name) {
10871 			case IP_ADD_MEMBERSHIP:
10872 				mcast_opt = B_FALSE;
10873 				/* FALLTHRU */
10874 			case MCAST_JOIN_GROUP:
10875 				fmode = MODE_IS_EXCLUDE;
10876 				optfn = ip_opt_add_group;
10877 				break;
10878 
10879 			case IP_DROP_MEMBERSHIP:
10880 				mcast_opt = B_FALSE;
10881 				/* FALLTHRU */
10882 			case MCAST_LEAVE_GROUP:
10883 				fmode = MODE_IS_INCLUDE;
10884 				optfn = ip_opt_delete_group;
10885 				break;
10886 			}
10887 
10888 			if (mcast_opt) {
10889 				greqp = (struct group_req *)i1;
10890 				sin = (struct sockaddr_in *)&greqp->gr_group;
10891 				if (sin->sin_family != AF_INET) {
10892 					*outlenp = 0;
10893 					return (ENOPROTOOPT);
10894 				}
10895 				group = (ipaddr_t)sin->sin_addr.s_addr;
10896 				ifaddr = INADDR_ANY;
10897 				ifindexp = &greqp->gr_interface;
10898 			} else {
10899 				mreqp = (struct ip_mreq *)i1;
10900 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10901 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10902 				ifindexp = NULL;
10903 			}
10904 
10905 			/*
10906 			 * In the multirouting case, we need to replicate
10907 			 * the request on all interfaces that will take part
10908 			 * in replication.  We do so because multirouting is
10909 			 * reflective, thus we will probably receive multi-
10910 			 * casts on those interfaces.
10911 			 * The ip_multirt_apply_membership() succeeds if the
10912 			 * operation succeeds on at least one interface.
10913 			 */
10914 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10915 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10916 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10917 			if (ire != NULL) {
10918 				if (ire->ire_flags & RTF_MULTIRT) {
10919 					error = ip_multirt_apply_membership(
10920 					    optfn, ire, connp, checkonly, group,
10921 					    fmode, INADDR_ANY, first_mp);
10922 					done = B_TRUE;
10923 				}
10924 				ire_refrele(ire);
10925 			}
10926 			if (!done) {
10927 				error = optfn(connp, checkonly, group, ifaddr,
10928 				    ifindexp, fmode, INADDR_ANY, first_mp);
10929 			}
10930 			if (error) {
10931 				/*
10932 				 * EINPROGRESS is a soft error, needs retry
10933 				 * so don't make *outlenp zero.
10934 				 */
10935 				if (error != EINPROGRESS)
10936 					*outlenp = 0;
10937 				return (error);
10938 			}
10939 			/* OK return - copy input buffer into output buffer */
10940 			if (invalp != outvalp) {
10941 				/* don't trust bcopy for identical src/dst */
10942 				bcopy(invalp, outvalp, inlen);
10943 			}
10944 			*outlenp = inlen;
10945 			return (0);
10946 		}
10947 		case IP_BLOCK_SOURCE:
10948 		case IP_UNBLOCK_SOURCE:
10949 		case IP_ADD_SOURCE_MEMBERSHIP:
10950 		case IP_DROP_SOURCE_MEMBERSHIP:
10951 		case MCAST_BLOCK_SOURCE:
10952 		case MCAST_UNBLOCK_SOURCE:
10953 		case MCAST_JOIN_SOURCE_GROUP:
10954 		case MCAST_LEAVE_SOURCE_GROUP: {
10955 			struct ip_mreq_source *imreqp;
10956 			struct group_source_req *gsreqp;
10957 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10958 			uint32_t ifindex = 0;
10959 			mcast_record_t fmode;
10960 			struct sockaddr_in *sin;
10961 			ire_t *ire;
10962 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10963 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10964 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10965 
10966 			switch (name) {
10967 			case IP_BLOCK_SOURCE:
10968 				mcast_opt = B_FALSE;
10969 				/* FALLTHRU */
10970 			case MCAST_BLOCK_SOURCE:
10971 				fmode = MODE_IS_EXCLUDE;
10972 				optfn = ip_opt_add_group;
10973 				break;
10974 
10975 			case IP_UNBLOCK_SOURCE:
10976 				mcast_opt = B_FALSE;
10977 				/* FALLTHRU */
10978 			case MCAST_UNBLOCK_SOURCE:
10979 				fmode = MODE_IS_EXCLUDE;
10980 				optfn = ip_opt_delete_group;
10981 				break;
10982 
10983 			case IP_ADD_SOURCE_MEMBERSHIP:
10984 				mcast_opt = B_FALSE;
10985 				/* FALLTHRU */
10986 			case MCAST_JOIN_SOURCE_GROUP:
10987 				fmode = MODE_IS_INCLUDE;
10988 				optfn = ip_opt_add_group;
10989 				break;
10990 
10991 			case IP_DROP_SOURCE_MEMBERSHIP:
10992 				mcast_opt = B_FALSE;
10993 				/* FALLTHRU */
10994 			case MCAST_LEAVE_SOURCE_GROUP:
10995 				fmode = MODE_IS_INCLUDE;
10996 				optfn = ip_opt_delete_group;
10997 				break;
10998 			}
10999 
11000 			if (mcast_opt) {
11001 				gsreqp = (struct group_source_req *)i1;
11002 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11003 					*outlenp = 0;
11004 					return (ENOPROTOOPT);
11005 				}
11006 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11007 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11008 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11009 				src = (ipaddr_t)sin->sin_addr.s_addr;
11010 				ifindex = gsreqp->gsr_interface;
11011 			} else {
11012 				imreqp = (struct ip_mreq_source *)i1;
11013 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11014 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11015 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11016 			}
11017 
11018 			/*
11019 			 * In the multirouting case, we need to replicate
11020 			 * the request as noted in the mcast cases above.
11021 			 */
11022 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11023 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11024 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11025 			if (ire != NULL) {
11026 				if (ire->ire_flags & RTF_MULTIRT) {
11027 					error = ip_multirt_apply_membership(
11028 					    optfn, ire, connp, checkonly, grp,
11029 					    fmode, src, first_mp);
11030 					done = B_TRUE;
11031 				}
11032 				ire_refrele(ire);
11033 			}
11034 			if (!done) {
11035 				error = optfn(connp, checkonly, grp, ifaddr,
11036 				    &ifindex, fmode, src, first_mp);
11037 			}
11038 			if (error != 0) {
11039 				/*
11040 				 * EINPROGRESS is a soft error, needs retry
11041 				 * so don't make *outlenp zero.
11042 				 */
11043 				if (error != EINPROGRESS)
11044 					*outlenp = 0;
11045 				return (error);
11046 			}
11047 			/* OK return - copy input buffer into output buffer */
11048 			if (invalp != outvalp) {
11049 				bcopy(invalp, outvalp, inlen);
11050 			}
11051 			*outlenp = inlen;
11052 			return (0);
11053 		}
11054 		case IP_SEC_OPT:
11055 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11056 			if (error != 0) {
11057 				*outlenp = 0;
11058 				return (error);
11059 			}
11060 			break;
11061 		case IP_HDRINCL:
11062 		case IP_OPTIONS:
11063 		case T_IP_OPTIONS:
11064 		case IP_TOS:
11065 		case T_IP_TOS:
11066 		case IP_TTL:
11067 		case IP_RECVDSTADDR:
11068 		case IP_RECVOPTS:
11069 			/* OK return - copy input buffer into output buffer */
11070 			if (invalp != outvalp) {
11071 				/* don't trust bcopy for identical src/dst */
11072 				bcopy(invalp, outvalp, inlen);
11073 			}
11074 			*outlenp = inlen;
11075 			return (0);
11076 		case IP_RECVIF:
11077 			/* Retrieve the inbound interface index */
11078 			if (!checkonly) {
11079 				mutex_enter(&connp->conn_lock);
11080 				connp->conn_recvif = *i1 ? 1 : 0;
11081 				mutex_exit(&connp->conn_lock);
11082 			}
11083 			break;	/* goto sizeof (int) option return */
11084 		case IP_RECVPKTINFO:
11085 			if (!checkonly) {
11086 				mutex_enter(&connp->conn_lock);
11087 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11088 				mutex_exit(&connp->conn_lock);
11089 			}
11090 			break;	/* goto sizeof (int) option return */
11091 		case IP_RECVSLLA:
11092 			/* Retrieve the source link layer address */
11093 			if (!checkonly) {
11094 				mutex_enter(&connp->conn_lock);
11095 				connp->conn_recvslla = *i1 ? 1 : 0;
11096 				mutex_exit(&connp->conn_lock);
11097 			}
11098 			break;	/* goto sizeof (int) option return */
11099 		case MRT_INIT:
11100 		case MRT_DONE:
11101 		case MRT_ADD_VIF:
11102 		case MRT_DEL_VIF:
11103 		case MRT_ADD_MFC:
11104 		case MRT_DEL_MFC:
11105 		case MRT_ASSERT:
11106 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
11107 				*outlenp = 0;
11108 				return (error);
11109 			}
11110 			error = ip_mrouter_set((int)name, q, checkonly,
11111 			    (uchar_t *)invalp, inlen, first_mp);
11112 			if (error) {
11113 				*outlenp = 0;
11114 				return (error);
11115 			}
11116 			/* OK return - copy input buffer into output buffer */
11117 			if (invalp != outvalp) {
11118 				/* don't trust bcopy for identical src/dst */
11119 				bcopy(invalp, outvalp, inlen);
11120 			}
11121 			*outlenp = inlen;
11122 			return (0);
11123 		case IP_BOUND_IF:
11124 		case IP_XMIT_IF:
11125 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11126 			    level, name, first_mp);
11127 			if (error != 0)
11128 				return (error);
11129 			break; 		/* goto sizeof (int) option return */
11130 
11131 		case IP_UNSPEC_SRC:
11132 			/* Allow sending with a zero source address */
11133 			if (!checkonly) {
11134 				mutex_enter(&connp->conn_lock);
11135 				connp->conn_unspec_src = *i1 ? 1 : 0;
11136 				mutex_exit(&connp->conn_lock);
11137 			}
11138 			break;	/* goto sizeof (int) option return */
11139 		default:
11140 			/*
11141 			 * "soft" error (negative)
11142 			 * option not handled at this level
11143 			 * Note: Do not modify *outlenp
11144 			 */
11145 			return (-EINVAL);
11146 		}
11147 		break;
11148 	case IPPROTO_IPV6:
11149 		switch (name) {
11150 		case IPV6_BOUND_IF:
11151 		case IPV6_BOUND_PIF:
11152 		case IPV6_DONTFAILOVER_IF:
11153 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11154 			    level, name, first_mp);
11155 			if (error != 0)
11156 				return (error);
11157 			break; 		/* goto sizeof (int) option return */
11158 
11159 		case IPV6_MULTICAST_IF:
11160 			/*
11161 			 * The only possible errors are EINPROGRESS and
11162 			 * EINVAL. EINPROGRESS will be restarted and is not
11163 			 * a hard error. We call this option on both V4 and V6
11164 			 * If both return EINVAL, then this call returns
11165 			 * EINVAL. If at least one of them succeeds we
11166 			 * return success.
11167 			 */
11168 			found = B_FALSE;
11169 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11170 			    level, name, first_mp);
11171 			if (error == EINPROGRESS)
11172 				return (error);
11173 			if (error == 0)
11174 				found = B_TRUE;
11175 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11176 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11177 			if (error == 0)
11178 				found = B_TRUE;
11179 			if (!found)
11180 				return (error);
11181 			break; 		/* goto sizeof (int) option return */
11182 
11183 		case IPV6_MULTICAST_HOPS:
11184 			/* Recorded in transport above IP */
11185 			break;	/* goto sizeof (int) option return */
11186 		case IPV6_MULTICAST_LOOP:
11187 			if (!checkonly) {
11188 				mutex_enter(&connp->conn_lock);
11189 				connp->conn_multicast_loop = *i1;
11190 				mutex_exit(&connp->conn_lock);
11191 			}
11192 			break;	/* goto sizeof (int) option return */
11193 		case IPV6_JOIN_GROUP:
11194 		case MCAST_JOIN_GROUP:
11195 		case IPV6_LEAVE_GROUP:
11196 		case MCAST_LEAVE_GROUP: {
11197 			struct ipv6_mreq *ip_mreqp;
11198 			struct group_req *greqp;
11199 			ire_t *ire;
11200 			boolean_t done = B_FALSE;
11201 			in6_addr_t groupv6;
11202 			uint32_t ifindex;
11203 			boolean_t mcast_opt = B_TRUE;
11204 			mcast_record_t fmode;
11205 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11206 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11207 
11208 			switch (name) {
11209 			case IPV6_JOIN_GROUP:
11210 				mcast_opt = B_FALSE;
11211 				/* FALLTHRU */
11212 			case MCAST_JOIN_GROUP:
11213 				fmode = MODE_IS_EXCLUDE;
11214 				optfn = ip_opt_add_group_v6;
11215 				break;
11216 
11217 			case IPV6_LEAVE_GROUP:
11218 				mcast_opt = B_FALSE;
11219 				/* FALLTHRU */
11220 			case MCAST_LEAVE_GROUP:
11221 				fmode = MODE_IS_INCLUDE;
11222 				optfn = ip_opt_delete_group_v6;
11223 				break;
11224 			}
11225 
11226 			if (mcast_opt) {
11227 				struct sockaddr_in *sin;
11228 				struct sockaddr_in6 *sin6;
11229 				greqp = (struct group_req *)i1;
11230 				if (greqp->gr_group.ss_family == AF_INET) {
11231 					sin = (struct sockaddr_in *)
11232 					    &(greqp->gr_group);
11233 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11234 					    &groupv6);
11235 				} else {
11236 					sin6 = (struct sockaddr_in6 *)
11237 					    &(greqp->gr_group);
11238 					groupv6 = sin6->sin6_addr;
11239 				}
11240 				ifindex = greqp->gr_interface;
11241 			} else {
11242 				ip_mreqp = (struct ipv6_mreq *)i1;
11243 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11244 				ifindex = ip_mreqp->ipv6mr_interface;
11245 			}
11246 			/*
11247 			 * In the multirouting case, we need to replicate
11248 			 * the request on all interfaces that will take part
11249 			 * in replication.  We do so because multirouting is
11250 			 * reflective, thus we will probably receive multi-
11251 			 * casts on those interfaces.
11252 			 * The ip_multirt_apply_membership_v6() succeeds if
11253 			 * the operation succeeds on at least one interface.
11254 			 */
11255 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11256 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11257 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11258 			if (ire != NULL) {
11259 				if (ire->ire_flags & RTF_MULTIRT) {
11260 					error = ip_multirt_apply_membership_v6(
11261 					    optfn, ire, connp, checkonly,
11262 					    &groupv6, fmode, &ipv6_all_zeros,
11263 					    first_mp);
11264 					done = B_TRUE;
11265 				}
11266 				ire_refrele(ire);
11267 			}
11268 			if (!done) {
11269 				error = optfn(connp, checkonly, &groupv6,
11270 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11271 			}
11272 			if (error) {
11273 				/*
11274 				 * EINPROGRESS is a soft error, needs retry
11275 				 * so don't make *outlenp zero.
11276 				 */
11277 				if (error != EINPROGRESS)
11278 					*outlenp = 0;
11279 				return (error);
11280 			}
11281 			/* OK return - copy input buffer into output buffer */
11282 			if (invalp != outvalp) {
11283 				/* don't trust bcopy for identical src/dst */
11284 				bcopy(invalp, outvalp, inlen);
11285 			}
11286 			*outlenp = inlen;
11287 			return (0);
11288 		}
11289 		case MCAST_BLOCK_SOURCE:
11290 		case MCAST_UNBLOCK_SOURCE:
11291 		case MCAST_JOIN_SOURCE_GROUP:
11292 		case MCAST_LEAVE_SOURCE_GROUP: {
11293 			struct group_source_req *gsreqp;
11294 			in6_addr_t v6grp, v6src;
11295 			uint32_t ifindex;
11296 			mcast_record_t fmode;
11297 			ire_t *ire;
11298 			boolean_t done = B_FALSE;
11299 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11300 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11301 
11302 			switch (name) {
11303 			case MCAST_BLOCK_SOURCE:
11304 				fmode = MODE_IS_EXCLUDE;
11305 				optfn = ip_opt_add_group_v6;
11306 				break;
11307 			case MCAST_UNBLOCK_SOURCE:
11308 				fmode = MODE_IS_EXCLUDE;
11309 				optfn = ip_opt_delete_group_v6;
11310 				break;
11311 			case MCAST_JOIN_SOURCE_GROUP:
11312 				fmode = MODE_IS_INCLUDE;
11313 				optfn = ip_opt_add_group_v6;
11314 				break;
11315 			case MCAST_LEAVE_SOURCE_GROUP:
11316 				fmode = MODE_IS_INCLUDE;
11317 				optfn = ip_opt_delete_group_v6;
11318 				break;
11319 			}
11320 
11321 			gsreqp = (struct group_source_req *)i1;
11322 			ifindex = gsreqp->gsr_interface;
11323 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11324 				struct sockaddr_in *s;
11325 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11326 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11327 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11328 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11329 			} else {
11330 				struct sockaddr_in6 *s6;
11331 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11332 				v6grp = s6->sin6_addr;
11333 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11334 				v6src = s6->sin6_addr;
11335 			}
11336 
11337 			/*
11338 			 * In the multirouting case, we need to replicate
11339 			 * the request as noted in the mcast cases above.
11340 			 */
11341 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11342 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11343 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11344 			if (ire != NULL) {
11345 				if (ire->ire_flags & RTF_MULTIRT) {
11346 					error = ip_multirt_apply_membership_v6(
11347 					    optfn, ire, connp, checkonly,
11348 					    &v6grp, fmode, &v6src, first_mp);
11349 					done = B_TRUE;
11350 				}
11351 				ire_refrele(ire);
11352 			}
11353 			if (!done) {
11354 				error = optfn(connp, checkonly, &v6grp,
11355 				    ifindex, fmode, &v6src, first_mp);
11356 			}
11357 			if (error != 0) {
11358 				/*
11359 				 * EINPROGRESS is a soft error, needs retry
11360 				 * so don't make *outlenp zero.
11361 				 */
11362 				if (error != EINPROGRESS)
11363 					*outlenp = 0;
11364 				return (error);
11365 			}
11366 			/* OK return - copy input buffer into output buffer */
11367 			if (invalp != outvalp) {
11368 				bcopy(invalp, outvalp, inlen);
11369 			}
11370 			*outlenp = inlen;
11371 			return (0);
11372 		}
11373 		case IPV6_UNICAST_HOPS:
11374 			/* Recorded in transport above IP */
11375 			break;	/* goto sizeof (int) option return */
11376 		case IPV6_UNSPEC_SRC:
11377 			/* Allow sending with a zero source address */
11378 			if (!checkonly) {
11379 				mutex_enter(&connp->conn_lock);
11380 				connp->conn_unspec_src = *i1 ? 1 : 0;
11381 				mutex_exit(&connp->conn_lock);
11382 			}
11383 			break;	/* goto sizeof (int) option return */
11384 		case IPV6_RECVPKTINFO:
11385 			if (!checkonly) {
11386 				mutex_enter(&connp->conn_lock);
11387 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11388 				mutex_exit(&connp->conn_lock);
11389 			}
11390 			break;	/* goto sizeof (int) option return */
11391 		case IPV6_RECVTCLASS:
11392 			if (!checkonly) {
11393 				if (*i1 < 0 || *i1 > 1) {
11394 					return (EINVAL);
11395 				}
11396 				mutex_enter(&connp->conn_lock);
11397 				connp->conn_ipv6_recvtclass = *i1;
11398 				mutex_exit(&connp->conn_lock);
11399 			}
11400 			break;
11401 		case IPV6_RECVPATHMTU:
11402 			if (!checkonly) {
11403 				if (*i1 < 0 || *i1 > 1) {
11404 					return (EINVAL);
11405 				}
11406 				mutex_enter(&connp->conn_lock);
11407 				connp->conn_ipv6_recvpathmtu = *i1;
11408 				mutex_exit(&connp->conn_lock);
11409 			}
11410 			break;
11411 		case IPV6_RECVHOPLIMIT:
11412 			if (!checkonly) {
11413 				mutex_enter(&connp->conn_lock);
11414 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11415 				mutex_exit(&connp->conn_lock);
11416 			}
11417 			break;	/* goto sizeof (int) option return */
11418 		case IPV6_RECVHOPOPTS:
11419 			if (!checkonly) {
11420 				mutex_enter(&connp->conn_lock);
11421 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11422 				mutex_exit(&connp->conn_lock);
11423 			}
11424 			break;	/* goto sizeof (int) option return */
11425 		case IPV6_RECVDSTOPTS:
11426 			if (!checkonly) {
11427 				mutex_enter(&connp->conn_lock);
11428 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11429 				mutex_exit(&connp->conn_lock);
11430 			}
11431 			break;	/* goto sizeof (int) option return */
11432 		case IPV6_RECVRTHDR:
11433 			if (!checkonly) {
11434 				mutex_enter(&connp->conn_lock);
11435 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11436 				mutex_exit(&connp->conn_lock);
11437 			}
11438 			break;	/* goto sizeof (int) option return */
11439 		case IPV6_RECVRTHDRDSTOPTS:
11440 			if (!checkonly) {
11441 				mutex_enter(&connp->conn_lock);
11442 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11443 				mutex_exit(&connp->conn_lock);
11444 			}
11445 			break;	/* goto sizeof (int) option return */
11446 		case IPV6_PKTINFO:
11447 			if (inlen == 0)
11448 				return (-EINVAL);	/* clearing option */
11449 			error = ip6_set_pktinfo(cr, connp,
11450 			    (struct in6_pktinfo *)invalp, first_mp);
11451 			if (error != 0)
11452 				*outlenp = 0;
11453 			else
11454 				*outlenp = inlen;
11455 			return (error);
11456 		case IPV6_NEXTHOP: {
11457 			struct sockaddr_in6 *sin6;
11458 
11459 			/* Verify that the nexthop is reachable */
11460 			if (inlen == 0)
11461 				return (-EINVAL);	/* clearing option */
11462 
11463 			sin6 = (struct sockaddr_in6 *)invalp;
11464 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11465 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11466 			    NULL, MATCH_IRE_DEFAULT);
11467 
11468 			if (ire == NULL) {
11469 				*outlenp = 0;
11470 				return (EHOSTUNREACH);
11471 			}
11472 			ire_refrele(ire);
11473 			return (-EINVAL);
11474 		}
11475 		case IPV6_SEC_OPT:
11476 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11477 			if (error != 0) {
11478 				*outlenp = 0;
11479 				return (error);
11480 			}
11481 			break;
11482 		case IPV6_SRC_PREFERENCES: {
11483 			/*
11484 			 * This is implemented strictly in the ip module
11485 			 * (here and in tcp_opt_*() to accomodate tcp
11486 			 * sockets).  Modules above ip pass this option
11487 			 * down here since ip is the only one that needs to
11488 			 * be aware of source address preferences.
11489 			 *
11490 			 * This socket option only affects connected
11491 			 * sockets that haven't already bound to a specific
11492 			 * IPv6 address.  In other words, sockets that
11493 			 * don't call bind() with an address other than the
11494 			 * unspecified address and that call connect().
11495 			 * ip_bind_connected_v6() passes these preferences
11496 			 * to the ipif_select_source_v6() function.
11497 			 */
11498 			if (inlen != sizeof (uint32_t))
11499 				return (EINVAL);
11500 			error = ip6_set_src_preferences(connp,
11501 			    *(uint32_t *)invalp);
11502 			if (error != 0) {
11503 				*outlenp = 0;
11504 				return (error);
11505 			} else {
11506 				*outlenp = sizeof (uint32_t);
11507 			}
11508 			break;
11509 		}
11510 		case IPV6_V6ONLY:
11511 			if (*i1 < 0 || *i1 > 1) {
11512 				return (EINVAL);
11513 			}
11514 			mutex_enter(&connp->conn_lock);
11515 			connp->conn_ipv6_v6only = *i1;
11516 			mutex_exit(&connp->conn_lock);
11517 			break;
11518 		default:
11519 			return (-EINVAL);
11520 		}
11521 		break;
11522 	default:
11523 		/*
11524 		 * "soft" error (negative)
11525 		 * option not handled at this level
11526 		 * Note: Do not modify *outlenp
11527 		 */
11528 		return (-EINVAL);
11529 	}
11530 	/*
11531 	 * Common case of return from an option that is sizeof (int)
11532 	 */
11533 	*(int *)outvalp = *i1;
11534 	*outlenp = sizeof (int);
11535 	return (0);
11536 }
11537 
11538 /*
11539  * This routine gets default values of certain options whose default
11540  * values are maintained by protocol specific code
11541  */
11542 /* ARGSUSED */
11543 int
11544 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11545 {
11546 	int *i1 = (int *)ptr;
11547 
11548 	switch (level) {
11549 	case IPPROTO_IP:
11550 		switch (name) {
11551 		case IP_MULTICAST_TTL:
11552 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11553 			return (sizeof (uchar_t));
11554 		case IP_MULTICAST_LOOP:
11555 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11556 			return (sizeof (uchar_t));
11557 		default:
11558 			return (-1);
11559 		}
11560 	case IPPROTO_IPV6:
11561 		switch (name) {
11562 		case IPV6_UNICAST_HOPS:
11563 			*i1 = ipv6_def_hops;
11564 			return (sizeof (int));
11565 		case IPV6_MULTICAST_HOPS:
11566 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11567 			return (sizeof (int));
11568 		case IPV6_MULTICAST_LOOP:
11569 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11570 			return (sizeof (int));
11571 		case IPV6_V6ONLY:
11572 			*i1 = 1;
11573 			return (sizeof (int));
11574 		default:
11575 			return (-1);
11576 		}
11577 	default:
11578 		return (-1);
11579 	}
11580 	/* NOTREACHED */
11581 }
11582 
11583 /*
11584  * Given a destination address and a pointer to where to put the information
11585  * this routine fills in the mtuinfo.
11586  */
11587 int
11588 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11589     struct ip6_mtuinfo *mtuinfo)
11590 {
11591 	ire_t *ire;
11592 
11593 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11594 		return (-1);
11595 
11596 	bzero(mtuinfo, sizeof (*mtuinfo));
11597 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11598 	mtuinfo->ip6m_addr.sin6_port = port;
11599 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11600 
11601 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11602 	if (ire != NULL) {
11603 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11604 		ire_refrele(ire);
11605 	} else {
11606 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11607 	}
11608 	return (sizeof (struct ip6_mtuinfo));
11609 }
11610 
11611 /*
11612  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11613  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11614  * isn't.  This doesn't matter as the error checking is done properly for the
11615  * other MRT options coming in through ip_opt_set.
11616  */
11617 int
11618 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11619 {
11620 	conn_t		*connp = Q_TO_CONN(q);
11621 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11622 
11623 	switch (level) {
11624 	case IPPROTO_IP:
11625 		switch (name) {
11626 		case MRT_VERSION:
11627 		case MRT_ASSERT:
11628 			(void) ip_mrouter_get(name, q, ptr);
11629 			return (sizeof (int));
11630 		case IP_SEC_OPT:
11631 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11632 		case IP_NEXTHOP:
11633 			if (connp->conn_nexthop_set) {
11634 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11635 				return (sizeof (ipaddr_t));
11636 			} else
11637 				return (0);
11638 		case IP_RECVPKTINFO:
11639 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11640 			return (sizeof (int));
11641 		default:
11642 			break;
11643 		}
11644 		break;
11645 	case IPPROTO_IPV6:
11646 		switch (name) {
11647 		case IPV6_SEC_OPT:
11648 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11649 		case IPV6_SRC_PREFERENCES: {
11650 			return (ip6_get_src_preferences(connp,
11651 			    (uint32_t *)ptr));
11652 		}
11653 		case IPV6_V6ONLY:
11654 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11655 			return (sizeof (int));
11656 		case IPV6_PATHMTU:
11657 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11658 				(struct ip6_mtuinfo *)ptr));
11659 		default:
11660 			break;
11661 		}
11662 		break;
11663 	default:
11664 		break;
11665 	}
11666 	return (-1);
11667 }
11668 
11669 /* Named Dispatch routine to get a current value out of our parameter table. */
11670 /* ARGSUSED */
11671 static int
11672 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11673 {
11674 	ipparam_t *ippa = (ipparam_t *)cp;
11675 
11676 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11677 	return (0);
11678 }
11679 
11680 /* ARGSUSED */
11681 static int
11682 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11683 {
11684 
11685 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11686 	return (0);
11687 }
11688 
11689 /*
11690  * Set ip{,6}_forwarding values.  This means walking through all of the
11691  * ill's and toggling their forwarding values.
11692  */
11693 /* ARGSUSED */
11694 static int
11695 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11696 {
11697 	long new_value;
11698 	int *forwarding_value = (int *)cp;
11699 	ill_t *walker;
11700 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11701 	ill_walk_context_t ctx;
11702 
11703 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11704 	    new_value < 0 || new_value > 1) {
11705 		return (EINVAL);
11706 	}
11707 
11708 	*forwarding_value = new_value;
11709 
11710 	/*
11711 	 * Regardless of the current value of ip_forwarding, set all per-ill
11712 	 * values of ip_forwarding to the value being set.
11713 	 *
11714 	 * Bring all the ill's up to date with the new global value.
11715 	 */
11716 	rw_enter(&ill_g_lock, RW_READER);
11717 
11718 	if (isv6)
11719 		walker = ILL_START_WALK_V6(&ctx);
11720 	else
11721 		walker = ILL_START_WALK_V4(&ctx);
11722 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11723 		(void) ill_forward_set(q, mp, (new_value != 0),
11724 		    (caddr_t)walker);
11725 	}
11726 	rw_exit(&ill_g_lock);
11727 
11728 	return (0);
11729 }
11730 
11731 /*
11732  * Walk through the param array specified registering each element with the
11733  * Named Dispatch handler. This is called only during init. So it is ok
11734  * not to acquire any locks
11735  */
11736 static boolean_t
11737 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11738     ipndp_t *ipnd, size_t ipnd_cnt)
11739 {
11740 	for (; ippa_cnt-- > 0; ippa++) {
11741 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11742 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11743 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11744 				nd_free(&ip_g_nd);
11745 				return (B_FALSE);
11746 			}
11747 		}
11748 	}
11749 
11750 	for (; ipnd_cnt-- > 0; ipnd++) {
11751 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11752 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11753 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11754 			    ipnd->ip_ndp_data)) {
11755 				nd_free(&ip_g_nd);
11756 				return (B_FALSE);
11757 			}
11758 		}
11759 	}
11760 
11761 	return (B_TRUE);
11762 }
11763 
11764 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11765 /* ARGSUSED */
11766 static int
11767 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11768 {
11769 	long		new_value;
11770 	ipparam_t	*ippa = (ipparam_t *)cp;
11771 
11772 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11773 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11774 		return (EINVAL);
11775 	}
11776 	ippa->ip_param_value = new_value;
11777 	return (0);
11778 }
11779 
11780 /*
11781  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11782  * When an ipf is passed here for the first time, if
11783  * we already have in-order fragments on the queue, we convert from the fast-
11784  * path reassembly scheme to the hard-case scheme.  From then on, additional
11785  * fragments are reassembled here.  We keep track of the start and end offsets
11786  * of each piece, and the number of holes in the chain.  When the hole count
11787  * goes to zero, we are done!
11788  *
11789  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11790  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11791  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11792  * after the call to ip_reassemble().
11793  */
11794 int
11795 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11796     size_t msg_len)
11797 {
11798 	uint_t	end;
11799 	mblk_t	*next_mp;
11800 	mblk_t	*mp1;
11801 	uint_t	offset;
11802 	boolean_t incr_dups = B_TRUE;
11803 	boolean_t offset_zero_seen = B_FALSE;
11804 	boolean_t pkt_boundary_checked = B_FALSE;
11805 
11806 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11807 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11808 
11809 	/* Add in byte count */
11810 	ipf->ipf_count += msg_len;
11811 	if (ipf->ipf_end) {
11812 		/*
11813 		 * We were part way through in-order reassembly, but now there
11814 		 * is a hole.  We walk through messages already queued, and
11815 		 * mark them for hard case reassembly.  We know that up till
11816 		 * now they were in order starting from offset zero.
11817 		 */
11818 		offset = 0;
11819 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11820 			IP_REASS_SET_START(mp1, offset);
11821 			if (offset == 0) {
11822 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11823 				offset = -ipf->ipf_nf_hdr_len;
11824 			}
11825 			offset += mp1->b_wptr - mp1->b_rptr;
11826 			IP_REASS_SET_END(mp1, offset);
11827 		}
11828 		/* One hole at the end. */
11829 		ipf->ipf_hole_cnt = 1;
11830 		/* Brand it as a hard case, forever. */
11831 		ipf->ipf_end = 0;
11832 	}
11833 	/* Walk through all the new pieces. */
11834 	do {
11835 		end = start + (mp->b_wptr - mp->b_rptr);
11836 		/*
11837 		 * If start is 0, decrease 'end' only for the first mblk of
11838 		 * the fragment. Otherwise 'end' can get wrong value in the
11839 		 * second pass of the loop if first mblk is exactly the
11840 		 * size of ipf_nf_hdr_len.
11841 		 */
11842 		if (start == 0 && !offset_zero_seen) {
11843 			/* First segment */
11844 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11845 			end -= ipf->ipf_nf_hdr_len;
11846 			offset_zero_seen = B_TRUE;
11847 		}
11848 		next_mp = mp->b_cont;
11849 		/*
11850 		 * We are checking to see if there is any interesing data
11851 		 * to process.  If there isn't and the mblk isn't the
11852 		 * one which carries the unfragmentable header then we
11853 		 * drop it.  It's possible to have just the unfragmentable
11854 		 * header come through without any data.  That needs to be
11855 		 * saved.
11856 		 *
11857 		 * If the assert at the top of this function holds then the
11858 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11859 		 * is infrequently traveled enough that the test is left in
11860 		 * to protect against future code changes which break that
11861 		 * invariant.
11862 		 */
11863 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11864 			/* Empty.  Blast it. */
11865 			IP_REASS_SET_START(mp, 0);
11866 			IP_REASS_SET_END(mp, 0);
11867 			/*
11868 			 * If the ipf points to the mblk we are about to free,
11869 			 * update ipf to point to the next mblk (or NULL
11870 			 * if none).
11871 			 */
11872 			if (ipf->ipf_mp->b_cont == mp)
11873 				ipf->ipf_mp->b_cont = next_mp;
11874 			freeb(mp);
11875 			continue;
11876 		}
11877 		mp->b_cont = NULL;
11878 		IP_REASS_SET_START(mp, start);
11879 		IP_REASS_SET_END(mp, end);
11880 		if (!ipf->ipf_tail_mp) {
11881 			ipf->ipf_tail_mp = mp;
11882 			ipf->ipf_mp->b_cont = mp;
11883 			if (start == 0 || !more) {
11884 				ipf->ipf_hole_cnt = 1;
11885 				/*
11886 				 * if the first fragment comes in more than one
11887 				 * mblk, this loop will be executed for each
11888 				 * mblk. Need to adjust hole count so exiting
11889 				 * this routine will leave hole count at 1.
11890 				 */
11891 				if (next_mp)
11892 					ipf->ipf_hole_cnt++;
11893 			} else
11894 				ipf->ipf_hole_cnt = 2;
11895 			continue;
11896 		} else if (ipf->ipf_last_frag_seen && !more &&
11897 			    !pkt_boundary_checked) {
11898 			/*
11899 			 * We check datagram boundary only if this fragment
11900 			 * claims to be the last fragment and we have seen a
11901 			 * last fragment in the past too. We do this only
11902 			 * once for a given fragment.
11903 			 *
11904 			 * start cannot be 0 here as fragments with start=0
11905 			 * and MF=0 gets handled as a complete packet. These
11906 			 * fragments should not reach here.
11907 			 */
11908 
11909 			if (start + msgdsize(mp) !=
11910 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11911 				/*
11912 				 * We have two fragments both of which claim
11913 				 * to be the last fragment but gives conflicting
11914 				 * information about the whole datagram size.
11915 				 * Something fishy is going on. Drop the
11916 				 * fragment and free up the reassembly list.
11917 				 */
11918 				return (IP_REASS_FAILED);
11919 			}
11920 
11921 			/*
11922 			 * We shouldn't come to this code block again for this
11923 			 * particular fragment.
11924 			 */
11925 			pkt_boundary_checked = B_TRUE;
11926 		}
11927 
11928 		/* New stuff at or beyond tail? */
11929 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11930 		if (start >= offset) {
11931 			if (ipf->ipf_last_frag_seen) {
11932 				/* current fragment is beyond last fragment */
11933 				return (IP_REASS_FAILED);
11934 			}
11935 			/* Link it on end. */
11936 			ipf->ipf_tail_mp->b_cont = mp;
11937 			ipf->ipf_tail_mp = mp;
11938 			if (more) {
11939 				if (start != offset)
11940 					ipf->ipf_hole_cnt++;
11941 			} else if (start == offset && next_mp == NULL)
11942 					ipf->ipf_hole_cnt--;
11943 			continue;
11944 		}
11945 		mp1 = ipf->ipf_mp->b_cont;
11946 		offset = IP_REASS_START(mp1);
11947 		/* New stuff at the front? */
11948 		if (start < offset) {
11949 			if (start == 0) {
11950 				if (end >= offset) {
11951 					/* Nailed the hole at the begining. */
11952 					ipf->ipf_hole_cnt--;
11953 				}
11954 			} else if (end < offset) {
11955 				/*
11956 				 * A hole, stuff, and a hole where there used
11957 				 * to be just a hole.
11958 				 */
11959 				ipf->ipf_hole_cnt++;
11960 			}
11961 			mp->b_cont = mp1;
11962 			/* Check for overlap. */
11963 			while (end > offset) {
11964 				if (end < IP_REASS_END(mp1)) {
11965 					mp->b_wptr -= end - offset;
11966 					IP_REASS_SET_END(mp, offset);
11967 					BUMP_MIB(ill->ill_ip_mib,
11968 					    ipIfStatsReasmPartDups);
11969 					break;
11970 				}
11971 				/* Did we cover another hole? */
11972 				if ((mp1->b_cont &&
11973 				    IP_REASS_END(mp1) !=
11974 				    IP_REASS_START(mp1->b_cont) &&
11975 				    end >= IP_REASS_START(mp1->b_cont)) ||
11976 				    (!ipf->ipf_last_frag_seen && !more)) {
11977 					ipf->ipf_hole_cnt--;
11978 				}
11979 				/* Clip out mp1. */
11980 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11981 					/*
11982 					 * After clipping out mp1, this guy
11983 					 * is now hanging off the end.
11984 					 */
11985 					ipf->ipf_tail_mp = mp;
11986 				}
11987 				IP_REASS_SET_START(mp1, 0);
11988 				IP_REASS_SET_END(mp1, 0);
11989 				/* Subtract byte count */
11990 				ipf->ipf_count -= mp1->b_datap->db_lim -
11991 				    mp1->b_datap->db_base;
11992 				freeb(mp1);
11993 				BUMP_MIB(ill->ill_ip_mib,
11994 				    ipIfStatsReasmPartDups);
11995 				mp1 = mp->b_cont;
11996 				if (!mp1)
11997 					break;
11998 				offset = IP_REASS_START(mp1);
11999 			}
12000 			ipf->ipf_mp->b_cont = mp;
12001 			continue;
12002 		}
12003 		/*
12004 		 * The new piece starts somewhere between the start of the head
12005 		 * and before the end of the tail.
12006 		 */
12007 		for (; mp1; mp1 = mp1->b_cont) {
12008 			offset = IP_REASS_END(mp1);
12009 			if (start < offset) {
12010 				if (end <= offset) {
12011 					/* Nothing new. */
12012 					IP_REASS_SET_START(mp, 0);
12013 					IP_REASS_SET_END(mp, 0);
12014 					/* Subtract byte count */
12015 					ipf->ipf_count -= mp->b_datap->db_lim -
12016 					    mp->b_datap->db_base;
12017 					if (incr_dups) {
12018 						ipf->ipf_num_dups++;
12019 						incr_dups = B_FALSE;
12020 					}
12021 					freeb(mp);
12022 					BUMP_MIB(ill->ill_ip_mib,
12023 					    ipIfStatsReasmDuplicates);
12024 					break;
12025 				}
12026 				/*
12027 				 * Trim redundant stuff off beginning of new
12028 				 * piece.
12029 				 */
12030 				IP_REASS_SET_START(mp, offset);
12031 				mp->b_rptr += offset - start;
12032 				BUMP_MIB(ill->ill_ip_mib,
12033 				    ipIfStatsReasmPartDups);
12034 				start = offset;
12035 				if (!mp1->b_cont) {
12036 					/*
12037 					 * After trimming, this guy is now
12038 					 * hanging off the end.
12039 					 */
12040 					mp1->b_cont = mp;
12041 					ipf->ipf_tail_mp = mp;
12042 					if (!more) {
12043 						ipf->ipf_hole_cnt--;
12044 					}
12045 					break;
12046 				}
12047 			}
12048 			if (start >= IP_REASS_START(mp1->b_cont))
12049 				continue;
12050 			/* Fill a hole */
12051 			if (start > offset)
12052 				ipf->ipf_hole_cnt++;
12053 			mp->b_cont = mp1->b_cont;
12054 			mp1->b_cont = mp;
12055 			mp1 = mp->b_cont;
12056 			offset = IP_REASS_START(mp1);
12057 			if (end >= offset) {
12058 				ipf->ipf_hole_cnt--;
12059 				/* Check for overlap. */
12060 				while (end > offset) {
12061 					if (end < IP_REASS_END(mp1)) {
12062 						mp->b_wptr -= end - offset;
12063 						IP_REASS_SET_END(mp, offset);
12064 						/*
12065 						 * TODO we might bump
12066 						 * this up twice if there is
12067 						 * overlap at both ends.
12068 						 */
12069 						BUMP_MIB(ill->ill_ip_mib,
12070 						    ipIfStatsReasmPartDups);
12071 						break;
12072 					}
12073 					/* Did we cover another hole? */
12074 					if ((mp1->b_cont &&
12075 					    IP_REASS_END(mp1)
12076 					    != IP_REASS_START(mp1->b_cont) &&
12077 					    end >=
12078 					    IP_REASS_START(mp1->b_cont)) ||
12079 					    (!ipf->ipf_last_frag_seen &&
12080 					    !more)) {
12081 						ipf->ipf_hole_cnt--;
12082 					}
12083 					/* Clip out mp1. */
12084 					if ((mp->b_cont = mp1->b_cont) ==
12085 					    NULL) {
12086 						/*
12087 						 * After clipping out mp1,
12088 						 * this guy is now hanging
12089 						 * off the end.
12090 						 */
12091 						ipf->ipf_tail_mp = mp;
12092 					}
12093 					IP_REASS_SET_START(mp1, 0);
12094 					IP_REASS_SET_END(mp1, 0);
12095 					/* Subtract byte count */
12096 					ipf->ipf_count -=
12097 					    mp1->b_datap->db_lim -
12098 					    mp1->b_datap->db_base;
12099 					freeb(mp1);
12100 					BUMP_MIB(ill->ill_ip_mib,
12101 					    ipIfStatsReasmPartDups);
12102 					mp1 = mp->b_cont;
12103 					if (!mp1)
12104 						break;
12105 					offset = IP_REASS_START(mp1);
12106 				}
12107 			}
12108 			break;
12109 		}
12110 	} while (start = end, mp = next_mp);
12111 
12112 	/* Fragment just processed could be the last one. Remember this fact */
12113 	if (!more)
12114 		ipf->ipf_last_frag_seen = B_TRUE;
12115 
12116 	/* Still got holes? */
12117 	if (ipf->ipf_hole_cnt)
12118 		return (IP_REASS_PARTIAL);
12119 	/* Clean up overloaded fields to avoid upstream disasters. */
12120 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12121 		IP_REASS_SET_START(mp1, 0);
12122 		IP_REASS_SET_END(mp1, 0);
12123 	}
12124 	return (IP_REASS_COMPLETE);
12125 }
12126 
12127 /*
12128  * ipsec processing for the fast path, used for input UDP Packets
12129  */
12130 static boolean_t
12131 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12132     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
12133 {
12134 	uint32_t	ill_index;
12135 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12136 
12137 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12138 	/* The ill_index of the incoming ILL */
12139 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12140 
12141 	/* pass packet up to the transport */
12142 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12143 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12144 		    NULL, mctl_present);
12145 		if (*first_mpp == NULL) {
12146 			return (B_FALSE);
12147 		}
12148 	}
12149 
12150 	/* Initiate IPPF processing for fastpath UDP */
12151 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12152 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12153 		if (*mpp == NULL) {
12154 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12155 			    "deferred/dropped during IPPF processing\n"));
12156 			return (B_FALSE);
12157 		}
12158 	}
12159 	/*
12160 	 * We make the checks as below since we are in the fast path
12161 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12162 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12163 	 */
12164 	if (connp->conn_recvif || connp->conn_recvslla ||
12165 	    connp->conn_ip_recvpktinfo) {
12166 		if (connp->conn_recvif) {
12167 			in_flags = IPF_RECVIF;
12168 		}
12169 		/*
12170 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12171 		 * so the flag passed to ip_add_info is based on IP version
12172 		 * of connp.
12173 		 */
12174 		if (connp->conn_ip_recvpktinfo) {
12175 			if (connp->conn_af_isv6) {
12176 				/*
12177 				 * V6 only needs index
12178 				 */
12179 				in_flags |= IPF_RECVIF;
12180 			} else {
12181 				/*
12182 				 * V4 needs index + matching address.
12183 				 */
12184 				in_flags |= IPF_RECVADDR;
12185 			}
12186 		}
12187 		if (connp->conn_recvslla) {
12188 			in_flags |= IPF_RECVSLLA;
12189 		}
12190 		/*
12191 		 * since in_flags are being set ill will be
12192 		 * referenced in ip_add_info, so it better not
12193 		 * be NULL.
12194 		 */
12195 		/*
12196 		 * the actual data will be contained in b_cont
12197 		 * upon successful return of the following call.
12198 		 * If the call fails then the original mblk is
12199 		 * returned.
12200 		 */
12201 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp));
12202 	}
12203 
12204 	return (B_TRUE);
12205 }
12206 
12207 /*
12208  * Fragmentation reassembly.  Each ILL has a hash table for
12209  * queuing packets undergoing reassembly for all IPIFs
12210  * associated with the ILL.  The hash is based on the packet
12211  * IP ident field.  The ILL frag hash table was allocated
12212  * as a timer block at the time the ILL was created.  Whenever
12213  * there is anything on the reassembly queue, the timer will
12214  * be running.  Returns B_TRUE if successful else B_FALSE;
12215  * frees mp on failure.
12216  */
12217 static boolean_t
12218 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12219     uint32_t *cksum_val, uint16_t *cksum_flags)
12220 {
12221 	uint32_t	frag_offset_flags;
12222 	ill_t		*ill = (ill_t *)q->q_ptr;
12223 	mblk_t		*mp = *mpp;
12224 	mblk_t		*t_mp;
12225 	ipaddr_t	dst;
12226 	uint8_t		proto = ipha->ipha_protocol;
12227 	uint32_t	sum_val;
12228 	uint16_t	sum_flags;
12229 	ipf_t		*ipf;
12230 	ipf_t		**ipfp;
12231 	ipfb_t		*ipfb;
12232 	uint16_t	ident;
12233 	uint32_t	offset;
12234 	ipaddr_t	src;
12235 	uint_t		hdr_length;
12236 	uint32_t	end;
12237 	mblk_t		*mp1;
12238 	mblk_t		*tail_mp;
12239 	size_t		count;
12240 	size_t		msg_len;
12241 	uint8_t		ecn_info = 0;
12242 	uint32_t	packet_size;
12243 	boolean_t	pruned = B_FALSE;
12244 
12245 	if (cksum_val != NULL)
12246 		*cksum_val = 0;
12247 	if (cksum_flags != NULL)
12248 		*cksum_flags = 0;
12249 
12250 	/*
12251 	 * Drop the fragmented as early as possible, if
12252 	 * we don't have resource(s) to re-assemble.
12253 	 */
12254 	if (ip_reass_queue_bytes == 0) {
12255 		freemsg(mp);
12256 		return (B_FALSE);
12257 	}
12258 
12259 	/* Check for fragmentation offset; return if there's none */
12260 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12261 	    (IPH_MF | IPH_OFFSET)) == 0)
12262 		return (B_TRUE);
12263 
12264 	/*
12265 	 * We utilize hardware computed checksum info only for UDP since
12266 	 * IP fragmentation is a normal occurence for the protocol.  In
12267 	 * addition, checksum offload support for IP fragments carrying
12268 	 * UDP payload is commonly implemented across network adapters.
12269 	 */
12270 	ASSERT(ill != NULL);
12271 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12272 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12273 		mblk_t *mp1 = mp->b_cont;
12274 		int32_t len;
12275 
12276 		/* Record checksum information from the packet */
12277 		sum_val = (uint32_t)DB_CKSUM16(mp);
12278 		sum_flags = DB_CKSUMFLAGS(mp);
12279 
12280 		/* IP payload offset from beginning of mblk */
12281 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12282 
12283 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12284 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12285 		    offset >= DB_CKSUMSTART(mp) &&
12286 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12287 			uint32_t adj;
12288 			/*
12289 			 * Partial checksum has been calculated by hardware
12290 			 * and attached to the packet; in addition, any
12291 			 * prepended extraneous data is even byte aligned.
12292 			 * If any such data exists, we adjust the checksum;
12293 			 * this would also handle any postpended data.
12294 			 */
12295 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12296 			    mp, mp1, len, adj);
12297 
12298 			/* One's complement subtract extraneous checksum */
12299 			if (adj >= sum_val)
12300 				sum_val = ~(adj - sum_val) & 0xFFFF;
12301 			else
12302 				sum_val -= adj;
12303 		}
12304 	} else {
12305 		sum_val = 0;
12306 		sum_flags = 0;
12307 	}
12308 
12309 	/* Clear hardware checksumming flag */
12310 	DB_CKSUMFLAGS(mp) = 0;
12311 
12312 	ident = ipha->ipha_ident;
12313 	offset = (frag_offset_flags << 3) & 0xFFFF;
12314 	src = ipha->ipha_src;
12315 	dst = ipha->ipha_dst;
12316 	hdr_length = IPH_HDR_LENGTH(ipha);
12317 	end = ntohs(ipha->ipha_length) - hdr_length;
12318 
12319 	/* If end == 0 then we have a packet with no data, so just free it */
12320 	if (end == 0) {
12321 		freemsg(mp);
12322 		return (B_FALSE);
12323 	}
12324 
12325 	/* Record the ECN field info. */
12326 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12327 	if (offset != 0) {
12328 		/*
12329 		 * If this isn't the first piece, strip the header, and
12330 		 * add the offset to the end value.
12331 		 */
12332 		mp->b_rptr += hdr_length;
12333 		end += offset;
12334 	}
12335 
12336 	msg_len = MBLKSIZE(mp);
12337 	tail_mp = mp;
12338 	while (tail_mp->b_cont != NULL) {
12339 		tail_mp = tail_mp->b_cont;
12340 		msg_len += MBLKSIZE(tail_mp);
12341 	}
12342 
12343 	/* If the reassembly list for this ILL will get too big, prune it */
12344 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12345 	    ip_reass_queue_bytes) {
12346 		ill_frag_prune(ill,
12347 		    (ip_reass_queue_bytes < msg_len) ? 0 :
12348 		    (ip_reass_queue_bytes - msg_len));
12349 		pruned = B_TRUE;
12350 	}
12351 
12352 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12353 	mutex_enter(&ipfb->ipfb_lock);
12354 
12355 	ipfp = &ipfb->ipfb_ipf;
12356 	/* Try to find an existing fragment queue for this packet. */
12357 	for (;;) {
12358 		ipf = ipfp[0];
12359 		if (ipf != NULL) {
12360 			/*
12361 			 * It has to match on ident and src/dst address.
12362 			 */
12363 			if (ipf->ipf_ident == ident &&
12364 			    ipf->ipf_src == src &&
12365 			    ipf->ipf_dst == dst &&
12366 			    ipf->ipf_protocol == proto) {
12367 				/*
12368 				 * If we have received too many
12369 				 * duplicate fragments for this packet
12370 				 * free it.
12371 				 */
12372 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12373 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12374 					freemsg(mp);
12375 					mutex_exit(&ipfb->ipfb_lock);
12376 					return (B_FALSE);
12377 				}
12378 				/* Found it. */
12379 				break;
12380 			}
12381 			ipfp = &ipf->ipf_hash_next;
12382 			continue;
12383 		}
12384 
12385 		/*
12386 		 * If we pruned the list, do we want to store this new
12387 		 * fragment?. We apply an optimization here based on the
12388 		 * fact that most fragments will be received in order.
12389 		 * So if the offset of this incoming fragment is zero,
12390 		 * it is the first fragment of a new packet. We will
12391 		 * keep it.  Otherwise drop the fragment, as we have
12392 		 * probably pruned the packet already (since the
12393 		 * packet cannot be found).
12394 		 */
12395 		if (pruned && offset != 0) {
12396 			mutex_exit(&ipfb->ipfb_lock);
12397 			freemsg(mp);
12398 			return (B_FALSE);
12399 		}
12400 
12401 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12402 			/*
12403 			 * Too many fragmented packets in this hash
12404 			 * bucket. Free the oldest.
12405 			 */
12406 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12407 		}
12408 
12409 		/* New guy.  Allocate a frag message. */
12410 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12411 		if (mp1 == NULL) {
12412 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12413 			freemsg(mp);
12414 reass_done:
12415 			mutex_exit(&ipfb->ipfb_lock);
12416 			return (B_FALSE);
12417 		}
12418 
12419 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12420 		mp1->b_cont = mp;
12421 
12422 		/* Initialize the fragment header. */
12423 		ipf = (ipf_t *)mp1->b_rptr;
12424 		ipf->ipf_mp = mp1;
12425 		ipf->ipf_ptphn = ipfp;
12426 		ipfp[0] = ipf;
12427 		ipf->ipf_hash_next = NULL;
12428 		ipf->ipf_ident = ident;
12429 		ipf->ipf_protocol = proto;
12430 		ipf->ipf_src = src;
12431 		ipf->ipf_dst = dst;
12432 		ipf->ipf_nf_hdr_len = 0;
12433 		/* Record reassembly start time. */
12434 		ipf->ipf_timestamp = gethrestime_sec();
12435 		/* Record ipf generation and account for frag header */
12436 		ipf->ipf_gen = ill->ill_ipf_gen++;
12437 		ipf->ipf_count = MBLKSIZE(mp1);
12438 		ipf->ipf_last_frag_seen = B_FALSE;
12439 		ipf->ipf_ecn = ecn_info;
12440 		ipf->ipf_num_dups = 0;
12441 		ipfb->ipfb_frag_pkts++;
12442 		ipf->ipf_checksum = 0;
12443 		ipf->ipf_checksum_flags = 0;
12444 
12445 		/* Store checksum value in fragment header */
12446 		if (sum_flags != 0) {
12447 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12448 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12449 			ipf->ipf_checksum = sum_val;
12450 			ipf->ipf_checksum_flags = sum_flags;
12451 		}
12452 
12453 		/*
12454 		 * We handle reassembly two ways.  In the easy case,
12455 		 * where all the fragments show up in order, we do
12456 		 * minimal bookkeeping, and just clip new pieces on
12457 		 * the end.  If we ever see a hole, then we go off
12458 		 * to ip_reassemble which has to mark the pieces and
12459 		 * keep track of the number of holes, etc.  Obviously,
12460 		 * the point of having both mechanisms is so we can
12461 		 * handle the easy case as efficiently as possible.
12462 		 */
12463 		if (offset == 0) {
12464 			/* Easy case, in-order reassembly so far. */
12465 			ipf->ipf_count += msg_len;
12466 			ipf->ipf_tail_mp = tail_mp;
12467 			/*
12468 			 * Keep track of next expected offset in
12469 			 * ipf_end.
12470 			 */
12471 			ipf->ipf_end = end;
12472 			ipf->ipf_nf_hdr_len = hdr_length;
12473 		} else {
12474 			/* Hard case, hole at the beginning. */
12475 			ipf->ipf_tail_mp = NULL;
12476 			/*
12477 			 * ipf_end == 0 means that we have given up
12478 			 * on easy reassembly.
12479 			 */
12480 			ipf->ipf_end = 0;
12481 
12482 			/* Forget checksum offload from now on */
12483 			ipf->ipf_checksum_flags = 0;
12484 
12485 			/*
12486 			 * ipf_hole_cnt is set by ip_reassemble.
12487 			 * ipf_count is updated by ip_reassemble.
12488 			 * No need to check for return value here
12489 			 * as we don't expect reassembly to complete
12490 			 * or fail for the first fragment itself.
12491 			 */
12492 			(void) ip_reassemble(mp, ipf,
12493 			    (frag_offset_flags & IPH_OFFSET) << 3,
12494 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12495 		}
12496 		/* Update per ipfb and ill byte counts */
12497 		ipfb->ipfb_count += ipf->ipf_count;
12498 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12499 		ill->ill_frag_count += ipf->ipf_count;
12500 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12501 		/* If the frag timer wasn't already going, start it. */
12502 		mutex_enter(&ill->ill_lock);
12503 		ill_frag_timer_start(ill);
12504 		mutex_exit(&ill->ill_lock);
12505 		goto reass_done;
12506 	}
12507 
12508 	/*
12509 	 * If the packet's flag has changed (it could be coming up
12510 	 * from an interface different than the previous, therefore
12511 	 * possibly different checksum capability), then forget about
12512 	 * any stored checksum states.  Otherwise add the value to
12513 	 * the existing one stored in the fragment header.
12514 	 */
12515 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12516 		sum_val += ipf->ipf_checksum;
12517 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12518 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12519 		ipf->ipf_checksum = sum_val;
12520 	} else if (ipf->ipf_checksum_flags != 0) {
12521 		/* Forget checksum offload from now on */
12522 		ipf->ipf_checksum_flags = 0;
12523 	}
12524 
12525 	/*
12526 	 * We have a new piece of a datagram which is already being
12527 	 * reassembled.  Update the ECN info if all IP fragments
12528 	 * are ECN capable.  If there is one which is not, clear
12529 	 * all the info.  If there is at least one which has CE
12530 	 * code point, IP needs to report that up to transport.
12531 	 */
12532 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12533 		if (ecn_info == IPH_ECN_CE)
12534 			ipf->ipf_ecn = IPH_ECN_CE;
12535 	} else {
12536 		ipf->ipf_ecn = IPH_ECN_NECT;
12537 	}
12538 	if (offset && ipf->ipf_end == offset) {
12539 		/* The new fragment fits at the end */
12540 		ipf->ipf_tail_mp->b_cont = mp;
12541 		/* Update the byte count */
12542 		ipf->ipf_count += msg_len;
12543 		/* Update per ipfb and ill byte counts */
12544 		ipfb->ipfb_count += msg_len;
12545 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12546 		ill->ill_frag_count += msg_len;
12547 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12548 		if (frag_offset_flags & IPH_MF) {
12549 			/* More to come. */
12550 			ipf->ipf_end = end;
12551 			ipf->ipf_tail_mp = tail_mp;
12552 			goto reass_done;
12553 		}
12554 	} else {
12555 		/* Go do the hard cases. */
12556 		int ret;
12557 
12558 		if (offset == 0)
12559 			ipf->ipf_nf_hdr_len = hdr_length;
12560 
12561 		/* Save current byte count */
12562 		count = ipf->ipf_count;
12563 		ret = ip_reassemble(mp, ipf,
12564 		    (frag_offset_flags & IPH_OFFSET) << 3,
12565 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12566 		/* Count of bytes added and subtracted (freeb()ed) */
12567 		count = ipf->ipf_count - count;
12568 		if (count) {
12569 			/* Update per ipfb and ill byte counts */
12570 			ipfb->ipfb_count += count;
12571 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12572 			ill->ill_frag_count += count;
12573 			ASSERT(ill->ill_frag_count > 0);
12574 		}
12575 		if (ret == IP_REASS_PARTIAL) {
12576 			goto reass_done;
12577 		} else if (ret == IP_REASS_FAILED) {
12578 			/* Reassembly failed. Free up all resources */
12579 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12580 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12581 				IP_REASS_SET_START(t_mp, 0);
12582 				IP_REASS_SET_END(t_mp, 0);
12583 			}
12584 			freemsg(mp);
12585 			goto reass_done;
12586 		}
12587 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12588 	}
12589 	/*
12590 	 * We have completed reassembly.  Unhook the frag header from
12591 	 * the reassembly list.
12592 	 *
12593 	 * Before we free the frag header, record the ECN info
12594 	 * to report back to the transport.
12595 	 */
12596 	ecn_info = ipf->ipf_ecn;
12597 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12598 	ipfp = ipf->ipf_ptphn;
12599 
12600 	/* We need to supply these to caller */
12601 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12602 		sum_val = ipf->ipf_checksum;
12603 	else
12604 		sum_val = 0;
12605 
12606 	mp1 = ipf->ipf_mp;
12607 	count = ipf->ipf_count;
12608 	ipf = ipf->ipf_hash_next;
12609 	if (ipf != NULL)
12610 		ipf->ipf_ptphn = ipfp;
12611 	ipfp[0] = ipf;
12612 	ill->ill_frag_count -= count;
12613 	ASSERT(ipfb->ipfb_count >= count);
12614 	ipfb->ipfb_count -= count;
12615 	ipfb->ipfb_frag_pkts--;
12616 	mutex_exit(&ipfb->ipfb_lock);
12617 	/* Ditch the frag header. */
12618 	mp = mp1->b_cont;
12619 
12620 	freeb(mp1);
12621 
12622 	/* Restore original IP length in header. */
12623 	packet_size = (uint32_t)msgdsize(mp);
12624 	if (packet_size > IP_MAXPACKET) {
12625 		freemsg(mp);
12626 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12627 		return (B_FALSE);
12628 	}
12629 
12630 	if (DB_REF(mp) > 1) {
12631 		mblk_t *mp2 = copymsg(mp);
12632 
12633 		freemsg(mp);
12634 		if (mp2 == NULL) {
12635 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12636 			return (B_FALSE);
12637 		}
12638 		mp = mp2;
12639 	}
12640 	ipha = (ipha_t *)mp->b_rptr;
12641 
12642 	ipha->ipha_length = htons((uint16_t)packet_size);
12643 	/* We're now complete, zip the frag state */
12644 	ipha->ipha_fragment_offset_and_flags = 0;
12645 	/* Record the ECN info. */
12646 	ipha->ipha_type_of_service &= 0xFC;
12647 	ipha->ipha_type_of_service |= ecn_info;
12648 	*mpp = mp;
12649 
12650 	/* Reassembly is successful; return checksum information if needed */
12651 	if (cksum_val != NULL)
12652 		*cksum_val = sum_val;
12653 	if (cksum_flags != NULL)
12654 		*cksum_flags = sum_flags;
12655 
12656 	return (B_TRUE);
12657 }
12658 
12659 /*
12660  * Perform ip header check sum update local options.
12661  * return B_TRUE if all is well, else return B_FALSE and release
12662  * the mp. caller is responsible for decrementing ire ref cnt.
12663  */
12664 static boolean_t
12665 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12666 {
12667 	mblk_t		*first_mp;
12668 	boolean_t	mctl_present;
12669 	uint16_t	sum;
12670 
12671 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12672 	/*
12673 	 * Don't do the checksum if it has gone through AH/ESP
12674 	 * processing.
12675 	 */
12676 	if (!mctl_present) {
12677 		sum = ip_csum_hdr(ipha);
12678 		if (sum != 0) {
12679 			if (ill != NULL) {
12680 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12681 			} else {
12682 				BUMP_MIB(&ip_mib, ipIfStatsInCksumErrs);
12683 			}
12684 			freemsg(first_mp);
12685 			return (B_FALSE);
12686 		}
12687 	}
12688 
12689 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12690 		if (mctl_present)
12691 			freeb(first_mp);
12692 		return (B_FALSE);
12693 	}
12694 
12695 	return (B_TRUE);
12696 }
12697 
12698 /*
12699  * All udp packet are delivered to the local host via this routine.
12700  */
12701 void
12702 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12703     ill_t *recv_ill)
12704 {
12705 	uint32_t	sum;
12706 	uint32_t	u1;
12707 	boolean_t	mctl_present;
12708 	conn_t		*connp;
12709 	mblk_t		*first_mp;
12710 	uint16_t	*up;
12711 	ill_t		*ill = (ill_t *)q->q_ptr;
12712 	uint16_t	reass_hck_flags = 0;
12713 
12714 #define	rptr    ((uchar_t *)ipha)
12715 
12716 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12717 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12718 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12719 	ASSERT(ill != NULL);
12720 
12721 	/*
12722 	 * FAST PATH for udp packets
12723 	 */
12724 
12725 	/* u1 is # words of IP options */
12726 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12727 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12728 
12729 	/* IP options present */
12730 	if (u1 != 0)
12731 		goto ipoptions;
12732 
12733 	/* Check the IP header checksum.  */
12734 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12735 		/* Clear the IP header h/w cksum flag */
12736 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12737 	} else {
12738 #define	uph	((uint16_t *)ipha)
12739 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12740 		    uph[6] + uph[7] + uph[8] + uph[9];
12741 #undef	uph
12742 		/* finish doing IP checksum */
12743 		sum = (sum & 0xFFFF) + (sum >> 16);
12744 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12745 		/*
12746 		 * Don't verify header checksum if this packet is coming
12747 		 * back from AH/ESP as we already did it.
12748 		 */
12749 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12750 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12751 			freemsg(first_mp);
12752 			return;
12753 		}
12754 	}
12755 
12756 	/*
12757 	 * Count for SNMP of inbound packets for ire.
12758 	 * if mctl is present this might be a secure packet and
12759 	 * has already been counted for in ip_proto_input().
12760 	 */
12761 	if (!mctl_present) {
12762 		UPDATE_IB_PKT_COUNT(ire);
12763 		ire->ire_last_used_time = lbolt;
12764 	}
12765 
12766 	/* packet part of fragmented IP packet? */
12767 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12768 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12769 		goto fragmented;
12770 	}
12771 
12772 	/* u1 = IP header length (20 bytes) */
12773 	u1 = IP_SIMPLE_HDR_LENGTH;
12774 
12775 	/* packet does not contain complete IP & UDP headers */
12776 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12777 		goto udppullup;
12778 
12779 	/* up points to UDP header */
12780 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12781 #define	iphs    ((uint16_t *)ipha)
12782 
12783 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12784 	if (up[3] != 0) {
12785 		mblk_t *mp1 = mp->b_cont;
12786 		boolean_t cksum_err;
12787 		uint16_t hck_flags = 0;
12788 
12789 		/* Pseudo-header checksum */
12790 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12791 		    iphs[9] + up[2];
12792 
12793 		/*
12794 		 * Revert to software checksum calculation if the interface
12795 		 * isn't capable of checksum offload or if IPsec is present.
12796 		 */
12797 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12798 			hck_flags = DB_CKSUMFLAGS(mp);
12799 
12800 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12801 			IP_STAT(ip_in_sw_cksum);
12802 
12803 		IP_CKSUM_RECV(hck_flags, u1,
12804 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12805 		    (int32_t)((uchar_t *)up - rptr),
12806 		    mp, mp1, cksum_err);
12807 
12808 		if (cksum_err) {
12809 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12810 			if (hck_flags & HCK_FULLCKSUM)
12811 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12812 			else if (hck_flags & HCK_PARTIALCKSUM)
12813 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12814 			else
12815 				IP_STAT(ip_udp_in_sw_cksum_err);
12816 
12817 			freemsg(first_mp);
12818 			return;
12819 		}
12820 	}
12821 
12822 	/* Non-fragmented broadcast or multicast packet? */
12823 	if (ire->ire_type == IRE_BROADCAST)
12824 		goto udpslowpath;
12825 
12826 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12827 	    ire->ire_zoneid)) != NULL) {
12828 		ASSERT(connp->conn_upq != NULL);
12829 		IP_STAT(ip_udp_fast_path);
12830 
12831 		if (CONN_UDP_FLOWCTLD(connp)) {
12832 			freemsg(mp);
12833 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12834 		} else {
12835 			if (!mctl_present) {
12836 				BUMP_MIB(ill->ill_ip_mib,
12837 				    ipIfStatsHCInDelivers);
12838 			}
12839 			/*
12840 			 * mp and first_mp can change.
12841 			 */
12842 			if (ip_udp_check(q, connp, recv_ill,
12843 			    ipha, &mp, &first_mp, mctl_present)) {
12844 				/* Send it upstream */
12845 				CONN_UDP_RECV(connp, mp);
12846 			}
12847 		}
12848 		/*
12849 		 * freeb() cannot deal with null mblk being passed
12850 		 * in and first_mp can be set to null in the call
12851 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12852 		 */
12853 		if (mctl_present && first_mp != NULL) {
12854 			freeb(first_mp);
12855 		}
12856 		CONN_DEC_REF(connp);
12857 		return;
12858 	}
12859 
12860 	/*
12861 	 * if we got here we know the packet is not fragmented and
12862 	 * has no options. The classifier could not find a conn_t and
12863 	 * most likely its an icmp packet so send it through slow path.
12864 	 */
12865 
12866 	goto udpslowpath;
12867 
12868 ipoptions:
12869 	if (!ip_options_cksum(q, ill, mp, ipha, ire)) {
12870 		goto slow_done;
12871 	}
12872 
12873 	UPDATE_IB_PKT_COUNT(ire);
12874 	ire->ire_last_used_time = lbolt;
12875 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12876 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12877 fragmented:
12878 		/*
12879 		 * "sum" and "reass_hck_flags" are non-zero if the
12880 		 * reassembled packet has a valid hardware computed
12881 		 * checksum information associated with it.
12882 		 */
12883 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12884 			goto slow_done;
12885 		/*
12886 		 * Make sure that first_mp points back to mp as
12887 		 * the mp we came in with could have changed in
12888 		 * ip_rput_fragment().
12889 		 */
12890 		ASSERT(!mctl_present);
12891 		ipha = (ipha_t *)mp->b_rptr;
12892 		first_mp = mp;
12893 	}
12894 
12895 	/* Now we have a complete datagram, destined for this machine. */
12896 	u1 = IPH_HDR_LENGTH(ipha);
12897 	/* Pull up the UDP header, if necessary. */
12898 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12899 udppullup:
12900 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12901 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12902 			freemsg(first_mp);
12903 			goto slow_done;
12904 		}
12905 		ipha = (ipha_t *)mp->b_rptr;
12906 	}
12907 
12908 	/*
12909 	 * Validate the checksum for the reassembled packet; for the
12910 	 * pullup case we calculate the payload checksum in software.
12911 	 */
12912 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12913 	if (up[3] != 0) {
12914 		boolean_t cksum_err;
12915 
12916 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12917 			IP_STAT(ip_in_sw_cksum);
12918 
12919 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12920 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12921 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12922 		    iphs[9] + up[2], sum, cksum_err);
12923 
12924 		if (cksum_err) {
12925 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12926 
12927 			if (reass_hck_flags & HCK_FULLCKSUM)
12928 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12929 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12930 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12931 			else
12932 				IP_STAT(ip_udp_in_sw_cksum_err);
12933 
12934 			freemsg(first_mp);
12935 			goto slow_done;
12936 		}
12937 	}
12938 udpslowpath:
12939 
12940 	/* Clear hardware checksum flag to be safe */
12941 	DB_CKSUMFLAGS(mp) = 0;
12942 
12943 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12944 	    (ire->ire_type == IRE_BROADCAST),
12945 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12946 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12947 
12948 slow_done:
12949 	IP_STAT(ip_udp_slow_path);
12950 	return;
12951 
12952 #undef  iphs
12953 #undef  rptr
12954 }
12955 
12956 /* ARGSUSED */
12957 static mblk_t *
12958 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12959     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12960     ill_rx_ring_t *ill_ring)
12961 {
12962 	conn_t		*connp;
12963 	uint32_t	sum;
12964 	uint32_t	u1;
12965 	uint16_t	*up;
12966 	int		offset;
12967 	ssize_t		len;
12968 	mblk_t		*mp1;
12969 	boolean_t	syn_present = B_FALSE;
12970 	tcph_t		*tcph;
12971 	uint_t		ip_hdr_len;
12972 	ill_t		*ill = (ill_t *)q->q_ptr;
12973 	zoneid_t	zoneid = ire->ire_zoneid;
12974 	boolean_t	cksum_err;
12975 	uint16_t	hck_flags = 0;
12976 
12977 #define	rptr	((uchar_t *)ipha)
12978 
12979 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12980 	ASSERT(ill != NULL);
12981 
12982 	/*
12983 	 * FAST PATH for tcp packets
12984 	 */
12985 
12986 	/* u1 is # words of IP options */
12987 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12988 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12989 
12990 	/* IP options present */
12991 	if (u1) {
12992 		goto ipoptions;
12993 	} else {
12994 		/* Check the IP header checksum.  */
12995 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12996 			/* Clear the IP header h/w cksum flag */
12997 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12998 		} else {
12999 #define	uph	((uint16_t *)ipha)
13000 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13001 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13002 #undef	uph
13003 			/* finish doing IP checksum */
13004 			sum = (sum & 0xFFFF) + (sum >> 16);
13005 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13006 			/*
13007 			 * Don't verify header checksum if this packet
13008 			 * is coming back from AH/ESP as we already did it.
13009 			 */
13010 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13011 				BUMP_MIB(ill->ill_ip_mib,
13012 				    ipIfStatsInCksumErrs);
13013 				goto error;
13014 			}
13015 		}
13016 	}
13017 
13018 	if (!mctl_present) {
13019 		UPDATE_IB_PKT_COUNT(ire);
13020 		ire->ire_last_used_time = lbolt;
13021 	}
13022 
13023 	/* packet part of fragmented IP packet? */
13024 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13025 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13026 		goto fragmented;
13027 	}
13028 
13029 	/* u1 = IP header length (20 bytes) */
13030 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13031 
13032 	/* does packet contain IP+TCP headers? */
13033 	len = mp->b_wptr - rptr;
13034 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13035 		IP_STAT(ip_tcppullup);
13036 		goto tcppullup;
13037 	}
13038 
13039 	/* TCP options present? */
13040 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13041 
13042 	/*
13043 	 * If options need to be pulled up, then goto tcpoptions.
13044 	 * otherwise we are still in the fast path
13045 	 */
13046 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13047 		IP_STAT(ip_tcpoptions);
13048 		goto tcpoptions;
13049 	}
13050 
13051 	/* multiple mblks of tcp data? */
13052 	if ((mp1 = mp->b_cont) != NULL) {
13053 		/* more then two? */
13054 		if (mp1->b_cont != NULL) {
13055 			IP_STAT(ip_multipkttcp);
13056 			goto multipkttcp;
13057 		}
13058 		len += mp1->b_wptr - mp1->b_rptr;
13059 	}
13060 
13061 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13062 
13063 	/* part of pseudo checksum */
13064 
13065 	/* TCP datagram length */
13066 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13067 
13068 #define	iphs    ((uint16_t *)ipha)
13069 
13070 #ifdef	_BIG_ENDIAN
13071 	u1 += IPPROTO_TCP;
13072 #else
13073 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13074 #endif
13075 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13076 
13077 	/*
13078 	 * Revert to software checksum calculation if the interface
13079 	 * isn't capable of checksum offload or if IPsec is present.
13080 	 */
13081 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13082 		hck_flags = DB_CKSUMFLAGS(mp);
13083 
13084 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13085 		IP_STAT(ip_in_sw_cksum);
13086 
13087 	IP_CKSUM_RECV(hck_flags, u1,
13088 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13089 	    (int32_t)((uchar_t *)up - rptr),
13090 	    mp, mp1, cksum_err);
13091 
13092 	if (cksum_err) {
13093 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13094 
13095 		if (hck_flags & HCK_FULLCKSUM)
13096 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
13097 		else if (hck_flags & HCK_PARTIALCKSUM)
13098 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
13099 		else
13100 			IP_STAT(ip_tcp_in_sw_cksum_err);
13101 
13102 		goto error;
13103 	}
13104 
13105 try_again:
13106 
13107 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
13108 	    NULL) {
13109 		/* Send the TH_RST */
13110 		goto no_conn;
13111 	}
13112 
13113 	/*
13114 	 * TCP FAST PATH for AF_INET socket.
13115 	 *
13116 	 * TCP fast path to avoid extra work. An AF_INET socket type
13117 	 * does not have facility to receive extra information via
13118 	 * ip_process or ip_add_info. Also, when the connection was
13119 	 * established, we made a check if this connection is impacted
13120 	 * by any global IPSec policy or per connection policy (a
13121 	 * policy that comes in effect later will not apply to this
13122 	 * connection). Since all this can be determined at the
13123 	 * connection establishment time, a quick check of flags
13124 	 * can avoid extra work.
13125 	 */
13126 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13127 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
13128 		ASSERT(first_mp == mp);
13129 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13130 		SET_SQUEUE(mp, tcp_rput_data, connp);
13131 		return (mp);
13132 	}
13133 
13134 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13135 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13136 		if (IPCL_IS_TCP(connp)) {
13137 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13138 			DB_CKSUMSTART(mp) =
13139 			    (intptr_t)ip_squeue_get(ill_ring);
13140 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13141 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
13142 				BUMP_MIB(ill->ill_ip_mib,
13143 				    ipIfStatsHCInDelivers);
13144 				SET_SQUEUE(mp, connp->conn_recv, connp);
13145 				return (mp);
13146 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13147 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
13148 				BUMP_MIB(ill->ill_ip_mib,
13149 				    ipIfStatsHCInDelivers);
13150 				ip_squeue_enter_unbound++;
13151 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13152 				    connp);
13153 				return (mp);
13154 			}
13155 			syn_present = B_TRUE;
13156 		}
13157 
13158 	}
13159 
13160 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13161 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13162 
13163 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13164 		/* No need to send this packet to TCP */
13165 		if ((flags & TH_RST) || (flags & TH_URG)) {
13166 			CONN_DEC_REF(connp);
13167 			freemsg(first_mp);
13168 			return (NULL);
13169 		}
13170 		if (flags & TH_ACK) {
13171 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
13172 			CONN_DEC_REF(connp);
13173 			return (NULL);
13174 		}
13175 
13176 		CONN_DEC_REF(connp);
13177 		freemsg(first_mp);
13178 		return (NULL);
13179 	}
13180 
13181 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
13182 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13183 		    ipha, NULL, mctl_present);
13184 		if (first_mp == NULL) {
13185 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13186 			CONN_DEC_REF(connp);
13187 			return (NULL);
13188 		}
13189 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13190 			ASSERT(syn_present);
13191 			if (mctl_present) {
13192 				ASSERT(first_mp != mp);
13193 				first_mp->b_datap->db_struioflag |=
13194 				    STRUIO_POLICY;
13195 			} else {
13196 				ASSERT(first_mp == mp);
13197 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13198 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13199 			}
13200 		} else {
13201 			/*
13202 			 * Discard first_mp early since we're dealing with a
13203 			 * fully-connected conn_t and tcp doesn't do policy in
13204 			 * this case.
13205 			 */
13206 			if (mctl_present) {
13207 				freeb(first_mp);
13208 				mctl_present = B_FALSE;
13209 			}
13210 			first_mp = mp;
13211 		}
13212 	}
13213 
13214 	/* Initiate IPPF processing for fastpath */
13215 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13216 		uint32_t	ill_index;
13217 
13218 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13219 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13220 		if (mp == NULL) {
13221 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13222 			    "deferred/dropped during IPPF processing\n"));
13223 			CONN_DEC_REF(connp);
13224 			if (mctl_present)
13225 				freeb(first_mp);
13226 			return (NULL);
13227 		} else if (mctl_present) {
13228 			/*
13229 			 * ip_process might return a new mp.
13230 			 */
13231 			ASSERT(first_mp != mp);
13232 			first_mp->b_cont = mp;
13233 		} else {
13234 			first_mp = mp;
13235 		}
13236 
13237 	}
13238 
13239 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13240 		/*
13241 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13242 		 * make sure IPF_RECVIF is passed to ip_add_info.
13243 		 */
13244 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13245 		    IPCL_ZONEID(connp));
13246 		if (mp == NULL) {
13247 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13248 			CONN_DEC_REF(connp);
13249 			if (mctl_present)
13250 				freeb(first_mp);
13251 			return (NULL);
13252 		} else if (mctl_present) {
13253 			/*
13254 			 * ip_add_info might return a new mp.
13255 			 */
13256 			ASSERT(first_mp != mp);
13257 			first_mp->b_cont = mp;
13258 		} else {
13259 			first_mp = mp;
13260 		}
13261 	}
13262 
13263 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13264 	if (IPCL_IS_TCP(connp)) {
13265 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13266 		return (first_mp);
13267 	} else {
13268 		putnext(connp->conn_rq, first_mp);
13269 		CONN_DEC_REF(connp);
13270 		return (NULL);
13271 	}
13272 
13273 no_conn:
13274 	/* Initiate IPPf processing, if needed. */
13275 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13276 		uint32_t ill_index;
13277 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13278 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13279 		if (first_mp == NULL) {
13280 			return (NULL);
13281 		}
13282 	}
13283 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13284 
13285 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid);
13286 	return (NULL);
13287 ipoptions:
13288 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire)) {
13289 		goto slow_done;
13290 	}
13291 
13292 	UPDATE_IB_PKT_COUNT(ire);
13293 	ire->ire_last_used_time = lbolt;
13294 
13295 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13296 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13297 fragmented:
13298 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13299 			if (mctl_present)
13300 				freeb(first_mp);
13301 			goto slow_done;
13302 		}
13303 		/*
13304 		 * Make sure that first_mp points back to mp as
13305 		 * the mp we came in with could have changed in
13306 		 * ip_rput_fragment().
13307 		 */
13308 		ASSERT(!mctl_present);
13309 		ipha = (ipha_t *)mp->b_rptr;
13310 		first_mp = mp;
13311 	}
13312 
13313 	/* Now we have a complete datagram, destined for this machine. */
13314 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13315 
13316 	len = mp->b_wptr - mp->b_rptr;
13317 	/* Pull up a minimal TCP header, if necessary. */
13318 	if (len < (u1 + 20)) {
13319 tcppullup:
13320 		if (!pullupmsg(mp, u1 + 20)) {
13321 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13322 			goto error;
13323 		}
13324 		ipha = (ipha_t *)mp->b_rptr;
13325 		len = mp->b_wptr - mp->b_rptr;
13326 	}
13327 
13328 	/*
13329 	 * Extract the offset field from the TCP header.  As usual, we
13330 	 * try to help the compiler more than the reader.
13331 	 */
13332 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13333 	if (offset != 5) {
13334 tcpoptions:
13335 		if (offset < 5) {
13336 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13337 			goto error;
13338 		}
13339 		/*
13340 		 * There must be TCP options.
13341 		 * Make sure we can grab them.
13342 		 */
13343 		offset <<= 2;
13344 		offset += u1;
13345 		if (len < offset) {
13346 			if (!pullupmsg(mp, offset)) {
13347 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13348 				goto error;
13349 			}
13350 			ipha = (ipha_t *)mp->b_rptr;
13351 			len = mp->b_wptr - rptr;
13352 		}
13353 	}
13354 
13355 	/* Get the total packet length in len, including headers. */
13356 	if (mp->b_cont) {
13357 multipkttcp:
13358 		len = msgdsize(mp);
13359 	}
13360 
13361 	/*
13362 	 * Check the TCP checksum by pulling together the pseudo-
13363 	 * header checksum, and passing it to ip_csum to be added in
13364 	 * with the TCP datagram.
13365 	 *
13366 	 * Since we are not using the hwcksum if available we must
13367 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13368 	 * If either of these fails along the way the mblk is freed.
13369 	 * If this logic ever changes and mblk is reused to say send
13370 	 * ICMP's back, then this flag may need to be cleared in
13371 	 * other places as well.
13372 	 */
13373 	DB_CKSUMFLAGS(mp) = 0;
13374 
13375 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13376 
13377 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13378 #ifdef	_BIG_ENDIAN
13379 	u1 += IPPROTO_TCP;
13380 #else
13381 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13382 #endif
13383 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13384 	/*
13385 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13386 	 */
13387 	IP_STAT(ip_in_sw_cksum);
13388 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13389 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13390 		goto error;
13391 	}
13392 
13393 	IP_STAT(ip_tcp_slow_path);
13394 	goto try_again;
13395 #undef  iphs
13396 #undef  rptr
13397 
13398 error:
13399 	freemsg(first_mp);
13400 slow_done:
13401 	return (NULL);
13402 }
13403 
13404 /* ARGSUSED */
13405 static void
13406 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13407     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13408 {
13409 	conn_t		*connp;
13410 	uint32_t	sum;
13411 	uint32_t	u1;
13412 	ssize_t		len;
13413 	sctp_hdr_t	*sctph;
13414 	zoneid_t	zoneid = ire->ire_zoneid;
13415 	uint32_t	pktsum;
13416 	uint32_t	calcsum;
13417 	uint32_t	ports;
13418 	uint_t		ipif_seqid;
13419 	in6_addr_t	map_src, map_dst;
13420 	ill_t		*ill = (ill_t *)q->q_ptr;
13421 
13422 #define	rptr	((uchar_t *)ipha)
13423 
13424 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13425 	ASSERT(ill != NULL);
13426 
13427 	/* u1 is # words of IP options */
13428 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13429 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13430 
13431 	/* IP options present */
13432 	if (u1 > 0) {
13433 		goto ipoptions;
13434 	} else {
13435 		/* Check the IP header checksum.  */
13436 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13437 #define	uph	((uint16_t *)ipha)
13438 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13439 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13440 #undef	uph
13441 			/* finish doing IP checksum */
13442 			sum = (sum & 0xFFFF) + (sum >> 16);
13443 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13444 			/*
13445 			 * Don't verify header checksum if this packet
13446 			 * is coming back from AH/ESP as we already did it.
13447 			 */
13448 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13449 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13450 				goto error;
13451 			}
13452 		}
13453 		/*
13454 		 * Since there is no SCTP h/w cksum support yet, just
13455 		 * clear the flag.
13456 		 */
13457 		DB_CKSUMFLAGS(mp) = 0;
13458 	}
13459 
13460 	/*
13461 	 * Don't verify header checksum if this packet is coming
13462 	 * back from AH/ESP as we already did it.
13463 	 */
13464 	if (!mctl_present) {
13465 		UPDATE_IB_PKT_COUNT(ire);
13466 		ire->ire_last_used_time = lbolt;
13467 	}
13468 
13469 	/* packet part of fragmented IP packet? */
13470 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13471 	if (u1 & (IPH_MF | IPH_OFFSET))
13472 		goto fragmented;
13473 
13474 	/* u1 = IP header length (20 bytes) */
13475 	u1 = IP_SIMPLE_HDR_LENGTH;
13476 
13477 find_sctp_client:
13478 	/* Pullup if we don't have the sctp common header. */
13479 	len = MBLKL(mp);
13480 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13481 		if (mp->b_cont == NULL ||
13482 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13483 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13484 			goto error;
13485 		}
13486 		ipha = (ipha_t *)mp->b_rptr;
13487 		len = MBLKL(mp);
13488 	}
13489 
13490 	sctph = (sctp_hdr_t *)(rptr + u1);
13491 #ifdef	DEBUG
13492 	if (!skip_sctp_cksum) {
13493 #endif
13494 		pktsum = sctph->sh_chksum;
13495 		sctph->sh_chksum = 0;
13496 		calcsum = sctp_cksum(mp, u1);
13497 		if (calcsum != pktsum) {
13498 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13499 			goto error;
13500 		}
13501 		sctph->sh_chksum = pktsum;
13502 #ifdef	DEBUG	/* skip_sctp_cksum */
13503 	}
13504 #endif
13505 	/* get the ports */
13506 	ports = *(uint32_t *)&sctph->sh_sport;
13507 
13508 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13509 	IRE_REFRELE(ire);
13510 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13511 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13512 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13513 	    mp)) == NULL) {
13514 		/* Check for raw socket or OOTB handling */
13515 		goto no_conn;
13516 	}
13517 
13518 	/* Found a client; up it goes */
13519 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13520 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13521 	return;
13522 
13523 no_conn:
13524 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13525 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13526 	return;
13527 
13528 ipoptions:
13529 	DB_CKSUMFLAGS(mp) = 0;
13530 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire))
13531 		goto slow_done;
13532 
13533 	UPDATE_IB_PKT_COUNT(ire);
13534 	ire->ire_last_used_time = lbolt;
13535 
13536 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13537 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13538 fragmented:
13539 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13540 			goto slow_done;
13541 		/*
13542 		 * Make sure that first_mp points back to mp as
13543 		 * the mp we came in with could have changed in
13544 		 * ip_rput_fragment().
13545 		 */
13546 		ASSERT(!mctl_present);
13547 		ipha = (ipha_t *)mp->b_rptr;
13548 		first_mp = mp;
13549 	}
13550 
13551 	/* Now we have a complete datagram, destined for this machine. */
13552 	u1 = IPH_HDR_LENGTH(ipha);
13553 	goto find_sctp_client;
13554 #undef  iphs
13555 #undef  rptr
13556 
13557 error:
13558 	freemsg(first_mp);
13559 slow_done:
13560 	IRE_REFRELE(ire);
13561 }
13562 
13563 #define	VER_BITS	0xF0
13564 #define	VERSION_6	0x60
13565 
13566 static boolean_t
13567 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13568     ipaddr_t *dstp)
13569 {
13570 	uint_t	opt_len;
13571 	ipha_t *ipha;
13572 	ssize_t len;
13573 	uint_t	pkt_len;
13574 
13575 	ASSERT(ill != NULL);
13576 	IP_STAT(ip_ipoptions);
13577 	ipha = *iphapp;
13578 
13579 #define	rptr    ((uchar_t *)ipha)
13580 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13581 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13582 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13583 		freemsg(mp);
13584 		return (B_FALSE);
13585 	}
13586 
13587 	/* multiple mblk or too short */
13588 	pkt_len = ntohs(ipha->ipha_length);
13589 
13590 	/* Get the number of words of IP options in the IP header. */
13591 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13592 	if (opt_len) {
13593 		/* IP Options present!  Validate and process. */
13594 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13595 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13596 			goto done;
13597 		}
13598 		/*
13599 		 * Recompute complete header length and make sure we
13600 		 * have access to all of it.
13601 		 */
13602 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13603 		if (len > (mp->b_wptr - rptr)) {
13604 			if (len > pkt_len) {
13605 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13606 				goto done;
13607 			}
13608 			if (!pullupmsg(mp, len)) {
13609 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13610 				goto done;
13611 			}
13612 			ipha = (ipha_t *)mp->b_rptr;
13613 		}
13614 		/*
13615 		 * Go off to ip_rput_options which returns the next hop
13616 		 * destination address, which may have been affected
13617 		 * by source routing.
13618 		 */
13619 		IP_STAT(ip_opt);
13620 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13621 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13622 			return (B_FALSE);
13623 		}
13624 	}
13625 	*iphapp = ipha;
13626 	return (B_TRUE);
13627 done:
13628 	/* clear b_prev - used by ip_mroute_decap */
13629 	mp->b_prev = NULL;
13630 	freemsg(mp);
13631 	return (B_FALSE);
13632 #undef  rptr
13633 }
13634 
13635 /*
13636  * Deal with the fact that there is no ire for the destination.
13637  * The incoming ill (in_ill) is passed in to ip_newroute only
13638  * in the case of packets coming from mobile ip forward tunnel.
13639  * It must be null otherwise.
13640  */
13641 static ire_t *
13642 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13643     ipaddr_t dst)
13644 {
13645 	ipha_t	*ipha;
13646 	ill_t	*ill;
13647 	ire_t	*ire;
13648 	boolean_t	check_multirt = B_FALSE;
13649 
13650 	ipha = (ipha_t *)mp->b_rptr;
13651 	ill = (ill_t *)q->q_ptr;
13652 
13653 	ASSERT(ill != NULL);
13654 	/*
13655 	 * No IRE for this destination, so it can't be for us.
13656 	 * Unless we are forwarding, drop the packet.
13657 	 * We have to let source routed packets through
13658 	 * since we don't yet know if they are 'ping -l'
13659 	 * packets i.e. if they will go out over the
13660 	 * same interface as they came in on.
13661 	 */
13662 	if (ll_multicast) {
13663 		freemsg(mp);
13664 		return (NULL);
13665 	}
13666 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13667 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13668 		freemsg(mp);
13669 		return (NULL);
13670 	}
13671 
13672 	/*
13673 	 * Mark this packet as having originated externally.
13674 	 *
13675 	 * For non-forwarding code path, ire_send later double
13676 	 * checks this interface to see if it is still exists
13677 	 * post-ARP resolution.
13678 	 *
13679 	 * Also, IPQOS uses this to differentiate between
13680 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13681 	 * QOS packet processing in ip_wput_attach_llhdr().
13682 	 * The QoS module can mark the b_band for a fastpath message
13683 	 * or the dl_priority field in a unitdata_req header for
13684 	 * CoS marking. This info can only be found in
13685 	 * ip_wput_attach_llhdr().
13686 	 */
13687 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13688 	/*
13689 	 * Clear the indication that this may have a hardware checksum
13690 	 * as we are not using it
13691 	 */
13692 	DB_CKSUMFLAGS(mp) = 0;
13693 
13694 	if (in_ill != NULL) {
13695 		/*
13696 		 * Now hand the packet to ip_newroute.
13697 		 */
13698 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13699 		return (NULL);
13700 	}
13701 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13702 	    MBLK_GETLABEL(mp));
13703 
13704 	if (ire == NULL && check_multirt) {
13705 		/* Let ip_newroute handle CGTP  */
13706 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13707 		return (NULL);
13708 	}
13709 
13710 	if (ire != NULL)
13711 		return (ire);
13712 
13713 	mp->b_prev = mp->b_next = 0;
13714 	/* send icmp unreachable */
13715 	q = WR(q);
13716 	/* Sent by forwarding path, and router is global zone */
13717 	if (ip_source_routed(ipha)) {
13718 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13719 		    GLOBAL_ZONEID);
13720 	} else {
13721 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13722 	}
13723 
13724 	return (NULL);
13725 
13726 }
13727 
13728 /*
13729  * check ip header length and align it.
13730  */
13731 static boolean_t
13732 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13733 {
13734 	ssize_t len;
13735 	ill_t *ill;
13736 	ipha_t	*ipha;
13737 
13738 	len = MBLKL(mp);
13739 
13740 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13741 		ill = (ill_t *)q->q_ptr;
13742 
13743 		if (!OK_32PTR(mp->b_rptr))
13744 			IP_STAT(ip_notaligned1);
13745 		else
13746 			IP_STAT(ip_notaligned2);
13747 		/* Guard against bogus device drivers */
13748 		if (len < 0) {
13749 			/* clear b_prev - used by ip_mroute_decap */
13750 			mp->b_prev = NULL;
13751 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13752 			freemsg(mp);
13753 			return (B_FALSE);
13754 		}
13755 
13756 		if (ip_rput_pullups++ == 0) {
13757 			ipha = (ipha_t *)mp->b_rptr;
13758 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13759 			    "ip_check_and_align_header: %s forced us to "
13760 			    " pullup pkt, hdr len %ld, hdr addr %p",
13761 			    ill->ill_name, len, ipha);
13762 		}
13763 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13764 			/* clear b_prev - used by ip_mroute_decap */
13765 			mp->b_prev = NULL;
13766 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13767 			freemsg(mp);
13768 			return (B_FALSE);
13769 		}
13770 	}
13771 	return (B_TRUE);
13772 }
13773 
13774 static boolean_t
13775 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13776 {
13777 	ill_group_t	*ill_group;
13778 	ill_group_t	*ire_group;
13779 	queue_t 	*q;
13780 	ill_t		*ire_ill;
13781 	uint_t		ill_ifindex;
13782 
13783 	q = *qp;
13784 	/*
13785 	 * We need to check to make sure the packet came in
13786 	 * on the queue associated with the destination IRE.
13787 	 * Note that for multicast packets and broadcast packets sent to
13788 	 * a broadcast address which is shared between multiple interfaces
13789 	 * we should not do this since we just got a random broadcast ire.
13790 	 */
13791 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13792 		boolean_t check_multi = B_TRUE;
13793 
13794 		/*
13795 		 * This packet came in on an interface other than the
13796 		 * one associated with the destination address.
13797 		 * "Gateway" it to the appropriate interface here.
13798 		 * As long as the ills belong to the same group,
13799 		 * we don't consider them to arriving on the wrong
13800 		 * interface. Thus, when the switch is doing inbound
13801 		 * load spreading, we won't drop packets when we
13802 		 * are doing strict multihoming checks. Note, the
13803 		 * same holds true for 'usesrc groups' where the
13804 		 * destination address may belong to another interface
13805 		 * to allow multipathing to happen
13806 		 */
13807 		ill_group = ill->ill_group;
13808 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13809 		ill_ifindex = ill->ill_usesrc_ifindex;
13810 		ire_group = ire_ill->ill_group;
13811 
13812 		/*
13813 		 * If it's part of the same IPMP group, or if it's a legal
13814 		 * address on the 'usesrc' interface, then bypass strict
13815 		 * checks.
13816 		 */
13817 		if (ill_group != NULL && ill_group == ire_group) {
13818 			check_multi = B_FALSE;
13819 		} else if (ill_ifindex != 0 &&
13820 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13821 			check_multi = B_FALSE;
13822 		}
13823 
13824 		if (check_multi &&
13825 		    ip_strict_dst_multihoming &&
13826 		    ((ill->ill_flags &
13827 		    ire->ire_ipif->ipif_ill->ill_flags &
13828 		    ILLF_ROUTER) == 0)) {
13829 			/* Drop packet */
13830 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13831 			freemsg(mp);
13832 			return (B_TRUE);
13833 		}
13834 
13835 		/*
13836 		 * Change the queue (for non-virtual destination network
13837 		 * interfaces) and ip_rput_local will be called with the right
13838 		 * queue
13839 		 */
13840 		q = ire->ire_rfq;
13841 	}
13842 	/* Must be broadcast.  We'll take it. */
13843 	*qp = q;
13844 	return (B_FALSE);
13845 }
13846 
13847 ire_t *
13848 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13849 {
13850 	ipha_t	*ipha;
13851 	ipaddr_t ip_dst, ip_src;
13852 	ire_t	*src_ire = NULL;
13853 	ill_t	*stq_ill;
13854 	uint_t	hlen;
13855 	uint_t	pkt_len;
13856 	uint32_t sum;
13857 	queue_t	*dev_q;
13858 	boolean_t check_multirt = B_FALSE;
13859 
13860 
13861 	ipha = (ipha_t *)mp->b_rptr;
13862 
13863 	/*
13864 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13865 	 * The loopback address check for both src and dst has already
13866 	 * been checked in ip_input
13867 	 */
13868 	ip_dst = ntohl(dst);
13869 	ip_src = ntohl(ipha->ipha_src);
13870 
13871 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13872 	    IN_CLASSD(ip_src)) {
13873 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13874 		goto drop;
13875 	}
13876 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13877 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13878 
13879 	if (src_ire != NULL) {
13880 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13881 		goto drop;
13882 	}
13883 
13884 
13885 	/* No ire cache of nexthop. So first create one  */
13886 	if (ire == NULL) {
13887 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13888 		/*
13889 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13890 		 * is not set. So upon return from ire_forward
13891 		 * check_multirt should remain as false.
13892 		 */
13893 		ASSERT(!check_multirt);
13894 		if (ire == NULL) {
13895 			/* An attempt was made to forward the packet */
13896 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13897 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13898 			mp->b_prev = mp->b_next = 0;
13899 			/* send icmp unreachable */
13900 			/* Sent by forwarding path, and router is global zone */
13901 			if (ip_source_routed(ipha)) {
13902 				icmp_unreachable(ill->ill_wq, mp,
13903 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13904 			} else {
13905 				icmp_unreachable(ill->ill_wq, mp,
13906 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13907 			}
13908 			return (ire);
13909 		}
13910 	}
13911 
13912 	/*
13913 	 * Forwarding fastpath exception case:
13914 	 * If either of the follwoing case is true, we take
13915 	 * the slowpath
13916 	 *	o forwarding is not enabled
13917 	 *	o incoming and outgoing interface are the same, or the same
13918 	 *	  IPMP group
13919 	 *	o corresponding ire is in incomplete state
13920 	 *	o packet needs fragmentation
13921 	 *
13922 	 * The codeflow from here on is thus:
13923 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13924 	 */
13925 	pkt_len = ntohs(ipha->ipha_length);
13926 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13927 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13928 	    !(ill->ill_flags & ILLF_ROUTER) ||
13929 	    (ill == stq_ill) ||
13930 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13931 	    (ire->ire_nce == NULL) ||
13932 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13933 	    (pkt_len > ire->ire_max_frag) ||
13934 	    ipha->ipha_ttl <= 1) {
13935 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13936 		    ipha, ill, B_FALSE);
13937 		return (ire);
13938 	}
13939 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13940 
13941 	DTRACE_PROBE4(ip4__forwarding__start,
13942 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13943 
13944 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
13945 	    ill, stq_ill, ipha, mp, mp);
13946 
13947 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13948 
13949 	if (mp == NULL)
13950 		goto drop;
13951 
13952 	mp->b_datap->db_struioun.cksum.flags = 0;
13953 	/* Adjust the checksum to reflect the ttl decrement. */
13954 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13955 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13956 	ipha->ipha_ttl--;
13957 
13958 	dev_q = ire->ire_stq->q_next;
13959 	if ((dev_q->q_next != NULL ||
13960 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13961 		goto indiscard;
13962 	}
13963 
13964 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13965 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13966 
13967 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13968 		mblk_t *mpip = mp;
13969 
13970 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13971 		if (mp != NULL) {
13972 			DTRACE_PROBE4(ip4__physical__out__start,
13973 			    ill_t *, NULL, ill_t *, stq_ill,
13974 			    ipha_t *, ipha, mblk_t *, mp);
13975 			FW_HOOKS(ip4_physical_out_event,
13976 			    ipv4firewall_physical_out,
13977 			    NULL, stq_ill, ipha, mp, mpip);
13978 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13979 			    mp);
13980 			if (mp == NULL)
13981 				goto drop;
13982 
13983 			UPDATE_IB_PKT_COUNT(ire);
13984 			ire->ire_last_used_time = lbolt;
13985 			BUMP_MIB(stq_ill->ill_ip_mib,
13986 			    ipIfStatsHCOutForwDatagrams);
13987 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13988 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
13989 			    pkt_len);
13990 			putnext(ire->ire_stq, mp);
13991 			return (ire);
13992 		}
13993 	}
13994 
13995 indiscard:
13996 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13997 drop:
13998 	if (mp != NULL)
13999 		freemsg(mp);
14000 	if (src_ire != NULL)
14001 		ire_refrele(src_ire);
14002 	return (ire);
14003 
14004 }
14005 
14006 /*
14007  * This function is called in the forwarding slowpath, when
14008  * either the ire lacks the link-layer address, or the packet needs
14009  * further processing(eg. fragmentation), before transmission.
14010  */
14011 
14012 static void
14013 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14014     ill_t *ill, boolean_t ll_multicast)
14015 {
14016 	ill_group_t	*ill_group;
14017 	ill_group_t	*ire_group;
14018 	queue_t		*dev_q;
14019 	ire_t		*src_ire;
14020 
14021 	ASSERT(ire->ire_stq != NULL);
14022 
14023 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14024 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14025 
14026 	if (ll_multicast != 0) {
14027 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14028 		goto drop_pkt;
14029 	}
14030 
14031 	/*
14032 	 * check if ipha_src is a broadcast address. Note that this
14033 	 * check is redundant when we get here from ip_fast_forward()
14034 	 * which has already done this check. However, since we can
14035 	 * also get here from ip_rput_process_broadcast() or, for
14036 	 * for the slow path through ip_fast_forward(), we perform
14037 	 * the check again for code-reusability
14038 	 */
14039 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14040 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
14041 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14042 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14043 		if (src_ire != NULL)
14044 			ire_refrele(src_ire);
14045 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14046 		ip2dbg(("ip_rput_process_forward: Received packet with"
14047 		    " bad src/dst address on %s\n", ill->ill_name));
14048 		goto drop_pkt;
14049 	}
14050 
14051 	ill_group = ill->ill_group;
14052 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14053 	/*
14054 	 * Check if we want to forward this one at this time.
14055 	 * We allow source routed packets on a host provided that
14056 	 * they go out the same interface or same interface group
14057 	 * as they came in on.
14058 	 *
14059 	 * XXX To be quicker, we may wish to not chase pointers to
14060 	 * get the ILLF_ROUTER flag and instead store the
14061 	 * forwarding policy in the ire.  An unfortunate
14062 	 * side-effect of that would be requiring an ire flush
14063 	 * whenever the ILLF_ROUTER flag changes.
14064 	 */
14065 	if (((ill->ill_flags &
14066 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14067 	    ILLF_ROUTER) == 0) &&
14068 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
14069 	    (ill_group != NULL && ill_group == ire_group)))) {
14070 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14071 		if (ip_source_routed(ipha)) {
14072 			q = WR(q);
14073 			/*
14074 			 * Clear the indication that this may have
14075 			 * hardware checksum as we are not using it.
14076 			 */
14077 			DB_CKSUMFLAGS(mp) = 0;
14078 			/* Sent by forwarding path, and router is global zone */
14079 			icmp_unreachable(q, mp,
14080 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
14081 			return;
14082 		}
14083 		goto drop_pkt;
14084 	}
14085 
14086 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14087 
14088 	/* Packet is being forwarded. Turning off hwcksum flag. */
14089 	DB_CKSUMFLAGS(mp) = 0;
14090 	if (ip_g_send_redirects) {
14091 		/*
14092 		 * Check whether the incoming interface and outgoing
14093 		 * interface is part of the same group. If so,
14094 		 * send redirects.
14095 		 *
14096 		 * Check the source address to see if it originated
14097 		 * on the same logical subnet it is going back out on.
14098 		 * If so, we should be able to send it a redirect.
14099 		 * Avoid sending a redirect if the destination
14100 		 * is directly connected (i.e., ipha_dst is the same
14101 		 * as ire_gateway_addr or the ire_addr of the
14102 		 * nexthop IRE_CACHE ), or if the packet was source
14103 		 * routed out this interface.
14104 		 */
14105 		ipaddr_t src, nhop;
14106 		mblk_t	*mp1;
14107 		ire_t	*nhop_ire = NULL;
14108 
14109 		/*
14110 		 * Check whether ire_rfq and q are from the same ill
14111 		 * or if they are not same, they at least belong
14112 		 * to the same group. If so, send redirects.
14113 		 */
14114 		if ((ire->ire_rfq == q ||
14115 		    (ill_group != NULL && ill_group == ire_group)) &&
14116 		    !ip_source_routed(ipha)) {
14117 
14118 			nhop = (ire->ire_gateway_addr != 0 ?
14119 			    ire->ire_gateway_addr : ire->ire_addr);
14120 
14121 			if (ipha->ipha_dst == nhop) {
14122 				/*
14123 				 * We avoid sending a redirect if the
14124 				 * destination is directly connected
14125 				 * because it is possible that multiple
14126 				 * IP subnets may have been configured on
14127 				 * the link, and the source may not
14128 				 * be on the same subnet as ip destination,
14129 				 * even though they are on the same
14130 				 * physical link.
14131 				 */
14132 				goto sendit;
14133 			}
14134 
14135 			src = ipha->ipha_src;
14136 
14137 			/*
14138 			 * We look up the interface ire for the nexthop,
14139 			 * to see if ipha_src is in the same subnet
14140 			 * as the nexthop.
14141 			 *
14142 			 * Note that, if, in the future, IRE_CACHE entries
14143 			 * are obsoleted,  this lookup will not be needed,
14144 			 * as the ire passed to this function will be the
14145 			 * same as the nhop_ire computed below.
14146 			 */
14147 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14148 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14149 			    0, NULL, MATCH_IRE_TYPE);
14150 
14151 			if (nhop_ire != NULL) {
14152 				if ((src & nhop_ire->ire_mask) ==
14153 				    (nhop & nhop_ire->ire_mask)) {
14154 					/*
14155 					 * The source is directly connected.
14156 					 * Just copy the ip header (which is
14157 					 * in the first mblk)
14158 					 */
14159 					mp1 = copyb(mp);
14160 					if (mp1 != NULL) {
14161 						icmp_send_redirect(WR(q), mp1,
14162 						    nhop);
14163 					}
14164 				}
14165 				ire_refrele(nhop_ire);
14166 			}
14167 		}
14168 	}
14169 sendit:
14170 	dev_q = ire->ire_stq->q_next;
14171 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14172 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14173 		freemsg(mp);
14174 		return;
14175 	}
14176 
14177 	ip_rput_forward(ire, ipha, mp, ill);
14178 	return;
14179 
14180 drop_pkt:
14181 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14182 	freemsg(mp);
14183 }
14184 
14185 ire_t *
14186 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14187     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14188 {
14189 	queue_t		*q;
14190 	uint16_t	hcksumflags;
14191 
14192 	q = *qp;
14193 
14194 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14195 
14196 	/*
14197 	 * Clear the indication that this may have hardware
14198 	 * checksum as we are not using it for forwarding.
14199 	 */
14200 	hcksumflags = DB_CKSUMFLAGS(mp);
14201 	DB_CKSUMFLAGS(mp) = 0;
14202 
14203 	/*
14204 	 * Directed broadcast forwarding: if the packet came in over a
14205 	 * different interface then it is routed out over we can forward it.
14206 	 */
14207 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14208 		ire_refrele(ire);
14209 		freemsg(mp);
14210 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14211 		return (NULL);
14212 	}
14213 	/*
14214 	 * For multicast we have set dst to be INADDR_BROADCAST
14215 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14216 	 * only for broadcast packets.
14217 	 */
14218 	if (!CLASSD(ipha->ipha_dst)) {
14219 		ire_t *new_ire;
14220 		ipif_t *ipif;
14221 		/*
14222 		 * For ill groups, as the switch duplicates broadcasts
14223 		 * across all the ports, we need to filter out and
14224 		 * send up only one copy. There is one copy for every
14225 		 * broadcast address on each ill. Thus, we look for a
14226 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14227 		 * later to see whether this ill is eligible to receive
14228 		 * them or not. ill_nominate_bcast_rcv() nominates only
14229 		 * one set of IREs for receiving.
14230 		 */
14231 
14232 		ipif = ipif_get_next_ipif(NULL, ill);
14233 		if (ipif == NULL) {
14234 			ire_refrele(ire);
14235 			freemsg(mp);
14236 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14237 			return (NULL);
14238 		}
14239 		new_ire = ire_ctable_lookup(dst, 0, 0,
14240 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
14241 		ipif_refrele(ipif);
14242 
14243 		if (new_ire != NULL) {
14244 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14245 				ire_refrele(ire);
14246 				ire_refrele(new_ire);
14247 				freemsg(mp);
14248 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14249 				return (NULL);
14250 			}
14251 			/*
14252 			 * In the special case of multirouted broadcast
14253 			 * packets, we unconditionally need to "gateway"
14254 			 * them to the appropriate interface here.
14255 			 * In the normal case, this cannot happen, because
14256 			 * there is no broadcast IRE tagged with the
14257 			 * RTF_MULTIRT flag.
14258 			 */
14259 			if (new_ire->ire_flags & RTF_MULTIRT) {
14260 				ire_refrele(new_ire);
14261 				if (ire->ire_rfq != NULL) {
14262 					q = ire->ire_rfq;
14263 					*qp = q;
14264 				}
14265 			} else {
14266 				ire_refrele(ire);
14267 				ire = new_ire;
14268 			}
14269 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14270 			if (!ip_g_forward_directed_bcast) {
14271 				/*
14272 				 * Free the message if
14273 				 * ip_g_forward_directed_bcast is turned
14274 				 * off for non-local broadcast.
14275 				 */
14276 				ire_refrele(ire);
14277 				freemsg(mp);
14278 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14279 				return (NULL);
14280 			}
14281 		} else {
14282 			/*
14283 			 * This CGTP packet successfully passed the
14284 			 * CGTP filter, but the related CGTP
14285 			 * broadcast IRE has not been found,
14286 			 * meaning that the redundant ipif is
14287 			 * probably down. However, if we discarded
14288 			 * this packet, its duplicate would be
14289 			 * filtered out by the CGTP filter so none
14290 			 * of them would get through. So we keep
14291 			 * going with this one.
14292 			 */
14293 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14294 			if (ire->ire_rfq != NULL) {
14295 				q = ire->ire_rfq;
14296 				*qp = q;
14297 			}
14298 		}
14299 	}
14300 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
14301 		/*
14302 		 * Verify that there are not more then one
14303 		 * IRE_BROADCAST with this broadcast address which
14304 		 * has ire_stq set.
14305 		 * TODO: simplify, loop over all IRE's
14306 		 */
14307 		ire_t	*ire1;
14308 		int	num_stq = 0;
14309 		mblk_t	*mp1;
14310 
14311 		/* Find the first one with ire_stq set */
14312 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14313 		for (ire1 = ire; ire1 &&
14314 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14315 		    ire1 = ire1->ire_next)
14316 			;
14317 		if (ire1) {
14318 			ire_refrele(ire);
14319 			ire = ire1;
14320 			IRE_REFHOLD(ire);
14321 		}
14322 
14323 		/* Check if there are additional ones with stq set */
14324 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14325 			if (ire->ire_addr != ire1->ire_addr)
14326 				break;
14327 			if (ire1->ire_stq) {
14328 				num_stq++;
14329 				break;
14330 			}
14331 		}
14332 		rw_exit(&ire->ire_bucket->irb_lock);
14333 		if (num_stq == 1 && ire->ire_stq != NULL) {
14334 			ip1dbg(("ip_rput_process_broadcast: directed "
14335 			    "broadcast to 0x%x\n",
14336 			    ntohl(ire->ire_addr)));
14337 			mp1 = copymsg(mp);
14338 			if (mp1) {
14339 				switch (ipha->ipha_protocol) {
14340 				case IPPROTO_UDP:
14341 					ip_udp_input(q, mp1, ipha, ire, ill);
14342 					break;
14343 				default:
14344 					ip_proto_input(q, mp1, ipha, ire, ill);
14345 					break;
14346 				}
14347 			}
14348 			/*
14349 			 * Adjust ttl to 2 (1+1 - the forward engine
14350 			 * will decrement it by one.
14351 			 */
14352 			if (ip_csum_hdr(ipha)) {
14353 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14354 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14355 				freemsg(mp);
14356 				ire_refrele(ire);
14357 				return (NULL);
14358 			}
14359 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
14360 			ipha->ipha_hdr_checksum = 0;
14361 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14362 			ip_rput_process_forward(q, mp, ire, ipha,
14363 			    ill, ll_multicast);
14364 			ire_refrele(ire);
14365 			return (NULL);
14366 		}
14367 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14368 		    ntohl(ire->ire_addr)));
14369 	}
14370 
14371 
14372 	/* Restore any hardware checksum flags */
14373 	DB_CKSUMFLAGS(mp) = hcksumflags;
14374 	return (ire);
14375 }
14376 
14377 /* ARGSUSED */
14378 static boolean_t
14379 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14380     int *ll_multicast, ipaddr_t *dstp)
14381 {
14382 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14383 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14384 	    ntohs(ipha->ipha_length));
14385 
14386 	/*
14387 	 * Forward packets only if we have joined the allmulti
14388 	 * group on this interface.
14389 	 */
14390 	if (ip_g_mrouter && ill->ill_join_allmulti) {
14391 		int retval;
14392 
14393 		/*
14394 		 * Clear the indication that this may have hardware
14395 		 * checksum as we are not using it.
14396 		 */
14397 		DB_CKSUMFLAGS(mp) = 0;
14398 		retval = ip_mforward(ill, ipha, mp);
14399 		/* ip_mforward updates mib variables if needed */
14400 		/* clear b_prev - used by ip_mroute_decap */
14401 		mp->b_prev = NULL;
14402 
14403 		switch (retval) {
14404 		case 0:
14405 			/*
14406 			 * pkt is okay and arrived on phyint.
14407 			 *
14408 			 * If we are running as a multicast router
14409 			 * we need to see all IGMP and/or PIM packets.
14410 			 */
14411 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14412 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14413 				goto done;
14414 			}
14415 			break;
14416 		case -1:
14417 			/* pkt is mal-formed, toss it */
14418 			goto drop_pkt;
14419 		case 1:
14420 			/* pkt is okay and arrived on a tunnel */
14421 			/*
14422 			 * If we are running a multicast router
14423 			 *  we need to see all igmp packets.
14424 			 */
14425 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14426 				*dstp = INADDR_BROADCAST;
14427 				*ll_multicast = 1;
14428 				return (B_FALSE);
14429 			}
14430 
14431 			goto drop_pkt;
14432 		}
14433 	}
14434 
14435 	ILM_WALKER_HOLD(ill);
14436 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14437 		/*
14438 		 * This might just be caused by the fact that
14439 		 * multiple IP Multicast addresses map to the same
14440 		 * link layer multicast - no need to increment counter!
14441 		 */
14442 		ILM_WALKER_RELE(ill);
14443 		freemsg(mp);
14444 		return (B_TRUE);
14445 	}
14446 	ILM_WALKER_RELE(ill);
14447 done:
14448 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14449 	/*
14450 	 * This assumes the we deliver to all streams for multicast
14451 	 * and broadcast packets.
14452 	 */
14453 	*dstp = INADDR_BROADCAST;
14454 	*ll_multicast = 1;
14455 	return (B_FALSE);
14456 drop_pkt:
14457 	ip2dbg(("ip_rput: drop pkt\n"));
14458 	freemsg(mp);
14459 	return (B_TRUE);
14460 }
14461 
14462 static boolean_t
14463 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14464     int *ll_multicast, mblk_t **mpp)
14465 {
14466 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14467 	boolean_t must_copy = B_FALSE;
14468 	struct iocblk   *iocp;
14469 	ipha_t		*ipha;
14470 
14471 #define	rptr    ((uchar_t *)ipha)
14472 
14473 	first_mp = *first_mpp;
14474 	mp = *mpp;
14475 
14476 	ASSERT(first_mp == mp);
14477 
14478 	/*
14479 	 * if db_ref > 1 then copymsg and free original. Packet may be
14480 	 * changed and do not want other entity who has a reference to this
14481 	 * message to trip over the changes. This is a blind change because
14482 	 * trying to catch all places that might change packet is too
14483 	 * difficult (since it may be a module above this one)
14484 	 *
14485 	 * This corresponds to the non-fast path case. We walk down the full
14486 	 * chain in this case, and check the db_ref count of all the dblks,
14487 	 * and do a copymsg if required. It is possible that the db_ref counts
14488 	 * of the data blocks in the mblk chain can be different.
14489 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14490 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14491 	 * 'snoop' is running.
14492 	 */
14493 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14494 		if (mp1->b_datap->db_ref > 1) {
14495 			must_copy = B_TRUE;
14496 			break;
14497 		}
14498 	}
14499 
14500 	if (must_copy) {
14501 		mp1 = copymsg(mp);
14502 		if (mp1 == NULL) {
14503 			for (mp1 = mp; mp1 != NULL;
14504 			    mp1 = mp1->b_cont) {
14505 				mp1->b_next = NULL;
14506 				mp1->b_prev = NULL;
14507 			}
14508 			freemsg(mp);
14509 			if (ill != NULL) {
14510 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14511 			} else {
14512 				BUMP_MIB(&ip_mib, ipIfStatsInDiscards);
14513 			}
14514 			return (B_TRUE);
14515 		}
14516 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14517 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14518 			/* Copy b_prev - used by ip_mroute_decap */
14519 			to_mp->b_prev = from_mp->b_prev;
14520 			from_mp->b_prev = NULL;
14521 		}
14522 		*first_mpp = first_mp = mp1;
14523 		freemsg(mp);
14524 		mp = mp1;
14525 		*mpp = mp1;
14526 	}
14527 
14528 	ipha = (ipha_t *)mp->b_rptr;
14529 
14530 	/*
14531 	 * previous code has a case for M_DATA.
14532 	 * We want to check how that happens.
14533 	 */
14534 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14535 	switch (first_mp->b_datap->db_type) {
14536 	case M_PROTO:
14537 	case M_PCPROTO:
14538 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14539 		    DL_UNITDATA_IND) {
14540 			/* Go handle anything other than data elsewhere. */
14541 			ip_rput_dlpi(q, mp);
14542 			return (B_TRUE);
14543 		}
14544 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14545 		/* Ditch the DLPI header. */
14546 		mp1 = mp->b_cont;
14547 		ASSERT(first_mp == mp);
14548 		*first_mpp = mp1;
14549 		freeb(mp);
14550 		*mpp = mp1;
14551 		return (B_FALSE);
14552 	case M_IOCACK:
14553 		ip1dbg(("got iocack "));
14554 		iocp = (struct iocblk *)mp->b_rptr;
14555 		switch (iocp->ioc_cmd) {
14556 		case DL_IOC_HDR_INFO:
14557 			ill = (ill_t *)q->q_ptr;
14558 			ill_fastpath_ack(ill, mp);
14559 			return (B_TRUE);
14560 		case SIOCSTUNPARAM:
14561 		case OSIOCSTUNPARAM:
14562 			/* Go through qwriter_ip */
14563 			break;
14564 		case SIOCGTUNPARAM:
14565 		case OSIOCGTUNPARAM:
14566 			ip_rput_other(NULL, q, mp, NULL);
14567 			return (B_TRUE);
14568 		default:
14569 			putnext(q, mp);
14570 			return (B_TRUE);
14571 		}
14572 		/* FALLTHRU */
14573 	case M_ERROR:
14574 	case M_HANGUP:
14575 		/*
14576 		 * Since this is on the ill stream we unconditionally
14577 		 * bump up the refcount
14578 		 */
14579 		ill_refhold(ill);
14580 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14581 		    B_FALSE);
14582 		return (B_TRUE);
14583 	case M_CTL:
14584 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14585 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14586 			IPHADA_M_CTL)) {
14587 			/*
14588 			 * It's an IPsec accelerated packet.
14589 			 * Make sure that the ill from which we received the
14590 			 * packet has enabled IPsec hardware acceleration.
14591 			 */
14592 			if (!(ill->ill_capabilities &
14593 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14594 				/* IPsec kstats: bean counter */
14595 				freemsg(mp);
14596 				return (B_TRUE);
14597 			}
14598 
14599 			/*
14600 			 * Make mp point to the mblk following the M_CTL,
14601 			 * then process according to type of mp.
14602 			 * After this processing, first_mp will point to
14603 			 * the data-attributes and mp to the pkt following
14604 			 * the M_CTL.
14605 			 */
14606 			mp = first_mp->b_cont;
14607 			if (mp == NULL) {
14608 				freemsg(first_mp);
14609 				return (B_TRUE);
14610 			}
14611 			/*
14612 			 * A Hardware Accelerated packet can only be M_DATA
14613 			 * ESP or AH packet.
14614 			 */
14615 			if (mp->b_datap->db_type != M_DATA) {
14616 				/* non-M_DATA IPsec accelerated packet */
14617 				IPSECHW_DEBUG(IPSECHW_PKT,
14618 				    ("non-M_DATA IPsec accelerated pkt\n"));
14619 				freemsg(first_mp);
14620 				return (B_TRUE);
14621 			}
14622 			ipha = (ipha_t *)mp->b_rptr;
14623 			if (ipha->ipha_protocol != IPPROTO_AH &&
14624 			    ipha->ipha_protocol != IPPROTO_ESP) {
14625 				IPSECHW_DEBUG(IPSECHW_PKT,
14626 				    ("non-M_DATA IPsec accelerated pkt\n"));
14627 				freemsg(first_mp);
14628 				return (B_TRUE);
14629 			}
14630 			*mpp = mp;
14631 			return (B_FALSE);
14632 		}
14633 		putnext(q, mp);
14634 		return (B_TRUE);
14635 	case M_FLUSH:
14636 		if (*mp->b_rptr & FLUSHW) {
14637 			*mp->b_rptr &= ~FLUSHR;
14638 			qreply(q, mp);
14639 			return (B_TRUE);
14640 		}
14641 		freemsg(mp);
14642 		return (B_TRUE);
14643 	case M_IOCNAK:
14644 		ip1dbg(("got iocnak "));
14645 		iocp = (struct iocblk *)mp->b_rptr;
14646 		switch (iocp->ioc_cmd) {
14647 		case DL_IOC_HDR_INFO:
14648 		case SIOCSTUNPARAM:
14649 		case OSIOCSTUNPARAM:
14650 			/*
14651 			 * Since this is on the ill stream we unconditionally
14652 			 * bump up the refcount
14653 			 */
14654 			ill_refhold(ill);
14655 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14656 			    CUR_OP, B_FALSE);
14657 			return (B_TRUE);
14658 		case SIOCGTUNPARAM:
14659 		case OSIOCGTUNPARAM:
14660 			ip_rput_other(NULL, q, mp, NULL);
14661 			return (B_TRUE);
14662 		default:
14663 			break;
14664 		}
14665 		/* FALLTHRU */
14666 	default:
14667 		putnext(q, mp);
14668 		return (B_TRUE);
14669 	}
14670 }
14671 
14672 /* Read side put procedure.  Packets coming from the wire arrive here. */
14673 void
14674 ip_rput(queue_t *q, mblk_t *mp)
14675 {
14676 	ill_t	*ill;
14677 	mblk_t	 *dmp = NULL;
14678 
14679 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14680 
14681 	ill = (ill_t *)q->q_ptr;
14682 
14683 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14684 		union DL_primitives *dl;
14685 
14686 		/*
14687 		 * Things are opening or closing. Only accept DLPI control
14688 		 * messages. In the open case, the ill->ill_ipif has not yet
14689 		 * been created. In the close case, things hanging off the
14690 		 * ill could have been freed already. In either case it
14691 		 * may not be safe to proceed further.
14692 		 */
14693 
14694 		dl = (union DL_primitives *)mp->b_rptr;
14695 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14696 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14697 			/*
14698 			 * Also SIOC[GS]TUN* ioctls can come here.
14699 			 */
14700 			inet_freemsg(mp);
14701 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14702 			    "ip_input_end: q %p (%S)", q, "uninit");
14703 			return;
14704 		}
14705 	}
14706 
14707 	/*
14708 	 * if db_ref > 1 then copymsg and free original. Packet may be
14709 	 * changed and we do not want the other entity who has a reference to
14710 	 * this message to trip over the changes. This is a blind change because
14711 	 * trying to catch all places that might change the packet is too
14712 	 * difficult.
14713 	 *
14714 	 * This corresponds to the fast path case, where we have a chain of
14715 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14716 	 * in the mblk chain. There doesn't seem to be a reason why a device
14717 	 * driver would send up data with varying db_ref counts in the mblk
14718 	 * chain. In any case the Fast path is a private interface, and our
14719 	 * drivers don't do such a thing. Given the above assumption, there is
14720 	 * no need to walk down the entire mblk chain (which could have a
14721 	 * potential performance problem)
14722 	 */
14723 	if (mp->b_datap->db_ref > 1) {
14724 		mblk_t  *mp1;
14725 		boolean_t adjusted = B_FALSE;
14726 		IP_STAT(ip_db_ref);
14727 
14728 		/*
14729 		 * The IP_RECVSLLA option depends on having the link layer
14730 		 * header. First check that:
14731 		 * a> the underlying device is of type ether, since this
14732 		 * option is currently supported only over ethernet.
14733 		 * b> there is enough room to copy over the link layer header.
14734 		 *
14735 		 * Once the checks are done, adjust rptr so that the link layer
14736 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14737 		 * be returned by some non-ethernet drivers but in this case the
14738 		 * second check will fail.
14739 		 */
14740 		if (ill->ill_type == IFT_ETHER &&
14741 		    (mp->b_rptr - mp->b_datap->db_base) >=
14742 		    sizeof (struct ether_header)) {
14743 			mp->b_rptr -= sizeof (struct ether_header);
14744 			adjusted = B_TRUE;
14745 		}
14746 		mp1 = copymsg(mp);
14747 		if (mp1 == NULL) {
14748 			mp->b_next = NULL;
14749 			/* clear b_prev - used by ip_mroute_decap */
14750 			mp->b_prev = NULL;
14751 			freemsg(mp);
14752 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14753 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14754 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14755 			return;
14756 		}
14757 		if (adjusted) {
14758 			/*
14759 			 * Copy is done. Restore the pointer in the _new_ mblk
14760 			 */
14761 			mp1->b_rptr += sizeof (struct ether_header);
14762 		}
14763 		/* Copy b_prev - used by ip_mroute_decap */
14764 		mp1->b_prev = mp->b_prev;
14765 		mp->b_prev = NULL;
14766 		freemsg(mp);
14767 		mp = mp1;
14768 	}
14769 	if (DB_TYPE(mp) == M_DATA) {
14770 		dmp = mp;
14771 	} else if (DB_TYPE(mp) == M_PROTO &&
14772 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14773 		dmp = mp->b_cont;
14774 	}
14775 	if (dmp != NULL) {
14776 		/*
14777 		 * IP header ptr not aligned?
14778 		 * OR IP header not complete in first mblk
14779 		 */
14780 		if (!OK_32PTR(dmp->b_rptr) ||
14781 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14782 			if (!ip_check_and_align_header(q, dmp))
14783 				return;
14784 		}
14785 	}
14786 
14787 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14788 	    "ip_rput_end: q %p (%S)", q, "end");
14789 
14790 	ip_input(ill, NULL, mp, NULL);
14791 }
14792 
14793 /*
14794  * Direct read side procedure capable of dealing with chains. GLDv3 based
14795  * drivers call this function directly with mblk chains while STREAMS
14796  * read side procedure ip_rput() calls this for single packet with ip_ring
14797  * set to NULL to process one packet at a time.
14798  *
14799  * The ill will always be valid if this function is called directly from
14800  * the driver.
14801  *
14802  * If ip_input() is called from GLDv3:
14803  *
14804  *   - This must be a non-VLAN IP stream.
14805  *   - 'mp' is either an untagged or a special priority-tagged packet.
14806  *   - Any VLAN tag that was in the MAC header has been stripped.
14807  *
14808  * Thus, there is no need to adjust b_rptr in this function.
14809  */
14810 /* ARGSUSED */
14811 void
14812 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14813     struct mac_header_info_s *mhip)
14814 {
14815 	ipaddr_t		dst = NULL;
14816 	ipaddr_t		prev_dst;
14817 	ire_t			*ire = NULL;
14818 	ipha_t			*ipha;
14819 	uint_t			pkt_len;
14820 	ssize_t			len;
14821 	uint_t			opt_len;
14822 	int			ll_multicast;
14823 	int			cgtp_flt_pkt;
14824 	queue_t			*q = ill->ill_rq;
14825 	squeue_t		*curr_sqp = NULL;
14826 	mblk_t 			*head = NULL;
14827 	mblk_t			*tail = NULL;
14828 	mblk_t			*first_mp;
14829 	mblk_t 			*mp;
14830 	int			cnt = 0;
14831 
14832 	ASSERT(mp_chain != NULL);
14833 	ASSERT(ill != NULL);
14834 
14835 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14836 
14837 #define	rptr	((uchar_t *)ipha)
14838 
14839 	while (mp_chain != NULL) {
14840 		first_mp = mp = mp_chain;
14841 		mp_chain = mp_chain->b_next;
14842 		mp->b_next = NULL;
14843 		ll_multicast = 0;
14844 
14845 		/*
14846 		 * We do ire caching from one iteration to
14847 		 * another. In the event the packet chain contains
14848 		 * all packets from the same dst, this caching saves
14849 		 * an ire_cache_lookup for each of the succeeding
14850 		 * packets in a packet chain.
14851 		 */
14852 		prev_dst = dst;
14853 
14854 		/*
14855 		 * ip_input fast path
14856 		 */
14857 
14858 		/* mblk type is not M_DATA */
14859 		if (mp->b_datap->db_type != M_DATA) {
14860 			if (ip_rput_process_notdata(q, &first_mp, ill,
14861 			    &ll_multicast, &mp))
14862 				continue;
14863 		}
14864 
14865 		/* Make sure its an M_DATA and that its aligned */
14866 		ASSERT(mp->b_datap->db_type == M_DATA);
14867 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14868 
14869 		ipha = (ipha_t *)mp->b_rptr;
14870 		len = mp->b_wptr - rptr;
14871 		pkt_len = ntohs(ipha->ipha_length);
14872 
14873 		/*
14874 		 * We must count all incoming packets, even if they end
14875 		 * up being dropped later on.
14876 		 */
14877 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14878 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14879 
14880 		/* multiple mblk or too short */
14881 		len -= pkt_len;
14882 		if (len != 0) {
14883 			/*
14884 			 * Make sure we have data length consistent
14885 			 * with the IP header.
14886 			 */
14887 			if (mp->b_cont == NULL) {
14888 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14889 					BUMP_MIB(ill->ill_ip_mib,
14890 					    ipIfStatsInHdrErrors);
14891 					ip2dbg(("ip_input: drop pkt\n"));
14892 					freemsg(mp);
14893 					continue;
14894 				}
14895 				mp->b_wptr = rptr + pkt_len;
14896 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14897 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14898 					BUMP_MIB(ill->ill_ip_mib,
14899 					    ipIfStatsInHdrErrors);
14900 					ip2dbg(("ip_input: drop pkt\n"));
14901 					freemsg(mp);
14902 					continue;
14903 				}
14904 				(void) adjmsg(mp, -len);
14905 				IP_STAT(ip_multimblk3);
14906 			}
14907 		}
14908 
14909 		/* Obtain the dst of the current packet */
14910 		dst = ipha->ipha_dst;
14911 
14912 		if (IP_LOOPBACK_ADDR(dst) ||
14913 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14914 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14915 			cmn_err(CE_CONT, "dst %X src %X\n",
14916 			    dst, ipha->ipha_src);
14917 			freemsg(mp);
14918 			continue;
14919 		}
14920 
14921 		/*
14922 		 * The event for packets being received from a 'physical'
14923 		 * interface is placed after validation of the source and/or
14924 		 * destination address as being local so that packets can be
14925 		 * redirected to loopback addresses using ipnat.
14926 		 */
14927 		DTRACE_PROBE4(ip4__physical__in__start,
14928 		    ill_t *, ill, ill_t *, NULL,
14929 		    ipha_t *, ipha, mblk_t *, first_mp);
14930 
14931 		FW_HOOKS(ip4_physical_in_event, ipv4firewall_physical_in,
14932 		    ill, NULL, ipha, first_mp, mp);
14933 
14934 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14935 
14936 		if (first_mp == NULL) {
14937 			continue;
14938 		}
14939 		dst = ipha->ipha_dst;
14940 
14941 		/*
14942 		 * Attach any necessary label information to
14943 		 * this packet
14944 		 */
14945 		if (is_system_labeled() &&
14946 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14947 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14948 			freemsg(mp);
14949 			continue;
14950 		}
14951 
14952 		/*
14953 		 * Reuse the cached ire only if the ipha_dst of the previous
14954 		 * packet is the same as the current packet AND it is not
14955 		 * INADDR_ANY.
14956 		 */
14957 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14958 		    (ire != NULL)) {
14959 			ire_refrele(ire);
14960 			ire = NULL;
14961 		}
14962 		opt_len = ipha->ipha_version_and_hdr_length -
14963 		    IP_SIMPLE_HDR_VERSION;
14964 
14965 		/*
14966 		 * Check to see if we can take the fastpath.
14967 		 * That is possible if the following conditions are met
14968 		 *	o Tsol disabled
14969 		 *	o CGTP disabled
14970 		 *	o ipp_action_count is 0
14971 		 *	o Mobile IP not running
14972 		 *	o no options in the packet
14973 		 *	o not a RSVP packet
14974 		 * 	o not a multicast packet
14975 		 */
14976 		if (!is_system_labeled() &&
14977 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14978 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14979 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14980 		    !ll_multicast && !CLASSD(dst)) {
14981 			if (ire == NULL)
14982 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14983 
14984 			/* incoming packet is for forwarding */
14985 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14986 				ire = ip_fast_forward(ire, dst, ill, mp);
14987 				continue;
14988 			}
14989 			/* incoming packet is for local consumption */
14990 			if (ire->ire_type & IRE_LOCAL)
14991 				goto local;
14992 		}
14993 
14994 		/*
14995 		 * Disable ire caching for anything more complex
14996 		 * than the simple fast path case we checked for above.
14997 		 */
14998 		if (ire != NULL) {
14999 			ire_refrele(ire);
15000 			ire = NULL;
15001 		}
15002 
15003 		/* Full-blown slow path */
15004 		if (opt_len != 0) {
15005 			if (len != 0)
15006 				IP_STAT(ip_multimblk4);
15007 			else
15008 				IP_STAT(ip_ipoptions);
15009 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15010 			    &dst))
15011 				continue;
15012 		}
15013 
15014 		/*
15015 		 * Invoke the CGTP (multirouting) filtering module to process
15016 		 * the incoming packet. Packets identified as duplicates
15017 		 * must be discarded. Filtering is active only if the
15018 		 * the ip_cgtp_filter ndd variable is non-zero.
15019 		 */
15020 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15021 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
15022 			cgtp_flt_pkt =
15023 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
15024 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15025 				freemsg(first_mp);
15026 				continue;
15027 			}
15028 		}
15029 
15030 		/*
15031 		 * If rsvpd is running, let RSVP daemon handle its processing
15032 		 * and forwarding of RSVP multicast/unicast packets.
15033 		 * If rsvpd is not running but mrouted is running, RSVP
15034 		 * multicast packets are forwarded as multicast traffic
15035 		 * and RSVP unicast packets are forwarded by unicast router.
15036 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15037 		 * packets are not forwarded, but the unicast packets are
15038 		 * forwarded like unicast traffic.
15039 		 */
15040 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15041 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
15042 			/* RSVP packet and rsvpd running. Treat as ours */
15043 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15044 			/*
15045 			 * This assumes that we deliver to all streams for
15046 			 * multicast and broadcast packets.
15047 			 * We have to force ll_multicast to 1 to handle the
15048 			 * M_DATA messages passed in from ip_mroute_decap.
15049 			 */
15050 			dst = INADDR_BROADCAST;
15051 			ll_multicast = 1;
15052 		} else if (CLASSD(dst)) {
15053 			/* packet is multicast */
15054 			mp->b_next = NULL;
15055 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15056 			    &ll_multicast, &dst))
15057 				continue;
15058 		}
15059 
15060 
15061 		/*
15062 		 * Check if the packet is coming from the Mobile IP
15063 		 * forward tunnel interface
15064 		 */
15065 		if (ill->ill_srcif_refcnt > 0) {
15066 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
15067 			    NULL, ill, MATCH_IRE_TYPE);
15068 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
15069 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
15070 
15071 				/* We need to resolve the link layer info */
15072 				ire_refrele(ire);
15073 				ire = NULL;
15074 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
15075 				    ll_multicast, dst);
15076 				continue;
15077 			}
15078 		}
15079 
15080 		if (ire == NULL) {
15081 			ire = ire_cache_lookup(dst, ALL_ZONES,
15082 			    MBLK_GETLABEL(mp));
15083 		}
15084 
15085 		/*
15086 		 * If mipagent is running and reverse tunnel is created as per
15087 		 * mobile node request, then any packet coming through the
15088 		 * incoming interface from the mobile-node, should be reverse
15089 		 * tunneled to it's home agent except those that are destined
15090 		 * to foreign agent only.
15091 		 * This needs source address based ire lookup. The routing
15092 		 * entries for source address based lookup are only created by
15093 		 * mipagent program only when a reverse tunnel is created.
15094 		 * Reference : RFC2002, RFC2344
15095 		 */
15096 		if (ill->ill_mrtun_refcnt > 0) {
15097 			ipaddr_t	srcaddr;
15098 			ire_t		*tmp_ire;
15099 
15100 			tmp_ire = ire;	/* Save, we might need it later */
15101 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
15102 			    ire->ire_type != IRE_BROADCAST)) {
15103 				srcaddr = ipha->ipha_src;
15104 				ire = ire_mrtun_lookup(srcaddr, ill);
15105 				if (ire != NULL) {
15106 					/*
15107 					 * Should not be getting iphada packet
15108 					 * here. we should only get those for
15109 					 * IRE_LOCAL traffic, excluded above.
15110 					 * Fail-safe (drop packet) in the event
15111 					 * hardware is misbehaving.
15112 					 */
15113 					if (first_mp != mp) {
15114 						/* IPsec KSTATS: beancount me */
15115 						freemsg(first_mp);
15116 					} else {
15117 						/*
15118 						 * This packet must be forwarded
15119 						 * to Reverse Tunnel
15120 						 */
15121 						ip_mrtun_forward(ire, ill, mp);
15122 					}
15123 					ire_refrele(ire);
15124 					ire = NULL;
15125 					if (tmp_ire != NULL) {
15126 						ire_refrele(tmp_ire);
15127 						tmp_ire = NULL;
15128 					}
15129 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15130 					    "ip_input_end: q %p (%S)",
15131 					    q, "uninit");
15132 					continue;
15133 				}
15134 			}
15135 			/*
15136 			 * If this packet is from a non-mobilenode  or a
15137 			 * mobile-node which does not request reverse
15138 			 * tunnel service
15139 			 */
15140 			ire = tmp_ire;
15141 		}
15142 
15143 
15144 		/*
15145 		 * If we reach here that means the incoming packet satisfies
15146 		 * one of the following conditions:
15147 		 *   - packet is from a mobile node which does not request
15148 		 *	reverse tunnel
15149 		 *   - packet is from a non-mobile node, which is the most
15150 		 *	common case
15151 		 *   - packet is from a reverse tunnel enabled mobile node
15152 		 *	and destined to foreign agent only
15153 		 */
15154 
15155 		if (ire == NULL) {
15156 			/*
15157 			 * No IRE for this destination, so it can't be for us.
15158 			 * Unless we are forwarding, drop the packet.
15159 			 * We have to let source routed packets through
15160 			 * since we don't yet know if they are 'ping -l'
15161 			 * packets i.e. if they will go out over the
15162 			 * same interface as they came in on.
15163 			 */
15164 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
15165 			if (ire == NULL)
15166 				continue;
15167 		}
15168 
15169 		/*
15170 		 * Broadcast IRE may indicate either broadcast or
15171 		 * multicast packet
15172 		 */
15173 		if (ire->ire_type == IRE_BROADCAST) {
15174 			/*
15175 			 * Skip broadcast checks if packet is UDP multicast;
15176 			 * we'd rather not enter ip_rput_process_broadcast()
15177 			 * unless the packet is broadcast for real, since
15178 			 * that routine is a no-op for multicast.
15179 			 */
15180 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15181 			    !CLASSD(ipha->ipha_dst)) {
15182 				ire = ip_rput_process_broadcast(&q, mp,
15183 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15184 				    ll_multicast);
15185 				if (ire == NULL)
15186 					continue;
15187 			}
15188 		} else if (ire->ire_stq != NULL) {
15189 			/* fowarding? */
15190 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15191 			    ll_multicast);
15192 			/* ip_rput_process_forward consumed the packet */
15193 			continue;
15194 		}
15195 
15196 local:
15197 		/* packet not for us */
15198 		if (ire->ire_rfq != q) {
15199 			if (ip_rput_notforus(&q, mp, ire, ill))
15200 				continue;
15201 		}
15202 
15203 		switch (ipha->ipha_protocol) {
15204 		case IPPROTO_TCP:
15205 			ASSERT(first_mp == mp);
15206 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15207 				mp, 0, q, ip_ring)) != NULL) {
15208 				if (curr_sqp == NULL) {
15209 					curr_sqp = GET_SQUEUE(mp);
15210 					ASSERT(cnt == 0);
15211 					cnt++;
15212 					head = tail = mp;
15213 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15214 					ASSERT(tail != NULL);
15215 					cnt++;
15216 					tail->b_next = mp;
15217 					tail = mp;
15218 				} else {
15219 					/*
15220 					 * A different squeue. Send the
15221 					 * chain for the previous squeue on
15222 					 * its way. This shouldn't happen
15223 					 * often unless interrupt binding
15224 					 * changes.
15225 					 */
15226 					IP_STAT(ip_input_multi_squeue);
15227 					squeue_enter_chain(curr_sqp, head,
15228 					    tail, cnt, SQTAG_IP_INPUT);
15229 					curr_sqp = GET_SQUEUE(mp);
15230 					head = mp;
15231 					tail = mp;
15232 					cnt = 1;
15233 				}
15234 			}
15235 			continue;
15236 		case IPPROTO_UDP:
15237 			ASSERT(first_mp == mp);
15238 			ip_udp_input(q, mp, ipha, ire, ill);
15239 			continue;
15240 		case IPPROTO_SCTP:
15241 			ASSERT(first_mp == mp);
15242 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15243 			    q, dst);
15244 			/* ire has been released by ip_sctp_input */
15245 			ire = NULL;
15246 			continue;
15247 		default:
15248 			ip_proto_input(q, first_mp, ipha, ire, ill);
15249 			continue;
15250 		}
15251 	}
15252 
15253 	if (ire != NULL)
15254 		ire_refrele(ire);
15255 
15256 	if (head != NULL)
15257 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15258 
15259 	/*
15260 	 * This code is there just to make netperf/ttcp look good.
15261 	 *
15262 	 * Its possible that after being in polling mode (and having cleared
15263 	 * the backlog), squeues have turned the interrupt frequency higher
15264 	 * to improve latency at the expense of more CPU utilization (less
15265 	 * packets per interrupts or more number of interrupts). Workloads
15266 	 * like ttcp/netperf do manage to tickle polling once in a while
15267 	 * but for the remaining time, stay in higher interrupt mode since
15268 	 * their packet arrival rate is pretty uniform and this shows up
15269 	 * as higher CPU utilization. Since people care about CPU utilization
15270 	 * while running netperf/ttcp, turn the interrupt frequency back to
15271 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15272 	 */
15273 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15274 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15275 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15276 			ip_ring->rr_blank(ip_ring->rr_handle,
15277 			    ip_ring->rr_normal_blank_time,
15278 			    ip_ring->rr_normal_pkt_cnt);
15279 		}
15280 	}
15281 
15282 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15283 	    "ip_input_end: q %p (%S)", q, "end");
15284 #undef	rptr
15285 }
15286 
15287 static void
15288 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15289     t_uscalar_t err)
15290 {
15291 	if (dl_err == DL_SYSERR) {
15292 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15293 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15294 		    ill->ill_name, dlpi_prim_str(prim), err);
15295 		return;
15296 	}
15297 
15298 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15299 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15300 	    dlpi_err_str(dl_err));
15301 }
15302 
15303 /*
15304  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15305  * than DL_UNITDATA_IND messages. If we need to process this message
15306  * exclusively, we call qwriter_ip, in which case we also need to call
15307  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15308  */
15309 void
15310 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15311 {
15312 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15313 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15314 	ill_t		*ill;
15315 
15316 	ip1dbg(("ip_rput_dlpi"));
15317 	ill = (ill_t *)q->q_ptr;
15318 	switch (dloa->dl_primitive) {
15319 	case DL_ERROR_ACK:
15320 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15321 		    "%s (0x%x), unix %u\n", ill->ill_name,
15322 		    dlpi_prim_str(dlea->dl_error_primitive),
15323 		    dlea->dl_error_primitive,
15324 		    dlpi_err_str(dlea->dl_errno),
15325 		    dlea->dl_errno,
15326 		    dlea->dl_unix_errno));
15327 		switch (dlea->dl_error_primitive) {
15328 		case DL_UNBIND_REQ:
15329 			mutex_enter(&ill->ill_lock);
15330 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15331 			cv_signal(&ill->ill_cv);
15332 			mutex_exit(&ill->ill_lock);
15333 			/* FALLTHRU */
15334 		case DL_NOTIFY_REQ:
15335 		case DL_ATTACH_REQ:
15336 		case DL_DETACH_REQ:
15337 		case DL_INFO_REQ:
15338 		case DL_BIND_REQ:
15339 		case DL_ENABMULTI_REQ:
15340 		case DL_PHYS_ADDR_REQ:
15341 		case DL_CAPABILITY_REQ:
15342 		case DL_CONTROL_REQ:
15343 			/*
15344 			 * Refhold the ill to match qwriter_ip which does a
15345 			 * refrele. Since this is on the ill stream we
15346 			 * unconditionally bump up the refcount without
15347 			 * checking for ILL_CAN_LOOKUP
15348 			 */
15349 			ill_refhold(ill);
15350 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15351 			    CUR_OP, B_FALSE);
15352 			return;
15353 		case DL_DISABMULTI_REQ:
15354 			freemsg(mp);	/* Don't want to pass this up */
15355 			return;
15356 		default:
15357 			break;
15358 		}
15359 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15360 		    dlea->dl_errno, dlea->dl_unix_errno);
15361 		freemsg(mp);
15362 		return;
15363 	case DL_INFO_ACK:
15364 	case DL_BIND_ACK:
15365 	case DL_PHYS_ADDR_ACK:
15366 	case DL_NOTIFY_ACK:
15367 	case DL_CAPABILITY_ACK:
15368 	case DL_CONTROL_ACK:
15369 		/*
15370 		 * Refhold the ill to match qwriter_ip which does a refrele
15371 		 * Since this is on the ill stream we unconditionally
15372 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15373 		 */
15374 		ill_refhold(ill);
15375 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15376 		    CUR_OP, B_FALSE);
15377 		return;
15378 	case DL_NOTIFY_IND:
15379 		ill_refhold(ill);
15380 		/*
15381 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15382 		 * relation to the current ioctl in progress (if any). Hence we
15383 		 * pass in NEW_OP in this case.
15384 		 */
15385 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15386 		    NEW_OP, B_FALSE);
15387 		return;
15388 	case DL_OK_ACK:
15389 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15390 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15391 		switch (dloa->dl_correct_primitive) {
15392 		case DL_UNBIND_REQ:
15393 			mutex_enter(&ill->ill_lock);
15394 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15395 			cv_signal(&ill->ill_cv);
15396 			mutex_exit(&ill->ill_lock);
15397 			/* FALLTHRU */
15398 		case DL_ATTACH_REQ:
15399 		case DL_DETACH_REQ:
15400 			/*
15401 			 * Refhold the ill to match qwriter_ip which does a
15402 			 * refrele. Since this is on the ill stream we
15403 			 * unconditionally bump up the refcount
15404 			 */
15405 			ill_refhold(ill);
15406 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15407 			    CUR_OP, B_FALSE);
15408 			return;
15409 		case DL_ENABMULTI_REQ:
15410 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15411 				ill->ill_dlpi_multicast_state = IDS_OK;
15412 			break;
15413 
15414 		}
15415 		break;
15416 	default:
15417 		break;
15418 	}
15419 	freemsg(mp);
15420 }
15421 
15422 /*
15423  * Handling of DLPI messages that require exclusive access to the ipsq.
15424  *
15425  * Need to do ill_pending_mp_release on ioctl completion, which could
15426  * happen here. (along with mi_copy_done)
15427  */
15428 /* ARGSUSED */
15429 static void
15430 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15431 {
15432 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15433 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15434 	int		err = 0;
15435 	ill_t		*ill;
15436 	ipif_t		*ipif = NULL;
15437 	mblk_t		*mp1 = NULL;
15438 	conn_t		*connp = NULL;
15439 	t_uscalar_t	paddrreq;
15440 	mblk_t		*mp_hw;
15441 	boolean_t	success;
15442 	boolean_t	ioctl_aborted = B_FALSE;
15443 	boolean_t	log = B_TRUE;
15444 	hook_nic_event_t	*info;
15445 
15446 	ip1dbg(("ip_rput_dlpi_writer .."));
15447 	ill = (ill_t *)q->q_ptr;
15448 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15449 
15450 	ASSERT(IAM_WRITER_ILL(ill));
15451 
15452 	/*
15453 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15454 	 * both are null or non-null. However we can assert that only
15455 	 * after grabbing the ipsq_lock. So we don't make any assertion
15456 	 * here and in other places in the code.
15457 	 */
15458 	ipif = ipsq->ipsq_pending_ipif;
15459 	/*
15460 	 * The current ioctl could have been aborted by the user and a new
15461 	 * ioctl to bring up another ill could have started. We could still
15462 	 * get a response from the driver later.
15463 	 */
15464 	if (ipif != NULL && ipif->ipif_ill != ill)
15465 		ioctl_aborted = B_TRUE;
15466 
15467 	switch (dloa->dl_primitive) {
15468 	case DL_ERROR_ACK:
15469 		switch (dlea->dl_error_primitive) {
15470 		case DL_UNBIND_REQ:
15471 		case DL_ATTACH_REQ:
15472 		case DL_DETACH_REQ:
15473 		case DL_INFO_REQ:
15474 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15475 			break;
15476 		case DL_NOTIFY_REQ:
15477 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15478 			log = B_FALSE;
15479 			break;
15480 		case DL_PHYS_ADDR_REQ:
15481 			/*
15482 			 * For IPv6 only, there are two additional
15483 			 * phys_addr_req's sent to the driver to get the
15484 			 * IPv6 token and lla. This allows IP to acquire
15485 			 * the hardware address format for a given interface
15486 			 * without having built in knowledge of the hardware
15487 			 * address. ill_phys_addr_pend keeps track of the last
15488 			 * DL_PAR sent so we know which response we are
15489 			 * dealing with. ill_dlpi_done will update
15490 			 * ill_phys_addr_pend when it sends the next req.
15491 			 * We don't complete the IOCTL until all three DL_PARs
15492 			 * have been attempted, so set *_len to 0 and break.
15493 			 */
15494 			paddrreq = ill->ill_phys_addr_pend;
15495 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15496 			if (paddrreq == DL_IPV6_TOKEN) {
15497 				ill->ill_token_length = 0;
15498 				log = B_FALSE;
15499 				break;
15500 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15501 				ill->ill_nd_lla_len = 0;
15502 				log = B_FALSE;
15503 				break;
15504 			}
15505 			/*
15506 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15507 			 * We presumably have an IOCTL hanging out waiting
15508 			 * for completion. Find it and complete the IOCTL
15509 			 * with the error noted.
15510 			 * However, ill_dl_phys was called on an ill queue
15511 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15512 			 * set. But the ioctl is known to be pending on ill_wq.
15513 			 */
15514 			if (!ill->ill_ifname_pending)
15515 				break;
15516 			ill->ill_ifname_pending = 0;
15517 			if (!ioctl_aborted)
15518 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15519 			if (mp1 != NULL) {
15520 				/*
15521 				 * This operation (SIOCSLIFNAME) must have
15522 				 * happened on the ill. Assert there is no conn
15523 				 */
15524 				ASSERT(connp == NULL);
15525 				q = ill->ill_wq;
15526 			}
15527 			break;
15528 		case DL_BIND_REQ:
15529 			ill_dlpi_done(ill, DL_BIND_REQ);
15530 			if (ill->ill_ifname_pending)
15531 				break;
15532 			/*
15533 			 * Something went wrong with the bind.  We presumably
15534 			 * have an IOCTL hanging out waiting for completion.
15535 			 * Find it, take down the interface that was coming
15536 			 * up, and complete the IOCTL with the error noted.
15537 			 */
15538 			if (!ioctl_aborted)
15539 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15540 			if (mp1 != NULL) {
15541 				/*
15542 				 * This operation (SIOCSLIFFLAGS) must have
15543 				 * happened from a conn.
15544 				 */
15545 				ASSERT(connp != NULL);
15546 				q = CONNP_TO_WQ(connp);
15547 				if (ill->ill_move_in_progress) {
15548 					ILL_CLEAR_MOVE(ill);
15549 				}
15550 				(void) ipif_down(ipif, NULL, NULL);
15551 				/* error is set below the switch */
15552 			}
15553 			break;
15554 		case DL_ENABMULTI_REQ:
15555 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15556 
15557 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15558 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15559 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15560 				ipif_t *ipif;
15561 
15562 				log = B_FALSE;
15563 				printf("ip: joining multicasts failed (%d)"
15564 				    " on %s - will use link layer "
15565 				    "broadcasts for multicast\n",
15566 				    dlea->dl_errno, ill->ill_name);
15567 
15568 				/*
15569 				 * Set up the multicast mapping alone.
15570 				 * writer, so ok to access ill->ill_ipif
15571 				 * without any lock.
15572 				 */
15573 				ipif = ill->ill_ipif;
15574 				mutex_enter(&ill->ill_phyint->phyint_lock);
15575 				ill->ill_phyint->phyint_flags |=
15576 				    PHYI_MULTI_BCAST;
15577 				mutex_exit(&ill->ill_phyint->phyint_lock);
15578 
15579 				if (!ill->ill_isv6) {
15580 					(void) ipif_arp_setup_multicast(ipif,
15581 					    NULL);
15582 				} else {
15583 					(void) ipif_ndp_setup_multicast(ipif,
15584 					    NULL);
15585 				}
15586 			}
15587 			freemsg(mp);	/* Don't want to pass this up */
15588 			return;
15589 		case DL_CAPABILITY_REQ:
15590 		case DL_CONTROL_REQ:
15591 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15592 			    "DL_CAPABILITY/CONTROL REQ\n"));
15593 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15594 			ill->ill_dlpi_capab_state = IDS_FAILED;
15595 			freemsg(mp);
15596 			return;
15597 		}
15598 		/*
15599 		 * Note the error for IOCTL completion (mp1 is set when
15600 		 * ready to complete ioctl). If ill_ifname_pending_err is
15601 		 * set, an error occured during plumbing (ill_ifname_pending),
15602 		 * so we want to report that error.
15603 		 *
15604 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15605 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15606 		 * expected to get errack'd if the driver doesn't support
15607 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15608 		 * if these error conditions are encountered.
15609 		 */
15610 		if (mp1 != NULL) {
15611 			if (ill->ill_ifname_pending_err != 0)  {
15612 				err = ill->ill_ifname_pending_err;
15613 				ill->ill_ifname_pending_err = 0;
15614 			} else {
15615 				err = dlea->dl_unix_errno ?
15616 				    dlea->dl_unix_errno : ENXIO;
15617 			}
15618 		/*
15619 		 * If we're plumbing an interface and an error hasn't already
15620 		 * been saved, set ill_ifname_pending_err to the error passed
15621 		 * up. Ignore the error if log is B_FALSE (see comment above).
15622 		 */
15623 		} else if (log && ill->ill_ifname_pending &&
15624 		    ill->ill_ifname_pending_err == 0) {
15625 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15626 			dlea->dl_unix_errno : ENXIO;
15627 		}
15628 
15629 		if (log)
15630 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15631 			    dlea->dl_errno, dlea->dl_unix_errno);
15632 		break;
15633 	case DL_CAPABILITY_ACK: {
15634 		boolean_t reneg_flag = B_FALSE;
15635 		/* Call a routine to handle this one. */
15636 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15637 		/*
15638 		 * Check if the ACK is due to renegotiation case since we
15639 		 * will need to send a new CAPABILITY_REQ later.
15640 		 */
15641 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15642 			/* This is the ack for a renogiation case */
15643 			reneg_flag = B_TRUE;
15644 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15645 		}
15646 		ill_capability_ack(ill, mp);
15647 		if (reneg_flag)
15648 			ill_capability_probe(ill);
15649 		break;
15650 	}
15651 	case DL_CONTROL_ACK:
15652 		/* We treat all of these as "fire and forget" */
15653 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15654 		break;
15655 	case DL_INFO_ACK:
15656 		/* Call a routine to handle this one. */
15657 		ill_dlpi_done(ill, DL_INFO_REQ);
15658 		ip_ll_subnet_defaults(ill, mp);
15659 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15660 		return;
15661 	case DL_BIND_ACK:
15662 		/*
15663 		 * We should have an IOCTL waiting on this unless
15664 		 * sent by ill_dl_phys, in which case just return
15665 		 */
15666 		ill_dlpi_done(ill, DL_BIND_REQ);
15667 		if (ill->ill_ifname_pending)
15668 			break;
15669 
15670 		if (!ioctl_aborted)
15671 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15672 		if (mp1 == NULL)
15673 			break;
15674 		/*
15675 		 * Because mp1 was added by ill_dl_up(), and it always
15676 		 * passes a valid connp, connp must be valid here.
15677 		 */
15678 		ASSERT(connp != NULL);
15679 		q = CONNP_TO_WQ(connp);
15680 
15681 		/*
15682 		 * We are exclusive. So nothing can change even after
15683 		 * we get the pending mp. If need be we can put it back
15684 		 * and restart, as in calling ipif_arp_up()  below.
15685 		 */
15686 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15687 
15688 		mutex_enter(&ill->ill_lock);
15689 
15690 		ill->ill_dl_up = 1;
15691 
15692 		if ((info = ill->ill_nic_event_info) != NULL) {
15693 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15694 			    "attached for %s\n", info->hne_event,
15695 			    ill->ill_name));
15696 			if (info->hne_data != NULL)
15697 				kmem_free(info->hne_data, info->hne_datalen);
15698 			kmem_free(info, sizeof (hook_nic_event_t));
15699 		}
15700 
15701 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15702 		if (info != NULL) {
15703 			info->hne_nic = ill->ill_phyint->phyint_ifindex;
15704 			info->hne_lif = 0;
15705 			info->hne_event = NE_UP;
15706 			info->hne_data = NULL;
15707 			info->hne_datalen = 0;
15708 			info->hne_family = ill->ill_isv6 ? ipv6 : ipv4;
15709 		} else
15710 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15711 			    "event information for %s (ENOMEM)\n",
15712 			    ill->ill_name));
15713 
15714 		ill->ill_nic_event_info = info;
15715 
15716 		mutex_exit(&ill->ill_lock);
15717 
15718 		/*
15719 		 * Now bring up the resolver; when that is complete, we'll
15720 		 * create IREs.  Note that we intentionally mirror what
15721 		 * ipif_up() would have done, because we got here by way of
15722 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15723 		 */
15724 		if (ill->ill_isv6) {
15725 			/*
15726 			 * v6 interfaces.
15727 			 * Unlike ARP which has to do another bind
15728 			 * and attach, once we get here we are
15729 			 * done with NDP. Except in the case of
15730 			 * ILLF_XRESOLV, in which case we send an
15731 			 * AR_INTERFACE_UP to the external resolver.
15732 			 * If all goes well, the ioctl will complete
15733 			 * in ip_rput(). If there's an error, we
15734 			 * complete it here.
15735 			 */
15736 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr);
15737 			if (err == 0) {
15738 				if (ill->ill_flags & ILLF_XRESOLV) {
15739 					mutex_enter(&connp->conn_lock);
15740 					mutex_enter(&ill->ill_lock);
15741 					success = ipsq_pending_mp_add(
15742 					    connp, ipif, q, mp1, 0);
15743 					mutex_exit(&ill->ill_lock);
15744 					mutex_exit(&connp->conn_lock);
15745 					if (success) {
15746 						err = ipif_resolver_up(ipif,
15747 						    Res_act_initial);
15748 						if (err == EINPROGRESS) {
15749 							freemsg(mp);
15750 							return;
15751 						}
15752 						ASSERT(err != 0);
15753 						mp1 = ipsq_pending_mp_get(ipsq,
15754 						    &connp);
15755 						ASSERT(mp1 != NULL);
15756 					} else {
15757 						/* conn has started closing */
15758 						err = EINTR;
15759 					}
15760 				} else { /* Non XRESOLV interface */
15761 					(void) ipif_resolver_up(ipif,
15762 					    Res_act_initial);
15763 					err = ipif_up_done_v6(ipif);
15764 				}
15765 			}
15766 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15767 			/*
15768 			 * ARP and other v4 external resolvers.
15769 			 * Leave the pending mblk intact so that
15770 			 * the ioctl completes in ip_rput().
15771 			 */
15772 			mutex_enter(&connp->conn_lock);
15773 			mutex_enter(&ill->ill_lock);
15774 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15775 			mutex_exit(&ill->ill_lock);
15776 			mutex_exit(&connp->conn_lock);
15777 			if (success) {
15778 				err = ipif_resolver_up(ipif, Res_act_initial);
15779 				if (err == EINPROGRESS) {
15780 					freemsg(mp);
15781 					return;
15782 				}
15783 				ASSERT(err != 0);
15784 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15785 			} else {
15786 				/* The conn has started closing */
15787 				err = EINTR;
15788 			}
15789 		} else {
15790 			/*
15791 			 * This one is complete. Reply to pending ioctl.
15792 			 */
15793 			(void) ipif_resolver_up(ipif, Res_act_initial);
15794 			err = ipif_up_done(ipif);
15795 		}
15796 
15797 		if ((err == 0) && (ill->ill_up_ipifs)) {
15798 			err = ill_up_ipifs(ill, q, mp1);
15799 			if (err == EINPROGRESS) {
15800 				freemsg(mp);
15801 				return;
15802 			}
15803 		}
15804 
15805 		if (ill->ill_up_ipifs) {
15806 			ill_group_cleanup(ill);
15807 		}
15808 
15809 		break;
15810 	case DL_NOTIFY_IND: {
15811 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15812 		ire_t *ire;
15813 		boolean_t need_ire_walk_v4 = B_FALSE;
15814 		boolean_t need_ire_walk_v6 = B_FALSE;
15815 
15816 		switch (notify->dl_notification) {
15817 		case DL_NOTE_PHYS_ADDR:
15818 			err = ill_set_phys_addr(ill, mp);
15819 			break;
15820 
15821 		case DL_NOTE_FASTPATH_FLUSH:
15822 			ill_fastpath_flush(ill);
15823 			break;
15824 
15825 		case DL_NOTE_SDU_SIZE:
15826 			/*
15827 			 * Change the MTU size of the interface, of all
15828 			 * attached ipif's, and of all relevant ire's.  The
15829 			 * new value's a uint32_t at notify->dl_data.
15830 			 * Mtu change Vs. new ire creation - protocol below.
15831 			 *
15832 			 * a Mark the ipif as IPIF_CHANGING.
15833 			 * b Set the new mtu in the ipif.
15834 			 * c Change the ire_max_frag on all affected ires
15835 			 * d Unmark the IPIF_CHANGING
15836 			 *
15837 			 * To see how the protocol works, assume an interface
15838 			 * route is also being added simultaneously by
15839 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15840 			 * the ire. If the ire is created before step a,
15841 			 * it will be cleaned up by step c. If the ire is
15842 			 * created after step d, it will see the new value of
15843 			 * ipif_mtu. Any attempt to create the ire between
15844 			 * steps a to d will fail because of the IPIF_CHANGING
15845 			 * flag. Note that ire_create() is passed a pointer to
15846 			 * the ipif_mtu, and not the value. During ire_add
15847 			 * under the bucket lock, the ire_max_frag of the
15848 			 * new ire being created is set from the ipif/ire from
15849 			 * which it is being derived.
15850 			 */
15851 			mutex_enter(&ill->ill_lock);
15852 			ill->ill_max_frag = (uint_t)notify->dl_data;
15853 
15854 			/*
15855 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15856 			 * leave it alone
15857 			 */
15858 			if (ill->ill_mtu_userspecified) {
15859 				mutex_exit(&ill->ill_lock);
15860 				break;
15861 			}
15862 			ill->ill_max_mtu = ill->ill_max_frag;
15863 			if (ill->ill_isv6) {
15864 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15865 					ill->ill_max_mtu = IPV6_MIN_MTU;
15866 			} else {
15867 				if (ill->ill_max_mtu < IP_MIN_MTU)
15868 					ill->ill_max_mtu = IP_MIN_MTU;
15869 			}
15870 			for (ipif = ill->ill_ipif; ipif != NULL;
15871 			    ipif = ipif->ipif_next) {
15872 				/*
15873 				 * Don't override the mtu if the user
15874 				 * has explicitly set it.
15875 				 */
15876 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15877 					continue;
15878 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15879 				if (ipif->ipif_isv6)
15880 					ire = ipif_to_ire_v6(ipif);
15881 				else
15882 					ire = ipif_to_ire(ipif);
15883 				if (ire != NULL) {
15884 					ire->ire_max_frag = ipif->ipif_mtu;
15885 					ire_refrele(ire);
15886 				}
15887 				if (ipif->ipif_flags & IPIF_UP) {
15888 					if (ill->ill_isv6)
15889 						need_ire_walk_v6 = B_TRUE;
15890 					else
15891 						need_ire_walk_v4 = B_TRUE;
15892 				}
15893 			}
15894 			mutex_exit(&ill->ill_lock);
15895 			if (need_ire_walk_v4)
15896 				ire_walk_v4(ill_mtu_change, (char *)ill,
15897 				    ALL_ZONES);
15898 			if (need_ire_walk_v6)
15899 				ire_walk_v6(ill_mtu_change, (char *)ill,
15900 				    ALL_ZONES);
15901 			break;
15902 		case DL_NOTE_LINK_UP:
15903 		case DL_NOTE_LINK_DOWN: {
15904 			/*
15905 			 * We are writer. ill / phyint / ipsq assocs stable.
15906 			 * The RUNNING flag reflects the state of the link.
15907 			 */
15908 			phyint_t *phyint = ill->ill_phyint;
15909 			uint64_t new_phyint_flags;
15910 			boolean_t changed = B_FALSE;
15911 			boolean_t went_up;
15912 
15913 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15914 			mutex_enter(&phyint->phyint_lock);
15915 			new_phyint_flags = went_up ?
15916 			    phyint->phyint_flags | PHYI_RUNNING :
15917 			    phyint->phyint_flags & ~PHYI_RUNNING;
15918 			if (new_phyint_flags != phyint->phyint_flags) {
15919 				phyint->phyint_flags = new_phyint_flags;
15920 				changed = B_TRUE;
15921 			}
15922 			mutex_exit(&phyint->phyint_lock);
15923 			/*
15924 			 * ill_restart_dad handles the DAD restart and routing
15925 			 * socket notification logic.
15926 			 */
15927 			if (changed) {
15928 				ill_restart_dad(phyint->phyint_illv4, went_up);
15929 				ill_restart_dad(phyint->phyint_illv6, went_up);
15930 			}
15931 			break;
15932 		}
15933 		case DL_NOTE_PROMISC_ON_PHYS:
15934 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15935 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15936 			mutex_enter(&ill->ill_lock);
15937 			ill->ill_promisc_on_phys = B_TRUE;
15938 			mutex_exit(&ill->ill_lock);
15939 			break;
15940 		case DL_NOTE_PROMISC_OFF_PHYS:
15941 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15942 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15943 			mutex_enter(&ill->ill_lock);
15944 			ill->ill_promisc_on_phys = B_FALSE;
15945 			mutex_exit(&ill->ill_lock);
15946 			break;
15947 		case DL_NOTE_CAPAB_RENEG:
15948 			/*
15949 			 * Something changed on the driver side.
15950 			 * It wants us to renegotiate the capabilities
15951 			 * on this ill. The most likely cause is the
15952 			 * aggregation interface under us where a
15953 			 * port got added or went away.
15954 			 *
15955 			 * We reset the capabilities and set the
15956 			 * state to IDS_RENG so that when the ack
15957 			 * comes back, we can start the
15958 			 * renegotiation process.
15959 			 */
15960 			ill_capability_reset(ill);
15961 			ill->ill_dlpi_capab_state = IDS_RENEG;
15962 			break;
15963 		default:
15964 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15965 			    "type 0x%x for DL_NOTIFY_IND\n",
15966 			    notify->dl_notification));
15967 			break;
15968 		}
15969 
15970 		/*
15971 		 * As this is an asynchronous operation, we
15972 		 * should not call ill_dlpi_done
15973 		 */
15974 		break;
15975 	}
15976 	case DL_NOTIFY_ACK: {
15977 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15978 
15979 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15980 			ill->ill_note_link = 1;
15981 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15982 		break;
15983 	}
15984 	case DL_PHYS_ADDR_ACK: {
15985 		/*
15986 		 * As part of plumbing the interface via SIOCSLIFNAME,
15987 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
15988 		 * whose answers we receive here.  As each answer is received,
15989 		 * we call ill_dlpi_done() to dispatch the next request as
15990 		 * we're processing the current one.  Once all answers have
15991 		 * been received, we use ipsq_pending_mp_get() to dequeue the
15992 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
15993 		 * is invoked from an ill queue, conn_oper_pending_ill is not
15994 		 * available, but we know the ioctl is pending on ill_wq.)
15995 		 */
15996 		uint_t paddrlen, paddroff;
15997 
15998 		paddrreq = ill->ill_phys_addr_pend;
15999 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16000 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16001 
16002 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16003 		if (paddrreq == DL_IPV6_TOKEN) {
16004 			/*
16005 			 * bcopy to low-order bits of ill_token
16006 			 *
16007 			 * XXX Temporary hack - currently, all known tokens
16008 			 * are 64 bits, so I'll cheat for the moment.
16009 			 */
16010 			bcopy(mp->b_rptr + paddroff,
16011 			    &ill->ill_token.s6_addr32[2], paddrlen);
16012 			ill->ill_token_length = paddrlen;
16013 			break;
16014 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16015 			ASSERT(ill->ill_nd_lla_mp == NULL);
16016 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16017 			mp = NULL;
16018 			break;
16019 		}
16020 
16021 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16022 		ASSERT(ill->ill_phys_addr_mp == NULL);
16023 		if (!ill->ill_ifname_pending)
16024 			break;
16025 		ill->ill_ifname_pending = 0;
16026 		if (!ioctl_aborted)
16027 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16028 		if (mp1 != NULL) {
16029 			ASSERT(connp == NULL);
16030 			q = ill->ill_wq;
16031 		}
16032 		/*
16033 		 * If any error acks received during the plumbing sequence,
16034 		 * ill_ifname_pending_err will be set. Break out and send up
16035 		 * the error to the pending ioctl.
16036 		 */
16037 		if (ill->ill_ifname_pending_err != 0) {
16038 			err = ill->ill_ifname_pending_err;
16039 			ill->ill_ifname_pending_err = 0;
16040 			break;
16041 		}
16042 
16043 		ill->ill_phys_addr_mp = mp;
16044 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16045 		mp = NULL;
16046 
16047 		/*
16048 		 * If paddrlen is zero, the DLPI provider doesn't support
16049 		 * physical addresses.  The other two tests were historical
16050 		 * workarounds for bugs in our former PPP implementation, but
16051 		 * now other things have grown dependencies on them -- e.g.,
16052 		 * the tun module specifies a dl_addr_length of zero in its
16053 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16054 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16055 		 * but only after careful testing ensures that all dependent
16056 		 * broken DLPI providers have been fixed.
16057 		 */
16058 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16059 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16060 			ill->ill_phys_addr = NULL;
16061 		} else if (paddrlen != ill->ill_phys_addr_length) {
16062 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16063 			    paddrlen, ill->ill_phys_addr_length));
16064 			err = EINVAL;
16065 			break;
16066 		}
16067 
16068 		if (ill->ill_nd_lla_mp == NULL) {
16069 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16070 				err = ENOMEM;
16071 				break;
16072 			}
16073 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16074 		}
16075 
16076 		/*
16077 		 * Set the interface token.  If the zeroth interface address
16078 		 * is unspecified, then set it to the link local address.
16079 		 */
16080 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16081 			(void) ill_setdefaulttoken(ill);
16082 
16083 		ASSERT(ill->ill_ipif->ipif_id == 0);
16084 		if (ipif != NULL &&
16085 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
16086 			(void) ipif_setlinklocal(ipif);
16087 		break;
16088 	}
16089 	case DL_OK_ACK:
16090 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16091 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16092 		    dloa->dl_correct_primitive));
16093 		switch (dloa->dl_correct_primitive) {
16094 		case DL_UNBIND_REQ:
16095 		case DL_ATTACH_REQ:
16096 		case DL_DETACH_REQ:
16097 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16098 			break;
16099 		}
16100 		break;
16101 	default:
16102 		break;
16103 	}
16104 
16105 	freemsg(mp);
16106 	if (mp1 != NULL) {
16107 		/*
16108 		 * The operation must complete without EINPROGRESS
16109 		 * since ipsq_pending_mp_get() has removed the mblk
16110 		 * from ipsq_pending_mp.  Otherwise, the operation
16111 		 * will be stuck forever in the ipsq.
16112 		 */
16113 		ASSERT(err != EINPROGRESS);
16114 
16115 		switch (ipsq->ipsq_current_ioctl) {
16116 		case 0:
16117 			ipsq_current_finish(ipsq);
16118 			break;
16119 
16120 		case SIOCLIFADDIF:
16121 		case SIOCSLIFNAME:
16122 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16123 			break;
16124 
16125 		default:
16126 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16127 			break;
16128 		}
16129 	}
16130 }
16131 
16132 /*
16133  * ip_rput_other is called by ip_rput to handle messages modifying the global
16134  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16135  */
16136 /* ARGSUSED */
16137 void
16138 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16139 {
16140 	ill_t		*ill;
16141 	struct iocblk	*iocp;
16142 	mblk_t		*mp1;
16143 	conn_t		*connp = NULL;
16144 
16145 	ip1dbg(("ip_rput_other "));
16146 	ill = (ill_t *)q->q_ptr;
16147 	/*
16148 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16149 	 * in which case ipsq is NULL.
16150 	 */
16151 	if (ipsq != NULL) {
16152 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16153 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16154 	}
16155 
16156 	switch (mp->b_datap->db_type) {
16157 	case M_ERROR:
16158 	case M_HANGUP:
16159 		/*
16160 		 * The device has a problem.  We force the ILL down.  It can
16161 		 * be brought up again manually using SIOCSIFFLAGS (via
16162 		 * ifconfig or equivalent).
16163 		 */
16164 		ASSERT(ipsq != NULL);
16165 		if (mp->b_rptr < mp->b_wptr)
16166 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16167 		if (ill->ill_error == 0)
16168 			ill->ill_error = ENXIO;
16169 		if (!ill_down_start(q, mp))
16170 			return;
16171 		ipif_all_down_tail(ipsq, q, mp, NULL);
16172 		break;
16173 	case M_IOCACK:
16174 		iocp = (struct iocblk *)mp->b_rptr;
16175 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16176 		switch (iocp->ioc_cmd) {
16177 		case SIOCSTUNPARAM:
16178 		case OSIOCSTUNPARAM:
16179 			ASSERT(ipsq != NULL);
16180 			/*
16181 			 * Finish socket ioctl passed through to tun.
16182 			 * We should have an IOCTL waiting on this.
16183 			 */
16184 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16185 			if (ill->ill_isv6) {
16186 				struct iftun_req *ta;
16187 
16188 				/*
16189 				 * if a source or destination is
16190 				 * being set, try and set the link
16191 				 * local address for the tunnel
16192 				 */
16193 				ta = (struct iftun_req *)mp->b_cont->
16194 				    b_cont->b_rptr;
16195 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16196 					ipif_set_tun_llink(ill, ta);
16197 				}
16198 			}
16199 			if (mp1 != NULL) {
16200 				/*
16201 				 * Now copy back the b_next/b_prev used by
16202 				 * mi code for the mi_copy* functions.
16203 				 * See ip_sioctl_tunparam() for the reason.
16204 				 * Also protect against missing b_cont.
16205 				 */
16206 				if (mp->b_cont != NULL) {
16207 					mp->b_cont->b_next =
16208 					    mp1->b_cont->b_next;
16209 					mp->b_cont->b_prev =
16210 					    mp1->b_cont->b_prev;
16211 				}
16212 				inet_freemsg(mp1);
16213 				ASSERT(connp != NULL);
16214 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16215 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16216 			} else {
16217 				ASSERT(connp == NULL);
16218 				putnext(q, mp);
16219 			}
16220 			break;
16221 		case SIOCGTUNPARAM:
16222 		case OSIOCGTUNPARAM:
16223 			/*
16224 			 * This is really M_IOCDATA from the tunnel driver.
16225 			 * convert back and complete the ioctl.
16226 			 * We should have an IOCTL waiting on this.
16227 			 */
16228 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16229 			if (mp1) {
16230 				/*
16231 				 * Now copy back the b_next/b_prev used by
16232 				 * mi code for the mi_copy* functions.
16233 				 * See ip_sioctl_tunparam() for the reason.
16234 				 * Also protect against missing b_cont.
16235 				 */
16236 				if (mp->b_cont != NULL) {
16237 					mp->b_cont->b_next =
16238 					    mp1->b_cont->b_next;
16239 					mp->b_cont->b_prev =
16240 					    mp1->b_cont->b_prev;
16241 				}
16242 				inet_freemsg(mp1);
16243 				if (iocp->ioc_error == 0)
16244 					mp->b_datap->db_type = M_IOCDATA;
16245 				ASSERT(connp != NULL);
16246 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16247 				    iocp->ioc_error, COPYOUT, NULL);
16248 			} else {
16249 				ASSERT(connp == NULL);
16250 				putnext(q, mp);
16251 			}
16252 			break;
16253 		default:
16254 			break;
16255 		}
16256 		break;
16257 	case M_IOCNAK:
16258 		iocp = (struct iocblk *)mp->b_rptr;
16259 
16260 		switch (iocp->ioc_cmd) {
16261 		int mode;
16262 
16263 		case DL_IOC_HDR_INFO:
16264 			/*
16265 			 * If this was the first attempt turn of the
16266 			 * fastpath probing.
16267 			 */
16268 			mutex_enter(&ill->ill_lock);
16269 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16270 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16271 				mutex_exit(&ill->ill_lock);
16272 				ill_fastpath_nack(ill);
16273 				ip1dbg(("ip_rput: DLPI fastpath off on "
16274 				    "interface %s\n",
16275 				    ill->ill_name));
16276 			} else {
16277 				mutex_exit(&ill->ill_lock);
16278 			}
16279 			freemsg(mp);
16280 			break;
16281 		case SIOCSTUNPARAM:
16282 		case OSIOCSTUNPARAM:
16283 			ASSERT(ipsq != NULL);
16284 			/*
16285 			 * Finish socket ioctl passed through to tun
16286 			 * We should have an IOCTL waiting on this.
16287 			 */
16288 			/* FALLTHRU */
16289 		case SIOCGTUNPARAM:
16290 		case OSIOCGTUNPARAM:
16291 			/*
16292 			 * This is really M_IOCDATA from the tunnel driver.
16293 			 * convert back and complete the ioctl.
16294 			 * We should have an IOCTL waiting on this.
16295 			 */
16296 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16297 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16298 				mp1 = ill_pending_mp_get(ill, &connp,
16299 				    iocp->ioc_id);
16300 				mode = COPYOUT;
16301 				ipsq = NULL;
16302 			} else {
16303 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16304 				mode = NO_COPYOUT;
16305 			}
16306 			if (mp1 != NULL) {
16307 				/*
16308 				 * Now copy back the b_next/b_prev used by
16309 				 * mi code for the mi_copy* functions.
16310 				 * See ip_sioctl_tunparam() for the reason.
16311 				 * Also protect against missing b_cont.
16312 				 */
16313 				if (mp->b_cont != NULL) {
16314 					mp->b_cont->b_next =
16315 					    mp1->b_cont->b_next;
16316 					mp->b_cont->b_prev =
16317 					    mp1->b_cont->b_prev;
16318 				}
16319 				inet_freemsg(mp1);
16320 				if (iocp->ioc_error == 0)
16321 					iocp->ioc_error = EINVAL;
16322 				ASSERT(connp != NULL);
16323 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16324 				    iocp->ioc_error, mode, ipsq);
16325 			} else {
16326 				ASSERT(connp == NULL);
16327 				putnext(q, mp);
16328 			}
16329 			break;
16330 		default:
16331 			break;
16332 		}
16333 	default:
16334 		break;
16335 	}
16336 }
16337 
16338 /*
16339  * NOTE : This function does not ire_refrele the ire argument passed in.
16340  *
16341  * IPQoS notes
16342  * IP policy is invoked twice for a forwarded packet, once on the read side
16343  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16344  * enabled. An additional parameter, in_ill, has been added for this purpose.
16345  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16346  * because ip_mroute drops this information.
16347  *
16348  */
16349 void
16350 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16351 {
16352 	uint32_t	pkt_len;
16353 	queue_t	*q;
16354 	uint32_t	sum;
16355 #define	rptr	((uchar_t *)ipha)
16356 	uint32_t	max_frag;
16357 	uint32_t	ill_index;
16358 	ill_t		*out_ill;
16359 	mib2_ipIfStatsEntry_t *mibptr;
16360 
16361 	/* Get the ill_index of the incoming ILL */
16362 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16363 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ip_mib;
16364 
16365 	/* Initiate Read side IPPF processing */
16366 	if (IPP_ENABLED(IPP_FWD_IN)) {
16367 		ip_process(IPP_FWD_IN, &mp, ill_index);
16368 		if (mp == NULL) {
16369 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16370 			    "during IPPF processing\n"));
16371 			return;
16372 		}
16373 	}
16374 
16375 	pkt_len = ntohs(ipha->ipha_length);
16376 
16377 	/* Adjust the checksum to reflect the ttl decrement. */
16378 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16379 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16380 
16381 	if (ipha->ipha_ttl-- <= 1) {
16382 		if (ip_csum_hdr(ipha)) {
16383 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16384 			goto drop_pkt;
16385 		}
16386 		/*
16387 		 * Note: ire_stq this will be NULL for multicast
16388 		 * datagrams using the long path through arp (the IRE
16389 		 * is not an IRE_CACHE). This should not cause
16390 		 * problems since we don't generate ICMP errors for
16391 		 * multicast packets.
16392 		 */
16393 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16394 		q = ire->ire_stq;
16395 		if (q != NULL) {
16396 			/* Sent by forwarding path, and router is global zone */
16397 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16398 			    GLOBAL_ZONEID);
16399 		} else
16400 			freemsg(mp);
16401 		return;
16402 	}
16403 
16404 	/*
16405 	 * Don't forward if the interface is down
16406 	 */
16407 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16408 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16409 		ip2dbg(("ip_rput_forward:interface is down\n"));
16410 		goto drop_pkt;
16411 	}
16412 
16413 	/* Get the ill_index of the outgoing ILL */
16414 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16415 
16416 	out_ill = ire->ire_ipif->ipif_ill;
16417 
16418 	DTRACE_PROBE4(ip4__forwarding__start,
16419 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16420 
16421 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
16422 	    in_ill, out_ill, ipha, mp, mp);
16423 
16424 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16425 
16426 	if (mp == NULL)
16427 		return;
16428 	pkt_len = ntohs(ipha->ipha_length);
16429 
16430 	if (is_system_labeled()) {
16431 		mblk_t *mp1;
16432 
16433 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16434 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16435 			goto drop_pkt;
16436 		}
16437 		/* Size may have changed */
16438 		mp = mp1;
16439 		ipha = (ipha_t *)mp->b_rptr;
16440 		pkt_len = ntohs(ipha->ipha_length);
16441 	}
16442 
16443 	/* Check if there are options to update */
16444 	if (!IS_SIMPLE_IPH(ipha)) {
16445 		if (ip_csum_hdr(ipha)) {
16446 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16447 			goto drop_pkt;
16448 		}
16449 		if (ip_rput_forward_options(mp, ipha, ire)) {
16450 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16451 			return;
16452 		}
16453 
16454 		ipha->ipha_hdr_checksum = 0;
16455 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16456 	}
16457 	max_frag = ire->ire_max_frag;
16458 	if (pkt_len > max_frag) {
16459 		/*
16460 		 * It needs fragging on its way out.  We haven't
16461 		 * verified the header checksum yet.  Since we
16462 		 * are going to put a surely good checksum in the
16463 		 * outgoing header, we have to make sure that it
16464 		 * was good coming in.
16465 		 */
16466 		if (ip_csum_hdr(ipha)) {
16467 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16468 			goto drop_pkt;
16469 		}
16470 		/* Initiate Write side IPPF processing */
16471 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16472 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16473 			if (mp == NULL) {
16474 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16475 				    " during IPPF processing\n"));
16476 				return;
16477 			}
16478 		}
16479 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
16480 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16481 		return;
16482 	}
16483 
16484 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16485 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16486 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
16487 	    NULL, out_ill, ipha, mp, mp);
16488 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16489 	if (mp == NULL)
16490 		return;
16491 
16492 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16493 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16494 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16495 	/* ip_xmit_v4 always consumes the packet */
16496 	return;
16497 
16498 drop_pkt:;
16499 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16500 	freemsg(mp);
16501 #undef	rptr
16502 }
16503 
16504 void
16505 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16506 {
16507 	ire_t	*ire;
16508 
16509 	ASSERT(!ipif->ipif_isv6);
16510 	/*
16511 	 * Find an IRE which matches the destination and the outgoing
16512 	 * queue in the cache table. All we need is an IRE_CACHE which
16513 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16514 	 * then it is enough to have some IRE_CACHE in the group.
16515 	 */
16516 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16517 		dst = ipif->ipif_pp_dst_addr;
16518 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16519 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16520 	if (ire == NULL) {
16521 		/*
16522 		 * Mark this packet to make it be delivered to
16523 		 * ip_rput_forward after the new ire has been
16524 		 * created.
16525 		 */
16526 		mp->b_prev = NULL;
16527 		mp->b_next = mp;
16528 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16529 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16530 	} else {
16531 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16532 		IRE_REFRELE(ire);
16533 	}
16534 }
16535 
16536 /* Update any source route, record route or timestamp options */
16537 static int
16538 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16539 {
16540 	ipoptp_t	opts;
16541 	uchar_t		*opt;
16542 	uint8_t		optval;
16543 	uint8_t		optlen;
16544 	ipaddr_t	dst;
16545 	uint32_t	ts;
16546 	ire_t		*dst_ire = NULL;
16547 	ire_t		*tmp_ire = NULL;
16548 	timestruc_t	now;
16549 
16550 	ip2dbg(("ip_rput_forward_options\n"));
16551 	dst = ipha->ipha_dst;
16552 	for (optval = ipoptp_first(&opts, ipha);
16553 	    optval != IPOPT_EOL;
16554 	    optval = ipoptp_next(&opts)) {
16555 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16556 		opt = opts.ipoptp_cur;
16557 		optlen = opts.ipoptp_len;
16558 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16559 		    optval, opts.ipoptp_len));
16560 		switch (optval) {
16561 			uint32_t off;
16562 		case IPOPT_SSRR:
16563 		case IPOPT_LSRR:
16564 			/* Check if adminstratively disabled */
16565 			if (!ip_forward_src_routed) {
16566 				if (ire->ire_stq != NULL) {
16567 					/*
16568 					 * Sent by forwarding path, and router
16569 					 * is global zone
16570 					 */
16571 					icmp_unreachable(ire->ire_stq, mp,
16572 					    ICMP_SOURCE_ROUTE_FAILED,
16573 					    GLOBAL_ZONEID);
16574 				} else {
16575 					ip0dbg(("ip_rput_forward_options: "
16576 					    "unable to send unreach\n"));
16577 					freemsg(mp);
16578 				}
16579 				return (-1);
16580 			}
16581 
16582 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16583 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16584 			if (dst_ire == NULL) {
16585 				/*
16586 				 * Must be partial since ip_rput_options
16587 				 * checked for strict.
16588 				 */
16589 				break;
16590 			}
16591 			off = opt[IPOPT_OFFSET];
16592 			off--;
16593 		redo_srr:
16594 			if (optlen < IP_ADDR_LEN ||
16595 			    off > optlen - IP_ADDR_LEN) {
16596 				/* End of source route */
16597 				ip1dbg((
16598 				    "ip_rput_forward_options: end of SR\n"));
16599 				ire_refrele(dst_ire);
16600 				break;
16601 			}
16602 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16603 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16604 			    IP_ADDR_LEN);
16605 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16606 			    ntohl(dst)));
16607 
16608 			/*
16609 			 * Check if our address is present more than
16610 			 * once as consecutive hops in source route.
16611 			 */
16612 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16613 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16614 			if (tmp_ire != NULL) {
16615 				ire_refrele(tmp_ire);
16616 				off += IP_ADDR_LEN;
16617 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16618 				goto redo_srr;
16619 			}
16620 			ipha->ipha_dst = dst;
16621 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16622 			ire_refrele(dst_ire);
16623 			break;
16624 		case IPOPT_RR:
16625 			off = opt[IPOPT_OFFSET];
16626 			off--;
16627 			if (optlen < IP_ADDR_LEN ||
16628 			    off > optlen - IP_ADDR_LEN) {
16629 				/* No more room - ignore */
16630 				ip1dbg((
16631 				    "ip_rput_forward_options: end of RR\n"));
16632 				break;
16633 			}
16634 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16635 			    IP_ADDR_LEN);
16636 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16637 			break;
16638 		case IPOPT_TS:
16639 			/* Insert timestamp if there is room */
16640 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16641 			case IPOPT_TS_TSONLY:
16642 				off = IPOPT_TS_TIMELEN;
16643 				break;
16644 			case IPOPT_TS_PRESPEC:
16645 			case IPOPT_TS_PRESPEC_RFC791:
16646 				/* Verify that the address matched */
16647 				off = opt[IPOPT_OFFSET] - 1;
16648 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16649 				dst_ire = ire_ctable_lookup(dst, 0,
16650 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16651 				    MATCH_IRE_TYPE);
16652 
16653 				if (dst_ire == NULL) {
16654 					/* Not for us */
16655 					break;
16656 				}
16657 				ire_refrele(dst_ire);
16658 				/* FALLTHRU */
16659 			case IPOPT_TS_TSANDADDR:
16660 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16661 				break;
16662 			default:
16663 				/*
16664 				 * ip_*put_options should have already
16665 				 * dropped this packet.
16666 				 */
16667 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16668 				    "unknown IT - bug in ip_rput_options?\n");
16669 				return (0);	/* Keep "lint" happy */
16670 			}
16671 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16672 				/* Increase overflow counter */
16673 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16674 				opt[IPOPT_POS_OV_FLG] =
16675 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16676 				    (off << 4));
16677 				break;
16678 			}
16679 			off = opt[IPOPT_OFFSET] - 1;
16680 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16681 			case IPOPT_TS_PRESPEC:
16682 			case IPOPT_TS_PRESPEC_RFC791:
16683 			case IPOPT_TS_TSANDADDR:
16684 				bcopy(&ire->ire_src_addr,
16685 				    (char *)opt + off, IP_ADDR_LEN);
16686 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16687 				/* FALLTHRU */
16688 			case IPOPT_TS_TSONLY:
16689 				off = opt[IPOPT_OFFSET] - 1;
16690 				/* Compute # of milliseconds since midnight */
16691 				gethrestime(&now);
16692 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16693 				    now.tv_nsec / (NANOSEC / MILLISEC);
16694 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16695 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16696 				break;
16697 			}
16698 			break;
16699 		}
16700 	}
16701 	return (0);
16702 }
16703 
16704 /*
16705  * This is called after processing at least one of AH/ESP headers.
16706  *
16707  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16708  * the actual, physical interface on which the packet was received,
16709  * but, when ip_strict_dst_multihoming is set to 1, could be the
16710  * interface which had the ipha_dst configured when the packet went
16711  * through ip_rput. The ill_index corresponding to the recv_ill
16712  * is saved in ipsec_in_rill_index
16713  */
16714 void
16715 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16716 {
16717 	mblk_t *mp;
16718 	ipaddr_t dst;
16719 	in6_addr_t *v6dstp;
16720 	ipha_t *ipha;
16721 	ip6_t *ip6h;
16722 	ipsec_in_t *ii;
16723 	boolean_t ill_need_rele = B_FALSE;
16724 	boolean_t rill_need_rele = B_FALSE;
16725 	boolean_t ire_need_rele = B_FALSE;
16726 
16727 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16728 	ASSERT(ii->ipsec_in_ill_index != 0);
16729 
16730 	mp = ipsec_mp->b_cont;
16731 	ASSERT(mp != NULL);
16732 
16733 
16734 	if (ill == NULL) {
16735 		ASSERT(recv_ill == NULL);
16736 		/*
16737 		 * We need to get the original queue on which ip_rput_local
16738 		 * or ip_rput_data_v6 was called.
16739 		 */
16740 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16741 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16742 		ill_need_rele = B_TRUE;
16743 
16744 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16745 			recv_ill = ill_lookup_on_ifindex(
16746 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16747 			    NULL, NULL, NULL, NULL);
16748 			rill_need_rele = B_TRUE;
16749 		} else {
16750 			recv_ill = ill;
16751 		}
16752 
16753 		if ((ill == NULL) || (recv_ill == NULL)) {
16754 			ip0dbg(("ip_fanout_proto_again: interface "
16755 			    "disappeared\n"));
16756 			if (ill != NULL)
16757 				ill_refrele(ill);
16758 			if (recv_ill != NULL)
16759 				ill_refrele(recv_ill);
16760 			freemsg(ipsec_mp);
16761 			return;
16762 		}
16763 	}
16764 
16765 	ASSERT(ill != NULL && recv_ill != NULL);
16766 
16767 	if (mp->b_datap->db_type == M_CTL) {
16768 		/*
16769 		 * AH/ESP is returning the ICMP message after
16770 		 * removing their headers. Fanout again till
16771 		 * it gets to the right protocol.
16772 		 */
16773 		if (ii->ipsec_in_v4) {
16774 			icmph_t *icmph;
16775 			int iph_hdr_length;
16776 			int hdr_length;
16777 
16778 			ipha = (ipha_t *)mp->b_rptr;
16779 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16780 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16781 			ipha = (ipha_t *)&icmph[1];
16782 			hdr_length = IPH_HDR_LENGTH(ipha);
16783 			/*
16784 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16785 			 * Reset the type to M_DATA.
16786 			 */
16787 			mp->b_datap->db_type = M_DATA;
16788 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16789 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16790 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16791 		} else {
16792 			icmp6_t *icmp6;
16793 			int hdr_length;
16794 
16795 			ip6h = (ip6_t *)mp->b_rptr;
16796 			/* Don't call hdr_length_v6() unless you have to. */
16797 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16798 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16799 			else
16800 				hdr_length = IPV6_HDR_LEN;
16801 
16802 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16803 			/*
16804 			 * icmp_inbound_error_fanout_v6 may need to do
16805 			 * pullupmsg.  Reset the type to M_DATA.
16806 			 */
16807 			mp->b_datap->db_type = M_DATA;
16808 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16809 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16810 		}
16811 		if (ill_need_rele)
16812 			ill_refrele(ill);
16813 		if (rill_need_rele)
16814 			ill_refrele(recv_ill);
16815 		return;
16816 	}
16817 
16818 	if (ii->ipsec_in_v4) {
16819 		ipha = (ipha_t *)mp->b_rptr;
16820 		dst = ipha->ipha_dst;
16821 		if (CLASSD(dst)) {
16822 			/*
16823 			 * Multicast has to be delivered to all streams.
16824 			 */
16825 			dst = INADDR_BROADCAST;
16826 		}
16827 
16828 		if (ire == NULL) {
16829 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16830 			    MBLK_GETLABEL(mp));
16831 			if (ire == NULL) {
16832 				if (ill_need_rele)
16833 					ill_refrele(ill);
16834 				if (rill_need_rele)
16835 					ill_refrele(recv_ill);
16836 				ip1dbg(("ip_fanout_proto_again: "
16837 				    "IRE not found"));
16838 				freemsg(ipsec_mp);
16839 				return;
16840 			}
16841 			ire_need_rele = B_TRUE;
16842 		}
16843 
16844 		switch (ipha->ipha_protocol) {
16845 			case IPPROTO_UDP:
16846 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16847 				    recv_ill);
16848 				if (ire_need_rele)
16849 					ire_refrele(ire);
16850 				break;
16851 			case IPPROTO_TCP:
16852 				if (!ire_need_rele)
16853 					IRE_REFHOLD(ire);
16854 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16855 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16856 				IRE_REFRELE(ire);
16857 				if (mp != NULL)
16858 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16859 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16860 				break;
16861 			case IPPROTO_SCTP:
16862 				if (!ire_need_rele)
16863 					IRE_REFHOLD(ire);
16864 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16865 				    ipsec_mp, 0, ill->ill_rq, dst);
16866 				break;
16867 			default:
16868 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16869 				    recv_ill);
16870 				if (ire_need_rele)
16871 					ire_refrele(ire);
16872 				break;
16873 		}
16874 	} else {
16875 		uint32_t rput_flags = 0;
16876 
16877 		ip6h = (ip6_t *)mp->b_rptr;
16878 		v6dstp = &ip6h->ip6_dst;
16879 		/*
16880 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16881 		 * address.
16882 		 *
16883 		 * Currently, we don't store that state in the IPSEC_IN
16884 		 * message, and we may need to.
16885 		 */
16886 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16887 		    IP6_IN_LLMCAST : 0);
16888 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16889 		    NULL, NULL);
16890 	}
16891 	if (ill_need_rele)
16892 		ill_refrele(ill);
16893 	if (rill_need_rele)
16894 		ill_refrele(recv_ill);
16895 }
16896 
16897 /*
16898  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16899  * returns 'true' if there are still fragments left on the queue, in
16900  * which case we restart the timer.
16901  */
16902 void
16903 ill_frag_timer(void *arg)
16904 {
16905 	ill_t	*ill = (ill_t *)arg;
16906 	boolean_t frag_pending;
16907 
16908 	mutex_enter(&ill->ill_lock);
16909 	ASSERT(!ill->ill_fragtimer_executing);
16910 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16911 		ill->ill_frag_timer_id = 0;
16912 		mutex_exit(&ill->ill_lock);
16913 		return;
16914 	}
16915 	ill->ill_fragtimer_executing = 1;
16916 	mutex_exit(&ill->ill_lock);
16917 
16918 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16919 
16920 	/*
16921 	 * Restart the timer, if we have fragments pending or if someone
16922 	 * wanted us to be scheduled again.
16923 	 */
16924 	mutex_enter(&ill->ill_lock);
16925 	ill->ill_fragtimer_executing = 0;
16926 	ill->ill_frag_timer_id = 0;
16927 	if (frag_pending || ill->ill_fragtimer_needrestart)
16928 		ill_frag_timer_start(ill);
16929 	mutex_exit(&ill->ill_lock);
16930 }
16931 
16932 void
16933 ill_frag_timer_start(ill_t *ill)
16934 {
16935 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16936 
16937 	/* If the ill is closing or opening don't proceed */
16938 	if (ill->ill_state_flags & ILL_CONDEMNED)
16939 		return;
16940 
16941 	if (ill->ill_fragtimer_executing) {
16942 		/*
16943 		 * ill_frag_timer is currently executing. Just record the
16944 		 * the fact that we want the timer to be restarted.
16945 		 * ill_frag_timer will post a timeout before it returns,
16946 		 * ensuring it will be called again.
16947 		 */
16948 		ill->ill_fragtimer_needrestart = 1;
16949 		return;
16950 	}
16951 
16952 	if (ill->ill_frag_timer_id == 0) {
16953 		/*
16954 		 * The timer is neither running nor is the timeout handler
16955 		 * executing. Post a timeout so that ill_frag_timer will be
16956 		 * called
16957 		 */
16958 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16959 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16960 		ill->ill_fragtimer_needrestart = 0;
16961 	}
16962 }
16963 
16964 /*
16965  * This routine is needed for loopback when forwarding multicasts.
16966  *
16967  * IPQoS Notes:
16968  * IPPF processing is done in fanout routines.
16969  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16970  * processing for IPSec packets is done when it comes back in clear.
16971  * NOTE : The callers of this function need to do the ire_refrele for the
16972  *	  ire that is being passed in.
16973  */
16974 void
16975 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16976     ill_t *recv_ill)
16977 {
16978 	ill_t	*ill = (ill_t *)q->q_ptr;
16979 	uint32_t	sum;
16980 	uint32_t	u1;
16981 	uint32_t	u2;
16982 	int		hdr_length;
16983 	boolean_t	mctl_present;
16984 	mblk_t		*first_mp = mp;
16985 	mblk_t		*hada_mp = NULL;
16986 	ipha_t		*inner_ipha;
16987 
16988 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16989 	    "ip_rput_locl_start: q %p", q);
16990 
16991 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16992 	ASSERT(ill != NULL);
16993 
16994 
16995 #define	rptr	((uchar_t *)ipha)
16996 #define	iphs	((uint16_t *)ipha)
16997 
16998 	/*
16999 	 * no UDP or TCP packet should come here anymore.
17000 	 */
17001 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
17002 	    (ipha->ipha_protocol != IPPROTO_UDP));
17003 
17004 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17005 	if (mctl_present &&
17006 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17007 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17008 
17009 		/*
17010 		 * It's an IPsec accelerated packet.
17011 		 * Keep a pointer to the data attributes around until
17012 		 * we allocate the ipsec_info_t.
17013 		 */
17014 		IPSECHW_DEBUG(IPSECHW_PKT,
17015 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17016 		hada_mp = first_mp;
17017 		hada_mp->b_cont = NULL;
17018 		/*
17019 		 * Since it is accelerated, it comes directly from
17020 		 * the ill and the data attributes is followed by
17021 		 * the packet data.
17022 		 */
17023 		ASSERT(mp->b_datap->db_type != M_CTL);
17024 		first_mp = mp;
17025 		mctl_present = B_FALSE;
17026 	}
17027 
17028 	/*
17029 	 * IF M_CTL is not present, then ipsec_in_is_secure
17030 	 * should return B_TRUE. There is a case where loopback
17031 	 * packets has an M_CTL in the front with all the
17032 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
17033 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17034 	 * packets never comes here, it is safe to ASSERT the
17035 	 * following.
17036 	 */
17037 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17038 
17039 
17040 	/* u1 is # words of IP options */
17041 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
17042 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17043 
17044 	if (u1) {
17045 		if (!ip_options_cksum(q, ill, mp, ipha, ire)) {
17046 			if (hada_mp != NULL)
17047 				freemsg(hada_mp);
17048 			return;
17049 		}
17050 	} else {
17051 		/* Check the IP header checksum.  */
17052 #define	uph	((uint16_t *)ipha)
17053 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17054 		    uph[6] + uph[7] + uph[8] + uph[9];
17055 #undef  uph
17056 		/* finish doing IP checksum */
17057 		sum = (sum & 0xFFFF) + (sum >> 16);
17058 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17059 		/*
17060 		 * Don't verify header checksum if this packet is coming
17061 		 * back from AH/ESP as we already did it.
17062 		 */
17063 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17064 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17065 			goto drop_pkt;
17066 		}
17067 	}
17068 
17069 	/*
17070 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17071 	 * might be called more than once for secure packets, count only
17072 	 * the first time.
17073 	 */
17074 	if (!mctl_present) {
17075 		UPDATE_IB_PKT_COUNT(ire);
17076 		ire->ire_last_used_time = lbolt;
17077 	}
17078 
17079 	/* Check for fragmentation offset. */
17080 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17081 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17082 	if (u1) {
17083 		/*
17084 		 * We re-assemble fragments before we do the AH/ESP
17085 		 * processing. Thus, M_CTL should not be present
17086 		 * while we are re-assembling.
17087 		 */
17088 		ASSERT(!mctl_present);
17089 		ASSERT(first_mp == mp);
17090 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17091 			return;
17092 		}
17093 		/*
17094 		 * Make sure that first_mp points back to mp as
17095 		 * the mp we came in with could have changed in
17096 		 * ip_rput_fragment().
17097 		 */
17098 		ipha = (ipha_t *)mp->b_rptr;
17099 		first_mp = mp;
17100 	}
17101 
17102 	/*
17103 	 * Clear hardware checksumming flag as it is currently only
17104 	 * used by TCP and UDP.
17105 	 */
17106 	DB_CKSUMFLAGS(mp) = 0;
17107 
17108 	/* Now we have a complete datagram, destined for this machine. */
17109 	u1 = IPH_HDR_LENGTH(ipha);
17110 	switch (ipha->ipha_protocol) {
17111 	case IPPROTO_ICMP: {
17112 		ire_t		*ire_zone;
17113 		ilm_t		*ilm;
17114 		mblk_t		*mp1;
17115 		zoneid_t	last_zoneid;
17116 
17117 		if (CLASSD(ipha->ipha_dst) &&
17118 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17119 			ASSERT(ire->ire_type == IRE_BROADCAST);
17120 			/*
17121 			 * In the multicast case, applications may have joined
17122 			 * the group from different zones, so we need to deliver
17123 			 * the packet to each of them. Loop through the
17124 			 * multicast memberships structures (ilm) on the receive
17125 			 * ill and send a copy of the packet up each matching
17126 			 * one. However, we don't do this for multicasts sent on
17127 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17128 			 * they must stay in the sender's zone.
17129 			 *
17130 			 * ilm_add_v6() ensures that ilms in the same zone are
17131 			 * contiguous in the ill_ilm list. We use this property
17132 			 * to avoid sending duplicates needed when two
17133 			 * applications in the same zone join the same group on
17134 			 * different logical interfaces: we ignore the ilm if
17135 			 * its zoneid is the same as the last matching one.
17136 			 * In addition, the sending of the packet for
17137 			 * ire_zoneid is delayed until all of the other ilms
17138 			 * have been exhausted.
17139 			 */
17140 			last_zoneid = -1;
17141 			ILM_WALKER_HOLD(recv_ill);
17142 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17143 			    ilm = ilm->ilm_next) {
17144 				if ((ilm->ilm_flags & ILM_DELETED) ||
17145 				    ipha->ipha_dst != ilm->ilm_addr ||
17146 				    ilm->ilm_zoneid == last_zoneid ||
17147 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17148 				    ilm->ilm_zoneid == ALL_ZONES ||
17149 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17150 					continue;
17151 				mp1 = ip_copymsg(first_mp);
17152 				if (mp1 == NULL)
17153 					continue;
17154 				icmp_inbound(q, mp1, B_TRUE, ill,
17155 				    0, sum, mctl_present, B_TRUE,
17156 				    recv_ill, ilm->ilm_zoneid);
17157 				last_zoneid = ilm->ilm_zoneid;
17158 			}
17159 			ILM_WALKER_RELE(recv_ill);
17160 		} else if (ire->ire_type == IRE_BROADCAST) {
17161 			/*
17162 			 * In the broadcast case, there may be many zones
17163 			 * which need a copy of the packet delivered to them.
17164 			 * There is one IRE_BROADCAST per broadcast address
17165 			 * and per zone; we walk those using a helper function.
17166 			 * In addition, the sending of the packet for ire is
17167 			 * delayed until all of the other ires have been
17168 			 * processed.
17169 			 */
17170 			IRB_REFHOLD(ire->ire_bucket);
17171 			ire_zone = NULL;
17172 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17173 			    ire)) != NULL) {
17174 				mp1 = ip_copymsg(first_mp);
17175 				if (mp1 == NULL)
17176 					continue;
17177 
17178 				UPDATE_IB_PKT_COUNT(ire_zone);
17179 				ire_zone->ire_last_used_time = lbolt;
17180 				icmp_inbound(q, mp1, B_TRUE, ill,
17181 				    0, sum, mctl_present, B_TRUE,
17182 				    recv_ill, ire_zone->ire_zoneid);
17183 			}
17184 			IRB_REFRELE(ire->ire_bucket);
17185 		}
17186 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17187 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17188 		    ire->ire_zoneid);
17189 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17190 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17191 		return;
17192 	}
17193 	case IPPROTO_IGMP:
17194 		/*
17195 		 * If we are not willing to accept IGMP packets in clear,
17196 		 * then check with global policy.
17197 		 */
17198 		if (igmp_accept_clear_messages == 0) {
17199 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17200 			    ipha, NULL, mctl_present);
17201 			if (first_mp == NULL)
17202 				return;
17203 		}
17204 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17205 			freemsg(first_mp);
17206 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17207 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17208 			return;
17209 		}
17210 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17211 			/* Bad packet - discarded by igmp_input */
17212 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17213 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17214 			if (mctl_present)
17215 				freeb(first_mp);
17216 			return;
17217 		}
17218 		/*
17219 		 * igmp_input() may have returned the pulled up message.
17220 		 * So first_mp and ipha need to be reinitialized.
17221 		 */
17222 		ipha = (ipha_t *)mp->b_rptr;
17223 		if (mctl_present)
17224 			first_mp->b_cont = mp;
17225 		else
17226 			first_mp = mp;
17227 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17228 			/* No user-level listener for IGMP packets */
17229 			goto drop_pkt;
17230 		}
17231 		/* deliver to local raw users */
17232 		break;
17233 	case IPPROTO_PIM:
17234 		/*
17235 		 * If we are not willing to accept PIM packets in clear,
17236 		 * then check with global policy.
17237 		 */
17238 		if (pim_accept_clear_messages == 0) {
17239 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17240 			    ipha, NULL, mctl_present);
17241 			if (first_mp == NULL)
17242 				return;
17243 		}
17244 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17245 			freemsg(first_mp);
17246 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17247 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17248 			return;
17249 		}
17250 		if (pim_input(q, mp) != 0) {
17251 			/* Bad packet - discarded by pim_input */
17252 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17253 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17254 			if (mctl_present)
17255 				freeb(first_mp);
17256 			return;
17257 		}
17258 
17259 		/*
17260 		 * pim_input() may have pulled up the message so ipha needs to
17261 		 * be reinitialized.
17262 		 */
17263 		ipha = (ipha_t *)mp->b_rptr;
17264 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17265 			/* No user-level listener for PIM packets */
17266 			goto drop_pkt;
17267 		}
17268 		/* deliver to local raw users */
17269 		break;
17270 	case IPPROTO_ENCAP:
17271 		/*
17272 		 * Handle self-encapsulated packets (IP-in-IP where
17273 		 * the inner addresses == the outer addresses).
17274 		 */
17275 		hdr_length = IPH_HDR_LENGTH(ipha);
17276 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17277 		    mp->b_wptr) {
17278 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17279 			    sizeof (ipha_t) - mp->b_rptr)) {
17280 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17281 				freemsg(first_mp);
17282 				return;
17283 			}
17284 			ipha = (ipha_t *)mp->b_rptr;
17285 		}
17286 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17287 		/*
17288 		 * Check the sanity of the inner IP header.
17289 		 */
17290 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17291 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17292 			freemsg(first_mp);
17293 			return;
17294 		}
17295 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17296 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17297 			freemsg(first_mp);
17298 			return;
17299 		}
17300 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17301 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17302 			ipsec_in_t *ii;
17303 
17304 			/*
17305 			 * Self-encapsulated tunnel packet. Remove
17306 			 * the outer IP header and fanout again.
17307 			 * We also need to make sure that the inner
17308 			 * header is pulled up until options.
17309 			 */
17310 			mp->b_rptr = (uchar_t *)inner_ipha;
17311 			ipha = inner_ipha;
17312 			hdr_length = IPH_HDR_LENGTH(ipha);
17313 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17314 				if (!pullupmsg(mp, (uchar_t *)ipha +
17315 				    + hdr_length - mp->b_rptr)) {
17316 					freemsg(first_mp);
17317 					return;
17318 				}
17319 				ipha = (ipha_t *)mp->b_rptr;
17320 			}
17321 			if (!mctl_present) {
17322 				ASSERT(first_mp == mp);
17323 				/*
17324 				 * This means that somebody is sending
17325 				 * Self-encapsualted packets without AH/ESP.
17326 				 * If AH/ESP was present, we would have already
17327 				 * allocated the first_mp.
17328 				 */
17329 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
17330 				    NULL) {
17331 					ip1dbg(("ip_proto_input: IPSEC_IN "
17332 					    "allocation failure.\n"));
17333 					BUMP_MIB(ill->ill_ip_mib,
17334 					    ipIfStatsInDiscards);
17335 					freemsg(mp);
17336 					return;
17337 				}
17338 				first_mp->b_cont = mp;
17339 			}
17340 			/*
17341 			 * We generally store the ill_index if we need to
17342 			 * do IPSEC processing as we lose the ill queue when
17343 			 * we come back. But in this case, we never should
17344 			 * have to store the ill_index here as it should have
17345 			 * been stored previously when we processed the
17346 			 * AH/ESP header in this routine or for non-ipsec
17347 			 * cases, we still have the queue. But for some bad
17348 			 * packets from the wire, we can get to IPSEC after
17349 			 * this and we better store the index for that case.
17350 			 */
17351 			ill = (ill_t *)q->q_ptr;
17352 			ii = (ipsec_in_t *)first_mp->b_rptr;
17353 			ii->ipsec_in_ill_index =
17354 			    ill->ill_phyint->phyint_ifindex;
17355 			ii->ipsec_in_rill_index =
17356 			    recv_ill->ill_phyint->phyint_ifindex;
17357 			if (ii->ipsec_in_decaps) {
17358 				/*
17359 				 * This packet is self-encapsulated multiple
17360 				 * times. We don't want to recurse infinitely.
17361 				 * To keep it simple, drop the packet.
17362 				 */
17363 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17364 				freemsg(first_mp);
17365 				return;
17366 			}
17367 			ii->ipsec_in_decaps = B_TRUE;
17368 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17369 			    ire);
17370 			return;
17371 		}
17372 		break;
17373 	case IPPROTO_AH:
17374 	case IPPROTO_ESP: {
17375 		/*
17376 		 * Fast path for AH/ESP. If this is the first time
17377 		 * we are sending a datagram to AH/ESP, allocate
17378 		 * a IPSEC_IN message and prepend it. Otherwise,
17379 		 * just fanout.
17380 		 */
17381 
17382 		int ipsec_rc;
17383 		ipsec_in_t *ii;
17384 
17385 		IP_STAT(ipsec_proto_ahesp);
17386 		if (!mctl_present) {
17387 			ASSERT(first_mp == mp);
17388 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
17389 				ip1dbg(("ip_proto_input: IPSEC_IN "
17390 				    "allocation failure.\n"));
17391 				freemsg(hada_mp); /* okay ifnull */
17392 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17393 				freemsg(mp);
17394 				return;
17395 			}
17396 			/*
17397 			 * Store the ill_index so that when we come back
17398 			 * from IPSEC we ride on the same queue.
17399 			 */
17400 			ill = (ill_t *)q->q_ptr;
17401 			ii = (ipsec_in_t *)first_mp->b_rptr;
17402 			ii->ipsec_in_ill_index =
17403 			    ill->ill_phyint->phyint_ifindex;
17404 			ii->ipsec_in_rill_index =
17405 			    recv_ill->ill_phyint->phyint_ifindex;
17406 			first_mp->b_cont = mp;
17407 			/*
17408 			 * Cache hardware acceleration info.
17409 			 */
17410 			if (hada_mp != NULL) {
17411 				IPSECHW_DEBUG(IPSECHW_PKT,
17412 				    ("ip_rput_local: caching data attr.\n"));
17413 				ii->ipsec_in_accelerated = B_TRUE;
17414 				ii->ipsec_in_da = hada_mp;
17415 				hada_mp = NULL;
17416 			}
17417 		} else {
17418 			ii = (ipsec_in_t *)first_mp->b_rptr;
17419 		}
17420 
17421 		if (!ipsec_loaded()) {
17422 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17423 			    ire->ire_zoneid);
17424 			return;
17425 		}
17426 
17427 		/* select inbound SA and have IPsec process the pkt */
17428 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17429 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17430 			if (esph == NULL)
17431 				return;
17432 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17433 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17434 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17435 			    first_mp, esph);
17436 		} else {
17437 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17438 			if (ah == NULL)
17439 				return;
17440 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17441 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17442 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17443 			    first_mp, ah);
17444 		}
17445 
17446 		switch (ipsec_rc) {
17447 		case IPSEC_STATUS_SUCCESS:
17448 			break;
17449 		case IPSEC_STATUS_FAILED:
17450 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17451 			/* FALLTHRU */
17452 		case IPSEC_STATUS_PENDING:
17453 			return;
17454 		}
17455 		/* we're done with IPsec processing, send it up */
17456 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17457 		return;
17458 	}
17459 	default:
17460 		break;
17461 	}
17462 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17463 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17464 		    ire->ire_zoneid));
17465 		goto drop_pkt;
17466 	}
17467 	/*
17468 	 * Handle protocols with which IP is less intimate.  There
17469 	 * can be more than one stream bound to a particular
17470 	 * protocol.  When this is the case, each one gets a copy
17471 	 * of any incoming packets.
17472 	 */
17473 	ip_fanout_proto(q, first_mp, ill, ipha,
17474 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17475 	    B_TRUE, recv_ill, ire->ire_zoneid);
17476 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17477 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17478 	return;
17479 
17480 drop_pkt:
17481 	freemsg(first_mp);
17482 	if (hada_mp != NULL)
17483 		freeb(hada_mp);
17484 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17485 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17486 #undef	rptr
17487 #undef  iphs
17488 
17489 }
17490 
17491 /*
17492  * Update any source route, record route or timestamp options.
17493  * Check that we are at end of strict source route.
17494  * The options have already been checked for sanity in ip_rput_options().
17495  */
17496 static boolean_t
17497 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17498 {
17499 	ipoptp_t	opts;
17500 	uchar_t		*opt;
17501 	uint8_t		optval;
17502 	uint8_t		optlen;
17503 	ipaddr_t	dst;
17504 	uint32_t	ts;
17505 	ire_t		*dst_ire;
17506 	timestruc_t	now;
17507 	zoneid_t	zoneid;
17508 	ill_t		*ill;
17509 
17510 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17511 
17512 	ip2dbg(("ip_rput_local_options\n"));
17513 
17514 	for (optval = ipoptp_first(&opts, ipha);
17515 	    optval != IPOPT_EOL;
17516 	    optval = ipoptp_next(&opts)) {
17517 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17518 		opt = opts.ipoptp_cur;
17519 		optlen = opts.ipoptp_len;
17520 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17521 		    optval, optlen));
17522 		switch (optval) {
17523 			uint32_t off;
17524 		case IPOPT_SSRR:
17525 		case IPOPT_LSRR:
17526 			off = opt[IPOPT_OFFSET];
17527 			off--;
17528 			if (optlen < IP_ADDR_LEN ||
17529 			    off > optlen - IP_ADDR_LEN) {
17530 				/* End of source route */
17531 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17532 				break;
17533 			}
17534 			/*
17535 			 * This will only happen if two consecutive entries
17536 			 * in the source route contains our address or if
17537 			 * it is a packet with a loose source route which
17538 			 * reaches us before consuming the whole source route
17539 			 */
17540 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17541 			if (optval == IPOPT_SSRR) {
17542 				goto bad_src_route;
17543 			}
17544 			/*
17545 			 * Hack: instead of dropping the packet truncate the
17546 			 * source route to what has been used by filling the
17547 			 * rest with IPOPT_NOP.
17548 			 */
17549 			opt[IPOPT_OLEN] = (uint8_t)off;
17550 			while (off < optlen) {
17551 				opt[off++] = IPOPT_NOP;
17552 			}
17553 			break;
17554 		case IPOPT_RR:
17555 			off = opt[IPOPT_OFFSET];
17556 			off--;
17557 			if (optlen < IP_ADDR_LEN ||
17558 			    off > optlen - IP_ADDR_LEN) {
17559 				/* No more room - ignore */
17560 				ip1dbg((
17561 				    "ip_rput_local_options: end of RR\n"));
17562 				break;
17563 			}
17564 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17565 			    IP_ADDR_LEN);
17566 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17567 			break;
17568 		case IPOPT_TS:
17569 			/* Insert timestamp if there is romm */
17570 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17571 			case IPOPT_TS_TSONLY:
17572 				off = IPOPT_TS_TIMELEN;
17573 				break;
17574 			case IPOPT_TS_PRESPEC:
17575 			case IPOPT_TS_PRESPEC_RFC791:
17576 				/* Verify that the address matched */
17577 				off = opt[IPOPT_OFFSET] - 1;
17578 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17579 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17580 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17581 				if (dst_ire == NULL) {
17582 					/* Not for us */
17583 					break;
17584 				}
17585 				ire_refrele(dst_ire);
17586 				/* FALLTHRU */
17587 			case IPOPT_TS_TSANDADDR:
17588 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17589 				break;
17590 			default:
17591 				/*
17592 				 * ip_*put_options should have already
17593 				 * dropped this packet.
17594 				 */
17595 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17596 				    "unknown IT - bug in ip_rput_options?\n");
17597 				return (B_TRUE);	/* Keep "lint" happy */
17598 			}
17599 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17600 				/* Increase overflow counter */
17601 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17602 				opt[IPOPT_POS_OV_FLG] =
17603 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17604 				    (off << 4));
17605 				break;
17606 			}
17607 			off = opt[IPOPT_OFFSET] - 1;
17608 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17609 			case IPOPT_TS_PRESPEC:
17610 			case IPOPT_TS_PRESPEC_RFC791:
17611 			case IPOPT_TS_TSANDADDR:
17612 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17613 				    IP_ADDR_LEN);
17614 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17615 				/* FALLTHRU */
17616 			case IPOPT_TS_TSONLY:
17617 				off = opt[IPOPT_OFFSET] - 1;
17618 				/* Compute # of milliseconds since midnight */
17619 				gethrestime(&now);
17620 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17621 				    now.tv_nsec / (NANOSEC / MILLISEC);
17622 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17623 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17624 				break;
17625 			}
17626 			break;
17627 		}
17628 	}
17629 	return (B_TRUE);
17630 
17631 bad_src_route:
17632 	q = WR(q);
17633 	if (q->q_next != NULL)
17634 		ill = q->q_ptr;
17635 	else
17636 		ill = NULL;
17637 
17638 	/* make sure we clear any indication of a hardware checksum */
17639 	DB_CKSUMFLAGS(mp) = 0;
17640 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill);
17641 	if (zoneid == ALL_ZONES)
17642 		freemsg(mp);
17643 	else
17644 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17645 	return (B_FALSE);
17646 
17647 }
17648 
17649 /*
17650  * Process IP options in an inbound packet.  If an option affects the
17651  * effective destination address, return the next hop address via dstp.
17652  * Returns -1 if something fails in which case an ICMP error has been sent
17653  * and mp freed.
17654  */
17655 static int
17656 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17657 {
17658 	ipoptp_t	opts;
17659 	uchar_t		*opt;
17660 	uint8_t		optval;
17661 	uint8_t		optlen;
17662 	ipaddr_t	dst;
17663 	intptr_t	code = 0;
17664 	ire_t		*ire = NULL;
17665 	zoneid_t	zoneid;
17666 	ill_t		*ill;
17667 
17668 	ip2dbg(("ip_rput_options\n"));
17669 	dst = ipha->ipha_dst;
17670 	for (optval = ipoptp_first(&opts, ipha);
17671 	    optval != IPOPT_EOL;
17672 	    optval = ipoptp_next(&opts)) {
17673 		opt = opts.ipoptp_cur;
17674 		optlen = opts.ipoptp_len;
17675 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17676 		    optval, optlen));
17677 		/*
17678 		 * Note: we need to verify the checksum before we
17679 		 * modify anything thus this routine only extracts the next
17680 		 * hop dst from any source route.
17681 		 */
17682 		switch (optval) {
17683 			uint32_t off;
17684 		case IPOPT_SSRR:
17685 		case IPOPT_LSRR:
17686 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17687 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17688 			if (ire == NULL) {
17689 				if (optval == IPOPT_SSRR) {
17690 					ip1dbg(("ip_rput_options: not next"
17691 					    " strict source route 0x%x\n",
17692 					    ntohl(dst)));
17693 					code = (char *)&ipha->ipha_dst -
17694 					    (char *)ipha;
17695 					goto param_prob; /* RouterReq's */
17696 				}
17697 				ip2dbg(("ip_rput_options: "
17698 				    "not next source route 0x%x\n",
17699 				    ntohl(dst)));
17700 				break;
17701 			}
17702 			ire_refrele(ire);
17703 
17704 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17705 				ip1dbg((
17706 				    "ip_rput_options: bad option offset\n"));
17707 				code = (char *)&opt[IPOPT_OLEN] -
17708 				    (char *)ipha;
17709 				goto param_prob;
17710 			}
17711 			off = opt[IPOPT_OFFSET];
17712 			off--;
17713 		redo_srr:
17714 			if (optlen < IP_ADDR_LEN ||
17715 			    off > optlen - IP_ADDR_LEN) {
17716 				/* End of source route */
17717 				ip1dbg(("ip_rput_options: end of SR\n"));
17718 				break;
17719 			}
17720 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17721 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17722 			    ntohl(dst)));
17723 
17724 			/*
17725 			 * Check if our address is present more than
17726 			 * once as consecutive hops in source route.
17727 			 * XXX verify per-interface ip_forwarding
17728 			 * for source route?
17729 			 */
17730 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17731 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17732 
17733 			if (ire != NULL) {
17734 				ire_refrele(ire);
17735 				off += IP_ADDR_LEN;
17736 				goto redo_srr;
17737 			}
17738 
17739 			if (dst == htonl(INADDR_LOOPBACK)) {
17740 				ip1dbg(("ip_rput_options: loopback addr in "
17741 				    "source route!\n"));
17742 				goto bad_src_route;
17743 			}
17744 			/*
17745 			 * For strict: verify that dst is directly
17746 			 * reachable.
17747 			 */
17748 			if (optval == IPOPT_SSRR) {
17749 				ire = ire_ftable_lookup(dst, 0, 0,
17750 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17751 				    MBLK_GETLABEL(mp),
17752 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17753 				if (ire == NULL) {
17754 					ip1dbg(("ip_rput_options: SSRR not "
17755 					    "directly reachable: 0x%x\n",
17756 					    ntohl(dst)));
17757 					goto bad_src_route;
17758 				}
17759 				ire_refrele(ire);
17760 			}
17761 			/*
17762 			 * Defer update of the offset and the record route
17763 			 * until the packet is forwarded.
17764 			 */
17765 			break;
17766 		case IPOPT_RR:
17767 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17768 				ip1dbg((
17769 				    "ip_rput_options: bad option offset\n"));
17770 				code = (char *)&opt[IPOPT_OLEN] -
17771 				    (char *)ipha;
17772 				goto param_prob;
17773 			}
17774 			break;
17775 		case IPOPT_TS:
17776 			/*
17777 			 * Verify that length >= 5 and that there is either
17778 			 * room for another timestamp or that the overflow
17779 			 * counter is not maxed out.
17780 			 */
17781 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17782 			if (optlen < IPOPT_MINLEN_IT) {
17783 				goto param_prob;
17784 			}
17785 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17786 				ip1dbg((
17787 				    "ip_rput_options: bad option offset\n"));
17788 				code = (char *)&opt[IPOPT_OFFSET] -
17789 				    (char *)ipha;
17790 				goto param_prob;
17791 			}
17792 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17793 			case IPOPT_TS_TSONLY:
17794 				off = IPOPT_TS_TIMELEN;
17795 				break;
17796 			case IPOPT_TS_TSANDADDR:
17797 			case IPOPT_TS_PRESPEC:
17798 			case IPOPT_TS_PRESPEC_RFC791:
17799 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17800 				break;
17801 			default:
17802 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17803 				    (char *)ipha;
17804 				goto param_prob;
17805 			}
17806 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17807 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17808 				/*
17809 				 * No room and the overflow counter is 15
17810 				 * already.
17811 				 */
17812 				goto param_prob;
17813 			}
17814 			break;
17815 		}
17816 	}
17817 
17818 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17819 		*dstp = dst;
17820 		return (0);
17821 	}
17822 
17823 	ip1dbg(("ip_rput_options: error processing IP options."));
17824 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17825 
17826 param_prob:
17827 	q = WR(q);
17828 	if (q->q_next != NULL)
17829 		ill = q->q_ptr;
17830 	else
17831 		ill = NULL;
17832 
17833 	/* make sure we clear any indication of a hardware checksum */
17834 	DB_CKSUMFLAGS(mp) = 0;
17835 	/* Don't know whether this is for non-global or global/forwarding */
17836 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17837 	if (zoneid == ALL_ZONES)
17838 		freemsg(mp);
17839 	else
17840 		icmp_param_problem(q, mp, (uint8_t)code, zoneid);
17841 	return (-1);
17842 
17843 bad_src_route:
17844 	q = WR(q);
17845 	if (q->q_next != NULL)
17846 		ill = q->q_ptr;
17847 	else
17848 		ill = NULL;
17849 
17850 	/* make sure we clear any indication of a hardware checksum */
17851 	DB_CKSUMFLAGS(mp) = 0;
17852 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17853 	if (zoneid == ALL_ZONES)
17854 		freemsg(mp);
17855 	else
17856 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17857 	return (-1);
17858 }
17859 
17860 /*
17861  * IP & ICMP info in >=14 msg's ...
17862  *  - ip fixed part (mib2_ip_t)
17863  *  - icmp fixed part (mib2_icmp_t)
17864  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17865  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17866  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17867  *  - ipRouteAttributeTable (ip 102)	labeled routes
17868  *  - ip multicast membership (ip_member_t)
17869  *  - ip multicast source filtering (ip_grpsrc_t)
17870  *  - igmp fixed part (struct igmpstat)
17871  *  - multicast routing stats (struct mrtstat)
17872  *  - multicast routing vifs (array of struct vifctl)
17873  *  - multicast routing routes (array of struct mfcctl)
17874  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17875  *					One per ill plus one generic
17876  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17877  *					One per ill plus one generic
17878  *  - ipv6RouteEntry			all IPv6 IREs
17879  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17880  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17881  *  - ipv6AddrEntry			all IPv6 ipifs
17882  *  - ipv6 multicast membership (ipv6_member_t)
17883  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17884  *
17885  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17886  *
17887  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17888  * already filled in by the caller.
17889  * Return value of 0 indicates that no messages were sent and caller
17890  * should free mpctl.
17891  */
17892 int
17893 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17894 {
17895 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17896 		return (0);
17897 	}
17898 
17899 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl)) == NULL) {
17900 		return (1);
17901 	}
17902 
17903 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17904 		return (1);
17905 	}
17906 
17907 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17908 		return (1);
17909 	}
17910 
17911 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17912 		return (1);
17913 	}
17914 
17915 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17916 		return (1);
17917 	}
17918 
17919 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17920 		return (1);
17921 	}
17922 
17923 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17924 		return (1);
17925 	}
17926 
17927 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17928 		return (1);
17929 	}
17930 
17931 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17932 		return (1);
17933 	}
17934 
17935 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17936 		return (1);
17937 	}
17938 
17939 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17940 		return (1);
17941 	}
17942 
17943 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17944 		return (1);
17945 	}
17946 
17947 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17948 		return (1);
17949 	}
17950 
17951 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17952 		return (1);
17953 	}
17954 
17955 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17956 		return (1);
17957 	}
17958 
17959 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17960 		return (1);
17961 	}
17962 
17963 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17964 		return (1);
17965 	}
17966 	freemsg(mpctl);
17967 	return (1);
17968 }
17969 
17970 
17971 /* Get global (legacy) IPv4 statistics */
17972 static mblk_t *
17973 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib)
17974 {
17975 	mib2_ip_t		old_ip_mib;
17976 	struct opthdr		*optp;
17977 	mblk_t			*mp2ctl;
17978 
17979 	/*
17980 	 * make a copy of the original message
17981 	 */
17982 	mp2ctl = copymsg(mpctl);
17983 
17984 	/* fixed length IP structure... */
17985 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17986 	optp->level = MIB2_IP;
17987 	optp->name = 0;
17988 	SET_MIB(old_ip_mib.ipForwarding,
17989 	    (WE_ARE_FORWARDING ? 1 : 2));
17990 	SET_MIB(old_ip_mib.ipDefaultTTL,
17991 	    (uint32_t)ip_def_ttl);
17992 	SET_MIB(old_ip_mib.ipReasmTimeout,
17993 	    ip_g_frag_timeout);
17994 	SET_MIB(old_ip_mib.ipAddrEntrySize,
17995 	    sizeof (mib2_ipAddrEntry_t));
17996 	SET_MIB(old_ip_mib.ipRouteEntrySize,
17997 	    sizeof (mib2_ipRouteEntry_t));
17998 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
17999 	    sizeof (mib2_ipNetToMediaEntry_t));
18000 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18001 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18002 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18003 	    sizeof (mib2_ipAttributeEntry_t));
18004 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18005 
18006 	/*
18007 	 * Grab the statistics from the new IP MIB
18008 	 */
18009 	SET_MIB(old_ip_mib.ipInReceives,
18010 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18011 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18012 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18013 	SET_MIB(old_ip_mib.ipForwDatagrams,
18014 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18015 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18016 	    ipmib->ipIfStatsInUnknownProtos);
18017 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18018 	SET_MIB(old_ip_mib.ipInDelivers,
18019 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18020 	SET_MIB(old_ip_mib.ipOutRequests,
18021 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18022 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18023 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18024 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18025 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18026 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18027 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18028 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18029 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18030 
18031 	/* ipRoutingDiscards is not being used */
18032 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18033 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18034 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18035 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18036 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18037 	    ipmib->ipIfStatsReasmDuplicates);
18038 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18039 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18040 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18041 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18042 	SET_MIB(old_ip_mib.rawipInOverflows,
18043 	    ipmib->rawipIfStatsInOverflows);
18044 
18045 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18046 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18047 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18048 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18049 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18050 	    ipmib->ipIfStatsOutSwitchIPVersion);
18051 
18052 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18053 	    (int)sizeof (old_ip_mib))) {
18054 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18055 		    (uint_t)sizeof (old_ip_mib)));
18056 	}
18057 
18058 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18059 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18060 	    (int)optp->level, (int)optp->name, (int)optp->len));
18061 	qreply(q, mpctl);
18062 	return (mp2ctl);
18063 }
18064 
18065 /* Per interface IPv4 statistics */
18066 static mblk_t *
18067 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl)
18068 {
18069 	struct opthdr		*optp;
18070 	mblk_t			*mp2ctl;
18071 	ill_t			*ill;
18072 	ill_walk_context_t	ctx;
18073 	mblk_t			*mp_tail = NULL;
18074 	mib2_ipIfStatsEntry_t	global_ip_mib;
18075 
18076 	/*
18077 	 * Make a copy of the original message
18078 	 */
18079 	mp2ctl = copymsg(mpctl);
18080 
18081 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18082 	optp->level = MIB2_IP;
18083 	optp->name = MIB2_IP_TRAFFIC_STATS;
18084 	/* Include "unknown interface" ip_mib */
18085 	ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18086 	ip_mib.ipIfStatsIfIndex = MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18087 	SET_MIB(ip_mib.ipIfStatsForwarding, (WE_ARE_FORWARDING ? 1 : 2));
18088 	SET_MIB(ip_mib.ipIfStatsDefaultTTL, (uint32_t)ip_def_ttl);
18089 	SET_MIB(ip_mib.ipIfStatsEntrySize, sizeof (mib2_ipIfStatsEntry_t));
18090 	SET_MIB(ip_mib.ipIfStatsAddrEntrySize, sizeof (mib2_ipAddrEntry_t));
18091 	SET_MIB(ip_mib.ipIfStatsRouteEntrySize, sizeof (mib2_ipRouteEntry_t));
18092 	SET_MIB(ip_mib.ipIfStatsNetToMediaEntrySize,
18093 	    sizeof (mib2_ipNetToMediaEntry_t));
18094 	SET_MIB(ip_mib.ipIfStatsMemberEntrySize, sizeof (ip_member_t));
18095 	SET_MIB(ip_mib.ipIfStatsGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18096 
18097 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip_mib,
18098 	    (int)sizeof (ip_mib))) {
18099 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18100 		    "failed to allocate %u bytes\n",
18101 		    (uint_t)sizeof (ip_mib)));
18102 	}
18103 
18104 	bcopy(&ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18105 
18106 	rw_enter(&ill_g_lock, RW_READER);
18107 	ill = ILL_START_WALK_V4(&ctx);
18108 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18109 		ill->ill_ip_mib->ipIfStatsIfIndex =
18110 		    ill->ill_phyint->phyint_ifindex;
18111 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18112 		    (WE_ARE_FORWARDING ? 1 : 2));
18113 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18114 		    (uint32_t)ip_def_ttl);
18115 
18116 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18117 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18118 		    (char *)ill->ill_ip_mib,
18119 		    (int)sizeof (*ill->ill_ip_mib))) {
18120 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18121 			    "failed to allocate %u bytes\n",
18122 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18123 		}
18124 	}
18125 	rw_exit(&ill_g_lock);
18126 
18127 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18128 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18129 	    "level %d, name %d, len %d\n",
18130 	    (int)optp->level, (int)optp->name, (int)optp->len));
18131 	qreply(q, mpctl);
18132 
18133 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib));
18134 }
18135 
18136 /* Global IPv4 ICMP statistics */
18137 static mblk_t *
18138 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
18139 {
18140 	struct opthdr		*optp;
18141 	mblk_t			*mp2ctl;
18142 
18143 	/*
18144 	 * Make a copy of the original message
18145 	 */
18146 	mp2ctl = copymsg(mpctl);
18147 
18148 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18149 	optp->level = MIB2_ICMP;
18150 	optp->name = 0;
18151 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
18152 	    (int)sizeof (icmp_mib))) {
18153 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18154 		    (uint_t)sizeof (icmp_mib)));
18155 	}
18156 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18157 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18158 	    (int)optp->level, (int)optp->name, (int)optp->len));
18159 	qreply(q, mpctl);
18160 	return (mp2ctl);
18161 }
18162 
18163 /* Global IPv4 IGMP statistics */
18164 static mblk_t *
18165 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
18166 {
18167 	struct opthdr		*optp;
18168 	mblk_t			*mp2ctl;
18169 
18170 	/*
18171 	 * make a copy of the original message
18172 	 */
18173 	mp2ctl = copymsg(mpctl);
18174 
18175 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18176 	optp->level = EXPER_IGMP;
18177 	optp->name = 0;
18178 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
18179 	    (int)sizeof (igmpstat))) {
18180 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18181 		    (uint_t)sizeof (igmpstat)));
18182 	}
18183 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18184 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18185 	    (int)optp->level, (int)optp->name, (int)optp->len));
18186 	qreply(q, mpctl);
18187 	return (mp2ctl);
18188 }
18189 
18190 /* Global IPv4 Multicast Routing statistics */
18191 static mblk_t *
18192 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
18193 {
18194 	struct opthdr		*optp;
18195 	mblk_t			*mp2ctl;
18196 
18197 	/*
18198 	 * make a copy of the original message
18199 	 */
18200 	mp2ctl = copymsg(mpctl);
18201 
18202 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18203 	optp->level = EXPER_DVMRP;
18204 	optp->name = 0;
18205 	if (!ip_mroute_stats(mpctl->b_cont)) {
18206 		ip0dbg(("ip_mroute_stats: failed\n"));
18207 	}
18208 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18209 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18210 	    (int)optp->level, (int)optp->name, (int)optp->len));
18211 	qreply(q, mpctl);
18212 	return (mp2ctl);
18213 }
18214 
18215 /* IPv4 address information */
18216 static mblk_t *
18217 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
18218 {
18219 	struct opthdr		*optp;
18220 	mblk_t			*mp2ctl;
18221 	mblk_t			*mp_tail = NULL;
18222 	ill_t			*ill;
18223 	ipif_t			*ipif;
18224 	uint_t			bitval;
18225 	mib2_ipAddrEntry_t	mae;
18226 	zoneid_t		zoneid;
18227 	ill_walk_context_t ctx;
18228 
18229 	/*
18230 	 * make a copy of the original message
18231 	 */
18232 	mp2ctl = copymsg(mpctl);
18233 
18234 	/* ipAddrEntryTable */
18235 
18236 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18237 	optp->level = MIB2_IP;
18238 	optp->name = MIB2_IP_ADDR;
18239 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18240 
18241 	rw_enter(&ill_g_lock, RW_READER);
18242 	ill = ILL_START_WALK_V4(&ctx);
18243 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18244 		for (ipif = ill->ill_ipif; ipif != NULL;
18245 		    ipif = ipif->ipif_next) {
18246 			if (ipif->ipif_zoneid != zoneid &&
18247 			    ipif->ipif_zoneid != ALL_ZONES)
18248 				continue;
18249 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18250 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18251 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18252 
18253 			(void) ipif_get_name(ipif,
18254 			    mae.ipAdEntIfIndex.o_bytes,
18255 			    OCTET_LENGTH);
18256 			mae.ipAdEntIfIndex.o_length =
18257 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18258 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18259 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18260 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18261 			mae.ipAdEntInfo.ae_subnet_len =
18262 			    ip_mask_to_plen(ipif->ipif_net_mask);
18263 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18264 			for (bitval = 1;
18265 			    bitval &&
18266 			    !(bitval & ipif->ipif_brd_addr);
18267 			    bitval <<= 1)
18268 				noop;
18269 			mae.ipAdEntBcastAddr = bitval;
18270 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18271 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18272 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18273 			mae.ipAdEntInfo.ae_broadcast_addr =
18274 			    ipif->ipif_brd_addr;
18275 			mae.ipAdEntInfo.ae_pp_dst_addr =
18276 			    ipif->ipif_pp_dst_addr;
18277 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18278 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18279 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18280 
18281 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18282 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18283 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18284 				    "allocate %u bytes\n",
18285 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18286 			}
18287 		}
18288 	}
18289 	rw_exit(&ill_g_lock);
18290 
18291 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18292 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18293 	    (int)optp->level, (int)optp->name, (int)optp->len));
18294 	qreply(q, mpctl);
18295 	return (mp2ctl);
18296 }
18297 
18298 /* IPv6 address information */
18299 static mblk_t *
18300 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
18301 {
18302 	struct opthdr		*optp;
18303 	mblk_t			*mp2ctl;
18304 	mblk_t			*mp_tail = NULL;
18305 	ill_t			*ill;
18306 	ipif_t			*ipif;
18307 	mib2_ipv6AddrEntry_t	mae6;
18308 	zoneid_t		zoneid;
18309 	ill_walk_context_t	ctx;
18310 
18311 	/*
18312 	 * make a copy of the original message
18313 	 */
18314 	mp2ctl = copymsg(mpctl);
18315 
18316 	/* ipv6AddrEntryTable */
18317 
18318 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18319 	optp->level = MIB2_IP6;
18320 	optp->name = MIB2_IP6_ADDR;
18321 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18322 
18323 	rw_enter(&ill_g_lock, RW_READER);
18324 	ill = ILL_START_WALK_V6(&ctx);
18325 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18326 		for (ipif = ill->ill_ipif; ipif != NULL;
18327 		    ipif = ipif->ipif_next) {
18328 			if (ipif->ipif_zoneid != zoneid &&
18329 			    ipif->ipif_zoneid != ALL_ZONES)
18330 				continue;
18331 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18332 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18333 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18334 
18335 			(void) ipif_get_name(ipif,
18336 			    mae6.ipv6AddrIfIndex.o_bytes,
18337 			    OCTET_LENGTH);
18338 			mae6.ipv6AddrIfIndex.o_length =
18339 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18340 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18341 			mae6.ipv6AddrPfxLength =
18342 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18343 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18344 			mae6.ipv6AddrInfo.ae_subnet_len =
18345 			    mae6.ipv6AddrPfxLength;
18346 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18347 
18348 			/* Type: stateless(1), stateful(2), unknown(3) */
18349 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18350 				mae6.ipv6AddrType = 1;
18351 			else
18352 				mae6.ipv6AddrType = 2;
18353 			/* Anycast: true(1), false(2) */
18354 			if (ipif->ipif_flags & IPIF_ANYCAST)
18355 				mae6.ipv6AddrAnycastFlag = 1;
18356 			else
18357 				mae6.ipv6AddrAnycastFlag = 2;
18358 
18359 			/*
18360 			 * Address status: preferred(1), deprecated(2),
18361 			 * invalid(3), inaccessible(4), unknown(5)
18362 			 */
18363 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18364 				mae6.ipv6AddrStatus = 3;
18365 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18366 				mae6.ipv6AddrStatus = 2;
18367 			else
18368 				mae6.ipv6AddrStatus = 1;
18369 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18370 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18371 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18372 						ipif->ipif_v6pp_dst_addr;
18373 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18374 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18375 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18376 			mae6.ipv6AddrIdentifier = ill->ill_token;
18377 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18378 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18379 			mae6.ipv6AddrRetransmitTime =
18380 			    ill->ill_reachable_retrans_time;
18381 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18382 				(char *)&mae6,
18383 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18384 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18385 				    "allocate %u bytes\n",
18386 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18387 			}
18388 		}
18389 	}
18390 	rw_exit(&ill_g_lock);
18391 
18392 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18393 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18394 	    (int)optp->level, (int)optp->name, (int)optp->len));
18395 	qreply(q, mpctl);
18396 	return (mp2ctl);
18397 }
18398 
18399 /* IPv4 multicast group membership. */
18400 static mblk_t *
18401 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
18402 {
18403 	struct opthdr		*optp;
18404 	mblk_t			*mp2ctl;
18405 	ill_t			*ill;
18406 	ipif_t			*ipif;
18407 	ilm_t			*ilm;
18408 	ip_member_t		ipm;
18409 	mblk_t			*mp_tail = NULL;
18410 	ill_walk_context_t	ctx;
18411 	zoneid_t		zoneid;
18412 
18413 	/*
18414 	 * make a copy of the original message
18415 	 */
18416 	mp2ctl = copymsg(mpctl);
18417 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18418 
18419 	/* ipGroupMember table */
18420 	optp = (struct opthdr *)&mpctl->b_rptr[
18421 	    sizeof (struct T_optmgmt_ack)];
18422 	optp->level = MIB2_IP;
18423 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18424 
18425 	rw_enter(&ill_g_lock, RW_READER);
18426 	ill = ILL_START_WALK_V4(&ctx);
18427 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18428 		ILM_WALKER_HOLD(ill);
18429 		for (ipif = ill->ill_ipif; ipif != NULL;
18430 		    ipif = ipif->ipif_next) {
18431 			if (ipif->ipif_zoneid != zoneid &&
18432 			    ipif->ipif_zoneid != ALL_ZONES)
18433 				continue;	/* not this zone */
18434 			(void) ipif_get_name(ipif,
18435 			    ipm.ipGroupMemberIfIndex.o_bytes,
18436 			    OCTET_LENGTH);
18437 			ipm.ipGroupMemberIfIndex.o_length =
18438 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18439 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18440 				ASSERT(ilm->ilm_ipif != NULL);
18441 				ASSERT(ilm->ilm_ill == NULL);
18442 				if (ilm->ilm_ipif != ipif)
18443 					continue;
18444 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18445 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18446 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18447 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18448 				    (char *)&ipm, (int)sizeof (ipm))) {
18449 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18450 					    "failed to allocate %u bytes\n",
18451 						(uint_t)sizeof (ipm)));
18452 				}
18453 			}
18454 		}
18455 		ILM_WALKER_RELE(ill);
18456 	}
18457 	rw_exit(&ill_g_lock);
18458 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18459 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18460 	    (int)optp->level, (int)optp->name, (int)optp->len));
18461 	qreply(q, mpctl);
18462 	return (mp2ctl);
18463 }
18464 
18465 /* IPv6 multicast group membership. */
18466 static mblk_t *
18467 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
18468 {
18469 	struct opthdr		*optp;
18470 	mblk_t			*mp2ctl;
18471 	ill_t			*ill;
18472 	ilm_t			*ilm;
18473 	ipv6_member_t		ipm6;
18474 	mblk_t			*mp_tail = NULL;
18475 	ill_walk_context_t	ctx;
18476 	zoneid_t		zoneid;
18477 
18478 	/*
18479 	 * make a copy of the original message
18480 	 */
18481 	mp2ctl = copymsg(mpctl);
18482 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18483 
18484 	/* ip6GroupMember table */
18485 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18486 	optp->level = MIB2_IP6;
18487 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18488 
18489 	rw_enter(&ill_g_lock, RW_READER);
18490 	ill = ILL_START_WALK_V6(&ctx);
18491 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18492 		ILM_WALKER_HOLD(ill);
18493 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18494 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18495 			ASSERT(ilm->ilm_ipif == NULL);
18496 			ASSERT(ilm->ilm_ill != NULL);
18497 			if (ilm->ilm_zoneid != zoneid)
18498 				continue;	/* not this zone */
18499 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18500 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18501 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18502 			if (!snmp_append_data2(mpctl->b_cont,
18503 			    &mp_tail,
18504 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18505 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18506 				    "failed to allocate %u bytes\n",
18507 				    (uint_t)sizeof (ipm6)));
18508 			}
18509 		}
18510 		ILM_WALKER_RELE(ill);
18511 	}
18512 	rw_exit(&ill_g_lock);
18513 
18514 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18515 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18516 	    (int)optp->level, (int)optp->name, (int)optp->len));
18517 	qreply(q, mpctl);
18518 	return (mp2ctl);
18519 }
18520 
18521 /* IP multicast filtered sources */
18522 static mblk_t *
18523 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
18524 {
18525 	struct opthdr		*optp;
18526 	mblk_t			*mp2ctl;
18527 	ill_t			*ill;
18528 	ipif_t			*ipif;
18529 	ilm_t			*ilm;
18530 	ip_grpsrc_t		ips;
18531 	mblk_t			*mp_tail = NULL;
18532 	ill_walk_context_t	ctx;
18533 	zoneid_t		zoneid;
18534 	int			i;
18535 	slist_t			*sl;
18536 
18537 	/*
18538 	 * make a copy of the original message
18539 	 */
18540 	mp2ctl = copymsg(mpctl);
18541 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18542 
18543 	/* ipGroupSource table */
18544 	optp = (struct opthdr *)&mpctl->b_rptr[
18545 	    sizeof (struct T_optmgmt_ack)];
18546 	optp->level = MIB2_IP;
18547 	optp->name = EXPER_IP_GROUP_SOURCES;
18548 
18549 	rw_enter(&ill_g_lock, RW_READER);
18550 	ill = ILL_START_WALK_V4(&ctx);
18551 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18552 		ILM_WALKER_HOLD(ill);
18553 		for (ipif = ill->ill_ipif; ipif != NULL;
18554 		    ipif = ipif->ipif_next) {
18555 			if (ipif->ipif_zoneid != zoneid)
18556 				continue;	/* not this zone */
18557 			(void) ipif_get_name(ipif,
18558 			    ips.ipGroupSourceIfIndex.o_bytes,
18559 			    OCTET_LENGTH);
18560 			ips.ipGroupSourceIfIndex.o_length =
18561 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18562 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18563 				ASSERT(ilm->ilm_ipif != NULL);
18564 				ASSERT(ilm->ilm_ill == NULL);
18565 				sl = ilm->ilm_filter;
18566 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18567 					continue;
18568 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18569 				for (i = 0; i < sl->sl_numsrc; i++) {
18570 					if (!IN6_IS_ADDR_V4MAPPED(
18571 					    &sl->sl_addr[i]))
18572 						continue;
18573 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18574 					    ips.ipGroupSourceAddress);
18575 					if (snmp_append_data2(mpctl->b_cont,
18576 					    &mp_tail, (char *)&ips,
18577 					    (int)sizeof (ips)) == 0) {
18578 						ip1dbg(("ip_snmp_get_mib2_"
18579 						    "ip_group_src: failed to "
18580 						    "allocate %u bytes\n",
18581 						    (uint_t)sizeof (ips)));
18582 					}
18583 				}
18584 			}
18585 		}
18586 		ILM_WALKER_RELE(ill);
18587 	}
18588 	rw_exit(&ill_g_lock);
18589 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18590 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18591 	    (int)optp->level, (int)optp->name, (int)optp->len));
18592 	qreply(q, mpctl);
18593 	return (mp2ctl);
18594 }
18595 
18596 /* IPv6 multicast filtered sources. */
18597 static mblk_t *
18598 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18599 {
18600 	struct opthdr		*optp;
18601 	mblk_t			*mp2ctl;
18602 	ill_t			*ill;
18603 	ilm_t			*ilm;
18604 	ipv6_grpsrc_t		ips6;
18605 	mblk_t			*mp_tail = NULL;
18606 	ill_walk_context_t	ctx;
18607 	zoneid_t		zoneid;
18608 	int			i;
18609 	slist_t			*sl;
18610 
18611 	/*
18612 	 * make a copy of the original message
18613 	 */
18614 	mp2ctl = copymsg(mpctl);
18615 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18616 
18617 	/* ip6GroupMember table */
18618 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18619 	optp->level = MIB2_IP6;
18620 	optp->name = EXPER_IP6_GROUP_SOURCES;
18621 
18622 	rw_enter(&ill_g_lock, RW_READER);
18623 	ill = ILL_START_WALK_V6(&ctx);
18624 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18625 		ILM_WALKER_HOLD(ill);
18626 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18627 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18628 			ASSERT(ilm->ilm_ipif == NULL);
18629 			ASSERT(ilm->ilm_ill != NULL);
18630 			sl = ilm->ilm_filter;
18631 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18632 				continue;
18633 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18634 			for (i = 0; i < sl->sl_numsrc; i++) {
18635 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18636 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18637 				    (char *)&ips6, (int)sizeof (ips6))) {
18638 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18639 					    "group_src: failed to allocate "
18640 					    "%u bytes\n",
18641 					    (uint_t)sizeof (ips6)));
18642 				}
18643 			}
18644 		}
18645 		ILM_WALKER_RELE(ill);
18646 	}
18647 	rw_exit(&ill_g_lock);
18648 
18649 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18650 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18651 	    (int)optp->level, (int)optp->name, (int)optp->len));
18652 	qreply(q, mpctl);
18653 	return (mp2ctl);
18654 }
18655 
18656 /* Multicast routing virtual interface table. */
18657 static mblk_t *
18658 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18659 {
18660 	struct opthdr		*optp;
18661 	mblk_t			*mp2ctl;
18662 
18663 	/*
18664 	 * make a copy of the original message
18665 	 */
18666 	mp2ctl = copymsg(mpctl);
18667 
18668 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18669 	optp->level = EXPER_DVMRP;
18670 	optp->name = EXPER_DVMRP_VIF;
18671 	if (!ip_mroute_vif(mpctl->b_cont)) {
18672 		ip0dbg(("ip_mroute_vif: failed\n"));
18673 	}
18674 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18675 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18676 	    (int)optp->level, (int)optp->name, (int)optp->len));
18677 	qreply(q, mpctl);
18678 	return (mp2ctl);
18679 }
18680 
18681 /* Multicast routing table. */
18682 static mblk_t *
18683 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18684 {
18685 	struct opthdr		*optp;
18686 	mblk_t			*mp2ctl;
18687 
18688 	/*
18689 	 * make a copy of the original message
18690 	 */
18691 	mp2ctl = copymsg(mpctl);
18692 
18693 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18694 	optp->level = EXPER_DVMRP;
18695 	optp->name = EXPER_DVMRP_MRT;
18696 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18697 		ip0dbg(("ip_mroute_mrt: failed\n"));
18698 	}
18699 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18700 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18701 	    (int)optp->level, (int)optp->name, (int)optp->len));
18702 	qreply(q, mpctl);
18703 	return (mp2ctl);
18704 }
18705 
18706 /*
18707  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18708  * in one IRE walk.
18709  */
18710 static mblk_t *
18711 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18712 {
18713 	struct opthdr	*optp;
18714 	mblk_t		*mp2ctl;	/* Returned */
18715 	mblk_t		*mp3ctl;	/* nettomedia */
18716 	mblk_t		*mp4ctl;	/* routeattrs */
18717 	iproutedata_t	ird;
18718 	zoneid_t	zoneid;
18719 
18720 	/*
18721 	 * make copies of the original message
18722 	 *	- mp2ctl is returned unchanged to the caller for his use
18723 	 *	- mpctl is sent upstream as ipRouteEntryTable
18724 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18725 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18726 	 */
18727 	mp2ctl = copymsg(mpctl);
18728 	mp3ctl = copymsg(mpctl);
18729 	mp4ctl = copymsg(mpctl);
18730 	if (mp3ctl == NULL || mp4ctl == NULL) {
18731 		freemsg(mp4ctl);
18732 		freemsg(mp3ctl);
18733 		freemsg(mp2ctl);
18734 		freemsg(mpctl);
18735 		return (NULL);
18736 	}
18737 
18738 	bzero(&ird, sizeof (ird));
18739 
18740 	ird.ird_route.lp_head = mpctl->b_cont;
18741 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18742 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18743 
18744 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18745 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18746 	if (zoneid == GLOBAL_ZONEID) {
18747 		/*
18748 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18749 		 * the sys_net_config privilege, it can only run in the global
18750 		 * zone, so we don't display these IREs in the other zones.
18751 		 */
18752 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18753 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18754 	}
18755 
18756 	/* ipRouteEntryTable in mpctl */
18757 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18758 	optp->level = MIB2_IP;
18759 	optp->name = MIB2_IP_ROUTE;
18760 	optp->len = msgdsize(ird.ird_route.lp_head);
18761 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18762 	    (int)optp->level, (int)optp->name, (int)optp->len));
18763 	qreply(q, mpctl);
18764 
18765 	/* ipNetToMediaEntryTable in mp3ctl */
18766 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18767 	optp->level = MIB2_IP;
18768 	optp->name = MIB2_IP_MEDIA;
18769 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18770 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18771 	    (int)optp->level, (int)optp->name, (int)optp->len));
18772 	qreply(q, mp3ctl);
18773 
18774 	/* ipRouteAttributeTable in mp4ctl */
18775 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18776 	optp->level = MIB2_IP;
18777 	optp->name = EXPER_IP_RTATTR;
18778 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18779 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18780 	    (int)optp->level, (int)optp->name, (int)optp->len));
18781 	if (optp->len == 0)
18782 		freemsg(mp4ctl);
18783 	else
18784 		qreply(q, mp4ctl);
18785 
18786 	return (mp2ctl);
18787 }
18788 
18789 /*
18790  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18791  * ipv6NetToMediaEntryTable in an NDP walk.
18792  */
18793 static mblk_t *
18794 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18795 {
18796 	struct opthdr	*optp;
18797 	mblk_t		*mp2ctl;	/* Returned */
18798 	mblk_t		*mp3ctl;	/* nettomedia */
18799 	mblk_t		*mp4ctl;	/* routeattrs */
18800 	iproutedata_t	ird;
18801 	zoneid_t	zoneid;
18802 
18803 	/*
18804 	 * make copies of the original message
18805 	 *	- mp2ctl is returned unchanged to the caller for his use
18806 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18807 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18808 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18809 	 */
18810 	mp2ctl = copymsg(mpctl);
18811 	mp3ctl = copymsg(mpctl);
18812 	mp4ctl = copymsg(mpctl);
18813 	if (mp3ctl == NULL || mp4ctl == NULL) {
18814 		freemsg(mp4ctl);
18815 		freemsg(mp3ctl);
18816 		freemsg(mp2ctl);
18817 		freemsg(mpctl);
18818 		return (NULL);
18819 	}
18820 
18821 	bzero(&ird, sizeof (ird));
18822 
18823 	ird.ird_route.lp_head = mpctl->b_cont;
18824 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18825 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18826 
18827 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18828 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18829 
18830 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18831 	optp->level = MIB2_IP6;
18832 	optp->name = MIB2_IP6_ROUTE;
18833 	optp->len = msgdsize(ird.ird_route.lp_head);
18834 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18835 	    (int)optp->level, (int)optp->name, (int)optp->len));
18836 	qreply(q, mpctl);
18837 
18838 	/* ipv6NetToMediaEntryTable in mp3ctl */
18839 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18840 
18841 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18842 	optp->level = MIB2_IP6;
18843 	optp->name = MIB2_IP6_MEDIA;
18844 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18845 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18846 	    (int)optp->level, (int)optp->name, (int)optp->len));
18847 	qreply(q, mp3ctl);
18848 
18849 	/* ipv6RouteAttributeTable in mp4ctl */
18850 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18851 	optp->level = MIB2_IP6;
18852 	optp->name = EXPER_IP_RTATTR;
18853 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18854 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18855 	    (int)optp->level, (int)optp->name, (int)optp->len));
18856 	if (optp->len == 0)
18857 		freemsg(mp4ctl);
18858 	else
18859 		qreply(q, mp4ctl);
18860 
18861 	return (mp2ctl);
18862 }
18863 
18864 /*
18865  * IPv6 mib: One per ill
18866  */
18867 static mblk_t *
18868 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18869 {
18870 	struct opthdr		*optp;
18871 	mblk_t			*mp2ctl;
18872 	ill_t			*ill;
18873 	ill_walk_context_t	ctx;
18874 	mblk_t			*mp_tail = NULL;
18875 
18876 	/*
18877 	 * Make a copy of the original message
18878 	 */
18879 	mp2ctl = copymsg(mpctl);
18880 
18881 	/* fixed length IPv6 structure ... */
18882 
18883 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18884 	optp->level = MIB2_IP6;
18885 	optp->name = 0;
18886 	/* Include "unknown interface" ip6_mib */
18887 	ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
18888 	ip6_mib.ipIfStatsIfIndex = MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18889 	SET_MIB(ip6_mib.ipIfStatsForwarding, ipv6_forward ? 1 : 2);
18890 	SET_MIB(ip6_mib.ipIfStatsDefaultHopLimit, ipv6_def_hops);
18891 	SET_MIB(ip6_mib.ipIfStatsEntrySize,
18892 	    sizeof (mib2_ipIfStatsEntry_t));
18893 	SET_MIB(ip6_mib.ipIfStatsAddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18894 	SET_MIB(ip6_mib.ipIfStatsRouteEntrySize,
18895 	    sizeof (mib2_ipv6RouteEntry_t));
18896 	SET_MIB(ip6_mib.ipIfStatsNetToMediaEntrySize,
18897 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18898 	SET_MIB(ip6_mib.ipIfStatsMemberEntrySize, sizeof (ipv6_member_t));
18899 	SET_MIB(ip6_mib.ipIfStatsGroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18900 
18901 	/*
18902 	 * Synchronize 64- and 32-bit counters
18903 	 */
18904 	SYNC32_MIB(&ip6_mib, ipIfStatsInReceives, ipIfStatsHCInReceives);
18905 	SYNC32_MIB(&ip6_mib, ipIfStatsInDelivers, ipIfStatsHCInDelivers);
18906 	SYNC32_MIB(&ip6_mib, ipIfStatsOutRequests, ipIfStatsHCOutRequests);
18907 	SYNC32_MIB(&ip6_mib, ipIfStatsOutForwDatagrams,
18908 	    ipIfStatsHCOutForwDatagrams);
18909 	SYNC32_MIB(&ip6_mib, ipIfStatsOutMcastPkts, ipIfStatsHCOutMcastPkts);
18910 	SYNC32_MIB(&ip6_mib, ipIfStatsInMcastPkts, ipIfStatsHCInMcastPkts);
18911 
18912 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18913 	    (int)sizeof (ip6_mib))) {
18914 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18915 		    (uint_t)sizeof (ip6_mib)));
18916 	}
18917 
18918 	rw_enter(&ill_g_lock, RW_READER);
18919 	ill = ILL_START_WALK_V6(&ctx);
18920 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18921 		ill->ill_ip_mib->ipIfStatsIfIndex =
18922 		    ill->ill_phyint->phyint_ifindex;
18923 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18924 		    ipv6_forward ? 1 : 2);
18925 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
18926 		    ill->ill_max_hops);
18927 
18928 		/*
18929 		 * Synchronize 64- and 32-bit counters
18930 		 */
18931 		SYNC32_MIB(&ip6_mib, ipIfStatsInReceives,
18932 		    ipIfStatsHCInReceives);
18933 		SYNC32_MIB(&ip6_mib, ipIfStatsInDelivers,
18934 		    ipIfStatsHCInDelivers);
18935 		SYNC32_MIB(&ip6_mib, ipIfStatsOutRequests,
18936 		    ipIfStatsHCOutRequests);
18937 		SYNC32_MIB(&ip6_mib, ipIfStatsOutForwDatagrams,
18938 		    ipIfStatsHCOutForwDatagrams);
18939 		SYNC32_MIB(&ip6_mib, ipIfStatsOutMcastPkts,
18940 		    ipIfStatsHCOutMcastPkts);
18941 		SYNC32_MIB(&ip6_mib, ipIfStatsInMcastPkts,
18942 		    ipIfStatsHCInMcastPkts);
18943 
18944 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18945 		    (char *)ill->ill_ip_mib,
18946 		    (int)sizeof (*ill->ill_ip_mib))) {
18947 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18948 				"%u bytes\n",
18949 				(uint_t)sizeof (*ill->ill_ip_mib)));
18950 		}
18951 	}
18952 	rw_exit(&ill_g_lock);
18953 
18954 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18955 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18956 	    (int)optp->level, (int)optp->name, (int)optp->len));
18957 	qreply(q, mpctl);
18958 	return (mp2ctl);
18959 }
18960 
18961 /*
18962  * ICMPv6 mib: One per ill
18963  */
18964 static mblk_t *
18965 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18966 {
18967 	struct opthdr		*optp;
18968 	mblk_t			*mp2ctl;
18969 	ill_t			*ill;
18970 	ill_walk_context_t	ctx;
18971 	mblk_t			*mp_tail = NULL;
18972 	/*
18973 	 * Make a copy of the original message
18974 	 */
18975 	mp2ctl = copymsg(mpctl);
18976 
18977 	/* fixed length ICMPv6 structure ... */
18978 
18979 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18980 	optp->level = MIB2_ICMP6;
18981 	optp->name = 0;
18982 	/* Include "unknown interface" icmp6_mib */
18983 	icmp6_mib.ipv6IfIcmpIfIndex = MIB2_UNKNOWN_INTERFACE; /* netstat flag */
18984 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18985 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18986 	    (int)sizeof (icmp6_mib))) {
18987 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18988 		    (uint_t)sizeof (icmp6_mib)));
18989 	}
18990 
18991 	rw_enter(&ill_g_lock, RW_READER);
18992 	ill = ILL_START_WALK_V6(&ctx);
18993 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18994 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18995 		    ill->ill_phyint->phyint_ifindex;
18996 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18997 		    (char *)ill->ill_icmp6_mib,
18998 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18999 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19000 			    "%u bytes\n",
19001 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19002 		}
19003 	}
19004 	rw_exit(&ill_g_lock);
19005 
19006 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19007 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19008 	    (int)optp->level, (int)optp->name, (int)optp->len));
19009 	qreply(q, mpctl);
19010 	return (mp2ctl);
19011 }
19012 
19013 /*
19014  * ire_walk routine to create both ipRouteEntryTable and
19015  * ipRouteAttributeTable in one IRE walk
19016  */
19017 static void
19018 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19019 {
19020 	ill_t				*ill;
19021 	ipif_t				*ipif;
19022 	mib2_ipRouteEntry_t		*re;
19023 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19024 	ipaddr_t			gw_addr;
19025 	tsol_ire_gw_secattr_t		*attrp;
19026 	tsol_gc_t			*gc = NULL;
19027 	tsol_gcgrp_t			*gcgrp = NULL;
19028 	uint_t				sacnt = 0;
19029 	int				i;
19030 
19031 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19032 
19033 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19034 		return;
19035 
19036 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19037 		mutex_enter(&attrp->igsa_lock);
19038 		if ((gc = attrp->igsa_gc) != NULL) {
19039 			gcgrp = gc->gc_grp;
19040 			ASSERT(gcgrp != NULL);
19041 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19042 			sacnt = 1;
19043 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19044 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19045 			gc = gcgrp->gcgrp_head;
19046 			sacnt = gcgrp->gcgrp_count;
19047 		}
19048 		mutex_exit(&attrp->igsa_lock);
19049 
19050 		/* do nothing if there's no gc to report */
19051 		if (gc == NULL) {
19052 			ASSERT(sacnt == 0);
19053 			if (gcgrp != NULL) {
19054 				/* we might as well drop the lock now */
19055 				rw_exit(&gcgrp->gcgrp_rwlock);
19056 				gcgrp = NULL;
19057 			}
19058 			attrp = NULL;
19059 		}
19060 
19061 		ASSERT(gc == NULL || (gcgrp != NULL &&
19062 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19063 	}
19064 	ASSERT(sacnt == 0 || gc != NULL);
19065 
19066 	if (sacnt != 0 &&
19067 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19068 		kmem_free(re, sizeof (*re));
19069 		rw_exit(&gcgrp->gcgrp_rwlock);
19070 		return;
19071 	}
19072 
19073 	/*
19074 	 * Return all IRE types for route table... let caller pick and choose
19075 	 */
19076 	re->ipRouteDest = ire->ire_addr;
19077 	ipif = ire->ire_ipif;
19078 	re->ipRouteIfIndex.o_length = 0;
19079 	if (ire->ire_type == IRE_CACHE) {
19080 		ill = (ill_t *)ire->ire_stq->q_ptr;
19081 		re->ipRouteIfIndex.o_length =
19082 		    ill->ill_name_length == 0 ? 0 :
19083 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19084 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19085 		    re->ipRouteIfIndex.o_length);
19086 	} else if (ipif != NULL) {
19087 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19088 		    OCTET_LENGTH);
19089 		re->ipRouteIfIndex.o_length =
19090 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19091 	}
19092 	re->ipRouteMetric1 = -1;
19093 	re->ipRouteMetric2 = -1;
19094 	re->ipRouteMetric3 = -1;
19095 	re->ipRouteMetric4 = -1;
19096 
19097 	gw_addr = ire->ire_gateway_addr;
19098 
19099 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19100 		re->ipRouteNextHop = ire->ire_src_addr;
19101 	else
19102 		re->ipRouteNextHop = gw_addr;
19103 	/* indirect(4), direct(3), or invalid(2) */
19104 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19105 		re->ipRouteType = 2;
19106 	else
19107 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19108 	re->ipRouteProto = -1;
19109 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19110 	re->ipRouteMask = ire->ire_mask;
19111 	re->ipRouteMetric5 = -1;
19112 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19113 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19114 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19115 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19116 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19117 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19118 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19119 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19120 	re->ipRouteInfo.re_in_ill.o_length = 0;
19121 
19122 	if (ire->ire_flags & RTF_DYNAMIC) {
19123 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19124 	} else {
19125 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19126 	}
19127 
19128 	if (ire->ire_in_ill != NULL) {
19129 		re->ipRouteInfo.re_in_ill.o_length =
19130 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19131 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19132 		bcopy(ire->ire_in_ill->ill_name,
19133 		    re->ipRouteInfo.re_in_ill.o_bytes,
19134 		    re->ipRouteInfo.re_in_ill.o_length);
19135 	}
19136 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19137 
19138 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19139 	    (char *)re, (int)sizeof (*re))) {
19140 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19141 		    (uint_t)sizeof (*re)));
19142 	}
19143 
19144 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19145 		iaeptr->iae_routeidx = ird->ird_idx;
19146 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19147 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19148 	}
19149 
19150 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19151 	    (char *)iae, sacnt * sizeof (*iae))) {
19152 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19153 		    (unsigned)(sacnt * sizeof (*iae))));
19154 	}
19155 
19156 	/* bump route index for next pass */
19157 	ird->ird_idx++;
19158 
19159 	kmem_free(re, sizeof (*re));
19160 	if (sacnt != 0)
19161 		kmem_free(iae, sacnt * sizeof (*iae));
19162 
19163 	if (gcgrp != NULL)
19164 		rw_exit(&gcgrp->gcgrp_rwlock);
19165 }
19166 
19167 /*
19168  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19169  */
19170 static void
19171 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19172 {
19173 	ill_t				*ill;
19174 	ipif_t				*ipif;
19175 	mib2_ipv6RouteEntry_t		*re;
19176 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19177 	in6_addr_t			gw_addr_v6;
19178 	tsol_ire_gw_secattr_t		*attrp;
19179 	tsol_gc_t			*gc = NULL;
19180 	tsol_gcgrp_t			*gcgrp = NULL;
19181 	uint_t				sacnt = 0;
19182 	int				i;
19183 
19184 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19185 
19186 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19187 		return;
19188 
19189 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19190 		mutex_enter(&attrp->igsa_lock);
19191 		if ((gc = attrp->igsa_gc) != NULL) {
19192 			gcgrp = gc->gc_grp;
19193 			ASSERT(gcgrp != NULL);
19194 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19195 			sacnt = 1;
19196 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19197 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19198 			gc = gcgrp->gcgrp_head;
19199 			sacnt = gcgrp->gcgrp_count;
19200 		}
19201 		mutex_exit(&attrp->igsa_lock);
19202 
19203 		/* do nothing if there's no gc to report */
19204 		if (gc == NULL) {
19205 			ASSERT(sacnt == 0);
19206 			if (gcgrp != NULL) {
19207 				/* we might as well drop the lock now */
19208 				rw_exit(&gcgrp->gcgrp_rwlock);
19209 				gcgrp = NULL;
19210 			}
19211 			attrp = NULL;
19212 		}
19213 
19214 		ASSERT(gc == NULL || (gcgrp != NULL &&
19215 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19216 	}
19217 	ASSERT(sacnt == 0 || gc != NULL);
19218 
19219 	if (sacnt != 0 &&
19220 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19221 		kmem_free(re, sizeof (*re));
19222 		rw_exit(&gcgrp->gcgrp_rwlock);
19223 		return;
19224 	}
19225 
19226 	/*
19227 	 * Return all IRE types for route table... let caller pick and choose
19228 	 */
19229 	re->ipv6RouteDest = ire->ire_addr_v6;
19230 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19231 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19232 	re->ipv6RouteIfIndex.o_length = 0;
19233 	ipif = ire->ire_ipif;
19234 	if (ire->ire_type == IRE_CACHE) {
19235 		ill = (ill_t *)ire->ire_stq->q_ptr;
19236 		re->ipv6RouteIfIndex.o_length =
19237 		    ill->ill_name_length == 0 ? 0 :
19238 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19239 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19240 		    re->ipv6RouteIfIndex.o_length);
19241 	} else if (ipif != NULL) {
19242 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19243 		    OCTET_LENGTH);
19244 		re->ipv6RouteIfIndex.o_length =
19245 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19246 	}
19247 
19248 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19249 
19250 	mutex_enter(&ire->ire_lock);
19251 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19252 	mutex_exit(&ire->ire_lock);
19253 
19254 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19255 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19256 	else
19257 		re->ipv6RouteNextHop = gw_addr_v6;
19258 
19259 	/* remote(4), local(3), or discard(2) */
19260 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19261 		re->ipv6RouteType = 2;
19262 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19263 		re->ipv6RouteType = 3;
19264 	else
19265 		re->ipv6RouteType = 4;
19266 
19267 	re->ipv6RouteProtocol	= -1;
19268 	re->ipv6RoutePolicy	= 0;
19269 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19270 	re->ipv6RouteNextHopRDI	= 0;
19271 	re->ipv6RouteWeight	= 0;
19272 	re->ipv6RouteMetric	= 0;
19273 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19274 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19275 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19276 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19277 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19278 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19279 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19280 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19281 
19282 	if (ire->ire_flags & RTF_DYNAMIC) {
19283 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19284 	} else {
19285 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19286 	}
19287 
19288 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19289 	    (char *)re, (int)sizeof (*re))) {
19290 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19291 		    (uint_t)sizeof (*re)));
19292 	}
19293 
19294 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19295 		iaeptr->iae_routeidx = ird->ird_idx;
19296 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19297 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19298 	}
19299 
19300 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19301 	    (char *)iae, sacnt * sizeof (*iae))) {
19302 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19303 		    (unsigned)(sacnt * sizeof (*iae))));
19304 	}
19305 
19306 	/* bump route index for next pass */
19307 	ird->ird_idx++;
19308 
19309 	kmem_free(re, sizeof (*re));
19310 	if (sacnt != 0)
19311 		kmem_free(iae, sacnt * sizeof (*iae));
19312 
19313 	if (gcgrp != NULL)
19314 		rw_exit(&gcgrp->gcgrp_rwlock);
19315 }
19316 
19317 /*
19318  * ndp_walk routine to create ipv6NetToMediaEntryTable
19319  */
19320 static int
19321 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19322 {
19323 	ill_t				*ill;
19324 	mib2_ipv6NetToMediaEntry_t	ntme;
19325 	dl_unitdata_req_t		*dl;
19326 
19327 	ill = nce->nce_ill;
19328 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19329 		return (0);
19330 
19331 	/*
19332 	 * Neighbor cache entry attached to IRE with on-link
19333 	 * destination.
19334 	 */
19335 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19336 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19337 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19338 	    (nce->nce_res_mp != NULL)) {
19339 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19340 		ntme.ipv6NetToMediaPhysAddress.o_length =
19341 		    dl->dl_dest_addr_length;
19342 	} else {
19343 		ntme.ipv6NetToMediaPhysAddress.o_length =
19344 		    ill->ill_phys_addr_length;
19345 	}
19346 	if (nce->nce_res_mp != NULL) {
19347 		bcopy((char *)nce->nce_res_mp->b_rptr +
19348 		    NCE_LL_ADDR_OFFSET(ill),
19349 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19350 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19351 	} else {
19352 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19353 		    ill->ill_phys_addr_length);
19354 	}
19355 	/*
19356 	 * Note: Returns ND_* states. Should be:
19357 	 * reachable(1), stale(2), delay(3), probe(4),
19358 	 * invalid(5), unknown(6)
19359 	 */
19360 	ntme.ipv6NetToMediaState = nce->nce_state;
19361 	ntme.ipv6NetToMediaLastUpdated = 0;
19362 
19363 	/* other(1), dynamic(2), static(3), local(4) */
19364 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19365 		ntme.ipv6NetToMediaType = 4;
19366 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19367 		ntme.ipv6NetToMediaType = 1;
19368 	} else {
19369 		ntme.ipv6NetToMediaType = 2;
19370 	}
19371 
19372 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19373 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19374 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19375 		    (uint_t)sizeof (ntme)));
19376 	}
19377 	return (0);
19378 }
19379 
19380 /*
19381  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19382  */
19383 /* ARGSUSED */
19384 int
19385 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19386 {
19387 	switch (level) {
19388 	case MIB2_IP:
19389 	case MIB2_ICMP:
19390 		switch (name) {
19391 		default:
19392 			break;
19393 		}
19394 		return (1);
19395 	default:
19396 		return (1);
19397 	}
19398 }
19399 
19400 /*
19401  * When there exists both a 64- and 32-bit counter of a particular type
19402  * (i.e., InReceives), only the 64-bit counters are added.
19403  */
19404 void
19405 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19406 {
19407 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19408 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19409 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19410 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19411 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19412 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19413 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19414 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19415 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19416 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19417 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19418 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19419 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19420 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19421 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19422 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19423 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19424 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19425 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19426 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19427 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19428 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19429 	    o2->ipIfStatsInWrongIPVersion);
19430 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19431 	    o2->ipIfStatsInWrongIPVersion);
19432 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19433 	    o2->ipIfStatsOutSwitchIPVersion);
19434 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19435 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19436 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19437 	    o2->ipIfStatsHCInForwDatagrams);
19438 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19439 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19440 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19441 	    o2->ipIfStatsHCOutForwDatagrams);
19442 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19443 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19444 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19445 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19446 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19447 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19448 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19449 	    o2->ipIfStatsHCOutMcastOctets);
19450 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19451 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19452 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19453 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19454 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19455 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19456 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19457 }
19458 
19459 void
19460 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19461 {
19462 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19463 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19464 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19465 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19466 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19467 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19468 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19469 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19470 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19471 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19472 	    o2->ipv6IfIcmpInRouterSolicits);
19473 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19474 	    o2->ipv6IfIcmpInRouterAdvertisements);
19475 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19476 	    o2->ipv6IfIcmpInNeighborSolicits);
19477 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19478 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19479 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19480 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19481 	    o2->ipv6IfIcmpInGroupMembQueries);
19482 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19483 	    o2->ipv6IfIcmpInGroupMembResponses);
19484 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19485 	    o2->ipv6IfIcmpInGroupMembReductions);
19486 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19487 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19488 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19489 	    o2->ipv6IfIcmpOutDestUnreachs);
19490 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19491 	    o2->ipv6IfIcmpOutAdminProhibs);
19492 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19493 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19494 	    o2->ipv6IfIcmpOutParmProblems);
19495 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19496 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19497 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19498 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19499 	    o2->ipv6IfIcmpOutRouterSolicits);
19500 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19501 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19502 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19503 	    o2->ipv6IfIcmpOutNeighborSolicits);
19504 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19505 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19506 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19507 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19508 	    o2->ipv6IfIcmpOutGroupMembQueries);
19509 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19510 	    o2->ipv6IfIcmpOutGroupMembResponses);
19511 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19512 	    o2->ipv6IfIcmpOutGroupMembReductions);
19513 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19514 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19515 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19516 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19517 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19518 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19519 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19520 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19521 	    o2->ipv6IfIcmpInGroupMembTotal);
19522 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19523 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19524 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19525 	    o2->ipv6IfIcmpInGroupMembBadReports);
19526 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19527 	    o2->ipv6IfIcmpInGroupMembOurReports);
19528 }
19529 
19530 /*
19531  * Called before the options are updated to check if this packet will
19532  * be source routed from here.
19533  * This routine assumes that the options are well formed i.e. that they
19534  * have already been checked.
19535  */
19536 static boolean_t
19537 ip_source_routed(ipha_t *ipha)
19538 {
19539 	ipoptp_t	opts;
19540 	uchar_t		*opt;
19541 	uint8_t		optval;
19542 	uint8_t		optlen;
19543 	ipaddr_t	dst;
19544 	ire_t		*ire;
19545 
19546 	if (IS_SIMPLE_IPH(ipha)) {
19547 		ip2dbg(("not source routed\n"));
19548 		return (B_FALSE);
19549 	}
19550 	dst = ipha->ipha_dst;
19551 	for (optval = ipoptp_first(&opts, ipha);
19552 	    optval != IPOPT_EOL;
19553 	    optval = ipoptp_next(&opts)) {
19554 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19555 		opt = opts.ipoptp_cur;
19556 		optlen = opts.ipoptp_len;
19557 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19558 		    optval, optlen));
19559 		switch (optval) {
19560 			uint32_t off;
19561 		case IPOPT_SSRR:
19562 		case IPOPT_LSRR:
19563 			/*
19564 			 * If dst is one of our addresses and there are some
19565 			 * entries left in the source route return (true).
19566 			 */
19567 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19568 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
19569 			if (ire == NULL) {
19570 				ip2dbg(("ip_source_routed: not next"
19571 				    " source route 0x%x\n",
19572 				    ntohl(dst)));
19573 				return (B_FALSE);
19574 			}
19575 			ire_refrele(ire);
19576 			off = opt[IPOPT_OFFSET];
19577 			off--;
19578 			if (optlen < IP_ADDR_LEN ||
19579 			    off > optlen - IP_ADDR_LEN) {
19580 				/* End of source route */
19581 				ip1dbg(("ip_source_routed: end of SR\n"));
19582 				return (B_FALSE);
19583 			}
19584 			return (B_TRUE);
19585 		}
19586 	}
19587 	ip2dbg(("not source routed\n"));
19588 	return (B_FALSE);
19589 }
19590 
19591 /*
19592  * Check if the packet contains any source route.
19593  */
19594 static boolean_t
19595 ip_source_route_included(ipha_t *ipha)
19596 {
19597 	ipoptp_t	opts;
19598 	uint8_t		optval;
19599 
19600 	if (IS_SIMPLE_IPH(ipha))
19601 		return (B_FALSE);
19602 	for (optval = ipoptp_first(&opts, ipha);
19603 	    optval != IPOPT_EOL;
19604 	    optval = ipoptp_next(&opts)) {
19605 		switch (optval) {
19606 		case IPOPT_SSRR:
19607 		case IPOPT_LSRR:
19608 			return (B_TRUE);
19609 		}
19610 	}
19611 	return (B_FALSE);
19612 }
19613 
19614 /*
19615  * Called when the IRE expiration timer fires.
19616  */
19617 /* ARGSUSED */
19618 void
19619 ip_trash_timer_expire(void *args)
19620 {
19621 	int	flush_flag = 0;
19622 
19623 	/*
19624 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19625 	 * This lock makes sure that a new invocation of this function
19626 	 * that occurs due to an almost immediate timer firing will not
19627 	 * progress beyond this point until the current invocation is done
19628 	 */
19629 	mutex_enter(&ip_trash_timer_lock);
19630 	ip_ire_expire_id = 0;
19631 	mutex_exit(&ip_trash_timer_lock);
19632 
19633 	/* Periodic timer */
19634 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
19635 		/*
19636 		 * Remove all IRE_CACHE entries since they might
19637 		 * contain arp information.
19638 		 */
19639 		flush_flag |= FLUSH_ARP_TIME;
19640 		ip_ire_arp_time_elapsed = 0;
19641 		IP_STAT(ip_ire_arp_timer_expired);
19642 	}
19643 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
19644 		/* Remove all redirects */
19645 		flush_flag |= FLUSH_REDIRECT_TIME;
19646 		ip_ire_rd_time_elapsed = 0;
19647 		IP_STAT(ip_ire_redirect_timer_expired);
19648 	}
19649 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
19650 		/* Increase path mtu */
19651 		flush_flag |= FLUSH_MTU_TIME;
19652 		ip_ire_pmtu_time_elapsed = 0;
19653 		IP_STAT(ip_ire_pmtu_timer_expired);
19654 	}
19655 
19656 	/*
19657 	 * Optimize for the case when there are no redirects in the
19658 	 * ftable, that is, no need to walk the ftable in that case.
19659 	 */
19660 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19661 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19662 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
19663 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
19664 	}
19665 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
19666 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19667 		    ire_expire, (char *)(uintptr_t)flush_flag,
19668 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
19669 	}
19670 	if (flush_flag & FLUSH_MTU_TIME) {
19671 		/*
19672 		 * Walk all IPv6 IRE's and update them
19673 		 * Note that ARP and redirect timers are not
19674 		 * needed since NUD handles stale entries.
19675 		 */
19676 		flush_flag = FLUSH_MTU_TIME;
19677 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
19678 		    ALL_ZONES);
19679 	}
19680 
19681 	ip_ire_arp_time_elapsed += ip_timer_interval;
19682 	ip_ire_rd_time_elapsed += ip_timer_interval;
19683 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19684 
19685 	/*
19686 	 * Hold the lock to serialize timeout calls and prevent
19687 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19688 	 * for the timer to fire and a new invocation of this function
19689 	 * to start before the return value of timeout has been stored
19690 	 * in ip_ire_expire_id by the current invocation.
19691 	 */
19692 	mutex_enter(&ip_trash_timer_lock);
19693 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19694 	    MSEC_TO_TICK(ip_timer_interval));
19695 	mutex_exit(&ip_trash_timer_lock);
19696 }
19697 
19698 /*
19699  * Called by the memory allocator subsystem directly, when the system
19700  * is running low on memory.
19701  */
19702 /* ARGSUSED */
19703 void
19704 ip_trash_ire_reclaim(void *args)
19705 {
19706 	ire_cache_count_t icc;
19707 	ire_cache_reclaim_t icr;
19708 	ncc_cache_count_t ncc;
19709 	nce_cache_reclaim_t ncr;
19710 	uint_t delete_cnt;
19711 	/*
19712 	 * Memory reclaim call back.
19713 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19714 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19715 	 * entries, determine what fraction to free for
19716 	 * each category of IRE_CACHE entries giving absolute priority
19717 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19718 	 * entry will be freed unless all offlink entries are freed).
19719 	 */
19720 	icc.icc_total = 0;
19721 	icc.icc_unused = 0;
19722 	icc.icc_offlink = 0;
19723 	icc.icc_pmtu = 0;
19724 	icc.icc_onlink = 0;
19725 	ire_walk(ire_cache_count, (char *)&icc);
19726 
19727 	/*
19728 	 * Free NCEs for IPv6 like the onlink ires.
19729 	 */
19730 	ncc.ncc_total = 0;
19731 	ncc.ncc_host = 0;
19732 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19733 
19734 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19735 	    icc.icc_pmtu + icc.icc_onlink);
19736 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19737 	IP_STAT(ip_trash_ire_reclaim_calls);
19738 	if (delete_cnt == 0)
19739 		return;
19740 	IP_STAT(ip_trash_ire_reclaim_success);
19741 	/* Always delete all unused offlink entries */
19742 	icr.icr_unused = 1;
19743 	if (delete_cnt <= icc.icc_unused) {
19744 		/*
19745 		 * Only need to free unused entries.  In other words,
19746 		 * there are enough unused entries to free to meet our
19747 		 * target number of freed ire cache entries.
19748 		 */
19749 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19750 		ncr.ncr_host = 0;
19751 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19752 		/*
19753 		 * Only need to free unused entries, plus a fraction of offlink
19754 		 * entries.  It follows from the first if statement that
19755 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19756 		 */
19757 		delete_cnt -= icc.icc_unused;
19758 		/* Round up # deleted by truncating fraction */
19759 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19760 		icr.icr_pmtu = icr.icr_onlink = 0;
19761 		ncr.ncr_host = 0;
19762 	} else if (delete_cnt <=
19763 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19764 		/*
19765 		 * Free all unused and offlink entries, plus a fraction of
19766 		 * pmtu entries.  It follows from the previous if statement
19767 		 * that icc_pmtu is non-zero, and that
19768 		 * delete_cnt != icc_unused + icc_offlink.
19769 		 */
19770 		icr.icr_offlink = 1;
19771 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19772 		/* Round up # deleted by truncating fraction */
19773 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19774 		icr.icr_onlink = 0;
19775 		ncr.ncr_host = 0;
19776 	} else {
19777 		/*
19778 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19779 		 * of onlink entries.  If we're here, then we know that
19780 		 * icc_onlink is non-zero, and that
19781 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19782 		 */
19783 		icr.icr_offlink = icr.icr_pmtu = 1;
19784 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19785 		    icc.icc_pmtu;
19786 		/* Round up # deleted by truncating fraction */
19787 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19788 		/* Using the same delete fraction as for onlink IREs */
19789 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19790 	}
19791 #ifdef DEBUG
19792 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19793 	    "fractions %d/%d/%d/%d\n",
19794 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19795 	    icc.icc_unused, icc.icc_offlink,
19796 	    icc.icc_pmtu, icc.icc_onlink,
19797 	    icr.icr_unused, icr.icr_offlink,
19798 	    icr.icr_pmtu, icr.icr_onlink));
19799 #endif
19800 	ire_walk(ire_cache_reclaim, (char *)&icr);
19801 	if (ncr.ncr_host != 0)
19802 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19803 		    (uchar_t *)&ncr);
19804 #ifdef DEBUG
19805 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19806 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19807 	ire_walk(ire_cache_count, (char *)&icc);
19808 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19809 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19810 	    icc.icc_pmtu, icc.icc_onlink));
19811 #endif
19812 }
19813 
19814 /*
19815  * ip_unbind is called when a copy of an unbind request is received from the
19816  * upper level protocol.  We remove this conn from any fanout hash list it is
19817  * on, and zero out the bind information.  No reply is expected up above.
19818  */
19819 mblk_t *
19820 ip_unbind(queue_t *q, mblk_t *mp)
19821 {
19822 	conn_t	*connp = Q_TO_CONN(q);
19823 
19824 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19825 
19826 	if (is_system_labeled() && connp->conn_anon_port) {
19827 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19828 		    connp->conn_mlp_type, connp->conn_ulp,
19829 		    ntohs(connp->conn_lport), B_FALSE);
19830 		connp->conn_anon_port = 0;
19831 	}
19832 	connp->conn_mlp_type = mlptSingle;
19833 
19834 	ipcl_hash_remove(connp);
19835 
19836 	ASSERT(mp->b_cont == NULL);
19837 	/*
19838 	 * Convert mp into a T_OK_ACK
19839 	 */
19840 	mp = mi_tpi_ok_ack_alloc(mp);
19841 
19842 	/*
19843 	 * should not happen in practice... T_OK_ACK is smaller than the
19844 	 * original message.
19845 	 */
19846 	if (mp == NULL)
19847 		return (NULL);
19848 
19849 	/*
19850 	 * Don't bzero the ports if its TCP since TCP still needs the
19851 	 * lport to remove it from its own bind hash. TCP will do the
19852 	 * cleanup.
19853 	 */
19854 	if (!IPCL_IS_TCP(connp))
19855 		bzero(&connp->u_port, sizeof (connp->u_port));
19856 
19857 	return (mp);
19858 }
19859 
19860 /*
19861  * Write side put procedure.  Outbound data, IOCTLs, responses from
19862  * resolvers, etc, come down through here.
19863  *
19864  * arg2 is always a queue_t *.
19865  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19866  * the zoneid.
19867  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19868  */
19869 void
19870 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19871 {
19872 	ip_output_options(arg, mp, arg2, caller, &zero_info);
19873 }
19874 
19875 void
19876 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
19877     ip_opt_info_t *infop)
19878 {
19879 	conn_t		*connp = NULL;
19880 	queue_t		*q = (queue_t *)arg2;
19881 	ipha_t		*ipha;
19882 #define	rptr	((uchar_t *)ipha)
19883 	ire_t		*ire = NULL;
19884 	ire_t		*sctp_ire = NULL;
19885 	uint32_t	v_hlen_tos_len;
19886 	ipaddr_t	dst;
19887 	mblk_t		*first_mp = NULL;
19888 	boolean_t	mctl_present;
19889 	ipsec_out_t	*io;
19890 	int		match_flags;
19891 	ill_t		*attach_ill = NULL;
19892 					/* Bind to IPIF_NOFAILOVER ill etc. */
19893 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19894 	ipif_t		*dst_ipif;
19895 	boolean_t	multirt_need_resolve = B_FALSE;
19896 	mblk_t		*copy_mp = NULL;
19897 	int		err;
19898 	zoneid_t	zoneid;
19899 	int	adjust;
19900 	uint16_t iplen;
19901 	boolean_t	need_decref = B_FALSE;
19902 	boolean_t	ignore_dontroute = B_FALSE;
19903 	boolean_t	ignore_nexthop = B_FALSE;
19904 	boolean_t	ip_nexthop = B_FALSE;
19905 	ipaddr_t	nexthop_addr;
19906 
19907 #ifdef	_BIG_ENDIAN
19908 #define	V_HLEN	(v_hlen_tos_len >> 24)
19909 #else
19910 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19911 #endif
19912 
19913 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19914 	    "ip_wput_start: q %p", q);
19915 
19916 	/*
19917 	 * ip_wput fast path
19918 	 */
19919 
19920 	/* is packet from ARP ? */
19921 	if (q->q_next != NULL) {
19922 		zoneid = (zoneid_t)(uintptr_t)arg;
19923 		goto qnext;
19924 	}
19925 
19926 	connp = (conn_t *)arg;
19927 	ASSERT(connp != NULL);
19928 	zoneid = connp->conn_zoneid;
19929 
19930 	/* is queue flow controlled? */
19931 	if ((q->q_first != NULL || connp->conn_draining) &&
19932 	    (caller == IP_WPUT)) {
19933 		ASSERT(!need_decref);
19934 		(void) putq(q, mp);
19935 		return;
19936 	}
19937 
19938 	/* Multidata transmit? */
19939 	if (DB_TYPE(mp) == M_MULTIDATA) {
19940 		/*
19941 		 * We should never get here, since all Multidata messages
19942 		 * originating from tcp should have been directed over to
19943 		 * tcp_multisend() in the first place.
19944 		 */
19945 		BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
19946 		freemsg(mp);
19947 		return;
19948 	} else if (DB_TYPE(mp) != M_DATA)
19949 		goto notdata;
19950 
19951 	if (mp->b_flag & MSGHASREF) {
19952 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19953 		mp->b_flag &= ~MSGHASREF;
19954 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19955 		need_decref = B_TRUE;
19956 	}
19957 	ipha = (ipha_t *)mp->b_rptr;
19958 
19959 	/* is IP header non-aligned or mblk smaller than basic IP header */
19960 #ifndef SAFETY_BEFORE_SPEED
19961 	if (!OK_32PTR(rptr) ||
19962 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19963 		goto hdrtoosmall;
19964 #endif
19965 
19966 	ASSERT(OK_32PTR(ipha));
19967 
19968 	/*
19969 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19970 	 * wrong version, we'll catch it again in ip_output_v6.
19971 	 *
19972 	 * Note that this is *only* locally-generated output here, and never
19973 	 * forwarded data, and that we need to deal only with transports that
19974 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19975 	 * label.)
19976 	 */
19977 	if (is_system_labeled() &&
19978 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19979 	    !connp->conn_ulp_labeled) {
19980 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19981 		    connp->conn_mac_exempt);
19982 		ipha = (ipha_t *)mp->b_rptr;
19983 		if (err != 0) {
19984 			first_mp = mp;
19985 			if (err == EINVAL)
19986 				goto icmp_parameter_problem;
19987 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19988 			goto discard_pkt;
19989 		}
19990 		iplen = ntohs(ipha->ipha_length) + adjust;
19991 		ipha->ipha_length = htons(iplen);
19992 	}
19993 
19994 	ASSERT(infop != NULL);
19995 
19996 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
19997 		/*
19998 		 * IP_PKTINFO ancillary option is present.
19999 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20000 		 * allows using address of any zone as the source address.
20001 		 */
20002 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20003 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20004 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY);
20005 		if (ire == NULL)
20006 			goto drop_pkt;
20007 		ire_refrele(ire);
20008 		ire = NULL;
20009 	}
20010 
20011 	/*
20012 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20013 	 * ill index passed in IP_PKTINFO.
20014 	 */
20015 	if (infop->ip_opt_ill_index != 0 &&
20016 	    connp->conn_xmit_if_ill == NULL &&
20017 	    connp->conn_nofailover_ill == NULL) {
20018 
20019 		xmit_ill = ill_lookup_on_ifindex(
20020 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL);
20021 
20022 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20023 			goto drop_pkt;
20024 		/*
20025 		 * check that there is an ipif belonging
20026 		 * to our zone. IPCL_ZONEID is not used because
20027 		 * IP_ALLZONES option is valid only when the ill is
20028 		 * accessible from all zones i.e has a valid ipif in
20029 		 * all zones.
20030 		 */
20031 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20032 			goto drop_pkt;
20033 		}
20034 	}
20035 
20036 	/*
20037 	 * If there is a policy, try to attach an ipsec_out in
20038 	 * the front. At the end, first_mp either points to a
20039 	 * M_DATA message or IPSEC_OUT message linked to a
20040 	 * M_DATA message. We have to do it now as we might
20041 	 * lose the "conn" if we go through ip_newroute.
20042 	 */
20043 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20044 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
20045 		    ipha->ipha_protocol)) == NULL)) {
20046 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20047 			if (need_decref)
20048 				CONN_DEC_REF(connp);
20049 			return;
20050 		} else {
20051 			ASSERT(mp->b_datap->db_type == M_CTL);
20052 			first_mp = mp;
20053 			mp = mp->b_cont;
20054 			mctl_present = B_TRUE;
20055 		}
20056 	} else {
20057 		first_mp = mp;
20058 		mctl_present = B_FALSE;
20059 	}
20060 
20061 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20062 
20063 	/* is wrong version or IP options present */
20064 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20065 		goto version_hdrlen_check;
20066 	dst = ipha->ipha_dst;
20067 
20068 	if (connp->conn_nofailover_ill != NULL) {
20069 		attach_ill = conn_get_held_ill(connp,
20070 		    &connp->conn_nofailover_ill, &err);
20071 		if (err == ILL_LOOKUP_FAILED) {
20072 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20073 			if (need_decref)
20074 				CONN_DEC_REF(connp);
20075 			freemsg(first_mp);
20076 			return;
20077 		}
20078 	}
20079 
20080 
20081 	/* is packet multicast? */
20082 	if (CLASSD(dst))
20083 		goto multicast;
20084 
20085 	/*
20086 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20087 	 * takes precedence over conn_dontroute and conn_nexthop_set
20088 	 */
20089 	if (xmit_ill != NULL) {
20090 		goto send_from_ill;
20091 	}
20092 
20093 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20094 	    (connp->conn_nexthop_set)) {
20095 		/*
20096 		 * If the destination is a broadcast or a loopback
20097 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20098 		 * through the standard path. But in the case of local
20099 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20100 		 * the standard path not IP_XMIT_IF.
20101 		 */
20102 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20103 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20104 		    (ire->ire_type != IRE_LOOPBACK))) {
20105 			if ((connp->conn_dontroute ||
20106 			    connp->conn_nexthop_set) && (ire != NULL) &&
20107 			    (ire->ire_type == IRE_LOCAL))
20108 				goto standard_path;
20109 
20110 			if (ire != NULL) {
20111 				ire_refrele(ire);
20112 				/* No more access to ire */
20113 				ire = NULL;
20114 			}
20115 			/*
20116 			 * bypass routing checks and go directly to
20117 			 * interface.
20118 			 */
20119 			if (connp->conn_dontroute) {
20120 				goto dontroute;
20121 			} else if (connp->conn_nexthop_set) {
20122 				ip_nexthop = B_TRUE;
20123 				nexthop_addr = connp->conn_nexthop_v4;
20124 				goto send_from_ill;
20125 			}
20126 
20127 			/*
20128 			 * If IP_XMIT_IF socket option is set,
20129 			 * then we allow unicast and multicast
20130 			 * packets to go through the ill. It is
20131 			 * quite possible that the destination
20132 			 * is not in the ire cache table and we
20133 			 * do not want to go to ip_newroute()
20134 			 * instead we call ip_newroute_ipif.
20135 			 */
20136 			xmit_ill = conn_get_held_ill(connp,
20137 			    &connp->conn_xmit_if_ill, &err);
20138 			if (err == ILL_LOOKUP_FAILED) {
20139 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20140 				if (attach_ill != NULL)
20141 					ill_refrele(attach_ill);
20142 				if (need_decref)
20143 					CONN_DEC_REF(connp);
20144 				freemsg(first_mp);
20145 				return;
20146 			}
20147 			goto send_from_ill;
20148 		}
20149 standard_path:
20150 		/* Must be a broadcast, a loopback or a local ire */
20151 		if (ire != NULL) {
20152 			ire_refrele(ire);
20153 			/* No more access to ire */
20154 			ire = NULL;
20155 		}
20156 	}
20157 
20158 	if (attach_ill != NULL)
20159 		goto send_from_ill;
20160 
20161 	/*
20162 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20163 	 * this for the tcp global queue and listen end point
20164 	 * as it does not really have a real destination to
20165 	 * talk to.  This is also true for SCTP.
20166 	 */
20167 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20168 	    !connp->conn_fully_bound) {
20169 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20170 		if (ire == NULL)
20171 			goto noirefound;
20172 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20173 		    "ip_wput_end: q %p (%S)", q, "end");
20174 
20175 		/*
20176 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20177 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20178 		 */
20179 		if (ire->ire_flags & RTF_MULTIRT) {
20180 
20181 			/*
20182 			 * Force the TTL of multirouted packets if required.
20183 			 * The TTL of such packets is bounded by the
20184 			 * ip_multirt_ttl ndd variable.
20185 			 */
20186 			if ((ip_multirt_ttl > 0) &&
20187 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
20188 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20189 				    "(was %d), dst 0x%08x\n",
20190 				    ip_multirt_ttl, ipha->ipha_ttl,
20191 				    ntohl(ire->ire_addr)));
20192 				ipha->ipha_ttl = ip_multirt_ttl;
20193 			}
20194 			/*
20195 			 * We look at this point if there are pending
20196 			 * unresolved routes. ire_multirt_resolvable()
20197 			 * checks in O(n) that all IRE_OFFSUBNET ire
20198 			 * entries for the packet's destination and
20199 			 * flagged RTF_MULTIRT are currently resolved.
20200 			 * If some remain unresolved, we make a copy
20201 			 * of the current message. It will be used
20202 			 * to initiate additional route resolutions.
20203 			 */
20204 			multirt_need_resolve =
20205 			    ire_multirt_need_resolve(ire->ire_addr,
20206 			    MBLK_GETLABEL(first_mp));
20207 			ip2dbg(("ip_wput[TCP]: ire %p, "
20208 			    "multirt_need_resolve %d, first_mp %p\n",
20209 			    (void *)ire, multirt_need_resolve,
20210 			    (void *)first_mp));
20211 			if (multirt_need_resolve) {
20212 				copy_mp = copymsg(first_mp);
20213 				if (copy_mp != NULL) {
20214 					MULTIRT_DEBUG_TAG(copy_mp);
20215 				}
20216 			}
20217 		}
20218 
20219 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20220 
20221 		/*
20222 		 * Try to resolve another multiroute if
20223 		 * ire_multirt_need_resolve() deemed it necessary.
20224 		 */
20225 		if (copy_mp != NULL) {
20226 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20227 		}
20228 		if (need_decref)
20229 			CONN_DEC_REF(connp);
20230 		return;
20231 	}
20232 
20233 	/*
20234 	 * Access to conn_ire_cache. (protected by conn_lock)
20235 	 *
20236 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20237 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20238 	 * send a packet or two with the IRE_CACHE that is going away.
20239 	 * Access to the ire requires an ire refhold on the ire prior to
20240 	 * its use since an interface unplumb thread may delete the cached
20241 	 * ire and release the refhold at any time.
20242 	 *
20243 	 * Caching an ire in the conn_ire_cache
20244 	 *
20245 	 * o Caching an ire pointer in the conn requires a strict check for
20246 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20247 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20248 	 * in the conn is done after making sure under the bucket lock that the
20249 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20250 	 * caching an ire after the unplumb thread has cleaned up the conn.
20251 	 * If the conn does not send a packet subsequently the unplumb thread
20252 	 * will be hanging waiting for the ire count to drop to zero.
20253 	 *
20254 	 * o We also need to atomically test for a null conn_ire_cache and
20255 	 * set the conn_ire_cache under the the protection of the conn_lock
20256 	 * to avoid races among concurrent threads trying to simultaneously
20257 	 * cache an ire in the conn_ire_cache.
20258 	 */
20259 	mutex_enter(&connp->conn_lock);
20260 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20261 
20262 	if (ire != NULL && ire->ire_addr == dst &&
20263 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20264 
20265 		IRE_REFHOLD(ire);
20266 		mutex_exit(&connp->conn_lock);
20267 
20268 	} else {
20269 		boolean_t cached = B_FALSE;
20270 		connp->conn_ire_cache = NULL;
20271 		mutex_exit(&connp->conn_lock);
20272 		/* Release the old ire */
20273 		if (ire != NULL && sctp_ire == NULL)
20274 			IRE_REFRELE_NOTR(ire);
20275 
20276 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20277 		if (ire == NULL)
20278 			goto noirefound;
20279 		IRE_REFHOLD_NOTR(ire);
20280 
20281 		mutex_enter(&connp->conn_lock);
20282 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
20283 		    connp->conn_ire_cache == NULL) {
20284 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20285 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20286 				connp->conn_ire_cache = ire;
20287 				cached = B_TRUE;
20288 			}
20289 			rw_exit(&ire->ire_bucket->irb_lock);
20290 		}
20291 		mutex_exit(&connp->conn_lock);
20292 
20293 		/*
20294 		 * We can continue to use the ire but since it was
20295 		 * not cached, we should drop the extra reference.
20296 		 */
20297 		if (!cached)
20298 			IRE_REFRELE_NOTR(ire);
20299 	}
20300 
20301 
20302 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20303 	    "ip_wput_end: q %p (%S)", q, "end");
20304 
20305 	/*
20306 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20307 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20308 	 */
20309 	if (ire->ire_flags & RTF_MULTIRT) {
20310 
20311 		/*
20312 		 * Force the TTL of multirouted packets if required.
20313 		 * The TTL of such packets is bounded by the
20314 		 * ip_multirt_ttl ndd variable.
20315 		 */
20316 		if ((ip_multirt_ttl > 0) &&
20317 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20318 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20319 			    "(was %d), dst 0x%08x\n",
20320 			    ip_multirt_ttl, ipha->ipha_ttl,
20321 			    ntohl(ire->ire_addr)));
20322 			ipha->ipha_ttl = ip_multirt_ttl;
20323 		}
20324 
20325 		/*
20326 		 * At this point, we check to see if there are any pending
20327 		 * unresolved routes. ire_multirt_resolvable()
20328 		 * checks in O(n) that all IRE_OFFSUBNET ire
20329 		 * entries for the packet's destination and
20330 		 * flagged RTF_MULTIRT are currently resolved.
20331 		 * If some remain unresolved, we make a copy
20332 		 * of the current message. It will be used
20333 		 * to initiate additional route resolutions.
20334 		 */
20335 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20336 		    MBLK_GETLABEL(first_mp));
20337 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20338 		    "multirt_need_resolve %d, first_mp %p\n",
20339 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20340 		if (multirt_need_resolve) {
20341 			copy_mp = copymsg(first_mp);
20342 			if (copy_mp != NULL) {
20343 				MULTIRT_DEBUG_TAG(copy_mp);
20344 			}
20345 		}
20346 	}
20347 
20348 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20349 
20350 	/*
20351 	 * Try to resolve another multiroute if
20352 	 * ire_multirt_resolvable() deemed it necessary
20353 	 */
20354 	if (copy_mp != NULL) {
20355 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20356 	}
20357 	if (need_decref)
20358 		CONN_DEC_REF(connp);
20359 	return;
20360 
20361 qnext:
20362 	/*
20363 	 * Upper Level Protocols pass down complete IP datagrams
20364 	 * as M_DATA messages.	Everything else is a sideshow.
20365 	 *
20366 	 * 1) We could be re-entering ip_wput because of ip_neworute
20367 	 *    in which case we could have a IPSEC_OUT message. We
20368 	 *    need to pass through ip_wput like other datagrams and
20369 	 *    hence cannot branch to ip_wput_nondata.
20370 	 *
20371 	 * 2) ARP, AH, ESP, and other clients who are on the module
20372 	 *    instance of IP stream, give us something to deal with.
20373 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20374 	 *
20375 	 * 3) ICMP replies also could come here.
20376 	 */
20377 	if (DB_TYPE(mp) != M_DATA) {
20378 	    notdata:
20379 		if (DB_TYPE(mp) == M_CTL) {
20380 			/*
20381 			 * M_CTL messages are used by ARP, AH and ESP to
20382 			 * communicate with IP. We deal with IPSEC_IN and
20383 			 * IPSEC_OUT here. ip_wput_nondata handles other
20384 			 * cases.
20385 			 */
20386 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20387 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20388 				first_mp = mp->b_cont;
20389 				first_mp->b_flag &= ~MSGHASREF;
20390 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20391 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20392 				CONN_DEC_REF(connp);
20393 				connp = NULL;
20394 			}
20395 			if (ii->ipsec_info_type == IPSEC_IN) {
20396 				/*
20397 				 * Either this message goes back to
20398 				 * IPSEC for further processing or to
20399 				 * ULP after policy checks.
20400 				 */
20401 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20402 				return;
20403 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20404 				io = (ipsec_out_t *)ii;
20405 				if (io->ipsec_out_proc_begin) {
20406 					/*
20407 					 * IPSEC processing has already started.
20408 					 * Complete it.
20409 					 * IPQoS notes: We don't care what is
20410 					 * in ipsec_out_ill_index since this
20411 					 * won't be processed for IPQoS policies
20412 					 * in ipsec_out_process.
20413 					 */
20414 					ipsec_out_process(q, mp, NULL,
20415 					    io->ipsec_out_ill_index);
20416 					return;
20417 				} else {
20418 					connp = (q->q_next != NULL) ?
20419 					    NULL : Q_TO_CONN(q);
20420 					first_mp = mp;
20421 					mp = mp->b_cont;
20422 					mctl_present = B_TRUE;
20423 				}
20424 				zoneid = io->ipsec_out_zoneid;
20425 				ASSERT(zoneid != ALL_ZONES);
20426 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20427 				/*
20428 				 * It's an IPsec control message requesting
20429 				 * an SADB update to be sent to the IPsec
20430 				 * hardware acceleration capable ills.
20431 				 */
20432 				ipsec_ctl_t *ipsec_ctl =
20433 				    (ipsec_ctl_t *)mp->b_rptr;
20434 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20435 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20436 				mblk_t *cmp = mp->b_cont;
20437 
20438 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20439 				ASSERT(cmp != NULL);
20440 
20441 				freeb(mp);
20442 				ill_ipsec_capab_send_all(satype, cmp, sa);
20443 				return;
20444 			} else {
20445 				/*
20446 				 * This must be ARP or special TSOL signaling.
20447 				 */
20448 				ip_wput_nondata(NULL, q, mp, NULL);
20449 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20450 				    "ip_wput_end: q %p (%S)", q, "nondata");
20451 				return;
20452 			}
20453 		} else {
20454 			/*
20455 			 * This must be non-(ARP/AH/ESP) messages.
20456 			 */
20457 			ASSERT(!need_decref);
20458 			ip_wput_nondata(NULL, q, mp, NULL);
20459 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20460 			    "ip_wput_end: q %p (%S)", q, "nondata");
20461 			return;
20462 		}
20463 	} else {
20464 		first_mp = mp;
20465 		mctl_present = B_FALSE;
20466 	}
20467 
20468 	ASSERT(first_mp != NULL);
20469 	/*
20470 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20471 	 * to make sure that this packet goes out on the same interface it
20472 	 * came in. We handle that here.
20473 	 */
20474 	if (mctl_present) {
20475 		uint_t ifindex;
20476 
20477 		io = (ipsec_out_t *)first_mp->b_rptr;
20478 		if (io->ipsec_out_attach_if ||
20479 		    io->ipsec_out_xmit_if ||
20480 		    io->ipsec_out_ip_nexthop) {
20481 			ill_t	*ill;
20482 
20483 			/*
20484 			 * We may have lost the conn context if we are
20485 			 * coming here from ip_newroute(). Copy the
20486 			 * nexthop information.
20487 			 */
20488 			if (io->ipsec_out_ip_nexthop) {
20489 				ip_nexthop = B_TRUE;
20490 				nexthop_addr = io->ipsec_out_nexthop_addr;
20491 
20492 				ipha = (ipha_t *)mp->b_rptr;
20493 				dst = ipha->ipha_dst;
20494 				goto send_from_ill;
20495 			} else {
20496 				ASSERT(io->ipsec_out_ill_index != 0);
20497 				ifindex = io->ipsec_out_ill_index;
20498 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20499 				    NULL, NULL, NULL, NULL);
20500 				/*
20501 				 * ipsec_out_xmit_if bit is used to tell
20502 				 * ip_wput to use the ill to send outgoing data
20503 				 * as we have no conn when data comes from ICMP
20504 				 * error msg routines. Currently this feature is
20505 				 * only used by ip_mrtun_forward routine.
20506 				 */
20507 				if (io->ipsec_out_xmit_if) {
20508 					xmit_ill = ill;
20509 					if (xmit_ill == NULL) {
20510 						ip1dbg(("ip_output:bad ifindex "
20511 						    "for xmit_ill %d\n",
20512 						    ifindex));
20513 						freemsg(first_mp);
20514 						BUMP_MIB(&ip_mib,
20515 						    ipIfStatsOutDiscards);
20516 						ASSERT(!need_decref);
20517 						return;
20518 					}
20519 					/* Free up the ipsec_out_t mblk */
20520 					ASSERT(first_mp->b_cont == mp);
20521 					first_mp->b_cont = NULL;
20522 					freeb(first_mp);
20523 					/* Just send the IP header+ICMP+data */
20524 					first_mp = mp;
20525 					ipha = (ipha_t *)mp->b_rptr;
20526 					dst = ipha->ipha_dst;
20527 					goto send_from_ill;
20528 				} else {
20529 					attach_ill = ill;
20530 				}
20531 
20532 				if (attach_ill == NULL) {
20533 					ASSERT(xmit_ill == NULL);
20534 					ip1dbg(("ip_output: bad ifindex for "
20535 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20536 					    ifindex));
20537 					freemsg(first_mp);
20538 					BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20539 					ASSERT(!need_decref);
20540 					return;
20541 				}
20542 			}
20543 		}
20544 	}
20545 
20546 	ASSERT(xmit_ill == NULL);
20547 
20548 	/* We have a complete IP datagram heading outbound. */
20549 	ipha = (ipha_t *)mp->b_rptr;
20550 
20551 #ifndef SPEED_BEFORE_SAFETY
20552 	/*
20553 	 * Make sure we have a full-word aligned message and that at least
20554 	 * a simple IP header is accessible in the first message.  If not,
20555 	 * try a pullup.
20556 	 */
20557 	if (!OK_32PTR(rptr) ||
20558 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20559 	    hdrtoosmall:
20560 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20561 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20562 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20563 			if (first_mp == NULL)
20564 				first_mp = mp;
20565 			goto discard_pkt;
20566 		}
20567 
20568 		/* This function assumes that mp points to an IPv4 packet. */
20569 		if (is_system_labeled() && q->q_next == NULL &&
20570 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20571 		    !connp->conn_ulp_labeled) {
20572 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20573 			    &adjust, connp->conn_mac_exempt);
20574 			ipha = (ipha_t *)mp->b_rptr;
20575 			if (first_mp != NULL)
20576 				first_mp->b_cont = mp;
20577 			if (err != 0) {
20578 				if (first_mp == NULL)
20579 					first_mp = mp;
20580 				if (err == EINVAL)
20581 					goto icmp_parameter_problem;
20582 				ip2dbg(("ip_wput: label check failed (%d)\n",
20583 				    err));
20584 				goto discard_pkt;
20585 			}
20586 			iplen = ntohs(ipha->ipha_length) + adjust;
20587 			ipha->ipha_length = htons(iplen);
20588 		}
20589 
20590 		ipha = (ipha_t *)mp->b_rptr;
20591 		if (first_mp == NULL) {
20592 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20593 			/*
20594 			 * If we got here because of "goto hdrtoosmall"
20595 			 * We need to attach a IPSEC_OUT.
20596 			 */
20597 			if (connp->conn_out_enforce_policy) {
20598 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20599 				    NULL, ipha->ipha_protocol)) == NULL)) {
20600 					BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20601 					if (need_decref)
20602 						CONN_DEC_REF(connp);
20603 					return;
20604 				} else {
20605 					ASSERT(mp->b_datap->db_type == M_CTL);
20606 					first_mp = mp;
20607 					mp = mp->b_cont;
20608 					mctl_present = B_TRUE;
20609 				}
20610 			} else {
20611 				first_mp = mp;
20612 				mctl_present = B_FALSE;
20613 			}
20614 		}
20615 	}
20616 #endif
20617 
20618 	/* Most of the code below is written for speed, not readability */
20619 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20620 
20621 	/*
20622 	 * If ip_newroute() fails, we're going to need a full
20623 	 * header for the icmp wraparound.
20624 	 */
20625 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20626 		uint_t	v_hlen;
20627 	    version_hdrlen_check:
20628 		ASSERT(first_mp != NULL);
20629 		v_hlen = V_HLEN;
20630 		/*
20631 		 * siphon off IPv6 packets coming down from transport
20632 		 * layer modules here.
20633 		 * Note: high-order bit carries NUD reachability confirmation
20634 		 */
20635 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20636 			/*
20637 			 * XXX implement a IPv4 and IPv6 packet counter per
20638 			 * conn and switch when ratio exceeds e.g. 10:1
20639 			 */
20640 #ifdef notyet
20641 			if (q->q_next == NULL) /* Avoid ill queue */
20642 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
20643 #endif
20644 			BUMP_MIB(&ip_mib, ipIfStatsOutWrongIPVersion);
20645 			ASSERT(xmit_ill == NULL);
20646 			if (attach_ill != NULL)
20647 				ill_refrele(attach_ill);
20648 			if (need_decref)
20649 				mp->b_flag |= MSGHASREF;
20650 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20651 			return;
20652 		}
20653 
20654 		if ((v_hlen >> 4) != IP_VERSION) {
20655 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20656 			    "ip_wput_end: q %p (%S)", q, "badvers");
20657 			goto discard_pkt;
20658 		}
20659 		/*
20660 		 * Is the header length at least 20 bytes?
20661 		 *
20662 		 * Are there enough bytes accessible in the header?  If
20663 		 * not, try a pullup.
20664 		 */
20665 		v_hlen &= 0xF;
20666 		v_hlen <<= 2;
20667 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20668 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20669 			    "ip_wput_end: q %p (%S)", q, "badlen");
20670 			goto discard_pkt;
20671 		}
20672 		if (v_hlen > (mp->b_wptr - rptr)) {
20673 			if (!pullupmsg(mp, v_hlen)) {
20674 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20675 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20676 				goto discard_pkt;
20677 			}
20678 			ipha = (ipha_t *)mp->b_rptr;
20679 		}
20680 		/*
20681 		 * Move first entry from any source route into ipha_dst and
20682 		 * verify the options
20683 		 */
20684 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
20685 			ASSERT(xmit_ill == NULL);
20686 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20687 			if (attach_ill != NULL)
20688 				ill_refrele(attach_ill);
20689 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20690 			    "ip_wput_end: q %p (%S)", q, "badopts");
20691 			if (need_decref)
20692 				CONN_DEC_REF(connp);
20693 			return;
20694 		}
20695 	}
20696 	dst = ipha->ipha_dst;
20697 
20698 	/*
20699 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20700 	 * we have to run the packet through ip_newroute which will take
20701 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20702 	 * a resolver, or assigning a default gateway, etc.
20703 	 */
20704 	if (CLASSD(dst)) {
20705 		ipif_t	*ipif;
20706 		uint32_t setsrc = 0;
20707 
20708 	    multicast:
20709 		ASSERT(first_mp != NULL);
20710 		ip2dbg(("ip_wput: CLASSD\n"));
20711 		if (connp == NULL) {
20712 			/*
20713 			 * Use the first good ipif on the ill.
20714 			 * XXX Should this ever happen? (Appears
20715 			 * to show up with just ppp and no ethernet due
20716 			 * to in.rdisc.)
20717 			 * However, ire_send should be able to
20718 			 * call ip_wput_ire directly.
20719 			 *
20720 			 * XXX Also, this can happen for ICMP and other packets
20721 			 * with multicast source addresses.  Perhaps we should
20722 			 * fix things so that we drop the packet in question,
20723 			 * but for now, just run with it.
20724 			 */
20725 			ill_t *ill = (ill_t *)q->q_ptr;
20726 
20727 			/*
20728 			 * Don't honor attach_if for this case. If ill
20729 			 * is part of the group, ipif could belong to
20730 			 * any ill and we cannot maintain attach_ill
20731 			 * and ipif_ill same anymore and the assert
20732 			 * below would fail.
20733 			 */
20734 			if (mctl_present && io->ipsec_out_attach_if) {
20735 				io->ipsec_out_ill_index = 0;
20736 				io->ipsec_out_attach_if = B_FALSE;
20737 				ASSERT(attach_ill != NULL);
20738 				ill_refrele(attach_ill);
20739 				attach_ill = NULL;
20740 			}
20741 
20742 			ASSERT(attach_ill == NULL);
20743 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20744 			if (ipif == NULL) {
20745 				if (need_decref)
20746 					CONN_DEC_REF(connp);
20747 				freemsg(first_mp);
20748 				return;
20749 			}
20750 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20751 			    ntohl(dst), ill->ill_name));
20752 		} else {
20753 			/*
20754 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
20755 			 * and IP_MULTICAST_IF.
20756 			 * Block comment above this function explains the
20757 			 * locking mechanism used here
20758 			 */
20759 			if (xmit_ill == NULL) {
20760 				xmit_ill = conn_get_held_ill(connp,
20761 				    &connp->conn_xmit_if_ill, &err);
20762 				if (err == ILL_LOOKUP_FAILED) {
20763 					ip1dbg(("ip_wput: No ill for "
20764 					    "IP_XMIT_IF\n"));
20765 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20766 					goto drop_pkt;
20767 				}
20768 			}
20769 
20770 			if (xmit_ill == NULL) {
20771 				ipif = conn_get_held_ipif(connp,
20772 				    &connp->conn_multicast_ipif, &err);
20773 				if (err == IPIF_LOOKUP_FAILED) {
20774 					ip1dbg(("ip_wput: No ipif for "
20775 					    "multicast\n"));
20776 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20777 					goto drop_pkt;
20778 				}
20779 			}
20780 			if (xmit_ill != NULL) {
20781 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20782 				if (ipif == NULL) {
20783 					ip1dbg(("ip_wput: No ipif for "
20784 					    "IP_XMIT_IF\n"));
20785 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20786 					goto drop_pkt;
20787 				}
20788 			} else if (ipif == NULL || ipif->ipif_isv6) {
20789 				/*
20790 				 * We must do this ipif determination here
20791 				 * else we could pass through ip_newroute
20792 				 * and come back here without the conn context.
20793 				 *
20794 				 * Note: we do late binding i.e. we bind to
20795 				 * the interface when the first packet is sent.
20796 				 * For performance reasons we do not rebind on
20797 				 * each packet but keep the binding until the
20798 				 * next IP_MULTICAST_IF option.
20799 				 *
20800 				 * conn_multicast_{ipif,ill} are shared between
20801 				 * IPv4 and IPv6 and AF_INET6 sockets can
20802 				 * send both IPv4 and IPv6 packets. Hence
20803 				 * we have to check that "isv6" matches above.
20804 				 */
20805 				if (ipif != NULL)
20806 					ipif_refrele(ipif);
20807 				ipif = ipif_lookup_group(dst, zoneid);
20808 				if (ipif == NULL) {
20809 					ip1dbg(("ip_wput: No ipif for "
20810 					    "multicast\n"));
20811 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20812 					goto drop_pkt;
20813 				}
20814 				err = conn_set_held_ipif(connp,
20815 				    &connp->conn_multicast_ipif, ipif);
20816 				if (err == IPIF_LOOKUP_FAILED) {
20817 					ipif_refrele(ipif);
20818 					ip1dbg(("ip_wput: No ipif for "
20819 					    "multicast\n"));
20820 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20821 					goto drop_pkt;
20822 				}
20823 			}
20824 		}
20825 		ASSERT(!ipif->ipif_isv6);
20826 		/*
20827 		 * As we may lose the conn by the time we reach ip_wput_ire,
20828 		 * we copy conn_multicast_loop and conn_dontroute on to an
20829 		 * ipsec_out. In case if this datagram goes out secure,
20830 		 * we need the ill_index also. Copy that also into the
20831 		 * ipsec_out.
20832 		 */
20833 		if (mctl_present) {
20834 			io = (ipsec_out_t *)first_mp->b_rptr;
20835 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20836 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20837 		} else {
20838 			ASSERT(mp == first_mp);
20839 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20840 			    BPRI_HI)) == NULL) {
20841 				ipif_refrele(ipif);
20842 				first_mp = mp;
20843 				goto discard_pkt;
20844 			}
20845 			first_mp->b_datap->db_type = M_CTL;
20846 			first_mp->b_wptr += sizeof (ipsec_info_t);
20847 			/* ipsec_out_secure is B_FALSE now */
20848 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20849 			io = (ipsec_out_t *)first_mp->b_rptr;
20850 			io->ipsec_out_type = IPSEC_OUT;
20851 			io->ipsec_out_len = sizeof (ipsec_out_t);
20852 			io->ipsec_out_use_global_policy = B_TRUE;
20853 			first_mp->b_cont = mp;
20854 			mctl_present = B_TRUE;
20855 		}
20856 		if (attach_ill != NULL) {
20857 			ASSERT(attach_ill == ipif->ipif_ill);
20858 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20859 
20860 			/*
20861 			 * Check if we need an ire that will not be
20862 			 * looked up by anybody else i.e. HIDDEN.
20863 			 */
20864 			if (ill_is_probeonly(attach_ill)) {
20865 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20866 			}
20867 			io->ipsec_out_ill_index =
20868 			    attach_ill->ill_phyint->phyint_ifindex;
20869 			io->ipsec_out_attach_if = B_TRUE;
20870 		} else {
20871 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20872 			io->ipsec_out_ill_index =
20873 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20874 		}
20875 		if (connp != NULL) {
20876 			io->ipsec_out_multicast_loop =
20877 			    connp->conn_multicast_loop;
20878 			io->ipsec_out_dontroute = connp->conn_dontroute;
20879 			io->ipsec_out_zoneid = connp->conn_zoneid;
20880 		}
20881 		/*
20882 		 * If the application uses IP_MULTICAST_IF with
20883 		 * different logical addresses of the same ILL, we
20884 		 * need to make sure that the soruce address of
20885 		 * the packet matches the logical IP address used
20886 		 * in the option. We do it by initializing ipha_src
20887 		 * here. This should keep IPSEC also happy as
20888 		 * when we return from IPSEC processing, we don't
20889 		 * have to worry about getting the right address on
20890 		 * the packet. Thus it is sufficient to look for
20891 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20892 		 * MATCH_IRE_IPIF.
20893 		 *
20894 		 * NOTE : We need to do it for non-secure case also as
20895 		 * this might go out secure if there is a global policy
20896 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20897 		 * address, the source should be initialized already and
20898 		 * hence we won't be initializing here.
20899 		 *
20900 		 * As we do not have the ire yet, it is possible that
20901 		 * we set the source address here and then later discover
20902 		 * that the ire implies the source address to be assigned
20903 		 * through the RTF_SETSRC flag.
20904 		 * In that case, the setsrc variable will remind us
20905 		 * that overwritting the source address by the one
20906 		 * of the RTF_SETSRC-flagged ire is allowed.
20907 		 */
20908 		if (ipha->ipha_src == INADDR_ANY &&
20909 		    (connp == NULL || !connp->conn_unspec_src)) {
20910 			ipha->ipha_src = ipif->ipif_src_addr;
20911 			setsrc = RTF_SETSRC;
20912 		}
20913 		/*
20914 		 * Find an IRE which matches the destination and the outgoing
20915 		 * queue (i.e. the outgoing interface.)
20916 		 * For loopback use a unicast IP address for
20917 		 * the ire lookup.
20918 		 */
20919 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20920 		    PHYI_LOOPBACK) {
20921 			dst = ipif->ipif_lcl_addr;
20922 		}
20923 		/*
20924 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20925 		 * We don't need to lookup ire in ctable as the packet
20926 		 * needs to be sent to the destination through the specified
20927 		 * ill irrespective of ires in the cache table.
20928 		 */
20929 		ire = NULL;
20930 		if (xmit_ill == NULL) {
20931 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20932 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20933 		}
20934 
20935 		/*
20936 		 * refrele attach_ill as its not needed anymore.
20937 		 */
20938 		if (attach_ill != NULL) {
20939 			ill_refrele(attach_ill);
20940 			attach_ill = NULL;
20941 		}
20942 
20943 		if (ire == NULL) {
20944 			/*
20945 			 * Multicast loopback and multicast forwarding is
20946 			 * done in ip_wput_ire.
20947 			 *
20948 			 * Mark this packet to make it be delivered to
20949 			 * ip_wput_ire after the new ire has been
20950 			 * created.
20951 			 *
20952 			 * The call to ip_newroute_ipif takes into account
20953 			 * the setsrc reminder. In any case, we take care
20954 			 * of the RTF_MULTIRT flag.
20955 			 */
20956 			mp->b_prev = mp->b_next = NULL;
20957 			if (xmit_ill == NULL ||
20958 			    xmit_ill->ill_ipif_up_count > 0) {
20959 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20960 				    setsrc | RTF_MULTIRT, zoneid, infop);
20961 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20962 				    "ip_wput_end: q %p (%S)", q, "noire");
20963 			} else {
20964 				freemsg(first_mp);
20965 			}
20966 			ipif_refrele(ipif);
20967 			if (xmit_ill != NULL)
20968 				ill_refrele(xmit_ill);
20969 			if (need_decref)
20970 				CONN_DEC_REF(connp);
20971 			return;
20972 		}
20973 
20974 		ipif_refrele(ipif);
20975 		ipif = NULL;
20976 		ASSERT(xmit_ill == NULL);
20977 
20978 		/*
20979 		 * Honor the RTF_SETSRC flag for multicast packets,
20980 		 * if allowed by the setsrc reminder.
20981 		 */
20982 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20983 			ipha->ipha_src = ire->ire_src_addr;
20984 		}
20985 
20986 		/*
20987 		 * Unconditionally force the TTL to 1 for
20988 		 * multirouted multicast packets:
20989 		 * multirouted multicast should not cross
20990 		 * multicast routers.
20991 		 */
20992 		if (ire->ire_flags & RTF_MULTIRT) {
20993 			if (ipha->ipha_ttl > 1) {
20994 				ip2dbg(("ip_wput: forcing multicast "
20995 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20996 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20997 				ipha->ipha_ttl = 1;
20998 			}
20999 		}
21000 	} else {
21001 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
21002 		if ((ire != NULL) && (ire->ire_type &
21003 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21004 			ignore_dontroute = B_TRUE;
21005 			ignore_nexthop = B_TRUE;
21006 		}
21007 		if (ire != NULL) {
21008 			ire_refrele(ire);
21009 			ire = NULL;
21010 		}
21011 		/*
21012 		 * Guard against coming in from arp in which case conn is NULL.
21013 		 * Also guard against non M_DATA with dontroute set but
21014 		 * destined to local, loopback or broadcast addresses.
21015 		 */
21016 		if (connp != NULL && connp->conn_dontroute &&
21017 		    !ignore_dontroute) {
21018 dontroute:
21019 			/*
21020 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21021 			 * routing protocols from seeing false direct
21022 			 * connectivity.
21023 			 */
21024 			ipha->ipha_ttl = 1;
21025 			/*
21026 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21027 			 * along with SO_DONTROUTE, higher precedence is
21028 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21029 			 */
21030 			if (connp->conn_xmit_if_ill == NULL) {
21031 				/* If suitable ipif not found, drop packet */
21032 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
21033 				if (dst_ipif == NULL) {
21034 					ip1dbg(("ip_wput: no route for "
21035 					    "dst using SO_DONTROUTE\n"));
21036 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
21037 					mp->b_prev = mp->b_next = NULL;
21038 					if (first_mp == NULL)
21039 						first_mp = mp;
21040 					goto drop_pkt;
21041 				} else {
21042 					/*
21043 					 * If suitable ipif has been found, set
21044 					 * xmit_ill to the corresponding
21045 					 * ipif_ill because we'll be following
21046 					 * the IP_XMIT_IF logic.
21047 					 */
21048 					ASSERT(xmit_ill == NULL);
21049 					xmit_ill = dst_ipif->ipif_ill;
21050 					mutex_enter(&xmit_ill->ill_lock);
21051 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21052 						mutex_exit(&xmit_ill->ill_lock);
21053 						xmit_ill = NULL;
21054 						ipif_refrele(dst_ipif);
21055 						ip1dbg(("ip_wput: no route for"
21056 						    " dst using"
21057 						    " SO_DONTROUTE\n"));
21058 						BUMP_MIB(&ip_mib,
21059 						    ipIfStatsOutNoRoutes);
21060 						mp->b_prev = mp->b_next = NULL;
21061 						if (first_mp == NULL)
21062 							first_mp = mp;
21063 						goto drop_pkt;
21064 					}
21065 					ill_refhold_locked(xmit_ill);
21066 					mutex_exit(&xmit_ill->ill_lock);
21067 					ipif_refrele(dst_ipif);
21068 				}
21069 			}
21070 
21071 		}
21072 		/*
21073 		 * If we are bound to IPIF_NOFAILOVER address, look for
21074 		 * an IRE_CACHE matching the ill.
21075 		 */
21076 send_from_ill:
21077 		if (attach_ill != NULL) {
21078 			ipif_t	*attach_ipif;
21079 
21080 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21081 
21082 			/*
21083 			 * Check if we need an ire that will not be
21084 			 * looked up by anybody else i.e. HIDDEN.
21085 			 */
21086 			if (ill_is_probeonly(attach_ill)) {
21087 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21088 			}
21089 
21090 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21091 			if (attach_ipif == NULL) {
21092 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21093 				goto discard_pkt;
21094 			}
21095 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21096 			    zoneid, MBLK_GETLABEL(mp), match_flags);
21097 			ipif_refrele(attach_ipif);
21098 		} else if (xmit_ill != NULL || (connp != NULL &&
21099 			    connp->conn_xmit_if_ill != NULL)) {
21100 			/*
21101 			 * Mark this packet as originated locally
21102 			 */
21103 			mp->b_prev = mp->b_next = NULL;
21104 			/*
21105 			 * xmit_ill could be NULL if SO_DONTROUTE
21106 			 * is also set.
21107 			 */
21108 			if (xmit_ill == NULL) {
21109 				xmit_ill = conn_get_held_ill(connp,
21110 				    &connp->conn_xmit_if_ill, &err);
21111 				if (err == ILL_LOOKUP_FAILED) {
21112 					BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
21113 					if (need_decref)
21114 						CONN_DEC_REF(connp);
21115 					freemsg(first_mp);
21116 					return;
21117 				}
21118 				if (xmit_ill == NULL) {
21119 					if (connp->conn_dontroute)
21120 						goto dontroute;
21121 					goto send_from_ill;
21122 				}
21123 			}
21124 			/*
21125 			 * Could be SO_DONTROUTE case also.
21126 			 * check at least one interface is UP as
21127 			 * specified by this ILL
21128 			 */
21129 			if (xmit_ill->ill_ipif_up_count > 0) {
21130 				ipif_t *ipif;
21131 
21132 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21133 				if (ipif == NULL) {
21134 					ip1dbg(("ip_output: "
21135 					    "xmit_ill NULL ipif\n"));
21136 					goto drop_pkt;
21137 				}
21138 				/*
21139 				 * Look for a ire that is part of the group,
21140 				 * if found use it else call ip_newroute_ipif.
21141 				 * IPCL_ZONEID is not used for matching because
21142 				 * IP_ALLZONES option is valid only when the
21143 				 * ill is accessible from all zones i.e has a
21144 				 * valid ipif in all zones.
21145 				 */
21146 				match_flags = MATCH_IRE_ILL_GROUP |
21147 				    MATCH_IRE_SECATTR;
21148 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21149 				    MBLK_GETLABEL(mp), match_flags);
21150 				/*
21151 				 * If an ire exists use it or else create
21152 				 * an ire but don't add it to the cache.
21153 				 * Adding an ire may cause issues with
21154 				 * asymmetric routing.
21155 				 * In case of multiroute always act as if
21156 				 * ire does not exist.
21157 				 */
21158 				if (ire == NULL ||
21159 				    ire->ire_flags & RTF_MULTIRT) {
21160 					if (ire != NULL)
21161 						ire_refrele(ire);
21162 					ip_newroute_ipif(q, first_mp, ipif,
21163 					    dst, connp, 0, zoneid, infop);
21164 					ipif_refrele(ipif);
21165 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21166 					ill_refrele(xmit_ill);
21167 					if (need_decref)
21168 						CONN_DEC_REF(connp);
21169 					return;
21170 				}
21171 				ipif_refrele(ipif);
21172 			} else {
21173 				goto drop_pkt;
21174 			}
21175 		} else if (ip_nexthop || (connp != NULL &&
21176 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21177 			if (!ip_nexthop) {
21178 				ip_nexthop = B_TRUE;
21179 				nexthop_addr = connp->conn_nexthop_v4;
21180 			}
21181 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21182 			    MATCH_IRE_GW;
21183 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21184 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
21185 		} else {
21186 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
21187 		}
21188 		if (!ire) {
21189 			/*
21190 			 * Make sure we don't load spread if this
21191 			 * is IPIF_NOFAILOVER case.
21192 			 */
21193 			if ((attach_ill != NULL) ||
21194 			    (ip_nexthop && !ignore_nexthop)) {
21195 				if (mctl_present) {
21196 					io = (ipsec_out_t *)first_mp->b_rptr;
21197 					ASSERT(first_mp->b_datap->db_type ==
21198 					    M_CTL);
21199 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21200 				} else {
21201 					ASSERT(mp == first_mp);
21202 					first_mp = allocb(
21203 					    sizeof (ipsec_info_t), BPRI_HI);
21204 					if (first_mp == NULL) {
21205 						first_mp = mp;
21206 						goto discard_pkt;
21207 					}
21208 					first_mp->b_datap->db_type = M_CTL;
21209 					first_mp->b_wptr +=
21210 					    sizeof (ipsec_info_t);
21211 					/* ipsec_out_secure is B_FALSE now */
21212 					bzero(first_mp->b_rptr,
21213 					    sizeof (ipsec_info_t));
21214 					io = (ipsec_out_t *)first_mp->b_rptr;
21215 					io->ipsec_out_type = IPSEC_OUT;
21216 					io->ipsec_out_len =
21217 					    sizeof (ipsec_out_t);
21218 					io->ipsec_out_use_global_policy =
21219 					    B_TRUE;
21220 					first_mp->b_cont = mp;
21221 					mctl_present = B_TRUE;
21222 				}
21223 				if (attach_ill != NULL) {
21224 					io->ipsec_out_ill_index = attach_ill->
21225 					    ill_phyint->phyint_ifindex;
21226 					io->ipsec_out_attach_if = B_TRUE;
21227 				} else {
21228 					io->ipsec_out_ip_nexthop = ip_nexthop;
21229 					io->ipsec_out_nexthop_addr =
21230 					    nexthop_addr;
21231 				}
21232 			}
21233 noirefound:
21234 			/*
21235 			 * Mark this packet as having originated on
21236 			 * this machine.  This will be noted in
21237 			 * ire_add_then_send, which needs to know
21238 			 * whether to run it back through ip_wput or
21239 			 * ip_rput following successful resolution.
21240 			 */
21241 			mp->b_prev = NULL;
21242 			mp->b_next = NULL;
21243 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid);
21244 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21245 			    "ip_wput_end: q %p (%S)", q, "newroute");
21246 			if (attach_ill != NULL)
21247 				ill_refrele(attach_ill);
21248 			if (xmit_ill != NULL)
21249 				ill_refrele(xmit_ill);
21250 			if (need_decref)
21251 				CONN_DEC_REF(connp);
21252 			return;
21253 		}
21254 	}
21255 
21256 	/* We now know where we are going with it. */
21257 
21258 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21259 	    "ip_wput_end: q %p (%S)", q, "end");
21260 
21261 	/*
21262 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21263 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21264 	 */
21265 	if (ire->ire_flags & RTF_MULTIRT) {
21266 		/*
21267 		 * Force the TTL of multirouted packets if required.
21268 		 * The TTL of such packets is bounded by the
21269 		 * ip_multirt_ttl ndd variable.
21270 		 */
21271 		if ((ip_multirt_ttl > 0) &&
21272 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
21273 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21274 			    "(was %d), dst 0x%08x\n",
21275 			    ip_multirt_ttl, ipha->ipha_ttl,
21276 			    ntohl(ire->ire_addr)));
21277 			ipha->ipha_ttl = ip_multirt_ttl;
21278 		}
21279 		/*
21280 		 * At this point, we check to see if there are any pending
21281 		 * unresolved routes. ire_multirt_resolvable()
21282 		 * checks in O(n) that all IRE_OFFSUBNET ire
21283 		 * entries for the packet's destination and
21284 		 * flagged RTF_MULTIRT are currently resolved.
21285 		 * If some remain unresolved, we make a copy
21286 		 * of the current message. It will be used
21287 		 * to initiate additional route resolutions.
21288 		 */
21289 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21290 		    MBLK_GETLABEL(first_mp));
21291 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21292 		    "multirt_need_resolve %d, first_mp %p\n",
21293 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21294 		if (multirt_need_resolve) {
21295 			copy_mp = copymsg(first_mp);
21296 			if (copy_mp != NULL) {
21297 				MULTIRT_DEBUG_TAG(copy_mp);
21298 			}
21299 		}
21300 	}
21301 
21302 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21303 	/*
21304 	 * Try to resolve another multiroute if
21305 	 * ire_multirt_resolvable() deemed it necessary.
21306 	 * At this point, we need to distinguish
21307 	 * multicasts from other packets. For multicasts,
21308 	 * we call ip_newroute_ipif() and request that both
21309 	 * multirouting and setsrc flags are checked.
21310 	 */
21311 	if (copy_mp != NULL) {
21312 		if (CLASSD(dst)) {
21313 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
21314 			if (ipif) {
21315 				ASSERT(infop->ip_opt_ill_index == 0);
21316 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21317 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21318 				ipif_refrele(ipif);
21319 			} else {
21320 				MULTIRT_DEBUG_UNTAG(copy_mp);
21321 				freemsg(copy_mp);
21322 				copy_mp = NULL;
21323 			}
21324 		} else {
21325 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
21326 		}
21327 	}
21328 	if (attach_ill != NULL)
21329 		ill_refrele(attach_ill);
21330 	if (xmit_ill != NULL)
21331 		ill_refrele(xmit_ill);
21332 	if (need_decref)
21333 		CONN_DEC_REF(connp);
21334 	return;
21335 
21336 icmp_parameter_problem:
21337 	/* could not have originated externally */
21338 	ASSERT(mp->b_prev == NULL);
21339 	if (ip_hdr_complete(ipha, zoneid) == 0) {
21340 		BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
21341 		/* it's the IP header length that's in trouble */
21342 		icmp_param_problem(q, first_mp, 0, zoneid);
21343 		first_mp = NULL;
21344 	}
21345 
21346 discard_pkt:
21347 	BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
21348 drop_pkt:
21349 	ip1dbg(("ip_wput: dropped packet\n"));
21350 	if (ire != NULL)
21351 		ire_refrele(ire);
21352 	if (need_decref)
21353 		CONN_DEC_REF(connp);
21354 	freemsg(first_mp);
21355 	if (attach_ill != NULL)
21356 		ill_refrele(attach_ill);
21357 	if (xmit_ill != NULL)
21358 		ill_refrele(xmit_ill);
21359 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21360 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21361 }
21362 
21363 /*
21364  * If this is a conn_t queue, then we pass in the conn. This includes the
21365  * zoneid.
21366  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21367  * in which case we use the global zoneid since those are all part of
21368  * the global zone.
21369  */
21370 void
21371 ip_wput(queue_t *q, mblk_t *mp)
21372 {
21373 	if (CONN_Q(q))
21374 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21375 	else
21376 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21377 }
21378 
21379 /*
21380  *
21381  * The following rules must be observed when accessing any ipif or ill
21382  * that has been cached in the conn. Typically conn_nofailover_ill,
21383  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21384  *
21385  * Access: The ipif or ill pointed to from the conn can be accessed under
21386  * the protection of the conn_lock or after it has been refheld under the
21387  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21388  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21389  * The reason for this is that a concurrent unplumb could actually be
21390  * cleaning up these cached pointers by walking the conns and might have
21391  * finished cleaning up the conn in question. The macros check that an
21392  * unplumb has not yet started on the ipif or ill.
21393  *
21394  * Caching: An ipif or ill pointer may be cached in the conn only after
21395  * making sure that an unplumb has not started. So the caching is done
21396  * while holding both the conn_lock and the ill_lock and after using the
21397  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21398  * flag before starting the cleanup of conns.
21399  *
21400  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21401  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21402  * or a reference to the ipif or a reference to an ire that references the
21403  * ipif. An ipif does not change its ill except for failover/failback. Since
21404  * failover/failback happens only after bringing down the ipif and making sure
21405  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21406  * the above holds.
21407  */
21408 ipif_t *
21409 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21410 {
21411 	ipif_t	*ipif;
21412 	ill_t	*ill;
21413 
21414 	*err = 0;
21415 	rw_enter(&ill_g_lock, RW_READER);
21416 	mutex_enter(&connp->conn_lock);
21417 	ipif = *ipifp;
21418 	if (ipif != NULL) {
21419 		ill = ipif->ipif_ill;
21420 		mutex_enter(&ill->ill_lock);
21421 		if (IPIF_CAN_LOOKUP(ipif)) {
21422 			ipif_refhold_locked(ipif);
21423 			mutex_exit(&ill->ill_lock);
21424 			mutex_exit(&connp->conn_lock);
21425 			rw_exit(&ill_g_lock);
21426 			return (ipif);
21427 		} else {
21428 			*err = IPIF_LOOKUP_FAILED;
21429 		}
21430 		mutex_exit(&ill->ill_lock);
21431 	}
21432 	mutex_exit(&connp->conn_lock);
21433 	rw_exit(&ill_g_lock);
21434 	return (NULL);
21435 }
21436 
21437 ill_t *
21438 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21439 {
21440 	ill_t	*ill;
21441 
21442 	*err = 0;
21443 	mutex_enter(&connp->conn_lock);
21444 	ill = *illp;
21445 	if (ill != NULL) {
21446 		mutex_enter(&ill->ill_lock);
21447 		if (ILL_CAN_LOOKUP(ill)) {
21448 			ill_refhold_locked(ill);
21449 			mutex_exit(&ill->ill_lock);
21450 			mutex_exit(&connp->conn_lock);
21451 			return (ill);
21452 		} else {
21453 			*err = ILL_LOOKUP_FAILED;
21454 		}
21455 		mutex_exit(&ill->ill_lock);
21456 	}
21457 	mutex_exit(&connp->conn_lock);
21458 	return (NULL);
21459 }
21460 
21461 static int
21462 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21463 {
21464 	ill_t	*ill;
21465 
21466 	ill = ipif->ipif_ill;
21467 	mutex_enter(&connp->conn_lock);
21468 	mutex_enter(&ill->ill_lock);
21469 	if (IPIF_CAN_LOOKUP(ipif)) {
21470 		*ipifp = ipif;
21471 		mutex_exit(&ill->ill_lock);
21472 		mutex_exit(&connp->conn_lock);
21473 		return (0);
21474 	}
21475 	mutex_exit(&ill->ill_lock);
21476 	mutex_exit(&connp->conn_lock);
21477 	return (IPIF_LOOKUP_FAILED);
21478 }
21479 
21480 /*
21481  * This is called if the outbound datagram needs fragmentation.
21482  *
21483  * NOTE : This function does not ire_refrele the ire argument passed in.
21484  */
21485 static void
21486 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid)
21487 {
21488 	ipha_t		*ipha;
21489 	mblk_t		*mp;
21490 	uint32_t	v_hlen_tos_len;
21491 	uint32_t	max_frag;
21492 	uint32_t	frag_flag;
21493 	boolean_t	dont_use;
21494 
21495 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21496 		mp = ipsec_mp->b_cont;
21497 	} else {
21498 		mp = ipsec_mp;
21499 	}
21500 
21501 	ipha = (ipha_t *)mp->b_rptr;
21502 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21503 
21504 #ifdef	_BIG_ENDIAN
21505 #define	V_HLEN	(v_hlen_tos_len >> 24)
21506 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21507 #else
21508 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21509 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21510 #endif
21511 
21512 #ifndef SPEED_BEFORE_SAFETY
21513 	/*
21514 	 * Check that ipha_length is consistent with
21515 	 * the mblk length
21516 	 */
21517 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21518 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21519 		    LENGTH, msgdsize(mp)));
21520 		freemsg(ipsec_mp);
21521 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21522 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21523 		    "packet length mismatch");
21524 		return;
21525 	}
21526 #endif
21527 	/*
21528 	 * Don't use frag_flag if pre-built packet or source
21529 	 * routed or if multicast (since multicast packets do not solicit
21530 	 * ICMP "packet too big" messages). Get the values of
21531 	 * max_frag and frag_flag atomically by acquiring the
21532 	 * ire_lock.
21533 	 */
21534 	mutex_enter(&ire->ire_lock);
21535 	max_frag = ire->ire_max_frag;
21536 	frag_flag = ire->ire_frag_flag;
21537 	mutex_exit(&ire->ire_lock);
21538 
21539 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21540 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21541 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21542 
21543 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21544 	    (dont_use ? 0 : frag_flag), zoneid);
21545 }
21546 
21547 /*
21548  * Used for deciding the MSS size for the upper layer. Thus
21549  * we need to check the outbound policy values in the conn.
21550  */
21551 int
21552 conn_ipsec_length(conn_t *connp)
21553 {
21554 	ipsec_latch_t *ipl;
21555 
21556 	ipl = connp->conn_latch;
21557 	if (ipl == NULL)
21558 		return (0);
21559 
21560 	if (ipl->ipl_out_policy == NULL)
21561 		return (0);
21562 
21563 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21564 }
21565 
21566 /*
21567  * Returns an estimate of the IPSEC headers size. This is used if
21568  * we don't want to call into IPSEC to get the exact size.
21569  */
21570 int
21571 ipsec_out_extra_length(mblk_t *ipsec_mp)
21572 {
21573 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21574 	ipsec_action_t *a;
21575 
21576 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21577 	if (!io->ipsec_out_secure)
21578 		return (0);
21579 
21580 	a = io->ipsec_out_act;
21581 
21582 	if (a == NULL) {
21583 		ASSERT(io->ipsec_out_policy != NULL);
21584 		a = io->ipsec_out_policy->ipsp_act;
21585 	}
21586 	ASSERT(a != NULL);
21587 
21588 	return (a->ipa_ovhd);
21589 }
21590 
21591 /*
21592  * Returns an estimate of the IPSEC headers size. This is used if
21593  * we don't want to call into IPSEC to get the exact size.
21594  */
21595 int
21596 ipsec_in_extra_length(mblk_t *ipsec_mp)
21597 {
21598 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21599 	ipsec_action_t *a;
21600 
21601 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21602 
21603 	a = ii->ipsec_in_action;
21604 	return (a == NULL ? 0 : a->ipa_ovhd);
21605 }
21606 
21607 /*
21608  * If there are any source route options, return the true final
21609  * destination. Otherwise, return the destination.
21610  */
21611 ipaddr_t
21612 ip_get_dst(ipha_t *ipha)
21613 {
21614 	ipoptp_t	opts;
21615 	uchar_t		*opt;
21616 	uint8_t		optval;
21617 	uint8_t		optlen;
21618 	ipaddr_t	dst;
21619 	uint32_t off;
21620 
21621 	dst = ipha->ipha_dst;
21622 
21623 	if (IS_SIMPLE_IPH(ipha))
21624 		return (dst);
21625 
21626 	for (optval = ipoptp_first(&opts, ipha);
21627 	    optval != IPOPT_EOL;
21628 	    optval = ipoptp_next(&opts)) {
21629 		opt = opts.ipoptp_cur;
21630 		optlen = opts.ipoptp_len;
21631 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21632 		switch (optval) {
21633 		case IPOPT_SSRR:
21634 		case IPOPT_LSRR:
21635 			off = opt[IPOPT_OFFSET];
21636 			/*
21637 			 * If one of the conditions is true, it means
21638 			 * end of options and dst already has the right
21639 			 * value.
21640 			 */
21641 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21642 				off = optlen - IP_ADDR_LEN;
21643 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21644 			}
21645 			return (dst);
21646 		default:
21647 			break;
21648 		}
21649 	}
21650 
21651 	return (dst);
21652 }
21653 
21654 mblk_t *
21655 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21656     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21657 {
21658 	ipsec_out_t	*io;
21659 	mblk_t		*first_mp;
21660 	boolean_t policy_present;
21661 
21662 	first_mp = mp;
21663 	if (mp->b_datap->db_type == M_CTL) {
21664 		io = (ipsec_out_t *)first_mp->b_rptr;
21665 		/*
21666 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21667 		 *
21668 		 * 1) There is per-socket policy (including cached global
21669 		 *    policy) or a policy on the IP-in-IP tunnel.
21670 		 * 2) There is no per-socket policy, but it is
21671 		 *    a multicast packet that needs to go out
21672 		 *    on a specific interface. This is the case
21673 		 *    where (ip_wput and ip_wput_multicast) attaches
21674 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21675 		 *
21676 		 * In case (2) we check with global policy to
21677 		 * see if there is a match and set the ill_index
21678 		 * appropriately so that we can lookup the ire
21679 		 * properly in ip_wput_ipsec_out.
21680 		 */
21681 
21682 		/*
21683 		 * ipsec_out_use_global_policy is set to B_FALSE
21684 		 * in ipsec_in_to_out(). Refer to that function for
21685 		 * details.
21686 		 */
21687 		if ((io->ipsec_out_latch == NULL) &&
21688 		    (io->ipsec_out_use_global_policy)) {
21689 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21690 				    ire, connp, unspec_src, zoneid));
21691 		}
21692 		if (!io->ipsec_out_secure) {
21693 			/*
21694 			 * If this is not a secure packet, drop
21695 			 * the IPSEC_OUT mp and treat it as a clear
21696 			 * packet. This happens when we are sending
21697 			 * a ICMP reply back to a clear packet. See
21698 			 * ipsec_in_to_out() for details.
21699 			 */
21700 			mp = first_mp->b_cont;
21701 			freeb(first_mp);
21702 		}
21703 		return (mp);
21704 	}
21705 	/*
21706 	 * See whether we need to attach a global policy here. We
21707 	 * don't depend on the conn (as it could be null) for deciding
21708 	 * what policy this datagram should go through because it
21709 	 * should have happened in ip_wput if there was some
21710 	 * policy. This normally happens for connections which are not
21711 	 * fully bound preventing us from caching policies in
21712 	 * ip_bind. Packets coming from the TCP listener/global queue
21713 	 * - which are non-hard_bound - could also be affected by
21714 	 * applying policy here.
21715 	 *
21716 	 * If this packet is coming from tcp global queue or listener,
21717 	 * we will be applying policy here.  This may not be *right*
21718 	 * if these packets are coming from the detached connection as
21719 	 * it could have gone in clear before. This happens only if a
21720 	 * TCP connection started when there is no policy and somebody
21721 	 * added policy before it became detached. Thus packets of the
21722 	 * detached connection could go out secure and the other end
21723 	 * would drop it because it will be expecting in clear. The
21724 	 * converse is not true i.e if somebody starts a TCP
21725 	 * connection and deletes the policy, all the packets will
21726 	 * still go out with the policy that existed before deleting
21727 	 * because ip_unbind sends up policy information which is used
21728 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21729 	 * TCP to attach a dummy IPSEC_OUT and set
21730 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21731 	 * affect performance for normal cases, we are not doing it.
21732 	 * Thus, set policy before starting any TCP connections.
21733 	 *
21734 	 * NOTE - We might apply policy even for a hard bound connection
21735 	 * - for which we cached policy in ip_bind - if somebody added
21736 	 * global policy after we inherited the policy in ip_bind.
21737 	 * This means that the packets that were going out in clear
21738 	 * previously would start going secure and hence get dropped
21739 	 * on the other side. To fix this, TCP attaches a dummy
21740 	 * ipsec_out and make sure that we don't apply global policy.
21741 	 */
21742 	if (ipha != NULL)
21743 		policy_present = ipsec_outbound_v4_policy_present;
21744 	else
21745 		policy_present = ipsec_outbound_v6_policy_present;
21746 	if (!policy_present)
21747 		return (mp);
21748 
21749 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21750 		    zoneid));
21751 }
21752 
21753 ire_t *
21754 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21755 {
21756 	ipaddr_t addr;
21757 	ire_t *save_ire;
21758 	irb_t *irb;
21759 	ill_group_t *illgrp;
21760 	int	err;
21761 
21762 	save_ire = ire;
21763 	addr = ire->ire_addr;
21764 
21765 	ASSERT(ire->ire_type == IRE_BROADCAST);
21766 
21767 	illgrp = connp->conn_outgoing_ill->ill_group;
21768 	if (illgrp == NULL) {
21769 		*conn_outgoing_ill = conn_get_held_ill(connp,
21770 		    &connp->conn_outgoing_ill, &err);
21771 		if (err == ILL_LOOKUP_FAILED) {
21772 			ire_refrele(save_ire);
21773 			return (NULL);
21774 		}
21775 		return (save_ire);
21776 	}
21777 	/*
21778 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21779 	 * If it is part of the group, we need to send on the ire
21780 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21781 	 * to this group. This is okay as IP_BOUND_IF really means
21782 	 * any ill in the group. We depend on the fact that the
21783 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21784 	 * if such an ire exists. This is possible only if you have
21785 	 * at least one ill in the group that has not failed.
21786 	 *
21787 	 * First get to the ire that matches the address and group.
21788 	 *
21789 	 * We don't look for an ire with a matching zoneid because a given zone
21790 	 * won't always have broadcast ires on all ills in the group.
21791 	 */
21792 	irb = ire->ire_bucket;
21793 	rw_enter(&irb->irb_lock, RW_READER);
21794 	if (ire->ire_marks & IRE_MARK_NORECV) {
21795 		/*
21796 		 * If the current zone only has an ire broadcast for this
21797 		 * address marked NORECV, the ire we want is ahead in the
21798 		 * bucket, so we look it up deliberately ignoring the zoneid.
21799 		 */
21800 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21801 			if (ire->ire_addr != addr)
21802 				continue;
21803 			/* skip over deleted ires */
21804 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21805 				continue;
21806 		}
21807 	}
21808 	while (ire != NULL) {
21809 		/*
21810 		 * If a new interface is coming up, we could end up
21811 		 * seeing the loopback ire and the non-loopback ire
21812 		 * may not have been added yet. So check for ire_stq
21813 		 */
21814 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21815 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21816 			break;
21817 		}
21818 		ire = ire->ire_next;
21819 	}
21820 	if (ire != NULL && ire->ire_addr == addr &&
21821 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21822 		IRE_REFHOLD(ire);
21823 		rw_exit(&irb->irb_lock);
21824 		ire_refrele(save_ire);
21825 		*conn_outgoing_ill = ire_to_ill(ire);
21826 		/*
21827 		 * Refhold the ill to make the conn_outgoing_ill
21828 		 * independent of the ire. ip_wput_ire goes in a loop
21829 		 * and may refrele the ire. Since we have an ire at this
21830 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21831 		 */
21832 		ill_refhold(*conn_outgoing_ill);
21833 		return (ire);
21834 	}
21835 	rw_exit(&irb->irb_lock);
21836 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21837 	/*
21838 	 * If we can't find a suitable ire, return the original ire.
21839 	 */
21840 	return (save_ire);
21841 }
21842 
21843 /*
21844  * This function does the ire_refrele of the ire passed in as the
21845  * argument. As this function looks up more ires i.e broadcast ires,
21846  * it needs to REFRELE them. Currently, for simplicity we don't
21847  * differentiate the one passed in and looked up here. We always
21848  * REFRELE.
21849  * IPQoS Notes:
21850  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21851  * IPSec packets are done in ipsec_out_process.
21852  *
21853  */
21854 void
21855 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21856     zoneid_t zoneid)
21857 {
21858 	ipha_t		*ipha;
21859 #define	rptr	((uchar_t *)ipha)
21860 	queue_t		*stq;
21861 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21862 	uint32_t	v_hlen_tos_len;
21863 	uint32_t	ttl_protocol;
21864 	ipaddr_t	src;
21865 	ipaddr_t	dst;
21866 	uint32_t	cksum;
21867 	ipaddr_t	orig_src;
21868 	ire_t		*ire1;
21869 	mblk_t		*next_mp;
21870 	uint_t		hlen;
21871 	uint16_t	*up;
21872 	uint32_t	max_frag = ire->ire_max_frag;
21873 	ill_t		*ill = ire_to_ill(ire);
21874 	int		clusterwide;
21875 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21876 	int		ipsec_len;
21877 	mblk_t		*first_mp;
21878 	ipsec_out_t	*io;
21879 	boolean_t	conn_dontroute;		/* conn value for multicast */
21880 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21881 	boolean_t	multicast_forward;	/* Should we forward ? */
21882 	boolean_t	unspec_src;
21883 	ill_t		*conn_outgoing_ill = NULL;
21884 	ill_t		*ire_ill;
21885 	ill_t		*ire1_ill;
21886 	ill_t		*out_ill;
21887 	uint32_t 	ill_index = 0;
21888 	boolean_t	multirt_send = B_FALSE;
21889 	int		err;
21890 	ipxmit_state_t	pktxmit_state;
21891 
21892 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21893 	    "ip_wput_ire_start: q %p", q);
21894 
21895 	multicast_forward = B_FALSE;
21896 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21897 
21898 	if (ire->ire_flags & RTF_MULTIRT) {
21899 		/*
21900 		 * Multirouting case. The bucket where ire is stored
21901 		 * probably holds other RTF_MULTIRT flagged ire
21902 		 * to the destination. In this call to ip_wput_ire,
21903 		 * we attempt to send the packet through all
21904 		 * those ires. Thus, we first ensure that ire is the
21905 		 * first RTF_MULTIRT ire in the bucket,
21906 		 * before walking the ire list.
21907 		 */
21908 		ire_t *first_ire;
21909 		irb_t *irb = ire->ire_bucket;
21910 		ASSERT(irb != NULL);
21911 
21912 		/* Make sure we do not omit any multiroute ire. */
21913 		IRB_REFHOLD(irb);
21914 		for (first_ire = irb->irb_ire;
21915 		    first_ire != NULL;
21916 		    first_ire = first_ire->ire_next) {
21917 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21918 			    (first_ire->ire_addr == ire->ire_addr) &&
21919 			    !(first_ire->ire_marks &
21920 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21921 				break;
21922 		}
21923 
21924 		if ((first_ire != NULL) && (first_ire != ire)) {
21925 			IRE_REFHOLD(first_ire);
21926 			ire_refrele(ire);
21927 			ire = first_ire;
21928 			ill = ire_to_ill(ire);
21929 		}
21930 		IRB_REFRELE(irb);
21931 	}
21932 
21933 	/*
21934 	 * conn_outgoing_ill is used only in the broadcast loop.
21935 	 * for performance we don't grab the mutexs in the fastpath
21936 	 */
21937 	if ((connp != NULL) &&
21938 	    (connp->conn_xmit_if_ill == NULL) &&
21939 	    (ire->ire_type == IRE_BROADCAST) &&
21940 	    ((connp->conn_nofailover_ill != NULL) ||
21941 	    (connp->conn_outgoing_ill != NULL))) {
21942 		/*
21943 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21944 		 * option. So, see if this endpoint is bound to a
21945 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21946 		 * that if the interface is failed, we will still send
21947 		 * the packet on the same ill which is what we want.
21948 		 */
21949 		conn_outgoing_ill = conn_get_held_ill(connp,
21950 		    &connp->conn_nofailover_ill, &err);
21951 		if (err == ILL_LOOKUP_FAILED) {
21952 			ire_refrele(ire);
21953 			freemsg(mp);
21954 			return;
21955 		}
21956 		if (conn_outgoing_ill == NULL) {
21957 			/*
21958 			 * Choose a good ill in the group to send the
21959 			 * packets on.
21960 			 */
21961 			ire = conn_set_outgoing_ill(connp, ire,
21962 			    &conn_outgoing_ill);
21963 			if (ire == NULL) {
21964 				freemsg(mp);
21965 				return;
21966 			}
21967 		}
21968 	}
21969 
21970 	if (mp->b_datap->db_type != M_CTL) {
21971 		ipha = (ipha_t *)mp->b_rptr;
21972 	} else {
21973 		io = (ipsec_out_t *)mp->b_rptr;
21974 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21975 		ASSERT(zoneid == io->ipsec_out_zoneid);
21976 		ASSERT(zoneid != ALL_ZONES);
21977 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21978 		dst = ipha->ipha_dst;
21979 		/*
21980 		 * For the multicast case, ipsec_out carries conn_dontroute and
21981 		 * conn_multicast_loop as conn may not be available here. We
21982 		 * need this for multicast loopback and forwarding which is done
21983 		 * later in the code.
21984 		 */
21985 		if (CLASSD(dst)) {
21986 			conn_dontroute = io->ipsec_out_dontroute;
21987 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21988 			/*
21989 			 * If conn_dontroute is not set or conn_multicast_loop
21990 			 * is set, we need to do forwarding/loopback. For
21991 			 * datagrams from ip_wput_multicast, conn_dontroute is
21992 			 * set to B_TRUE and conn_multicast_loop is set to
21993 			 * B_FALSE so that we neither do forwarding nor
21994 			 * loopback.
21995 			 */
21996 			if (!conn_dontroute || conn_multicast_loop)
21997 				multicast_forward = B_TRUE;
21998 		}
21999 	}
22000 
22001 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22002 	    ire->ire_zoneid != ALL_ZONES) {
22003 		/*
22004 		 * When a zone sends a packet to another zone, we try to deliver
22005 		 * the packet under the same conditions as if the destination
22006 		 * was a real node on the network. To do so, we look for a
22007 		 * matching route in the forwarding table.
22008 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22009 		 * ip_newroute() does.
22010 		 * Note that IRE_LOCAL are special, since they are used
22011 		 * when the zoneid doesn't match in some cases. This means that
22012 		 * we need to handle ipha_src differently since ire_src_addr
22013 		 * belongs to the receiving zone instead of the sending zone.
22014 		 * When ip_restrict_interzone_loopback is set, then
22015 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22016 		 * for loopback between zones when the logical "Ethernet" would
22017 		 * have looped them back.
22018 		 */
22019 		ire_t *src_ire;
22020 
22021 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22022 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22023 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
22024 		if (src_ire != NULL &&
22025 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22026 		    (!ip_restrict_interzone_loopback ||
22027 		    ire_local_same_ill_group(ire, src_ire))) {
22028 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22029 				ipha->ipha_src = src_ire->ire_src_addr;
22030 			ire_refrele(src_ire);
22031 		} else {
22032 			ire_refrele(ire);
22033 			if (conn_outgoing_ill != NULL)
22034 				ill_refrele(conn_outgoing_ill);
22035 			BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
22036 			if (src_ire != NULL) {
22037 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22038 					ire_refrele(src_ire);
22039 					freemsg(mp);
22040 					return;
22041 				}
22042 				ire_refrele(src_ire);
22043 			}
22044 			if (ip_hdr_complete(ipha, zoneid)) {
22045 				/* Failed */
22046 				freemsg(mp);
22047 				return;
22048 			}
22049 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid);
22050 			return;
22051 		}
22052 	}
22053 
22054 	if (mp->b_datap->db_type == M_CTL ||
22055 	    ipsec_outbound_v4_policy_present) {
22056 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22057 		    unspec_src, zoneid);
22058 		if (mp == NULL) {
22059 			ire_refrele(ire);
22060 			if (conn_outgoing_ill != NULL)
22061 				ill_refrele(conn_outgoing_ill);
22062 			return;
22063 		}
22064 	}
22065 
22066 	first_mp = mp;
22067 	ipsec_len = 0;
22068 
22069 	if (first_mp->b_datap->db_type == M_CTL) {
22070 		io = (ipsec_out_t *)first_mp->b_rptr;
22071 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22072 		mp = first_mp->b_cont;
22073 		ipsec_len = ipsec_out_extra_length(first_mp);
22074 		ASSERT(ipsec_len >= 0);
22075 		/* We already picked up the zoneid from the M_CTL above */
22076 		ASSERT(zoneid == io->ipsec_out_zoneid);
22077 		ASSERT(zoneid != ALL_ZONES);
22078 
22079 		/*
22080 		 * Drop M_CTL here if IPsec processing is not needed.
22081 		 * (Non-IPsec use of M_CTL extracted any information it
22082 		 * needed above).
22083 		 */
22084 		if (ipsec_len == 0) {
22085 			freeb(first_mp);
22086 			first_mp = mp;
22087 		}
22088 	}
22089 
22090 	/*
22091 	 * Fast path for ip_wput_ire
22092 	 */
22093 
22094 	ipha = (ipha_t *)mp->b_rptr;
22095 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22096 	dst = ipha->ipha_dst;
22097 
22098 	/*
22099 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22100 	 * if the socket is a SOCK_RAW type. The transport checksum should
22101 	 * be provided in the pre-built packet, so we don't need to compute it.
22102 	 * Also, other application set flags, like DF, should not be altered.
22103 	 * Other transport MUST pass down zero.
22104 	 */
22105 	ip_hdr_included = ipha->ipha_ident;
22106 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22107 
22108 	if (CLASSD(dst)) {
22109 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22110 		    ntohl(dst),
22111 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22112 		    ntohl(ire->ire_addr)));
22113 	}
22114 
22115 /* Macros to extract header fields from data already in registers */
22116 #ifdef	_BIG_ENDIAN
22117 #define	V_HLEN	(v_hlen_tos_len >> 24)
22118 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22119 #define	PROTO	(ttl_protocol & 0xFF)
22120 #else
22121 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22122 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22123 #define	PROTO	(ttl_protocol >> 8)
22124 #endif
22125 
22126 
22127 	orig_src = src = ipha->ipha_src;
22128 	/* (The loop back to "another" is explained down below.) */
22129 another:;
22130 	/*
22131 	 * Assign an ident value for this packet.  We assign idents on
22132 	 * a per destination basis out of the IRE.  There could be
22133 	 * other threads targeting the same destination, so we have to
22134 	 * arrange for a atomic increment.  Note that we use a 32-bit
22135 	 * atomic add because it has better performance than its
22136 	 * 16-bit sibling.
22137 	 *
22138 	 * If running in cluster mode and if the source address
22139 	 * belongs to a replicated service then vector through
22140 	 * cl_inet_ipident vector to allocate ip identifier
22141 	 * NOTE: This is a contract private interface with the
22142 	 * clustering group.
22143 	 */
22144 	clusterwide = 0;
22145 	if (cl_inet_ipident) {
22146 		ASSERT(cl_inet_isclusterwide);
22147 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22148 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22149 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22150 			    AF_INET, (uint8_t *)(uintptr_t)src,
22151 			    (uint8_t *)(uintptr_t)dst);
22152 			clusterwide = 1;
22153 		}
22154 	}
22155 	if (!clusterwide) {
22156 		ipha->ipha_ident =
22157 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22158 	}
22159 
22160 #ifndef _BIG_ENDIAN
22161 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22162 #endif
22163 
22164 	/*
22165 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22166 	 * This is needed to obey conn_unspec_src when packets go through
22167 	 * ip_newroute + arp.
22168 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22169 	 */
22170 	if (src == INADDR_ANY && !unspec_src) {
22171 		/*
22172 		 * Assign the appropriate source address from the IRE if none
22173 		 * was specified.
22174 		 */
22175 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22176 
22177 		/*
22178 		 * With IP multipathing, broadcast packets are sent on the ire
22179 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22180 		 * the group. However, this ire might not be in the same zone so
22181 		 * we can't always use its source address. We look for a
22182 		 * broadcast ire in the same group and in the right zone.
22183 		 */
22184 		if (ire->ire_type == IRE_BROADCAST &&
22185 		    ire->ire_zoneid != zoneid) {
22186 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22187 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22188 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
22189 			if (src_ire != NULL) {
22190 				src = src_ire->ire_src_addr;
22191 				ire_refrele(src_ire);
22192 			} else {
22193 				ire_refrele(ire);
22194 				if (conn_outgoing_ill != NULL)
22195 					ill_refrele(conn_outgoing_ill);
22196 				freemsg(first_mp);
22197 				if (ill != NULL) {
22198 					BUMP_MIB(ill->ill_ip_mib,
22199 					    ipIfStatsOutDiscards);
22200 				} else {
22201 					BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
22202 				}
22203 				return;
22204 			}
22205 		} else {
22206 			src = ire->ire_src_addr;
22207 		}
22208 
22209 		if (connp == NULL) {
22210 			ip1dbg(("ip_wput_ire: no connp and no src "
22211 			    "address for dst 0x%x, using src 0x%x\n",
22212 			    ntohl(dst),
22213 			    ntohl(src)));
22214 		}
22215 		ipha->ipha_src = src;
22216 	}
22217 	stq = ire->ire_stq;
22218 
22219 	/*
22220 	 * We only allow ire chains for broadcasts since there will
22221 	 * be multiple IRE_CACHE entries for the same multicast
22222 	 * address (one per ipif).
22223 	 */
22224 	next_mp = NULL;
22225 
22226 	/* broadcast packet */
22227 	if (ire->ire_type == IRE_BROADCAST)
22228 		goto broadcast;
22229 
22230 	/* loopback ? */
22231 	if (stq == NULL)
22232 		goto nullstq;
22233 
22234 	/* The ill_index for outbound ILL */
22235 	ill_index = Q_TO_INDEX(stq);
22236 
22237 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22238 	ttl_protocol = ((uint16_t *)ipha)[4];
22239 
22240 	/* pseudo checksum (do it in parts for IP header checksum) */
22241 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22242 
22243 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22244 		queue_t *dev_q = stq->q_next;
22245 
22246 		/* flow controlled */
22247 		if ((dev_q->q_next || dev_q->q_first) &&
22248 		    !canput(dev_q))
22249 			goto blocked;
22250 		if ((PROTO == IPPROTO_UDP) &&
22251 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22252 			hlen = (V_HLEN & 0xF) << 2;
22253 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22254 			if (*up != 0) {
22255 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22256 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22257 				/* Software checksum? */
22258 				if (DB_CKSUMFLAGS(mp) == 0) {
22259 					IP_STAT(ip_out_sw_cksum);
22260 					IP_STAT_UPDATE(
22261 					    ip_udp_out_sw_cksum_bytes,
22262 					    LENGTH - hlen);
22263 				}
22264 			}
22265 		}
22266 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22267 		hlen = (V_HLEN & 0xF) << 2;
22268 		if (PROTO == IPPROTO_TCP) {
22269 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22270 			/*
22271 			 * The packet header is processed once and for all, even
22272 			 * in the multirouting case. We disable hardware
22273 			 * checksum if the packet is multirouted, as it will be
22274 			 * replicated via several interfaces, and not all of
22275 			 * them may have this capability.
22276 			 */
22277 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22278 			    LENGTH, max_frag, ipsec_len, cksum);
22279 			/* Software checksum? */
22280 			if (DB_CKSUMFLAGS(mp) == 0) {
22281 				IP_STAT(ip_out_sw_cksum);
22282 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22283 				    LENGTH - hlen);
22284 			}
22285 		} else {
22286 			sctp_hdr_t	*sctph;
22287 
22288 			ASSERT(PROTO == IPPROTO_SCTP);
22289 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22290 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22291 			/*
22292 			 * Zero out the checksum field to ensure proper
22293 			 * checksum calculation.
22294 			 */
22295 			sctph->sh_chksum = 0;
22296 #ifdef	DEBUG
22297 			if (!skip_sctp_cksum)
22298 #endif
22299 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22300 		}
22301 	}
22302 
22303 	/*
22304 	 * If this is a multicast packet and originated from ip_wput
22305 	 * we need to do loopback and forwarding checks. If it comes
22306 	 * from ip_wput_multicast, we SHOULD not do this.
22307 	 */
22308 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22309 
22310 	/* checksum */
22311 	cksum += ttl_protocol;
22312 
22313 	/* fragment the packet */
22314 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22315 		goto fragmentit;
22316 	/*
22317 	 * Don't use frag_flag if packet is pre-built or source
22318 	 * routed or if multicast (since multicast packets do
22319 	 * not solicit ICMP "packet too big" messages).
22320 	 */
22321 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22322 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22323 	    !ip_source_route_included(ipha)) &&
22324 	    !CLASSD(ipha->ipha_dst))
22325 		ipha->ipha_fragment_offset_and_flags |=
22326 		    htons(ire->ire_frag_flag);
22327 
22328 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22329 		/* calculate IP header checksum */
22330 		cksum += ipha->ipha_ident;
22331 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22332 		cksum += ipha->ipha_fragment_offset_and_flags;
22333 
22334 		/* IP options present */
22335 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22336 		if (hlen)
22337 			goto checksumoptions;
22338 
22339 		/* calculate hdr checksum */
22340 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22341 		cksum = ~(cksum + (cksum >> 16));
22342 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22343 	}
22344 	if (ipsec_len != 0) {
22345 		/*
22346 		 * We will do the rest of the processing after
22347 		 * we come back from IPSEC in ip_wput_ipsec_out().
22348 		 */
22349 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22350 
22351 		io = (ipsec_out_t *)first_mp->b_rptr;
22352 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22353 				ill_phyint->phyint_ifindex;
22354 
22355 		ipsec_out_process(q, first_mp, ire, ill_index);
22356 		ire_refrele(ire);
22357 		if (conn_outgoing_ill != NULL)
22358 			ill_refrele(conn_outgoing_ill);
22359 		return;
22360 	}
22361 
22362 	/*
22363 	 * In most cases, the emission loop below is entered only
22364 	 * once. Only in the case where the ire holds the
22365 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22366 	 * flagged ires in the bucket, and send the packet
22367 	 * through all crossed RTF_MULTIRT routes.
22368 	 */
22369 	if (ire->ire_flags & RTF_MULTIRT) {
22370 		multirt_send = B_TRUE;
22371 	}
22372 	do {
22373 		if (multirt_send) {
22374 			irb_t *irb;
22375 			/*
22376 			 * We are in a multiple send case, need to get
22377 			 * the next ire and make a duplicate of the packet.
22378 			 * ire1 holds here the next ire to process in the
22379 			 * bucket. If multirouting is expected,
22380 			 * any non-RTF_MULTIRT ire that has the
22381 			 * right destination address is ignored.
22382 			 */
22383 			irb = ire->ire_bucket;
22384 			ASSERT(irb != NULL);
22385 
22386 			IRB_REFHOLD(irb);
22387 			for (ire1 = ire->ire_next;
22388 			    ire1 != NULL;
22389 			    ire1 = ire1->ire_next) {
22390 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22391 					continue;
22392 				if (ire1->ire_addr != ire->ire_addr)
22393 					continue;
22394 				if (ire1->ire_marks &
22395 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22396 					continue;
22397 
22398 				/* Got one */
22399 				IRE_REFHOLD(ire1);
22400 				break;
22401 			}
22402 			IRB_REFRELE(irb);
22403 
22404 			if (ire1 != NULL) {
22405 				next_mp = copyb(mp);
22406 				if ((next_mp == NULL) ||
22407 				    ((mp->b_cont != NULL) &&
22408 				    ((next_mp->b_cont =
22409 				    dupmsg(mp->b_cont)) == NULL))) {
22410 					freemsg(next_mp);
22411 					next_mp = NULL;
22412 					ire_refrele(ire1);
22413 					ire1 = NULL;
22414 				}
22415 			}
22416 
22417 			/* Last multiroute ire; don't loop anymore. */
22418 			if (ire1 == NULL) {
22419 				multirt_send = B_FALSE;
22420 			}
22421 		}
22422 
22423 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22424 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22425 		    mblk_t *, mp);
22426 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
22427 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp);
22428 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22429 		if (mp == NULL)
22430 			goto release_ire_and_ill;
22431 
22432 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22433 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22434 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22435 		if ((pktxmit_state == SEND_FAILED) ||
22436 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22437 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22438 			    "- packet dropped\n"));
22439 release_ire_and_ill:
22440 			ire_refrele(ire);
22441 			if (next_mp != NULL) {
22442 				freemsg(next_mp);
22443 				ire_refrele(ire1);
22444 			}
22445 			if (conn_outgoing_ill != NULL)
22446 				ill_refrele(conn_outgoing_ill);
22447 			return;
22448 		}
22449 
22450 		if (CLASSD(dst)) {
22451 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22452 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22453 			    ntohs(ipha->ipha_length));
22454 		}
22455 
22456 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22457 		    "ip_wput_ire_end: q %p (%S)",
22458 		    q, "last copy out");
22459 		IRE_REFRELE(ire);
22460 
22461 		if (multirt_send) {
22462 			ASSERT(ire1);
22463 			/*
22464 			 * Proceed with the next RTF_MULTIRT ire,
22465 			 * Also set up the send-to queue accordingly.
22466 			 */
22467 			ire = ire1;
22468 			ire1 = NULL;
22469 			stq = ire->ire_stq;
22470 			mp = next_mp;
22471 			next_mp = NULL;
22472 			ipha = (ipha_t *)mp->b_rptr;
22473 			ill_index = Q_TO_INDEX(stq);
22474 			ill = (ill_t *)stq->q_ptr;
22475 		}
22476 	} while (multirt_send);
22477 	if (conn_outgoing_ill != NULL)
22478 		ill_refrele(conn_outgoing_ill);
22479 	return;
22480 
22481 	/*
22482 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22483 	 */
22484 broadcast:
22485 	{
22486 		/*
22487 		 * Avoid broadcast storms by setting the ttl to 1
22488 		 * for broadcasts. This parameter can be set
22489 		 * via ndd, so make sure that for the SO_DONTROUTE
22490 		 * case that ipha_ttl is always set to 1.
22491 		 * In the event that we are replying to incoming
22492 		 * ICMP packets, conn could be NULL.
22493 		 */
22494 		if ((connp != NULL) && connp->conn_dontroute)
22495 			ipha->ipha_ttl = 1;
22496 		else
22497 			ipha->ipha_ttl = ip_broadcast_ttl;
22498 
22499 		/*
22500 		 * Note that we are not doing a IRB_REFHOLD here.
22501 		 * Actually we don't care if the list changes i.e
22502 		 * if somebody deletes an IRE from the list while
22503 		 * we drop the lock, the next time we come around
22504 		 * ire_next will be NULL and hence we won't send
22505 		 * out multiple copies which is fine.
22506 		 */
22507 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22508 		ire1 = ire->ire_next;
22509 		if (conn_outgoing_ill != NULL) {
22510 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22511 				ASSERT(ire1 == ire->ire_next);
22512 				if (ire1 != NULL && ire1->ire_addr == dst) {
22513 					ire_refrele(ire);
22514 					ire = ire1;
22515 					IRE_REFHOLD(ire);
22516 					ire1 = ire->ire_next;
22517 					continue;
22518 				}
22519 				rw_exit(&ire->ire_bucket->irb_lock);
22520 				/* Did not find a matching ill */
22521 				ip1dbg(("ip_wput_ire: broadcast with no "
22522 				    "matching IP_BOUND_IF ill %s\n",
22523 				    conn_outgoing_ill->ill_name));
22524 				freemsg(first_mp);
22525 				if (ire != NULL)
22526 					ire_refrele(ire);
22527 				ill_refrele(conn_outgoing_ill);
22528 				return;
22529 			}
22530 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22531 			/*
22532 			 * If the next IRE has the same address and is not one
22533 			 * of the two copies that we need to send, try to see
22534 			 * whether this copy should be sent at all. This
22535 			 * assumes that we insert loopbacks first and then
22536 			 * non-loopbacks. This is acheived by inserting the
22537 			 * loopback always before non-loopback.
22538 			 * This is used to send a single copy of a broadcast
22539 			 * packet out all physical interfaces that have an
22540 			 * matching IRE_BROADCAST while also looping
22541 			 * back one copy (to ip_wput_local) for each
22542 			 * matching physical interface. However, we avoid
22543 			 * sending packets out different logical that match by
22544 			 * having ipif_up/ipif_down supress duplicate
22545 			 * IRE_BROADCASTS.
22546 			 *
22547 			 * This feature is currently used to get broadcasts
22548 			 * sent to multiple interfaces, when the broadcast
22549 			 * address being used applies to multiple interfaces.
22550 			 * For example, a whole net broadcast will be
22551 			 * replicated on every connected subnet of
22552 			 * the target net.
22553 			 *
22554 			 * Each zone has its own set of IRE_BROADCASTs, so that
22555 			 * we're able to distribute inbound packets to multiple
22556 			 * zones who share a broadcast address. We avoid looping
22557 			 * back outbound packets in different zones but on the
22558 			 * same ill, as the application would see duplicates.
22559 			 *
22560 			 * If the interfaces are part of the same group,
22561 			 * we would want to send only one copy out for
22562 			 * whole group.
22563 			 *
22564 			 * This logic assumes that ire_add_v4() groups the
22565 			 * IRE_BROADCAST entries so that those with the same
22566 			 * ire_addr and ill_group are kept together.
22567 			 */
22568 			ire_ill = ire->ire_ipif->ipif_ill;
22569 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22570 				if (ire_ill->ill_group != NULL &&
22571 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22572 					/*
22573 					 * If the current zone only has an ire
22574 					 * broadcast for this address marked
22575 					 * NORECV, the ire we want is ahead in
22576 					 * the bucket, so we look it up
22577 					 * deliberately ignoring the zoneid.
22578 					 */
22579 					for (ire1 = ire->ire_bucket->irb_ire;
22580 					    ire1 != NULL;
22581 					    ire1 = ire1->ire_next) {
22582 						ire1_ill =
22583 						    ire1->ire_ipif->ipif_ill;
22584 						if (ire1->ire_addr != dst)
22585 							continue;
22586 						/* skip over the current ire */
22587 						if (ire1 == ire)
22588 							continue;
22589 						/* skip over deleted ires */
22590 						if (ire1->ire_marks &
22591 						    IRE_MARK_CONDEMNED)
22592 							continue;
22593 						/*
22594 						 * non-loopback ire in our
22595 						 * group: use it for the next
22596 						 * pass in the loop
22597 						 */
22598 						if (ire1->ire_stq != NULL &&
22599 						    ire1_ill->ill_group ==
22600 						    ire_ill->ill_group)
22601 							break;
22602 					}
22603 				}
22604 			} else {
22605 				while (ire1 != NULL && ire1->ire_addr == dst) {
22606 					ire1_ill = ire1->ire_ipif->ipif_ill;
22607 					/*
22608 					 * We can have two broadcast ires on the
22609 					 * same ill in different zones; here
22610 					 * we'll send a copy of the packet on
22611 					 * each ill and the fanout code will
22612 					 * call conn_wantpacket() to check that
22613 					 * the zone has the broadcast address
22614 					 * configured on the ill. If the two
22615 					 * ires are in the same group we only
22616 					 * send one copy up.
22617 					 */
22618 					if (ire1_ill != ire_ill &&
22619 					    (ire1_ill->ill_group == NULL ||
22620 					    ire_ill->ill_group == NULL ||
22621 					    ire1_ill->ill_group !=
22622 					    ire_ill->ill_group)) {
22623 						break;
22624 					}
22625 					ire1 = ire1->ire_next;
22626 				}
22627 			}
22628 		}
22629 		ASSERT(multirt_send == B_FALSE);
22630 		if (ire1 != NULL && ire1->ire_addr == dst) {
22631 			if ((ire->ire_flags & RTF_MULTIRT) &&
22632 			    (ire1->ire_flags & RTF_MULTIRT)) {
22633 				/*
22634 				 * We are in the multirouting case.
22635 				 * The message must be sent at least
22636 				 * on both ires. These ires have been
22637 				 * inserted AFTER the standard ones
22638 				 * in ip_rt_add(). There are thus no
22639 				 * other ire entries for the destination
22640 				 * address in the rest of the bucket
22641 				 * that do not have the RTF_MULTIRT
22642 				 * flag. We don't process a copy
22643 				 * of the message here. This will be
22644 				 * done in the final sending loop.
22645 				 */
22646 				multirt_send = B_TRUE;
22647 			} else {
22648 				next_mp = ip_copymsg(first_mp);
22649 				if (next_mp != NULL)
22650 					IRE_REFHOLD(ire1);
22651 			}
22652 		}
22653 		rw_exit(&ire->ire_bucket->irb_lock);
22654 	}
22655 
22656 	if (stq) {
22657 		/*
22658 		 * A non-NULL send-to queue means this packet is going
22659 		 * out of this machine.
22660 		 */
22661 		out_ill = (ill_t *)stq->q_ptr;
22662 
22663 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22664 		ttl_protocol = ((uint16_t *)ipha)[4];
22665 		/*
22666 		 * We accumulate the pseudo header checksum in cksum.
22667 		 * This is pretty hairy code, so watch close.  One
22668 		 * thing to keep in mind is that UDP and TCP have
22669 		 * stored their respective datagram lengths in their
22670 		 * checksum fields.  This lines things up real nice.
22671 		 */
22672 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22673 		    (src >> 16) + (src & 0xFFFF);
22674 		/*
22675 		 * We assume the udp checksum field contains the
22676 		 * length, so to compute the pseudo header checksum,
22677 		 * all we need is the protocol number and src/dst.
22678 		 */
22679 		/* Provide the checksums for UDP and TCP. */
22680 		if ((PROTO == IPPROTO_TCP) &&
22681 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22682 			/* hlen gets the number of uchar_ts in the IP header */
22683 			hlen = (V_HLEN & 0xF) << 2;
22684 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22685 			IP_STAT(ip_out_sw_cksum);
22686 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22687 			    LENGTH - hlen);
22688 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22689 			if (*up == 0)
22690 				*up = 0xFFFF;
22691 		} else if (PROTO == IPPROTO_SCTP &&
22692 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22693 			sctp_hdr_t	*sctph;
22694 
22695 			hlen = (V_HLEN & 0xF) << 2;
22696 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22697 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22698 			sctph->sh_chksum = 0;
22699 #ifdef	DEBUG
22700 			if (!skip_sctp_cksum)
22701 #endif
22702 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22703 		} else {
22704 			queue_t *dev_q = stq->q_next;
22705 
22706 			if ((dev_q->q_next || dev_q->q_first) &&
22707 			    !canput(dev_q)) {
22708 			    blocked:
22709 				ipha->ipha_ident = ip_hdr_included;
22710 				/*
22711 				 * If we don't have a conn to apply
22712 				 * backpressure, free the message.
22713 				 * In the ire_send path, we don't know
22714 				 * the position to requeue the packet. Rather
22715 				 * than reorder packets, we just drop this
22716 				 * packet.
22717 				 */
22718 				if (ip_output_queue && connp != NULL &&
22719 				    caller != IRE_SEND) {
22720 					if (caller == IP_WSRV) {
22721 						connp->conn_did_putbq = 1;
22722 						(void) putbq(connp->conn_wq,
22723 						    first_mp);
22724 						conn_drain_insert(connp);
22725 						/*
22726 						 * This is the service thread,
22727 						 * and the queue is already
22728 						 * noenabled. The check for
22729 						 * canput and the putbq is not
22730 						 * atomic. So we need to check
22731 						 * again.
22732 						 */
22733 						if (canput(stq->q_next))
22734 							connp->conn_did_putbq
22735 							    = 0;
22736 						IP_STAT(ip_conn_flputbq);
22737 					} else {
22738 						/*
22739 						 * We are not the service proc.
22740 						 * ip_wsrv will be scheduled or
22741 						 * is already running.
22742 						 */
22743 						(void) putq(connp->conn_wq,
22744 						    first_mp);
22745 					}
22746 				} else {
22747 					out_ill = (ill_t *)stq->q_ptr;
22748 					BUMP_MIB(out_ill->ill_ip_mib,
22749 					    ipIfStatsOutDiscards);
22750 					freemsg(first_mp);
22751 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22752 					    "ip_wput_ire_end: q %p (%S)",
22753 					    q, "discard");
22754 				}
22755 				ire_refrele(ire);
22756 				if (next_mp) {
22757 					ire_refrele(ire1);
22758 					freemsg(next_mp);
22759 				}
22760 				if (conn_outgoing_ill != NULL)
22761 					ill_refrele(conn_outgoing_ill);
22762 				return;
22763 			}
22764 			if ((PROTO == IPPROTO_UDP) &&
22765 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22766 				/*
22767 				 * hlen gets the number of uchar_ts in the
22768 				 * IP header
22769 				 */
22770 				hlen = (V_HLEN & 0xF) << 2;
22771 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22772 				max_frag = ire->ire_max_frag;
22773 				if (*up != 0) {
22774 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22775 					    up, PROTO, hlen, LENGTH, max_frag,
22776 					    ipsec_len, cksum);
22777 					/* Software checksum? */
22778 					if (DB_CKSUMFLAGS(mp) == 0) {
22779 						IP_STAT(ip_out_sw_cksum);
22780 						IP_STAT_UPDATE(
22781 						    ip_udp_out_sw_cksum_bytes,
22782 						    LENGTH - hlen);
22783 					}
22784 				}
22785 			}
22786 		}
22787 		/*
22788 		 * Need to do this even when fragmenting. The local
22789 		 * loopback can be done without computing checksums
22790 		 * but forwarding out other interface must be done
22791 		 * after the IP checksum (and ULP checksums) have been
22792 		 * computed.
22793 		 *
22794 		 * NOTE : multicast_forward is set only if this packet
22795 		 * originated from ip_wput. For packets originating from
22796 		 * ip_wput_multicast, it is not set.
22797 		 */
22798 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22799 		    multi_loopback:
22800 			ip2dbg(("ip_wput: multicast, loop %d\n",
22801 			    conn_multicast_loop));
22802 
22803 			/*  Forget header checksum offload */
22804 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22805 
22806 			/*
22807 			 * Local loopback of multicasts?  Check the
22808 			 * ill.
22809 			 *
22810 			 * Note that the loopback function will not come
22811 			 * in through ip_rput - it will only do the
22812 			 * client fanout thus we need to do an mforward
22813 			 * as well.  The is different from the BSD
22814 			 * logic.
22815 			 */
22816 			if (ill != NULL) {
22817 				ilm_t	*ilm;
22818 
22819 				ILM_WALKER_HOLD(ill);
22820 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22821 				    ALL_ZONES);
22822 				ILM_WALKER_RELE(ill);
22823 				if (ilm != NULL) {
22824 					/*
22825 					 * Pass along the virtual output q.
22826 					 * ip_wput_local() will distribute the
22827 					 * packet to all the matching zones,
22828 					 * except the sending zone when
22829 					 * IP_MULTICAST_LOOP is false.
22830 					 */
22831 					ip_multicast_loopback(q, ill, first_mp,
22832 					    conn_multicast_loop ? 0 :
22833 					    IP_FF_NO_MCAST_LOOP, zoneid);
22834 				}
22835 			}
22836 			if (ipha->ipha_ttl == 0) {
22837 				/*
22838 				 * 0 => only to this host i.e. we are
22839 				 * done. We are also done if this was the
22840 				 * loopback interface since it is sufficient
22841 				 * to loopback one copy of a multicast packet.
22842 				 */
22843 				freemsg(first_mp);
22844 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22845 				    "ip_wput_ire_end: q %p (%S)",
22846 				    q, "loopback");
22847 				ire_refrele(ire);
22848 				if (conn_outgoing_ill != NULL)
22849 					ill_refrele(conn_outgoing_ill);
22850 				return;
22851 			}
22852 			/*
22853 			 * ILLF_MULTICAST is checked in ip_newroute
22854 			 * i.e. we don't need to check it here since
22855 			 * all IRE_CACHEs come from ip_newroute.
22856 			 * For multicast traffic, SO_DONTROUTE is interpreted
22857 			 * to mean only send the packet out the interface
22858 			 * (optionally specified with IP_MULTICAST_IF)
22859 			 * and do not forward it out additional interfaces.
22860 			 * RSVP and the rsvp daemon is an example of a
22861 			 * protocol and user level process that
22862 			 * handles it's own routing. Hence, it uses the
22863 			 * SO_DONTROUTE option to accomplish this.
22864 			 */
22865 
22866 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22867 				/* Unconditionally redo the checksum */
22868 				ipha->ipha_hdr_checksum = 0;
22869 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22870 
22871 				/*
22872 				 * If this needs to go out secure, we need
22873 				 * to wait till we finish the IPSEC
22874 				 * processing.
22875 				 */
22876 				if (ipsec_len == 0 &&
22877 				    ip_mforward(ill, ipha, mp)) {
22878 					freemsg(first_mp);
22879 					ip1dbg(("ip_wput: mforward failed\n"));
22880 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22881 					    "ip_wput_ire_end: q %p (%S)",
22882 					    q, "mforward failed");
22883 					ire_refrele(ire);
22884 					if (conn_outgoing_ill != NULL)
22885 						ill_refrele(conn_outgoing_ill);
22886 					return;
22887 				}
22888 			}
22889 		}
22890 		max_frag = ire->ire_max_frag;
22891 		cksum += ttl_protocol;
22892 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22893 			/* No fragmentation required for this one. */
22894 			/*
22895 			 * Don't use frag_flag if packet is pre-built or source
22896 			 * routed or if multicast (since multicast packets do
22897 			 * not solicit ICMP "packet too big" messages).
22898 			 */
22899 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22900 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22901 			    !ip_source_route_included(ipha)) &&
22902 			    !CLASSD(ipha->ipha_dst))
22903 				ipha->ipha_fragment_offset_and_flags |=
22904 				    htons(ire->ire_frag_flag);
22905 
22906 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22907 				/* Complete the IP header checksum. */
22908 				cksum += ipha->ipha_ident;
22909 				cksum += (v_hlen_tos_len >> 16)+
22910 				    (v_hlen_tos_len & 0xFFFF);
22911 				cksum += ipha->ipha_fragment_offset_and_flags;
22912 				hlen = (V_HLEN & 0xF) -
22913 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22914 				if (hlen) {
22915 				    checksumoptions:
22916 					/*
22917 					 * Account for the IP Options in the IP
22918 					 * header checksum.
22919 					 */
22920 					up = (uint16_t *)(rptr+
22921 					    IP_SIMPLE_HDR_LENGTH);
22922 					do {
22923 						cksum += up[0];
22924 						cksum += up[1];
22925 						up += 2;
22926 					} while (--hlen);
22927 				}
22928 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22929 				cksum = ~(cksum + (cksum >> 16));
22930 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22931 			}
22932 			if (ipsec_len != 0) {
22933 				ipsec_out_process(q, first_mp, ire, ill_index);
22934 				if (!next_mp) {
22935 					ire_refrele(ire);
22936 					if (conn_outgoing_ill != NULL)
22937 						ill_refrele(conn_outgoing_ill);
22938 					return;
22939 				}
22940 				goto next;
22941 			}
22942 
22943 			/*
22944 			 * multirt_send has already been handled
22945 			 * for broadcast, but not yet for multicast
22946 			 * or IP options.
22947 			 */
22948 			if (next_mp == NULL) {
22949 				if (ire->ire_flags & RTF_MULTIRT) {
22950 					multirt_send = B_TRUE;
22951 				}
22952 			}
22953 
22954 			/*
22955 			 * In most cases, the emission loop below is
22956 			 * entered only once. Only in the case where
22957 			 * the ire holds the RTF_MULTIRT flag, do we loop
22958 			 * to process all RTF_MULTIRT ires in the bucket,
22959 			 * and send the packet through all crossed
22960 			 * RTF_MULTIRT routes.
22961 			 */
22962 			do {
22963 				if (multirt_send) {
22964 					irb_t *irb;
22965 
22966 					irb = ire->ire_bucket;
22967 					ASSERT(irb != NULL);
22968 					/*
22969 					 * We are in a multiple send case,
22970 					 * need to get the next IRE and make
22971 					 * a duplicate of the packet.
22972 					 */
22973 					IRB_REFHOLD(irb);
22974 					for (ire1 = ire->ire_next;
22975 					    ire1 != NULL;
22976 					    ire1 = ire1->ire_next) {
22977 						if (!(ire1->ire_flags &
22978 						    RTF_MULTIRT))
22979 							continue;
22980 						if (ire1->ire_addr !=
22981 						    ire->ire_addr)
22982 							continue;
22983 						if (ire1->ire_marks &
22984 						    (IRE_MARK_CONDEMNED|
22985 							IRE_MARK_HIDDEN))
22986 							continue;
22987 
22988 						/* Got one */
22989 						IRE_REFHOLD(ire1);
22990 						break;
22991 					}
22992 					IRB_REFRELE(irb);
22993 
22994 					if (ire1 != NULL) {
22995 						next_mp = copyb(mp);
22996 						if ((next_mp == NULL) ||
22997 						    ((mp->b_cont != NULL) &&
22998 						    ((next_mp->b_cont =
22999 						    dupmsg(mp->b_cont))
23000 						    == NULL))) {
23001 							freemsg(next_mp);
23002 							next_mp = NULL;
23003 							ire_refrele(ire1);
23004 							ire1 = NULL;
23005 						}
23006 					}
23007 
23008 					/*
23009 					 * Last multiroute ire; don't loop
23010 					 * anymore. The emission is over
23011 					 * and next_mp is NULL.
23012 					 */
23013 					if (ire1 == NULL) {
23014 						multirt_send = B_FALSE;
23015 					}
23016 				}
23017 
23018 				out_ill = ire->ire_ipif->ipif_ill;
23019 				DTRACE_PROBE4(ip4__physical__out__start,
23020 				    ill_t *, NULL,
23021 				    ill_t *, out_ill,
23022 				    ipha_t *, ipha, mblk_t *, mp);
23023 				FW_HOOKS(ip4_physical_out_event,
23024 				    ipv4firewall_physical_out,
23025 				    NULL, out_ill, ipha, mp, mp);
23026 				DTRACE_PROBE1(ip4__physical__out__end,
23027 				    mblk_t *, mp);
23028 				if (mp == NULL)
23029 					goto release_ire_and_ill_2;
23030 
23031 				ASSERT(ipsec_len == 0);
23032 				mp->b_prev =
23033 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23034 				DTRACE_PROBE2(ip__xmit__2,
23035 				    mblk_t *, mp, ire_t *, ire);
23036 				pktxmit_state = ip_xmit_v4(mp, ire,
23037 				    NULL, B_TRUE);
23038 				if ((pktxmit_state == SEND_FAILED) ||
23039 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23040 release_ire_and_ill_2:
23041 					if (next_mp) {
23042 						freemsg(next_mp);
23043 						ire_refrele(ire1);
23044 					}
23045 					ire_refrele(ire);
23046 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23047 					    "ip_wput_ire_end: q %p (%S)",
23048 					    q, "discard MDATA");
23049 					if (conn_outgoing_ill != NULL)
23050 						ill_refrele(conn_outgoing_ill);
23051 					return;
23052 				}
23053 
23054 				if (CLASSD(dst)) {
23055 					BUMP_MIB(out_ill->ill_ip_mib,
23056 					    ipIfStatsHCOutMcastPkts);
23057 					UPDATE_MIB(out_ill->ill_ip_mib,
23058 					    ipIfStatsHCOutMcastOctets,
23059 					    ntohs(ipha->ipha_length));
23060 				} else if (ire->ire_type == IRE_BROADCAST) {
23061 					BUMP_MIB(out_ill->ill_ip_mib,
23062 					    ipIfStatsHCOutBcastPkts);
23063 				}
23064 
23065 				if (multirt_send) {
23066 					/*
23067 					 * We are in a multiple send case,
23068 					 * need to re-enter the sending loop
23069 					 * using the next ire.
23070 					 */
23071 					ire_refrele(ire);
23072 					ire = ire1;
23073 					stq = ire->ire_stq;
23074 					mp = next_mp;
23075 					next_mp = NULL;
23076 					ipha = (ipha_t *)mp->b_rptr;
23077 					ill_index = Q_TO_INDEX(stq);
23078 				}
23079 			} while (multirt_send);
23080 
23081 			if (!next_mp) {
23082 				/*
23083 				 * Last copy going out (the ultra-common
23084 				 * case).  Note that we intentionally replicate
23085 				 * the putnext rather than calling it before
23086 				 * the next_mp check in hopes of a little
23087 				 * tail-call action out of the compiler.
23088 				 */
23089 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23090 				    "ip_wput_ire_end: q %p (%S)",
23091 				    q, "last copy out(1)");
23092 				ire_refrele(ire);
23093 				if (conn_outgoing_ill != NULL)
23094 					ill_refrele(conn_outgoing_ill);
23095 				return;
23096 			}
23097 			/* More copies going out below. */
23098 		} else {
23099 			int offset;
23100 		    fragmentit:
23101 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23102 			/*
23103 			 * If this would generate a icmp_frag_needed message,
23104 			 * we need to handle it before we do the IPSEC
23105 			 * processing. Otherwise, we need to strip the IPSEC
23106 			 * headers before we send up the message to the ULPs
23107 			 * which becomes messy and difficult.
23108 			 */
23109 			if (ipsec_len != 0) {
23110 				if ((max_frag < (unsigned int)(LENGTH +
23111 				    ipsec_len)) && (offset & IPH_DF)) {
23112 					out_ill = (ill_t *)stq->q_ptr;
23113 					BUMP_MIB(out_ill->ill_ip_mib,
23114 					    ipIfStatsOutFragFails);
23115 					BUMP_MIB(out_ill->ill_ip_mib,
23116 					    ipIfStatsOutFragReqds);
23117 					ipha->ipha_hdr_checksum = 0;
23118 					ipha->ipha_hdr_checksum =
23119 					    (uint16_t)ip_csum_hdr(ipha);
23120 					icmp_frag_needed(ire->ire_stq, first_mp,
23121 					    max_frag, zoneid);
23122 					if (!next_mp) {
23123 						ire_refrele(ire);
23124 						if (conn_outgoing_ill != NULL) {
23125 							ill_refrele(
23126 							    conn_outgoing_ill);
23127 						}
23128 						return;
23129 					}
23130 				} else {
23131 					/*
23132 					 * This won't cause a icmp_frag_needed
23133 					 * message. to be generated. Send it on
23134 					 * the wire. Note that this could still
23135 					 * cause fragmentation and all we
23136 					 * do is the generation of the message
23137 					 * to the ULP if needed before IPSEC.
23138 					 */
23139 					if (!next_mp) {
23140 						ipsec_out_process(q, first_mp,
23141 						    ire, ill_index);
23142 						TRACE_2(TR_FAC_IP,
23143 						    TR_IP_WPUT_IRE_END,
23144 						    "ip_wput_ire_end: q %p "
23145 						    "(%S)", q,
23146 						    "last ipsec_out_process");
23147 						ire_refrele(ire);
23148 						if (conn_outgoing_ill != NULL) {
23149 							ill_refrele(
23150 							    conn_outgoing_ill);
23151 						}
23152 						return;
23153 					}
23154 					ipsec_out_process(q, first_mp,
23155 					    ire, ill_index);
23156 				}
23157 			} else {
23158 				/*
23159 				 * Initiate IPPF processing. For
23160 				 * fragmentable packets we finish
23161 				 * all QOS packet processing before
23162 				 * calling:
23163 				 * ip_wput_ire_fragmentit->ip_wput_frag
23164 				 */
23165 
23166 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
23167 					ip_process(IPP_LOCAL_OUT, &mp,
23168 					    ill_index);
23169 					if (mp == NULL) {
23170 						out_ill = (ill_t *)stq->q_ptr;
23171 						BUMP_MIB(out_ill->ill_ip_mib,
23172 						    ipIfStatsOutDiscards);
23173 						if (next_mp != NULL) {
23174 							freemsg(next_mp);
23175 							ire_refrele(ire1);
23176 						}
23177 						ire_refrele(ire);
23178 						TRACE_2(TR_FAC_IP,
23179 						    TR_IP_WPUT_IRE_END,
23180 						    "ip_wput_ire: q %p (%S)",
23181 						    q, "discard MDATA");
23182 						if (conn_outgoing_ill != NULL) {
23183 							ill_refrele(
23184 							    conn_outgoing_ill);
23185 						}
23186 						return;
23187 					}
23188 				}
23189 				if (!next_mp) {
23190 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23191 					    "ip_wput_ire_end: q %p (%S)",
23192 					    q, "last fragmentation");
23193 					ip_wput_ire_fragmentit(mp, ire,
23194 					    zoneid);
23195 					ire_refrele(ire);
23196 					if (conn_outgoing_ill != NULL)
23197 						ill_refrele(conn_outgoing_ill);
23198 					return;
23199 				}
23200 				ip_wput_ire_fragmentit(mp, ire, zoneid);
23201 			}
23202 		}
23203 	} else {
23204 	    nullstq:
23205 		/* A NULL stq means the destination address is local. */
23206 		UPDATE_OB_PKT_COUNT(ire);
23207 		ire->ire_last_used_time = lbolt;
23208 		ASSERT(ire->ire_ipif != NULL);
23209 		if (!next_mp) {
23210 			/*
23211 			 * Is there an "in" and "out" for traffic local
23212 			 * to a host (loopback)?  The code in Solaris doesn't
23213 			 * explicitly draw a line in its code for in vs out,
23214 			 * so we've had to draw a line in the sand: ip_wput_ire
23215 			 * is considered to be the "output" side and
23216 			 * ip_wput_local to be the "input" side.
23217 			 */
23218 			out_ill = ire->ire_ipif->ipif_ill;
23219 
23220 			DTRACE_PROBE4(ip4__loopback__out__start,
23221 			    ill_t *, NULL, ill_t *, out_ill,
23222 			    ipha_t *, ipha, mblk_t *, first_mp);
23223 
23224 			FW_HOOKS(ip4_loopback_out_event,
23225 			    ipv4firewall_loopback_out,
23226 			    NULL, out_ill, ipha, first_mp, mp);
23227 
23228 			DTRACE_PROBE1(ip4__loopback__out_end,
23229 			    mblk_t *, first_mp);
23230 
23231 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23232 			    "ip_wput_ire_end: q %p (%S)",
23233 			    q, "local address");
23234 
23235 			if (first_mp != NULL)
23236 				ip_wput_local(q, out_ill, ipha,
23237 				    first_mp, ire, 0, ire->ire_zoneid);
23238 			ire_refrele(ire);
23239 			if (conn_outgoing_ill != NULL)
23240 				ill_refrele(conn_outgoing_ill);
23241 			return;
23242 		}
23243 
23244 		out_ill = ire->ire_ipif->ipif_ill;
23245 
23246 		DTRACE_PROBE4(ip4__loopback__out__start,
23247 		    ill_t *, NULL, ill_t *, out_ill,
23248 		    ipha_t *, ipha, mblk_t *, first_mp);
23249 
23250 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
23251 		    NULL, out_ill, ipha, first_mp, mp);
23252 
23253 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23254 
23255 		if (first_mp != NULL)
23256 			ip_wput_local(q, out_ill, ipha,
23257 			    first_mp, ire, 0, ire->ire_zoneid);
23258 	}
23259 next:
23260 	/*
23261 	 * More copies going out to additional interfaces.
23262 	 * ire1 has already been held. We don't need the
23263 	 * "ire" anymore.
23264 	 */
23265 	ire_refrele(ire);
23266 	ire = ire1;
23267 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23268 	mp = next_mp;
23269 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23270 	ill = ire_to_ill(ire);
23271 	first_mp = mp;
23272 	if (ipsec_len != 0) {
23273 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23274 		mp = mp->b_cont;
23275 	}
23276 	dst = ire->ire_addr;
23277 	ipha = (ipha_t *)mp->b_rptr;
23278 	/*
23279 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23280 	 * Restore ipha_ident "no checksum" flag.
23281 	 */
23282 	src = orig_src;
23283 	ipha->ipha_ident = ip_hdr_included;
23284 	goto another;
23285 
23286 #undef	rptr
23287 #undef	Q_TO_INDEX
23288 }
23289 
23290 /*
23291  * Routine to allocate a message that is used to notify the ULP about MDT.
23292  * The caller may provide a pointer to the link-layer MDT capabilities,
23293  * or NULL if MDT is to be disabled on the stream.
23294  */
23295 mblk_t *
23296 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23297 {
23298 	mblk_t *mp;
23299 	ip_mdt_info_t *mdti;
23300 	ill_mdt_capab_t *idst;
23301 
23302 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23303 		DB_TYPE(mp) = M_CTL;
23304 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23305 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23306 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23307 		idst = &(mdti->mdt_capab);
23308 
23309 		/*
23310 		 * If the caller provides us with the capability, copy
23311 		 * it over into our notification message; otherwise
23312 		 * we zero out the capability portion.
23313 		 */
23314 		if (isrc != NULL)
23315 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23316 		else
23317 			bzero((caddr_t)idst, sizeof (*idst));
23318 	}
23319 	return (mp);
23320 }
23321 
23322 /*
23323  * Routine which determines whether MDT can be enabled on the destination
23324  * IRE and IPC combination, and if so, allocates and returns the MDT
23325  * notification mblk that may be used by ULP.  We also check if we need to
23326  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23327  * MDT usage in the past have been lifted.  This gets called during IP
23328  * and ULP binding.
23329  */
23330 mblk_t *
23331 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23332     ill_mdt_capab_t *mdt_cap)
23333 {
23334 	mblk_t *mp;
23335 	boolean_t rc = B_FALSE;
23336 
23337 	ASSERT(dst_ire != NULL);
23338 	ASSERT(connp != NULL);
23339 	ASSERT(mdt_cap != NULL);
23340 
23341 	/*
23342 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23343 	 * Multidata, which is handled in tcp_multisend().  This
23344 	 * is the reason why we do all these checks here, to ensure
23345 	 * that we don't enable Multidata for the cases which we
23346 	 * can't handle at the moment.
23347 	 */
23348 	do {
23349 		/* Only do TCP at the moment */
23350 		if (connp->conn_ulp != IPPROTO_TCP)
23351 			break;
23352 
23353 		/*
23354 		 * IPSEC outbound policy present?  Note that we get here
23355 		 * after calling ipsec_conn_cache_policy() where the global
23356 		 * policy checking is performed.  conn_latch will be
23357 		 * non-NULL as long as there's a policy defined,
23358 		 * i.e. conn_out_enforce_policy may be NULL in such case
23359 		 * when the connection is non-secure, and hence we check
23360 		 * further if the latch refers to an outbound policy.
23361 		 */
23362 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23363 			break;
23364 
23365 		/* CGTP (multiroute) is enabled? */
23366 		if (dst_ire->ire_flags & RTF_MULTIRT)
23367 			break;
23368 
23369 		/* Outbound IPQoS enabled? */
23370 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
23371 			/*
23372 			 * In this case, we disable MDT for this and all
23373 			 * future connections going over the interface.
23374 			 */
23375 			mdt_cap->ill_mdt_on = 0;
23376 			break;
23377 		}
23378 
23379 		/* socket option(s) present? */
23380 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23381 			break;
23382 
23383 		rc = B_TRUE;
23384 	/* CONSTCOND */
23385 	} while (0);
23386 
23387 	/* Remember the result */
23388 	connp->conn_mdt_ok = rc;
23389 
23390 	if (!rc)
23391 		return (NULL);
23392 	else if (!mdt_cap->ill_mdt_on) {
23393 		/*
23394 		 * If MDT has been previously turned off in the past, and we
23395 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23396 		 * then enable it for this interface.
23397 		 */
23398 		mdt_cap->ill_mdt_on = 1;
23399 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23400 		    "interface %s\n", ill_name));
23401 	}
23402 
23403 	/* Allocate the MDT info mblk */
23404 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23405 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23406 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23407 		return (NULL);
23408 	}
23409 	return (mp);
23410 }
23411 
23412 /*
23413  * Routine to allocate a message that is used to notify the ULP about LSO.
23414  * The caller may provide a pointer to the link-layer LSO capabilities,
23415  * or NULL if LSO is to be disabled on the stream.
23416  */
23417 mblk_t *
23418 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23419 {
23420 	mblk_t *mp;
23421 	ip_lso_info_t *lsoi;
23422 	ill_lso_capab_t *idst;
23423 
23424 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23425 		DB_TYPE(mp) = M_CTL;
23426 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23427 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23428 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23429 		idst = &(lsoi->lso_capab);
23430 
23431 		/*
23432 		 * If the caller provides us with the capability, copy
23433 		 * it over into our notification message; otherwise
23434 		 * we zero out the capability portion.
23435 		 */
23436 		if (isrc != NULL)
23437 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23438 		else
23439 			bzero((caddr_t)idst, sizeof (*idst));
23440 	}
23441 	return (mp);
23442 }
23443 
23444 /*
23445  * Routine which determines whether LSO can be enabled on the destination
23446  * IRE and IPC combination, and if so, allocates and returns the LSO
23447  * notification mblk that may be used by ULP.  We also check if we need to
23448  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23449  * LSO usage in the past have been lifted.  This gets called during IP
23450  * and ULP binding.
23451  */
23452 mblk_t *
23453 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23454     ill_lso_capab_t *lso_cap)
23455 {
23456 	mblk_t *mp;
23457 
23458 	ASSERT(dst_ire != NULL);
23459 	ASSERT(connp != NULL);
23460 	ASSERT(lso_cap != NULL);
23461 
23462 	connp->conn_lso_ok = B_TRUE;
23463 
23464 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23465 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23466 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23467 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23468 	    (IPP_ENABLED(IPP_LOCAL_OUT))) {
23469 		connp->conn_lso_ok = B_FALSE;
23470 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
23471 			/*
23472 			 * Disable LSO for this and all future connections going
23473 			 * over the interface.
23474 			 */
23475 			lso_cap->ill_lso_on = 0;
23476 		}
23477 	}
23478 
23479 	if (!connp->conn_lso_ok)
23480 		return (NULL);
23481 	else if (!lso_cap->ill_lso_on) {
23482 		/*
23483 		 * If LSO has been previously turned off in the past, and we
23484 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23485 		 * then enable it for this interface.
23486 		 */
23487 		lso_cap->ill_lso_on = 1;
23488 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23489 		    ill_name));
23490 	}
23491 
23492 	/* Allocate the LSO info mblk */
23493 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23494 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23495 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23496 
23497 	return (mp);
23498 }
23499 
23500 /*
23501  * Create destination address attribute, and fill it with the physical
23502  * destination address and SAP taken from the template DL_UNITDATA_REQ
23503  * message block.
23504  */
23505 boolean_t
23506 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23507 {
23508 	dl_unitdata_req_t *dlurp;
23509 	pattr_t *pa;
23510 	pattrinfo_t pa_info;
23511 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23512 	uint_t das_len, das_off;
23513 
23514 	ASSERT(dlmp != NULL);
23515 
23516 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23517 	das_len = dlurp->dl_dest_addr_length;
23518 	das_off = dlurp->dl_dest_addr_offset;
23519 
23520 	pa_info.type = PATTR_DSTADDRSAP;
23521 	pa_info.len = sizeof (**das) + das_len - 1;
23522 
23523 	/* create and associate the attribute */
23524 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23525 	if (pa != NULL) {
23526 		ASSERT(*das != NULL);
23527 		(*das)->addr_is_group = 0;
23528 		(*das)->addr_len = (uint8_t)das_len;
23529 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23530 	}
23531 
23532 	return (pa != NULL);
23533 }
23534 
23535 /*
23536  * Create hardware checksum attribute and fill it with the values passed.
23537  */
23538 boolean_t
23539 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23540     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23541 {
23542 	pattr_t *pa;
23543 	pattrinfo_t pa_info;
23544 
23545 	ASSERT(mmd != NULL);
23546 
23547 	pa_info.type = PATTR_HCKSUM;
23548 	pa_info.len = sizeof (pattr_hcksum_t);
23549 
23550 	/* create and associate the attribute */
23551 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23552 	if (pa != NULL) {
23553 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23554 
23555 		hck->hcksum_start_offset = start_offset;
23556 		hck->hcksum_stuff_offset = stuff_offset;
23557 		hck->hcksum_end_offset = end_offset;
23558 		hck->hcksum_flags = flags;
23559 	}
23560 	return (pa != NULL);
23561 }
23562 
23563 /*
23564  * Create zerocopy attribute and fill it with the specified flags
23565  */
23566 boolean_t
23567 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23568 {
23569 	pattr_t *pa;
23570 	pattrinfo_t pa_info;
23571 
23572 	ASSERT(mmd != NULL);
23573 	pa_info.type = PATTR_ZCOPY;
23574 	pa_info.len = sizeof (pattr_zcopy_t);
23575 
23576 	/* create and associate the attribute */
23577 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23578 	if (pa != NULL) {
23579 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23580 
23581 		zcopy->zcopy_flags = flags;
23582 	}
23583 	return (pa != NULL);
23584 }
23585 
23586 /*
23587  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23588  * block chain. We could rewrite to handle arbitrary message block chains but
23589  * that would make the code complicated and slow. Right now there three
23590  * restrictions:
23591  *
23592  *   1. The first message block must contain the complete IP header and
23593  *	at least 1 byte of payload data.
23594  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23595  *	so that we can use a single Multidata message.
23596  *   3. No frag must be distributed over two or more message blocks so
23597  *	that we don't need more than two packet descriptors per frag.
23598  *
23599  * The above restrictions allow us to support userland applications (which
23600  * will send down a single message block) and NFS over UDP (which will
23601  * send down a chain of at most three message blocks).
23602  *
23603  * We also don't use MDT for payloads with less than or equal to
23604  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23605  */
23606 boolean_t
23607 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23608 {
23609 	int	blocks;
23610 	ssize_t	total, missing, size;
23611 
23612 	ASSERT(mp != NULL);
23613 	ASSERT(hdr_len > 0);
23614 
23615 	size = MBLKL(mp) - hdr_len;
23616 	if (size <= 0)
23617 		return (B_FALSE);
23618 
23619 	/* The first mblk contains the header and some payload. */
23620 	blocks = 1;
23621 	total = size;
23622 	size %= len;
23623 	missing = (size == 0) ? 0 : (len - size);
23624 	mp = mp->b_cont;
23625 
23626 	while (mp != NULL) {
23627 		/*
23628 		 * Give up if we encounter a zero length message block.
23629 		 * In practice, this should rarely happen and therefore
23630 		 * not worth the trouble of freeing and re-linking the
23631 		 * mblk from the chain to handle such case.
23632 		 */
23633 		if ((size = MBLKL(mp)) == 0)
23634 			return (B_FALSE);
23635 
23636 		/* Too many payload buffers for a single Multidata message? */
23637 		if (++blocks > MULTIDATA_MAX_PBUFS)
23638 			return (B_FALSE);
23639 
23640 		total += size;
23641 		/* Is a frag distributed over two or more message blocks? */
23642 		if (missing > size)
23643 			return (B_FALSE);
23644 		size -= missing;
23645 
23646 		size %= len;
23647 		missing = (size == 0) ? 0 : (len - size);
23648 
23649 		mp = mp->b_cont;
23650 	}
23651 
23652 	return (total > ip_wput_frag_mdt_min);
23653 }
23654 
23655 /*
23656  * Outbound IPv4 fragmentation routine using MDT.
23657  */
23658 static void
23659 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23660     uint32_t frag_flag, int offset)
23661 {
23662 	ipha_t		*ipha_orig;
23663 	int		i1, ip_data_end;
23664 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23665 	mblk_t		*hdr_mp, *md_mp = NULL;
23666 	unsigned char	*hdr_ptr, *pld_ptr;
23667 	multidata_t	*mmd;
23668 	ip_pdescinfo_t	pdi;
23669 	ill_t		*ill;
23670 
23671 	ASSERT(DB_TYPE(mp) == M_DATA);
23672 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23673 
23674 	ill = ire_to_ill(ire);
23675 	ASSERT(ill != NULL);
23676 
23677 	ipha_orig = (ipha_t *)mp->b_rptr;
23678 	mp->b_rptr += sizeof (ipha_t);
23679 
23680 	/* Calculate how many packets we will send out */
23681 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23682 	pkts = (i1 + len - 1) / len;
23683 	ASSERT(pkts > 1);
23684 
23685 	/* Allocate a message block which will hold all the IP Headers. */
23686 	wroff = ip_wroff_extra;
23687 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23688 
23689 	i1 = pkts * hdr_chunk_len;
23690 	/*
23691 	 * Create the header buffer, Multidata and destination address
23692 	 * and SAP attribute that should be associated with it.
23693 	 */
23694 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23695 	    ((hdr_mp->b_wptr += i1),
23696 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23697 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23698 		freemsg(mp);
23699 		if (md_mp == NULL) {
23700 			freemsg(hdr_mp);
23701 		} else {
23702 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
23703 			freemsg(md_mp);
23704 		}
23705 		IP_STAT(ip_frag_mdt_allocfail);
23706 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23707 		return;
23708 	}
23709 	IP_STAT(ip_frag_mdt_allocd);
23710 
23711 	/*
23712 	 * Add a payload buffer to the Multidata; this operation must not
23713 	 * fail, or otherwise our logic in this routine is broken.  There
23714 	 * is no memory allocation done by the routine, so any returned
23715 	 * failure simply tells us that we've done something wrong.
23716 	 *
23717 	 * A failure tells us that either we're adding the same payload
23718 	 * buffer more than once, or we're trying to add more buffers than
23719 	 * allowed.  None of the above cases should happen, and we panic
23720 	 * because either there's horrible heap corruption, and/or
23721 	 * programming mistake.
23722 	 */
23723 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23724 		goto pbuf_panic;
23725 
23726 	hdr_ptr = hdr_mp->b_rptr;
23727 	pld_ptr = mp->b_rptr;
23728 
23729 	/* Establish the ending byte offset, based on the starting offset. */
23730 	offset <<= 3;
23731 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23732 	    IP_SIMPLE_HDR_LENGTH;
23733 
23734 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23735 
23736 	while (pld_ptr < mp->b_wptr) {
23737 		ipha_t		*ipha;
23738 		uint16_t	offset_and_flags;
23739 		uint16_t	ip_len;
23740 		int		error;
23741 
23742 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23743 		ipha = (ipha_t *)(hdr_ptr + wroff);
23744 		ASSERT(OK_32PTR(ipha));
23745 		*ipha = *ipha_orig;
23746 
23747 		if (ip_data_end - offset > len) {
23748 			offset_and_flags = IPH_MF;
23749 		} else {
23750 			/*
23751 			 * Last frag. Set len to the length of this last piece.
23752 			 */
23753 			len = ip_data_end - offset;
23754 			/* A frag of a frag might have IPH_MF non-zero */
23755 			offset_and_flags =
23756 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23757 			    IPH_MF;
23758 		}
23759 		offset_and_flags |= (uint16_t)(offset >> 3);
23760 		offset_and_flags |= (uint16_t)frag_flag;
23761 		/* Store the offset and flags in the IP header. */
23762 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23763 
23764 		/* Store the length in the IP header. */
23765 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23766 		ipha->ipha_length = htons(ip_len);
23767 
23768 		/*
23769 		 * Set the IP header checksum.  Note that mp is just
23770 		 * the header, so this is easy to pass to ip_csum.
23771 		 */
23772 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23773 
23774 		/*
23775 		 * Record offset and size of header and data of the next packet
23776 		 * in the multidata message.
23777 		 */
23778 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23779 		PDESC_PLD_INIT(&pdi);
23780 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23781 		ASSERT(i1 > 0);
23782 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23783 		if (i1 == len) {
23784 			pld_ptr += len;
23785 		} else {
23786 			i1 = len - i1;
23787 			mp = mp->b_cont;
23788 			ASSERT(mp != NULL);
23789 			ASSERT(MBLKL(mp) >= i1);
23790 			/*
23791 			 * Attach the next payload message block to the
23792 			 * multidata message.
23793 			 */
23794 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23795 				goto pbuf_panic;
23796 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23797 			pld_ptr = mp->b_rptr + i1;
23798 		}
23799 
23800 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23801 		    KM_NOSLEEP)) == NULL) {
23802 			/*
23803 			 * Any failure other than ENOMEM indicates that we
23804 			 * have passed in invalid pdesc info or parameters
23805 			 * to mmd_addpdesc, which must not happen.
23806 			 *
23807 			 * EINVAL is a result of failure on boundary checks
23808 			 * against the pdesc info contents.  It should not
23809 			 * happen, and we panic because either there's
23810 			 * horrible heap corruption, and/or programming
23811 			 * mistake.
23812 			 */
23813 			if (error != ENOMEM) {
23814 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23815 				    "pdesc logic error detected for "
23816 				    "mmd %p pinfo %p (%d)\n",
23817 				    (void *)mmd, (void *)&pdi, error);
23818 				/* NOTREACHED */
23819 			}
23820 			IP_STAT(ip_frag_mdt_addpdescfail);
23821 			/* Free unattached payload message blocks as well */
23822 			md_mp->b_cont = mp->b_cont;
23823 			goto free_mmd;
23824 		}
23825 
23826 		/* Advance fragment offset. */
23827 		offset += len;
23828 
23829 		/* Advance to location for next header in the buffer. */
23830 		hdr_ptr += hdr_chunk_len;
23831 
23832 		/* Did we reach the next payload message block? */
23833 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23834 			mp = mp->b_cont;
23835 			/*
23836 			 * Attach the next message block with payload
23837 			 * data to the multidata message.
23838 			 */
23839 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23840 				goto pbuf_panic;
23841 			pld_ptr = mp->b_rptr;
23842 		}
23843 	}
23844 
23845 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23846 	ASSERT(mp->b_wptr == pld_ptr);
23847 
23848 	/* Update IP statistics */
23849 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
23850 
23851 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23852 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23853 
23854 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23855 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23856 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23857 
23858 	if (pkt_type == OB_PKT) {
23859 		ire->ire_ob_pkt_count += pkts;
23860 		if (ire->ire_ipif != NULL)
23861 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23862 	} else {
23863 		/*
23864 		 * The type is IB_PKT in the forwarding path and in
23865 		 * the mobile IP case when the packet is being reverse-
23866 		 * tunneled to the home agent.
23867 		 */
23868 		ire->ire_ib_pkt_count += pkts;
23869 		ASSERT(!IRE_IS_LOCAL(ire));
23870 		if (ire->ire_type & IRE_BROADCAST) {
23871 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23872 		} else {
23873 			UPDATE_MIB(ill->ill_ip_mib,
23874 			    ipIfStatsHCOutForwDatagrams, pkts);
23875 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23876 		}
23877 	}
23878 	ire->ire_last_used_time = lbolt;
23879 	/* Send it down */
23880 	putnext(ire->ire_stq, md_mp);
23881 	return;
23882 
23883 pbuf_panic:
23884 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23885 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23886 	    pbuf_idx);
23887 	/* NOTREACHED */
23888 }
23889 
23890 /*
23891  * Outbound IP fragmentation routine.
23892  *
23893  * NOTE : This routine does not ire_refrele the ire that is passed in
23894  * as the argument.
23895  */
23896 static void
23897 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23898     uint32_t frag_flag, zoneid_t zoneid)
23899 {
23900 	int		i1;
23901 	mblk_t		*ll_hdr_mp;
23902 	int 		ll_hdr_len;
23903 	int		hdr_len;
23904 	mblk_t		*hdr_mp;
23905 	ipha_t		*ipha;
23906 	int		ip_data_end;
23907 	int		len;
23908 	mblk_t		*mp = mp_orig, *mp1;
23909 	int		offset;
23910 	queue_t		*q;
23911 	uint32_t	v_hlen_tos_len;
23912 	mblk_t		*first_mp;
23913 	boolean_t	mctl_present;
23914 	ill_t		*ill;
23915 	ill_t		*out_ill;
23916 	mblk_t		*xmit_mp;
23917 	mblk_t		*carve_mp;
23918 	ire_t		*ire1 = NULL;
23919 	ire_t		*save_ire = NULL;
23920 	mblk_t  	*next_mp = NULL;
23921 	boolean_t	last_frag = B_FALSE;
23922 	boolean_t	multirt_send = B_FALSE;
23923 	ire_t		*first_ire = NULL;
23924 	irb_t		*irb = NULL;
23925 	mib2_ipIfStatsEntry_t *mibptr = NULL;
23926 
23927 	ill = ire_to_ill(ire);
23928 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ip_mib;
23929 
23930 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
23931 
23932 	/*
23933 	 * IPSEC does not allow hw accelerated packets to be fragmented
23934 	 * This check is made in ip_wput_ipsec_out prior to coming here
23935 	 * via ip_wput_ire_fragmentit.
23936 	 *
23937 	 * If at this point we have an ire whose ARP request has not
23938 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23939 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23940 	 * This packet and all fragmentable packets for this ire will
23941 	 * continue to get dropped while ire_nce->nce_state remains in
23942 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23943 	 * ND_REACHABLE, all subsquent large packets for this ire will
23944 	 * get fragemented and sent out by this function.
23945 	 */
23946 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23947 		/* If nce_state is ND_INITIAL, trigger ARP query */
23948 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23949 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23950 		    " -  dropping packet\n"));
23951 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23952 		freemsg(mp);
23953 		return;
23954 	}
23955 
23956 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23957 	    "ip_wput_frag_start:");
23958 
23959 	if (mp->b_datap->db_type == M_CTL) {
23960 		first_mp = mp;
23961 		mp_orig = mp = mp->b_cont;
23962 		mctl_present = B_TRUE;
23963 	} else {
23964 		first_mp = mp;
23965 		mctl_present = B_FALSE;
23966 	}
23967 
23968 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23969 	ipha = (ipha_t *)mp->b_rptr;
23970 
23971 	/*
23972 	 * If the Don't Fragment flag is on, generate an ICMP destination
23973 	 * unreachable, fragmentation needed.
23974 	 */
23975 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23976 	if (offset & IPH_DF) {
23977 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23978 		/*
23979 		 * Need to compute hdr checksum if called from ip_wput_ire.
23980 		 * Note that ip_rput_forward verifies the checksum before
23981 		 * calling this routine so in that case this is a noop.
23982 		 */
23983 		ipha->ipha_hdr_checksum = 0;
23984 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23985 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid);
23986 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23987 		    "ip_wput_frag_end:(%S)",
23988 		    "don't fragment");
23989 		return;
23990 	}
23991 	if (mctl_present)
23992 		freeb(first_mp);
23993 	/*
23994 	 * Establish the starting offset.  May not be zero if we are fragging
23995 	 * a fragment that is being forwarded.
23996 	 */
23997 	offset = offset & IPH_OFFSET;
23998 
23999 	/* TODO why is this test needed? */
24000 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24001 	if (((max_frag - LENGTH) & ~7) < 8) {
24002 		/* TODO: notify ulp somehow */
24003 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24004 		freemsg(mp);
24005 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24006 		    "ip_wput_frag_end:(%S)",
24007 		    "len < 8");
24008 		return;
24009 	}
24010 
24011 	hdr_len = (V_HLEN & 0xF) << 2;
24012 
24013 	ipha->ipha_hdr_checksum = 0;
24014 
24015 	/*
24016 	 * Establish the number of bytes maximum per frag, after putting
24017 	 * in the header.
24018 	 */
24019 	len = (max_frag - hdr_len) & ~7;
24020 
24021 	/* Check if we can use MDT to send out the frags. */
24022 	ASSERT(!IRE_IS_LOCAL(ire));
24023 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
24024 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
24025 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24026 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24027 		ASSERT(ill->ill_mdt_capab != NULL);
24028 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24029 			/*
24030 			 * If MDT has been previously turned off in the past,
24031 			 * and we currently can do MDT (due to IPQoS policy
24032 			 * removal, etc.) then enable it for this interface.
24033 			 */
24034 			ill->ill_mdt_capab->ill_mdt_on = 1;
24035 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24036 			    ill->ill_name));
24037 		}
24038 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24039 		    offset);
24040 		return;
24041 	}
24042 
24043 	/* Get a copy of the header for the trailing frags */
24044 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
24045 	if (!hdr_mp) {
24046 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24047 		freemsg(mp);
24048 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24049 		    "ip_wput_frag_end:(%S)",
24050 		    "couldn't copy hdr");
24051 		return;
24052 	}
24053 	if (DB_CRED(mp) != NULL)
24054 		mblk_setcred(hdr_mp, DB_CRED(mp));
24055 
24056 	/* Store the starting offset, with the MoreFrags flag. */
24057 	i1 = offset | IPH_MF | frag_flag;
24058 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24059 
24060 	/* Establish the ending byte offset, based on the starting offset. */
24061 	offset <<= 3;
24062 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24063 
24064 	/* Store the length of the first fragment in the IP header. */
24065 	i1 = len + hdr_len;
24066 	ASSERT(i1 <= IP_MAXPACKET);
24067 	ipha->ipha_length = htons((uint16_t)i1);
24068 
24069 	/*
24070 	 * Compute the IP header checksum for the first frag.  We have to
24071 	 * watch out that we stop at the end of the header.
24072 	 */
24073 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24074 
24075 	/*
24076 	 * Now carve off the first frag.  Note that this will include the
24077 	 * original IP header.
24078 	 */
24079 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24080 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24081 		freeb(hdr_mp);
24082 		freemsg(mp_orig);
24083 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24084 		    "ip_wput_frag_end:(%S)",
24085 		    "couldn't carve first");
24086 		return;
24087 	}
24088 
24089 	/*
24090 	 * Multirouting case. Each fragment is replicated
24091 	 * via all non-condemned RTF_MULTIRT routes
24092 	 * currently resolved.
24093 	 * We ensure that first_ire is the first RTF_MULTIRT
24094 	 * ire in the bucket.
24095 	 */
24096 	if (ire->ire_flags & RTF_MULTIRT) {
24097 		irb = ire->ire_bucket;
24098 		ASSERT(irb != NULL);
24099 
24100 		multirt_send = B_TRUE;
24101 
24102 		/* Make sure we do not omit any multiroute ire. */
24103 		IRB_REFHOLD(irb);
24104 		for (first_ire = irb->irb_ire;
24105 		    first_ire != NULL;
24106 		    first_ire = first_ire->ire_next) {
24107 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24108 			    (first_ire->ire_addr == ire->ire_addr) &&
24109 			    !(first_ire->ire_marks &
24110 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24111 				break;
24112 		}
24113 
24114 		if (first_ire != NULL) {
24115 			if (first_ire != ire) {
24116 				IRE_REFHOLD(first_ire);
24117 				/*
24118 				 * Do not release the ire passed in
24119 				 * as the argument.
24120 				 */
24121 				ire = first_ire;
24122 			} else {
24123 				first_ire = NULL;
24124 			}
24125 		}
24126 		IRB_REFRELE(irb);
24127 
24128 		/*
24129 		 * Save the first ire; we will need to restore it
24130 		 * for the trailing frags.
24131 		 * We REFHOLD save_ire, as each iterated ire will be
24132 		 * REFRELEd.
24133 		 */
24134 		save_ire = ire;
24135 		IRE_REFHOLD(save_ire);
24136 	}
24137 
24138 	/*
24139 	 * First fragment emission loop.
24140 	 * In most cases, the emission loop below is entered only
24141 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24142 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24143 	 * bucket, and send the fragment through all crossed
24144 	 * RTF_MULTIRT routes.
24145 	 */
24146 	do {
24147 		if (ire->ire_flags & RTF_MULTIRT) {
24148 			/*
24149 			 * We are in a multiple send case, need to get
24150 			 * the next ire and make a copy of the packet.
24151 			 * ire1 holds here the next ire to process in the
24152 			 * bucket. If multirouting is expected,
24153 			 * any non-RTF_MULTIRT ire that has the
24154 			 * right destination address is ignored.
24155 			 *
24156 			 * We have to take into account the MTU of
24157 			 * each walked ire. max_frag is set by the
24158 			 * the caller and generally refers to
24159 			 * the primary ire entry. Here we ensure that
24160 			 * no route with a lower MTU will be used, as
24161 			 * fragments are carved once for all ires,
24162 			 * then replicated.
24163 			 */
24164 			ASSERT(irb != NULL);
24165 			IRB_REFHOLD(irb);
24166 			for (ire1 = ire->ire_next;
24167 			    ire1 != NULL;
24168 			    ire1 = ire1->ire_next) {
24169 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24170 					continue;
24171 				if (ire1->ire_addr != ire->ire_addr)
24172 					continue;
24173 				if (ire1->ire_marks &
24174 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24175 					continue;
24176 				/*
24177 				 * Ensure we do not exceed the MTU
24178 				 * of the next route.
24179 				 */
24180 				if (ire1->ire_max_frag < max_frag) {
24181 					ip_multirt_bad_mtu(ire1, max_frag);
24182 					continue;
24183 				}
24184 
24185 				/* Got one. */
24186 				IRE_REFHOLD(ire1);
24187 				break;
24188 			}
24189 			IRB_REFRELE(irb);
24190 
24191 			if (ire1 != NULL) {
24192 				next_mp = copyb(mp);
24193 				if ((next_mp == NULL) ||
24194 				    ((mp->b_cont != NULL) &&
24195 				    ((next_mp->b_cont =
24196 				    dupmsg(mp->b_cont)) == NULL))) {
24197 					freemsg(next_mp);
24198 					next_mp = NULL;
24199 					ire_refrele(ire1);
24200 					ire1 = NULL;
24201 				}
24202 			}
24203 
24204 			/* Last multiroute ire; don't loop anymore. */
24205 			if (ire1 == NULL) {
24206 				multirt_send = B_FALSE;
24207 			}
24208 		}
24209 
24210 		ll_hdr_len = 0;
24211 		LOCK_IRE_FP_MP(ire);
24212 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24213 		if (ll_hdr_mp != NULL) {
24214 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24215 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24216 		} else {
24217 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24218 		}
24219 
24220 		/* If there is a transmit header, get a copy for this frag. */
24221 		/*
24222 		 * TODO: should check db_ref before calling ip_carve_mp since
24223 		 * it might give us a dup.
24224 		 */
24225 		if (!ll_hdr_mp) {
24226 			/* No xmit header. */
24227 			xmit_mp = mp;
24228 
24229 		/* We have a link-layer header that can fit in our mblk. */
24230 		} else if (mp->b_datap->db_ref == 1 &&
24231 		    ll_hdr_len != 0 &&
24232 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24233 			/* M_DATA fastpath */
24234 			mp->b_rptr -= ll_hdr_len;
24235 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24236 			xmit_mp = mp;
24237 
24238 		/* Corner case if copyb has failed */
24239 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24240 			UNLOCK_IRE_FP_MP(ire);
24241 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24242 			freeb(hdr_mp);
24243 			freemsg(mp);
24244 			freemsg(mp_orig);
24245 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24246 			    "ip_wput_frag_end:(%S)",
24247 			    "discard");
24248 
24249 			if (multirt_send) {
24250 				ASSERT(ire1);
24251 				ASSERT(next_mp);
24252 
24253 				freemsg(next_mp);
24254 				ire_refrele(ire1);
24255 			}
24256 			if (save_ire != NULL)
24257 				IRE_REFRELE(save_ire);
24258 
24259 			if (first_ire != NULL)
24260 				ire_refrele(first_ire);
24261 			return;
24262 
24263 		/*
24264 		 * Case of res_mp OR the fastpath mp can't fit
24265 		 * in the mblk
24266 		 */
24267 		} else {
24268 			xmit_mp->b_cont = mp;
24269 			if (DB_CRED(mp) != NULL)
24270 				mblk_setcred(xmit_mp, DB_CRED(mp));
24271 			/*
24272 			 * Get priority marking, if any.
24273 			 * We propagate the CoS marking from the
24274 			 * original packet that went to QoS processing
24275 			 * in ip_wput_ire to the newly carved mp.
24276 			 */
24277 			if (DB_TYPE(xmit_mp) == M_DATA)
24278 				xmit_mp->b_band = mp->b_band;
24279 		}
24280 		UNLOCK_IRE_FP_MP(ire);
24281 
24282 		q = ire->ire_stq;
24283 		out_ill = (ill_t *)q->q_ptr;
24284 
24285 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24286 
24287 		DTRACE_PROBE4(ip4__physical__out__start,
24288 		    ill_t *, NULL, ill_t *, out_ill,
24289 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24290 
24291 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
24292 		    NULL, out_ill, ipha, xmit_mp, mp);
24293 
24294 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24295 
24296 		if (xmit_mp != NULL) {
24297 			putnext(q, xmit_mp);
24298 
24299 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24300 			UPDATE_MIB(out_ill->ill_ip_mib,
24301 			    ipIfStatsHCOutOctets, i1);
24302 
24303 			if (pkt_type != OB_PKT) {
24304 				/*
24305 				 * Update the packet count and MIB stats
24306 				 * of trailing RTF_MULTIRT ires.
24307 				 */
24308 				UPDATE_OB_PKT_COUNT(ire);
24309 				BUMP_MIB(out_ill->ill_ip_mib,
24310 				    ipIfStatsOutFragReqds);
24311 			}
24312 		}
24313 
24314 		if (multirt_send) {
24315 			/*
24316 			 * We are in a multiple send case; look for
24317 			 * the next ire and re-enter the loop.
24318 			 */
24319 			ASSERT(ire1);
24320 			ASSERT(next_mp);
24321 			/* REFRELE the current ire before looping */
24322 			ire_refrele(ire);
24323 			ire = ire1;
24324 			ire1 = NULL;
24325 			mp = next_mp;
24326 			next_mp = NULL;
24327 		}
24328 	} while (multirt_send);
24329 
24330 	ASSERT(ire1 == NULL);
24331 
24332 	/* Restore the original ire; we need it for the trailing frags */
24333 	if (save_ire != NULL) {
24334 		/* REFRELE the last iterated ire */
24335 		ire_refrele(ire);
24336 		/* save_ire has been REFHOLDed */
24337 		ire = save_ire;
24338 		save_ire = NULL;
24339 		q = ire->ire_stq;
24340 	}
24341 
24342 	if (pkt_type == OB_PKT) {
24343 		UPDATE_OB_PKT_COUNT(ire);
24344 	} else {
24345 		out_ill = (ill_t *)q->q_ptr;
24346 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24347 		UPDATE_IB_PKT_COUNT(ire);
24348 	}
24349 
24350 	/* Advance the offset to the second frag starting point. */
24351 	offset += len;
24352 	/*
24353 	 * Update hdr_len from the copied header - there might be less options
24354 	 * in the later fragments.
24355 	 */
24356 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24357 	/* Loop until done. */
24358 	for (;;) {
24359 		uint16_t	offset_and_flags;
24360 		uint16_t	ip_len;
24361 
24362 		if (ip_data_end - offset > len) {
24363 			/*
24364 			 * Carve off the appropriate amount from the original
24365 			 * datagram.
24366 			 */
24367 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24368 				mp = NULL;
24369 				break;
24370 			}
24371 			/*
24372 			 * More frags after this one.  Get another copy
24373 			 * of the header.
24374 			 */
24375 			if (carve_mp->b_datap->db_ref == 1 &&
24376 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24377 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24378 				/* Inline IP header */
24379 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24380 				    hdr_mp->b_rptr;
24381 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24382 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24383 				mp = carve_mp;
24384 			} else {
24385 				if (!(mp = copyb(hdr_mp))) {
24386 					freemsg(carve_mp);
24387 					break;
24388 				}
24389 				/* Get priority marking, if any. */
24390 				mp->b_band = carve_mp->b_band;
24391 				mp->b_cont = carve_mp;
24392 			}
24393 			ipha = (ipha_t *)mp->b_rptr;
24394 			offset_and_flags = IPH_MF;
24395 		} else {
24396 			/*
24397 			 * Last frag.  Consume the header. Set len to
24398 			 * the length of this last piece.
24399 			 */
24400 			len = ip_data_end - offset;
24401 
24402 			/*
24403 			 * Carve off the appropriate amount from the original
24404 			 * datagram.
24405 			 */
24406 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24407 				mp = NULL;
24408 				break;
24409 			}
24410 			if (carve_mp->b_datap->db_ref == 1 &&
24411 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24412 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24413 				/* Inline IP header */
24414 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24415 				    hdr_mp->b_rptr;
24416 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24417 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24418 				mp = carve_mp;
24419 				freeb(hdr_mp);
24420 				hdr_mp = mp;
24421 			} else {
24422 				mp = hdr_mp;
24423 				/* Get priority marking, if any. */
24424 				mp->b_band = carve_mp->b_band;
24425 				mp->b_cont = carve_mp;
24426 			}
24427 			ipha = (ipha_t *)mp->b_rptr;
24428 			/* A frag of a frag might have IPH_MF non-zero */
24429 			offset_and_flags =
24430 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24431 			    IPH_MF;
24432 		}
24433 		offset_and_flags |= (uint16_t)(offset >> 3);
24434 		offset_and_flags |= (uint16_t)frag_flag;
24435 		/* Store the offset and flags in the IP header. */
24436 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24437 
24438 		/* Store the length in the IP header. */
24439 		ip_len = (uint16_t)(len + hdr_len);
24440 		ipha->ipha_length = htons(ip_len);
24441 
24442 		/*
24443 		 * Set the IP header checksum.	Note that mp is just
24444 		 * the header, so this is easy to pass to ip_csum.
24445 		 */
24446 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24447 
24448 		/* Attach a transmit header, if any, and ship it. */
24449 		if (pkt_type == OB_PKT) {
24450 			UPDATE_OB_PKT_COUNT(ire);
24451 		} else {
24452 			out_ill = (ill_t *)q->q_ptr;
24453 			BUMP_MIB(out_ill->ill_ip_mib,
24454 			    ipIfStatsHCOutForwDatagrams);
24455 			UPDATE_IB_PKT_COUNT(ire);
24456 		}
24457 
24458 		if (ire->ire_flags & RTF_MULTIRT) {
24459 			irb = ire->ire_bucket;
24460 			ASSERT(irb != NULL);
24461 
24462 			multirt_send = B_TRUE;
24463 
24464 			/*
24465 			 * Save the original ire; we will need to restore it
24466 			 * for the tailing frags.
24467 			 */
24468 			save_ire = ire;
24469 			IRE_REFHOLD(save_ire);
24470 		}
24471 		/*
24472 		 * Emission loop for this fragment, similar
24473 		 * to what is done for the first fragment.
24474 		 */
24475 		do {
24476 			if (multirt_send) {
24477 				/*
24478 				 * We are in a multiple send case, need to get
24479 				 * the next ire and make a copy of the packet.
24480 				 */
24481 				ASSERT(irb != NULL);
24482 				IRB_REFHOLD(irb);
24483 				for (ire1 = ire->ire_next;
24484 				    ire1 != NULL;
24485 				    ire1 = ire1->ire_next) {
24486 					if (!(ire1->ire_flags & RTF_MULTIRT))
24487 						continue;
24488 					if (ire1->ire_addr != ire->ire_addr)
24489 						continue;
24490 					if (ire1->ire_marks &
24491 					    (IRE_MARK_CONDEMNED|
24492 						IRE_MARK_HIDDEN))
24493 						continue;
24494 					/*
24495 					 * Ensure we do not exceed the MTU
24496 					 * of the next route.
24497 					 */
24498 					if (ire1->ire_max_frag < max_frag) {
24499 						ip_multirt_bad_mtu(ire1,
24500 						    max_frag);
24501 						continue;
24502 					}
24503 
24504 					/* Got one. */
24505 					IRE_REFHOLD(ire1);
24506 					break;
24507 				}
24508 				IRB_REFRELE(irb);
24509 
24510 				if (ire1 != NULL) {
24511 					next_mp = copyb(mp);
24512 					if ((next_mp == NULL) ||
24513 					    ((mp->b_cont != NULL) &&
24514 					    ((next_mp->b_cont =
24515 					    dupmsg(mp->b_cont)) == NULL))) {
24516 						freemsg(next_mp);
24517 						next_mp = NULL;
24518 						ire_refrele(ire1);
24519 						ire1 = NULL;
24520 					}
24521 				}
24522 
24523 				/* Last multiroute ire; don't loop anymore. */
24524 				if (ire1 == NULL) {
24525 					multirt_send = B_FALSE;
24526 				}
24527 			}
24528 
24529 			/* Update transmit header */
24530 			ll_hdr_len = 0;
24531 			LOCK_IRE_FP_MP(ire);
24532 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24533 			if (ll_hdr_mp != NULL) {
24534 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24535 				ll_hdr_len = MBLKL(ll_hdr_mp);
24536 			} else {
24537 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24538 			}
24539 
24540 			if (!ll_hdr_mp) {
24541 				xmit_mp = mp;
24542 
24543 			/*
24544 			 * We have link-layer header that can fit in
24545 			 * our mblk.
24546 			 */
24547 			} else if (mp->b_datap->db_ref == 1 &&
24548 			    ll_hdr_len != 0 &&
24549 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24550 				/* M_DATA fastpath */
24551 				mp->b_rptr -= ll_hdr_len;
24552 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24553 				    ll_hdr_len);
24554 				xmit_mp = mp;
24555 
24556 			/*
24557 			 * Case of res_mp OR the fastpath mp can't fit
24558 			 * in the mblk
24559 			 */
24560 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24561 				xmit_mp->b_cont = mp;
24562 				if (DB_CRED(mp) != NULL)
24563 					mblk_setcred(xmit_mp, DB_CRED(mp));
24564 				/* Get priority marking, if any. */
24565 				if (DB_TYPE(xmit_mp) == M_DATA)
24566 					xmit_mp->b_band = mp->b_band;
24567 
24568 			/* Corner case if copyb failed */
24569 			} else {
24570 				/*
24571 				 * Exit both the replication and
24572 				 * fragmentation loops.
24573 				 */
24574 				UNLOCK_IRE_FP_MP(ire);
24575 				goto drop_pkt;
24576 			}
24577 			UNLOCK_IRE_FP_MP(ire);
24578 
24579 			mp1 = mp;
24580 			out_ill = (ill_t *)q->q_ptr;
24581 
24582 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24583 
24584 			DTRACE_PROBE4(ip4__physical__out__start,
24585 			    ill_t *, NULL, ill_t *, out_ill,
24586 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24587 
24588 			FW_HOOKS(ip4_physical_out_event,
24589 			    ipv4firewall_physical_out,
24590 			    NULL, out_ill, ipha, xmit_mp, mp);
24591 
24592 			DTRACE_PROBE1(ip4__physical__out__end,
24593 			    mblk_t *, xmit_mp);
24594 
24595 			if (mp != mp1 && hdr_mp == mp1)
24596 				hdr_mp = mp;
24597 			if (mp != mp1 && mp_orig == mp1)
24598 				mp_orig = mp;
24599 
24600 			if (xmit_mp != NULL) {
24601 				putnext(q, xmit_mp);
24602 
24603 				BUMP_MIB(out_ill->ill_ip_mib,
24604 				    ipIfStatsHCOutTransmits);
24605 				UPDATE_MIB(out_ill->ill_ip_mib,
24606 				    ipIfStatsHCOutOctets, ip_len);
24607 
24608 				if (pkt_type != OB_PKT) {
24609 					/*
24610 					 * Update the packet count of trailing
24611 					 * RTF_MULTIRT ires.
24612 					 */
24613 					UPDATE_OB_PKT_COUNT(ire);
24614 				}
24615 			}
24616 
24617 			/* All done if we just consumed the hdr_mp. */
24618 			if (mp == hdr_mp) {
24619 				last_frag = B_TRUE;
24620 				BUMP_MIB(out_ill->ill_ip_mib,
24621 				    ipIfStatsOutFragOKs);
24622 			}
24623 
24624 			if (multirt_send) {
24625 				/*
24626 				 * We are in a multiple send case; look for
24627 				 * the next ire and re-enter the loop.
24628 				 */
24629 				ASSERT(ire1);
24630 				ASSERT(next_mp);
24631 				/* REFRELE the current ire before looping */
24632 				ire_refrele(ire);
24633 				ire = ire1;
24634 				ire1 = NULL;
24635 				q = ire->ire_stq;
24636 				mp = next_mp;
24637 				next_mp = NULL;
24638 			}
24639 		} while (multirt_send);
24640 		/*
24641 		 * Restore the original ire; we need it for the
24642 		 * trailing frags
24643 		 */
24644 		if (save_ire != NULL) {
24645 			ASSERT(ire1 == NULL);
24646 			/* REFRELE the last iterated ire */
24647 			ire_refrele(ire);
24648 			/* save_ire has been REFHOLDed */
24649 			ire = save_ire;
24650 			q = ire->ire_stq;
24651 			save_ire = NULL;
24652 		}
24653 
24654 		if (last_frag) {
24655 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24656 			    "ip_wput_frag_end:(%S)",
24657 			    "consumed hdr_mp");
24658 
24659 			if (first_ire != NULL)
24660 				ire_refrele(first_ire);
24661 			return;
24662 		}
24663 		/* Otherwise, advance and loop. */
24664 		offset += len;
24665 	}
24666 
24667 drop_pkt:
24668 	/* Clean up following allocation failure. */
24669 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24670 	freemsg(mp);
24671 	if (mp != hdr_mp)
24672 		freeb(hdr_mp);
24673 	if (mp != mp_orig)
24674 		freemsg(mp_orig);
24675 
24676 	if (save_ire != NULL)
24677 		IRE_REFRELE(save_ire);
24678 	if (first_ire != NULL)
24679 		ire_refrele(first_ire);
24680 
24681 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24682 	    "ip_wput_frag_end:(%S)",
24683 	    "end--alloc failure");
24684 }
24685 
24686 /*
24687  * Copy the header plus those options which have the copy bit set
24688  */
24689 static mblk_t *
24690 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
24691 {
24692 	mblk_t	*mp;
24693 	uchar_t	*up;
24694 
24695 	/*
24696 	 * Quick check if we need to look for options without the copy bit
24697 	 * set
24698 	 */
24699 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
24700 	if (!mp)
24701 		return (mp);
24702 	mp->b_rptr += ip_wroff_extra;
24703 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24704 		bcopy(rptr, mp->b_rptr, hdr_len);
24705 		mp->b_wptr += hdr_len + ip_wroff_extra;
24706 		return (mp);
24707 	}
24708 	up  = mp->b_rptr;
24709 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24710 	up += IP_SIMPLE_HDR_LENGTH;
24711 	rptr += IP_SIMPLE_HDR_LENGTH;
24712 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24713 	while (hdr_len > 0) {
24714 		uint32_t optval;
24715 		uint32_t optlen;
24716 
24717 		optval = *rptr;
24718 		if (optval == IPOPT_EOL)
24719 			break;
24720 		if (optval == IPOPT_NOP)
24721 			optlen = 1;
24722 		else
24723 			optlen = rptr[1];
24724 		if (optval & IPOPT_COPY) {
24725 			bcopy(rptr, up, optlen);
24726 			up += optlen;
24727 		}
24728 		rptr += optlen;
24729 		hdr_len -= optlen;
24730 	}
24731 	/*
24732 	 * Make sure that we drop an even number of words by filling
24733 	 * with EOL to the next word boundary.
24734 	 */
24735 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24736 	    hdr_len & 0x3; hdr_len++)
24737 		*up++ = IPOPT_EOL;
24738 	mp->b_wptr = up;
24739 	/* Update header length */
24740 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24741 	return (mp);
24742 }
24743 
24744 /*
24745  * Delivery to local recipients including fanout to multiple recipients.
24746  * Does not do checksumming of UDP/TCP.
24747  * Note: q should be the read side queue for either the ill or conn.
24748  * Note: rq should be the read side q for the lower (ill) stream.
24749  * We don't send packets to IPPF processing, thus the last argument
24750  * to all the fanout calls are B_FALSE.
24751  */
24752 void
24753 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24754     int fanout_flags, zoneid_t zoneid)
24755 {
24756 	uint32_t	protocol;
24757 	mblk_t		*first_mp;
24758 	boolean_t	mctl_present;
24759 	int		ire_type;
24760 #define	rptr	((uchar_t *)ipha)
24761 
24762 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24763 	    "ip_wput_local_start: q %p", q);
24764 
24765 	if (ire != NULL) {
24766 		ire_type = ire->ire_type;
24767 	} else {
24768 		/*
24769 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24770 		 * packet is not multicast, we can't tell the ire type.
24771 		 */
24772 		ASSERT(CLASSD(ipha->ipha_dst));
24773 		ire_type = IRE_BROADCAST;
24774 	}
24775 
24776 	first_mp = mp;
24777 	if (first_mp->b_datap->db_type == M_CTL) {
24778 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24779 		if (!io->ipsec_out_secure) {
24780 			/*
24781 			 * This ipsec_out_t was allocated in ip_wput
24782 			 * for multicast packets to store the ill_index.
24783 			 * As this is being delivered locally, we don't
24784 			 * need this anymore.
24785 			 */
24786 			mp = first_mp->b_cont;
24787 			freeb(first_mp);
24788 			first_mp = mp;
24789 			mctl_present = B_FALSE;
24790 		} else {
24791 			/*
24792 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24793 			 * security properties for the looped-back packet.
24794 			 */
24795 			mctl_present = B_TRUE;
24796 			mp = first_mp->b_cont;
24797 			ASSERT(mp != NULL);
24798 			ipsec_out_to_in(first_mp);
24799 		}
24800 	} else {
24801 		mctl_present = B_FALSE;
24802 	}
24803 
24804 	DTRACE_PROBE4(ip4__loopback__in__start,
24805 	    ill_t *, ill, ill_t *, NULL,
24806 	    ipha_t *, ipha, mblk_t *, first_mp);
24807 
24808 	FW_HOOKS(ip4_loopback_in_event, ipv4firewall_loopback_in,
24809 	    ill, NULL, ipha, first_mp, mp);
24810 
24811 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24812 
24813 	if (first_mp == NULL)
24814 		return;
24815 
24816 	loopback_packets++;
24817 
24818 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24819 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24820 	if (!IS_SIMPLE_IPH(ipha)) {
24821 		ip_wput_local_options(ipha);
24822 	}
24823 
24824 	protocol = ipha->ipha_protocol;
24825 	switch (protocol) {
24826 	case IPPROTO_ICMP: {
24827 		ire_t		*ire_zone;
24828 		ilm_t		*ilm;
24829 		mblk_t		*mp1;
24830 		zoneid_t	last_zoneid;
24831 
24832 		if (CLASSD(ipha->ipha_dst) &&
24833 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
24834 			ASSERT(ire_type == IRE_BROADCAST);
24835 			/*
24836 			 * In the multicast case, applications may have joined
24837 			 * the group from different zones, so we need to deliver
24838 			 * the packet to each of them. Loop through the
24839 			 * multicast memberships structures (ilm) on the receive
24840 			 * ill and send a copy of the packet up each matching
24841 			 * one. However, we don't do this for multicasts sent on
24842 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24843 			 * they must stay in the sender's zone.
24844 			 *
24845 			 * ilm_add_v6() ensures that ilms in the same zone are
24846 			 * contiguous in the ill_ilm list. We use this property
24847 			 * to avoid sending duplicates needed when two
24848 			 * applications in the same zone join the same group on
24849 			 * different logical interfaces: we ignore the ilm if
24850 			 * it's zoneid is the same as the last matching one.
24851 			 * In addition, the sending of the packet for
24852 			 * ire_zoneid is delayed until all of the other ilms
24853 			 * have been exhausted.
24854 			 */
24855 			last_zoneid = -1;
24856 			ILM_WALKER_HOLD(ill);
24857 			for (ilm = ill->ill_ilm; ilm != NULL;
24858 			    ilm = ilm->ilm_next) {
24859 				if ((ilm->ilm_flags & ILM_DELETED) ||
24860 				    ipha->ipha_dst != ilm->ilm_addr ||
24861 				    ilm->ilm_zoneid == last_zoneid ||
24862 				    ilm->ilm_zoneid == zoneid ||
24863 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24864 					continue;
24865 				mp1 = ip_copymsg(first_mp);
24866 				if (mp1 == NULL)
24867 					continue;
24868 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24869 				    mctl_present, B_FALSE, ill,
24870 				    ilm->ilm_zoneid);
24871 				last_zoneid = ilm->ilm_zoneid;
24872 			}
24873 			ILM_WALKER_RELE(ill);
24874 			/*
24875 			 * Loopback case: the sending endpoint has
24876 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24877 			 * dispatch the multicast packet to the sending zone.
24878 			 */
24879 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24880 				freemsg(first_mp);
24881 				return;
24882 			}
24883 		} else if (ire_type == IRE_BROADCAST) {
24884 			/*
24885 			 * In the broadcast case, there may be many zones
24886 			 * which need a copy of the packet delivered to them.
24887 			 * There is one IRE_BROADCAST per broadcast address
24888 			 * and per zone; we walk those using a helper function.
24889 			 * In addition, the sending of the packet for zoneid is
24890 			 * delayed until all of the other ires have been
24891 			 * processed.
24892 			 */
24893 			IRB_REFHOLD(ire->ire_bucket);
24894 			ire_zone = NULL;
24895 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24896 			    ire)) != NULL) {
24897 				mp1 = ip_copymsg(first_mp);
24898 				if (mp1 == NULL)
24899 					continue;
24900 
24901 				UPDATE_IB_PKT_COUNT(ire_zone);
24902 				ire_zone->ire_last_used_time = lbolt;
24903 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24904 				    mctl_present, B_FALSE, ill,
24905 				    ire_zone->ire_zoneid);
24906 			}
24907 			IRB_REFRELE(ire->ire_bucket);
24908 		}
24909 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
24910 		    0, mctl_present, B_FALSE, ill, zoneid);
24911 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24912 		    "ip_wput_local_end: q %p (%S)",
24913 		    q, "icmp");
24914 		return;
24915 	}
24916 	case IPPROTO_IGMP:
24917 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
24918 			/* Bad packet - discarded by igmp_input */
24919 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24920 			    "ip_wput_local_end: q %p (%S)",
24921 			    q, "igmp_input--bad packet");
24922 			if (mctl_present)
24923 				freeb(first_mp);
24924 			return;
24925 		}
24926 		/*
24927 		 * igmp_input() may have returned the pulled up message.
24928 		 * So first_mp and ipha need to be reinitialized.
24929 		 */
24930 		ipha = (ipha_t *)mp->b_rptr;
24931 		if (mctl_present)
24932 			first_mp->b_cont = mp;
24933 		else
24934 			first_mp = mp;
24935 		/* deliver to local raw users */
24936 		break;
24937 	case IPPROTO_ENCAP:
24938 		/*
24939 		 * This case is covered by either ip_fanout_proto, or by
24940 		 * the above security processing for self-tunneled packets.
24941 		 */
24942 		break;
24943 	case IPPROTO_UDP: {
24944 		uint16_t	*up;
24945 		uint32_t	ports;
24946 
24947 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
24948 		    UDP_PORTS_OFFSET);
24949 		/* Force a 'valid' checksum. */
24950 		up[3] = 0;
24951 
24952 		ports = *(uint32_t *)up;
24953 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24954 		    (ire_type == IRE_BROADCAST),
24955 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24956 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
24957 		    ill, zoneid);
24958 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24959 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24960 		return;
24961 	}
24962 	case IPPROTO_TCP: {
24963 
24964 		/*
24965 		 * For TCP, discard broadcast packets.
24966 		 */
24967 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24968 			freemsg(first_mp);
24969 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
24970 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24971 			return;
24972 		}
24973 
24974 		if (mp->b_datap->db_type == M_DATA) {
24975 			/*
24976 			 * M_DATA mblk, so init mblk (chain) for no struio().
24977 			 */
24978 			mblk_t	*mp1 = mp;
24979 
24980 			do
24981 				mp1->b_datap->db_struioflag = 0;
24982 			while ((mp1 = mp1->b_cont) != NULL);
24983 		}
24984 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24985 		    <= mp->b_wptr);
24986 		ip_fanout_tcp(q, first_mp, ill, ipha,
24987 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24988 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
24989 		    mctl_present, B_FALSE, zoneid);
24990 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24991 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24992 		return;
24993 	}
24994 	case IPPROTO_SCTP:
24995 	{
24996 		uint32_t	ports;
24997 
24998 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24999 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25000 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25001 		    IP_FF_IPINFO,
25002 		    mctl_present, B_FALSE, 0, zoneid);
25003 		return;
25004 	}
25005 
25006 	default:
25007 		break;
25008 	}
25009 	/*
25010 	 * Find a client for some other protocol.  We give
25011 	 * copies to multiple clients, if more than one is
25012 	 * bound.
25013 	 */
25014 	ip_fanout_proto(q, first_mp, ill, ipha,
25015 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25016 	    mctl_present, B_FALSE, ill, zoneid);
25017 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25018 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25019 #undef	rptr
25020 }
25021 
25022 /*
25023  * Update any source route, record route, or timestamp options.
25024  * Check that we are at end of strict source route.
25025  * The options have been sanity checked by ip_wput_options().
25026  */
25027 static void
25028 ip_wput_local_options(ipha_t *ipha)
25029 {
25030 	ipoptp_t	opts;
25031 	uchar_t		*opt;
25032 	uint8_t		optval;
25033 	uint8_t		optlen;
25034 	ipaddr_t	dst;
25035 	uint32_t	ts;
25036 	ire_t		*ire;
25037 	timestruc_t	now;
25038 
25039 	ip2dbg(("ip_wput_local_options\n"));
25040 	for (optval = ipoptp_first(&opts, ipha);
25041 	    optval != IPOPT_EOL;
25042 	    optval = ipoptp_next(&opts)) {
25043 		opt = opts.ipoptp_cur;
25044 		optlen = opts.ipoptp_len;
25045 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25046 		switch (optval) {
25047 			uint32_t off;
25048 		case IPOPT_SSRR:
25049 		case IPOPT_LSRR:
25050 			off = opt[IPOPT_OFFSET];
25051 			off--;
25052 			if (optlen < IP_ADDR_LEN ||
25053 			    off > optlen - IP_ADDR_LEN) {
25054 				/* End of source route */
25055 				break;
25056 			}
25057 			/*
25058 			 * This will only happen if two consecutive entries
25059 			 * in the source route contains our address or if
25060 			 * it is a packet with a loose source route which
25061 			 * reaches us before consuming the whole source route
25062 			 */
25063 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25064 			if (optval == IPOPT_SSRR) {
25065 				return;
25066 			}
25067 			/*
25068 			 * Hack: instead of dropping the packet truncate the
25069 			 * source route to what has been used by filling the
25070 			 * rest with IPOPT_NOP.
25071 			 */
25072 			opt[IPOPT_OLEN] = (uint8_t)off;
25073 			while (off < optlen) {
25074 				opt[off++] = IPOPT_NOP;
25075 			}
25076 			break;
25077 		case IPOPT_RR:
25078 			off = opt[IPOPT_OFFSET];
25079 			off--;
25080 			if (optlen < IP_ADDR_LEN ||
25081 			    off > optlen - IP_ADDR_LEN) {
25082 				/* No more room - ignore */
25083 				ip1dbg((
25084 				    "ip_wput_forward_options: end of RR\n"));
25085 				break;
25086 			}
25087 			dst = htonl(INADDR_LOOPBACK);
25088 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25089 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25090 			break;
25091 		case IPOPT_TS:
25092 			/* Insert timestamp if there is romm */
25093 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25094 			case IPOPT_TS_TSONLY:
25095 				off = IPOPT_TS_TIMELEN;
25096 				break;
25097 			case IPOPT_TS_PRESPEC:
25098 			case IPOPT_TS_PRESPEC_RFC791:
25099 				/* Verify that the address matched */
25100 				off = opt[IPOPT_OFFSET] - 1;
25101 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25102 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25103 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
25104 				if (ire == NULL) {
25105 					/* Not for us */
25106 					break;
25107 				}
25108 				ire_refrele(ire);
25109 				/* FALLTHRU */
25110 			case IPOPT_TS_TSANDADDR:
25111 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25112 				break;
25113 			default:
25114 				/*
25115 				 * ip_*put_options should have already
25116 				 * dropped this packet.
25117 				 */
25118 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25119 				    "unknown IT - bug in ip_wput_options?\n");
25120 				return;	/* Keep "lint" happy */
25121 			}
25122 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25123 				/* Increase overflow counter */
25124 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25125 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25126 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25127 				    (off << 4);
25128 				break;
25129 			}
25130 			off = opt[IPOPT_OFFSET] - 1;
25131 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25132 			case IPOPT_TS_PRESPEC:
25133 			case IPOPT_TS_PRESPEC_RFC791:
25134 			case IPOPT_TS_TSANDADDR:
25135 				dst = htonl(INADDR_LOOPBACK);
25136 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25137 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25138 				/* FALLTHRU */
25139 			case IPOPT_TS_TSONLY:
25140 				off = opt[IPOPT_OFFSET] - 1;
25141 				/* Compute # of milliseconds since midnight */
25142 				gethrestime(&now);
25143 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25144 				    now.tv_nsec / (NANOSEC / MILLISEC);
25145 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25146 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25147 				break;
25148 			}
25149 			break;
25150 		}
25151 	}
25152 }
25153 
25154 /*
25155  * Send out a multicast packet on interface ipif.
25156  * The sender does not have an conn.
25157  * Caller verifies that this isn't a PHYI_LOOPBACK.
25158  */
25159 void
25160 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25161 {
25162 	ipha_t	*ipha;
25163 	ire_t	*ire;
25164 	ipaddr_t	dst;
25165 	mblk_t		*first_mp;
25166 
25167 	/* igmp_sendpkt always allocates a ipsec_out_t */
25168 	ASSERT(mp->b_datap->db_type == M_CTL);
25169 	ASSERT(!ipif->ipif_isv6);
25170 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
25171 
25172 	first_mp = mp;
25173 	mp = first_mp->b_cont;
25174 	ASSERT(mp->b_datap->db_type == M_DATA);
25175 	ipha = (ipha_t *)mp->b_rptr;
25176 
25177 	/*
25178 	 * Find an IRE which matches the destination and the outgoing
25179 	 * queue (i.e. the outgoing interface.)
25180 	 */
25181 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25182 		dst = ipif->ipif_pp_dst_addr;
25183 	else
25184 		dst = ipha->ipha_dst;
25185 	/*
25186 	 * The source address has already been initialized by the
25187 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25188 	 * be sufficient rather than MATCH_IRE_IPIF.
25189 	 *
25190 	 * This function is used for sending IGMP packets. We need
25191 	 * to make sure that we send the packet out of the interface
25192 	 * (ipif->ipif_ill) where we joined the group. This is to
25193 	 * prevent from switches doing IGMP snooping to send us multicast
25194 	 * packets for a given group on the interface we have joined.
25195 	 * If we can't find an ire, igmp_sendpkt has already initialized
25196 	 * ipsec_out_attach_if so that this will not be load spread in
25197 	 * ip_newroute_ipif.
25198 	 */
25199 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25200 	    MATCH_IRE_ILL);
25201 	if (!ire) {
25202 		/*
25203 		 * Mark this packet to make it be delivered to
25204 		 * ip_wput_ire after the new ire has been
25205 		 * created.
25206 		 */
25207 		mp->b_prev = NULL;
25208 		mp->b_next = NULL;
25209 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25210 		    zoneid, &zero_info);
25211 		return;
25212 	}
25213 
25214 	/*
25215 	 * Honor the RTF_SETSRC flag; this is the only case
25216 	 * where we force this addr whatever the current src addr is,
25217 	 * because this address is set by igmp_sendpkt(), and
25218 	 * cannot be specified by any user.
25219 	 */
25220 	if (ire->ire_flags & RTF_SETSRC) {
25221 		ipha->ipha_src = ire->ire_src_addr;
25222 	}
25223 
25224 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25225 }
25226 
25227 /*
25228  * NOTE : This function does not ire_refrele the ire argument passed in.
25229  *
25230  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25231  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25232  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25233  * the ire_lock to access the nce_fp_mp in this case.
25234  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25235  * prepending a fastpath message IPQoS processing must precede it, we also set
25236  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25237  * (IPQoS might have set the b_band for CoS marking).
25238  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25239  * must follow it so that IPQoS can mark the dl_priority field for CoS
25240  * marking, if needed.
25241  */
25242 static mblk_t *
25243 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25244 {
25245 	uint_t	hlen;
25246 	ipha_t *ipha;
25247 	mblk_t *mp1;
25248 	boolean_t qos_done = B_FALSE;
25249 	uchar_t	*ll_hdr;
25250 
25251 #define	rptr	((uchar_t *)ipha)
25252 
25253 	ipha = (ipha_t *)mp->b_rptr;
25254 	hlen = 0;
25255 	LOCK_IRE_FP_MP(ire);
25256 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25257 		ASSERT(DB_TYPE(mp1) == M_DATA);
25258 		/* Initiate IPPF processing */
25259 		if ((proc != 0) && IPP_ENABLED(proc)) {
25260 			UNLOCK_IRE_FP_MP(ire);
25261 			ip_process(proc, &mp, ill_index);
25262 			if (mp == NULL)
25263 				return (NULL);
25264 
25265 			ipha = (ipha_t *)mp->b_rptr;
25266 			LOCK_IRE_FP_MP(ire);
25267 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25268 				qos_done = B_TRUE;
25269 				goto no_fp_mp;
25270 			}
25271 			ASSERT(DB_TYPE(mp1) == M_DATA);
25272 		}
25273 		hlen = MBLKL(mp1);
25274 		/*
25275 		 * Check if we have enough room to prepend fastpath
25276 		 * header
25277 		 */
25278 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25279 			ll_hdr = rptr - hlen;
25280 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25281 			/*
25282 			 * Set the b_rptr to the start of the link layer
25283 			 * header
25284 			 */
25285 			mp->b_rptr = ll_hdr;
25286 			mp1 = mp;
25287 		} else {
25288 			mp1 = copyb(mp1);
25289 			if (mp1 == NULL)
25290 				goto unlock_err;
25291 			mp1->b_band = mp->b_band;
25292 			mp1->b_cont = mp;
25293 			/*
25294 			 * certain system generated traffic may not
25295 			 * have cred/label in ip header block. This
25296 			 * is true even for a labeled system. But for
25297 			 * labeled traffic, inherit the label in the
25298 			 * new header.
25299 			 */
25300 			if (DB_CRED(mp) != NULL)
25301 				mblk_setcred(mp1, DB_CRED(mp));
25302 			/*
25303 			 * XXX disable ICK_VALID and compute checksum
25304 			 * here; can happen if nce_fp_mp changes and
25305 			 * it can't be copied now due to insufficient
25306 			 * space. (unlikely, fp mp can change, but it
25307 			 * does not increase in length)
25308 			 */
25309 		}
25310 		UNLOCK_IRE_FP_MP(ire);
25311 	} else {
25312 no_fp_mp:
25313 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25314 		if (mp1 == NULL) {
25315 unlock_err:
25316 			UNLOCK_IRE_FP_MP(ire);
25317 			freemsg(mp);
25318 			return (NULL);
25319 		}
25320 		UNLOCK_IRE_FP_MP(ire);
25321 		mp1->b_cont = mp;
25322 		/*
25323 		 * certain system generated traffic may not
25324 		 * have cred/label in ip header block. This
25325 		 * is true even for a labeled system. But for
25326 		 * labeled traffic, inherit the label in the
25327 		 * new header.
25328 		 */
25329 		if (DB_CRED(mp) != NULL)
25330 			mblk_setcred(mp1, DB_CRED(mp));
25331 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
25332 			ip_process(proc, &mp1, ill_index);
25333 			if (mp1 == NULL)
25334 				return (NULL);
25335 		}
25336 	}
25337 	return (mp1);
25338 #undef rptr
25339 }
25340 
25341 /*
25342  * Finish the outbound IPsec processing for an IPv6 packet. This function
25343  * is called from ipsec_out_process() if the IPsec packet was processed
25344  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25345  * asynchronously.
25346  */
25347 void
25348 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25349     ire_t *ire_arg)
25350 {
25351 	in6_addr_t *v6dstp;
25352 	ire_t *ire;
25353 	mblk_t *mp;
25354 	ip6_t *ip6h1;
25355 	uint_t	ill_index;
25356 	ipsec_out_t *io;
25357 	boolean_t attach_if, hwaccel;
25358 	uint32_t flags = IP6_NO_IPPOLICY;
25359 	int match_flags;
25360 	zoneid_t zoneid;
25361 	boolean_t ill_need_rele = B_FALSE;
25362 	boolean_t ire_need_rele = B_FALSE;
25363 
25364 	mp = ipsec_mp->b_cont;
25365 	ip6h1 = (ip6_t *)mp->b_rptr;
25366 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25367 	ill_index = io->ipsec_out_ill_index;
25368 	if (io->ipsec_out_reachable) {
25369 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25370 	}
25371 	attach_if = io->ipsec_out_attach_if;
25372 	hwaccel = io->ipsec_out_accelerated;
25373 	zoneid = io->ipsec_out_zoneid;
25374 	ASSERT(zoneid != ALL_ZONES);
25375 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25376 	/* Multicast addresses should have non-zero ill_index. */
25377 	v6dstp = &ip6h->ip6_dst;
25378 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25379 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25380 	ASSERT(!attach_if || ill_index != 0);
25381 	if (ill_index != 0) {
25382 		if (ill == NULL) {
25383 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25384 			    B_TRUE);
25385 
25386 			/* Failure case frees things for us. */
25387 			if (ill == NULL)
25388 				return;
25389 
25390 			ill_need_rele = B_TRUE;
25391 		}
25392 		/*
25393 		 * If this packet needs to go out on a particular interface
25394 		 * honor it.
25395 		 */
25396 		if (attach_if) {
25397 			match_flags = MATCH_IRE_ILL;
25398 
25399 			/*
25400 			 * Check if we need an ire that will not be
25401 			 * looked up by anybody else i.e. HIDDEN.
25402 			 */
25403 			if (ill_is_probeonly(ill)) {
25404 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25405 			}
25406 		}
25407 	}
25408 	ASSERT(mp != NULL);
25409 
25410 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25411 		boolean_t unspec_src;
25412 		ipif_t	*ipif;
25413 
25414 		/*
25415 		 * Use the ill_index to get the right ill.
25416 		 */
25417 		unspec_src = io->ipsec_out_unspec_src;
25418 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25419 		if (ipif == NULL) {
25420 			if (ill_need_rele)
25421 				ill_refrele(ill);
25422 			freemsg(ipsec_mp);
25423 			return;
25424 		}
25425 
25426 		if (ire_arg != NULL) {
25427 			ire = ire_arg;
25428 		} else {
25429 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25430 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25431 			ire_need_rele = B_TRUE;
25432 		}
25433 		if (ire != NULL) {
25434 			ipif_refrele(ipif);
25435 			/*
25436 			 * XXX Do the multicast forwarding now, as the IPSEC
25437 			 * processing has been done.
25438 			 */
25439 			goto send;
25440 		}
25441 
25442 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25443 		mp->b_prev = NULL;
25444 		mp->b_next = NULL;
25445 
25446 		/*
25447 		 * If the IPsec packet was processed asynchronously,
25448 		 * drop it now.
25449 		 */
25450 		if (q == NULL) {
25451 			if (ill_need_rele)
25452 				ill_refrele(ill);
25453 			freemsg(ipsec_mp);
25454 			return;
25455 		}
25456 
25457 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25458 		    unspec_src, zoneid);
25459 		ipif_refrele(ipif);
25460 	} else {
25461 		if (attach_if) {
25462 			ipif_t	*ipif;
25463 
25464 			ipif = ipif_get_next_ipif(NULL, ill);
25465 			if (ipif == NULL) {
25466 				if (ill_need_rele)
25467 					ill_refrele(ill);
25468 				freemsg(ipsec_mp);
25469 				return;
25470 			}
25471 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25472 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25473 			ire_need_rele = B_TRUE;
25474 			ipif_refrele(ipif);
25475 		} else {
25476 			if (ire_arg != NULL) {
25477 				ire = ire_arg;
25478 			} else {
25479 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
25480 				ire_need_rele = B_TRUE;
25481 			}
25482 		}
25483 		if (ire != NULL)
25484 			goto send;
25485 		/*
25486 		 * ire disappeared underneath.
25487 		 *
25488 		 * What we need to do here is the ip_newroute
25489 		 * logic to get the ire without doing the IPSEC
25490 		 * processing. Follow the same old path. But this
25491 		 * time, ip_wput or ire_add_then_send will call us
25492 		 * directly as all the IPSEC operations are done.
25493 		 */
25494 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25495 		mp->b_prev = NULL;
25496 		mp->b_next = NULL;
25497 
25498 		/*
25499 		 * If the IPsec packet was processed asynchronously,
25500 		 * drop it now.
25501 		 */
25502 		if (q == NULL) {
25503 			if (ill_need_rele)
25504 				ill_refrele(ill);
25505 			freemsg(ipsec_mp);
25506 			return;
25507 		}
25508 
25509 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25510 		    zoneid);
25511 	}
25512 	if (ill != NULL && ill_need_rele)
25513 		ill_refrele(ill);
25514 	return;
25515 send:
25516 	if (ill != NULL && ill_need_rele)
25517 		ill_refrele(ill);
25518 
25519 	/* Local delivery */
25520 	if (ire->ire_stq == NULL) {
25521 		ill_t	*out_ill;
25522 		ASSERT(q != NULL);
25523 
25524 		/* PFHooks: LOOPBACK_OUT */
25525 		out_ill = ire->ire_ipif->ipif_ill;
25526 
25527 		DTRACE_PROBE4(ip6__loopback__out__start,
25528 		    ill_t *, NULL, ill_t *, out_ill,
25529 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25530 
25531 		FW_HOOKS6(ip6_loopback_out_event, ipv6firewall_loopback_out,
25532 		    NULL, out_ill, ip6h1, ipsec_mp, mp);
25533 
25534 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25535 
25536 		if (ipsec_mp != NULL)
25537 			ip_wput_local_v6(RD(q), out_ill,
25538 			    ip6h, ipsec_mp, ire, 0);
25539 		if (ire_need_rele)
25540 			ire_refrele(ire);
25541 		return;
25542 	}
25543 	/*
25544 	 * Everything is done. Send it out on the wire.
25545 	 * We force the insertion of a fragment header using the
25546 	 * IPH_FRAG_HDR flag in two cases:
25547 	 * - after reception of an ICMPv6 "packet too big" message
25548 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25549 	 * - for multirouted IPv6 packets, so that the receiver can
25550 	 *   discard duplicates according to their fragment identifier
25551 	 */
25552 	/* XXX fix flow control problems. */
25553 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25554 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25555 		if (hwaccel) {
25556 			/*
25557 			 * hardware acceleration does not handle these
25558 			 * "slow path" cases.
25559 			 */
25560 			/* IPsec KSTATS: should bump bean counter here. */
25561 			if (ire_need_rele)
25562 				ire_refrele(ire);
25563 			freemsg(ipsec_mp);
25564 			return;
25565 		}
25566 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25567 		    (mp->b_cont ? msgdsize(mp) :
25568 		    mp->b_wptr - (uchar_t *)ip6h)) {
25569 			/* IPsec KSTATS: should bump bean counter here. */
25570 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25571 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25572 			    msgdsize(mp)));
25573 			if (ire_need_rele)
25574 				ire_refrele(ire);
25575 			freemsg(ipsec_mp);
25576 			return;
25577 		}
25578 		ASSERT(mp->b_prev == NULL);
25579 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25580 		    ntohs(ip6h->ip6_plen) +
25581 		    IPV6_HDR_LEN, ire->ire_max_frag));
25582 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25583 		    ire->ire_max_frag);
25584 	} else {
25585 		UPDATE_OB_PKT_COUNT(ire);
25586 		ire->ire_last_used_time = lbolt;
25587 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25588 	}
25589 	if (ire_need_rele)
25590 		ire_refrele(ire);
25591 	freeb(ipsec_mp);
25592 }
25593 
25594 void
25595 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25596 {
25597 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25598 	da_ipsec_t *hada;	/* data attributes */
25599 	ill_t *ill = (ill_t *)q->q_ptr;
25600 
25601 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25602 
25603 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25604 		/* IPsec KSTATS: Bump lose counter here! */
25605 		freemsg(mp);
25606 		return;
25607 	}
25608 
25609 	/*
25610 	 * It's an IPsec packet that must be
25611 	 * accelerated by the Provider, and the
25612 	 * outbound ill is IPsec acceleration capable.
25613 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25614 	 * to the ill.
25615 	 * IPsec KSTATS: should bump packet counter here.
25616 	 */
25617 
25618 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25619 	if (hada_mp == NULL) {
25620 		/* IPsec KSTATS: should bump packet counter here. */
25621 		freemsg(mp);
25622 		return;
25623 	}
25624 
25625 	hada_mp->b_datap->db_type = M_CTL;
25626 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25627 	hada_mp->b_cont = mp;
25628 
25629 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25630 	bzero(hada, sizeof (da_ipsec_t));
25631 	hada->da_type = IPHADA_M_CTL;
25632 
25633 	putnext(q, hada_mp);
25634 }
25635 
25636 /*
25637  * Finish the outbound IPsec processing. This function is called from
25638  * ipsec_out_process() if the IPsec packet was processed
25639  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25640  * asynchronously.
25641  */
25642 void
25643 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25644     ire_t *ire_arg)
25645 {
25646 	uint32_t v_hlen_tos_len;
25647 	ipaddr_t	dst;
25648 	ipif_t	*ipif = NULL;
25649 	ire_t *ire;
25650 	ire_t *ire1 = NULL;
25651 	mblk_t *next_mp = NULL;
25652 	uint32_t max_frag;
25653 	boolean_t multirt_send = B_FALSE;
25654 	mblk_t *mp;
25655 	mblk_t *mp1;
25656 	ipha_t *ipha1;
25657 	uint_t	ill_index;
25658 	ipsec_out_t *io;
25659 	boolean_t attach_if;
25660 	int match_flags, offset;
25661 	irb_t *irb = NULL;
25662 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25663 	zoneid_t zoneid;
25664 	uint32_t cksum;
25665 	uint16_t *up;
25666 	ipxmit_state_t	pktxmit_state;
25667 #ifdef	_BIG_ENDIAN
25668 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25669 #else
25670 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25671 #endif
25672 
25673 	mp = ipsec_mp->b_cont;
25674 	ipha1 = (ipha_t *)mp->b_rptr;
25675 	ASSERT(mp != NULL);
25676 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25677 	dst = ipha->ipha_dst;
25678 
25679 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25680 	ill_index = io->ipsec_out_ill_index;
25681 	attach_if = io->ipsec_out_attach_if;
25682 	zoneid = io->ipsec_out_zoneid;
25683 	ASSERT(zoneid != ALL_ZONES);
25684 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25685 	if (ill_index != 0) {
25686 		if (ill == NULL) {
25687 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25688 			    ill_index, B_FALSE);
25689 
25690 			/* Failure case frees things for us. */
25691 			if (ill == NULL)
25692 				return;
25693 
25694 			ill_need_rele = B_TRUE;
25695 		}
25696 		/*
25697 		 * If this packet needs to go out on a particular interface
25698 		 * honor it.
25699 		 */
25700 		if (attach_if) {
25701 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25702 
25703 			/*
25704 			 * Check if we need an ire that will not be
25705 			 * looked up by anybody else i.e. HIDDEN.
25706 			 */
25707 			if (ill_is_probeonly(ill)) {
25708 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25709 			}
25710 		}
25711 	}
25712 
25713 	if (CLASSD(dst)) {
25714 		boolean_t conn_dontroute;
25715 		/*
25716 		 * Use the ill_index to get the right ipif.
25717 		 */
25718 		conn_dontroute = io->ipsec_out_dontroute;
25719 		if (ill_index == 0)
25720 			ipif = ipif_lookup_group(dst, zoneid);
25721 		else
25722 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25723 		if (ipif == NULL) {
25724 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25725 			    " multicast\n"));
25726 			BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
25727 			freemsg(ipsec_mp);
25728 			goto done;
25729 		}
25730 		/*
25731 		 * ipha_src has already been intialized with the
25732 		 * value of the ipif in ip_wput. All we need now is
25733 		 * an ire to send this downstream.
25734 		 */
25735 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25736 		    MBLK_GETLABEL(mp), match_flags);
25737 		if (ire != NULL) {
25738 			ill_t *ill1;
25739 			/*
25740 			 * Do the multicast forwarding now, as the IPSEC
25741 			 * processing has been done.
25742 			 */
25743 			if (ip_g_mrouter && !conn_dontroute &&
25744 			    (ill1 = ire_to_ill(ire))) {
25745 				if (ip_mforward(ill1, ipha, mp)) {
25746 					freemsg(ipsec_mp);
25747 					ip1dbg(("ip_wput_ipsec_out: mforward "
25748 					    "failed\n"));
25749 					ire_refrele(ire);
25750 					goto done;
25751 				}
25752 			}
25753 			goto send;
25754 		}
25755 
25756 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25757 		mp->b_prev = NULL;
25758 		mp->b_next = NULL;
25759 
25760 		/*
25761 		 * If the IPsec packet was processed asynchronously,
25762 		 * drop it now.
25763 		 */
25764 		if (q == NULL) {
25765 			freemsg(ipsec_mp);
25766 			goto done;
25767 		}
25768 
25769 		/*
25770 		 * We may be using a wrong ipif to create the ire.
25771 		 * But it is okay as the source address is assigned
25772 		 * for the packet already. Next outbound packet would
25773 		 * create the IRE with the right IPIF in ip_wput.
25774 		 *
25775 		 * Also handle RTF_MULTIRT routes.
25776 		 */
25777 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25778 		    zoneid, &zero_info);
25779 	} else {
25780 		if (attach_if) {
25781 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25782 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25783 		} else {
25784 			if (ire_arg != NULL) {
25785 				ire = ire_arg;
25786 				ire_need_rele = B_FALSE;
25787 			} else {
25788 				ire = ire_cache_lookup(dst, zoneid,
25789 				    MBLK_GETLABEL(mp));
25790 			}
25791 		}
25792 		if (ire != NULL) {
25793 			goto send;
25794 		}
25795 
25796 		/*
25797 		 * ire disappeared underneath.
25798 		 *
25799 		 * What we need to do here is the ip_newroute
25800 		 * logic to get the ire without doing the IPSEC
25801 		 * processing. Follow the same old path. But this
25802 		 * time, ip_wput or ire_add_then_put will call us
25803 		 * directly as all the IPSEC operations are done.
25804 		 */
25805 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25806 		mp->b_prev = NULL;
25807 		mp->b_next = NULL;
25808 
25809 		/*
25810 		 * If the IPsec packet was processed asynchronously,
25811 		 * drop it now.
25812 		 */
25813 		if (q == NULL) {
25814 			freemsg(ipsec_mp);
25815 			goto done;
25816 		}
25817 
25818 		/*
25819 		 * Since we're going through ip_newroute() again, we
25820 		 * need to make sure we don't:
25821 		 *
25822 		 *	1.) Trigger the ASSERT() with the ipha_ident
25823 		 *	    overloading.
25824 		 *	2.) Redo transport-layer checksumming, since we've
25825 		 *	    already done all that to get this far.
25826 		 *
25827 		 * The easiest way not do either of the above is to set
25828 		 * the ipha_ident field to IP_HDR_INCLUDED.
25829 		 */
25830 		ipha->ipha_ident = IP_HDR_INCLUDED;
25831 		ip_newroute(q, ipsec_mp, dst, NULL,
25832 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid);
25833 	}
25834 	goto done;
25835 send:
25836 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
25837 		/*
25838 		 * ESP NAT-Traversal packet.
25839 		 *
25840 		 * Just do software checksum for now.
25841 		 */
25842 
25843 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
25844 		IP_STAT(ip_out_sw_cksum);
25845 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
25846 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
25847 #define	iphs	((uint16_t *)ipha)
25848 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
25849 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
25850 		    IP_SIMPLE_HDR_LENGTH);
25851 #undef iphs
25852 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
25853 			cksum = 0xFFFF;
25854 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
25855 			if (mp1->b_wptr - mp1->b_rptr >=
25856 			    offset + sizeof (uint16_t)) {
25857 				up = (uint16_t *)(mp1->b_rptr + offset);
25858 				*up = cksum;
25859 				break;	/* out of for loop */
25860 			} else {
25861 				offset -= (mp->b_wptr - mp->b_rptr);
25862 			}
25863 	} /* Otherwise, just keep the all-zero checksum. */
25864 
25865 	if (ire->ire_stq == NULL) {
25866 		ill_t	*out_ill;
25867 		/*
25868 		 * Loopbacks go through ip_wput_local except for one case.
25869 		 * We come here if we generate a icmp_frag_needed message
25870 		 * after IPSEC processing is over. When this function calls
25871 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25872 		 * icmp_frag_needed. The message generated comes back here
25873 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25874 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25875 		 * source address as it is usually set in ip_wput_ire. As
25876 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25877 		 * and we end up here. We can't enter ip_wput_ire once the
25878 		 * IPSEC processing is over and hence we need to do it here.
25879 		 */
25880 		ASSERT(q != NULL);
25881 		UPDATE_OB_PKT_COUNT(ire);
25882 		ire->ire_last_used_time = lbolt;
25883 		if (ipha->ipha_src == 0)
25884 			ipha->ipha_src = ire->ire_src_addr;
25885 
25886 		/* PFHooks: LOOPBACK_OUT */
25887 		out_ill = ire->ire_ipif->ipif_ill;
25888 
25889 		DTRACE_PROBE4(ip4__loopback__out__start,
25890 		    ill_t *, NULL, ill_t *, out_ill,
25891 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25892 
25893 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
25894 		    NULL, out_ill, ipha1, ipsec_mp, mp);
25895 
25896 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25897 
25898 		if (ipsec_mp != NULL)
25899 			ip_wput_local(RD(q), out_ill,
25900 			    ipha, ipsec_mp, ire, 0, zoneid);
25901 		if (ire_need_rele)
25902 			ire_refrele(ire);
25903 		goto done;
25904 	}
25905 
25906 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25907 		/*
25908 		 * We are through with IPSEC processing.
25909 		 * Fragment this and send it on the wire.
25910 		 */
25911 		if (io->ipsec_out_accelerated) {
25912 			/*
25913 			 * The packet has been accelerated but must
25914 			 * be fragmented. This should not happen
25915 			 * since AH and ESP must not accelerate
25916 			 * packets that need fragmentation, however
25917 			 * the configuration could have changed
25918 			 * since the AH or ESP processing.
25919 			 * Drop packet.
25920 			 * IPsec KSTATS: bump bean counter here.
25921 			 */
25922 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25923 			    "fragmented accelerated packet!\n"));
25924 			freemsg(ipsec_mp);
25925 		} else {
25926 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid);
25927 		}
25928 		if (ire_need_rele)
25929 			ire_refrele(ire);
25930 		goto done;
25931 	}
25932 
25933 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25934 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25935 	    (void *)ire->ire_ipif, (void *)ipif));
25936 
25937 	/*
25938 	 * Multiroute the secured packet, unless IPsec really
25939 	 * requires the packet to go out only through a particular
25940 	 * interface.
25941 	 */
25942 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
25943 		ire_t *first_ire;
25944 		irb = ire->ire_bucket;
25945 		ASSERT(irb != NULL);
25946 		/*
25947 		 * This ire has been looked up as the one that
25948 		 * goes through the given ipif;
25949 		 * make sure we do not omit any other multiroute ire
25950 		 * that may be present in the bucket before this one.
25951 		 */
25952 		IRB_REFHOLD(irb);
25953 		for (first_ire = irb->irb_ire;
25954 		    first_ire != NULL;
25955 		    first_ire = first_ire->ire_next) {
25956 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25957 			    (first_ire->ire_addr == ire->ire_addr) &&
25958 			    !(first_ire->ire_marks &
25959 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
25960 				break;
25961 		}
25962 
25963 		if ((first_ire != NULL) && (first_ire != ire)) {
25964 			/*
25965 			 * Don't change the ire if the packet must
25966 			 * be fragmented if sent via this new one.
25967 			 */
25968 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25969 				IRE_REFHOLD(first_ire);
25970 				if (ire_need_rele)
25971 					ire_refrele(ire);
25972 				else
25973 					ire_need_rele = B_TRUE;
25974 				ire = first_ire;
25975 			}
25976 		}
25977 		IRB_REFRELE(irb);
25978 
25979 		multirt_send = B_TRUE;
25980 		max_frag = ire->ire_max_frag;
25981 	} else {
25982 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
25983 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25984 			    "flag, attach_if %d\n", attach_if));
25985 		}
25986 	}
25987 
25988 	/*
25989 	 * In most cases, the emission loop below is entered only once.
25990 	 * Only in the case where the ire holds the RTF_MULTIRT
25991 	 * flag, we loop to process all RTF_MULTIRT ires in the
25992 	 * bucket, and send the packet through all crossed
25993 	 * RTF_MULTIRT routes.
25994 	 */
25995 	do {
25996 		if (multirt_send) {
25997 			/*
25998 			 * ire1 holds here the next ire to process in the
25999 			 * bucket. If multirouting is expected,
26000 			 * any non-RTF_MULTIRT ire that has the
26001 			 * right destination address is ignored.
26002 			 */
26003 			ASSERT(irb != NULL);
26004 			IRB_REFHOLD(irb);
26005 			for (ire1 = ire->ire_next;
26006 			    ire1 != NULL;
26007 			    ire1 = ire1->ire_next) {
26008 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26009 					continue;
26010 				if (ire1->ire_addr != ire->ire_addr)
26011 					continue;
26012 				if (ire1->ire_marks &
26013 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26014 					continue;
26015 				/* No loopback here */
26016 				if (ire1->ire_stq == NULL)
26017 					continue;
26018 				/*
26019 				 * Ensure we do not exceed the MTU
26020 				 * of the next route.
26021 				 */
26022 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26023 					ip_multirt_bad_mtu(ire1, max_frag);
26024 					continue;
26025 				}
26026 
26027 				IRE_REFHOLD(ire1);
26028 				break;
26029 			}
26030 			IRB_REFRELE(irb);
26031 			if (ire1 != NULL) {
26032 				/*
26033 				 * We are in a multiple send case, need to
26034 				 * make a copy of the packet.
26035 				 */
26036 				next_mp = copymsg(ipsec_mp);
26037 				if (next_mp == NULL) {
26038 					ire_refrele(ire1);
26039 					ire1 = NULL;
26040 				}
26041 			}
26042 		}
26043 		/*
26044 		 * Everything is done. Send it out on the wire
26045 		 *
26046 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26047 		 * either send it on the wire or, in the case of
26048 		 * HW acceleration, call ipsec_hw_putnext.
26049 		 */
26050 		if (ire->ire_nce &&
26051 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26052 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26053 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26054 			/*
26055 			 * If ire's link-layer is unresolved (this
26056 			 * would only happen if the incomplete ire
26057 			 * was added to cachetable via forwarding path)
26058 			 * don't bother going to ip_xmit_v4. Just drop the
26059 			 * packet.
26060 			 * There is a slight risk here, in that, if we
26061 			 * have the forwarding path create an incomplete
26062 			 * IRE, then until the IRE is completed, any
26063 			 * transmitted IPSEC packets will be dropped
26064 			 * instead of being queued waiting for resolution.
26065 			 *
26066 			 * But the likelihood of a forwarding packet and a wput
26067 			 * packet sending to the same dst at the same time
26068 			 * and there not yet be an ARP entry for it is small.
26069 			 * Furthermore, if this actually happens, it might
26070 			 * be likely that wput would generate multiple
26071 			 * packets (and forwarding would also have a train
26072 			 * of packets) for that destination. If this is
26073 			 * the case, some of them would have been dropped
26074 			 * anyway, since ARP only queues a few packets while
26075 			 * waiting for resolution
26076 			 *
26077 			 * NOTE: We should really call ip_xmit_v4,
26078 			 * and let it queue the packet and send the
26079 			 * ARP query and have ARP come back thus:
26080 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26081 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26082 			 * hw accel work. But it's too complex to get
26083 			 * the IPsec hw  acceleration approach to fit
26084 			 * well with ip_xmit_v4 doing ARP without
26085 			 * doing IPSEC simplification. For now, we just
26086 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26087 			 * that we can continue with the send on the next
26088 			 * attempt.
26089 			 *
26090 			 * XXX THis should be revisited, when
26091 			 * the IPsec/IP interaction is cleaned up
26092 			 */
26093 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26094 			    " - dropping packet\n"));
26095 			freemsg(ipsec_mp);
26096 			/*
26097 			 * Call ip_xmit_v4() to trigger ARP query
26098 			 * in case the nce_state is ND_INITIAL
26099 			 */
26100 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26101 			goto drop_pkt;
26102 		}
26103 
26104 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26105 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26106 		    mblk_t *, mp);
26107 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
26108 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp);
26109 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
26110 		if (mp == NULL)
26111 			goto drop_pkt;
26112 
26113 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26114 		pktxmit_state = ip_xmit_v4(mp, ire,
26115 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26116 
26117 		if ((pktxmit_state ==  SEND_FAILED) ||
26118 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26119 
26120 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26121 drop_pkt:
26122 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26123 			    ipIfStatsOutDiscards);
26124 			if (ire_need_rele)
26125 				ire_refrele(ire);
26126 			if (ire1 != NULL) {
26127 				ire_refrele(ire1);
26128 				freemsg(next_mp);
26129 			}
26130 			goto done;
26131 		}
26132 
26133 		freeb(ipsec_mp);
26134 		if (ire_need_rele)
26135 			ire_refrele(ire);
26136 
26137 		if (ire1 != NULL) {
26138 			ire = ire1;
26139 			ire_need_rele = B_TRUE;
26140 			ASSERT(next_mp);
26141 			ipsec_mp = next_mp;
26142 			mp = ipsec_mp->b_cont;
26143 			ire1 = NULL;
26144 			next_mp = NULL;
26145 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26146 		} else {
26147 			multirt_send = B_FALSE;
26148 		}
26149 	} while (multirt_send);
26150 done:
26151 	if (ill != NULL && ill_need_rele)
26152 		ill_refrele(ill);
26153 	if (ipif != NULL)
26154 		ipif_refrele(ipif);
26155 }
26156 
26157 /*
26158  * Get the ill corresponding to the specified ire, and compare its
26159  * capabilities with the protocol and algorithms specified by the
26160  * the SA obtained from ipsec_out. If they match, annotate the
26161  * ipsec_out structure to indicate that the packet needs acceleration.
26162  *
26163  *
26164  * A packet is eligible for outbound hardware acceleration if the
26165  * following conditions are satisfied:
26166  *
26167  * 1. the packet will not be fragmented
26168  * 2. the provider supports the algorithm
26169  * 3. there is no pending control message being exchanged
26170  * 4. snoop is not attached
26171  * 5. the destination address is not a broadcast or multicast address.
26172  *
26173  * Rationale:
26174  *	- Hardware drivers do not support fragmentation with
26175  *	  the current interface.
26176  *	- snoop, multicast, and broadcast may result in exposure of
26177  *	  a cleartext datagram.
26178  * We check all five of these conditions here.
26179  *
26180  * XXX would like to nuke "ire_t *" parameter here; problem is that
26181  * IRE is only way to figure out if a v4 address is a broadcast and
26182  * thus ineligible for acceleration...
26183  */
26184 static void
26185 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26186 {
26187 	ipsec_out_t *io;
26188 	mblk_t *data_mp;
26189 	uint_t plen, overhead;
26190 
26191 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26192 		return;
26193 
26194 	if (ill == NULL)
26195 		return;
26196 
26197 	/*
26198 	 * Destination address is a broadcast or multicast.  Punt.
26199 	 */
26200 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26201 	    IRE_LOCAL)))
26202 		return;
26203 
26204 	data_mp = ipsec_mp->b_cont;
26205 
26206 	if (ill->ill_isv6) {
26207 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26208 
26209 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26210 			return;
26211 
26212 		plen = ip6h->ip6_plen;
26213 	} else {
26214 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26215 
26216 		if (CLASSD(ipha->ipha_dst))
26217 			return;
26218 
26219 		plen = ipha->ipha_length;
26220 	}
26221 	/*
26222 	 * Is there a pending DLPI control message being exchanged
26223 	 * between IP/IPsec and the DLS Provider? If there is, it
26224 	 * could be a SADB update, and the state of the DLS Provider
26225 	 * SADB might not be in sync with the SADB maintained by
26226 	 * IPsec. To avoid dropping packets or using the wrong keying
26227 	 * material, we do not accelerate this packet.
26228 	 */
26229 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26230 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26231 		    "ill_dlpi_pending! don't accelerate packet\n"));
26232 		return;
26233 	}
26234 
26235 	/*
26236 	 * Is the Provider in promiscous mode? If it does, we don't
26237 	 * accelerate the packet since it will bounce back up to the
26238 	 * listeners in the clear.
26239 	 */
26240 	if (ill->ill_promisc_on_phys) {
26241 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26242 		    "ill in promiscous mode, don't accelerate packet\n"));
26243 		return;
26244 	}
26245 
26246 	/*
26247 	 * Will the packet require fragmentation?
26248 	 */
26249 
26250 	/*
26251 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26252 	 * as is used elsewhere.
26253 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26254 	 *	+ 2-byte trailer
26255 	 */
26256 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26257 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26258 
26259 	if ((plen + overhead) > ill->ill_max_mtu)
26260 		return;
26261 
26262 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26263 
26264 	/*
26265 	 * Can the ill accelerate this IPsec protocol and algorithm
26266 	 * specified by the SA?
26267 	 */
26268 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26269 	    ill->ill_isv6, sa)) {
26270 		return;
26271 	}
26272 
26273 	/*
26274 	 * Tell AH or ESP that the outbound ill is capable of
26275 	 * accelerating this packet.
26276 	 */
26277 	io->ipsec_out_is_capab_ill = B_TRUE;
26278 }
26279 
26280 /*
26281  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26282  *
26283  * If this function returns B_TRUE, the requested SA's have been filled
26284  * into the ipsec_out_*_sa pointers.
26285  *
26286  * If the function returns B_FALSE, the packet has been "consumed", most
26287  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26288  *
26289  * The SA references created by the protocol-specific "select"
26290  * function will be released when the ipsec_mp is freed, thanks to the
26291  * ipsec_out_free destructor -- see spd.c.
26292  */
26293 static boolean_t
26294 ipsec_out_select_sa(mblk_t *ipsec_mp)
26295 {
26296 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26297 	ipsec_out_t *io;
26298 	ipsec_policy_t *pp;
26299 	ipsec_action_t *ap;
26300 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26301 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26302 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26303 
26304 	if (!io->ipsec_out_secure) {
26305 		/*
26306 		 * We came here by mistake.
26307 		 * Don't bother with ipsec processing
26308 		 * We should "discourage" this path in the future.
26309 		 */
26310 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26311 		return (B_FALSE);
26312 	}
26313 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26314 	ASSERT((io->ipsec_out_policy != NULL) ||
26315 	    (io->ipsec_out_act != NULL));
26316 
26317 	ASSERT(io->ipsec_out_failed == B_FALSE);
26318 
26319 	/*
26320 	 * IPSEC processing has started.
26321 	 */
26322 	io->ipsec_out_proc_begin = B_TRUE;
26323 	ap = io->ipsec_out_act;
26324 	if (ap == NULL) {
26325 		pp = io->ipsec_out_policy;
26326 		ASSERT(pp != NULL);
26327 		ap = pp->ipsp_act;
26328 		ASSERT(ap != NULL);
26329 	}
26330 
26331 	/*
26332 	 * We have an action.  now, let's select SA's.
26333 	 * (In the future, we can cache this in the conn_t..)
26334 	 */
26335 	if (ap->ipa_want_esp) {
26336 		if (io->ipsec_out_esp_sa == NULL) {
26337 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26338 			    IPPROTO_ESP);
26339 		}
26340 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26341 	}
26342 
26343 	if (ap->ipa_want_ah) {
26344 		if (io->ipsec_out_ah_sa == NULL) {
26345 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26346 			    IPPROTO_AH);
26347 		}
26348 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26349 		/*
26350 		 * The ESP and AH processing order needs to be preserved
26351 		 * when both protocols are required (ESP should be applied
26352 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26353 		 * when both ESP and AH are required, and an AH ACQUIRE
26354 		 * is needed.
26355 		 */
26356 		if (ap->ipa_want_esp && need_ah_acquire)
26357 			need_esp_acquire = B_TRUE;
26358 	}
26359 
26360 	/*
26361 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26362 	 * Release SAs that got referenced, but will not be used until we
26363 	 * acquire _all_ of the SAs we need.
26364 	 */
26365 	if (need_ah_acquire || need_esp_acquire) {
26366 		if (io->ipsec_out_ah_sa != NULL) {
26367 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26368 			io->ipsec_out_ah_sa = NULL;
26369 		}
26370 		if (io->ipsec_out_esp_sa != NULL) {
26371 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26372 			io->ipsec_out_esp_sa = NULL;
26373 		}
26374 
26375 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26376 		return (B_FALSE);
26377 	}
26378 
26379 	return (B_TRUE);
26380 }
26381 
26382 /*
26383  * Process an IPSEC_OUT message and see what you can
26384  * do with it.
26385  * IPQoS Notes:
26386  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26387  * IPSec.
26388  * XXX would like to nuke ire_t.
26389  * XXX ill_index better be "real"
26390  */
26391 void
26392 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26393 {
26394 	ipsec_out_t *io;
26395 	ipsec_policy_t *pp;
26396 	ipsec_action_t *ap;
26397 	ipha_t *ipha;
26398 	ip6_t *ip6h;
26399 	mblk_t *mp;
26400 	ill_t *ill;
26401 	zoneid_t zoneid;
26402 	ipsec_status_t ipsec_rc;
26403 	boolean_t ill_need_rele = B_FALSE;
26404 
26405 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26406 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26407 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26408 	mp = ipsec_mp->b_cont;
26409 
26410 	/*
26411 	 * Initiate IPPF processing. We do it here to account for packets
26412 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26413 	 * We can check for ipsec_out_proc_begin even for such packets, as
26414 	 * they will always be false (asserted below).
26415 	 */
26416 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
26417 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26418 		    io->ipsec_out_ill_index : ill_index);
26419 		if (mp == NULL) {
26420 			ip2dbg(("ipsec_out_process: packet dropped "\
26421 			    "during IPPF processing\n"));
26422 			freeb(ipsec_mp);
26423 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26424 			return;
26425 		}
26426 	}
26427 
26428 	if (!io->ipsec_out_secure) {
26429 		/*
26430 		 * We came here by mistake.
26431 		 * Don't bother with ipsec processing
26432 		 * Should "discourage" this path in the future.
26433 		 */
26434 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26435 		goto done;
26436 	}
26437 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26438 	ASSERT((io->ipsec_out_policy != NULL) ||
26439 	    (io->ipsec_out_act != NULL));
26440 	ASSERT(io->ipsec_out_failed == B_FALSE);
26441 
26442 	if (!ipsec_loaded()) {
26443 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26444 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26445 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26446 		} else {
26447 			BUMP_MIB(&ip6_mib, ipIfStatsOutDiscards);
26448 		}
26449 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26450 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
26451 		return;
26452 	}
26453 
26454 	/*
26455 	 * IPSEC processing has started.
26456 	 */
26457 	io->ipsec_out_proc_begin = B_TRUE;
26458 	ap = io->ipsec_out_act;
26459 	if (ap == NULL) {
26460 		pp = io->ipsec_out_policy;
26461 		ASSERT(pp != NULL);
26462 		ap = pp->ipsp_act;
26463 		ASSERT(ap != NULL);
26464 	}
26465 
26466 	/*
26467 	 * Save the outbound ill index. When the packet comes back
26468 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26469 	 * before sending it the accelerated packet.
26470 	 */
26471 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26472 		int ifindex;
26473 		ill = ire_to_ill(ire);
26474 		ifindex = ill->ill_phyint->phyint_ifindex;
26475 		io->ipsec_out_capab_ill_index = ifindex;
26476 	}
26477 
26478 	/*
26479 	 * The order of processing is first insert a IP header if needed.
26480 	 * Then insert the ESP header and then the AH header.
26481 	 */
26482 	if ((io->ipsec_out_se_done == B_FALSE) &&
26483 	    (ap->ipa_want_se)) {
26484 		/*
26485 		 * First get the outer IP header before sending
26486 		 * it to ESP.
26487 		 */
26488 		ipha_t *oipha, *iipha;
26489 		mblk_t *outer_mp, *inner_mp;
26490 
26491 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26492 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26493 			    "ipsec_out_process: "
26494 			    "Self-Encapsulation failed: Out of memory\n");
26495 			freemsg(ipsec_mp);
26496 			if (ill != NULL) {
26497 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26498 			} else {
26499 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26500 			}
26501 			return;
26502 		}
26503 		inner_mp = ipsec_mp->b_cont;
26504 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26505 		oipha = (ipha_t *)outer_mp->b_rptr;
26506 		iipha = (ipha_t *)inner_mp->b_rptr;
26507 		*oipha = *iipha;
26508 		outer_mp->b_wptr += sizeof (ipha_t);
26509 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26510 		    sizeof (ipha_t));
26511 		oipha->ipha_protocol = IPPROTO_ENCAP;
26512 		oipha->ipha_version_and_hdr_length =
26513 		    IP_SIMPLE_HDR_VERSION;
26514 		oipha->ipha_hdr_checksum = 0;
26515 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26516 		outer_mp->b_cont = inner_mp;
26517 		ipsec_mp->b_cont = outer_mp;
26518 
26519 		io->ipsec_out_se_done = B_TRUE;
26520 		io->ipsec_out_tunnel = B_TRUE;
26521 	}
26522 
26523 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26524 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26525 	    !ipsec_out_select_sa(ipsec_mp))
26526 		return;
26527 
26528 	/*
26529 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26530 	 * to do the heavy lifting.
26531 	 */
26532 	zoneid = io->ipsec_out_zoneid;
26533 	ASSERT(zoneid != ALL_ZONES);
26534 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26535 		ASSERT(io->ipsec_out_esp_sa != NULL);
26536 		io->ipsec_out_esp_done = B_TRUE;
26537 		/*
26538 		 * Note that since hw accel can only apply one transform,
26539 		 * not two, we skip hw accel for ESP if we also have AH
26540 		 * This is an design limitation of the interface
26541 		 * which should be revisited.
26542 		 */
26543 		ASSERT(ire != NULL);
26544 		if (io->ipsec_out_ah_sa == NULL) {
26545 			ill = (ill_t *)ire->ire_stq->q_ptr;
26546 			ipsec_out_is_accelerated(ipsec_mp,
26547 			    io->ipsec_out_esp_sa, ill, ire);
26548 		}
26549 
26550 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26551 		switch (ipsec_rc) {
26552 		case IPSEC_STATUS_SUCCESS:
26553 			break;
26554 		case IPSEC_STATUS_FAILED:
26555 			if (ill != NULL) {
26556 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26557 			} else {
26558 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26559 			}
26560 			/* FALLTHRU */
26561 		case IPSEC_STATUS_PENDING:
26562 			return;
26563 		}
26564 	}
26565 
26566 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26567 		ASSERT(io->ipsec_out_ah_sa != NULL);
26568 		io->ipsec_out_ah_done = B_TRUE;
26569 		if (ire == NULL) {
26570 			int idx = io->ipsec_out_capab_ill_index;
26571 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26572 			    NULL, NULL, NULL, NULL);
26573 			ill_need_rele = B_TRUE;
26574 		} else {
26575 			ill = (ill_t *)ire->ire_stq->q_ptr;
26576 		}
26577 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26578 		    ire);
26579 
26580 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26581 		switch (ipsec_rc) {
26582 		case IPSEC_STATUS_SUCCESS:
26583 			break;
26584 		case IPSEC_STATUS_FAILED:
26585 			if (ill != NULL) {
26586 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26587 			} else {
26588 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26589 			}
26590 			/* FALLTHRU */
26591 		case IPSEC_STATUS_PENDING:
26592 			if (ill != NULL && ill_need_rele)
26593 				ill_refrele(ill);
26594 			return;
26595 		}
26596 	}
26597 	/*
26598 	 * We are done with IPSEC processing. Send it over
26599 	 * the wire.
26600 	 */
26601 done:
26602 	mp = ipsec_mp->b_cont;
26603 	ipha = (ipha_t *)mp->b_rptr;
26604 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26605 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26606 	} else {
26607 		ip6h = (ip6_t *)ipha;
26608 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26609 	}
26610 	if (ill != NULL && ill_need_rele)
26611 		ill_refrele(ill);
26612 }
26613 
26614 /* ARGSUSED */
26615 void
26616 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26617 {
26618 	opt_restart_t	*or;
26619 	int	err;
26620 	conn_t	*connp;
26621 
26622 	ASSERT(CONN_Q(q));
26623 	connp = Q_TO_CONN(q);
26624 
26625 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26626 	or = (opt_restart_t *)first_mp->b_rptr;
26627 	/*
26628 	 * We don't need to pass any credentials here since this is just
26629 	 * a restart. The credentials are passed in when svr4_optcom_req
26630 	 * is called the first time (from ip_wput_nondata).
26631 	 */
26632 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26633 		err = svr4_optcom_req(q, first_mp, NULL,
26634 		    &ip_opt_obj);
26635 	} else {
26636 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26637 		err = tpi_optcom_req(q, first_mp, NULL,
26638 		    &ip_opt_obj);
26639 	}
26640 	if (err != EINPROGRESS) {
26641 		/* operation is done */
26642 		CONN_OPER_PENDING_DONE(connp);
26643 	}
26644 }
26645 
26646 /*
26647  * ioctls that go through a down/up sequence may need to wait for the down
26648  * to complete. This involves waiting for the ire and ipif refcnts to go down
26649  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26650  */
26651 /* ARGSUSED */
26652 void
26653 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26654 {
26655 	struct iocblk *iocp;
26656 	mblk_t *mp1;
26657 	ip_ioctl_cmd_t *ipip;
26658 	int err;
26659 	sin_t	*sin;
26660 	struct lifreq *lifr;
26661 	struct ifreq *ifr;
26662 
26663 	iocp = (struct iocblk *)mp->b_rptr;
26664 	ASSERT(ipsq != NULL);
26665 	/* Existence of mp1 verified in ip_wput_nondata */
26666 	mp1 = mp->b_cont->b_cont;
26667 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26668 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26669 		/*
26670 		 * Special case where ipsq_current_ipif is not set:
26671 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26672 		 * ill could also have become part of a ipmp group in the
26673 		 * process, we are here as were not able to complete the
26674 		 * operation in ipif_set_values because we could not become
26675 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26676 		 * will not be set so we need to set it.
26677 		 */
26678 		ill_t *ill = q->q_ptr;
26679 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26680 	}
26681 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26682 
26683 	if (ipip->ipi_cmd_type == IF_CMD) {
26684 		/* This a old style SIOC[GS]IF* command */
26685 		ifr = (struct ifreq *)mp1->b_rptr;
26686 		sin = (sin_t *)&ifr->ifr_addr;
26687 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26688 		/* This a new style SIOC[GS]LIF* command */
26689 		lifr = (struct lifreq *)mp1->b_rptr;
26690 		sin = (sin_t *)&lifr->lifr_addr;
26691 	} else {
26692 		sin = NULL;
26693 	}
26694 
26695 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26696 	    ipip, mp1->b_rptr);
26697 
26698 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26699 }
26700 
26701 /*
26702  * ioctl processing
26703  *
26704  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
26705  * the ioctl command in the ioctl tables and determines the copyin data size
26706  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
26707  * size.
26708  *
26709  * ioctl processing then continues when the M_IOCDATA makes its way down.
26710  * Now the ioctl is looked up again in the ioctl table, and its properties are
26711  * extracted. The associated 'conn' is then refheld till the end of the ioctl
26712  * and the general ioctl processing function ip_process_ioctl is called.
26713  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26714  * so goes thru the serialization primitive ipsq_try_enter. Then the
26715  * appropriate function to handle the ioctl is called based on the entry in
26716  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26717  * which also refreleases the 'conn' that was refheld at the start of the
26718  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26719  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
26720  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
26721  *
26722  * Many exclusive ioctls go thru an internal down up sequence as part of
26723  * the operation. For example an attempt to change the IP address of an
26724  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26725  * does all the cleanup such as deleting all ires that use this address.
26726  * Then we need to wait till all references to the interface go away.
26727  */
26728 void
26729 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26730 {
26731 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26732 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
26733 	cmd_info_t ci;
26734 	int err;
26735 	boolean_t entered_ipsq = B_FALSE;
26736 
26737 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26738 
26739 	if (ipip == NULL)
26740 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26741 
26742 	/*
26743 	 * SIOCLIFADDIF needs to go thru a special path since the
26744 	 * ill may not exist yet. This happens in the case of lo0
26745 	 * which is created using this ioctl.
26746 	 */
26747 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26748 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26749 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26750 		return;
26751 	}
26752 
26753 	ci.ci_ipif = NULL;
26754 	switch (ipip->ipi_cmd_type) {
26755 	case IF_CMD:
26756 	case LIF_CMD:
26757 		/*
26758 		 * ioctls that pass in a [l]ifreq appear here.
26759 		 * ip_extract_lifreq_cmn returns a refheld ipif in
26760 		 * ci.ci_ipif
26761 		 */
26762 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
26763 		    ipip->ipi_flags, &ci, ip_process_ioctl);
26764 		if (err != 0) {
26765 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26766 			return;
26767 		}
26768 		ASSERT(ci.ci_ipif != NULL);
26769 		break;
26770 
26771 	case TUN_CMD:
26772 		/*
26773 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
26774 		 * a refheld ipif in ci.ci_ipif
26775 		 */
26776 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
26777 		if (err != 0) {
26778 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26779 			return;
26780 		}
26781 		ASSERT(ci.ci_ipif != NULL);
26782 		break;
26783 
26784 	case MISC_CMD:
26785 		/*
26786 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
26787 		 * For eg. SIOCGLIFCONF will appear here.
26788 		 */
26789 		switch (ipip->ipi_cmd) {
26790 		case IF_UNITSEL:
26791 			/* ioctl comes down the ill */
26792 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26793 			ipif_refhold(ci.ci_ipif);
26794 			break;
26795 		case SIOCGMSFILTER:
26796 		case SIOCSMSFILTER:
26797 		case SIOCGIPMSFILTER:
26798 		case SIOCSIPMSFILTER:
26799 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
26800 			    ip_process_ioctl);
26801 			if (err != 0) {
26802 				ip_ioctl_finish(q, mp, err, IPI2MODE(ipip),
26803 				    NULL);
26804 			}
26805 			break;
26806 		}
26807 		err = 0;
26808 		ci.ci_sin = NULL;
26809 		ci.ci_sin6 = NULL;
26810 		ci.ci_lifr = NULL;
26811 		break;
26812 	}
26813 
26814 	/*
26815 	 * If ipsq is non-null, we are already being called exclusively
26816 	 */
26817 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26818 	if (!(ipip->ipi_flags & IPI_WR)) {
26819 		/*
26820 		 * A return value of EINPROGRESS means the ioctl is
26821 		 * either queued and waiting for some reason or has
26822 		 * already completed.
26823 		 */
26824 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26825 		    ci.ci_lifr);
26826 		if (ci.ci_ipif != NULL)
26827 			ipif_refrele(ci.ci_ipif);
26828 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26829 		return;
26830 	}
26831 
26832 	ASSERT(ci.ci_ipif != NULL);
26833 
26834 	if (ipsq == NULL) {
26835 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26836 		    ip_process_ioctl, NEW_OP, B_TRUE);
26837 		entered_ipsq = B_TRUE;
26838 	}
26839 	/*
26840 	 * Release the ipif so that ipif_down and friends that wait for
26841 	 * references to go away are not misled about the current ipif_refcnt
26842 	 * values. We are writer so we can access the ipif even after releasing
26843 	 * the ipif.
26844 	 */
26845 	ipif_refrele(ci.ci_ipif);
26846 	if (ipsq == NULL)
26847 		return;
26848 
26849 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26850 
26851 	/*
26852 	 * For most set ioctls that come here, this serves as a single point
26853 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26854 	 * be any new references to the ipif. This helps functions that go
26855 	 * through this path and end up trying to wait for the refcnts
26856 	 * associated with the ipif to go down to zero. Some exceptions are
26857 	 * Failover, Failback, and Groupname commands that operate on more than
26858 	 * just the ci.ci_ipif. These commands internally determine the
26859 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26860 	 * flags on that set. Another exception is the Removeif command that
26861 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26862 	 * ipif to operate on.
26863 	 */
26864 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26865 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26866 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26867 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26868 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26869 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26870 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26871 
26872 	/*
26873 	 * A return value of EINPROGRESS means the ioctl is
26874 	 * either queued and waiting for some reason or has
26875 	 * already completed.
26876 	 */
26877 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26878 
26879 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26880 
26881 	if (entered_ipsq)
26882 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26883 }
26884 
26885 /*
26886  * Complete the ioctl. Typically ioctls use the mi package and need to
26887  * do mi_copyout/mi_copy_done.
26888  */
26889 void
26890 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26891 {
26892 	conn_t	*connp = NULL;
26893 
26894 	if (err == EINPROGRESS)
26895 		return;
26896 
26897 	if (CONN_Q(q)) {
26898 		connp = Q_TO_CONN(q);
26899 		ASSERT(connp->conn_ref >= 2);
26900 	}
26901 
26902 	switch (mode) {
26903 	case COPYOUT:
26904 		if (err == 0)
26905 			mi_copyout(q, mp);
26906 		else
26907 			mi_copy_done(q, mp, err);
26908 		break;
26909 
26910 	case NO_COPYOUT:
26911 		mi_copy_done(q, mp, err);
26912 		break;
26913 
26914 	default:
26915 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
26916 		break;
26917 	}
26918 
26919 	/*
26920 	 * The refhold placed at the start of the ioctl is released here.
26921 	 */
26922 	if (connp != NULL)
26923 		CONN_OPER_PENDING_DONE(connp);
26924 
26925 	if (ipsq != NULL)
26926 		ipsq_current_finish(ipsq);
26927 }
26928 
26929 /*
26930  * This is called from ip_wput_nondata to resume a deferred TCP bind.
26931  */
26932 /* ARGSUSED */
26933 void
26934 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
26935 {
26936 	conn_t *connp = arg;
26937 	tcp_t	*tcp;
26938 
26939 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
26940 	tcp = connp->conn_tcp;
26941 
26942 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
26943 		freemsg(mp);
26944 	else
26945 		tcp_rput_other(tcp, mp);
26946 	CONN_OPER_PENDING_DONE(connp);
26947 }
26948 
26949 /* Called from ip_wput for all non data messages */
26950 /* ARGSUSED */
26951 void
26952 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26953 {
26954 	mblk_t		*mp1;
26955 	ire_t		*ire, *fake_ire;
26956 	ill_t		*ill;
26957 	struct iocblk	*iocp;
26958 	ip_ioctl_cmd_t	*ipip;
26959 	cred_t		*cr;
26960 	conn_t		*connp = NULL;
26961 	int		cmd, err;
26962 	nce_t		*nce;
26963 	ipif_t		*ipif;
26964 
26965 	if (CONN_Q(q))
26966 		connp = Q_TO_CONN(q);
26967 
26968 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26969 
26970 	/* Check if it is a queue to /dev/sctp. */
26971 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26972 	    connp->conn_rq == NULL) {
26973 		sctp_wput(q, mp);
26974 		return;
26975 	}
26976 
26977 	switch (DB_TYPE(mp)) {
26978 	case M_IOCTL:
26979 		/*
26980 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26981 		 * will arrange to copy in associated control structures.
26982 		 */
26983 		ip_sioctl_copyin_setup(q, mp);
26984 		return;
26985 	case M_IOCDATA:
26986 		/*
26987 		 * Ensure that this is associated with one of our trans-
26988 		 * parent ioctls.  If it's not ours, discard it if we're
26989 		 * running as a driver, or pass it on if we're a module.
26990 		 */
26991 		iocp = (struct iocblk *)mp->b_rptr;
26992 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26993 		if (ipip == NULL) {
26994 			if (q->q_next == NULL) {
26995 				goto nak;
26996 			} else {
26997 				putnext(q, mp);
26998 			}
26999 			return;
27000 		} else if ((q->q_next != NULL) &&
27001 		    !(ipip->ipi_flags & IPI_MODOK)) {
27002 			/*
27003 			 * the ioctl is one we recognise, but is not
27004 			 * consumed by IP as a module, pass M_IOCDATA
27005 			 * for processing downstream, but only for
27006 			 * common Streams ioctls.
27007 			 */
27008 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27009 				putnext(q, mp);
27010 				return;
27011 			} else {
27012 				goto nak;
27013 			}
27014 		}
27015 
27016 		/* IOCTL continuation following copyin or copyout. */
27017 		if (mi_copy_state(q, mp, NULL) == -1) {
27018 			/*
27019 			 * The copy operation failed.  mi_copy_state already
27020 			 * cleaned up, so we're out of here.
27021 			 */
27022 			return;
27023 		}
27024 		/*
27025 		 * If we just completed a copy in, we become writer and
27026 		 * continue processing in ip_sioctl_copyin_done.  If it
27027 		 * was a copy out, we call mi_copyout again.  If there is
27028 		 * nothing more to copy out, it will complete the IOCTL.
27029 		 */
27030 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27031 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27032 				mi_copy_done(q, mp, EPROTO);
27033 				return;
27034 			}
27035 			/*
27036 			 * Check for cases that need more copying.  A return
27037 			 * value of 0 means a second copyin has been started,
27038 			 * so we return; a return value of 1 means no more
27039 			 * copying is needed, so we continue.
27040 			 */
27041 			cmd = iocp->ioc_cmd;
27042 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27043 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27044 			    MI_COPY_COUNT(mp) == 1) {
27045 				if (ip_copyin_msfilter(q, mp) == 0)
27046 					return;
27047 			}
27048 			/*
27049 			 * Refhold the conn, till the ioctl completes. This is
27050 			 * needed in case the ioctl ends up in the pending mp
27051 			 * list. Every mp in the ill_pending_mp list and
27052 			 * the ipsq_pending_mp must have a refhold on the conn
27053 			 * to resume processing. The refhold is released when
27054 			 * the ioctl completes. (normally or abnormally)
27055 			 * In all cases ip_ioctl_finish is called to finish
27056 			 * the ioctl.
27057 			 */
27058 			if (connp != NULL) {
27059 				/* This is not a reentry */
27060 				ASSERT(ipsq == NULL);
27061 				CONN_INC_REF(connp);
27062 			} else {
27063 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27064 					mi_copy_done(q, mp, EINVAL);
27065 					return;
27066 				}
27067 			}
27068 
27069 			ip_process_ioctl(ipsq, q, mp, ipip);
27070 
27071 		} else {
27072 			mi_copyout(q, mp);
27073 		}
27074 		return;
27075 nak:
27076 		iocp->ioc_error = EINVAL;
27077 		mp->b_datap->db_type = M_IOCNAK;
27078 		iocp->ioc_count = 0;
27079 		qreply(q, mp);
27080 		return;
27081 
27082 	case M_IOCNAK:
27083 		/*
27084 		 * The only way we could get here is if a resolver didn't like
27085 		 * an IOCTL we sent it.	 This shouldn't happen.
27086 		 */
27087 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27088 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27089 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27090 		freemsg(mp);
27091 		return;
27092 	case M_IOCACK:
27093 		/* Finish socket ioctls passed through to ARP. */
27094 		ip_sioctl_iocack(q, mp);
27095 		return;
27096 	case M_FLUSH:
27097 		if (*mp->b_rptr & FLUSHW)
27098 			flushq(q, FLUSHALL);
27099 		if (q->q_next) {
27100 			/*
27101 			 * M_FLUSH is sent up to IP by some drivers during
27102 			 * unbind. ip_rput has already replied to it. We are
27103 			 * here for the M_FLUSH that we originated in IP
27104 			 * before sending the unbind request to the driver.
27105 			 * Just free it as we don't queue packets in IP
27106 			 * on the write side of the device instance.
27107 			 */
27108 			freemsg(mp);
27109 			return;
27110 		}
27111 		if (*mp->b_rptr & FLUSHR) {
27112 			*mp->b_rptr &= ~FLUSHW;
27113 			qreply(q, mp);
27114 			return;
27115 		}
27116 		freemsg(mp);
27117 		return;
27118 	case IRE_DB_REQ_TYPE:
27119 		/* An Upper Level Protocol wants a copy of an IRE. */
27120 		ip_ire_req(q, mp);
27121 		return;
27122 	case M_CTL:
27123 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27124 			break;
27125 
27126 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27127 		    TUN_HELLO) {
27128 			ASSERT(connp != NULL);
27129 			connp->conn_flags |= IPCL_IPTUN;
27130 			freeb(mp);
27131 			return;
27132 		}
27133 
27134 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27135 		    IP_ULP_OUT_LABELED) {
27136 			out_labeled_t *olp;
27137 
27138 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27139 				break;
27140 			olp = (out_labeled_t *)mp->b_rptr;
27141 			connp->conn_ulp_labeled = olp->out_qnext == q;
27142 			freemsg(mp);
27143 			return;
27144 		}
27145 
27146 		/* M_CTL messages are used by ARP to tell us things. */
27147 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27148 			break;
27149 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27150 		case AR_ENTRY_SQUERY:
27151 			ip_wput_ctl(q, mp);
27152 			return;
27153 		case AR_CLIENT_NOTIFY:
27154 			ip_arp_news(q, mp);
27155 			return;
27156 		case AR_DLPIOP_DONE:
27157 			ASSERT(q->q_next != NULL);
27158 			ill = (ill_t *)q->q_ptr;
27159 			/* qwriter_ip releases the refhold */
27160 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27161 			ill_refhold(ill);
27162 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
27163 			    CUR_OP, B_FALSE);
27164 			return;
27165 		case AR_ARP_CLOSING:
27166 			/*
27167 			 * ARP (above us) is closing. If no ARP bringup is
27168 			 * currently pending, ack the message so that ARP
27169 			 * can complete its close. Also mark ill_arp_closing
27170 			 * so that new ARP bringups will fail. If any
27171 			 * ARP bringup is currently in progress, we will
27172 			 * ack this when the current ARP bringup completes.
27173 			 */
27174 			ASSERT(q->q_next != NULL);
27175 			ill = (ill_t *)q->q_ptr;
27176 			mutex_enter(&ill->ill_lock);
27177 			ill->ill_arp_closing = 1;
27178 			if (!ill->ill_arp_bringup_pending) {
27179 				mutex_exit(&ill->ill_lock);
27180 				qreply(q, mp);
27181 			} else {
27182 				mutex_exit(&ill->ill_lock);
27183 				freemsg(mp);
27184 			}
27185 			return;
27186 		case AR_ARP_EXTEND:
27187 			/*
27188 			 * The ARP module above us is capable of duplicate
27189 			 * address detection.  Old ATM drivers will not send
27190 			 * this message.
27191 			 */
27192 			ASSERT(q->q_next != NULL);
27193 			ill = (ill_t *)q->q_ptr;
27194 			ill->ill_arp_extend = B_TRUE;
27195 			freemsg(mp);
27196 			return;
27197 		default:
27198 			break;
27199 		}
27200 		break;
27201 	case M_PROTO:
27202 	case M_PCPROTO:
27203 		/*
27204 		 * The only PROTO messages we expect are ULP binds and
27205 		 * copies of option negotiation acknowledgements.
27206 		 */
27207 		switch (((union T_primitives *)mp->b_rptr)->type) {
27208 		case O_T_BIND_REQ:
27209 		case T_BIND_REQ: {
27210 			/* Request can get queued in bind */
27211 			ASSERT(connp != NULL);
27212 			/*
27213 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27214 			 * instead of going through this path.  We only get
27215 			 * here in the following cases:
27216 			 *
27217 			 * a. Bind retries, where ipsq is non-NULL.
27218 			 * b. T_BIND_REQ is issued from non TCP/UDP
27219 			 *    transport, e.g. icmp for raw socket,
27220 			 *    in which case ipsq will be NULL.
27221 			 */
27222 			ASSERT(ipsq != NULL ||
27223 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27224 
27225 			/* Don't increment refcnt if this is a re-entry */
27226 			if (ipsq == NULL)
27227 				CONN_INC_REF(connp);
27228 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27229 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27230 			if (mp == NULL)
27231 				return;
27232 			if (IPCL_IS_TCP(connp)) {
27233 				/*
27234 				 * In the case of TCP endpoint we
27235 				 * come here only for bind retries
27236 				 */
27237 				ASSERT(ipsq != NULL);
27238 				CONN_INC_REF(connp);
27239 				squeue_fill(connp->conn_sqp, mp,
27240 				    ip_resume_tcp_bind, connp,
27241 				    SQTAG_BIND_RETRY);
27242 				return;
27243 			} else if (IPCL_IS_UDP(connp)) {
27244 				/*
27245 				 * In the case of UDP endpoint we
27246 				 * come here only for bind retries
27247 				 */
27248 				ASSERT(ipsq != NULL);
27249 				udp_resume_bind(connp, mp);
27250 				return;
27251 			}
27252 			qreply(q, mp);
27253 			CONN_OPER_PENDING_DONE(connp);
27254 			return;
27255 		}
27256 		case T_SVR4_OPTMGMT_REQ:
27257 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27258 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27259 
27260 			ASSERT(connp != NULL);
27261 			if (!snmpcom_req(q, mp, ip_snmp_set,
27262 			    ip_snmp_get, cr)) {
27263 				/*
27264 				 * Call svr4_optcom_req so that it can
27265 				 * generate the ack. We don't come here
27266 				 * if this operation is being restarted.
27267 				 * ip_restart_optmgmt will drop the conn ref.
27268 				 * In the case of ipsec option after the ipsec
27269 				 * load is complete conn_restart_ipsec_waiter
27270 				 * drops the conn ref.
27271 				 */
27272 				ASSERT(ipsq == NULL);
27273 				CONN_INC_REF(connp);
27274 				if (ip_check_for_ipsec_opt(q, mp))
27275 					return;
27276 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27277 				if (err != EINPROGRESS) {
27278 					/* Operation is done */
27279 					CONN_OPER_PENDING_DONE(connp);
27280 				}
27281 			}
27282 			return;
27283 		case T_OPTMGMT_REQ:
27284 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27285 			/*
27286 			 * Note: No snmpcom_req support through new
27287 			 * T_OPTMGMT_REQ.
27288 			 * Call tpi_optcom_req so that it can
27289 			 * generate the ack.
27290 			 */
27291 			ASSERT(connp != NULL);
27292 			ASSERT(ipsq == NULL);
27293 			/*
27294 			 * We don't come here for restart. ip_restart_optmgmt
27295 			 * will drop the conn ref. In the case of ipsec option
27296 			 * after the ipsec load is complete
27297 			 * conn_restart_ipsec_waiter drops the conn ref.
27298 			 */
27299 			CONN_INC_REF(connp);
27300 			if (ip_check_for_ipsec_opt(q, mp))
27301 				return;
27302 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27303 			if (err != EINPROGRESS) {
27304 				/* Operation is done */
27305 				CONN_OPER_PENDING_DONE(connp);
27306 			}
27307 			return;
27308 		case T_UNBIND_REQ:
27309 			mp = ip_unbind(q, mp);
27310 			qreply(q, mp);
27311 			return;
27312 		default:
27313 			/*
27314 			 * Have to drop any DLPI messages coming down from
27315 			 * arp (such as an info_req which would cause ip
27316 			 * to receive an extra info_ack if it was passed
27317 			 * through.
27318 			 */
27319 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27320 			    (int)*(uint_t *)mp->b_rptr));
27321 			freemsg(mp);
27322 			return;
27323 		}
27324 		/* NOTREACHED */
27325 	case IRE_DB_TYPE: {
27326 		nce_t		*nce;
27327 		ill_t		*ill;
27328 		in6_addr_t	gw_addr_v6;
27329 
27330 
27331 		/*
27332 		 * This is a response back from a resolver.  It
27333 		 * consists of a message chain containing:
27334 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27335 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27336 		 * The LL_HDR_MBLK is the DLPI header to use to get
27337 		 * the attached packet, and subsequent ones for the
27338 		 * same destination, transmitted.
27339 		 */
27340 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27341 			break;
27342 		/*
27343 		 * First, check to make sure the resolution succeeded.
27344 		 * If it failed, the second mblk will be empty.
27345 		 * If it is, free the chain, dropping the packet.
27346 		 * (We must ire_delete the ire; that frees the ire mblk)
27347 		 * We're doing this now to support PVCs for ATM; it's
27348 		 * a partial xresolv implementation. When we fully implement
27349 		 * xresolv interfaces, instead of freeing everything here
27350 		 * we'll initiate neighbor discovery.
27351 		 *
27352 		 * For v4 (ARP and other external resolvers) the resolver
27353 		 * frees the message, so no check is needed. This check
27354 		 * is required, though, for a full xresolve implementation.
27355 		 * Including this code here now both shows how external
27356 		 * resolvers can NACK a resolution request using an
27357 		 * existing design that has no specific provisions for NACKs,
27358 		 * and also takes into account that the current non-ARP
27359 		 * external resolver has been coded to use this method of
27360 		 * NACKing for all IPv6 (xresolv) cases,
27361 		 * whether our xresolv implementation is complete or not.
27362 		 *
27363 		 */
27364 		ire = (ire_t *)mp->b_rptr;
27365 		ill = ire_to_ill(ire);
27366 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27367 		if (mp1->b_rptr == mp1->b_wptr) {
27368 			if (ire->ire_ipversion == IPV6_VERSION) {
27369 				/*
27370 				 * XRESOLV interface.
27371 				 */
27372 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27373 				mutex_enter(&ire->ire_lock);
27374 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27375 				mutex_exit(&ire->ire_lock);
27376 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27377 					nce = ndp_lookup_v6(ill,
27378 					    &ire->ire_addr_v6, B_FALSE);
27379 				} else {
27380 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27381 					    B_FALSE);
27382 				}
27383 				if (nce != NULL) {
27384 					nce_resolv_failed(nce);
27385 					ndp_delete(nce);
27386 					NCE_REFRELE(nce);
27387 				}
27388 			}
27389 			mp->b_cont = NULL;
27390 			freemsg(mp1);		/* frees the pkt as well */
27391 			ASSERT(ire->ire_nce == NULL);
27392 			ire_delete((ire_t *)mp->b_rptr);
27393 			return;
27394 		}
27395 
27396 		/*
27397 		 * Split them into IRE_MBLK and pkt and feed it into
27398 		 * ire_add_then_send. Then in ire_add_then_send
27399 		 * the IRE will be added, and then the packet will be
27400 		 * run back through ip_wput. This time it will make
27401 		 * it to the wire.
27402 		 */
27403 		mp->b_cont = NULL;
27404 		mp = mp1->b_cont;		/* now, mp points to pkt */
27405 		mp1->b_cont = NULL;
27406 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27407 		if (ire->ire_ipversion == IPV6_VERSION) {
27408 			/*
27409 			 * XRESOLV interface. Find the nce and put a copy
27410 			 * of the dl_unitdata_req in nce_res_mp
27411 			 */
27412 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27413 			mutex_enter(&ire->ire_lock);
27414 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27415 			mutex_exit(&ire->ire_lock);
27416 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27417 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27418 				    B_FALSE);
27419 			} else {
27420 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27421 			}
27422 			if (nce != NULL) {
27423 				/*
27424 				 * We have to protect nce_res_mp here
27425 				 * from being accessed by other threads
27426 				 * while we change the mblk pointer.
27427 				 * Other functions will also lock the nce when
27428 				 * accessing nce_res_mp.
27429 				 *
27430 				 * The reason we change the mblk pointer
27431 				 * here rather than copying the resolved address
27432 				 * into the template is that, unlike with
27433 				 * ethernet, we have no guarantee that the
27434 				 * resolved address length will be
27435 				 * smaller than or equal to the lla length
27436 				 * with which the template was allocated,
27437 				 * (for ethernet, they're equal)
27438 				 * so we have to use the actual resolved
27439 				 * address mblk - which holds the real
27440 				 * dl_unitdata_req with the resolved address.
27441 				 *
27442 				 * Doing this is the same behavior as was
27443 				 * previously used in the v4 ARP case.
27444 				 */
27445 				mutex_enter(&nce->nce_lock);
27446 				if (nce->nce_res_mp != NULL)
27447 					freemsg(nce->nce_res_mp);
27448 				nce->nce_res_mp = mp1;
27449 				mutex_exit(&nce->nce_lock);
27450 				/*
27451 				 * We do a fastpath probe here because
27452 				 * we have resolved the address without
27453 				 * using Neighbor Discovery.
27454 				 * In the non-XRESOLV v6 case, the fastpath
27455 				 * probe is done right after neighbor
27456 				 * discovery completes.
27457 				 */
27458 				if (nce->nce_res_mp != NULL) {
27459 					int res;
27460 					nce_fastpath_list_add(nce);
27461 					res = ill_fastpath_probe(ill,
27462 					    nce->nce_res_mp);
27463 					if (res != 0 && res != EAGAIN)
27464 						nce_fastpath_list_delete(nce);
27465 				}
27466 
27467 				ire_add_then_send(q, ire, mp);
27468 				/*
27469 				 * Now we have to clean out any packets
27470 				 * that may have been queued on the nce
27471 				 * while it was waiting for address resolution
27472 				 * to complete.
27473 				 */
27474 				mutex_enter(&nce->nce_lock);
27475 				mp1 = nce->nce_qd_mp;
27476 				nce->nce_qd_mp = NULL;
27477 				mutex_exit(&nce->nce_lock);
27478 				while (mp1 != NULL) {
27479 					mblk_t *nxt_mp;
27480 					queue_t *fwdq = NULL;
27481 					ill_t   *inbound_ill;
27482 					uint_t ifindex;
27483 
27484 					nxt_mp = mp1->b_next;
27485 					mp1->b_next = NULL;
27486 					/*
27487 					 * Retrieve ifindex stored in
27488 					 * ip_rput_data_v6()
27489 					 */
27490 					ifindex =
27491 					    (uint_t)(uintptr_t)mp1->b_prev;
27492 					inbound_ill =
27493 						ill_lookup_on_ifindex(ifindex,
27494 						    B_TRUE, NULL, NULL, NULL,
27495 						    NULL);
27496 					mp1->b_prev = NULL;
27497 					if (inbound_ill != NULL)
27498 						fwdq = inbound_ill->ill_rq;
27499 
27500 					if (fwdq != NULL) {
27501 						put(fwdq, mp1);
27502 						ill_refrele(inbound_ill);
27503 					} else
27504 						put(WR(ill->ill_rq), mp1);
27505 					mp1 = nxt_mp;
27506 				}
27507 				NCE_REFRELE(nce);
27508 			} else {	/* nce is NULL; clean up */
27509 				ire_delete(ire);
27510 				freemsg(mp);
27511 				freemsg(mp1);
27512 				return;
27513 			}
27514 		} else {
27515 			nce_t *arpce;
27516 			/*
27517 			 * Link layer resolution succeeded. Recompute the
27518 			 * ire_nce.
27519 			 */
27520 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27521 			if ((arpce = ndp_lookup_v4(ill,
27522 			    (ire->ire_gateway_addr != INADDR_ANY ?
27523 			    &ire->ire_gateway_addr : &ire->ire_addr),
27524 			    B_FALSE)) == NULL) {
27525 				freeb(ire->ire_mp);
27526 				freeb(mp1);
27527 				freemsg(mp);
27528 				return;
27529 			}
27530 			mutex_enter(&arpce->nce_lock);
27531 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27532 			if (arpce->nce_state == ND_REACHABLE) {
27533 				/*
27534 				 * Someone resolved this before us;
27535 				 * cleanup the res_mp. Since ire has
27536 				 * not been added yet, the call to ire_add_v4
27537 				 * from ire_add_then_send (when a dup is
27538 				 * detected) will clean up the ire.
27539 				 */
27540 				freeb(mp1);
27541 			} else {
27542 				if (arpce->nce_res_mp != NULL)
27543 					freemsg(arpce->nce_res_mp);
27544 				arpce->nce_res_mp = mp1;
27545 				arpce->nce_state = ND_REACHABLE;
27546 			}
27547 			mutex_exit(&arpce->nce_lock);
27548 			if (ire->ire_marks & IRE_MARK_NOADD) {
27549 				/*
27550 				 * this ire will not be added to the ire
27551 				 * cache table, so we can set the ire_nce
27552 				 * here, as there are no atomicity constraints.
27553 				 */
27554 				ire->ire_nce = arpce;
27555 				/*
27556 				 * We are associating this nce with the ire
27557 				 * so change the nce ref taken in
27558 				 * ndp_lookup_v4() from
27559 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27560 				 */
27561 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27562 			} else {
27563 				NCE_REFRELE(arpce);
27564 			}
27565 			ire_add_then_send(q, ire, mp);
27566 		}
27567 		return;	/* All is well, the packet has been sent. */
27568 	}
27569 	case IRE_ARPRESOLVE_TYPE: {
27570 
27571 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27572 			break;
27573 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27574 		mp->b_cont = NULL;
27575 		/*
27576 		 * First, check to make sure the resolution succeeded.
27577 		 * If it failed, the second mblk will be empty.
27578 		 */
27579 		if (mp1->b_rptr == mp1->b_wptr) {
27580 			/* cleanup  the incomplete ire, free queued packets */
27581 			freemsg(mp); /* fake ire */
27582 			freeb(mp1);  /* dl_unitdata response */
27583 			return;
27584 		}
27585 
27586 		/*
27587 		 * update any incomplete nce_t found. we lookup the ctable
27588 		 * and find the nce from the ire->ire_nce because we need
27589 		 * to pass the ire to ip_xmit_v4 later, and can find both
27590 		 * ire and nce in one lookup from the ctable.
27591 		 */
27592 		fake_ire = (ire_t *)mp->b_rptr;
27593 		/*
27594 		 * By the time we come back here from ARP
27595 		 * the logical outgoing interface  of the incomplete ire
27596 		 * we added in ire_forward could have disappeared,
27597 		 * causing the incomplete ire to also have
27598 		 * dissapeared. So we need to retreive the
27599 		 * proper ipif for the ire  before looking
27600 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27601 		 */
27602 		ill = q->q_ptr;
27603 
27604 		/* Get the outgoing ipif */
27605 		mutex_enter(&ill->ill_lock);
27606 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27607 			mutex_exit(&ill->ill_lock);
27608 			freemsg(mp); /* fake ire */
27609 			freeb(mp1);  /* dl_unitdata response */
27610 			return;
27611 		}
27612 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27613 
27614 		if (ipif == NULL) {
27615 			mutex_exit(&ill->ill_lock);
27616 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27617 			freemsg(mp);
27618 			freeb(mp1);
27619 			return;
27620 		}
27621 		ipif_refhold_locked(ipif);
27622 		mutex_exit(&ill->ill_lock);
27623 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27624 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27625 		    ipif, fake_ire->ire_zoneid, NULL,
27626 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
27627 		ipif_refrele(ipif);
27628 		if (ire == NULL) {
27629 			/*
27630 			 * no ire was found; check if there is an nce
27631 			 * for this lookup; if it has no ire's pointing at it
27632 			 * cleanup.
27633 			 */
27634 			if ((nce = ndp_lookup_v4(ill,
27635 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27636 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27637 			    B_FALSE)) != NULL) {
27638 				/*
27639 				 * cleanup: just reset nce.
27640 				 * We check for refcnt 2 (one for the nce
27641 				 * hash list + 1 for the ref taken by
27642 				 * ndp_lookup_v4) to ensure that there are
27643 				 * no ire's pointing at the nce.
27644 				 */
27645 				if (nce->nce_refcnt == 2) {
27646 					nce = nce_reinit(nce);
27647 				}
27648 				if (nce != NULL)
27649 					NCE_REFRELE(nce);
27650 			}
27651 			freeb(mp1);  /* dl_unitdata response */
27652 			freemsg(mp); /* fake ire */
27653 			return;
27654 		}
27655 		nce = ire->ire_nce;
27656 		DTRACE_PROBE2(ire__arpresolve__type,
27657 		    ire_t *, ire, nce_t *, nce);
27658 		ASSERT(nce->nce_state != ND_INITIAL);
27659 		mutex_enter(&nce->nce_lock);
27660 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27661 		if (nce->nce_state == ND_REACHABLE) {
27662 			/*
27663 			 * Someone resolved this before us;
27664 			 * our response is not needed any more.
27665 			 */
27666 			mutex_exit(&nce->nce_lock);
27667 			freeb(mp1);  /* dl_unitdata response */
27668 		} else {
27669 			if (nce->nce_res_mp != NULL) {
27670 				freemsg(nce->nce_res_mp);
27671 				/* existing dl_unitdata template */
27672 			}
27673 			nce->nce_res_mp = mp1;
27674 			nce->nce_state = ND_REACHABLE;
27675 			mutex_exit(&nce->nce_lock);
27676 			ire_fastpath(ire);
27677 		}
27678 		/*
27679 		 * The cached nce_t has been updated to be reachable;
27680 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
27681 		 */
27682 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27683 		freemsg(mp);
27684 		/*
27685 		 * send out queued packets.
27686 		 */
27687 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27688 
27689 		IRE_REFRELE(ire);
27690 		return;
27691 	}
27692 	default:
27693 		break;
27694 	}
27695 	if (q->q_next) {
27696 		putnext(q, mp);
27697 	} else
27698 		freemsg(mp);
27699 }
27700 
27701 /*
27702  * Process IP options in an outbound packet.  Modify the destination if there
27703  * is a source route option.
27704  * Returns non-zero if something fails in which case an ICMP error has been
27705  * sent and mp freed.
27706  */
27707 static int
27708 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27709     boolean_t mctl_present, zoneid_t zoneid)
27710 {
27711 	ipoptp_t	opts;
27712 	uchar_t		*opt;
27713 	uint8_t		optval;
27714 	uint8_t		optlen;
27715 	ipaddr_t	dst;
27716 	intptr_t	code = 0;
27717 	mblk_t		*mp;
27718 	ire_t		*ire = NULL;
27719 
27720 	ip2dbg(("ip_wput_options\n"));
27721 	mp = ipsec_mp;
27722 	if (mctl_present) {
27723 		mp = ipsec_mp->b_cont;
27724 	}
27725 
27726 	dst = ipha->ipha_dst;
27727 	for (optval = ipoptp_first(&opts, ipha);
27728 	    optval != IPOPT_EOL;
27729 	    optval = ipoptp_next(&opts)) {
27730 		opt = opts.ipoptp_cur;
27731 		optlen = opts.ipoptp_len;
27732 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27733 		    optval, optlen));
27734 		switch (optval) {
27735 			uint32_t off;
27736 		case IPOPT_SSRR:
27737 		case IPOPT_LSRR:
27738 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27739 				ip1dbg((
27740 				    "ip_wput_options: bad option offset\n"));
27741 				code = (char *)&opt[IPOPT_OLEN] -
27742 				    (char *)ipha;
27743 				goto param_prob;
27744 			}
27745 			off = opt[IPOPT_OFFSET];
27746 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27747 			    ntohl(dst)));
27748 			/*
27749 			 * For strict: verify that dst is directly
27750 			 * reachable.
27751 			 */
27752 			if (optval == IPOPT_SSRR) {
27753 				ire = ire_ftable_lookup(dst, 0, 0,
27754 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27755 				    MBLK_GETLABEL(mp),
27756 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
27757 				if (ire == NULL) {
27758 					ip1dbg(("ip_wput_options: SSRR not"
27759 					    " directly reachable: 0x%x\n",
27760 					    ntohl(dst)));
27761 					goto bad_src_route;
27762 				}
27763 				ire_refrele(ire);
27764 			}
27765 			break;
27766 		case IPOPT_RR:
27767 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27768 				ip1dbg((
27769 				    "ip_wput_options: bad option offset\n"));
27770 				code = (char *)&opt[IPOPT_OLEN] -
27771 				    (char *)ipha;
27772 				goto param_prob;
27773 			}
27774 			break;
27775 		case IPOPT_TS:
27776 			/*
27777 			 * Verify that length >=5 and that there is either
27778 			 * room for another timestamp or that the overflow
27779 			 * counter is not maxed out.
27780 			 */
27781 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27782 			if (optlen < IPOPT_MINLEN_IT) {
27783 				goto param_prob;
27784 			}
27785 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27786 				ip1dbg((
27787 				    "ip_wput_options: bad option offset\n"));
27788 				code = (char *)&opt[IPOPT_OFFSET] -
27789 				    (char *)ipha;
27790 				goto param_prob;
27791 			}
27792 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27793 			case IPOPT_TS_TSONLY:
27794 				off = IPOPT_TS_TIMELEN;
27795 				break;
27796 			case IPOPT_TS_TSANDADDR:
27797 			case IPOPT_TS_PRESPEC:
27798 			case IPOPT_TS_PRESPEC_RFC791:
27799 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27800 				break;
27801 			default:
27802 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27803 				    (char *)ipha;
27804 				goto param_prob;
27805 			}
27806 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27807 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27808 				/*
27809 				 * No room and the overflow counter is 15
27810 				 * already.
27811 				 */
27812 				goto param_prob;
27813 			}
27814 			break;
27815 		}
27816 	}
27817 
27818 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27819 		return (0);
27820 
27821 	ip1dbg(("ip_wput_options: error processing IP options."));
27822 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27823 
27824 param_prob:
27825 	/*
27826 	 * Since ip_wput() isn't close to finished, we fill
27827 	 * in enough of the header for credible error reporting.
27828 	 */
27829 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27830 		/* Failed */
27831 		freemsg(ipsec_mp);
27832 		return (-1);
27833 	}
27834 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid);
27835 	return (-1);
27836 
27837 bad_src_route:
27838 	/*
27839 	 * Since ip_wput() isn't close to finished, we fill
27840 	 * in enough of the header for credible error reporting.
27841 	 */
27842 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27843 		/* Failed */
27844 		freemsg(ipsec_mp);
27845 		return (-1);
27846 	}
27847 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
27848 	return (-1);
27849 }
27850 
27851 /*
27852  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27853  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27854  * thru /etc/system.
27855  */
27856 #define	CONN_MAXDRAINCNT	64
27857 
27858 static void
27859 conn_drain_init(void)
27860 {
27861 	int i;
27862 
27863 	conn_drain_list_cnt = conn_drain_nthreads;
27864 
27865 	if ((conn_drain_list_cnt == 0) ||
27866 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27867 		/*
27868 		 * Default value of the number of drainers is the
27869 		 * number of cpus, subject to maximum of 8 drainers.
27870 		 */
27871 		if (boot_max_ncpus != -1)
27872 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27873 		else
27874 			conn_drain_list_cnt = MIN(max_ncpus, 8);
27875 	}
27876 
27877 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
27878 	    KM_SLEEP);
27879 
27880 	for (i = 0; i < conn_drain_list_cnt; i++) {
27881 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
27882 		    MUTEX_DEFAULT, NULL);
27883 	}
27884 }
27885 
27886 static void
27887 conn_drain_fini(void)
27888 {
27889 	int i;
27890 
27891 	for (i = 0; i < conn_drain_list_cnt; i++)
27892 		mutex_destroy(&conn_drain_list[i].idl_lock);
27893 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
27894 	conn_drain_list = NULL;
27895 }
27896 
27897 /*
27898  * Note: For an overview of how flowcontrol is handled in IP please see the
27899  * IP Flowcontrol notes at the top of this file.
27900  *
27901  * Flow control has blocked us from proceeding. Insert the given conn in one
27902  * of the conn drain lists. These conn wq's will be qenabled later on when
27903  * STREAMS flow control does a backenable. conn_walk_drain will enable
27904  * the first conn in each of these drain lists. Each of these qenabled conns
27905  * in turn enables the next in the list, after it runs, or when it closes,
27906  * thus sustaining the drain process.
27907  *
27908  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27909  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27910  * running at any time, on a given conn, since there can be only 1 service proc
27911  * running on a queue at any time.
27912  */
27913 void
27914 conn_drain_insert(conn_t *connp)
27915 {
27916 	idl_t	*idl;
27917 	uint_t	index;
27918 
27919 	mutex_enter(&connp->conn_lock);
27920 	if (connp->conn_state_flags & CONN_CLOSING) {
27921 		/*
27922 		 * The conn is closing as a result of which CONN_CLOSING
27923 		 * is set. Return.
27924 		 */
27925 		mutex_exit(&connp->conn_lock);
27926 		return;
27927 	} else if (connp->conn_idl == NULL) {
27928 		/*
27929 		 * Assign the next drain list round robin. We dont' use
27930 		 * a lock, and thus it may not be strictly round robin.
27931 		 * Atomicity of load/stores is enough to make sure that
27932 		 * conn_drain_list_index is always within bounds.
27933 		 */
27934 		index = conn_drain_list_index;
27935 		ASSERT(index < conn_drain_list_cnt);
27936 		connp->conn_idl = &conn_drain_list[index];
27937 		index++;
27938 		if (index == conn_drain_list_cnt)
27939 			index = 0;
27940 		conn_drain_list_index = index;
27941 	}
27942 	mutex_exit(&connp->conn_lock);
27943 
27944 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27945 	if ((connp->conn_drain_prev != NULL) ||
27946 	    (connp->conn_state_flags & CONN_CLOSING)) {
27947 		/*
27948 		 * The conn is already in the drain list, OR
27949 		 * the conn is closing. We need to check again for
27950 		 * the closing case again since close can happen
27951 		 * after we drop the conn_lock, and before we
27952 		 * acquire the CONN_DRAIN_LIST_LOCK.
27953 		 */
27954 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27955 		return;
27956 	} else {
27957 		idl = connp->conn_idl;
27958 	}
27959 
27960 	/*
27961 	 * The conn is not in the drain list. Insert it at the
27962 	 * tail of the drain list. The drain list is circular
27963 	 * and doubly linked. idl_conn points to the 1st element
27964 	 * in the list.
27965 	 */
27966 	if (idl->idl_conn == NULL) {
27967 		idl->idl_conn = connp;
27968 		connp->conn_drain_next = connp;
27969 		connp->conn_drain_prev = connp;
27970 	} else {
27971 		conn_t *head = idl->idl_conn;
27972 
27973 		connp->conn_drain_next = head;
27974 		connp->conn_drain_prev = head->conn_drain_prev;
27975 		head->conn_drain_prev->conn_drain_next = connp;
27976 		head->conn_drain_prev = connp;
27977 	}
27978 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27979 }
27980 
27981 /*
27982  * This conn is closing, and we are called from ip_close. OR
27983  * This conn has been serviced by ip_wsrv, and we need to do the tail
27984  * processing.
27985  * If this conn is part of the drain list, we may need to sustain the drain
27986  * process by qenabling the next conn in the drain list. We may also need to
27987  * remove this conn from the list, if it is done.
27988  */
27989 static void
27990 conn_drain_tail(conn_t *connp, boolean_t closing)
27991 {
27992 	idl_t *idl;
27993 
27994 	/*
27995 	 * connp->conn_idl is stable at this point, and no lock is needed
27996 	 * to check it. If we are called from ip_close, close has already
27997 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27998 	 * called us only because conn_idl is non-null. If we are called thru
27999 	 * service, conn_idl could be null, but it cannot change because
28000 	 * service is single-threaded per queue, and there cannot be another
28001 	 * instance of service trying to call conn_drain_insert on this conn
28002 	 * now.
28003 	 */
28004 	ASSERT(!closing || (connp->conn_idl != NULL));
28005 
28006 	/*
28007 	 * If connp->conn_idl is null, the conn has not been inserted into any
28008 	 * drain list even once since creation of the conn. Just return.
28009 	 */
28010 	if (connp->conn_idl == NULL)
28011 		return;
28012 
28013 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28014 
28015 	if (connp->conn_drain_prev == NULL) {
28016 		/* This conn is currently not in the drain list.  */
28017 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28018 		return;
28019 	}
28020 	idl = connp->conn_idl;
28021 	if (idl->idl_conn_draining == connp) {
28022 		/*
28023 		 * This conn is the current drainer. If this is the last conn
28024 		 * in the drain list, we need to do more checks, in the 'if'
28025 		 * below. Otherwwise we need to just qenable the next conn,
28026 		 * to sustain the draining, and is handled in the 'else'
28027 		 * below.
28028 		 */
28029 		if (connp->conn_drain_next == idl->idl_conn) {
28030 			/*
28031 			 * This conn is the last in this list. This round
28032 			 * of draining is complete. If idl_repeat is set,
28033 			 * it means another flow enabling has happened from
28034 			 * the driver/streams and we need to another round
28035 			 * of draining.
28036 			 * If there are more than 2 conns in the drain list,
28037 			 * do a left rotate by 1, so that all conns except the
28038 			 * conn at the head move towards the head by 1, and the
28039 			 * the conn at the head goes to the tail. This attempts
28040 			 * a more even share for all queues that are being
28041 			 * drained.
28042 			 */
28043 			if ((connp->conn_drain_next != connp) &&
28044 			    (idl->idl_conn->conn_drain_next != connp)) {
28045 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28046 			}
28047 			if (idl->idl_repeat) {
28048 				qenable(idl->idl_conn->conn_wq);
28049 				idl->idl_conn_draining = idl->idl_conn;
28050 				idl->idl_repeat = 0;
28051 			} else {
28052 				idl->idl_conn_draining = NULL;
28053 			}
28054 		} else {
28055 			/*
28056 			 * If the next queue that we are now qenable'ing,
28057 			 * is closing, it will remove itself from this list
28058 			 * and qenable the subsequent queue in ip_close().
28059 			 * Serialization is acheived thru idl_lock.
28060 			 */
28061 			qenable(connp->conn_drain_next->conn_wq);
28062 			idl->idl_conn_draining = connp->conn_drain_next;
28063 		}
28064 	}
28065 	if (!connp->conn_did_putbq || closing) {
28066 		/*
28067 		 * Remove ourself from the drain list, if we did not do
28068 		 * a putbq, or if the conn is closing.
28069 		 * Note: It is possible that q->q_first is non-null. It means
28070 		 * that these messages landed after we did a enableok() in
28071 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28072 		 * service them.
28073 		 */
28074 		if (connp->conn_drain_next == connp) {
28075 			/* Singleton in the list */
28076 			ASSERT(connp->conn_drain_prev == connp);
28077 			idl->idl_conn = NULL;
28078 			idl->idl_conn_draining = NULL;
28079 		} else {
28080 			connp->conn_drain_prev->conn_drain_next =
28081 			    connp->conn_drain_next;
28082 			connp->conn_drain_next->conn_drain_prev =
28083 			    connp->conn_drain_prev;
28084 			if (idl->idl_conn == connp)
28085 				idl->idl_conn = connp->conn_drain_next;
28086 			ASSERT(idl->idl_conn_draining != connp);
28087 
28088 		}
28089 		connp->conn_drain_next = NULL;
28090 		connp->conn_drain_prev = NULL;
28091 	}
28092 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28093 }
28094 
28095 /*
28096  * Write service routine. Shared perimeter entry point.
28097  * ip_wsrv can be called in any of the following ways.
28098  * 1. The device queue's messages has fallen below the low water mark
28099  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28100  *    the drain lists and backenable the first conn in each list.
28101  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28102  *    qenabled non-tcp upper layers. We start dequeing messages and call
28103  *    ip_wput for each message.
28104  */
28105 
28106 void
28107 ip_wsrv(queue_t *q)
28108 {
28109 	conn_t	*connp;
28110 	ill_t	*ill;
28111 	mblk_t	*mp;
28112 
28113 	if (q->q_next) {
28114 		ill = (ill_t *)q->q_ptr;
28115 		if (ill->ill_state_flags == 0) {
28116 			/*
28117 			 * The device flow control has opened up.
28118 			 * Walk through conn drain lists and qenable the
28119 			 * first conn in each list. This makes sense only
28120 			 * if the stream is fully plumbed and setup.
28121 			 * Hence the if check above.
28122 			 */
28123 			ip1dbg(("ip_wsrv: walking\n"));
28124 			conn_walk_drain();
28125 		}
28126 		return;
28127 	}
28128 
28129 	connp = Q_TO_CONN(q);
28130 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28131 
28132 	/*
28133 	 * 1. Set conn_draining flag to signal that service is active.
28134 	 *
28135 	 * 2. ip_output determines whether it has been called from service,
28136 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28137 	 *    has been called from service.
28138 	 *
28139 	 * 3. Message ordering is preserved by the following logic.
28140 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28141 	 *    the message at the tail, if conn_draining is set (i.e. service
28142 	 *    is running) or if q->q_first is non-null.
28143 	 *
28144 	 *    ii. If ip_output is called from service, and if ip_output cannot
28145 	 *    putnext due to flow control, it does a putbq.
28146 	 *
28147 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28148 	 *    (causing an infinite loop).
28149 	 */
28150 	ASSERT(!connp->conn_did_putbq);
28151 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28152 		connp->conn_draining = 1;
28153 		noenable(q);
28154 		while ((mp = getq(q)) != NULL) {
28155 			ASSERT(CONN_Q(q));
28156 
28157 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28158 			if (connp->conn_did_putbq) {
28159 				/* ip_wput did a putbq */
28160 				break;
28161 			}
28162 		}
28163 		/*
28164 		 * At this point, a thread coming down from top, calling
28165 		 * ip_wput, may end up queueing the message. We have not yet
28166 		 * enabled the queue, so ip_wsrv won't be called again.
28167 		 * To avoid this race, check q->q_first again (in the loop)
28168 		 * If the other thread queued the message before we call
28169 		 * enableok(), we will catch it in the q->q_first check.
28170 		 * If the other thread queues the message after we call
28171 		 * enableok(), ip_wsrv will be called again by STREAMS.
28172 		 */
28173 		connp->conn_draining = 0;
28174 		enableok(q);
28175 	}
28176 
28177 	/* Enable the next conn for draining */
28178 	conn_drain_tail(connp, B_FALSE);
28179 
28180 	connp->conn_did_putbq = 0;
28181 }
28182 
28183 /*
28184  * Walk the list of all conn's calling the function provided with the
28185  * specified argument for each.	 Note that this only walks conn's that
28186  * have been bound.
28187  * Applies to both IPv4 and IPv6.
28188  */
28189 static void
28190 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
28191 {
28192 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
28193 	    func, arg, zoneid);
28194 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
28195 	    func, arg, zoneid);
28196 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
28197 	    func, arg, zoneid);
28198 	conn_walk_fanout_table(ipcl_proto_fanout,
28199 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
28200 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
28201 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
28202 }
28203 
28204 /*
28205  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28206  * of conns that need to be drained, check if drain is already in progress.
28207  * If so set the idl_repeat bit, indicating that the last conn in the list
28208  * needs to reinitiate the drain once again, for the list. If drain is not
28209  * in progress for the list, initiate the draining, by qenabling the 1st
28210  * conn in the list. The drain is self-sustaining, each qenabled conn will
28211  * in turn qenable the next conn, when it is done/blocked/closing.
28212  */
28213 static void
28214 conn_walk_drain(void)
28215 {
28216 	int i;
28217 	idl_t *idl;
28218 
28219 	IP_STAT(ip_conn_walk_drain);
28220 
28221 	for (i = 0; i < conn_drain_list_cnt; i++) {
28222 		idl = &conn_drain_list[i];
28223 		mutex_enter(&idl->idl_lock);
28224 		if (idl->idl_conn == NULL) {
28225 			mutex_exit(&idl->idl_lock);
28226 			continue;
28227 		}
28228 		/*
28229 		 * If this list is not being drained currently by
28230 		 * an ip_wsrv thread, start the process.
28231 		 */
28232 		if (idl->idl_conn_draining == NULL) {
28233 			ASSERT(idl->idl_repeat == 0);
28234 			qenable(idl->idl_conn->conn_wq);
28235 			idl->idl_conn_draining = idl->idl_conn;
28236 		} else {
28237 			idl->idl_repeat = 1;
28238 		}
28239 		mutex_exit(&idl->idl_lock);
28240 	}
28241 }
28242 
28243 /*
28244  * Walk an conn hash table of `count' buckets, calling func for each entry.
28245  */
28246 static void
28247 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28248     zoneid_t zoneid)
28249 {
28250 	conn_t	*connp;
28251 
28252 	while (count-- > 0) {
28253 		mutex_enter(&connfp->connf_lock);
28254 		for (connp = connfp->connf_head; connp != NULL;
28255 		    connp = connp->conn_next) {
28256 			if (zoneid == GLOBAL_ZONEID ||
28257 			    zoneid == connp->conn_zoneid) {
28258 				CONN_INC_REF(connp);
28259 				mutex_exit(&connfp->connf_lock);
28260 				(*func)(connp, arg);
28261 				mutex_enter(&connfp->connf_lock);
28262 				CONN_DEC_REF(connp);
28263 			}
28264 		}
28265 		mutex_exit(&connfp->connf_lock);
28266 		connfp++;
28267 	}
28268 }
28269 
28270 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28271 static void
28272 conn_report1(conn_t *connp, void *mp)
28273 {
28274 	char	buf1[INET6_ADDRSTRLEN];
28275 	char	buf2[INET6_ADDRSTRLEN];
28276 	uint_t	print_len, buf_len;
28277 
28278 	ASSERT(connp != NULL);
28279 
28280 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28281 	if (buf_len <= 0)
28282 		return;
28283 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
28284 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
28285 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28286 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28287 	    "%5d %s/%05d %s/%05d\n",
28288 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28289 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28290 	    buf1, connp->conn_lport,
28291 	    buf2, connp->conn_fport);
28292 	if (print_len < buf_len) {
28293 		((mblk_t *)mp)->b_wptr += print_len;
28294 	} else {
28295 		((mblk_t *)mp)->b_wptr += buf_len;
28296 	}
28297 }
28298 
28299 /*
28300  * Named Dispatch routine to produce a formatted report on all conns
28301  * that are listed in one of the fanout tables.
28302  * This report is accessed by using the ndd utility to "get" ND variable
28303  * "ip_conn_status".
28304  */
28305 /* ARGSUSED */
28306 static int
28307 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28308 {
28309 	(void) mi_mpprintf(mp,
28310 	    "CONN      " MI_COL_HDRPAD_STR
28311 	    "rfq      " MI_COL_HDRPAD_STR
28312 	    "stq      " MI_COL_HDRPAD_STR
28313 	    " zone local                 remote");
28314 
28315 	/*
28316 	 * Because of the ndd constraint, at most we can have 64K buffer
28317 	 * to put in all conn info.  So to be more efficient, just
28318 	 * allocate a 64K buffer here, assuming we need that large buffer.
28319 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28320 	 */
28321 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28322 		/* The following may work even if we cannot get a large buf. */
28323 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28324 		return (0);
28325 	}
28326 
28327 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
28328 	return (0);
28329 }
28330 
28331 /*
28332  * Determine if the ill and multicast aspects of that packets
28333  * "matches" the conn.
28334  */
28335 boolean_t
28336 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28337     zoneid_t zoneid)
28338 {
28339 	ill_t *in_ill;
28340 	boolean_t found;
28341 	ipif_t *ipif;
28342 	ire_t *ire;
28343 	ipaddr_t dst, src;
28344 
28345 	dst = ipha->ipha_dst;
28346 	src = ipha->ipha_src;
28347 
28348 	/*
28349 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28350 	 * unicast, broadcast and multicast reception to
28351 	 * conn_incoming_ill. conn_wantpacket itself is called
28352 	 * only for BROADCAST and multicast.
28353 	 *
28354 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28355 	 *    is part of a group. Hence, we should be receiving
28356 	 *    just one copy of broadcast for the whole group.
28357 	 *    Thus, if it is part of the group the packet could
28358 	 *    come on any ill of the group and hence we need a
28359 	 *    match on the group. Otherwise, match on ill should
28360 	 *    be sufficient.
28361 	 *
28362 	 * 2) ip_rput does not suppress duplicate multicast packets.
28363 	 *    If there are two interfaces in a ill group and we have
28364 	 *    2 applications (conns) joined a multicast group G on
28365 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28366 	 *    will give us two packets because we join G on both the
28367 	 *    interfaces rather than nominating just one interface
28368 	 *    for receiving multicast like broadcast above. So,
28369 	 *    we have to call ilg_lookup_ill to filter out duplicate
28370 	 *    copies, if ill is part of a group.
28371 	 */
28372 	in_ill = connp->conn_incoming_ill;
28373 	if (in_ill != NULL) {
28374 		if (in_ill->ill_group == NULL) {
28375 			if (in_ill != ill)
28376 				return (B_FALSE);
28377 		} else if (in_ill->ill_group != ill->ill_group) {
28378 			return (B_FALSE);
28379 		}
28380 	}
28381 
28382 	if (!CLASSD(dst)) {
28383 		if (IPCL_ZONE_MATCH(connp, zoneid))
28384 			return (B_TRUE);
28385 		/*
28386 		 * The conn is in a different zone; we need to check that this
28387 		 * broadcast address is configured in the application's zone and
28388 		 * on one ill in the group.
28389 		 */
28390 		ipif = ipif_get_next_ipif(NULL, ill);
28391 		if (ipif == NULL)
28392 			return (B_FALSE);
28393 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28394 		    connp->conn_zoneid, NULL,
28395 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
28396 		ipif_refrele(ipif);
28397 		if (ire != NULL) {
28398 			ire_refrele(ire);
28399 			return (B_TRUE);
28400 		} else {
28401 			return (B_FALSE);
28402 		}
28403 	}
28404 
28405 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28406 	    connp->conn_zoneid == zoneid) {
28407 		/*
28408 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28409 		 * disabled, therefore we don't dispatch the multicast packet to
28410 		 * the sending zone.
28411 		 */
28412 		return (B_FALSE);
28413 	}
28414 
28415 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
28416 	    connp->conn_zoneid != zoneid) {
28417 		/*
28418 		 * Multicast packet on the loopback interface: we only match
28419 		 * conns who joined the group in the specified zone.
28420 		 */
28421 		return (B_FALSE);
28422 	}
28423 
28424 	if (connp->conn_multi_router) {
28425 		/* multicast packet and multicast router socket: send up */
28426 		return (B_TRUE);
28427 	}
28428 
28429 	mutex_enter(&connp->conn_lock);
28430 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28431 	mutex_exit(&connp->conn_lock);
28432 	return (found);
28433 }
28434 
28435 /*
28436  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28437  */
28438 /* ARGSUSED */
28439 static void
28440 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28441 {
28442 	ill_t *ill = (ill_t *)q->q_ptr;
28443 	mblk_t	*mp1, *mp2;
28444 	ipif_t  *ipif;
28445 	int err = 0;
28446 	conn_t *connp = NULL;
28447 	ipsq_t	*ipsq;
28448 	arc_t	*arc;
28449 
28450 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28451 
28452 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28453 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28454 
28455 	ASSERT(IAM_WRITER_ILL(ill));
28456 	mp2 = mp->b_cont;
28457 	mp->b_cont = NULL;
28458 
28459 	/*
28460 	 * We have now received the arp bringup completion message
28461 	 * from ARP. Mark the arp bringup as done. Also if the arp
28462 	 * stream has already started closing, send up the AR_ARP_CLOSING
28463 	 * ack now since ARP is waiting in close for this ack.
28464 	 */
28465 	mutex_enter(&ill->ill_lock);
28466 	ill->ill_arp_bringup_pending = 0;
28467 	if (ill->ill_arp_closing) {
28468 		mutex_exit(&ill->ill_lock);
28469 		/* Let's reuse the mp for sending the ack */
28470 		arc = (arc_t *)mp->b_rptr;
28471 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28472 		arc->arc_cmd = AR_ARP_CLOSING;
28473 		qreply(q, mp);
28474 	} else {
28475 		mutex_exit(&ill->ill_lock);
28476 		freeb(mp);
28477 	}
28478 
28479 	ipsq = ill->ill_phyint->phyint_ipsq;
28480 	ipif = ipsq->ipsq_pending_ipif;
28481 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28482 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28483 	if (mp1 == NULL) {
28484 		/* bringup was aborted by the user */
28485 		freemsg(mp2);
28486 		return;
28487 	}
28488 
28489 	/*
28490 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28491 	 * must have an associated conn_t.  Otherwise, we're bringing this
28492 	 * interface back up as part of handling an asynchronous event (e.g.,
28493 	 * physical address change).
28494 	 */
28495 	if (ipsq->ipsq_current_ioctl != 0) {
28496 		ASSERT(connp != NULL);
28497 		q = CONNP_TO_WQ(connp);
28498 	} else {
28499 		ASSERT(connp == NULL);
28500 		q = ill->ill_rq;
28501 	}
28502 
28503 	/*
28504 	 * If the DL_BIND_REQ fails, it is noted
28505 	 * in arc_name_offset.
28506 	 */
28507 	err = *((int *)mp2->b_rptr);
28508 	if (err == 0) {
28509 		if (ipif->ipif_isv6) {
28510 			if ((err = ipif_up_done_v6(ipif)) != 0)
28511 				ip0dbg(("ip_arp_done: init failed\n"));
28512 		} else {
28513 			if ((err = ipif_up_done(ipif)) != 0)
28514 				ip0dbg(("ip_arp_done: init failed\n"));
28515 		}
28516 	} else {
28517 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28518 	}
28519 
28520 	freemsg(mp2);
28521 
28522 	if ((err == 0) && (ill->ill_up_ipifs)) {
28523 		err = ill_up_ipifs(ill, q, mp1);
28524 		if (err == EINPROGRESS)
28525 			return;
28526 	}
28527 
28528 	if (ill->ill_up_ipifs)
28529 		ill_group_cleanup(ill);
28530 
28531 	/*
28532 	 * The operation must complete without EINPROGRESS since
28533 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28534 	 * Otherwise, the operation will be stuck forever in the ipsq.
28535 	 */
28536 	ASSERT(err != EINPROGRESS);
28537 	if (ipsq->ipsq_current_ioctl != 0)
28538 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28539 	else
28540 		ipsq_current_finish(ipsq);
28541 }
28542 
28543 /* Allocate the private structure */
28544 static int
28545 ip_priv_alloc(void **bufp)
28546 {
28547 	void	*buf;
28548 
28549 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28550 		return (ENOMEM);
28551 
28552 	*bufp = buf;
28553 	return (0);
28554 }
28555 
28556 /* Function to delete the private structure */
28557 void
28558 ip_priv_free(void *buf)
28559 {
28560 	ASSERT(buf != NULL);
28561 	kmem_free(buf, sizeof (ip_priv_t));
28562 }
28563 
28564 /*
28565  * The entry point for IPPF processing.
28566  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28567  * routine just returns.
28568  *
28569  * When called, ip_process generates an ipp_packet_t structure
28570  * which holds the state information for this packet and invokes the
28571  * the classifier (via ipp_packet_process). The classification, depending on
28572  * configured filters, results in a list of actions for this packet. Invoking
28573  * an action may cause the packet to be dropped, in which case the resulting
28574  * mblk (*mpp) is NULL. proc indicates the callout position for
28575  * this packet and ill_index is the interface this packet on or will leave
28576  * on (inbound and outbound resp.).
28577  */
28578 void
28579 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28580 {
28581 	mblk_t		*mp;
28582 	ip_priv_t	*priv;
28583 	ipp_action_id_t	aid;
28584 	int		rc = 0;
28585 	ipp_packet_t	*pp;
28586 #define	IP_CLASS	"ip"
28587 
28588 	/* If the classifier is not loaded, return  */
28589 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28590 		return;
28591 	}
28592 
28593 	mp = *mpp;
28594 	ASSERT(mp != NULL);
28595 
28596 	/* Allocate the packet structure */
28597 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28598 	if (rc != 0) {
28599 		*mpp = NULL;
28600 		freemsg(mp);
28601 		return;
28602 	}
28603 
28604 	/* Allocate the private structure */
28605 	rc = ip_priv_alloc((void **)&priv);
28606 	if (rc != 0) {
28607 		*mpp = NULL;
28608 		freemsg(mp);
28609 		ipp_packet_free(pp);
28610 		return;
28611 	}
28612 	priv->proc = proc;
28613 	priv->ill_index = ill_index;
28614 	ipp_packet_set_private(pp, priv, ip_priv_free);
28615 	ipp_packet_set_data(pp, mp);
28616 
28617 	/* Invoke the classifier */
28618 	rc = ipp_packet_process(&pp);
28619 	if (pp != NULL) {
28620 		mp = ipp_packet_get_data(pp);
28621 		ipp_packet_free(pp);
28622 		if (rc != 0) {
28623 			freemsg(mp);
28624 			*mpp = NULL;
28625 		}
28626 	} else {
28627 		*mpp = NULL;
28628 	}
28629 #undef	IP_CLASS
28630 }
28631 
28632 /*
28633  * Propagate a multicast group membership operation (add/drop) on
28634  * all the interfaces crossed by the related multirt routes.
28635  * The call is considered successful if the operation succeeds
28636  * on at least one interface.
28637  */
28638 static int
28639 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28640     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28641     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28642     mblk_t *first_mp)
28643 {
28644 	ire_t		*ire_gw;
28645 	irb_t		*irb;
28646 	int		error = 0;
28647 	opt_restart_t	*or;
28648 
28649 	irb = ire->ire_bucket;
28650 	ASSERT(irb != NULL);
28651 
28652 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28653 
28654 	or = (opt_restart_t *)first_mp->b_rptr;
28655 	IRB_REFHOLD(irb);
28656 	for (; ire != NULL; ire = ire->ire_next) {
28657 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28658 			continue;
28659 		if (ire->ire_addr != group)
28660 			continue;
28661 
28662 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28663 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28664 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
28665 		/* No resolver exists for the gateway; skip this ire. */
28666 		if (ire_gw == NULL)
28667 			continue;
28668 
28669 		/*
28670 		 * This function can return EINPROGRESS. If so the operation
28671 		 * will be restarted from ip_restart_optmgmt which will
28672 		 * call ip_opt_set and option processing will restart for
28673 		 * this option. So we may end up calling 'fn' more than once.
28674 		 * This requires that 'fn' is idempotent except for the
28675 		 * return value. The operation is considered a success if
28676 		 * it succeeds at least once on any one interface.
28677 		 */
28678 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28679 		    NULL, fmode, src, first_mp);
28680 		if (error == 0)
28681 			or->or_private = CGTP_MCAST_SUCCESS;
28682 
28683 		if (ip_debug > 0) {
28684 			ulong_t	off;
28685 			char	*ksym;
28686 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28687 			ip2dbg(("ip_multirt_apply_membership: "
28688 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28689 			    "error %d [success %u]\n",
28690 			    ksym ? ksym : "?",
28691 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28692 			    error, or->or_private));
28693 		}
28694 
28695 		ire_refrele(ire_gw);
28696 		if (error == EINPROGRESS) {
28697 			IRB_REFRELE(irb);
28698 			return (error);
28699 		}
28700 	}
28701 	IRB_REFRELE(irb);
28702 	/*
28703 	 * Consider the call as successful if we succeeded on at least
28704 	 * one interface. Otherwise, return the last encountered error.
28705 	 */
28706 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28707 }
28708 
28709 
28710 /*
28711  * Issue a warning regarding a route crossing an interface with an
28712  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28713  * amount of time is logged.
28714  */
28715 static void
28716 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28717 {
28718 	hrtime_t	current = gethrtime();
28719 	char		buf[INET_ADDRSTRLEN];
28720 
28721 	/* Convert interval in ms to hrtime in ns */
28722 	if (multirt_bad_mtu_last_time +
28723 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
28724 	    current) {
28725 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28726 		    "to %s, incorrect MTU %u (expected %u)\n",
28727 		    ip_dot_addr(ire->ire_addr, buf),
28728 		    ire->ire_max_frag, max_frag);
28729 
28730 		multirt_bad_mtu_last_time = current;
28731 	}
28732 }
28733 
28734 
28735 /*
28736  * Get the CGTP (multirouting) filtering status.
28737  * If 0, the CGTP hooks are transparent.
28738  */
28739 /* ARGSUSED */
28740 static int
28741 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28742 {
28743 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28744 
28745 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28746 	return (0);
28747 }
28748 
28749 
28750 /*
28751  * Set the CGTP (multirouting) filtering status.
28752  * If the status is changed from active to transparent
28753  * or from transparent to active, forward the new status
28754  * to the filtering module (if loaded).
28755  */
28756 /* ARGSUSED */
28757 static int
28758 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28759     cred_t *ioc_cr)
28760 {
28761 	long		new_value;
28762 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28763 
28764 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28765 	    new_value < 0 || new_value > 1) {
28766 		return (EINVAL);
28767 	}
28768 
28769 	/*
28770 	 * Do not enable CGTP filtering - thus preventing the hooks
28771 	 * from being invoked - if the version number of the
28772 	 * filtering module hooks does not match.
28773 	 */
28774 	if ((ip_cgtp_filter_ops != NULL) &&
28775 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
28776 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
28777 		    "(module hooks version %d, expecting %d)\n",
28778 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
28779 		return (ENOTSUP);
28780 	}
28781 
28782 	if ((!*ip_cgtp_filter_value) && new_value) {
28783 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28784 		    ip_cgtp_filter_ops == NULL ?
28785 		    " (module not loaded)" : "");
28786 	}
28787 	if (*ip_cgtp_filter_value && (!new_value)) {
28788 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28789 		    ip_cgtp_filter_ops == NULL ?
28790 		    " (module not loaded)" : "");
28791 	}
28792 
28793 	if (ip_cgtp_filter_ops != NULL) {
28794 		int	res;
28795 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
28796 			return (res);
28797 		}
28798 	}
28799 
28800 	*ip_cgtp_filter_value = (boolean_t)new_value;
28801 
28802 	return (0);
28803 }
28804 
28805 
28806 /*
28807  * Return the expected CGTP hooks version number.
28808  */
28809 int
28810 ip_cgtp_filter_supported(void)
28811 {
28812 	return (ip_cgtp_filter_rev);
28813 }
28814 
28815 
28816 /*
28817  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
28818  * or by invoking this function. In the first case, the version number
28819  * of the registered structure is checked at hooks activation time
28820  * in ip_cgtp_filter_set().
28821  */
28822 int
28823 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
28824 {
28825 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28826 		return (ENOTSUP);
28827 
28828 	ip_cgtp_filter_ops = ops;
28829 	return (0);
28830 }
28831 
28832 static squeue_func_t
28833 ip_squeue_switch(int val)
28834 {
28835 	squeue_func_t rval = squeue_fill;
28836 
28837 	switch (val) {
28838 	case IP_SQUEUE_ENTER_NODRAIN:
28839 		rval = squeue_enter_nodrain;
28840 		break;
28841 	case IP_SQUEUE_ENTER:
28842 		rval = squeue_enter;
28843 		break;
28844 	default:
28845 		break;
28846 	}
28847 	return (rval);
28848 }
28849 
28850 /* ARGSUSED */
28851 static int
28852 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28853     caddr_t addr, cred_t *cr)
28854 {
28855 	int *v = (int *)addr;
28856 	long new_value;
28857 
28858 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28859 		return (EINVAL);
28860 
28861 	ip_input_proc = ip_squeue_switch(new_value);
28862 	*v = new_value;
28863 	return (0);
28864 }
28865 
28866 /* ARGSUSED */
28867 static int
28868 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28869     caddr_t addr, cred_t *cr)
28870 {
28871 	int *v = (int *)addr;
28872 	long new_value;
28873 
28874 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28875 		return (EINVAL);
28876 
28877 	*v = new_value;
28878 	return (0);
28879 }
28880 
28881 static void
28882 ip_kstat_init(void)
28883 {
28884 	ip_named_kstat_t template = {
28885 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
28886 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
28887 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
28888 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
28889 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
28890 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
28891 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
28892 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
28893 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
28894 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
28895 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
28896 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
28897 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
28898 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
28899 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
28900 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
28901 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
28902 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
28903 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
28904 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
28905 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
28906 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
28907 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
28908 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
28909 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
28910 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
28911 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
28912 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
28913 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
28914 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
28915 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
28916 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
28917 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
28918 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
28919 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
28920 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
28921 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
28922 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
28923 	};
28924 
28925 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
28926 					NUM_OF_FIELDS(ip_named_kstat_t),
28927 					0);
28928 	if (!ip_mibkp)
28929 		return;
28930 
28931 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
28932 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
28933 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
28934 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
28935 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
28936 
28937 	template.netToMediaEntrySize.value.i32 =
28938 		sizeof (mib2_ipNetToMediaEntry_t);
28939 
28940 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
28941 
28942 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
28943 
28944 	ip_mibkp->ks_update = ip_kstat_update;
28945 
28946 	kstat_install(ip_mibkp);
28947 }
28948 
28949 static void
28950 ip_kstat_fini(void)
28951 {
28952 
28953 	if (ip_mibkp != NULL) {
28954 		kstat_delete(ip_mibkp);
28955 		ip_mibkp = NULL;
28956 	}
28957 }
28958 
28959 static int
28960 ip_kstat_update(kstat_t *kp, int rw)
28961 {
28962 	ip_named_kstat_t *ipkp;
28963 	mib2_ipIfStatsEntry_t ipmib;
28964 	ill_walk_context_t ctx;
28965 	ill_t *ill;
28966 
28967 	if (!kp || !kp->ks_data)
28968 		return (EIO);
28969 
28970 	if (rw == KSTAT_WRITE)
28971 		return (EACCES);
28972 
28973 	ipkp = (ip_named_kstat_t *)kp->ks_data;
28974 
28975 	bcopy(&ip_mib, &ipmib, sizeof (ipmib));
28976 	rw_enter(&ill_g_lock, RW_READER);
28977 	ill = ILL_START_WALK_V4(&ctx);
28978 	for (; ill != NULL; ill = ill_next(&ctx, ill))
28979 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
28980 	rw_exit(&ill_g_lock);
28981 
28982 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
28983 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
28984 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
28985 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
28986 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
28987 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
28988 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
28989 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
28990 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
28991 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
28992 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
28993 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
28994 	ipkp->reasmTimeout.value.ui32 =		ip_g_frag_timeout;
28995 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
28996 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
28997 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
28998 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
28999 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29000 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29001 
29002 	ipkp->routingDiscards.value.ui32 =	0;
29003 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29004 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29005 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29006 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29007 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29008 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29009 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29010 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29011 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29012 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29013 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29014 
29015 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29016 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29017 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29018 
29019 	return (0);
29020 }
29021 
29022 static void
29023 icmp_kstat_init(void)
29024 {
29025 	icmp_named_kstat_t template = {
29026 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29027 		{ "inErrors",		KSTAT_DATA_UINT32 },
29028 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29029 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29030 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29031 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29032 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29033 		{ "inEchos",		KSTAT_DATA_UINT32 },
29034 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29035 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29036 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29037 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29038 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29039 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29040 		{ "outErrors",		KSTAT_DATA_UINT32 },
29041 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29042 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29043 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29044 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29045 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29046 		{ "outEchos",		KSTAT_DATA_UINT32 },
29047 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29048 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29049 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29050 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29051 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29052 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29053 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29054 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29055 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29056 		{ "outDrops",		KSTAT_DATA_UINT32 },
29057 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29058 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29059 	};
29060 
29061 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29062 					NUM_OF_FIELDS(icmp_named_kstat_t),
29063 					0);
29064 	if (icmp_mibkp == NULL)
29065 		return;
29066 
29067 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
29068 
29069 	icmp_mibkp->ks_update = icmp_kstat_update;
29070 
29071 	kstat_install(icmp_mibkp);
29072 }
29073 
29074 static void
29075 icmp_kstat_fini(void)
29076 {
29077 
29078 	if (icmp_mibkp != NULL) {
29079 		kstat_delete(icmp_mibkp);
29080 		icmp_mibkp = NULL;
29081 	}
29082 }
29083 
29084 static int
29085 icmp_kstat_update(kstat_t *kp, int rw)
29086 {
29087 	icmp_named_kstat_t *icmpkp;
29088 
29089 	if ((kp == NULL) || (kp->ks_data == NULL))
29090 		return (EIO);
29091 
29092 	if (rw == KSTAT_WRITE)
29093 		return (EACCES);
29094 
29095 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29096 
29097 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
29098 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
29099 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
29100 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
29101 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
29102 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
29103 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
29104 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
29105 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
29106 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
29107 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
29108 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
29109 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
29110 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
29111 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
29112 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
29113 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
29114 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
29115 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
29116 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
29117 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
29118 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
29119 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
29120 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
29121 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
29122 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
29123 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
29124 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
29125 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
29126 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
29127 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
29128 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
29129 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
29130 
29131 	return (0);
29132 }
29133 
29134 /*
29135  * This is the fanout function for raw socket opened for SCTP.  Note
29136  * that it is called after SCTP checks that there is no socket which
29137  * wants a packet.  Then before SCTP handles this out of the blue packet,
29138  * this function is called to see if there is any raw socket for SCTP.
29139  * If there is and it is bound to the correct address, the packet will
29140  * be sent to that socket.  Note that only one raw socket can be bound to
29141  * a port.  This is assured in ipcl_sctp_hash_insert();
29142  */
29143 void
29144 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29145     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29146     uint_t ipif_seqid, zoneid_t zoneid)
29147 {
29148 	conn_t		*connp;
29149 	queue_t		*rq;
29150 	mblk_t		*first_mp;
29151 	boolean_t	secure;
29152 	ip6_t		*ip6h;
29153 
29154 	first_mp = mp;
29155 	if (mctl_present) {
29156 		mp = first_mp->b_cont;
29157 		secure = ipsec_in_is_secure(first_mp);
29158 		ASSERT(mp != NULL);
29159 	} else {
29160 		secure = B_FALSE;
29161 	}
29162 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29163 
29164 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
29165 	if (connp == NULL) {
29166 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
29167 		    mctl_present);
29168 		return;
29169 	}
29170 	rq = connp->conn_rq;
29171 	if (!canputnext(rq)) {
29172 		CONN_DEC_REF(connp);
29173 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29174 		freemsg(first_mp);
29175 		return;
29176 	}
29177 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
29178 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
29179 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29180 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29181 		if (first_mp == NULL) {
29182 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29183 			CONN_DEC_REF(connp);
29184 			return;
29185 		}
29186 	}
29187 	/*
29188 	 * We probably should not send M_CTL message up to
29189 	 * raw socket.
29190 	 */
29191 	if (mctl_present)
29192 		freeb(first_mp);
29193 
29194 	/* Initiate IPPF processing here if needed. */
29195 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
29196 	    (!isv4 && IP6_IN_IPP(flags))) {
29197 		ip_process(IPP_LOCAL_IN, &mp,
29198 		    recv_ill->ill_phyint->phyint_ifindex);
29199 		if (mp == NULL) {
29200 			CONN_DEC_REF(connp);
29201 			return;
29202 		}
29203 	}
29204 
29205 	if (connp->conn_recvif || connp->conn_recvslla ||
29206 	    ((connp->conn_ip_recvpktinfo ||
29207 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29208 	    (flags & IP_FF_IPINFO))) {
29209 		int in_flags = 0;
29210 
29211 		/*
29212 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29213 		 * IPF_RECVIF.
29214 		 */
29215 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29216 			in_flags = IPF_RECVIF;
29217 		}
29218 		if (connp->conn_recvslla) {
29219 			in_flags |= IPF_RECVSLLA;
29220 		}
29221 		if (isv4) {
29222 			mp = ip_add_info(mp, recv_ill, in_flags,
29223 			    IPCL_ZONEID(connp));
29224 		} else {
29225 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29226 			if (mp == NULL) {
29227 				BUMP_MIB(recv_ill->ill_ip_mib,
29228 				    ipIfStatsInDiscards);
29229 				CONN_DEC_REF(connp);
29230 				return;
29231 			}
29232 		}
29233 	}
29234 
29235 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29236 	/*
29237 	 * We are sending the IPSEC_IN message also up. Refer
29238 	 * to comments above this function.
29239 	 */
29240 	putnext(rq, mp);
29241 	CONN_DEC_REF(connp);
29242 }
29243 
29244 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29245 {									\
29246 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29247 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29248 }
29249 /*
29250  * This function should be called only if all packet processing
29251  * including fragmentation is complete. Callers of this function
29252  * must set mp->b_prev to one of these values:
29253  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29254  * prior to handing over the mp as first argument to this function.
29255  *
29256  * If the ire passed by caller is incomplete, this function
29257  * queues the packet and if necessary, sends ARP request and bails.
29258  * If the ire passed is fully resolved, we simply prepend
29259  * the link-layer header to the packet, do ipsec hw acceleration
29260  * work if necessary, and send the packet out on the wire.
29261  *
29262  * NOTE: IPSEC will only call this function with fully resolved
29263  * ires if hw acceleration is involved.
29264  * TODO list :
29265  * 	a Handle M_MULTIDATA so that
29266  *	  tcp_multisend->tcp_multisend_data can
29267  *	  call ip_xmit_v4 directly
29268  *	b Handle post-ARP work for fragments so that
29269  *	  ip_wput_frag can call this function.
29270  */
29271 ipxmit_state_t
29272 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29273 {
29274 	nce_t		*arpce;
29275 	queue_t		*q;
29276 	int		ill_index;
29277 	mblk_t		*nxt_mp, *first_mp;
29278 	boolean_t	xmit_drop = B_FALSE;
29279 	ip_proc_t	proc;
29280 	ill_t		*out_ill;
29281 	int		pkt_len;
29282 
29283 	arpce = ire->ire_nce;
29284 	ASSERT(arpce != NULL);
29285 
29286 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29287 
29288 	mutex_enter(&arpce->nce_lock);
29289 	switch (arpce->nce_state) {
29290 	case ND_REACHABLE:
29291 		/* If there are other queued packets, queue this packet */
29292 		if (arpce->nce_qd_mp != NULL) {
29293 			if (mp != NULL)
29294 				nce_queue_mp_common(arpce, mp, B_FALSE);
29295 			mp = arpce->nce_qd_mp;
29296 		}
29297 		arpce->nce_qd_mp = NULL;
29298 		mutex_exit(&arpce->nce_lock);
29299 
29300 		/*
29301 		 * Flush the queue.  In the common case, where the
29302 		 * ARP is already resolved,  it will go through the
29303 		 * while loop only once.
29304 		 */
29305 		while (mp != NULL) {
29306 
29307 			nxt_mp = mp->b_next;
29308 			mp->b_next = NULL;
29309 			ASSERT(mp->b_datap->db_type != M_CTL);
29310 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29311 			/*
29312 			 * This info is needed for IPQOS to do COS marking
29313 			 * in ip_wput_attach_llhdr->ip_process.
29314 			 */
29315 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29316 			mp->b_prev = NULL;
29317 
29318 			/* set up ill index for outbound qos processing */
29319 			out_ill = ire->ire_ipif->ipif_ill;
29320 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29321 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29322 			    ill_index);
29323 			if (first_mp == NULL) {
29324 				xmit_drop = B_TRUE;
29325 				BUMP_MIB(out_ill->ill_ip_mib,
29326 				    ipIfStatsOutDiscards);
29327 				goto next_mp;
29328 			}
29329 			/* non-ipsec hw accel case */
29330 			if (io == NULL || !io->ipsec_out_accelerated) {
29331 				/* send it */
29332 				q = ire->ire_stq;
29333 				if (proc == IPP_FWD_OUT) {
29334 					UPDATE_IB_PKT_COUNT(ire);
29335 				} else {
29336 					UPDATE_OB_PKT_COUNT(ire);
29337 				}
29338 				ire->ire_last_used_time = lbolt;
29339 
29340 				if (flow_ctl_enabled || canputnext(q))  {
29341 					if (proc == IPP_FWD_OUT) {
29342 						BUMP_MIB(out_ill->ill_ip_mib,
29343 						ipIfStatsHCOutForwDatagrams);
29344 					}
29345 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29346 					    pkt_len);
29347 
29348 					putnext(q, first_mp);
29349 				} else {
29350 					BUMP_MIB(out_ill->ill_ip_mib,
29351 					    ipIfStatsOutDiscards);
29352 					xmit_drop = B_TRUE;
29353 					freemsg(first_mp);
29354 				}
29355 			} else {
29356 				/*
29357 				 * Safety Pup says: make sure this
29358 				 *  is going to the right interface!
29359 				 */
29360 				ill_t *ill1 =
29361 				    (ill_t *)ire->ire_stq->q_ptr;
29362 				int ifindex =
29363 				    ill1->ill_phyint->phyint_ifindex;
29364 				if (ifindex !=
29365 				    io->ipsec_out_capab_ill_index) {
29366 					xmit_drop = B_TRUE;
29367 					freemsg(mp);
29368 				} else {
29369 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29370 					    pkt_len);
29371 					ipsec_hw_putnext(ire->ire_stq, mp);
29372 				}
29373 			}
29374 next_mp:
29375 			mp = nxt_mp;
29376 		} /* while (mp != NULL) */
29377 		if (xmit_drop)
29378 			return (SEND_FAILED);
29379 		else
29380 			return (SEND_PASSED);
29381 
29382 	case ND_INITIAL:
29383 	case ND_INCOMPLETE:
29384 
29385 		/*
29386 		 * While we do send off packets to dests that
29387 		 * use fully-resolved CGTP routes, we do not
29388 		 * handle unresolved CGTP routes.
29389 		 */
29390 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29391 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29392 
29393 		if (mp != NULL) {
29394 			/* queue the packet */
29395 			nce_queue_mp_common(arpce, mp, B_FALSE);
29396 		}
29397 
29398 		if (arpce->nce_state == ND_INCOMPLETE) {
29399 			mutex_exit(&arpce->nce_lock);
29400 			DTRACE_PROBE3(ip__xmit__incomplete,
29401 			    (ire_t *), ire, (mblk_t *), mp,
29402 			    (ipsec_out_t *), io);
29403 			return (LOOKUP_IN_PROGRESS);
29404 		}
29405 
29406 		arpce->nce_state = ND_INCOMPLETE;
29407 		mutex_exit(&arpce->nce_lock);
29408 		/*
29409 		 * Note that ire_add() (called from ire_forward())
29410 		 * holds a ref on the ire until ARP is completed.
29411 		 */
29412 
29413 		ire_arpresolve(ire, ire_to_ill(ire));
29414 		return (LOOKUP_IN_PROGRESS);
29415 	default:
29416 		ASSERT(0);
29417 		mutex_exit(&arpce->nce_lock);
29418 		return (LLHDR_RESLV_FAILED);
29419 	}
29420 }
29421 
29422 #undef	UPDATE_IP_MIB_OB_COUNTERS
29423 
29424 /*
29425  * Return B_TRUE if the buffers differ in length or content.
29426  * This is used for comparing extension header buffers.
29427  * Note that an extension header would be declared different
29428  * even if all that changed was the next header value in that header i.e.
29429  * what really changed is the next extension header.
29430  */
29431 boolean_t
29432 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29433     uint_t blen)
29434 {
29435 	if (!b_valid)
29436 		blen = 0;
29437 
29438 	if (alen != blen)
29439 		return (B_TRUE);
29440 	if (alen == 0)
29441 		return (B_FALSE);	/* Both zero length */
29442 	return (bcmp(abuf, bbuf, alen));
29443 }
29444 
29445 /*
29446  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29447  * Return B_FALSE if memory allocation fails - don't change any state!
29448  */
29449 boolean_t
29450 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29451     const void *src, uint_t srclen)
29452 {
29453 	void *dst;
29454 
29455 	if (!src_valid)
29456 		srclen = 0;
29457 
29458 	ASSERT(*dstlenp == 0);
29459 	if (src != NULL && srclen != 0) {
29460 		dst = mi_alloc(srclen, BPRI_MED);
29461 		if (dst == NULL)
29462 			return (B_FALSE);
29463 	} else {
29464 		dst = NULL;
29465 	}
29466 	if (*dstp != NULL)
29467 		mi_free(*dstp);
29468 	*dstp = dst;
29469 	*dstlenp = dst == NULL ? 0 : srclen;
29470 	return (B_TRUE);
29471 }
29472 
29473 /*
29474  * Replace what is in *dst, *dstlen with the source.
29475  * Assumes ip_allocbuf has already been called.
29476  */
29477 void
29478 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29479     const void *src, uint_t srclen)
29480 {
29481 	if (!src_valid)
29482 		srclen = 0;
29483 
29484 	ASSERT(*dstlenp == srclen);
29485 	if (src != NULL && srclen != 0)
29486 		bcopy(src, *dstp, srclen);
29487 }
29488 
29489 /*
29490  * Free the storage pointed to by the members of an ip6_pkt_t.
29491  */
29492 void
29493 ip6_pkt_free(ip6_pkt_t *ipp)
29494 {
29495 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29496 
29497 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29498 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29499 		ipp->ipp_hopopts = NULL;
29500 		ipp->ipp_hopoptslen = 0;
29501 	}
29502 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29503 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29504 		ipp->ipp_rtdstopts = NULL;
29505 		ipp->ipp_rtdstoptslen = 0;
29506 	}
29507 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29508 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29509 		ipp->ipp_dstopts = NULL;
29510 		ipp->ipp_dstoptslen = 0;
29511 	}
29512 	if (ipp->ipp_fields & IPPF_RTHDR) {
29513 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29514 		ipp->ipp_rthdr = NULL;
29515 		ipp->ipp_rthdrlen = 0;
29516 	}
29517 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29518 	    IPPF_RTHDR);
29519 }
29520